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

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

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