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