optimize makeFuture and Future<T>::Future()
[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
83   explicit Core(Try<T>&& t)
84     : fsm_(State::OnlyResult),
85       attached_(1),
86       result_(std::move(t)) {}
87
88   ~Core() {
89     assert(attached_ == 0);
90   }
91
92   // not copyable
93   Core(Core const&) = delete;
94   Core& operator=(Core const&) = delete;
95
96   // not movable (see comment in the implementation of Future::then)
97   Core(Core&&) noexcept = delete;
98   Core& operator=(Core&&) = delete;
99
100   /// May call from any thread
101   bool hasResult() const {
102     switch (fsm_.getState()) {
103       case State::OnlyResult:
104       case State::Armed:
105       case State::Done:
106         assert(!!result_);
107         return true;
108
109       default:
110         return false;
111     }
112   }
113
114   /// May call from any thread
115   bool ready() const {
116     return hasResult();
117   }
118
119   /// May call from any thread
120   Try<T>& getTry() {
121     if (ready()) {
122       return *result_;
123     } else {
124       throw FutureNotReady();
125     }
126   }
127
128   template <typename F>
129   class LambdaBufHelper {
130    public:
131     explicit LambdaBufHelper(F&& func) : func_(std::forward<F>(func)) {}
132     void operator()(Try<T>&& t) {
133       SCOPE_EXIT { this->~LambdaBufHelper(); };
134       func_(std::move(t));
135     }
136    private:
137     F func_;
138   };
139
140   /// Call only from Future thread.
141   template <typename F>
142   void setCallback(F func) {
143     bool transitionToArmed = false;
144     auto setCallback_ = [&]{
145       context_ = RequestContext::saveContext();
146
147       // Move the lambda into the Core if it fits
148       if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
149         auto funcLoc = static_cast<LambdaBufHelper<F>*>((void*)lambdaBuf_);
150         new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
151         callback_ = std::ref(*funcLoc);
152       } else {
153         callback_ = std::move(func);
154       }
155     };
156
157     FSM_START(fsm_)
158       case State::Start:
159         FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
160         break;
161
162       case State::OnlyResult:
163         FSM_UPDATE(fsm_, State::Armed, setCallback_);
164         transitionToArmed = true;
165         break;
166
167       case State::OnlyCallback:
168       case State::Armed:
169       case State::Done:
170         throw std::logic_error("setCallback called twice");
171     FSM_END
172
173     // we could always call this, it is an optimization to only call it when
174     // it might be needed.
175     if (transitionToArmed) {
176       maybeCallback();
177     }
178   }
179
180   /// Call only from Promise thread
181   void setResult(Try<T>&& t) {
182     bool transitionToArmed = false;
183     auto setResult_ = [&]{ result_ = std::move(t); };
184     FSM_START(fsm_)
185       case State::Start:
186         FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
187         break;
188
189       case State::OnlyCallback:
190         FSM_UPDATE(fsm_, State::Armed, setResult_);
191         transitionToArmed = true;
192         break;
193
194       case State::OnlyResult:
195       case State::Armed:
196       case State::Done:
197         throw std::logic_error("setResult called twice");
198     FSM_END
199
200     if (transitionToArmed) {
201       maybeCallback();
202     }
203   }
204
205   /// Called by a destructing Future (in the Future thread, by definition)
206   void detachFuture() {
207     activate();
208     detachOne();
209   }
210
211   /// Called by a destructing Promise (in the Promise thread, by definition)
212   void detachPromise() {
213     // detachPromise() and setResult() should never be called in parallel
214     // so we don't need to protect this.
215     if (!result_) {
216       setResult(Try<T>(exception_wrapper(BrokenPromise())));
217     }
218     detachOne();
219   }
220
221   /// May call from any thread
222   void deactivate() {
223     active_ = false;
224   }
225
226   /// May call from any thread
227   void activate() {
228     active_ = true;
229     maybeCallback();
230   }
231
232   /// May call from any thread
233   bool isActive() { return active_; }
234
235   /// Call only from Future thread
236   void setExecutor(Executor* x, int8_t priority) {
237     folly::MSLGuard g(executorLock_);
238     executor_ = x;
239     priority_ = priority;
240   }
241
242   Executor* getExecutor() {
243     folly::MSLGuard g(executorLock_);
244     return executor_;
245   }
246
247   /// Call only from Future thread
248   void raise(exception_wrapper e) {
249     folly::MSLGuard guard(interruptLock_);
250     if (!interrupt_ && !hasResult()) {
251       interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
252       if (interruptHandler_) {
253         interruptHandler_(*interrupt_);
254       }
255     }
256   }
257
258   std::function<void(exception_wrapper const&)> getInterruptHandler() {
259     folly::MSLGuard guard(interruptLock_);
260     return interruptHandler_;
261   }
262
263   /// Call only from Promise thread
264   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
265     folly::MSLGuard guard(interruptLock_);
266     if (!hasResult()) {
267       if (interrupt_) {
268         fn(*interrupt_);
269       } else {
270         interruptHandler_ = std::move(fn);
271       }
272     }
273   }
274
275  protected:
276   void maybeCallback() {
277     FSM_START(fsm_)
278       case State::Armed:
279         if (active_) {
280           FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
281         }
282         FSM_BREAK
283
284       default:
285         FSM_BREAK
286     FSM_END
287   }
288
289   void doCallback() {
290     RequestContext::setContext(context_);
291
292     // TODO(6115514) semantic race on reading executor_ and setExecutor()
293     Executor* x;
294     int8_t priority;
295     {
296       folly::MSLGuard g(executorLock_);
297       x = executor_;
298       priority = priority_;
299     }
300
301     if (x) {
302       ++attached_; // keep Core alive until executor did its thing
303       try {
304         if (LIKELY(x->getNumPriorities() == 1)) {
305           x->add([this]() mutable {
306             SCOPE_EXIT { detachOne(); };
307             callback_(std::move(*result_));
308           });
309         } else {
310           x->addWithPriority([this]() mutable {
311             SCOPE_EXIT { detachOne(); };
312             callback_(std::move(*result_));
313           }, priority);
314         }
315       } catch (...) {
316         result_ = Try<T>(exception_wrapper(std::current_exception()));
317         callback_(std::move(*result_));
318       }
319     } else {
320       callback_(std::move(*result_));
321     }
322   }
323
324   void detachOne() {
325     auto a = --attached_;
326     assert(a >= 0);
327     assert(a <= 2);
328     if (a == 0) {
329       delete this;
330     }
331   }
332
333   FSM<State> fsm_ {State::Start};
334   std::atomic<unsigned char> attached_ {2};
335   std::atomic<bool> active_ {true};
336   folly::MicroSpinLock interruptLock_ {0};
337   folly::MicroSpinLock executorLock_ {0};
338   int8_t priority_ {-1};
339   Executor* executor_ {nullptr};
340   folly::Optional<Try<T>> result_ {};
341   std::function<void(Try<T>&&)> callback_ {nullptr};
342   static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
343   char lambdaBuf_[lambdaBufSize];
344   std::shared_ptr<RequestContext> context_ {nullptr};
345   std::unique_ptr<exception_wrapper> interrupt_ {};
346   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
347 };
348
349 template <typename... Ts>
350 struct CollectAllVariadicContext {
351   CollectAllVariadicContext() {}
352   template <typename T, size_t I>
353   inline void setPartialResult(Try<T>& t) {
354     std::get<I>(results) = std::move(t);
355   }
356   ~CollectAllVariadicContext() {
357     p.setValue(std::move(results));
358   }
359   Promise<std::tuple<Try<Ts>...>> p;
360   std::tuple<Try<Ts>...> results;
361   typedef Future<std::tuple<Try<Ts>...>> type;
362 };
363
364 template <typename... Ts>
365 struct CollectVariadicContext {
366   CollectVariadicContext() {}
367   template <typename T, size_t I>
368   inline void setPartialResult(Try<T>& t) {
369     if (t.hasException()) {
370        if (!threw.exchange(true)) {
371          p.setException(std::move(t.exception()));
372        }
373      } else if (!threw) {
374        std::get<I>(results) = std::move(t.value());
375      }
376   }
377   ~CollectVariadicContext() {
378     if (!threw.exchange(true)) {
379       p.setValue(std::move(results));
380     }
381   }
382   Promise<std::tuple<Ts...>> p;
383   std::tuple<Ts...> results;
384   std::atomic<bool> threw;
385   typedef Future<std::tuple<Ts...>> type;
386 };
387
388 template <template <typename ...> class T, typename... Ts>
389 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx) {
390   // base case
391 }
392
393 template <template <typename ...> class T, typename... Ts,
394           typename THead, typename... TTail>
395 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
396                            THead&& head, TTail&&... tail) {
397   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
398     ctx->template setPartialResult<typename THead::value_type,
399                                    sizeof...(Ts) - sizeof...(TTail) - 1>(t);
400   });
401   // template tail-recursion
402   collectVariadicHelper(ctx, std::forward<TTail>(tail)...);
403 }
404
405 }} // folly::detail