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