Move this `reduce` to `helpers.h`
[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<void> sleep(Duration, Timekeeper* = nullptr);
41
42   /// Create a Future chain from a sequence of callbacks. i.e.
43   ///
44   ///   f.then(a).then(b).then(c);
45   ///
46   /// where f is a Future<A> and the result of the chain is a Future<Z>
47   /// becomes
48   ///
49   ///   f.then(chain<A,Z>(a, b, c));
50   // If anyone figures how to get chain to deduce A and Z, I'll buy you a drink.
51   template <class A, class Z, class... Callbacks>
52   std::function<Future<Z>(Try<A>)>
53   chain(Callbacks... fns);
54
55   /**
56    * Set func as the callback for each input Future and return a vector of
57    * Futures containing the results in the input order.
58    */
59   template <class It, class F,
60             class ItT = typename std::iterator_traits<It>::value_type,
61             class Result = decltype(std::declval<ItT>().then(std::declval<F>()))>
62   std::vector<Future<Result>> map(It first, It last, F func);
63
64   // Sugar for the most common case
65   template <class Collection, class F>
66   auto map(Collection&& c, F&& func)
67       -> decltype(map(c.begin(), c.end(), func)) {
68     return map(c.begin(), c.end(), std::forward<F>(func));
69   }
70
71 }
72
73 /**
74   Make a completed Future by moving in a value. e.g.
75
76     string foo = "foo";
77     auto f = makeFuture(std::move(foo));
78
79   or
80
81     auto f = makeFuture<string>("foo");
82 */
83 template <class T>
84 Future<typename std::decay<T>::type> makeFuture(T&& t);
85
86 /** Make a completed void Future. */
87 Future<void> makeFuture();
88
89 /** Make a completed Future by executing a function. If the function throws
90   we capture the exception, otherwise we capture the result. */
91 template <class F>
92 auto makeFutureWith(
93   F&& func,
94   typename std::enable_if<
95     !std::is_reference<F>::value, bool>::type sdf = false)
96   -> Future<decltype(func())>;
97
98 template <class F>
99 auto makeFutureWith(
100   F const& func)
101   -> Future<decltype(func())>;
102
103 /// Make a failed Future from an exception_ptr.
104 /// Because the Future's type cannot be inferred you have to specify it, e.g.
105 ///
106 ///   auto f = makeFuture<string>(std::current_exception());
107 template <class T>
108 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
109
110 /// Make a failed Future from an exception_wrapper.
111 template <class T>
112 Future<T> makeFuture(exception_wrapper ew);
113
114 /** Make a Future from an exception type E that can be passed to
115   std::make_exception_ptr(). */
116 template <class T, class E>
117 typename std::enable_if<std::is_base_of<std::exception, E>::value,
118                         Future<T>>::type
119 makeFuture(E const& e);
120
121 /** Make a Future out of a Try */
122 template <class T>
123 Future<T> makeFuture(Try<T>&& t);
124
125 /*
126  * Return a new Future that will call back on the given Executor.
127  * This is just syntactic sugar for makeFuture().via(executor)
128  *
129  * @param executor the Executor to call back on
130  *
131  * @returns a void Future that will call back on the given executor
132  */
133 template <typename Executor>
134 Future<void> via(Executor* executor);
135
136 /** When all the input Futures complete, the returned Future will complete.
137   Errors do not cause early termination; this Future will always succeed
138   after all its Futures have finished (whether successfully or with an
139   error).
140
141   The Futures are moved in, so your copies are invalid. If you need to
142   chain further from these Futures, use the variant with an output iterator.
143
144   This function is thread-safe for Futures running on different threads. But
145   if you are doing anything non-trivial after, you will probably want to
146   follow with `via(executor)` because it will complete in whichever thread the
147   last Future completes in.
148
149   The return type for Future<T> input is a Future<std::vector<Try<T>>>
150   */
151 template <class InputIterator>
152 Future<std::vector<Try<
153   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
154 collectAll(InputIterator first, InputIterator last);
155
156 /// Sugar for the most common case
157 template <class Collection>
158 auto collectAll(Collection&& c) -> decltype(collectAll(c.begin(), c.end())) {
159   return collectAll(c.begin(), c.end());
160 }
161
162 /// This version takes a varying number of Futures instead of an iterator.
163 /// The return type for (Future<T1>, Future<T2>, ...) input
164 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
165 /// The Futures are moved in, so your copies are invalid.
166 template <typename... Fs>
167 typename detail::VariadicContext<
168   typename std::decay<Fs>::type::value_type...>::type
169 collectAll(Fs&&... fs);
170
171 /// Like collectAll, but will short circuit on the first exception. Thus, the
172 /// type of the returned Future is std::vector<T> instead of
173 /// std::vector<Try<T>>
174 template <class InputIterator>
175 Future<typename detail::CollectContext<
176   typename std::iterator_traits<InputIterator>::value_type::value_type
177 >::result_type>
178 collect(InputIterator first, InputIterator last);
179
180 /// Sugar for the most common case
181 template <class Collection>
182 auto collect(Collection&& c) -> decltype(collect(c.begin(), c.end())) {
183   return collect(c.begin(), c.end());
184 }
185
186 /** The result is a pair of the index of the first Future to complete and
187   the Try. If multiple Futures complete at the same time (or are already
188   complete when passed in), the "winner" is chosen non-deterministically.
189
190   This function is thread-safe for Futures running on different threads.
191   */
192 template <class InputIterator>
193 Future<std::pair<
194   size_t,
195   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
196 collectAny(InputIterator first, InputIterator last);
197
198 /// Sugar for the most common case
199 template <class Collection>
200 auto collectAny(Collection&& c) -> decltype(collectAny(c.begin(), c.end())) {
201   return collectAny(c.begin(), c.end());
202 }
203
204 /** when n Futures have completed, the Future completes with a vector of
205   the index and Try of those n Futures (the indices refer to the original
206   order, but the result vector will be in an arbitrary order)
207
208   Not thread safe.
209   */
210 template <class InputIterator>
211 Future<std::vector<std::pair<
212   size_t,
213   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
214 collectN(InputIterator first, InputIterator last, size_t n);
215
216 /// Sugar for the most common case
217 template <class Collection>
218 auto collectN(Collection&& c, size_t n)
219     -> decltype(collectN(c.begin(), c.end(), n)) {
220   return collectN(c.begin(), c.end(), n);
221 }
222
223 template <typename F, typename T, typename ItT>
224 using MaybeTryArg = typename std::conditional<
225   detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
226
227 template<typename F, typename T, typename Arg>
228 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
229
230 /** repeatedly calls func on every result, e.g.
231     reduce(reduce(reduce(T initial, result of first), result of second), ...)
232
233     The type of the final result is a Future of the type of the initial value.
234
235     Func can either return a T, or a Future<T>
236   */
237 template <class It, class T, class F,
238           class ItT = typename std::iterator_traits<It>::value_type::value_type,
239           class Arg = MaybeTryArg<F, T, ItT>>
240 typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
241 reduce(It first, It last, T initial, F func);
242
243 template <class It, class T, class F,
244           class ItT = typename std::iterator_traits<It>::value_type::value_type,
245           class Arg = MaybeTryArg<F, T, ItT>>
246 typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
247 reduce(It first, It last, T initial, F func);
248
249 /// Sugar for the most common case
250 template <class Collection, class T, class F>
251 auto reduce(Collection&& c, T&& initial, F&& func)
252     -> decltype(reduce(c.begin(), c.end(), initial, func)) {
253   return reduce(
254       c.begin(),
255       c.end(),
256       std::forward<T>(initial),
257       std::forward<F>(func));
258 }
259
260 } // namespace folly