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