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