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