2 * Copyright 2015 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/Optional.h>
25 #include <folly/SmallLocks.h>
27 #include <folly/futures/Try.h>
28 #include <folly/futures/Promise.h>
29 #include <folly/futures/Future.h>
30 #include <folly/Executor.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.
78 /// This must be heap-constructed. There's probably a way to enforce that in
79 /// code but since this is just internal detail code and I don't know how
80 /// off-hand, I'm punting.
83 explicit Core(Try<T>&& t)
84 : fsm_(State::OnlyResult),
86 result_(std::move(t)) {}
89 assert(attached_ == 0);
93 Core(Core const&) = delete;
94 Core& operator=(Core const&) = delete;
96 // not movable (see comment in the implementation of Future::then)
97 Core(Core&&) noexcept = delete;
98 Core& operator=(Core&&) = delete;
100 /// May call from any thread
101 bool hasResult() const {
102 switch (fsm_.getState()) {
103 case State::OnlyResult:
114 /// May call from any thread
119 /// May call from any thread
124 throw FutureNotReady();
128 template <typename F>
129 class LambdaBufHelper {
131 explicit LambdaBufHelper(F&& func) : func_(std::forward<F>(func)) {}
132 void operator()(Try<T>&& t) {
133 SCOPE_EXIT { this->~LambdaBufHelper(); };
140 /// Call only from Future thread.
141 template <typename F>
142 void setCallback(F func) {
143 bool transitionToArmed = false;
144 auto setCallback_ = [&]{
145 context_ = RequestContext::saveContext();
147 // Move the lambda into the Core if it fits
148 if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
149 auto funcLoc = static_cast<LambdaBufHelper<F>*>((void*)lambdaBuf_);
150 new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
151 callback_ = std::ref(*funcLoc);
153 callback_ = std::move(func);
159 FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
162 case State::OnlyResult:
163 FSM_UPDATE(fsm_, State::Armed, setCallback_);
164 transitionToArmed = true;
167 case State::OnlyCallback:
170 throw std::logic_error("setCallback called twice");
173 // we could always call this, it is an optimization to only call it when
174 // it might be needed.
175 if (transitionToArmed) {
180 /// Call only from Promise thread
181 void setResult(Try<T>&& t) {
182 bool transitionToArmed = false;
183 auto setResult_ = [&]{ result_ = std::move(t); };
186 FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
189 case State::OnlyCallback:
190 FSM_UPDATE(fsm_, State::Armed, setResult_);
191 transitionToArmed = true;
194 case State::OnlyResult:
197 throw std::logic_error("setResult called twice");
200 if (transitionToArmed) {
205 /// Called by a destructing Future (in the Future thread, by definition)
206 void detachFuture() {
211 /// Called by a destructing Promise (in the Promise thread, by definition)
212 void detachPromise() {
213 // detachPromise() and setResult() should never be called in parallel
214 // so we don't need to protect this.
216 setResult(Try<T>(exception_wrapper(BrokenPromise())));
221 /// May call from any thread
226 /// May call from any thread
232 /// May call from any thread
233 bool isActive() { return active_; }
235 /// Call only from Future thread
236 void setExecutor(Executor* x, int8_t priority) {
237 folly::MSLGuard g(executorLock_);
239 priority_ = priority;
242 Executor* getExecutor() {
243 folly::MSLGuard g(executorLock_);
247 /// Call only from Future thread
248 void raise(exception_wrapper e) {
249 folly::MSLGuard guard(interruptLock_);
250 if (!interrupt_ && !hasResult()) {
251 interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
252 if (interruptHandler_) {
253 interruptHandler_(*interrupt_);
258 std::function<void(exception_wrapper const&)> getInterruptHandler() {
259 folly::MSLGuard guard(interruptLock_);
260 return interruptHandler_;
263 /// Call only from Promise thread
264 void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
265 folly::MSLGuard guard(interruptLock_);
270 interruptHandler_ = std::move(fn);
276 void maybeCallback() {
280 FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
290 RequestContext::setContext(context_);
292 // TODO(6115514) semantic race on reading executor_ and setExecutor()
296 folly::MSLGuard g(executorLock_);
298 priority = priority_;
302 ++attached_; // keep Core alive until executor did its thing
304 if (LIKELY(x->getNumPriorities() == 1)) {
305 x->add([this]() mutable {
306 SCOPE_EXIT { detachOne(); };
307 callback_(std::move(*result_));
310 x->addWithPriority([this]() mutable {
311 SCOPE_EXIT { detachOne(); };
312 callback_(std::move(*result_));
316 result_ = Try<T>(exception_wrapper(std::current_exception()));
317 callback_(std::move(*result_));
320 callback_(std::move(*result_));
325 auto a = --attached_;
333 FSM<State> fsm_ {State::Start};
334 std::atomic<unsigned char> attached_ {2};
335 std::atomic<bool> active_ {true};
336 folly::MicroSpinLock interruptLock_ {0};
337 folly::MicroSpinLock executorLock_ {0};
338 int8_t priority_ {-1};
339 Executor* executor_ {nullptr};
340 folly::Optional<Try<T>> result_ {};
341 std::function<void(Try<T>&&)> callback_ {nullptr};
342 static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
343 char lambdaBuf_[lambdaBufSize];
344 std::shared_ptr<RequestContext> context_ {nullptr};
345 std::unique_ptr<exception_wrapper> interrupt_ {};
346 std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
349 template <typename... Ts>
350 struct CollectAllVariadicContext {
351 CollectAllVariadicContext() {}
352 template <typename T, size_t I>
353 inline void setPartialResult(Try<T>& t) {
354 std::get<I>(results) = std::move(t);
356 ~CollectAllVariadicContext() {
357 p.setValue(std::move(results));
359 Promise<std::tuple<Try<Ts>...>> p;
360 std::tuple<Try<Ts>...> results;
361 typedef Future<std::tuple<Try<Ts>...>> type;
364 template <typename... Ts>
365 struct CollectVariadicContext {
366 CollectVariadicContext() {}
367 template <typename T, size_t I>
368 inline void setPartialResult(Try<T>& t) {
369 if (t.hasException()) {
370 if (!threw.exchange(true)) {
371 p.setException(std::move(t.exception()));
374 std::get<I>(results) = std::move(t.value());
377 ~CollectVariadicContext() {
378 if (!threw.exchange(true)) {
379 p.setValue(std::move(results));
382 Promise<std::tuple<Ts...>> p;
383 std::tuple<Ts...> results;
384 std::atomic<bool> threw;
385 typedef Future<std::tuple<Ts...>> type;
388 template <template <typename ...> class T, typename... Ts>
389 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx) {
393 template <template <typename ...> class T, typename... Ts,
394 typename THead, typename... TTail>
395 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
396 THead&& head, TTail&&... tail) {
397 head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
398 ctx->template setPartialResult<typename THead::value_type,
399 sizeof...(Ts) - sizeof...(TTail) - 1>(t);
401 // template tail-recursion
402 collectVariadicHelper(ctx, std::forward<TTail>(tail)...);