Resolve the circular dependency between folly/futures/detail/Core.h and Future.h...
[folly.git] / folly / futures / detail / Core.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <atomic>
20 #include <mutex>
21 #include <stdexcept>
22 #include <vector>
23
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>
32
33 #include <folly/io/async/Request.h>
34
35 namespace folly { namespace detail {
36
37 /*
38         OnlyCallback
39        /            \
40   Start              Armed - Done
41        \            /
42          OnlyResult
43
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).
48 */
49 enum class State : uint8_t {
50   Start,
51   OnlyResult,
52   OnlyCallback,
53   Armed,
54   Done,
55 };
56
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.
66 ///
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.
75 template<typename T>
76 class Core final {
77   static_assert(!std::is_void<T>::value,
78                 "void futures are not supported. Use Unit instead.");
79  public:
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) {}
84
85   explicit Core(Try<T>&& t)
86     : result_(std::move(t)),
87       fsm_(State::OnlyResult),
88       attached_(1) {}
89
90   ~Core() {
91     DCHECK(attached_ == 0);
92   }
93
94   // not copyable
95   Core(Core const&) = delete;
96   Core& operator=(Core const&) = delete;
97
98   // not movable (see comment in the implementation of Future::then)
99   Core(Core&&) noexcept = delete;
100   Core& operator=(Core&&) = delete;
101
102   /// May call from any thread
103   bool hasResult() const noexcept {
104     switch (fsm_.getState()) {
105       case State::OnlyResult:
106       case State::Armed:
107       case State::Done:
108         assert(!!result_);
109         return true;
110
111       default:
112         return false;
113     }
114   }
115
116   /// May call from any thread
117   bool ready() const noexcept {
118     return hasResult();
119   }
120
121   /// May call from any thread
122   Try<T>& getTry() {
123     if (ready()) {
124       return *result_;
125     } else {
126       throw FutureNotReady();
127     }
128   }
129
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);
137     };
138
139     FSM_START(fsm_)
140       case State::Start:
141         FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
142         break;
143
144       case State::OnlyResult:
145         FSM_UPDATE(fsm_, State::Armed, setCallback_);
146         transitionToArmed = true;
147         break;
148
149       case State::OnlyCallback:
150       case State::Armed:
151       case State::Done:
152         throw std::logic_error("setCallback called twice");
153     FSM_END
154
155     // we could always call this, it is an optimization to only call it when
156     // it might be needed.
157     if (transitionToArmed) {
158       maybeCallback();
159     }
160   }
161
162   /// Call only from Promise thread
163   void setResult(Try<T>&& t) {
164     bool transitionToArmed = false;
165     auto setResult_ = [&]{ result_ = std::move(t); };
166     FSM_START(fsm_)
167       case State::Start:
168         FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
169         break;
170
171       case State::OnlyCallback:
172         FSM_UPDATE(fsm_, State::Armed, setResult_);
173         transitionToArmed = true;
174         break;
175
176       case State::OnlyResult:
177       case State::Armed:
178       case State::Done:
179         throw std::logic_error("setResult called twice");
180     FSM_END
181
182     if (transitionToArmed) {
183       maybeCallback();
184     }
185   }
186
187   /// Called by a destructing Future (in the Future thread, by definition)
188   void detachFuture() {
189     activate();
190     detachOne();
191   }
192
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()))));
199     }
200     detachOne();
201   }
202
203   /// May call from any thread
204   void deactivate() {
205     active_.store(false, std::memory_order_release);
206   }
207
208   /// May call from any thread
209   void activate() {
210     active_.store(true, std::memory_order_release);
211     maybeCallback();
212   }
213
214   /// May call from any thread
215   bool isActive() { return active_.load(std::memory_order_acquire); }
216
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();
221     }
222     executor_ = x;
223     priority_ = priority;
224     executorLock_.unlock();
225   }
226
227   void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
228     executor_ = x;
229     priority_ = priority;
230   }
231
232   Executor* getExecutor() {
233     return executor_;
234   }
235
236   /// Call only from Future thread
237   void raise(exception_wrapper e) {
238     if (!interruptLock_.try_lock()) {
239       interruptLock_.lock();
240     }
241     if (!interrupt_ && !hasResult()) {
242       interrupt_ = std::make_unique<exception_wrapper>(std::move(e));
243       if (interruptHandler_) {
244         interruptHandler_(*interrupt_);
245       }
246     }
247     interruptLock_.unlock();
248   }
249
250   std::function<void(exception_wrapper const&)> getInterruptHandler() {
251     if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
252       return nullptr;
253     }
254     if (!interruptLock_.try_lock()) {
255       interruptLock_.lock();
256     }
257     auto handler = interruptHandler_;
258     interruptLock_.unlock();
259     return handler;
260   }
261
262   /// Call only from Promise thread
263   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
264     if (!interruptLock_.try_lock()) {
265       interruptLock_.lock();
266     }
267     if (!hasResult()) {
268       if (interrupt_) {
269         fn(*interrupt_);
270       } else {
271         setInterruptHandlerNoLock(std::move(fn));
272       }
273     }
274     interruptLock_.unlock();
275   }
276
277   void setInterruptHandlerNoLock(
278       std::function<void(exception_wrapper const&)> fn) {
279     interruptHandlerSet_.store(true, std::memory_order_relaxed);
280     interruptHandler_ = std::move(fn);
281   }
282
283  private:
284   // Helper class that stores a pointer to the `Core` object and calls
285   // `derefCallback` and `detachOne` in the destructor.
286   class CoreAndCallbackReference {
287    public:
288     explicit CoreAndCallbackReference(Core* core) noexcept : core_(core) {}
289
290     ~CoreAndCallbackReference() {
291       if (core_) {
292         core_->derefCallback();
293         core_->detachOne();
294       }
295     }
296
297     CoreAndCallbackReference(CoreAndCallbackReference const& o) = delete;
298     CoreAndCallbackReference& operator=(CoreAndCallbackReference const& o) =
299         delete;
300
301     CoreAndCallbackReference(CoreAndCallbackReference&& o) noexcept {
302       std::swap(core_, o.core_);
303     }
304
305     Core* getCore() const noexcept {
306       return core_;
307     }
308
309    private:
310     Core* core_{nullptr};
311   };
312
313   void maybeCallback() {
314     FSM_START(fsm_)
315       case State::Armed:
316         if (active_.load(std::memory_order_acquire)) {
317           FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
318         }
319         FSM_BREAK
320
321       default:
322         FSM_BREAK
323     FSM_END
324   }
325
326   void doCallback() {
327     Executor* x = executor_;
328     int8_t priority;
329     if (x) {
330       if (!executorLock_.try_lock()) {
331         executorLock_.lock();
332       }
333       x = executor_;
334       priority = priority_;
335       executorLock_.unlock();
336     }
337
338     if (x) {
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.
349       attached_ += 2;
350       callbackReferences_ += 2;
351       CoreAndCallbackReference guard_local_scope(this);
352       CoreAndCallbackReference guard_lambda(this);
353       try {
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_));
360           });
361         } else {
362           x->addWithPriority(
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_));
368               },
369               priority);
370         }
371       } catch (const std::exception& e) {
372         ew = exception_wrapper(std::current_exception(), e);
373       } catch (...) {
374         ew = exception_wrapper(std::current_exception());
375       }
376       if (ew) {
377         RequestContextScopeGuard rctx(context_);
378         result_ = Try<T>(std::move(ew));
379         callback_(std::move(*result_));
380       }
381     } else {
382       attached_++;
383       SCOPE_EXIT {
384         callback_ = {};
385         detachOne();
386       };
387       RequestContextScopeGuard rctx(context_);
388       callback_(std::move(*result_));
389     }
390   }
391
392   void detachOne() {
393     auto a = attached_--;
394     assert(a >= 1);
395     if (a == 1) {
396       delete this;
397     }
398   }
399
400   void derefCallback() {
401     if (--callbackReferences_ == 0) {
402       callback_ = {};
403     }
404   }
405
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_;
410   FSM<State> fsm_;
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};
422 };
423
424 template <template <typename...> class T, typename... Ts>
425 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
426   // base case
427 }
428
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<
436         ValueType,
437         sizeof...(Ts) - sizeof...(TTail)-1>(t);
438   });
439   // template tail-recursion
440   collectVariadicHelper(ctx, std::forward<TTail>(tail)...);
441 }
442
443 }} // folly::detail