Copyright 2014->2015
[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 /// 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     activateNoDeprecatedWarning();
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() DEPRECATED {
197     active_ = false;
198   }
199
200   /// May call from any thread
201   void activate() DEPRECATED {
202     activateNoDeprecatedWarning();
203   }
204
205   /// May call from any thread
206   bool isActive() { return active_; }
207
208   /// Call only from Future thread
209   void setExecutor(Executor* x) {
210     executor_ = x;
211   }
212
213   Executor* getExecutor() {
214     return executor_;
215   }
216
217   /// Call only from Future thread
218   void raise(exception_wrapper e) {
219     std::lock_guard<decltype(interruptLock_)> guard(interruptLock_);
220     if (!interrupt_ && !hasResult()) {
221       interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
222       if (interruptHandler_) {
223         interruptHandler_(*interrupt_);
224       }
225     }
226   }
227
228   /// Call only from Promise thread
229   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
230     std::lock_guard<decltype(interruptLock_)> guard(interruptLock_);
231     if (!hasResult()) {
232       if (interrupt_) {
233         fn(*interrupt_);
234       } else {
235         interruptHandler_ = std::move(fn);
236       }
237     }
238   }
239
240  protected:
241   void activateNoDeprecatedWarning() {
242     active_ = true;
243     maybeCallback();
244   }
245
246   void maybeCallback() {
247     FSM_START(fsm_)
248       case State::Armed:
249         if (active_) {
250           FSM_UPDATE2(fsm_, State::Done, []{},
251                                          std::bind(&Core::doCallback, this));
252         }
253         FSM_BREAK
254
255       default:
256         FSM_BREAK
257     FSM_END
258   }
259
260   void doCallback() {
261     // TODO(5306911) we should probably try/catch around the callback
262
263     RequestContext::setContext(context_);
264
265     // TODO(6115514) semantic race on reading executor_ and setExecutor()
266     Executor* x = executor_;
267     if (x) {
268       MoveWrapper<std::function<void(Try<T>&&)>> cb(std::move(callback_));
269       MoveWrapper<Try<T>> val(std::move(*result_));
270       x->add([cb, val]() mutable { (*cb)(std::move(*val)); });
271     } else {
272       callback_(std::move(*result_));
273     }
274   }
275
276   void detachOne() {
277     auto d = ++detached_;
278     assert(d >= 1);
279     assert(d <= 2);
280     if (d == 2) {
281       delete this;
282     }
283   }
284
285   FSM<State> fsm_ {State::Start};
286   std::atomic<unsigned char> detached_ {0};
287   std::atomic<bool> active_ {true};
288   folly::MicroSpinLock interruptLock_ {0};
289   folly::Optional<Try<T>> result_ {};
290   std::function<void(Try<T>&&)> callback_ {nullptr};
291   std::shared_ptr<RequestContext> context_ {nullptr};
292   std::atomic<Executor*> executor_ {nullptr};
293   std::unique_ptr<exception_wrapper> interrupt_ {};
294   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
295 };
296
297 template <typename... Ts>
298 struct VariadicContext {
299   VariadicContext() : total(0), count(0) {}
300   Promise<std::tuple<Try<Ts>... > > p;
301   std::tuple<Try<Ts>... > results;
302   size_t total;
303   std::atomic<size_t> count;
304   typedef Future<std::tuple<Try<Ts>...>> type;
305 };
306
307 template <typename... Ts, typename THead, typename... Fs>
308 typename std::enable_if<sizeof...(Fs) == 0, void>::type
309 whenAllVariadicHelper(VariadicContext<Ts...> *ctx, THead&& head, Fs&&... tail) {
310   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
311     std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
312     if (++ctx->count == ctx->total) {
313       ctx->p.setValue(std::move(ctx->results));
314       delete ctx;
315     }
316   });
317 }
318
319 template <typename... Ts, typename THead, typename... Fs>
320 typename std::enable_if<sizeof...(Fs) != 0, void>::type
321 whenAllVariadicHelper(VariadicContext<Ts...> *ctx, THead&& head, Fs&&... tail) {
322   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
323     std::get<sizeof...(Ts) - sizeof...(Fs) - 1>(ctx->results) = std::move(t);
324     if (++ctx->count == ctx->total) {
325       ctx->p.setValue(std::move(ctx->results));
326       delete ctx;
327     }
328   });
329   // template tail-recursion
330   whenAllVariadicHelper(ctx, std::forward<Fs>(tail)...);
331 }
332
333 template <typename T>
334 struct WhenAllContext {
335   WhenAllContext() : count(0) {}
336   Promise<std::vector<Try<T> > > p;
337   std::vector<Try<T> > results;
338   std::atomic<size_t> count;
339 };
340
341 template <typename T>
342 struct WhenAnyContext {
343   explicit WhenAnyContext(size_t n) : done(false), ref_count(n) {};
344   Promise<std::pair<size_t, Try<T>>> p;
345   std::atomic<bool> done;
346   std::atomic<size_t> ref_count;
347   void decref() {
348     if (--ref_count == 0) {
349       delete this;
350     }
351   }
352 };
353
354 }} // folly::detail