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_CAPABILITY_H_ Chris@47: #define CAPNP_CAPABILITY_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: #if CAPNP_LITE Chris@47: #error "RPC APIs, including this header, are not available in lite mode." Chris@47: #endif Chris@47: Chris@47: #include Chris@47: #include Chris@47: #include "any.h" Chris@47: #include "pointer-helpers.h" Chris@47: Chris@47: namespace capnp { Chris@47: Chris@47: template Chris@47: class Response; Chris@47: Chris@47: template Chris@47: class RemotePromise: public kj::Promise>, public T::Pipeline { Chris@47: // A Promise which supports pipelined calls. T is typically a struct type. T must declare Chris@47: // an inner "mix-in" type "Pipeline" which implements pipelining; RemotePromise simply Chris@47: // multiply-inherits that type along with Promise>. T::Pipeline must be movable, Chris@47: // but does not need to be copyable (i.e. just like Promise). Chris@47: // Chris@47: // The promise is for an owned pointer so that the RPC system can allocate the MessageReader Chris@47: // itself. Chris@47: Chris@47: public: Chris@47: inline RemotePromise(kj::Promise>&& promise, typename T::Pipeline&& pipeline) Chris@47: : kj::Promise>(kj::mv(promise)), Chris@47: T::Pipeline(kj::mv(pipeline)) {} Chris@47: inline RemotePromise(decltype(nullptr)) Chris@47: : kj::Promise>(nullptr), Chris@47: T::Pipeline(nullptr) {} Chris@47: KJ_DISALLOW_COPY(RemotePromise); Chris@47: RemotePromise(RemotePromise&& other) = default; Chris@47: RemotePromise& operator=(RemotePromise&& other) = default; Chris@47: }; Chris@47: Chris@47: class LocalClient; Chris@47: namespace _ { // private Chris@47: struct RawSchema; Chris@47: struct RawBrandedSchema; Chris@47: extern const RawSchema NULL_INTERFACE_SCHEMA; // defined in schema.c++ Chris@47: class CapabilityServerSetBase; Chris@47: } // namespace _ (private) Chris@47: Chris@47: struct Capability { Chris@47: // A capability without type-safe methods. Typed capability clients wrap `Client` and typed Chris@47: // capability servers subclass `Server` to dispatch to the regular, typed methods. Chris@47: Chris@47: class Client; Chris@47: class Server; Chris@47: Chris@47: struct _capnpPrivate { Chris@47: struct IsInterface; Chris@47: static constexpr uint64_t typeId = 0x3; Chris@47: static constexpr Kind kind = Kind::INTERFACE; Chris@47: static constexpr _::RawSchema const* schema = &_::NULL_INTERFACE_SCHEMA; Chris@47: Chris@47: static const _::RawBrandedSchema* const brand; Chris@47: // Can't quite declare this one inline without including generated-header-support.h. Avoiding Chris@47: // for now by declaring out-of-line. Chris@47: // TODO(cleanup): Split RawSchema stuff into its own header that can be included here, or Chris@47: // something. Chris@47: }; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Capability clients Chris@47: Chris@47: class RequestHook; Chris@47: class ResponseHook; Chris@47: class PipelineHook; Chris@47: class ClientHook; Chris@47: Chris@47: template Chris@47: class Request: public Params::Builder { Chris@47: // A call that hasn't been sent yet. This class extends a Builder for the call's "Params" Chris@47: // structure with a method send() that actually sends it. Chris@47: // Chris@47: // Given a Cap'n Proto method `foo(a :A, b :B): C`, the generated client interface will have Chris@47: // a method `Request fooRequest()` (as well as a convenience method Chris@47: // `RemotePromise foo(A::Reader a, B::Reader b)`). Chris@47: Chris@47: public: Chris@47: inline Request(typename Params::Builder builder, kj::Own&& hook) Chris@47: : Params::Builder(builder), hook(kj::mv(hook)) {} Chris@47: inline Request(decltype(nullptr)): Params::Builder(nullptr) {} Chris@47: Chris@47: RemotePromise send() KJ_WARN_UNUSED_RESULT; Chris@47: // Send the call and return a promise for the results. Chris@47: Chris@47: private: Chris@47: kj::Own hook; Chris@47: Chris@47: friend class Capability::Client; Chris@47: friend struct DynamicCapability; Chris@47: template Chris@47: friend class CallContext; Chris@47: friend class RequestHook; Chris@47: }; Chris@47: Chris@47: template Chris@47: class Response: public Results::Reader { Chris@47: // A completed call. This class extends a Reader for the call's answer structure. The Response Chris@47: // is move-only -- once it goes out-of-scope, the underlying message will be freed. Chris@47: Chris@47: public: Chris@47: inline Response(typename Results::Reader reader, kj::Own&& hook) Chris@47: : Results::Reader(reader), hook(kj::mv(hook)) {} Chris@47: Chris@47: private: Chris@47: kj::Own hook; Chris@47: Chris@47: template Chris@47: friend class Request; Chris@47: friend class ResponseHook; Chris@47: }; Chris@47: Chris@47: class Capability::Client { Chris@47: // Base type for capability clients. Chris@47: Chris@47: public: Chris@47: typedef Capability Reads; Chris@47: typedef Capability Calls; Chris@47: Chris@47: Client(decltype(nullptr)); Chris@47: // If you need to declare a Client before you have anything to assign to it (perhaps because Chris@47: // the assignment is going to occur in an if/else scope), you can start by initializing it to Chris@47: // `nullptr`. The resulting client is not meant to be called and throws exceptions from all Chris@47: // methods. Chris@47: Chris@47: template ()>> Chris@47: Client(kj::Own&& server); Chris@47: // Make a client capability that wraps the given server capability. The server's methods will Chris@47: // only be executed in the given EventLoop, regardless of what thread calls the client's methods. Chris@47: Chris@47: template ()>> Chris@47: Client(kj::Promise&& promise); Chris@47: // Make a client from a promise for a future client. The resulting client queues calls until the Chris@47: // promise resolves. Chris@47: Chris@47: Client(kj::Exception&& exception); Chris@47: // Make a broken client that throws the given exception from all calls. Chris@47: Chris@47: Client(Client& other); Chris@47: Client& operator=(Client& other); Chris@47: // Copies by reference counting. Warning: This refcounting is not thread-safe. All copies of Chris@47: // the client must remain in one thread. Chris@47: Chris@47: Client(Client&&) = default; Chris@47: Client& operator=(Client&&) = default; Chris@47: // Move constructor avoids reference counting. Chris@47: Chris@47: explicit Client(kj::Own&& hook); Chris@47: // For use by the RPC implementation: Wrap a ClientHook. Chris@47: Chris@47: template Chris@47: typename T::Client castAs(); Chris@47: // Reinterpret the capability as implementing the given interface. Note that no error will occur Chris@47: // here if the capability does not actually implement this interface, but later method calls will Chris@47: // fail. It's up to the application to decide how indicate that additional interfaces are Chris@47: // supported. Chris@47: // Chris@47: // TODO(perf): GCC 4.8 / Clang 3.3: rvalue-qualified version for better performance. Chris@47: Chris@47: template Chris@47: typename T::Client castAs(InterfaceSchema schema); Chris@47: // Dynamic version. `T` must be `DynamicCapability`, and you must `#include `. Chris@47: Chris@47: kj::Promise whenResolved(); Chris@47: // If the capability is actually only a promise, the returned promise resolves once the Chris@47: // capability itself has resolved to its final destination (or propagates the exception if Chris@47: // the capability promise is rejected). This is mainly useful for error-checking in the case Chris@47: // where no calls are being made. There is no reason to wait for this before making calls; if Chris@47: // the capability does not resolve, the call results will propagate the error. Chris@47: Chris@47: Request typelessRequest( Chris@47: uint64_t interfaceId, uint16_t methodId, Chris@47: kj::Maybe sizeHint); Chris@47: // Make a request without knowing the types of the params or results. You specify the type ID Chris@47: // and method number manually. Chris@47: Chris@47: // TODO(someday): method(s) for Join Chris@47: Chris@47: protected: Chris@47: Client() = default; Chris@47: Chris@47: template Chris@47: Request newCall(uint64_t interfaceId, uint16_t methodId, Chris@47: kj::Maybe sizeHint); Chris@47: Chris@47: private: Chris@47: kj::Own hook; Chris@47: Chris@47: static kj::Own makeLocalClient(kj::Own&& server); Chris@47: Chris@47: template Chris@47: friend struct _::PointerHelpers; Chris@47: friend struct DynamicCapability; Chris@47: friend class Orphanage; Chris@47: friend struct DynamicStruct; Chris@47: friend struct DynamicList; Chris@47: template Chris@47: friend struct List; Chris@47: friend class _::CapabilityServerSetBase; Chris@47: friend class ClientHook; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Capability servers Chris@47: Chris@47: class CallContextHook; Chris@47: Chris@47: template Chris@47: class CallContext: public kj::DisallowConstCopy { Chris@47: // Wrapper around CallContextHook with a specific return type. Chris@47: // Chris@47: // Methods of this class may only be called from within the server's event loop, not from other Chris@47: // threads. Chris@47: // Chris@47: // The CallContext becomes invalid as soon as the call reports completion. Chris@47: Chris@47: public: Chris@47: explicit CallContext(CallContextHook& hook); Chris@47: Chris@47: typename Params::Reader getParams(); Chris@47: // Get the params payload. Chris@47: Chris@47: void releaseParams(); Chris@47: // Release the params payload. getParams() will throw an exception after this is called. Chris@47: // Releasing the params may allow the RPC system to free up buffer space to handle other Chris@47: // requests. Long-running asynchronous methods should try to call this as early as is Chris@47: // convenient. Chris@47: Chris@47: typename Results::Builder getResults(kj::Maybe sizeHint = nullptr); Chris@47: typename Results::Builder initResults(kj::Maybe sizeHint = nullptr); Chris@47: void setResults(typename Results::Reader value); Chris@47: void adoptResults(Orphan&& value); Chris@47: Orphanage getResultsOrphanage(kj::Maybe sizeHint = nullptr); Chris@47: // Manipulate the results payload. The "Return" message (part of the RPC protocol) will Chris@47: // typically be allocated the first time one of these is called. Some RPC systems may Chris@47: // allocate these messages in a limited space (such as a shared memory segment), therefore the Chris@47: // application should delay calling these as long as is convenient to do so (but don't delay Chris@47: // if doing so would require extra copies later). Chris@47: // Chris@47: // `sizeHint` indicates a guess at the message size. This will usually be used to decide how Chris@47: // much space to allocate for the first message segment (don't worry: only space that is actually Chris@47: // used will be sent on the wire). If omitted, the system decides. The message root pointer Chris@47: // should not be included in the size. So, if you are simply going to copy some existing message Chris@47: // directly into the results, just call `.totalSize()` and pass that in. Chris@47: Chris@47: template Chris@47: kj::Promise tailCall(Request&& tailRequest); Chris@47: // Resolve the call by making a tail call. `tailRequest` is a request that has been filled in Chris@47: // but not yet sent. The context will send the call, then fill in the results with the result Chris@47: // of the call. If tailCall() is used, {get,init,set,adopt}Results (above) *must not* be called. Chris@47: // Chris@47: // The RPC implementation may be able to optimize a tail call to another machine such that the Chris@47: // results never actually pass through this machine. Even if no such optimization is possible, Chris@47: // `tailCall()` may allow pipelined calls to be forwarded optimistically to the new call site. Chris@47: // Chris@47: // In general, this should be the last thing a method implementation calls, and the promise Chris@47: // returned from `tailCall()` should then be returned by the method implementation. Chris@47: Chris@47: void allowCancellation(); Chris@47: // Indicate that it is OK for the RPC system to discard its Promise for this call's result if Chris@47: // the caller cancels the call, thereby transitively canceling any asynchronous operations the Chris@47: // call implementation was performing. This is not done by default because it could represent a Chris@47: // security risk: applications must be carefully written to ensure that they do not end up in Chris@47: // a bad state if an operation is canceled at an arbitrary point. However, for long-running Chris@47: // method calls that hold significant resources, prompt cancellation is often useful. Chris@47: // Chris@47: // Keep in mind that asynchronous cancellation cannot occur while the method is synchronously Chris@47: // executing on a local thread. The method must perform an asynchronous operation or call Chris@47: // `EventLoop::current().evalLater()` to yield control. Chris@47: // Chris@47: // Note: You might think that we should offer `onCancel()` and/or `isCanceled()` methods that Chris@47: // provide notification when the caller cancels the request without forcefully killing off the Chris@47: // promise chain. Unfortunately, this composes poorly with promise forking: the canceled Chris@47: // path may be just one branch of a fork of the result promise. The other branches still want Chris@47: // the call to continue. Promise forking is used within the Cap'n Proto implementation -- in Chris@47: // particular each pipelined call forks the result promise. So, if a caller made a pipelined Chris@47: // call and then dropped the original object, the call should not be canceled, but it would be Chris@47: // excessively complicated for the framework to avoid notififying of cancellation as long as Chris@47: // pipelined calls still exist. Chris@47: Chris@47: private: Chris@47: CallContextHook* hook; Chris@47: Chris@47: friend class Capability::Server; Chris@47: friend struct DynamicCapability; Chris@47: }; Chris@47: Chris@47: class Capability::Server { Chris@47: // Objects implementing a Cap'n Proto interface must subclass this. Typically, such objects Chris@47: // will instead subclass a typed Server interface which will take care of implementing Chris@47: // dispatchCall(). Chris@47: Chris@47: public: Chris@47: typedef Capability Serves; Chris@47: Chris@47: virtual kj::Promise dispatchCall(uint64_t interfaceId, uint16_t methodId, Chris@47: CallContext context) = 0; Chris@47: // Call the given method. `params` is the input struct, and should be released as soon as it Chris@47: // is no longer needed. `context` may be used to allocate the output struct and deal with Chris@47: // cancellation. Chris@47: Chris@47: // TODO(someday): Method which can optionally be overridden to implement Join when the object is Chris@47: // a proxy. Chris@47: Chris@47: protected: Chris@47: inline Capability::Client thisCap(); Chris@47: // Get a capability pointing to this object, much like the `this` keyword. Chris@47: // Chris@47: // The effect of this method is undefined if: Chris@47: // - No capability client has been created pointing to this object. (This is always the case in Chris@47: // the server's constructor.) Chris@47: // - The capability client pointing at this object has been destroyed. (This is always the case Chris@47: // in the server's destructor.) Chris@47: // - Multiple capability clients have been created around the same server (possible if the server Chris@47: // is refcounted, which is not recommended since the client itself provides refcounting). Chris@47: Chris@47: template Chris@47: CallContext internalGetTypedContext( Chris@47: CallContext typeless); Chris@47: kj::Promise internalUnimplemented(const char* actualInterfaceName, Chris@47: uint64_t requestedTypeId); Chris@47: kj::Promise internalUnimplemented(const char* interfaceName, Chris@47: uint64_t typeId, uint16_t methodId); Chris@47: kj::Promise internalUnimplemented(const char* interfaceName, const char* methodName, Chris@47: uint64_t typeId, uint16_t methodId); Chris@47: Chris@47: private: Chris@47: ClientHook* thisHook = nullptr; Chris@47: friend class LocalClient; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: Chris@47: class ReaderCapabilityTable: private _::CapTableReader { Chris@47: // Class which imbues Readers with the ability to read capabilities. Chris@47: // Chris@47: // In Cap'n Proto format, the encoding of a capability pointer is simply an integer index into Chris@47: // an external table. Since these pointers fundamentally point outside the message, a Chris@47: // MessageReader by default has no idea what they point at, and therefore reading capabilities Chris@47: // from such a reader will throw exceptions. Chris@47: // Chris@47: // In order to be able to read capabilities, you must first attach a capability table, using Chris@47: // this class. By "imbuing" a Reader, you get a new Reader which will interpret capability Chris@47: // pointers by treating them as indexes into the ReaderCapabilityTable. Chris@47: // Chris@47: // Note that when using Cap'n Proto's RPC system, this is handled automatically. Chris@47: Chris@47: public: Chris@47: explicit ReaderCapabilityTable(kj::Array>> table); Chris@47: KJ_DISALLOW_COPY(ReaderCapabilityTable); Chris@47: Chris@47: template Chris@47: T imbue(T reader); Chris@47: // Return a reader equivalent to `reader` except that when reading capability-valued fields, Chris@47: // the capabilities are looked up in this table. Chris@47: Chris@47: private: Chris@47: kj::Array>> table; Chris@47: Chris@47: kj::Maybe> extractCap(uint index) override; Chris@47: }; Chris@47: Chris@47: class BuilderCapabilityTable: private _::CapTableBuilder { Chris@47: // Class which imbues Builders with the ability to read and write capabilities. Chris@47: // Chris@47: // This is much like ReaderCapabilityTable, except for builders. The table starts out empty, Chris@47: // but capabilities can be added to it over time. Chris@47: Chris@47: public: Chris@47: BuilderCapabilityTable(); Chris@47: KJ_DISALLOW_COPY(BuilderCapabilityTable); Chris@47: Chris@47: inline kj::ArrayPtr>> getTable() { return table; } Chris@47: Chris@47: template Chris@47: T imbue(T builder); Chris@47: // Return a builder equivalent to `builder` except that when reading capability-valued fields, Chris@47: // the capabilities are looked up in this table. Chris@47: Chris@47: private: Chris@47: kj::Vector>> table; Chris@47: Chris@47: kj::Maybe> extractCap(uint index) override; Chris@47: uint injectCap(kj::Own&& cap) override; Chris@47: void dropCap(uint index) override; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: Chris@47: namespace _ { // private Chris@47: Chris@47: class CapabilityServerSetBase { Chris@47: public: Chris@47: Capability::Client addInternal(kj::Own&& server, void* ptr); Chris@47: kj::Promise getLocalServerInternal(Capability::Client& client); Chris@47: }; Chris@47: Chris@47: } // namespace _ (private) Chris@47: Chris@47: template Chris@47: class CapabilityServerSet: private _::CapabilityServerSetBase { Chris@47: // Allows a server to recognize its own capabilities when passed back to it, and obtain the Chris@47: // underlying Server objects associated with them. Chris@47: // Chris@47: // All objects in the set must have the same interface type T. The objects may implement various Chris@47: // interfaces derived from T (and in fact T can be `capnp::Capability` to accept all objects), Chris@47: // but note that if you compile with RTTI disabled then you will not be able to down-cast through Chris@47: // virtual inheritance, and all inheritance between server interfaces is virtual. So, with RTTI Chris@47: // disabled, you will likely need to set T to be the most-derived Cap'n Proto interface type, Chris@47: // and you server class will need to be directly derived from that, so that you can use Chris@47: // static_cast (or kj::downcast) to cast to it after calling getLocalServer(). (If you compile Chris@47: // with RTTI, then you can freely dynamic_cast and ignore this issue!) Chris@47: Chris@47: public: Chris@47: CapabilityServerSet() = default; Chris@47: KJ_DISALLOW_COPY(CapabilityServerSet); Chris@47: Chris@47: typename T::Client add(kj::Own&& server); Chris@47: // Create a new capability Client for the given Server and also add this server to the set. Chris@47: Chris@47: kj::Promise> getLocalServer(typename T::Client& client); Chris@47: // Given a Client pointing to a server previously passed to add(), return the corresponding Chris@47: // Server. This returns a promise because if the input client is itself a promise, this must Chris@47: // wait for it to resolve. Keep in mind that the server will be deleted when all clients are Chris@47: // gone, so the caller should make sure to keep the client alive (hence why this method only Chris@47: // accepts an lvalue input). Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Hook interfaces which must be implemented by the RPC system. Applications never call these Chris@47: // directly; the RPC system implements them and the types defined earlier in this file wrap them. Chris@47: Chris@47: class RequestHook { Chris@47: // Hook interface implemented by RPC system representing a request being built. Chris@47: Chris@47: public: Chris@47: virtual RemotePromise send() = 0; Chris@47: // Send the call and return a promise for the result. Chris@47: Chris@47: virtual const void* getBrand() = 0; Chris@47: // Returns a void* that identifies who made this request. This can be used by an RPC adapter to Chris@47: // discover when tail call is going to be sent over its own connection and therefore can be Chris@47: // optimized into a remote tail call. Chris@47: Chris@47: template Chris@47: inline static kj::Own from(Request&& request) { Chris@47: return kj::mv(request.hook); Chris@47: } Chris@47: }; Chris@47: Chris@47: class ResponseHook { Chris@47: // Hook interface implemented by RPC system representing a response. Chris@47: // Chris@47: // At present this class has no methods. It exists only for garbage collection -- when the Chris@47: // ResponseHook is destroyed, the results can be freed. Chris@47: Chris@47: public: Chris@47: virtual ~ResponseHook() noexcept(false); Chris@47: // Just here to make sure the type is dynamic. Chris@47: Chris@47: template Chris@47: inline static kj::Own from(Response&& response) { Chris@47: return kj::mv(response.hook); Chris@47: } Chris@47: }; Chris@47: Chris@47: // class PipelineHook is declared in any.h because it is needed there. Chris@47: Chris@47: class ClientHook { Chris@47: public: Chris@47: ClientHook(); Chris@47: Chris@47: virtual Request newCall( Chris@47: uint64_t interfaceId, uint16_t methodId, kj::Maybe sizeHint) = 0; Chris@47: // Start a new call, allowing the client to allocate request/response objects as it sees fit. Chris@47: // This version is used when calls are made from application code in the local process. Chris@47: Chris@47: struct VoidPromiseAndPipeline { Chris@47: kj::Promise promise; Chris@47: kj::Own pipeline; Chris@47: }; Chris@47: Chris@47: virtual VoidPromiseAndPipeline call(uint64_t interfaceId, uint16_t methodId, Chris@47: kj::Own&& context) = 0; Chris@47: // Call the object, but the caller controls allocation of the request/response objects. If the Chris@47: // callee insists on allocating these objects itself, it must make a copy. This version is used Chris@47: // when calls come in over the network via an RPC system. Note that even if the returned Chris@47: // `Promise` is discarded, the call may continue executing if any pipelined calls are Chris@47: // waiting for it. Chris@47: // Chris@47: // Since the caller of this method chooses the CallContext implementation, it is the caller's Chris@47: // responsibility to ensure that the returned promise is not canceled unless allowed via Chris@47: // the context's `allowCancellation()`. Chris@47: // Chris@47: // The call must not begin synchronously; the callee must arrange for the call to begin in a Chris@47: // later turn of the event loop. Otherwise, application code may call back and affect the Chris@47: // callee's state in an unexpected way. Chris@47: Chris@47: virtual kj::Maybe getResolved() = 0; Chris@47: // If this ClientHook is a promise that has already resolved, returns the inner, resolved version Chris@47: // of the capability. The caller may permanently replace this client with the resolved one if Chris@47: // desired. Returns null if the client isn't a promise or hasn't resolved yet -- use Chris@47: // `whenMoreResolved()` to distinguish between them. Chris@47: Chris@47: virtual kj::Maybe>> whenMoreResolved() = 0; Chris@47: // If this client is a settled reference (not a promise), return nullptr. Otherwise, return a Chris@47: // promise that eventually resolves to a new client that is closer to being the final, settled Chris@47: // client (i.e. the value eventually returned by `getResolved()`). Calling this repeatedly Chris@47: // should eventually produce a settled client. Chris@47: Chris@47: kj::Promise whenResolved(); Chris@47: // Repeatedly calls whenMoreResolved() until it returns nullptr. Chris@47: Chris@47: virtual kj::Own addRef() = 0; Chris@47: // Return a new reference to the same capability. Chris@47: Chris@47: virtual const void* getBrand() = 0; Chris@47: // Returns a void* that identifies who made this client. This can be used by an RPC adapter to Chris@47: // discover when a capability it needs to marshal is one that it created in the first place, and Chris@47: // therefore it can transfer the capability without proxying. Chris@47: Chris@47: static const uint NULL_CAPABILITY_BRAND; Chris@47: // Value is irrelevant; used for pointer. Chris@47: Chris@47: inline bool isNull() { return getBrand() == &NULL_CAPABILITY_BRAND; } Chris@47: // Returns true if the capability was created as a result of assigning a Client to null or by Chris@47: // reading a null pointer out of a Cap'n Proto message. Chris@47: Chris@47: virtual void* getLocalServer(_::CapabilityServerSetBase& capServerSet); Chris@47: // If this is a local capability created through `capServerSet`, return the underlying Server. Chris@47: // Otherwise, return nullptr. Default implementation (which everyone except LocalClient should Chris@47: // use) always returns nullptr. Chris@47: Chris@47: static kj::Own from(Capability::Client client) { return kj::mv(client.hook); } Chris@47: }; Chris@47: Chris@47: class CallContextHook { Chris@47: // Hook interface implemented by RPC system to manage a call on the server side. See Chris@47: // CallContext. Chris@47: Chris@47: public: Chris@47: virtual AnyPointer::Reader getParams() = 0; Chris@47: virtual void releaseParams() = 0; Chris@47: virtual AnyPointer::Builder getResults(kj::Maybe sizeHint) = 0; Chris@47: virtual kj::Promise tailCall(kj::Own&& request) = 0; Chris@47: virtual void allowCancellation() = 0; Chris@47: Chris@47: virtual kj::Promise onTailCall() = 0; Chris@47: // If `tailCall()` is called, resolves to the PipelineHook from the tail call. An Chris@47: // implementation of `ClientHook::call()` is allowed to call this at most once. Chris@47: Chris@47: virtual ClientHook::VoidPromiseAndPipeline directTailCall(kj::Own&& request) = 0; Chris@47: // Call this when you would otherwise call onTailCall() immediately followed by tailCall(). Chris@47: // Implementations of tailCall() should typically call directTailCall() and then fulfill the Chris@47: // promise fulfiller for onTailCall() with the returned pipeline. Chris@47: Chris@47: virtual kj::Own addRef() = 0; Chris@47: }; Chris@47: Chris@47: kj::Own newLocalPromiseClient(kj::Promise>&& promise); Chris@47: // Returns a ClientHook that queues up calls until `promise` resolves, then forwards them to Chris@47: // the new client. This hook's `getResolved()` and `whenMoreResolved()` methods will reflect the Chris@47: // redirection to the eventual replacement client. Chris@47: Chris@47: kj::Own newLocalPromisePipeline(kj::Promise>&& promise); Chris@47: // Returns a PipelineHook that queues up calls until `promise` resolves, then forwards them to Chris@47: // the new pipeline. Chris@47: Chris@47: kj::Own newBrokenCap(kj::StringPtr reason); Chris@47: kj::Own newBrokenCap(kj::Exception&& reason); Chris@47: // Helper function that creates a capability which simply throws exceptions when called. Chris@47: Chris@47: kj::Own newBrokenPipeline(kj::Exception&& reason); Chris@47: // Helper function that creates a pipeline which simply throws exceptions when called. Chris@47: Chris@47: Request newBrokenRequest( Chris@47: kj::Exception&& reason, kj::Maybe sizeHint); Chris@47: // Helper function that creates a Request object that simply throws exceptions when sent. Chris@47: Chris@47: // ======================================================================================= Chris@47: // Extend PointerHelpers for interfaces Chris@47: Chris@47: namespace _ { // private Chris@47: Chris@47: template Chris@47: struct PointerHelpers { Chris@47: static inline typename T::Client get(PointerReader reader) { Chris@47: return typename T::Client(reader.getCapability()); Chris@47: } Chris@47: static inline typename T::Client get(PointerBuilder builder) { Chris@47: return typename T::Client(builder.getCapability()); Chris@47: } Chris@47: static inline void set(PointerBuilder builder, typename T::Client&& value) { Chris@47: builder.setCapability(kj::mv(value.Capability::Client::hook)); Chris@47: } Chris@47: static inline void set(PointerBuilder builder, typename T::Client& value) { Chris@47: builder.setCapability(value.Capability::Client::hook->addRef()); Chris@47: } Chris@47: static inline void adopt(PointerBuilder builder, Orphan&& value) { Chris@47: builder.adopt(kj::mv(value.builder)); Chris@47: } Chris@47: static inline Orphan disown(PointerBuilder builder) { Chris@47: return Orphan(builder.disown()); Chris@47: } Chris@47: }; Chris@47: Chris@47: } // namespace _ (private) Chris@47: Chris@47: // ======================================================================================= Chris@47: // Extend List for interfaces Chris@47: Chris@47: template Chris@47: struct List { Chris@47: List() = delete; Chris@47: Chris@47: class Reader { Chris@47: public: Chris@47: typedef List Reads; Chris@47: Chris@47: Reader() = default; Chris@47: inline explicit Reader(_::ListReader reader): reader(reader) {} Chris@47: Chris@47: inline uint size() const { return reader.size() / ELEMENTS; } Chris@47: inline typename T::Client operator[](uint index) const { Chris@47: KJ_IREQUIRE(index < size()); Chris@47: return typename T::Client(reader.getPointerElement(index * ELEMENTS).getCapability()); Chris@47: } Chris@47: Chris@47: typedef _::IndexingIterator Iterator; Chris@47: inline Iterator begin() const { return Iterator(this, 0); } Chris@47: inline Iterator end() const { return Iterator(this, size()); } Chris@47: Chris@47: private: Chris@47: _::ListReader reader; Chris@47: template Chris@47: friend struct _::PointerHelpers; Chris@47: template Chris@47: friend struct List; Chris@47: friend class Orphanage; Chris@47: template Chris@47: friend struct ToDynamic_; Chris@47: }; Chris@47: Chris@47: class Builder { Chris@47: public: Chris@47: typedef List Builds; Chris@47: Chris@47: Builder() = delete; Chris@47: inline Builder(decltype(nullptr)) {} Chris@47: inline explicit Builder(_::ListBuilder builder): builder(builder) {} Chris@47: Chris@47: inline operator Reader() const { return Reader(builder.asReader()); } Chris@47: inline Reader asReader() const { return Reader(builder.asReader()); } Chris@47: Chris@47: inline uint size() const { return builder.size() / ELEMENTS; } Chris@47: inline typename T::Client operator[](uint index) { Chris@47: KJ_IREQUIRE(index < size()); Chris@47: return typename T::Client(builder.getPointerElement(index * ELEMENTS).getCapability()); Chris@47: } Chris@47: inline void set(uint index, typename T::Client value) { Chris@47: KJ_IREQUIRE(index < size()); Chris@47: builder.getPointerElement(index * ELEMENTS).setCapability(kj::mv(value.hook)); Chris@47: } Chris@47: inline void adopt(uint index, Orphan&& value) { Chris@47: KJ_IREQUIRE(index < size()); Chris@47: builder.getPointerElement(index * ELEMENTS).adopt(kj::mv(value)); Chris@47: } Chris@47: inline Orphan disown(uint index) { Chris@47: KJ_IREQUIRE(index < size()); Chris@47: return Orphan(builder.getPointerElement(index * ELEMENTS).disown()); Chris@47: } Chris@47: Chris@47: typedef _::IndexingIterator Iterator; Chris@47: inline Iterator begin() { return Iterator(this, 0); } Chris@47: inline Iterator end() { return Iterator(this, size()); } Chris@47: Chris@47: private: Chris@47: _::ListBuilder builder; Chris@47: friend class Orphanage; Chris@47: template Chris@47: friend struct ToDynamic_; Chris@47: }; Chris@47: Chris@47: private: Chris@47: inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) { Chris@47: return builder.initList(ElementSize::POINTER, size * ELEMENTS); Chris@47: } Chris@47: inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) { Chris@47: return builder.getList(ElementSize::POINTER, defaultValue); Chris@47: } Chris@47: inline static _::ListReader getFromPointer( Chris@47: const _::PointerReader& reader, const word* defaultValue) { Chris@47: return reader.getList(ElementSize::POINTER, defaultValue); Chris@47: } Chris@47: Chris@47: template Chris@47: friend struct List; Chris@47: template Chris@47: friend struct _::PointerHelpers; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Inline implementation details Chris@47: Chris@47: template Chris@47: RemotePromise Request::send() { Chris@47: auto typelessPromise = hook->send(); Chris@47: hook = nullptr; // prevent reuse Chris@47: Chris@47: // Convert the Promise to return the correct response type. Chris@47: // Explicitly upcast to kj::Promise to make clear that calling .then() doesn't invalidate the Chris@47: // Pipeline part of the RemotePromise. Chris@47: auto typedPromise = kj::implicitCast>&>(typelessPromise) Chris@47: .then([](Response&& response) -> Response { Chris@47: return Response(response.getAs(), kj::mv(response.hook)); Chris@47: }); Chris@47: Chris@47: // Wrap the typeless pipeline in a typed wrapper. Chris@47: typename Results::Pipeline typedPipeline( Chris@47: kj::mv(kj::implicitCast(typelessPromise))); Chris@47: Chris@47: return RemotePromise(kj::mv(typedPromise), kj::mv(typedPipeline)); Chris@47: } Chris@47: Chris@47: inline Capability::Client::Client(kj::Own&& hook): hook(kj::mv(hook)) {} Chris@47: template Chris@47: inline Capability::Client::Client(kj::Own&& server) Chris@47: : hook(makeLocalClient(kj::mv(server))) {} Chris@47: template Chris@47: inline Capability::Client::Client(kj::Promise&& promise) Chris@47: : hook(newLocalPromiseClient(promise.then([](T&& t) { return kj::mv(t.hook); }))) {} Chris@47: inline Capability::Client::Client(Client& other): hook(other.hook->addRef()) {} Chris@47: inline Capability::Client& Capability::Client::operator=(Client& other) { Chris@47: hook = other.hook->addRef(); Chris@47: return *this; Chris@47: } Chris@47: template Chris@47: inline typename T::Client Capability::Client::castAs() { Chris@47: return typename T::Client(hook->addRef()); Chris@47: } Chris@47: inline kj::Promise Capability::Client::whenResolved() { Chris@47: return hook->whenResolved(); Chris@47: } Chris@47: inline Request Capability::Client::typelessRequest( Chris@47: uint64_t interfaceId, uint16_t methodId, Chris@47: kj::Maybe sizeHint) { Chris@47: return newCall(interfaceId, methodId, sizeHint); Chris@47: } Chris@47: template Chris@47: inline Request Capability::Client::newCall( Chris@47: uint64_t interfaceId, uint16_t methodId, kj::Maybe sizeHint) { Chris@47: auto typeless = hook->newCall(interfaceId, methodId, sizeHint); Chris@47: return Request(typeless.template getAs(), kj::mv(typeless.hook)); Chris@47: } Chris@47: Chris@47: template Chris@47: inline CallContext::CallContext(CallContextHook& hook): hook(&hook) {} Chris@47: template Chris@47: inline typename Params::Reader CallContext::getParams() { Chris@47: return hook->getParams().template getAs(); Chris@47: } Chris@47: template Chris@47: inline void CallContext::releaseParams() { Chris@47: hook->releaseParams(); Chris@47: } Chris@47: template Chris@47: inline typename Results::Builder CallContext::getResults( Chris@47: kj::Maybe sizeHint) { Chris@47: // `template` keyword needed due to: http://llvm.org/bugs/show_bug.cgi?id=17401 Chris@47: return hook->getResults(sizeHint).template getAs(); Chris@47: } Chris@47: template Chris@47: inline typename Results::Builder CallContext::initResults( Chris@47: kj::Maybe sizeHint) { Chris@47: // `template` keyword needed due to: http://llvm.org/bugs/show_bug.cgi?id=17401 Chris@47: return hook->getResults(sizeHint).template initAs(); Chris@47: } Chris@47: template Chris@47: inline void CallContext::setResults(typename Results::Reader value) { Chris@47: hook->getResults(value.totalSize()).template setAs(value); Chris@47: } Chris@47: template Chris@47: inline void CallContext::adoptResults(Orphan&& value) { Chris@47: hook->getResults(nullptr).adopt(kj::mv(value)); Chris@47: } Chris@47: template Chris@47: inline Orphanage CallContext::getResultsOrphanage( Chris@47: kj::Maybe sizeHint) { Chris@47: return Orphanage::getForMessageContaining(hook->getResults(sizeHint)); Chris@47: } Chris@47: template Chris@47: template Chris@47: inline kj::Promise CallContext::tailCall( Chris@47: Request&& tailRequest) { Chris@47: return hook->tailCall(kj::mv(tailRequest.hook)); Chris@47: } Chris@47: template Chris@47: inline void CallContext::allowCancellation() { Chris@47: hook->allowCancellation(); Chris@47: } Chris@47: Chris@47: template Chris@47: CallContext Capability::Server::internalGetTypedContext( Chris@47: CallContext typeless) { Chris@47: return CallContext(*typeless.hook); Chris@47: } Chris@47: Chris@47: Capability::Client Capability::Server::thisCap() { Chris@47: return Client(thisHook->addRef()); Chris@47: } Chris@47: Chris@47: template Chris@47: T ReaderCapabilityTable::imbue(T reader) { Chris@47: return T(_::PointerHelpers>::getInternalReader(reader).imbue(this)); Chris@47: } Chris@47: Chris@47: template Chris@47: T BuilderCapabilityTable::imbue(T builder) { Chris@47: return T(_::PointerHelpers>::getInternalBuilder(kj::mv(builder)).imbue(this)); Chris@47: } Chris@47: Chris@47: template Chris@47: typename T::Client CapabilityServerSet::add(kj::Own&& server) { Chris@47: void* ptr = reinterpret_cast(server.get()); Chris@47: // Clang insists that `castAs` is a template-dependent member and therefore we need the Chris@47: // `template` keyword here, but AFAICT this is wrong: addImpl() is not a template. Chris@47: return addInternal(kj::mv(server), ptr).template castAs(); Chris@47: } Chris@47: Chris@47: template Chris@47: kj::Promise> CapabilityServerSet::getLocalServer( Chris@47: typename T::Client& client) { Chris@47: return getLocalServerInternal(client) Chris@47: .then([](void* server) -> kj::Maybe { Chris@47: if (server == nullptr) { Chris@47: return nullptr; Chris@47: } else { Chris@47: return *reinterpret_cast(server); Chris@47: } Chris@47: }); Chris@47: } Chris@47: Chris@47: template Chris@47: struct Orphanage::GetInnerReader { Chris@47: static inline kj::Own apply(typename T::Client t) { Chris@47: return ClientHook::from(kj::mv(t)); Chris@47: } Chris@47: }; Chris@47: Chris@47: } // namespace capnp Chris@47: Chris@47: #endif // CAPNP_CAPABILITY_H_