capability.h 36.4 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21 22 23 24

#ifndef CAPNP_CAPABILITY_H_
#define CAPNP_CAPABILITY_H_

25 26 27 28
#if defined(__GNUC__) && !CAPNP_HEADER_WARNINGS
#pragma GCC system_header
#endif

29 30 31 32
#if CAPNP_LITE
#error "RPC APIs, including this header, are not available in lite mode."
#endif

33
#include <kj/async.h>
34
#include <kj/vector.h>
35
#include "any.h"
36
#include "pointer-helpers.h"
37 38 39

namespace capnp {

40
template <typename Results>
41 42
class Response;

43
template <typename T>
44 45 46 47 48 49 50 51
class RemotePromise: public kj::Promise<Response<T>>, public T::Pipeline {
  // A Promise which supports pipelined calls.  T is typically a struct type.  T must declare
  // an inner "mix-in" type "Pipeline" which implements pipelining; RemotePromise simply
  // multiply-inherits that type along with Promise<Response<T>>.  T::Pipeline must be movable,
  // but does not need to be copyable (i.e. just like Promise<T>).
  //
  // The promise is for an owned pointer so that the RPC system can allocate the MessageReader
  // itself.
52 53

public:
54 55
  inline RemotePromise(kj::Promise<Response<T>>&& promise, typename T::Pipeline&& pipeline)
      : kj::Promise<Response<T>>(kj::mv(promise)),
56 57
        T::Pipeline(kj::mv(pipeline)) {}
  inline RemotePromise(decltype(nullptr))
58 59
      : kj::Promise<Response<T>>(nullptr),
        T::Pipeline(nullptr) {}
60 61 62 63 64
  KJ_DISALLOW_COPY(RemotePromise);
  RemotePromise(RemotePromise&& other) = default;
  RemotePromise& operator=(RemotePromise&& other) = default;
};

65
class LocalClient;
66 67
namespace _ { // private
struct RawSchema;
68
struct RawBrandedSchema;
69
extern const RawSchema NULL_INTERFACE_SCHEMA;  // defined in schema.c++
70
class CapabilityServerSetBase;
71 72 73 74 75 76 77 78 79 80
}  // namespace _ (private)

struct Capability {
  // A capability without type-safe methods.  Typed capability clients wrap `Client` and typed
  // capability servers subclass `Server` to dispatch to the regular, typed methods.

  class Client;
  class Server;

  struct _capnpPrivate {
81
    struct IsInterface;
82 83 84
    static constexpr uint64_t typeId = 0x3;
    static constexpr Kind kind = Kind::INTERFACE;
    static constexpr _::RawSchema const* schema = &_::NULL_INTERFACE_SCHEMA;
85 86 87 88 89 90

    static const _::RawBrandedSchema* const brand;
    // Can't quite declare this one inline without including generated-header-support.h. Avoiding
    // for now by declaring out-of-line.
    // TODO(cleanup): Split RawSchema stuff into its own header that can be included here, or
    //   something.
91 92 93
  };
};

94
// =======================================================================================
95
// Capability clients
96

97 98 99 100
class RequestHook;
class ResponseHook;
class PipelineHook;
class ClientHook;
101

102
template <typename Params, typename Results>
103 104 105 106 107 108 109
class Request: public Params::Builder {
  // A call that hasn't been sent yet.  This class extends a Builder for the call's "Params"
  // structure with a method send() that actually sends it.
  //
  // Given a Cap'n Proto method `foo(a :A, b :B): C`, the generated client interface will have
  // a method `Request<FooParams, C> startFoo()` (as well as a convenience method
  // `RemotePromise<C> foo(A::Reader a, B::Reader b)`).
110 111

public:
112 113
  inline Request(typename Params::Builder builder, kj::Own<RequestHook>&& hook)
      : Params::Builder(builder), hook(kj::mv(hook)) {}
114

115 116
  RemotePromise<Results> send();
  // Send the call and return a promise for the results.
117

118 119
private:
  kj::Own<RequestHook> hook;
120 121

  friend class Capability::Client;
122
  friend struct DynamicCapability;
123 124
  template <typename, typename>
  friend class CallContext;
125
  friend class RequestHook;
126 127
};

128 129
template <typename Results>
class Response: public Results::Reader {
130 131 132 133
  // A completed call.  This class extends a Reader for the call's answer structure.  The Response
  // is move-only -- once it goes out-of-scope, the underlying message will be freed.

public:
134
  inline Response(typename Results::Reader reader, kj::Own<ResponseHook>&& hook)
135
      : Results::Reader(reader), hook(kj::mv(hook)) {}
136 137

private:
138
  kj::Own<ResponseHook> hook;
139 140 141

  template <typename, typename>
  friend class Request;
142
  friend class ResponseHook;
143 144 145 146 147 148
};

class Capability::Client {
  // Base type for capability clients.

public:
149 150 151
  typedef Capability Reads;
  typedef Capability Calls;

152
  Client(decltype(nullptr));
153 154 155 156
  // If you need to declare a Client before you have anything to assign to it (perhaps because
  // the assignment is going to occur in an if/else scope), you can start by initializing it to
  // `nullptr`.  The resulting client is not meant to be called and throws exceptions from all
  // methods.
157

158
  template <typename T, typename = kj::EnableIf<kj::canConvert<T*, Capability::Server*>()>>
159
  Client(kj::Own<T>&& server);
160 161 162
  // Make a client capability that wraps the given server capability.  The server's methods will
  // only be executed in the given EventLoop, regardless of what thread calls the client's methods.

163
  template <typename T, typename = kj::EnableIf<kj::canConvert<T*, Client*>()>>
164
  Client(kj::Promise<T>&& promise);
165 166 167 168 169 170
  // Make a client from a promise for a future client.  The resulting client queues calls until the
  // promise resolves.

  Client(kj::Exception&& exception);
  // Make a broken client that throws the given exception from all calls.

171 172 173 174
  Client(Client& other);
  Client& operator=(Client& other);
  // Copies by reference counting.  Warning:  This refcounting is not thread-safe.  All copies of
  // the client must remain in one thread.
175 176 177

  Client(Client&&) = default;
  Client& operator=(Client&&) = default;
178
  // Move constructor avoids reference counting.
179

180
  explicit Client(kj::Own<ClientHook>&& hook);
181 182
  // For use by the RPC implementation:  Wrap a ClientHook.

183
  template <typename T>
184
  typename T::Client castAs();
185 186 187 188 189
  // Reinterpret the capability as implementing the given interface.  Note that no error will occur
  // here if the capability does not actually implement this interface, but later method calls will
  // fail.  It's up to the application to decide how indicate that additional interfaces are
  // supported.
  //
Kenton Varda's avatar
Kenton Varda committed
190
  // TODO(perf):  GCC 4.8 / Clang 3.3:  rvalue-qualified version for better performance.
191 192

  template <typename T>
193
  typename T::Client castAs(InterfaceSchema schema);
194 195
  // Dynamic version.  `T` must be `DynamicCapability`, and you must `#include <capnp/dynamic.h>`.

196
  kj::Promise<void> whenResolved();
197 198 199 200 201 202
  // If the capability is actually only a promise, the returned promise resolves once the
  // capability itself has resolved to its final destination (or propagates the exception if
  // the capability promise is rejected).  This is mainly useful for error-checking in the case
  // where no calls are being made.  There is no reason to wait for this before making calls; if
  // the capability does not resolve, the call results will propagate the error.

203 204 205 206 207 208
  Request<AnyPointer, AnyPointer> typelessRequest(
      uint64_t interfaceId, uint16_t methodId,
      kj::Maybe<MessageSize> sizeHint);
  // Make a request without knowing the types of the params or results. You specify the type ID
  // and method number manually.

209
  // TODO(someday):  method(s) for Join
210

211 212 213 214 215
protected:
  Client() = default;

  template <typename Params, typename Results>
  Request<Params, Results> newCall(uint64_t interfaceId, uint16_t methodId,
216
                                   kj::Maybe<MessageSize> sizeHint);
217

218
private:
219
  kj::Own<ClientHook> hook;
220

221
  static kj::Own<ClientHook> makeLocalClient(kj::Own<Capability::Server>&& server);
222

Kenton Varda's avatar
Kenton Varda committed
223 224
  template <typename, Kind>
  friend struct _::PointerHelpers;
225 226 227 228 229 230
  friend struct DynamicCapability;
  friend class Orphanage;
  friend struct DynamicStruct;
  friend struct DynamicList;
  template <typename, Kind>
  friend struct List;
231
  friend class _::CapabilityServerSetBase;
232
  friend class ClientHook;
233 234 235
};

// =======================================================================================
236
// Capability servers
237 238 239

class CallContextHook;

240
template <typename Params, typename Results>
241
class CallContext: public kj::DisallowConstCopy {
242
  // Wrapper around CallContextHook with a specific return type.
243 244 245
  //
  // Methods of this class may only be called from within the server's event loop, not from other
  // threads.
Kenton Varda's avatar
Kenton Varda committed
246 247
  //
  // The CallContext becomes invalid as soon as the call reports completion.
248 249

public:
250 251 252 253 254 255 256 257 258 259 260
  explicit CallContext(CallContextHook& hook);

  typename Params::Reader getParams();
  // Get the params payload.

  void releaseParams();
  // Release the params payload.  getParams() will throw an exception after this is called.
  // Releasing the params may allow the RPC system to free up buffer space to handle other
  // requests.  Long-running asynchronous methods should try to call this as early as is
  // convenient.

261 262
  typename Results::Builder getResults(kj::Maybe<MessageSize> sizeHint = nullptr);
  typename Results::Builder initResults(kj::Maybe<MessageSize> sizeHint = nullptr);
263 264
  void setResults(typename Results::Reader value);
  void adoptResults(Orphan<Results>&& value);
265
  Orphanage getResultsOrphanage(kj::Maybe<MessageSize> sizeHint = nullptr);
266 267
  // Manipulate the results payload.  The "Return" message (part of the RPC protocol) will
  // typically be allocated the first time one of these is called.  Some RPC systems may
268 269 270
  // allocate these messages in a limited space (such as a shared memory segment), therefore the
  // application should delay calling these as long as is convenient to do so (but don't delay
  // if doing so would require extra copies later).
Kenton Varda's avatar
Kenton Varda committed
271
  //
272 273 274 275 276
  // `sizeHint` indicates a guess at the message size.  This will usually be used to decide how
  // much space to allocate for the first message segment (don't worry: only space that is actually
  // used will be sent on the wire).  If omitted, the system decides.  The message root pointer
  // should not be included in the size.  So, if you are simply going to copy some existing message
  // directly into the results, just call `.totalSize()` and pass that in.
277

278 279 280 281 282 283 284 285 286 287 288 289 290
  template <typename SubParams>
  kj::Promise<void> tailCall(Request<SubParams, Results>&& tailRequest);
  // Resolve the call by making a tail call.  `tailRequest` is a request that has been filled in
  // but not yet sent.  The context will send the call, then fill in the results with the result
  // of the call.  If tailCall() is used, {get,init,set,adopt}Results (above) *must not* be called.
  //
  // The RPC implementation may be able to optimize a tail call to another machine such that the
  // results never actually pass through this machine.  Even if no such optimization is possible,
  // `tailCall()` may allow pipelined calls to be forwarded optimistically to the new call site.
  //
  // In general, this should be the last thing a method implementation calls, and the promise
  // returned from `tailCall()` should then be returned by the method implementation.

291
  void allowCancellation();
292 293 294 295 296 297 298 299 300 301
  // Indicate that it is OK for the RPC system to discard its Promise for this call's result if
  // the caller cancels the call, thereby transitively canceling any asynchronous operations the
  // call implementation was performing.  This is not done by default because it could represent a
  // security risk:  applications must be carefully written to ensure that they do not end up in
  // a bad state if an operation is canceled at an arbitrary point.  However, for long-running
  // method calls that hold significant resources, prompt cancellation is often useful.
  //
  // Keep in mind that asynchronous cancellation cannot occur while the method is synchronously
  // executing on a local thread.  The method must perform an asynchronous operation or call
  // `EventLoop::current().runLater()` to yield control.
Kenton Varda's avatar
Kenton Varda committed
302
  //
303 304 305 306 307 308 309 310 311
  // Note:  You might think that we should offer `onCancel()` and/or `isCanceled()` methods that
  // provide notification when the caller cancels the request without forcefully killing off the
  // promise chain.  Unfortunately, this composes poorly with promise forking:  the canceled
  // path may be just one branch of a fork of the result promise.  The other branches still want
  // the call to continue.  Promise forking is used within the Cap'n Proto implementation -- in
  // particular each pipelined call forks the result promise.  So, if a caller made a pipelined
  // call and then dropped the original object, the call should not be canceled, but it would be
  // excessively complicated for the framework to avoid notififying of cancellation as long as
  // pipelined calls still exist.
312

313
private:
314 315 316
  CallContextHook* hook;

  friend class Capability::Server;
317
  friend struct DynamicCapability;
318 319
};

320 321 322 323
class Capability::Server {
  // Objects implementing a Cap'n Proto interface must subclass this.  Typically, such objects
  // will instead subclass a typed Server interface which will take care of implementing
  // dispatchCall().
324 325

public:
326 327
  typedef Capability Serves;

328
  virtual kj::Promise<void> dispatchCall(uint64_t interfaceId, uint16_t methodId,
329
                                         CallContext<AnyPointer, AnyPointer> context) = 0;
330 331 332 333
  // Call the given method.  `params` is the input struct, and should be released as soon as it
  // is no longer needed.  `context` may be used to allocate the output struct and deal with
  // cancellation.

334
  // TODO(someday):  Method which can optionally be overridden to implement Join when the object is
335
  //   a proxy.
336 337

protected:
338 339 340 341 342 343 344 345 346 347 348
  inline Capability::Client thisCap();
  // Get a capability pointing to this object, much like the `this` keyword.
  //
  // The effect of this method is undefined if:
  // - No capability client has been created pointing to this object. (This is always the case in
  //   the server's constructor.)
  // - The capability client pointing at this object has been destoryed. (This is always the case
  //   in the server's destructor.)
  // - Multiple capability clients have been created around the same server (possible if the server
  //   is refcounted, which is not recommended since the client itself provides refcounting).

349 350
  template <typename Params, typename Results>
  CallContext<Params, Results> internalGetTypedContext(
351
      CallContext<AnyPointer, AnyPointer> typeless);
352 353 354 355 356 357
  kj::Promise<void> internalUnimplemented(const char* actualInterfaceName,
                                          uint64_t requestedTypeId);
  kj::Promise<void> internalUnimplemented(const char* interfaceName,
                                          uint64_t typeId, uint16_t methodId);
  kj::Promise<void> internalUnimplemented(const char* interfaceName, const char* methodName,
                                          uint64_t typeId, uint16_t methodId);
358 359 360 361

private:
  ClientHook* thisHook = nullptr;
  friend class LocalClient;
362 363
};

364 365
// =======================================================================================

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
class ReaderCapabilityTable: private _::CapTableReader {
  // Class which imbues Readers with the ability to read capabilities.
  //
  // In Cap'n Proto format, the encoding of a capability pointer is simply an integer index into
  // an external table. Since these pointers fundamentally point outside the message, a
  // MessageReader by default has no idea what they point at, and therefore reading capabilities
  // from such a reader will throw exceptions.
  //
  // In order to be able to read capabilities, you must first attach a capability table, using
  // this class. By "imbuing" a Reader, you get a new Reader which will interpret capability
  // pointers by treating them as indexes into the ReaderCapabilityTable.
  //
  // Note that when using Cap'n Proto's RPC system, this is handled automatically.

public:
  explicit ReaderCapabilityTable(kj::Array<kj::Maybe<kj::Own<ClientHook>>> table);
  KJ_DISALLOW_COPY(ReaderCapabilityTable);

  template <typename T>
  T imbue(T reader);
  // Return a reader equivalent to `reader` except that when reading capability-valued fields,
  // the capabilities are looked up in this table.

private:
  kj::Array<kj::Maybe<kj::Own<ClientHook>>> table;

  kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override;
};

class BuilderCapabilityTable: private _::CapTableBuilder {
  // Class which imbues Builders with the ability to read and write capabilities.
  //
  // This is much like ReaderCapabilityTable, except for builders. The table starts out empty,
  // but capabilities can be added to it over time.

public:
  BuilderCapabilityTable();
  KJ_DISALLOW_COPY(BuilderCapabilityTable);

  inline kj::ArrayPtr<kj::Maybe<kj::Own<ClientHook>>> getTable() { return table; }

  template <typename T>
  T imbue(T builder);
  // Return a builder equivalent to `builder` except that when reading capability-valued fields,
  // the capabilities are looked up in this table.

private:
  kj::Vector<kj::Maybe<kj::Own<ClientHook>>> table;

  kj::Maybe<kj::Own<ClientHook>> extractCap(uint index) override;
  uint injectCap(kj::Own<ClientHook>&& cap) override;
  void dropCap(uint index) override;
};

// =======================================================================================

422 423 424 425 426 427 428 429 430 431 432 433
namespace _ {  // private

class CapabilityServerSetBase {
public:
  Capability::Client addInternal(kj::Own<Capability::Server>&& server, void* ptr);
  kj::Promise<void*> getLocalServerInternal(Capability::Client& client);
};

}  // namespace _ (private)

template <typename T>
class CapabilityServerSet: private _::CapabilityServerSetBase {
434 435
  // Allows a server to recognize its own capabilities when passed back to it, and obtain the
  // underlying Server objects associated with them.
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
  //
  // All objects in the set must have the same interface type T. The objects may implement various
  // interfaces derived from T (and in fact T can be `capnp::Capability` to accept all objects),
  // but note that if you compile with RTTI disabled then you will not be able to down-cast through
  // virtual inheritance, and all inheritance between server interfaces is virtual. So, with RTTI
  // disabled, you will likely need to set T to be the most-derived Cap'n Proto interface type,
  // and you server class will need to be directly derived from that, so that you can use
  // static_cast (or kj::downcast) to cast to it after calling getLocalServer(). (If you compile
  // with RTTI, then you can freely dynamic_cast and ignore this issue!)

public:
  CapabilityServerSet() = default;
  KJ_DISALLOW_COPY(CapabilityServerSet);

  typename T::Client add(kj::Own<typename T::Server>&& server);
  // Create a new capability Client for the given Server and also add this server to the set.

  kj::Promise<kj::Maybe<typename T::Server&>> getLocalServer(typename T::Client& client);
  // Given a Client pointing to a server previously passed to add(), return the corresponding
  // Server. This returns a promise because if the input client is itself a promise, this must
  // wait for it to resolve. Keep in mind that the server will be deleted when all clients are
  // gone, so the caller should make sure to keep the client alive (hence why this method only
  // accepts an lvalue input).
};

461
// =======================================================================================
462 463
// Hook interfaces which must be implemented by the RPC system.  Applications never call these
// directly; the RPC system implements them and the types defined earlier in this file wrap them.
464

465 466
class RequestHook {
  // Hook interface implemented by RPC system representing a request being built.
467

468
public:
469
  virtual RemotePromise<AnyPointer> send() = 0;
470
  // Send the call and return a promise for the result.
471

472
  virtual const void* getBrand() = 0;
473 474 475
  // Returns a void* that identifies who made this request.  This can be used by an RPC adapter to
  // discover when tail call is going to be sent over its own connection and therefore can be
  // optimized into a remote tail call.
476 477 478 479 480

  template <typename T, typename U>
  inline static kj::Own<RequestHook> from(Request<T, U>&& request) {
    return kj::mv(request.hook);
  }
481 482
};

483 484 485 486
class ResponseHook {
  // Hook interface implemented by RPC system representing a response.
  //
  // At present this class has no methods.  It exists only for garbage collection -- when the
487
  // ResponseHook is destroyed, the results can be freed.
488 489

public:
Kenton Varda's avatar
Kenton Varda committed
490 491
  virtual ~ResponseHook() noexcept(false);
  // Just here to make sure the type is dynamic.
492 493 494 495 496

  template <typename T>
  inline static kj::Own<ResponseHook> from(Response<T>&& response) {
    return kj::mv(response.hook);
  }
497 498
};

499
// class PipelineHook is declared in any.h because it is needed there.
500

501
class ClientHook {
502
public:
503 504
  ClientHook();

505
  virtual Request<AnyPointer, AnyPointer> newCall(
506
      uint64_t interfaceId, uint16_t methodId, kj::Maybe<MessageSize> sizeHint) = 0;
Kenton Varda's avatar
Kenton Varda committed
507 508
  // Start a new call, allowing the client to allocate request/response objects as it sees fit.
  // This version is used when calls are made from application code in the local process.
509

Kenton Varda's avatar
Kenton Varda committed
510 511
  struct VoidPromiseAndPipeline {
    kj::Promise<void> promise;
512
    kj::Own<PipelineHook> pipeline;
Kenton Varda's avatar
Kenton Varda committed
513 514 515
  };

  virtual VoidPromiseAndPipeline call(uint64_t interfaceId, uint16_t methodId,
516
                                      kj::Own<CallContextHook>&& context) = 0;
Kenton Varda's avatar
Kenton Varda committed
517
  // Call the object, but the caller controls allocation of the request/response objects.  If the
518
  // callee insists on allocating these objects itself, it must make a copy.  This version is used
519 520 521
  // when calls come in over the network via an RPC system.  Note that even if the returned
  // `Promise<void>` is discarded, the call may continue executing if any pipelined calls are
  // waiting for it.
Kenton Varda's avatar
Kenton Varda committed
522
  //
523 524
  // Since the caller of this method chooses the CallContext implementation, it is the caller's
  // responsibility to ensure that the returned promise is not canceled unless allowed via
525
  // the context's `allowCancellation()`.
526
  //
527 528 529
  // The call must not begin synchronously; the callee must arrange for the call to begin in a
  // later turn of the event loop. Otherwise, application code may call back and affect the
  // callee's state in an unexpected way.
Kenton Varda's avatar
Kenton Varda committed
530

531
  virtual kj::Maybe<ClientHook&> getResolved() = 0;
532 533 534 535 536
  // If this ClientHook is a promise that has already resolved, returns the inner, resolved version
  // of the capability.  The caller may permanently replace this client with the resolved one if
  // desired.  Returns null if the client isn't a promise or hasn't resolved yet -- use
  // `whenMoreResolved()` to distinguish between them.

537
  virtual kj::Maybe<kj::Promise<kj::Own<ClientHook>>> whenMoreResolved() = 0;
Kenton Varda's avatar
Kenton Varda committed
538 539
  // If this client is a settled reference (not a promise), return nullptr.  Otherwise, return a
  // promise that eventually resolves to a new client that is closer to being the final, settled
540 541
  // client (i.e. the value eventually returned by `getResolved()`).  Calling this repeatedly
  // should eventually produce a settled client.
Kenton Varda's avatar
Kenton Varda committed
542

543
  kj::Promise<void> whenResolved();
544 545
  // Repeatedly calls whenMoreResolved() until it returns nullptr.

546
  virtual kj::Own<ClientHook> addRef() = 0;
547
  // Return a new reference to the same capability.
548

549
  virtual const void* getBrand() = 0;
550 551 552
  // Returns a void* that identifies who made this client.  This can be used by an RPC adapter to
  // discover when a capability it needs to marshal is one that it created in the first place, and
  // therefore it can transfer the capability without proxying.
553

554 555 556 557 558 559 560
  static const uint NULL_CAPABILITY_BRAND;
  // Value is irrelevant; used for pointer.

  inline bool isNull() { return getBrand() == &NULL_CAPABILITY_BRAND; }
  // Returns true if the capability was created as a result of assigning a Client to null or by
  // reading a null pointer out of a Cap'n Proto message.

561 562 563 564
  virtual void* getLocalServer(_::CapabilityServerSetBase& capServerSet);
  // If this is a local capability created through `capServerSet`, return the underlying Server.
  // Otherwise, return nullptr. Default implementation (which everyone except LocalClient should
  // use) always returns nullptr.
565 566

  static kj::Own<ClientHook> from(Capability::Client client) { return kj::mv(client.hook); }
567 568
};

569 570 571
class CallContextHook {
  // Hook interface implemented by RPC system to manage a call on the server side.  See
  // CallContext<T>.
572 573

public:
574
  virtual AnyPointer::Reader getParams() = 0;
575
  virtual void releaseParams() = 0;
576
  virtual AnyPointer::Builder getResults(kj::Maybe<MessageSize> sizeHint) = 0;
577
  virtual kj::Promise<void> tailCall(kj::Own<RequestHook>&& request) = 0;
578
  virtual void allowCancellation() = 0;
579

580
  virtual kj::Promise<AnyPointer::Pipeline> onTailCall() = 0;
581 582 583
  // If `tailCall()` is called, resolves to the PipelineHook from the tail call.  An
  // implementation of `ClientHook::call()` is allowed to call this at most once.

584 585 586 587 588
  virtual ClientHook::VoidPromiseAndPipeline directTailCall(kj::Own<RequestHook>&& request) = 0;
  // Call this when you would otherwise call onTailCall() immediately followed by tailCall().
  // Implementations of tailCall() should typically call directTailCall() and then fulfill the
  // promise fulfiller for onTailCall() with the returned pipeline.

589
  virtual kj::Own<CallContextHook> addRef() = 0;
590
};
591

592
kj::Own<ClientHook> newLocalPromiseClient(kj::Promise<kj::Own<ClientHook>>&& promise);
Kenton Varda's avatar
Kenton Varda committed
593 594 595 596
// Returns a ClientHook that queues up calls until `promise` resolves, then forwards them to
// the new client.  This hook's `getResolved()` and `whenMoreResolved()` methods will reflect the
// redirection to the eventual replacement client.

597 598 599 600 601 602 603
kj::Own<ClientHook> newBrokenCap(kj::StringPtr reason);
kj::Own<ClientHook> newBrokenCap(kj::Exception&& reason);
// Helper function that creates a capability which simply throws exceptions when called.

kj::Own<PipelineHook> newBrokenPipeline(kj::Exception&& reason);
// Helper function that creates a pipeline which simply throws exceptions when called.

604 605 606 607
Request<AnyPointer, AnyPointer> newBrokenRequest(
    kj::Exception&& reason, kj::Maybe<MessageSize> sizeHint);
// Helper function that creates a Request object that simply throws exceptions when sent.

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
// =======================================================================================
// Extend PointerHelpers for interfaces

namespace _ {  // private

template <typename T>
struct PointerHelpers<T, Kind::INTERFACE> {
  static inline typename T::Client get(PointerReader reader) {
    return typename T::Client(reader.getCapability());
  }
  static inline typename T::Client get(PointerBuilder builder) {
    return typename T::Client(builder.getCapability());
  }
  static inline void set(PointerBuilder builder, typename T::Client&& value) {
    builder.setCapability(kj::mv(value.Capability::Client::hook));
  }
624
  static inline void set(PointerBuilder builder, typename T::Client& value) {
625 626
    builder.setCapability(value.Capability::Client::hook->addRef());
  }
627 628 629 630 631 632 633 634 635 636
  static inline void adopt(PointerBuilder builder, Orphan<T>&& value) {
    builder.adopt(kj::mv(value.builder));
  }
  static inline Orphan<T> disown(PointerBuilder builder) {
    return Orphan<T>(builder.disown());
  }
};

}  // namespace _ (private)

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
// =======================================================================================
// Extend List for interfaces

template <typename T>
struct List<T, Kind::INTERFACE> {
  List() = delete;

  class Reader {
  public:
    typedef List<T> Reads;

    Reader() = default;
    inline explicit Reader(_::ListReader reader): reader(reader) {}

    inline uint size() const { return reader.size() / ELEMENTS; }
    inline typename T::Client operator[](uint index) const {
      KJ_IREQUIRE(index < size());
      return typename T::Client(reader.getPointerElement(index * ELEMENTS).getCapability());
    }

    typedef _::IndexingIterator<const Reader, typename T::Client> Iterator;
    inline Iterator begin() const { return Iterator(this, 0); }
    inline Iterator end() const { return Iterator(this, size()); }

  private:
    _::ListReader reader;
    template <typename U, Kind K>
    friend struct _::PointerHelpers;
    template <typename U, Kind K>
    friend struct List;
    friend class Orphanage;
    template <typename U, Kind K>
    friend struct ToDynamic_;
  };

  class Builder {
  public:
    typedef List<T> Builds;

    Builder() = delete;
    inline Builder(decltype(nullptr)) {}
    inline explicit Builder(_::ListBuilder builder): builder(builder) {}

    inline operator Reader() { return Reader(builder.asReader()); }
    inline Reader asReader() { return Reader(builder.asReader()); }

    inline uint size() const { return builder.size() / ELEMENTS; }
    inline typename T::Client operator[](uint index) {
      KJ_IREQUIRE(index < size());
      return typename T::Client(builder.getPointerElement(index * ELEMENTS).getCapability());
    }
    inline void set(uint index, typename T::Client value) {
      KJ_IREQUIRE(index < size());
      builder.getPointerElement(index * ELEMENTS).setCapability(kj::mv(value.hook));
    }
    inline void adopt(uint index, Orphan<T>&& value) {
      KJ_IREQUIRE(index < size());
      builder.getPointerElement(index * ELEMENTS).adopt(kj::mv(value));
    }
    inline Orphan<T> disown(uint index) {
      KJ_IREQUIRE(index < size());
      return Orphan<T>(builder.getPointerElement(index * ELEMENTS).disown());
    }

    typedef _::IndexingIterator<Builder, typename T::Client> Iterator;
    inline Iterator begin() { return Iterator(this, 0); }
    inline Iterator end() { return Iterator(this, size()); }

  private:
    _::ListBuilder builder;
    friend class Orphanage;
    template <typename U, Kind K>
    friend struct ToDynamic_;
  };

private:
  inline static _::ListBuilder initPointer(_::PointerBuilder builder, uint size) {
714
    return builder.initList(ElementSize::POINTER, size * ELEMENTS);
715 716
  }
  inline static _::ListBuilder getFromPointer(_::PointerBuilder builder, const word* defaultValue) {
717
    return builder.getList(ElementSize::POINTER, defaultValue);
718 719 720
  }
  inline static _::ListReader getFromPointer(
      const _::PointerReader& reader, const word* defaultValue) {
721
    return reader.getList(ElementSize::POINTER, defaultValue);
722 723 724 725 726 727 728 729
  }

  template <typename U, Kind k>
  friend struct List;
  template <typename U, Kind K>
  friend struct _::PointerHelpers;
};

730 731 732
// =======================================================================================
// Inline implementation details

733 734
template <typename Params, typename Results>
RemotePromise<Results> Request<Params, Results>::send() {
735
  auto typelessPromise = hook->send();
736
  hook = nullptr;  // prevent reuse
737 738 739 740

  // Convert the Promise to return the correct response type.
  // Explicitly upcast to kj::Promise to make clear that calling .then() doesn't invalidate the
  // Pipeline part of the RemotePromise.
741 742
  auto typedPromise = kj::implicitCast<kj::Promise<Response<AnyPointer>>&>(typelessPromise)
      .then([](Response<AnyPointer>&& response) -> Response<Results> {
743
        return Response<Results>(response.getAs<Results>(), kj::mv(response.hook));
744 745 746
      });

  // Wrap the typeless pipeline in a typed wrapper.
747
  typename Results::Pipeline typedPipeline(
748
      kj::mv(kj::implicitCast<AnyPointer::Pipeline&>(typelessPromise)));
749

750
  return RemotePromise<Results>(kj::mv(typedPromise), kj::mv(typedPipeline));
751 752
}

753
inline Capability::Client::Client(kj::Own<ClientHook>&& hook): hook(kj::mv(hook)) {}
754
template <typename T, typename>
755 756
inline Capability::Client::Client(kj::Own<T>&& server)
    : hook(makeLocalClient(kj::mv(server))) {}
757
template <typename T, typename>
758 759 760 761
inline Capability::Client::Client(kj::Promise<T>&& promise)
    : hook(newLocalPromiseClient(promise.then([](T&& t) { return kj::mv(t.hook); }))) {}
inline Capability::Client::Client(Client& other): hook(other.hook->addRef()) {}
inline Capability::Client& Capability::Client::operator=(Client& other) {
762 763 764
  hook = other.hook->addRef();
  return *this;
}
765
template <typename T>
766
inline typename T::Client Capability::Client::castAs() {
767 768
  return typename T::Client(hook->addRef());
}
769
inline kj::Promise<void> Capability::Client::whenResolved() {
770 771
  return hook->whenResolved();
}
772 773 774 775 776
inline Request<AnyPointer, AnyPointer> Capability::Client::typelessRequest(
    uint64_t interfaceId, uint16_t methodId,
    kj::Maybe<MessageSize> sizeHint) {
  return newCall<AnyPointer, AnyPointer>(interfaceId, methodId, sizeHint);
}
777 778
template <typename Params, typename Results>
inline Request<Params, Results> Capability::Client::newCall(
779 780
    uint64_t interfaceId, uint16_t methodId, kj::Maybe<MessageSize> sizeHint) {
  auto typeless = hook->newCall(interfaceId, methodId, sizeHint);
781 782
  return Request<Params, Results>(typeless.template getAs<Params>(), kj::mv(typeless.hook));
}
783

784 785 786 787 788 789 790 791 792 793 794
template <typename Params, typename Results>
inline CallContext<Params, Results>::CallContext(CallContextHook& hook): hook(&hook) {}
template <typename Params, typename Results>
inline typename Params::Reader CallContext<Params, Results>::getParams() {
  return hook->getParams().template getAs<Params>();
}
template <typename Params, typename Results>
inline void CallContext<Params, Results>::releaseParams() {
  hook->releaseParams();
}
template <typename Params, typename Results>
Kenton Varda's avatar
Kenton Varda committed
795
inline typename Results::Builder CallContext<Params, Results>::getResults(
796
    kj::Maybe<MessageSize> sizeHint) {
797
  // `template` keyword needed due to: http://llvm.org/bugs/show_bug.cgi?id=17401
798
  return hook->getResults(sizeHint).template getAs<Results>();
799
}
800
template <typename Params, typename Results>
Kenton Varda's avatar
Kenton Varda committed
801
inline typename Results::Builder CallContext<Params, Results>::initResults(
802
    kj::Maybe<MessageSize> sizeHint) {
803
  // `template` keyword needed due to: http://llvm.org/bugs/show_bug.cgi?id=17401
804
  return hook->getResults(sizeHint).template initAs<Results>();
805
}
806 807
template <typename Params, typename Results>
inline void CallContext<Params, Results>::setResults(typename Results::Reader value) {
808
  hook->getResults(value.totalSize()).template setAs<Results>(value);
809
}
810 811
template <typename Params, typename Results>
inline void CallContext<Params, Results>::adoptResults(Orphan<Results>&& value) {
812
  hook->getResults(nullptr).adopt(kj::mv(value));
813
}
814
template <typename Params, typename Results>
815 816 817
inline Orphanage CallContext<Params, Results>::getResultsOrphanage(
    kj::Maybe<MessageSize> sizeHint) {
  return Orphanage::getForMessageContaining(hook->getResults(sizeHint));
818
}
819
template <typename Params, typename Results>
820 821 822 823 824 825
template <typename SubParams>
inline kj::Promise<void> CallContext<Params, Results>::tailCall(
    Request<SubParams, Results>&& tailRequest) {
  return hook->tailCall(kj::mv(tailRequest.hook));
}
template <typename Params, typename Results>
826 827
inline void CallContext<Params, Results>::allowCancellation() {
  hook->allowCancellation();
828
}
829

830 831
template <typename Params, typename Results>
CallContext<Params, Results> Capability::Server::internalGetTypedContext(
832
    CallContext<AnyPointer, AnyPointer> typeless) {
833 834 835
  return CallContext<Params, Results>(*typeless.hook);
}

836 837
Capability::Client Capability::Server::thisCap() {
  return Client(thisHook->addRef());
838 839
}

840 841 842 843 844 845 846 847 848 849
template <typename T>
T ReaderCapabilityTable::imbue(T reader) {
  return T(_::PointerHelpers<FromReader<T>>::getInternalReader(reader).imbue(this));
}

template <typename T>
T BuilderCapabilityTable::imbue(T builder) {
  return T(_::PointerHelpers<FromBuilder<T>>::getInternalBuilder(kj::mv(builder)).imbue(this));
}

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
template <typename T>
typename T::Client CapabilityServerSet<T>::add(kj::Own<typename T::Server>&& server) {
  void* ptr = reinterpret_cast<void*>(server.get());
  // Clang insists that `castAs` is a template-dependent member and therefore we need the
  // `template` keyword here, but AFAICT this is wrong: addImpl() is not a template.
  return addInternal(kj::mv(server), ptr).template castAs<T>();
}

template <typename T>
kj::Promise<kj::Maybe<typename T::Server&>> CapabilityServerSet<T>::getLocalServer(
    typename T::Client& client) {
  return getLocalServerInternal(client)
      .then([](void* server) -> kj::Maybe<typename T::Server&> {
    if (server == nullptr) {
      return nullptr;
    } else {
      return *reinterpret_cast<typename T::Server*>(server);
    }
  });
}

871 872 873
}  // namespace capnp

#endif  // CAPNP_CAPABILITY_H_