Chris@47: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@47: // Licensed under the MIT License: Chris@47: // Chris@47: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@47: // of this software and associated documentation files (the "Software"), to deal Chris@47: // in the Software without restriction, including without limitation the rights Chris@47: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@47: // copies of the Software, and to permit persons to whom the Software is Chris@47: // furnished to do so, subject to the following conditions: Chris@47: // Chris@47: // The above copyright notice and this permission notice shall be included in Chris@47: // all copies or substantial portions of the Software. Chris@47: // Chris@47: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@47: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@47: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@47: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@47: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@47: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@47: // THE SOFTWARE. Chris@47: Chris@47: // This file contains extended inline implementation details that are required along with async.h. Chris@47: // We move this all into a separate file to make async.h more readable. Chris@47: // Chris@47: // Non-inline declarations here are defined in async.c++. Chris@47: Chris@47: #ifndef KJ_ASYNC_H_ Chris@47: #error "Do not include this directly; include kj/async.h." Chris@47: #include "async.h" // help IDE parse this file Chris@47: #endif Chris@47: Chris@47: #ifndef KJ_ASYNC_INL_H_ Chris@47: #define KJ_ASYNC_INL_H_ Chris@47: Chris@47: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@47: #pragma GCC system_header Chris@47: #endif Chris@47: Chris@47: namespace kj { Chris@47: namespace _ { // private Chris@47: Chris@47: template Chris@47: class ExceptionOr; Chris@47: Chris@47: class ExceptionOrValue { Chris@47: public: Chris@47: ExceptionOrValue(bool, Exception&& exception): exception(kj::mv(exception)) {} Chris@47: KJ_DISALLOW_COPY(ExceptionOrValue); Chris@47: Chris@47: void addException(Exception&& exception) { Chris@47: if (this->exception == nullptr) { Chris@47: this->exception = kj::mv(exception); Chris@47: } Chris@47: } Chris@47: Chris@47: template Chris@47: ExceptionOr& as() { return *static_cast*>(this); } Chris@47: template Chris@47: const ExceptionOr& as() const { return *static_cast*>(this); } Chris@47: Chris@47: Maybe exception; Chris@47: Chris@47: protected: Chris@47: // Allow subclasses to have move constructor / assignment. Chris@47: ExceptionOrValue() = default; Chris@47: ExceptionOrValue(ExceptionOrValue&& other) = default; Chris@47: ExceptionOrValue& operator=(ExceptionOrValue&& other) = default; Chris@47: }; Chris@47: Chris@47: template Chris@47: class ExceptionOr: public ExceptionOrValue { Chris@47: public: Chris@47: ExceptionOr() = default; Chris@47: ExceptionOr(T&& value): value(kj::mv(value)) {} Chris@47: ExceptionOr(bool, Exception&& exception): ExceptionOrValue(false, kj::mv(exception)) {} Chris@47: ExceptionOr(ExceptionOr&&) = default; Chris@47: ExceptionOr& operator=(ExceptionOr&&) = default; Chris@47: Chris@47: Maybe value; Chris@47: }; Chris@47: Chris@47: class Event { Chris@47: // An event waiting to be executed. Not for direct use by applications -- promises use this Chris@47: // internally. Chris@47: Chris@47: public: Chris@47: Event(); Chris@47: ~Event() noexcept(false); Chris@47: KJ_DISALLOW_COPY(Event); Chris@47: Chris@47: void armDepthFirst(); Chris@47: // Enqueue this event so that `fire()` will be called from the event loop soon. Chris@47: // Chris@47: // Events scheduled in this way are executed in depth-first order: if an event callback arms Chris@47: // more events, those events are placed at the front of the queue (in the order in which they Chris@47: // were armed), so that they run immediately after the first event's callback returns. Chris@47: // Chris@47: // Depth-first event scheduling is appropriate for events that represent simple continuations Chris@47: // of a previous event that should be globbed together for performance. Depth-first scheduling Chris@47: // can lead to starvation, so any long-running task must occasionally yield with Chris@47: // `armBreadthFirst()`. (Promise::then() uses depth-first whereas evalLater() uses Chris@47: // breadth-first.) Chris@47: // Chris@47: // To use breadth-first scheduling instead, use `armBreadthFirst()`. Chris@47: Chris@47: void armBreadthFirst(); Chris@47: // Like `armDepthFirst()` except that the event is placed at the end of the queue. Chris@47: Chris@47: kj::String trace(); Chris@47: // Dump debug info about this event. Chris@47: Chris@47: virtual _::PromiseNode* getInnerForTrace(); Chris@47: // If this event wraps a PromiseNode, get that node. Used for debug tracing. Chris@47: // Default implementation returns nullptr. Chris@47: Chris@47: protected: Chris@47: virtual Maybe> fire() = 0; Chris@47: // Fire the event. Possibly returns a pointer to itself, which will be discarded by the Chris@47: // caller. This is the only way that an event can delete itself as a result of firing, as Chris@47: // doing so from within fire() will throw an exception. Chris@47: Chris@47: private: Chris@47: friend class kj::EventLoop; Chris@47: EventLoop& loop; Chris@47: Event* next; Chris@47: Event** prev; Chris@47: bool firing = false; Chris@47: }; Chris@47: Chris@47: class PromiseNode { Chris@47: // A Promise contains a chain of PromiseNodes tracking the pending transformations. Chris@47: // Chris@47: // To reduce generated code bloat, PromiseNode is not a template. Instead, it makes very hacky Chris@47: // use of pointers to ExceptionOrValue which actually point to ExceptionOr, but are only Chris@47: // so down-cast in the few places that really need to be templated. Luckily this is all Chris@47: // internal implementation details. Chris@47: Chris@47: public: Chris@47: virtual void onReady(Event& event) noexcept = 0; Chris@47: // Arms the given event when ready. Chris@47: Chris@47: virtual void setSelfPointer(Own* selfPtr) noexcept; Chris@47: // Tells the node that `selfPtr` is the pointer that owns this node, and will continue to own Chris@47: // this node until it is destroyed or setSelfPointer() is called again. ChainPromiseNode uses Chris@47: // this to shorten redundant chains. The default implementation does nothing; only Chris@47: // ChainPromiseNode should implement this. Chris@47: Chris@47: virtual void get(ExceptionOrValue& output) noexcept = 0; Chris@47: // Get the result. `output` points to an ExceptionOr into which the result will be written. Chris@47: // Can only be called once, and only after the node is ready. Must be called directly from the Chris@47: // event loop, with no application code on the stack. Chris@47: Chris@47: virtual PromiseNode* getInnerForTrace(); Chris@47: // If this node wraps some other PromiseNode, get the wrapped node. Used for debug tracing. Chris@47: // Default implementation returns nullptr. Chris@47: Chris@47: protected: Chris@47: class OnReadyEvent { Chris@47: // Helper class for implementing onReady(). Chris@47: Chris@47: public: Chris@47: void init(Event& newEvent); Chris@47: // Returns true if arm() was already called. Chris@47: Chris@47: void arm(); Chris@47: // Arms the event if init() has already been called and makes future calls to init() return Chris@47: // true. Chris@47: Chris@47: private: Chris@47: Event* event = nullptr; Chris@47: }; Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class ImmediatePromiseNodeBase: public PromiseNode { Chris@47: public: Chris@47: ImmediatePromiseNodeBase(); Chris@47: ~ImmediatePromiseNodeBase() noexcept(false); Chris@47: Chris@47: void onReady(Event& event) noexcept override; Chris@47: }; Chris@47: Chris@47: template Chris@47: class ImmediatePromiseNode final: public ImmediatePromiseNodeBase { Chris@47: // A promise that has already been resolved to an immediate value or exception. Chris@47: Chris@47: public: Chris@47: ImmediatePromiseNode(ExceptionOr&& result): result(kj::mv(result)) {} Chris@47: Chris@47: void get(ExceptionOrValue& output) noexcept override { Chris@47: output.as() = kj::mv(result); Chris@47: } Chris@47: Chris@47: private: Chris@47: ExceptionOr result; Chris@47: }; Chris@47: Chris@47: class ImmediateBrokenPromiseNode final: public ImmediatePromiseNodeBase { Chris@47: public: Chris@47: ImmediateBrokenPromiseNode(Exception&& exception); Chris@47: Chris@47: void get(ExceptionOrValue& output) noexcept override; Chris@47: Chris@47: private: Chris@47: Exception exception; Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class AttachmentPromiseNodeBase: public PromiseNode { Chris@47: public: Chris@47: AttachmentPromiseNodeBase(Own&& dependency); Chris@47: Chris@47: void onReady(Event& event) noexcept override; Chris@47: void get(ExceptionOrValue& output) noexcept override; Chris@47: PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: private: Chris@47: Own dependency; Chris@47: Chris@47: void dropDependency(); Chris@47: Chris@47: template Chris@47: friend class AttachmentPromiseNode; Chris@47: }; Chris@47: Chris@47: template Chris@47: class AttachmentPromiseNode final: public AttachmentPromiseNodeBase { Chris@47: // A PromiseNode that holds on to some object (usually, an Own, but could be any movable Chris@47: // object) until the promise resolves. Chris@47: Chris@47: public: Chris@47: AttachmentPromiseNode(Own&& dependency, Attachment&& attachment) Chris@47: : AttachmentPromiseNodeBase(kj::mv(dependency)), Chris@47: attachment(kj::mv(attachment)) {} Chris@47: Chris@47: ~AttachmentPromiseNode() noexcept(false) { Chris@47: // We need to make sure the dependency is deleted before we delete the attachment because the Chris@47: // dependency may be using the attachment. Chris@47: dropDependency(); Chris@47: } Chris@47: Chris@47: private: Chris@47: Attachment attachment; Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class PtmfHelper { Chris@47: // This class is a private helper for GetFunctorStartAddress. The class represents the internal Chris@47: // representation of a pointer-to-member-function. Chris@47: Chris@47: template Chris@47: friend struct GetFunctorStartAddress; Chris@47: Chris@47: #if __GNUG__ Chris@47: void* ptr; Chris@47: ptrdiff_t adj; Chris@47: // Layout of a pointer-to-member-function used by GCC and compatible compilers. Chris@47: #else Chris@47: #error "TODO(port): PTMF instruction address extraction" Chris@47: #endif Chris@47: Chris@47: #define BODY \ Chris@47: PtmfHelper result; \ Chris@47: static_assert(sizeof(p) == sizeof(result), "unknown ptmf layout"); \ Chris@47: memcpy(&result, &p, sizeof(result)); \ Chris@47: return result Chris@47: Chris@47: template Chris@47: static PtmfHelper from(F p) { BODY; } Chris@47: // Create a PtmfHelper from some arbitrary pointer-to-member-function which is not Chris@47: // overloaded nor a template. In this case the compiler is able to deduce the full function Chris@47: // signature directly given the name since there is only one function with that name. Chris@47: Chris@47: template Chris@47: static PtmfHelper from(R (C::*p)(NoInfer

...)) { BODY; } Chris@47: template Chris@47: static PtmfHelper from(R (C::*p)(NoInfer

...) const) { BODY; } Chris@47: // Create a PtmfHelper from some poniter-to-member-function which is a template. In this case Chris@47: // the function must match exactly the containing type C, return type R, and parameter types P... Chris@47: // GetFunctorStartAddress normally specifies exactly the correct C and R, but can only make a Chris@47: // guess at P. Luckily, if the function parameters are template parameters then it's not Chris@47: // necessary to be precise about P. Chris@47: #undef BODY Chris@47: Chris@47: void* apply(void* obj) { Chris@47: #if defined(__arm__) || defined(__mips__) || defined(__aarch64__) Chris@47: if (adj & 1) { Chris@47: ptrdiff_t voff = (ptrdiff_t)ptr; Chris@47: #else Chris@47: ptrdiff_t voff = (ptrdiff_t)ptr; Chris@47: if (voff & 1) { Chris@47: voff &= ~1; Chris@47: #endif Chris@47: return *(void**)(*(char**)obj + voff); Chris@47: } else { Chris@47: return ptr; Chris@47: } Chris@47: } Chris@47: }; Chris@47: Chris@47: template Chris@47: struct GetFunctorStartAddress { Chris@47: // Given a functor (any object defining operator()), return the start address of the function, Chris@47: // suitable for passing to addr2line to obtain a source file/line for debugging purposes. Chris@47: // Chris@47: // This turns out to be incredibly hard to implement in the presence of overloaded or templated Chris@47: // functors. Therefore, we impose these specific restrictions, specific to our use case: Chris@47: // - Overloading is not allowed, but templating is. (Generally we only intend to support lambdas Chris@47: // anyway.) Chris@47: // - The template parameters to GetFunctorStartAddress specify a hint as to the expected Chris@47: // parameter types. If the functor is templated, its parameters must match exactly these types. Chris@47: // (If it's not templated, ParamTypes are ignored.) Chris@47: Chris@47: template Chris@47: static void* apply(Func&& func) { Chris@47: typedef decltype(func(instance()...)) ReturnType; Chris@47: return PtmfHelper::from, ParamTypes...>( Chris@47: &Decay::operator()).apply(&func); Chris@47: } Chris@47: }; Chris@47: Chris@47: template <> Chris@47: struct GetFunctorStartAddress: public GetFunctorStartAddress<> {}; Chris@47: // Hack for TransformPromiseNode use case: an input type of `Void` indicates that the function Chris@47: // actually has no parameters. Chris@47: Chris@47: class TransformPromiseNodeBase: public PromiseNode { Chris@47: public: Chris@47: TransformPromiseNodeBase(Own&& dependency, void* continuationTracePtr); Chris@47: Chris@47: void onReady(Event& event) noexcept override; Chris@47: void get(ExceptionOrValue& output) noexcept override; Chris@47: PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: private: Chris@47: Own dependency; Chris@47: void* continuationTracePtr; Chris@47: Chris@47: void dropDependency(); Chris@47: void getDepResult(ExceptionOrValue& output); Chris@47: Chris@47: virtual void getImpl(ExceptionOrValue& output) = 0; Chris@47: Chris@47: template Chris@47: friend class TransformPromiseNode; Chris@47: }; Chris@47: Chris@47: template Chris@47: class TransformPromiseNode final: public TransformPromiseNodeBase { Chris@47: // A PromiseNode that transforms the result of another PromiseNode through an application-provided Chris@47: // function (implements `then()`). Chris@47: Chris@47: public: Chris@47: TransformPromiseNode(Own&& dependency, Func&& func, ErrorFunc&& errorHandler) Chris@47: : TransformPromiseNodeBase(kj::mv(dependency), Chris@47: GetFunctorStartAddress::apply(func)), Chris@47: func(kj::fwd(func)), errorHandler(kj::fwd(errorHandler)) {} Chris@47: Chris@47: ~TransformPromiseNode() noexcept(false) { Chris@47: // We need to make sure the dependency is deleted before we delete the continuations because it Chris@47: // is a common pattern for the continuations to hold ownership of objects that might be in-use Chris@47: // by the dependency. Chris@47: dropDependency(); Chris@47: } Chris@47: Chris@47: private: Chris@47: Func func; Chris@47: ErrorFunc errorHandler; Chris@47: Chris@47: void getImpl(ExceptionOrValue& output) override { Chris@47: ExceptionOr depResult; Chris@47: getDepResult(depResult); Chris@47: KJ_IF_MAYBE(depException, depResult.exception) { Chris@47: output.as() = handle( Chris@47: MaybeVoidCaller>>::apply( Chris@47: errorHandler, kj::mv(*depException))); Chris@47: } else KJ_IF_MAYBE(depValue, depResult.value) { Chris@47: output.as() = handle(MaybeVoidCaller::apply(func, kj::mv(*depValue))); Chris@47: } Chris@47: } Chris@47: Chris@47: ExceptionOr handle(T&& value) { Chris@47: return kj::mv(value); Chris@47: } Chris@47: ExceptionOr handle(PropagateException::Bottom&& value) { Chris@47: return ExceptionOr(false, value.asException()); Chris@47: } Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class ForkHubBase; Chris@47: Chris@47: class ForkBranchBase: public PromiseNode { Chris@47: public: Chris@47: ForkBranchBase(Own&& hub); Chris@47: ~ForkBranchBase() noexcept(false); Chris@47: Chris@47: void hubReady() noexcept; Chris@47: // Called by the hub to indicate that it is ready. Chris@47: Chris@47: // implements PromiseNode ------------------------------------------ Chris@47: void onReady(Event& event) noexcept override; Chris@47: PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: protected: Chris@47: inline ExceptionOrValue& getHubResultRef(); Chris@47: Chris@47: void releaseHub(ExceptionOrValue& output); Chris@47: // Release the hub. If an exception is thrown, add it to `output`. Chris@47: Chris@47: private: Chris@47: OnReadyEvent onReadyEvent; Chris@47: Chris@47: Own hub; Chris@47: ForkBranchBase* next = nullptr; Chris@47: ForkBranchBase** prevPtr = nullptr; Chris@47: Chris@47: friend class ForkHubBase; Chris@47: }; Chris@47: Chris@47: template T copyOrAddRef(T& t) { return t; } Chris@47: template Own copyOrAddRef(Own& t) { return t->addRef(); } Chris@47: Chris@47: template Chris@47: class ForkBranch final: public ForkBranchBase { Chris@47: // A PromiseNode that implements one branch of a fork -- i.e. one of the branches that receives Chris@47: // a const reference. Chris@47: Chris@47: public: Chris@47: ForkBranch(Own&& hub): ForkBranchBase(kj::mv(hub)) {} Chris@47: Chris@47: void get(ExceptionOrValue& output) noexcept override { Chris@47: ExceptionOr& hubResult = getHubResultRef().template as(); Chris@47: KJ_IF_MAYBE(value, hubResult.value) { Chris@47: output.as().value = copyOrAddRef(*value); Chris@47: } else { Chris@47: output.as().value = nullptr; Chris@47: } Chris@47: output.exception = hubResult.exception; Chris@47: releaseHub(output); Chris@47: } Chris@47: }; Chris@47: Chris@47: template Chris@47: class SplitBranch final: public ForkBranchBase { Chris@47: // A PromiseNode that implements one branch of a fork -- i.e. one of the branches that receives Chris@47: // a const reference. Chris@47: Chris@47: public: Chris@47: SplitBranch(Own&& hub): ForkBranchBase(kj::mv(hub)) {} Chris@47: Chris@47: typedef kj::Decay(kj::instance()))> Element; Chris@47: Chris@47: void get(ExceptionOrValue& output) noexcept override { Chris@47: ExceptionOr& hubResult = getHubResultRef().template as(); Chris@47: KJ_IF_MAYBE(value, hubResult.value) { Chris@47: output.as().value = kj::mv(kj::get(*value)); Chris@47: } else { Chris@47: output.as().value = nullptr; Chris@47: } Chris@47: output.exception = hubResult.exception; Chris@47: releaseHub(output); Chris@47: } Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class ForkHubBase: public Refcounted, protected Event { Chris@47: public: Chris@47: ForkHubBase(Own&& inner, ExceptionOrValue& resultRef); Chris@47: Chris@47: inline ExceptionOrValue& getResultRef() { return resultRef; } Chris@47: Chris@47: private: Chris@47: Own inner; Chris@47: ExceptionOrValue& resultRef; Chris@47: Chris@47: ForkBranchBase* headBranch = nullptr; Chris@47: ForkBranchBase** tailBranch = &headBranch; Chris@47: // Tail becomes null once the inner promise is ready and all branches have been notified. Chris@47: Chris@47: Maybe> fire() override; Chris@47: _::PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: friend class ForkBranchBase; Chris@47: }; Chris@47: Chris@47: template Chris@47: class ForkHub final: public ForkHubBase { Chris@47: // A PromiseNode that implements the hub of a fork. The first call to Promise::fork() replaces Chris@47: // the promise's outer node with a ForkHub, and subsequent calls add branches to that hub (if Chris@47: // possible). Chris@47: Chris@47: public: Chris@47: ForkHub(Own&& inner): ForkHubBase(kj::mv(inner), result) {} Chris@47: Chris@47: Promise<_::UnfixVoid> addBranch() { Chris@47: return Promise<_::UnfixVoid>(false, kj::heap>(addRef(*this))); Chris@47: } Chris@47: Chris@47: _::SplitTuplePromise split() { Chris@47: return splitImpl(MakeIndexes()>()); Chris@47: } Chris@47: Chris@47: private: Chris@47: ExceptionOr result; Chris@47: Chris@47: template Chris@47: _::SplitTuplePromise splitImpl(Indexes) { Chris@47: return kj::tuple(addSplit()...); Chris@47: } Chris@47: Chris@47: template Chris@47: Promise::Element>> addSplit() { Chris@47: return Promise::Element>>( Chris@47: false, maybeChain(kj::heap>(addRef(*this)), Chris@47: implicitCast::Element*>(nullptr))); Chris@47: } Chris@47: }; Chris@47: Chris@47: inline ExceptionOrValue& ForkBranchBase::getHubResultRef() { Chris@47: return hub->getResultRef(); Chris@47: } Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class ChainPromiseNode final: public PromiseNode, public Event { Chris@47: // Promise node which reduces Promise> to Promise. Chris@47: // Chris@47: // `Event` is only a public base class because otherwise we can't cast Own to Chris@47: // Own. Ugh, templates and private... Chris@47: Chris@47: public: Chris@47: explicit ChainPromiseNode(Own inner); Chris@47: ~ChainPromiseNode() noexcept(false); Chris@47: Chris@47: void onReady(Event& event) noexcept override; Chris@47: void setSelfPointer(Own* selfPtr) noexcept override; Chris@47: void get(ExceptionOrValue& output) noexcept override; Chris@47: PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: private: Chris@47: enum State { Chris@47: STEP1, Chris@47: STEP2 Chris@47: }; Chris@47: Chris@47: State state; Chris@47: Chris@47: Own inner; Chris@47: // In STEP1, a PromiseNode for a Promise. Chris@47: // In STEP2, a PromiseNode for a T. Chris@47: Chris@47: Event* onReadyEvent = nullptr; Chris@47: Own* selfPtr = nullptr; Chris@47: Chris@47: Maybe> fire() override; Chris@47: }; Chris@47: Chris@47: template Chris@47: Own maybeChain(Own&& node, Promise*) { Chris@47: return heap(kj::mv(node)); Chris@47: } Chris@47: Chris@47: template Chris@47: Own&& maybeChain(Own&& node, T*) { Chris@47: return kj::mv(node); Chris@47: } Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class ExclusiveJoinPromiseNode final: public PromiseNode { Chris@47: public: Chris@47: ExclusiveJoinPromiseNode(Own left, Own right); Chris@47: ~ExclusiveJoinPromiseNode() noexcept(false); Chris@47: Chris@47: void onReady(Event& event) noexcept override; Chris@47: void get(ExceptionOrValue& output) noexcept override; Chris@47: PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: private: Chris@47: class Branch: public Event { Chris@47: public: Chris@47: Branch(ExclusiveJoinPromiseNode& joinNode, Own dependency); Chris@47: ~Branch() noexcept(false); Chris@47: Chris@47: bool get(ExceptionOrValue& output); Chris@47: // Returns true if this is the side that finished. Chris@47: Chris@47: Maybe> fire() override; Chris@47: _::PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: private: Chris@47: ExclusiveJoinPromiseNode& joinNode; Chris@47: Own dependency; Chris@47: }; Chris@47: Chris@47: Branch left; Chris@47: Branch right; Chris@47: OnReadyEvent onReadyEvent; Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class ArrayJoinPromiseNodeBase: public PromiseNode { Chris@47: public: Chris@47: ArrayJoinPromiseNodeBase(Array> promises, Chris@47: ExceptionOrValue* resultParts, size_t partSize); Chris@47: ~ArrayJoinPromiseNodeBase() noexcept(false); Chris@47: Chris@47: void onReady(Event& event) noexcept override final; Chris@47: void get(ExceptionOrValue& output) noexcept override final; Chris@47: PromiseNode* getInnerForTrace() override final; Chris@47: Chris@47: protected: Chris@47: virtual void getNoError(ExceptionOrValue& output) noexcept = 0; Chris@47: // Called to compile the result only in the case where there were no errors. Chris@47: Chris@47: private: Chris@47: uint countLeft; Chris@47: OnReadyEvent onReadyEvent; Chris@47: Chris@47: class Branch final: public Event { Chris@47: public: Chris@47: Branch(ArrayJoinPromiseNodeBase& joinNode, Own dependency, Chris@47: ExceptionOrValue& output); Chris@47: ~Branch() noexcept(false); Chris@47: Chris@47: Maybe> fire() override; Chris@47: _::PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: Maybe getPart(); Chris@47: // Calls dependency->get(output). If there was an exception, return it. Chris@47: Chris@47: private: Chris@47: ArrayJoinPromiseNodeBase& joinNode; Chris@47: Own dependency; Chris@47: ExceptionOrValue& output; Chris@47: }; Chris@47: Chris@47: Array branches; Chris@47: }; Chris@47: Chris@47: template Chris@47: class ArrayJoinPromiseNode final: public ArrayJoinPromiseNodeBase { Chris@47: public: Chris@47: ArrayJoinPromiseNode(Array> promises, Chris@47: Array> resultParts) Chris@47: : ArrayJoinPromiseNodeBase(kj::mv(promises), resultParts.begin(), sizeof(ExceptionOr)), Chris@47: resultParts(kj::mv(resultParts)) {} Chris@47: Chris@47: protected: Chris@47: void getNoError(ExceptionOrValue& output) noexcept override { Chris@47: auto builder = heapArrayBuilder(resultParts.size()); Chris@47: for (auto& part: resultParts) { Chris@47: KJ_IASSERT(part.value != nullptr, Chris@47: "Bug in KJ promise framework: Promise result had neither value no exception."); Chris@47: builder.add(kj::mv(*_::readMaybe(part.value))); Chris@47: } Chris@47: output.as>() = builder.finish(); Chris@47: } Chris@47: Chris@47: private: Chris@47: Array> resultParts; Chris@47: }; Chris@47: Chris@47: template <> Chris@47: class ArrayJoinPromiseNode final: public ArrayJoinPromiseNodeBase { Chris@47: public: Chris@47: ArrayJoinPromiseNode(Array> promises, Chris@47: Array> resultParts); Chris@47: ~ArrayJoinPromiseNode(); Chris@47: Chris@47: protected: Chris@47: void getNoError(ExceptionOrValue& output) noexcept override; Chris@47: Chris@47: private: Chris@47: Array> resultParts; Chris@47: }; Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class EagerPromiseNodeBase: public PromiseNode, protected Event { Chris@47: // A PromiseNode that eagerly evaluates its dependency even if its dependent does not eagerly Chris@47: // evaluate it. Chris@47: Chris@47: public: Chris@47: EagerPromiseNodeBase(Own&& dependency, ExceptionOrValue& resultRef); Chris@47: Chris@47: void onReady(Event& event) noexcept override; Chris@47: PromiseNode* getInnerForTrace() override; Chris@47: Chris@47: private: Chris@47: Own dependency; Chris@47: OnReadyEvent onReadyEvent; Chris@47: Chris@47: ExceptionOrValue& resultRef; Chris@47: Chris@47: Maybe> fire() override; Chris@47: }; Chris@47: Chris@47: template Chris@47: class EagerPromiseNode final: public EagerPromiseNodeBase { Chris@47: public: Chris@47: EagerPromiseNode(Own&& dependency) Chris@47: : EagerPromiseNodeBase(kj::mv(dependency), result) {} Chris@47: Chris@47: void get(ExceptionOrValue& output) noexcept override { Chris@47: output.as() = kj::mv(result); Chris@47: } Chris@47: Chris@47: private: Chris@47: ExceptionOr result; Chris@47: }; Chris@47: Chris@47: template Chris@47: Own spark(Own&& node) { Chris@47: // Forces evaluation of the given node to begin as soon as possible, even if no one is waiting Chris@47: // on it. Chris@47: return heap>(kj::mv(node)); Chris@47: } Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: class AdapterPromiseNodeBase: public PromiseNode { Chris@47: public: Chris@47: void onReady(Event& event) noexcept override; Chris@47: Chris@47: protected: Chris@47: inline void setReady() { Chris@47: onReadyEvent.arm(); Chris@47: } Chris@47: Chris@47: private: Chris@47: OnReadyEvent onReadyEvent; Chris@47: }; Chris@47: Chris@47: template Chris@47: class AdapterPromiseNode final: public AdapterPromiseNodeBase, Chris@47: private PromiseFulfiller> { Chris@47: // A PromiseNode that wraps a PromiseAdapter. Chris@47: Chris@47: public: Chris@47: template Chris@47: AdapterPromiseNode(Params&&... params) Chris@47: : adapter(static_cast>&>(*this), kj::fwd(params)...) {} Chris@47: Chris@47: void get(ExceptionOrValue& output) noexcept override { Chris@47: KJ_IREQUIRE(!isWaiting()); Chris@47: output.as() = kj::mv(result); Chris@47: } Chris@47: Chris@47: private: Chris@47: ExceptionOr result; Chris@47: bool waiting = true; Chris@47: Adapter adapter; Chris@47: Chris@47: void fulfill(T&& value) override { Chris@47: if (waiting) { Chris@47: waiting = false; Chris@47: result = ExceptionOr(kj::mv(value)); Chris@47: setReady(); Chris@47: } Chris@47: } Chris@47: Chris@47: void reject(Exception&& exception) override { Chris@47: if (waiting) { Chris@47: waiting = false; Chris@47: result = ExceptionOr(false, kj::mv(exception)); Chris@47: setReady(); Chris@47: } Chris@47: } Chris@47: Chris@47: bool isWaiting() override { Chris@47: return waiting; Chris@47: } Chris@47: }; Chris@47: Chris@47: } // namespace _ (private) Chris@47: Chris@47: // ======================================================================================= Chris@47: Chris@47: template Chris@47: Promise::Promise(_::FixVoid value) Chris@47: : PromiseBase(heap<_::ImmediatePromiseNode<_::FixVoid>>(kj::mv(value))) {} Chris@47: Chris@47: template Chris@47: Promise::Promise(kj::Exception&& exception) Chris@47: : PromiseBase(heap<_::ImmediateBrokenPromiseNode>(kj::mv(exception))) {} Chris@47: Chris@47: template Chris@47: template Chris@47: PromiseForResult Promise::then(Func&& func, ErrorFunc&& errorHandler) { Chris@47: typedef _::FixVoid<_::ReturnType> ResultT; Chris@47: Chris@47: Own<_::PromiseNode> intermediate = Chris@47: heap<_::TransformPromiseNode, Func, ErrorFunc>>( Chris@47: kj::mv(node), kj::fwd(func), kj::fwd(errorHandler)); Chris@47: return PromiseForResult(false, Chris@47: _::maybeChain(kj::mv(intermediate), implicitCast(nullptr))); Chris@47: } Chris@47: Chris@47: namespace _ { // private Chris@47: Chris@47: template Chris@47: struct IdentityFunc { Chris@47: inline T operator()(T&& value) const { Chris@47: return kj::mv(value); Chris@47: } Chris@47: }; Chris@47: template Chris@47: struct IdentityFunc> { Chris@47: inline Promise operator()(T&& value) const { Chris@47: return kj::mv(value); Chris@47: } Chris@47: }; Chris@47: template <> Chris@47: struct IdentityFunc { Chris@47: inline void operator()() const {} Chris@47: }; Chris@47: template <> Chris@47: struct IdentityFunc> { Chris@47: Promise operator()() const; Chris@47: // This can't be inline because it will make the translation unit depend on kj-async. Awkwardly, Chris@47: // Cap'n Proto relies on being able to include this header without creating such a link-time Chris@47: // dependency. Chris@47: }; Chris@47: Chris@47: } // namespace _ (private) Chris@47: Chris@47: template Chris@47: template Chris@47: Promise Promise::catch_(ErrorFunc&& errorHandler) { Chris@47: // then()'s ErrorFunc can only return a Promise if Func also returns a Promise. In this case, Chris@47: // Func is being filled in automatically. We want to make sure ErrorFunc can return a Promise, Chris@47: // but we don't want the extra overhead of promise chaining if ErrorFunc doesn't actually Chris@47: // return a promise. So we make our Func return match ErrorFunc. Chris@47: return then(_::IdentityFunc()))>(), Chris@47: kj::fwd(errorHandler)); Chris@47: } Chris@47: Chris@47: template Chris@47: T Promise::wait(WaitScope& waitScope) { Chris@47: _::ExceptionOr<_::FixVoid> result; Chris@47: Chris@47: waitImpl(kj::mv(node), result, waitScope); Chris@47: Chris@47: KJ_IF_MAYBE(value, result.value) { Chris@47: KJ_IF_MAYBE(exception, result.exception) { Chris@47: throwRecoverableException(kj::mv(*exception)); Chris@47: } Chris@47: return _::returnMaybeVoid(kj::mv(*value)); Chris@47: } else KJ_IF_MAYBE(exception, result.exception) { Chris@47: throwFatalException(kj::mv(*exception)); Chris@47: } else { Chris@47: // Result contained neither a value nor an exception? Chris@47: KJ_UNREACHABLE; Chris@47: } Chris@47: } Chris@47: Chris@47: template Chris@47: ForkedPromise Promise::fork() { Chris@47: return ForkedPromise(false, refcounted<_::ForkHub<_::FixVoid>>(kj::mv(node))); Chris@47: } Chris@47: Chris@47: template Chris@47: Promise ForkedPromise::addBranch() { Chris@47: return hub->addBranch(); Chris@47: } Chris@47: Chris@47: template Chris@47: _::SplitTuplePromise Promise::split() { Chris@47: return refcounted<_::ForkHub<_::FixVoid>>(kj::mv(node))->split(); Chris@47: } Chris@47: Chris@47: template Chris@47: Promise Promise::exclusiveJoin(Promise&& other) { Chris@47: return Promise(false, heap<_::ExclusiveJoinPromiseNode>(kj::mv(node), kj::mv(other.node))); Chris@47: } Chris@47: Chris@47: template Chris@47: template Chris@47: Promise Promise::attach(Attachments&&... attachments) { Chris@47: return Promise(false, kj::heap<_::AttachmentPromiseNode>>( Chris@47: kj::mv(node), kj::tuple(kj::fwd(attachments)...))); Chris@47: } Chris@47: Chris@47: template Chris@47: template Chris@47: Promise Promise::eagerlyEvaluate(ErrorFunc&& errorHandler) { Chris@47: // See catch_() for commentary. Chris@47: return Promise(false, _::spark<_::FixVoid>(then( Chris@47: _::IdentityFunc()))>(), Chris@47: kj::fwd(errorHandler)).node)); Chris@47: } Chris@47: Chris@47: template Chris@47: Promise Promise::eagerlyEvaluate(decltype(nullptr)) { Chris@47: return Promise(false, _::spark<_::FixVoid>(kj::mv(node))); Chris@47: } Chris@47: Chris@47: template Chris@47: kj::String Promise::trace() { Chris@47: return PromiseBase::trace(); Chris@47: } Chris@47: Chris@47: template Chris@47: inline PromiseForResult evalLater(Func&& func) { Chris@47: return _::yield().then(kj::fwd(func), _::PropagateException()); Chris@47: } Chris@47: Chris@47: template Chris@47: inline PromiseForResult evalNow(Func&& func) { Chris@47: PromiseForResult result = nullptr; Chris@47: KJ_IF_MAYBE(e, kj::runCatchingExceptions([&]() { Chris@47: result = func(); Chris@47: })) { Chris@47: result = kj::mv(*e); Chris@47: } Chris@47: return result; Chris@47: } Chris@47: Chris@47: template Chris@47: template Chris@47: void Promise::detach(ErrorFunc&& errorHandler) { Chris@47: return _::detach(then([](T&&) {}, kj::fwd(errorHandler))); Chris@47: } Chris@47: Chris@47: template <> Chris@47: template Chris@47: void Promise::detach(ErrorFunc&& errorHandler) { Chris@47: return _::detach(then([]() {}, kj::fwd(errorHandler))); Chris@47: } Chris@47: Chris@47: template Chris@47: Promise> joinPromises(Array>&& promises) { Chris@47: return Promise>(false, kj::heap<_::ArrayJoinPromiseNode>( Chris@47: KJ_MAP(p, promises) { return kj::mv(p.node); }, Chris@47: heapArray<_::ExceptionOr>(promises.size()))); Chris@47: } Chris@47: Chris@47: // ======================================================================================= Chris@47: Chris@47: namespace _ { // private Chris@47: Chris@47: template Chris@47: class WeakFulfiller final: public PromiseFulfiller, private kj::Disposer { Chris@47: // A wrapper around PromiseFulfiller which can be detached. Chris@47: // Chris@47: // There are a couple non-trivialities here: Chris@47: // - If the WeakFulfiller is discarded, we want the promise it fulfills to be implicitly Chris@47: // rejected. Chris@47: // - We cannot destroy the WeakFulfiller until the application has discarded it *and* it has been Chris@47: // detached from the underlying fulfiller, because otherwise the later detach() call will go Chris@47: // to a dangling pointer. Essentially, WeakFulfiller is reference counted, although the Chris@47: // refcount never goes over 2 and we manually implement the refcounting because we need to do Chris@47: // other special things when each side detaches anyway. To this end, WeakFulfiller is its own Chris@47: // Disposer -- dispose() is called when the application discards its owned pointer to the Chris@47: // fulfiller and detach() is called when the promise is destroyed. Chris@47: Chris@47: public: Chris@47: KJ_DISALLOW_COPY(WeakFulfiller); Chris@47: Chris@47: static kj::Own make() { Chris@47: WeakFulfiller* ptr = new WeakFulfiller; Chris@47: return Own(ptr, *ptr); Chris@47: } Chris@47: Chris@47: void fulfill(FixVoid&& value) override { Chris@47: if (inner != nullptr) { Chris@47: inner->fulfill(kj::mv(value)); Chris@47: } Chris@47: } Chris@47: Chris@47: void reject(Exception&& exception) override { Chris@47: if (inner != nullptr) { Chris@47: inner->reject(kj::mv(exception)); Chris@47: } Chris@47: } Chris@47: Chris@47: bool isWaiting() override { Chris@47: return inner != nullptr && inner->isWaiting(); Chris@47: } Chris@47: Chris@47: void attach(PromiseFulfiller& newInner) { Chris@47: inner = &newInner; Chris@47: } Chris@47: Chris@47: void detach(PromiseFulfiller& from) { Chris@47: if (inner == nullptr) { Chris@47: // Already disposed. Chris@47: delete this; Chris@47: } else { Chris@47: KJ_IREQUIRE(inner == &from); Chris@47: inner = nullptr; Chris@47: } Chris@47: } Chris@47: Chris@47: private: Chris@47: mutable PromiseFulfiller* inner; Chris@47: Chris@47: WeakFulfiller(): inner(nullptr) {} Chris@47: Chris@47: void disposeImpl(void* pointer) const override { Chris@47: // TODO(perf): Factor some of this out so it isn't regenerated for every fulfiller type? Chris@47: Chris@47: if (inner == nullptr) { Chris@47: // Already detached. Chris@47: delete this; Chris@47: } else { Chris@47: if (inner->isWaiting()) { Chris@47: inner->reject(kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__, Chris@47: kj::heapString("PromiseFulfiller was destroyed without fulfilling the promise."))); Chris@47: } Chris@47: inner = nullptr; Chris@47: } Chris@47: } Chris@47: }; Chris@47: Chris@47: template Chris@47: class PromiseAndFulfillerAdapter { Chris@47: public: Chris@47: PromiseAndFulfillerAdapter(PromiseFulfiller& fulfiller, Chris@47: WeakFulfiller& wrapper) Chris@47: : fulfiller(fulfiller), wrapper(wrapper) { Chris@47: wrapper.attach(fulfiller); Chris@47: } Chris@47: Chris@47: ~PromiseAndFulfillerAdapter() noexcept(false) { Chris@47: wrapper.detach(fulfiller); Chris@47: } Chris@47: Chris@47: private: Chris@47: PromiseFulfiller& fulfiller; Chris@47: WeakFulfiller& wrapper; Chris@47: }; Chris@47: Chris@47: } // namespace _ (private) Chris@47: Chris@47: template Chris@47: template Chris@47: bool PromiseFulfiller::rejectIfThrows(Func&& func) { Chris@47: KJ_IF_MAYBE(exception, kj::runCatchingExceptions(kj::mv(func))) { Chris@47: reject(kj::mv(*exception)); Chris@47: return false; Chris@47: } else { Chris@47: return true; Chris@47: } Chris@47: } Chris@47: Chris@47: template Chris@47: bool PromiseFulfiller::rejectIfThrows(Func&& func) { Chris@47: KJ_IF_MAYBE(exception, kj::runCatchingExceptions(kj::mv(func))) { Chris@47: reject(kj::mv(*exception)); Chris@47: return false; Chris@47: } else { Chris@47: return true; Chris@47: } Chris@47: } Chris@47: Chris@47: template Chris@47: Promise newAdaptedPromise(Params&&... adapterConstructorParams) { Chris@47: return Promise(false, heap<_::AdapterPromiseNode<_::FixVoid, Adapter>>( Chris@47: kj::fwd(adapterConstructorParams)...)); Chris@47: } Chris@47: Chris@47: template Chris@47: PromiseFulfillerPair newPromiseAndFulfiller() { Chris@47: auto wrapper = _::WeakFulfiller::make(); Chris@47: Chris@47: Own<_::PromiseNode> intermediate( Chris@47: heap<_::AdapterPromiseNode<_::FixVoid, _::PromiseAndFulfillerAdapter>>(*wrapper)); Chris@47: Promise<_::JoinPromises> promise(false, Chris@47: _::maybeChain(kj::mv(intermediate), implicitCast(nullptr))); Chris@47: Chris@47: return PromiseFulfillerPair { kj::mv(promise), kj::mv(wrapper) }; Chris@47: } Chris@47: Chris@47: } // namespace kj Chris@47: Chris@47: #endif // KJ_ASYNC_INL_H_