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