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