rearrange Future.h
[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> Future(T2&& val);
60
61   template <class F = T,
62             typename std::enable_if<std::is_void<F>::value, int>::type = 0>
63   Future();
64
65   ~Future();
66
67   /** Return the reference to result. Should not be called if !isReady().
68     Will rethrow the exception if an exception has been
69     captured.
70     */
71   typename std::add_lvalue_reference<T>::type
72   value();
73   typename std::add_lvalue_reference<const T>::type
74   value() const;
75
76   /// Returns an inactive Future which will call back on the other side of
77   /// executor (when it is activated).
78   ///
79   /// NB remember that Futures activate when they destruct. This is good,
80   /// it means that this will work:
81   ///
82   ///   f.via(e).then(a).then(b);
83   ///
84   /// a and b will execute in the same context (the far side of e), because
85   /// the Future (temporary variable) created by via(e) does not call back
86   /// until it destructs, which is after then(a) and then(b) have been wired
87   /// up.
88   ///
89   /// But this is still racy:
90   ///
91   ///   f = f.via(e).then(a);
92   ///   f.then(b);
93   // The ref-qualifier allows for `this` to be moved out so we
94   // don't get access-after-free situations in chaining.
95   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
96   template <typename Executor>
97   Future<T> via(Executor* executor) &&;
98
99   /// This variant creates a new future, where the ref-qualifier && version
100   /// moves `this` out. This one is less efficient but avoids confusing users
101   /// when "return f.via(x);" fails.
102   template <typename Executor>
103   Future<T> via(Executor* executor) &;
104
105   /** True when the result (or exception) is ready. */
106   bool isReady() const;
107
108   /** A reference to the Try of the value */
109   Try<T>& getTry();
110
111   /// If the promise has been fulfilled, return an Optional with the Try<T>.
112   /// Otherwise return an empty Optional.
113   /// Note that this moves the Try<T> out.
114   Optional<Try<T>> poll();
115
116   /// Block until the future is fulfilled. Returns the value (moved out), or
117   /// throws the exception. The future must not already have a callback.
118   T get();
119
120   /// Block until the future is fulfilled, or until timed out. Returns the
121   /// value (moved out), or throws the exception (which might be a TimedOut
122   /// exception).
123   T get(Duration dur);
124
125   /// Call e->drive() repeatedly until the future is fulfilled. Examples
126   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
127   /// value (moved out), or throws the exception.
128   T getVia(DrivableExecutor* e);
129
130   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
131   /// Future<T> instance.
132   template <class F = T>
133   typename std::enable_if<isFuture<F>::value,
134                           Future<typename isFuture<T>::Inner>>::type
135   unwrap();
136
137   /** When this Future has completed, execute func which is a function that
138     takes one of:
139       (const) Try<T>&&
140       (const) Try<T>&
141       (const) Try<T>
142       (const) T&&
143       (const) T&
144       (const) T
145       (void)
146
147     Func shall return either another Future or a value.
148
149     A Future for the return type of func is returned.
150
151     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
152
153     The Future given to the functor is ready, and the functor may call
154     value(), which may rethrow if this has captured an exception. If func
155     throws, the exception will be captured in the Future that is returned.
156     */
157   /* TODO n3428 and other async frameworks have something like then(scheduler,
158      Future), we might want to support a similar API which could be
159      implemented a little more efficiently than
160      f.via(executor).then(callback) */
161   template <typename F, typename R = detail::callableResult<T, F>>
162   typename R::Return then(F func) {
163     typedef typename R::Arg Arguments;
164     return thenImplementation<F, R>(std::move(func), Arguments());
165   }
166
167   /// Variant where func is an member function
168   ///
169   ///   struct Worker { R doWork(Try<T>); }
170   ///
171   ///   Worker *w;
172   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
173   ///
174   /// This is just sugar for
175   ///
176   ///   f1.then(std::bind(&Worker::doWork, w));
177   template <typename R, typename Caller, typename... Args>
178   Future<typename isFuture<R>::Inner>
179   then(R(Caller::*func)(Args...), Caller *instance);
180
181 // TODO(6838553)
182 #ifndef __clang__
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... Args>
196   auto then(Executor* x, Args&&... args)
197     -> decltype(this->then(std::forward<Args>(args)...));
198 #endif
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  protected:
375   typedef detail::Core<T>* corePtr;
376
377   // shared core state object
378   corePtr core_;
379
380   explicit
381   Future(corePtr obj) : core_(obj) {}
382
383   void detach();
384
385   void throwIfInvalid() const;
386
387   friend class Promise<T>;
388   template <class> friend class Future;
389
390   // Variant: returns a value
391   // e.g. f.then([](Try<T> t){ return t.value(); });
392   template <typename F, typename R, bool isTry, typename... Args>
393   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
394   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
395
396   // Variant: returns a Future
397   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
398   template <typename F, typename R, bool isTry, typename... Args>
399   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
400   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
401
402   Executor* getExecutor() { return core_->getExecutor(); }
403   void setExecutor(Executor* x) { core_->setExecutor(x); }
404 };
405
406
407 // Sugar for the most common case
408 template <class Collection, class T, class F>
409 auto reduce(Collection&& c, T&& initial, F&& func)
410     -> decltype(reduce(c.begin(), c.end(), initial, func)) {
411   return reduce(
412       c.begin(),
413       c.end(),
414       std::forward<T>(initial),
415       std::forward<F>(func));
416 }
417
418 } // folly
419
420 #include <folly/futures/Future-inl.h>