folly/futures: replace MoveWrappers with generalised lambda capture
[folly.git] / folly / futures / detail / Core.h
1 /*
2  * Copyright 2016 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/Executor.h>
25 #include <folly/Function.h>
26 #include <folly/MicroSpinLock.h>
27 #include <folly/Optional.h>
28 #include <folly/futures/Future.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/futures/Try.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   // Core is assumed to be convertible only if the type is convertible
103   // and the size is the same. This is a compromise for the complexity
104   // of having to make Core truly have a conversion constructor which
105   // would cause various other problems.
106   // If we made Core move constructible then we would need to update the
107   // Promise and Future with the location of the new Core. This is complex
108   // and may be inefficient.
109   // Core should only be modified so that for size(T) == size(U),
110   // sizeof(Core<T>) == size(Core<U>).
111   // This assumption is used as a proxy to make sure that
112   // the members of Core<T> and Core<U> line up so that we can use a
113   // reinterpret cast.
114   template <
115       class U,
116       typename = typename std::enable_if<std::is_convertible<U, T>::value &&
117                                          sizeof(U) == sizeof(T)>::type>
118   static Core<T>* convert(Core<U>* from) {
119     return reinterpret_cast<Core<T>*>(from);
120   }
121
122   /// May call from any thread
123   bool hasResult() const {
124     switch (fsm_.getState()) {
125       case State::OnlyResult:
126       case State::Armed:
127       case State::Done:
128         assert(!!result_);
129         return true;
130
131       default:
132         return false;
133     }
134   }
135
136   /// May call from any thread
137   bool ready() const {
138     return hasResult();
139   }
140
141   /// May call from any thread
142   Try<T>& getTry() {
143     if (ready()) {
144       return *result_;
145     } else {
146       throw FutureNotReady();
147     }
148   }
149
150   /// Call only from Future thread.
151   template <typename F>
152   void setCallback(F&& func) {
153     bool transitionToArmed = false;
154     auto setCallback_ = [&]{
155       context_ = RequestContext::saveContext();
156       callback_ = std::forward<F>(func);
157     };
158
159     FSM_START(fsm_)
160       case State::Start:
161         FSM_UPDATE(fsm_, State::OnlyCallback, setCallback_);
162         break;
163
164       case State::OnlyResult:
165         FSM_UPDATE(fsm_, State::Armed, setCallback_);
166         transitionToArmed = true;
167         break;
168
169       case State::OnlyCallback:
170       case State::Armed:
171       case State::Done:
172         throw std::logic_error("setCallback called twice");
173     FSM_END
174
175     // we could always call this, it is an optimization to only call it when
176     // it might be needed.
177     if (transitionToArmed) {
178       maybeCallback();
179     }
180   }
181
182   /// Call only from Promise thread
183   void setResult(Try<T>&& t) {
184     bool transitionToArmed = false;
185     auto setResult_ = [&]{ result_ = std::move(t); };
186     FSM_START(fsm_)
187       case State::Start:
188         FSM_UPDATE(fsm_, State::OnlyResult, setResult_);
189         break;
190
191       case State::OnlyCallback:
192         FSM_UPDATE(fsm_, State::Armed, setResult_);
193         transitionToArmed = true;
194         break;
195
196       case State::OnlyResult:
197       case State::Armed:
198       case State::Done:
199         throw std::logic_error("setResult called twice");
200     FSM_END
201
202     if (transitionToArmed) {
203       maybeCallback();
204     }
205   }
206
207   /// Called by a destructing Future (in the Future thread, by definition)
208   void detachFuture() {
209     activate();
210     detachOne();
211   }
212
213   /// Called by a destructing Promise (in the Promise thread, by definition)
214   void detachPromise() {
215     // detachPromise() and setResult() should never be called in parallel
216     // so we don't need to protect this.
217     if (UNLIKELY(!result_)) {
218       setResult(Try<T>(exception_wrapper(BrokenPromise(typeid(T).name()))));
219     }
220     detachOne();
221   }
222
223   /// May call from any thread
224   void deactivate() {
225     active_.store(false, std::memory_order_release);
226   }
227
228   /// May call from any thread
229   void activate() {
230     active_.store(true, std::memory_order_release);
231     maybeCallback();
232   }
233
234   /// May call from any thread
235   bool isActive() { return active_.load(std::memory_order_acquire); }
236
237   /// Call only from Future thread
238   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
239     if (!executorLock_.try_lock()) {
240       executorLock_.lock();
241     }
242     executor_ = x;
243     priority_ = priority;
244     executorLock_.unlock();
245   }
246
247   void setExecutorNoLock(Executor* x, int8_t priority = Executor::MID_PRI) {
248     executor_ = x;
249     priority_ = priority;
250   }
251
252   Executor* getExecutor() {
253     return executor_;
254   }
255
256   /// Call only from Future thread
257   void raise(exception_wrapper e) {
258     if (!interruptLock_.try_lock()) {
259       interruptLock_.lock();
260     }
261     if (!interrupt_ && !hasResult()) {
262       interrupt_ = folly::make_unique<exception_wrapper>(std::move(e));
263       if (interruptHandler_) {
264         interruptHandler_(*interrupt_);
265       }
266     }
267     interruptLock_.unlock();
268   }
269
270   std::function<void(exception_wrapper const&)> getInterruptHandler() {
271     if (!interruptHandlerSet_.load(std::memory_order_acquire)) {
272       return nullptr;
273     }
274     if (!interruptLock_.try_lock()) {
275       interruptLock_.lock();
276     }
277     auto handler = interruptHandler_;
278     interruptLock_.unlock();
279     return handler;
280   }
281
282   /// Call only from Promise thread
283   void setInterruptHandler(std::function<void(exception_wrapper const&)> fn) {
284     if (!interruptLock_.try_lock()) {
285       interruptLock_.lock();
286     }
287     if (!hasResult()) {
288       if (interrupt_) {
289         fn(*interrupt_);
290       } else {
291         setInterruptHandlerNoLock(std::move(fn));
292       }
293     }
294     interruptLock_.unlock();
295   }
296
297   void setInterruptHandlerNoLock(
298       std::function<void(exception_wrapper const&)> fn) {
299     interruptHandlerSet_.store(true, std::memory_order_relaxed);
300     interruptHandler_ = std::move(fn);
301   }
302
303  protected:
304   void maybeCallback() {
305     FSM_START(fsm_)
306       case State::Armed:
307         if (active_.load(std::memory_order_acquire)) {
308           FSM_UPDATE2(fsm_, State::Done, []{}, [this]{ this->doCallback(); });
309         }
310         FSM_BREAK
311
312       default:
313         FSM_BREAK
314     FSM_END
315   }
316
317   void doCallback() {
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     // keep Core alive until callback did its thing
330     ++attached_;
331
332     if (x) {
333       try {
334         if (LIKELY(x->getNumPriorities() == 1)) {
335           x->add([this]() mutable {
336             SCOPE_EXIT { detachOne(); };
337             RequestContext::setContext(context_);
338             SCOPE_EXIT { callback_ = {}; };
339             callback_(std::move(*result_));
340           });
341         } else {
342           x->addWithPriority([this]() mutable {
343             SCOPE_EXIT { detachOne(); };
344             RequestContext::setContext(context_);
345             SCOPE_EXIT { callback_ = {}; };
346             callback_(std::move(*result_));
347           }, priority);
348         }
349       } catch (...) {
350         --attached_; // Account for extra ++attached_ before try
351         RequestContext::setContext(context_);
352         result_ = Try<T>(exception_wrapper(std::current_exception()));
353         SCOPE_EXIT { callback_ = {}; };
354         callback_(std::move(*result_));
355       }
356     } else {
357       SCOPE_EXIT { detachOne(); };
358       RequestContext::setContext(context_);
359       SCOPE_EXIT { callback_ = {}; };
360       callback_(std::move(*result_));
361     }
362   }
363
364   void detachOne() {
365     auto a = --attached_;
366     assert(a >= 0);
367     assert(a <= 2);
368     if (a == 0) {
369       delete this;
370     }
371   }
372
373   // Core should only be modified so that for size(T) == size(U),
374   // sizeof(Core<T>) == size(Core<U>).
375   // See Core::convert for details.
376
377   folly::Function<
378       void(Try<T>&&),
379       folly::FunctionMoveCtor::MAY_THROW,
380       8 * sizeof(void*)>
381       callback_;
382   // place result_ next to increase the likelihood that the value will be
383   // contained entirely in one cache line
384   folly::Optional<Try<T>> result_;
385   FSM<State> fsm_;
386   std::atomic<unsigned char> attached_;
387   std::atomic<bool> active_ {true};
388   std::atomic<bool> interruptHandlerSet_ {false};
389   folly::MicroSpinLock interruptLock_ {0};
390   folly::MicroSpinLock executorLock_ {0};
391   int8_t priority_ {-1};
392   Executor* executor_ {nullptr};
393   std::shared_ptr<RequestContext> context_ {nullptr};
394   std::unique_ptr<exception_wrapper> interrupt_ {};
395   std::function<void(exception_wrapper const&)> interruptHandler_ {nullptr};
396 };
397
398 template <typename... Ts>
399 struct CollectAllVariadicContext {
400   CollectAllVariadicContext() {}
401   template <typename T, size_t I>
402   inline void setPartialResult(Try<T>& t) {
403     std::get<I>(results) = std::move(t);
404   }
405   ~CollectAllVariadicContext() {
406     p.setValue(std::move(results));
407   }
408   Promise<std::tuple<Try<Ts>...>> p;
409   std::tuple<Try<Ts>...> results;
410   typedef Future<std::tuple<Try<Ts>...>> type;
411 };
412
413 template <typename... Ts>
414 struct CollectVariadicContext {
415   CollectVariadicContext() {}
416   template <typename T, size_t I>
417   inline void setPartialResult(Try<T>& t) {
418     if (t.hasException()) {
419        if (!threw.exchange(true)) {
420          p.setException(std::move(t.exception()));
421        }
422      } else if (!threw) {
423        std::get<I>(results) = std::move(t);
424      }
425   }
426   ~CollectVariadicContext() {
427     if (!threw.exchange(true)) {
428       p.setValue(unwrap(std::move(results)));
429     }
430   }
431   Promise<std::tuple<Ts...>> p;
432   std::tuple<folly::Try<Ts>...> results;
433   std::atomic<bool> threw {false};
434   typedef Future<std::tuple<Ts...>> type;
435
436  private:
437   template <typename... Ts2>
438   static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& o,
439                                   Ts2&&... ts2) {
440     static_assert(sizeof...(ts2) <
441                   std::tuple_size<std::tuple<folly::Try<Ts>...>>::value,
442                   "Non-templated unwrap should be used instead");
443     assert(std::get<sizeof...(ts2)>(o).hasValue());
444
445     return unwrap(std::move(o),
446                   std::forward<Ts2>(ts2)...,
447                   std::move(*std::get<sizeof...(ts2)>(o)));
448   }
449
450   static std::tuple<Ts...> unwrap(std::tuple<folly::Try<Ts>...>&& /* o */,
451                                   Ts&&... ts) {
452     return std::tuple<Ts...>(std::forward<Ts>(ts)...);
453   }
454 };
455
456 template <template <typename...> class T, typename... Ts>
457 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& /* ctx */) {
458   // base case
459 }
460
461 template <template <typename ...> class T, typename... Ts,
462           typename THead, typename... TTail>
463 void collectVariadicHelper(const std::shared_ptr<T<Ts...>>& ctx,
464                            THead&& head, TTail&&... tail) {
465   head.setCallback_([ctx](Try<typename THead::value_type>&& t) {
466     ctx->template setPartialResult<typename THead::value_type,
467                                    sizeof...(Ts) - sizeof...(TTail) - 1>(t);
468   });
469   // template tail-recursion
470   collectVariadicHelper(ctx, std::forward<TTail>(tail)...);
471 }
472
473 }} // folly::detail