Future<Unit>::Future()
[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 T2 = T,
62             typename std::enable_if<
63               folly::is_void_or_unit<T2>::value,
64               int>::type = 0>
65   Future();
66
67   ~Future();
68
69   /** Return the reference to result. Should not be called if !isReady().
70     Will rethrow the exception if an exception has been
71     captured.
72     */
73   typename std::add_lvalue_reference<T>::type
74   value();
75   typename std::add_lvalue_reference<const T>::type
76   value() const;
77
78   /// Returns an inactive Future which will call back on the other side of
79   /// executor (when it is activated).
80   ///
81   /// NB remember that Futures activate when they destruct. This is good,
82   /// it means that this will work:
83   ///
84   ///   f.via(e).then(a).then(b);
85   ///
86   /// a and b will execute in the same context (the far side of e), because
87   /// the Future (temporary variable) created by via(e) does not call back
88   /// until it destructs, which is after then(a) and then(b) have been wired
89   /// up.
90   ///
91   /// But this is still racy:
92   ///
93   ///   f = f.via(e).then(a);
94   ///   f.then(b);
95   // The ref-qualifier allows for `this` to be moved out so we
96   // don't get access-after-free situations in chaining.
97   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
98   template <typename Executor>
99   Future<T> via(Executor* executor) &&;
100
101   /// This variant creates a new future, where the ref-qualifier && version
102   /// moves `this` out. This one is less efficient but avoids confusing users
103   /// when "return f.via(x);" fails.
104   template <typename Executor>
105   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 // TODO(6838553)
184 #ifndef __clang__
185   /// Execute the callback via the given Executor. The executor doesn't stick.
186   ///
187   /// Contrast
188   ///
189   ///   f.via(x).then(b).then(c)
190   ///
191   /// with
192   ///
193   ///   f.then(x, b).then(c)
194   ///
195   /// In the former both b and c execute via x. In the latter, only b executes
196   /// via x, and c executes via the same executor (if any) that f had.
197   template <class... Args>
198   auto then(Executor* x, Args&&... args)
199     -> decltype(this->then(std::forward<Args>(args)...));
200 #endif
201
202   /// Convenience method for ignoring the value and creating a Future<void>.
203   /// Exceptions still propagate.
204   Future<void> then();
205
206   /// Set an error callback for this Future. The callback should take a single
207   /// argument of the type that you want to catch, and should return a value of
208   /// the same type as this Future, or a Future of that type (see overload
209   /// below). For instance,
210   ///
211   /// makeFuture()
212   ///   .then([] {
213   ///     throw std::runtime_error("oh no!");
214   ///     return 42;
215   ///   })
216   ///   .onError([] (std::runtime_error& e) {
217   ///     LOG(INFO) << "std::runtime_error: " << e.what();
218   ///     return -1; // or makeFuture<int>(-1)
219   ///   });
220   template <class F>
221   typename std::enable_if<
222     !detail::callableWith<F, exception_wrapper>::value &&
223     !detail::Extract<F>::ReturnsFuture::value,
224     Future<T>>::type
225   onError(F&& func);
226
227   /// Overload of onError where the error callback returns a Future<T>
228   template <class F>
229   typename std::enable_if<
230     !detail::callableWith<F, exception_wrapper>::value &&
231     detail::Extract<F>::ReturnsFuture::value,
232     Future<T>>::type
233   onError(F&& func);
234
235   /// Overload of onError that takes exception_wrapper and returns Future<T>
236   template <class F>
237   typename std::enable_if<
238     detail::callableWith<F, exception_wrapper>::value &&
239     detail::Extract<F>::ReturnsFuture::value,
240     Future<T>>::type
241   onError(F&& func);
242
243   /// Overload of onError that takes exception_wrapper and returns T
244   template <class F>
245   typename std::enable_if<
246     detail::callableWith<F, exception_wrapper>::value &&
247     !detail::Extract<F>::ReturnsFuture::value,
248     Future<T>>::type
249   onError(F&& func);
250
251   /// func is like std::function<void()> and is executed unconditionally, and
252   /// the value/exception is passed through to the resulting Future.
253   /// func shouldn't throw, but if it does it will be captured and propagated,
254   /// and discard any value/exception that this Future has obtained.
255   template <class F>
256   Future<T> ensure(F func);
257
258   /// Like onError, but for timeouts. example:
259   ///
260   ///   Future<int> f = makeFuture<int>(42)
261   ///     .delayed(long_time)
262   ///     .onTimeout(short_time,
263   ///       []() -> int{ return -1; });
264   ///
265   /// or perhaps
266   ///
267   ///   Future<int> f = makeFuture<int>(42)
268   ///     .delayed(long_time)
269   ///     .onTimeout(short_time,
270   ///       []() { return makeFuture<int>(some_exception); });
271   template <class F>
272   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
273
274   /// This is not the method you're looking for.
275   ///
276   /// This needs to be public because it's used by make* and when*, and it's
277   /// not worth listing all those and their fancy template signatures as
278   /// friends. But it's not for public consumption.
279   template <class F>
280   void setCallback_(F&& func);
281
282   /// A Future's callback is executed when all three of these conditions have
283   /// become true: it has a value (set by the Promise), it has a callback (set
284   /// by then), and it is active (active by default).
285   ///
286   /// Inactive Futures will activate upon destruction.
287   Future<T>& activate() & {
288     core_->activate();
289     return *this;
290   }
291   Future<T>& deactivate() & {
292     core_->deactivate();
293     return *this;
294   }
295   Future<T> activate() && {
296     core_->activate();
297     return std::move(*this);
298   }
299   Future<T> deactivate() && {
300     core_->deactivate();
301     return std::move(*this);
302   }
303
304   bool isActive() {
305     return core_->isActive();
306   }
307
308   template <class E>
309   void raise(E&& exception) {
310     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
311         std::move(exception)));
312   }
313
314   /// Raise an interrupt. If the promise holder has an interrupt
315   /// handler it will be called and potentially stop asynchronous work from
316   /// being done. This is advisory only - a promise holder may not set an
317   /// interrupt handler, or may do anything including ignore. But, if you know
318   /// your future supports this the most likely result is stopping or
319   /// preventing the asynchronous operation (if in time), and the promise
320   /// holder setting an exception on the future. (That may happen
321   /// asynchronously, of course.)
322   void raise(exception_wrapper interrupt);
323
324   void cancel() {
325     raise(FutureCancellation());
326   }
327
328   /// Throw TimedOut if this Future does not complete within the given
329   /// duration from now. The optional Timeekeeper is as with futures::sleep().
330   Future<T> within(Duration, Timekeeper* = nullptr);
331
332   /// Throw the given exception if this Future does not complete within the
333   /// given duration from now. The optional Timeekeeper is as with
334   /// futures::sleep().
335   template <class E>
336   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
337
338   /// Delay the completion of this Future for at least this duration from
339   /// now. The optional Timekeeper is as with futures::sleep().
340   Future<T> delayed(Duration, Timekeeper* = nullptr);
341
342   /// Block until this Future is complete. Returns a reference to this Future.
343   Future<T>& wait() &;
344
345   /// Overload of wait() for rvalue Futures
346   Future<T>&& wait() &&;
347
348   /// Block until this Future is complete or until the given Duration passes.
349   /// Returns a reference to this Future
350   Future<T>& wait(Duration) &;
351
352   /// Overload of wait(Duration) for rvalue Futures
353   Future<T>&& wait(Duration) &&;
354
355   /// Call e->drive() repeatedly until the future is fulfilled. Examples
356   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
357   /// reference to this Future so that you can chain calls if desired.
358   /// value (moved out), or throws the exception.
359   Future<T>& waitVia(DrivableExecutor* e) &;
360
361   /// Overload of waitVia() for rvalue Futures
362   Future<T>&& waitVia(DrivableExecutor* e) &&;
363
364   /// If the value in this Future is equal to the given Future, when they have
365   /// both completed, the value of the resulting Future<bool> will be true. It
366   /// will be false otherwise (including when one or both Futures have an
367   /// exception)
368   Future<bool> willEqual(Future<T>&);
369
370   /// predicate behaves like std::function<bool(T const&)>
371   /// If the predicate does not obtain with the value, the result
372   /// is a folly::PredicateDoesNotObtain exception
373   template <class F>
374   Future<T> filter(F predicate);
375
376  protected:
377   typedef detail::Core<T>* corePtr;
378
379   // shared core state object
380   corePtr core_;
381
382   explicit
383   Future(corePtr obj) : core_(obj) {}
384
385   void detach();
386
387   void throwIfInvalid() const;
388
389   friend class Promise<T>;
390   template <class> friend class Future;
391
392   // Variant: returns a value
393   // e.g. f.then([](Try<T> t){ return t.value(); });
394   template <typename F, typename R, bool isTry, typename... Args>
395   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
396   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
397
398   // Variant: returns a Future
399   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
400   template <typename F, typename R, bool isTry, typename... Args>
401   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
402   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
403
404   Executor* getExecutor() { return core_->getExecutor(); }
405   void setExecutor(Executor* x) { core_->setExecutor(x); }
406 };
407
408
409 } // folly
410
411 #include <folly/futures/Future-inl.h>