various perf improvements
[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     : result_(std::move(t)),
85       fsm_(State::OnlyResult),
86       attached_(1) {}
87
88   ~Core() {
89     DCHECK(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 (UNLIKELY(!result_)) {
216       setResult(Try<T>(exception_wrapper(BrokenPromise())));
217     }
218     detachOne();
219   }
220
221   /// May call from any thread
222   void deactivate() {
223     active_.store(false, std::memory_order_release);
224   }
225
226   /// May call from any thread
227   void activate() {
228     active_.store(true, std::memory_order_release);
229     maybeCallback();
230   }
231
232   /// May call from any thread
233   bool isActive() { return active_.load(std::memory_order_acquire); }
234
235   /// Call only from Future thread
236   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
237     if (!executorLock_.try_lock()) {
238       executorLock_.lock();
239     }
240     executor_ = x;
241     priority_ = priority;
242     executorLock_.unlock();
243   }
244
245   void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
246     executor_ = x;
247     priority_ = priority;
248   }
249
250   Executor* getExecutor() {
251     return executor_;
252   }
253
254   /// Call only from Future thread
255   void raise(exception_wrapper e) {
256     if (!interruptLock_.try_lock()) {
257       interruptLock_.lock();
258     }
259     if (!interrupt_ && !hasResult()) {
260       interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
261       if (interruptHandler_) {
262         interruptHandler_(*interrupt_);
263       }
264     }
265     interruptLock_.unlock();
266   }
267
268   std::function<void(exception_wrapper const&)> getInterruptHandler() {
269     if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
270       return nullptr;
271     }
272     if (!interruptLock_.try_lock()) {
273       interruptLock_.lock();
274     }
275     auto handler = interruptHandler_;
276     interruptLock_.unlock();
277     return handler;
278   }
279
280   /// Call only from Promise thread
281   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
282     if (!interruptLock_.try_lock()) {
283       interruptLock_.lock();
284     }
285     if (!hasResult()) {
286       if (interrupt_) {
287         fn(*interrupt_);
288       } else {
289         setInterruptHandlerNoLock(std::move(fn));
290       }
291     }
292     interruptLock_.unlock();
293   }
294
295   void setInterruptHandlerNoLock(
296       std::function<void(exception_wrapper const&)> fn) {
297     interruptHandlerSet_.store(true, std::memory_order_relaxed);
298     interruptHandler_ = std::move(fn);
299   }
300
301  protected:
302   void maybeCallback() {
303     FSM_START(fsm_)
304       case State::Armed:
305         if (active_.load(std::memory_order_acquire)) {
306           FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
307         }
308         FSM_BREAK
309
310       default:
311         FSM_BREAK
312     FSM_END
313   }
314
315   void doCallback() {
316     RequestContext::setContext(context_);
317
318     Executor* x = executor_;
319     int8_t priority;
320     if (x) {
321       if (!executorLock_.try_lock()) {
322         executorLock_.lock();
323       }
324       x = executor_;
325       priority = priority_;
326       executorLock_.unlock();
327     }
328
329     if (x) {
330       // keep Core alive until executor did its thing
331       ++attached_;
332       try {
333         if (LIKELY(x->getNumPriorities() == 1)) {
334           x->add([this]() mutable {
335             SCOPE_EXIT { detachOne(); };
336             callback_(std::move(*result_));
337           });
338         } else {
339           x->addWithPriority([this]() mutable {
340             SCOPE_EXIT { detachOne(); };
341             callback_(std::move(*result_));
342           }, priority);
343         }
344       } catch (...) {
345         result_ = Try<T>(exception_wrapper(std::current_exception()));
346         callback_(std::move(*result_));
347       }
348     } else {
349       callback_(std::move(*result_));
350     }
351   }
352
353   void detachOne() {
354     auto a = --attached_;
355     assert(a >= 0);
356     assert(a <= 2);
357     if (a == 0) {
358       delete this;
359     }
360   }
361
362   // lambdaBuf occupies exactly one cache line
363   static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
364   char lambdaBuf_[lambdaBufSize];
365   // place result_ next to increase the likelihood that the value will be
366   // contained entirely in one cache line
367   folly::Optional<Try<T>> result_ {};
368   std::function<void(Try<T>&&)> callback_ {nullptr};
369   FSM<State> fsm_ {State::Start};
370   std::atomic<unsigned char> attached_ {2};
371   std::atomic<bool> active_ {true};
372   std::atomic<bool> interruptHandlerSet_ {false};
373   folly::MicroSpinLock interruptLock_ {0};
374   folly::MicroSpinLock executorLock_ {0};
375   int8_t priority_ {-1};
376   Executor* executor_ {nullptr};
377   std::shared_ptr<RequestContext> context_ {nullptr};
378   std::unique_ptr<exception_wrapper> interrupt_ {};
379   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
380 };
381
382 template <typename... Ts>
383 struct CollectAllVariadicContext {
384   CollectAllVariadicContext() {}
385   template <typename T, size_t I>
386   inline void setPartialResult(Try<T>& t) {
387     std::get<I>(results) = std::move(t);
388   }
389   ~CollectAllVariadicContext() {
390     p.setValue(std::move(results));
391   }
392   Promise<std::tuple<Try<Ts>...>> p;
393   std::tuple<Try<Ts>...> results;
394   typedef Future<std::tuple<Try<Ts>...>> type;
395 };
396
397 template <typename... Ts>
398 struct CollectVariadicContext {
399   CollectVariadicContext() {}
400   template <typename T, size_t I>
401   inline void setPartialResult(Try<T>& t) {
402     if (t.hasException()) {
403        if (!threw.exchange(true)) {
404          p.setException(std::move(t.exception()));
405        }
406      } else if (!threw) {
407        std::get<I>(results) = std::move(t.value());
408      }
409   }
410   ~CollectVariadicContext() {
411     if (!threw.exchange(true)) {
412       p.setValue(std::move(results));
413     }
414   }
415   Promise<std::tuple<Ts...>> p;
416   std::tuple<Ts...> results;
417   std::atomic<bool> threw;
418   typedef Future<std::tuple<Ts...>> type;
419 };
420
421 template <template <typename ...> class T, typename... Ts>
422 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx) {
423   // base case
424 }
425
426 template <template <typename ...> class T, typename... Ts,
427           typename THead, typename... TTail>
428 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
429                            THead&& head, TTail&&... tail) {
430   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
431     ctx->template setPartialResult<typename THead::value_type,
432                                    sizeof...(Ts) - sizeof...(TTail) - 1>(t);
433   });
434   // template tail-recursion
435   collectVariadicHelper(ctx, std::forward<TTail>(tail)...);
436 }
437
438 }} // folly::detail