(Wangle) Have Core own an FSM instead of inheriting
[folly.git] / folly / futures / detail / Core.h
1 /*
2  * Copyright 2014 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 /// 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.
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(detached_ == 2);
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   /// 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);
129     };
130
131     FSM_START(fsm_)
132       case State::Start:
133         FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
134         break;
135
136       case State::OnlyResult:
137         FSM_UPDATE(fsm_, State::Armed, setCallback_);
138         transitionToArmed = true;
139         break;
140
141       case State::OnlyCallback:
142       case State::Armed:
143       case State::Done:
144         throw std::logic_error("setCallback called twice");
145     FSM_END
146
147     // we could always call this, it is an optimization to only call it when
148     // it might be needed.
149     if (transitionToArmed) {
150       maybeCallback();
151     }
152   }
153
154   /// Call only from Promise thread
155   void setResult(Try<T>&& t) {
156     bool transitionToArmed = false;
157     auto setResult_ = [&]{ result_ = std::move(t); };
158     FSM_START(fsm_)
159       case State::Start:
160         FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
161         break;
162
163       case State::OnlyCallback:
164         FSM_UPDATE(fsm_, State::Armed, setResult_);
165         transitionToArmed = true;
166         break;
167
168       case State::OnlyResult:
169       case State::Armed:
170       case State::Done:
171         throw std::logic_error("setResult called twice");
172     FSM_END
173
174     if (transitionToArmed) {
175       maybeCallback();
176     }
177   }
178
179   /// Called by a destructing Future (in the Future thread, by definition)
180   void detachFuture() {
181     activate();
182     detachOne();
183   }
184
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.
189     if (!result_) {
190       setResult(Try<T>(exception_wrapper(BrokenPromise())));
191     }
192     detachOne();
193   }
194
195   /// May call from any thread
196   void deactivate() {
197     active_ = false;
198   }
199
200   /// May call from any thread
201   void activate() {
202     active_ = true;
203     maybeCallback();
204   }
205
206   /// May call from any thread
207   bool isActive() { return active_; }
208
209   /// Call only from Future thread
210   void setExecutor(Executor* x) {
211     executor_ = x;
212   }
213
214   /// Call only from Future thread
215   void raise(exception_wrapper e) {
216     std::lock_guard<decltype(interruptLock_)> guard(interruptLock_);
217     if (!interrupt_ && !hasResult()) {
218       interrupt_ = std::move(e);
219       if (interruptHandler_) {
220         interruptHandler_(interrupt_);
221       }
222     }
223   }
224
225   /// Call only from Promise thread
226   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
227     std::lock_guard<decltype(interruptLock_)> guard(interruptLock_);
228     if (!hasResult()) {
229       if (!!interrupt_) {
230         fn(interrupt_);
231       } else {
232         interruptHandler_ = std::move(fn);
233       }
234     }
235   }
236
237  private:
238   void maybeCallback() {
239     FSM_START(fsm_)
240       case State::Armed:
241         if (active_) {
242           FSM_UPDATE2(fsm_, State::Done, []{},
243                                          std::bind(&Core::doCallback, this));
244         }
245         FSM_BREAK
246
247       default:
248         FSM_BREAK
249     FSM_END
250   }
251
252   void doCallback() {
253     // TODO(5306911) we should probably try/catch around the callback
254
255     RequestContext::setContext(context_);
256
257     // TODO(6115514) semantic race on reading executor_ and setExecutor()
258     Executor* x = executor_;
259     if (x) {
260       MoveWrapper<std::function<void(Try<T>&&)>> cb(std::move(callback_));
261       MoveWrapper<Try<T>> val(std::move(*result_));
262       x->add([cb, val]() mutable { (*cb)(std::move(*val)); });
263     } else {
264       callback_(std::move(*result_));
265     }
266   }
267
268   void detachOne() {
269     auto d = ++detached_;
270     assert(d >= 1);
271     assert(d <= 2);
272     if (d == 2) {
273       delete this;
274     }
275   }
276
277   FSM<State> fsm_ {State::Start};
278   std::atomic<unsigned char> detached_ {0};
279   std::atomic<bool> active_ {true};
280   folly::MicroSpinLock interruptLock_ {0};
281   folly::Optional<Try<T>> result_ {};
282   std::function<void(Try<T>&&)> callback_ {nullptr};
283   std::shared_ptr<RequestContext> context_ {nullptr};
284   std::atomic<Executor*> executor_ {nullptr};
285   exception_wrapper interrupt_ {};
286   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
287 };
288
289 template <typename... Ts>
290 struct VariadicContext {
291   VariadicContext() : total(0), count(0) {}
292   Promise<std::tuple<Try<Ts>... > > p;
293   std::tuple<Try<Ts>... > results;
294   size_t total;
295   std::atomic<size_t> count;
296   typedef Future<std::tuple<Try<Ts>...>> type;
297 };
298
299 template <typename... Ts, typename THead, typename... Fs>
300 typename std::enable_if<sizeof...(Fs) == 0, void>::type
301 whenAllVariadicHelper(VariadicContext<Ts...> *ctx, THead&& head, Fs&&... tail) {
302   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
303     std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
304     if (++ctx->count == ctx->total) {
305       ctx->p.setValue(std::move(ctx->results));
306       delete ctx;
307     }
308   });
309 }
310
311 template <typename... Ts, typename THead, typename... Fs>
312 typename std::enable_if<sizeof...(Fs) != 0, void>::type
313 whenAllVariadicHelper(VariadicContext<Ts...> *ctx, THead&& head, Fs&&... tail) {
314   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
315     std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
316     if (++ctx->count == ctx->total) {
317       ctx->p.setValue(std::move(ctx->results));
318       delete ctx;
319     }
320   });
321   // template tail-recursion
322   whenAllVariadicHelper(ctx, std::forward<Fs>(tail)...);
323 }
324
325 template <typename T>
326 struct WhenAllContext {
327   WhenAllContext() : count(0) {}
328   Promise<std::vector<Try<T> > > p;
329   std::vector<Try<T> > results;
330   std::atomic<size_t> count;
331 };
332
333 template <typename T>
334 struct WhenAnyContext {
335   explicit WhenAnyContext(size_t n) : done(false), ref_count(n) {};
336   Promise<std::pair<size_t, Try<T>>> p;
337   std::atomic<bool> done;
338   std::atomic<size_t> ref_count;
339   void decref() {
340     if (--ref_count == 0) {
341       delete this;
342     }
343   }
344 };
345
346 }} // folly::detail