instance Eq Unit
[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   /* TODO n3428 and other async frameworks have something like then(scheduler,
169      Future), we might want to support a similar API which could be
170      implemented a little more efficiently than
171      f.via(executor).then(callback) */
172   template <typename F, typename R = detail::callableResult<T, F>>
173   typename R::Return then(F func) {
174     typedef typename R::Arg Arguments;
175     return thenImplementation<F, R>(std::move(func), Arguments());
176   }
177
178   /// Variant where func is an member function
179   ///
180   ///   struct Worker { R doWork(Try<T>); }
181   ///
182   ///   Worker *w;
183   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
184   ///
185   /// This is just sugar for
186   ///
187   ///   f1.then(std::bind(&Worker::doWork, w));
188   template <typename R, typename Caller, typename... Args>
189   Future<typename isFuture<R>::Inner>
190   then(R(Caller::*func)(Args...), Caller *instance);
191
192   /// Execute the callback via the given Executor. The executor doesn't stick.
193   ///
194   /// Contrast
195   ///
196   ///   f.via(x).then(b).then(c)
197   ///
198   /// with
199   ///
200   ///   f.then(x, b).then(c)
201   ///
202   /// In the former both b and c execute via x. In the latter, only b executes
203   /// via x, and c executes via the same executor (if any) that f had.
204   template <class Executor, class Arg, class... Args>
205   auto then(Executor* x, Arg&& arg, Args&&... args)
206     -> decltype(this->then(std::forward<Arg>(arg),
207                            std::forward<Args>(args)...));
208
209   /// Convenience method for ignoring the value and creating a Future<void>.
210   /// Exceptions still propagate.
211   Future<void> then();
212
213   /// Set an error callback for this Future. The callback should take a single
214   /// argument of the type that you want to catch, and should return a value of
215   /// the same type as this Future, or a Future of that type (see overload
216   /// below). For instance,
217   ///
218   /// makeFuture()
219   ///   .then([] {
220   ///     throw std::runtime_error("oh no!");
221   ///     return 42;
222   ///   })
223   ///   .onError([] (std::runtime_error& e) {
224   ///     LOG(INFO) << "std::runtime_error: " << e.what();
225   ///     return -1; // or makeFuture<int>(-1)
226   ///   });
227   template <class F>
228   typename std::enable_if<
229     !detail::callableWith<F, exception_wrapper>::value &&
230     !detail::Extract<F>::ReturnsFuture::value,
231     Future<T>>::type
232   onError(F&& func);
233
234   /// Overload of onError where the error callback returns a Future<T>
235   template <class F>
236   typename std::enable_if<
237     !detail::callableWith<F, exception_wrapper>::value &&
238     detail::Extract<F>::ReturnsFuture::value,
239     Future<T>>::type
240   onError(F&& func);
241
242   /// Overload of onError that takes exception_wrapper and returns Future<T>
243   template <class F>
244   typename std::enable_if<
245     detail::callableWith<F, exception_wrapper>::value &&
246     detail::Extract<F>::ReturnsFuture::value,
247     Future<T>>::type
248   onError(F&& func);
249
250   /// Overload of onError that takes exception_wrapper and returns T
251   template <class F>
252   typename std::enable_if<
253     detail::callableWith<F, exception_wrapper>::value &&
254     !detail::Extract<F>::ReturnsFuture::value,
255     Future<T>>::type
256   onError(F&& func);
257
258   /// func is like std::function<void()> and is executed unconditionally, and
259   /// the value/exception is passed through to the resulting Future.
260   /// func shouldn't throw, but if it does it will be captured and propagated,
261   /// and discard any value/exception that this Future has obtained.
262   template <class F>
263   Future<T> ensure(F func);
264
265   /// Like onError, but for timeouts. example:
266   ///
267   ///   Future<int> f = makeFuture<int>(42)
268   ///     .delayed(long_time)
269   ///     .onTimeout(short_time,
270   ///       []() -> int{ return -1; });
271   ///
272   /// or perhaps
273   ///
274   ///   Future<int> f = makeFuture<int>(42)
275   ///     .delayed(long_time)
276   ///     .onTimeout(short_time,
277   ///       []() { return makeFuture<int>(some_exception); });
278   template <class F>
279   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
280
281   /// This is not the method you're looking for.
282   ///
283   /// This needs to be public because it's used by make* and when*, and it's
284   /// not worth listing all those and their fancy template signatures as
285   /// friends. But it's not for public consumption.
286   template <class F>
287   void setCallback_(F&& func);
288
289   /// A Future's callback is executed when all three of these conditions have
290   /// become true: it has a value (set by the Promise), it has a callback (set
291   /// by then), and it is active (active by default).
292   ///
293   /// Inactive Futures will activate upon destruction.
294   Future<T>& activate() & DEPRECATED {
295     core_->activate();
296     return *this;
297   }
298   Future<T>& deactivate() & DEPRECATED {
299     core_->deactivate();
300     return *this;
301   }
302   Future<T> activate() && DEPRECATED {
303     core_->activate();
304     return std::move(*this);
305   }
306   Future<T> deactivate() && DEPRECATED {
307     core_->deactivate();
308     return std::move(*this);
309   }
310
311   bool isActive() {
312     return core_->isActive();
313   }
314
315   template <class E>
316   void raise(E&& exception) {
317     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
318         std::move(exception)));
319   }
320
321   /// Raise an interrupt. If the promise holder has an interrupt
322   /// handler it will be called and potentially stop asynchronous work from
323   /// being done. This is advisory only - a promise holder may not set an
324   /// interrupt handler, or may do anything including ignore. But, if you know
325   /// your future supports this the most likely result is stopping or
326   /// preventing the asynchronous operation (if in time), and the promise
327   /// holder setting an exception on the future. (That may happen
328   /// asynchronously, of course.)
329   void raise(exception_wrapper interrupt);
330
331   void cancel() {
332     raise(FutureCancellation());
333   }
334
335   /// Throw TimedOut if this Future does not complete within the given
336   /// duration from now. The optional Timeekeeper is as with futures::sleep().
337   Future<T> within(Duration, Timekeeper* = nullptr);
338
339   /// Throw the given exception if this Future does not complete within the
340   /// given duration from now. The optional Timeekeeper is as with
341   /// futures::sleep().
342   template <class E>
343   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
344
345   /// Delay the completion of this Future for at least this duration from
346   /// now. The optional Timekeeper is as with futures::sleep().
347   Future<T> delayed(Duration, Timekeeper* = nullptr);
348
349   /// Block until this Future is complete. Returns a reference to this Future.
350   Future<T>& wait() &;
351
352   /// Overload of wait() for rvalue Futures
353   Future<T>&& wait() &&;
354
355   /// Block until this Future is complete or until the given Duration passes.
356   /// Returns a reference to this Future
357   Future<T>& wait(Duration) &;
358
359   /// Overload of wait(Duration) for rvalue Futures
360   Future<T>&& wait(Duration) &&;
361
362   /// Call e->drive() repeatedly until the future is fulfilled. Examples
363   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
364   /// reference to this Future so that you can chain calls if desired.
365   /// value (moved out), or throws the exception.
366   Future<T>& waitVia(DrivableExecutor* e) &;
367
368   /// Overload of waitVia() for rvalue Futures
369   Future<T>&& waitVia(DrivableExecutor* e) &&;
370
371   /// If the value in this Future is equal to the given Future, when they have
372   /// both completed, the value of the resulting Future<bool> will be true. It
373   /// will be false otherwise (including when one or both Futures have an
374   /// exception)
375   Future<bool> willEqual(Future<T>&);
376
377   /// predicate behaves like std::function<bool(T const&)>
378   /// If the predicate does not obtain with the value, the result
379   /// is a folly::PredicateDoesNotObtain exception
380   template <class F>
381   Future<T> filter(F predicate);
382
383   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
384   /// the result of collect or collectAll
385   template <class I, class F>
386   Future<I> reduce(I&& initial, F&& func);
387
388   /// Create a Future chain from a sequence of callbacks. i.e.
389   ///
390   ///   f.then(a).then(b).then(c)
391   ///
392   /// where f is a Future<A> and the result of the chain is a Future<D>
393   /// becomes
394   ///
395   ///   f.thenMulti(a, b, c);
396   template <class Callback, class... Callbacks>
397   auto thenMulti(Callback&& fn, Callbacks&&... fns)
398     -> decltype(this->then(std::forward<Callback>(fn)).
399                       thenMulti(std::forward<Callbacks>(fns)...));
400
401   // Nothing to see here, just thenMulti's base case
402   template <class Callback>
403   auto thenMulti(Callback&& fn)
404     -> decltype(this->then(std::forward<Callback>(fn)));
405
406   /// Create a Future chain from a sequence of callbacks. i.e.
407   ///
408   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
409   ///
410   /// where f is a Future<A> and the result of the chain is a Future<D>
411   /// becomes
412   ///
413   ///   f.thenMultiWithExecutor(executor, a, b, c);
414   template <class Callback, class... Callbacks>
415   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
416     -> decltype(this->then(std::forward<Callback>(fn)).
417                       thenMulti(std::forward<Callbacks>(fns)...));
418
419   // Nothing to see here, just thenMultiWithExecutor's base case
420   template <class Callback>
421   auto thenMultiWithExecutor(Executor* x, Callback&& fn)
422     -> decltype(this->then(std::forward<Callback>(fn)));
423
424   /// Discard a result, but propagate an exception.
425   Future<Unit> unit() {
426     return then([]{ return Unit{}; });
427   }
428
429  protected:
430   typedef detail::Core<T>* corePtr;
431
432   // shared core state object
433   corePtr core_;
434
435   explicit
436   Future(corePtr obj) : core_(obj) {}
437
438   void detach();
439
440   void throwIfInvalid() const;
441
442   friend class Promise<T>;
443   template <class> friend class Future;
444
445   template <class T2>
446   friend Future<T2> makeFuture(Try<T2>&&);
447
448   // Variant: returns a value
449   // e.g. f.then([](Try<T> t){ return t.value(); });
450   template <typename F, typename R, bool isTry, typename... Args>
451   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
452   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
453
454   // Variant: returns a Future
455   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
456   template <typename F, typename R, bool isTry, typename... Args>
457   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
458   thenImplementation(F func, detail::argResult<isTry, F, Args...>);
459
460   Executor* getExecutor() { return core_->getExecutor(); }
461   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
462     core_->setExecutor(x, priority);
463   }
464 };
465
466 } // folly
467
468 #include <folly/futures/Future-inl.h>