Nuke Future<void> (folly/futures)
[folly.git] / folly / futures / helpers.h
1 /*
2  * Copyright 2015 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 #pragma once
17
18 #include <folly/futures/Future.h>
19
20 namespace folly {
21
22 /// This namespace is for utility functions that would usually be static
23 /// members of Future, except they don't make sense there because they don't
24 /// depend on the template type (rather, on the type of their arguments in
25 /// some cases). This is the least-bad naming scheme we could think of. Some
26 /// of the functions herein have really-likely-to-collide names, like "map"
27 /// and "sleep".
28 namespace futures {
29   /// Returns a Future that will complete after the specified duration. The
30   /// Duration typedef of a `std::chrono` duration type indicates the
31   /// resolution you can expect to be meaningful (milliseconds at the time of
32   /// writing). Normally you wouldn't need to specify a Timekeeper, we will
33   /// use the global futures timekeeper (we run a thread whose job it is to
34   /// keep time for futures timeouts) but we provide the option for power
35   /// users.
36   ///
37   /// The Timekeeper thread will be lazily created the first time it is
38   /// needed. If your program never uses any timeouts or other time-based
39   /// Futures you will pay no Timekeeper thread overhead.
40   Future<Unit> sleep(Duration, Timekeeper* = nullptr);
41
42   /**
43    * Set func as the callback for each input Future and return a vector of
44    * Futures containing the results in the input order.
45    */
46   template <class It, class F,
47             class ItT = typename std::iterator_traits<It>::value_type,
48             class Result
49       = typename decltype(std::declval<ItT>().then(std::declval<F>()))::value_type>
50   std::vector<Future<Result>> map(It first, It last, F func);
51
52   // Sugar for the most common case
53   template <class Collection, class F>
54   auto map(Collection&& c, F&& func)
55       -> decltype(map(c.begin(), c.end(), func)) {
56     return map(c.begin(), c.end(), std::forward<F>(func));
57   }
58
59 } // namespace futures
60
61 /**
62   Make a completed Future by moving in a value. e.g.
63
64     string foo = "foo";
65     auto f = makeFuture(std::move(foo));
66
67   or
68
69     auto f = makeFuture<string>("foo");
70 */
71 template <class T>
72 Future<typename std::decay<T>::type> makeFuture(T&& t);
73
74 /** Make a completed void Future. */
75 Future<Unit> makeFuture();
76
77 /** Make a completed Future by executing a function. If the function throws
78   we capture the exception, otherwise we capture the result. */
79 template <class F>
80 auto makeFutureWith(
81     F&& func,
82     typename std::enable_if<!std::is_reference<F>::value, bool>::type sdf)
83     -> Future<typename Unit::Lift<decltype(func())>::type>;
84
85 template <class F>
86 auto makeFutureWith(F const& func)
87     -> Future<typename Unit::Lift<decltype(func())>::type>;
88
89 /// Make a failed Future from an exception_ptr.
90 /// Because the Future's type cannot be inferred you have to specify it, e.g.
91 ///
92 ///   auto f = makeFuture<string>(std::current_exception());
93 template <class T>
94 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
95
96 /// Make a failed Future from an exception_wrapper.
97 template <class T>
98 Future<T> makeFuture(exception_wrapper ew);
99
100 /** Make a Future from an exception type E that can be passed to
101   std::make_exception_ptr(). */
102 template <class T, class E>
103 typename std::enable_if<std::is_base_of<std::exception, E>::value,
104                         Future<T>>::type
105 makeFuture(E const& e);
106
107 /** Make a Future out of a Try */
108 template <class T>
109 Future<T> makeFuture(Try<T>&& t);
110
111 /*
112  * Return a new Future that will call back on the given Executor.
113  * This is just syntactic sugar for makeFuture().via(executor)
114  *
115  * @param executor the Executor to call back on
116  * @param priority optionally, the priority to add with. Defaults to 0 which
117  * represents medium priority.
118  *
119  * @returns a void Future that will call back on the given executor
120  */
121 inline Future<Unit> via(
122     Executor* executor,
123     int8_t priority = Executor::MID_PRI);
124
125 /// Execute a function via the given executor and return a future.
126 /// This is semantically equivalent to via(executor).then(func), but
127 /// easier to read and slightly more efficient.
128 template <class Func>
129 auto via(Executor*, Func func)
130   -> Future<typename isFuture<decltype(func())>::Inner>;
131
132 /** When all the input Futures complete, the returned Future will complete.
133   Errors do not cause early termination; this Future will always succeed
134   after all its Futures have finished (whether successfully or with an
135   error).
136
137   The Futures are moved in, so your copies are invalid. If you need to
138   chain further from these Futures, use the variant with an output iterator.
139
140   This function is thread-safe for Futures running on different threads. But
141   if you are doing anything non-trivial after, you will probably want to
142   follow with `via(executor)` because it will complete in whichever thread the
143   last Future completes in.
144
145   The return type for Future<T> input is a Future<std::vector<Try<T>>>
146   */
147 template <class InputIterator>
148 Future<std::vector<Try<
149   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
150 collectAll(InputIterator first, InputIterator last);
151
152 /// Sugar for the most common case
153 template <class Collection>
154 auto collectAll(Collection&& c) -> decltype(collectAll(c.begin(), c.end())) {
155   return collectAll(c.begin(), c.end());
156 }
157
158 /// This version takes a varying number of Futures instead of an iterator.
159 /// The return type for (Future<T1>, Future<T2>, ...) input
160 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
161 /// The Futures are moved in, so your copies are invalid.
162 template <typename... Fs>
163 typename detail::CollectAllVariadicContext<
164   typename std::decay<Fs>::type::value_type...>::type
165 collectAll(Fs&&... fs);
166
167 /// Like collectAll, but will short circuit on the first exception. Thus, the
168 /// type of the returned Future is std::vector<T> instead of
169 /// std::vector<Try<T>>
170 template <class InputIterator>
171 Future<typename detail::CollectContext<
172   typename std::iterator_traits<InputIterator>::value_type::value_type
173 >::result_type>
174 collect(InputIterator first, InputIterator last);
175
176 /// Sugar for the most common case
177 template <class Collection>
178 auto collect(Collection&& c) -> decltype(collect(c.begin(), c.end())) {
179   return collect(c.begin(), c.end());
180 }
181
182 /// Like collectAll, but will short circuit on the first exception. Thus, the
183 /// type of the returned Future is std::tuple<T1, T2, ...> instead of
184 /// std::tuple<Try<T1>, Try<T2>, ...>
185 template <typename... Fs>
186 typename detail::CollectVariadicContext<
187   typename std::decay<Fs>::type::value_type...>::type
188 collect(Fs&&... fs);
189
190 /** The result is a pair of the index of the first Future to complete and
191   the Try. If multiple Futures complete at the same time (or are already
192   complete when passed in), the "winner" is chosen non-deterministically.
193
194   This function is thread-safe for Futures running on different threads.
195   */
196 template <class InputIterator>
197 Future<std::pair<
198   size_t,
199   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
200 collectAny(InputIterator first, InputIterator last);
201
202 /// Sugar for the most common case
203 template <class Collection>
204 auto collectAny(Collection&& c) -> decltype(collectAny(c.begin(), c.end())) {
205   return collectAny(c.begin(), c.end());
206 }
207
208 /** when n Futures have completed, the Future completes with a vector of
209   the index and Try of those n Futures (the indices refer to the original
210   order, but the result vector will be in an arbitrary order)
211
212   Not thread safe.
213   */
214 template <class InputIterator>
215 Future<std::vector<std::pair<
216   size_t,
217   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
218 collectN(InputIterator first, InputIterator last, size_t n);
219
220 /// Sugar for the most common case
221 template <class Collection>
222 auto collectN(Collection&& c, size_t n)
223     -> decltype(collectN(c.begin(), c.end(), n)) {
224   return collectN(c.begin(), c.end(), n);
225 }
226
227 /** window creates up to n Futures using the values
228     in the collection, and then another Future for each Future
229     that completes
230
231     this is basically a sliding window of Futures of size n
232
233     func must return a Future for each value in input
234   */
235 template <class Collection, class F,
236           class ItT = typename std::iterator_traits<
237             typename Collection::iterator>::value_type,
238           class Result = typename detail::resultOf<F, ItT&&>::value_type>
239 std::vector<Future<Result>>
240 window(Collection input, F func, size_t n);
241
242 template <typename F, typename T, typename ItT>
243 using MaybeTryArg = typename std::conditional<
244   detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
245
246 template<typename F, typename T, typename Arg>
247 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
248
249 /** repeatedly calls func on every result, e.g.
250     reduce(reduce(reduce(T initial, result of first), result of second), ...)
251
252     The type of the final result is a Future of the type of the initial value.
253
254     Func can either return a T, or a Future<T>
255
256     func is called in order of the input, see unorderedReduce if that is not
257     a requirement
258   */
259 template <class It, class T, class F>
260 Future<T> reduce(It first, It last, T&& initial, F&& func);
261
262 /// Sugar for the most common case
263 template <class Collection, class T, class F>
264 auto reduce(Collection&& c, T&& initial, F&& func)
265     -> decltype(reduce(c.begin(), c.end(), std::forward<T>(initial),
266                 std::forward<F>(func))) {
267   return reduce(
268       c.begin(),
269       c.end(),
270       std::forward<T>(initial),
271       std::forward<F>(func));
272 }
273
274 /** like reduce, but calls func on finished futures as they complete
275     does NOT keep the order of the input
276   */
277 template <class It, class T, class F,
278           class ItT = typename std::iterator_traits<It>::value_type::value_type,
279           class Arg = MaybeTryArg<F, T, ItT>>
280 Future<T> unorderedReduce(It first, It last, T initial, F func);
281
282 /// Sugar for the most common case
283 template <class Collection, class T, class F>
284 auto unorderedReduce(Collection&& c, T&& initial, F&& func)
285     -> decltype(unorderedReduce(c.begin(), c.end(), std::forward<T>(initial),
286                 std::forward<F>(func))) {
287   return unorderedReduce(
288       c.begin(),
289       c.end(),
290       std::forward<T>(initial),
291       std::forward<F>(func));
292 }
293
294 } // namespace