2 * Copyright 2014 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 /// fulfil 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 assert(detached_ == 2);
87 Core(Core const&) = delete;
88 Core& operator=(Core const&) = delete;
90 // not movable (see comment in the implementation of Future::then)
91 Core(Core&&) noexcept = delete;
92 Core& operator=(Core&&) = delete;
94 /// May call from any thread
95 bool hasResult() const {
96 switch (fsm_.getState()) {
97 case State::OnlyResult:
108 /// May call from any thread
113 /// May call from any thread
118 throw FutureNotReady();
122 /// Call only from Future thread.
123 template <typename F>
124 void setCallback(F func) {
125 bool transitionToArmed = false;
126 auto setCallback_ = [&]{
127 context_ = RequestContext::saveContext();
128 callback_ = std::move(func);
133 FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
136 case State::OnlyResult:
137 FSM_UPDATE(fsm_, State::Armed, setCallback_);
138 transitionToArmed = true;
141 case State::OnlyCallback:
144 throw std::logic_error("setCallback called twice");
147 // we could always call this, it is an optimization to only call it when
148 // it might be needed.
149 if (transitionToArmed) {
154 /// Call only from Promise thread
155 void setResult(Try<T>&& t) {
156 bool transitionToArmed = false;
157 auto setResult_ = [&]{ result_ = std::move(t); };
160 FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
163 case State::OnlyCallback:
164 FSM_UPDATE(fsm_, State::Armed, setResult_);
165 transitionToArmed = true;
168 case State::OnlyResult:
171 throw std::logic_error("setResult called twice");
174 if (transitionToArmed) {
179 /// Called by a destructing Future (in the Future thread, by definition)
180 void detachFuture() {
181 activateNoDeprecatedWarning();
185 /// Called by a destructing Promise (in the Promise thread, by definition)
186 void detachPromise() {
187 // detachPromise() and setResult() should never be called in parallel
188 // so we don't need to protect this.
190 setResult(Try<T>(exception_wrapper(BrokenPromise())));
195 /// May call from any thread
196 void deactivate() DEPRECATED {
200 /// May call from any thread
201 void activate() DEPRECATED {
202 activateNoDeprecatedWarning();
205 /// May call from any thread
206 bool isActive() { return active_; }
208 /// Call only from Future thread
209 void setExecutor(Executor* x) {
213 Executor* getExecutor() {
217 /// Call only from Future thread
218 void raise(exception_wrapper e) {
219 std::lock_guard<decltype(interruptLock_)> guard(interruptLock_);
220 if (!interrupt_ && !hasResult()) {
221 interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
222 if (interruptHandler_) {
223 interruptHandler_(*interrupt_);
228 /// Call only from Promise thread
229 void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
230 std::lock_guard<decltype(interruptLock_)> guard(interruptLock_);
235 interruptHandler_ = std::move(fn);
241 void activateNoDeprecatedWarning() {
246 void maybeCallback() {
250 FSM_UPDATE2(fsm_, State::Done, []{},
251 std::bind(&Core::doCallback, this));
261 // TODO(5306911) we should probably try/catch around the callback
263 RequestContext::setContext(context_);
265 // TODO(6115514) semantic race on reading executor_ and setExecutor()
266 Executor* x = executor_;
268 MoveWrapper<std::function<void(Try<T>&&)>> cb(std::move(callback_));
269 MoveWrapper<Try<T>> val(std::move(*result_));
270 x->add([cb, val]() mutable { (*cb)(std::move(*val)); });
272 callback_(std::move(*result_));
277 auto d = ++detached_;
285 FSM<State> fsm_ {State::Start};
286 std::atomic<unsigned char> detached_ {0};
287 std::atomic<bool> active_ {true};
288 folly::MicroSpinLock interruptLock_ {0};
289 folly::Optional<Try<T>> result_ {};
290 std::function<void(Try<T>&&)> callback_ {nullptr};
291 std::shared_ptr<RequestContext> context_ {nullptr};
292 std::atomic<Executor*> executor_ {nullptr};
293 std::unique_ptr<exception_wrapper> interrupt_ {};
294 std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
297 template <typename... Ts>
298 struct VariadicContext {
299 VariadicContext() : total(0), count(0) {}
300 Promise<std::tuple<Try<Ts>... > > p;
301 std::tuple<Try<Ts>... > results;
303 std::atomic<size_t> count;
304 typedef Future<std::tuple<Try<Ts>...>> type;
307 template <typename... Ts, typename THead, typename... Fs>
308 typename std::enable_if<sizeof...(Fs) == 0, void>::type
309 whenAllVariadicHelper(VariadicContext<Ts...> *ctx, THead&& head, Fs&&... tail) {
310 head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
311 std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
312 if (++ctx->count == ctx->total) {
313 ctx->p.setValue(std::move(ctx->results));
319 template <typename... Ts, typename THead, typename... Fs>
320 typename std::enable_if<sizeof...(Fs) != 0, void>::type
321 whenAllVariadicHelper(VariadicContext<Ts...> *ctx, THead&& head, Fs&&... tail) {
322 head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
323 std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
324 if (++ctx->count == ctx->total) {
325 ctx->p.setValue(std::move(ctx->results));
329 // template tail-recursion
330 whenAllVariadicHelper(ctx, std::forward<Fs>(tail)...);
333 template <typename T>
334 struct WhenAllContext {
335 WhenAllContext() : count(0) {}
336 Promise<std::vector<Try<T> > > p;
337 std::vector<Try<T> > results;
338 std::atomic<size_t> count;
341 template <typename T>
342 struct WhenAnyContext {
343 explicit WhenAnyContext(size_t n) : done(false), ref_count(n) {};
344 Promise<std::pair<size_t, Try<T>>> p;
345 std::atomic<bool> done;
346 std::atomic<size_t> ref_count;
348 if (--ref_count == 0) {