(Wangle) Swap order of Try<T> and T matching
[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::Extract<F>::ReturnsFuture::value,
348     Future<T>>::type
349   onError(F&& func);
350
351   /// Overload of onError where the error callback returns a Future<T>
352   template <class F>
353   typename std::enable_if<
354     detail::Extract<F>::ReturnsFuture::value,
355     Future<T>>::type
356   onError(F&& func);
357
358   /// func is like std::function<void()> and is executed unconditionally, and
359   /// the value/exception is passed through to the resulting Future.
360   /// func shouldn't throw, but if it does it will be captured and propagated,
361   /// and discard any value/exception that this Future has obtained.
362   template <class F>
363   Future<T> ensure(F func);
364
365   /// Like onError, but for timeouts. example:
366   ///
367   ///   Future<int> f = makeFuture<int>(42)
368   ///     .delayed(long_time)
369   ///     .onTimeout(short_time,
370   ///       []() -> int{ return -1; });
371   ///
372   /// or perhaps
373   ///
374   ///   Future<int> f = makeFuture<int>(42)
375   ///     .delayed(long_time)
376   ///     .onTimeout(short_time,
377   ///       []() { return makeFuture<int>(some_exception); });
378   template <class F>
379   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
380
381   /// This is not the method you're looking for.
382   ///
383   /// This needs to be public because it's used by make* and when*, and it's
384   /// not worth listing all those and their fancy template signatures as
385   /// friends. But it's not for public consumption.
386   template <class F>
387   void setCallback_(F&& func);
388
389   /// A Future's callback is executed when all three of these conditions have
390   /// become true: it has a value (set by the Promise), it has a callback (set
391   /// by then), and it is active (active by default).
392   ///
393   /// Inactive Futures will activate upon destruction.
394   Future<T>& activate() & {
395     core_->activate();
396     return *this;
397   }
398   Future<T>& deactivate() & {
399     core_->deactivate();
400     return *this;
401   }
402   Future<T> activate() && {
403     core_->activate();
404     return std::move(*this);
405   }
406   Future<T> deactivate() && {
407     core_->deactivate();
408     return std::move(*this);
409   }
410
411   bool isActive() {
412     return core_->isActive();
413   }
414
415   template <class E>
416   void raise(E&& exception) {
417     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
418         std::move(exception)));
419   }
420
421   /// Raise an interrupt. If the promise holder has an interrupt
422   /// handler it will be called and potentially stop asynchronous work from
423   /// being done. This is advisory only - a promise holder may not set an
424   /// interrupt handler, or may do anything including ignore. But, if you know
425   /// your future supports this the most likely result is stopping or
426   /// preventing the asynchronous operation (if in time), and the promise
427   /// holder setting an exception on the future. (That may happen
428   /// asynchronously, of course.)
429   void raise(exception_wrapper interrupt);
430
431   void cancel() {
432     raise(FutureCancellation());
433   }
434
435   /// Throw TimedOut if this Future does not complete within the given
436   /// duration from now. The optional Timeekeeper is as with futures::sleep().
437   Future<T> within(Duration, Timekeeper* = nullptr);
438
439   /// Throw the given exception if this Future does not complete within the
440   /// given duration from now. The optional Timeekeeper is as with
441   /// futures::sleep().
442   template <class E>
443   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
444
445   /// Delay the completion of this Future for at least this duration from
446   /// now. The optional Timekeeper is as with futures::sleep().
447   Future<T> delayed(Duration, Timekeeper* = nullptr);
448
449   /// Block until this Future is complete. Returns a reference to this Future.
450   Future<T>& wait() &;
451
452   /// Overload of wait() for rvalue Futures
453   Future<T>&& wait() &&;
454
455   /// Block until this Future is complete or until the given Duration passes.
456   /// Returns a reference to this Future
457   Future<T>& wait(Duration) &;
458
459   /// Overload of wait(Duration) for rvalue Futures
460   Future<T>&& wait(Duration) &&;
461
462   /// Call e->drive() repeatedly until the future is fulfilled. Examples
463   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
464   /// reference to this Future so that you can chain calls if desired.
465   /// value (moved out), or throws the exception.
466   Future<T>& waitVia(DrivableExecutor* e) &;
467
468   /// Overload of waitVia() for rvalue Futures
469   Future<T>&& waitVia(DrivableExecutor* e) &&;
470
471   /// If the value in this Future is equal to the given Future, when they have
472   /// both completed, the value of the resulting Future<bool> will be true. It
473   /// will be false otherwise (including when one or both Futures have an
474   /// exception)
475   Future<bool> willEqual(Future<T>&);
476
477   /// predicate behaves like std::function<bool(T const&)>
478   /// If the predicate does not obtain with the value, the result
479   /// is a folly::PredicateDoesNotObtain exception
480   template <class F>
481   Future<T> filter(F predicate);
482
483  protected:
484   typedef detail::Core<T>* corePtr;
485
486   // shared core state object
487   corePtr core_;
488
489   explicit
490   Future(corePtr obj) : core_(obj) {}
491
492   void detach();
493
494   void throwIfInvalid() const;
495
496   friend class Promise<T>;
497   template <class> friend class Future;
498
499   // Variant: returns a value
500   // e.g. f.then([](Try<T> t){ return t.value(); });
501   template <typename F, typename R, bool isTry, typename... Args>
502   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
503   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
504
505   // Variant: returns a Future
506   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
507   template <typename F, typename R, bool isTry, typename... Args>
508   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
509   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
510
511   Executor* getExecutor() { return core_->getExecutor(); }
512   void setExecutor(Executor* x) { core_->setExecutor(x); }
513 };
514
515 /**
516   Make a completed Future by moving in a value. e.g.
517
518     string foo = "foo";
519     auto f = makeFuture(std::move(foo));
520
521   or
522
523     auto f = makeFuture<string>("foo");
524 */
525 template <class T>
526 Future<typename std::decay<T>::type> makeFuture(T&& t);
527
528 /** Make a completed void Future. */
529 Future<void> makeFuture();
530
531 /** Make a completed Future by executing a function. If the function throws
532   we capture the exception, otherwise we capture the result. */
533 template <class F>
534 auto makeFutureTry(
535   F&& func,
536   typename std::enable_if<
537     !std::is_reference<F>::value, bool>::type sdf = false)
538   -> Future<decltype(func())>;
539
540 template <class F>
541 auto makeFutureTry(
542   F const& func)
543   -> Future<decltype(func())>;
544
545 /// Make a failed Future from an exception_ptr.
546 /// Because the Future's type cannot be inferred you have to specify it, e.g.
547 ///
548 ///   auto f = makeFuture<string>(std::current_exception());
549 template <class T>
550 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
551
552 /// Make a failed Future from an exception_wrapper.
553 template <class T>
554 Future<T> makeFuture(exception_wrapper ew);
555
556 /** Make a Future from an exception type E that can be passed to
557   std::make_exception_ptr(). */
558 template <class T, class E>
559 typename std::enable_if<std::is_base_of<std::exception, E>::value,
560                         Future<T>>::type
561 makeFuture(E const& e);
562
563 /** Make a Future out of a Try */
564 template <class T>
565 Future<T> makeFuture(Try<T>&& t);
566
567 /*
568  * Return a new Future that will call back on the given Executor.
569  * This is just syntactic sugar for makeFuture().via(executor)
570  *
571  * @param executor the Executor to call back on
572  *
573  * @returns a void Future that will call back on the given executor
574  */
575 template <typename Executor>
576 Future<void> via(Executor* executor);
577
578 /** When all the input Futures complete, the returned Future will complete.
579   Errors do not cause early termination; this Future will always succeed
580   after all its Futures have finished (whether successfully or with an
581   error).
582
583   The Futures are moved in, so your copies are invalid. If you need to
584   chain further from these Futures, use the variant with an output iterator.
585
586   This function is thread-safe for Futures running on different threads. But
587   if you are doing anything non-trivial after, you will probably want to
588   follow with `via(executor)` because it will complete in whichever thread the
589   last Future completes in.
590
591   The return type for Future<T> input is a Future<std::vector<Try<T>>>
592   */
593 template <class InputIterator>
594 Future<std::vector<Try<
595   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
596 whenAll(InputIterator first, InputIterator last);
597
598 /// This version takes a varying number of Futures instead of an iterator.
599 /// The return type for (Future<T1>, Future<T2>, ...) input
600 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
601 /// The Futures are moved in, so your copies are invalid.
602 template <typename... Fs>
603 typename detail::VariadicContext<
604   typename std::decay<Fs>::type::value_type...>::type
605 whenAll(Fs&&... fs);
606
607 /** The result is a pair of the index of the first Future to complete and
608   the Try. If multiple Futures complete at the same time (or are already
609   complete when passed in), the "winner" is chosen non-deterministically.
610
611   This function is thread-safe for Futures running on different threads.
612   */
613 template <class InputIterator>
614 Future<std::pair<
615   size_t,
616   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
617 whenAny(InputIterator first, InputIterator last);
618
619 /** when n Futures have completed, the Future completes with a vector of
620   the index and Try of those n Futures (the indices refer to the original
621   order, but the result vector will be in an arbitrary order)
622
623   Not thread safe.
624   */
625 template <class InputIterator>
626 Future<std::vector<std::pair<
627   size_t,
628   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
629 whenN(InputIterator first, InputIterator last, size_t n);
630
631 template <typename F, typename T, typename ItT>
632 using MaybeTryArg = typename std::conditional<
633   detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
634
635 template<typename F, typename T, typename Arg>
636 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
637
638 /** repeatedly calls func on every result, e.g.
639     reduce(reduce(reduce(T initial, result of first), result of second), ...)
640
641     The type of the final result is a Future of the type of the initial value.
642
643     Func can either return a T, or a Future<T>
644   */
645 template <class It, class T, class F,
646           class ItT = typename std::iterator_traits<It>::value_type::value_type,
647           class Arg = MaybeTryArg<F, T, ItT>>
648 typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
649 reduce(It first, It last, T initial, F func);
650
651 template <class It, class T, class F,
652           class ItT = typename std::iterator_traits<It>::value_type::value_type,
653           class Arg = MaybeTryArg<F, T, ItT>>
654 typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
655 reduce(It first, It last, T initial, F func);
656
657 } // folly
658
659 #include <folly/futures/Future-inl.h>