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