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