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