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