async.c++ 24.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "async.h"
#include "debug.h"
26
#include "vector.h"
27
#include "threadlocal.h"
28
#include <exception>
29
#include <map>
30

Kenton Varda's avatar
Kenton Varda committed
31
#if KJ_USE_FUTEX
32 33 34
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/futex.h>
35
#endif
36

37 38
#if !KJ_NO_RTTI
#include <typeinfo>
39 40
#if __GNUC__
#include <cxxabi.h>
41 42
#include <stdlib.h>
#endif
43 44
#endif

45 46 47 48
namespace kj {

namespace {

49
KJ_THREADLOCAL_PTR(EventLoop) threadLocalEventLoop = nullptr;
50

51
#define _kJ_ALREADY_READY reinterpret_cast< ::kj::_::Event*>(1)
52

53 54 55 56 57 58
EventLoop& currentEventLoop() {
  EventLoop* loop = threadLocalEventLoop;
  KJ_REQUIRE(loop != nullptr, "No event loop is running on this thread.");
  return *loop;
}

59
class BoolEvent: public _::Event {
60 61 62
public:
  bool fired = false;

63
  Maybe<Own<_::Event>> fire() override {
64
    fired = true;
65
    return nullptr;
66 67 68
  }
};

69 70
class YieldPromiseNode final: public _::PromiseNode {
public:
Kenton Varda's avatar
Kenton Varda committed
71
  void onReady(_::Event& event) noexcept override {
72
    event.armBreadthFirst();
73 74
  }
  void get(_::ExceptionOrValue& output) noexcept override {
Kenton Varda's avatar
Kenton Varda committed
75
    output.as<_::Void>() = _::Void();
76 77 78
  }
};

79
class NeverDonePromiseNode final: public _::PromiseNode {
80
public:
Kenton Varda's avatar
Kenton Varda committed
81 82
  void onReady(_::Event& event) noexcept override {
    // ignore
83 84 85 86 87 88
  }
  void get(_::ExceptionOrValue& output) noexcept override {
    KJ_FAIL_REQUIRE("Not ready.");
  }
};

89 90
}  // namespace

Kenton Varda's avatar
Kenton Varda committed
91 92 93 94
namespace _ {  // private

class TaskSetImpl {
public:
95 96
  inline TaskSetImpl(TaskSet::ErrorHandler& errorHandler)
    : errorHandler(errorHandler) {}
Kenton Varda's avatar
Kenton Varda committed
97 98 99

  ~TaskSetImpl() noexcept(false) {
    // std::map doesn't like it when elements' destructors throw, so carefully disassemble it.
100 101 102
    if (!tasks.empty()) {
      Vector<Own<Task>> deleteMe(tasks.size());
      for (auto& entry: tasks) {
Kenton Varda's avatar
Kenton Varda committed
103 104 105 106 107
        deleteMe.add(kj::mv(entry.second));
      }
    }
  }

108
  class Task final: public Event {
Kenton Varda's avatar
Kenton Varda committed
109
  public:
110 111
    Task(TaskSetImpl& taskSet, Own<_::PromiseNode>&& nodeParam)
        : taskSet(taskSet), node(kj::mv(nodeParam)) {
112
      node->setSelfPointer(&node);
Kenton Varda's avatar
Kenton Varda committed
113
      node->onReady(*this);
Kenton Varda's avatar
Kenton Varda committed
114 115 116
    }

  protected:
117
    Maybe<Own<Event>> fire() override {
Kenton Varda's avatar
Kenton Varda committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
      // Get the result.
      _::ExceptionOr<_::Void> result;
      node->get(result);

      // Delete the node, catching any exceptions.
      KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
        node = nullptr;
      })) {
        result.addException(kj::mv(*exception));
      }

      // Call the error handler if there was an exception.
      KJ_IF_MAYBE(e, result.exception) {
        taskSet.errorHandler.taskFailed(kj::mv(*e));
      }
133 134 135 136 137 138 139 140 141 142 143

      // Remove from the task map.
      auto iter = taskSet.tasks.find(this);
      KJ_ASSERT(iter != taskSet.tasks.end());
      Own<Event> self = kj::mv(iter->second);
      taskSet.tasks.erase(iter);
      return mv(self);
    }

    _::PromiseNode* getInnerForTrace() override {
      return node;
Kenton Varda's avatar
Kenton Varda committed
144 145 146
    }

  private:
147
    TaskSetImpl& taskSet;
Kenton Varda's avatar
Kenton Varda committed
148 149 150
    kj::Own<_::PromiseNode> node;
  };

151 152
  void add(Promise<void>&& promise) {
    auto task = heap<Task>(*this, kj::mv(promise.node));
Kenton Varda's avatar
Kenton Varda committed
153
    Task* ptr = task;
154 155 156 157 158 159 160 161 162
    tasks.insert(std::make_pair(ptr, kj::mv(task)));
  }

  kj::String trace() {
    kj::Vector<kj::String> traces;
    for (auto& entry: tasks) {
      traces.add(entry.second->trace());
    }
    return kj::strArray(traces, "\n============================================\n");
Kenton Varda's avatar
Kenton Varda committed
163 164 165 166 167
  }

private:
  TaskSet::ErrorHandler& errorHandler;

168
  // TODO(perf):  Use a linked list instead.
169
  std::map<Task*, Own<Task>> tasks;
Kenton Varda's avatar
Kenton Varda committed
170 171 172 173 174 175 176 177 178 179 180 181 182
};

class LoggingErrorHandler: public TaskSet::ErrorHandler {
public:
  static LoggingErrorHandler instance;

  void taskFailed(kj::Exception&& exception) override {
    KJ_LOG(ERROR, "Uncaught exception in daemonized task.", exception);
  }
};

LoggingErrorHandler LoggingErrorHandler::instance = LoggingErrorHandler();

183 184 185 186 187 188 189 190 191 192 193 194 195
class NullEventPort: public EventPort {
public:
  void wait() override {
    KJ_FAIL_REQUIRE("Nothing to wait for; this thread would hang forever.");
  }

  void poll() override {}

  static NullEventPort instance;
};

NullEventPort NullEventPort::instance = NullEventPort();

Kenton Varda's avatar
Kenton Varda committed
196 197 198 199
}  // namespace _ (private)

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

200
void EventPort::setRunnable(bool runnable) {}
201

202 203
EventLoop::EventLoop()
    : port(_::NullEventPort::instance),
204
      daemons(kj::heap<_::TaskSetImpl>(_::LoggingErrorHandler::instance)) {}
205

206 207
EventLoop::EventLoop(EventPort& port)
    : port(port),
208
      daemons(kj::heap<_::TaskSetImpl>(_::LoggingErrorHandler::instance)) {}
Kenton Varda's avatar
Kenton Varda committed
209

210
EventLoop::~EventLoop() noexcept(false) {
211 212 213 214 215 216 217 218 219
  // Destroy all "daemon" tasks, noting that their destructors might try to access the EventLoop
  // some more.
  daemons = nullptr;

  // The application _should_ destroy everything using the EventLoop before destroying the
  // EventLoop itself, so if there are events on the loop, this indicates a memory leak.
  KJ_REQUIRE(head == nullptr, "EventLoop destroyed with events still in the queue.  Memory leak?",
             head->trace()) {
    // Unlink all the events and hope that no one ever fires them...
220
    _::Event* event = head;
221
    while (event != nullptr) {
222
      _::Event* next = event->next;
223 224 225 226 227 228
      event->next = nullptr;
      event->prev = nullptr;
      event = next;
    }
    break;
  }
229 230 231 232 233 234

  KJ_REQUIRE(threadLocalEventLoop != this,
             "EventLoop destroyed while still current for the thread.") {
    threadLocalEventLoop = nullptr;
    break;
  }
235
}
236

237
void EventLoop::run(uint maxTurnCount) {
238 239 240
  running = true;
  KJ_DEFER(running = false);

241 242 243 244 245
  for (uint i = 0; i < maxTurnCount; i++) {
    if (!turn()) {
      break;
    }
  }
246 247

  setRunnable(head != nullptr);
248 249
}

250 251
bool EventLoop::turn() {
  _::Event* event = head;
252

253 254 255 256 257 258 259 260
  if (event == nullptr) {
    // No events in the queue.
    return false;
  } else {
    head = event->next;
    if (head != nullptr) {
      head->prev = &head;
    }
261

262 263 264 265
    depthFirstInsertPoint = &head;
    if (tail == &event->next) {
      tail = &head;
    }
266

267 268
    event->next = nullptr;
    event->prev = nullptr;
269

270 271 272 273 274 275
    Maybe<Own<_::Event>> eventToDestroy;
    {
      event->firing = true;
      KJ_DEFER(event->firing = false);
      eventToDestroy = event->fire();
    }
Kenton Varda's avatar
Kenton Varda committed
276

277 278 279 280
    depthFirstInsertPoint = &head;
    return true;
  }
}
281

282 283 284 285 286 287 288
void EventLoop::setRunnable(bool runnable) {
  if (runnable != lastRunnableState) {
    port.setRunnable(runnable);
    lastRunnableState = runnable;
  }
}

289 290 291 292 293 294 295 296 297 298 299 300 301
void EventLoop::enterScope() {
  KJ_REQUIRE(threadLocalEventLoop == nullptr, "This thread already has an EventLoop.");
  threadLocalEventLoop = this;
}

void EventLoop::leaveScope() {
  KJ_REQUIRE(threadLocalEventLoop == this,
             "WaitScope destroyed in a different thread than it was created in.") {
    break;
  }
  threadLocalEventLoop = nullptr;
}

302
namespace _ {  // private
303

304 305 306
void waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, WaitScope& waitScope) {
  EventLoop& loop = waitScope.loop;
  KJ_REQUIRE(&loop == threadLocalEventLoop, "WaitScope not valid for this thread.");
307
  KJ_REQUIRE(!loop.running, "wait() is not allowed from within event callbacks.");
308

309
  BoolEvent doneEvent;
310
  node->setSelfPointer(&node);
311 312 313 314 315 316 317 318 319 320
  node->onReady(doneEvent);

  loop.running = true;
  KJ_DEFER(loop.running = false);

  while (!doneEvent.fired) {
    if (!loop.turn()) {
      // No events in the queue.  Wait for callback.
      loop.port.wait();
    }
321
  }
322

323 324
  loop.setRunnable(loop.head != nullptr);

325
  node->get(result);
326
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
327 328 329 330
    node = nullptr;
  })) {
    result.addException(kj::mv(*exception));
  }
331 332
}

333
Promise<void> yield() {
334 335 336
  return Promise<void>(false, kj::heap<YieldPromiseNode>());
}

337 338 339 340
Own<PromiseNode> neverDone() {
  return kj::heap<NeverDonePromiseNode>();
}

Kenton Varda's avatar
Kenton Varda committed
341
void NeverDone::wait(WaitScope& waitScope) const {
342 343 344 345 346
  ExceptionOr<Void> dummy;
  waitImpl(neverDone(), dummy, waitScope);
  KJ_UNREACHABLE;
}

347
void detach(kj::Promise<void>&& promise) {
348 349 350
  EventLoop& loop = currentEventLoop();
  KJ_REQUIRE(loop.daemons.get() != nullptr, "EventLoop is shutting down.") { return; }
  loop.daemons->add(kj::mv(promise));
351 352
}

353
Event::Event()
354
    : loop(currentEventLoop()), next(nullptr), prev(nullptr) {}
355

356
Event::~Event() noexcept(false) {
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  if (prev != nullptr) {
    if (loop.tail == &next) {
      loop.tail = prev;
    }
    if (loop.depthFirstInsertPoint == &next) {
      loop.depthFirstInsertPoint = prev;
    }

    *prev = next;
    if (next != nullptr) {
      next->prev = prev;
    }
  }

  KJ_REQUIRE(!firing, "Promise callback destroyed itself.");
  KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
             "Promise destroyed from a different thread than it was created in.");
Kenton Varda's avatar
Kenton Varda committed
374 375
}

376
void Event::armDepthFirst() {
377 378 379
  KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
             "Event armed from different thread than it was created in.  You must use "
             "the thread-safe work queue to queue events cross-thread.");
380

381 382 383 384 385 386 387
  if (prev == nullptr) {
    next = *loop.depthFirstInsertPoint;
    prev = loop.depthFirstInsertPoint;
    *prev = this;
    if (next != nullptr) {
      next->prev = &next;
    }
388

389 390 391 392 393
    loop.depthFirstInsertPoint = &next;

    if (loop.tail == prev) {
      loop.tail = &next;
    }
394 395

    loop.setRunnable(true);
396 397 398
  }
}

399
void Event::armBreadthFirst() {
400 401 402 403 404 405 406 407 408 409 410 411 412
  KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
             "Event armed from different thread than it was created in.  You must use "
             "the thread-safe work queue to queue events cross-thread.");

  if (prev == nullptr) {
    next = *loop.tail;
    prev = loop.tail;
    *prev = this;
    if (next != nullptr) {
      next->prev = &next;
    }

    loop.tail = &next;
413 414

    loop.setRunnable(true);
415 416 417
  }
}

418
_::PromiseNode* Event::getInnerForTrace() {
419 420 421
  return nullptr;
}

422
#if !KJ_NO_RTTI
423 424 425 426
#if __GNUC__
static kj::String demangleTypeName(const char* name) {
  int status;
  char* buf = abi::__cxa_demangle(name, nullptr, nullptr, &status);
427
  kj::String result = kj::heapString(buf == nullptr ? name : buf);
428 429 430 431 432 433 434 435
  free(buf);
  return kj::mv(result);
}
#else
static kj::String demangleTypeName(const char* name) {
  return kj::heapString(name);
}
#endif
436
#endif
437

438
static kj::String traceImpl(Event* event, _::PromiseNode* node) {
439 440 441
#if KJ_NO_RTTI
  return heapString("Trace not available because RTTI is disabled.");
#else
442 443 444 445 446 447 448 449 450 451 452 453
  kj::Vector<kj::String> trace;

  if (event != nullptr) {
    trace.add(demangleTypeName(typeid(*event).name()));
  }

  while (node != nullptr) {
    trace.add(demangleTypeName(typeid(*node).name()));
    node = node->getInnerForTrace();
  }

  return strArray(trace, "\n");
454
#endif
455 456
}

457
kj::String Event::trace() {
458
  return traceImpl(this, getInnerForTrace());
459 460
}

461 462
}  // namespace _ (private)

463 464
// =======================================================================================

465 466
TaskSet::TaskSet(ErrorHandler& errorHandler)
    : impl(heap<_::TaskSetImpl>(errorHandler)) {}
467 468 469

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

470
void TaskSet::add(Promise<void>&& promise) {
471 472 473
  impl->add(kj::mv(promise));
}

474 475 476 477
kj::String TaskSet::trace() {
  return impl->trace();
}

478 479
namespace _ {  // private

480 481 482 483
kj::String PromiseBase::trace() {
  return traceImpl(nullptr, node);
}

484 485
void PromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {}

486
PromiseNode* PromiseNode::getInnerForTrace() { return nullptr; }
487

Kenton Varda's avatar
Kenton Varda committed
488
void PromiseNode::OnReadyEvent::init(Event& newEvent) {
489
  if (event == _kJ_ALREADY_READY) {
Kenton Varda's avatar
Kenton Varda committed
490 491 492 493
    // A new continuation was added to a promise that was already ready.  In this case, we schedule
    // breadth-first, to make it difficult for applications to accidentally starve the event loop
    // by repeatedly waiting on immediate promises.
    newEvent.armBreadthFirst();
494 495
  } else {
    event = &newEvent;
496 497 498
  }
}

499 500 501 502
void PromiseNode::OnReadyEvent::arm() {
  if (event == nullptr) {
    event = _kJ_ALREADY_READY;
  } else {
Kenton Varda's avatar
Kenton Varda committed
503 504 505
    // A promise resolved and an event is already waiting on it.  In this case, arm in depth-first
    // order so that the event runs immediately after the current one.  This way, chained promises
    // execute together for better cache locality and lower latency.
506
    event->armDepthFirst();
507 508 509
  }
}

510 511
// -------------------------------------------------------------------

512 513 514
ImmediatePromiseNodeBase::ImmediatePromiseNodeBase() {}
ImmediatePromiseNodeBase::~ImmediatePromiseNodeBase() noexcept(false) {}

Kenton Varda's avatar
Kenton Varda committed
515 516 517
void ImmediatePromiseNodeBase::onReady(Event& event) noexcept {
  event.armBreadthFirst();
}
518 519 520 521 522 523 524 525

ImmediateBrokenPromiseNode::ImmediateBrokenPromiseNode(Exception&& exception)
    : exception(kj::mv(exception)) {}

void ImmediateBrokenPromiseNode::get(ExceptionOrValue& output) noexcept {
  output.exception = kj::mv(exception);
}

526 527
// -------------------------------------------------------------------

528 529 530 531
AttachmentPromiseNodeBase::AttachmentPromiseNodeBase(Own<PromiseNode>&& dependencyParam)
    : dependency(kj::mv(dependencyParam)) {
  dependency->setSelfPointer(&dependency);
}
532

Kenton Varda's avatar
Kenton Varda committed
533 534
void AttachmentPromiseNodeBase::onReady(Event& event) noexcept {
  dependency->onReady(event);
535 536 537 538 539 540
}

void AttachmentPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
  dependency->get(output);
}

541 542
PromiseNode* AttachmentPromiseNodeBase::getInnerForTrace() {
  return dependency;
543 544 545 546 547 548 549 550
}

void AttachmentPromiseNodeBase::dropDependency() {
  dependency = nullptr;
}

// -------------------------------------------------------------------

551 552 553 554
TransformPromiseNodeBase::TransformPromiseNodeBase(Own<PromiseNode>&& dependencyParam)
    : dependency(kj::mv(dependencyParam)) {
  dependency->setSelfPointer(&dependency);
}
555

Kenton Varda's avatar
Kenton Varda committed
556 557
void TransformPromiseNodeBase::onReady(Event& event) noexcept {
  dependency->onReady(event);
558 559 560 561 562
}

void TransformPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
    getImpl(output);
563
    dropDependency();
564 565 566 567 568
  })) {
    output.addException(kj::mv(*exception));
  }
}

569 570
PromiseNode* TransformPromiseNodeBase::getInnerForTrace() {
  return dependency;
571 572
}

573 574 575 576
void TransformPromiseNodeBase::dropDependency() {
  dependency = nullptr;
}

577 578 579 580 581 582 583 584 585
void TransformPromiseNodeBase::getDepResult(ExceptionOrValue& output) {
  dependency->get(output);
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
    dependency = nullptr;
  })) {
    output.addException(kj::mv(*exception));
  }
}

586 587
// -------------------------------------------------------------------

588
ForkBranchBase::ForkBranchBase(Own<ForkHubBase>&& hubParam): hub(kj::mv(hubParam)) {
589
  if (hub->tailBranch == nullptr) {
590
    onReadyEvent.arm();
591 592
  } else {
    // Insert into hub's linked list of branches.
593
    prevPtr = hub->tailBranch;
594 595
    *prevPtr = this;
    next = nullptr;
596
    hub->tailBranch = &next;
597 598 599
  }
}

Kenton Varda's avatar
Kenton Varda committed
600
ForkBranchBase::~ForkBranchBase() noexcept(false) {
601 602 603
  if (prevPtr != nullptr) {
    // Remove from hub's linked list of branches.
    *prevPtr = next;
604
    (next == nullptr ? hub->tailBranch : next->prevPtr) = prevPtr;
605 606 607 608
  }
}

void ForkBranchBase::hubReady() noexcept {
609
  onReadyEvent.arm();
610 611 612 613
}

void ForkBranchBase::releaseHub(ExceptionOrValue& output) {
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
614
    hub = nullptr;
615 616 617 618 619
  })) {
    output.addException(kj::mv(*exception));
  }
}

Kenton Varda's avatar
Kenton Varda committed
620 621
void ForkBranchBase::onReady(Event& event) noexcept {
  onReadyEvent.init(event);
622 623
}

624 625
PromiseNode* ForkBranchBase::getInnerForTrace() {
  return hub->getInnerForTrace();
626 627 628 629
}

// -------------------------------------------------------------------

630 631
ForkHubBase::ForkHubBase(Own<PromiseNode>&& innerParam, ExceptionOrValue& resultRef)
    : inner(kj::mv(innerParam)), resultRef(resultRef) {
632
  inner->setSelfPointer(&inner);
Kenton Varda's avatar
Kenton Varda committed
633
  inner->onReady(*this);
634
}
635

636
Maybe<Own<Event>> ForkHubBase::fire() {
637 638 639 640 641 642 643
  // Dependency is ready.  Fetch its result and then delete the node.
  inner->get(resultRef);
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
    inner = nullptr;
  })) {
    resultRef.addException(kj::mv(*exception));
  }
644

645
  for (auto branch = headBranch; branch != nullptr; branch = branch->next) {
646 647 648
    branch->hubReady();
    *branch->prevPtr = nullptr;
    branch->prevPtr = nullptr;
649
  }
650
  *tailBranch = nullptr;
651 652

  // Indicate that the list is no longer active.
653
  tailBranch = nullptr;
654 655 656 657 658 659

  return nullptr;
}

_::PromiseNode* ForkHubBase::getInnerForTrace() {
  return inner;
660 661 662 663
}

// -------------------------------------------------------------------

664 665
ChainPromiseNode::ChainPromiseNode(Own<PromiseNode> innerParam)
    : state(STEP1), inner(kj::mv(innerParam)) {
666
  inner->setSelfPointer(&inner);
Kenton Varda's avatar
Kenton Varda committed
667
  inner->onReady(*this);
668 669
}

670
ChainPromiseNode::~ChainPromiseNode() noexcept(false) {}
671

Kenton Varda's avatar
Kenton Varda committed
672
void ChainPromiseNode::onReady(Event& event) noexcept {
673 674
  switch (state) {
    case STEP1:
675
      KJ_REQUIRE(onReadyEvent == nullptr, "onReady() can only be called once.");
676
      onReadyEvent = &event;
Kenton Varda's avatar
Kenton Varda committed
677
      return;
678
    case STEP2:
Kenton Varda's avatar
Kenton Varda committed
679 680
      inner->onReady(event);
      return;
681 682 683 684
  }
  KJ_UNREACHABLE;
}

685 686 687 688 689 690 691 692 693
void ChainPromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {
  if (state == STEP2) {
    *selfPtr = kj::mv(inner);  // deletes this!
    selfPtr->get()->setSelfPointer(selfPtr);
  } else {
    this->selfPtr = selfPtr;
  }
}

694
void ChainPromiseNode::get(ExceptionOrValue& output) noexcept {
695
  KJ_REQUIRE(state == STEP2);
696 697 698
  return inner->get(output);
}

699 700
PromiseNode* ChainPromiseNode::getInnerForTrace() {
  return inner;
701 702
}

703
Maybe<Own<Event>> ChainPromiseNode::fire() {
704
  KJ_REQUIRE(state != STEP2);
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

  static_assert(sizeof(Promise<int>) == sizeof(PromiseBase),
      "This code assumes Promise<T> does not add any new members to PromiseBase.");

  ExceptionOr<PromiseBase> intermediate;
  inner->get(intermediate);

  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
    inner = nullptr;
  })) {
    intermediate.addException(kj::mv(*exception));
  }

  KJ_IF_MAYBE(exception, intermediate.exception) {
    // There is an exception.  If there is also a value, delete it.
    kj::runCatchingExceptions([&,this]() { intermediate.value = nullptr; });
    // Now set step2 to a rejected promise.
    inner = heap<ImmediateBrokenPromiseNode>(kj::mv(*exception));
  } else KJ_IF_MAYBE(value, intermediate.value) {
    // There is a value and no exception.  The value is itself a promise.  Adopt it as our
    // step2.
    inner = kj::mv(value->node);
  } else {
    // We can only get here if inner->get() returned neither an exception nor a
    // value, which never actually happens.
730
    KJ_FAIL_ASSERT("Inner node returned empty value.");
731 732 733
  }
  state = STEP2;

734 735 736 737 738 739 740 741
  if (selfPtr != nullptr) {
    // Hey, we can shorten the chain here.
    auto chain = selfPtr->downcast<ChainPromiseNode>();
    *selfPtr = kj::mv(inner);
    selfPtr->get()->setSelfPointer(selfPtr);
    if (onReadyEvent != nullptr) {
      selfPtr->get()->onReady(*onReadyEvent);
    }
742

743 744 745 746 747 748 749 750 751 752
    // Return our self-pointer so that the caller takes care of deleting it.
    return Own<Event>(kj::mv(chain));
  } else {
    inner->setSelfPointer(&inner);
    if (onReadyEvent != nullptr) {
      inner->onReady(*onReadyEvent);
    }

    return nullptr;
  }
753 754
}

755 756
// -------------------------------------------------------------------

757 758
ExclusiveJoinPromiseNode::ExclusiveJoinPromiseNode(Own<PromiseNode> left, Own<PromiseNode> right)
    : left(*this, kj::mv(left)), right(*this, kj::mv(right)) {}
759 760 761

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

Kenton Varda's avatar
Kenton Varda committed
762 763
void ExclusiveJoinPromiseNode::onReady(Event& event) noexcept {
  onReadyEvent.init(event);
764 765 766
}

void ExclusiveJoinPromiseNode::get(ExceptionOrValue& output) noexcept {
767
  KJ_REQUIRE(left.get(output) || right.get(output), "get() called before ready.");
768 769
}

770 771 772 773 774 775
PromiseNode* ExclusiveJoinPromiseNode::getInnerForTrace() {
  auto result = left.getInnerForTrace();
  if (result == nullptr) {
    result = right.getInnerForTrace();
  }
  return result;
776 777 778
}

ExclusiveJoinPromiseNode::Branch::Branch(
779 780
    ExclusiveJoinPromiseNode& joinNode, Own<PromiseNode> dependencyParam)
    : joinNode(joinNode), dependency(kj::mv(dependencyParam)) {
781
  dependency->setSelfPointer(&dependency);
Kenton Varda's avatar
Kenton Varda committed
782
  dependency->onReady(*this);
783 784
}

785
ExclusiveJoinPromiseNode::Branch::~Branch() noexcept(false) {}
786 787

bool ExclusiveJoinPromiseNode::Branch::get(ExceptionOrValue& output) {
788
  if (dependency) {
789 790 791 792 793 794 795
    dependency->get(output);
    return true;
  } else {
    return false;
  }
}

796
Maybe<Own<Event>> ExclusiveJoinPromiseNode::Branch::fire() {
797 798 799
  // Cancel the branch that didn't return first.  Ignore exceptions caused by cancellation.
  if (this == &joinNode.left) {
    kj::runCatchingExceptions([&]() { joinNode.right.dependency = nullptr; });
800
  } else {
801 802
    kj::runCatchingExceptions([&]() { joinNode.left.dependency = nullptr; });
  }
803

804 805 806
  joinNode.onReadyEvent.arm();
  return nullptr;
}
807

808 809
PromiseNode* ExclusiveJoinPromiseNode::Branch::getInnerForTrace() {
  return dependency;
810 811 812 813
}

// -------------------------------------------------------------------

814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
ArrayJoinPromiseNodeBase::ArrayJoinPromiseNodeBase(
    Array<Own<PromiseNode>> promises, ExceptionOrValue* resultParts, size_t partSize)
    : countLeft(promises.size()) {
  // Make the branches.
  auto builder = heapArrayBuilder<Branch>(promises.size());
  for (uint i: indices(promises)) {
    ExceptionOrValue& output = *reinterpret_cast<ExceptionOrValue*>(
        reinterpret_cast<byte*>(resultParts) + i * partSize);
    builder.add(*this, kj::mv(promises[i]), output);
  }
  branches = builder.finish();

  if (branches.size() == 0) {
    onReadyEvent.arm();
  }
}
ArrayJoinPromiseNodeBase::~ArrayJoinPromiseNodeBase() noexcept(false) {}

void ArrayJoinPromiseNodeBase::onReady(Event& event) noexcept {
  onReadyEvent.init(event);
}

void ArrayJoinPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
  // If any of the elements threw exceptions, propagate them.
  for (auto& branch: branches) {
    KJ_IF_MAYBE(exception, branch.getPart()) {
      output.addException(kj::mv(*exception));
    }
  }

  if (output.exception == nullptr) {
    // No errors.  The template subclass will need to fill in the result.
    getNoError(output);
  }
}

PromiseNode* ArrayJoinPromiseNodeBase::getInnerForTrace() {
  return branches.size() == 0 ? nullptr : branches[0].getInnerForTrace();
}

ArrayJoinPromiseNodeBase::Branch::Branch(
    ArrayJoinPromiseNodeBase& joinNode, Own<PromiseNode> dependencyParam, ExceptionOrValue& output)
    : joinNode(joinNode), dependency(kj::mv(dependencyParam)), output(output) {
  dependency->setSelfPointer(&dependency);
  dependency->onReady(*this);
}

ArrayJoinPromiseNodeBase::Branch::~Branch() noexcept(false) {}

Maybe<Own<Event>> ArrayJoinPromiseNodeBase::Branch::fire() {
  if (--joinNode.countLeft == 0) {
    joinNode.onReadyEvent.arm();
  }
  return nullptr;
}

_::PromiseNode* ArrayJoinPromiseNodeBase::Branch::getInnerForTrace() {
  return dependency->getInnerForTrace();
}

Maybe<Exception> ArrayJoinPromiseNodeBase::Branch::getPart() {
  dependency->get(output);
  return kj::mv(output.exception);
}

// -------------------------------------------------------------------

881 882 883
EagerPromiseNodeBase::EagerPromiseNodeBase(
    Own<PromiseNode>&& dependencyParam, ExceptionOrValue& resultRef)
    : dependency(kj::mv(dependencyParam)), resultRef(resultRef) {
884
  dependency->setSelfPointer(&dependency);
Kenton Varda's avatar
Kenton Varda committed
885
  dependency->onReady(*this);
886 887
}

Kenton Varda's avatar
Kenton Varda committed
888 889
void EagerPromiseNodeBase::onReady(Event& event) noexcept {
  onReadyEvent.init(event);
890 891
}

892 893
PromiseNode* EagerPromiseNodeBase::getInnerForTrace() {
  return dependency;
894 895
}

896
Maybe<Own<Event>> EagerPromiseNodeBase::fire() {
897 898 899 900 901
  dependency->get(resultRef);
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
    dependency = nullptr;
  })) {
    resultRef.addException(kj::mv(*exception));
902
  }
903 904 905

  onReadyEvent.arm();
  return nullptr;
906 907
}

908 909
// -------------------------------------------------------------------

Kenton Varda's avatar
Kenton Varda committed
910 911
void AdapterPromiseNodeBase::onReady(Event& event) noexcept {
  onReadyEvent.init(event);
912 913 914
}

}  // namespace _ (private)
915
}  // namespace kj