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

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

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