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