(Wangle) Clean up move constructors
[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, Try<T>&&>::value,
103       detail::argResult<true, F, Try<T>&&>,
104       typename std::conditional<
105         callableWith<F, Try<T>&>::value,
106         detail::argResult<true, F, Try<T>&>,
107         typename std::conditional<
108           callableWith<F, T&&>::value,
109           detail::argResult<false, F, T&&>,
110           detail::argResult<false, F, 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  protected:
478   typedef detail::Core<T>* corePtr;
479
480   // shared core state object
481   corePtr core_;
482
483   explicit
484   Future(corePtr obj) : core_(obj) {}
485
486   void detach();
487
488   void throwIfInvalid() const;
489
490   friend class Promise<T>;
491   template <class> friend class Future;
492
493   // Variant: returns a value
494   // e.g. f.then([](Try<T> t){ return t.value(); });
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   // Variant: returns a Future
500   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
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   Executor* getExecutor() { return core_->getExecutor(); }
506   void setExecutor(Executor* x) { core_->setExecutor(x); }
507 };
508
509 /**
510   Make a completed Future by moving in a value. e.g.
511
512     string foo = "foo";
513     auto f = makeFuture(std::move(foo));
514
515   or
516
517     auto f = makeFuture<string>("foo");
518 */
519 template <class T>
520 Future<typename std::decay<T>::type> makeFuture(T&& t);
521
522 /** Make a completed void Future. */
523 Future<void> makeFuture();
524
525 /** Make a completed Future by executing a function. If the function throws
526   we capture the exception, otherwise we capture the result. */
527 template <class F>
528 auto makeFutureTry(
529   F&& func,
530   typename std::enable_if<
531     !std::is_reference<F>::value, bool>::type sdf = false)
532   -> Future<decltype(func())>;
533
534 template <class F>
535 auto makeFutureTry(
536   F const& func)
537   -> Future<decltype(func())>;
538
539 /// Make a failed Future from an exception_ptr.
540 /// Because the Future's type cannot be inferred you have to specify it, e.g.
541 ///
542 ///   auto f = makeFuture<string>(std::current_exception());
543 template <class T>
544 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
545
546 /// Make a failed Future from an exception_wrapper.
547 template <class T>
548 Future<T> makeFuture(exception_wrapper ew);
549
550 /** Make a Future from an exception type E that can be passed to
551   std::make_exception_ptr(). */
552 template <class T, class E>
553 typename std::enable_if<std::is_base_of<std::exception, E>::value,
554                         Future<T>>::type
555 makeFuture(E const& e);
556
557 /** Make a Future out of a Try */
558 template <class T>
559 Future<T> makeFuture(Try<T>&& t);
560
561 /*
562  * Return a new Future that will call back on the given Executor.
563  * This is just syntactic sugar for makeFuture().via(executor)
564  *
565  * @param executor the Executor to call back on
566  *
567  * @returns a void Future that will call back on the given executor
568  */
569 template <typename Executor>
570 Future<void> via(Executor* executor);
571
572 /** When all the input Futures complete, the returned Future will complete.
573   Errors do not cause early termination; this Future will always succeed
574   after all its Futures have finished (whether successfully or with an
575   error).
576
577   The Futures are moved in, so your copies are invalid. If you need to
578   chain further from these Futures, use the variant with an output iterator.
579
580   This function is thread-safe for Futures running on different threads. But
581   if you are doing anything non-trivial after, you will probably want to
582   follow with `via(executor)` because it will complete in whichever thread the
583   last Future completes in.
584
585   The return type for Future<T> input is a Future<std::vector<Try<T>>>
586   */
587 template <class InputIterator>
588 Future<std::vector<Try<
589   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
590 whenAll(InputIterator first, InputIterator last);
591
592 /// This version takes a varying number of Futures instead of an iterator.
593 /// The return type for (Future<T1>, Future<T2>, ...) input
594 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
595 /// The Futures are moved in, so your copies are invalid.
596 template <typename... Fs>
597 typename detail::VariadicContext<
598   typename std::decay<Fs>::type::value_type...>::type
599 whenAll(Fs&&... fs);
600
601 /** The result is a pair of the index of the first Future to complete and
602   the Try. If multiple Futures complete at the same time (or are already
603   complete when passed in), the "winner" is chosen non-deterministically.
604
605   This function is thread-safe for Futures running on different threads.
606   */
607 template <class InputIterator>
608 Future<std::pair<
609   size_t,
610   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
611 whenAny(InputIterator first, InputIterator last);
612
613 /** when n Futures have completed, the Future completes with a vector of
614   the index and Try of those n Futures (the indices refer to the original
615   order, but the result vector will be in an arbitrary order)
616
617   Not thread safe.
618   */
619 template <class InputIterator>
620 Future<std::vector<std::pair<
621   size_t,
622   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
623 whenN(InputIterator first, InputIterator last, size_t n);
624
625 } // folly
626
627 #include <folly/futures/Future-inl.h>