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

22 23
#include "schema.capnp.h"

24
#ifdef CAPNP_CAPABILITY_H_INCLUDED
25 26 27
#error "schema.capnp should not depend on capability.h, because it contains no interfaces."
#endif

Kenton Varda's avatar
Kenton Varda committed
28
#include <capnp/test.capnp.h>
29

30
#ifndef CAPNP_CAPABILITY_H_INCLUDED
31 32 33
#error "test.capnp did not include capability.h."
#endif

34 35 36
#include "capability.h"
#include "test-util.h"
#include <kj/debug.h>
37
#include <kj/compat/gtest.h>
38 39 40 41 42 43

namespace capnp {
namespace _ {
namespace {

TEST(Capability, Basic) {
44
  kj::EventLoop loop;
45
  kj::WaitScope waitScope(loop);
46

47
  int callCount = 0;
48
  test::TestInterface::Client client(kj::heap<TestInterfaceImpl>(callCount));
49 50 51 52 53 54 55 56 57 58

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

  auto request2 = client.bazRequest();
  initTestMessage(request2.initS());
  auto promise2 = request2.send();

59
  bool barFailed = false;
60
  auto request3 = client.barRequest();
61
  auto promise3 = request3.send().then(
62 63
      [](Response<test::TestInterface::BarResults>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
64
      }, [&](kj::Exception&& e) {
65
        EXPECT_EQ(kj::Exception::Type::UNIMPLEMENTED, e.getType());
66
        barFailed = true;
67 68 69 70
      });

  EXPECT_EQ(0, callCount);

71
  auto response1 = promise1.wait(waitScope);
72 73 74

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

75
  auto response2 = promise2.wait(waitScope);
76

77
  promise3.wait(waitScope);
78 79

  EXPECT_EQ(2, callCount);
80
  EXPECT_TRUE(barFailed);
81 82 83
}

TEST(Capability, Inheritance) {
84
  kj::EventLoop loop;
85
  kj::WaitScope waitScope(loop);
86

87
  int callCount = 0;
88
  test::TestExtends::Client client1(kj::heap<TestExtendsImpl>(callCount));
89 90
  test::TestInterface::Client client2 = client1;
  auto client = client2.castAs<test::TestExtends>();
91 92 93 94 95 96 97 98 99 100

  auto request1 = client.fooRequest();
  request1.setI(321);
  auto promise1 = request1.send();

  auto request2 = client.graultRequest();
  auto promise2 = request2.send();

  EXPECT_EQ(0, callCount);

101
  auto response2 = promise2.wait(waitScope);
102 103 104

  checkTestMessage(response2);

105
  auto response1 = promise1.wait(waitScope);
106 107 108 109 110 111

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

  EXPECT_EQ(2, callCount);
}

112
TEST(Capability, Pipelining) {
113
  kj::EventLoop loop;
114
  kj::WaitScope waitScope(loop);
115 116 117

  int callCount = 0;
  int chainedCallCount = 0;
118
  test::TestPipeline::Client client(kj::heap<TestPipelineImpl>(callCount));
119 120

  auto request = client.getCapRequest();
121
  request.setN(234);
122
  request.setInCap(test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
123 124 125

  auto promise = request.send();

126
  auto pipelineRequest = promise.getOutBox().getCap().fooRequest();
127 128 129
  pipelineRequest.setI(321);
  auto pipelinePromise = pipelineRequest.send();

130 131 132 133 134
  auto pipelineRequest2 = promise.getOutBox().getCap().castAs<test::TestExtends>().graultRequest();
  auto pipelinePromise2 = pipelineRequest2.send();

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

135 136 137
  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

138
  auto response = pipelinePromise.wait(waitScope);
139 140
  EXPECT_EQ("bar", response.getX());

141
  auto response2 = pipelinePromise2.wait(waitScope);
142 143 144 145 146 147
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
  EXPECT_EQ(1, chainedCallCount);
}

148
TEST(Capability, TailCall) {
149
  kj::EventLoop loop;
150
  kj::WaitScope waitScope(loop);
151 152 153 154

  int calleeCallCount = 0;
  int callerCallCount = 0;

155 156
  test::TestTailCallee::Client callee(kj::heap<TestTailCalleeImpl>(calleeCallCount));
  test::TestTailCaller::Client caller(kj::heap<TestTailCallerImpl>(callerCallCount));
157 158 159 160 161 162 163 164 165

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

  auto promise = request.send();

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

166
  auto response = promise.wait(waitScope);
167 168 169 170 171 172 173
  EXPECT_EQ(456, response.getI());
  EXPECT_EQ(456, response.getI());

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

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

174 175 176
  EXPECT_EQ(0, dependentCall0.wait(waitScope).getN());
  EXPECT_EQ(1, dependentCall1.wait(waitScope).getN());
  EXPECT_EQ(2, dependentCall2.wait(waitScope).getN());
177 178 179 180 181

  EXPECT_EQ(1, calleeCallCount);
  EXPECT_EQ(1, callerCallCount);
}

182
TEST(Capability, AsyncCancelation) {
183
  // Tests allowCancellation().
184

185
  kj::EventLoop loop;
186
  kj::WaitScope waitScope(loop);
187 188 189

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

  int callCount = 0;
193
  int handleCount = 0;
194

195
  test::TestMoreStuff::Client client(kj::heap<TestMoreStuffImpl>(callCount, handleCount));
196 197 198 199 200

  kj::Promise<void> promise = nullptr;

  bool returned = false;
  {
201
    auto request = client.expectCancelRequest();
202
    request.setCap(test::TestInterface::Client(kj::heap<TestCapDestructor>(kj::mv(paf.fulfiller))));
203
    promise = request.send().then(
204
        [&](Response<test::TestMoreStuff::ExpectCancelResults>&& response) {
205
      returned = true;
206
    }).eagerlyEvaluate(nullptr);
207
  }
208 209
  kj::evalLater([]() {}).wait(waitScope);
  kj::evalLater([]() {}).wait(waitScope);
210 211 212 213 214 215

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

  promise = nullptr;  // request cancellation
216
  destructionPromise.wait(waitScope);
217 218 219 220 221

  EXPECT_TRUE(destroyed);
  EXPECT_FALSE(returned);
}

222 223 224
// =======================================================================================

TEST(Capability, DynamicClient) {
225
  kj::EventLoop loop;
226
  kj::WaitScope waitScope(loop);
227 228 229

  int callCount = 0;
  DynamicCapability::Client client =
230
      test::TestInterface::Client(kj::heap<TestInterfaceImpl>(callCount));
231 232 233 234 235 236 237 238 239 240 241 242

  auto request1 = client.newRequest("foo");
  request1.set("i", 123);
  request1.set("j", true);
  auto promise1 = request1.send();

  auto request2 = client.newRequest("baz");
  initDynamicTestMessage(request2.init("s").as<DynamicStruct>());
  auto promise2 = request2.send();

  bool barFailed = false;
  auto request3 = client.newRequest("bar");
243
  auto promise3 = request3.send().then(
244 245 246
      [](Response<DynamicStruct>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
      }, [&](kj::Exception&& e) {
247
        EXPECT_EQ(kj::Exception::Type::UNIMPLEMENTED, e.getType());
248 249 250 251 252
        barFailed = true;
      });

  EXPECT_EQ(0, callCount);

253
  auto response1 = promise1.wait(waitScope);
254 255 256

  EXPECT_EQ("foo", response1.get("x").as<Text>());

257
  auto response2 = promise2.wait(waitScope);
258

259
  promise3.wait(waitScope);
260 261 262 263 264 265

  EXPECT_EQ(2, callCount);
  EXPECT_TRUE(barFailed);
}

TEST(Capability, DynamicClientInheritance) {
266
  kj::EventLoop loop;
267
  kj::WaitScope waitScope(loop);
268 269 270 271

  int callCount = 0;

  DynamicCapability::Client client1 =
272
      test::TestExtends::Client(kj::heap<TestExtendsImpl>(callCount));
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  EXPECT_EQ(Schema::from<test::TestExtends>(), client1.getSchema());
  EXPECT_NE(Schema::from<test::TestInterface>(), client1.getSchema());

  DynamicCapability::Client client2 = client1.upcast(Schema::from<test::TestInterface>());
  EXPECT_EQ(Schema::from<test::TestInterface>(), client2.getSchema());

  EXPECT_ANY_THROW(client2.upcast(Schema::from<test::TestExtends>()));
  auto client = client2.castAs<DynamicCapability>(Schema::from<test::TestExtends>());

  auto request1 = client.newRequest("foo");
  request1.set("i", 321);
  auto promise1 = request1.send();

  auto request2 = client.newRequest("grault");
  auto promise2 = request2.send();

  EXPECT_EQ(0, callCount);

291
  auto response2 = promise2.wait(waitScope);
292 293 294

  checkDynamicTestMessage(response2.as<DynamicStruct>());

295
  auto response1 = promise1.wait(waitScope);
296 297 298

  EXPECT_EQ("bar", response1.get("x").as<Text>());

299
  EXPECT_EQ(2, callCount);
300 301 302
}

TEST(Capability, DynamicClientPipelining) {
303
  kj::EventLoop loop;
304
  kj::WaitScope waitScope(loop);
305 306 307 308

  int callCount = 0;
  int chainedCallCount = 0;
  DynamicCapability::Client client =
309
      test::TestPipeline::Client(kj::heap<TestPipelineImpl>(callCount));
310 311 312

  auto request = client.newRequest("getCap");
  request.set("n", 234);
313
  request.set("inCap", test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
314 315 316 317 318 319 320 321 322 323

  auto promise = request.send();

  auto outCap = promise.get("outBox").releaseAs<DynamicStruct>()
                       .get("cap").releaseAs<DynamicCapability>();
  auto pipelineRequest = outCap.newRequest("foo");
  pipelineRequest.set("i", 321);
  auto pipelinePromise = pipelineRequest.send();

  auto pipelineRequest2 = outCap.castAs<test::TestExtends>().graultRequest();
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  auto pipelinePromise2 = pipelineRequest2.send();

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

  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

  auto response = pipelinePromise.wait(waitScope);
  EXPECT_EQ("bar", response.get("x").as<Text>());

  auto response2 = pipelinePromise2.wait(waitScope);
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
  EXPECT_EQ(1, chainedCallCount);
}

TEST(Capability, DynamicClientPipelineAnyCap) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  int callCount = 0;
  int chainedCallCount = 0;
  DynamicCapability::Client client =
      test::TestPipeline::Client(kj::heap<TestPipelineImpl>(callCount));

  auto request = client.newRequest("getAnyCap");
  request.set("n", 234);
  request.set("inCap", test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));

  auto promise = request.send();

  auto outAnyCap = promise.get("outBox").releaseAs<DynamicStruct>()
                          .get("cap").releaseAs<DynamicCapability>();

  EXPECT_EQ(Schema::from<Capability>(), outAnyCap.getSchema());
  auto outCap = outAnyCap.castAs<DynamicCapability>(Schema::from<test::TestInterface>());

  auto pipelineRequest = outCap.newRequest("foo");
  pipelineRequest.set("i", 321);
  auto pipelinePromise = pipelineRequest.send();

  auto pipelineRequest2 = outCap.castAs<test::TestExtends>().graultRequest();
367 368 369 370 371 372 373
  auto pipelinePromise2 = pipelineRequest2.send();

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

  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

374
  auto response = pipelinePromise.wait(waitScope);
375 376
  EXPECT_EQ("bar", response.get("x").as<Text>());

377
  auto response2 = pipelinePromise2.wait(waitScope);
378 379 380
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
381 382 383
  EXPECT_EQ(1, chainedCallCount);
}

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
// =======================================================================================

class TestInterfaceDynamicImpl final: public DynamicCapability::Server {
public:
  TestInterfaceDynamicImpl(int& callCount)
      : DynamicCapability::Server(Schema::from<test::TestInterface>()),
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "foo") {
      ++callCount;
      auto params = context.getParams();
      EXPECT_EQ(123, params.get("i").as<int>());
      EXPECT_TRUE(params.get("j").as<bool>());
      context.getResults().set("x", "foo");
      return kj::READY_NOW;
    } else if (methodName == "baz") {
      ++callCount;
      auto params = context.getParams();
      checkDynamicTestMessage(params.get("s").as<DynamicStruct>());
      context.releaseParams();
      EXPECT_ANY_THROW(context.getParams());
      return kj::READY_NOW;
    } else {
412
      KJ_UNIMPLEMENTED("Method not implemented", methodName) { break; }
413
      return kj::READY_NOW;
414 415 416 417 418
    }
  }
};

TEST(Capability, DynamicServer) {
419
  kj::EventLoop loop;
420
  kj::WaitScope waitScope(loop);
421 422 423

  int callCount = 0;
  test::TestInterface::Client client =
424
      DynamicCapability::Client(kj::heap<TestInterfaceDynamicImpl>(callCount))
425 426 427 428 429 430 431 432 433 434 435 436 437
          .castAs<test::TestInterface>();

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

  auto request2 = client.bazRequest();
  initTestMessage(request2.initS());
  auto promise2 = request2.send();

  bool barFailed = false;
  auto request3 = client.barRequest();
438
  auto promise3 = request3.send().then(
439 440 441
      [](Response<test::TestInterface::BarResults>&& response) {
        ADD_FAILURE() << "Expected bar() call to fail.";
      }, [&](kj::Exception&& e) {
442
        EXPECT_EQ(kj::Exception::Type::UNIMPLEMENTED, e.getType());
443 444 445 446 447
        barFailed = true;
      });

  EXPECT_EQ(0, callCount);

448
  auto response1 = promise1.wait(waitScope);
449 450 451

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

452
  auto response2 = promise2.wait(waitScope);
453

454
  promise3.wait(waitScope);
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

  EXPECT_EQ(2, callCount);
  EXPECT_TRUE(barFailed);
}

class TestExtendsDynamicImpl final: public DynamicCapability::Server {
public:
  TestExtendsDynamicImpl(int& callCount)
      : DynamicCapability::Server(Schema::from<test::TestExtends>()),
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "foo") {
      ++callCount;
      auto params = context.getParams();
      EXPECT_EQ(321, params.get("i").as<int>());
      EXPECT_FALSE(params.get("j").as<bool>());
      context.getResults().set("x", "bar");
      return kj::READY_NOW;
    } else if (methodName == "grault") {
      ++callCount;
      context.releaseParams();
      initDynamicTestMessage(context.getResults());
      return kj::READY_NOW;
    } else {
      KJ_FAIL_ASSERT("Method not implemented", methodName);
    }
  }
};

TEST(Capability, DynamicServerInheritance) {
490
  kj::EventLoop loop;
491
  kj::WaitScope waitScope(loop);
492 493 494

  int callCount = 0;
  test::TestExtends::Client client1 =
495
      DynamicCapability::Client(kj::heap<TestExtendsDynamicImpl>(callCount))
496 497 498 499 500 501 502 503 504 505 506 507 508
          .castAs<test::TestExtends>();
  test::TestInterface::Client client2 = client1;
  auto client = client2.castAs<test::TestExtends>();

  auto request1 = client.fooRequest();
  request1.setI(321);
  auto promise1 = request1.send();

  auto request2 = client.graultRequest();
  auto promise2 = request2.send();

  EXPECT_EQ(0, callCount);

509
  auto response2 = promise2.wait(waitScope);
510 511 512

  checkTestMessage(response2);

513
  auto response1 = promise1.wait(waitScope);
514 515 516 517 518 519 520 521 522

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

  EXPECT_EQ(2, callCount);
}

class TestPipelineDynamicImpl final: public DynamicCapability::Server {
public:
  TestPipelineDynamicImpl(int& callCount)
523
      : DynamicCapability::Server(Schema::from<test::TestPipeline>()),
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "getCap") {
      ++callCount;

      auto params = context.getParams();
      EXPECT_EQ(234, params.get("n").as<uint32_t>());

      auto cap = params.get("inCap").as<DynamicCapability>();
      context.releaseParams();

      auto request = cap.newRequest("foo");
      request.set("i", 123);
      request.set("j", true);

      return request.send().then(
545
          [this,KJ_CPCAP(context)](capnp::Response<DynamicStruct>&& response) mutable {
546 547 548 549 550 551 552 553 554
            EXPECT_EQ("foo", response.get("x").as<Text>());

            auto result = context.getResults();
            result.set("s", "bar");

            auto box = result.init("outBox").as<DynamicStruct>();

            // Too lazy to write a whole separate test for each of these cases...  so just make
            // sure they both compile here, and only actually test the latter.
555
            box.set("cap", kj::heap<TestExtendsDynamicImpl>(callCount));
556 557 558 559 560 561 562 563 564 565 566
#if __GNUG__ && !__clang__ && __GNUG__ == 4 && __GNUC_MINOR__ == 9
            // The last line in this block tickles a bug in Debian G++ 4.9.2 that is not present
            // in 4.8.x nor in 4.9.4:
            //     https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=781060
            //
            // Unfortunatley 4.9.2 is present on many Debian Jessie systems..
            //
            // For the moment, we can get away with skipping the last line as the previous line
            // will set things up in a way that allows the test to complete successfully.
            return;
#endif
567
            box.set("cap", kj::heap<TestExtendsImpl>(callCount));
568 569 570 571 572 573 574 575
          });
    } else {
      KJ_FAIL_ASSERT("Method not implemented", methodName);
    }
  }
};

TEST(Capability, DynamicServerPipelining) {
576
  kj::EventLoop loop;
577
  kj::WaitScope waitScope(loop);
578 579 580

  int callCount = 0;
  int chainedCallCount = 0;
581 582 583
  test::TestPipeline::Client client =
      DynamicCapability::Client(kj::heap<TestPipelineDynamicImpl>(callCount))
          .castAs<test::TestPipeline>();
584 585 586

  auto request = client.getCapRequest();
  request.setN(234);
587
  request.setInCap(test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

  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.

  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

603
  auto response = pipelinePromise.wait(waitScope);
604 605
  EXPECT_EQ("bar", response.getX());

606
  auto response2 = pipelinePromise2.wait(waitScope);
607 608 609 610 611 612
  checkTestMessage(response2);

  EXPECT_EQ(3, callCount);
  EXPECT_EQ(1, chainedCallCount);
}

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
class TestTailCallerDynamicImpl final: public DynamicCapability::Server {
public:
  TestTailCallerDynamicImpl(int& callCount)
      : DynamicCapability::Server(Schema::from<test::TestTailCaller>()),
        callCount(callCount) {}

  int& callCount;

  kj::Promise<void> call(InterfaceSchema::Method method,
                         CallContext<DynamicStruct, DynamicStruct> context) {
    auto methodName = method.getProto().getName();
    if (methodName == "foo") {
      ++callCount;

      auto params = context.getParams();
      auto tailRequest = params.get("callee").as<DynamicCapability>().newRequest("foo");
      tailRequest.set("i", params.get("i"));
      tailRequest.set("t", "from TestTailCaller");
      return context.tailCall(kj::mv(tailRequest));
    } else {
      KJ_FAIL_ASSERT("Method not implemented", methodName);
    }
  }
};

TEST(Capability, DynamicServerTailCall) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  int calleeCallCount = 0;
  int callerCallCount = 0;

  test::TestTailCallee::Client callee(kj::heap<TestTailCalleeImpl>(calleeCallCount));
  test::TestTailCaller::Client caller =
      DynamicCapability::Client(kj::heap<TestTailCallerDynamicImpl>(callerCallCount))
          .castAs<test::TestTailCaller>();

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

  auto promise = request.send();

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

  auto response = promise.wait(waitScope);
  EXPECT_EQ(456, response.getI());
  EXPECT_EQ(456, response.getI());

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

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

  EXPECT_EQ(0, dependentCall0.wait(waitScope).getN());
  EXPECT_EQ(1, dependentCall1.wait(waitScope).getN());
  EXPECT_EQ(2, dependentCall2.wait(waitScope).getN());

  EXPECT_EQ(1, calleeCallCount);
  EXPECT_EQ(1, callerCallCount);
}

674 675
// =======================================================================================

676 677
void verifyClient(test::TestInterface::Client client, const int& callCount,
                  kj::WaitScope& waitScope) {
678 679 680 681
  int origCount = callCount;
  auto request = client.fooRequest();
  request.setI(123);
  request.setJ(true);
682
  auto response = request.send().wait(waitScope);
683 684 685 686
  EXPECT_EQ("foo", response.getX());
  EXPECT_EQ(origCount + 1, callCount);
}

687 688
void verifyClient(DynamicCapability::Client client, const int& callCount,
                  kj::WaitScope& waitScope) {
689 690 691 692
  int origCount = callCount;
  auto request = client.newRequest("foo");
  request.set("i", 123);
  request.set("j", true);
693
  auto response = request.send().wait(waitScope);
694 695 696 697
  EXPECT_EQ("foo", response.get("x").as<Text>());
  EXPECT_EQ(origCount + 1, callCount);
}

698
TEST(Capability, AnyPointersAndOrphans) {
699
  kj::EventLoop loop;
700
  kj::WaitScope waitScope(loop);
701 702 703 704 705 706 707

  int callCount1 = 0;
  int callCount2 = 0;

  // We use a TestPipeline instance here merely as a way to conveniently obtain an imbued message
  // instance.
  test::TestPipeline::Client baseClient(nullptr);
708 709
  test::TestInterface::Client client1(kj::heap<TestInterfaceImpl>(callCount1));
  test::TestInterface::Client client2(kj::heap<TestInterfaceImpl>(callCount2));
710 711 712 713 714 715 716 717 718 719 720

  auto request = baseClient.testPointersRequest();
  request.setCap(client1);

  EXPECT_TRUE(request.hasCap());

  Orphan<test::TestInterface> orphan = request.disownCap();
  EXPECT_FALSE(orphan == nullptr);

  EXPECT_FALSE(request.hasCap());

721 722
  verifyClient(orphan.get(), callCount1, waitScope);
  verifyClient(orphan.getReader(), callCount1, waitScope);
723 724 725 726

  request.getObj().adopt(kj::mv(orphan));
  EXPECT_TRUE(orphan == nullptr);

727 728
  verifyClient(request.getObj().getAs<test::TestInterface>(), callCount1, waitScope);
  verifyClient(request.asReader().getObj().getAs<test::TestInterface>(), callCount1, waitScope);
729
  verifyClient(request.getObj().getAs<DynamicCapability>(
730
      Schema::from<test::TestInterface>()), callCount1, waitScope);
731
  verifyClient(request.asReader().getObj().getAs<DynamicCapability>(
732
      Schema::from<test::TestInterface>()), callCount1, waitScope);
733 734 735 736 737

  request.getObj().clear();
  EXPECT_FALSE(request.hasObj());

  request.getObj().setAs<test::TestInterface>(client2);
738
  verifyClient(request.getObj().getAs<test::TestInterface>(), callCount2, waitScope);
739 740 741

  Orphan<DynamicCapability> dynamicOrphan = request.getObj().disownAs<DynamicCapability>(
      Schema::from<test::TestInterface>());
742 743
  verifyClient(dynamicOrphan.get(), callCount2, waitScope);
  verifyClient(dynamicOrphan.getReader(), callCount2, waitScope);
744 745

  Orphan<DynamicValue> dynamicValueOrphan = kj::mv(dynamicOrphan);
746
  verifyClient(dynamicValueOrphan.get().as<DynamicCapability>(), callCount2, waitScope);
747 748 749

  orphan = dynamicValueOrphan.releaseAs<test::TestInterface>();
  EXPECT_FALSE(orphan == nullptr);
750
  verifyClient(orphan.get(), callCount2, waitScope);
751 752 753 754

  request.adoptCap(kj::mv(orphan));
  EXPECT_TRUE(orphan == nullptr);

755
  verifyClient(request.getCap(), callCount2, waitScope);
756 757

  Orphan<DynamicCapability> dynamicOrphan2 = request.disownCap();
758 759
  verifyClient(dynamicOrphan2.get(), callCount2, waitScope);
  verifyClient(dynamicOrphan2.getReader(), callCount2, waitScope);
760 761 762
}

TEST(Capability, Lists) {
763
  kj::EventLoop loop;
764
  kj::WaitScope waitScope(loop);
765 766 767 768

  int callCount1 = 0;
  int callCount2 = 0;
  int callCount3 = 0;
769 770 771 772
  test::TestPipeline::Client baseClient(kj::heap<TestPipelineImpl>(callCount1));
  test::TestInterface::Client client1(kj::heap<TestInterfaceImpl>(callCount1));
  test::TestInterface::Client client2(kj::heap<TestInterfaceImpl>(callCount2));
  test::TestInterface::Client client3(kj::heap<TestInterfaceImpl>(callCount3));
773 774 775 776 777 778 779 780

  auto request = baseClient.testPointersRequest();

  auto list = request.initList(3);
  list.set(0, client1);
  list.set(1, client2);
  list.set(2, client3);

781 782 783
  verifyClient(list[0], callCount1, waitScope);
  verifyClient(list[1], callCount2, waitScope);
  verifyClient(list[2], callCount3, waitScope);
784 785

  auto listReader = request.asReader().getList();
786 787 788
  verifyClient(listReader[0], callCount1, waitScope);
  verifyClient(listReader[1], callCount2, waitScope);
  verifyClient(listReader[2], callCount3, waitScope);
789 790

  auto dynamicList = toDynamic(list);
791 792 793
  verifyClient(dynamicList[0].as<DynamicCapability>(), callCount1, waitScope);
  verifyClient(dynamicList[1].as<DynamicCapability>(), callCount2, waitScope);
  verifyClient(dynamicList[2].as<DynamicCapability>(), callCount3, waitScope);
794 795

  auto dynamicListReader = toDynamic(listReader);
796 797 798
  verifyClient(dynamicListReader[0].as<DynamicCapability>(), callCount1, waitScope);
  verifyClient(dynamicListReader[1].as<DynamicCapability>(), callCount2, waitScope);
  verifyClient(dynamicListReader[2].as<DynamicCapability>(), callCount3, waitScope);
799 800
}

801 802 803 804 805 806 807
TEST(Capability, KeywordMethods) {
  // Verify that keywords are only munged where necessary.

  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);
  bool called = false;

Kenton Varda's avatar
Kenton Varda committed
808
  class TestKeywordMethodsImpl final: public test::TestKeywordMethods::Server {
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  public:
    TestKeywordMethodsImpl(bool& called): called(called) {}

    kj::Promise<void> delete_(DeleteContext context) override {
      called = true;
      return kj::READY_NOW;
    }

  private:
    bool& called;
  };

  test::TestKeywordMethods::Client client = kj::heap<TestKeywordMethodsImpl>(called);
  client.deleteRequest().send().wait(waitScope);

  EXPECT_TRUE(called);
}

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
TEST(Capability, Generics) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  typedef test::TestGenerics<TestAllTypes>::Interface<List<uint32_t>> Interface;
  Interface::Client client = nullptr;

  auto request = client.callRequest();
  request.setBaz("hello");
  initTestMessage(request.initInnerBound().initFoo());
  initTestMessage(request.initInnerUnbound().getFoo().initAs<TestAllTypes>());

  auto promise = request.send().then([](capnp::Response<Interface::CallResults>&& response) {
    // This doesn't actually execute; we're just checking that it compiles.
    List<uint32_t>::Reader qux = response.getQux();
    qux.size();
    checkTestMessage(response.getGen().getFoo());
844 845 846
  }, [](kj::Exception&& e) {
    // Ignore exception (which we'll always get because we're calling a null capability).
  });
847 848

  promise.wait(waitScope);
849 850 851 852 853

  // Check that asGeneric<>() compiles.
  test::TestGenerics<TestAllTypes>::Interface<>::Client castClient = client.asGeneric<>();
  test::TestGenerics<TestAllTypes>::Interface<TestAllTypes>::Client castClient2 =
      client.asGeneric<TestAllTypes>();
854
  test::TestGenerics<>::Interface<List<uint32_t>>::Client castClient3 = client.asTestGenericsGeneric<>();
855 856 857 858 859 860 861 862 863
}

TEST(Capability, Generics2) {
  MallocMessageBuilder builder;
  auto root = builder.getRoot<test::TestUseGenerics>();

  root.initCap().setFoo(test::TestInterface::Client(nullptr));
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
TEST(Capability, ImplicitParams) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  typedef test::TestImplicitMethodParams Interface;
  Interface::Client client = nullptr;

  capnp::Request<Interface::CallParams<Text, TestAllTypes>,
                 test::TestGenerics<Text, TestAllTypes>> request =
      client.callRequest<Text, TestAllTypes>();
  request.setFoo("hello");
  initTestMessage(request.initBar());

  auto promise = request.send()
      .then([](capnp::Response<test::TestGenerics<Text, TestAllTypes>>&& response) {
    // This doesn't actually execute; we're just checking that it compiles.
    Text::Reader text = response.getFoo();
    text.size();
    checkTestMessage(response.getRev().getFoo());
  }, [](kj::Exception&& e) {});

  promise.wait(waitScope);
}

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
TEST(Capability, CapabilityServerSet) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  CapabilityServerSet<test::TestInterface> set1, set2;

  int callCount = 0;
  test::TestInterface::Client clientStandalone(kj::heap<TestInterfaceImpl>(callCount));
  test::TestInterface::Client clientNull = nullptr;

  auto ownServer1 = kj::heap<TestInterfaceImpl>(callCount);
  auto& server1 = *ownServer1;
  test::TestInterface::Client client1 = set1.add(kj::mv(ownServer1));

  auto ownServer2 = kj::heap<TestInterfaceImpl>(callCount);
  auto& server2 = *ownServer2;
904
  test::TestInterface::Client client2 = set2.add(kj::mv(ownServer2));
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

  // Getting the local server using the correct set works.
  EXPECT_EQ(&server1, &KJ_ASSERT_NONNULL(set1.getLocalServer(client1).wait(waitScope)));
  EXPECT_EQ(&server2, &KJ_ASSERT_NONNULL(set2.getLocalServer(client2).wait(waitScope)));

  // Getting the local server using the wrong set doesn't work.
  EXPECT_TRUE(set1.getLocalServer(client2).wait(waitScope) == nullptr);
  EXPECT_TRUE(set2.getLocalServer(client1).wait(waitScope) == nullptr);
  EXPECT_TRUE(set1.getLocalServer(clientStandalone).wait(waitScope) == nullptr);
  EXPECT_TRUE(set1.getLocalServer(clientNull).wait(waitScope) == nullptr);

  // A promise client waits to be resolved.
  auto paf = kj::newPromiseAndFulfiller<test::TestInterface::Client>();
  test::TestInterface::Client clientPromise = kj::mv(paf.promise);

920 921 922 923
  auto errorPaf = kj::newPromiseAndFulfiller<test::TestInterface::Client>();
  test::TestInterface::Client errorPromise = kj::mv(errorPaf.promise);

  bool resolved1 = false, resolved2 = false, resolved3 = false;
924 925 926 927 928 929 930 931 932 933
  auto promise1 = set1.getLocalServer(clientPromise)
      .then([&](kj::Maybe<test::TestInterface::Server&> server) {
    resolved1 = true;
    EXPECT_EQ(&server1, &KJ_ASSERT_NONNULL(server));
  });
  auto promise2 = set2.getLocalServer(clientPromise)
      .then([&](kj::Maybe<test::TestInterface::Server&> server) {
    resolved2 = true;
    EXPECT_TRUE(server == nullptr);
  });
934 935 936 937 938 939 940
  auto promise3 = set1.getLocalServer(errorPromise)
      .then([&](kj::Maybe<test::TestInterface::Server&> server) {
    KJ_FAIL_EXPECT("getLocalServer() on error promise should have thrown");
  }, [&](kj::Exception&& e) {
    resolved3 = true;
    KJ_EXPECT(e.getDescription().endsWith("foo"), e.getDescription());
  });
941 942 943 944 945 946 947 948

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

  EXPECT_FALSE(resolved1);
  EXPECT_FALSE(resolved2);
949
  EXPECT_FALSE(resolved3);
950 951

  paf.fulfiller->fulfill(kj::cp(client1));
952
  errorPaf.fulfiller->reject(KJ_EXCEPTION(FAILED, "foo"));
953 954 955

  promise1.wait(waitScope);
  promise2.wait(waitScope);
956
  promise3.wait(waitScope);
957 958 959

  EXPECT_TRUE(resolved1);
  EXPECT_TRUE(resolved2);
960
  EXPECT_TRUE(resolved3);
961
}
962

963 964 965 966 967 968 969 970 971 972 973 974 975
class TestThisCap final: public test::TestInterface::Server {
public:
  TestThisCap(int& callCount): callCount(callCount) {}
  ~TestThisCap() noexcept(false) { callCount = -1; }

  test::TestInterface::Client getSelf() {
    return thisCap();
  }

protected:
  kj::Promise<void> bar(BarContext context) {
    ++callCount;
    return kj::READY_NOW;
976 977
  }

978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
private:
  int& callCount;
};

TEST(Capability, ThisCap) {
  int callCount = 0;
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  auto server = kj::heap<TestThisCap>(callCount);
  TestThisCap* serverPtr = server;

  test::TestInterface::Client client = kj::mv(server);
  client.barRequest().send().wait(waitScope);
  EXPECT_EQ(1, callCount);

  test::TestInterface::Client client2 = serverPtr->getSelf();
  EXPECT_EQ(1, callCount);
  client2.barRequest().send().wait(waitScope);
  EXPECT_EQ(2, callCount);

  client = nullptr;

  EXPECT_EQ(2, callCount);
  client2.barRequest().send().wait(waitScope);
  EXPECT_EQ(3, callCount);

1005 1006
  client2 = nullptr;

1007
  EXPECT_EQ(-1, callCount);
1008 1009
}

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
TEST(Capability, TransferCap) {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  MallocMessageBuilder message;
  auto root = message.initRoot<test::TestTransferCap>();

  auto orphan = message.getOrphanage().newOrphan<test::TestTransferCap::Element>();
  auto e = orphan.get();
  e.setText("foo");
  e.setCap(KJ_EXCEPTION(FAILED, "whatever"));

  root.initList(1).adoptWithCaveats(0, kj::mv(orphan));

  // This line used to throw due to capability pointers being incorrectly transferred.
  auto cap = root.getList()[0].getCap();

  cap.whenResolved().then([]() {
    KJ_FAIL_EXPECT("didn't throw?");
  }, [](kj::Exception&&) {
    // success
  }).wait(waitScope);
}

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 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 1075 1076 1077 1078 1079 1080 1081 1082
KJ_TEST("Promise<RemotePromise<T>> automatically reduces to RemotePromise<T>") {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  int callCount = 0;
  test::TestInterface::Client client(kj::heap<TestInterfaceImpl>(callCount));

  RemotePromise<test::TestInterface::FooResults> promise = kj::evalLater([&]() {
    auto request = client.fooRequest();
    request.setI(123);
    request.setJ(true);
    return request.send();
  });

  EXPECT_EQ(0, callCount);
  auto response = promise.wait(waitScope);
  EXPECT_EQ("foo", response.getX());
  EXPECT_EQ(1, callCount);
}

KJ_TEST("Promise<RemotePromise<T>> automatically reduces to RemotePromise<T> with pipelining") {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  int callCount = 0;
  int chainedCallCount = 0;
  test::TestPipeline::Client client(kj::heap<TestPipelineImpl>(callCount));

  auto promise = kj::evalLater([&]() {
    auto request = client.getCapRequest();
    request.setN(234);
    request.setInCap(test::TestInterface::Client(kj::heap<TestInterfaceImpl>(chainedCallCount)));
    return request.send();
  });

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

  EXPECT_EQ(0, callCount);
  EXPECT_EQ(0, chainedCallCount);

  auto response = pipelinePromise.wait(waitScope);
  EXPECT_EQ("bar", response.getX());

  EXPECT_EQ(2, callCount);
  EXPECT_EQ(1, chainedCallCount);
}

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
KJ_TEST("clone() with caps") {
  int dummy = 0;
  MallocMessageBuilder builder(2048);
  auto root = builder.getRoot<AnyPointer>().initAs<List<test::TestInterface>>(3);
  root.set(0, kj::heap<TestInterfaceImpl>(dummy));
  root.set(1, kj::heap<TestInterfaceImpl>(dummy));
  root.set(2, kj::heap<TestInterfaceImpl>(dummy));

  auto copyPtr = clone(root.asReader());
  auto& copy = *copyPtr;

  KJ_ASSERT(copy.size() == 3);
  KJ_EXPECT(ClientHook::from(copy[0]).get() == ClientHook::from(root[0]).get());
  KJ_EXPECT(ClientHook::from(copy[1]).get() == ClientHook::from(root[1]).get());
  KJ_EXPECT(ClientHook::from(copy[2]).get() == ClientHook::from(root[2]).get());

  KJ_EXPECT(ClientHook::from(copy[0]).get() != ClientHook::from(root[1]).get());
  KJ_EXPECT(ClientHook::from(copy[1]).get() != ClientHook::from(root[2]).get());
  KJ_EXPECT(ClientHook::from(copy[2]).get() != ClientHook::from(root[0]).get());
}

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
KJ_TEST("Streaming calls block subsequent calls") {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  auto ownServer = kj::heap<TestStreamingImpl>();
  auto& server = *ownServer;
  test::TestStreaming::Client cap = kj::mv(ownServer);

  kj::Promise<void> promise1 = nullptr, promise2 = nullptr, promise3 = nullptr;

  {
    auto req = cap.doStreamIRequest();
    req.setI(123);
1117
    promise1 = req.send();
1118 1119 1120 1121 1122
  }

  {
    auto req = cap.doStreamJRequest();
    req.setJ(321);
1123
    promise2 = req.send();
1124 1125 1126 1127 1128
  }

  {
    auto req = cap.doStreamIRequest();
    req.setI(456);
1129
    promise3 = req.send();
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 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
  }

  auto promise4 = cap.finishStreamRequest().send();

  KJ_EXPECT(server.iSum == 0);
  KJ_EXPECT(server.jSum == 0);

  KJ_EXPECT(!promise1.poll(waitScope));
  KJ_EXPECT(!promise2.poll(waitScope));
  KJ_EXPECT(!promise3.poll(waitScope));
  KJ_EXPECT(!promise4.poll(waitScope));

  KJ_EXPECT(server.iSum == 123);
  KJ_EXPECT(server.jSum == 0);

  KJ_ASSERT_NONNULL(server.fulfiller)->fulfill();

  KJ_EXPECT(promise1.poll(waitScope));
  KJ_EXPECT(!promise2.poll(waitScope));
  KJ_EXPECT(!promise3.poll(waitScope));
  KJ_EXPECT(!promise4.poll(waitScope));

  KJ_EXPECT(server.iSum == 123);
  KJ_EXPECT(server.jSum == 321);

  KJ_ASSERT_NONNULL(server.fulfiller)->fulfill();

  KJ_EXPECT(promise1.poll(waitScope));
  KJ_EXPECT(promise2.poll(waitScope));
  KJ_EXPECT(!promise3.poll(waitScope));
  KJ_EXPECT(!promise4.poll(waitScope));

  KJ_EXPECT(server.iSum == 579);
  KJ_EXPECT(server.jSum == 321);

  KJ_ASSERT_NONNULL(server.fulfiller)->fulfill();

  KJ_EXPECT(promise1.poll(waitScope));
  KJ_EXPECT(promise2.poll(waitScope));
  KJ_EXPECT(promise3.poll(waitScope));
  KJ_EXPECT(promise4.poll(waitScope));

  auto result = promise4.wait(waitScope);
  KJ_EXPECT(result.getTotalI() == 579);
  KJ_EXPECT(result.getTotalJ() == 321);
}

KJ_TEST("Streaming calls can be canceled") {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  auto ownServer = kj::heap<TestStreamingImpl>();
  auto& server = *ownServer;
  test::TestStreaming::Client cap = kj::mv(ownServer);

  kj::Promise<void> promise1 = nullptr, promise2 = nullptr, promise3 = nullptr;

  {
    auto req = cap.doStreamIRequest();
    req.setI(123);
1190
    promise1 = req.send();
1191 1192 1193 1194 1195
  }

  {
    auto req = cap.doStreamJRequest();
    req.setJ(321);
1196
    promise2 = req.send();
1197 1198 1199 1200 1201
  }

  {
    auto req = cap.doStreamIRequest();
    req.setI(456);
1202
    promise3 = req.send();
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
  }

  auto promise4 = cap.finishStreamRequest().send();

  // Cancel the streaming calls.
  promise1 = nullptr;
  promise2 = nullptr;
  promise3 = nullptr;

  KJ_EXPECT(server.iSum == 0);
  KJ_EXPECT(server.jSum == 0);

  KJ_EXPECT(!promise4.poll(waitScope));

  KJ_EXPECT(server.iSum == 123);
  KJ_EXPECT(server.jSum == 0);

  KJ_ASSERT_NONNULL(server.fulfiller)->fulfill();

  KJ_EXPECT(!promise4.poll(waitScope));

  // The call to doStreamJ() opted into cancellation so the next call to doStreamI() happens
  // immediately.
  KJ_EXPECT(server.iSum == 579);
  KJ_EXPECT(server.jSum == 321);

  KJ_ASSERT_NONNULL(server.fulfiller)->fulfill();

  KJ_EXPECT(promise4.poll(waitScope));

  auto result = promise4.wait(waitScope);
  KJ_EXPECT(result.getTotalI() == 579);
  KJ_EXPECT(result.getTotalJ() == 321);
}

KJ_TEST("Streaming call throwing cascades to following calls") {
  kj::EventLoop loop;
  kj::WaitScope waitScope(loop);

  auto ownServer = kj::heap<TestStreamingImpl>();
  auto& server = *ownServer;
  test::TestStreaming::Client cap = kj::mv(ownServer);

  server.jShouldThrow = true;

  kj::Promise<void> promise1 = nullptr, promise2 = nullptr, promise3 = nullptr;

  {
    auto req = cap.doStreamIRequest();
    req.setI(123);
1253
    promise1 = req.send();
1254 1255 1256 1257 1258
  }

  {
    auto req = cap.doStreamJRequest();
    req.setJ(321);
1259
    promise2 = req.send();
1260 1261 1262 1263 1264
  }

  {
    auto req = cap.doStreamIRequest();
    req.setI(456);
1265
    promise3 = req.send();
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
  }

  auto promise4 = cap.finishStreamRequest().send();

  KJ_EXPECT(server.iSum == 0);
  KJ_EXPECT(server.jSum == 0);

  KJ_EXPECT(!promise1.poll(waitScope));
  KJ_EXPECT(!promise2.poll(waitScope));
  KJ_EXPECT(!promise3.poll(waitScope));
  KJ_EXPECT(!promise4.poll(waitScope));

  KJ_EXPECT(server.iSum == 123);
  KJ_EXPECT(server.jSum == 0);

  KJ_ASSERT_NONNULL(server.fulfiller)->fulfill();

  KJ_EXPECT(promise1.poll(waitScope));
  KJ_EXPECT(promise2.poll(waitScope));
  KJ_EXPECT(promise3.poll(waitScope));
  KJ_EXPECT(promise4.poll(waitScope));

  KJ_EXPECT(server.iSum == 123);
  KJ_EXPECT(server.jSum == 321);

  KJ_EXPECT_THROW_MESSAGE("throw requested", promise2.wait(waitScope));
  KJ_EXPECT_THROW_MESSAGE("throw requested", promise3.wait(waitScope));
  KJ_EXPECT_THROW_MESSAGE("throw requested", promise4.wait(waitScope));
}

1296 1297 1298
}  // namespace
}  // namespace _
}  // namespace capnp