template< -> template <
[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 <utility>
23 #include <vector>
24
25 #include <folly/Executor.h>
26 #include <folly/Function.h>
27 #include <folly/MicroSpinLock.h>
28 #include <folly/Optional.h>
29 #include <folly/ScopeGuard.h>
30 #include <folly/Try.h>
31 #include <folly/Utility.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/detail/FSM.h>
34 #include <folly/portability/BitsFunctexcept.h>
35
36 #include <folly/io/async/Request.h>
37
38 namespace folly {
39 namespace futures {
40 namespace detail {
41
42 /*
43         OnlyCallback
44        /            \
45   Start              Armed - Done
46        \            /
47          OnlyResult
48
49 This state machine is fairly self-explanatory. The most important bit is
50 that the callback is only executed on the transition from Armed to Done,
51 and that transition can happen immediately after transitioning from Only*
52 to Armed, if it is active (the usual case).
53 */
54 enum class State : uint8_t {
55   Start,
56   OnlyResult,
57   OnlyCallback,
58   Armed,
59   Done,
60 };
61
62 /// The shared state object for Future and Promise.
63 /// Some methods must only be called by either the Future thread or the
64 /// Promise thread. The Future thread is the thread that currently "owns" the
65 /// Future and its callback-related operations, and the Promise thread is
66 /// likewise the thread that currently "owns" the Promise and its
67 /// result-related operations. Also, Futures own interruption, Promises own
68 /// interrupt handlers. Unfortunately, there are things that users can do to
69 /// break this, and we can't detect that. However if they follow move
70 /// semantics religiously wrt threading, they should be ok.
71 ///
72 /// It's worth pointing out that Futures and/or Promises can and usually will
73 /// migrate between threads, though this usually happens within the API code.
74 /// For example, an async operation will probably make a Promise, grab its
75 /// Future, then move the Promise into another thread that will eventually
76 /// fulfill it. With executors and via, this gets slightly more complicated at
77 /// first blush, but it's the same principle. In general, as long as the user
78 /// doesn't access a Future or Promise object from more than one thread at a
79 /// time there won't be any problems.
80 template <typename T>
81 class Core final {
82   static_assert(!std::is_void<T>::value,
83                 "void futures are not supported. Use Unit instead.");
84  public:
85   /// This must be heap-constructed. There's probably a way to enforce that in
86   /// code but since this is just internal detail code and I don't know how
87   /// off-hand, I'm punting.
88   Core() : result_(), fsm_(State::Start), attached_(2) {}
89
90   explicit Core(Try<T>&& t)
91     : result_(std::move(t)),
92       fsm_(State::OnlyResult),
93       attached_(1) {}
94
95   template <typename... Args>
96   explicit Core(in_place_t, Args&&... args) noexcept(
97       std::is_nothrow_constructible<T, Args&&...>::value)
98       : result_(in_place, in_place, std::forward<Args>(args)...),
99         fsm_(State::OnlyResult),
100         attached_(1) {}
101
102   ~Core() {
103     DCHECK(attached_ == 0);
104   }
105
106   // not copyable
107   Core(Core const&) = delete;
108   Core& operator=(Core const&) = delete;
109
110   // not movable (see comment in the implementation of Future::then)
111   Core(Core&&) noexcept = delete;
112   Core& operator=(Core&&) = delete;
113
114   /// May call from any thread
115   bool hasResult() const noexcept {
116     switch (fsm_.getState()) {
117       case State::OnlyResult:
118       case State::Armed:
119       case State::Done:
120         assert(!!result_);
121         return true;
122
123       default:
124         return false;
125     }
126   }
127
128   /// May call from any thread
129   bool ready() const noexcept {
130     return hasResult();
131   }
132
133   /// May call from any thread
134   Try<T>& getTry() {
135     if (ready()) {
136       return *result_;
137     } else {
138       throwFutureNotReady();
139     }
140   }
141
142   /// Call only from Future thread.
143   template <typename F>
144   void setCallback(F&& func) {
145     bool transitionToArmed = false;
146     auto setCallback_ = [&]{
147       context_ = RequestContext::saveContext();
148       callback_ = std::forward<F>(func);
149     };
150
151     FSM_START(fsm_)
152       case State::Start:
153         FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
154         break;
155
156       case State::OnlyResult:
157         FSM_UPDATE(fsm_, State::Armed, setCallback_);
158         transitionToArmed = true;
159         break;
160
161       case State::OnlyCallback:
162       case State::Armed:
163       case State::Done:
164         std::__throw_logic_error("setCallback called twice");
165     FSM_END
166
167     // we could always call this, it is an optimization to only call it when
168     // it might be needed.
169     if (transitionToArmed) {
170       maybeCallback();
171     }
172   }
173
174   /// Call only from Promise thread
175   void setResult(Try<T>&& t) {
176     bool transitionToArmed = false;
177     auto setResult_ = [&]{ result_ = std::move(t); };
178     FSM_START(fsm_)
179       case State::Start:
180         FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
181         break;
182
183       case State::OnlyCallback:
184         FSM_UPDATE(fsm_, State::Armed, setResult_);
185         transitionToArmed = true;
186         break;
187
188       case State::OnlyResult:
189       case State::Armed:
190       case State::Done:
191         std::__throw_logic_error("setResult called twice");
192     FSM_END
193
194     if (transitionToArmed) {
195       maybeCallback();
196     }
197   }
198
199   /// Called by a destructing Future (in the Future thread, by definition)
200   void detachFuture() {
201     activate();
202     detachOne();
203   }
204
205   /// Called by a destructing Promise (in the Promise thread, by definition)
206   void detachPromise() {
207     // detachPromise() and setResult() should never be called in parallel
208     // so we don't need to protect this.
209     if (UNLIKELY(!result_)) {
210       setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
211     }
212     detachOne();
213   }
214
215   /// May call from any thread
216   void deactivate() {
217     active_.store(false, std::memory_order_release);
218   }
219
220   /// May call from any thread
221   void activate() {
222     active_.store(true, std::memory_order_release);
223     maybeCallback();
224   }
225
226   /// May call from any thread
227   bool isActive() { return active_.load(std::memory_order_acquire); }
228
229   /// Call only from Future thread
230   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
231     if (!executorLock_.try_lock()) {
232       executorLock_.lock();
233     }
234     executor_ = x;
235     priority_ = priority;
236     executorLock_.unlock();
237   }
238
239   void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
240     executor_ = x;
241     priority_ = priority;
242   }
243
244   Executor* getExecutor() {
245     return executor_;
246   }
247
248   /// Call only from Future thread
249   void raise(exception_wrapper e) {
250     if (!interruptLock_.try_lock()) {
251       interruptLock_.lock();
252     }
253     if (!interrupt_ && !hasResult()) {
254       interrupt_ = std::make_unique<exception_wrapper>(std::move(e));
255       if (interruptHandler_) {
256         interruptHandler_(*interrupt_);
257       }
258     }
259     interruptLock_.unlock();
260   }
261
262   std::function<void(exception_wrapper const&)> getInterruptHandler() {
263     if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
264       return nullptr;
265     }
266     if (!interruptLock_.try_lock()) {
267       interruptLock_.lock();
268     }
269     auto handler = interruptHandler_;
270     interruptLock_.unlock();
271     return handler;
272   }
273
274   /// Call only from Promise thread
275   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
276     if (!interruptLock_.try_lock()) {
277       interruptLock_.lock();
278     }
279     if (!hasResult()) {
280       if (interrupt_) {
281         fn(*interrupt_);
282       } else {
283         setInterruptHandlerNoLock(std::move(fn));
284       }
285     }
286     interruptLock_.unlock();
287   }
288
289   void setInterruptHandlerNoLock(
290       std::function<void(exception_wrapper const&)> fn) {
291     interruptHandlerSet_.store(true, std::memory_order_relaxed);
292     interruptHandler_ = std::move(fn);
293   }
294
295  private:
296   // Helper class that stores a pointer to the `Core` object and calls
297   // `derefCallback` and `detachOne` in the destructor.
298   class CoreAndCallbackReference {
299    public:
300     explicit CoreAndCallbackReference(Core* core) noexcept : core_(core) {}
301
302     ~CoreAndCallbackReference() {
303       if (core_) {
304         core_->derefCallback();
305         core_->detachOne();
306       }
307     }
308
309     CoreAndCallbackReference(CoreAndCallbackReference const& o) = delete;
310     CoreAndCallbackReference& operator=(CoreAndCallbackReference const& o) =
311         delete;
312
313     CoreAndCallbackReference(CoreAndCallbackReference&& o) noexcept {
314       std::swap(core_, o.core_);
315     }
316
317     Core* getCore() const noexcept {
318       return core_;
319     }
320
321    private:
322     Core* core_{nullptr};
323   };
324
325   void maybeCallback() {
326     FSM_START(fsm_)
327       case State::Armed:
328         if (active_.load(std::memory_order_acquire)) {
329           FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
330         }
331         FSM_BREAK
332
333       default:
334         FSM_BREAK
335     FSM_END
336   }
337
338   void doCallback() {
339     Executor* x = executor_;
340     // initialize, solely to appease clang's -Wconditional-uninitialized
341     int8_t priority = 0;
342     if (x) {
343       if (!executorLock_.try_lock()) {
344         executorLock_.lock();
345       }
346       x = executor_;
347       priority = priority_;
348       executorLock_.unlock();
349     }
350
351     if (x) {
352       exception_wrapper ew;
353       // We need to reset `callback_` after it was executed (which can happen
354       // through the executor or, if `Executor::add` throws, below). The
355       // executor might discard the function without executing it (now or
356       // later), in which case `callback_` also needs to be reset.
357       // The `Core` has to be kept alive throughout that time, too. Hence we
358       // increment `attached_` and `callbackReferences_` by two, and construct
359       // exactly two `CoreAndCallbackReference` objects, which call
360       // `derefCallback` and `detachOne` in their destructor. One will guard
361       // this scope, the other one will guard the lambda passed to the executor.
362       attached_ += 2;
363       callbackReferences_ += 2;
364       CoreAndCallbackReference guard_local_scope(this);
365       CoreAndCallbackReference guard_lambda(this);
366       try {
367         if (LIKELY(x->getNumPriorities() == 1)) {
368           x->add([core_ref = std::move(guard_lambda)]() mutable {
369             auto cr = std::move(core_ref);
370             Core* const core = cr.getCore();
371             RequestContextScopeGuard rctx(core->context_);
372             core->callback_(std::move(*core->result_));
373           });
374         } else {
375           x->addWithPriority(
376               [core_ref = std::move(guard_lambda)]() mutable {
377                 auto cr = std::move(core_ref);
378                 Core* const core = cr.getCore();
379                 RequestContextScopeGuard rctx(core->context_);
380                 core->callback_(std::move(*core->result_));
381               },
382               priority);
383         }
384       } catch (const std::exception& e) {
385         ew = exception_wrapper(std::current_exception(), e);
386       } catch (...) {
387         ew = exception_wrapper(std::current_exception());
388       }
389       if (ew) {
390         RequestContextScopeGuard rctx(context_);
391         result_ = Try<T>(std::move(ew));
392         callback_(std::move(*result_));
393       }
394     } else {
395       attached_++;
396       SCOPE_EXIT {
397         callback_ = {};
398         detachOne();
399       };
400       RequestContextScopeGuard rctx(context_);
401       callback_(std::move(*result_));
402     }
403   }
404
405   void detachOne() {
406     auto a = attached_--;
407     assert(a >= 1);
408     if (a == 1) {
409       delete this;
410     }
411   }
412
413   void derefCallback() {
414     if (--callbackReferences_ == 0) {
415       callback_ = {};
416     }
417   }
418
419   folly::Function<void(Try<T>&&)> callback_;
420   // place result_ next to increase the likelihood that the value will be
421   // contained entirely in one cache line
422   folly::Optional<Try<T>> result_;
423   FSM<State> fsm_;
424   std::atomic<unsigned char> attached_;
425   std::atomic<unsigned char> callbackReferences_{0};
426   std::atomic<bool> active_ {true};
427   std::atomic<bool> interruptHandlerSet_ {false};
428   folly::MicroSpinLock interruptLock_ {0};
429   folly::MicroSpinLock executorLock_ {0};
430   int8_t priority_ {-1};
431   Executor* executor_ {nullptr};
432   std::shared_ptr<RequestContext> context_ {nullptr};
433   std::unique_ptr<exception_wrapper> interrupt_ {};
434   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
435 };
436
437 template <template <typename...> class T, typename... Ts>
438 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
439   // base case
440 }
441
442 template <template <typename ...> class T, typename... Ts,
443           typename THead, typename... TTail>
444 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
445                            THead&& head, TTail&&... tail) {
446   using ValueType = typename std::decay<THead>::type::value_type;
447   std::forward<THead>(head).setCallback_([ctx](Try<ValueType>&& t) {
448     ctx->template setPartialResult<
449         ValueType,
450         sizeof...(Ts) - sizeof...(TTail)-1>(t);
451   });
452   // template tail-recursion
453   collectVariadicHelper(ctx, std::forward<TTail>(tail)...);
454 }
455
456 } // namespace detail
457 } // namespace futures
458 } // namespace folly