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