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