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