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