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