5b2dc82f7b44b6c8f9a4a910f1f17fdb0c6c1204
[folly.git] / folly / futures / Future.h
1 /*
2  * Copyright 2017-present 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 #pragma once
17
18 #include <algorithm>
19 #include <exception>
20 #include <functional>
21 #include <memory>
22 #include <type_traits>
23 #include <vector>
24
25 #include <folly/Optional.h>
26 #include <folly/Portability.h>
27 #include <folly/ScopeGuard.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
50 namespace futures {
51 namespace detail {
52 template <class T>
53 class FutureBase {
54  public:
55   typedef T value_type;
56
57   /// Construct a Future from a value (perfect forwarding)
58   template <
59       class T2 = T,
60       typename = typename std::enable_if<
61           !isFuture<typename std::decay<T2>::type>::value &&
62           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
63   /* implicit */ FutureBase(T2&& val);
64
65   template <class T2 = T>
66   /* implicit */ FutureBase(
67       typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
68
69   template <
70       class... Args,
71       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
72           type = 0>
73   explicit FutureBase(in_place_t, Args&&... args);
74
75   FutureBase(FutureBase<T> const&) = delete;
76   FutureBase(SemiFuture<T>&&) noexcept;
77   FutureBase(Future<T>&&) noexcept;
78
79   // not copyable
80   FutureBase(Future<T> const&) = delete;
81   FutureBase(SemiFuture<T> const&) = delete;
82
83   ~FutureBase();
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 a reference to the try of the result. Throws as for value if
100   /// future is not valid.
101   Try<T>& result() &;
102   Try<T> const& result() const&;
103   Try<T>&& result() &&;
104   Try<T> const&& result() const&&;
105
106   /** True when the result (or exception) is ready. */
107   bool isReady() const;
108
109   /// sugar for getTry().hasValue()
110   bool hasValue();
111
112   /// sugar for getTry().hasException()
113   bool hasException();
114
115   /// If the promise has been fulfilled, return an Optional with the Try<T>.
116   /// Otherwise return an empty Optional.
117   /// Note that this moves the Try<T> out.
118   Optional<Try<T>> poll();
119
120   /// This is not the method you're looking for.
121   ///
122   /// This needs to be public because it's used by make* and when*, and it's
123   /// not worth listing all those and their fancy template signatures as
124   /// friends. But it's not for public consumption.
125   template <class F>
126   void setCallback_(F&& func);
127
128   bool isActive() {
129     return core_->isActive();
130   }
131
132   template <class E>
133   void raise(E&& exception) {
134     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
135         std::forward<E>(exception)));
136   }
137
138   /// Raise an interrupt. If the promise holder has an interrupt
139   /// handler it will be called and potentially stop asynchronous work from
140   /// being done. This is advisory only - a promise holder may not set an
141   /// interrupt handler, or may do anything including ignore. But, if you know
142   /// your future supports this the most likely result is stopping or
143   /// preventing the asynchronous operation (if in time), and the promise
144   /// holder setting an exception on the future. (That may happen
145   /// asynchronously, of course.)
146   void raise(exception_wrapper interrupt);
147
148   void cancel() {
149     raise(FutureCancellation());
150   }
151
152  protected:
153   friend class Promise<T>;
154   template <class>
155   friend class SemiFuture;
156   template <class>
157   friend class Future;
158
159   using corePtr = futures::detail::Core<T>*;
160
161   // shared core state object
162   corePtr core_;
163
164   explicit FutureBase(corePtr obj) : core_(obj) {}
165
166   explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
167
168   void detach();
169
170   void throwIfInvalid() const;
171
172   template <class FutureType>
173   void assign(FutureType&) noexcept;
174
175   Executor* getExecutor() {
176     return core_->getExecutor();
177   }
178
179   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
180     core_->setExecutor(x, priority);
181   }
182
183   // Variant: returns a value
184   // e.g. f.then([](Try<T> t){ return t.value(); });
185   template <typename F, typename R, bool isTry, typename... Args>
186   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
187   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
188
189   // Variant: returns a Future
190   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
191   template <typename F, typename R, bool isTry, typename... Args>
192   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
193   thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
194 };
195 } // namespace detail
196 } // namespace futures
197
198 template <class T>
199 class SemiFuture : private futures::detail::FutureBase<T> {
200  private:
201   using Base = futures::detail::FutureBase<T>;
202   using DeferredExecutor = futures::detail::DeferredExecutor;
203
204  public:
205   static SemiFuture<T> makeEmpty(); // equivalent to moved-from
206
207   // Export public interface of FutureBase
208   // FutureBase is inherited privately to avoid subclasses being cast to
209   // a FutureBase pointer
210   using typename Base::value_type;
211
212   /// Construct a Future from a value (perfect forwarding)
213   template <
214       class T2 = T,
215       typename = typename std::enable_if<
216           !isFuture<typename std::decay<T2>::type>::value &&
217           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
218   /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
219
220   template <class T2 = T>
221   /* implicit */ SemiFuture(
222       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
223       : Base(p) {}
224
225   template <
226       class... Args,
227       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
228           type = 0>
229   explicit SemiFuture(in_place_t, Args&&... args)
230       : Base(in_place, std::forward<Args>(args)...) {}
231
232   SemiFuture(SemiFuture<T> const&) = delete;
233   // movable
234   SemiFuture(SemiFuture<T>&&) noexcept;
235   // safe move-constructabilty from Future
236   /* implicit */ SemiFuture(Future<T>&&) noexcept;
237
238   using Base::cancel;
239   using Base::hasException;
240   using Base::hasValue;
241   using Base::isActive;
242   using Base::isReady;
243   using Base::poll;
244   using Base::raise;
245   using Base::setCallback_;
246   using Base::value;
247   using Base::result;
248
249   SemiFuture& operator=(SemiFuture const&) = delete;
250   SemiFuture& operator=(SemiFuture&&) noexcept;
251   SemiFuture& operator=(Future<T>&&) noexcept;
252
253   /// Block until the future is fulfilled. Returns the value (moved out), or
254   /// throws the exception. The future must not already have a callback.
255   T get() &&;
256
257   /// Block until the future is fulfilled, or until timed out. Returns the
258   /// value (moved out), or throws the exception (which might be a TimedOut
259   /// exception).
260   T get(Duration dur) &&;
261
262   /// Block until the future is fulfilled, or until timed out. Returns the
263   /// Try of the value (moved out).
264   Try<T> getTry() &&;
265
266   /// Block until the future is fulfilled, or until timed out. Returns the
267   /// Try of the value (moved out) or may throw a TimedOut exception.
268   Try<T> getTry(Duration dur) &&;
269
270   /// Call e->drive() repeatedly until the future is fulfilled. Examples
271   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
272   /// value (moved out), or throws the exception.
273   T getVia(DrivableExecutor* e) &&;
274
275   /// Call e->drive() repeatedly until the future is fulfilled. Examples
276   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
277   /// Try of the value (moved out).
278   Try<T> getTryVia(DrivableExecutor* e) &&;
279
280   /// Block until this Future is complete. Returns a reference to this Future.
281   SemiFuture<T>& wait() &;
282
283   /// Overload of wait() for rvalue Futures
284   SemiFuture<T>&& wait() &&;
285
286   /// Block until this Future is complete or until the given Duration passes.
287   /// Returns a reference to this Future
288   SemiFuture<T>& wait(Duration) &;
289
290   /// Overload of wait(Duration) for rvalue Futures
291   SemiFuture<T>&& wait(Duration) &&;
292
293   /// Call e->drive() repeatedly until the future is fulfilled. Examples
294   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
295   /// reference to this SemiFuture so that you can chain calls if desired.
296   /// value (moved out), or throws the exception.
297   SemiFuture<T>& waitVia(DrivableExecutor* e) &;
298
299   /// Overload of waitVia() for rvalue Futures
300   SemiFuture<T>&& waitVia(DrivableExecutor* e) &&;
301
302   /// Returns an inactive Future which will call back on the other side of
303   /// executor (when it is activated).
304   ///
305   /// NB remember that Futures activate when they destruct. This is good,
306   /// it means that this will work:
307   ///
308   ///   f.via(e).then(a).then(b);
309   ///
310   /// a and b will execute in the same context (the far side of e), because
311   /// the Future (temporary variable) created by via(e) does not call back
312   /// until it destructs, which is after then(a) and then(b) have been wired
313   /// up.
314   ///
315   /// But this is still racy:
316   ///
317   ///   f = f.via(e).then(a);
318   ///   f.then(b);
319   // The ref-qualifier allows for `this` to be moved out so we
320   // don't get access-after-free situations in chaining.
321   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
322   inline Future<T> via(
323       Executor* executor,
324       int8_t priority = Executor::MID_PRI) &&;
325
326   /**
327    * Defer work to run on the consumer of the future.
328    * This work will be run eithe ron an executor that the caller sets on the
329    * SemiFuture, or inline with the call to .get().
330    * NB: This is a custom method because boost-blocking executors is a
331    * special-case for work deferral in folly. With more general boost-blocking
332    * support all executors would boost block and we would simply use some form
333    * of driveable executor here.
334    */
335   template <typename F>
336   SemiFuture<typename futures::detail::callableResult<T, F>::Return::value_type>
337   defer(F&& func) &&;
338
339   // Public as for setCallback_
340   // Ensure that a boostable executor performs work to chain deferred work
341   // cleanly
342   void boost_();
343
344  private:
345   friend class Promise<T>;
346   template <class>
347   friend class futures::detail::FutureBase;
348   template <class>
349   friend class SemiFuture;
350
351   using typename Base::corePtr;
352   using Base::setExecutor;
353   using Base::throwIfInvalid;
354
355   template <class T2>
356   friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
357
358   explicit SemiFuture(corePtr obj) : Base(obj) {}
359
360   explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
361       : Base(futures::detail::EmptyConstruct{}) {}
362 };
363
364 template <class T>
365 class Future : private futures::detail::FutureBase<T> {
366  private:
367   using Base = futures::detail::FutureBase<T>;
368
369  public:
370   // Export public interface of FutureBase
371   // FutureBase is inherited privately to avoid subclasses being cast to
372   // a FutureBase pointer
373   using typename Base::value_type;
374
375   /// Construct a Future from a value (perfect forwarding)
376   template <
377       class T2 = T,
378       typename = typename std::enable_if<
379           !isFuture<typename std::decay<T2>::type>::value &&
380           !isSemiFuture<typename std::decay<T2>::type>::value>::type>
381   /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
382
383   template <class T2 = T>
384   /* implicit */ Future(
385       typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
386       : Base(p) {}
387
388   template <
389       class... Args,
390       typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
391           type = 0>
392   explicit Future(in_place_t, Args&&... args)
393       : Base(in_place, std::forward<Args>(args)...) {}
394
395   Future(Future<T> const&) = delete;
396   // movable
397   Future(Future<T>&&) noexcept;
398
399   // converting move
400   template <
401       class T2,
402       typename std::enable_if<
403           !std::is_same<T, typename std::decay<T2>::type>::value &&
404               std::is_constructible<T, T2&&>::value &&
405               std::is_convertible<T2&&, T>::value,
406           int>::type = 0>
407   /* implicit */ Future(Future<T2>&&);
408   template <
409       class T2,
410       typename std::enable_if<
411           !std::is_same<T, typename std::decay<T2>::type>::value &&
412               std::is_constructible<T, T2&&>::value &&
413               !std::is_convertible<T2&&, T>::value,
414           int>::type = 0>
415   explicit Future(Future<T2>&&);
416   template <
417       class T2,
418       typename std::enable_if<
419           !std::is_same<T, typename std::decay<T2>::type>::value &&
420               std::is_constructible<T, T2&&>::value,
421           int>::type = 0>
422   Future& operator=(Future<T2>&&);
423
424   using Base::cancel;
425   using Base::hasException;
426   using Base::hasValue;
427   using Base::isActive;
428   using Base::isReady;
429   using Base::poll;
430   using Base::raise;
431   using Base::setCallback_;
432   using Base::value;
433   using Base::result;
434
435   static Future<T> makeEmpty(); // equivalent to moved-from
436
437   // not copyable
438   Future& operator=(Future const&) = delete;
439
440   // movable
441   Future& operator=(Future&&) noexcept;
442
443   /// Call e->drive() repeatedly until the future is fulfilled. Examples
444   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
445   /// value (moved out), or throws the exception.
446   T getVia(DrivableExecutor* e);
447
448   /// Call e->drive() repeatedly until the future is fulfilled. Examples
449   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
450   /// reference to the Try of the value.
451   Try<T>& getTryVia(DrivableExecutor* e);
452
453   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
454   /// Future<T> instance.
455   template <class F = T>
456   typename std::
457       enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
458       unwrap();
459
460   /// Returns an inactive Future which will call back on the other side of
461   /// executor (when it is activated).
462   ///
463   /// NB remember that Futures activate when they destruct. This is good,
464   /// it means that this will work:
465   ///
466   ///   f.via(e).then(a).then(b);
467   ///
468   /// a and b will execute in the same context (the far side of e), because
469   /// the Future (temporary variable) created by via(e) does not call back
470   /// until it destructs, which is after then(a) and then(b) have been wired
471   /// up.
472   ///
473   /// But this is still racy:
474   ///
475   ///   f = f.via(e).then(a);
476   ///   f.then(b);
477   // The ref-qualifier allows for `this` to be moved out so we
478   // don't get access-after-free situations in chaining.
479   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
480   inline Future<T> via(
481       Executor* executor,
482       int8_t priority = Executor::MID_PRI) &&;
483
484   /// This variant creates a new future, where the ref-qualifier && version
485   /// moves `this` out. This one is less efficient but avoids confusing users
486   /// when "return f.via(x);" fails.
487   inline Future<T> via(
488       Executor* executor,
489       int8_t priority = Executor::MID_PRI) &;
490
491   /** When this Future has completed, execute func which is a function that
492     takes one of:
493       (const) Try<T>&&
494       (const) Try<T>&
495       (const) Try<T>
496       (const) T&&
497       (const) T&
498       (const) T
499       (void)
500
501     Func shall return either another Future or a value.
502
503     A Future for the return type of func is returned.
504
505     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
506
507     The Future given to the functor is ready, and the functor may call
508     value(), which may rethrow if this has captured an exception. If func
509     throws, the exception will be captured in the Future that is returned.
510     */
511   template <typename F, typename R = futures::detail::callableResult<T, F>>
512   typename R::Return then(F&& func) {
513     return this->template thenImplementation<F, R>(
514         std::forward<F>(func), typename R::Arg());
515   }
516
517   /// Variant where func is an member function
518   ///
519   ///   struct Worker { R doWork(Try<T>); }
520   ///
521   ///   Worker *w;
522   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
523   ///
524   /// This is just sugar for
525   ///
526   ///   f1.then(std::bind(&Worker::doWork, w));
527   template <typename R, typename Caller, typename... Args>
528   Future<typename isFuture<R>::Inner> then(
529       R (Caller::*func)(Args...),
530       Caller* instance);
531
532   /// Execute the callback via the given Executor. The executor doesn't stick.
533   ///
534   /// Contrast
535   ///
536   ///   f.via(x).then(b).then(c)
537   ///
538   /// with
539   ///
540   ///   f.then(x, b).then(c)
541   ///
542   /// In the former both b and c execute via x. In the latter, only b executes
543   /// via x, and c executes via the same executor (if any) that f had.
544   template <class Executor, class Arg, class... Args>
545   auto then(Executor* x, Arg&& arg, Args&&... args) {
546     auto oldX = this->getExecutor();
547     this->setExecutor(x);
548     return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
549         .via(oldX);
550   }
551
552   /// Convenience method for ignoring the value and creating a Future<Unit>.
553   /// Exceptions still propagate.
554   /// This function is identical to .unit().
555   Future<Unit> then();
556
557   /// Convenience method for ignoring the value and creating a Future<Unit>.
558   /// Exceptions still propagate.
559   /// This function is identical to parameterless .then().
560   Future<Unit> unit() {
561     return then();
562   }
563
564   /// Set an error callback for this Future. The callback should take a single
565   /// argument of the type that you want to catch, and should return a value of
566   /// the same type as this Future, or a Future of that type (see overload
567   /// below). For instance,
568   ///
569   /// makeFuture()
570   ///   .then([] {
571   ///     throw std::runtime_error("oh no!");
572   ///     return 42;
573   ///   })
574   ///   .onError([] (std::runtime_error& e) {
575   ///     LOG(INFO) << "std::runtime_error: " << e.what();
576   ///     return -1; // or makeFuture<int>(-1)
577   ///   });
578   template <class F>
579   typename std::enable_if<
580       !futures::detail::callableWith<F, exception_wrapper>::value &&
581           !futures::detail::callableWith<F, exception_wrapper&>::value &&
582           !futures::detail::Extract<F>::ReturnsFuture::value,
583       Future<T>>::type
584   onError(F&& func);
585
586   /// Overload of onError where the error callback returns a Future<T>
587   template <class F>
588   typename std::enable_if<
589       !futures::detail::callableWith<F, exception_wrapper>::value &&
590           !futures::detail::callableWith<F, exception_wrapper&>::value &&
591           futures::detail::Extract<F>::ReturnsFuture::value,
592       Future<T>>::type
593   onError(F&& func);
594
595   /// Overload of onError that takes exception_wrapper and returns Future<T>
596   template <class F>
597   typename std::enable_if<
598       futures::detail::callableWith<F, exception_wrapper>::value &&
599           futures::detail::Extract<F>::ReturnsFuture::value,
600       Future<T>>::type
601   onError(F&& func);
602
603   /// Overload of onError that takes exception_wrapper and returns T
604   template <class F>
605   typename std::enable_if<
606       futures::detail::callableWith<F, exception_wrapper>::value &&
607           !futures::detail::Extract<F>::ReturnsFuture::value,
608       Future<T>>::type
609   onError(F&& func);
610
611   /// func is like std::function<void()> and is executed unconditionally, and
612   /// the value/exception is passed through to the resulting Future.
613   /// func shouldn't throw, but if it does it will be captured and propagated,
614   /// and discard any value/exception that this Future has obtained.
615   template <class F>
616   Future<T> ensure(F&& func);
617
618   /// Like onError, but for timeouts. example:
619   ///
620   ///   Future<int> f = makeFuture<int>(42)
621   ///     .delayed(long_time)
622   ///     .onTimeout(short_time,
623   ///       []() -> int{ return -1; });
624   ///
625   /// or perhaps
626   ///
627   ///   Future<int> f = makeFuture<int>(42)
628   ///     .delayed(long_time)
629   ///     .onTimeout(short_time,
630   ///       []() { return makeFuture<int>(some_exception); });
631   template <class F>
632   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
633
634   /// A Future's callback is executed when all three of these conditions have
635   /// become true: it has a value (set by the Promise), it has a callback (set
636   /// by then), and it is active (active by default).
637   ///
638   /// Inactive Futures will activate upon destruction.
639   FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
640     this->core_->activate();
641     return *this;
642   }
643   FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
644     this->core_->deactivate();
645     return *this;
646   }
647   FOLLY_DEPRECATED("do not use") Future<T> activate() && {
648     this->core_->activate();
649     return std::move(*this);
650   }
651   FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
652     this->core_->deactivate();
653     return std::move(*this);
654   }
655
656   /// Throw TimedOut if this Future does not complete within the given
657   /// duration from now. The optional Timeekeeper is as with futures::sleep().
658   Future<T> within(Duration, Timekeeper* = nullptr);
659
660   /// Throw the given exception if this Future does not complete within the
661   /// given duration from now. The optional Timeekeeper is as with
662   /// futures::sleep().
663   template <class E>
664   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
665
666   /// Delay the completion of this Future for at least this duration from
667   /// now. The optional Timekeeper is as with futures::sleep().
668   Future<T> delayed(Duration, Timekeeper* = nullptr);
669
670   /// Block until the future is fulfilled. Returns the value (moved out), or
671   /// throws the exception. The future must not already have a callback.
672   T get();
673
674   /// Block until the future is fulfilled, or until timed out. Returns the
675   /// value (moved out), or throws the exception (which might be a TimedOut
676   /// exception).
677   T get(Duration dur);
678
679   /** A reference to the Try of the value */
680   Try<T>& getTry();
681
682   /// Block until this Future is complete. Returns a reference to this Future.
683   Future<T>& wait() &;
684
685   /// Overload of wait() for rvalue Futures
686   Future<T>&& wait() &&;
687
688   /// Block until this Future is complete or until the given Duration passes.
689   /// Returns a reference to this Future
690   Future<T>& wait(Duration) &;
691
692   /// Overload of wait(Duration) for rvalue Futures
693   Future<T>&& wait(Duration) &&;
694
695   /// Call e->drive() repeatedly until the future is fulfilled. Examples
696   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
697   /// reference to this Future so that you can chain calls if desired.
698   /// value (moved out), or throws the exception.
699   Future<T>& waitVia(DrivableExecutor* e) &;
700
701   /// Overload of waitVia() for rvalue Futures
702   Future<T>&& waitVia(DrivableExecutor* e) &&;
703
704   /// If the value in this Future is equal to the given Future, when they have
705   /// both completed, the value of the resulting Future<bool> will be true. It
706   /// will be false otherwise (including when one or both Futures have an
707   /// exception)
708   Future<bool> willEqual(Future<T>&);
709
710   /// predicate behaves like std::function<bool(T const&)>
711   /// If the predicate does not obtain with the value, the result
712   /// is a folly::PredicateDoesNotObtain exception
713   template <class F>
714   Future<T> filter(F&& predicate);
715
716   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
717   /// the result of collect or collectAll
718   template <class I, class F>
719   Future<I> reduce(I&& initial, F&& func);
720
721   /// Create a Future chain from a sequence of callbacks. i.e.
722   ///
723   ///   f.then(a).then(b).then(c)
724   ///
725   /// where f is a Future<A> and the result of the chain is a Future<D>
726   /// becomes
727   ///
728   ///   f.thenMulti(a, b, c);
729   template <class Callback, class... Callbacks>
730   auto thenMulti(Callback&& fn, Callbacks&&... fns) {
731     // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
732     return then(std::forward<Callback>(fn))
733         .thenMulti(std::forward<Callbacks>(fns)...);
734   }
735
736   template <class Callback>
737   auto thenMulti(Callback&& fn) {
738     // thenMulti with one callback is just a then
739     return then(std::forward<Callback>(fn));
740   }
741
742   /// Create a Future chain from a sequence of callbacks. i.e.
743   ///
744   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
745   ///
746   /// where f is a Future<A> and the result of the chain is a Future<D>
747   /// becomes
748   ///
749   ///   f.thenMultiWithExecutor(executor, a, b, c);
750   template <class Callback, class... Callbacks>
751   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
752     // thenMultiExecutor with two callbacks is
753     // via(x).then(a).thenMulti(b, ...).via(oldX)
754     auto oldX = this->getExecutor();
755     this->setExecutor(x);
756     return then(std::forward<Callback>(fn))
757         .thenMulti(std::forward<Callbacks>(fns)...)
758         .via(oldX);
759   }
760
761   template <class Callback>
762   auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
763     // thenMulti with one callback is just a then with an executor
764     return then(x, std::forward<Callback>(fn));
765   }
766
767   // Convert this Future to a SemiFuture to safely export from a library
768   // without exposing a continuation interface
769   SemiFuture<T> semi() {
770     return SemiFuture<T>{std::move(*this)};
771   }
772
773  protected:
774   friend class Promise<T>;
775   template <class>
776   friend class futures::detail::FutureBase;
777   template <class>
778   friend class Future;
779   template <class>
780   friend class SemiFuture;
781
782   using Base::setExecutor;
783   using Base::throwIfInvalid;
784   using typename Base::corePtr;
785
786   explicit Future(corePtr obj) : Base(obj) {}
787
788   explicit Future(futures::detail::EmptyConstruct) noexcept
789       : Base(futures::detail::EmptyConstruct{}) {}
790
791   template <class T2>
792   friend Future<T2> makeFuture(Try<T2>&&);
793
794   /// Repeat the given future (i.e., the computation it contains)
795   /// n times.
796   ///
797   /// thunk behaves like std::function<Future<T2>(void)>
798   template <class F>
799   friend Future<Unit> times(int n, F&& thunk);
800
801   /// Carry out the computation contained in the given future if
802   /// the predicate holds.
803   ///
804   /// thunk behaves like std::function<Future<T2>(void)>
805   template <class F>
806   friend Future<Unit> when(bool p, F&& thunk);
807
808   /// Carry out the computation contained in the given future if
809   /// while the predicate continues to hold.
810   ///
811   /// thunk behaves like std::function<Future<T2>(void)>
812   ///
813   /// predicate behaves like std::function<bool(void)>
814   template <class P, class F>
815   friend Future<Unit> whileDo(P&& predicate, F&& thunk);
816 };
817
818 } // namespace folly
819
820 #include <folly/futures/Future-inl.h>