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