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