2b81407f55c50a6dc347907fd9b1d11660060a65
[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/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   /// Create a Future chain from a sequence of callbacks. i.e.
171   ///
172   ///   f.then(a).then(b).then(c);
173   ///
174   /// where f is a Future<A> and the result of the chain is a Future<Z>
175   /// becomes
176   ///
177   ///   f.then(chain<A,Z>(a, b, c));
178   // If anyone figures how to get chain to deduce A and Z, I'll buy you a drink.
179   template <class A, class Z, class... Callbacks>
180   std::function<Future<Z>(Try<A>)>
181   chain(Callbacks... fns);
182 }
183
184 template <class T>
185 class Future {
186  public:
187   typedef T value_type;
188
189   // not copyable
190   Future(Future const&) = delete;
191   Future& operator=(Future const&) = delete;
192
193   // movable
194   Future(Future&&) noexcept;
195   Future& operator=(Future&&);
196
197   // makeFuture
198   template <class F = T>
199   /* implicit */
200   Future(const typename std::enable_if<!std::is_void<F>::value, F>::type& val);
201
202   template <class F = T>
203   /* implicit */
204   Future(typename std::enable_if<!std::is_void<F>::value, F>::type&& val);
205
206   template <class F = T,
207             typename std::enable_if<std::is_void<F>::value, int>::type = 0>
208   Future();
209
210   ~Future();
211
212   /** Return the reference to result. Should not be called if !isReady().
213     Will rethrow the exception if an exception has been
214     captured.
215     */
216   typename std::add_lvalue_reference<T>::type
217   value();
218   typename std::add_lvalue_reference<const T>::type
219   value() const;
220
221   /// Returns an inactive Future which will call back on the other side of
222   /// executor (when it is activated).
223   ///
224   /// NB remember that Futures activate when they destruct. This is good,
225   /// it means that this will work:
226   ///
227   ///   f.via(e).then(a).then(b);
228   ///
229   /// a and b will execute in the same context (the far side of e), because
230   /// the Future (temporary variable) created by via(e) does not call back
231   /// until it destructs, which is after then(a) and then(b) have been wired
232   /// up.
233   ///
234   /// But this is still racy:
235   ///
236   ///   f = f.via(e).then(a);
237   ///   f.then(b);
238   // The ref-qualifier allows for `this` to be moved out so we
239   // don't get access-after-free situations in chaining.
240   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
241   template <typename Executor>
242   Future<T> via(Executor* executor) &&;
243
244   /// This variant creates a new future, where the ref-qualifier && version
245   /// moves `this` out. This one is less efficient but avoids confusing users
246   /// when "return f.via(x);" fails.
247   template <typename Executor>
248   Future<T> via(Executor* executor) &;
249
250   /** True when the result (or exception) is ready. */
251   bool isReady() const;
252
253   /** A reference to the Try of the value */
254   Try<T>& getTry();
255
256   /// Block until the future is fulfilled. Returns the value (moved out), or
257   /// throws the exception. The future must not already have a callback.
258   T get();
259
260   /// Block until the future is fulfilled, or until timed out. Returns the
261   /// value (moved out), or throws the exception (which might be a TimedOut
262   /// exception).
263   T get(Duration dur);
264
265   /// Call e->drive() repeatedly until the future is fulfilled. Examples
266   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
267   /// value (moved out), or throws the exception.
268   T getVia(DrivableExecutor* e);
269
270   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
271   /// Future<T> instance.
272   template <class F = T>
273   typename std::enable_if<isFuture<F>::value,
274                           Future<typename isFuture<T>::Inner>>::type
275   unwrap();
276
277   /** When this Future has completed, execute func which is a function that
278     takes one of:
279       (const) Try<T>&&
280       (const) Try<T>&
281       (const) Try<T>
282       (const) T&&
283       (const) T&
284       (const) T
285       (void)
286
287     Func shall return either another Future or a value.
288
289     A Future for the return type of func is returned.
290
291     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
292
293     The Future given to the functor is ready, and the functor may call
294     value(), which may rethrow if this has captured an exception. If func
295     throws, the exception will be captured in the Future that is returned.
296     */
297   /* TODO n3428 and other async frameworks have something like then(scheduler,
298      Future), we might want to support a similar API which could be
299      implemented a little more efficiently than
300      f.via(executor).then(callback) */
301   template <typename F, typename R = detail::callableResult<T, F>>
302   typename R::Return then(F func) {
303     typedef typename R::Arg Arguments;
304     return thenImplementation<F, R>(std::move(func), Arguments());
305   }
306
307   /// Variant where func is an member function
308   ///
309   ///   struct Worker { R doWork(Try<T>); }
310   ///
311   ///   Worker *w;
312   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
313   ///
314   /// This is just sugar for
315   ///
316   ///   f1.then(std::bind(&Worker::doWork, w));
317   template <typename R, typename Caller, typename... Args>
318   Future<typename isFuture<R>::Inner>
319   then(R(Caller::*func)(Args...), Caller *instance);
320
321   /// Convenience method for ignoring the value and creating a Future<void>.
322   /// Exceptions still propagate.
323   Future<void> then();
324
325   /// Set an error callback for this Future. The callback should take a single
326   /// argument of the type that you want to catch, and should return a value of
327   /// the same type as this Future, or a Future of that type (see overload
328   /// below). For instance,
329   ///
330   /// makeFuture()
331   ///   .then([] {
332   ///     throw std::runtime_error("oh no!");
333   ///     return 42;
334   ///   })
335   ///   .onError([] (std::runtime_error& e) {
336   ///     LOG(INFO) << "std::runtime_error: " << e.what();
337   ///     return -1; // or makeFuture<int>(-1)
338   ///   });
339   template <class F>
340   typename std::enable_if<
341     !detail::Extract<F>::ReturnsFuture::value,
342     Future<T>>::type
343   onError(F&& func);
344
345   /// Overload of onError where the error callback returns a Future<T>
346   template <class F>
347   typename std::enable_if<
348     detail::Extract<F>::ReturnsFuture::value,
349     Future<T>>::type
350   onError(F&& func);
351
352   /// func is like std::function<void()> and is executed unconditionally, and
353   /// the value/exception is passed through to the resulting Future.
354   /// func shouldn't throw, but if it does it will be captured and propagated,
355   /// and discard any value/exception that this Future has obtained.
356   template <class F>
357   Future<T> ensure(F func);
358
359   /// Like onError, but for timeouts. example:
360   ///
361   ///   Future<int> f = makeFuture<int>(42)
362   ///     .delayed(long_time)
363   ///     .onTimeout(short_time,
364   ///       []() -> int{ return -1; });
365   ///
366   /// or perhaps
367   ///
368   ///   Future<int> f = makeFuture<int>(42)
369   ///     .delayed(long_time)
370   ///     .onTimeout(short_time,
371   ///       []() { return makeFuture<int>(some_exception); });
372   template <class F>
373   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
374
375   /// This is not the method you're looking for.
376   ///
377   /// This needs to be public because it's used by make* and when*, and it's
378   /// not worth listing all those and their fancy template signatures as
379   /// friends. But it's not for public consumption.
380   template <class F>
381   void setCallback_(F&& func);
382
383   /// A Future's callback is executed when all three of these conditions have
384   /// become true: it has a value (set by the Promise), it has a callback (set
385   /// by then), and it is active (active by default).
386   ///
387   /// Inactive Futures will activate upon destruction.
388   Future<T>& activate() & {
389     core_->activate();
390     return *this;
391   }
392   Future<T>& deactivate() & {
393     core_->deactivate();
394     return *this;
395   }
396   Future<T> activate() && {
397     core_->activate();
398     return std::move(*this);
399   }
400   Future<T> deactivate() && {
401     core_->deactivate();
402     return std::move(*this);
403   }
404
405   bool isActive() {
406     return core_->isActive();
407   }
408
409   template <class E>
410   void raise(E&& exception) {
411     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
412         std::move(exception)));
413   }
414
415   /// Raise an interrupt. If the promise holder has an interrupt
416   /// handler it will be called and potentially stop asynchronous work from
417   /// being done. This is advisory only - a promise holder may not set an
418   /// interrupt handler, or may do anything including ignore. But, if you know
419   /// your future supports this the most likely result is stopping or
420   /// preventing the asynchronous operation (if in time), and the promise
421   /// holder setting an exception on the future. (That may happen
422   /// asynchronously, of course.)
423   void raise(exception_wrapper interrupt);
424
425   void cancel() {
426     raise(FutureCancellation());
427   }
428
429   /// Throw TimedOut if this Future does not complete within the given
430   /// duration from now. The optional Timeekeeper is as with futures::sleep().
431   Future<T> within(Duration, Timekeeper* = nullptr);
432
433   /// Throw the given exception if this Future does not complete within the
434   /// given duration from now. The optional Timeekeeper is as with
435   /// futures::sleep().
436   template <class E>
437   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
438
439   /// Delay the completion of this Future for at least this duration from
440   /// now. The optional Timekeeper is as with futures::sleep().
441   Future<T> delayed(Duration, Timekeeper* = nullptr);
442
443   /// Block until this Future is complete. Returns a reference to this Future.
444   Future<T>& wait() &;
445
446   /// Overload of wait() for rvalue Futures
447   Future<T>&& wait() &&;
448
449   /// Block until this Future is complete or until the given Duration passes.
450   /// Returns a reference to this Future
451   Future<T>& wait(Duration) &;
452
453   /// Overload of wait(Duration) for rvalue Futures
454   Future<T>&& wait(Duration) &&;
455
456   /// Call e->drive() repeatedly until the future is fulfilled. Examples
457   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
458   /// reference to this Future so that you can chain calls if desired.
459   /// value (moved out), or throws the exception.
460   Future<T>& waitVia(DrivableExecutor* e) &;
461
462   /// Overload of waitVia() for rvalue Futures
463   Future<T>&& waitVia(DrivableExecutor* e) &&;
464
465   /// If the value in this Future is equal to the given Future, when they have
466   /// both completed, the value of the resulting Future<bool> will be true. It
467   /// will be false otherwise (including when one or both Futures have an
468   /// exception)
469   Future<bool> willEqual(Future<T>&);
470
471  protected:
472   typedef detail::Core<T>* corePtr;
473
474   // shared core state object
475   corePtr core_;
476
477   explicit
478   Future(corePtr obj) : core_(obj) {}
479
480   void detach();
481
482   void throwIfInvalid() const;
483
484   friend class Promise<T>;
485   template <class> friend class Future;
486
487   // Variant: returns a value
488   // e.g. f.then([](Try<T> t){ return t.value(); });
489   template <typename F, typename R, bool isTry, typename... Args>
490   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
491   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
492
493   // Variant: returns a Future
494   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
495   template <typename F, typename R, bool isTry, typename... Args>
496   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
497   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
498
499   Executor* getExecutor() { return core_->getExecutor(); }
500   void setExecutor(Executor* x) { core_->setExecutor(x); }
501 };
502
503 /**
504   Make a completed Future by moving in a value. e.g.
505
506     string foo = "foo";
507     auto f = makeFuture(std::move(foo));
508
509   or
510
511     auto f = makeFuture<string>("foo");
512 */
513 template <class T>
514 Future<typename std::decay<T>::type> makeFuture(T&& t);
515
516 /** Make a completed void Future. */
517 Future<void> makeFuture();
518
519 /** Make a completed Future by executing a function. If the function throws
520   we capture the exception, otherwise we capture the result. */
521 template <class F>
522 auto makeFutureTry(
523   F&& func,
524   typename std::enable_if<
525     !std::is_reference<F>::value, bool>::type sdf = false)
526   -> Future<decltype(func())>;
527
528 template <class F>
529 auto makeFutureTry(
530   F const& func)
531   -> Future<decltype(func())>;
532
533 /// Make a failed Future from an exception_ptr.
534 /// Because the Future's type cannot be inferred you have to specify it, e.g.
535 ///
536 ///   auto f = makeFuture<string>(std::current_exception());
537 template <class T>
538 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
539
540 /// Make a failed Future from an exception_wrapper.
541 template <class T>
542 Future<T> makeFuture(exception_wrapper ew);
543
544 /** Make a Future from an exception type E that can be passed to
545   std::make_exception_ptr(). */
546 template <class T, class E>
547 typename std::enable_if<std::is_base_of<std::exception, E>::value,
548                         Future<T>>::type
549 makeFuture(E const& e);
550
551 /** Make a Future out of a Try */
552 template <class T>
553 Future<T> makeFuture(Try<T>&& t);
554
555 /*
556  * Return a new Future that will call back on the given Executor.
557  * This is just syntactic sugar for makeFuture().via(executor)
558  *
559  * @param executor the Executor to call back on
560  *
561  * @returns a void Future that will call back on the given executor
562  */
563 template <typename Executor>
564 Future<void> via(Executor* executor);
565
566 /** When all the input Futures complete, the returned Future will complete.
567   Errors do not cause early termination; this Future will always succeed
568   after all its Futures have finished (whether successfully or with an
569   error).
570
571   The Futures are moved in, so your copies are invalid. If you need to
572   chain further from these Futures, use the variant with an output iterator.
573
574   This function is thread-safe for Futures running on different threads. But
575   if you are doing anything non-trivial after, you will probably want to
576   follow with `via(executor)` because it will complete in whichever thread the
577   last Future completes in.
578
579   The return type for Future<T> input is a Future<std::vector<Try<T>>>
580   */
581 template <class InputIterator>
582 Future<std::vector<Try<
583   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
584 whenAll(InputIterator first, InputIterator last);
585
586 /// This version takes a varying number of Futures instead of an iterator.
587 /// The return type for (Future<T1>, Future<T2>, ...) input
588 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
589 /// The Futures are moved in, so your copies are invalid.
590 template <typename... Fs>
591 typename detail::VariadicContext<
592   typename std::decay<Fs>::type::value_type...>::type
593 whenAll(Fs&&... fs);
594
595 /** The result is a pair of the index of the first Future to complete and
596   the Try. If multiple Futures complete at the same time (or are already
597   complete when passed in), the "winner" is chosen non-deterministically.
598
599   This function is thread-safe for Futures running on different threads.
600   */
601 template <class InputIterator>
602 Future<std::pair<
603   size_t,
604   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
605 whenAny(InputIterator first, InputIterator last);
606
607 /** when n Futures have completed, the Future completes with a vector of
608   the index and Try of those n Futures (the indices refer to the original
609   order, but the result vector will be in an arbitrary order)
610
611   Not thread safe.
612   */
613 template <class InputIterator>
614 Future<std::vector<std::pair<
615   size_t,
616   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
617 whenN(InputIterator first, InputIterator last, size_t n);
618
619 } // folly
620
621 #include <folly/futures/Future-inl.h>