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