Chris@64: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@64: // Licensed under the MIT License: Chris@64: // Chris@64: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@64: // of this software and associated documentation files (the "Software"), to deal Chris@64: // in the Software without restriction, including without limitation the rights Chris@64: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@64: // copies of the Software, and to permit persons to whom the Software is Chris@64: // furnished to do so, subject to the following conditions: Chris@64: // Chris@64: // The above copyright notice and this permission notice shall be included in Chris@64: // all copies or substantial portions of the Software. Chris@64: // Chris@64: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@64: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@64: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@64: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@64: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@64: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@64: // THE SOFTWARE. Chris@64: Chris@64: #ifndef KJ_ASYNC_H_ Chris@64: #define KJ_ASYNC_H_ Chris@64: Chris@64: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@64: #pragma GCC system_header Chris@64: #endif Chris@64: Chris@64: #include "async-prelude.h" Chris@64: #include "exception.h" Chris@64: #include "refcount.h" Chris@64: Chris@64: namespace kj { Chris@64: Chris@64: class EventLoop; Chris@64: class WaitScope; Chris@64: Chris@64: template Chris@64: class Promise; Chris@64: template Chris@64: class ForkedPromise; Chris@64: template Chris@64: class PromiseFulfiller; Chris@64: template Chris@64: struct PromiseFulfillerPair; Chris@64: Chris@64: template Chris@64: using PromiseForResult = Promise<_::JoinPromises<_::ReturnType>>; Chris@64: // Evaluates to the type of Promise for the result of calling functor type Func with parameter type Chris@64: // T. If T is void, then the promise is for the result of calling Func with no arguments. If Chris@64: // Func itself returns a promise, the promises are joined, so you never get Promise>. Chris@64: Chris@64: // ======================================================================================= Chris@64: // Promises Chris@64: Chris@64: template Chris@64: class Promise: protected _::PromiseBase { Chris@64: // The basic primitive of asynchronous computation in KJ. Similar to "futures", but designed Chris@64: // specifically for event loop concurrency. Similar to E promises and JavaScript Promises/A. Chris@64: // Chris@64: // A Promise represents a promise to produce a value of type T some time in the future. Once Chris@64: // that value has been produced, the promise is "fulfilled". Alternatively, a promise can be Chris@64: // "broken", with an Exception describing what went wrong. You may implicitly convert a value of Chris@64: // type T to an already-fulfilled Promise. You may implicitly convert the constant Chris@64: // `kj::READY_NOW` to an already-fulfilled Promise. You may also implicitly convert a Chris@64: // `kj::Exception` to an already-broken promise of any type. Chris@64: // Chris@64: // Promises are linear types -- they are moveable but not copyable. If a Promise is destroyed Chris@64: // or goes out of scope (without being moved elsewhere), any ongoing asynchronous operations Chris@64: // meant to fulfill the promise will be canceled if possible. All methods of `Promise` (unless Chris@64: // otherwise noted) actually consume the promise in the sense of move semantics. (Arguably they Chris@64: // should be rvalue-qualified, but at the time this interface was created compilers didn't widely Chris@64: // support that yet and anyway it would be pretty ugly typing kj::mv(promise).whatever().) If Chris@64: // you want to use one Promise in two different places, you must fork it with `fork()`. Chris@64: // Chris@64: // To use the result of a Promise, you must call `then()` and supply a callback function to Chris@64: // call with the result. `then()` returns another promise, for the result of the callback. Chris@64: // Any time that this would result in Promise>, the promises are collapsed into a Chris@64: // simple Promise that first waits for the outer promise, then the inner. Example: Chris@64: // Chris@64: // // Open a remote file, read the content, and then count the Chris@64: // // number of lines of text. Chris@64: // // Note that none of the calls here block. `file`, `content` Chris@64: // // and `lineCount` are all initialized immediately before any Chris@64: // // asynchronous operations occur. The lambda callbacks are Chris@64: // // called later. Chris@64: // Promise> file = openFtp("ftp://host/foo/bar"); Chris@64: // Promise content = file.then( Chris@64: // [](Own file) -> Promise { Chris@64: // return file.readAll(); Chris@64: // }); Chris@64: // Promise lineCount = content.then( Chris@64: // [](String text) -> int { Chris@64: // uint count = 0; Chris@64: // for (char c: text) count += (c == '\n'); Chris@64: // return count; Chris@64: // }); Chris@64: // Chris@64: // For `then()` to work, the current thread must have an active `EventLoop`. Each callback Chris@64: // is scheduled to execute in that loop. Since `then()` schedules callbacks only on the current Chris@64: // thread's event loop, you do not need to worry about two callbacks running at the same time. Chris@64: // You will need to set up at least one `EventLoop` at the top level of your program before you Chris@64: // can use promises. Chris@64: // Chris@64: // To adapt a non-Promise-based asynchronous API to promises, use `newAdaptedPromise()`. Chris@64: // Chris@64: // Systems using promises should consider supporting the concept of "pipelining". Pipelining Chris@64: // means allowing a caller to start issuing method calls against a promised object before the Chris@64: // promise has actually been fulfilled. This is particularly useful if the promise is for a Chris@64: // remote object living across a network, as this can avoid round trips when chaining a series Chris@64: // of calls. It is suggested that any class T which supports pipelining implement a subclass of Chris@64: // Promise which adds "eventual send" methods -- methods which, when called, say "please Chris@64: // invoke the corresponding method on the promised value once it is available". These methods Chris@64: // should in turn return promises for the eventual results of said invocations. Cap'n Proto, Chris@64: // for example, implements the type `RemotePromise` which supports pipelining RPC requests -- see Chris@64: // `capnp/capability.h`. Chris@64: // Chris@64: // KJ Promises are based on E promises: Chris@64: // http://wiki.erights.org/wiki/Walnut/Distributed_Computing#Promises Chris@64: // Chris@64: // KJ Promises are also inspired in part by the evolving standards for JavaScript/ECMAScript Chris@64: // promises, which are themselves influenced by E promises: Chris@64: // http://promisesaplus.com/ Chris@64: // https://github.com/domenic/promises-unwrapping Chris@64: Chris@64: public: Chris@64: Promise(_::FixVoid value); Chris@64: // Construct an already-fulfilled Promise from a value of type T. For non-void promises, the Chris@64: // parameter type is simply T. So, e.g., in a function that returns `Promise`, you can Chris@64: // say `return 123;` to return a promise that is already fulfilled to 123. Chris@64: // Chris@64: // For void promises, use `kj::READY_NOW` as the value, e.g. `return kj::READY_NOW`. Chris@64: Chris@64: Promise(kj::Exception&& e); Chris@64: // Construct an already-broken Promise. Chris@64: Chris@64: inline Promise(decltype(nullptr)) {} Chris@64: Chris@64: template Chris@64: PromiseForResult then(Func&& func, ErrorFunc&& errorHandler = _::PropagateException()) Chris@64: KJ_WARN_UNUSED_RESULT; Chris@64: // Register a continuation function to be executed when the promise completes. The continuation Chris@64: // (`func`) takes the promised value (an rvalue of type `T`) as its parameter. The continuation Chris@64: // may return a new value; `then()` itself returns a promise for the continuation's eventual Chris@64: // result. If the continuation itself returns a `Promise`, then `then()` shall also return Chris@64: // a `Promise` which first waits for the original promise, then executes the continuation, Chris@64: // then waits for the inner promise (i.e. it automatically "unwraps" the promise). Chris@64: // Chris@64: // In all cases, `then()` returns immediately. The continuation is executed later. The Chris@64: // continuation is always executed on the same EventLoop (and, therefore, the same thread) which Chris@64: // called `then()`, therefore no synchronization is necessary on state shared by the continuation Chris@64: // and the surrounding scope. If no EventLoop is running on the current thread, `then()` throws Chris@64: // an exception. Chris@64: // Chris@64: // You may also specify an error handler continuation as the second parameter. `errorHandler` Chris@64: // must be a functor taking a parameter of type `kj::Exception&&`. It must return the same Chris@64: // type as `func` returns (except when `func` returns `Promise`, in which case `errorHandler` Chris@64: // may return either `Promise` or just `U`). The default error handler simply propagates the Chris@64: // exception to the returned promise. Chris@64: // Chris@64: // Either `func` or `errorHandler` may, of course, throw an exception, in which case the promise Chris@64: // is broken. When compiled with -fno-exceptions, the framework will still detect when a Chris@64: // recoverable exception was thrown inside of a continuation and will consider the promise Chris@64: // broken even though a (presumably garbage) result was returned. Chris@64: // Chris@64: // If the returned promise is destroyed before the callback runs, the callback will be canceled Chris@64: // (it will never run). Chris@64: // Chris@64: // Note that `then()` -- like all other Promise methods -- consumes the promise on which it is Chris@64: // called, in the sense of move semantics. After returning, the original promise is no longer Chris@64: // valid, but `then()` returns a new promise. Chris@64: // Chris@64: // *Advanced implementation tips:* Most users will never need to worry about the below, but Chris@64: // it is good to be aware of. Chris@64: // Chris@64: // As an optimization, if the callback function `func` does _not_ return another promise, then Chris@64: // execution of `func` itself may be delayed until its result is known to be needed. The Chris@64: // expectation here is that `func` is just doing some transformation on the results, not Chris@64: // scheduling any other actions, therefore the system doesn't need to be proactive about Chris@64: // evaluating it. This way, a chain of trivial then() transformations can be executed all at Chris@64: // once without repeatedly re-scheduling through the event loop. Use the `eagerlyEvaluate()` Chris@64: // method to suppress this behavior. Chris@64: // Chris@64: // On the other hand, if `func` _does_ return another promise, then the system evaluates `func` Chris@64: // as soon as possible, because the promise it returns might be for a newly-scheduled Chris@64: // long-running asynchronous task. Chris@64: // Chris@64: // As another optimization, when a callback function registered with `then()` is actually Chris@64: // scheduled, it is scheduled to occur immediately, preempting other work in the event queue. Chris@64: // This allows a long chain of `then`s to execute all at once, improving cache locality by Chris@64: // clustering operations on the same data. However, this implies that starvation can occur Chris@64: // if a chain of `then()`s takes a very long time to execute without ever stopping to wait for Chris@64: // actual I/O. To solve this, use `kj::evalLater()` to yield control; this way, all other events Chris@64: // in the queue will get a chance to run before your callback is executed. Chris@64: Chris@64: Promise ignoreResult() KJ_WARN_UNUSED_RESULT { return then([](T&&) {}); } Chris@64: // Convenience method to convert the promise to a void promise by ignoring the return value. Chris@64: // Chris@64: // You must still wait on the returned promise if you want the task to execute. Chris@64: Chris@64: template Chris@64: Promise catch_(ErrorFunc&& errorHandler) KJ_WARN_UNUSED_RESULT; Chris@64: // Equivalent to `.then(identityFunc, errorHandler)`, where `identifyFunc` is a function that Chris@64: // just returns its input. Chris@64: Chris@64: T wait(WaitScope& waitScope); Chris@64: // Run the event loop until the promise is fulfilled, then return its result. If the promise Chris@64: // is rejected, throw an exception. Chris@64: // Chris@64: // wait() is primarily useful at the top level of a program -- typically, within the function Chris@64: // that allocated the EventLoop. For example, a program that performs one or two RPCs and then Chris@64: // exits would likely use wait() in its main() function to wait on each RPC. On the other hand, Chris@64: // server-side code generally cannot use wait(), because it has to be able to accept multiple Chris@64: // requests at once. Chris@64: // Chris@64: // If the promise is rejected, `wait()` throws an exception. If the program was compiled without Chris@64: // exceptions (-fno-exceptions), this will usually abort. In this case you really should first Chris@64: // use `then()` to set an appropriate handler for the exception case, so that the promise you Chris@64: // actually wait on never throws. Chris@64: // Chris@64: // `waitScope` is an object proving that the caller is in a scope where wait() is allowed. By Chris@64: // convention, any function which might call wait(), or which might call another function which Chris@64: // might call wait(), must take `WaitScope&` as one of its parameters. This is needed for two Chris@64: // reasons: Chris@64: // * `wait()` is not allowed during an event callback, because event callbacks are themselves Chris@64: // called during some other `wait()`, and such recursive `wait()`s would only be able to Chris@64: // complete in LIFO order, which might mean that the outer `wait()` ends up waiting longer Chris@64: // than it is supposed to. To prevent this, a `WaitScope` cannot be constructed or used during Chris@64: // an event callback. Chris@64: // * Since `wait()` runs the event loop, unrelated event callbacks may execute before `wait()` Chris@64: // returns. This means that anyone calling `wait()` must be reentrant -- state may change Chris@64: // around them in arbitrary ways. Therefore, callers really need to know if a function they Chris@64: // are calling might wait(), and the `WaitScope&` parameter makes this clear. Chris@64: // Chris@64: // TODO(someday): Implement fibers, and let them call wait() even when they are handling an Chris@64: // event. Chris@64: Chris@64: ForkedPromise fork() KJ_WARN_UNUSED_RESULT; Chris@64: // Forks the promise, so that multiple different clients can independently wait on the result. Chris@64: // `T` must be copy-constructable for this to work. Or, in the special case where `T` is Chris@64: // `Own`, `U` must have a method `Own addRef()` which returns a new reference to the same Chris@64: // (or an equivalent) object (probably implemented via reference counting). Chris@64: Chris@64: _::SplitTuplePromise split(); Chris@64: // Split a promise for a tuple into a tuple of promises. Chris@64: // Chris@64: // E.g. if you have `Promise>`, `split()` returns Chris@64: // `kj::Tuple, Promise>`. Chris@64: Chris@64: Promise exclusiveJoin(Promise&& other) KJ_WARN_UNUSED_RESULT; Chris@64: // Return a new promise that resolves when either the original promise resolves or `other` Chris@64: // resolves (whichever comes first). The promise that didn't resolve first is canceled. Chris@64: Chris@64: // TODO(someday): inclusiveJoin(), or perhaps just join(), which waits for both completions Chris@64: // and produces a tuple? Chris@64: Chris@64: template Chris@64: Promise attach(Attachments&&... attachments) KJ_WARN_UNUSED_RESULT; Chris@64: // "Attaches" one or more movable objects (often, Owns) to the promise, such that they will Chris@64: // be destroyed when the promise resolves. This is useful when a promise's callback contains Chris@64: // pointers into some object and you want to make sure the object still exists when the callback Chris@64: // runs -- after calling then(), use attach() to add necessary objects to the result. Chris@64: Chris@64: template Chris@64: Promise eagerlyEvaluate(ErrorFunc&& errorHandler) KJ_WARN_UNUSED_RESULT; Chris@64: Promise eagerlyEvaluate(decltype(nullptr)) KJ_WARN_UNUSED_RESULT; Chris@64: // Force eager evaluation of this promise. Use this if you are going to hold on to the promise Chris@64: // for awhile without consuming the result, but you want to make sure that the system actually Chris@64: // processes it. Chris@64: // Chris@64: // `errorHandler` is a function that takes `kj::Exception&&`, like the second parameter to Chris@64: // `then()`, except that it must return void. We make you specify this because otherwise it's Chris@64: // easy to forget to handle errors in a promise that you never use. You may specify nullptr for Chris@64: // the error handler if you are sure that ignoring errors is fine, or if you know that you'll Chris@64: // eventually wait on the promise somewhere. Chris@64: Chris@64: template Chris@64: void detach(ErrorFunc&& errorHandler); Chris@64: // Allows the promise to continue running in the background until it completes or the Chris@64: // `EventLoop` is destroyed. Be careful when using this: since you can no longer cancel this Chris@64: // promise, you need to make sure that the promise owns all the objects it touches or make sure Chris@64: // those objects outlive the EventLoop. Chris@64: // Chris@64: // `errorHandler` is a function that takes `kj::Exception&&`, like the second parameter to Chris@64: // `then()`, except that it must return void. Chris@64: // Chris@64: // This function exists mainly to implement the Cap'n Proto requirement that RPC calls cannot be Chris@64: // canceled unless the callee explicitly permits it. Chris@64: Chris@64: kj::String trace(); Chris@64: // Returns a dump of debug info about this promise. Not for production use. Requires RTTI. Chris@64: // This method does NOT consume the promise as other methods do. Chris@64: Chris@64: private: Chris@64: Promise(bool, Own<_::PromiseNode>&& node): PromiseBase(kj::mv(node)) {} Chris@64: // Second parameter prevent ambiguity with immediate-value constructor. Chris@64: Chris@64: template Chris@64: friend class Promise; Chris@64: friend class EventLoop; Chris@64: template Chris@64: friend Promise newAdaptedPromise(Params&&... adapterConstructorParams); Chris@64: template Chris@64: friend PromiseFulfillerPair newPromiseAndFulfiller(); Chris@64: template Chris@64: friend class _::ForkHub; Chris@64: friend class _::TaskSetImpl; Chris@64: friend Promise _::yield(); Chris@64: friend class _::NeverDone; Chris@64: template Chris@64: friend Promise> joinPromises(Array>&& promises); Chris@64: friend Promise joinPromises(Array>&& promises); Chris@64: }; Chris@64: Chris@64: template Chris@64: class ForkedPromise { Chris@64: // The result of `Promise::fork()` and `EventLoop::fork()`. Allows branches to be created. Chris@64: // Like `Promise`, this is a pass-by-move type. Chris@64: Chris@64: public: Chris@64: inline ForkedPromise(decltype(nullptr)) {} Chris@64: Chris@64: Promise addBranch(); Chris@64: // Add a new branch to the fork. The branch is equivalent to the original promise. Chris@64: Chris@64: private: Chris@64: Own<_::ForkHub<_::FixVoid>> hub; Chris@64: Chris@64: inline ForkedPromise(bool, Own<_::ForkHub<_::FixVoid>>&& hub): hub(kj::mv(hub)) {} Chris@64: Chris@64: friend class Promise; Chris@64: friend class EventLoop; Chris@64: }; Chris@64: Chris@64: constexpr _::Void READY_NOW = _::Void(); Chris@64: // Use this when you need a Promise that is already fulfilled -- this value can be implicitly Chris@64: // cast to `Promise`. Chris@64: Chris@64: constexpr _::NeverDone NEVER_DONE = _::NeverDone(); Chris@64: // The opposite of `READY_NOW`, return this when the promise should never resolve. This can be Chris@64: // implicitly converted to any promise type. You may also call `NEVER_DONE.wait()` to wait Chris@64: // forever (useful for servers). Chris@64: Chris@64: template Chris@64: PromiseForResult evalLater(Func&& func) KJ_WARN_UNUSED_RESULT; Chris@64: // Schedule for the given zero-parameter function to be executed in the event loop at some Chris@64: // point in the near future. Returns a Promise for its result -- or, if `func()` itself returns Chris@64: // a promise, `evalLater()` returns a Promise for the result of resolving that promise. Chris@64: // Chris@64: // Example usage: Chris@64: // Promise x = evalLater([]() { return 123; }); Chris@64: // Chris@64: // The above is exactly equivalent to: Chris@64: // Promise x = Promise(READY_NOW).then([]() { return 123; }); Chris@64: // Chris@64: // If the returned promise is destroyed before the callback runs, the callback will be canceled Chris@64: // (never called). Chris@64: // Chris@64: // If you schedule several evaluations with `evalLater` during the same callback, they are Chris@64: // guaranteed to be executed in order. Chris@64: Chris@64: template Chris@64: PromiseForResult evalNow(Func&& func) KJ_WARN_UNUSED_RESULT; Chris@64: // Run `func()` and return a promise for its result. `func()` executes before `evalNow()` returns. Chris@64: // If `func()` throws an exception, the exception is caught and wrapped in a promise -- this is the Chris@64: // main reason why `evalNow()` is useful. Chris@64: Chris@64: template Chris@64: Promise> joinPromises(Array>&& promises); Chris@64: // Join an array of promises into a promise for an array. Chris@64: Chris@64: // ======================================================================================= Chris@64: // Hack for creating a lambda that holds an owned pointer. Chris@64: Chris@64: template Chris@64: class CaptureByMove { Chris@64: public: Chris@64: inline CaptureByMove(Func&& func, MovedParam&& param) Chris@64: : func(kj::mv(func)), param(kj::mv(param)) {} Chris@64: Chris@64: template Chris@64: inline auto operator()(Params&&... params) Chris@64: -> decltype(kj::instance()(kj::instance(), kj::fwd(params)...)) { Chris@64: return func(kj::mv(param), kj::fwd(params)...); Chris@64: } Chris@64: Chris@64: private: Chris@64: Func func; Chris@64: MovedParam param; Chris@64: }; Chris@64: Chris@64: template Chris@64: inline CaptureByMove> mvCapture(MovedParam&& param, Func&& func) { Chris@64: // Hack to create a "lambda" which captures a variable by moving it rather than copying or Chris@64: // referencing. C++14 generalized captures should make this obsolete, but for now in C++11 this Chris@64: // is commonly needed for Promise continuations that own their state. Example usage: Chris@64: // Chris@64: // Own ptr = makeFoo(); Chris@64: // Promise promise = callRpc(); Chris@64: // promise.then(mvCapture(ptr, [](Own&& ptr, int result) { Chris@64: // return ptr->finish(result); Chris@64: // })); Chris@64: Chris@64: return CaptureByMove>(kj::fwd(func), kj::mv(param)); Chris@64: } Chris@64: Chris@64: // ======================================================================================= Chris@64: // Advanced promise construction Chris@64: Chris@64: template Chris@64: class PromiseFulfiller { Chris@64: // A callback which can be used to fulfill a promise. Only the first call to fulfill() or Chris@64: // reject() matters; subsequent calls are ignored. Chris@64: Chris@64: public: Chris@64: virtual void fulfill(T&& value) = 0; Chris@64: // Fulfill the promise with the given value. Chris@64: Chris@64: virtual void reject(Exception&& exception) = 0; Chris@64: // Reject the promise with an error. Chris@64: Chris@64: virtual bool isWaiting() = 0; Chris@64: // Returns true if the promise is still unfulfilled and someone is potentially waiting for it. Chris@64: // Returns false if fulfill()/reject() has already been called *or* if the promise to be Chris@64: // fulfilled has been discarded and therefore the result will never be used anyway. Chris@64: Chris@64: template Chris@64: bool rejectIfThrows(Func&& func); Chris@64: // Call the function (with no arguments) and return true. If an exception is thrown, call Chris@64: // `fulfiller.reject()` and then return false. When compiled with exceptions disabled, Chris@64: // non-fatal exceptions are still detected and handled correctly. Chris@64: }; Chris@64: Chris@64: template <> Chris@64: class PromiseFulfiller { Chris@64: // Specialization of PromiseFulfiller for void promises. See PromiseFulfiller. Chris@64: Chris@64: public: Chris@64: virtual void fulfill(_::Void&& value = _::Void()) = 0; Chris@64: // Call with zero parameters. The parameter is a dummy that only exists so that subclasses don't Chris@64: // have to specialize for . Chris@64: Chris@64: virtual void reject(Exception&& exception) = 0; Chris@64: virtual bool isWaiting() = 0; Chris@64: Chris@64: template Chris@64: bool rejectIfThrows(Func&& func); Chris@64: }; Chris@64: Chris@64: template Chris@64: Promise newAdaptedPromise(Params&&... adapterConstructorParams); Chris@64: // Creates a new promise which owns an instance of `Adapter` which encapsulates the operation Chris@64: // that will eventually fulfill the promise. This is primarily useful for adapting non-KJ Chris@64: // asynchronous APIs to use promises. Chris@64: // Chris@64: // An instance of `Adapter` will be allocated and owned by the returned `Promise`. A Chris@64: // `PromiseFulfiller&` will be passed as the first parameter to the adapter's constructor, Chris@64: // and `adapterConstructorParams` will be forwarded as the subsequent parameters. The adapter Chris@64: // is expected to perform some asynchronous operation and call the `PromiseFulfiller` once Chris@64: // it is finished. Chris@64: // Chris@64: // The adapter is destroyed when its owning Promise is destroyed. This may occur before the Chris@64: // Promise has been fulfilled. In this case, the adapter's destructor should cancel the Chris@64: // asynchronous operation. Once the adapter is destroyed, the fulfillment callback cannot be Chris@64: // called. Chris@64: // Chris@64: // An adapter implementation should be carefully written to ensure that it cannot accidentally Chris@64: // be left unfulfilled permanently because of an exception. Consider making liberal use of Chris@64: // `PromiseFulfiller::rejectIfThrows()`. Chris@64: Chris@64: template Chris@64: struct PromiseFulfillerPair { Chris@64: Promise<_::JoinPromises> promise; Chris@64: Own> fulfiller; Chris@64: }; Chris@64: Chris@64: template Chris@64: PromiseFulfillerPair newPromiseAndFulfiller(); Chris@64: // Construct a Promise and a separate PromiseFulfiller which can be used to fulfill the promise. Chris@64: // If the PromiseFulfiller is destroyed before either of its methods are called, the Promise is Chris@64: // implicitly rejected. Chris@64: // Chris@64: // Although this function is easier to use than `newAdaptedPromise()`, it has the serious drawback Chris@64: // that there is no way to handle cancellation (i.e. detect when the Promise is discarded). Chris@64: // Chris@64: // You can arrange to fulfill a promise with another promise by using a promise type for T. E.g. Chris@64: // `newPromiseAndFulfiller>()` will produce a promise of type `Promise` but the Chris@64: // fulfiller will be of type `PromiseFulfiller>`. Thus you pass a `Promise` to the Chris@64: // `fulfill()` callback, and the promises are chained. Chris@64: Chris@64: // ======================================================================================= Chris@64: // TaskSet Chris@64: Chris@64: class TaskSet { Chris@64: // Holds a collection of Promises and ensures that each executes to completion. Memory Chris@64: // associated with each promise is automatically freed when the promise completes. Destroying Chris@64: // the TaskSet itself automatically cancels all unfinished promises. Chris@64: // Chris@64: // This is useful for "daemon" objects that perform background tasks which aren't intended to Chris@64: // fulfill any particular external promise, but which may need to be canceled (and thus can't Chris@64: // use `Promise::detach()`). The daemon object holds a TaskSet to collect these tasks it is Chris@64: // working on. This way, if the daemon itself is destroyed, the TaskSet is detroyed as well, Chris@64: // and everything the daemon is doing is canceled. Chris@64: Chris@64: public: Chris@64: class ErrorHandler { Chris@64: public: Chris@64: virtual void taskFailed(kj::Exception&& exception) = 0; Chris@64: }; Chris@64: Chris@64: TaskSet(ErrorHandler& errorHandler); Chris@64: // `loop` will be used to wait on promises. `errorHandler` will be executed any time a task Chris@64: // throws an exception, and will execute within the given EventLoop. Chris@64: Chris@64: ~TaskSet() noexcept(false); Chris@64: Chris@64: void add(Promise&& promise); Chris@64: Chris@64: kj::String trace(); Chris@64: // Return debug info about all promises currently in the TaskSet. Chris@64: Chris@64: private: Chris@64: Own<_::TaskSetImpl> impl; Chris@64: }; Chris@64: Chris@64: // ======================================================================================= Chris@64: // The EventLoop class Chris@64: Chris@64: class EventPort { Chris@64: // Interfaces between an `EventLoop` and events originating from outside of the loop's thread. Chris@64: // All such events come in through the `EventPort` implementation. Chris@64: // Chris@64: // An `EventPort` implementation may interface with low-level operating system APIs and/or other Chris@64: // threads. You can also write an `EventPort` which wraps some other (non-KJ) event loop Chris@64: // framework, allowing the two to coexist in a single thread. Chris@64: Chris@64: public: Chris@64: virtual bool wait() = 0; Chris@64: // Wait for an external event to arrive, sleeping if necessary. Once at least one event has Chris@64: // arrived, queue it to the event loop (e.g. by fulfilling a promise) and return. Chris@64: // Chris@64: // This is called during `Promise::wait()` whenever the event queue becomes empty, in order to Chris@64: // wait for new events to populate the queue. Chris@64: // Chris@64: // It is safe to return even if nothing has actually been queued, so long as calling `wait()` in Chris@64: // a loop will eventually sleep. (That is to say, false positives are fine.) Chris@64: // Chris@64: // Returns true if wake() has been called from another thread. (Precisely, returns true if Chris@64: // no previous call to wait `wait()` nor `poll()` has returned true since `wake()` was last Chris@64: // called.) Chris@64: Chris@64: virtual bool poll() = 0; Chris@64: // Check if any external events have arrived, but do not sleep. If any events have arrived, Chris@64: // add them to the event queue (e.g. by fulfilling promises) before returning. Chris@64: // Chris@64: // This may be called during `Promise::wait()` when the EventLoop has been executing for a while Chris@64: // without a break but is still non-empty. Chris@64: // Chris@64: // Returns true if wake() has been called from another thread. (Precisely, returns true if Chris@64: // no previous call to wait `wait()` nor `poll()` has returned true since `wake()` was last Chris@64: // called.) Chris@64: Chris@64: virtual void setRunnable(bool runnable); Chris@64: // Called to notify the `EventPort` when the `EventLoop` has work to do; specifically when it Chris@64: // transitions from empty -> runnable or runnable -> empty. This is typically useful when Chris@64: // integrating with an external event loop; if the loop is currently runnable then you should Chris@64: // arrange to call run() on it soon. The default implementation does nothing. Chris@64: Chris@64: virtual void wake() const; Chris@64: // Wake up the EventPort's thread from another thread. Chris@64: // Chris@64: // Unlike all other methods on this interface, `wake()` may be called from another thread, hence Chris@64: // it is `const`. Chris@64: // Chris@64: // Technically speaking, `wake()` causes the target thread to cease sleeping and not to sleep Chris@64: // again until `wait()` or `poll()` has returned true at least once. Chris@64: // Chris@64: // The default implementation throws an UNIMPLEMENTED exception. Chris@64: }; Chris@64: Chris@64: class EventLoop { Chris@64: // Represents a queue of events being executed in a loop. Most code won't interact with Chris@64: // EventLoop directly, but instead use `Promise`s to interact with it indirectly. See the Chris@64: // documentation for `Promise`. Chris@64: // Chris@64: // Each thread can have at most one current EventLoop. To make an `EventLoop` current for Chris@64: // the thread, create a `WaitScope`. Async APIs require that the thread has a current EventLoop, Chris@64: // or they will throw exceptions. APIs that use `Promise::wait()` additionally must explicitly Chris@64: // be passed a reference to the `WaitScope` to make the caller aware that they might block. Chris@64: // Chris@64: // Generally, you will want to construct an `EventLoop` at the top level of your program, e.g. Chris@64: // in the main() function, or in the start function of a thread. You can then use it to Chris@64: // construct some promises and wait on the result. Example: Chris@64: // Chris@64: // int main() { Chris@64: // // `loop` becomes the official EventLoop for the thread. Chris@64: // MyEventPort eventPort; Chris@64: // EventLoop loop(eventPort); Chris@64: // Chris@64: // // Now we can call an async function. Chris@64: // Promise textPromise = getHttp("http://example.com"); Chris@64: // Chris@64: // // And we can wait for the promise to complete. Note that you can only use `wait()` Chris@64: // // from the top level, not from inside a promise callback. Chris@64: // String text = textPromise.wait(); Chris@64: // print(text); Chris@64: // return 0; Chris@64: // } Chris@64: // Chris@64: // Most applications that do I/O will prefer to use `setupAsyncIo()` from `async-io.h` rather Chris@64: // than allocate an `EventLoop` directly. Chris@64: Chris@64: public: Chris@64: EventLoop(); Chris@64: // Construct an `EventLoop` which does not receive external events at all. Chris@64: Chris@64: explicit EventLoop(EventPort& port); Chris@64: // Construct an `EventLoop` which receives external events through the given `EventPort`. Chris@64: Chris@64: ~EventLoop() noexcept(false); Chris@64: Chris@64: void run(uint maxTurnCount = maxValue); Chris@64: // Run the event loop for `maxTurnCount` turns or until there is nothing left to be done, Chris@64: // whichever comes first. This never calls the `EventPort`'s `sleep()` or `poll()`. It will Chris@64: // call the `EventPort`'s `setRunnable(false)` if the queue becomes empty. Chris@64: Chris@64: bool isRunnable(); Chris@64: // Returns true if run() would currently do anything, or false if the queue is empty. Chris@64: Chris@64: private: Chris@64: EventPort& port; Chris@64: Chris@64: bool running = false; Chris@64: // True while looping -- wait() is then not allowed. Chris@64: Chris@64: bool lastRunnableState = false; Chris@64: // What did we last pass to port.setRunnable()? Chris@64: Chris@64: _::Event* head = nullptr; Chris@64: _::Event** tail = &head; Chris@64: _::Event** depthFirstInsertPoint = &head; Chris@64: Chris@64: Own<_::TaskSetImpl> daemons; Chris@64: Chris@64: bool turn(); Chris@64: void setRunnable(bool runnable); Chris@64: void enterScope(); Chris@64: void leaveScope(); Chris@64: Chris@64: friend void _::detach(kj::Promise&& promise); Chris@64: friend void _::waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, Chris@64: WaitScope& waitScope); Chris@64: friend class _::Event; Chris@64: friend class WaitScope; Chris@64: }; Chris@64: Chris@64: class WaitScope { Chris@64: // Represents a scope in which asynchronous programming can occur. A `WaitScope` should usually Chris@64: // be allocated on the stack and serves two purposes: Chris@64: // * While the `WaitScope` exists, its `EventLoop` is registered as the current loop for the Chris@64: // thread. Most operations dealing with `Promise` (including all of its methods) do not work Chris@64: // unless the thread has a current `EventLoop`. Chris@64: // * `WaitScope` may be passed to `Promise::wait()` to synchronously wait for a particular Chris@64: // promise to complete. See `Promise::wait()` for an extended discussion. Chris@64: Chris@64: public: Chris@64: inline explicit WaitScope(EventLoop& loop): loop(loop) { loop.enterScope(); } Chris@64: inline ~WaitScope() { loop.leaveScope(); } Chris@64: KJ_DISALLOW_COPY(WaitScope); Chris@64: Chris@64: private: Chris@64: EventLoop& loop; Chris@64: friend class EventLoop; Chris@64: friend void _::waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, Chris@64: WaitScope& waitScope); Chris@64: }; Chris@64: Chris@64: } // namespace kj Chris@64: Chris@64: #include "async-inl.h" Chris@64: Chris@64: #endif // KJ_ASYNC_H_