(wangle) comment cleanup
[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. */
79   bool isReady() const;
80
81   /** A reference to the Try of the value */
82   Try<T>& getTry();
83
84   /** When this Future has completed, execute func which is a function that
85     takes a Try<T>&&. A Future for the return type of func is
86     returned. e.g.
87
88     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
89
90     The Future given to the functor is ready, and the functor may call
91     value(), which may rethrow if this has captured an exception. If func
92     throws, the exception will be captured in the Future that is returned.
93     */
94   /* TODO n3428 and other async frameworks have something like then(scheduler,
95      Future), we probably want to support a similar API (instead of
96      executeWith). */
97   template <class F>
98   typename std::enable_if<
99     !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
100     Future<typename std::result_of<F(Try<T>&&)>::type> >::type
101   then(F&& func);
102
103   /// Variant where func returns a future<T> instead of a T. e.g.
104   ///
105   ///   Future<string> f2 = f1.then(
106   ///     [](Try<T>&&) { return makeFuture<string>("foo"); });
107   template <class F>
108   typename std::enable_if<
109     isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
110     Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
111   then(F&& func);
112
113   /// Convenience method for ignoring the value and creating a Future<void>.
114   /// Exceptions still propagate.
115   Future<void> then();
116
117   /// Use of this method is advanced wizardry.
118   /// XXX should this be protected?
119   template <class F>
120   void setContinuation(F&& func);
121
122  private:
123   typedef detail::FutureObject<T>* objPtr;
124
125   // shared state object
126   objPtr obj_;
127
128   explicit
129   Future(objPtr obj) : obj_(obj) {}
130
131   void throwIfInvalid() const;
132
133   friend class Promise<T>;
134 };
135
136 /**
137   Make a completed Future by moving in a value. e.g.
138
139     string foo = "foo";
140     auto f = makeFuture(std::move(foo));
141
142   or
143
144     auto f = makeFuture<string>("foo");
145 */
146 template <class T>
147 Future<typename std::decay<T>::type> makeFuture(T&& t);
148
149 /** Make a completed void Future. */
150 Future<void> makeFuture();
151
152 /** Make a completed Future by executing a function. If the function throws
153   we capture the exception, otherwise we capture the result. */
154 template <class F>
155 auto makeFutureTry(
156   F&& func,
157   typename std::enable_if<
158     !std::is_reference<F>::value, bool>::type sdf = false)
159   -> Future<decltype(func())>;
160
161 template <class F>
162 auto makeFutureTry(
163   F const& func)
164   -> Future<decltype(func())>;
165
166 /// Make a failed Future from an exception_ptr.
167 /// Because the Future's type cannot be inferred you have to specify it, e.g.
168 ///
169 ///   auto f = makeFuture<string>(std::current_exception());
170 template <class T>
171 Future<T> makeFuture(std::exception_ptr const& e);
172
173 /** Make a Future from an exception type E that can be passed to
174   std::make_exception_ptr(). */
175 template <class T, class E>
176 typename std::enable_if<std::is_base_of<std::exception, E>::value, Future<T>>::type
177 makeFuture(E const& e);
178
179 /** When all the input Futures complete, the returned Future will complete.
180   Errors do not cause early termination; this Future will always succeed
181   after all its Futures have finished (whether successfully or with an
182   error).
183
184   The Futures are moved in, so your copies are invalid. If you need to
185   chain further from these Futures, use the variant with an output iterator.
186
187   XXX is this still true?
188   This function is thread-safe for Futures running on different threads.
189
190   The return type for Future<T> input is a Future<std::vector<Try<T>>>
191   */
192 template <class InputIterator>
193 Future<std::vector<Try<
194   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
195 whenAll(InputIterator first, InputIterator last);
196
197 /// This version takes a varying number of Futures instead of an iterator.
198 /// The return type for (Future<T1>, Future<T2>, ...) input
199 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
200 // XXX why does it take Fs& instead of Fs&&?
201 template <typename... Fs>
202 typename detail::VariadicContext<typename Fs::value_type...>::type
203 whenAll(Fs&... fs);
204
205 /** The result is a pair of the index of the first Future to complete and
206   the Try. If multiple Futures complete at the same time (or are already
207   complete when passed in), the "winner" is chosen non-deterministically.
208
209   This function is thread-safe for Futures running on different threads.
210   */
211 template <class InputIterator>
212 Future<std::pair<
213   size_t,
214   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
215 whenAny(InputIterator first, InputIterator last);
216
217 /** when n Futures have completed, the Future completes with a vector of
218   the index and Try of those n Futures (the indices refer to the original
219   order, but the result vector will be in an arbitrary order)
220
221   Not thread safe.
222   */
223 template <class InputIterator>
224 Future<std::vector<std::pair<
225   size_t,
226   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
227 whenN(InputIterator first, InputIterator last, size_t n);
228
229 }} // folly::wangle
230
231 #include "Future-inl.h"