cannam@133: --- cannam@133: layout: page cannam@133: title: C++ RPC cannam@133: --- cannam@133: cannam@133: # C++ RPC cannam@133: cannam@133: The Cap'n Proto C++ RPC layer sits on top of the [serialization layer](cxx.html) and implements cannam@133: the [RPC protocol](rpc.html). cannam@133: cannam@133: ## Current Status cannam@133: cannam@133: As of version 0.4, Cap'n Proto's C++ RPC implementation is a [Level 1](rpc.html#protocol-features) cannam@133: implementation. Persistent capabilities, three-way introductions, and distributed equality are cannam@133: not yet implemented. cannam@133: cannam@133: ## Sample Code cannam@133: cannam@133: The [Calculator example](https://github.com/sandstorm-io/capnproto/tree/master/c++/samples) implements cannam@133: a fully-functional Cap'n Proto client and server. cannam@133: cannam@133: ## KJ Concurrency Framework cannam@133: cannam@133: RPC naturally requires a notion of concurrency. Unfortunately, cannam@133: [all concurrency models suck](https://plus.google.com/u/0/+KentonVarda/posts/D95XKtB5DhK). cannam@133: cannam@133: Cap'n Proto's RPC is based on the [KJ library](cxx.html#kj-library)'s event-driven concurrency cannam@133: framework. The core of the KJ asynchronous framework (events, promises, callbacks) is defined in cannam@133: `kj/async.h`, with I/O interfaces (streams, sockets, networks) defined in `kj/async-io.h`. cannam@133: cannam@133: ### Event Loop Concurrency cannam@133: cannam@133: KJ's concurrency model is based on event loops. While multiple threads are allowed, each thread cannam@133: must have its own event loop. KJ discourages fine-grained interaction between threads as cannam@133: synchronization is expensive and error-prone. Instead, threads are encouraged to communicate cannam@133: through Cap'n Proto RPC. cannam@133: cannam@133: KJ's event loop model bears a lot of similarity to the Javascript concurrency model. Experienced cannam@133: Javascript hackers -- especially node.js hackers -- will feel right at home. cannam@133: cannam@133: _As of version 0.4, the only supported way to communicate between threads is over pipes or cannam@133: socketpairs. This will be improved in future versions. For now, just set up an RPC connection cannam@133: over that socketpair. :)_ cannam@133: cannam@133: ### Promises cannam@133: cannam@133: Function calls that do I/O must do so asynchronously, and must return a "promise" for the cannam@133: result. Promises -- also known as "futures" in some systems -- are placeholders for the results cannam@133: of operations that have not yet completed. When the operation completes, we say that the promise cannam@133: "resolves" to a value, or is "fulfilled". A promise can also be "rejected", which means an cannam@133: exception occurred. cannam@133: cannam@133: {% highlight c++ %} cannam@133: // Example promise-based interfaces. cannam@133: cannam@133: kj::Promise fetchHttp(kj::StringPtr url); cannam@133: // Asynchronously fetches an HTTP document and returns cannam@133: // the content as a string. cannam@133: cannam@133: kj::Promise sendEmail(kj::StringPtr address, cannam@133: kj::StringPtr title, kj::StringPtr body); cannam@133: // Sends an e-mail to the given address with the given title cannam@133: // and body. The returned promise resolves (to nothing) when cannam@133: // the message has been successfully sent. cannam@133: {% endhighlight %} cannam@133: cannam@133: As you will see, KJ promises are very similar to the evolving Javascript promise standard, and cannam@133: much of the [wisdom around it](https://www.google.com/search?q=javascript+promises) can be directly cannam@133: applied to KJ promises. cannam@133: cannam@133: ### Callbacks cannam@133: cannam@133: If you want to do something with the result of a promise, you must first wait for it to complete. cannam@133: This is normally done by registering a callback to execute on completion. Luckily, C++11 just cannam@133: introduced lambdas, which makes this far more pleasant than it would have been a few years ago! cannam@133: cannam@133: {% highlight c++ %} cannam@133: kj::Promise contentPromise = cannam@133: fetchHttp("http://example.com"); cannam@133: cannam@133: kj::Promise lineCountPromise = cannam@133: contentPromise.then([](kj::String&& content) { cannam@133: return countChars(content, '\n'); cannam@133: }); cannam@133: {% endhighlight %} cannam@133: cannam@133: The callback passed to `then()` takes the promised result as its parameter and returns a new value. cannam@133: `then()` itself returns a new promise for that value which the callback will eventually return. cannam@133: If the callback itself returns a promise, then `then()` actually returns a promise for the cannam@133: resolution of the latter promise -- that is, `Promise>` is automatically reduced to cannam@133: `Promise`. cannam@133: cannam@133: Note that `then()` consumes the original promise: you can only call `then()` once. This is true cannam@133: of all of the methods of `Promise`. The only way to consume a promise in multiple places is to cannam@133: first "fork" it with the `fork()` method, which we don't get into here. Relatedly, promises cannam@133: are linear types, which means they have move constructors but not copy constructors. cannam@133: cannam@133: ### Error Propagation cannam@133: cannam@133: `then()` takes an optional second parameter for handling errors. Think of this like a `catch` cannam@133: block. cannam@133: cannam@133: {% highlight c++ %} cannam@133: kj::Promise lineCountPromise = cannam@133: promise.then([](kj::String&& content) { cannam@133: return countChars(content, '\n'); cannam@133: }, [](kj::Exception&& exception) { cannam@133: // Error! Pretend the document was empty. cannam@133: return 0; cannam@133: }); cannam@133: {% endhighlight %} cannam@133: cannam@133: Note that the KJ framework coerces all exceptions to `kj::Exception` -- the exception's description cannam@133: (as returned by `what()`) will be retained, but any type-specific information is lost. Under KJ cannam@133: exception philosophy, exceptions always represent an error that should not occur under normal cannam@133: operation, and the only purpose of exceptions is to make software fault-tolerant. In particular, cannam@133: the only reasonable ways to handle an exception are to try again, tell a human, and/or propagate cannam@133: to the caller. To that end, `kj::Exception` contains information useful for reporting purposes cannam@133: and to help decide if trying again is reasonable, but typed exception hierarchies are not useful cannam@133: and not supported. cannam@133: cannam@133: It is recommended that Cap'n Proto code use the assertion macros in `kj/debug.h` to throw cannam@133: exceptions rather than use the C++ `throw` keyword. These macros make it easy to add useful cannam@133: debug information to an exception and generally play nicely with the KJ framework. In fact, you cannam@133: can even use these macros -- and propagate exceptions through promises -- if you compile your code cannam@133: with exceptions disabled. See the headers for more information. cannam@133: cannam@133: ### Waiting cannam@133: cannam@133: It is illegal for code running in an event callback to wait, since this would stall the event loop. cannam@133: However, if you are the one responsible for starting the event loop in the first place, then KJ cannam@133: makes it easy to say "run the event loop until this promise resolves, then return the result". cannam@133: cannam@133: {% highlight c++ %} cannam@133: kj::EventLoop loop; cannam@133: kj::WaitScope waitScope(loop); cannam@133: cannam@133: kj::Promise contentPromise = cannam@133: fetchHttp("http://example.com"); cannam@133: cannam@133: kj::String content = contentPromise.wait(waitScope); cannam@133: cannam@133: int lineCount = countChars(content, '\n'); cannam@133: {% endhighlight %} cannam@133: cannam@133: Using `wait()` is common in high-level client-side code. On the other hand, it is almost never cannam@133: used in servers. cannam@133: cannam@133: ### Cancellation cannam@133: cannam@133: If you discard a `Promise` without calling any of its methods, the operation it was waiting for cannam@133: is canceled, because the `Promise` itself owns that operation. This means than any pending cannam@133: callbacks simply won't be executed. If you need explicit notification when a promise is canceled, cannam@133: you can use its `attach()` method to attach an object with a destructor -- the destructor will be cannam@133: called when the promise either completes or is canceled. cannam@133: cannam@133: ### Other Features cannam@133: cannam@133: KJ supports a number of primitive operations that can be performed on promises. The complete API cannam@133: is documented directly in the `kj/async.h` header. Additionally, see the `kj/async-io.h` header cannam@133: for APIs for performing basic network I/O -- although Cap'n Proto RPC users typically won't need cannam@133: to use these APIs directly. cannam@133: cannam@133: ## Generated Code cannam@133: cannam@133: Imagine the following interface: cannam@133: cannam@133: {% highlight capnp %} cannam@133: interface Directory { cannam@133: create @0 (name :Text) -> (file :File); cannam@133: open @1 (name :Text) -> (file :File); cannam@133: remove @2 (name :Text); cannam@133: } cannam@133: {% endhighlight %} cannam@133: cannam@133: `capnp compile` will generate code that looks like this (edited for readability): cannam@133: cannam@133: {% highlight c++ %} cannam@133: struct Directory { cannam@133: Directory() = delete; cannam@133: cannam@133: class Client; cannam@133: class Server; cannam@133: cannam@133: struct CreateParams; cannam@133: struct CreateResults; cannam@133: struct OpenParams; cannam@133: struct OpenResults; cannam@133: struct RemoveParams; cannam@133: struct RemoveResults; cannam@133: // Each of these is equivalent to what would be generated for cannam@133: // a Cap'n Proto struct with one field for each parameter / cannam@133: // result. cannam@133: }; cannam@133: cannam@133: class Directory::Client cannam@133: : public virtual capnp::Capability::Client { cannam@133: public: cannam@133: Client(std::nullptr_t); cannam@133: Client(kj::Own server); cannam@133: Client(kj::Promise promise); cannam@133: Client(kj::Exception exception); cannam@133: cannam@133: capnp::Request createRequest(); cannam@133: capnp::Request openRequest(); cannam@133: capnp::Request removeRequest(); cannam@133: }; cannam@133: cannam@133: class Directory::Server cannam@133: : public virtual capnp::Capability::Server { cannam@133: protected: cannam@133: typedef capnp::CallContext CreateContext; cannam@133: typedef capnp::CallContext OpenContext; cannam@133: typedef capnp::CallContext RemoveContext; cannam@133: // Convenience typedefs. cannam@133: cannam@133: virtual kj::Promise create(CreateContext context); cannam@133: virtual kj::Promise open(OpenContext context); cannam@133: virtual kj::Promise remove(RemoveContext context); cannam@133: // Methods for you to implement. cannam@133: }; cannam@133: {% endhighlight %} cannam@133: cannam@133: ### Clients cannam@133: cannam@133: The generated `Client` type represents a reference to a remote `Server`. `Client`s are cannam@133: pass-by-value types that use reference counting under the hood. (Warning: For performance cannam@133: reasons, the reference counting used by `Client`s is not thread-safe, so you must not copy a cannam@133: `Client` to another thread, unless you do it by means of an inter-thread RPC.) cannam@133: cannam@133: A `Client` can be implicitly constructed from any of: cannam@133: cannam@133: * A `kj::Own`, which takes ownership of the server object and creates a client that cannam@133: calls it. (You can get a `kj::Own` to a newly-allocated heap object using cannam@133: `kj::heap(constructorParams)`; see `kj/memory.h`.) cannam@133: * A `kj::Promise`, which creates a client whose methods first wait for the promise to cannam@133: resolve, then forward the call to the resulting client. cannam@133: * A `kj::Exception`, which creates a client whose methods always throw that exception. cannam@133: * `nullptr`, which creates a client whose methods always throw. This is meant to be used to cannam@133: initialize variables that will be initialized to a real value later on. cannam@133: cannam@133: For each interface method `foo()`, the `Client` has a method `fooRequest()` which creates a new cannam@133: request to call `foo()`. The returned `capnp::Request` object has methods equivalent to a cannam@133: `Builder` for the parameter struct (`FooParams`), with the addition of a method `send()`. cannam@133: `send()` sends the RPC and returns a `capnp::RemotePromise`. cannam@133: cannam@133: This `RemotePromise` is equivalent to `kj::Promise>`, but also has cannam@133: methods that allow pipelining. Namely: cannam@133: cannam@133: * For each interface-typed result, it has a getter method which returns a `Client` of that type. cannam@133: Calling this client will send a pipelined call to the server. cannam@133: * For each struct-typed result, it has a getter method which returns an object containing pipeline cannam@133: getters for that struct's fields. cannam@133: cannam@133: In other words, the `RemotePromise` effectively implements a subset of the eventual results' cannam@133: `Reader` interface -- one that only allows access to interfaces and sub-structs. cannam@133: cannam@133: The `RemotePromise` eventually resolves to `capnp::Response`, which behaves like a cannam@133: `Reader` for the result struct except that it also owns the result message. cannam@133: cannam@133: {% highlight c++ %} cannam@133: Directory::Client dir = ...; cannam@133: cannam@133: // Create a new request for the `open()` method. cannam@133: auto request = dir.openRequest(); cannam@133: request.setName("foo"); cannam@133: cannam@133: // Send the request. cannam@133: auto promise = request.send(); cannam@133: cannam@133: // Make a pipelined request. cannam@133: auto promise2 = promise.getFile().getSizeRequest().send(); cannam@133: cannam@133: // Wait for the full results. cannam@133: auto promise3 = promise2.then( cannam@133: [](capnp::Response&& response) { cannam@133: cout << "File size is: " << response.getSize() << endl; cannam@133: }); cannam@133: {% endhighlight %} cannam@133: cannam@133: For [generic methods](language.html#generic-methods), the `fooRequest()` method will be a template; cannam@133: you must explicitly specify type parameters. cannam@133: cannam@133: ### Servers cannam@133: cannam@133: The generated `Server` type is an abstract interface which may be subclassed to implement a cannam@133: capability. Each method takes a `context` argument and returns a `kj::Promise` which cannam@133: resolves when the call is finished. The parameter and result structures are accessed through the cannam@133: context -- `context.getParams()` returns a `Reader` for the parameters, and `context.getResults()` cannam@133: returns a `Builder` for the results. The context also has methods for controlling RPC logistics, cannam@133: such as cancellation -- see `capnp::CallContext` in `capnp/capability.h` for details. cannam@133: cannam@133: Accessing the results through the context (rather than by returning them) is unintuitive, but cannam@133: necessary because the underlying RPC transport needs to have control over where the results are cannam@133: allocated. For example, a zero-copy shared memory transport would need to allocate the results in cannam@133: the shared memory segment. Hence, the method implementation cannot just create its own cannam@133: `MessageBuilder`. cannam@133: cannam@133: {% highlight c++ %} cannam@133: class DirectoryImpl final: public Directory::Server { cannam@133: public: cannam@133: kj::Promise open(OpenContext context) override { cannam@133: auto iter = files.find(context.getParams().getName()); cannam@133: cannam@133: // Throw an exception if not found. cannam@133: KJ_REQUIRE(iter != files.end(), "File not found."); cannam@133: cannam@133: context.getResults().setFile(iter->second); cannam@133: cannam@133: return kj::READY_NOW; cannam@133: } cannam@133: cannam@133: // Any method which we don't implement will simply throw cannam@133: // an exception by default. cannam@133: cannam@133: private: cannam@133: std::map files; cannam@133: }; cannam@133: {% endhighlight %} cannam@133: cannam@133: On the server side, [generic methods](language.html#generic-methods) are NOT templates. Instead, cannam@133: the generated code is exactly as if all of the generic parameters were bound to `AnyPointer`. The cannam@133: server generally does not get to know exactly what type the client requested; it must be designed cannam@133: to be correct for any parameterization. cannam@133: cannam@133: ## Initializing RPC cannam@133: cannam@133: Cap'n Proto makes it easy to start up an RPC client or server using the "EZ RPC" classes, cannam@133: defined in `capnp/ez-rpc.h`. These classes get you up and running quickly, but they hide a lot cannam@133: of details that power users will likely want to manipulate. Check out the comments in `ez-rpc.h` cannam@133: to understand exactly what you get and what you miss. For the purpose of this overview, we'll cannam@133: show you how to use EZ RPC to get started. cannam@133: cannam@133: ### Starting a client cannam@133: cannam@133: A client should typically look like this: cannam@133: cannam@133: {% highlight c++ %} cannam@133: #include cannam@133: #include "my-interface.capnp.h" cannam@133: #include cannam@133: cannam@133: int main(int argc, const char* argv[]) { cannam@133: // We expect one argument specifying the server address. cannam@133: if (argc != 2) { cannam@133: std::cerr << "usage: " << argv[0] << " HOST[:PORT]" << std::endl; cannam@133: return 1; cannam@133: } cannam@133: cannam@133: // Set up the EzRpcClient, connecting to the server on port cannam@133: // 5923 unless a different port was specified by the user. cannam@133: capnp::EzRpcClient client(argv[1], 5923); cannam@133: auto& waitScope = client.getWaitScope(); cannam@133: cannam@133: // Request the bootstrap capability from the server. cannam@133: MyInterface::Client cap = client.getMain(); cannam@133: cannam@133: // Make a call to the capability. cannam@133: auto request = cap.fooRequest(); cannam@133: request.setParam(123); cannam@133: auto promise = request.send(); cannam@133: cannam@133: // Wait for the result. This is the only line that blocks. cannam@133: auto response = promise.wait(waitScope); cannam@133: cannam@133: // All done. cannam@133: std::cout << response.getResult() << std::endl; cannam@133: return 0; cannam@133: } cannam@133: {% endhighlight %} cannam@133: cannam@133: Note that for the connect address, Cap'n Proto supports DNS host names as well as IPv4 and IPv6 cannam@133: addresses. Additionally, a Unix domain socket can be specified as `unix:` followed by a path name. cannam@133: cannam@133: For a more complete example, see the cannam@133: [calculator client sample](https://github.com/sandstorm-io/capnproto/tree/master/c++/samples/calculator-client.c++). cannam@133: cannam@133: ### Starting a server cannam@133: cannam@133: A server might look something like this: cannam@133: cannam@133: {% highlight c++ %} cannam@133: #include cannam@133: #include "my-interface-impl.h" cannam@133: #include cannam@133: cannam@133: int main(int argc, const char* argv[]) { cannam@133: // We expect one argument specifying the address to which cannam@133: // to bind and accept connections. cannam@133: if (argc != 2) { cannam@133: std::cerr << "usage: " << argv[0] << " ADDRESS[:PORT]" cannam@133: << std::endl; cannam@133: return 1; cannam@133: } cannam@133: cannam@133: // Set up the EzRpcServer, binding to port 5923 unless a cannam@133: // different port was specified by the user. Note that the cannam@133: // first parameter here can be any "Client" object or anything cannam@133: // that can implicitly cast to a "Client" object. You can even cannam@133: // re-export a capability imported from another server. cannam@133: capnp::EzRpcServer server(kj::heap(), argv[1], 5923); cannam@133: auto& waitScope = server.getWaitScope(); cannam@133: cannam@133: // Run forever, accepting connections and handling requests. cannam@133: kj::NEVER_DONE.wait(waitScope); cannam@133: } cannam@133: {% endhighlight %} cannam@133: cannam@133: Note that for the bind address, Cap'n Proto supports DNS host names as well as IPv4 and IPv6 cannam@133: addresses. The special address `*` can be used to bind to the same port on all local IPv4 and cannam@133: IPv6 interfaces. Additionally, a Unix domain socket can be specified as `unix:` followed by a cannam@133: path name. cannam@133: cannam@133: For a more complete example, see the cannam@133: [calculator server sample](https://github.com/sandstorm-io/capnproto/tree/master/c++/samples/calculator-server.c++). cannam@133: cannam@133: ## Debugging cannam@133: cannam@133: If you've written a server and you want to connect to it to issue some calls for debugging, perhaps cannam@133: interactively, the easiest way to do it is to use [pycapnp](http://jparyani.github.io/pycapnp/). cannam@133: We have decided not to add RPC functionality to the `capnp` command-line tool because pycapnp is cannam@133: better than anything we might provide.