(Wangle) chain -> thenMulti + thenMultiWithExecutor
[folly.git] / folly / futures / Future.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 <algorithm>
20 #include <exception>
21 #include <functional>
22 #include <memory>
23 #include <type_traits>
24 #include <vector>
25
26 #include <folly/Optional.h>
27 #include <folly/MoveWrapper.h>
28 #include <folly/futures/Deprecated.h>
29 #include <folly/futures/DrivableExecutor.h>
30 #include <folly/futures/Promise.h>
31 #include <folly/futures/Try.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/detail/Types.h>
34
35 // boring predeclarations and details
36 #include <folly/futures/Future-pre.h>
37
38 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
39 // Needs to be included after Future-pre.h and before Future-inl.h
40 #include <folly/futures/helpers.h>
41
42 namespace folly {
43
44 template <class T>
45 class Future {
46  public:
47   typedef T value_type;
48
49   // not copyable
50   Future(Future const&) = delete;
51   Future& operator=(Future const&) = delete;
52
53   // movable
54   Future(Future&&) noexcept;
55   Future& operator=(Future&&) noexcept;
56
57   /// Construct a Future from a value (perfect forwarding)
58   template <class T2 = T, typename =
59             typename std::enable_if<
60               !isFuture<typename std::decay<T2>::type>::value>::type>
61   /* implicit */ Future(T2&& val);
62
63   template <class T2 = T,
64             typename std::enable_if<
65               folly::is_void_or_unit<T2>::value,
66               int>::type = 0>
67   Future();
68
69   ~Future();
70
71   /** Return the reference to result. Should not be called if !isReady().
72     Will rethrow the exception if an exception has been
73     captured.
74     */
75   typename std::add_lvalue_reference<T>::type
76   value();
77   typename std::add_lvalue_reference<const T>::type
78   value() const;
79
80   /// Returns an inactive Future which will call back on the other side of
81   /// executor (when it is activated).
82   ///
83   /// NB remember that Futures activate when they destruct. This is good,
84   /// it means that this will work:
85   ///
86   ///   f.via(e).then(a).then(b);
87   ///
88   /// a and b will execute in the same context (the far side of e), because
89   /// the Future (temporary variable) created by via(e) does not call back
90   /// until it destructs, which is after then(a) and then(b) have been wired
91   /// up.
92   ///
93   /// But this is still racy:
94   ///
95   ///   f = f.via(e).then(a);
96   ///   f.then(b);
97   // The ref-qualifier allows for `this` to be moved out so we
98   // don't get access-after-free situations in chaining.
99   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
100   inline Future<T> via(
101       Executor* executor,
102       int8_t priority = Executor::MID_PRI) &&;
103
104   /// This variant creates a new future, where the ref-qualifier && version
105   /// moves `this` out. This one is less efficient but avoids confusing users
106   /// when "return f.via(x);" fails.
107   inline Future<T> via(
108       Executor* executor,
109       int8_t priority = Executor::MID_PRI) &;
110
111   /** True when the result (or exception) is ready. */
112   bool isReady() const;
113
114   /** A reference to the Try of the value */
115   Try<T>& getTry();
116
117   /// If the promise has been fulfilled, return an Optional with the Try<T>.
118   /// Otherwise return an empty Optional.
119   /// Note that this moves the Try<T> out.
120   Optional<Try<T>> poll();
121
122   /// Block until the future is fulfilled. Returns the value (moved out), or
123   /// throws the exception. The future must not already have a callback.
124   T get();
125
126   /// Block until the future is fulfilled, or until timed out. Returns the
127   /// value (moved out), or throws the exception (which might be a TimedOut
128   /// exception).
129   T get(Duration dur);
130
131   /// Call e->drive() repeatedly until the future is fulfilled. Examples
132   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
133   /// value (moved out), or throws the exception.
134   T getVia(DrivableExecutor* e);
135
136   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
137   /// Future<T> instance.
138   template <class F = T>
139   typename std::enable_if<isFuture<F>::value,
140                           Future<typename isFuture<T>::Inner>>::type
141   unwrap();
142
143   /** When this Future has completed, execute func which is a function that
144     takes one of:
145       (const) Try<T>&&
146       (const) Try<T>&
147       (const) Try<T>
148       (const) T&&
149       (const) T&
150       (const) T
151       (void)
152
153     Func shall return either another Future or a value.
154
155     A Future for the return type of func is returned.
156
157     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
158
159     The Future given to the functor is ready, and the functor may call
160     value(), which may rethrow if this has captured an exception. If func
161     throws, the exception will be captured in the Future that is returned.
162     */
163   /* TODO n3428 and other async frameworks have something like then(scheduler,
164      Future), we might want to support a similar API which could be
165      implemented a little more efficiently than
166      f.via(executor).then(callback) */
167   template <typename F, typename R = detail::callableResult<T, F>>
168   typename R::Return then(F func) {
169     typedef typename R::Arg Arguments;
170     return thenImplementation<F, R>(std::move(func), Arguments());
171   }
172
173   /// Variant where func is an member function
174   ///
175   ///   struct Worker { R doWork(Try<T>); }
176   ///
177   ///   Worker *w;
178   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
179   ///
180   /// This is just sugar for
181   ///
182   ///   f1.then(std::bind(&Worker::doWork, w));
183   template <typename R, typename Caller, typename... Args>
184   Future<typename isFuture<R>::Inner>
185   then(R(Caller::*func)(Args...), Caller *instance);
186
187   /// Execute the callback via the given Executor. The executor doesn't stick.
188   ///
189   /// Contrast
190   ///
191   ///   f.via(x).then(b).then(c)
192   ///
193   /// with
194   ///
195   ///   f.then(x, b).then(c)
196   ///
197   /// In the former both b and c execute via x. In the latter, only b executes
198   /// via x, and c executes via the same executor (if any) that f had.
199   template <class Executor, class Arg, class... Args>
200   auto then(Executor* x, Arg&& arg, Args&&... args)
201     -> decltype(this->then(std::forward<Arg>(arg),
202                            std::forward<Args>(args)...));
203
204   /// Convenience method for ignoring the value and creating a Future<void>.
205   /// Exceptions still propagate.
206   Future<void> then();
207
208   /// Set an error callback for this Future. The callback should take a single
209   /// argument of the type that you want to catch, and should return a value of
210   /// the same type as this Future, or a Future of that type (see overload
211   /// below). For instance,
212   ///
213   /// makeFuture()
214   ///   .then([] {
215   ///     throw std::runtime_error("oh no!");
216   ///     return 42;
217   ///   })
218   ///   .onError([] (std::runtime_error& e) {
219   ///     LOG(INFO) << "std::runtime_error: " << e.what();
220   ///     return -1; // or makeFuture<int>(-1)
221   ///   });
222   template <class F>
223   typename std::enable_if<
224     !detail::callableWith<F, exception_wrapper>::value &&
225     !detail::Extract<F>::ReturnsFuture::value,
226     Future<T>>::type
227   onError(F&& func);
228
229   /// Overload of onError where the error callback returns a Future<T>
230   template <class F>
231   typename std::enable_if<
232     !detail::callableWith<F, exception_wrapper>::value &&
233     detail::Extract<F>::ReturnsFuture::value,
234     Future<T>>::type
235   onError(F&& func);
236
237   /// Overload of onError that takes exception_wrapper and returns Future<T>
238   template <class F>
239   typename std::enable_if<
240     detail::callableWith<F, exception_wrapper>::value &&
241     detail::Extract<F>::ReturnsFuture::value,
242     Future<T>>::type
243   onError(F&& func);
244
245   /// Overload of onError that takes exception_wrapper and returns T
246   template <class F>
247   typename std::enable_if<
248     detail::callableWith<F, exception_wrapper>::value &&
249     !detail::Extract<F>::ReturnsFuture::value,
250     Future<T>>::type
251   onError(F&& func);
252
253   /// func is like std::function<void()> and is executed unconditionally, and
254   /// the value/exception is passed through to the resulting Future.
255   /// func shouldn't throw, but if it does it will be captured and propagated,
256   /// and discard any value/exception that this Future has obtained.
257   template <class F>
258   Future<T> ensure(F func);
259
260   /// Like onError, but for timeouts. example:
261   ///
262   ///   Future<int> f = makeFuture<int>(42)
263   ///     .delayed(long_time)
264   ///     .onTimeout(short_time,
265   ///       []() -> int{ return -1; });
266   ///
267   /// or perhaps
268   ///
269   ///   Future<int> f = makeFuture<int>(42)
270   ///     .delayed(long_time)
271   ///     .onTimeout(short_time,
272   ///       []() { return makeFuture<int>(some_exception); });
273   template <class F>
274   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
275
276   /// This is not the method you're looking for.
277   ///
278   /// This needs to be public because it's used by make* and when*, and it's
279   /// not worth listing all those and their fancy template signatures as
280   /// friends. But it's not for public consumption.
281   template <class F>
282   void setCallback_(F&& func);
283
284   /// A Future's callback is executed when all three of these conditions have
285   /// become true: it has a value (set by the Promise), it has a callback (set
286   /// by then), and it is active (active by default).
287   ///
288   /// Inactive Futures will activate upon destruction.
289   Future<T>& activate() & DEPRECATED {
290     core_->activate();
291     return *this;
292   }
293   Future<T>& deactivate() & DEPRECATED {
294     core_->deactivate();
295     return *this;
296   }
297   Future<T> activate() && DEPRECATED {
298     core_->activate();
299     return std::move(*this);
300   }
301   Future<T> deactivate() && DEPRECATED {
302     core_->deactivate();
303     return std::move(*this);
304   }
305
306   bool isActive() {
307     return core_->isActive();
308   }
309
310   template <class E>
311   void raise(E&& exception) {
312     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
313         std::move(exception)));
314   }
315
316   /// Raise an interrupt. If the promise holder has an interrupt
317   /// handler it will be called and potentially stop asynchronous work from
318   /// being done. This is advisory only - a promise holder may not set an
319   /// interrupt handler, or may do anything including ignore. But, if you know
320   /// your future supports this the most likely result is stopping or
321   /// preventing the asynchronous operation (if in time), and the promise
322   /// holder setting an exception on the future. (That may happen
323   /// asynchronously, of course.)
324   void raise(exception_wrapper interrupt);
325
326   void cancel() {
327     raise(FutureCancellation());
328   }
329
330   /// Throw TimedOut if this Future does not complete within the given
331   /// duration from now. The optional Timeekeeper is as with futures::sleep().
332   Future<T> within(Duration, Timekeeper* = nullptr);
333
334   /// Throw the given exception if this Future does not complete within the
335   /// given duration from now. The optional Timeekeeper is as with
336   /// futures::sleep().
337   template <class E>
338   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
339
340   /// Delay the completion of this Future for at least this duration from
341   /// now. The optional Timekeeper is as with futures::sleep().
342   Future<T> delayed(Duration, Timekeeper* = nullptr);
343
344   /// Block until this Future is complete. Returns a reference to this Future.
345   Future<T>& wait() &;
346
347   /// Overload of wait() for rvalue Futures
348   Future<T>&& wait() &&;
349
350   /// Block until this Future is complete or until the given Duration passes.
351   /// Returns a reference to this Future
352   Future<T>& wait(Duration) &;
353
354   /// Overload of wait(Duration) for rvalue Futures
355   Future<T>&& wait(Duration) &&;
356
357   /// Call e->drive() repeatedly until the future is fulfilled. Examples
358   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
359   /// reference to this Future so that you can chain calls if desired.
360   /// value (moved out), or throws the exception.
361   Future<T>& waitVia(DrivableExecutor* e) &;
362
363   /// Overload of waitVia() for rvalue Futures
364   Future<T>&& waitVia(DrivableExecutor* e) &&;
365
366   /// If the value in this Future is equal to the given Future, when they have
367   /// both completed, the value of the resulting Future<bool> will be true. It
368   /// will be false otherwise (including when one or both Futures have an
369   /// exception)
370   Future<bool> willEqual(Future<T>&);
371
372   /// predicate behaves like std::function<bool(T const&)>
373   /// If the predicate does not obtain with the value, the result
374   /// is a folly::PredicateDoesNotObtain exception
375   template <class F>
376   Future<T> filter(F predicate);
377
378   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
379   /// the result of collect or collectAll
380   template <class I, class F>
381   Future<I> reduce(I&& initial, F&& func);
382
383   /// Create a Future chain from a sequence of callbacks. i.e.
384   ///
385   ///   f.then(a).then(b).then(c)
386   ///
387   /// where f is a Future<A> and the result of the chain is a Future<D>
388   /// becomes
389   ///
390   ///   f.thenMulti(a, b, c);
391   template <class Callback, class... Callbacks>
392   auto thenMulti(Callback&& fn, Callbacks&&... fns)
393     -> decltype(this->then(std::forward<Callback>(fn)).
394                       thenMulti(std::forward<Callbacks>(fns)...));
395
396   // Nothing to see here, just thenMulti's base case
397   template <class Callback>
398   auto thenMulti(Callback&& fn)
399     -> decltype(this->then(std::forward<Callback>(fn)));
400
401   /// Create a Future chain from a sequence of callbacks. i.e.
402   ///
403   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
404   ///
405   /// where f is a Future<A> and the result of the chain is a Future<D>
406   /// becomes
407   ///
408   ///   f.thenMultiWithExecutor(executor, a, b, c);
409   template <class Callback, class... Callbacks>
410   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
411     -> decltype(this->then(std::forward<Callback>(fn)).
412                       thenMulti(std::forward<Callbacks>(fns)...));
413
414   // Nothing to see here, just thenMultiWithExecutor's base case
415   template <class Callback>
416   auto thenMultiWithExecutor(Executor* x, Callback&& fn)
417     -> decltype(this->then(std::forward<Callback>(fn)));
418
419  protected:
420   typedef detail::Core<T>* corePtr;
421
422   // shared core state object
423   corePtr core_;
424
425   explicit
426   Future(corePtr obj) : core_(obj) {}
427
428   void detach();
429
430   void throwIfInvalid() const;
431
432   friend class Promise<T>;
433   template <class> friend class Future;
434
435   // Variant: returns a value
436   // e.g. f.then([](Try<T> t){ return t.value(); });
437   template <typename F, typename R, bool isTry, typename... Args>
438   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
439   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
440
441   // Variant: returns a Future
442   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
443   template <typename F, typename R, bool isTry, typename... Args>
444   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
445   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
446
447   Executor* getExecutor() { return core_->getExecutor(); }
448   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
449     core_->setExecutor(x, priority);
450   }
451 };
452
453 } // folly
454
455 #include <folly/futures/Future-inl.h>