getVia() and waitVia()
[folly.git] / folly / futures / Future.h
1 /*
2  * Copyright 2014 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/MoveWrapper.h>
27 #include <folly/futures/Deprecated.h>
28 #include <folly/futures/DrivableExecutor.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/futures/Try.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/detail/Types.h>
33
34 namespace folly {
35
36 template <class> struct Promise;
37
38 namespace detail {
39
40 template <class> struct Core;
41 template <class...> struct VariadicContext;
42
43 template <class T>
44 struct AliasIfVoid {
45   typedef typename std::conditional<
46     std::is_same<T, void>::value,
47     int,
48     T>::type type;
49 };
50
51
52 template <typename T>
53 struct IsFuture : std::integral_constant<bool, false> {
54     typedef T Inner;
55 };
56
57 template <template <typename T> class Future, typename T>
58 struct IsFuture<Future<T>> : std::integral_constant<bool, true> {
59     typedef T Inner;
60 };
61
62 template <typename...>
63 struct ArgType;
64
65 template <typename Arg, typename... Args>
66 struct ArgType<Arg, Args...> {
67   typedef Arg FirstArg;
68 };
69
70 template <>
71 struct ArgType<> {
72   typedef void FirstArg;
73 };
74
75 template <typename L>
76 struct Extract : Extract<decltype(&L::operator())> { };
77
78 template <typename Class, typename R, typename... Args>
79 struct Extract<R(Class::*)(Args...) const> {
80   typedef IsFuture<R> ReturnsFuture;
81   typedef Future<typename ReturnsFuture::Inner> Return;
82   typedef typename ReturnsFuture::Inner RawReturn;
83   typedef typename ArgType<Args...>::FirstArg FirstArg;
84 };
85
86 template <typename Class, typename R, typename... Args>
87 struct Extract<R(Class::*)(Args...)> {
88   typedef IsFuture<R> ReturnsFuture;
89   typedef Future<typename ReturnsFuture::Inner> Return;
90   typedef typename ReturnsFuture::Inner RawReturn;
91   typedef typename ArgType<Args...>::FirstArg FirstArg;
92 };
93
94 } // detail
95
96 struct Timekeeper;
97
98 template <typename T> struct isFuture;
99
100 /// This namespace is for utility functions that would usually be static
101 /// members of Future, except they don't make sense there because they don't
102 /// depend on the template type (rather, on the type of their arguments in
103 /// some cases). This is the least-bad naming scheme we could think of. Some
104 /// of the functions herein have really-likely-to-collide names, like "map"
105 /// and "sleep".
106 namespace futures {
107   /// Returns a Future that will complete after the specified duration. The
108   /// Duration typedef of a `std::chrono` duration type indicates the
109   /// resolution you can expect to be meaningful (milliseconds at the time of
110   /// writing). Normally you wouldn't need to specify a Timekeeper, we will
111   /// use the global futures timekeeper (we run a thread whose job it is to
112   /// keep time for futures timeouts) but we provide the option for power
113   /// users.
114   ///
115   /// The Timekeeper thread will be lazily created the first time it is
116   /// needed. If your program never uses any timeouts or other time-based
117   /// Futures you will pay no Timekeeper thread overhead.
118   Future<void> sleep(Duration, Timekeeper* = nullptr);
119 }
120
121 template <class T>
122 class Future {
123  public:
124   typedef T value_type;
125
126   // not copyable
127   Future(Future const&) = delete;
128   Future& operator=(Future const&) = delete;
129
130   // movable
131   Future(Future&&) noexcept;
132   Future& operator=(Future&&);
133
134   ~Future();
135
136   /** Return the reference to result. Should not be called if !isReady().
137     Will rethrow the exception if an exception has been
138     captured.
139
140     This function is not thread safe - the returned Future can only
141     be executed from the thread that the executor runs it in.
142     See below for a thread safe version
143     */
144   typename std::add_lvalue_reference<T>::type
145   value();
146   typename std::add_lvalue_reference<const T>::type
147   value() const;
148
149   /// Returns an inactive Future which will call back on the other side of
150   /// executor (when it is activated).
151   ///
152   /// NB remember that Futures activate when they destruct. This is good,
153   /// it means that this will work:
154   ///
155   ///   f.via(e).then(a).then(b);
156   ///
157   /// a and b will execute in the same context (the far side of e), because
158   /// the Future (temporary variable) created by via(e) does not call back
159   /// until it destructs, which is after then(a) and then(b) have been wired
160   /// up.
161   ///
162   /// But this is still racy:
163   ///
164   ///   f = f.via(e).then(a);
165   ///   f.then(b);
166   // The ref-qualifier allows for `this` to be moved out so we
167   // don't get access-after-free situations in chaining.
168   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
169   template <typename Executor>
170   Future<T> via(Executor* executor) &&;
171
172   /// This variant creates a new future, where the ref-qualifier && version
173   /// moves `this` out. This one is less efficient but avoids confusing users
174   /// when "return f.via(x);" fails.
175   template <typename Executor>
176   Future<T> via(Executor* executor) &;
177
178   /** True when the result (or exception) is ready. */
179   bool isReady() const;
180
181   /** A reference to the Try of the value */
182   Try<T>& getTry();
183
184   /// Block until the future is fulfilled. Returns the value (moved out), or
185   /// throws the exception. The future must not already have a callback.
186   T get();
187
188   /// Block until the future is fulfilled, or until timed out. Returns the
189   /// value (moved out), or throws the exception (which might be a TimedOut
190   /// exception).
191   T get(Duration dur);
192
193   /// Call e->drive() repeatedly until the future is fulfilled. Examples
194   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
195   /// value (moved out), or throws the exception.
196   T getVia(DrivableExecutor* e);
197
198   /** When this Future has completed, execute func which is a function that
199     takes a Try<T>&&. A Future for the return type of func is
200     returned. e.g.
201
202     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
203
204     The Future given to the functor is ready, and the functor may call
205     value(), which may rethrow if this has captured an exception. If func
206     throws, the exception will be captured in the Future that is returned.
207     */
208   /* TODO n3428 and other async frameworks have something like then(scheduler,
209      Future), we might want to support a similar API which could be
210      implemented a little more efficiently than
211      f.via(executor).then(callback) */
212   template <class F>
213   typename std::enable_if<
214     !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
215     Future<typename std::result_of<F(Try<T>&&)>::type> >::type
216   then(F&& func);
217
218   /// Variant where func takes a T directly, bypassing a try. Any exceptions
219   /// will be implicitly passed on to the resultant Future.
220   ///
221   ///   Future<int> f = makeFuture<int>(42).then([](int i) { return i+1; });
222   template <class F>
223   typename std::enable_if<
224     !std::is_same<T, void>::value &&
225     !isFuture<typename std::result_of<
226       F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
227     Future<typename std::result_of<
228       F(typename detail::AliasIfVoid<T>::type&&)>::type> >::type
229   then(F&& func);
230
231   /// Like the above variant, but for void futures. That is, func takes no
232   /// argument.
233   ///
234   ///   Future<int> f = makeFuture().then([] { return 42; });
235   template <class F>
236   typename std::enable_if<
237     std::is_same<T, void>::value &&
238     !isFuture<typename std::result_of<F()>::type>::value,
239     Future<typename std::result_of<F()>::type> >::type
240   then(F&& func);
241
242   /// Variant where func returns a Future<T> instead of a T. e.g.
243   ///
244   ///   Future<string> f2 = f1.then(
245   ///     [](Try<T>&&) { return makeFuture<string>("foo"); });
246   template <class F>
247   typename std::enable_if<
248     isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
249     Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
250   then(F&& func);
251
252   /// Variant where func returns a Future<T2> and takes a T directly, bypassing
253   /// a Try. Any exceptions will be implicitly passed on to the resultant
254   /// Future. For example,
255   ///
256   ///   Future<int> f = makeFuture<int>(42).then(
257   ///     [](int i) { return makeFuture<int>(i+1); });
258   template <class F>
259   typename std::enable_if<
260     !std::is_same<T, void>::value &&
261     isFuture<typename std::result_of<
262       F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
263     Future<typename std::result_of<
264       F(typename detail::AliasIfVoid<T>::type&&)>::type::value_type> >::type
265   then(F&& func);
266
267   /// Like the above variant, but for void futures. That is, func takes no
268   /// argument and returns a future.
269   ///
270   ///   Future<int> f = makeFuture().then(
271   ///     [] { return makeFuture<int>(42); });
272   template <class F>
273   typename std::enable_if<
274     std::is_same<T, void>::value &&
275     isFuture<typename std::result_of<F()>::type>::value,
276     Future<typename std::result_of<F()>::type::value_type> >::type
277   then(F&& func);
278
279   /// Variant where func is an ordinary function (static method, method)
280   ///
281   ///   R doWork(Try<T>&&);
282   ///
283   ///   Future<R> f2 = f1.then(doWork);
284   ///
285   /// or
286   ///
287   ///   struct Worker {
288   ///     static R doWork(Try<T>&&); }
289   ///
290   ///   Future<R> f2 = f1.then(&Worker::doWork);
291   template <class = T, class R = std::nullptr_t>
292   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
293   inline then(R(*func)(Try<T>&&)) {
294     return then([func](Try<T>&& t) {
295       return (*func)(std::move(t));
296     });
297   }
298
299   /// Variant where func returns a Future<R> instead of a R. e.g.
300   ///
301   ///   struct Worker {
302   ///     Future<R> doWork(Try<T>&&); }
303   ///
304   ///   Future<R> f2 = f1.then(&Worker::doWork);
305   template <class = T, class R = std::nullptr_t>
306   typename std::enable_if<isFuture<R>::value, R>::type
307   inline then(R(*func)(Try<T>&&)) {
308     return then([func](Try<T>&& t) {
309       return (*func)(std::move(t));
310     });
311   }
312
313   /// Variant where func is an member function
314   ///
315   ///   struct Worker {
316   ///     R doWork(Try<T>&&); }
317   ///
318   ///   Worker *w;
319   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
320   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
321   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
322   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
323     return then([instance, func](Try<T>&& t) {
324       return (instance->*func)(std::move(t));
325     });
326   }
327
328   // Same as above, but func takes void instead of Try<void>&&
329   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
330   typename std::enable_if<
331       std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
332   inline then(Caller *instance, R(Caller::*func)()) {
333     return then([instance, func]() {
334       return (instance->*func)();
335     });
336   }
337
338   // Same as above, but func takes T&& instead of Try<T>&&
339   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
340   typename std::enable_if<
341       !std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
342   inline then(
343       Caller *instance,
344       R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
345     return then([instance, func](T&& t) {
346       return (instance->*func)(std::move(t));
347     });
348   }
349
350   /// Variant where func returns a Future<R> instead of a R. e.g.
351   ///
352   ///   struct Worker {
353   ///     Future<R> doWork(Try<T>&&); }
354   ///
355   ///   Worker *w;
356   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
357   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
358   typename std::enable_if<isFuture<R>::value, R>::type
359   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
360     return then([instance, func](Try<T>&& t) {
361       return (instance->*func)(std::move(t));
362     });
363   }
364
365   // Same as above, but func takes void instead of Try<void>&&
366   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
367   typename std::enable_if<
368       std::is_same<T, void>::value && isFuture<R>::value, R>::type
369   inline then(Caller *instance, R(Caller::*func)()) {
370     return then([instance, func]() {
371       return (instance->*func)();
372     });
373   }
374
375   // Same as above, but func takes T&& instead of Try<T>&&
376   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
377   typename std::enable_if<
378       !std::is_same<T, void>::value && isFuture<R>::value, R>::type
379   inline then(
380       Caller *instance,
381       R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
382     return then([instance, func](T&& t) {
383       return (instance->*func)(std::move(t));
384     });
385   }
386
387   /// Convenience method for ignoring the value and creating a Future<void>.
388   /// Exceptions still propagate.
389   Future<void> then();
390
391   /// Set an error callback for this Future. The callback should take a single
392   /// argument of the type that you want to catch, and should return a value of
393   /// the same type as this Future, or a Future of that type (see overload
394   /// below). For instance,
395   ///
396   /// makeFuture()
397   ///   .then([] {
398   ///     throw std::runtime_error("oh no!");
399   ///     return 42;
400   ///   })
401   ///   .onError([] (std::runtime_error& e) {
402   ///     LOG(INFO) << "std::runtime_error: " << e.what();
403   ///     return -1; // or makeFuture<int>(-1)
404   ///   });
405   template <class F>
406   typename std::enable_if<
407     !detail::Extract<F>::ReturnsFuture::value,
408     Future<T>>::type
409   onError(F&& func);
410
411   /// Overload of onError where the error callback returns a Future<T>
412   template <class F>
413   typename std::enable_if<
414     detail::Extract<F>::ReturnsFuture::value,
415     Future<T>>::type
416   onError(F&& func);
417
418   /// This is not the method you're looking for.
419   ///
420   /// This needs to be public because it's used by make* and when*, and it's
421   /// not worth listing all those and their fancy template signatures as
422   /// friends. But it's not for public consumption.
423   template <class F>
424   void setCallback_(F&& func);
425
426   /// A Future's callback is executed when all three of these conditions have
427   /// become true: it has a value (set by the Promise), it has a callback (set
428   /// by then), and it is active (active by default).
429   ///
430   /// Inactive Futures will activate upon destruction.
431   Future<T>& activate() & {
432     core_->activate();
433     return *this;
434   }
435   Future<T>& deactivate() & {
436     core_->deactivate();
437     return *this;
438   }
439   Future<T> activate() && {
440     core_->activate();
441     return std::move(*this);
442   }
443   Future<T> deactivate() && {
444     core_->deactivate();
445     return std::move(*this);
446   }
447
448   bool isActive() {
449     return core_->isActive();
450   }
451
452   template <class E>
453   void raise(E&& exception) {
454     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
455         std::move(exception)));
456   }
457
458   /// Raise an interrupt. If the promise holder has an interrupt
459   /// handler it will be called and potentially stop asynchronous work from
460   /// being done. This is advisory only - a promise holder may not set an
461   /// interrupt handler, or may do anything including ignore. But, if you know
462   /// your future supports this the most likely result is stopping or
463   /// preventing the asynchronous operation (if in time), and the promise
464   /// holder setting an exception on the future. (That may happen
465   /// asynchronously, of course.)
466   void raise(exception_wrapper interrupt);
467
468   void cancel() {
469     raise(FutureCancellation());
470   }
471
472   /// Throw TimedOut if this Future does not complete within the given
473   /// duration from now. The optional Timeekeeper is as with futures::sleep().
474   Future<T> within(Duration, Timekeeper* = nullptr);
475
476   /// Throw the given exception if this Future does not complete within the
477   /// given duration from now. The optional Timeekeeper is as with
478   /// futures::sleep().
479   template <class E>
480   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
481
482   /// Delay the completion of this Future for at least this duration from
483   /// now. The optional Timekeeper is as with futures::sleep().
484   Future<T> delayed(Duration, Timekeeper* = nullptr);
485
486   /// Block until this Future is complete. Returns a new Future containing the
487   /// result.
488   Future<T> wait();
489
490   /// Block until this Future is complete or until the given Duration passes.
491   /// Returns a new Future which either contains the result or is incomplete,
492   /// depending on whether the Duration passed.
493   Future<T> wait(Duration);
494
495   /// Call e->drive() repeatedly until the future is fulfilled. Examples
496   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
497   /// reference to this Future so that you can chain calls if desired.
498   /// value (moved out), or throws the exception.
499   Future<T>& waitVia(DrivableExecutor* e) &;
500
501   /// Overload of waitVia() for rvalue Futures
502   Future<T> waitVia(DrivableExecutor* e) &&;
503
504  private:
505   typedef detail::Core<T>* corePtr;
506
507   // shared core state object
508   corePtr core_;
509
510   explicit
511   Future(corePtr obj) : core_(obj) {}
512
513   void detach();
514
515   void throwIfInvalid() const;
516
517   friend class Promise<T>;
518 };
519
520 /**
521   Make a completed Future by moving in a value. e.g.
522
523     string foo = "foo";
524     auto f = makeFuture(std::move(foo));
525
526   or
527
528     auto f = makeFuture<string>("foo");
529 */
530 template <class T>
531 Future<typename std::decay<T>::type> makeFuture(T&& t);
532
533 /** Make a completed void Future. */
534 Future<void> makeFuture();
535
536 /** Make a completed Future by executing a function. If the function throws
537   we capture the exception, otherwise we capture the result. */
538 template <class F>
539 auto makeFutureTry(
540   F&& func,
541   typename std::enable_if<
542     !std::is_reference<F>::value, bool>::type sdf = false)
543   -> Future<decltype(func())>;
544
545 template <class F>
546 auto makeFutureTry(
547   F const& func)
548   -> Future<decltype(func())>;
549
550 /// Make a failed Future from an exception_ptr.
551 /// Because the Future's type cannot be inferred you have to specify it, e.g.
552 ///
553 ///   auto f = makeFuture<string>(std::current_exception());
554 template <class T>
555 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
556
557 /// Make a failed Future from an exception_wrapper.
558 template <class T>
559 Future<T> makeFuture(exception_wrapper ew);
560
561 /** Make a Future from an exception type E that can be passed to
562   std::make_exception_ptr(). */
563 template <class T, class E>
564 typename std::enable_if<std::is_base_of<std::exception, E>::value,
565                         Future<T>>::type
566 makeFuture(E const& e);
567
568 /** Make a Future out of a Try */
569 template <class T>
570 Future<T> makeFuture(Try<T>&& t);
571
572 /*
573  * Return a new Future that will call back on the given Executor.
574  * This is just syntactic sugar for makeFuture().via(executor)
575  *
576  * @param executor the Executor to call back on
577  *
578  * @returns a void Future that will call back on the given executor
579  */
580 template <typename Executor>
581 Future<void> via(Executor* executor);
582
583 /** When all the input Futures complete, the returned Future will complete.
584   Errors do not cause early termination; this Future will always succeed
585   after all its Futures have finished (whether successfully or with an
586   error).
587
588   The Futures are moved in, so your copies are invalid. If you need to
589   chain further from these Futures, use the variant with an output iterator.
590
591   XXX is this still true?
592   This function is thread-safe for Futures running on different threads.
593
594   The return type for Future<T> input is a Future<std::vector<Try<T>>>
595   */
596 template <class InputIterator>
597 Future<std::vector<Try<
598   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
599 whenAll(InputIterator first, InputIterator last);
600
601 /// This version takes a varying number of Futures instead of an iterator.
602 /// The return type for (Future<T1>, Future<T2>, ...) input
603 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
604 /// The Futures are moved in, so your copies are invalid.
605 template <typename... Fs>
606 typename detail::VariadicContext<
607   typename std::decay<Fs>::type::value_type...>::type
608 whenAll(Fs&&... fs);
609
610 /** The result is a pair of the index of the first Future to complete and
611   the Try. If multiple Futures complete at the same time (or are already
612   complete when passed in), the "winner" is chosen non-deterministically.
613
614   This function is thread-safe for Futures running on different threads.
615   */
616 template <class InputIterator>
617 Future<std::pair<
618   size_t,
619   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
620 whenAny(InputIterator first, InputIterator last);
621
622 /** when n Futures have completed, the Future completes with a vector of
623   the index and Try of those n Futures (the indices refer to the original
624   order, but the result vector will be in an arbitrary order)
625
626   Not thread safe.
627   */
628 template <class InputIterator>
629 Future<std::vector<std::pair<
630   size_t,
631   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
632 whenN(InputIterator first, InputIterator last, size_t n);
633
634 } // folly
635
636 #include <folly/futures/Future-inl.h>