async.c++ 27.2 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 "async.h"
#include "debug.h"
24
#include "vector.h"
25
#include "threadlocal.h"
26

Kenton Varda's avatar
Kenton Varda committed
27
#if KJ_USE_FUTEX
28 29 30
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/futex.h>
31
#endif
32

33 34
#if !KJ_NO_RTTI
#include <typeinfo>
35 36
#if __GNUC__
#include <cxxabi.h>
37 38
#include <stdlib.h>
#endif
39 40
#endif

41 42 43 44
namespace kj {

namespace {

45
KJ_THREADLOCAL_PTR(EventLoop) threadLocalEventLoop = nullptr;
46

47
#define _kJ_ALREADY_READY reinterpret_cast< ::kj::_::Event*>(1)
48

49 50 51 52 53 54
EventLoop& currentEventLoop() {
  EventLoop* loop = threadLocalEventLoop;
  KJ_REQUIRE(loop != nullptr, "No event loop is running on this thread.");
  return *loop;
}

55
class BoolEvent: public _::Event {
56 57 58
public:
  bool fired = false;

59
  Maybe<Own<_::Event>> fire() override {
60
    fired = true;
61
    return nullptr;
62 63 64
  }
};

65 66
class YieldPromiseNode final: public _::PromiseNode {
public:
67 68
  void onReady(_::Event* event) noexcept override {
    if (event) event->armBreadthFirst();
69 70
  }
  void get(_::ExceptionOrValue& output) noexcept override {
Kenton Varda's avatar
Kenton Varda committed
71
    output.as<_::Void>() = _::Void();
72 73 74
  }
};

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

85 86
}  // namespace

87 88 89 90
TaskSet::TaskSet(TaskSet::ErrorHandler& errorHandler)
  : errorHandler(errorHandler) {}

TaskSet::~TaskSet() noexcept(false) {}
Kenton Varda's avatar
Kenton Varda committed
91

92
class TaskSet::Task final: public _::Event {
Kenton Varda's avatar
Kenton Varda committed
93
public:
94 95 96 97
  Task(TaskSet& taskSet, Own<_::PromiseNode>&& nodeParam)
      : taskSet(taskSet), node(kj::mv(nodeParam)) {
    node->setSelfPointer(&node);
    node->onReady(this);
Kenton Varda's avatar
Kenton Varda committed
98 99
  }

100 101
  Maybe<Own<Task>> next;
  Maybe<Own<Task>>* prev = nullptr;
Kenton Varda's avatar
Kenton Varda committed
102

103 104 105 106 107
protected:
  Maybe<Own<Event>> fire() override {
    // Get the result.
    _::ExceptionOr<_::Void> result;
    node->get(result);
Kenton Varda's avatar
Kenton Varda committed
108

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

116 117 118
    // Call the error handler if there was an exception.
    KJ_IF_MAYBE(e, result.exception) {
      taskSet.errorHandler.taskFailed(kj::mv(*e));
119 120
    }

121 122 123
    // Remove from the task list.
    KJ_IF_MAYBE(n, next) {
      n->get()->prev = prev;
Kenton Varda's avatar
Kenton Varda committed
124
    }
125 126 127 128 129
    Own<Event> self = kj::mv(KJ_ASSERT_NONNULL(*prev));
    KJ_ASSERT(self.get() == this);
    *prev = kj::mv(next);
    next = nullptr;
    prev = nullptr;
130 131 132 133 134 135 136 137

    KJ_IF_MAYBE(f, taskSet.emptyFulfiller) {
      if (taskSet.tasks == nullptr) {
        f->get()->fulfill();
        taskSet.emptyFulfiller = nullptr;
      }
    }

138 139 140 141 142 143
    return mv(self);
  }

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

145 146 147 148
private:
  TaskSet& taskSet;
  Own<_::PromiseNode> node;
};
Kenton Varda's avatar
Kenton Varda committed
149

150 151 152 153 154
void TaskSet::add(Promise<void>&& promise) {
  auto task = heap<Task>(*this, kj::mv(promise.node));
  KJ_IF_MAYBE(head, tasks) {
    head->get()->prev = &task->next;
    task->next = kj::mv(tasks);
155
  }
156 157 158
  task->prev = &tasks;
  tasks = kj::mv(task);
}
159

160 161 162 163 164 165 166 167 168 169
kj::String TaskSet::trace() {
  kj::Vector<kj::String> traces;

  Maybe<Own<Task>>* ptr = &tasks;
  for (;;) {
    KJ_IF_MAYBE(task, *ptr) {
      traces.add(task->get()->trace());
      ptr = &task->get()->next;
    } else {
      break;
170
    }
Kenton Varda's avatar
Kenton Varda committed
171 172
  }

173 174
  return kj::strArray(traces, "\n============================================\n");
}
Kenton Varda's avatar
Kenton Varda committed
175

176 177 178 179 180 181 182 183 184 185 186 187
Promise<void> TaskSet::onEmpty() {
  KJ_REQUIRE(emptyFulfiller == nullptr, "onEmpty() can only be called once at a time");

  if (tasks == nullptr) {
    return READY_NOW;
  } else {
    auto paf = newPromiseAndFulfiller<void>();
    emptyFulfiller = kj::mv(paf.fulfiller);
    return kj::mv(paf.promise);
  }
}

188
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
189 190 191 192 193 194 195 196 197 198 199 200

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();

201 202
class NullEventPort: public EventPort {
public:
203
  bool wait() override {
204 205 206
    KJ_FAIL_REQUIRE("Nothing to wait for; this thread would hang forever.");
  }

207 208 209
  bool poll() override { return false; }

  void wake() const override {
210
    // TODO(someday): Implement using condvar.
211 212 213
    kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED,
        "Cross-thread events are not yet implemented for EventLoops with no EventPort."));
  }
214 215 216 217 218 219

  static NullEventPort instance;
};

NullEventPort NullEventPort::instance = NullEventPort();

Kenton Varda's avatar
Kenton Varda committed
220 221 222 223
}  // namespace _ (private)

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

224
void EventPort::setRunnable(bool runnable) {}
225

226 227 228 229 230
void EventPort::wake() const {
  kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED,
      "cross-thread wake() not implemented by this EventPort implementation"));
}

231 232
EventLoop::EventLoop()
    : port(_::NullEventPort::instance),
233
      daemons(kj::heap<TaskSet>(_::LoggingErrorHandler::instance)) {}
234

235 236
EventLoop::EventLoop(EventPort& port)
    : port(port),
237
      daemons(kj::heap<TaskSet>(_::LoggingErrorHandler::instance)) {}
Kenton Varda's avatar
Kenton Varda committed
238

239
EventLoop::~EventLoop() noexcept(false) {
240 241 242 243 244 245 246 247 248
  // 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...
249
    _::Event* event = head;
250
    while (event != nullptr) {
251
      _::Event* next = event->next;
252 253 254 255 256 257
      event->next = nullptr;
      event->prev = nullptr;
      event = next;
    }
    break;
  }
258 259 260 261 262 263

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

266
void EventLoop::run(uint maxTurnCount) {
267 268 269
  running = true;
  KJ_DEFER(running = false);

270 271 272 273 274
  for (uint i = 0; i < maxTurnCount; i++) {
    if (!turn()) {
      break;
    }
  }
275

276
  setRunnable(isRunnable());
277 278
}

279 280
bool EventLoop::turn() {
  _::Event* event = head;
281

282 283 284 285 286 287 288 289
  if (event == nullptr) {
    // No events in the queue.
    return false;
  } else {
    head = event->next;
    if (head != nullptr) {
      head->prev = &head;
    }
290

291 292 293 294
    depthFirstInsertPoint = &head;
    if (tail == &event->next) {
      tail = &head;
    }
295

296 297
    event->next = nullptr;
    event->prev = nullptr;
298

299 300 301 302 303 304
    Maybe<Own<_::Event>> eventToDestroy;
    {
      event->firing = true;
      KJ_DEFER(event->firing = false);
      eventToDestroy = event->fire();
    }
Kenton Varda's avatar
Kenton Varda committed
305

306 307 308 309
    depthFirstInsertPoint = &head;
    return true;
  }
}
310

311 312 313 314
bool EventLoop::isRunnable() {
  return head != nullptr;
}

315 316 317 318 319 320 321
void EventLoop::setRunnable(bool runnable) {
  if (runnable != lastRunnableState) {
    port.setRunnable(runnable);
    lastRunnableState = runnable;
  }
}

322 323 324 325 326 327 328 329 330 331 332 333 334
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;
}

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
void WaitScope::poll() {
  KJ_REQUIRE(&loop == threadLocalEventLoop, "WaitScope not valid for this thread.");
  KJ_REQUIRE(!loop.running, "poll() is not allowed from within event callbacks.");

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

  for (;;) {
    if (!loop.turn()) {
      // No events in the queue.  Poll for I/O.
      loop.port.poll();

      if (!loop.isRunnable()) {
        // Still no events in the queue. We're done.
        return;
      }
    }
  }
}

355
namespace _ {  // private
356

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

362
  BoolEvent doneEvent;
363
  node->setSelfPointer(&node);
364
  node->onReady(&doneEvent);
365 366 367 368 369 370 371 372 373

  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();
    }
374
  }
375

376
  loop.setRunnable(loop.isRunnable());
377

378
  node->get(result);
379
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
380 381 382 383
    node = nullptr;
  })) {
    result.addException(kj::mv(*exception));
  }
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 412 413 414
bool pollImpl(_::PromiseNode& node, WaitScope& waitScope) {
  EventLoop& loop = waitScope.loop;
  KJ_REQUIRE(&loop == threadLocalEventLoop, "WaitScope not valid for this thread.");
  KJ_REQUIRE(!loop.running, "poll() is not allowed from within event callbacks.");

  BoolEvent doneEvent;
  node.onReady(&doneEvent);

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

  while (!doneEvent.fired) {
    if (!loop.turn()) {
      // No events in the queue.  Poll for I/O.
      loop.port.poll();

      if (!doneEvent.fired && !loop.isRunnable()) {
        // No progress. Give up.
        node.onReady(nullptr);
        loop.setRunnable(false);
        return false;
      }
    }
  }

  loop.setRunnable(loop.isRunnable());
  return true;
}

415
Promise<void> yield() {
416 417 418
  return Promise<void>(false, kj::heap<YieldPromiseNode>());
}

419 420 421 422
Own<PromiseNode> neverDone() {
  return kj::heap<NeverDonePromiseNode>();
}

Kenton Varda's avatar
Kenton Varda committed
423
void NeverDone::wait(WaitScope& waitScope) const {
424 425 426 427 428
  ExceptionOr<Void> dummy;
  waitImpl(neverDone(), dummy, waitScope);
  KJ_UNREACHABLE;
}

429
void detach(kj::Promise<void>&& promise) {
430 431 432
  EventLoop& loop = currentEventLoop();
  KJ_REQUIRE(loop.daemons.get() != nullptr, "EventLoop is shutting down.") { return; }
  loop.daemons->add(kj::mv(promise));
433 434
}

435
Event::Event()
436
    : loop(currentEventLoop()), next(nullptr), prev(nullptr) {}
437

438
Event::~Event() noexcept(false) {
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  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
456 457
}

458
void Event::armDepthFirst() {
459 460 461
  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.");
462

463 464 465 466 467 468 469
  if (prev == nullptr) {
    next = *loop.depthFirstInsertPoint;
    prev = loop.depthFirstInsertPoint;
    *prev = this;
    if (next != nullptr) {
      next->prev = &next;
    }
470

471 472 473 474 475
    loop.depthFirstInsertPoint = &next;

    if (loop.tail == prev) {
      loop.tail = &next;
    }
476 477

    loop.setRunnable(true);
478 479 480
  }
}

481
void Event::armBreadthFirst() {
482 483 484 485 486 487 488 489 490 491 492 493 494
  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;
495 496

    loop.setRunnable(true);
497 498 499
  }
}

500
_::PromiseNode* Event::getInnerForTrace() {
501 502 503
  return nullptr;
}

504
#if !KJ_NO_RTTI
505 506 507 508
#if __GNUC__
static kj::String demangleTypeName(const char* name) {
  int status;
  char* buf = abi::__cxa_demangle(name, nullptr, nullptr, &status);
509
  kj::String result = kj::heapString(buf == nullptr ? name : buf);
510 511 512 513 514 515 516 517
  free(buf);
  return kj::mv(result);
}
#else
static kj::String demangleTypeName(const char* name) {
  return kj::heapString(name);
}
#endif
518
#endif
519

520
static kj::String traceImpl(Event* event, _::PromiseNode* node) {
521 522 523
#if KJ_NO_RTTI
  return heapString("Trace not available because RTTI is disabled.");
#else
524 525 526 527 528 529 530 531 532 533 534 535
  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");
536
#endif
537 538
}

539
kj::String Event::trace() {
540
  return traceImpl(this, getInnerForTrace());
541 542
}

543 544
}  // namespace _ (private)

545 546
// =======================================================================================

547 548
namespace _ {  // private

549 550 551 552
kj::String PromiseBase::trace() {
  return traceImpl(nullptr, node);
}

553 554
void PromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {}

555
PromiseNode* PromiseNode::getInnerForTrace() { return nullptr; }
556

557
void PromiseNode::OnReadyEvent::init(Event* newEvent) {
558
  if (event == _kJ_ALREADY_READY) {
Kenton Varda's avatar
Kenton Varda committed
559 560 561
    // 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.
562
    if (newEvent) newEvent->armBreadthFirst();
563
  } else {
564
    event = newEvent;
565 566 567
  }
}

568
void PromiseNode::OnReadyEvent::arm() {
569 570 571
  KJ_ASSERT(event != _kJ_ALREADY_READY, "arm() should only be called once");

  if (event != nullptr) {
Kenton Varda's avatar
Kenton Varda committed
572 573 574
    // 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.
575
    event->armDepthFirst();
576
  }
577 578

  event = _kJ_ALREADY_READY;
579 580
}

581 582
// -------------------------------------------------------------------

583 584 585
ImmediatePromiseNodeBase::ImmediatePromiseNodeBase() {}
ImmediatePromiseNodeBase::~ImmediatePromiseNodeBase() noexcept(false) {}

586 587
void ImmediatePromiseNodeBase::onReady(Event* event) noexcept {
  if (event) event->armBreadthFirst();
Kenton Varda's avatar
Kenton Varda committed
588
}
589 590 591 592 593 594 595 596

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

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

597 598
// -------------------------------------------------------------------

599 600 601 602
AttachmentPromiseNodeBase::AttachmentPromiseNodeBase(Own<PromiseNode>&& dependencyParam)
    : dependency(kj::mv(dependencyParam)) {
  dependency->setSelfPointer(&dependency);
}
603

604
void AttachmentPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
605
  dependency->onReady(event);
606 607 608 609 610 611
}

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

612 613
PromiseNode* AttachmentPromiseNodeBase::getInnerForTrace() {
  return dependency;
614 615 616 617 618 619 620 621
}

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

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

Kenton Varda's avatar
Kenton Varda committed
622 623 624
TransformPromiseNodeBase::TransformPromiseNodeBase(
    Own<PromiseNode>&& dependencyParam, void* continuationTracePtr)
    : dependency(kj::mv(dependencyParam)), continuationTracePtr(continuationTracePtr) {
625 626
  dependency->setSelfPointer(&dependency);
}
627

628
void TransformPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
629
  dependency->onReady(event);
630 631 632 633 634
}

void TransformPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
    getImpl(output);
635
    dropDependency();
636 637 638 639 640
  })) {
    output.addException(kj::mv(*exception));
  }
}

641 642
PromiseNode* TransformPromiseNodeBase::getInnerForTrace() {
  return dependency;
643 644
}

645 646 647 648
void TransformPromiseNodeBase::dropDependency() {
  dependency = nullptr;
}

649 650 651 652 653 654 655
void TransformPromiseNodeBase::getDepResult(ExceptionOrValue& output) {
  dependency->get(output);
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
    dependency = nullptr;
  })) {
    output.addException(kj::mv(*exception));
  }
Kenton Varda's avatar
Kenton Varda committed
656 657 658 659

  KJ_IF_MAYBE(e, output.exception) {
    e->addTrace(continuationTracePtr);
  }
660 661
}

662 663
// -------------------------------------------------------------------

664
ForkBranchBase::ForkBranchBase(Own<ForkHubBase>&& hubParam): hub(kj::mv(hubParam)) {
665
  if (hub->tailBranch == nullptr) {
666
    onReadyEvent.arm();
667 668
  } else {
    // Insert into hub's linked list of branches.
669
    prevPtr = hub->tailBranch;
670 671
    *prevPtr = this;
    next = nullptr;
672
    hub->tailBranch = &next;
673 674 675
  }
}

Kenton Varda's avatar
Kenton Varda committed
676
ForkBranchBase::~ForkBranchBase() noexcept(false) {
677 678 679
  if (prevPtr != nullptr) {
    // Remove from hub's linked list of branches.
    *prevPtr = next;
680
    (next == nullptr ? hub->tailBranch : next->prevPtr) = prevPtr;
681 682 683 684
  }
}

void ForkBranchBase::hubReady() noexcept {
685
  onReadyEvent.arm();
686 687 688 689
}

void ForkBranchBase::releaseHub(ExceptionOrValue& output) {
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
690
    hub = nullptr;
691 692 693 694 695
  })) {
    output.addException(kj::mv(*exception));
  }
}

696
void ForkBranchBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
697
  onReadyEvent.init(event);
698 699
}

700 701
PromiseNode* ForkBranchBase::getInnerForTrace() {
  return hub->getInnerForTrace();
702 703 704 705
}

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

706 707
ForkHubBase::ForkHubBase(Own<PromiseNode>&& innerParam, ExceptionOrValue& resultRef)
    : inner(kj::mv(innerParam)), resultRef(resultRef) {
708
  inner->setSelfPointer(&inner);
709
  inner->onReady(this);
710
}
711

712
Maybe<Own<Event>> ForkHubBase::fire() {
713 714 715 716 717 718 719
  // 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));
  }
720

721
  for (auto branch = headBranch; branch != nullptr; branch = branch->next) {
722 723 724
    branch->hubReady();
    *branch->prevPtr = nullptr;
    branch->prevPtr = nullptr;
725
  }
726
  *tailBranch = nullptr;
727 728

  // Indicate that the list is no longer active.
729
  tailBranch = nullptr;
730 731 732 733 734 735

  return nullptr;
}

_::PromiseNode* ForkHubBase::getInnerForTrace() {
  return inner;
736 737 738 739
}

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

740 741
ChainPromiseNode::ChainPromiseNode(Own<PromiseNode> innerParam)
    : state(STEP1), inner(kj::mv(innerParam)) {
742
  inner->setSelfPointer(&inner);
743
  inner->onReady(this);
744 745
}

746
ChainPromiseNode::~ChainPromiseNode() noexcept(false) {}
747

748
void ChainPromiseNode::onReady(Event* event) noexcept {
749 750
  switch (state) {
    case STEP1:
751
      KJ_REQUIRE(onReadyEvent == nullptr, "onReady() can only be called once.");
752
      onReadyEvent = event;
Kenton Varda's avatar
Kenton Varda committed
753
      return;
754
    case STEP2:
Kenton Varda's avatar
Kenton Varda committed
755 756
      inner->onReady(event);
      return;
757 758 759 760
  }
  KJ_UNREACHABLE;
}

761 762 763 764 765 766 767 768 769
void ChainPromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {
  if (state == STEP2) {
    *selfPtr = kj::mv(inner);  // deletes this!
    selfPtr->get()->setSelfPointer(selfPtr);
  } else {
    this->selfPtr = selfPtr;
  }
}

770
void ChainPromiseNode::get(ExceptionOrValue& output) noexcept {
771
  KJ_REQUIRE(state == STEP2);
772 773 774
  return inner->get(output);
}

775 776
PromiseNode* ChainPromiseNode::getInnerForTrace() {
  return inner;
777 778
}

779
Maybe<Own<Event>> ChainPromiseNode::fire() {
780
  KJ_REQUIRE(state != STEP2);
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795

  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.
796
    kj::runCatchingExceptions([&]() { intermediate.value = nullptr; });
797 798 799 800 801 802 803 804 805
    // 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.
806
    KJ_FAIL_ASSERT("Inner node returned empty value.");
807 808 809
  }
  state = STEP2;

810 811 812 813 814 815
  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) {
816
      selfPtr->get()->onReady(onReadyEvent);
817
    }
818

819 820 821 822 823
    // 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) {
824
      inner->onReady(onReadyEvent);
825 826 827 828
    }

    return nullptr;
  }
829 830
}

831 832
// -------------------------------------------------------------------

833 834
ExclusiveJoinPromiseNode::ExclusiveJoinPromiseNode(Own<PromiseNode> left, Own<PromiseNode> right)
    : left(*this, kj::mv(left)), right(*this, kj::mv(right)) {}
835 836 837

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

838
void ExclusiveJoinPromiseNode::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
839
  onReadyEvent.init(event);
840 841 842
}

void ExclusiveJoinPromiseNode::get(ExceptionOrValue& output) noexcept {
843
  KJ_REQUIRE(left.get(output) || right.get(output), "get() called before ready.");
844 845
}

846 847 848 849 850 851
PromiseNode* ExclusiveJoinPromiseNode::getInnerForTrace() {
  auto result = left.getInnerForTrace();
  if (result == nullptr) {
    result = right.getInnerForTrace();
  }
  return result;
852 853 854
}

ExclusiveJoinPromiseNode::Branch::Branch(
855 856
    ExclusiveJoinPromiseNode& joinNode, Own<PromiseNode> dependencyParam)
    : joinNode(joinNode), dependency(kj::mv(dependencyParam)) {
857
  dependency->setSelfPointer(&dependency);
858
  dependency->onReady(this);
859 860
}

861
ExclusiveJoinPromiseNode::Branch::~Branch() noexcept(false) {}
862 863

bool ExclusiveJoinPromiseNode::Branch::get(ExceptionOrValue& output) {
864
  if (dependency) {
865 866 867 868 869 870 871
    dependency->get(output);
    return true;
  } else {
    return false;
  }
}

872
Maybe<Own<Event>> ExclusiveJoinPromiseNode::Branch::fire() {
873 874 875
  // Cancel the branch that didn't return first.  Ignore exceptions caused by cancellation.
  if (this == &joinNode.left) {
    kj::runCatchingExceptions([&]() { joinNode.right.dependency = nullptr; });
876
  } else {
877 878
    kj::runCatchingExceptions([&]() { joinNode.left.dependency = nullptr; });
  }
879

880 881 882
  joinNode.onReadyEvent.arm();
  return nullptr;
}
883

884 885
PromiseNode* ExclusiveJoinPromiseNode::Branch::getInnerForTrace() {
  return dependency;
886 887 888 889
}

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

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
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) {}

908
void ArrayJoinPromiseNodeBase::onReady(Event* event) noexcept {
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
  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);
934
  dependency->onReady(this);
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
}

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);
}

Kenton Varda's avatar
Kenton Varda committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
ArrayJoinPromiseNode<void>::ArrayJoinPromiseNode(
    Array<Own<PromiseNode>> promises, Array<ExceptionOr<_::Void>> resultParts)
    : ArrayJoinPromiseNodeBase(kj::mv(promises), resultParts.begin(), sizeof(ExceptionOr<_::Void>)),
      resultParts(kj::mv(resultParts)) {}

ArrayJoinPromiseNode<void>::~ArrayJoinPromiseNode() {}

void ArrayJoinPromiseNode<void>::getNoError(ExceptionOrValue& output) noexcept {
  output.as<_::Void>() = _::Void();
}

}  // namespace _ (private)

Promise<void> joinPromises(Array<Promise<void>>&& promises) {
  return Promise<void>(false, kj::heap<_::ArrayJoinPromiseNode<void>>(
      KJ_MAP(p, promises) { return kj::mv(p.node); },
      heapArray<_::ExceptionOr<_::Void>>(promises.size())));
}

namespace _ {  // (private)

976 977
// -------------------------------------------------------------------

978 979 980
EagerPromiseNodeBase::EagerPromiseNodeBase(
    Own<PromiseNode>&& dependencyParam, ExceptionOrValue& resultRef)
    : dependency(kj::mv(dependencyParam)), resultRef(resultRef) {
981
  dependency->setSelfPointer(&dependency);
982
  dependency->onReady(this);
983 984
}

985
void EagerPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
986
  onReadyEvent.init(event);
987 988
}

989 990
PromiseNode* EagerPromiseNodeBase::getInnerForTrace() {
  return dependency;
991 992
}

993
Maybe<Own<Event>> EagerPromiseNodeBase::fire() {
994 995 996 997 998
  dependency->get(resultRef);
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
    dependency = nullptr;
  })) {
    resultRef.addException(kj::mv(*exception));
999
  }
1000 1001 1002

  onReadyEvent.arm();
  return nullptr;
1003 1004
}

1005 1006
// -------------------------------------------------------------------

1007
void AdapterPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1008
  onReadyEvent.init(event);
1009 1010
}

Kenton Varda's avatar
Kenton Varda committed
1011 1012 1013 1014
// -------------------------------------------------------------------

Promise<void> IdentityFunc<Promise<void>>::operator()() const { return READY_NOW; }

1015
}  // namespace _ (private)
1016
}  // namespace kj