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