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

#include "async.h"
#include "debug.h"
#include <gtest/gtest.h>

namespace kj {
namespace {

TEST(Async, EvalVoid) {
30
  EventLoop loop;
31
  WaitScope waitScope(loop);
32 33 34

  bool done = false;

35
  Promise<void> promise = evalLater([&]() { done = true; });
36
  EXPECT_FALSE(done);
37
  promise.wait(waitScope);
38 39 40 41
  EXPECT_TRUE(done);
}

TEST(Async, EvalInt) {
42
  EventLoop loop;
43
  WaitScope waitScope(loop);
44 45 46

  bool done = false;

47
  Promise<int> promise = evalLater([&]() { done = true; return 123; });
48
  EXPECT_FALSE(done);
49
  EXPECT_EQ(123, promise.wait(waitScope));
50 51 52 53
  EXPECT_TRUE(done);
}

TEST(Async, There) {
54
  EventLoop loop;
55
  WaitScope waitScope(loop);
56 57 58 59

  Promise<int> a = 123;
  bool done = false;

60
  Promise<int> promise = a.then([&](int ai) { done = true; return ai + 321; });
61
  EXPECT_FALSE(done);
62
  EXPECT_EQ(444, promise.wait(waitScope));
63 64 65 66
  EXPECT_TRUE(done);
}

TEST(Async, ThereVoid) {
67
  EventLoop loop;
68
  WaitScope waitScope(loop);
69 70 71 72

  Promise<int> a = 123;
  int value = 0;

73
  Promise<void> promise = a.then([&](int ai) { value = ai; });
74
  EXPECT_EQ(0, value);
75
  promise.wait(waitScope);
76 77 78 79
  EXPECT_EQ(123, value);
}

TEST(Async, Exception) {
80
  EventLoop loop;
81
  WaitScope waitScope(loop);
82

83 84
  Promise<int> promise = evalLater(
      [&]() -> int { KJ_FAIL_ASSERT("foo") { return 123; } });
85 86
  EXPECT_TRUE(kj::runCatchingExceptions([&]() {
    // wait() only returns when compiling with -fno-exceptions.
87
    EXPECT_EQ(123, promise.wait(waitScope));
88 89 90 91
  }) != nullptr);
}

TEST(Async, HandleException) {
92
  EventLoop loop;
93
  WaitScope waitScope(loop);
94

95 96
  Promise<int> promise = evalLater(
      [&]() -> int { KJ_FAIL_ASSERT("foo") { return 123; } });
97 98
  int line = __LINE__ - 1;

99
  promise = promise.then(
100 101 102
      [](int i) { return i + 1; },
      [&](Exception&& e) { EXPECT_EQ(line, e.getLine()); return 345; });

103
  EXPECT_EQ(345, promise.wait(waitScope));
104 105 106
}

TEST(Async, PropagateException) {
107
  EventLoop loop;
108
  WaitScope waitScope(loop);
109

110 111
  Promise<int> promise = evalLater(
      [&]() -> int { KJ_FAIL_ASSERT("foo") { return 123; } });
112 113
  int line = __LINE__ - 1;

114
  promise = promise.then([](int i) { return i + 1; });
115

116
  promise = promise.then(
117 118 119
      [](int i) { return i + 2; },
      [&](Exception&& e) { EXPECT_EQ(line, e.getLine()); return 345; });

120
  EXPECT_EQ(345, promise.wait(waitScope));
121 122 123
}

TEST(Async, PropagateExceptionTypeChange) {
124
  EventLoop loop;
125
  WaitScope waitScope(loop);
126

127 128
  Promise<int> promise = evalLater(
      [&]() -> int { KJ_FAIL_ASSERT("foo") { return 123; } });
129 130
  int line = __LINE__ - 1;

131
  Promise<StringPtr> promise2 = promise.then([](int i) -> StringPtr { return "foo"; });
132

133
  promise2 = promise2.then(
134 135 136
      [](StringPtr s) -> StringPtr { return "bar"; },
      [&](Exception&& e) -> StringPtr { EXPECT_EQ(line, e.getLine()); return "baz"; });

137
  EXPECT_EQ("baz", promise2.wait(waitScope));
138 139 140
}

TEST(Async, Then) {
141
  EventLoop loop;
142
  WaitScope waitScope(loop);
143

144
  bool done = false;
145

146 147 148 149
  Promise<int> promise = Promise<int>(123).then([&](int i) {
    done = true;
    return i + 321;
  });
150

151
  EXPECT_FALSE(done);
152

153
  EXPECT_EQ(444, promise.wait(waitScope));
154

155
  EXPECT_TRUE(done);
156 157 158
}

TEST(Async, Chain) {
159
  EventLoop loop;
160
  WaitScope waitScope(loop);
161

162 163
  Promise<int> promise = evalLater([&]() -> int { return 123; });
  Promise<int> promise2 = evalLater([&]() -> int { return 321; });
164

165 166 167 168 169
  auto promise3 = promise.then([&](int i) {
    return promise2.then([&loop,i](int j) {
      return i + j;
    });
  });
170

171
  EXPECT_EQ(444, promise3.wait(waitScope));
172 173
}

174 175 176 177 178 179 180 181
TEST(Async, DeepChain) {
  EventLoop loop;
  WaitScope waitScope(loop);

  Promise<void> promise = NEVER_DONE;

  // Create a ridiculous chain of promises.
  for (uint i = 0; i < 1000; i++) {
182
    promise = evalLater(mvCapture(promise, [](Promise<void> promise) {
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
      return kj::mv(promise);
    }));
  }

  loop.run();

  auto trace = promise.trace();
  uint lines = 0;
  for (char c: trace) {
    lines += c == '\n';
  }

  // Chain nodes should have been collapsed such that instead of a chain of 1000 nodes, we have
  // 2-ish nodes.  We'll give a little room for implementation freedom.
  EXPECT_LT(lines, 5);
}

TEST(Async, DeepChain2) {
  EventLoop loop;
  WaitScope waitScope(loop);

  Promise<void> promise = nullptr;
  promise = evalLater([&]() {
    auto trace = promise.trace();
    uint lines = 0;
    for (char c: trace) {
      lines += c == '\n';
    }

    // Chain nodes should have been collapsed such that instead of a chain of 1000 nodes, we have
    // 2-ish nodes.  We'll give a little room for implementation freedom.
    EXPECT_LT(lines, 5);
  });

  // Create a ridiculous chain of promises.
  for (uint i = 0; i < 1000; i++) {
219
    promise = evalLater(mvCapture(promise, [](Promise<void> promise) {
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
      return kj::mv(promise);
    }));
  }

  promise.wait(waitScope);
}

Promise<void> makeChain(uint i) {
  if (i > 0) {
    return evalLater([i]() -> Promise<void> {
      return makeChain(i - 1);
    });
  } else {
    return NEVER_DONE;
  }
}

TEST(Async, DeepChain3) {
  EventLoop loop;
  WaitScope waitScope(loop);

  Promise<void> promise = makeChain(1000);

  loop.run();

  auto trace = promise.trace();
  uint lines = 0;
  for (char c: trace) {
    lines += c == '\n';
  }

  // Chain nodes should have been collapsed such that instead of a chain of 1000 nodes, we have
  // 2-ish nodes.  We'll give a little room for implementation freedom.
  EXPECT_LT(lines, 5);
}

Promise<void> makeChain2(uint i, Promise<void> promise) {
  if (i > 0) {
    return evalLater(mvCapture(promise, [i](Promise<void>&& promise) -> Promise<void> {
      return makeChain2(i - 1, kj::mv(promise));
    }));
  } else {
    return kj::mv(promise);
  }
}

TEST(Async, DeepChain4) {
  EventLoop loop;
  WaitScope waitScope(loop);

  Promise<void> promise = nullptr;
  promise = evalLater([&]() {
    auto trace = promise.trace();
    uint lines = 0;
    for (char c: trace) {
      lines += c == '\n';
    }

    // Chain nodes should have been collapsed such that instead of a chain of 1000 nodes, we have
    // 2-ish nodes.  We'll give a little room for implementation freedom.
    EXPECT_LT(lines, 5);
  });

  promise = makeChain2(1000, kj::mv(promise));

  promise.wait(waitScope);
}

288
TEST(Async, SeparateFulfiller) {
289
  EventLoop loop;
290
  WaitScope waitScope(loop);
291 292 293 294 295 296 297

  auto pair = newPromiseAndFulfiller<int>();

  EXPECT_TRUE(pair.fulfiller->isWaiting());
  pair.fulfiller->fulfill(123);
  EXPECT_FALSE(pair.fulfiller->isWaiting());

298
  EXPECT_EQ(123, pair.promise.wait(waitScope));
299 300 301
}

TEST(Async, SeparateFulfillerVoid) {
302
  EventLoop loop;
303
  WaitScope waitScope(loop);
304 305 306 307 308 309 310

  auto pair = newPromiseAndFulfiller<void>();

  EXPECT_TRUE(pair.fulfiller->isWaiting());
  pair.fulfiller->fulfill();
  EXPECT_FALSE(pair.fulfiller->isWaiting());

311
  pair.promise.wait(waitScope);
312 313 314 315 316 317
}

TEST(Async, SeparateFulfillerCanceled) {
  auto pair = newPromiseAndFulfiller<void>();

  EXPECT_TRUE(pair.fulfiller->isWaiting());
318
  pair.promise = nullptr;
319 320 321
  EXPECT_FALSE(pair.fulfiller->isWaiting());
}

322
TEST(Async, SeparateFulfillerChained) {
323
  EventLoop loop;
324
  WaitScope waitScope(loop);
325

326
  auto pair = newPromiseAndFulfiller<Promise<int>>();
327 328 329 330 331 332 333 334
  auto inner = newPromiseAndFulfiller<int>();

  EXPECT_TRUE(pair.fulfiller->isWaiting());
  pair.fulfiller->fulfill(kj::mv(inner.promise));
  EXPECT_FALSE(pair.fulfiller->isWaiting());

  inner.fulfiller->fulfill(123);

335
  EXPECT_EQ(123, pair.promise.wait(waitScope));
336 337
}

338 339 340 341 342
#if KJ_NO_EXCEPTIONS
#undef EXPECT_ANY_THROW
#define EXPECT_ANY_THROW(code) EXPECT_DEATH(code, ".")
#endif

343
TEST(Async, SeparateFulfillerDiscarded) {
344
  EventLoop loop;
345
  WaitScope waitScope(loop);
346 347 348 349

  auto pair = newPromiseAndFulfiller<int>();
  pair.fulfiller = nullptr;

350
  EXPECT_ANY_THROW(pair.promise.wait(waitScope));
351 352
}

353 354 355
TEST(Async, SeparateFulfillerMemoryLeak) {
  auto paf = kj::newPromiseAndFulfiller<void>();
  paf.fulfiller->fulfill();
356 357 358
}

TEST(Async, Ordering) {
359
  EventLoop loop;
360
  WaitScope waitScope(loop);
361 362 363 364

  int counter = 0;
  Promise<void> promises[6] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};

365
  promises[1] = evalLater([&]() {
366
    EXPECT_EQ(0, counter++);
Kenton Varda's avatar
Kenton Varda committed
367 368 369 370 371 372 373

    {
      // Use a promise and fulfiller so that we can fulfill the promise after waiting on it in
      // order to induce depth-first scheduling.
      auto paf = kj::newPromiseAndFulfiller<void>();
      promises[2] = paf.promise.then([&]() {
        EXPECT_EQ(1, counter++);
374
      }).eagerlyEvaluate(nullptr);
Kenton Varda's avatar
Kenton Varda committed
375 376 377 378 379 380 381 382 383
      paf.fulfiller->fulfill();
    }

    // .then() is scheduled breadth-first if the promise has already resolved, but depth-first
    // if the promise resolves later.
    promises[3] = Promise<void>(READY_NOW).then([&]() {
      EXPECT_EQ(4, counter++);
    }).then([&]() {
      EXPECT_EQ(5, counter++);
384
    }).eagerlyEvaluate(nullptr);
Kenton Varda's avatar
Kenton Varda committed
385 386 387 388 389

    {
      auto paf = kj::newPromiseAndFulfiller<void>();
      promises[4] = paf.promise.then([&]() {
        EXPECT_EQ(2, counter++);
390
      }).eagerlyEvaluate(nullptr);
Kenton Varda's avatar
Kenton Varda committed
391 392 393 394
      paf.fulfiller->fulfill();
    }

    // evalLater() is like READY_NOW.then().
395
    promises[5] = evalLater([&]() {
396
      EXPECT_EQ(6, counter++);
397 398
    }).eagerlyEvaluate(nullptr);
  }).eagerlyEvaluate(nullptr);
399

400
  promises[0] = evalLater([&]() {
401
    EXPECT_EQ(3, counter++);
402 403 404 405

    // Making this a chain should NOT cause it to preempt promises[1].  (This was a problem at one
    // point.)
    return Promise<void>(READY_NOW);
406
  }).eagerlyEvaluate(nullptr);
407

408
  for (auto i: indices(promises)) {
409
    kj::mv(promises[i]).wait(waitScope);
410 411
  }

412
  EXPECT_EQ(7, counter);
413 414
}

415
TEST(Async, Fork) {
416
  EventLoop loop;
417
  WaitScope waitScope(loop);
418

419
  Promise<int> promise = evalLater([&]() { return 123; });
420

421
  auto fork = promise.fork();
422

423 424 425
  auto branch1 = fork.addBranch().then([](int i) {
    EXPECT_EQ(123, i);
    return 456;
426
  });
427 428 429 430 431 432 433 434
  auto branch2 = fork.addBranch().then([](int i) {
    EXPECT_EQ(123, i);
    return 789;
  });

  {
    auto releaseFork = kj::mv(fork);
  }
435

436 437
  EXPECT_EQ(456, branch1.wait(waitScope));
  EXPECT_EQ(789, branch2.wait(waitScope));
438 439 440 441 442
}

struct RefcountedInt: public Refcounted {
  RefcountedInt(int i): i(i) {}
  int i;
443
  Own<RefcountedInt> addRef() { return kj::addRef(*this); }
444 445 446
};

TEST(Async, ForkRef) {
447
  EventLoop loop;
448
  WaitScope waitScope(loop);
449

450 451 452
  Promise<Own<RefcountedInt>> promise = evalLater([&]() {
    return refcounted<RefcountedInt>(123);
  });
453

454
  auto fork = promise.fork();
455

456
  auto branch1 = fork.addBranch().then([](Own<RefcountedInt>&& i) {
457 458 459
    EXPECT_EQ(123, i->i);
    return 456;
  });
460
  auto branch2 = fork.addBranch().then([](Own<RefcountedInt>&& i) {
461 462
    EXPECT_EQ(123, i->i);
    return 789;
463 464
  });

465 466 467 468
  {
    auto releaseFork = kj::mv(fork);
  }

469 470
  EXPECT_EQ(456, branch1.wait(waitScope));
  EXPECT_EQ(789, branch2.wait(waitScope));
471 472
}

473 474
TEST(Async, ExclusiveJoin) {
  {
475
    EventLoop loop;
476
    WaitScope waitScope(loop);
477

478
    auto left = evalLater([&]() { return 123; });
479 480
    auto right = newPromiseAndFulfiller<int>();  // never fulfilled

481
    EXPECT_EQ(123, left.exclusiveJoin(kj::mv(right.promise)).wait(waitScope));
482 483 484
  }

  {
485
    EventLoop loop;
486
    WaitScope waitScope(loop);
487 488

    auto left = newPromiseAndFulfiller<int>();  // never fulfilled
489
    auto right = evalLater([&]() { return 123; });
490

491
    EXPECT_EQ(123, left.promise.exclusiveJoin(kj::mv(right)).wait(waitScope));
492 493 494
  }

  {
495
    EventLoop loop;
496
    WaitScope waitScope(loop);
497

498 499
    auto left = evalLater([&]() { return 123; });
    auto right = evalLater([&]() { return 456; });
500

501
    EXPECT_EQ(123, left.exclusiveJoin(kj::mv(right)).wait(waitScope));
502 503 504
  }

  {
505
    EventLoop loop;
506
    WaitScope waitScope(loop);
507

508
    auto left = evalLater([&]() { return 123; });
509
    auto right = evalLater([&]() { return 456; }).eagerlyEvaluate(nullptr);
510

511
    EXPECT_EQ(456, left.exclusiveJoin(kj::mv(right)).wait(waitScope));
512 513 514
  }
}

515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
TEST(Async, ArrayJoin) {
  EventLoop loop;
  WaitScope waitScope(loop);

  auto builder = heapArrayBuilder<Promise<int>>(3);
  builder.add(123);
  builder.add(456);
  builder.add(789);

  Promise<Array<int>> promise = joinPromises(builder.finish());

  auto result = promise.wait(waitScope);

  ASSERT_EQ(3u, result.size());
  EXPECT_EQ(123, result[0]);
  EXPECT_EQ(456, result[1]);
  EXPECT_EQ(789, result[2]);
}

534 535 536 537 538 539 540 541 542 543
class ErrorHandlerImpl: public TaskSet::ErrorHandler {
public:
  uint exceptionCount = 0;
  void taskFailed(kj::Exception&& exception) override {
    EXPECT_TRUE(exception.getDescription().endsWith("example TaskSet failure"));
    ++exceptionCount;
  }
};

TEST(Async, TaskSet) {
544
  EventLoop loop;
545
  WaitScope waitScope(loop);
546
  ErrorHandlerImpl errorHandler;
547
  TaskSet tasks(errorHandler);
548 549 550

  int counter = 0;

551
  tasks.add(evalLater([&]() {
552 553
    EXPECT_EQ(0, counter++);
  }));
554
  tasks.add(evalLater([&]() {
555 556 557
    EXPECT_EQ(1, counter++);
    KJ_FAIL_ASSERT("example TaskSet failure") { break; }
  }));
558
  tasks.add(evalLater([&]() {
559 560 561
    EXPECT_EQ(2, counter++);
  }));

562
  (void)evalLater([&]() {
563 564 565
    ADD_FAILURE() << "Promise without waiter shouldn't execute.";
  });

566
  evalLater([&]() {
567
    EXPECT_EQ(3, counter++);
568
  }).wait(waitScope);
569 570

  EXPECT_EQ(4, counter);
571
  EXPECT_EQ(1u, errorHandler.exceptionCount);
572 573
}

574 575 576 577 578 579 580 581 582 583 584 585
class DestructorDetector {
public:
  DestructorDetector(bool& setTrue): setTrue(setTrue) {}
  ~DestructorDetector() { setTrue = true; }

private:
  bool& setTrue;
};

TEST(Async, Attach) {
  bool destroyed = false;

586
  EventLoop loop;
587
  WaitScope waitScope(loop);
588

589
  Promise<int> promise = evalLater([&]() {
590 591
    EXPECT_FALSE(destroyed);
    return 123;
592
  }).attach(kj::heap<DestructorDetector>(destroyed));
593

594
  promise = promise.then([&](int i) {
595 596 597 598 599
    EXPECT_TRUE(destroyed);
    return i + 321;
  });

  EXPECT_FALSE(destroyed);
600
  EXPECT_EQ(444, promise.wait(waitScope));
601 602 603 604 605 606
  EXPECT_TRUE(destroyed);
}

TEST(Async, EagerlyEvaluate) {
  bool called = false;

607
  EventLoop loop;
608
  WaitScope waitScope(loop);
609

610 611 612
  Promise<void> promise = Promise<void>(READY_NOW).then([&]() {
    called = true;
  });
613
  evalLater([]() {}).wait(waitScope);
614 615 616

  EXPECT_FALSE(called);

617
  promise = promise.eagerlyEvaluate(nullptr);
618

619
  evalLater([]() {}).wait(waitScope);
620 621 622 623

  EXPECT_TRUE(called);
}

624
TEST(Async, Detach) {
625
  EventLoop loop;
626
  WaitScope waitScope(loop);
627 628 629 630 631 632

  bool ran1 = false;
  bool ran2 = false;
  bool ran3 = false;

  evalLater([&]() { ran1 = true; });
633
  evalLater([&]() { ran2 = true; }).detach([](kj::Exception&&) { ADD_FAILURE(); });
634
  evalLater([]() { KJ_FAIL_ASSERT("foo"){break;} }).detach([&](kj::Exception&& e) { ran3 = true; });
635 636 637 638 639

  EXPECT_FALSE(ran1);
  EXPECT_FALSE(ran2);
  EXPECT_FALSE(ran3);

640
  evalLater([]() {}).wait(waitScope);
641 642 643 644 645 646

  EXPECT_FALSE(ran1);
  EXPECT_TRUE(ran2);
  EXPECT_TRUE(ran3);
}

647 648 649 650 651
class DummyEventPort: public EventPort {
public:
  bool runnable = false;
  int callCount = 0;

652 653
  bool wait() override { KJ_FAIL_ASSERT("Nothing to wait for."); }
  bool poll() override { return false; }
654
  void setRunnable(bool runnable) override {
655 656 657 658 659 660 661 662
    this->runnable = runnable;
    ++callCount;
  }
};

TEST(Async, SetRunnable) {
  DummyEventPort port;
  EventLoop loop(port);
663
  WaitScope waitScope(loop);
664 665 666 667 668

  EXPECT_FALSE(port.runnable);
  EXPECT_EQ(0, port.callCount);

  {
669
    auto promise = evalLater([]() {}).eagerlyEvaluate(nullptr);
670 671 672 673 674 675

    EXPECT_TRUE(port.runnable);
    loop.run(1);
    EXPECT_FALSE(port.runnable);
    EXPECT_EQ(2, port.callCount);

676
    promise.wait(waitScope);
677 678 679 680 681 682
    EXPECT_FALSE(port.runnable);
    EXPECT_EQ(4, port.callCount);
  }

  {
    auto paf = newPromiseAndFulfiller<void>();
683
    auto promise = paf.promise.then([]() {}).eagerlyEvaluate(nullptr);
684 685
    EXPECT_FALSE(port.runnable);

686
    auto promise2 = evalLater([]() {}).eagerlyEvaluate(nullptr);
687 688 689 690 691 692 693 694
    paf.fulfiller->fulfill();

    EXPECT_TRUE(port.runnable);
    loop.run(1);
    EXPECT_TRUE(port.runnable);
    loop.run(10);
    EXPECT_FALSE(port.runnable);

695
    promise.wait(waitScope);
696 697 698 699 700 701
    EXPECT_FALSE(port.runnable);

    EXPECT_EQ(8, port.callCount);
  }
}

702 703
}  // namespace
}  // namespace kj