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