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

22 23
#define CAPNP_TESTING_CAPNP 1

24 25
#include "rpc.h"
#include "test-util.h"
Kenton Varda's avatar
Kenton Varda committed
26
#include "schema.h"
27
#include "serialize.h"
28
#include <kj/debug.h>
Kenton Varda's avatar
Kenton Varda committed
29
#include <kj/string-tree.h>
30
#include <kj/compat/gtest.h>
31
#include <capnp/rpc.capnp.h>
32 33 34
#include <map>
#include <queue>

35 36 37 38 39 40 41 42 43
// TODO(cleanup): Auto-generate stringification functions for union discriminants.
namespace capnp {
namespace rpc {
inline kj::String KJ_STRINGIFY(Message::Which which) {
  return kj::str(static_cast<uint16_t>(which));
}
}  // namespace rpc
}  // namespace capnp

44 45 46 47
namespace capnp {
namespace _ {  // private
namespace {

Kenton Varda's avatar
Kenton Varda committed
48 49 50
class RpcDumper {
  // Class which stringifies RPC messages for debugging purposes, including decoding params and
  // results based on the call's interface and method IDs and extracting cap descriptors.
51 52 53
  //
  // TODO(cleanup):  Clean this code up and move it to someplace reusable, so it can be used as
  //   a packet inspector / debugging tool for Cap'n Proto network traffic.
Kenton Varda's avatar
Kenton Varda committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

public:
  void addSchema(InterfaceSchema schema) {
    schemas[schema.getProto().getId()] = schema;
  }

  enum Sender {
    CLIENT,
    SERVER
  };

  kj::String dump(rpc::Message::Reader message, Sender sender) {
    const char* senderName = sender == CLIENT ? "client" : "server";

    switch (message.which()) {
      case rpc::Message::CALL: {
        auto call = message.getCall();
        auto iter = schemas.find(call.getInterfaceId());
        if (iter == schemas.end()) {
          break;
        }
        InterfaceSchema schema = iter->second;
        auto methods = schema.getMethods();
        if (call.getMethodId() >= methods.size()) {
          break;
        }
        InterfaceSchema::Method method = methods[call.getMethodId()];

        auto schemaProto = schema.getProto();
        auto interfaceName =
            schemaProto.getDisplayName().slice(schemaProto.getDisplayNamePrefixLength());

        auto methodProto = method.getProto();
87 88
        auto paramType = method.getParamType();
        auto resultType = method.getResultType();
Kenton Varda's avatar
Kenton Varda committed
89

90 91 92
        if (call.getSendResultsTo().isCaller()) {
          returnTypes[std::make_pair(sender, call.getQuestionId())] = resultType;
        }
Kenton Varda's avatar
Kenton Varda committed
93

94
        auto payload = call.getParams();
95
        auto params = kj::str(payload.getContent().getAs<DynamicStruct>(paramType));
Kenton Varda's avatar
Kenton Varda committed
96 97 98 99 100 101

        auto sendResultsTo = call.getSendResultsTo();

        return kj::str(senderName, "(", call.getQuestionId(), "): call ",
                       call.getTarget(), " <- ", interfaceName, ".",
                       methodProto.getName(), params,
102
                       " caps:[", kj::strArray(payload.getCapTable(), ", "), "]",
Kenton Varda's avatar
Kenton Varda committed
103 104 105 106 107 108 109 110
                       sendResultsTo.isCaller() ? kj::str()
                                                : kj::str(" sendResultsTo:", sendResultsTo));
      }

      case rpc::Message::RETURN: {
        auto ret = message.getReturn();

        auto iter = returnTypes.find(
111
            std::make_pair(sender == CLIENT ? SERVER : CLIENT, ret.getAnswerId()));
Kenton Varda's avatar
Kenton Varda committed
112 113 114 115 116 117 118 119 120 121 122 123
        if (iter == returnTypes.end()) {
          break;
        }

        auto schema = iter->second;
        returnTypes.erase(iter);
        if (ret.which() != rpc::Return::RESULTS) {
          // Oops, no results returned.  We don't check this earlier because we want to make sure
          // returnTypes.erase() gets a chance to happen.
          break;
        }

124
        auto payload = ret.getResults();
Kenton Varda's avatar
Kenton Varda committed
125 126

        if (schema.getProto().isStruct()) {
127
          auto results = kj::str(payload.getContent().getAs<DynamicStruct>(schema.asStruct()));
Kenton Varda's avatar
Kenton Varda committed
128

129
          return kj::str(senderName, "(", ret.getAnswerId(), "): return ", results,
130
                         " caps:[", kj::strArray(payload.getCapTable(), ", "), "]");
Kenton Varda's avatar
Kenton Varda committed
131
        } else if (schema.getProto().isInterface()) {
132
          payload.getContent().getAs<DynamicCapability>(schema.asInterface());
133
          return kj::str(senderName, "(", ret.getAnswerId(), "): return cap ",
134
                         kj::strArray(payload.getCapTable(), ", "));
Kenton Varda's avatar
Kenton Varda committed
135 136 137 138 139
        } else {
          break;
        }
      }

140 141
      case rpc::Message::BOOTSTRAP: {
        auto restore = message.getBootstrap();
Kenton Varda's avatar
Kenton Varda committed
142 143 144

        returnTypes[std::make_pair(sender, restore.getQuestionId())] = InterfaceSchema();

145 146
        return kj::str(senderName, "(", restore.getQuestionId(), "): bootstrap ",
                       restore.getDeprecatedObjectId().getAs<test::TestSturdyRefObjectId>());
Kenton Varda's avatar
Kenton Varda committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
      }

      default:
        break;
    }

    return kj::str(senderName, ": ", message);
  }

private:
  std::map<uint64_t, InterfaceSchema> schemas;
  std::map<std::pair<Sender, uint32_t>, Schema> returnTypes;
};

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

163 164 165 166
class TestNetworkAdapter;

class TestNetwork {
public:
167
  TestNetwork() {
Kenton Varda's avatar
Kenton Varda committed
168 169 170 171 172 173 174 175
    dumper.addSchema(Schema::from<test::TestInterface>());
    dumper.addSchema(Schema::from<test::TestExtends>());
    dumper.addSchema(Schema::from<test::TestPipeline>());
    dumper.addSchema(Schema::from<test::TestCallOrder>());
    dumper.addSchema(Schema::from<test::TestTailCallee>());
    dumper.addSchema(Schema::from<test::TestTailCaller>());
    dumper.addSchema(Schema::from<test::TestMoreStuff>());
  }
176 177 178 179
  ~TestNetwork() noexcept(false);

  TestNetworkAdapter& add(kj::StringPtr name);

180 181 182
  kj::Maybe<TestNetworkAdapter&> find(kj::StringPtr name) {
    auto iter = map.find(name);
    if (iter == map.end()) {
183 184 185 186 187 188
      return nullptr;
    } else {
      return *iter->second;
    }
  }

Kenton Varda's avatar
Kenton Varda committed
189 190
  RpcDumper dumper;

191
private:
192
  std::map<kj::StringPtr, kj::Own<TestNetworkAdapter>> map;
193 194 195
};

typedef VatNetwork<
196
    test::TestSturdyRefHostId, test::TestProvisionId, test::TestRecipientId,
197
    test::TestThirdPartyCapId, test::TestJoinResult> TestNetworkAdapterBase;
198 199 200

class TestNetworkAdapter final: public TestNetworkAdapterBase {
public:
201 202 203
  TestNetworkAdapter(TestNetwork& network): network(network) {}

  ~TestNetworkAdapter() {
204
    kj::Exception exception = KJ_EXCEPTION(FAILED, "Network was destroyed.");
Kenton Varda's avatar
Kenton Varda committed
205
    for (auto& entry: connections) {
206 207 208
      entry.second->disconnect(kj::cp(exception));
    }
  }
209 210 211

  uint getSentCount() { return sent; }
  uint getReceivedCount() { return received; }
212 213 214

  typedef TestNetworkAdapterBase::Connection Connection;

Kenton Varda's avatar
Kenton Varda committed
215 216
  class ConnectionImpl final
      : public Connection, public kj::Refcounted, public kj::TaskSet::ErrorHandler {
217
  public:
Kenton Varda's avatar
Kenton Varda committed
218
    ConnectionImpl(TestNetworkAdapter& network, RpcDumper::Sender sender)
219
        : network(network), sender(sender), tasks(kj::heap<kj::TaskSet>(*this)) {}
220 221 222 223 224 225 226 227

    void attach(ConnectionImpl& other) {
      KJ_REQUIRE(partner == nullptr);
      KJ_REQUIRE(other.partner == nullptr);
      partner = other;
      other.partner = *this;
    }

228
    void disconnect(kj::Exception&& exception) {
Kenton Varda's avatar
Kenton Varda committed
229 230 231
      while (!fulfillers.empty()) {
        fulfillers.front()->reject(kj::cp(exception));
        fulfillers.pop();
232 233 234 235 236 237 238
      }

      networkException = kj::mv(exception);

      tasks = nullptr;
    }

Kenton Varda's avatar
Kenton Varda committed
239
    class IncomingRpcMessageImpl final: public IncomingRpcMessage, public kj::Refcounted {
240
    public:
241 242 243
      IncomingRpcMessageImpl(kj::Array<word> data)
          : data(kj::mv(data)),
            message(this->data) {}
244

245
      AnyPointer::Reader getBody() override {
246
        return message.getRoot<AnyPointer>();
247 248
      }

249 250 251 252
      size_t sizeInWords() override {
        return data.size();
      }

253 254
      kj::Array<word> data;
      FlatArrayMessageReader message;
255 256 257 258
    };

    class OutgoingRpcMessageImpl final: public OutgoingRpcMessage {
    public:
259
      OutgoingRpcMessageImpl(ConnectionImpl& connection, uint firstSegmentWordSize)
260
          : connection(connection),
261 262
            message(firstSegmentWordSize == 0 ? SUGGESTED_FIRST_SEGMENT_WORDS
                                              : firstSegmentWordSize) {}
263

264
      AnyPointer::Builder getBody() override {
265 266 267
        return message.getRoot<AnyPointer>();
      }

268
      void send() override {
269 270 271 272
        if (connection.networkException != nullptr) {
          return;
        }

273 274
        ++connection.network.sent;

Kenton Varda's avatar
Kenton Varda committed
275 276
        // Uncomment to get a debug dump.
//        kj::String msg = connection.network.network.dumper.dump(
277
//            message.getRoot<rpc::Message>(), connection.sender);
Kenton Varda's avatar
Kenton Varda committed
278 279
//        KJ_ DBG(msg);

280 281
        auto incomingMessage = kj::heap<IncomingRpcMessageImpl>(messageToFlatArray(message));

Kenton Varda's avatar
Kenton Varda committed
282
        auto connectionPtr = &connection;
283
        connection.tasks->add(kj::evalLater(kj::mvCapture(incomingMessage,
284
            [connectionPtr](kj::Own<IncomingRpcMessageImpl>&& message) {
Kenton Varda's avatar
Kenton Varda committed
285
          KJ_IF_MAYBE(p, connectionPtr->partner) {
Kenton Varda's avatar
Kenton Varda committed
286 287
            if (p->fulfillers.empty()) {
              p->messages.push(kj::mv(message));
Kenton Varda's avatar
Kenton Varda committed
288
            } else {
Kenton Varda's avatar
Kenton Varda committed
289 290 291 292
              ++p->network.received;
              p->fulfillers.front()->fulfill(
                  kj::Own<IncomingRpcMessage>(kj::mv(message)));
              p->fulfillers.pop();
Kenton Varda's avatar
Kenton Varda committed
293
            }
294
          }
Kenton Varda's avatar
Kenton Varda committed
295
        })));
296 297
      }

298 299 300 301
      size_t sizeInWords() override {
        return message.sizeInWords();
      }

302
    private:
303
      ConnectionImpl& connection;
304
      MallocMessageBuilder message;
305 306
    };

307 308 309 310 311
    test::TestSturdyRefHostId::Reader getPeerVatId() override {
      // Not actually implemented for the purpose of this test.
      return test::TestSturdyRefHostId::Reader();
    }

312
    kj::Own<OutgoingRpcMessage> newOutgoingMessage(uint firstSegmentWordSize) override {
313 314
      return kj::heap<OutgoingRpcMessageImpl>(*this, firstSegmentWordSize);
    }
315
    kj::Promise<kj::Maybe<kj::Own<IncomingRpcMessage>>> receiveIncomingMessage() override {
316 317 318 319
      KJ_IF_MAYBE(e, networkException) {
        return kj::cp(*e);
      }

Kenton Varda's avatar
Kenton Varda committed
320
      if (messages.empty()) {
Kenton Varda's avatar
Kenton Varda committed
321 322 323 324 325 326 327 328
        KJ_IF_MAYBE(f, fulfillOnEnd) {
          f->get()->fulfill();
          return kj::Maybe<kj::Own<IncomingRpcMessage>>(nullptr);
        } else {
          auto paf = kj::newPromiseAndFulfiller<kj::Maybe<kj::Own<IncomingRpcMessage>>>();
          fulfillers.push(kj::mv(paf.fulfiller));
          return kj::mv(paf.promise);
        }
329
      } else {
330
        ++network.received;
Kenton Varda's avatar
Kenton Varda committed
331 332
        auto result = kj::mv(messages.front());
        messages.pop();
333
        return kj::Maybe<kj::Own<IncomingRpcMessage>>(kj::mv(result));
334 335
      }
    }
Kenton Varda's avatar
Kenton Varda committed
336 337 338 339 340 341 342 343 344
    kj::Promise<void> shutdown() override {
      KJ_IF_MAYBE(p, partner) {
        auto paf = kj::newPromiseAndFulfiller<void>();
        p->fulfillOnEnd = kj::mv(paf.fulfiller);
        return kj::mv(paf.promise);
      } else {
        return kj::READY_NOW;
      }
    }
345

Kenton Varda's avatar
Kenton Varda committed
346 347 348 349
    void taskFailed(kj::Exception&& exception) override {
      ADD_FAILURE() << kj::str(exception).cStr();
    }

350
  private:
351
    TestNetworkAdapter& network;
352
    RpcDumper::Sender sender KJ_UNUSED_MEMBER;
353 354
    kj::Maybe<ConnectionImpl&> partner;

355 356
    kj::Maybe<kj::Exception> networkException;

Kenton Varda's avatar
Kenton Varda committed
357 358
    std::queue<kj::Own<kj::PromiseFulfiller<kj::Maybe<kj::Own<IncomingRpcMessage>>>>> fulfillers;
    std::queue<kj::Own<IncomingRpcMessage>> messages;
Kenton Varda's avatar
Kenton Varda committed
359
    kj::Maybe<kj::Own<kj::PromiseFulfiller<void>>> fulfillOnEnd;
Kenton Varda's avatar
Kenton Varda committed
360

361
    kj::Own<kj::TaskSet> tasks;
362 363
  };

364
  kj::Maybe<kj::Own<Connection>> connect(test::TestSturdyRefHostId::Reader hostId) override {
365
    TestNetworkAdapter& dst = KJ_REQUIRE_NONNULL(network.find(hostId.getHost()));
366

Kenton Varda's avatar
Kenton Varda committed
367 368
    auto iter = connections.find(&dst);
    if (iter == connections.end()) {
Kenton Varda's avatar
Kenton Varda committed
369 370
      auto local = kj::refcounted<ConnectionImpl>(*this, RpcDumper::CLIENT);
      auto remote = kj::refcounted<ConnectionImpl>(dst, RpcDumper::SERVER);
371 372
      local->attach(*remote);

Kenton Varda's avatar
Kenton Varda committed
373 374
      connections[&dst] = kj::addRef(*local);
      dst.connections[this] = kj::addRef(*remote);
375

Kenton Varda's avatar
Kenton Varda committed
376 377
      if (dst.fulfillerQueue.empty()) {
        dst.connectionQueue.push(kj::mv(remote));
378
      } else {
Kenton Varda's avatar
Kenton Varda committed
379 380
        dst.fulfillerQueue.front()->fulfill(kj::mv(remote));
        dst.fulfillerQueue.pop();
381 382
      }

383
      return kj::Own<Connection>(kj::mv(local));
384
    } else {
385
      return kj::Own<Connection>(kj::addRef(*iter->second));
386 387 388
    }
  }

389
  kj::Promise<kj::Own<Connection>> accept() override {
Kenton Varda's avatar
Kenton Varda committed
390
    if (connectionQueue.empty()) {
391
      auto paf = kj::newPromiseAndFulfiller<kj::Own<Connection>>();
Kenton Varda's avatar
Kenton Varda committed
392
      fulfillerQueue.push(kj::mv(paf.fulfiller));
393 394
      return kj::mv(paf.promise);
    } else {
Kenton Varda's avatar
Kenton Varda committed
395 396
      auto result = kj::mv(connectionQueue.front());
      connectionQueue.pop();
397 398 399 400 401
      return kj::mv(result);
    }
  }

private:
402 403 404
  TestNetwork& network;
  uint sent = 0;
  uint received = 0;
405

Kenton Varda's avatar
Kenton Varda committed
406 407 408
  std::map<const TestNetworkAdapter*, kj::Own<ConnectionImpl>> connections;
  std::queue<kj::Own<kj::PromiseFulfiller<kj::Own<Connection>>>> fulfillerQueue;
  std::queue<kj::Own<Connection>> connectionQueue;
409 410 411 412 413
};

TestNetwork::~TestNetwork() noexcept(false) {}

TestNetworkAdapter& TestNetwork::add(kj::StringPtr name) {
414
  return *(map[name] = kj::heap<TestNetworkAdapter>(*this));
415 416 417 418
}

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

419
class TestRestorer final: public SturdyRefRestorer<test::TestSturdyRefObjectId> {
420 421
public:
  int callCount = 0;
422
  int handleCount = 0;
423

424 425 426
  Capability::Client restore(test::TestSturdyRefObjectId::Reader objectId) override {
    switch (objectId.getTag()) {
      case test::TestSturdyRefObjectId::Tag::TEST_INTERFACE:
427
        return kj::heap<TestInterfaceImpl>(callCount);
428 429 430
      case test::TestSturdyRefObjectId::Tag::TEST_EXTENDS:
        return Capability::Client(newBrokenCap("No TestExtends implemented."));
      case test::TestSturdyRefObjectId::Tag::TEST_PIPELINE:
431
        return kj::heap<TestPipelineImpl>(callCount);
432 433 434 435
      case test::TestSturdyRefObjectId::Tag::TEST_TAIL_CALLEE:
        return kj::heap<TestTailCalleeImpl>(callCount);
      case test::TestSturdyRefObjectId::Tag::TEST_TAIL_CALLER:
        return kj::heap<TestTailCallerImpl>(callCount);
436
      case test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF:
437
        return kj::heap<TestMoreStuffImpl>(callCount, handleCount);
438 439 440 441 442
    }
    KJ_UNREACHABLE;
  }
};

Kenton Varda's avatar
Kenton Varda committed
443
struct TestContext {
444
  kj::EventLoop loop;
445
  kj::WaitScope waitScope;
446 447
  TestNetwork network;
  TestRestorer restorer;
448 449
  TestNetworkAdapter& clientNetwork;
  TestNetworkAdapter& serverNetwork;
450 451
  RpcSystem<test::TestSturdyRefHostId> rpcClient;
  RpcSystem<test::TestSturdyRefHostId> rpcServer;
452

Kenton Varda's avatar
Kenton Varda committed
453
  TestContext()
454 455
      : waitScope(loop),
        clientNetwork(network.add("client")),
Kenton Varda's avatar
Kenton Varda committed
456
        serverNetwork(network.add("server")),
457 458
        rpcClient(makeRpcClient(clientNetwork)),
        rpcServer(makeRpcServer(serverNetwork, restorer)) {}
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  TestContext(Capability::Client bootstrap,
              RealmGateway<test::TestSturdyRef, Text>::Client gateway)
      : waitScope(loop),
        clientNetwork(network.add("client")),
        serverNetwork(network.add("server")),
        rpcClient(makeRpcClient(clientNetwork, gateway)),
        rpcServer(makeRpcServer(serverNetwork, bootstrap)) {}
  TestContext(Capability::Client bootstrap,
              RealmGateway<test::TestSturdyRef, Text>::Client gateway,
              bool)
      : waitScope(loop),
        clientNetwork(network.add("client")),
        serverNetwork(network.add("server")),
        rpcClient(makeRpcClient(clientNetwork)),
        rpcServer(makeRpcServer(serverNetwork, bootstrap, gateway)) {}
Kenton Varda's avatar
Kenton Varda committed
474

475
  Capability::Client connect(test::TestSturdyRefObjectId::Tag tag) {
476
    MallocMessageBuilder refMessage(128);
477 478
    auto ref = refMessage.initRoot<test::TestSturdyRef>();
    auto hostId = ref.initHostId();
479 480
    hostId.setHost("server");
    ref.getObjectId().initAs<test::TestSturdyRefObjectId>().setTag(tag);
481

482
    return rpcClient.restore(hostId, ref.getObjectId());
483 484 485
  }
};

Kenton Varda's avatar
Kenton Varda committed
486 487 488 489
TEST(Rpc, Basic) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_INTERFACE)
490
      .castAs<test::TestInterface>();
491 492 493 494 495 496

  auto request1 = client.fooRequest();
  request1.setI(123);
  request1.setJ(true);
  auto promise1 = request1.send();

497 498 499
  // We used to call bar() after baz(), hence the numbering, but this masked the case where the
  // RPC system actually disconnected on bar() (thus returning an exception, which we decided
  // was expected).
500 501
  bool barFailed = false;
  auto request3 = client.barRequest();
502
  auto promise3 = request3.send().then(
503 504 505 506 507 508
      [](Response<test::TestInterface::BarResults>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
      }, [&](kj::Exception&& e) {
        barFailed = true;
      });

509 510 511 512
  auto request2 = client.bazRequest();
  initTestMessage(request2.initS());
  auto promise2 = request2.send();

Kenton Varda's avatar
Kenton Varda committed
513
  EXPECT_EQ(0, context.restorer.callCount);
514

515
  auto response1 = promise1.wait(context.waitScope);
516 517 518

  EXPECT_EQ("foo", response1.getX());

519
  auto response2 = promise2.wait(context.waitScope);
520

521
  promise3.wait(context.waitScope);
522

Kenton Varda's avatar
Kenton Varda committed
523
  EXPECT_EQ(2, context.restorer.callCount);
524 525 526
  EXPECT_TRUE(barFailed);
}

Kenton Varda's avatar
Kenton Varda committed
527 528 529 530
TEST(Rpc, Pipelining) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_PIPELINE)
531
      .castAs<test::TestPipeline>();
532 533 534 535 536

  int chainedCallCount = 0;

  auto request = client.getCapRequest();
  request.setN(234);
537
  request.setInCap(kj::heap<TestInterfaceImpl>(chainedCallCount));
538 539 540 541 542 543 544 545 546 547 548 549

  auto promise = request.send();

  auto pipelineRequest = promise.getOutBox().getCap().fooRequest();
  pipelineRequest.setI(321);
  auto pipelinePromise = pipelineRequest.send();

  auto pipelineRequest2 = promise.getOutBox().getCap().castAs<test::TestExtends>().graultRequest();
  auto pipelinePromise2 = pipelineRequest2.send();

  promise = nullptr;  // Just to be annoying, drop the original promise.

Kenton Varda's avatar
Kenton Varda committed
550
  EXPECT_EQ(0, context.restorer.callCount);
551 552
  EXPECT_EQ(0, chainedCallCount);

553
  auto response = pipelinePromise.wait(context.waitScope);
554 555
  EXPECT_EQ("bar", response.getX());

556
  auto response2 = pipelinePromise2.wait(context.waitScope);
557 558
  checkTestMessage(response2);

Kenton Varda's avatar
Kenton Varda committed
559
  EXPECT_EQ(3, context.restorer.callCount);
560 561 562
  EXPECT_EQ(1, chainedCallCount);
}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
TEST(Rpc, Release) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto handle1 = client.getHandleRequest().send().wait(context.waitScope).getHandle();
  auto promise = client.getHandleRequest().send();
  auto handle2 = promise.wait(context.waitScope).getHandle();

  EXPECT_EQ(2, context.restorer.handleCount);

  handle1 = nullptr;

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(1, context.restorer.handleCount);

  handle2 = nullptr;

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(1, context.restorer.handleCount);

  promise = nullptr;

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(0, context.restorer.handleCount);
}

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
TEST(Rpc, ReleaseOnCancel) {
  // At one time, there was a bug where if a Return contained capabilities, but the client had
  // canceled the request and already send a Finish (which presumably didn't reach the server before
  // the Return), then we'd leak those caps. Test for that.

  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();
  client.whenResolved().wait(context.waitScope);

  {
    auto promise = client.getHandleRequest().send();

    // If the server receives cancellation too early, it won't even return a capability in the
    // results, it will just return "canceled". We want to emulate the case where the return message
    // and the cancel (finish) message cross paths. It turns out that exactly two evalLater()s get
    // us there.
    //
    // TODO(cleanup): This is fragile, but I'm not sure how else to write it without a ton
    //   of scaffolding.
    kj::evalLater([]() {}).wait(context.waitScope);
    kj::evalLater([]() {}).wait(context.waitScope);
  }

  for (uint i = 0; i < 16; i++) kj::evalLater([]() {}).wait(context.waitScope);
  EXPECT_EQ(0, context.restorer.handleCount);
}

Kenton Varda's avatar
Kenton Varda committed
620 621 622 623
TEST(Rpc, TailCall) {
  TestContext context;

  auto caller = context.connect(test::TestSturdyRefObjectId::Tag::TEST_TAIL_CALLER)
624 625 626 627
      .castAs<test::TestTailCaller>();

  int calleeCallCount = 0;

628
  test::TestTailCallee::Client callee(kj::heap<TestTailCalleeImpl>(calleeCallCount));
629 630 631 632 633 634 635 636 637

  auto request = caller.fooRequest();
  request.setI(456);
  request.setCallee(callee);

  auto promise = request.send();

  auto dependentCall0 = promise.getC().getCallSequenceRequest().send();

638
  auto response = promise.wait(context.waitScope);
639
  EXPECT_EQ(456, response.getI());
640
  EXPECT_EQ("from TestTailCaller", response.getT());
641 642 643 644 645

  auto dependentCall1 = promise.getC().getCallSequenceRequest().send();

  auto dependentCall2 = response.getC().getCallSequenceRequest().send();

646 647 648
  EXPECT_EQ(0, dependentCall0.wait(context.waitScope).getN());
  EXPECT_EQ(1, dependentCall1.wait(context.waitScope).getN());
  EXPECT_EQ(2, dependentCall2.wait(context.waitScope).getN());
649 650

  EXPECT_EQ(1, calleeCallCount);
Kenton Varda's avatar
Kenton Varda committed
651
  EXPECT_EQ(1, context.restorer.callCount);
652 653
}

654 655
TEST(Rpc, Cancelation) {
  // Tests allowCancellation().
656

Kenton Varda's avatar
Kenton Varda committed
657 658
  TestContext context;

659 660
  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
661
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);
662

Kenton Varda's avatar
Kenton Varda committed
663
  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
664 665 666 667 668 669
      .castAs<test::TestMoreStuff>();

  kj::Promise<void> promise = nullptr;

  bool returned = false;
  {
670
    auto request = client.expectCancelRequest();
671 672
    request.setCap(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));
    promise = request.send().then(
673
        [&](Response<test::TestMoreStuff::ExpectCancelResults>&& response) {
674
      returned = true;
675
    }).eagerlyEvaluate(nullptr);
676
  }
677 678 679 680 681 682
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
683 684 685 686 687 688

  // We can detect that the method was canceled because it will drop the cap.
  EXPECT_FALSE(destroyed);
  EXPECT_FALSE(returned);

  promise = nullptr;  // request cancellation
689
  destructionPromise.wait(context.waitScope);
690 691 692 693 694

  EXPECT_TRUE(destroyed);
  EXPECT_FALSE(returned);
}

Kenton Varda's avatar
Kenton Varda committed
695 696 697 698
TEST(Rpc, PromiseResolve) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
699 700 701 702 703 704 705 706 707 708
      .castAs<test::TestMoreStuff>();

  int chainedCallCount = 0;

  auto request = client.callFooRequest();
  auto request2 = client.callFooWhenResolvedRequest();

  auto paf = kj::newPromiseAndFulfiller<test::TestInterface::Client>();

  {
709 710 711
    auto fork = paf.promise.fork();
    request.setCap(fork.addBranch());
    request2.setCap(fork.addBranch());
712 713 714 715 716
  }

  auto promise = request.send();
  auto promise2 = request2.send();

717 718
  // Make sure getCap() has been called on the server side by sending another call and waiting
  // for it.
719
  EXPECT_EQ(2, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
Kenton Varda's avatar
Kenton Varda committed
720
  EXPECT_EQ(3, context.restorer.callCount);
721 722

  // OK, now fulfill the local promise.
723
  paf.fulfiller->fulfill(kj::heap<TestInterfaceImpl>(chainedCallCount));
724 725

  // We should now be able to wait for getCap() to finish.
726 727
  EXPECT_EQ("bar", promise.wait(context.waitScope).getS());
  EXPECT_EQ("bar", promise2.wait(context.waitScope).getS());
728

Kenton Varda's avatar
Kenton Varda committed
729
  EXPECT_EQ(3, context.restorer.callCount);
730 731 732
  EXPECT_EQ(2, chainedCallCount);
}

Kenton Varda's avatar
Kenton Varda committed
733 734 735
TEST(Rpc, RetainAndRelease) {
  TestContext context;

736 737
  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
738
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);
739 740

  {
Kenton Varda's avatar
Kenton Varda committed
741
    auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
742 743 744 745
        .castAs<test::TestMoreStuff>();

    {
      auto request = client.holdRequest();
746
      request.setCap(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));
747
      request.send().wait(context.waitScope);
748 749 750
    }

    // Do some other call to add a round trip.
751
    EXPECT_EQ(1, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
752 753 754 755 756

    // Shouldn't be destroyed because it's being held by the server.
    EXPECT_FALSE(destroyed);

    // We can ask it to call the held capability.
757
    EXPECT_EQ("bar", client.callHeldRequest().send().wait(context.waitScope).getS());
758 759 760

    {
      // We can get the cap back from it.
761
      auto capCopy = client.getHeldRequest().send().wait(context.waitScope).getCap();
762 763 764

      {
        // And call it, without any network communications.
Kenton Varda's avatar
Kenton Varda committed
765
        uint oldSentCount = context.clientNetwork.getSentCount();
766 767 768
        auto request = capCopy.fooRequest();
        request.setI(123);
        request.setJ(true);
769
        EXPECT_EQ("foo", request.send().wait(context.waitScope).getX());
Kenton Varda's avatar
Kenton Varda committed
770
        EXPECT_EQ(oldSentCount, context.clientNetwork.getSentCount());
771 772 773 774 775 776
      }

      {
        // We can send another copy of the same cap to another method, and it works.
        auto request = client.callFooRequest();
        request.setCap(capCopy);
777
        EXPECT_EQ("bar", request.send().wait(context.waitScope).getS());
778 779 780 781
      }
    }

    // Give some time to settle.
782 783 784
    EXPECT_EQ(5, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
    EXPECT_EQ(6, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
    EXPECT_EQ(7, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
785 786 787 788 789 790 791

    // Can't be destroyed, we haven't released it.
    EXPECT_FALSE(destroyed);
  }

  // We released our client, which should cause the server to be released, which in turn will
  // release the cap pointing back to us.
792
  destructionPromise.wait(context.waitScope);
793 794 795
  EXPECT_TRUE(destroyed);
}

Kenton Varda's avatar
Kenton Varda committed
796 797 798 799
TEST(Rpc, Cancel) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
800 801 802 803
      .castAs<test::TestMoreStuff>();

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
804
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);
805 806 807

  {
    auto request = client.neverReturnRequest();
808
    request.setCap(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));
809 810 811 812 813

    {
      auto responsePromise = request.send();

      // Allow some time to settle.
814 815
      EXPECT_EQ(1, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
      EXPECT_EQ(2, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
816 817 818 819 820 821 822

      // The cap shouldn't have been destroyed yet because the call never returned.
      EXPECT_FALSE(destroyed);
    }
  }

  // Now the cap should be released.
823
  destructionPromise.wait(context.waitScope);
824 825 826
  EXPECT_TRUE(destroyed);
}

Kenton Varda's avatar
Kenton Varda committed
827 828 829 830
TEST(Rpc, SendTwice) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
831 832 833 834
      .castAs<test::TestMoreStuff>();

  auto paf = kj::newPromiseAndFulfiller<void>();
  bool destroyed = false;
835
  auto destructionPromise = paf.promise.then([&]() { destroyed = true; }).eagerlyEvaluate(nullptr);
836

837
  auto cap = test::TestInterface::Client(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller)));
838 839 840 841 842

  {
    auto request = client.callFooRequest();
    request.setCap(cap);

843
    EXPECT_EQ("bar", request.send().wait(context.waitScope).getS());
844 845 846
  }

  // Allow some time for the server to release `cap`.
847
  EXPECT_EQ(1, client.getCallSequenceRequest().send().wait(context.waitScope).getN());
848 849 850 851 852 853 854 855 856 857 858

  {
    // More requests with the same cap.
    auto request = client.callFooRequest();
    auto request2 = client.callFooRequest();
    request.setCap(cap);
    request2.setCap(kj::mv(cap));

    auto promise = request.send();
    auto promise2 = request2.send();

859 860
    EXPECT_EQ("bar", promise.wait(context.waitScope).getS());
    EXPECT_EQ("bar", promise2.wait(context.waitScope).getS());
861 862 863
  }

  // Now the cap should be released.
864
  destructionPromise.wait(context.waitScope);
865 866 867
  EXPECT_TRUE(destroyed);
}

Kenton Varda's avatar
Kenton Varda committed
868
RemotePromise<test::TestCallOrder::GetCallSequenceResults> getCallSequence(
869
    test::TestCallOrder::Client& client, uint expected) {
Kenton Varda's avatar
Kenton Varda committed
870 871 872 873 874
  auto req = client.getCallSequenceRequest();
  req.setExpected(expected);
  return req.send();
}

Kenton Varda's avatar
Kenton Varda committed
875 876 877 878
TEST(Rpc, Embargo) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
Kenton Varda's avatar
Kenton Varda committed
879 880
      .castAs<test::TestMoreStuff>();

881
  auto cap = test::TestCallOrder::Client(kj::heap<TestCallOrderImpl>());
Kenton Varda's avatar
Kenton Varda committed
882 883 884 885 886 887 888 889 890 891 892 893

  auto earlyCall = client.getCallSequenceRequest().send();

  auto echoRequest = client.echoRequest();
  echoRequest.setCap(cap);
  auto echo = echoRequest.send();

  auto pipeline = echo.getCap();

  auto call0 = getCallSequence(pipeline, 0);
  auto call1 = getCallSequence(pipeline, 1);

894
  earlyCall.wait(context.waitScope);
Kenton Varda's avatar
Kenton Varda committed
895 896 897

  auto call2 = getCallSequence(pipeline, 2);

898
  auto resolved = echo.wait(context.waitScope).getCap();
Kenton Varda's avatar
Kenton Varda committed
899 900 901 902 903

  auto call3 = getCallSequence(pipeline, 3);
  auto call4 = getCallSequence(pipeline, 4);
  auto call5 = getCallSequence(pipeline, 5);

904 905 906 907 908 909
  EXPECT_EQ(0, call0.wait(context.waitScope).getN());
  EXPECT_EQ(1, call1.wait(context.waitScope).getN());
  EXPECT_EQ(2, call2.wait(context.waitScope).getN());
  EXPECT_EQ(3, call3.wait(context.waitScope).getN());
  EXPECT_EQ(4, call4.wait(context.waitScope).getN());
  EXPECT_EQ(5, call5.wait(context.waitScope).getN());
Kenton Varda's avatar
Kenton Varda committed
910 911
}

912 913 914 915 916 917 918 919 920 921 922 923
template <typename T>
void expectPromiseThrows(kj::Promise<T>&& promise, kj::WaitScope& waitScope) {
  EXPECT_TRUE(promise.then([](T&&) { return false; }, [](kj::Exception&&) { return true; })
      .wait(waitScope));
}

template <>
void expectPromiseThrows(kj::Promise<void>&& promise, kj::WaitScope& waitScope) {
  EXPECT_TRUE(promise.then([]() { return false; }, [](kj::Exception&&) { return true; })
      .wait(waitScope));
}

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
TEST(Rpc, EmbargoError) {
  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto paf = kj::newPromiseAndFulfiller<test::TestCallOrder::Client>();

  auto cap = test::TestCallOrder::Client(kj::mv(paf.promise));

  auto earlyCall = client.getCallSequenceRequest().send();

  auto echoRequest = client.echoRequest();
  echoRequest.setCap(cap);
  auto echo = echoRequest.send();

  auto pipeline = echo.getCap();

  auto call0 = getCallSequence(pipeline, 0);
  auto call1 = getCallSequence(pipeline, 1);

  earlyCall.wait(context.waitScope);

  auto call2 = getCallSequence(pipeline, 2);

  auto resolved = echo.wait(context.waitScope).getCap();

  auto call3 = getCallSequence(pipeline, 3);
  auto call4 = getCallSequence(pipeline, 4);
  auto call5 = getCallSequence(pipeline, 5);

955
  paf.fulfiller->rejectIfThrows([]() { KJ_FAIL_ASSERT("foo") { break; } });
956

957 958 959 960 961 962
  expectPromiseThrows(kj::mv(call0), context.waitScope);
  expectPromiseThrows(kj::mv(call1), context.waitScope);
  expectPromiseThrows(kj::mv(call2), context.waitScope);
  expectPromiseThrows(kj::mv(call3), context.waitScope);
  expectPromiseThrows(kj::mv(call4), context.waitScope);
  expectPromiseThrows(kj::mv(call5), context.waitScope);
963 964 965 966 967

  // Verify that we're still connected (there were no protocol errors).
  getCallSequence(client, 1).wait(context.waitScope);
}

968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
TEST(Rpc, EmbargoNull) {
  // Set up a situation where we pipeline on a capability that ends up coming back null. This
  // should NOT cause a Disembargo to be sent, but due to a bug in earlier versions of Cap'n Proto,
  // a Disembargo was indeed sent to the null capability, which caused the server to disconnect
  // due to protocol error.

  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();

  auto promise = client.getNullRequest().send();

  auto cap = promise.getNullCap();

  auto call0 = cap.getCallSequenceRequest().send();

  promise.wait(context.waitScope);

  auto call1 = cap.getCallSequenceRequest().send();

  expectPromiseThrows(kj::mv(call0), context.waitScope);
  expectPromiseThrows(kj::mv(call1), context.waitScope);

  // Verify that we're still connected (there were no protocol errors).
  getCallSequence(client, 0).wait(context.waitScope);
}

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
TEST(Rpc, CallBrokenPromise) {
  // Tell the server to call back to a promise client, then resolve the promise to an error.

  TestContext context;

  auto client = context.connect(test::TestSturdyRefObjectId::Tag::TEST_MORE_STUFF)
      .castAs<test::TestMoreStuff>();
  auto paf = kj::newPromiseAndFulfiller<test::TestInterface::Client>();

  {
    auto req = client.holdRequest();
    req.setCap(kj::mv(paf.promise));
    req.send().wait(context.waitScope);
  }

  bool returned = false;
  auto req = client.callHeldRequest().send()
      .then([&](capnp::Response<test::TestMoreStuff::CallHeldResults>&&) {
    returned = true;
  }, [&](kj::Exception&& e) {
    returned = true;
    kj::throwRecoverableException(kj::mv(e));
  }).eagerlyEvaluate(nullptr);

  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);

  EXPECT_FALSE(returned);

1031
  paf.fulfiller->rejectIfThrows([]() { KJ_FAIL_ASSERT("foo") { break; } });
1032

1033
  expectPromiseThrows(kj::mv(req), context.waitScope);
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
  EXPECT_TRUE(returned);

  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);
  kj::evalLater([]() {}).wait(context.waitScope);

  // Verify that we're still connected (there were no protocol errors).
  getCallSequence(client, 1).wait(context.waitScope);
}

Kenton Varda's avatar
Kenton Varda committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
TEST(Rpc, Abort) {
  // Verify that aborts are received.

  TestContext context;

  MallocMessageBuilder refMessage(128);
  auto hostId = refMessage.initRoot<test::TestSturdyRefHostId>();
  hostId.setHost("server");

  auto conn = KJ_ASSERT_NONNULL(context.clientNetwork.connect(hostId));

  {
    // Send an invalid message (Return to non-existent question).
    auto msg = conn->newOutgoingMessage(128);
    auto body = msg->getBody().initAs<rpc::Message>().initReturn();
    body.setAnswerId(1234);
    body.setCanceled();
    msg->send();
  }

  auto reply = KJ_ASSERT_NONNULL(conn->receiveIncomingMessage().wait(context.waitScope));
  EXPECT_EQ(rpc::Message::ABORT, reply->getBody().getAs<rpc::Message>().which());

  EXPECT_TRUE(conn->receiveIncomingMessage().wait(context.waitScope) == nullptr);
}

1075 1076 1077 1078
// =======================================================================================

typedef RealmGateway<test::TestSturdyRef, Text> TestRealmGateway;

1079
class TestGateway final: public TestRealmGateway::Server {
1080 1081 1082 1083 1084
public:
  kj::Promise<void> import(ImportContext context) override {
    auto cap = context.getParams().getCap();
    context.releaseParams();
    return cap.saveRequest().send()
1085
        .then([KJ_CPCAP(context)](Response<Persistent<Text>::SaveResults> response) mutable {
1086 1087 1088 1089 1090 1091 1092 1093 1094
      context.getResults().initSturdyRef().getObjectId().setAs<Text>(
          kj::str("imported-", response.getSturdyRef()));
    });
  }

  kj::Promise<void> export_(ExportContext context) override {
    auto cap = context.getParams().getCap();
    context.releaseParams();
    return cap.saveRequest().send()
1095 1096
        .then([KJ_CPCAP(context)]
            (Response<Persistent<test::TestSturdyRef>::SaveResults> response) mutable {
1097 1098 1099 1100 1101 1102
      context.getResults().setSturdyRef(kj::str("exported-",
          response.getSturdyRef().getObjectId().getAs<Text>()));
    });
  }
};

1103
class TestPersistent final: public Persistent<test::TestSturdyRef>::Server {
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
public:
  TestPersistent(kj::StringPtr name): name(name) {}

  kj::Promise<void> save(SaveContext context) override {
    context.initResults().initSturdyRef().getObjectId().setAs<Text>(name);
    return kj::READY_NOW;
  }

private:
  kj::StringPtr name;
};

1116
class TestPersistentText final: public Persistent<Text>::Server {
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
public:
  TestPersistentText(kj::StringPtr name): name(name) {}

  kj::Promise<void> save(SaveContext context) override {
    context.initResults().setSturdyRef(name);
    return kj::READY_NOW;
  }

private:
  kj::StringPtr name;
};

TEST(Rpc, RealmGatewayImport) {
  TestRealmGateway::Client gateway = kj::heap<TestGateway>();
  Persistent<Text>::Client bootstrap = kj::heap<TestPersistentText>("foo");

  MallocMessageBuilder hostIdBuilder;
  auto hostId = hostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  hostId.setHost("server");

  TestContext context(bootstrap, gateway);
  auto client = context.rpcClient.bootstrap(hostId).castAs<Persistent<test::TestSturdyRef>>();

  auto response = client.saveRequest().send().wait(context.waitScope);

  EXPECT_EQ("imported-foo", response.getSturdyRef().getObjectId().getAs<Text>());
}

TEST(Rpc, RealmGatewayExport) {
  TestRealmGateway::Client gateway = kj::heap<TestGateway>();
  Persistent<test::TestSturdyRef>::Client bootstrap = kj::heap<TestPersistent>("foo");

  MallocMessageBuilder hostIdBuilder;
  auto hostId = hostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  hostId.setHost("server");

  TestContext context(bootstrap, gateway, true);
  auto client = context.rpcClient.bootstrap(hostId).castAs<Persistent<Text>>();

  auto response = client.saveRequest().send().wait(context.waitScope);

  EXPECT_EQ("exported-foo", response.getSturdyRef());
}

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
TEST(Rpc, RealmGatewayImportExport) {
  // Test that a save request which leaves the realm, bounces through a promise capability, and
  // then comes back into the realm, does not actually get translated both ways.

  TestRealmGateway::Client gateway = kj::heap<TestGateway>();
  Persistent<test::TestSturdyRef>::Client bootstrap = kj::heap<TestPersistent>("foo");

  MallocMessageBuilder serverHostIdBuilder;
  auto serverHostId = serverHostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  serverHostId.setHost("server");

  MallocMessageBuilder clientHostIdBuilder;
  auto clientHostId = clientHostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  clientHostId.setHost("client");

  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);
  TestNetwork network;
  TestNetworkAdapter& clientNetwork = network.add("client");
  TestNetworkAdapter& serverNetwork = network.add("server");
  RpcSystem<test::TestSturdyRefHostId> rpcClient =
      makeRpcServer(clientNetwork, bootstrap, gateway);
  auto paf = kj::newPromiseAndFulfiller<Capability::Client>();
  RpcSystem<test::TestSturdyRefHostId> rpcServer =
      makeRpcServer(serverNetwork, kj::mv(paf.promise));

  auto client = rpcClient.bootstrap(serverHostId).castAs<Persistent<test::TestSturdyRef>>();

  bool responseReady = false;
  auto responsePromise = client.saveRequest().send()
      .then([&](Response<Persistent<test::TestSturdyRef>::SaveResults>&& response) {
    responseReady = true;
    return kj::mv(response);
  }).eagerlyEvaluate(nullptr);

  // Crank the event loop to give the message time to reach the server and block on the promise
  // resolution.
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);

  EXPECT_FALSE(responseReady);

  paf.fulfiller->fulfill(rpcServer.bootstrap(clientHostId));

  auto response = responsePromise.wait(waitScope);

  // Should have the original value. If it went through export and re-import, though, then this
  // will be "imported-exported-foo", which is wrong.
  EXPECT_EQ("foo", response.getSturdyRef().getObjectId().getAs<Text>());
}

TEST(Rpc, RealmGatewayImportExport) {
  // Test that a save request which enters the realm, bounces through a promise capability, and
  // then goes back out of the realm, does not actually get translated both ways.

  TestRealmGateway::Client gateway = kj::heap<TestGateway>();
  Persistent<Text>::Client bootstrap = kj::heap<TestPersistentText>("foo");

  MallocMessageBuilder serverHostIdBuilder;
  auto serverHostId = serverHostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  serverHostId.setHost("server");

  MallocMessageBuilder clientHostIdBuilder;
  auto clientHostId = clientHostIdBuilder.getRoot<test::TestSturdyRefHostId>();
  clientHostId.setHost("client");

  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);
  TestNetwork network;
  TestNetworkAdapter& clientNetwork = network.add("client");
  TestNetworkAdapter& serverNetwork = network.add("server");
  RpcSystem<test::TestSturdyRefHostId> rpcClient =
      makeRpcServer(clientNetwork, bootstrap);
  auto paf = kj::newPromiseAndFulfiller<Capability::Client>();
  RpcSystem<test::TestSturdyRefHostId> rpcServer =
      makeRpcServer(serverNetwork, kj::mv(paf.promise), gateway);

  auto client = rpcClient.bootstrap(serverHostId).castAs<Persistent<Text>>();

  bool responseReady = false;
  auto responsePromise = client.saveRequest().send()
      .then([&](Response<Persistent<Text>::SaveResults>&& response) {
    responseReady = true;
    return kj::mv(response);
  }).eagerlyEvaluate(nullptr);

  // Crank the event loop to give the message time to reach the server and block on the promise
  // resolution.
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);

  EXPECT_FALSE(responseReady);

  paf.fulfiller->fulfill(rpcServer.bootstrap(clientHostId));

  auto response = responsePromise.wait(waitScope);

  // Should have the original value. If it went through import and re-export, though, then this
  // will be "exported-imported-foo", which is wrong.
  EXPECT_EQ("foo", response.getSturdyRef());
}

1267 1268 1269
}  // namespace
}  // namespace _ (private)
}  // namespace capnp