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