2 * Copyright 2015 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <folly/futures/Future.h>
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"
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
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);
42 /// Create a Future chain from a sequence of callbacks. i.e.
44 /// f.then(a).then(b).then(c);
46 /// where f is a Future<A> and the result of the chain is a Future<Z>
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);
56 * Set func as the callback for each input Future and return a vector of
57 * Futures containing the results in the input order.
59 template <class It, class F,
60 class ItT = typename std::iterator_traits<It>::value_type,
62 = typename decltype(std::declval<ItT>().then(std::declval<F>()))::value_type>
63 std::vector<Future<Result>> map(It first, It last, F func);
65 // Sugar for the most common case
66 template <class Collection, class F>
67 auto map(Collection&& c, F&& func)
68 -> decltype(map(c.begin(), c.end(), func)) {
69 return map(c.begin(), c.end(), std::forward<F>(func));
75 Make a completed Future by moving in a value. e.g.
78 auto f = makeFuture(std::move(foo));
82 auto f = makeFuture<string>("foo");
85 Future<typename std::decay<T>::type> makeFuture(T&& t);
87 /** Make a completed void Future. */
88 Future<void> makeFuture();
90 /** Make a completed Future by executing a function. If the function throws
91 we capture the exception, otherwise we capture the result. */
95 typename std::enable_if<
96 !std::is_reference<F>::value, bool>::type sdf = false)
97 -> Future<decltype(func())>;
102 -> Future<decltype(func())>;
104 /// Make a failed Future from an exception_ptr.
105 /// Because the Future's type cannot be inferred you have to specify it, e.g.
107 /// auto f = makeFuture<string>(std::current_exception());
109 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
111 /// Make a failed Future from an exception_wrapper.
113 Future<T> makeFuture(exception_wrapper ew);
115 /** Make a Future from an exception type E that can be passed to
116 std::make_exception_ptr(). */
117 template <class T, class E>
118 typename std::enable_if<std::is_base_of<std::exception, E>::value,
120 makeFuture(E const& e);
122 /** Make a Future out of a Try */
124 Future<T> makeFuture(Try<T>&& t);
127 * Return a new Future that will call back on the given Executor.
128 * This is just syntactic sugar for makeFuture().via(executor)
130 * @param executor the Executor to call back on
131 * @param priority optionally, the priority to add with. Defaults to 0 which
132 * represents medium priority.
134 * @returns a void Future that will call back on the given executor
136 inline Future<void> via(
138 int8_t priority = Executor::MID_PRI);
140 /** When all the input Futures complete, the returned Future will complete.
141 Errors do not cause early termination; this Future will always succeed
142 after all its Futures have finished (whether successfully or with an
145 The Futures are moved in, so your copies are invalid. If you need to
146 chain further from these Futures, use the variant with an output iterator.
148 This function is thread-safe for Futures running on different threads. But
149 if you are doing anything non-trivial after, you will probably want to
150 follow with `via(executor)` because it will complete in whichever thread the
151 last Future completes in.
153 The return type for Future<T> input is a Future<std::vector<Try<T>>>
155 template <class InputIterator>
156 Future<std::vector<Try<
157 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
158 collectAll(InputIterator first, InputIterator last);
160 /// Sugar for the most common case
161 template <class Collection>
162 auto collectAll(Collection&& c) -> decltype(collectAll(c.begin(), c.end())) {
163 return collectAll(c.begin(), c.end());
166 /// This version takes a varying number of Futures instead of an iterator.
167 /// The return type for (Future<T1>, Future<T2>, ...) input
168 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
169 /// The Futures are moved in, so your copies are invalid.
170 template <typename... Fs>
171 typename detail::VariadicContext<
172 typename std::decay<Fs>::type::value_type...>::type
173 collectAll(Fs&&... fs);
175 /// Like collectAll, but will short circuit on the first exception. Thus, the
176 /// type of the returned Future is std::vector<T> instead of
177 /// std::vector<Try<T>>
178 template <class InputIterator>
179 Future<typename detail::CollectContext<
180 typename std::iterator_traits<InputIterator>::value_type::value_type
182 collect(InputIterator first, InputIterator last);
184 /// Sugar for the most common case
185 template <class Collection>
186 auto collect(Collection&& c) -> decltype(collect(c.begin(), c.end())) {
187 return collect(c.begin(), c.end());
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.
194 This function is thread-safe for Futures running on different threads.
196 template <class InputIterator>
199 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
200 collectAny(InputIterator first, InputIterator last);
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());
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)
214 template <class InputIterator>
215 Future<std::vector<std::pair<
217 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
218 collectN(InputIterator first, InputIterator last, size_t n);
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);
227 template <typename F, typename T, typename ItT>
228 using MaybeTryArg = typename std::conditional<
229 detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
231 template<typename F, typename T, typename Arg>
232 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
234 /** repeatedly calls func on every result, e.g.
235 reduce(reduce(reduce(T initial, result of first), result of second), ...)
237 The type of the final result is a Future of the type of the initial value.
239 Func can either return a T, or a Future<T>
241 template <class It, class T, class F>
242 Future<T> reduce(It first, It last, T&& initial, F&& func);
244 /// Sugar for the most common case
245 template <class Collection, class T, class F>
246 auto reduce(Collection&& c, T&& initial, F&& func)
247 -> decltype(reduce(c.begin(), c.end(), std::forward<T>(initial),
248 std::forward<F>(func))) {
252 std::forward<T>(initial),
253 std::forward<F>(func));