folly: build with -Wunused-parameter
[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/MicroSpinLock.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   static_assert(!std::is_void<T>::value,
78                 "void futures are not supported. Use Unit instead.");
79  public:
80   /// This must be heap-constructed. There's probably a way to enforce that in
81   /// code but since this is just internal detail code and I don't know how
82   /// off-hand, I'm punting.
83   Core() : result_(), fsm_(State::Start), attached_(2) {}
84
85   explicit Core(Try<T>&& t)
86     : result_(std::move(t)),
87       fsm_(State::OnlyResult),
88       attached_(1) {}
89
90   ~Core() {
91     DCHECK(attached_ == 0);
92   }
93
94   // not copyable
95   Core(Core const&) = delete;
96   Core& operator=(Core const&) = delete;
97
98   // not movable (see comment in the implementation of Future::then)
99   Core(Core&&) noexcept = delete;
100   Core& operator=(Core&&) = delete;
101
102   /// May call from any thread
103   bool hasResult() const {
104     switch (fsm_.getState()) {
105       case State::OnlyResult:
106       case State::Armed:
107       case State::Done:
108         assert(!!result_);
109         return true;
110
111       default:
112         return false;
113     }
114   }
115
116   /// May call from any thread
117   bool ready() const {
118     return hasResult();
119   }
120
121   /// May call from any thread
122   Try<T>& getTry() {
123     if (ready()) {
124       return *result_;
125     } else {
126       throw FutureNotReady();
127     }
128   }
129
130   template <typename F>
131   class LambdaBufHelper {
132    public:
133     template <typename FF>
134     explicit LambdaBufHelper(FF&& func) : func_(std::forward<FF>(func)) {}
135     void operator()(Try<T>&& t) {
136       SCOPE_EXIT { this->~LambdaBufHelper(); };
137       func_(std::move(t));
138     }
139    private:
140     F func_;
141   };
142
143   /// Call only from Future thread.
144   template <typename F>
145   void setCallback(F func) {
146     bool transitionToArmed = false;
147     auto setCallback_ = [&]{
148       context_ = RequestContext::saveContext();
149
150       // Move the lambda into the Core if it fits
151       if (sizeof(LambdaBufHelper<F>) <= lambdaBufSize) {
152         auto funcLoc = reinterpret_cast<LambdaBufHelper<F>*>(&lambdaBuf_);
153         new (funcLoc) LambdaBufHelper<F>(std::forward<F>(func));
154         callback_ = std::ref(*funcLoc);
155       } else {
156         callback_ = std::move(func);
157       }
158     };
159
160     FSM_START(fsm_)
161       case State::Start:
162         FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
163         break;
164
165       case State::OnlyResult:
166         FSM_UPDATE(fsm_, State::Armed, setCallback_);
167         transitionToArmed = true;
168         break;
169
170       case State::OnlyCallback:
171       case State::Armed:
172       case State::Done:
173         throw std::logic_error("setCallback called twice");
174     FSM_END
175
176     // we could always call this, it is an optimization to only call it when
177     // it might be needed.
178     if (transitionToArmed) {
179       maybeCallback();
180     }
181   }
182
183   /// Call only from Promise thread
184   void setResult(Try<T>&& t) {
185     bool transitionToArmed = false;
186     auto setResult_ = [&]{ result_ = std::move(t); };
187     FSM_START(fsm_)
188       case State::Start:
189         FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
190         break;
191
192       case State::OnlyCallback:
193         FSM_UPDATE(fsm_, State::Armed, setResult_);
194         transitionToArmed = true;
195         break;
196
197       case State::OnlyResult:
198       case State::Armed:
199       case State::Done:
200         throw std::logic_error("setResult called twice");
201     FSM_END
202
203     if (transitionToArmed) {
204       maybeCallback();
205     }
206   }
207
208   /// Called by a destructing Future (in the Future thread, by definition)
209   void detachFuture() {
210     activate();
211     detachOne();
212   }
213
214   /// Called by a destructing Promise (in the Promise thread, by definition)
215   void detachPromise() {
216     // detachPromise() and setResult() should never be called in parallel
217     // so we don't need to protect this.
218     if (UNLIKELY(!result_)) {
219       setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
220     }
221     detachOne();
222   }
223
224   /// May call from any thread
225   void deactivate() {
226     active_.store(false, std::memory_order_release);
227   }
228
229   /// May call from any thread
230   void activate() {
231     active_.store(true, std::memory_order_release);
232     maybeCallback();
233   }
234
235   /// May call from any thread
236   bool isActive() { return active_.load(std::memory_order_acquire); }
237
238   /// Call only from Future thread
239   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
240     if (!executorLock_.try_lock()) {
241       executorLock_.lock();
242     }
243     executor_ = x;
244     priority_ = priority;
245     executorLock_.unlock();
246   }
247
248   void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
249     executor_ = x;
250     priority_ = priority;
251   }
252
253   Executor* getExecutor() {
254     return executor_;
255   }
256
257   /// Call only from Future thread
258   void raise(exception_wrapper e) {
259     if (!interruptLock_.try_lock()) {
260       interruptLock_.lock();
261     }
262     if (!interrupt_ && !hasResult()) {
263       interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
264       if (interruptHandler_) {
265         interruptHandler_(*interrupt_);
266       }
267     }
268     interruptLock_.unlock();
269   }
270
271   std::function<void(exception_wrapper const&)> getInterruptHandler() {
272     if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
273       return nullptr;
274     }
275     if (!interruptLock_.try_lock()) {
276       interruptLock_.lock();
277     }
278     auto handler = interruptHandler_;
279     interruptLock_.unlock();
280     return handler;
281   }
282
283   /// Call only from Promise thread
284   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
285     if (!interruptLock_.try_lock()) {
286       interruptLock_.lock();
287     }
288     if (!hasResult()) {
289       if (interrupt_) {
290         fn(*interrupt_);
291       } else {
292         setInterruptHandlerNoLock(std::move(fn));
293       }
294     }
295     interruptLock_.unlock();
296   }
297
298   void setInterruptHandlerNoLock(
299       std::function<void(exception_wrapper const&)> fn) {
300     interruptHandlerSet_.store(true, std::memory_order_relaxed);
301     interruptHandler_ = std::move(fn);
302   }
303
304  protected:
305   void maybeCallback() {
306     FSM_START(fsm_)
307       case State::Armed:
308         if (active_.load(std::memory_order_acquire)) {
309           FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
310         }
311         FSM_BREAK
312
313       default:
314         FSM_BREAK
315     FSM_END
316   }
317
318   void doCallback() {
319     Executor* x = executor_;
320     int8_t priority;
321     if (x) {
322       if (!executorLock_.try_lock()) {
323         executorLock_.lock();
324       }
325       x = executor_;
326       priority = priority_;
327       executorLock_.unlock();
328     }
329
330     if (x) {
331       // keep Core alive until executor did its thing
332       ++attached_;
333       try {
334         if (LIKELY(x->getNumPriorities() == 1)) {
335           x->add([this]() mutable {
336             SCOPE_EXIT { detachOne(); };
337             RequestContext::setContext(context_);
338             callback_(std::move(*result_));
339           });
340         } else {
341           x->addWithPriority([this]() mutable {
342             SCOPE_EXIT { detachOne(); };
343             RequestContext::setContext(context_);
344             callback_(std::move(*result_));
345           }, priority);
346         }
347       } catch (...) {
348         --attached_; // Account for extra ++attached_ before try
349         RequestContext::setContext(context_);
350         result_ = Try<T>(exception_wrapper(std::current_exception()));
351         callback_(std::move(*result_));
352       }
353     } else {
354       RequestContext::setContext(context_);
355       callback_(std::move(*result_));
356     }
357   }
358
359   void detachOne() {
360     auto a = --attached_;
361     assert(a >= 0);
362     assert(a <= 2);
363     if (a == 0) {
364       delete this;
365     }
366   }
367
368   // lambdaBuf occupies exactly one cache line
369   static constexpr size_t lambdaBufSize = 8 * sizeof(void*);
370   typename std::aligned_storage<lambdaBufSize>::type lambdaBuf_;
371   // place result_ next to increase the likelihood that the value will be
372   // contained entirely in one cache line
373   folly::Optional<Try<T>> result_;
374   std::function<void(Try<T>&&)> callback_ {nullptr};
375   FSM<State> fsm_;
376   std::atomic<unsigned char> attached_;
377   std::atomic<bool> active_ {true};
378   std::atomic<bool> interruptHandlerSet_ {false};
379   folly::MicroSpinLock interruptLock_ {0};
380   folly::MicroSpinLock executorLock_ {0};
381   int8_t priority_ {-1};
382   Executor* executor_ {nullptr};
383   std::shared_ptr<RequestContext> context_ {nullptr};
384   std::unique_ptr<exception_wrapper> interrupt_ {};
385   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
386 };
387
388 template <typename... Ts>
389 struct CollectAllVariadicContext {
390   CollectAllVariadicContext() {}
391   template <typename T, size_t I>
392   inline void setPartialResult(Try<T>& t) {
393     std::get<I>(results) = std::move(t);
394   }
395   ~CollectAllVariadicContext() {
396     p.setValue(std::move(results));
397   }
398   Promise<std::tuple<Try<Ts>...>> p;
399   std::tuple<Try<Ts>...> results;
400   typedef Future<std::tuple<Try<Ts>...>> type;
401 };
402
403 template <typename... Ts>
404 struct CollectVariadicContext {
405   CollectVariadicContext() {}
406   template <typename T, size_t I>
407   inline void setPartialResult(Try<T>& t) {
408     if (t.hasException()) {
409        if (!threw.exchange(true)) {
410          p.setException(std::move(t.exception()));
411        }
412      } else if (!threw) {
413        std::get<I>(results) = std::move(t);
414      }
415   }
416   ~CollectVariadicContext() {
417     if (!threw.exchange(true)) {
418       p.setValue(unwrap(std::move(results)));
419     }
420   }
421   Promise<std::tuple<Ts...>> p;
422   std::tuple<folly::Try<Ts>...> results;
423   std::atomic<bool> threw {false};
424   typedef Future<std::tuple<Ts...>> type;
425
426  private:
427   template <typename... Ts2>
428   static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& o,
429                                   Ts2&&... ts2) {
430     static_assert(sizeof...(ts2) <
431                   std::tuple_size<std::tuple<folly::Try<Ts>...>>::value,
432                   "Non-templated unwrap should be used instead");
433     assert(std::get<sizeof...(ts2)>(o).hasValue());
434
435     return unwrap(std::move(o),
436                   std::forward<Ts2>(ts2)...,
437                   std::move(*std::get<sizeof...(ts2)>(o)));
438   }
439
440   static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& /* o */,
441                                   Ts&&... ts) {
442     return std::tuple<Ts...>(std::forward<Ts>(ts)...);
443   }
444 };
445
446 template <template <typename...> class T, typename... Ts>
447 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
448   // base case
449 }
450
451 template <template <typename ...> class T, typename... Ts,
452           typename THead, typename... TTail>
453 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
454                            THead&& head, TTail&&... tail) {
455   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
456     ctx->template setPartialResult<typename THead::value_type,
457                                    sizeof...(Ts) - sizeof...(TTail) - 1>(t);
458   });
459   // template tail-recursion
460   collectVariadicHelper(ctx, std::forward<TTail>(tail)...);
461 }
462
463 }} // folly::detail