Chain interrupt handlers
[folly.git] / folly / futures / detail / Core.h
1 /*
2  * Copyright 2015 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/Optional.h>
25 #include <folly/SmallLocks.h>
26
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>
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 {
77  public:
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.
81   Core() {}
82   ~Core() {
83     assert(attached_ == 0);
84   }
85
86   // not copyable
87   Core(Core const&) = delete;
88   Core& operator=(Core const&) = delete;
89
90   // not movable (see comment in the implementation of Future::then)
91   Core(Core&&) noexcept = delete;
92   Core& operator=(Core&&) = delete;
93
94   /// May call from any thread
95   bool hasResult() const {
96     switch (fsm_.getState()) {
97       case State::OnlyResult:
98       case State::Armed:
99       case State::Done:
100         assert(!!result_);
101         return true;
102
103       default:
104         return false;
105     }
106   }
107
108   /// May call from any thread
109   bool ready() const {
110     return hasResult();
111   }
112
113   /// May call from any thread
114   Try<T>& getTry() {
115     if (ready()) {
116       return *result_;
117     } else {
118       throw FutureNotReady();
119     }
120   }
121
122   template <typename F>
123   class LambdaBufHelper {
124    public:
125     explicit LambdaBufHelper(F&& func) : func_(std::forward<F>(func)) {}
126     void operator()(Try<T>&& t) {
127       SCOPE_EXIT { this->~LambdaBufHelper(); };
128       func_(std::move(t));
129     }
130    private:
131     F func_;
132   };
133
134   /// Call only from Future thread.
135   template <typename F>
136   void setCallback(F func) {
137     bool transitionToArmed = false;
138     auto setCallback_ = [&]{
139       context_ = RequestContext::saveContext();
140
141       // Move the lambda into the Core if it fits
142       if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
143         auto funcLoc = static_cast<LambdaBufHelper<F>*>((void*)lambdaBuf_);
144         new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
145         callback_ = std::ref(*funcLoc);
146       } else {
147         callback_ = std::move(func);
148       }
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         throw std::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         throw std::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 (!result_) {
210       setResult(Try<T>(exception_wrapper(BrokenPromise())));
211     }
212     detachOne();
213   }
214
215   /// May call from any thread
216   void deactivate() {
217     active_ = false;
218   }
219
220   /// May call from any thread
221   void activate() {
222     active_ = true;
223     maybeCallback();
224   }
225
226   /// May call from any thread
227   bool isActive() { return active_; }
228
229   /// Call only from Future thread
230   void setExecutor(Executor* x, int8_t priority) {
231     folly::MSLGuard g(executorLock_);
232     executor_ = x;
233     priority_ = priority;
234   }
235
236   Executor* getExecutor() {
237     folly::MSLGuard g(executorLock_);
238     return executor_;
239   }
240
241   /// Call only from Future thread
242   void raise(exception_wrapper e) {
243     folly::MSLGuard guard(interruptLock_);
244     if (!interrupt_ && !hasResult()) {
245       interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
246       if (interruptHandler_) {
247         interruptHandler_(*interrupt_);
248       }
249     }
250   }
251
252   std::function<void(exception_wrapper const&)> getInterruptHandler() {
253     folly::MSLGuard guard(interruptLock_);
254     return interruptHandler_;
255   }
256
257   /// Call only from Promise thread
258   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
259     folly::MSLGuard guard(interruptLock_);
260     if (!hasResult()) {
261       if (interrupt_) {
262         fn(*interrupt_);
263       } else {
264         interruptHandler_ = std::move(fn);
265       }
266     }
267   }
268
269  protected:
270   void maybeCallback() {
271     FSM_START(fsm_)
272       case State::Armed:
273         if (active_) {
274           FSM_UPDATE2(fsm_, State::Done, []{},
275                                          std::bind(&Core::doCallback, this));
276         }
277         FSM_BREAK
278
279       default:
280         FSM_BREAK
281     FSM_END
282   }
283
284   void doCallback() {
285     RequestContext::setContext(context_);
286
287     // TODO(6115514) semantic race on reading executor_ and setExecutor()
288     Executor* x;
289     int8_t priority;
290     {
291       folly::MSLGuard g(executorLock_);
292       x = executor_;
293       priority = priority_;
294     }
295
296     if (x) {
297       ++attached_; // keep Core alive until executor did its thing
298       try {
299         if (LIKELY(x->getNumPriorities() == 1)) {
300           x->add([this]() mutable {
301             SCOPE_EXIT { detachOne(); };
302             callback_(std::move(*result_));
303           });
304         } else {
305           x->addWithPriority([this]() mutable {
306             SCOPE_EXIT { detachOne(); };
307             callback_(std::move(*result_));
308           }, priority);
309         }
310       } catch (...) {
311         result_ = Try<T>(exception_wrapper(std::current_exception()));
312         callback_(std::move(*result_));
313       }
314     } else {
315       callback_(std::move(*result_));
316     }
317   }
318
319   void detachOne() {
320     auto a = --attached_;
321     assert(a >= 0);
322     assert(a <= 2);
323     if (a == 0) {
324       delete this;
325     }
326   }
327
328   FSM<State> fsm_ {State::Start};
329   std::atomic<unsigned char> attached_ {2};
330   std::atomic<bool> active_ {true};
331   folly::MicroSpinLock interruptLock_ {0};
332   folly::MicroSpinLock executorLock_ {0};
333   int8_t priority_ {-1};
334   Executor* executor_ {nullptr};
335   folly::Optional<Try<T>> result_ {};
336   std::function<void(Try<T>&&)> callback_ {nullptr};
337   static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
338   char lambdaBuf_[lambdaBufSize];
339   std::shared_ptr<RequestContext> context_ {nullptr};
340   std::unique_ptr<exception_wrapper> interrupt_ {};
341   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
342 };
343
344 template <typename... Ts>
345 struct VariadicContext {
346   VariadicContext() {}
347   ~VariadicContext() {
348     p.setValue(std::move(results));
349   }
350   Promise<std::tuple<Try<Ts>... >> p;
351   std::tuple<Try<Ts>... > results;
352   typedef Future<std::tuple<Try<Ts>...>> type;
353 };
354
355 template <typename... Ts, typename THead, typename... Fs>
356 typename std::enable_if<sizeof...(Fs) == 0, void>::type
357 collectAllVariadicHelper(std::shared_ptr<VariadicContext<Ts...>> ctx,
358                          THead&& head, Fs&&... tail) {
359   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
360     std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
361   });
362 }
363
364 template <typename... Ts, typename THead, typename... Fs>
365 typename std::enable_if<sizeof...(Fs) != 0, void>::type
366 collectAllVariadicHelper(std::shared_ptr<VariadicContext<Ts...>> ctx,
367                          THead&& head, Fs&&... tail) {
368   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
369     std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
370   });
371   // template tail-recursion
372   collectAllVariadicHelper(ctx, std::forward<Fs>(tail)...);
373 }
374
375 }} // folly::detail