b0c32081253b06622df8d0ad0efe9e726dca8dfc
[folly.git] / folly / wangle / Future.h
1 /*
2  * Copyright 2014 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/MoveWrapper.h"
27 #include "Promise.h"
28 #include "Try.h"
29
30 namespace folly { namespace wangle {
31
32 template <typename T> struct isFuture;
33
34 template <class T>
35 class Future {
36  public:
37   typedef T value_type;
38
39   // not copyable
40   Future(Future const&) = delete;
41   Future& operator=(Future const&) = delete;
42
43   // movable
44   Future(Future&&) noexcept;
45   Future& operator=(Future&&);
46
47   ~Future();
48
49   /** Return the reference to result. Should not be called if !isReady().
50     Will rethrow the exception if an exception has been
51     captured.
52
53     This function is not thread safe - the returned Future can only
54     be executed from the thread that the executor runs it in.
55     See below for a thread safe version
56     */
57   typename std::add_lvalue_reference<T>::type
58   value();
59   typename std::add_lvalue_reference<const T>::type
60   value() const;
61
62   /// Returns a future which will call back on the other side of executor.
63   ///
64   ///   f.via(e).then(a); // safe
65   ///
66   ///   f.via(e).then(a).then(b); // faux pas
67   ///
68   /// a will definitely execute in the intended thread, but b may execute
69   /// either in that thread, or in the current thread. If you need to
70   /// guarantee where b executes, use a Later.
71   template <typename Executor>
72   Future<T> via(Executor* executor);
73
74   /** True when the result (or exception) is ready. */
75   bool isReady() const;
76
77   /** A reference to the Try of the value */
78   Try<T>& getTry();
79
80   /** When this Future has completed, execute func which is a function that
81     takes a Try<T>&&. A Future for the return type of func is
82     returned. e.g.
83
84     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
85
86     The Future given to the functor is ready, and the functor may call
87     value(), which may rethrow if this has captured an exception. If func
88     throws, the exception will be captured in the Future that is returned.
89     */
90   /* TODO n3428 and other async frameworks have something like then(scheduler,
91      Future), we probably want to support a similar API (instead of
92      via. or rather, via should return a cold future (Later) and we provide
93      then(scheduler, Future) ). */
94   template <class F>
95   typename std::enable_if<
96     !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
97     Future<typename std::result_of<F(Try<T>&&)>::type> >::type
98   then(F&& func);
99
100   /// Variant where func returns a Future<T> instead of a T. e.g.
101   ///
102   ///   Future<string> f2 = f1.then(
103   ///     [](Try<T>&&) { return makeFuture<string>("foo"); });
104   template <class F>
105   typename std::enable_if<
106     isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
107     Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
108   then(F&& func);
109
110   /// Variant where func is an ordinary function (static method, method)
111   ///
112   ///   R doWork(Try<T>&&);
113   ///
114   ///   Future<R> f2 = f1.then(doWork);
115   ///
116   /// or
117   ///
118   ///   struct Worker {
119   ///     static R doWork(Try<T>&&); }
120   ///
121   ///   Future<R> f2 = f1.then(&Worker::doWork);
122   template <class = T, class R = std::nullptr_t>
123   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
124   inline then(R(*func)(Try<T>&&)) {
125     return then([func](Try<T>&& t) {
126       return (*func)(std::move(t));
127     });
128   }
129
130   /// Variant where func returns a Future<R> instead of a R. e.g.
131   ///
132   ///   struct Worker {
133   ///     Future<R> doWork(Try<T>&&); }
134   ///
135   ///   Future<R> f2 = f1.then(&Worker::doWork);
136   template <class = T, class R = std::nullptr_t>
137   typename std::enable_if<isFuture<R>::value, R>::type
138   inline then(R(*func)(Try<T>&&)) {
139     return then([func](Try<T>&& t) {
140       return (*func)(std::move(t));
141     });
142   }
143
144   /// Variant where func is an member function
145   ///
146   ///   struct Worker {
147   ///     R doWork(Try<T>&&); }
148   ///
149   ///   Worker *w;
150   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
151   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
152   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
153   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
154     return then([instance, func](Try<T>&& t) {
155       return (instance->*func)(std::move(t));
156     });
157   }
158
159   /// Variant where func returns a Future<R> instead of a R. e.g.
160   ///
161   ///   struct Worker {
162   ///     Future<R> doWork(Try<T>&&); }
163   ///
164   ///   Worker *w;
165   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
166   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
167   typename std::enable_if<isFuture<R>::value, R>::type
168   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
169     return then([instance, func](Try<T>&& t) {
170       return (instance->*func)(std::move(t));
171     });
172   }
173
174   /// Convenience method for ignoring the value and creating a Future<void>.
175   /// Exceptions still propagate.
176   Future<void> then();
177
178   /// This is not the method you're looking for.
179   ///
180   /// This needs to be public because it's used by make* and when*, and it's
181   /// not worth listing all those and their fancy template signatures as
182   /// friends. But it's not for public consumption.
183   template <class F>
184   void setCallback_(F&& func);
185
186  private:
187   typedef detail::FutureObject<T>* objPtr;
188
189   // shared state object
190   objPtr obj_;
191
192   explicit
193   Future(objPtr obj) : obj_(obj) {}
194
195   void throwIfInvalid() const;
196
197   friend class Promise<T>;
198 };
199
200 /**
201   Make a completed Future by moving in a value. e.g.
202
203     string foo = "foo";
204     auto f = makeFuture(std::move(foo));
205
206   or
207
208     auto f = makeFuture<string>("foo");
209 */
210 template <class T>
211 Future<typename std::decay<T>::type> makeFuture(T&& t);
212
213 /** Make a completed void Future. */
214 Future<void> makeFuture();
215
216 /** Make a completed Future by executing a function. If the function throws
217   we capture the exception, otherwise we capture the result. */
218 template <class F>
219 auto makeFutureTry(
220   F&& func,
221   typename std::enable_if<
222     !std::is_reference<F>::value, bool>::type sdf = false)
223   -> Future<decltype(func())>;
224
225 template <class F>
226 auto makeFutureTry(
227   F const& func)
228   -> Future<decltype(func())>;
229
230 /// Make a failed Future from an exception_ptr.
231 /// Because the Future's type cannot be inferred you have to specify it, e.g.
232 ///
233 ///   auto f = makeFuture<string>(std::current_exception());
234 template <class T>
235 Future<T> makeFuture(std::exception_ptr const& e);
236
237 /** Make a Future from an exception type E that can be passed to
238   std::make_exception_ptr(). */
239 template <class T, class E>
240 typename std::enable_if<std::is_base_of<std::exception, E>::value, Future<T>>::type
241 makeFuture(E const& e);
242
243 /** Make a Future out of a Try */
244 template <class T>
245 Future<T> makeFuture(Try<T>&& t);
246
247 /** When all the input Futures complete, the returned Future will complete.
248   Errors do not cause early termination; this Future will always succeed
249   after all its Futures have finished (whether successfully or with an
250   error).
251
252   The Futures are moved in, so your copies are invalid. If you need to
253   chain further from these Futures, use the variant with an output iterator.
254
255   XXX is this still true?
256   This function is thread-safe for Futures running on different threads.
257
258   The return type for Future<T> input is a Future<std::vector<Try<T>>>
259   */
260 template <class InputIterator>
261 Future<std::vector<Try<
262   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
263 whenAll(InputIterator first, InputIterator last);
264
265 /// This version takes a varying number of Futures instead of an iterator.
266 /// The return type for (Future<T1>, Future<T2>, ...) input
267 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
268 /// The Futures are moved in, so your copies are invalid.
269 template <typename... Fs>
270 typename detail::VariadicContext<
271   typename std::decay<Fs>::type::value_type...>::type
272 whenAll(Fs&&... fs);
273
274 /** The result is a pair of the index of the first Future to complete and
275   the Try. If multiple Futures complete at the same time (or are already
276   complete when passed in), the "winner" is chosen non-deterministically.
277
278   This function is thread-safe for Futures running on different threads.
279   */
280 template <class InputIterator>
281 Future<std::pair<
282   size_t,
283   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
284 whenAny(InputIterator first, InputIterator last);
285
286 /** when n Futures have completed, the Future completes with a vector of
287   the index and Try of those n Futures (the indices refer to the original
288   order, but the result vector will be in an arbitrary order)
289
290   Not thread safe.
291   */
292 template <class InputIterator>
293 Future<std::vector<std::pair<
294   size_t,
295   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
296 whenN(InputIterator first, InputIterator last, size_t n);
297
298 /** Wait for the given future to complete on a semaphore. Returns a completed
299  * future containing the result.
300  *
301  * NB if the promise for the future would be fulfilled in the same thread that
302  * you call this, it will deadlock.
303  */
304 template <class T>
305 Future<T> waitWithSemaphore(Future<T>&& f);
306
307 /** Wait for up to `timeout` for the given future to complete. Returns a future
308  * which may or may not be completed depending whether the given future
309  * completed in time
310  *
311  * Note: each call to this starts a (short-lived) thread and allocates memory.
312  */
313 template <typename T, class Duration>
314 Future<T> waitWithSemaphore(Future<T>&& f, Duration timeout);
315
316 }} // folly::wangle
317
318 #include "Future-inl.h"