2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
24 #include <folly/Executor.h>
25 #include <folly/Function.h>
26 #include <folly/MicroSpinLock.h>
27 #include <folly/Optional.h>
28 #include <folly/ScopeGuard.h>
29 #include <folly/Try.h>
30 #include <folly/futures/FutureException.h>
31 #include <folly/futures/detail/FSM.h>
33 #include <folly/io/async/Request.h>
35 namespace folly { namespace detail {
44 This state machine is fairly self-explanatory. The most important bit is
45 that the callback is only executed on the transition from Armed to Done,
46 and that transition can happen immediately after transitioning from Only*
47 to Armed, if it is active (the usual case).
49 enum class State : uint8_t {
57 /// The shared state object for Future and Promise.
58 /// Some methods must only be called by either the Future thread or the
59 /// Promise thread. The Future thread is the thread that currently "owns" the
60 /// Future and its callback-related operations, and the Promise thread is
61 /// likewise the thread that currently "owns" the Promise and its
62 /// result-related operations. Also, Futures own interruption, Promises own
63 /// interrupt handlers. Unfortunately, there are things that users can do to
64 /// break this, and we can't detect that. However if they follow move
65 /// semantics religiously wrt threading, they should be ok.
67 /// It's worth pointing out that Futures and/or Promises can and usually will
68 /// migrate between threads, though this usually happens within the API code.
69 /// For example, an async operation will probably make a Promise, grab its
70 /// Future, then move the Promise into another thread that will eventually
71 /// fulfill it. With executors and via, this gets slightly more complicated at
72 /// first blush, but it's the same principle. In general, as long as the user
73 /// doesn't access a Future or Promise object from more than one thread at a
74 /// time there won't be any problems.
77 static_assert(!std::is_void<T>::value,
78 "void futures are not supported. Use Unit instead.");
80 /// This must be heap-constructed. There's probably a way to enforce that in
81 /// code but since this is just internal detail code and I don't know how
82 /// off-hand, I'm punting.
83 Core() : result_(), fsm_(State::Start), attached_(2) {}
85 explicit Core(Try<T>&& t)
86 : result_(std::move(t)),
87 fsm_(State::OnlyResult),
91 DCHECK(attached_ == 0);
95 Core(Core const&) = delete;
96 Core& operator=(Core const&) = delete;
98 // not movable (see comment in the implementation of Future::then)
99 Core(Core&&) noexcept = delete;
100 Core& operator=(Core&&) = delete;
102 /// May call from any thread
103 bool hasResult() const noexcept {
104 switch (fsm_.getState()) {
105 case State::OnlyResult:
116 /// May call from any thread
117 bool ready() const noexcept {
121 /// May call from any thread
126 throw FutureNotReady();
130 /// Call only from Future thread.
131 template <typename F>
132 void setCallback(F&& func) {
133 bool transitionToArmed = false;
134 auto setCallback_ = [&]{
135 context_ = RequestContext::saveContext();
136 callback_ = std::forward<F>(func);
141 FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
144 case State::OnlyResult:
145 FSM_UPDATE(fsm_, State::Armed, setCallback_);
146 transitionToArmed = true;
149 case State::OnlyCallback:
152 throw std::logic_error("setCallback called twice");
155 // we could always call this, it is an optimization to only call it when
156 // it might be needed.
157 if (transitionToArmed) {
162 /// Call only from Promise thread
163 void setResult(Try<T>&& t) {
164 bool transitionToArmed = false;
165 auto setResult_ = [&]{ result_ = std::move(t); };
168 FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
171 case State::OnlyCallback:
172 FSM_UPDATE(fsm_, State::Armed, setResult_);
173 transitionToArmed = true;
176 case State::OnlyResult:
179 throw std::logic_error("setResult called twice");
182 if (transitionToArmed) {
187 /// Called by a destructing Future (in the Future thread, by definition)
188 void detachFuture() {
193 /// Called by a destructing Promise (in the Promise thread, by definition)
194 void detachPromise() {
195 // detachPromise() and setResult() should never be called in parallel
196 // so we don't need to protect this.
197 if (UNLIKELY(!result_)) {
198 setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
203 /// May call from any thread
205 active_.store(false, std::memory_order_release);
208 /// May call from any thread
210 active_.store(true, std::memory_order_release);
214 /// May call from any thread
215 bool isActive() { return active_.load(std::memory_order_acquire); }
217 /// Call only from Future thread
218 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
219 if (!executorLock_.try_lock()) {
220 executorLock_.lock();
223 priority_ = priority;
224 executorLock_.unlock();
227 void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
229 priority_ = priority;
232 Executor* getExecutor() {
236 /// Call only from Future thread
237 void raise(exception_wrapper e) {
238 if (!interruptLock_.try_lock()) {
239 interruptLock_.lock();
241 if (!interrupt_ && !hasResult()) {
242 interrupt_ = std::make_unique<exception_wrapper>(std::move(e));
243 if (interruptHandler_) {
244 interruptHandler_(*interrupt_);
247 interruptLock_.unlock();
250 std::function<void(exception_wrapper const&)> getInterruptHandler() {
251 if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
254 if (!interruptLock_.try_lock()) {
255 interruptLock_.lock();
257 auto handler = interruptHandler_;
258 interruptLock_.unlock();
262 /// Call only from Promise thread
263 void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
264 if (!interruptLock_.try_lock()) {
265 interruptLock_.lock();
271 setInterruptHandlerNoLock(std::move(fn));
274 interruptLock_.unlock();
277 void setInterruptHandlerNoLock(
278 std::function<void(exception_wrapper const&)> fn) {
279 interruptHandlerSet_.store(true, std::memory_order_relaxed);
280 interruptHandler_ = std::move(fn);
284 // Helper class that stores a pointer to the `Core` object and calls
285 // `derefCallback` and `detachOne` in the destructor.
286 class CoreAndCallbackReference {
288 explicit CoreAndCallbackReference(Core* core) noexcept : core_(core) {}
290 ~CoreAndCallbackReference() {
292 core_->derefCallback();
297 CoreAndCallbackReference(CoreAndCallbackReference const& o) = delete;
298 CoreAndCallbackReference& operator=(CoreAndCallbackReference const& o) =
301 CoreAndCallbackReference(CoreAndCallbackReference&& o) noexcept {
302 std::swap(core_, o.core_);
305 Core* getCore() const noexcept {
310 Core* core_{nullptr};
313 void maybeCallback() {
316 if (active_.load(std::memory_order_acquire)) {
317 FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
327 Executor* x = executor_;
330 if (!executorLock_.try_lock()) {
331 executorLock_.lock();
334 priority = priority_;
335 executorLock_.unlock();
339 exception_wrapper ew;
340 // We need to reset `callback_` after it was executed (which can happen
341 // through the executor or, if `Executor::add` throws, below). The
342 // executor might discard the function without executing it (now or
343 // later), in which case `callback_` also needs to be reset.
344 // The `Core` has to be kept alive throughout that time, too. Hence we
345 // increment `attached_` and `callbackReferences_` by two, and construct
346 // exactly two `CoreAndCallbackReference` objects, which call
347 // `derefCallback` and `detachOne` in their destructor. One will guard
348 // this scope, the other one will guard the lambda passed to the executor.
350 callbackReferences_ += 2;
351 CoreAndCallbackReference guard_local_scope(this);
352 CoreAndCallbackReference guard_lambda(this);
354 if (LIKELY(x->getNumPriorities() == 1)) {
355 x->add([core_ref = std::move(guard_lambda)]() mutable {
356 auto cr = std::move(core_ref);
357 Core* const core = cr.getCore();
358 RequestContextScopeGuard rctx(core->context_);
359 core->callback_(std::move(*core->result_));
363 [core_ref = std::move(guard_lambda)]() mutable {
364 auto cr = std::move(core_ref);
365 Core* const core = cr.getCore();
366 RequestContextScopeGuard rctx(core->context_);
367 core->callback_(std::move(*core->result_));
371 } catch (const std::exception& e) {
372 ew = exception_wrapper(std::current_exception(), e);
374 ew = exception_wrapper(std::current_exception());
377 RequestContextScopeGuard rctx(context_);
378 result_ = Try<T>(std::move(ew));
379 callback_(std::move(*result_));
387 RequestContextScopeGuard rctx(context_);
388 callback_(std::move(*result_));
393 auto a = attached_--;
400 void derefCallback() {
401 if (--callbackReferences_ == 0) {
406 folly::Function<void(Try<T>&&)> callback_;
407 // place result_ next to increase the likelihood that the value will be
408 // contained entirely in one cache line
409 folly::Optional<Try<T>> result_;
411 std::atomic<unsigned char> attached_;
412 std::atomic<unsigned char> callbackReferences_{0};
413 std::atomic<bool> active_ {true};
414 std::atomic<bool> interruptHandlerSet_ {false};
415 folly::MicroSpinLock interruptLock_ {0};
416 folly::MicroSpinLock executorLock_ {0};
417 int8_t priority_ {-1};
418 Executor* executor_ {nullptr};
419 std::shared_ptr<RequestContext> context_ {nullptr};
420 std::unique_ptr<exception_wrapper> interrupt_ {};
421 std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
424 template <template <typename...> class T, typename... Ts>
425 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
429 template <template <typename ...> class T, typename... Ts,
430 typename THead, typename... TTail>
431 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
432 THead&& head, TTail&&... tail) {
433 using ValueType = typename std::decay<THead>::type::value_type;
434 std::forward<THead>(head).setCallback_([ctx](Try<ValueType>&& t) {
435 ctx->template setPartialResult<
437 sizeof...(Ts) - sizeof...(TTail)-1>(t);
439 // template tail-recursion
440 collectVariadicHelper(ctx, std::forward<TTail>(tail)...);