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