Move wangle to folly
[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
25 #include "folly/MoveWrapper.h"
26 #include "Promise.h"
27 #include "Try.h"
28
29 namespace folly { namespace wangle {
30
31 template <typename T> struct isFuture;
32
33 template <class T>
34 class Future {
35  public:
36   typedef T value_type;
37
38   // not copyable
39   Future(Future const&) = delete;
40   Future& operator=(Future const&) = delete;
41
42   // movable
43   Future(Future&&);
44   Future& operator=(Future&&);
45
46   ~Future();
47
48   /** Return the reference to result. Should not be called if !isReady().
49     Will rethrow the exception if an exception has been
50     captured.
51
52     This function is not thread safe - the returned Future can only
53     be executed from the thread that the executor runs it in.
54     See below for a thread safe version
55     */
56   typename std::add_lvalue_reference<T>::type
57   value();
58   typename std::add_lvalue_reference<const T>::type
59   value() const;
60
61   template <typename Executor>
62   Future<T> executeWithSameThread(Executor* executor);
63
64   /**
65      Thread-safe version of executeWith
66
67      Since an executor would likely start executing the Future chain
68      right away, it would be a race condition to call:
69      Future.executeWith(...).then(...), as there would be race
70      condition between the then and the running Future.
71      Instead, you may pass in a Promise so that we can set up
72      the rest of the chain in advance, without any racey
73      modifications of the continuation
74    */
75   template <typename Executor>
76   void executeWith(Executor* executor, Promise<T>&& cont_promise);
77
78   /** True when the result (or exception) is ready.  value() will not block
79       when this returns true. */
80   bool isReady() const;
81
82   /** Wait until the result (or exception) is ready. Once this returns,
83     value() will not block, and isReady() will return true.
84
85     XXX This implementation is simplistic and inefficient, but it does work
86     and a fully intelligent implementation is coming down the pipe.
87   */
88   void wait() const {
89     while (!isReady()) {
90       // spin
91       std::this_thread::yield();
92     }
93   }
94
95   Try<T>& valueTry();
96
97   /** When this Future has completed, execute func which is a function that
98     takes a Try<T>&&. A Future for the return type of func is
99     returned. e.g.
100
101     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
102
103     The functor given may call value() without blocking, which may rethrow if
104     this has captured an exception. If func throws, the exception will be
105     captured in the Future that is returned.
106     */
107   /* n3428 has then(scheduler&, F&&), we might want to reorganize to use
108      similar API. or maybe not */
109   template <class F>
110   typename std::enable_if<
111     !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
112     Future<typename std::result_of<F(Try<T>&&)>::type> >::type
113   then(F&& func);
114
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::value_type> >::type
119   then(F&& func);
120
121   /** Use this method on the Future when we don't really care about the
122     returned value and want to convert the Future<T> to a Future<void>
123     Convenience function
124     */
125   Future<void> then();
126
127   template <class F>
128   void setContinuation(F&& func);
129
130  private:
131   /* Eventually this may not be a shared_ptr, but something similar without
132      expensive thread-safety. */
133   typedef detail::FutureObject<T>* objPtr;
134
135   // shared state object
136   objPtr obj_;
137
138   explicit
139   Future(objPtr obj) : obj_(obj) {}
140
141   void throwIfInvalid() const;
142
143   friend class Promise<T>;
144 };
145
146 /** Make a completed Future by moving in a value. e.g.
147   auto f = makeFuture(string("foo"));
148 */
149 template <class T>
150 Future<typename std::decay<T>::type> makeFuture(T&& t);
151
152 /** Make a completed void Future. */
153 Future<void> makeFuture();
154
155 /** Make a completed Future by executing a function. If the function throws
156   we capture the exception, otherwise we capture the result. */
157 template <class F>
158 auto makeFutureTry(
159   F&& func,
160   typename std::enable_if<
161     !std::is_reference<F>::value, bool>::type sdf = false)
162   -> Future<decltype(func())>;
163
164 template <class F>
165 auto makeFutureTry(
166   F const& func)
167   -> Future<decltype(func())>;
168
169 /** Make a completed (error) Future from an exception_ptr. Because the type
170 can't be inferred you have to give it, e.g.
171
172 auto f = makeFuture<string>(std::current_exception());
173 */
174 template <class T>
175 Future<T> makeFuture(std::exception_ptr const& e);
176
177 /** Make a Future from an exception type E that can be passed to
178   std::make_exception_ptr(). */
179 template <class T, class E>
180 typename std::enable_if<std::is_base_of<std::exception, E>::value, Future<T>>::type
181 makeFuture(E const& e);
182
183 /** When all the input Futures complete, the returned Future will complete.
184   Errors do not cause early termination; this Future will always succeed
185   after all its Futures have finished (whether successfully or with an
186   error).
187
188   The Futures are moved in, so your copies are invalid. If you need to
189   chain further from these Futures, use the variant with an output iterator.
190
191   This function is thread-safe for Futures running on different threads.
192
193   The return type for Future<T> input is a Future<vector<Try<T>>>
194   */
195 template <class InputIterator>
196 Future<std::vector<Try<
197   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
198 whenAll(InputIterator first, InputIterator last);
199
200 /** This version takes a varying number of Futures instead of an iterator.
201   The return type for (Future<T1>, Future<T2>, ...) input
202   is a Future<tuple<Try<T1>, Try<T2>, ...>>.
203   */
204 template <typename... Fs>
205 typename detail::VariadicContext<typename Fs::value_type...>::type
206 whenAll(Fs&... fs);
207
208 /** The result is a pair of the index of the first Future to complete and
209   the Try. If multiple Futures complete at the same time (or are already
210   complete when passed in), the "winner" is chosen non-deterministically.
211
212   This function is thread-safe for Futures running on different threads.
213   */
214 template <class InputIterator>
215 Future<std::pair<
216   size_t,
217   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
218 whenAny(InputIterator first, InputIterator last);
219
220 /** when n Futures have completed, the Future completes with a vector of
221   the index and Try of those n Futures (the indices refer to the original
222   order, but the result vector will be in an arbitrary order)
223
224   Not thread safe.
225   */
226 template <class InputIterator>
227 Future<std::vector<std::pair<
228   size_t,
229   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
230 whenN(InputIterator first, InputIterator last, size_t n);
231
232 }} // folly::wangle
233
234 #include "Future-inl.h"
235
236 /*
237
238 TODO
239
240 I haven't included a Future<T&> specialization because I don't forsee us
241 using it, however it is not difficult to add when needed. Refer to
242 Future<void> for guidance. std::Future and boost::Future code would also be
243 instructive.
244
245 I think that this might be a good candidate for folly, once it has baked for
246 awhile.
247
248 */