c1deb6add651c92bacf11796b9a1e275a25559ae
[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&&);
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   /// Deprecated alias for via
75   template <typename Executor>
76   Future<T> executeWithSameThread(Executor* executor) {
77     return via(executor);
78   }
79
80   /**
81      Thread-safe version of executeWith
82
83      Since an executor would likely start executing the Future chain
84      right away, it would be a race condition to call:
85      Future.executeWith(...).then(...), as there would be race
86      condition between the then and the running Future.
87      Instead, you may pass in a Promise so that we can set up
88      the rest of the chain in advance, without any racey
89      modifications of the continuation
90
91      Deprecated. Use a Later.
92    */
93   template <typename Executor>
94   void executeWith(Executor* executor, Promise<T>&& cont_promise);
95
96   /** True when the result (or exception) is ready. */
97   bool isReady() const;
98
99   /** A reference to the Try of the value */
100   Try<T>& getTry();
101
102   /** When this Future has completed, execute func which is a function that
103     takes a Try<T>&&. A Future for the return type of func is
104     returned. e.g.
105
106     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
107
108     The Future given to the functor is ready, and the functor may call
109     value(), which may rethrow if this has captured an exception. If func
110     throws, the exception will be captured in the Future that is returned.
111     */
112   /* TODO n3428 and other async frameworks have something like then(scheduler,
113      Future), we probably want to support a similar API (instead of
114      executeWith). */
115   template <class F>
116   typename std::enable_if<
117     !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
118     Future<typename std::result_of<F(Try<T>&&)>::type> >::type
119   then(F&& func);
120
121   /// Variant where func returns a Future<T> instead of a T. e.g.
122   ///
123   ///   Future<string> f2 = f1.then(
124   ///     [](Try<T>&&) { return makeFuture<string>("foo"); });
125   template <class F>
126   typename std::enable_if<
127     isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
128     Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
129   then(F&& func);
130
131   /// Variant where func is an ordinary function (static method, method)
132   ///
133   ///   R doWork(Try<T>&&);
134   ///
135   ///   Future<R> f2 = f1.then(doWork);
136   ///
137   /// or
138   ///
139   ///   struct Worker {
140   ///     static R doWork(Try<T>&&); }
141   ///
142   ///   Future<R> f2 = f1.then(&Worker::doWork);
143   template <class = T, class R = std::nullptr_t>
144   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
145   inline then(R(*func)(Try<T>&&)) {
146     return then([func](Try<T>&& t) {
147       return (*func)(std::move(t));
148     });
149   }
150
151   /// Variant where func returns a Future<R> instead of a R. e.g.
152   ///
153   ///   struct Worker {
154   ///     Future<R> doWork(Try<T>&&); }
155   ///
156   ///   Future<R> f2 = f1.then(&Worker::doWork);
157   template <class = T, class R = std::nullptr_t>
158   typename std::enable_if<isFuture<R>::value, R>::type
159   inline then(R(*func)(Try<T>&&)) {
160     return then([func](Try<T>&& t) {
161       return (*func)(std::move(t));
162     });
163   }
164
165   /// Variant where func is an member function
166   ///
167   ///   struct Worker {
168   ///     R doWork(Try<T>&&); }
169   ///
170   ///   Worker *w;
171   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
172   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
173   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
174   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
175     return then([instance, func](Try<T>&& t) {
176       return (instance->*func)(std::move(t));
177     });
178   }
179
180   /// Variant where func returns a Future<R> instead of a R. e.g.
181   ///
182   ///   struct Worker {
183   ///     Future<R> doWork(Try<T>&&); }
184   ///
185   ///   Worker *w;
186   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
187   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
188   typename std::enable_if<isFuture<R>::value, R>::type
189   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
190     return then([instance, func](Try<T>&& t) {
191       return (instance->*func)(std::move(t));
192     });
193   }
194
195   /// Convenience method for ignoring the value and creating a Future<void>.
196   /// Exceptions still propagate.
197   Future<void> then();
198
199   /// Use of this method is advanced wizardry.
200   /// XXX should this be protected?
201   template <class F>
202   void setContinuation(F&& func);
203
204  private:
205   typedef detail::FutureObject<T>* objPtr;
206
207   // shared state object
208   objPtr obj_;
209
210   explicit
211   Future(objPtr obj) : obj_(obj) {}
212
213   void throwIfInvalid() const;
214
215   friend class Promise<T>;
216 };
217
218 /**
219   Make a completed Future by moving in a value. e.g.
220
221     string foo = "foo";
222     auto f = makeFuture(std::move(foo));
223
224   or
225
226     auto f = makeFuture<string>("foo");
227 */
228 template <class T>
229 Future<typename std::decay<T>::type> makeFuture(T&& t);
230
231 /** Make a completed void Future. */
232 Future<void> makeFuture();
233
234 /** Make a completed Future by executing a function. If the function throws
235   we capture the exception, otherwise we capture the result. */
236 template <class F>
237 auto makeFutureTry(
238   F&& func,
239   typename std::enable_if<
240     !std::is_reference<F>::value, bool>::type sdf = false)
241   -> Future<decltype(func())>;
242
243 template <class F>
244 auto makeFutureTry(
245   F const& func)
246   -> Future<decltype(func())>;
247
248 /// Make a failed Future from an exception_ptr.
249 /// Because the Future's type cannot be inferred you have to specify it, e.g.
250 ///
251 ///   auto f = makeFuture<string>(std::current_exception());
252 template <class T>
253 Future<T> makeFuture(std::exception_ptr const& e);
254
255 /** Make a Future from an exception type E that can be passed to
256   std::make_exception_ptr(). */
257 template <class T, class E>
258 typename std::enable_if<std::is_base_of<std::exception, E>::value, Future<T>>::type
259 makeFuture(E const& e);
260
261 /** When all the input Futures complete, the returned Future will complete.
262   Errors do not cause early termination; this Future will always succeed
263   after all its Futures have finished (whether successfully or with an
264   error).
265
266   The Futures are moved in, so your copies are invalid. If you need to
267   chain further from these Futures, use the variant with an output iterator.
268
269   XXX is this still true?
270   This function is thread-safe for Futures running on different threads.
271
272   The return type for Future<T> input is a Future<std::vector<Try<T>>>
273   */
274 template <class InputIterator>
275 Future<std::vector<Try<
276   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
277 whenAll(InputIterator first, InputIterator last);
278
279 /// This version takes a varying number of Futures instead of an iterator.
280 /// The return type for (Future<T1>, Future<T2>, ...) input
281 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
282 /// The Futures are moved in, so your copies are invalid.
283 template <typename... Fs>
284 typename detail::VariadicContext<
285   typename std::decay<Fs>::type::value_type...>::type
286 whenAll(Fs&&... fs);
287
288 /** The result is a pair of the index of the first Future to complete and
289   the Try. If multiple Futures complete at the same time (or are already
290   complete when passed in), the "winner" is chosen non-deterministically.
291
292   This function is thread-safe for Futures running on different threads.
293   */
294 template <class InputIterator>
295 Future<std::pair<
296   size_t,
297   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
298 whenAny(InputIterator first, InputIterator last);
299
300 /** when n Futures have completed, the Future completes with a vector of
301   the index and Try of those n Futures (the indices refer to the original
302   order, but the result vector will be in an arbitrary order)
303
304   Not thread safe.
305   */
306 template <class InputIterator>
307 Future<std::vector<std::pair<
308   size_t,
309   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
310 whenN(InputIterator first, InputIterator last, size_t n);
311
312 }} // folly::wangle
313
314 #include "Future-inl.h"