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

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

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