Chris@47: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@47: // Licensed under the MIT License: Chris@47: // Chris@47: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@47: // of this software and associated documentation files (the "Software"), to deal Chris@47: // in the Software without restriction, including without limitation the rights Chris@47: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@47: // copies of the Software, and to permit persons to whom the Software is Chris@47: // furnished to do so, subject to the following conditions: Chris@47: // Chris@47: // The above copyright notice and this permission notice shall be included in Chris@47: // all copies or substantial portions of the Software. Chris@47: // Chris@47: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@47: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@47: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@47: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@47: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@47: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@47: // THE SOFTWARE. Chris@47: Chris@47: #ifndef CAPNP_EZ_RPC_H_ Chris@47: #define CAPNP_EZ_RPC_H_ Chris@47: Chris@47: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) Chris@47: #pragma GCC system_header Chris@47: #endif Chris@47: Chris@47: #include "rpc.h" Chris@47: #include "message.h" Chris@47: Chris@47: struct sockaddr; Chris@47: Chris@47: namespace kj { class AsyncIoProvider; class LowLevelAsyncIoProvider; } Chris@47: Chris@47: namespace capnp { Chris@47: Chris@47: class EzRpcContext; Chris@47: Chris@47: class EzRpcClient { Chris@47: // Super-simple interface for setting up a Cap'n Proto RPC client. Example: Chris@47: // Chris@47: // # Cap'n Proto schema Chris@47: // interface Adder { Chris@47: // add @0 (left :Int32, right :Int32) -> (value :Int32); Chris@47: // } Chris@47: // Chris@47: // // C++ client Chris@47: // int main() { Chris@47: // capnp::EzRpcClient client("localhost:3456"); Chris@47: // Adder::Client adder = client.getMain(); Chris@47: // auto request = adder.addRequest(); Chris@47: // request.setLeft(12); Chris@47: // request.setRight(34); Chris@47: // auto response = request.send().wait(client.getWaitScope()); Chris@47: // assert(response.getValue() == 46); Chris@47: // return 0; Chris@47: // } Chris@47: // Chris@47: // // C++ server Chris@47: // class AdderImpl final: public Adder::Server { Chris@47: // public: Chris@47: // kj::Promise add(AddContext context) override { Chris@47: // auto params = context.getParams(); Chris@47: // context.getResults().setValue(params.getLeft() + params.getRight()); Chris@47: // return kj::READY_NOW; Chris@47: // } Chris@47: // }; Chris@47: // Chris@47: // int main() { Chris@47: // capnp::EzRpcServer server(kj::heap(), "*:3456"); Chris@47: // kj::NEVER_DONE.wait(server.getWaitScope()); Chris@47: // } Chris@47: // Chris@47: // This interface is easy, but it hides a lot of useful features available from the lower-level Chris@47: // classes: Chris@47: // - The server can only export a small set of public, singleton capabilities under well-known Chris@47: // string names. This is fine for transient services where no state needs to be kept between Chris@47: // connections, but hides the power of Cap'n Proto when it comes to long-lived resources. Chris@47: // - EzRpcClient/EzRpcServer automatically set up a `kj::EventLoop` and make it current for the Chris@47: // thread. Only one `kj::EventLoop` can exist per thread, so you cannot use these interfaces Chris@47: // if you wish to set up your own event loop. (However, you can safely create multiple Chris@47: // EzRpcClient / EzRpcServer objects in a single thread; they will make sure to make no more Chris@47: // than one EventLoop.) Chris@47: // - These classes only support simple two-party connections, not multilateral VatNetworks. Chris@47: // - These classes only support communication over a raw, unencrypted socket. If you want to Chris@47: // build on an abstract stream (perhaps one which supports encryption), you must use the Chris@47: // lower-level interfaces. Chris@47: // Chris@47: // Some of these restrictions will probably be lifted in future versions, but some things will Chris@47: // always require using the low-level interfaces directly. If you are interested in working Chris@47: // at a lower level, start by looking at these interfaces: Chris@47: // - `kj::setupAsyncIo()` in `kj/async-io.h`. Chris@47: // - `RpcSystem` in `capnp/rpc.h`. Chris@47: // - `TwoPartyVatNetwork` in `capnp/rpc-twoparty.h`. Chris@47: Chris@47: public: Chris@47: explicit EzRpcClient(kj::StringPtr serverAddress, uint defaultPort = 0, Chris@47: ReaderOptions readerOpts = ReaderOptions()); Chris@47: // Construct a new EzRpcClient and connect to the given address. The connection is formed in Chris@47: // the background -- if it fails, calls to capabilities returned by importCap() will fail with an Chris@47: // appropriate exception. Chris@47: // Chris@47: // `defaultPort` is the IP port number to use if `serverAddress` does not include it explicitly. Chris@47: // If unspecified, the port is required in `serverAddress`. Chris@47: // Chris@47: // The address is parsed by `kj::Network` in `kj/async-io.h`. See that interface for more info Chris@47: // on the address format, but basically it's what you'd expect. Chris@47: // Chris@47: // `readerOpts` is the ReaderOptions structure used to read each incoming message on the Chris@47: // connection. Setting this may be necessary if you need to receive very large individual Chris@47: // messages or messages. However, it is recommended that you instead think about how to change Chris@47: // your protocol to send large data blobs in multiple small chunks -- this is much better for Chris@47: // both security and performance. See `ReaderOptions` in `message.h` for more details. Chris@47: Chris@47: EzRpcClient(const struct sockaddr* serverAddress, uint addrSize, Chris@47: ReaderOptions readerOpts = ReaderOptions()); Chris@47: // Like the above constructor, but connects to an already-resolved socket address. Any address Chris@47: // format supported by `kj::Network` in `kj/async-io.h` is accepted. Chris@47: Chris@47: explicit EzRpcClient(int socketFd, ReaderOptions readerOpts = ReaderOptions()); Chris@47: // Create a client on top of an already-connected socket. Chris@47: // `readerOpts` acts as in the first constructor. Chris@47: Chris@47: ~EzRpcClient() noexcept(false); Chris@47: Chris@47: template Chris@47: typename Type::Client getMain(); Chris@47: Capability::Client getMain(); Chris@47: // Get the server's main (aka "bootstrap") interface. Chris@47: Chris@47: template Chris@47: typename Type::Client importCap(kj::StringPtr name) Chris@47: KJ_DEPRECATED("Change your server to export a main interface, then use getMain() instead."); Chris@47: Capability::Client importCap(kj::StringPtr name) Chris@47: KJ_DEPRECATED("Change your server to export a main interface, then use getMain() instead."); Chris@47: // ** DEPRECATED ** Chris@47: // Chris@47: // Ask the sever for the capability with the given name. You may specify a type to automatically Chris@47: // down-cast to that type. It is up to you to specify the correct expected type. Chris@47: // Chris@47: // Named interfaces are deprecated. The new preferred usage pattern is for the server to export Chris@47: // a "main" interface which itself has methods for getting any other interfaces. Chris@47: Chris@47: kj::WaitScope& getWaitScope(); Chris@47: // Get the `WaitScope` for the client's `EventLoop`, which allows you to synchronously wait on Chris@47: // promises. Chris@47: Chris@47: kj::AsyncIoProvider& getIoProvider(); Chris@47: // Get the underlying AsyncIoProvider set up by the RPC system. This is useful if you want Chris@47: // to do some non-RPC I/O in asynchronous fashion. Chris@47: Chris@47: kj::LowLevelAsyncIoProvider& getLowLevelIoProvider(); Chris@47: // Get the underlying LowLevelAsyncIoProvider set up by the RPC system. This is useful if you Chris@47: // want to do some non-RPC I/O in asynchronous fashion. Chris@47: Chris@47: private: Chris@47: struct Impl; Chris@47: kj::Own impl; Chris@47: }; Chris@47: Chris@47: class EzRpcServer { Chris@47: // The server counterpart to `EzRpcClient`. See `EzRpcClient` for an example. Chris@47: Chris@47: public: Chris@47: explicit EzRpcServer(Capability::Client mainInterface, kj::StringPtr bindAddress, Chris@47: uint defaultPort = 0, ReaderOptions readerOpts = ReaderOptions()); Chris@47: // Construct a new `EzRpcServer` that binds to the given address. An address of "*" means to Chris@47: // bind to all local addresses. Chris@47: // Chris@47: // `defaultPort` is the IP port number to use if `serverAddress` does not include it explicitly. Chris@47: // If unspecified, a port is chosen automatically, and you must call getPort() to find out what Chris@47: // it is. Chris@47: // Chris@47: // The address is parsed by `kj::Network` in `kj/async-io.h`. See that interface for more info Chris@47: // on the address format, but basically it's what you'd expect. Chris@47: // Chris@47: // The server might not begin listening immediately, especially if `bindAddress` needs to be Chris@47: // resolved. If you need to wait until the server is definitely up, wait on the promise returned Chris@47: // by `getPort()`. Chris@47: // Chris@47: // `readerOpts` is the ReaderOptions structure used to read each incoming message on the Chris@47: // connection. Setting this may be necessary if you need to receive very large individual Chris@47: // messages or messages. However, it is recommended that you instead think about how to change Chris@47: // your protocol to send large data blobs in multiple small chunks -- this is much better for Chris@47: // both security and performance. See `ReaderOptions` in `message.h` for more details. Chris@47: Chris@47: EzRpcServer(Capability::Client mainInterface, struct sockaddr* bindAddress, uint addrSize, Chris@47: ReaderOptions readerOpts = ReaderOptions()); Chris@47: // Like the above constructor, but binds to an already-resolved socket address. Any address Chris@47: // format supported by `kj::Network` in `kj/async-io.h` is accepted. Chris@47: Chris@47: EzRpcServer(Capability::Client mainInterface, int socketFd, uint port, Chris@47: ReaderOptions readerOpts = ReaderOptions()); Chris@47: // Create a server on top of an already-listening socket (i.e. one on which accept() may be Chris@47: // called). `port` is returned by `getPort()` -- it serves no other purpose. Chris@47: // `readerOpts` acts as in the other two above constructors. Chris@47: Chris@47: explicit EzRpcServer(kj::StringPtr bindAddress, uint defaultPort = 0, Chris@47: ReaderOptions readerOpts = ReaderOptions()) Chris@47: KJ_DEPRECATED("Please specify a main interface for your server."); Chris@47: EzRpcServer(struct sockaddr* bindAddress, uint addrSize, Chris@47: ReaderOptions readerOpts = ReaderOptions()) Chris@47: KJ_DEPRECATED("Please specify a main interface for your server."); Chris@47: EzRpcServer(int socketFd, uint port, ReaderOptions readerOpts = ReaderOptions()) Chris@47: KJ_DEPRECATED("Please specify a main interface for your server."); Chris@47: Chris@47: ~EzRpcServer() noexcept(false); Chris@47: Chris@47: void exportCap(kj::StringPtr name, Capability::Client cap); Chris@47: // Export a capability publicly under the given name, so that clients can import it. Chris@47: // Chris@47: // Keep in mind that you can implicitly convert `kj::Own&&` to Chris@47: // `Capability::Client`, so it's typical to pass something like Chris@47: // `kj::heap()` as the second parameter. Chris@47: Chris@47: kj::Promise getPort(); Chris@47: // Get the IP port number on which this server is listening. This promise won't resolve until Chris@47: // the server is actually listening. If the address was not an IP address (e.g. it was a Unix Chris@47: // domain socket) then getPort() resolves to zero. Chris@47: Chris@47: kj::WaitScope& getWaitScope(); Chris@47: // Get the `WaitScope` for the client's `EventLoop`, which allows you to synchronously wait on Chris@47: // promises. Chris@47: Chris@47: kj::AsyncIoProvider& getIoProvider(); Chris@47: // Get the underlying AsyncIoProvider set up by the RPC system. This is useful if you want Chris@47: // to do some non-RPC I/O in asynchronous fashion. Chris@47: Chris@47: kj::LowLevelAsyncIoProvider& getLowLevelIoProvider(); Chris@47: // Get the underlying LowLevelAsyncIoProvider set up by the RPC system. This is useful if you Chris@47: // want to do some non-RPC I/O in asynchronous fashion. Chris@47: Chris@47: private: Chris@47: struct Impl; Chris@47: kj::Own impl; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // inline implementation details Chris@47: Chris@47: template Chris@47: inline typename Type::Client EzRpcClient::getMain() { Chris@47: return getMain().castAs(); Chris@47: } Chris@47: Chris@47: template Chris@47: inline typename Type::Client EzRpcClient::importCap(kj::StringPtr name) { Chris@47: return importCap(name).castAs(); Chris@47: } Chris@47: Chris@47: } // namespace capnp Chris@47: Chris@47: #endif // CAPNP_EZ_RPC_H_