rpc.c++ 110 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

#include "rpc.h"
23
#include "message.h"
24 25 26
#include <kj/debug.h>
#include <kj/vector.h>
#include <kj/async.h>
Kenton Varda's avatar
Kenton Varda committed
27
#include <kj/one-of.h>
Kenton Varda's avatar
Kenton Varda committed
28
#include <kj/function.h>
29
#include <functional>  // std::greater
30
#include <unordered_map>
Kenton Varda's avatar
Kenton Varda committed
31
#include <map>
32 33
#include <queue>
#include <capnp/rpc.capnp.h>
34
#include <kj/io.h>
35 36 37 38 39 40

namespace capnp {
namespace _ {  // private

namespace {

Kenton Varda's avatar
Kenton Varda committed
41 42 43 44 45 46 47 48 49
template <typename T>
inline constexpr uint messageSizeHint() {
  return 1 + sizeInWords<rpc::Message>() + sizeInWords<T>();
}
template <>
inline constexpr uint messageSizeHint<void>() {
  return 1 + sizeInWords<rpc::Message>();
}

50 51 52
constexpr const uint MESSAGE_TARGET_SIZE_HINT = sizeInWords<rpc::MessageTarget>() +
    sizeInWords<rpc::PromisedAnswer>() + 16;  // +16 for ops; hope that's enough

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
constexpr const uint CAP_DESCRIPTOR_SIZE_HINT = sizeInWords<rpc::CapDescriptor>() +
    sizeInWords<rpc::PromisedAnswer>();

constexpr const uint64_t MAX_SIZE_HINT = 1 << 20;

uint copySizeHint(MessageSize size) {
  uint64_t sizeHint = size.wordCount + size.capCount * CAP_DESCRIPTOR_SIZE_HINT;
  return kj::min(MAX_SIZE_HINT, sizeHint);
}

uint firstSegmentSize(kj::Maybe<MessageSize> sizeHint, uint additional) {
  KJ_IF_MAYBE(s, sizeHint) {
    return copySizeHint(*s) + additional;
  } else {
    return 0;
  }
}

Kenton Varda's avatar
Kenton Varda committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
kj::Maybe<kj::Array<PipelineOp>> toPipelineOps(List<rpc::PromisedAnswer::Op>::Reader ops) {
  auto result = kj::heapArrayBuilder<PipelineOp>(ops.size());
  for (auto opReader: ops) {
    PipelineOp op;
    switch (opReader.which()) {
      case rpc::PromisedAnswer::Op::NOOP:
        op.type = PipelineOp::NOOP;
        break;
      case rpc::PromisedAnswer::Op::GET_POINTER_FIELD:
        op.type = PipelineOp::GET_POINTER_FIELD;
        op.pointerIndex = opReader.getGetPointerField();
        break;
      default:
        KJ_FAIL_REQUIRE("Unsupported pipeline op.", (uint)opReader.which()) {
          return nullptr;
        }
    }
88
    result.add(op);
Kenton Varda's avatar
Kenton Varda committed
89 90 91 92 93
  }
  return result.finish();
}

Orphan<List<rpc::PromisedAnswer::Op>> fromPipelineOps(
Kenton Varda's avatar
Kenton Varda committed
94
    Orphanage orphanage, kj::ArrayPtr<const PipelineOp> ops) {
Kenton Varda's avatar
Kenton Varda committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  auto result = orphanage.newOrphan<List<rpc::PromisedAnswer::Op>>(ops.size());
  auto builder = result.get();
  for (uint i: kj::indices(ops)) {
    rpc::PromisedAnswer::Op::Builder opBuilder = builder[i];
    switch (ops[i].type) {
      case PipelineOp::NOOP:
        opBuilder.setNoop();
        break;
      case PipelineOp::GET_POINTER_FIELD:
        opBuilder.setGetPointerField(ops[i].pointerIndex);
        break;
    }
  }
  return result;
}

Kenton Varda's avatar
Kenton Varda committed
111
kj::Exception toException(const rpc::Exception::Reader& exception) {
112 113
  return kj::Exception(static_cast<kj::Exception::Type>(exception.getType()),
      "(remote)", 0, kj::str("remote exception: ", exception.getReason()));
Kenton Varda's avatar
Kenton Varda committed
114 115 116
}

void fromException(const kj::Exception& exception, rpc::Exception::Builder builder) {
Kenton Varda's avatar
Kenton Varda committed
117 118
  // TODO(someday):  Indicate the remote server name as part of the stack trace.  Maybe even
  //   transmit stack traces?
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

  kj::StringPtr description = exception.getDescription();

  // Include context, if any.
  kj::Vector<kj::String> contextLines;
  for (auto context = exception.getContext();;) {
    KJ_IF_MAYBE(c, context) {
      contextLines.add(kj::str("context: ", c->file, ": ", c->line, ": ", c->description));
      context = c->next;
    } else {
      break;
    }
  }
  kj::String scratch;
  if (contextLines.size() > 0) {
    scratch = kj::str(description, '\n', kj::strArray(contextLines, "\n"));
    description = scratch;
  }

  builder.setReason(description);
139
  builder.setType(static_cast<rpc::Exception::Type>(exception.getType()));
Kenton Varda's avatar
Kenton Varda committed
140 141 142 143 144

  if (exception.getType() == kj::Exception::Type::FAILED &&
      !exception.getDescription().startsWith("remote exception:")) {
    KJ_LOG(INFO, "returning failure over rpc", exception);
  }
Kenton Varda's avatar
Kenton Varda committed
145 146
}

Kenton Varda's avatar
Kenton Varda committed
147
uint exceptionSizeHint(const kj::Exception& exception) {
Kenton Varda's avatar
Kenton Varda committed
148
  return sizeInWords<rpc::Exception>() + exception.getDescription().size() / sizeof(word) + 1;
Kenton Varda's avatar
Kenton Varda committed
149 150
}

Kenton Varda's avatar
Kenton Varda committed
151
// =======================================================================================
Kenton Varda's avatar
Kenton Varda committed
152

153 154 155 156 157 158 159 160 161 162 163 164 165
template <typename Id, typename T>
class ExportTable {
  // Table mapping integers to T, where the integers are chosen locally.

public:
  kj::Maybe<T&> find(Id id) {
    if (id < slots.size() && slots[id] != nullptr) {
      return slots[id];
    } else {
      return nullptr;
    }
  }

166
  T erase(Id id, T& entry) {
Kenton Varda's avatar
Kenton Varda committed
167 168
    // Remove an entry from the table and return it.  We return it so that the caller can be
    // careful to release it (possibly invoking arbitrary destructors) at a time that makes sense.
169 170 171 172 173 174 175 176
    // `entry` is a reference to the entry being released -- we require this in order to prove
    // that the caller has already done a find() to check that this entry exists.  We can't check
    // ourselves because the caller may have nullified the entry in the meantime.
    KJ_DREQUIRE(&entry == &slots[id]);
    T toRelease = kj::mv(slots[id]);
    slots[id] = T();
    freeIds.push(id);
    return toRelease;
177 178 179 180 181 182 183 184 185 186 187 188 189
  }

  T& next(Id& id) {
    if (freeIds.empty()) {
      id = slots.size();
      return slots.add();
    } else {
      id = freeIds.top();
      freeIds.pop();
      return slots[id];
    }
  }

190 191 192 193 194 195 196 197 198
  template <typename Func>
  void forEach(Func&& func) {
    for (Id i = 0; i < slots.size(); i++) {
      if (slots[i] != nullptr) {
        func(i, slots[i]);
      }
    }
  }

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
private:
  kj::Vector<T> slots;
  std::priority_queue<Id, std::vector<Id>, std::greater<Id>> freeIds;
};

template <typename Id, typename T>
class ImportTable {
  // Table mapping integers to T, where the integers are chosen remotely.

public:
  T& operator[](Id id) {
    if (id < kj::size(low)) {
      return low[id];
    } else {
      return high[id];
    }
  }

Kenton Varda's avatar
Kenton Varda committed
217 218 219 220 221
  kj::Maybe<T&> find(Id id) {
    if (id < kj::size(low)) {
      return low[id];
    } else {
      auto iter = high.find(id);
Kenton Varda's avatar
Kenton Varda committed
222
      if (iter == high.end()) {
Kenton Varda's avatar
Kenton Varda committed
223 224 225 226 227 228 229
        return nullptr;
      } else {
        return iter->second;
      }
    }
  }

Kenton Varda's avatar
Kenton Varda committed
230 231 232
  T erase(Id id) {
    // Remove an entry from the table and return it.  We return it so that the caller can be
    // careful to release it (possibly invoking arbitrary destructors) at a time that makes sense.
233
    if (id < kj::size(low)) {
Kenton Varda's avatar
Kenton Varda committed
234
      T toRelease = kj::mv(low[id]);
235
      low[id] = T();
Kenton Varda's avatar
Kenton Varda committed
236
      return toRelease;
237
    } else {
Kenton Varda's avatar
Kenton Varda committed
238
      T toRelease = kj::mv(high[id]);
239
      high.erase(id);
Kenton Varda's avatar
Kenton Varda committed
240
      return toRelease;
241 242 243
    }
  }

244 245 246 247 248 249 250 251 252 253
  template <typename Func>
  void forEach(Func&& func) {
    for (Id i: kj::indices(low)) {
      func(i, low[i]);
    }
    for (auto& entry: high) {
      func(entry.first, entry.second);
    }
  }

254 255 256 257 258
private:
  T low[16];
  std::unordered_map<Id, T> high;
};

Kenton Varda's avatar
Kenton Varda committed
259 260
// =======================================================================================

261
class RpcConnectionState final: public kj::TaskSet::ErrorHandler, public kj::Refcounted {
262
public:
Kenton Varda's avatar
Kenton Varda committed
263 264 265 266 267
  struct DisconnectInfo {
    kj::Promise<void> shutdownPromise;
    // Task which is working on sending an abort message and cleanly ending the connection.
  };

268
  RpcConnectionState(BootstrapFactoryBase& bootstrapFactory,
269
                     kj::Maybe<RealmGateway<>::Client> gateway,
270
                     kj::Maybe<SturdyRefRestorerBase&> restorer,
271
                     kj::Own<VatNetworkBase::Connection>&& connectionParam,
272 273
                     kj::Own<kj::PromiseFulfiller<DisconnectInfo>>&& disconnectFulfiller,
                     size_t flowLimit)
274
      : bootstrapFactory(bootstrapFactory), gateway(kj::mv(gateway)),
275 276
        restorer(restorer), disconnectFulfiller(kj::mv(disconnectFulfiller)), flowLimit(flowLimit),
        tasks(*this) {
277
    connection.init<Connected>(kj::mv(connectionParam));
278 279 280
    tasks.add(messageLoop());
  }

281
  kj::Own<ClientHook> restore(AnyPointer::Reader objectId) {
282 283 284 285
    if (connection.is<Disconnected>()) {
      return newBrokenCap(kj::cp(connection.get<Disconnected>()));
    }

286
    QuestionId questionId;
287
    auto& question = questions.next(questionId);
288

289
    question.isAwaitingReturn = true;
290

291
    auto paf = kj::newPromiseAndFulfiller<kj::Promise<kj::Own<RpcResponse>>>();
Kenton Varda's avatar
Kenton Varda committed
292

293 294
    auto questionRef = kj::refcounted<QuestionRef>(*this, questionId, kj::mv(paf.fulfiller));
    question.selfRef = *questionRef;
Kenton Varda's avatar
Kenton Varda committed
295

296
    paf.promise = paf.promise.attach(kj::addRef(*questionRef));
297 298

    {
299
      auto message = connection.get<Connected>()->newOutgoingMessage(
300
          objectId.targetSize().wordCount + messageSizeHint<rpc::Bootstrap>());
301

302
      auto builder = message->getBody().initAs<rpc::Message>().initBootstrap();
303
      builder.setQuestionId(questionId);
304
      builder.getDeprecatedObjectId().set(objectId);
305 306 307 308

      message->send();
    }

309
    auto pipeline = kj::refcounted<RpcPipeline>(*this, kj::mv(questionRef), kj::mv(paf.promise));
310

311
    return pipeline->getPipelinedCap(kj::Array<const PipelineOp>(nullptr));
Kenton Varda's avatar
Kenton Varda committed
312 313
  }

314
  void taskFailed(kj::Exception&& exception) override {
315 316 317 318
    disconnect(kj::mv(exception));
  }

  void disconnect(kj::Exception&& exception) {
319 320 321 322 323
    if (!connection.is<Connected>()) {
      // Already disconnected.
      return;
    }

324 325
    kj::Exception networkException(kj::Exception::Type::DISCONNECTED,
        exception.getFile(), exception.getLine(), kj::heapString(exception.getDescription()));
326 327

    KJ_IF_MAYBE(newException, kj::runCatchingExceptions([&]() {
328 329
      // Carefully pull all the objects out of the tables prior to releasing them because their
      // destructors could come back and mess with the tables.
330 331 332 333
      kj::Vector<kj::Own<PipelineHook>> pipelinesToRelease;
      kj::Vector<kj::Own<ClientHook>> clientsToRelease;
      kj::Vector<kj::Promise<kj::Own<RpcResponse>>> tailCallsToRelease;
      kj::Vector<kj::Promise<void>> resolveOpsToRelease;
334 335

      // All current questions complete with exceptions.
336
      questions.forEach([&](QuestionId id, Question& question) {
Kenton Varda's avatar
Kenton Varda committed
337
        KJ_IF_MAYBE(questionRef, question.selfRef) {
338 339
          // QuestionRef still present.
          questionRef->reject(kj::cp(networkException));
Kenton Varda's avatar
Kenton Varda committed
340
        }
341 342
      });

343
      answers.forEach([&](AnswerId id, Answer& answer) {
344 345 346 347
        KJ_IF_MAYBE(p, answer.pipeline) {
          pipelinesToRelease.add(kj::mv(*p));
        }

348
        KJ_IF_MAYBE(promise, answer.redirectedResults) {
349
          tailCallsToRelease.add(kj::mv(*promise));
350 351
        }

352 353 354 355 356
        KJ_IF_MAYBE(context, answer.callContext) {
          context->requestCancel();
        }
      });

357
      exports.forEach([&](ExportId id, Export& exp) {
358
        clientsToRelease.add(kj::mv(exp.clientHook));
359
        resolveOpsToRelease.add(kj::mv(exp.resolveOp));
360 361 362
        exp = Export();
      });

363
      imports.forEach([&](ImportId id, Import& import) {
364 365
        KJ_IF_MAYBE(f, import.promiseFulfiller) {
          f->get()->reject(kj::cp(networkException));
366 367 368
        }
      });

369
      embargoes.forEach([&](EmbargoId id, Embargo& embargo) {
370 371 372 373
        KJ_IF_MAYBE(f, embargo.fulfiller) {
          f->get()->reject(kj::cp(networkException));
        }
      });
374 375 376 377 378
    })) {
      // Some destructor must have thrown an exception.  There is no appropriate place to report
      // these errors.
      KJ_LOG(ERROR, "Uncaught exception when destroying capabilities dropped by disconnect.",
             *newException);
379 380
    }

381 382 383
    // Send an abort message, but ignore failure.
    kj::runCatchingExceptions([&]() {
      auto message = connection.get<Connected>()->newOutgoingMessage(
Kenton Varda's avatar
Kenton Varda committed
384
          messageSizeHint<void>() + exceptionSizeHint(exception));
385 386
      fromException(exception, message->getBody().getAs<rpc::Message>().initAbort());
      message->send();
387
    });
388 389

    // Indicate disconnect.
390 391 392 393 394 395 396 397 398 399 400
    auto shutdownPromise = connection.get<Connected>()->shutdown()
        .attach(kj::mv(connection.get<Connected>()))
        .then([]() -> kj::Promise<void> { return kj::READY_NOW; },
              [](kj::Exception&& e) -> kj::Promise<void> {
          // Don't report disconnects as an error.
          if (e.getType() != kj::Exception::Type::DISCONNECTED) {
            return kj::mv(e);
          }
          return kj::READY_NOW;
        });
    disconnectFulfiller->fulfill(DisconnectInfo { kj::mv(shutdownPromise) });
401
    connection.init<Disconnected>(kj::mv(networkException));
402 403
  }

404 405 406 407 408
  void setFlowLimit(size_t words) {
    flowLimit = words;
    maybeUnblockFlow();
  }

409
private:
410
  class RpcClient;
Kenton Varda's avatar
Kenton Varda committed
411
  class ImportClient;
412
  class PromiseClient;
Kenton Varda's avatar
Kenton Varda committed
413
  class QuestionRef;
Kenton Varda's avatar
Kenton Varda committed
414
  class RpcPipeline;
Kenton Varda's avatar
Kenton Varda committed
415
  class RpcCallContext;
Kenton Varda's avatar
Kenton Varda committed
416
  class RpcResponse;
Kenton Varda's avatar
Kenton Varda committed
417

418 419 420 421 422 423
  // =======================================================================================
  // The Four Tables entry types
  //
  // We have to define these before we can define the class's fields.

  typedef uint32_t QuestionId;
424
  typedef QuestionId AnswerId;
425
  typedef uint32_t ExportId;
426 427 428 429 430 431 432 433 434 435
  typedef ExportId ImportId;
  // See equivalent definitions in rpc.capnp.
  //
  // We always use the type that refers to the local table of the same name.  So e.g. although
  // QuestionId and AnswerId are the same type, we use QuestionId when referring to an entry in
  // the local question table (which corresponds to the peer's answer table) and use AnswerId
  // to refer to an entry in our answer table (which corresponds to the peer's question table).
  // Since all messages in the RPC protocol are defined from the sender's point of view, this
  // means that any time we read an ID from a received message, its type should invert.
  // TODO(cleanup):  Perhaps we could enforce that in a type-safe way?  Hmm...
436 437

  struct Question {
438 439 440
    kj::Array<ExportId> paramExports;
    // List of exports that were sent in the request.  If the response has `releaseParamCaps` these
    // will need to be released.
441

Kenton Varda's avatar
Kenton Varda committed
442 443 444
    kj::Maybe<QuestionRef&> selfRef;
    // The local QuestionRef, set to nullptr when it is destroyed, which is also when `Finish` is
    // sent.
445

446 447 448
    bool isAwaitingReturn = false;
    // True from when `Call` is sent until `Return` is received.

449 450 451
    bool isTailCall = false;
    // Is this a tail call?  If so, we don't expect to receive results in the `Return`.

452 453 454
    bool skipFinish = false;
    // If true, don't send a Finish message.

Kenton Varda's avatar
Kenton Varda committed
455
    inline bool operator==(decltype(nullptr)) const {
456
      return !isAwaitingReturn && selfRef == nullptr;
Kenton Varda's avatar
Kenton Varda committed
457 458
    }
    inline bool operator!=(decltype(nullptr)) const { return !operator==(nullptr); }
459 460 461
  };

  struct Answer {
462 463 464 465 466 467
    Answer() = default;
    Answer(const Answer&) = delete;
    Answer(Answer&&) = default;
    Answer& operator=(Answer&&) = default;
    // If we don't explicitly write all this, we get some stupid error deep in STL.

468 469 470 471
    bool active = false;
    // True from the point when the Call message is received to the point when both the `Finish`
    // message has been received and the `Return` has been sent.

472
    kj::Maybe<kj::Own<PipelineHook>> pipeline;
473 474
    // Send pipelined calls here.  Becomes null as soon as a `Finish` is received.

475
    kj::Maybe<kj::Promise<kj::Own<RpcResponse>>> redirectedResults;
476 477
    // For locally-redirected calls (Call.sendResultsTo.yourself), this is a promise for the call
    // result, to be picked up by a subsequent `Return`.
478

479
    kj::Maybe<RpcCallContext&> callContext;
480 481
    // The call context, if it's still active.  Becomes null when the `Return` message is sent.
    // This object, if non-null, is owned by `asyncOp`.
482

483 484 485
    kj::Array<ExportId> resultExports;
    // List of exports that were sent in the results.  If the finish has `releaseResultCaps` these
    // will need to be released.
486 487 488 489 490 491
  };

  struct Export {
    uint refcount = 0;
    // When this reaches 0, drop `clientHook` and free this export.

492
    kj::Own<ClientHook> clientHook;
493

494 495 496 497
    kj::Promise<void> resolveOp = nullptr;
    // If this export is a promise (not a settled capability), the `resolveOp` represents the
    // ongoing operation to wait for that promise to resolve and then send a `Resolve` message.

498 499 500 501 502 503 504 505 506 507 508
    inline bool operator==(decltype(nullptr)) const { return refcount == 0; }
    inline bool operator!=(decltype(nullptr)) const { return refcount != 0; }
  };

  struct Import {
    Import() = default;
    Import(const Import&) = delete;
    Import(Import&&) = default;
    Import& operator=(Import&&) = default;
    // If we don't explicitly write all this, we get some stupid error deep in STL.

509
    kj::Maybe<ImportClient&> importClient;
510 511
    // Becomes null when the import is destroyed.

512 513 514 515 516
    kj::Maybe<RpcClient&> appClient;
    // Either a copy of importClient, or, in the case of promises, the wrapping PromiseClient.
    // Becomes null when it is discarded *or* when the import is destroyed (e.g. the promise is
    // resolved and the import is no longer needed).

517
    kj::Maybe<kj::Own<kj::PromiseFulfiller<kj::Own<ClientHook>>>> promiseFulfiller;
518 519 520
    // If non-null, the import is a promise.
  };

Kenton Varda's avatar
Kenton Varda committed
521 522 523 524 525 526 527 528 529 530 531 532
  typedef uint32_t EmbargoId;

  struct Embargo {
    // For handling the `Disembargo` message when looping back to self.

    kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> fulfiller;
    // Fulfill this when the Disembargo arrives.

    inline bool operator==(decltype(nullptr)) const { return fulfiller == nullptr; }
    inline bool operator!=(decltype(nullptr)) const { return fulfiller != nullptr; }
  };

533 534 535
  // =======================================================================================
  // OK, now we can define RpcConnectionState's member data.

536
  BootstrapFactoryBase& bootstrapFactory;
537
  kj::Maybe<RealmGateway<>::Client> gateway;
538
  kj::Maybe<SturdyRefRestorerBase&> restorer;
539 540 541 542 543 544 545

  typedef kj::Own<VatNetworkBase::Connection> Connected;
  typedef kj::Exception Disconnected;
  kj::OneOf<Connected, Disconnected> connection;
  // Once the connection has failed, we drop it and replace it with an exception, which will be
  // thrown from all further calls.

Kenton Varda's avatar
Kenton Varda committed
546
  kj::Own<kj::PromiseFulfiller<DisconnectInfo>> disconnectFulfiller;
547

548 549
  ExportTable<ExportId, Export> exports;
  ExportTable<QuestionId, Question> questions;
550 551
  ImportTable<AnswerId, Answer> answers;
  ImportTable<ImportId, Import> imports;
552 553 554 555 556 557 558 559 560
  // The Four Tables!
  // The order of the tables is important for correct destruction.

  std::unordered_map<ClientHook*, ExportId> exportsByCap;
  // Maps already-exported ClientHook objects to their ID in the export table.

  ExportTable<EmbargoId, Embargo> embargoes;
  // There are only four tables.  This definitely isn't a fifth table.  I don't know what you're
  // talking about.
561

562 563 564 565 566 567 568
  size_t flowLimit;
  size_t callWordsInFlight = 0;

  kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> flowWaiter;
  // If non-null, we're currently blocking incoming messages waiting for callWordsInFlight to drop
  // below flowLimit. Fulfill this to un-block.

569 570 571
  kj::TaskSet tasks;

  // =====================================================================================
Kenton Varda's avatar
Kenton Varda committed
572
  // ClientHook implementations
573

Kenton Varda's avatar
Kenton Varda committed
574
  class RpcClient: public ClientHook, public kj::Refcounted {
575
  public:
576
    RpcClient(RpcConnectionState& connectionState)
577
        : connectionState(kj::addRef(connectionState)) {}
578

579 580
    virtual kj::Maybe<ExportId> writeDescriptor(rpc::CapDescriptor::Builder descriptor,
                                                kj::Vector<int>& fds) = 0;
581 582 583
    // Writes a CapDescriptor referencing this client.  The CapDescriptor must be sent as part of
    // the very next message sent on the connection, as it may become invalid if other things
    // happen.
Kenton Varda's avatar
Kenton Varda committed
584 585 586 587
    //
    // If writing the descriptor adds a new export to the export table, or increments the refcount
    // on an existing one, then the ID is returned and the caller is responsible for removing it
    // later.
Kenton Varda's avatar
Kenton Varda committed
588

589 590
    virtual kj::Maybe<kj::Own<ClientHook>> writeTarget(
        rpc::MessageTarget::Builder target) = 0;
Kenton Varda's avatar
Kenton Varda committed
591
    // Writes the appropriate call target for calls to this capability and returns null.
Kenton Varda's avatar
Kenton Varda committed
592
    //
Kenton Varda's avatar
Kenton Varda committed
593 594 595 596
    // - OR -
    //
    // If calls have been redirected to some other local ClientHook, returns that hook instead.
    // This can happen if the capability represents a promise that has been resolved.
Kenton Varda's avatar
Kenton Varda committed
597

598
    virtual kj::Own<ClientHook> getInnermostClient() = 0;
Kenton Varda's avatar
Kenton Varda committed
599 600 601 602
    // If this client just wraps some other client -- even if it is only *temporarily* wrapping
    // that other client -- return a reference to the other client, transitively.  Otherwise,
    // return a new reference to *this.

Kenton Varda's avatar
Kenton Varda committed
603 604
    // implements ClientHook -----------------------------------------

605
    Request<AnyPointer, AnyPointer> newCall(
606
        uint64_t interfaceId, uint16_t methodId, kj::Maybe<MessageSize> sizeHint) override {
607 608 609 610 611 612 613 614 615 616 617 618
      if (interfaceId == typeId<Persistent<>>() && methodId == 0) {
        KJ_IF_MAYBE(g, connectionState->gateway) {
          // Wait, this is a call to Persistent.save() and we need to translate it through our
          // gateway.
          //
          // We pull a neat trick here: We actually end up returning a RequestHook for an import
          // request on the gateway cap, but with the "root" of the request actually pointing
          // to the "params" field of the real request.

          sizeHint = sizeHint.map([](MessageSize hint) {
            ++hint.capCount;
            hint.wordCount += sizeInWords<RealmGateway<>::ImportParams>();
619
            return hint;
620 621 622
          });

          auto request = g->importRequest(sizeHint);
623
          request.setCap(Persistent<>::Client(kj::refcounted<NoInterceptClient>(*this)));
624

625 626 627 628 629 630 631 632 633 634 635
          // Awkwardly, request.initParams() would return a SaveParams struct, but to construct
          // the Request<AnyPointer, AnyPointer> to return we need an AnyPointer::Builder, and you
          // can't go backwards from a struct builder to an AnyPointer builder. So instead we
          // manually get at the pointer by converting the outer request to AnyStruct and then
          // pulling the pointer from the pointer section.
          auto pointers = toAny(request).getPointerSection();
          KJ_ASSERT(pointers.size() >= 2);
          auto paramsPtr = pointers[1];
          KJ_ASSERT(paramsPtr.isNull());

          return Request<AnyPointer, AnyPointer>(paramsPtr, RequestHook::from(kj::mv(request)));
636 637 638
        }
      }

639 640 641 642 643
      return newCallNoIntercept(interfaceId, methodId, sizeHint);
    }

    Request<AnyPointer, AnyPointer> newCallNoIntercept(
        uint64_t interfaceId, uint16_t methodId, kj::Maybe<MessageSize> sizeHint) {
644 645 646 647
      if (!connectionState->connection.is<Connected>()) {
        return newBrokenRequest(kj::cp(connectionState->connection.get<Disconnected>()), sizeHint);
      }

648
      auto request = kj::heap<RpcRequest>(
649 650
          *connectionState, *connectionState->connection.get<Connected>(),
          sizeHint, kj::addRef(*this));
651 652 653 654 655 656
      auto callBuilder = request->getCall();

      callBuilder.setInterfaceId(interfaceId);
      callBuilder.setMethodId(methodId);

      auto root = request->getRoot();
657
      return Request<AnyPointer, AnyPointer>(root, kj::mv(request));
658 659
    }

Kenton Varda's avatar
Kenton Varda committed
660
    VoidPromiseAndPipeline call(uint64_t interfaceId, uint16_t methodId,
661
                                kj::Own<CallContextHook>&& context) override {
662 663 664 665 666 667 668 669 670 671 672
      if (interfaceId == typeId<Persistent<>>() && methodId == 0) {
        KJ_IF_MAYBE(g, connectionState->gateway) {
          // Wait, this is a call to Persistent.save() and we need to translate it through our
          // gateway.
          auto params = context->getParams().getAs<Persistent<>::SaveParams>();

          auto requestSize = params.totalSize();
          ++requestSize.capCount;
          requestSize.wordCount += sizeInWords<RealmGateway<>::ImportParams>();

          auto request = g->importRequest(requestSize);
673
          request.setCap(Persistent<>::Client(kj::refcounted<NoInterceptClient>(*this)));
674 675 676 677 678 679 680 681
          request.setParams(params);

          context->allowCancellation();
          context->releaseParams();
          return context->directTailCall(RequestHook::from(kj::mv(request)));
        }
      }

682 683 684 685 686 687 688
      return callNoIntercept(interfaceId, methodId, kj::mv(context));
    }

    VoidPromiseAndPipeline callNoIntercept(uint64_t interfaceId, uint16_t methodId,
                                           kj::Own<CallContextHook>&& context) {
      // Implement call() by copying params and results messages.

Kenton Varda's avatar
Kenton Varda committed
689
      auto params = context->getParams();
690
      auto request = newCallNoIntercept(interfaceId, methodId, params.targetSize());
Kenton Varda's avatar
Kenton Varda committed
691

692
      request.set(params);
Kenton Varda's avatar
Kenton Varda committed
693 694
      context->releaseParams();

695
      // We can and should propagate cancellation.
696
      context->allowCancellation();
697

698
      return context->directTailCall(RequestHook::from(kj::mv(request)));
Kenton Varda's avatar
Kenton Varda committed
699 700
    }

701
    kj::Own<ClientHook> addRef() override {
Kenton Varda's avatar
Kenton Varda committed
702 703
      return kj::addRef(*this);
    }
704
    const void* getBrand() override {
705
      return connectionState.get();
Kenton Varda's avatar
Kenton Varda committed
706 707
    }

708
    kj::Own<RpcConnectionState> connectionState;
Kenton Varda's avatar
Kenton Varda committed
709 710
  };

711 712 713 714
  class ImportClient final: public RpcClient {
    // A ClientHook that wraps an entry in the import table.

  public:
715 716 717
    ImportClient(RpcConnectionState& connectionState, ImportId importId,
                 kj::Maybe<kj::AutoCloseFd> fd)
        : RpcClient(connectionState), importId(importId), fd(kj::mv(fd)) {}
Kenton Varda's avatar
Kenton Varda committed
718

Kenton Varda's avatar
Kenton Varda committed
719
    ~ImportClient() noexcept(false) {
720
      unwindDetector.catchExceptionsIfUnwinding([&]() {
721
        // Remove self from the import table, if the table is still pointing at us.
722 723 724 725 726
        KJ_IF_MAYBE(import, connectionState->imports.find(importId)) {
          KJ_IF_MAYBE(i, import->importClient) {
            if (i == this) {
              connectionState->imports.erase(importId);
            }
727 728
          }
        }
Kenton Varda's avatar
Kenton Varda committed
729

730
        // Send a message releasing our remote references.
731 732
        if (remoteRefcount > 0 && connectionState->connection.is<Connected>()) {
          auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
733 734 735 736 737 738 739
              messageSizeHint<rpc::Release>());
          rpc::Release::Builder builder = message->getBody().initAs<rpc::Message>().initRelease();
          builder.setId(importId);
          builder.setReferenceCount(remoteRefcount);
          message->send();
        }
      });
740 741
    }

742 743 744 745 746 747
    void setFdIfMissing(kj::Maybe<kj::AutoCloseFd> newFd) {
      if (fd == nullptr) {
        fd = kj::mv(newFd);
      }
    }

748 749 750
    void addRemoteRef() {
      // Add a new RemoteRef and return a new ref to this client representing it.
      ++remoteRefcount;
Kenton Varda's avatar
Kenton Varda committed
751
    }
752

753 754
    kj::Maybe<ExportId> writeDescriptor(rpc::CapDescriptor::Builder descriptor,
                                        kj::Vector<int>& fds) override {
Kenton Varda's avatar
Kenton Varda committed
755
      descriptor.setReceiverHosted(importId);
Kenton Varda's avatar
Kenton Varda committed
756
      return nullptr;
Kenton Varda's avatar
Kenton Varda committed
757 758
    }

759 760
    kj::Maybe<kj::Own<ClientHook>> writeTarget(
        rpc::MessageTarget::Builder target) override {
761
      target.setImportedCap(importId);
Kenton Varda's avatar
Kenton Varda committed
762
      return nullptr;
Kenton Varda's avatar
Kenton Varda committed
763 764
    }

765
    kj::Own<ClientHook> getInnermostClient() override {
Kenton Varda's avatar
Kenton Varda committed
766 767 768
      return kj::addRef(*this);
    }

Kenton Varda's avatar
Kenton Varda committed
769
    // implements ClientHook -----------------------------------------
770

771
    kj::Maybe<ClientHook&> getResolved() override {
772 773 774
      return nullptr;
    }

775
    kj::Maybe<kj::Promise<kj::Own<ClientHook>>> whenMoreResolved() override {
776 777 778
      return nullptr;
    }

779 780 781 782
    kj::Maybe<int> getFd() override {
      return fd.map([](auto& f) { return f.get(); });
    }

Kenton Varda's avatar
Kenton Varda committed
783
  private:
784
    ImportId importId;
785
    kj::Maybe<kj::AutoCloseFd> fd;
Kenton Varda's avatar
Kenton Varda committed
786 787 788

    uint remoteRefcount = 0;
    // Number of times we've received this import from the peer.
789 790

    kj::UnwindDetector unwindDetector;
Kenton Varda's avatar
Kenton Varda committed
791 792
  };

793 794 795
  class PipelineClient final: public RpcClient {
    // A ClientHook representing a pipelined promise.  Always wrapped in PromiseClient.

Kenton Varda's avatar
Kenton Varda committed
796
  public:
797 798
    PipelineClient(RpcConnectionState& connectionState,
                   kj::Own<QuestionRef>&& questionRef,
799
                   kj::Array<PipelineOp>&& ops)
Kenton Varda's avatar
Kenton Varda committed
800
        : RpcClient(connectionState), questionRef(kj::mv(questionRef)), ops(kj::mv(ops)) {}
Kenton Varda's avatar
Kenton Varda committed
801

802 803
   kj::Maybe<ExportId> writeDescriptor(rpc::CapDescriptor::Builder descriptor,
                                       kj::Vector<int>& fds) override {
Kenton Varda's avatar
Kenton Varda committed
804 805 806 807 808
      auto promisedAnswer = descriptor.initReceiverAnswer();
      promisedAnswer.setQuestionId(questionRef->getId());
      promisedAnswer.adoptTransform(fromPipelineOps(
          Orphanage::getForMessageContaining(descriptor), ops));
      return nullptr;
Kenton Varda's avatar
Kenton Varda committed
809 810
    }

811 812
    kj::Maybe<kj::Own<ClientHook>> writeTarget(
        rpc::MessageTarget::Builder target) override {
Kenton Varda's avatar
Kenton Varda committed
813 814 815 816
      auto builder = target.initPromisedAnswer();
      builder.setQuestionId(questionRef->getId());
      builder.adoptTransform(fromPipelineOps(Orphanage::getForMessageContaining(builder), ops));
      return nullptr;
817 818
    }

819
    kj::Own<ClientHook> getInnermostClient() override {
Kenton Varda's avatar
Kenton Varda committed
820 821 822
      return kj::addRef(*this);
    }

823
    // implements ClientHook -----------------------------------------
Kenton Varda's avatar
Kenton Varda committed
824

825
    kj::Maybe<ClientHook&> getResolved() override {
826 827 828
      return nullptr;
    }

829
    kj::Maybe<kj::Promise<kj::Own<ClientHook>>> whenMoreResolved() override {
830
      return nullptr;
Kenton Varda's avatar
Kenton Varda committed
831 832
    }

833 834 835 836
    kj::Maybe<int> getFd() override {
      return nullptr;
    }

Kenton Varda's avatar
Kenton Varda committed
837
  private:
838
    kj::Own<QuestionRef> questionRef;
839
    kj::Array<PipelineOp> ops;
Kenton Varda's avatar
Kenton Varda committed
840 841
  };

842 843 844 845
  class PromiseClient final: public RpcClient {
    // A ClientHook that initially wraps one client (in practice, an ImportClient or a
    // PipelineClient) and then, later on, redirects to some other client.

Kenton Varda's avatar
Kenton Varda committed
846
  public:
847 848 849
    PromiseClient(RpcConnectionState& connectionState,
                  kj::Own<ClientHook> initial,
                  kj::Promise<kj::Own<ClientHook>> eventual,
850
                  kj::Maybe<ImportId> importId)
851
        : RpcClient(connectionState),
852 853
          isResolved(false),
          cap(kj::mv(initial)),
854
          importId(importId),
855 856 857
          fork(eventual.fork()),
          resolveSelfPromise(fork.addBranch().then(
              [this](kj::Own<ClientHook>&& resolution) {
858
                resolve(kj::mv(resolution), false);
859
              }, [this](kj::Exception&& exception) {
860
                resolve(newBrokenCap(kj::mv(exception)), true);
861 862 863 864
              }).eagerlyEvaluate([&](kj::Exception&& e) {
                // Make any exceptions thrown from resolve() go to the connection's TaskSet which
                // will cause the connection to be terminated.
                connectionState.tasks.add(kj::mv(e));
Kenton Varda's avatar
Kenton Varda committed
865
              })) {
866 867 868 869 870 871
      // Create a client that starts out forwarding all calls to `initial` but, once `eventual`
      // resolves, will forward there instead.  In addition, `whenMoreResolved()` will return a fork
      // of `eventual`.  Note that this means the application could hold on to `eventual` even after
      // the `PromiseClient` is destroyed; `eventual` must therefore make sure to hold references to
      // anything that needs to stay alive in order to resolve it correctly (such as making sure the
      // import ID is not released).
Kenton Varda's avatar
Kenton Varda committed
872
    }
Kenton Varda's avatar
Kenton Varda committed
873

874 875 876 877 878 879
    ~PromiseClient() noexcept(false) {
      KJ_IF_MAYBE(id, importId) {
        // This object is representing an import promise.  That means the import table may still
        // contain a pointer back to it.  Remove that pointer.  Note that we have to verify that
        // the import still exists and the pointer still points back to this object because this
        // object may actually outlive the import.
880
        KJ_IF_MAYBE(import, connectionState->imports.find(*id)) {
881 882 883 884 885 886 887 888 889
          KJ_IF_MAYBE(c, import->appClient) {
            if (c == this) {
              import->appClient = nullptr;
            }
          }
        }
      }
    }

890 891
    kj::Maybe<ExportId> writeDescriptor(rpc::CapDescriptor::Builder descriptor,
                                        kj::Vector<int>& fds) override {
892
      receivedCall = true;
893
      return connectionState->writeDescriptor(*cap, descriptor, fds);
Kenton Varda's avatar
Kenton Varda committed
894
    }
Kenton Varda's avatar
Kenton Varda committed
895

896 897
    kj::Maybe<kj::Own<ClientHook>> writeTarget(
        rpc::MessageTarget::Builder target) override {
898
      receivedCall = true;
899
      return connectionState->writeTarget(*cap, target);
Kenton Varda's avatar
Kenton Varda committed
900 901
    }

902
    kj::Own<ClientHook> getInnermostClient() override {
903
      receivedCall = true;
904
      return connectionState->getInnermostClient(*cap);
Kenton Varda's avatar
Kenton Varda committed
905 906
    }

Kenton Varda's avatar
Kenton Varda committed
907
    // implements ClientHook -----------------------------------------
Kenton Varda's avatar
Kenton Varda committed
908

909
    Request<AnyPointer, AnyPointer> newCall(
910
        uint64_t interfaceId, uint16_t methodId, kj::Maybe<MessageSize> sizeHint) override {
911 912 913 914 915 916 917 918 919 920
      if (!isResolved && interfaceId == typeId<Persistent<>>() && methodId == 0 &&
          connectionState->gateway != nullptr) {
        // This is a call to Persistent.save(), and we're not resolved yet, and the underlying
        // remote capability will perform a gateway translation. This isn't right if the promise
        // ultimately resolves to a local capability. Instead, we'll need to queue the call until
        // the promise resolves.
        return newLocalPromiseClient(fork.addBranch())
            ->newCall(interfaceId, methodId, sizeHint);
      }

921
      receivedCall = true;
922
      return cap->newCall(interfaceId, methodId, sizeHint);
923 924
    }

925
    VoidPromiseAndPipeline call(uint64_t interfaceId, uint16_t methodId,
926
                                kj::Own<CallContextHook>&& context) override {
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
      if (!isResolved && interfaceId == typeId<Persistent<>>() && methodId == 0 &&
          connectionState->gateway != nullptr) {
        // This is a call to Persistent.save(), and we're not resolved yet, and the underlying
        // remote capability will perform a gateway translation. This isn't right if the promise
        // ultimately resolves to a local capability. Instead, we'll need to queue the call until
        // the promise resolves.

        auto vpapPromises = fork.addBranch().then(kj::mvCapture(context,
            [interfaceId,methodId](kj::Own<CallContextHook>&& context,
                                   kj::Own<ClientHook> resolvedCap) {
          auto vpap = resolvedCap->call(interfaceId, methodId, kj::mv(context));
          return kj::tuple(kj::mv(vpap.promise), kj::mv(vpap.pipeline));
        })).split();

        return {
          kj::mv(kj::get<0>(vpapPromises)),
          newLocalPromisePipeline(kj::mv(kj::get<1>(vpapPromises))),
        };
      }

947
      receivedCall = true;
948
      return cap->call(interfaceId, methodId, kj::mv(context));
949 950
    }

951
    kj::Maybe<ClientHook&> getResolved() override {
952 953
      if (isResolved) {
        return *cap;
954 955 956
      } else {
        return nullptr;
      }
Kenton Varda's avatar
Kenton Varda committed
957 958
    }

959
    kj::Maybe<kj::Promise<kj::Own<ClientHook>>> whenMoreResolved() override {
960
      return fork.addBranch();
Kenton Varda's avatar
Kenton Varda committed
961
    }
Kenton Varda's avatar
Kenton Varda committed
962

963 964 965 966 967 968 969 970 971 972 973 974 975 976
    kj::Maybe<int> getFd() override {
      if (isResolved) {
        return cap->getFd();
      } else {
        // In theory, before resolution, the ImportClient for the promise could have an FD
        // attached, if the promise itself was presented with an attached FD. However, we can't
        // really return that one here because it may be closed when we get the Resolve message
        // later. In theory we could have the PromiseClient itself take ownership of an FD that
        // arrived attached to a promise cap, but the use case for that is questionable. I'm
        // keeping it simple for now.
        return nullptr;
      }
    }

Kenton Varda's avatar
Kenton Varda committed
977
  private:
978 979
    bool isResolved;
    kj::Own<ClientHook> cap;
980

981
    kj::Maybe<ImportId> importId;
982
    kj::ForkedPromise<kj::Own<ClientHook>> fork;
Kenton Varda's avatar
Kenton Varda committed
983 984 985 986 987

    // Keep this last, because the continuation uses *this, so it should be destroyed first to
    // ensure the continuation is not still running.
    kj::Promise<void> resolveSelfPromise;

988
    bool receivedCall = false;
Kenton Varda's avatar
Kenton Varda committed
989

990
    void resolve(kj::Own<ClientHook> replacement, bool isError) {
991 992 993 994
      const void* replacementBrand = replacement->getBrand();
      if (replacementBrand != connectionState.get() &&
          replacementBrand != &ClientHook::NULL_CAPABILITY_BRAND &&
          receivedCall && !isError && connectionState->connection.is<Connected>()) {
995 996 997 998 999
        // The new capability is hosted locally, not on the remote machine.  And, we had made calls
        // to the promise.  We need to make sure those calls echo back to us before we allow new
        // calls to go directly to the local capability, so we need to set a local embargo and send
        // a `Disembargo` to echo through the peer.

1000
        auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
1001
            messageSizeHint<rpc::Disembargo>() + MESSAGE_TARGET_SIZE_HINT);
Kenton Varda's avatar
Kenton Varda committed
1002

Kenton Varda's avatar
Kenton Varda committed
1003
        auto disembargo = message->getBody().initAs<rpc::Message>().initDisembargo();
Kenton Varda's avatar
Kenton Varda committed
1004 1005

        {
1006
          auto redirect = connectionState->writeTarget(*cap, disembargo.initTarget());
Kenton Varda's avatar
Kenton Varda committed
1007 1008 1009 1010 1011
          KJ_ASSERT(redirect == nullptr,
                    "Original promise target should always be from this RPC connection.");
        }

        EmbargoId embargoId;
1012
        Embargo& embargo = connectionState->embargoes.next(embargoId);
Kenton Varda's avatar
Kenton Varda committed
1013 1014 1015 1016 1017 1018 1019

        disembargo.getContext().setSenderLoopback(embargoId);

        auto paf = kj::newPromiseAndFulfiller<void>();
        embargo.fulfiller = kj::mv(paf.fulfiller);

        // Make a promise which resolves to `replacement` as soon as the `Disembargo` comes back.
1020
        auto embargoPromise = paf.promise.then(
1021
            kj::mvCapture(replacement, [](kj::Own<ClientHook>&& replacement) {
Kenton Varda's avatar
Kenton Varda committed
1022 1023 1024 1025 1026
              return kj::mv(replacement);
            }));

        // We need to queue up calls in the meantime, so we'll resolve ourselves to a local promise
        // client instead.
1027
        replacement = newLocalPromiseClient(kj::mv(embargoPromise));
Kenton Varda's avatar
Kenton Varda committed
1028 1029 1030 1031 1032

        // Send the `Disembargo`.
        message->send();
      }

1033
      cap = kj::mv(replacement);
1034
      isResolved = true;
Kenton Varda's avatar
Kenton Varda committed
1035
    }
Kenton Varda's avatar
Kenton Varda committed
1036
  };
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  class NoInterceptClient final: public RpcClient {
    // A wrapper around an RpcClient which bypasses special handling of "save" requests. When we
    // intercept a "save" request and invoke a RealmGateway, we give it a version of the capability
    // with intercepting disabled, since usually the first thing the RealmGateway will do is turn
    // around and call save() again.
    //
    // This is admittedly sort of backwards: the interception of "save" ought to be the part
    // implemented by a wrapper. However, that would require placing a wrapper around every
    // RpcClient we create whereas NoInterceptClient only needs to be injected after a save()
    // request occurs and is intercepted.

  public:
    NoInterceptClient(RpcClient& inner)
        : RpcClient(*inner.connectionState),
          inner(kj::addRef(inner)) {}

1054 1055 1056
    kj::Maybe<ExportId> writeDescriptor(rpc::CapDescriptor::Builder descriptor,
                                        kj::Vector<int>& fds) override {
      return inner->writeDescriptor(descriptor, fds);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    }

    kj::Maybe<kj::Own<ClientHook>> writeTarget(rpc::MessageTarget::Builder target) override {
      return inner->writeTarget(target);
    }

    kj::Own<ClientHook> getInnermostClient() override {
      return inner->getInnermostClient();
    }

    Request<AnyPointer, AnyPointer> newCall(
        uint64_t interfaceId, uint16_t methodId, kj::Maybe<MessageSize> sizeHint) override {
      return inner->newCallNoIntercept(interfaceId, methodId, sizeHint);
    }
    VoidPromiseAndPipeline call(uint64_t interfaceId, uint16_t methodId,
                                kj::Own<CallContextHook>&& context) override {
      return inner->callNoIntercept(interfaceId, methodId, kj::mv(context));
    }

    kj::Maybe<ClientHook&> getResolved() override {
      return nullptr;
    }

    kj::Maybe<kj::Promise<kj::Own<ClientHook>>> whenMoreResolved() override {
      return nullptr;
    }

1084 1085 1086 1087
    kj::Maybe<int> getFd() override {
      return nullptr;
    }

1088 1089 1090 1091
  private:
    kj::Own<RpcClient> inner;
  };

1092 1093
  kj::Maybe<ExportId> writeDescriptor(ClientHook& cap, rpc::CapDescriptor::Builder descriptor,
                                      kj::Vector<int>& fds) {
1094
    // Write a descriptor for the given capability.
Kenton Varda's avatar
Kenton Varda committed
1095

1096
    // Find the innermost wrapped capability.
1097
    ClientHook* inner = &cap;
1098 1099 1100 1101 1102 1103 1104 1105
    for (;;) {
      KJ_IF_MAYBE(resolved, inner->getResolved()) {
        inner = resolved;
      } else {
        break;
      }
    }

1106 1107 1108 1109 1110
    KJ_IF_MAYBE(fd, inner->getFd()) {
      descriptor.setAttachedFd(fds.size());
      fds.add(kj::mv(*fd));
    }

1111
    if (inner->getBrand() == this) {
1112
      return kj::downcast<RpcClient>(*inner).writeDescriptor(descriptor, fds);
Kenton Varda's avatar
Kenton Varda committed
1113
    } else {
1114 1115
      auto iter = exportsByCap.find(inner);
      if (iter != exportsByCap.end()) {
1116
        // We've already seen and exported this capability before.  Just up the refcount.
1117
        auto& exp = KJ_ASSERT_NONNULL(exports.find(iter->second));
Kenton Varda's avatar
Kenton Varda committed
1118 1119 1120 1121
        ++exp.refcount;
        descriptor.setSenderHosted(iter->second);
        return iter->second;
      } else {
1122
        // This is the first time we've seen this capability.
Kenton Varda's avatar
Kenton Varda committed
1123
        ExportId exportId;
1124 1125
        auto& exp = exports.next(exportId);
        exportsByCap[inner] = exportId;
Kenton Varda's avatar
Kenton Varda committed
1126
        exp.refcount = 1;
1127 1128 1129 1130
        exp.clientHook = inner->addRef();

        KJ_IF_MAYBE(wrapped, inner->whenMoreResolved()) {
          // This is a promise.  Arrange for the `Resolve` message to be sent later.
Kenton Varda's avatar
Kenton Varda committed
1131
          exp.resolveOp = resolveExportedPromise(exportId, kj::mv(*wrapped));
1132 1133 1134
          descriptor.setSenderPromise(exportId);
        } else {
          descriptor.setSenderHosted(exportId);
1135 1136
        }

Kenton Varda's avatar
Kenton Varda committed
1137 1138
        return exportId;
      }
Kenton Varda's avatar
Kenton Varda committed
1139 1140 1141
    }
  }

1142
  kj::Array<ExportId> writeDescriptors(kj::ArrayPtr<kj::Maybe<kj::Own<ClientHook>>> capTable,
1143
                                       rpc::Payload::Builder payload, kj::Vector<int>& fds) {
1144 1145 1146
    auto capTableBuilder = payload.initCapTable(capTable.size());
    kj::Vector<ExportId> exports(capTable.size());
    for (uint i: kj::indices(capTable)) {
1147
      KJ_IF_MAYBE(cap, capTable[i]) {
1148
        KJ_IF_MAYBE(exportId, writeDescriptor(**cap, capTableBuilder[i], fds)) {
1149 1150 1151 1152
          exports.add(*exportId);
        }
      } else {
        capTableBuilder[i].setNone();
1153 1154 1155 1156 1157
      }
    }
    return exports.releaseAsArray();
  }

1158
  kj::Maybe<kj::Own<ClientHook>> writeTarget(ClientHook& cap, rpc::MessageTarget::Builder target) {
Kenton Varda's avatar
Kenton Varda committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    // If calls to the given capability should pass over this connection, fill in `target`
    // appropriately for such a call and return nullptr.  Otherwise, return a `ClientHook` to which
    // the call should be forwarded; the caller should then delegate the call to that `ClientHook`.
    //
    // The main case where this ends up returning non-null is if `cap` is a promise that has
    // recently resolved.  The application might have started building a request before the promise
    // resolved, and so the request may have been built on the assumption that it would be sent over
    // this network connection, but then the promise resolved to point somewhere else before the
    // request was sent.  Now the request has to be redirected to the new target instead.

    if (cap.getBrand() == this) {
1170
      return kj::downcast<RpcClient>(cap).writeTarget(target);
Kenton Varda's avatar
Kenton Varda committed
1171 1172 1173 1174 1175
    } else {
      return cap.addRef();
    }
  }

1176 1177
  kj::Own<ClientHook> getInnermostClient(ClientHook& client) {
    ClientHook* ptr = &client;
Kenton Varda's avatar
Kenton Varda committed
1178 1179 1180 1181 1182 1183 1184 1185 1186
    for (;;) {
      KJ_IF_MAYBE(inner, ptr->getResolved()) {
        ptr = inner;
      } else {
        break;
      }
    }

    if (ptr->getBrand() == this) {
1187
      return kj::downcast<RpcClient>(*ptr).getInnermostClient();
Kenton Varda's avatar
Kenton Varda committed
1188 1189 1190 1191 1192 1193
    } else {
      return ptr->addRef();
    }
  }

  kj::Promise<void> resolveExportedPromise(
1194
      ExportId exportId, kj::Promise<kj::Own<ClientHook>>&& promise) {
Kenton Varda's avatar
Kenton Varda committed
1195 1196 1197 1198
    // Implements exporting of a promise.  The promise has been exported under the given ID, and is
    // to eventually resolve to the ClientHook produced by `promise`.  This method waits for that
    // resolve to happen and then sends the appropriate `Resolve` message to the peer.

1199
    return promise.then(
1200
        [this,exportId](kj::Own<ClientHook>&& resolution) -> kj::Promise<void> {
Kenton Varda's avatar
Kenton Varda committed
1201 1202
      // Successful resolution.

1203 1204 1205 1206 1207
      KJ_ASSERT(connection.is<Connected>(),
                "Resolving export should have been canceled on disconnect.") {
        return kj::READY_NOW;
      }

Kenton Varda's avatar
Kenton Varda committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
      // Get the innermost ClientHook backing the resolved client.  This includes traversing
      // PromiseClients that haven't resolved yet to their underlying ImportClient or
      // PipelineClient, so that we get a remote promise that might resolve later.  This is
      // important to make sure that if the peer sends a `Disembargo` back to us, it bounces back
      // correctly instead of going to the result of some future resolution.  See the documentation
      // for `Disembargo` in `rpc.capnp`.
      resolution = getInnermostClient(*resolution);

      // Update the export table to point at this object instead.  We know that our entry in the
      // export table is still live because when it is destroyed the asynchronous resolution task
      // (i.e. this code) is canceled.
1219 1220
      auto& exp = KJ_ASSERT_NONNULL(exports.find(exportId));
      exportsByCap.erase(exp.clientHook);
Kenton Varda's avatar
Kenton Varda committed
1221 1222
      exp.clientHook = kj::mv(resolution);

1223
      if (exp.clientHook->getBrand() != this) {
Kenton Varda's avatar
Kenton Varda committed
1224 1225 1226
        // We're resolving to a local capability.  If we're resolving to a promise, we might be
        // able to reuse our export table entry and avoid sending a message.

1227
        KJ_IF_MAYBE(promise, exp.clientHook->whenMoreResolved()) {
Kenton Varda's avatar
Kenton Varda committed
1228 1229 1230 1231
          // We're replacing a promise with another local promise.  In this case, we might actually
          // be able to just reuse the existing export table entry to represent the new promise --
          // unless it already has an entry.  Let's check.

1232
          auto insertResult = exportsByCap.insert(std::make_pair(exp.clientHook.get(), exportId));
Kenton Varda's avatar
Kenton Varda committed
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

          if (insertResult.second) {
            // The new promise was not already in the table, therefore the existing export table
            // entry has now been repurposed to represent it.  There is no need to send a resolve
            // message at all.  We do, however, have to start resolving the next promise.
            return resolveExportedPromise(exportId, kj::mv(*promise));
          }
        }
      }

      // OK, we have to send a `Resolve` message.
1244
      auto message = connection.get<Connected>()->newOutgoingMessage(
Kenton Varda's avatar
Kenton Varda committed
1245 1246 1247
          messageSizeHint<rpc::Resolve>() + sizeInWords<rpc::CapDescriptor>() + 16);
      auto resolve = message->getBody().initAs<rpc::Message>().initResolve();
      resolve.setPromiseId(exportId);
1248 1249 1250
      kj::Vector<int> fds;
      writeDescriptor(*exp.clientHook, resolve.initCap(), fds);
      message->setFds(fds.releaseAsArray());
Kenton Varda's avatar
Kenton Varda committed
1251 1252 1253 1254 1255
      message->send();

      return kj::READY_NOW;
    }, [this,exportId](kj::Exception&& exception) {
      // send error resolution
1256
      auto message = connection.get<Connected>()->newOutgoingMessage(
Kenton Varda's avatar
Kenton Varda committed
1257 1258 1259 1260 1261
          messageSizeHint<rpc::Resolve>() + exceptionSizeHint(exception) + 8);
      auto resolve = message->getBody().initAs<rpc::Message>().initResolve();
      resolve.setPromiseId(exportId);
      fromException(exception, resolve.initException());
      message->send();
1262 1263 1264
    }).eagerlyEvaluate([this](kj::Exception&& exception) {
      // Put the exception on the TaskSet which will cause the connection to be terminated.
      tasks.add(kj::mv(exception));
Kenton Varda's avatar
Kenton Varda committed
1265 1266 1267
    });
  }

Kenton Varda's avatar
Kenton Varda committed
1268
  // =====================================================================================
1269
  // Interpreting CapDescriptor
Kenton Varda's avatar
Kenton Varda committed
1270

1271
  kj::Own<ClientHook> import(ImportId importId, bool isPromise, kj::Maybe<kj::AutoCloseFd> fd) {
1272
    // Receive a new import.
Kenton Varda's avatar
Kenton Varda committed
1273

1274 1275
    auto& import = imports[importId];
    kj::Own<ImportClient> importClient;
Kenton Varda's avatar
Kenton Varda committed
1276

1277 1278 1279
    // Create the ImportClient, or if one already exists, use it.
    KJ_IF_MAYBE(c, import.importClient) {
      importClient = kj::addRef(*c);
1280 1281 1282 1283 1284 1285 1286 1287 1288

      // If the same import is introduced multiple times, and it is missing an FD the first time,
      // but it has one on a later attempt, we want to attach the later one. This could happen
      // because the first introduction was part of a message that had too many other FDs and went
      // over the per-message limit. Perhaps the protocol design is such that this other message
      // doesn't really care if the FDs are transferred or not, but the later message really does
      // care; it would be bad if the previous message blocked later messages from delivering the
      // FD just because it happened to reference the same capability.
      importClient->setFdIfMissing(kj::mv(fd));
1289
    } else {
1290
      importClient = kj::refcounted<ImportClient>(*this, importId, kj::mv(fd));
1291
      import.importClient = *importClient;
Kenton Varda's avatar
Kenton Varda committed
1292
    }
1293

1294 1295
    // We just received a copy of this import ID, so the remote refcount has gone up.
    importClient->addRemoteRef();
Kenton Varda's avatar
Kenton Varda committed
1296

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    if (isPromise) {
      // We need to construct a PromiseClient around this import, if we haven't already.
      KJ_IF_MAYBE(c, import.appClient) {
        // Use the existing one.
        return kj::addRef(*c);
      } else {
        // Create a promise for this import's resolution.
        auto paf = kj::newPromiseAndFulfiller<kj::Own<ClientHook>>();
        import.promiseFulfiller = kj::mv(paf.fulfiller);

        // Make sure the import is not destroyed while this promise exists.
        paf.promise = paf.promise.attach(kj::addRef(*importClient));

        // Create a PromiseClient around it and return it.
        auto result = kj::refcounted<PromiseClient>(
            *this, kj::mv(importClient), kj::mv(paf.promise), importId);
        import.appClient = *result;
        return kj::mv(result);
1315
      }
1316 1317 1318
    } else {
      import.appClient = *importClient;
      return kj::mv(importClient);
1319
    }
1320
  }
1321

1322 1323 1324 1325 1326 1327 1328 1329
  kj::Maybe<kj::Own<ClientHook>> receiveCap(rpc::CapDescriptor::Reader descriptor,
                                            kj::ArrayPtr<kj::AutoCloseFd> fds) {
    uint fdIndex = descriptor.getAttachedFd();
    kj::Maybe<kj::AutoCloseFd> fd;
    if (fdIndex < fds.size() && fds[fdIndex] != nullptr) {
      fd = kj::mv(fds[fdIndex]);
    }

1330 1331
    switch (descriptor.which()) {
      case rpc::CapDescriptor::NONE:
1332
        return nullptr;
1333

1334
      case rpc::CapDescriptor::SENDER_HOSTED:
1335
        return import(descriptor.getSenderHosted(), false, kj::mv(fd));
1336
      case rpc::CapDescriptor::SENDER_PROMISE:
1337
        return import(descriptor.getSenderPromise(), true, kj::mv(fd));
1338

1339 1340 1341 1342
      case rpc::CapDescriptor::RECEIVER_HOSTED:
        KJ_IF_MAYBE(exp, exports.find(descriptor.getReceiverHosted())) {
          return exp->clientHook->addRef();
        } else {
1343 1344 1345
          return newBrokenCap("invalid 'receiverHosted' export ID");
        }

1346 1347
      case rpc::CapDescriptor::RECEIVER_ANSWER: {
        auto promisedAnswer = descriptor.getReceiverAnswer();
1348

1349 1350 1351 1352 1353 1354 1355
        KJ_IF_MAYBE(answer, answers.find(promisedAnswer.getQuestionId())) {
          if (answer->active) {
            KJ_IF_MAYBE(pipeline, answer->pipeline) {
              KJ_IF_MAYBE(ops, toPipelineOps(promisedAnswer.getTransform())) {
                return pipeline->get()->getPipelinedCap(*ops);
              } else {
                return newBrokenCap("unrecognized pipeline ops");
Kenton Varda's avatar
Kenton Varda committed
1356 1357
              }
            }
1358
          }
1359 1360
        }

1361
        return newBrokenCap("invalid 'receiverAnswer'");
1362 1363
      }

1364 1365
      case rpc::CapDescriptor::THIRD_PARTY_HOSTED:
        // We don't support third-party caps, so use the vine instead.
1366
        return import(descriptor.getThirdPartyHosted().getVineId(), false, kj::mv(fd));
Kenton Varda's avatar
Kenton Varda committed
1367

1368 1369 1370
      default:
        KJ_FAIL_REQUIRE("unknown CapDescriptor type") { break; }
        return newBrokenCap("unknown CapDescriptor type");
Kenton Varda's avatar
Kenton Varda committed
1371
    }
1372
  }
1373

1374 1375
  kj::Array<kj::Maybe<kj::Own<ClientHook>>> receiveCaps(List<rpc::CapDescriptor>::Reader capTable,
                                                        kj::ArrayPtr<kj::AutoCloseFd> fds) {
1376
    auto result = kj::heapArrayBuilder<kj::Maybe<kj::Own<ClientHook>>>(capTable.size());
1377
    for (auto cap: capTable) {
1378
      result.add(receiveCap(cap, fds));
Kenton Varda's avatar
Kenton Varda committed
1379
    }
1380 1381
    return result.finish();
  }
1382 1383

  // =====================================================================================
Kenton Varda's avatar
Kenton Varda committed
1384
  // RequestHook/PipelineHook/ResponseHook implementations
1385

Kenton Varda's avatar
Kenton Varda committed
1386 1387 1388 1389
  class QuestionRef: public kj::Refcounted {
    // A reference to an entry on the question table.  Used to detect when the `Finish` message
    // can be sent.

Kenton Varda's avatar
Kenton Varda committed
1390
  public:
1391
    inline QuestionRef(
1392 1393 1394
        RpcConnectionState& connectionState, QuestionId id,
        kj::Own<kj::PromiseFulfiller<kj::Promise<kj::Own<RpcResponse>>>> fulfiller)
        : connectionState(kj::addRef(connectionState)), id(id), fulfiller(kj::mv(fulfiller)) {}
Kenton Varda's avatar
Kenton Varda committed
1395 1396

    ~QuestionRef() {
1397
      unwindDetector.catchExceptionsIfUnwinding([&]() {
1398 1399 1400
        auto& question = KJ_ASSERT_NONNULL(
            connectionState->questions.find(id), "Question ID no longer on table?");

1401
        // Send the "Finish" message (if the connection is not already broken).
1402
        if (connectionState->connection.is<Connected>() && !question.skipFinish) {
1403
          auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
1404
              messageSizeHint<rpc::Finish>());
1405 1406
          auto builder = message->getBody().getAs<rpc::Message>().initFinish();
          builder.setQuestionId(id);
1407 1408 1409
          // If we're still awaiting a return, then this request is being canceled, and we're going
          // to ignore any capabilities in the return message, so set releaseResultCaps true. If we
          // already received the return, then we've already built local proxies for the caps and
David Renshaw's avatar
David Renshaw committed
1410
          // will send Release messages when those are destroyed.
1411
          builder.setReleaseResultCaps(question.isAwaitingReturn);
1412
          message->send();
1413
        }
Kenton Varda's avatar
Kenton Varda committed
1414

1415 1416 1417
        // Check if the question has returned and, if so, remove it from the table.
        // Remove question ID from the table.  Must do this *after* sending `Finish` to ensure that
        // the ID is not re-allocated before the `Finish` message can be sent.
1418 1419
        if (question.isAwaitingReturn) {
          // Still waiting for return, so just remove the QuestionRef pointer from the table.
1420
          question.selfRef = nullptr;
1421 1422 1423
        } else {
          // Call has already returned, so we can now remove it from the table.
          connectionState->questions.erase(id, question);
1424 1425
        }
      });
Kenton Varda's avatar
Kenton Varda committed
1426 1427 1428 1429
    }

    inline QuestionId getId() const { return id; }

1430
    void fulfill(kj::Own<RpcResponse>&& response) {
Kenton Varda's avatar
Kenton Varda committed
1431 1432 1433
      fulfiller->fulfill(kj::mv(response));
    }

1434
    void fulfill(kj::Promise<kj::Own<RpcResponse>>&& promise) {
1435 1436 1437
      fulfiller->fulfill(kj::mv(promise));
    }

Kenton Varda's avatar
Kenton Varda committed
1438 1439
    void reject(kj::Exception&& exception) {
      fulfiller->reject(kj::mv(exception));
1440
    }
Kenton Varda's avatar
Kenton Varda committed
1441 1442

  private:
1443
    kj::Own<RpcConnectionState> connectionState;
Kenton Varda's avatar
Kenton Varda committed
1444
    QuestionId id;
1445
    kj::Own<kj::PromiseFulfiller<kj::Promise<kj::Own<RpcResponse>>>> fulfiller;
1446
    kj::UnwindDetector unwindDetector;
Kenton Varda's avatar
Kenton Varda committed
1447 1448
  };

Kenton Varda's avatar
Kenton Varda committed
1449
  class RpcRequest final: public RequestHook {
1450
  public:
1451 1452
    RpcRequest(RpcConnectionState& connectionState, VatNetworkBase::Connection& connection,
               kj::Maybe<MessageSize> sizeHint, kj::Own<RpcClient>&& target)
1453
        : connectionState(kj::addRef(connectionState)),
Kenton Varda's avatar
Kenton Varda committed
1454
          target(kj::mv(target)),
1455
          message(connection.newOutgoingMessage(
1456 1457
              firstSegmentSize(sizeHint, messageSizeHint<rpc::Call>() +
                  sizeInWords<rpc::Payload>() + MESSAGE_TARGET_SIZE_HINT))),
Kenton Varda's avatar
Kenton Varda committed
1458
          callBuilder(message->getBody().getAs<rpc::Message>().initCall()),
1459
          paramsBuilder(capTable.imbue(callBuilder.getParams().getContent())) {}
Kenton Varda's avatar
Kenton Varda committed
1460

1461
    inline AnyPointer::Builder getRoot() {
Kenton Varda's avatar
Kenton Varda committed
1462 1463
      return paramsBuilder;
    }
Kenton Varda's avatar
Kenton Varda committed
1464 1465 1466
    inline rpc::Call::Builder getCall() {
      return callBuilder;
    }
Kenton Varda's avatar
Kenton Varda committed
1467

1468
    RemotePromise<AnyPointer> send() override {
1469
      if (!connectionState->connection.is<Connected>()) {
1470
        // Connection is broken.
1471
        const kj::Exception& e = connectionState->connection.get<Disconnected>();
1472
        return RemotePromise<AnyPointer>(
1473 1474
            kj::Promise<Response<AnyPointer>>(kj::cp(e)),
            AnyPointer::Pipeline(newBrokenPipeline(kj::cp(e))));
1475
      }
Kenton Varda's avatar
Kenton Varda committed
1476

1477 1478 1479
      KJ_IF_MAYBE(redirect, target->writeTarget(callBuilder.getTarget())) {
        // Whoops, this capability has been redirected while we were building the request!
        // We'll have to make a new request and do a copy.  Ick.
Kenton Varda's avatar
Kenton Varda committed
1480

1481
        auto replacement = redirect->get()->newCall(
1482
            callBuilder.getInterfaceId(), callBuilder.getMethodId(), paramsBuilder.targetSize());
1483 1484 1485
        replacement.set(paramsBuilder);
        return replacement.send();
      } else {
1486
        auto sendResult = sendInternal(false);
Kenton Varda's avatar
Kenton Varda committed
1487

1488
        auto forkedPromise = sendResult.promise.fork();
1489

1490 1491 1492
        // The pipeline must get notified of resolution before the app does to maintain ordering.
        auto pipeline = kj::refcounted<RpcPipeline>(
            *connectionState, kj::mv(sendResult.questionRef), forkedPromise.addBranch());
Kenton Varda's avatar
Kenton Varda committed
1493

1494 1495 1496 1497 1498
        auto appPromise = forkedPromise.addBranch().then(
            [=](kj::Own<RpcResponse>&& response) {
              auto reader = response->getResults();
              return Response<AnyPointer>(reader, kj::mv(response));
            });
Kenton Varda's avatar
Kenton Varda committed
1499

1500 1501 1502 1503
        return RemotePromise<AnyPointer>(
            kj::mv(appPromise),
            AnyPointer::Pipeline(kj::mv(pipeline)));
      }
Kenton Varda's avatar
Kenton Varda committed
1504 1505
    }

1506 1507 1508
    struct TailInfo {
      QuestionId questionId;
      kj::Promise<void> promise;
1509
      kj::Own<PipelineHook> pipeline;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    };

    kj::Maybe<TailInfo> tailSend() {
      // Send the request as a tail call.
      //
      // Returns null if for some reason a tail call is not possible and the caller should fall
      // back to using send() and copying the response.

      SendInternalResult sendResult;

1520
      if (!connectionState->connection.is<Connected>()) {
1521 1522 1523
        // Disconnected; fall back to a regular send() which will fail appropriately.
        return nullptr;
      }
1524

1525 1526 1527 1528 1529 1530
      KJ_IF_MAYBE(redirect, target->writeTarget(callBuilder.getTarget())) {
        // Whoops, this capability has been redirected while we were building the request!
        // Fall back to regular send().
        return nullptr;
      } else {
        sendResult = sendInternal(true);
1531 1532
      }

1533
      auto promise = sendResult.promise.then([](kj::Own<RpcResponse>&& response) {
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
        // Response should be null if `Return` handling code is correct.
        KJ_ASSERT(!response) { break; }
      });

      QuestionId questionId = sendResult.questionRef->getId();

      auto pipeline = kj::refcounted<RpcPipeline>(*connectionState, kj::mv(sendResult.questionRef));

      return TailInfo { questionId, kj::mv(promise), kj::mv(pipeline) };
    }

1545
    const void* getBrand() override {
1546 1547 1548
      return connectionState.get();
    }

Kenton Varda's avatar
Kenton Varda committed
1549
  private:
1550
    kj::Own<RpcConnectionState> connectionState;
Kenton Varda's avatar
Kenton Varda committed
1551

1552
    kj::Own<RpcClient> target;
Kenton Varda's avatar
Kenton Varda committed
1553
    kj::Own<OutgoingRpcMessage> message;
1554
    BuilderCapabilityTable capTable;
Kenton Varda's avatar
Kenton Varda committed
1555
    rpc::Call::Builder callBuilder;
1556
    AnyPointer::Builder paramsBuilder;
1557 1558 1559

    struct SendInternalResult {
      kj::Own<QuestionRef> questionRef;
1560
      kj::Promise<kj::Own<RpcResponse>> promise = nullptr;
1561 1562
    };

1563
    SendInternalResult sendInternal(bool isTailCall) {
1564
      // Build the cap table.
1565
      kj::Vector<int> fds;
1566
      auto exports = connectionState->writeDescriptors(
1567 1568
          capTable.getTable(), callBuilder.getParams(), fds);
      message->setFds(fds.releaseAsArray());
1569

1570
      // Init the question table.  Do this after writing descriptors to avoid interference.
1571
      QuestionId questionId;
1572
      auto& question = connectionState->questions.next(questionId);
1573 1574 1575
      question.isAwaitingReturn = true;
      question.paramExports = kj::mv(exports);
      question.isTailCall = isTailCall;
1576

1577 1578 1579 1580 1581 1582 1583 1584
      // Make the QuentionRef and result promise.
      SendInternalResult result;
      auto paf = kj::newPromiseAndFulfiller<kj::Promise<kj::Own<RpcResponse>>>();
      result.questionRef = kj::refcounted<QuestionRef>(
          *connectionState, questionId, kj::mv(paf.fulfiller));
      question.selfRef = *result.questionRef;
      result.promise = paf.promise.attach(kj::addRef(*result.questionRef));

1585
      // Finish and send.
1586 1587 1588 1589
      callBuilder.setQuestionId(questionId);
      if (isTailCall) {
        callBuilder.getSendResultsTo().setYourself();
      }
1590 1591 1592 1593 1594
      KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
        KJ_CONTEXT("sending RPC call",
           callBuilder.getInterfaceId(), callBuilder.getMethodId());
        message->send();
      })) {
1595 1596 1597 1598 1599
        // We can't safely throw the exception from here since we've already modified the question
        // table state. We'll have to reject the promise instead.
        question.isAwaitingReturn = false;
        question.skipFinish = true;
        result.questionRef->reject(kj::mv(*exception));
1600
      }
1601

1602
      // Send and return.
1603 1604
      return kj::mv(result);
    }
Kenton Varda's avatar
Kenton Varda committed
1605 1606
  };

Kenton Varda's avatar
Kenton Varda committed
1607
  class RpcPipeline final: public PipelineHook, public kj::Refcounted {
Kenton Varda's avatar
Kenton Varda committed
1608
  public:
1609 1610
    RpcPipeline(RpcConnectionState& connectionState, kj::Own<QuestionRef>&& questionRef,
                kj::Promise<kj::Own<RpcResponse>>&& redirectLaterParam)
1611
        : connectionState(kj::addRef(connectionState)),
1612 1613 1614
          redirectLater(redirectLaterParam.fork()),
          resolveSelfPromise(KJ_ASSERT_NONNULL(redirectLater).addBranch().then(
              [this](kj::Own<RpcResponse>&& response) {
Kenton Varda's avatar
Kenton Varda committed
1615
                resolve(kj::mv(response));
1616
              }, [this](kj::Exception&& exception) {
Kenton Varda's avatar
Kenton Varda committed
1617
                resolve(kj::mv(exception));
1618 1619 1620 1621
              }).eagerlyEvaluate([&](kj::Exception&& e) {
                // Make any exceptions thrown from resolve() go to the connection's TaskSet which
                // will cause the connection to be terminated.
                connectionState.tasks.add(kj::mv(e));
Kenton Varda's avatar
Kenton Varda committed
1622 1623 1624
              })) {
      // Construct a new RpcPipeline.

1625
      state.init<Waiting>(kj::mv(questionRef));
Kenton Varda's avatar
Kenton Varda committed
1626
    }
Kenton Varda's avatar
Kenton Varda committed
1627

1628
    RpcPipeline(RpcConnectionState& connectionState, kj::Own<QuestionRef>&& questionRef)
1629 1630 1631 1632
        : connectionState(kj::addRef(connectionState)),
          resolveSelfPromise(nullptr) {
      // Construct a new RpcPipeline that is never expected to resolve.

1633
      state.init<Waiting>(kj::mv(questionRef));
Kenton Varda's avatar
Kenton Varda committed
1634
    }
Kenton Varda's avatar
Kenton Varda committed
1635 1636 1637

    // implements PipelineHook ---------------------------------------

1638
    kj::Own<PipelineHook> addRef() override {
Kenton Varda's avatar
Kenton Varda committed
1639 1640 1641
      return kj::addRef(*this);
    }

1642
    kj::Own<ClientHook> getPipelinedCap(kj::ArrayPtr<const PipelineOp> ops) override {
Kenton Varda's avatar
Kenton Varda committed
1643 1644 1645 1646 1647 1648 1649
      auto copy = kj::heapArrayBuilder<PipelineOp>(ops.size());
      for (auto& op: ops) {
        copy.add(op);
      }
      return getPipelinedCap(copy.finish());
    }

1650
    kj::Own<ClientHook> getPipelinedCap(kj::Array<PipelineOp>&& ops) override {
1651
      if (state.is<Waiting>()) {
1652 1653
        // Wrap a PipelineClient in a PromiseClient.
        auto pipelineClient = kj::refcounted<PipelineClient>(
1654
            *connectionState, kj::addRef(*state.get<Waiting>()), kj::heapArray(ops.asPtr()));
1655

1656
        KJ_IF_MAYBE(r, redirectLater) {
1657 1658 1659 1660
          auto resolutionPromise = r->addBranch().then(kj::mvCapture(ops,
              [](kj::Array<PipelineOp> ops, kj::Own<RpcResponse>&& response) {
                return response->getResults().getPipelinedCap(ops);
              }));
1661

1662 1663 1664 1665 1666 1667
          return kj::refcounted<PromiseClient>(
              *connectionState, kj::mv(pipelineClient), kj::mv(resolutionPromise), nullptr);
        } else {
          // Oh, this pipeline will never get redirected, so just return the PipelineClient.
          return kj::mv(pipelineClient);
        }
1668 1669
      } else if (state.is<Resolved>()) {
        return state.get<Resolved>()->getResults().getPipelinedCap(ops);
Kenton Varda's avatar
Kenton Varda committed
1670
      } else {
1671
        return newBrokenCap(kj::cp(state.get<Broken>()));
Kenton Varda's avatar
Kenton Varda committed
1672
      }
Kenton Varda's avatar
Kenton Varda committed
1673 1674 1675
    }

  private:
1676 1677
    kj::Own<RpcConnectionState> connectionState;
    kj::Maybe<kj::ForkedPromise<kj::Own<RpcResponse>>> redirectLater;
Kenton Varda's avatar
Kenton Varda committed
1678

1679 1680
    typedef kj::Own<QuestionRef> Waiting;
    typedef kj::Own<RpcResponse> Resolved;
Kenton Varda's avatar
Kenton Varda committed
1681
    typedef kj::Exception Broken;
1682
    kj::OneOf<Waiting, Resolved, Broken> state;
Kenton Varda's avatar
Kenton Varda committed
1683 1684 1685 1686 1687

    // Keep this last, because the continuation uses *this, so it should be destroyed first to
    // ensure the continuation is not still running.
    kj::Promise<void> resolveSelfPromise;

1688
    void resolve(kj::Own<RpcResponse>&& response) {
1689 1690
      KJ_ASSERT(state.is<Waiting>(), "Already resolved?");
      state.init<Resolved>(kj::mv(response));
Kenton Varda's avatar
Kenton Varda committed
1691 1692 1693
    }

    void resolve(const kj::Exception&& exception) {
1694 1695
      KJ_ASSERT(state.is<Waiting>(), "Already resolved?");
      state.init<Broken>(kj::mv(exception));
Kenton Varda's avatar
Kenton Varda committed
1696
    }
Kenton Varda's avatar
Kenton Varda committed
1697 1698
  };

1699 1700
  class RpcResponse: public ResponseHook {
  public:
1701
    virtual AnyPointer::Reader getResults() = 0;
1702
    virtual kj::Own<RpcResponse> addRef() = 0;
1703 1704 1705
  };

  class RpcResponseImpl final: public RpcResponse, public kj::Refcounted {
Kenton Varda's avatar
Kenton Varda committed
1706
  public:
1707
    RpcResponseImpl(RpcConnectionState& connectionState,
1708 1709
                    kj::Own<QuestionRef>&& questionRef,
                    kj::Own<IncomingRpcMessage>&& message,
1710
                    kj::Array<kj::Maybe<kj::Own<ClientHook>>> capTableArray,
1711
                    AnyPointer::Reader results)
1712 1713
        : connectionState(kj::addRef(connectionState)),
          message(kj::mv(message)),
1714 1715
          capTable(kj::mv(capTableArray)),
          reader(capTable.imbue(results)),
Kenton Varda's avatar
Kenton Varda committed
1716
          questionRef(kj::mv(questionRef)) {}
Kenton Varda's avatar
Kenton Varda committed
1717

1718
    AnyPointer::Reader getResults() override {
Kenton Varda's avatar
Kenton Varda committed
1719 1720 1721
      return reader;
    }

1722
    kj::Own<RpcResponse> addRef() override {
Kenton Varda's avatar
Kenton Varda committed
1723 1724 1725
      return kj::addRef(*this);
    }

Kenton Varda's avatar
Kenton Varda committed
1726
  private:
1727
    kj::Own<RpcConnectionState> connectionState;
Kenton Varda's avatar
Kenton Varda committed
1728
    kj::Own<IncomingRpcMessage> message;
1729
    ReaderCapabilityTable capTable;
1730
    AnyPointer::Reader reader;
1731
    kj::Own<QuestionRef> questionRef;
Kenton Varda's avatar
Kenton Varda committed
1732 1733 1734 1735 1736 1737
  };

  // =====================================================================================
  // CallContextHook implementation

  class RpcServerResponse {
Kenton Varda's avatar
Kenton Varda committed
1738
  public:
1739
    virtual AnyPointer::Builder getResultsBuilder() = 0;
1740 1741 1742 1743
  };

  class RpcServerResponseImpl final: public RpcServerResponse {
  public:
1744
    RpcServerResponseImpl(RpcConnectionState& connectionState,
1745
                          kj::Own<OutgoingRpcMessage>&& message,
1746 1747 1748
                          rpc::Payload::Builder payload)
        : connectionState(connectionState),
          message(kj::mv(message)),
1749
          payload(payload) {}
Kenton Varda's avatar
Kenton Varda committed
1750

1751
    AnyPointer::Builder getResultsBuilder() override {
1752
      return capTable.imbue(payload.getContent());
Kenton Varda's avatar
Kenton Varda committed
1753 1754
    }

1755 1756 1757 1758 1759
    kj::Maybe<kj::Array<ExportId>> send() {
      // Send the response and return the export list.  Returns nullptr if there were no caps.
      // (Could return a non-null empty array if there were caps but none of them were exports.)

      // Build the cap table.
1760
      auto capTable = this->capTable.getTable();
1761 1762 1763
      kj::Vector<int> fds;
      auto exports = connectionState.writeDescriptors(capTable, payload, fds);
      message->setFds(fds.releaseAsArray());
1764

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
      // Capabilities that we are returning are subject to embargos. See `Disembargo` in rpc.capnp.
      // As explained there, in order to deal with the Tribble 4-way race condition, we need to
      // make sure that if we're returning any remote promises, that we ignore any subsequent
      // resolution of those promises for the purpose of pipelined requests on this answer. Luckily,
      // we can modify the cap table in-place.
      for (auto& slot: capTable) {
        KJ_IF_MAYBE(cap, slot) {
          slot = connectionState.getInnermostClient(**cap);
        }
      }

Kenton Varda's avatar
Kenton Varda committed
1776
      message->send();
1777 1778 1779 1780 1781
      if (capTable.size() == 0) {
        return nullptr;
      } else {
        return kj::mv(exports);
      }
Kenton Varda's avatar
Kenton Varda committed
1782 1783 1784
    }

  private:
1785
    RpcConnectionState& connectionState;
Kenton Varda's avatar
Kenton Varda committed
1786
    kj::Own<OutgoingRpcMessage> message;
1787
    BuilderCapabilityTable capTable;
1788
    rpc::Payload::Builder payload;
Kenton Varda's avatar
Kenton Varda committed
1789 1790
  };

1791 1792 1793
  class LocallyRedirectedRpcResponse final
      : public RpcResponse, public RpcServerResponse, public kj::Refcounted{
  public:
1794
    LocallyRedirectedRpcResponse(kj::Maybe<MessageSize> sizeHint)
1795 1796
        : message(sizeHint.map([](MessageSize size) { return size.wordCount; })
                          .orDefault(SUGGESTED_FIRST_SEGMENT_WORDS)) {}
1797

1798
    AnyPointer::Builder getResultsBuilder() override {
1799
      return message.getRoot<AnyPointer>();
1800 1801
    }

1802
    AnyPointer::Reader getResults() override {
1803
      return message.getRoot<AnyPointer>();
1804 1805
    }

1806
    kj::Own<RpcResponse> addRef() override {
1807 1808 1809 1810
      return kj::addRef(*this);
    }

  private:
1811
    MallocMessageBuilder message;
1812 1813
  };

Kenton Varda's avatar
Kenton Varda committed
1814 1815
  class RpcCallContext final: public CallContextHook, public kj::Refcounted {
  public:
1816
    RpcCallContext(RpcConnectionState& connectionState, AnswerId answerId,
1817 1818 1819
                   kj::Own<IncomingRpcMessage>&& request,
                   kj::Array<kj::Maybe<kj::Own<ClientHook>>> capTableArray,
                   const AnyPointer::Reader& params,
1820 1821
                   bool redirectResults, kj::Own<kj::PromiseFulfiller<void>>&& cancelFulfiller,
                   uint64_t interfaceId, uint16_t methodId)
1822
        : connectionState(kj::addRef(connectionState)),
1823
          answerId(answerId),
1824 1825
          interfaceId(interfaceId),
          methodId(methodId),
1826
          requestSize(request->sizeInWords()),
Kenton Varda's avatar
Kenton Varda committed
1827
          request(kj::mv(request)),
1828 1829
          paramsCapTable(kj::mv(capTableArray)),
          params(paramsCapTable.imbue(params)),
1830
          returnMessage(nullptr),
Kenton Varda's avatar
Kenton Varda committed
1831
          redirectResults(redirectResults),
1832 1833 1834
          cancelFulfiller(kj::mv(cancelFulfiller)) {
      connectionState.callWordsInFlight += requestSize;
    }
Kenton Varda's avatar
Kenton Varda committed
1835

1836 1837 1838 1839
    ~RpcCallContext() noexcept(false) {
      if (isFirstResponder()) {
        // We haven't sent a return yet, so we must have been canceled.  Send a cancellation return.
        unwindDetector.catchExceptionsIfUnwinding([&]() {
Kenton Varda's avatar
Kenton Varda committed
1840
          // Don't send anything if the connection is broken.
1841 1842
          if (connectionState->connection.is<Connected>()) {
            auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
1843
                messageSizeHint<rpc::Return>() + sizeInWords<rpc::Payload>());
Kenton Varda's avatar
Kenton Varda committed
1844
            auto builder = message->getBody().initAs<rpc::Message>().initReturn();
1845

1846
            builder.setAnswerId(answerId);
1847
            builder.setReleaseParamCaps(false);
1848

Kenton Varda's avatar
Kenton Varda committed
1849 1850 1851 1852 1853 1854 1855 1856 1857
            if (redirectResults) {
              // The reason we haven't sent a return is because the results were sent somewhere
              // else.
              builder.setResultsSentElsewhere();
            } else {
              builder.setCanceled();
            }

            message->send();
1858
          }
1859

1860
          cleanupAnswerTable(nullptr, true);
1861 1862 1863 1864
        });
      }
    }

1865
    kj::Own<RpcResponse> consumeRedirectedResponse() {
1866 1867
      KJ_ASSERT(redirectResults);

1868
      if (response == nullptr) getResults(MessageSize{0, 0});  // force initialization of response
1869 1870 1871 1872 1873 1874

      // Note that the context needs to keep its own reference to the response so that it doesn't
      // get GC'd until the PipelineHook drops its reference to the context.
      return kj::downcast<LocallyRedirectedRpcResponse>(*KJ_ASSERT_NONNULL(response)).addRef();
    }

Kenton Varda's avatar
Kenton Varda committed
1875
    void sendReturn() {
1876
      KJ_ASSERT(!redirectResults);
1877 1878 1879 1880

      // Avoid sending results if canceled so that we don't have to figure out whether or not
      // `releaseResultCaps` was set in the already-received `Finish`.
      if (!(cancellationFlags & CANCEL_REQUESTED) && isFirstResponder()) {
1881 1882 1883 1884 1885
        KJ_ASSERT(connectionState->connection.is<Connected>(),
                  "Cancellation should have been requested on disconnect.") {
          return;
        }

1886
        if (response == nullptr) getResults(MessageSize{0, 0});  // force initialization of response
Kenton Varda's avatar
Kenton Varda committed
1887

1888
        returnMessage.setAnswerId(answerId);
1889
        returnMessage.setReleaseParamCaps(false);
Kenton Varda's avatar
Kenton Varda committed
1890

1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
        kj::Maybe<kj::Array<ExportId>> exports;
        KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
          // Debug info incase send() fails due to overside message.
          KJ_CONTEXT("returning from RPC call", interfaceId, methodId);
          exports = kj::downcast<RpcServerResponseImpl>(*KJ_ASSERT_NONNULL(response)).send();
        })) {
          responseSent = false;
          sendErrorReturn(kj::mv(*exception));
          return;
        }

1902 1903 1904 1905 1906 1907 1908
        KJ_IF_MAYBE(e, exports) {
          // Caps were returned, so we can't free the pipeline yet.
          cleanupAnswerTable(kj::mv(*e), false);
        } else {
          // No caps in the results, therefore the pipeline is irrelevant.
          cleanupAnswerTable(nullptr, true);
        }
Kenton Varda's avatar
Kenton Varda committed
1909 1910 1911
      }
    }
    void sendErrorReturn(kj::Exception&& exception) {
1912
      KJ_ASSERT(!redirectResults);
Kenton Varda's avatar
Kenton Varda committed
1913
      if (isFirstResponder()) {
1914 1915 1916 1917
        if (connectionState->connection.is<Connected>()) {
          auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
              messageSizeHint<rpc::Return>() + exceptionSizeHint(exception));
          auto builder = message->getBody().initAs<rpc::Message>().initReturn();
Kenton Varda's avatar
Kenton Varda committed
1918

1919 1920 1921
          builder.setAnswerId(answerId);
          builder.setReleaseParamCaps(false);
          fromException(exception, builder.initException());
Kenton Varda's avatar
Kenton Varda committed
1922

1923 1924
          message->send();
        }
1925 1926 1927 1928

        // Do not allow releasing the pipeline because we want pipelined calls to propagate the
        // exception rather than fail with a "no such field" exception.
        cleanupAnswerTable(nullptr, false);
Kenton Varda's avatar
Kenton Varda committed
1929 1930 1931
      }
    }

1932
    void requestCancel() {
Kenton Varda's avatar
Kenton Varda committed
1933 1934 1935 1936 1937 1938
      // Hints that the caller wishes to cancel this call.  At the next time when cancellation is
      // deemed safe, the RpcCallContext shall send a canceled Return -- or if it never becomes
      // safe, the RpcCallContext will send a normal return when the call completes.  Either way
      // the RpcCallContext is now responsible for cleaning up the entry in the answer table, since
      // a Finish message was already received.

1939 1940 1941 1942
      bool previouslyAllowedButNotRequested = cancellationFlags == CANCEL_ALLOWED;
      cancellationFlags |= CANCEL_REQUESTED;

      if (previouslyAllowedButNotRequested) {
Kenton Varda's avatar
Kenton Varda committed
1943
        // We just set CANCEL_REQUESTED, and CANCEL_ALLOWED was already set previously.  Initiate
Kenton Varda's avatar
Kenton Varda committed
1944
        // the cancellation.
Kenton Varda's avatar
Kenton Varda committed
1945
        cancelFulfiller->fulfill();
Kenton Varda's avatar
Kenton Varda committed
1946
      }
Kenton Varda's avatar
Kenton Varda committed
1947
    }
1948 1949 1950

    // implements CallContextHook ------------------------------------

1951
    AnyPointer::Reader getParams() override {
1952 1953 1954 1955 1956 1957
      KJ_REQUIRE(request != nullptr, "Can't call getParams() after releaseParams().");
      return params;
    }
    void releaseParams() override {
      request = nullptr;
    }
1958
    AnyPointer::Builder getResults(kj::Maybe<MessageSize> sizeHint) override {
1959
      KJ_IF_MAYBE(r, response) {
1960
        return r->get()->getResultsBuilder();
1961
      } else {
1962 1963
        kj::Own<RpcServerResponse> response;

1964
        if (redirectResults || !connectionState->connection.is<Connected>()) {
1965
          response = kj::refcounted<LocallyRedirectedRpcResponse>(sizeHint);
1966
        } else {
1967
          auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
1968 1969
              firstSegmentSize(sizeHint, messageSizeHint<rpc::Return>() +
                               sizeInWords<rpc::Payload>()));
1970 1971 1972 1973 1974 1975
          returnMessage = message->getBody().initAs<rpc::Message>().initReturn();
          response = kj::heap<RpcServerResponseImpl>(
              *connectionState, kj::mv(message), returnMessage.getResults());
        }

        auto results = response->getResultsBuilder();
Kenton Varda's avatar
Kenton Varda committed
1976 1977
        this->response = kj::mv(response);
        return results;
1978 1979
      }
    }
1980 1981 1982
    kj::Promise<void> tailCall(kj::Own<RequestHook>&& request) override {
      auto result = directTailCall(kj::mv(request));
      KJ_IF_MAYBE(f, tailCallPipelineFulfiller) {
1983
        f->get()->fulfill(AnyPointer::Pipeline(kj::mv(result.pipeline)));
1984 1985 1986 1987
      }
      return kj::mv(result.promise);
    }
    ClientHook::VoidPromiseAndPipeline directTailCall(kj::Own<RequestHook>&& request) override {
1988 1989 1990
      KJ_REQUIRE(response == nullptr,
                 "Can't call tailCall() after initializing the results struct.");

1991
      if (request->getBrand() == connectionState.get() && !redirectResults) {
1992 1993 1994 1995 1996
        // The tail call is headed towards the peer that called us in the first place, so we can
        // optimize out the return trip.

        KJ_IF_MAYBE(tailInfo, kj::downcast<RpcRequest>(*request).tailSend()) {
          if (isFirstResponder()) {
1997 1998 1999 2000
            if (connectionState->connection.is<Connected>()) {
              auto message = connectionState->connection.get<Connected>()->newOutgoingMessage(
                  messageSizeHint<rpc::Return>());
              auto builder = message->getBody().initAs<rpc::Message>().initReturn();
2001

2002 2003 2004
              builder.setAnswerId(answerId);
              builder.setReleaseParamCaps(false);
              builder.setTakeFromOtherQuestion(tailInfo->questionId);
2005

2006 2007
              message->send();
            }
2008 2009 2010

            // There are no caps in our return message, but of course the tail results could have
            // caps, so we must continue to honor pipeline calls (and just bounce them back).
2011
            cleanupAnswerTable(nullptr, false);
2012
          }
2013
          return { kj::mv(tailInfo->promise), kj::mv(tailInfo->pipeline) };
2014 2015 2016 2017 2018 2019 2020
        }
      }

      // Just forwarding to another local call.
      auto promise = request->send();

      // Wait for response.
2021
      auto voidPromise = promise.then([this](Response<AnyPointer>&& tailResponse) {
2022 2023 2024
        // Copy the response.
        // TODO(perf):  It would be nice if we could somehow make the response get built in-place
        //   but requires some refactoring.
2025
        getResults(tailResponse.targetSize()).set(tailResponse);
2026
      });
2027 2028

      return { kj::mv(voidPromise), PipelineHook::from(kj::mv(promise)) };
2029
    }
2030 2031
    kj::Promise<AnyPointer::Pipeline> onTailCall() override {
      auto paf = kj::newPromiseAndFulfiller<AnyPointer::Pipeline>();
2032 2033 2034
      tailCallPipelineFulfiller = kj::mv(paf.fulfiller);
      return kj::mv(paf.promise);
    }
2035
    void allowCancellation() override {
2036 2037 2038 2039
      bool previouslyRequestedButNotAllowed = cancellationFlags == CANCEL_REQUESTED;
      cancellationFlags |= CANCEL_ALLOWED;

      if (previouslyRequestedButNotAllowed) {
Kenton Varda's avatar
Kenton Varda committed
2040 2041 2042
        // We just set CANCEL_ALLOWED, and CANCEL_REQUESTED was already set previously.  Initiate
        // the cancellation.
        cancelFulfiller->fulfill();
Kenton Varda's avatar
Kenton Varda committed
2043
      }
2044 2045 2046 2047 2048 2049
    }
    kj::Own<CallContextHook> addRef() override {
      return kj::addRef(*this);
    }

  private:
2050
    kj::Own<RpcConnectionState> connectionState;
2051
    AnswerId answerId;
2052

2053 2054 2055 2056
    uint64_t interfaceId;
    uint16_t methodId;
    // For debugging.

Kenton Varda's avatar
Kenton Varda committed
2057 2058
    // Request ---------------------------------------------

2059
    size_t requestSize;  // for flow limit purposes
Kenton Varda's avatar
Kenton Varda committed
2060
    kj::Maybe<kj::Own<IncomingRpcMessage>> request;
2061
    ReaderCapabilityTable paramsCapTable;
2062
    AnyPointer::Reader params;
Kenton Varda's avatar
Kenton Varda committed
2063

Kenton Varda's avatar
Kenton Varda committed
2064 2065 2066
    // Response --------------------------------------------

    kj::Maybe<kj::Own<RpcServerResponse>> response;
Kenton Varda's avatar
Kenton Varda committed
2067
    rpc::Return::Builder returnMessage;
2068
    bool redirectResults = false;
Kenton Varda's avatar
Kenton Varda committed
2069
    bool responseSent = false;
2070
    kj::Maybe<kj::Own<kj::PromiseFulfiller<AnyPointer::Pipeline>>> tailCallPipelineFulfiller;
Kenton Varda's avatar
Kenton Varda committed
2071 2072 2073 2074 2075 2076 2077 2078

    // Cancellation state ----------------------------------

    enum CancellationFlags {
      CANCEL_REQUESTED = 1,
      CANCEL_ALLOWED = 2
    };

2079
    uint8_t cancellationFlags = 0;
2080
    // When both flags are set, the cancellation process will begin.
Kenton Varda's avatar
Kenton Varda committed
2081

2082
    kj::Own<kj::PromiseFulfiller<void>> cancelFulfiller;
Kenton Varda's avatar
Kenton Varda committed
2083 2084 2085
    // Fulfilled when cancellation has been both requested and permitted.  The fulfilled promise is
    // exclusive-joined with the outermost promise waiting on the call return, so fulfilling it
    // cancels that promise.
Kenton Varda's avatar
Kenton Varda committed
2086

2087 2088
    kj::UnwindDetector unwindDetector;

Kenton Varda's avatar
Kenton Varda committed
2089 2090 2091 2092 2093 2094 2095
    // -----------------------------------------------------

    bool isFirstResponder() {
      if (responseSent) {
        return false;
      } else {
        responseSent = true;
2096 2097 2098
        return true;
      }
    }
Kenton Varda's avatar
Kenton Varda committed
2099

2100
    void cleanupAnswerTable(kj::Array<ExportId> resultExports, bool shouldFreePipeline) {
2101 2102 2103
      // We need to remove the `callContext` pointer -- which points back to us -- from the
      // answer table.  Or we might even be responsible for removing the entire answer table
      // entry.
Kenton Varda's avatar
Kenton Varda committed
2104

2105
      if (cancellationFlags & CANCEL_REQUESTED) {
2106 2107 2108
        // Already received `Finish` so it's our job to erase the table entry. We shouldn't have
        // sent results if canceled, so we shouldn't have an export list to deal with.
        KJ_ASSERT(resultExports.size() == 0);
2109
        connectionState->answers.erase(answerId);
2110
      } else {
2111
        // We just have to null out callContext and set the exports.
2112
        auto& answer = connectionState->answers[answerId];
2113
        answer.callContext = nullptr;
2114 2115 2116 2117 2118 2119
        answer.resultExports = kj::mv(resultExports);

        if (shouldFreePipeline) {
          // We can free the pipeline early, because we know all pipeline calls are invalid (e.g.
          // because there are no caps in the result to receive pipeline requests).
          KJ_ASSERT(resultExports.size() == 0);
Kenton Varda's avatar
Kenton Varda committed
2120
          answer.pipeline = nullptr;
Kenton Varda's avatar
Kenton Varda committed
2121 2122
        }
      }
2123 2124 2125 2126

      // Also, this is the right time to stop counting the call against the flow limit.
      connectionState->callWordsInFlight -= requestSize;
      connectionState->maybeUnblockFlow();
Kenton Varda's avatar
Kenton Varda committed
2127
    }
2128 2129
  };

Kenton Varda's avatar
Kenton Varda committed
2130 2131 2132
  // =====================================================================================
  // Message handling

2133 2134 2135 2136 2137 2138 2139 2140 2141
  void maybeUnblockFlow() {
    if (callWordsInFlight < flowLimit) {
      KJ_IF_MAYBE(w, flowWaiter) {
        w->get()->fulfill();
        flowWaiter = nullptr;
      }
    }
  }

2142
  kj::Promise<void> messageLoop() {
2143 2144 2145 2146
    if (!connection.is<Connected>()) {
      return kj::READY_NOW;
    }

2147 2148 2149 2150 2151 2152 2153 2154
    if (callWordsInFlight > flowLimit) {
      auto paf = kj::newPromiseAndFulfiller<void>();
      flowWaiter = kj::mv(paf.fulfiller);
      return paf.promise.then([this]() {
        return messageLoop();
      });
    }

2155
    return connection.get<Connected>()->receiveIncomingMessage().then(
2156
        [this](kj::Maybe<kj::Own<IncomingRpcMessage>>&& message) {
2157 2158
      KJ_IF_MAYBE(m, message) {
        handleMessage(kj::mv(*m));
2159
        return true;
2160
      } else {
2161
        disconnect(KJ_EXCEPTION(DISCONNECTED, "Peer disconnected."));
2162
        return false;
2163
      }
2164
    }).then([this](bool keepGoing) {
2165 2166 2167 2168
      // No exceptions; continue loop.
      //
      // (We do this in a separate continuation to handle the case where exceptions are
      // disabled.)
2169
      if (keepGoing) tasks.add(messageLoop());
2170
    });
2171 2172 2173 2174
  }

  void handleMessage(kj::Own<IncomingRpcMessage> message) {
    auto reader = message->getBody().getAs<rpc::Message>();
2175

2176 2177
    switch (reader.which()) {
      case rpc::Message::UNIMPLEMENTED:
Kenton Varda's avatar
Kenton Varda committed
2178
        handleUnimplemented(reader.getUnimplemented());
2179 2180 2181
        break;

      case rpc::Message::ABORT:
Kenton Varda's avatar
Kenton Varda committed
2182
        handleAbort(reader.getAbort());
2183 2184
        break;

2185 2186 2187 2188
      case rpc::Message::BOOTSTRAP:
        handleBootstrap(kj::mv(message), reader.getBootstrap());
        break;

2189
      case rpc::Message::CALL:
Kenton Varda's avatar
Kenton Varda committed
2190
        handleCall(kj::mv(message), reader.getCall());
2191 2192
        break;

Kenton Varda's avatar
Kenton Varda committed
2193
      case rpc::Message::RETURN:
Kenton Varda's avatar
Kenton Varda committed
2194
        handleReturn(kj::mv(message), reader.getReturn());
Kenton Varda's avatar
Kenton Varda committed
2195 2196 2197
        break;

      case rpc::Message::FINISH:
Kenton Varda's avatar
Kenton Varda committed
2198
        handleFinish(reader.getFinish());
Kenton Varda's avatar
Kenton Varda committed
2199 2200
        break;

Kenton Varda's avatar
Kenton Varda committed
2201
      case rpc::Message::RESOLVE:
2202
        handleResolve(kj::mv(message), reader.getResolve());
Kenton Varda's avatar
Kenton Varda committed
2203 2204 2205
        break;

      case rpc::Message::RELEASE:
2206
        handleRelease(reader.getRelease());
Kenton Varda's avatar
Kenton Varda committed
2207 2208
        break;

2209
      case rpc::Message::DISEMBARGO:
Kenton Varda's avatar
Kenton Varda committed
2210
        handleDisembargo(reader.getDisembargo());
2211 2212
        break;

2213
      default: {
2214 2215 2216 2217 2218 2219
        if (connection.is<Connected>()) {
          auto message = connection.get<Connected>()->newOutgoingMessage(
              firstSegmentSize(reader.totalSize(), messageSizeHint<void>()));
          message->getBody().initAs<rpc::Message>().setUnimplemented(reader);
          message->send();
        }
2220 2221 2222 2223 2224
        break;
      }
    }
  }

Kenton Varda's avatar
Kenton Varda committed
2225
  void handleUnimplemented(const rpc::Message::Reader& message) {
Kenton Varda's avatar
Kenton Varda committed
2226
    switch (message.which()) {
2227
      case rpc::Message::RESOLVE: {
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
        auto resolve = message.getResolve();
        switch (resolve.which()) {
          case rpc::Resolve::CAP: {
            auto cap = resolve.getCap();
            switch (cap.which()) {
              case rpc::CapDescriptor::NONE:
                // Nothing to do (but this ought never to happen).
                break;
              case rpc::CapDescriptor::SENDER_HOSTED:
                releaseExport(cap.getSenderHosted(), 1);
                break;
              case rpc::CapDescriptor::SENDER_PROMISE:
                releaseExport(cap.getSenderPromise(), 1);
                break;
              case rpc::CapDescriptor::RECEIVER_ANSWER:
              case rpc::CapDescriptor::RECEIVER_HOSTED:
                // Nothing to do.
                break;
              case rpc::CapDescriptor::THIRD_PARTY_HOSTED:
                releaseExport(cap.getThirdPartyHosted().getVineId(), 1);
                break;
            }
2250
            break;
2251 2252
          }
          case rpc::Resolve::EXCEPTION:
2253 2254 2255
            // Nothing to do.
            break;
        }
Kenton Varda's avatar
Kenton Varda committed
2256
        break;
2257
      }
Kenton Varda's avatar
Kenton Varda committed
2258 2259 2260 2261 2262

      default:
        KJ_FAIL_ASSERT("Peer did not implement required RPC message type.", (uint)message.which());
        break;
    }
2263 2264
  }

Kenton Varda's avatar
Kenton Varda committed
2265
  void handleAbort(const rpc::Exception::Reader& exception) {
2266 2267 2268
    kj::throwRecoverableException(toException(exception));
  }

2269 2270 2271
  // ---------------------------------------------------------------------------
  // Level 0

2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
  class SingleCapPipeline: public PipelineHook, public kj::Refcounted {
  public:
    SingleCapPipeline(kj::Own<ClientHook>&& cap)
        : cap(kj::mv(cap)) {}

    kj::Own<PipelineHook> addRef() override {
      return kj::addRef(*this);
    }

    kj::Own<ClientHook> getPipelinedCap(kj::ArrayPtr<const PipelineOp> ops) override {
      if (ops.size() == 0) {
        return cap->addRef();
      } else {
        return newBrokenCap("Invalid pipeline transform.");
      }
    }

  private:
    kj::Own<ClientHook> cap;
  };

  void handleBootstrap(kj::Own<IncomingRpcMessage>&& message,
                       const rpc::Bootstrap::Reader& bootstrap) {
    AnswerId answerId = bootstrap.getQuestionId();

    if (!connection.is<Connected>()) {
      // Disconnected; ignore.
      return;
    }

2302 2303
    VatNetworkBase::Connection& conn = *connection.get<Connected>();
    auto response = conn.newOutgoingMessage(
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
        messageSizeHint<rpc::Return>() + sizeInWords<rpc::CapDescriptor>() + 32);

    rpc::Return::Builder ret = response->getBody().getAs<rpc::Message>().initReturn();
    ret.setAnswerId(answerId);

    kj::Own<ClientHook> capHook;
    kj::Array<ExportId> resultExports;
    KJ_DEFER(releaseExports(resultExports));  // in case something goes wrong

    // Call the restorer and initialize the answer.
    KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
      Capability::Client cap = nullptr;
2316 2317 2318 2319 2320

      if (bootstrap.hasDeprecatedObjectId()) {
        KJ_IF_MAYBE(r, restorer) {
          cap = r->baseRestore(bootstrap.getDeprecatedObjectId());
        } else {
2321 2322 2323 2324
          KJ_FAIL_REQUIRE("This vat only supports a bootstrap interface, not the old "
                          "Cap'n-Proto-0.4-style named exports.") { return; }
        }
      } else {
2325
        cap = bootstrapFactory.baseCreateFor(conn.baseGetPeerVatId());
2326 2327
      }

2328
      BuilderCapabilityTable capTable;
2329
      auto payload = ret.initResults();
2330
      capTable.imbue(payload.getContent()).setAs<Capability>(kj::mv(cap));
2331

2332 2333
      auto capTableArray = capTable.getTable();
      KJ_DASSERT(capTableArray.size() == 1);
2334 2335 2336
      kj::Vector<int> fds;
      resultExports = writeDescriptors(capTableArray, payload, fds);
      response->setFds(fds.releaseAsArray());
2337
      capHook = KJ_ASSERT_NONNULL(capTableArray[0])->addRef();
2338 2339 2340 2341 2342 2343 2344 2345 2346
    })) {
      fromException(*exception, ret.initException());
      capHook = newBrokenCap(kj::mv(*exception));
    }

    message = nullptr;

    // Add the answer to the answer table for pipelining and send the response.
    auto& answer = answers[answerId];
2347
    KJ_REQUIRE(!answer.active, "questionId is already in use", answerId) {
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
      return;
    }

    answer.resultExports = kj::mv(resultExports);
    answer.active = true;
    answer.pipeline = kj::Own<PipelineHook>(kj::refcounted<SingleCapPipeline>(kj::mv(capHook)));

    response->send();
  }

Kenton Varda's avatar
Kenton Varda committed
2358
  void handleCall(kj::Own<IncomingRpcMessage>&& message, const rpc::Call::Reader& call) {
2359
    kj::Own<ClientHook> capability;
2360

Kenton Varda's avatar
Kenton Varda committed
2361 2362 2363 2364 2365
    KJ_IF_MAYBE(t, getMessageTarget(call.getTarget())) {
      capability = kj::mv(*t);
    } else {
      // Exception already reported.
      return;
2366 2367
    }

2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
    bool redirectResults;
    switch (call.getSendResultsTo().which()) {
      case rpc::Call::SendResultsTo::CALLER:
        redirectResults = false;
        break;
      case rpc::Call::SendResultsTo::YOURSELF:
        redirectResults = true;
        break;
      default:
        KJ_FAIL_REQUIRE("Unsupported `Call.sendResultsTo`.") { return; }
    }

2380
    auto payload = call.getParams();
2381
    auto capTableArray = receiveCaps(payload.getCapTable(), message->getAttachedFds());
Kenton Varda's avatar
Kenton Varda committed
2382 2383
    auto cancelPaf = kj::newPromiseAndFulfiller<void>();

2384
    AnswerId answerId = call.getQuestionId();
Kenton Varda's avatar
Kenton Varda committed
2385

2386
    auto context = kj::refcounted<RpcCallContext>(
2387
        *this, answerId, kj::mv(message), kj::mv(capTableArray), payload.getContent(),
2388 2389
        redirectResults, kj::mv(cancelPaf.fulfiller),
        call.getInterfaceId(), call.getMethodId());
2390

2391
    // No more using `call` after this point, as it now belongs to the context.
2392 2393

    {
2394
      auto& answer = answers[answerId];
2395 2396 2397 2398 2399 2400

      KJ_REQUIRE(!answer.active, "questionId is already in use") {
        return;
      }

      answer.active = true;
Kenton Varda's avatar
Kenton Varda committed
2401
      answer.callContext = *context;
Kenton Varda's avatar
Kenton Varda committed
2402 2403
    }

2404 2405
    auto promiseAndPipeline = startCall(
        call.getInterfaceId(), call.getMethodId(), kj::mv(capability), context->addRef());
Kenton Varda's avatar
Kenton Varda committed
2406

2407
    // Things may have changed -- in particular if startCall() immediately called
Kenton Varda's avatar
Kenton Varda committed
2408 2409 2410
    // context->directTailCall().

    {
2411
      auto& answer = answers[answerId];
Kenton Varda's avatar
Kenton Varda committed
2412

2413 2414
      answer.pipeline = kj::mv(promiseAndPipeline.pipeline);

2415
      if (redirectResults) {
Kenton Varda's avatar
Kenton Varda committed
2416
        auto resultsPromise = promiseAndPipeline.promise.then(
2417 2418 2419
            kj::mvCapture(context, [](kj::Own<RpcCallContext>&& context) {
              return context->consumeRedirectedResponse();
            }));
Kenton Varda's avatar
Kenton Varda committed
2420 2421

        // If the call that later picks up `redirectedResults` decides to discard it, we need to
2422
        // make sure our call is not itself canceled unless it has called allowCancellation().
Kenton Varda's avatar
Kenton Varda committed
2423 2424
        // So we fork the promise and join one branch with the cancellation promise, in order to
        // hold on to it.
2425
        auto forked = resultsPromise.fork();
Kenton Varda's avatar
Kenton Varda committed
2426 2427
        answer.redirectedResults = forked.addBranch();

2428 2429 2430
        cancelPaf.promise
            .exclusiveJoin(forked.addBranch().then([](kj::Own<RpcResponse>&&){}))
            .detach([](kj::Exception&&) {});
2431 2432 2433 2434 2435
      } else {
        // Hack:  Both the success and error continuations need to use the context.  We could
        //   refcount, but both will be destroyed at the same time anyway.
        RpcCallContext* contextPtr = context;

2436
        promiseAndPipeline.promise.then(
2437 2438 2439 2440
            [contextPtr]() {
              contextPtr->sendReturn();
            }, [contextPtr](kj::Exception&& exception) {
              contextPtr->sendErrorReturn(kj::mv(exception));
2441
            }).catch_([&](kj::Exception&& exception) {
2442 2443
              // Handle exceptions that occur in sendReturn()/sendErrorReturn().
              taskFailed(kj::mv(exception));
2444 2445 2446
            }).attach(kj::mv(context))
            .exclusiveJoin(kj::mv(cancelPaf.promise))
            .detach([](kj::Exception&&) {});
2447
      }
2448 2449 2450
    }
  }

2451 2452 2453 2454 2455 2456 2457 2458
  ClientHook::VoidPromiseAndPipeline startCall(
      uint64_t interfaceId, uint64_t methodId,
      kj::Own<ClientHook>&& capability, kj::Own<CallContextHook>&& context) {
    if (interfaceId == typeId<Persistent<>>() && methodId == 0) {
      KJ_IF_MAYBE(g, gateway) {
        // Wait, this is a call to Persistent.save() and we need to translate it through our
        // gateway.

2459 2460 2461 2462 2463 2464 2465 2466 2467
        KJ_IF_MAYBE(resolvedPromise, capability->whenMoreResolved()) {
          // The plot thickens: We're looking at a promise capability. It could end up resolving
          // to a capability outside the gateway, in which case we don't want to translate at all.

          auto promises = resolvedPromise->then(kj::mvCapture(context,
              [this,interfaceId,methodId](kj::Own<CallContextHook>&& context,
                                          kj::Own<ClientHook> resolvedCap) {
            auto vpap = startCall(interfaceId, methodId, kj::mv(resolvedCap), kj::mv(context));
            return kj::tuple(kj::mv(vpap.promise), kj::mv(vpap.pipeline));
2468
          })).attach(addRef(*this), kj::mv(capability)).split();
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483

          return {
            kj::mv(kj::get<0>(promises)),
            newLocalPromisePipeline(kj::mv(kj::get<1>(promises))),
          };
        }

        if (capability->getBrand() == this) {
          // This capability is one of our own, pointing back out over the network. That means
          // that it would be inappropriate to apply the gateway transformation. We just want to
          // reflect the call back.
          return kj::downcast<RpcClient>(*capability)
              .callNoIntercept(interfaceId, methodId, kj::mv(context));
        }

2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
        auto params = context->getParams().getAs<Persistent<>::SaveParams>();

        auto requestSize = params.totalSize();
        ++requestSize.capCount;
        requestSize.wordCount += sizeInWords<RealmGateway<>::ExportParams>();

        auto request = g->exportRequest(requestSize);
        request.setCap(Persistent<>::Client(capability->addRef()));
        request.setParams(params);

        context->allowCancellation();
        context->releaseParams();
        return context->directTailCall(RequestHook::from(kj::mv(request)));
      }
    }

2500
    return capability->call(interfaceId, methodId, kj::mv(context));
2501 2502
  }

2503
  kj::Maybe<kj::Own<ClientHook>> getMessageTarget(const rpc::MessageTarget::Reader& target) {
Kenton Varda's avatar
Kenton Varda committed
2504
    switch (target.which()) {
2505 2506
      case rpc::MessageTarget::IMPORTED_CAP: {
        KJ_IF_MAYBE(exp, exports.find(target.getImportedCap())) {
Kenton Varda's avatar
Kenton Varda committed
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
          return exp->clientHook->addRef();
        } else {
          KJ_FAIL_REQUIRE("Message target is not a current export ID.") {
            return nullptr;
          }
        }
        break;
      }

      case rpc::MessageTarget::PROMISED_ANSWER: {
        auto promisedAnswer = target.getPromisedAnswer();
2518
        kj::Own<PipelineHook> pipeline;
Kenton Varda's avatar
Kenton Varda committed
2519

2520 2521 2522 2523 2524 2525 2526
        auto& base = answers[promisedAnswer.getQuestionId()];
        KJ_REQUIRE(base.active, "PromisedAnswer.questionId is not a current question.") {
          return nullptr;
        }
        KJ_IF_MAYBE(p, base.pipeline) {
          pipeline = p->get()->addRef();
        } else {
2527 2528
          pipeline = newBrokenPipeline(KJ_EXCEPTION(FAILED,
              "Pipeline call on a request that returned no capabilities or was already closed."));
Kenton Varda's avatar
Kenton Varda committed
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
        }

        KJ_IF_MAYBE(ops, toPipelineOps(promisedAnswer.getTransform())) {
          return pipeline->getPipelinedCap(*ops);
        } else {
          // Exception already thrown.
          return nullptr;
        }
      }

      default:
        KJ_FAIL_REQUIRE("Unknown message target type.", target) {
          return nullptr;
        }
    }
2544 2545

    KJ_UNREACHABLE;
Kenton Varda's avatar
Kenton Varda committed
2546 2547
  }

Kenton Varda's avatar
Kenton Varda committed
2548
  void handleReturn(kj::Own<IncomingRpcMessage>&& message, const rpc::Return::Reader& ret) {
Kenton Varda's avatar
Kenton Varda committed
2549 2550
    // Transitive destructors can end up manipulating the question table and invalidating our
    // pointer into it, so make sure these destructors run later.
2551 2552
    kj::Array<ExportId> exportsToRelease;
    KJ_DEFER(releaseExports(exportsToRelease));
2553
    kj::Maybe<kj::Promise<kj::Own<RpcResponse>>> promiseToRelease;
2554

2555
    KJ_IF_MAYBE(question, questions.find(ret.getAnswerId())) {
2556 2557
      KJ_REQUIRE(question->isAwaitingReturn, "Duplicate Return.") { return; }
      question->isAwaitingReturn = false;
Kenton Varda's avatar
Kenton Varda committed
2558

2559 2560
      if (ret.getReleaseParamCaps()) {
        exportsToRelease = kj::mv(question->paramExports);
Kenton Varda's avatar
Kenton Varda committed
2561
      } else {
2562
        question->paramExports = nullptr;
Kenton Varda's avatar
Kenton Varda committed
2563
      }
2564

2565 2566
      KJ_IF_MAYBE(questionRef, question->selfRef) {
        switch (ret.which()) {
2567
          case rpc::Return::RESULTS: {
2568 2569 2570
            KJ_REQUIRE(!question->isTailCall,
                "Tail call `Return` must set `resultsSentElsewhere`, not `results`.") {
              return;
Kenton Varda's avatar
Kenton Varda committed
2571
            }
Kenton Varda's avatar
Kenton Varda committed
2572

2573
            auto payload = ret.getResults();
2574
            auto capTableArray = receiveCaps(payload.getCapTable(), message->getAttachedFds());
2575
            questionRef->fulfill(kj::refcounted<RpcResponseImpl>(
2576 2577
                *this, kj::addRef(*questionRef), kj::mv(message),
                kj::mv(capTableArray), payload.getContent()));
2578
            break;
2579
          }
2580

2581 2582 2583 2584
          case rpc::Return::EXCEPTION:
            KJ_REQUIRE(!question->isTailCall,
                "Tail call `Return` must set `resultsSentElsewhere`, not `exception`.") {
              return;
Kenton Varda's avatar
Kenton Varda committed
2585
            }
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597

            questionRef->reject(toException(ret.getException()));
            break;

          case rpc::Return::CANCELED:
            KJ_FAIL_REQUIRE("Return message falsely claims call was canceled.") { return; }
            break;

          case rpc::Return::RESULTS_SENT_ELSEWHERE:
            KJ_REQUIRE(question->isTailCall,
                "`Return` had `resultsSentElsewhere` but this was not a tail call.") {
              return;
2598 2599
            }

2600 2601 2602 2603
            // Tail calls are fulfilled with a null pointer.
            questionRef->fulfill(kj::Own<RpcResponse>());
            break;

2604 2605
          case rpc::Return::TAKE_FROM_OTHER_QUESTION:
            KJ_IF_MAYBE(answer, answers.find(ret.getTakeFromOtherQuestion())) {
2606 2607 2608
              KJ_IF_MAYBE(response, answer->redirectedResults) {
                questionRef->fulfill(kj::mv(*response));
              } else {
2609
                KJ_FAIL_REQUIRE("`Return.takeFromOtherQuestion` referenced a call that did not "
2610
                                "use `sendResultsTo.yourself`.") { return; }
2611 2612
              }
            } else {
2613
              KJ_FAIL_REQUIRE("`Return.takeFromOtherQuestion` had invalid answer ID.") { return; }
2614 2615
            }

2616
            break;
2617

2618 2619 2620 2621
          default:
            KJ_FAIL_REQUIRE("Unknown 'Return' type.") { return; }
        }
      } else {
2622
        if (ret.isTakeFromOtherQuestion()) {
2623
          // Be sure to release the tail call's promise.
2624
          KJ_IF_MAYBE(answer, answers.find(ret.getTakeFromOtherQuestion())) {
2625 2626 2627
            promiseToRelease = kj::mv(answer->redirectedResults);
          }
        }
Kenton Varda's avatar
Kenton Varda committed
2628

2629 2630
        // Looks like this question was canceled earlier, so `Finish` was already sent, with
        // `releaseResultCaps` set true so that we don't have to release them here.  We can go
2631
        // ahead and delete it from the table.
2632
        questions.erase(ret.getAnswerId(), *question);
Kenton Varda's avatar
Kenton Varda committed
2633
      }
Kenton Varda's avatar
Kenton Varda committed
2634

Kenton Varda's avatar
Kenton Varda committed
2635 2636 2637 2638 2639
    } else {
      KJ_FAIL_REQUIRE("Invalid question ID in Return message.") { return; }
    }
  }

Kenton Varda's avatar
Kenton Varda committed
2640
  void handleFinish(const rpc::Finish::Reader& finish) {
Kenton Varda's avatar
Kenton Varda committed
2641 2642
    // Delay release of these things until return so that transitive destructors don't accidentally
    // modify the answer table and invalidate our pointer into it.
2643 2644
    kj::Array<ExportId> exportsToRelease;
    KJ_DEFER(releaseExports(exportsToRelease));
2645
    Answer answerToRelease;
2646
    kj::Maybe<kj::Own<PipelineHook>> pipelineToRelease;
Kenton Varda's avatar
Kenton Varda committed
2647

2648
    KJ_IF_MAYBE(answer, answers.find(finish.getQuestionId())) {
2649
      KJ_REQUIRE(answer->active, "'Finish' for invalid question ID.") { return; }
Kenton Varda's avatar
Kenton Varda committed
2650

2651 2652 2653 2654
      if (finish.getReleaseResultCaps()) {
        exportsToRelease = kj::mv(answer->resultExports);
      } else {
        answer->resultExports = nullptr;
2655
      }
Kenton Varda's avatar
Kenton Varda committed
2656

2657 2658
      pipelineToRelease = kj::mv(answer->pipeline);

2659 2660 2661 2662 2663
      // If the call isn't actually done yet, cancel it.  Otherwise, we can go ahead and erase the
      // question from the table.
      KJ_IF_MAYBE(context, answer->callContext) {
        context->requestCancel();
      } else {
Kenton Varda's avatar
Kenton Varda committed
2664
        answerToRelease = answers.erase(finish.getQuestionId());
2665
      }
Kenton Varda's avatar
Kenton Varda committed
2666
    } else {
2667
      KJ_REQUIRE(answer->active, "'Finish' for invalid question ID.") { return; }
Kenton Varda's avatar
Kenton Varda committed
2668
    }
2669 2670
  }

2671 2672 2673
  // ---------------------------------------------------------------------------
  // Level 1

2674
  void handleResolve(kj::Own<IncomingRpcMessage>&& message, const rpc::Resolve::Reader& resolve) {
2675
    kj::Own<ClientHook> replacement;
2676
    kj::Maybe<kj::Exception> exception;
2677 2678 2679 2680

    // Extract the replacement capability.
    switch (resolve.which()) {
      case rpc::Resolve::CAP:
2681
        KJ_IF_MAYBE(cap, receiveCap(resolve.getCap(), message->getAttachedFds())) {
2682 2683 2684 2685
          replacement = kj::mv(*cap);
        } else {
          KJ_FAIL_REQUIRE("'Resolve' contained 'CapDescriptor.none'.") { return; }
        }
2686 2687 2688
        break;

      case rpc::Resolve::EXCEPTION:
2689 2690 2691 2692
        // We can't set `replacement` to a new broken cap here because this will confuse
        // PromiseClient::Resolve() into thinking that the remote promise resolved to a local
        // capability and therefore a Disembargo is needed. We must actually reject the promise.
        exception = toException(resolve.getException());
2693 2694 2695 2696 2697 2698 2699
        break;

      default:
        KJ_FAIL_REQUIRE("Unknown 'Resolve' type.") { return; }
    }

    // If the import is on the table, fulfill it.
2700
    KJ_IF_MAYBE(import, imports.find(resolve.getPromiseId())) {
2701 2702
      KJ_IF_MAYBE(fulfiller, import->promiseFulfiller) {
        // OK, this is in fact an unfulfilled promise!
2703 2704 2705 2706 2707
        KJ_IF_MAYBE(e, exception) {
          fulfiller->get()->reject(kj::mv(*e));
        } else {
          fulfiller->get()->fulfill(kj::mv(replacement));
        }
2708 2709 2710 2711 2712 2713 2714 2715
      } else if (import->importClient != nullptr) {
        // It appears this is a valid entry on the import table, but was not expected to be a
        // promise.
        KJ_FAIL_REQUIRE("Got 'Resolve' for a non-promise import.") { break; }
      }
    }
  }

2716
  void handleRelease(const rpc::Release::Reader& release) {
Kenton Varda's avatar
Kenton Varda committed
2717
    releaseExport(release.getId(), release.getReferenceCount());
2718 2719
  }

Kenton Varda's avatar
Kenton Varda committed
2720
  void releaseExport(ExportId id, uint refcount) {
2721
    KJ_IF_MAYBE(exp, exports.find(id)) {
2722
      KJ_REQUIRE(refcount <= exp->refcount, "Tried to drop export's refcount below zero.") {
Kenton Varda's avatar
Kenton Varda committed
2723
        return;
2724 2725 2726 2727
      }

      exp->refcount -= refcount;
      if (exp->refcount == 0) {
2728
        exportsByCap.erase(exp->clientHook);
2729
        exports.erase(id, *exp);
2730 2731 2732
      }
    } else {
      KJ_FAIL_REQUIRE("Tried to release invalid export ID.") {
Kenton Varda's avatar
Kenton Varda committed
2733
        return;
2734 2735 2736 2737
      }
    }
  }

2738 2739 2740 2741 2742 2743
  void releaseExports(kj::ArrayPtr<ExportId> exports) {
    for (auto exportId: exports) {
      releaseExport(exportId, 1);
    }
  }

Kenton Varda's avatar
Kenton Varda committed
2744 2745 2746 2747
  void handleDisembargo(const rpc::Disembargo::Reader& disembargo) {
    auto context = disembargo.getContext();
    switch (context.which()) {
      case rpc::Disembargo::Context::SENDER_LOOPBACK: {
2748
        kj::Own<ClientHook> target;
Kenton Varda's avatar
Kenton Varda committed
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770

        KJ_IF_MAYBE(t, getMessageTarget(disembargo.getTarget())) {
          target = kj::mv(*t);
        } else {
          // Exception already reported.
          return;
        }

        for (;;) {
          KJ_IF_MAYBE(r, target->getResolved()) {
            target = r->addRef();
          } else {
            break;
          }
        }

        KJ_REQUIRE(target->getBrand() == this,
                   "'Disembargo' of type 'senderLoopback' sent to an object that does not point "
                   "back to the sender.") {
          return;
        }

Kenton Varda's avatar
Kenton Varda committed
2771 2772 2773 2774
        EmbargoId embargoId = context.getSenderLoopback();

        // We need to insert an evalLater() here to make sure that any pending calls towards this
        // cap have had time to find their way through the event loop.
2775 2776
        tasks.add(kj::evalLater(kj::mvCapture(
            target, [this,embargoId](kj::Own<ClientHook>&& target) {
2777 2778 2779 2780
          if (!connection.is<Connected>()) {
            return;
          }

2781
          RpcClient& downcasted = kj::downcast<RpcClient>(*target);
Kenton Varda's avatar
Kenton Varda committed
2782

2783
          auto message = connection.get<Connected>()->newOutgoingMessage(
Kenton Varda's avatar
Kenton Varda committed
2784 2785 2786 2787 2788 2789
              messageSizeHint<rpc::Disembargo>() + MESSAGE_TARGET_SIZE_HINT);
          auto builder = message->getBody().initAs<rpc::Message>().initDisembargo();

          {
            auto redirect = downcasted.writeTarget(builder.initTarget());

2790
            // Disembargoes should only be sent to capabilities that were previously the subject of
Kenton Varda's avatar
Kenton Varda committed
2791
            // a `Resolve` message.  But `writeTarget` only ever returns non-null when called on
2792 2793 2794
            // a PromiseClient.  The code which sends `Resolve` and `Return` should have replaced
            // any promise with a direct node in order to solve the Tribble 4-way race condition.
            // See the documentation of Disembargo in rpc.capnp for more.
Kenton Varda's avatar
Kenton Varda committed
2795 2796
            KJ_REQUIRE(redirect == nullptr,
                       "'Disembargo' of type 'senderLoopback' sent to an object that does not "
2797
                       "appear to have been the subject of a previous 'Resolve' message.") {
Kenton Varda's avatar
Kenton Varda committed
2798 2799
              return;
            }
Kenton Varda's avatar
Kenton Varda committed
2800 2801
          }

Kenton Varda's avatar
Kenton Varda committed
2802
          builder.getContext().setReceiverLoopback(embargoId);
Kenton Varda's avatar
Kenton Varda committed
2803

Kenton Varda's avatar
Kenton Varda committed
2804 2805
          message->send();
        })));
Kenton Varda's avatar
Kenton Varda committed
2806 2807 2808 2809

        break;
      }

Kenton Varda's avatar
Kenton Varda committed
2810
      case rpc::Disembargo::Context::RECEIVER_LOOPBACK: {
2811
        KJ_IF_MAYBE(embargo, embargoes.find(context.getReceiverLoopback())) {
Kenton Varda's avatar
Kenton Varda committed
2812
          KJ_ASSERT_NONNULL(embargo->fulfiller)->fulfill();
2813
          embargoes.erase(context.getReceiverLoopback(), *embargo);
Kenton Varda's avatar
Kenton Varda committed
2814 2815 2816 2817 2818 2819
        } else {
          KJ_FAIL_REQUIRE("Invalid embargo ID in 'Disembargo.context.receiverLoopback'.") {
            return;
          }
        }
        break;
Kenton Varda's avatar
Kenton Varda committed
2820
      }
Kenton Varda's avatar
Kenton Varda committed
2821 2822 2823 2824 2825 2826

      default:
        KJ_FAIL_REQUIRE("Unimplemented Disembargo type.", disembargo) { return; }
    }
  }

2827 2828
  // ---------------------------------------------------------------------------
  // Level 2
2829 2830 2831 2832
};

}  // namespace

2833
class RpcSystemBase::Impl final: private BootstrapFactoryBase, private kj::TaskSet::ErrorHandler {
2834
public:
2835 2836 2837
  Impl(VatNetworkBase& network, kj::Maybe<Capability::Client> bootstrapInterface,
       kj::Maybe<RealmGateway<>::Client> gateway)
      : network(network), bootstrapInterface(kj::mv(bootstrapInterface)),
2838 2839 2840 2841 2842 2843
        bootstrapFactory(*this), gateway(kj::mv(gateway)), tasks(*this) {
    tasks.add(acceptLoop());
  }
  Impl(VatNetworkBase& network, BootstrapFactoryBase& bootstrapFactory,
       kj::Maybe<RealmGateway<>::Client> gateway)
      : network(network), bootstrapFactory(bootstrapFactory),
2844
        gateway(kj::mv(gateway)), tasks(*this) {
2845 2846 2847
    tasks.add(acceptLoop());
  }
  Impl(VatNetworkBase& network, SturdyRefRestorerBase& restorer)
2848
      : network(network), bootstrapFactory(*this), restorer(restorer), tasks(*this) {
2849 2850 2851 2852
    tasks.add(acceptLoop());
  }

  ~Impl() noexcept(false) {
2853 2854 2855 2856 2857
    unwindDetector.catchExceptionsIfUnwinding([&]() {
      // std::unordered_map doesn't like it when elements' destructors throw, so carefully
      // disassemble it.
      if (!connections.empty()) {
        kj::Vector<kj::Own<RpcConnectionState>> deleteMe(connections.size());
2858
        kj::Exception shutdownException = KJ_EXCEPTION(FAILED, "RpcSystem was destroyed.");
2859 2860 2861 2862
        for (auto& entry: connections) {
          entry.second->disconnect(kj::cp(shutdownException));
          deleteMe.add(kj::mv(entry.second));
        }
2863
      }
2864
    });
2865
  }
2866

2867
  Capability::Client bootstrap(AnyStruct::Reader vatId) {
2868 2869 2870 2871 2872
    // For now we delegate to restore() since it's equivalent, but eventually we'll remove restore()
    // and implement bootstrap() directly.
    return restore(vatId, AnyPointer::Reader());
  }

2873
  Capability::Client restore(AnyStruct::Reader vatId, AnyPointer::Reader objectId) {
2874
    KJ_IF_MAYBE(connection, network.baseConnect(vatId)) {
2875
      auto& state = getConnectionState(kj::mv(*connection));
2876 2877 2878 2879 2880 2881 2882
      return Capability::Client(state.restore(objectId));
    } else KJ_IF_MAYBE(r, restorer) {
      return r->baseRestore(objectId);
    } else {
      return Capability::Client(newBrokenCap(
          "SturdyRef referred to a local object but there is no local SturdyRef restorer."));
    }
2883 2884
  }

2885 2886 2887 2888 2889 2890 2891 2892
  void setFlowLimit(size_t words) {
    flowLimit = words;

    for (auto& conn: connections) {
      conn.second->setFlowLimit(words);
    }
  }

2893 2894
private:
  VatNetworkBase& network;
2895
  kj::Maybe<Capability::Client> bootstrapInterface;
2896
  BootstrapFactoryBase& bootstrapFactory;
2897
  kj::Maybe<RealmGateway<>::Client> gateway;
2898
  kj::Maybe<SturdyRefRestorerBase&> restorer;
2899
  size_t flowLimit = kj::maxValue;
2900 2901 2902 2903
  kj::TaskSet tasks;

  typedef std::unordered_map<VatNetworkBase::Connection*, kj::Own<RpcConnectionState>>
      ConnectionMap;
2904
  ConnectionMap connections;
Kenton Varda's avatar
Kenton Varda committed
2905

2906 2907
  kj::UnwindDetector unwindDetector;

2908 2909 2910
  RpcConnectionState& getConnectionState(kj::Own<VatNetworkBase::Connection>&& connection) {
    auto iter = connections.find(connection);
    if (iter == connections.end()) {
2911
      VatNetworkBase::Connection* connectionPtr = connection;
Kenton Varda's avatar
Kenton Varda committed
2912 2913 2914
      auto onDisconnect = kj::newPromiseAndFulfiller<RpcConnectionState::DisconnectInfo>();
      tasks.add(onDisconnect.promise
          .then([this,connectionPtr](RpcConnectionState::DisconnectInfo info) {
2915
        connections.erase(connectionPtr);
Kenton Varda's avatar
Kenton Varda committed
2916
        tasks.add(kj::mv(info.shutdownPromise));
2917 2918
      }));
      auto newState = kj::refcounted<RpcConnectionState>(
2919
          bootstrapFactory, gateway, restorer, kj::mv(connection),
2920
          kj::mv(onDisconnect.fulfiller), flowLimit);
2921
      RpcConnectionState& result = *newState;
2922
      connections.insert(std::make_pair(connectionPtr, kj::mv(newState)));
2923 2924 2925 2926 2927 2928 2929
      return result;
    } else {
      return *iter->second;
    }
  }

  kj::Promise<void> acceptLoop() {
2930
    auto receive = network.baseAccept().then(
2931
        [this](kj::Own<VatNetworkBase::Connection>&& connection) {
2932
      getConnectionState(kj::mv(connection));
2933 2934 2935 2936 2937 2938 2939 2940
    });
    return receive.then([this]() {
      // No exceptions; continue loop.
      //
      // (We do this in a separate continuation to handle the case where exceptions are
      // disabled.)
      tasks.add(acceptLoop());
    });
2941
  }
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958

  Capability::Client baseCreateFor(AnyStruct::Reader clientId) override {
    // Implements BootstrapFactory::baseCreateFor() in terms of `bootstrapInterface` or `restorer`,
    // for use when we were given one of those instead of an actual `bootstrapFactory`.

    KJ_IF_MAYBE(cap, bootstrapInterface) {
      return *cap;
    } else KJ_IF_MAYBE(r, restorer) {
      return r->baseRestore(AnyPointer::Reader());
    } else {
      return KJ_EXCEPTION(FAILED, "This vat does not expose any public/bootstrap interfaces.");
    }
  }

  void taskFailed(kj::Exception&& exception) override {
    KJ_LOG(ERROR, exception);
  }
2959 2960
};

2961
RpcSystemBase::RpcSystemBase(VatNetworkBase& network,
2962 2963 2964
                             kj::Maybe<Capability::Client> bootstrapInterface,
                             kj::Maybe<RealmGateway<>::Client> gateway)
    : impl(kj::heap<Impl>(network, kj::mv(bootstrapInterface), kj::mv(gateway))) {}
2965 2966 2967 2968
RpcSystemBase::RpcSystemBase(VatNetworkBase& network,
                             BootstrapFactoryBase& bootstrapFactory,
                             kj::Maybe<RealmGateway<>::Client> gateway)
    : impl(kj::heap<Impl>(network, bootstrapFactory, kj::mv(gateway))) {}
2969
RpcSystemBase::RpcSystemBase(VatNetworkBase& network, SturdyRefRestorerBase& restorer)
2970
    : impl(kj::heap<Impl>(network, restorer)) {}
2971
RpcSystemBase::RpcSystemBase(RpcSystemBase&& other) noexcept = default;
2972 2973
RpcSystemBase::~RpcSystemBase() noexcept(false) {}

2974
Capability::Client RpcSystemBase::baseBootstrap(AnyStruct::Reader vatId) {
2975 2976 2977
  return impl->bootstrap(vatId);
}

2978
Capability::Client RpcSystemBase::baseRestore(
2979
    AnyStruct::Reader hostId, AnyPointer::Reader objectId) {
2980
  return impl->restore(hostId, objectId);
2981 2982
}

2983 2984 2985 2986
void RpcSystemBase::baseSetFlowLimit(size_t words) {
  return impl->setFlowLimit(words);
}

2987 2988
}  // namespace _ (private)
}  // namespace capnp