ez-rpc.h 11.6 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21 22 23 24

#ifndef CAPNP_EZ_RPC_H_
#define CAPNP_EZ_RPC_H_

25 26 27 28
#if defined(__GNUC__) && !CAPNP_HEADER_WARNINGS
#pragma GCC system_header
#endif

29
#include "rpc.h"
30
#include "message.h"
31

32 33
struct sockaddr;

34
namespace kj { class AsyncIoProvider; class LowLevelAsyncIoProvider; }
35 36 37 38 39 40 41 42 43 44

namespace capnp {

class EzRpcContext;

class EzRpcClient {
  // Super-simple interface for setting up a Cap'n Proto RPC client.  Example:
  //
  //     # Cap'n Proto schema
  //     interface Adder {
Kenton Varda's avatar
Kenton Varda committed
45
  //       add @0 (left :Int32, right :Int32) -> (value :Int32);
46 47 48 49
  //     }
  //
  //     // C++ client
  //     int main() {
Kenton Varda's avatar
Kenton Varda committed
50
  //       capnp::EzRpcClient client("localhost:3456");
51
  //       Adder::Client adder = client.getMain<Adder>();
Kenton Varda's avatar
Kenton Varda committed
52
  //       auto request = adder.addRequest();
53 54
  //       request.setLeft(12);
  //       request.setRight(34);
Kenton Varda's avatar
Kenton Varda committed
55 56
  //       auto response = request.send().wait(client.getWaitScope());
  //       assert(response.getValue() == 46);
57 58 59 60
  //       return 0;
  //     }
  //
  //     // C++ server
Kenton Varda's avatar
Kenton Varda committed
61
  //     class AdderImpl final: public Adder::Server {
62
  //     public:
Kenton Varda's avatar
Kenton Varda committed
63 64 65
  //       kj::Promise<void> add(AddContext context) override {
  //         auto params = context.getParams();
  //         context.getResults().setValue(params.getLeft() + params.getRight());
66 67 68 69 70
  //         return kj::READY_NOW;
  //       }
  //     };
  //
  //     int main() {
71
  //       capnp::EzRpcServer server(kj::heap<AdderImpl>(), "*:3456");
72
  //       kj::NEVER_DONE.wait(server.getWaitScope());
73 74 75 76 77 78 79
  //     }
  //
  // This interface is easy, but it hides a lot of useful features available from the lower-level
  // classes:
  // - The server can only export a small set of public, singleton capabilities under well-known
  //   string names.  This is fine for transient services where no state needs to be kept between
  //   connections, but hides the power of Cap'n Proto when it comes to long-lived resources.
80 81 82 83 84
  // - EzRpcClient/EzRpcServer automatically set up a `kj::EventLoop` and make it current for the
  //   thread.  Only one `kj::EventLoop` can exist per thread, so you cannot use these interfaces
  //   if you wish to set up your own event loop.  (However, you can safely create multiple
  //   EzRpcClient / EzRpcServer objects in a single thread; they will make sure to make no more
  //   than one EventLoop.)
85
  // - These classes only support simple two-party connections, not multilateral VatNetworks.
86 87 88 89 90 91 92 93 94 95
  // - These classes only support communication over a raw, unencrypted socket.  If you want to
  //   build on an abstract stream (perhaps one which supports encryption), you must use the
  //   lower-level interfaces.
  //
  // Some of these restrictions will probably be lifted in future versions, but some things will
  // always require using the low-level interfaces directly.  If you are interested in working
  // at a lower level, start by looking at these interfaces:
  // - `kj::startAsyncIo()` in `kj/async-io.h`.
  // - `RpcSystem` in `capnp/rpc.h`.
  // - `TwoPartyVatNetwork` in `capnp/rpc-twoparty.h`.
96 97

public:
98 99
  explicit EzRpcClient(kj::StringPtr serverAddress, uint defaultPort = 0,
                       ReaderOptions readerOpts = ReaderOptions());
100 101 102 103 104 105 106 107 108
  // Construct a new EzRpcClient and connect to the given address.  The connection is formed in
  // the background -- if it fails, calls to capabilities returned by importCap() will fail with an
  // appropriate exception.
  //
  // `defaultPort` is the IP port number to use if `serverAddress` does not include it explicitly.
  // If unspecified, the port is required in `serverAddress`.
  //
  // The address is parsed by `kj::Network` in `kj/async-io.h`.  See that interface for more info
  // on the address format, but basically it's what you'd expect.
109
  //
110 111 112 113 114 115
  // `readerOpts` is the ReaderOptions structure used to read each incoming message on the
  // connection. Setting this may be necessary if you need to receive very large individual
  // messages or messages. However, it is recommended that you instead think about how to change
  // your protocol to send large data blobs in multiple small chunks -- this is much better for
  // both security and performance. See `ReaderOptions` in `message.h` for more details.

116 117
  EzRpcClient(const struct sockaddr* serverAddress, uint addrSize,
              ReaderOptions readerOpts = ReaderOptions());
118 119 120
  // Like the above constructor, but connects to an already-resolved socket address.  Any address
  // format supported by `kj::Network` in `kj/async-io.h` is accepted.

121
  explicit EzRpcClient(int socketFd, ReaderOptions readerOpts = ReaderOptions());
122
  // Create a client on top of an already-connected socket.
123
  // `readerOpts` acts as in the first constructor.
124 125 126 127

  ~EzRpcClient() noexcept(false);

  template <typename Type>
128 129 130 131 132 133 134 135 136 137 138
  typename Type::Client getMain();
  Capability::Client getMain();
  // Get the server's main (aka "bootstrap") interface.

  template <typename Type>
  typename Type::Client importCap(kj::StringPtr name)
      KJ_DEPRECATED("Change your server to export a main interface, then use getMain() instead.");
  Capability::Client importCap(kj::StringPtr name)
      KJ_DEPRECATED("Change your server to export a main interface, then use getMain() instead.");
  // ** DEPRECATED **
  //
139 140
  // Ask the sever for the capability with the given name.  You may specify a type to automatically
  // down-cast to that type.  It is up to you to specify the correct expected type.
141 142 143
  //
  // Named interfaces are deprecated. The new preferred usage pattern is for the server to export
  // a "main" interface which itself has methods for getting any other interfaces.
144

145 146 147 148
  kj::WaitScope& getWaitScope();
  // Get the `WaitScope` for the client's `EventLoop`, which allows you to synchronously wait on
  // promises.

149 150 151 152
  kj::AsyncIoProvider& getIoProvider();
  // Get the underlying AsyncIoProvider set up by the RPC system.  This is useful if you want
  // to do some non-RPC I/O in asynchronous fashion.

153 154 155 156
  kj::LowLevelAsyncIoProvider& getLowLevelIoProvider();
  // Get the underlying LowLevelAsyncIoProvider set up by the RPC system.  This is useful if you
  // want to do some non-RPC I/O in asynchronous fashion.

157 158 159 160 161 162 163 164 165
private:
  struct Impl;
  kj::Own<Impl> impl;
};

class EzRpcServer {
  // The server counterpart to `EzRpcClient`.  See `EzRpcClient` for an example.

public:
166 167
  explicit EzRpcServer(Capability::Client mainInterface, kj::StringPtr bindAddress,
                       uint defaultPort = 0, ReaderOptions readerOpts = ReaderOptions());
168 169 170 171 172 173 174 175 176 177 178 179 180
  // Construct a new `EzRpcServer` that binds to the given address.  An address of "*" means to
  // bind to all local addresses.
  //
  // `defaultPort` is the IP port number to use if `serverAddress` does not include it explicitly.
  // If unspecified, a port is chosen automatically, and you must call getPort() to find out what
  // it is.
  //
  // The address is parsed by `kj::Network` in `kj/async-io.h`.  See that interface for more info
  // on the address format, but basically it's what you'd expect.
  //
  // The server might not begin listening immediately, especially if `bindAddress` needs to be
  // resolved.  If you need to wait until the server is definitely up, wait on the promise returned
  // by `getPort()`.
181 182 183 184 185 186
  //
  // `readerOpts` is the ReaderOptions structure used to read each incoming message on the
  // connection. Setting this may be necessary if you need to receive very large individual
  // messages or messages. However, it is recommended that you instead think about how to change
  // your protocol to send large data blobs in multiple small chunks -- this is much better for
  // both security and performance. See `ReaderOptions` in `message.h` for more details.
187

188
  EzRpcServer(Capability::Client mainInterface, struct sockaddr* bindAddress, uint addrSize,
189
              ReaderOptions readerOpts = ReaderOptions());
190 191 192
  // Like the above constructor, but binds to an already-resolved socket address.  Any address
  // format supported by `kj::Network` in `kj/async-io.h` is accepted.

193 194
  EzRpcServer(Capability::Client mainInterface, int socketFd, uint port,
              ReaderOptions readerOpts = ReaderOptions());
195 196
  // Create a server on top of an already-listening socket (i.e. one on which accept() may be
  // called).  `port` is returned by `getPort()` -- it serves no other purpose.
197
  // `readerOpts` acts as in the other two above constructors.
198

199 200 201 202 203 204 205 206 207
  explicit EzRpcServer(kj::StringPtr bindAddress, uint defaultPort = 0,
                       ReaderOptions readerOpts = ReaderOptions())
      KJ_DEPRECATED("Please specify a main interface for your server.");
  EzRpcServer(struct sockaddr* bindAddress, uint addrSize,
              ReaderOptions readerOpts = ReaderOptions())
      KJ_DEPRECATED("Please specify a main interface for your server.");
  EzRpcServer(int socketFd, uint port, ReaderOptions readerOpts = ReaderOptions())
      KJ_DEPRECATED("Please specify a main interface for your server.");

208 209 210 211 212 213
  ~EzRpcServer() noexcept(false);

  void exportCap(kj::StringPtr name, Capability::Client cap);
  // Export a capability publicly under the given name, so that clients can import it.
  //
  // Keep in mind that you can implicitly convert `kj::Own<MyType::Server>&&` to
214
  // `Capability::Client`, so it's typical to pass something like
215 216 217 218 219 220 221
  // `kj::heap<MyImplementation>(<constructor params>)` as the second parameter.

  kj::Promise<uint> getPort();
  // Get the IP port number on which this server is listening.  This promise won't resolve until
  // the server is actually listening.  If the address was not an IP address (e.g. it was a Unix
  // domain socket) then getPort() resolves to zero.

222 223 224 225
  kj::WaitScope& getWaitScope();
  // Get the `WaitScope` for the client's `EventLoop`, which allows you to synchronously wait on
  // promises.

226 227 228 229
  kj::AsyncIoProvider& getIoProvider();
  // Get the underlying AsyncIoProvider set up by the RPC system.  This is useful if you want
  // to do some non-RPC I/O in asynchronous fashion.

230 231 232 233
  kj::LowLevelAsyncIoProvider& getLowLevelIoProvider();
  // Get the underlying LowLevelAsyncIoProvider set up by the RPC system.  This is useful if you
  // want to do some non-RPC I/O in asynchronous fashion.

234 235 236 237 238 239 240 241
private:
  struct Impl;
  kj::Own<Impl> impl;
};

// =======================================================================================
// inline implementation details

242 243 244 245 246
template <typename Type>
inline typename Type::Client EzRpcClient::getMain() {
  return getMain().castAs<Type>();
}

247 248 249 250 251 252 253 254
template <typename Type>
inline typename Type::Client EzRpcClient::importCap(kj::StringPtr name) {
  return importCap(name).castAs<Type>();
}

}  // namespace capnp

#endif  // CAPNP_EZ_RPC_H_