async.c++ 45.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 24 25
#if _WIN32
#define WIN32_LEAN_AND_MEAN 1  // lolz
#endif

26 27
#include "async.h"
#include "debug.h"
28
#include "vector.h"
29
#include "threadlocal.h"
30
#include "mutex.h"
31

32 33
#if _WIN32
#include <windows.h>  // just for Sleep(0)
Kenton Varda's avatar
Kenton Varda committed
34
#include "windows-sanity.h"
35 36 37 38
#else
#include <sched.h>    // just for sched_yield()
#endif

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

47 48 49 50
namespace kj {

namespace {

51
KJ_THREADLOCAL_PTR(EventLoop) threadLocalEventLoop = nullptr;
52

53
#define _kJ_ALREADY_READY reinterpret_cast< ::kj::_::Event*>(1)
54

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

61
class BoolEvent: public _::Event {
62 63 64
public:
  bool fired = false;

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

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

81 82 83 84 85 86 87 88 89 90
class YieldHarderPromiseNode final: public _::PromiseNode {
public:
  void onReady(_::Event* event) noexcept override {
    if (event) event->armLast();
  }
  void get(_::ExceptionOrValue& output) noexcept override {
    output.as<_::Void>() = _::Void();
  }
};

91
class NeverDonePromiseNode final: public _::PromiseNode {
92
public:
93
  void onReady(_::Event* event) noexcept override {
Kenton Varda's avatar
Kenton Varda committed
94
    // ignore
95 96 97 98 99 100
  }
  void get(_::ExceptionOrValue& output) noexcept override {
    KJ_FAIL_REQUIRE("Not ready.");
  }
};

101 102
}  // namespace

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
// =======================================================================================

Canceler::~Canceler() noexcept(false) {
  cancel("operation canceled");
}

void Canceler::cancel(StringPtr cancelReason) {
  if (isEmpty()) return;
  cancel(Exception(Exception::Type::FAILED, __FILE__, __LINE__, kj::str(cancelReason)));
}

void Canceler::cancel(const Exception& exception) {
  for (;;) {
    KJ_IF_MAYBE(a, list) {
      list = a->next;
      a->prev = nullptr;
      a->next = nullptr;
      a->cancel(kj::cp(exception));
    } else {
      break;
    }
  }
}

void Canceler::release() {
  for (;;) {
    KJ_IF_MAYBE(a, list) {
      list = a->next;
      a->prev = nullptr;
      a->next = nullptr;
    } else {
      break;
    }
  }
}

Canceler::AdapterBase::AdapterBase(Canceler& canceler)
    : prev(canceler.list),
      next(canceler.list) {
  canceler.list = *this;
  KJ_IF_MAYBE(n, next) {
    n->prev = next;
  }
}

Canceler::AdapterBase::~AdapterBase() noexcept(false) {
  KJ_IF_MAYBE(p, prev) {
    *p = next;
  }
  KJ_IF_MAYBE(n, next) {
    n->prev = prev;
  }
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170
Canceler::AdapterImpl<void>::AdapterImpl(kj::PromiseFulfiller<void>& fulfiller,
            Canceler& canceler, kj::Promise<void> inner)
    : AdapterBase(canceler),
      fulfiller(fulfiller),
      inner(inner.then(
          [&fulfiller]() { fulfiller.fulfill(); },
          [&fulfiller](kj::Exception&& e) { fulfiller.reject(kj::mv(e)); })
          .eagerlyEvaluate(nullptr)) {}

void Canceler::AdapterImpl<void>::cancel(kj::Exception&& e) {
  fulfiller.reject(kj::mv(e));
  inner = nullptr;
}

171 172
// =======================================================================================

173 174 175 176
TaskSet::TaskSet(TaskSet::ErrorHandler& errorHandler)
  : errorHandler(errorHandler) {}

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

178
class TaskSet::Task final: public _::Event {
Kenton Varda's avatar
Kenton Varda committed
179
public:
180 181 182 183
  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
184 185
  }

186 187
  Maybe<Own<Task>> next;
  Maybe<Own<Task>>* prev = nullptr;
Kenton Varda's avatar
Kenton Varda committed
188

189 190 191 192 193
protected:
  Maybe<Own<Event>> fire() override {
    // Get the result.
    _::ExceptionOr<_::Void> result;
    node->get(result);
Kenton Varda's avatar
Kenton Varda committed
194

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

202 203 204
    // Call the error handler if there was an exception.
    KJ_IF_MAYBE(e, result.exception) {
      taskSet.errorHandler.taskFailed(kj::mv(*e));
205 206
    }

207 208 209
    // Remove from the task list.
    KJ_IF_MAYBE(n, next) {
      n->get()->prev = prev;
Kenton Varda's avatar
Kenton Varda committed
210
    }
211 212 213 214 215
    Own<Event> self = kj::mv(KJ_ASSERT_NONNULL(*prev));
    KJ_ASSERT(self.get() == this);
    *prev = kj::mv(next);
    next = nullptr;
    prev = nullptr;
216 217 218 219 220 221 222 223

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

224 225 226 227 228 229
    return mv(self);
  }

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

231 232 233 234
private:
  TaskSet& taskSet;
  Own<_::PromiseNode> node;
};
Kenton Varda's avatar
Kenton Varda committed
235

236 237 238 239 240
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);
241
  }
242 243 244
  task->prev = &tasks;
  tasks = kj::mv(task);
}
245

246 247 248 249 250 251 252 253 254 255
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;
256
    }
Kenton Varda's avatar
Kenton Varda committed
257 258
  }

259 260
  return kj::strArray(traces, "\n============================================\n");
}
Kenton Varda's avatar
Kenton Varda committed
261

262 263 264 265 266 267 268 269 270 271 272 273
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);
  }
}

274
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

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

}  // namespace _ (private)

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

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
struct Executor::Impl {
  typedef Maybe<_::XThreadEvent&> _::XThreadEvent::*NextMember;
  typedef Maybe<_::XThreadEvent&>* _::XThreadEvent::*PrevMember;

  template <NextMember next, PrevMember prev>
  struct List {
    kj::Maybe<_::XThreadEvent&> head;
    kj::Maybe<_::XThreadEvent&>* tail = &head;

    bool empty() const {
      return head == nullptr;
    }

    void insert(_::XThreadEvent& event) {
      KJ_REQUIRE(event.*prev == nullptr);
      *tail = event;
      event.*prev = tail;
      tail = &(event.*next);
    }

    void erase(_::XThreadEvent& event) {
      KJ_REQUIRE(event.*prev != nullptr);
      *(event.*prev) = event.*next;
      KJ_IF_MAYBE(n, event.*next) {
        n->*prev = event.*prev;
      } else {
        KJ_DASSERT(tail == &(event.*next));
        tail = event.*prev;
      }
      event.*next = nullptr;
      event.*prev = nullptr;
    }

    template <typename Func>
    void forEach(Func&& func) {
      kj::Maybe<_::XThreadEvent&> current = head;
      for (;;) {
        KJ_IF_MAYBE(c, current) {
          auto nextItem = c->*next;
          func(*c);
          current = nextItem;
        } else {
          break;
        }
      }
    }
  };

  struct State {
    // Queues of notifications from other threads that need this thread's attention.

    List<&_::XThreadEvent::targetNext, &_::XThreadEvent::targetPrev> run;
    List<&_::XThreadEvent::targetNext, &_::XThreadEvent::targetPrev> cancel;
    List<&_::XThreadEvent::replyNext, &_::XThreadEvent::replyPrev> replies;

346 347 348 349 350
    bool waitingForCancel = false;
    // True if this thread is currently blocked waiting for some other thread to pump its
    // cancellation queue. If that other thread tries to block on *this* thread, then it could
    // deadlock -- it must take precautions against this.

351 352 353 354
    bool empty() const {
      return run.empty() && cancel.empty() && replies.empty();
    }

355
    void dispatchAll(Vector<_::XThreadEvent*>& eventsToCancelOutsideLock) {
356 357 358 359 360 361
      run.forEach([&](_::XThreadEvent& event) {
        run.erase(event);
        event.state = _::XThreadEvent::EXECUTING;
        event.armBreadthFirst();
      });

362
      dispatchCancels(eventsToCancelOutsideLock);
363 364 365 366 367 368 369

      replies.forEach([&](_::XThreadEvent& event) {
        replies.erase(event);
        event.onReadyEvent.armBreadthFirst();
      });
    }

370
    void dispatchCancels(Vector<_::XThreadEvent*>& eventsToCancelOutsideLock) {
371 372
      cancel.forEach([&](_::XThreadEvent& event) {
        cancel.erase(event);
373

Kenton Varda's avatar
Kenton Varda committed
374 375 376
        if (event.promiseNode == nullptr) {
          event.state = _::XThreadEvent::DONE;
        } else {
377 378 379 380
          // We can't destroy the promiseNode while the mutex is locked, because we don't know
          // what the destructor might do. But, we *must* destroy it before acknowledging
          // cancellation. So we have to add it to a list to destroy later.
          eventsToCancelOutsideLock.add(&event);
381 382 383 384 385 386 387
        }
      });
    }
  };

  kj::MutexGuarded<State> state;
  // After modifying state from another thread, the loop's port.wake() must be called.
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

  void processAsyncCancellations(Vector<_::XThreadEvent*>& eventsToCancelOutsideLock) {
    // After calling dispatchAll() or dispatchCancels() with the lock held, it may be that some
    // cancellations require dropping the lock before destroying the promiseNode. In that case
    // those cancellations will be added to the eventsToCancelOutsideLock Vector passed to the
    // method. That vector must then be passed to processAsyncCancellations() as soon as the lock
    // is released.

    for (auto& event: eventsToCancelOutsideLock) {
      event->promiseNode = nullptr;
      event->disarm();
    }

    // Now we need to mark all the events "done" under lock.
    auto lock = state.lockExclusive();
    for (auto& event: eventsToCancelOutsideLock) {
      event->state = _::XThreadEvent::DONE;
    }
  }
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
};

namespace _ {  // (private)

void XThreadEvent::ensureDoneOrCanceled() {
#if _MSC_VER
  {  // TODO(perf): TODO(msvc): Implement the double-checked lock optimization on MSVC.
#else
  if (__atomic_load_n(&state, __ATOMIC_ACQUIRE) != DONE) {
#endif
    auto lock = targetExecutor.impl->state.lockExclusive();
    switch (state) {
      case UNUSED:
        // Nothing to do.
        break;
      case QUEUED:
        lock->run.erase(*this);
424
        // No wake needed since we removed work rather than adding it.
425 426
        state = DONE;
        break;
427
      case EXECUTING: {
428
        lock->cancel.insert(*this);
429 430 431 432
        KJ_IF_MAYBE(p, targetExecutor.loop.port) {
          p->wake();
        }

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
        Maybe<Executor&> maybeSelfExecutor = nullptr;
        if (threadLocalEventLoop != nullptr) {
          KJ_IF_MAYBE(e, threadLocalEventLoop->executor) {
            maybeSelfExecutor = *e;
          }
        }

        KJ_IF_MAYBE(selfExecutor, maybeSelfExecutor) {
          // If, while waiting for other threads to process our cancellation request, we have
          // cancellation requests queued back to this thread, we must process them. Otherwise,
          // we could deadlock with two threads waiting on each other to process cancellations.
          //
          // We don't have a terribly good way to detect this, except to check if the remote
          // thread is itself waiting for cancellations and, if so, wake ourselves up to check for
          // cancellations to process. This will busy-loop but at least it should eventually
          // resolve assuming fair scheduling.
          //
          // To make things extra-annoying, in order to update our waitingForCancel flag, we have
          // to lock our own executor state, but we can't take both locks at once, so we have to
          // release the other lock in the meantime.

          // Make sure we unset waitingForCancel on the way out.
          KJ_DEFER({
            lock = {};

458 459 460
            Vector<_::XThreadEvent*> eventsToCancelOutsideLock;
            KJ_DEFER(selfExecutor->impl->processAsyncCancellations(eventsToCancelOutsideLock));

461 462
            auto selfLock = selfExecutor->impl->state.lockExclusive();
            selfLock->waitingForCancel = false;
463
            selfLock->dispatchCancels(eventsToCancelOutsideLock);
464 465 466 467 468 469 470 471 472 473 474 475

            // We don't need to re-take the lock on the other executor here; it's not used again
            // after this scope.
          });

          while (state != DONE) {
            bool otherThreadIsWaiting = lock->waitingForCancel;

            // Make sure our waitingForCancel is on and dispatch any pending cancellations on this
            // thread.
            lock = {};
            {
476 477 478
              Vector<_::XThreadEvent*> eventsToCancelOutsideLock;
              KJ_DEFER(selfExecutor->impl->processAsyncCancellations(eventsToCancelOutsideLock));

479 480 481 482 483 484
              auto selfLock = selfExecutor->impl->state.lockExclusive();
              selfLock->waitingForCancel = true;

              // Note that we don't have to proactively delete the PromiseNodes extracted from
              // the canceled events because those nodes belong to this thread and can't possibly
              // continue executing while we're blocked here.
485
              selfLock->dispatchCancels(eventsToCancelOutsideLock);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
            }

            if (otherThreadIsWaiting) {
              // We know the other thread was waiting for cancellations to complete a moment ago.
              // We may have just processed the necessary cancellations in this thread, in which
              // case the other thread needs a chance to receive control and notice this. Or, it
              // may be that the other thread is waiting for some third thread to take action.
              // Either way, we should yield control here to give things a chance to settle.
              // Otherwise we could end up in a tight busy loop.
#if _WIN32
              Sleep(0);
#else
              sched_yield();
#endif
            }

            // OK now we can take the original lock again.
            lock = targetExecutor.impl->state.lockExclusive();

            // OK, now we can wait for the other thread to either process our cancellation or
            // indicate that it is waiting for remote cancellation.
            lock.wait([&](const Executor::Impl::State& executorState) {
              return state == DONE || executorState.waitingForCancel;
            });
          }
        } else {
          // We have no executor of our own so we don't have to worry about cancellation cycles
          // causing deadlock.
          //
          // NOTE: I don't think we can actually get here, because it implies that this is a
          //   synchronous execution, which means there's no way to cancel it.
          lock.wait([&](auto&) { return state == DONE; });
        }
519 520
        KJ_DASSERT(targetPrev == nullptr);
        break;
521
      }
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
      case DONE:
        // Became done while we waited for lock. Nothing to do.
        break;
    }
  }

  KJ_IF_MAYBE(e, replyExecutor) {
    // Since we know we reached the DONE state (or never left UNUSED), we know that the remote
    // thread is all done playing with our `replyPrev` pointer. Only the current thread could
    // possibly modify it after this point. So we can skip the lock if it's already null.
    if (replyPrev != nullptr) {
      auto lock = e->impl->state.lockExclusive();
      lock->replies.erase(*this);
    }
  }
}

void XThreadEvent::done() {
  KJ_IF_MAYBE(e, replyExecutor) {
    // Queue the reply.
542 543 544 545 546 547 548 549
    {
      auto lock = e->impl->state.lockExclusive();
      lock->replies.insert(*this);
    }

    KJ_IF_MAYBE(p, e->loop.port) {
      p->wake();
    }
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
  }

  {
    auto lock = targetExecutor.impl->state.lockExclusive();
    KJ_DASSERT(state == EXECUTING);

    if (targetPrev != nullptr) {
      // We must be in the cancel list, because we can't be in the run list during EXECUTING state.
      // We can remove ourselves from the cancel list because at this point we're done anyway, so
      // whatever.
      lock->cancel.erase(*this);
    }

#if _MSC_VER
    // TODO(perf): TODO(msvc): Implement the double-checked lock optimization on MSVC.
    state = DONE;
#else
    __atomic_store_n(&state, DONE, __ATOMIC_RELEASE);
#endif
  }
}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
class XThreadEvent::DelayedDoneHack: public Disposer {
  // Crazy hack: In fire(), we want to call done() if the event is finished. But done() signals
  // the requesting thread to wake up and possibly delete the XThreadEvent. But the caller (the
  // EventLoop) still has to set `event->firing = false` after `fire()` returns, so this would be
  // a race condition use-after-free.
  //
  // It just so happens, though, that fire() is allowed to return an optional `Own<Event>` to drop,
  // and the caller drops that pointer immediately after setting event->firing = false. So we
  // return a pointer whose disposer calls done().
  //
  // It's not quite as much of a hack as it seems: The whole reason fire() returns an Own<Event> is
  // so that the event can delete itself, but do so after the caller sets event->firing = false.
  // It just happens to be that in this case, the event isn't deleting itself, but rather releasing
  // itself back to the other thread.

protected:
  void disposeImpl(void* pointer) const override {
    reinterpret_cast<XThreadEvent*>(pointer)->done();
  }
};

593
Maybe<Own<Event>> XThreadEvent::fire() {
Kenton Varda's avatar
Kenton Varda committed
594
  static constexpr DelayedDoneHack DISPOSER {};
595

596 597
  KJ_IF_MAYBE(n, promiseNode) {
    n->get()->get(result);
598
    promiseNode = nullptr;  // make sure to destroy in the thread that created it
599
    return Own<Event>(this, DISPOSER);
600 601 602 603 604 605 606 607 608
  } else {
    KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
      promiseNode = execute();
    })) {
      result.addException(kj::mv(*exception));
    };
    KJ_IF_MAYBE(n, promiseNode) {
      n->get()->onReady(this);
    } else {
609
      return Own<Event>(this, DISPOSER);
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
    }
  }

  return nullptr;
}

void XThreadEvent::onReady(Event* event) noexcept {
  onReadyEvent.init(event);
}

}  // namespace _

Executor::Executor(EventLoop& loop, Badge<EventLoop>): loop(loop), impl(kj::heap<Impl>()) {}
Executor::~Executor() noexcept(false) {}

void Executor::send(_::XThreadEvent& event, bool sync) const {
  KJ_ASSERT(event.state == _::XThreadEvent::UNUSED);

628 629 630 631 632 633 634 635 636 637 638 639 640 641
  if (sync) {
    if (threadLocalEventLoop == &loop) {
      // Invoking a sync request on our own thread. Just execute it directly; if we try to queue
      // it to the loop, we'll deadlock.
      auto promiseNode = event.execute();

      // If the function returns a promise, we have no way to pump the event loop to wait for it,
      // because the event loop may already be pumping somewhere up the stack.
      KJ_ASSERT(promiseNode == nullptr,
          "can't call executeSync() on own thread's executor with a promise-returning function");

      return;
    }
  } else {
642
    event.replyExecutor = getCurrentThreadExecutor();
643 644 645 646

    // Note that async requests will "just work" even if the target executor is our own thread's
    // executor. In theory we could detect this case to avoid some locking and signals but that
    // would be extra code complexity for probably little benefit.
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
  }

  auto lock = impl->state.lockExclusive();
  event.state = _::XThreadEvent::QUEUED;
  lock->run.insert(event);

  KJ_IF_MAYBE(p, loop.port) {
    p->wake();
  } else {
    // Event loop will be waiting on executor.wait(), which will be woken when we unlock the mutex.
  }

  if (sync) {
    lock.wait([&](auto&) { return event.state == _::XThreadEvent::DONE; });
  }
}

void Executor::wait() {
665 666
  Vector<_::XThreadEvent*> eventsToCancelOutsideLock;
  KJ_DEFER(impl->processAsyncCancellations(eventsToCancelOutsideLock));
667 668 669 670 671 672 673

  auto lock = impl->state.lockExclusive();

  lock.wait([](const Impl::State& state) {
    return !state.empty();
  });

674
  lock->dispatchAll(eventsToCancelOutsideLock);
675 676 677
}

bool Executor::poll() {
678 679
  Vector<_::XThreadEvent*> eventsToCancelOutsideLock;
  KJ_DEFER(impl->processAsyncCancellations(eventsToCancelOutsideLock));
680 681 682 683 684

  auto lock = impl->state.lockExclusive();
  if (lock->empty()) {
    return false;
  } else {
685
    lock->dispatchAll(eventsToCancelOutsideLock);
686 687 688 689 690 691 692 693 694 695
    return true;
  }
}

const Executor& getCurrentThreadExecutor() {
  return currentEventLoop().getExecutor();
}

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

696
void EventPort::setRunnable(bool runnable) {}
697

698 699 700 701 702
void EventPort::wake() const {
  kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED,
      "cross-thread wake() not implemented by this EventPort implementation"));
}

703
EventLoop::EventLoop()
704
    : daemons(kj::heap<TaskSet>(_::LoggingErrorHandler::instance)) {}
705

706 707
EventLoop::EventLoop(EventPort& port)
    : port(port),
708
      daemons(kj::heap<TaskSet>(_::LoggingErrorHandler::instance)) {}
Kenton Varda's avatar
Kenton Varda committed
709

710
EventLoop::~EventLoop() noexcept(false) {
711 712 713 714 715 716 717 718 719
  // 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...
720
    _::Event* event = head;
721
    while (event != nullptr) {
722
      _::Event* next = event->next;
723 724 725 726 727 728
      event->next = nullptr;
      event->prev = nullptr;
      event = next;
    }
    break;
  }
729 730 731 732 733 734

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

737
void EventLoop::run(uint maxTurnCount) {
738 739 740
  running = true;
  KJ_DEFER(running = false);

741 742 743 744 745
  for (uint i = 0; i < maxTurnCount; i++) {
    if (!turn()) {
      break;
    }
  }
746

747
  setRunnable(isRunnable());
748 749
}

750 751
bool EventLoop::turn() {
  _::Event* event = head;
752

753 754 755 756 757 758 759 760
  if (event == nullptr) {
    // No events in the queue.
    return false;
  } else {
    head = event->next;
    if (head != nullptr) {
      head->prev = &head;
    }
761

762
    depthFirstInsertPoint = &head;
763 764 765
    if (breadthFirstInsertPoint == &event->next) {
      breadthFirstInsertPoint = &head;
    }
766 767 768
    if (tail == &event->next) {
      tail = &head;
    }
769

770 771
    event->next = nullptr;
    event->prev = nullptr;
772

773 774 775 776 777 778
    Maybe<Own<_::Event>> eventToDestroy;
    {
      event->firing = true;
      KJ_DEFER(event->firing = false);
      eventToDestroy = event->fire();
    }
Kenton Varda's avatar
Kenton Varda committed
779

780 781 782 783
    depthFirstInsertPoint = &head;
    return true;
  }
}
784

785 786 787 788
bool EventLoop::isRunnable() {
  return head != nullptr;
}

789 790 791 792 793 794 795 796
const Executor& EventLoop::getExecutor() {
  KJ_IF_MAYBE(e, executor) {
    return *e;
  } else {
    return executor.emplace(*this, Badge<EventLoop>());
  }
}

797 798
void EventLoop::setRunnable(bool runnable) {
  if (runnable != lastRunnableState) {
799 800 801
    KJ_IF_MAYBE(p, port) {
      p->setRunnable(runnable);
    }
802 803 804 805
    lastRunnableState = runnable;
  }
}

806 807 808 809 810 811 812 813 814 815 816 817 818
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;
}

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
void EventLoop::wait() {
  KJ_IF_MAYBE(p, port) {
    if (p->wait()) {
      // Another thread called wake(). Check for cross-thread events.
      KJ_IF_MAYBE(e, executor) {
        e->poll();
      }
    }
  } else KJ_IF_MAYBE(e, executor) {
    e->wait();
  } else {
    KJ_FAIL_REQUIRE("Nothing to wait for; this thread would hang forever.");
  }
}

void EventLoop::poll() {
  KJ_IF_MAYBE(p, port) {
    if (p->poll()) {
      // Another thread called wake(). Check for cross-thread events.
      KJ_IF_MAYBE(e, executor) {
        e->poll();
      }
    }
  } else KJ_IF_MAYBE(e, executor) {
    e->poll();
  }
}

847 848 849 850 851 852 853 854 855 856
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.
857
      loop.poll();
858 859 860 861 862 863 864 865 866

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

867
namespace _ {  // private
868

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

874
  BoolEvent doneEvent;
875
  node->setSelfPointer(&node);
876
  node->onReady(&doneEvent);
877 878 879 880

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

881
  uint counter = 0;
882 883 884
  while (!doneEvent.fired) {
    if (!loop.turn()) {
      // No events in the queue.  Wait for callback.
885
      counter = 0;
886
      loop.wait();
887 888 889
    } else if (++counter > waitScope.busyPollInterval) {
      // Note: It's intentional that if busyPollInterval is kj::maxValue, we never poll.
      counter = 0;
890
      loop.poll();
891
    }
892
  }
893

894
  loop.setRunnable(loop.isRunnable());
895

896
  node->get(result);
897
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
898 899 900 901
    node = nullptr;
  })) {
    result.addException(kj::mv(*exception));
  }
902 903
}

904 905 906 907 908 909 910 911 912 913 914 915 916 917
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.
918
      loop.poll();
919 920 921 922 923 924 925 926 927 928 929 930 931 932

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

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

933
Promise<void> yield() {
934 935 936
  return Promise<void>(false, kj::heap<YieldPromiseNode>());
}

937 938 939 940
Promise<void> yieldHarder() {
  return Promise<void>(false, kj::heap<YieldHarderPromiseNode>());
}

941 942 943 944
Own<PromiseNode> neverDone() {
  return kj::heap<NeverDonePromiseNode>();
}

Kenton Varda's avatar
Kenton Varda committed
945
void NeverDone::wait(WaitScope& waitScope) const {
946 947 948 949 950
  ExceptionOr<Void> dummy;
  waitImpl(neverDone(), dummy, waitScope);
  KJ_UNREACHABLE;
}

951
void detach(kj::Promise<void>&& promise) {
952 953 954
  EventLoop& loop = currentEventLoop();
  KJ_REQUIRE(loop.daemons.get() != nullptr, "EventLoop is shutting down.") { return; }
  loop.daemons->add(kj::mv(promise));
955 956
}

957
Event::Event()
958
    : loop(currentEventLoop()), next(nullptr), prev(nullptr) {}
959

960 961
Event::Event(kj::EventLoop& loop)
    : loop(loop), next(nullptr), prev(nullptr) {}
962

963 964
Event::~Event() noexcept(false) {
  disarm();
965 966

  KJ_REQUIRE(!firing, "Promise callback destroyed itself.");
Kenton Varda's avatar
Kenton Varda committed
967 968
}

969
void Event::armDepthFirst() {
970 971
  KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
             "Event armed from different thread than it was created in.  You must use "
972
             "Executor to queue events cross-thread.");
973

974 975 976 977 978 979 980
  if (prev == nullptr) {
    next = *loop.depthFirstInsertPoint;
    prev = loop.depthFirstInsertPoint;
    *prev = this;
    if (next != nullptr) {
      next->prev = &next;
    }
981

982 983
    loop.depthFirstInsertPoint = &next;

984 985 986
    if (loop.breadthFirstInsertPoint == prev) {
      loop.breadthFirstInsertPoint = &next;
    }
987 988 989
    if (loop.tail == prev) {
      loop.tail = &next;
    }
990 991

    loop.setRunnable(true);
992 993 994
  }
}

995
void Event::armBreadthFirst() {
996 997
  KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
             "Event armed from different thread than it was created in.  You must use "
998
             "Executor to queue events cross-thread.");
999 1000

  if (prev == nullptr) {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    next = *loop.breadthFirstInsertPoint;
    prev = loop.breadthFirstInsertPoint;
    *prev = this;
    if (next != nullptr) {
      next->prev = &next;
    }

    loop.breadthFirstInsertPoint = &next;

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

    loop.setRunnable(true);
  }
}

void Event::armLast() {
  KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr,
             "Event armed from different thread than it was created in.  You must use "
             "Executor to queue events cross-thread.");

  if (prev == nullptr) {
    next = *loop.breadthFirstInsertPoint;
    prev = loop.breadthFirstInsertPoint;
1026 1027 1028 1029 1030
    *prev = this;
    if (next != nullptr) {
      next->prev = &next;
    }

1031 1032 1033 1034 1035 1036
    // We don't update loop.breadthFirstInsertPoint because we want further inserts to go *before*
    // this event.

    if (loop.tail == prev) {
      loop.tail = &next;
    }
1037 1038

    loop.setRunnable(true);
1039 1040 1041
  }
}

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
void Event::disarm() {
  if (prev != nullptr) {
    if (threadLocalEventLoop != &loop && threadLocalEventLoop != nullptr) {
      KJ_LOG(FATAL, "Promise destroyed from a different thread than it was created in.");
      // There's no way out of this place without UB, so abort now.
      abort();
    }

    if (loop.tail == &next) {
      loop.tail = prev;
    }
    if (loop.depthFirstInsertPoint == &next) {
      loop.depthFirstInsertPoint = prev;
    }
1056 1057 1058
    if (loop.breadthFirstInsertPoint == &next) {
      loop.breadthFirstInsertPoint = prev;
    }
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

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

    prev = nullptr;
    next = nullptr;
  }
}

1070
_::PromiseNode* Event::getInnerForTrace() {
1071 1072 1073
  return nullptr;
}

1074
#if !KJ_NO_RTTI
1075 1076 1077 1078
#if __GNUC__
static kj::String demangleTypeName(const char* name) {
  int status;
  char* buf = abi::__cxa_demangle(name, nullptr, nullptr, &status);
1079
  kj::String result = kj::heapString(buf == nullptr ? name : buf);
1080 1081 1082 1083 1084 1085 1086 1087
  free(buf);
  return kj::mv(result);
}
#else
static kj::String demangleTypeName(const char* name) {
  return kj::heapString(name);
}
#endif
1088
#endif
1089

1090
static kj::String traceImpl(Event* event, _::PromiseNode* node) {
1091 1092 1093
#if KJ_NO_RTTI
  return heapString("Trace not available because RTTI is disabled.");
#else
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  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");
1106
#endif
1107 1108
}

1109
kj::String Event::trace() {
1110
  return traceImpl(this, getInnerForTrace());
1111 1112
}

1113 1114
}  // namespace _ (private)

1115 1116
// =======================================================================================

1117 1118
namespace _ {  // private

1119 1120 1121 1122
kj::String PromiseBase::trace() {
  return traceImpl(nullptr, node);
}

1123 1124
void PromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {}

1125
PromiseNode* PromiseNode::getInnerForTrace() { return nullptr; }
1126

1127
void PromiseNode::OnReadyEvent::init(Event* newEvent) {
1128
  if (event == _kJ_ALREADY_READY) {
Kenton Varda's avatar
Kenton Varda committed
1129 1130 1131
    // 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.
1132
    if (newEvent) newEvent->armBreadthFirst();
1133
  } else {
1134
    event = newEvent;
1135 1136 1137
  }
}

1138
void PromiseNode::OnReadyEvent::arm() {
1139 1140 1141
  KJ_ASSERT(event != _kJ_ALREADY_READY, "arm() should only be called once");

  if (event != nullptr) {
Kenton Varda's avatar
Kenton Varda committed
1142 1143 1144
    // 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.
1145
    event->armDepthFirst();
1146
  }
1147 1148

  event = _kJ_ALREADY_READY;
1149 1150
}

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
void PromiseNode::OnReadyEvent::armBreadthFirst() {
  KJ_ASSERT(event != _kJ_ALREADY_READY, "armBreadthFirst() should only be called once");

  if (event != nullptr) {
    // A promise resolved and an event is already waiting on it.
    event->armBreadthFirst();
  }

  event = _kJ_ALREADY_READY;
}

1162 1163
// -------------------------------------------------------------------

1164 1165 1166
ImmediatePromiseNodeBase::ImmediatePromiseNodeBase() {}
ImmediatePromiseNodeBase::~ImmediatePromiseNodeBase() noexcept(false) {}

1167 1168
void ImmediatePromiseNodeBase::onReady(Event* event) noexcept {
  if (event) event->armBreadthFirst();
Kenton Varda's avatar
Kenton Varda committed
1169
}
1170 1171 1172 1173 1174 1175 1176 1177

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

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

1178 1179
// -------------------------------------------------------------------

1180 1181 1182 1183
AttachmentPromiseNodeBase::AttachmentPromiseNodeBase(Own<PromiseNode>&& dependencyParam)
    : dependency(kj::mv(dependencyParam)) {
  dependency->setSelfPointer(&dependency);
}
1184

1185
void AttachmentPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1186
  dependency->onReady(event);
1187 1188 1189 1190 1191 1192
}

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

1193 1194
PromiseNode* AttachmentPromiseNodeBase::getInnerForTrace() {
  return dependency;
1195 1196 1197 1198 1199 1200 1201 1202
}

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

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

Kenton Varda's avatar
Kenton Varda committed
1203 1204 1205
TransformPromiseNodeBase::TransformPromiseNodeBase(
    Own<PromiseNode>&& dependencyParam, void* continuationTracePtr)
    : dependency(kj::mv(dependencyParam)), continuationTracePtr(continuationTracePtr) {
1206 1207
  dependency->setSelfPointer(&dependency);
}
1208

1209
void TransformPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1210
  dependency->onReady(event);
1211 1212 1213 1214 1215
}

void TransformPromiseNodeBase::get(ExceptionOrValue& output) noexcept {
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() {
    getImpl(output);
1216
    dropDependency();
1217 1218 1219 1220 1221
  })) {
    output.addException(kj::mv(*exception));
  }
}

1222 1223
PromiseNode* TransformPromiseNodeBase::getInnerForTrace() {
  return dependency;
1224 1225
}

1226 1227 1228 1229
void TransformPromiseNodeBase::dropDependency() {
  dependency = nullptr;
}

1230 1231 1232 1233 1234 1235 1236
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
1237 1238 1239 1240

  KJ_IF_MAYBE(e, output.exception) {
    e->addTrace(continuationTracePtr);
  }
1241 1242
}

1243 1244
// -------------------------------------------------------------------

1245
ForkBranchBase::ForkBranchBase(Own<ForkHubBase>&& hubParam): hub(kj::mv(hubParam)) {
1246
  if (hub->tailBranch == nullptr) {
1247
    onReadyEvent.arm();
1248 1249
  } else {
    // Insert into hub's linked list of branches.
1250
    prevPtr = hub->tailBranch;
1251 1252
    *prevPtr = this;
    next = nullptr;
1253
    hub->tailBranch = &next;
1254 1255 1256
  }
}

Kenton Varda's avatar
Kenton Varda committed
1257
ForkBranchBase::~ForkBranchBase() noexcept(false) {
1258 1259 1260
  if (prevPtr != nullptr) {
    // Remove from hub's linked list of branches.
    *prevPtr = next;
1261
    (next == nullptr ? hub->tailBranch : next->prevPtr) = prevPtr;
1262 1263 1264 1265
  }
}

void ForkBranchBase::hubReady() noexcept {
1266
  onReadyEvent.arm();
1267 1268 1269 1270
}

void ForkBranchBase::releaseHub(ExceptionOrValue& output) {
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
1271
    hub = nullptr;
1272 1273 1274 1275 1276
  })) {
    output.addException(kj::mv(*exception));
  }
}

1277
void ForkBranchBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1278
  onReadyEvent.init(event);
1279 1280
}

1281 1282
PromiseNode* ForkBranchBase::getInnerForTrace() {
  return hub->getInnerForTrace();
1283 1284 1285 1286
}

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

1287 1288
ForkHubBase::ForkHubBase(Own<PromiseNode>&& innerParam, ExceptionOrValue& resultRef)
    : inner(kj::mv(innerParam)), resultRef(resultRef) {
1289
  inner->setSelfPointer(&inner);
1290
  inner->onReady(this);
1291
}
1292

1293
Maybe<Own<Event>> ForkHubBase::fire() {
1294 1295 1296 1297 1298 1299 1300
  // 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));
  }
1301

1302
  for (auto branch = headBranch; branch != nullptr; branch = branch->next) {
1303 1304 1305
    branch->hubReady();
    *branch->prevPtr = nullptr;
    branch->prevPtr = nullptr;
1306
  }
1307
  *tailBranch = nullptr;
1308 1309

  // Indicate that the list is no longer active.
1310
  tailBranch = nullptr;
1311 1312 1313 1314 1315 1316

  return nullptr;
}

_::PromiseNode* ForkHubBase::getInnerForTrace() {
  return inner;
1317 1318 1319 1320
}

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

1321 1322
ChainPromiseNode::ChainPromiseNode(Own<PromiseNode> innerParam)
    : state(STEP1), inner(kj::mv(innerParam)) {
1323
  inner->setSelfPointer(&inner);
1324
  inner->onReady(this);
1325 1326
}

1327
ChainPromiseNode::~ChainPromiseNode() noexcept(false) {}
1328

1329
void ChainPromiseNode::onReady(Event* event) noexcept {
1330 1331
  switch (state) {
    case STEP1:
1332
      onReadyEvent = event;
Kenton Varda's avatar
Kenton Varda committed
1333
      return;
1334
    case STEP2:
Kenton Varda's avatar
Kenton Varda committed
1335 1336
      inner->onReady(event);
      return;
1337 1338 1339 1340
  }
  KJ_UNREACHABLE;
}

1341 1342 1343 1344 1345 1346 1347 1348 1349
void ChainPromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {
  if (state == STEP2) {
    *selfPtr = kj::mv(inner);  // deletes this!
    selfPtr->get()->setSelfPointer(selfPtr);
  } else {
    this->selfPtr = selfPtr;
  }
}

1350
void ChainPromiseNode::get(ExceptionOrValue& output) noexcept {
1351
  KJ_REQUIRE(state == STEP2);
1352 1353 1354
  return inner->get(output);
}

1355 1356
PromiseNode* ChainPromiseNode::getInnerForTrace() {
  return inner;
1357 1358
}

1359
Maybe<Own<Event>> ChainPromiseNode::fire() {
1360
  KJ_REQUIRE(state != STEP2);
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

  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.
1376
    kj::runCatchingExceptions([&]() { intermediate.value = nullptr; });
1377 1378 1379 1380 1381 1382 1383 1384 1385
    // 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.
1386
    KJ_FAIL_ASSERT("Inner node returned empty value.");
1387 1388 1389
  }
  state = STEP2;

1390 1391 1392 1393 1394 1395
  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) {
1396
      selfPtr->get()->onReady(onReadyEvent);
1397
    }
1398

1399 1400 1401 1402 1403
    // 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) {
1404
      inner->onReady(onReadyEvent);
1405 1406 1407 1408
    }

    return nullptr;
  }
1409 1410
}

1411 1412
// -------------------------------------------------------------------

1413 1414
ExclusiveJoinPromiseNode::ExclusiveJoinPromiseNode(Own<PromiseNode> left, Own<PromiseNode> right)
    : left(*this, kj::mv(left)), right(*this, kj::mv(right)) {}
1415 1416 1417

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

1418
void ExclusiveJoinPromiseNode::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1419
  onReadyEvent.init(event);
1420 1421 1422
}

void ExclusiveJoinPromiseNode::get(ExceptionOrValue& output) noexcept {
1423
  KJ_REQUIRE(left.get(output) || right.get(output), "get() called before ready.");
1424 1425
}

1426 1427 1428 1429 1430 1431
PromiseNode* ExclusiveJoinPromiseNode::getInnerForTrace() {
  auto result = left.getInnerForTrace();
  if (result == nullptr) {
    result = right.getInnerForTrace();
  }
  return result;
1432 1433 1434
}

ExclusiveJoinPromiseNode::Branch::Branch(
1435 1436
    ExclusiveJoinPromiseNode& joinNode, Own<PromiseNode> dependencyParam)
    : joinNode(joinNode), dependency(kj::mv(dependencyParam)) {
1437
  dependency->setSelfPointer(&dependency);
1438
  dependency->onReady(this);
1439 1440
}

1441
ExclusiveJoinPromiseNode::Branch::~Branch() noexcept(false) {}
1442 1443

bool ExclusiveJoinPromiseNode::Branch::get(ExceptionOrValue& output) {
1444
  if (dependency) {
1445 1446 1447 1448 1449 1450 1451
    dependency->get(output);
    return true;
  } else {
    return false;
  }
}

1452
Maybe<Own<Event>> ExclusiveJoinPromiseNode::Branch::fire() {
1453 1454 1455 1456 1457 1458 1459 1460 1461
  if (dependency) {
    // Cancel the branch that didn't return first.  Ignore exceptions caused by cancellation.
    if (this == &joinNode.left) {
      kj::runCatchingExceptions([&]() { joinNode.right.dependency = nullptr; });
    } else {
      kj::runCatchingExceptions([&]() { joinNode.left.dependency = nullptr; });
    }

    joinNode.onReadyEvent.arm();
1462
  } else {
1463 1464
    // The other branch already fired, and this branch was canceled. It's possible for both
    // branches to fire if both were armed simultaneously.
1465 1466 1467
  }
  return nullptr;
}
1468

1469 1470
PromiseNode* ExclusiveJoinPromiseNode::Branch::getInnerForTrace() {
  return dependency;
1471 1472 1473 1474
}

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

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
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) {}

1493
void ArrayJoinPromiseNodeBase::onReady(Event* event) noexcept {
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
  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);
1519
  dependency->onReady(this);
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
}

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
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
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)

1561 1562
// -------------------------------------------------------------------

1563 1564 1565
EagerPromiseNodeBase::EagerPromiseNodeBase(
    Own<PromiseNode>&& dependencyParam, ExceptionOrValue& resultRef)
    : dependency(kj::mv(dependencyParam)), resultRef(resultRef) {
1566
  dependency->setSelfPointer(&dependency);
1567
  dependency->onReady(this);
1568 1569
}

1570
void EagerPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1571
  onReadyEvent.init(event);
1572 1573
}

1574 1575
PromiseNode* EagerPromiseNodeBase::getInnerForTrace() {
  return dependency;
1576 1577
}

1578
Maybe<Own<Event>> EagerPromiseNodeBase::fire() {
1579 1580 1581 1582 1583
  dependency->get(resultRef);
  KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() {
    dependency = nullptr;
  })) {
    resultRef.addException(kj::mv(*exception));
1584
  }
1585 1586 1587

  onReadyEvent.arm();
  return nullptr;
1588 1589
}

1590 1591
// -------------------------------------------------------------------

1592
void AdapterPromiseNodeBase::onReady(Event* event) noexcept {
Kenton Varda's avatar
Kenton Varda committed
1593
  onReadyEvent.init(event);
1594 1595
}

Kenton Varda's avatar
Kenton Varda committed
1596 1597 1598 1599
// -------------------------------------------------------------------

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

1600
}  // namespace _ (private)
1601
}  // namespace kj