2017
[folly.git] / folly / futures / Future.h
1 /*
2  * Copyright 2017 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/Portability.h>
28 #include <folly/futures/DrivableExecutor.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/Try.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/detail/Types.h>
33
34 // boring predeclarations and details
35 #include <folly/futures/Future-pre.h>
36
37 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
38 // Needs to be included after Future-pre.h and before Future-inl.h
39 #include <folly/futures/helpers.h>
40
41 namespace folly {
42
43 template <class T>
44 class Future {
45  public:
46   typedef T value_type;
47
48   // not copyable
49   Future(Future const&) = delete;
50   Future& operator=(Future const&) = delete;
51
52   // movable
53   Future(Future&&) noexcept;
54   Future& operator=(Future&&) noexcept;
55
56   // conversion constructors
57   template <
58       class U,
59       typename = typename std::enable_if<std::is_convertible<U, T>::value &&
60                                          sizeof(U) == sizeof(T)>::type>
61   /* implicit */ Future(Future<U>&&) noexcept;
62   template <
63       class U,
64       typename = typename std::enable_if<std::is_convertible<U, T>::value &&
65                                          sizeof(U) == sizeof(T)>::type>
66   /* implicit */ Future& operator=(Future<U>&&) noexcept;
67
68   /// Construct a Future from a value (perfect forwarding)
69   template <class T2 = T, typename =
70             typename std::enable_if<
71               !isFuture<typename std::decay<T2>::type>::value>::type>
72   /* implicit */ Future(T2&& val);
73
74   template <class T2 = T>
75   /* implicit */ Future(
76       typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
77
78   ~Future();
79
80   /** Return the reference to result. Should not be called if !isReady().
81     Will rethrow the exception if an exception has been
82     captured.
83     */
84   typename std::add_lvalue_reference<T>::type
85   value();
86   typename std::add_lvalue_reference<const T>::type
87   value() const;
88
89   /// Returns an inactive Future which will call back on the other side of
90   /// executor (when it is activated).
91   ///
92   /// NB remember that Futures activate when they destruct. This is good,
93   /// it means that this will work:
94   ///
95   ///   f.via(e).then(a).then(b);
96   ///
97   /// a and b will execute in the same context (the far side of e), because
98   /// the Future (temporary variable) created by via(e) does not call back
99   /// until it destructs, which is after then(a) and then(b) have been wired
100   /// up.
101   ///
102   /// But this is still racy:
103   ///
104   ///   f = f.via(e).then(a);
105   ///   f.then(b);
106   // The ref-qualifier allows for `this` to be moved out so we
107   // don't get access-after-free situations in chaining.
108   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
109   inline Future<T> via(
110       Executor* executor,
111       int8_t priority = Executor::MID_PRI) &&;
112
113   /// This variant creates a new future, where the ref-qualifier && version
114   /// moves `this` out. This one is less efficient but avoids confusing users
115   /// when "return f.via(x);" fails.
116   inline Future<T> via(
117       Executor* executor,
118       int8_t priority = Executor::MID_PRI) &;
119
120   /** True when the result (or exception) is ready. */
121   bool isReady() const;
122
123   /// sugar for getTry().hasValue()
124   bool hasValue();
125
126   /// sugar for getTry().hasException()
127   bool hasException();
128
129   /** A reference to the Try of the value */
130   Try<T>& getTry();
131
132   /// Call e->drive() repeatedly until the future is fulfilled. Examples
133   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
134   /// reference to the Try of the value.
135   Try<T>& getTryVia(DrivableExecutor* e);
136
137   /// If the promise has been fulfilled, return an Optional with the Try<T>.
138   /// Otherwise return an empty Optional.
139   /// Note that this moves the Try<T> out.
140   Optional<Try<T>> poll();
141
142   /// Block until the future is fulfilled. Returns the value (moved out), or
143   /// throws the exception. The future must not already have a callback.
144   T get();
145
146   /// Block until the future is fulfilled, or until timed out. Returns the
147   /// value (moved out), or throws the exception (which might be a TimedOut
148   /// exception).
149   T get(Duration dur);
150
151   /// Call e->drive() repeatedly until the future is fulfilled. Examples
152   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
153   /// value (moved out), or throws the exception.
154   T getVia(DrivableExecutor* e);
155
156   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
157   /// Future<T> instance.
158   template <class F = T>
159   typename std::enable_if<isFuture<F>::value,
160                           Future<typename isFuture<T>::Inner>>::type
161   unwrap();
162
163   /** When this Future has completed, execute func which is a function that
164     takes one of:
165       (const) Try<T>&&
166       (const) Try<T>&
167       (const) Try<T>
168       (const) T&&
169       (const) T&
170       (const) T
171       (void)
172
173     Func shall return either another Future or a value.
174
175     A Future for the return type of func is returned.
176
177     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
178
179     The Future given to the functor is ready, and the functor may call
180     value(), which may rethrow if this has captured an exception. If func
181     throws, the exception will be captured in the Future that is returned.
182     */
183   // gcc 4.8 requires that we cast function reference types to function pointer
184   // types. Fore more details see the comment on FunctionReferenceToPointer
185   // in Future-pre.h.
186   // gcc versions 4.9 and above (as well as clang) do not require this hack.
187   // For those, the FF tenplate parameter can be removed and occurences of FF
188   // replaced with F.
189   template <
190       typename F,
191       typename FF = typename detail::FunctionReferenceToPointer<F>::type,
192       typename R = detail::callableResult<T, FF>>
193   typename R::Return then(F&& func) {
194     typedef typename R::Arg Arguments;
195     return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
196   }
197
198   /// Variant where func is an member function
199   ///
200   ///   struct Worker { R doWork(Try<T>); }
201   ///
202   ///   Worker *w;
203   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
204   ///
205   /// This is just sugar for
206   ///
207   ///   f1.then(std::bind(&Worker::doWork, w));
208   template <typename R, typename Caller, typename... Args>
209   Future<typename isFuture<R>::Inner>
210   then(R(Caller::*func)(Args...), Caller *instance);
211
212   /// Execute the callback via the given Executor. The executor doesn't stick.
213   ///
214   /// Contrast
215   ///
216   ///   f.via(x).then(b).then(c)
217   ///
218   /// with
219   ///
220   ///   f.then(x, b).then(c)
221   ///
222   /// In the former both b and c execute via x. In the latter, only b executes
223   /// via x, and c executes via the same executor (if any) that f had.
224   template <class Executor, class Arg, class... Args>
225   auto then(Executor* x, Arg&& arg, Args&&... args)
226     -> decltype(this->then(std::forward<Arg>(arg),
227                            std::forward<Args>(args)...));
228
229   /// Convenience method for ignoring the value and creating a Future<Unit>.
230   /// Exceptions still propagate.
231   Future<Unit> then();
232
233   /// Set an error callback for this Future. The callback should take a single
234   /// argument of the type that you want to catch, and should return a value of
235   /// the same type as this Future, or a Future of that type (see overload
236   /// below). For instance,
237   ///
238   /// makeFuture()
239   ///   .then([] {
240   ///     throw std::runtime_error("oh no!");
241   ///     return 42;
242   ///   })
243   ///   .onError([] (std::runtime_error& e) {
244   ///     LOG(INFO) << "std::runtime_error: " << e.what();
245   ///     return -1; // or makeFuture<int>(-1)
246   ///   });
247   template <class F>
248   typename std::enable_if<
249     !detail::callableWith<F, exception_wrapper>::value &&
250     !detail::Extract<F>::ReturnsFuture::value,
251     Future<T>>::type
252   onError(F&& func);
253
254   /// Overload of onError where the error callback returns a Future<T>
255   template <class F>
256   typename std::enable_if<
257     !detail::callableWith<F, exception_wrapper>::value &&
258     detail::Extract<F>::ReturnsFuture::value,
259     Future<T>>::type
260   onError(F&& func);
261
262   /// Overload of onError that takes exception_wrapper and returns Future<T>
263   template <class F>
264   typename std::enable_if<
265     detail::callableWith<F, exception_wrapper>::value &&
266     detail::Extract<F>::ReturnsFuture::value,
267     Future<T>>::type
268   onError(F&& func);
269
270   /// Overload of onError that takes exception_wrapper and returns T
271   template <class F>
272   typename std::enable_if<
273     detail::callableWith<F, exception_wrapper>::value &&
274     !detail::Extract<F>::ReturnsFuture::value,
275     Future<T>>::type
276   onError(F&& func);
277
278   /// func is like std::function<void()> and is executed unconditionally, and
279   /// the value/exception is passed through to the resulting Future.
280   /// func shouldn't throw, but if it does it will be captured and propagated,
281   /// and discard any value/exception that this Future has obtained.
282   template <class F>
283   Future<T> ensure(F&& func);
284
285   /// Like onError, but for timeouts. example:
286   ///
287   ///   Future<int> f = makeFuture<int>(42)
288   ///     .delayed(long_time)
289   ///     .onTimeout(short_time,
290   ///       []() -> int{ return -1; });
291   ///
292   /// or perhaps
293   ///
294   ///   Future<int> f = makeFuture<int>(42)
295   ///     .delayed(long_time)
296   ///     .onTimeout(short_time,
297   ///       []() { return makeFuture<int>(some_exception); });
298   template <class F>
299   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
300
301   /// This is not the method you're looking for.
302   ///
303   /// This needs to be public because it's used by make* and when*, and it's
304   /// not worth listing all those and their fancy template signatures as
305   /// friends. But it's not for public consumption.
306   template <class F>
307   void setCallback_(F&& func);
308
309   /// A Future's callback is executed when all three of these conditions have
310   /// become true: it has a value (set by the Promise), it has a callback (set
311   /// by then), and it is active (active by default).
312   ///
313   /// Inactive Futures will activate upon destruction.
314   FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
315     core_->activate();
316     return *this;
317   }
318   FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
319     core_->deactivate();
320     return *this;
321   }
322   FOLLY_DEPRECATED("do not use") Future<T> activate() && {
323     core_->activate();
324     return std::move(*this);
325   }
326   FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
327     core_->deactivate();
328     return std::move(*this);
329   }
330
331   bool isActive() {
332     return core_->isActive();
333   }
334
335   template <class E>
336   void raise(E&& exception) {
337     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
338         std::forward<E>(exception)));
339   }
340
341   /// Raise an interrupt. If the promise holder has an interrupt
342   /// handler it will be called and potentially stop asynchronous work from
343   /// being done. This is advisory only - a promise holder may not set an
344   /// interrupt handler, or may do anything including ignore. But, if you know
345   /// your future supports this the most likely result is stopping or
346   /// preventing the asynchronous operation (if in time), and the promise
347   /// holder setting an exception on the future. (That may happen
348   /// asynchronously, of course.)
349   void raise(exception_wrapper interrupt);
350
351   void cancel() {
352     raise(FutureCancellation());
353   }
354
355   /// Throw TimedOut if this Future does not complete within the given
356   /// duration from now. The optional Timeekeeper is as with futures::sleep().
357   Future<T> within(Duration, Timekeeper* = nullptr);
358
359   /// Throw the given exception if this Future does not complete within the
360   /// given duration from now. The optional Timeekeeper is as with
361   /// futures::sleep().
362   template <class E>
363   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
364
365   /// Delay the completion of this Future for at least this duration from
366   /// now. The optional Timekeeper is as with futures::sleep().
367   Future<T> delayed(Duration, Timekeeper* = nullptr);
368
369   /// Block until this Future is complete. Returns a reference to this Future.
370   Future<T>& wait() &;
371
372   /// Overload of wait() for rvalue Futures
373   Future<T>&& wait() &&;
374
375   /// Block until this Future is complete or until the given Duration passes.
376   /// Returns a reference to this Future
377   Future<T>& wait(Duration) &;
378
379   /// Overload of wait(Duration) for rvalue Futures
380   Future<T>&& wait(Duration) &&;
381
382   /// Call e->drive() repeatedly until the future is fulfilled. Examples
383   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
384   /// reference to this Future so that you can chain calls if desired.
385   /// value (moved out), or throws the exception.
386   Future<T>& waitVia(DrivableExecutor* e) &;
387
388   /// Overload of waitVia() for rvalue Futures
389   Future<T>&& waitVia(DrivableExecutor* e) &&;
390
391   /// If the value in this Future is equal to the given Future, when they have
392   /// both completed, the value of the resulting Future<bool> will be true. It
393   /// will be false otherwise (including when one or both Futures have an
394   /// exception)
395   Future<bool> willEqual(Future<T>&);
396
397   /// predicate behaves like std::function<bool(T const&)>
398   /// If the predicate does not obtain with the value, the result
399   /// is a folly::PredicateDoesNotObtain exception
400   template <class F>
401   Future<T> filter(F&& predicate);
402
403   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
404   /// the result of collect or collectAll
405   template <class I, class F>
406   Future<I> reduce(I&& initial, F&& func);
407
408   /// Create a Future chain from a sequence of callbacks. i.e.
409   ///
410   ///   f.then(a).then(b).then(c)
411   ///
412   /// where f is a Future<A> and the result of the chain is a Future<D>
413   /// becomes
414   ///
415   ///   f.thenMulti(a, b, c);
416   template <class Callback, class... Callbacks>
417   auto thenMulti(Callback&& fn, Callbacks&&... fns)
418     -> decltype(this->then(std::forward<Callback>(fn)).
419                       thenMulti(std::forward<Callbacks>(fns)...));
420
421   // Nothing to see here, just thenMulti's base case
422   template <class Callback>
423   auto thenMulti(Callback&& fn)
424     -> decltype(this->then(std::forward<Callback>(fn)));
425
426   /// Create a Future chain from a sequence of callbacks. i.e.
427   ///
428   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
429   ///
430   /// where f is a Future<A> and the result of the chain is a Future<D>
431   /// becomes
432   ///
433   ///   f.thenMultiWithExecutor(executor, a, b, c);
434   template <class Callback, class... Callbacks>
435   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
436     -> decltype(this->then(std::forward<Callback>(fn)).
437                       thenMulti(std::forward<Callbacks>(fns)...));
438
439   // Nothing to see here, just thenMultiWithExecutor's base case
440   template <class Callback>
441   auto thenMultiWithExecutor(Executor* x, Callback&& fn)
442     -> decltype(this->then(std::forward<Callback>(fn)));
443
444   /// Discard a result, but propagate an exception.
445   Future<Unit> unit() {
446     return then([]{ return Unit{}; });
447   }
448
449  protected:
450   typedef detail::Core<T>* corePtr;
451
452   // shared core state object
453   corePtr core_;
454
455   explicit
456   Future(corePtr obj) : core_(obj) {}
457
458   void detach();
459
460   void throwIfInvalid() const;
461
462   friend class Promise<T>;
463   template <class> friend class Future;
464
465   template <class T2>
466   friend Future<T2> makeFuture(Try<T2>&&);
467
468   /// Repeat the given future (i.e., the computation it contains)
469   /// n times.
470   ///
471   /// thunk behaves like std::function<Future<T2>(void)>
472   template <class F>
473   friend Future<Unit> times(int n, F&& thunk);
474
475   /// Carry out the computation contained in the given future if
476   /// the predicate holds.
477   ///
478   /// thunk behaves like std::function<Future<T2>(void)>
479   template <class F>
480   friend Future<Unit> when(bool p, F&& thunk);
481
482   /// Carry out the computation contained in the given future if
483   /// while the predicate continues to hold.
484   ///
485   /// thunk behaves like std::function<Future<T2>(void)>
486   ///
487   /// predicate behaves like std::function<bool(void)>
488   template <class P, class F>
489   friend Future<Unit> whileDo(P&& predicate, F&& thunk);
490
491   // Variant: returns a value
492   // e.g. f.then([](Try<T> t){ return t.value(); });
493   template <typename F, typename R, bool isTry, typename... Args>
494   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
495   thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
496
497   // Variant: returns a Future
498   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
499   template <typename F, typename R, bool isTry, typename... Args>
500   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
501   thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
502
503   Executor* getExecutor() { return core_->getExecutor(); }
504   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
505     core_->setExecutor(x, priority);
506   }
507 };
508
509 } // folly
510
511 #include <folly/futures/Future-inl.h>