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