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