2 * Copyright 2017 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.
22 #include <folly/Portability.h>
23 #include <folly/Try.h>
24 #include <folly/futures/Future.h>
25 #include <folly/futures/Promise.h>
31 template <typename... Ts>
32 struct CollectAllVariadicContext {
33 CollectAllVariadicContext() {}
34 template <typename T, size_t I>
35 inline void setPartialResult(Try<T>& t) {
36 std::get<I>(results) = std::move(t);
38 ~CollectAllVariadicContext() {
39 p.setValue(std::move(results));
41 Promise<std::tuple<Try<Ts>...>> p;
42 std::tuple<Try<Ts>...> results;
43 typedef Future<std::tuple<Try<Ts>...>> type;
46 template <typename... Ts>
47 struct CollectVariadicContext {
48 CollectVariadicContext() {}
49 template <typename T, size_t I>
50 inline void setPartialResult(Try<T>& t) {
51 if (t.hasException()) {
52 if (!threw.exchange(true)) {
53 p.setException(std::move(t.exception()));
56 std::get<I>(results) = std::move(t);
59 ~CollectVariadicContext() noexcept {
60 if (!threw.exchange(true)) {
61 p.setValue(unwrapTryTuple(std::move(results)));
64 Promise<std::tuple<Ts...>> p;
65 std::tuple<folly::Try<Ts>...> results;
66 std::atomic<bool> threw{false};
67 typedef Future<std::tuple<Ts...>> type;
70 } // namespace futures
72 /// This namespace is for utility functions that would usually be static
73 /// members of Future, except they don't make sense there because they don't
74 /// depend on the template type (rather, on the type of their arguments in
75 /// some cases). This is the least-bad naming scheme we could think of. Some
76 /// of the functions herein have really-likely-to-collide names, like "map"
79 /// Returns a Future that will complete after the specified duration. The
80 /// Duration typedef of a `std::chrono` duration type indicates the
81 /// resolution you can expect to be meaningful (milliseconds at the time of
82 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
83 /// use the global futures timekeeper (we run a thread whose job it is to
84 /// keep time for futures timeouts) but we provide the option for power
87 /// The Timekeeper thread will be lazily created the first time it is
88 /// needed. If your program never uses any timeouts or other time-based
89 /// Futures you will pay no Timekeeper thread overhead.
90 Future<Unit> sleep(Duration, Timekeeper* = nullptr);
93 * Set func as the callback for each input Future and return a vector of
94 * Futures containing the results in the input order.
99 class ItT = typename std::iterator_traits<It>::value_type,
100 class Result = typename decltype(
101 std::declval<ItT>().then(std::declval<F>()))::value_type>
102 std::vector<Future<Result>> map(It first, It last, F func);
104 // Sugar for the most common case
105 template <class Collection, class F>
106 auto map(Collection&& c, F&& func)
107 -> decltype(map(c.begin(), c.end(), func)) {
108 return map(c.begin(), c.end(), std::forward<F>(func));
111 } // namespace futures
114 Make a completed SemiFuture by moving in a value. e.g.
117 auto f = makeSemiFuture(std::move(foo));
121 auto f = makeSemiFuture<string>("foo");
124 SemiFuture<typename std::decay<T>::type> makeSemiFuture(T&& t);
126 /** Make a completed void SemiFuture. */
127 SemiFuture<Unit> makeSemiFuture();
130 Make a SemiFuture by executing a function.
132 If the function returns a value of type T, makeSemiFutureWith
133 returns a completed SemiFuture<T>, capturing the value returned
136 If the function returns a SemiFuture<T> already, makeSemiFutureWith
139 Either way, if the function throws, a failed Future is
140 returned that captures the exception.
143 // makeSemiFutureWith(SemiFuture<T>()) -> SemiFuture<T>
145 typename std::enable_if<isSemiFuture<typename std::result_of<F()>::type>::value,
146 typename std::result_of<F()>::type>::type
147 makeSemiFutureWith(F&& func);
149 // makeSemiFutureWith(T()) -> SemiFuture<T>
150 // makeSemiFutureWith(void()) -> SemiFuture<Unit>
152 typename std::enable_if<
153 !(isSemiFuture<typename std::result_of<F()>::type>::value),
154 SemiFuture<typename Unit::Lift<typename std::result_of<F()>::type>::type>>::type
155 makeSemiFutureWith(F&& func);
157 /// Make a failed Future from an exception_ptr.
158 /// Because the Future's type cannot be inferred you have to specify it, e.g.
160 /// auto f = makeSemiFuture<string>(std::current_exception());
162 FOLLY_DEPRECATED("use makeSemiFuture(exception_wrapper)")
163 SemiFuture<T> makeSemiFuture(std::exception_ptr const& e);
165 /// Make a failed SemiFuture from an exception_wrapper.
167 SemiFuture<T> makeSemiFuture(exception_wrapper ew);
169 /** Make a SemiFuture from an exception type E that can be passed to
170 std::make_exception_ptr(). */
171 template <class T, class E>
172 typename std::enable_if<std::is_base_of<std::exception, E>::value,
174 makeSemiFuture(E const& e);
176 /** Make a Future out of a Try */
178 SemiFuture<T> makeSemiFuture(Try<T>&& t);
181 Make a completed Future by moving in a value. e.g.
184 auto f = makeFuture(std::move(foo));
188 auto f = makeFuture<string>("foo");
191 Future<typename std::decay<T>::type> makeFuture(T&& t);
193 /** Make a completed void Future. */
194 Future<Unit> makeFuture();
197 Make a Future by executing a function.
199 If the function returns a value of type T, makeFutureWith
200 returns a completed Future<T>, capturing the value returned
203 If the function returns a Future<T> already, makeFutureWith
206 Either way, if the function throws, a failed Future is
207 returned that captures the exception.
209 Calling makeFutureWith(func) is equivalent to calling
210 makeFuture().then(func).
213 // makeFutureWith(Future<T>()) -> Future<T>
215 typename std::enable_if<isFuture<typename std::result_of<F()>::type>::value,
216 typename std::result_of<F()>::type>::type
217 makeFutureWith(F&& func);
219 // makeFutureWith(T()) -> Future<T>
220 // makeFutureWith(void()) -> Future<Unit>
222 typename std::enable_if<
223 !(isFuture<typename std::result_of<F()>::type>::value),
224 Future<typename Unit::Lift<typename std::result_of<F()>::type>::type>>::type
225 makeFutureWith(F&& func);
227 /// Make a failed Future from an exception_ptr.
228 /// Because the Future's type cannot be inferred you have to specify it, e.g.
230 /// auto f = makeFuture<string>(std::current_exception());
232 FOLLY_DEPRECATED("use makeFuture(exception_wrapper)")
233 Future<T> makeFuture(std::exception_ptr const& e);
235 /// Make a failed Future from an exception_wrapper.
237 Future<T> makeFuture(exception_wrapper ew);
239 /** Make a Future from an exception type E that can be passed to
240 std::make_exception_ptr(). */
241 template <class T, class E>
242 typename std::enable_if<std::is_base_of<std::exception, E>::value,
244 makeFuture(E const& e);
246 /** Make a Future out of a Try */
248 Future<T> makeFuture(Try<T>&& t);
251 * Return a new Future that will call back on the given Executor.
252 * This is just syntactic sugar for makeFuture().via(executor)
254 * @param executor the Executor to call back on
255 * @param priority optionally, the priority to add with. Defaults to 0 which
256 * represents medium priority.
258 * @returns a void Future that will call back on the given executor
260 inline Future<Unit> via(
262 int8_t priority = Executor::MID_PRI);
264 /// Execute a function via the given executor and return a future.
265 /// This is semantically equivalent to via(executor).then(func), but
266 /// easier to read and slightly more efficient.
267 template <class Func>
268 auto via(Executor*, Func&& func)
269 -> Future<typename isFuture<decltype(std::declval<Func>()())>::Inner>;
271 /** When all the input Futures complete, the returned Future will complete.
272 Errors do not cause early termination; this Future will always succeed
273 after all its Futures have finished (whether successfully or with an
276 The Futures are moved in, so your copies are invalid. If you need to
277 chain further from these Futures, use the variant with an output iterator.
279 This function is thread-safe for Futures running on different threads. But
280 if you are doing anything non-trivial after, you will probably want to
281 follow with `via(executor)` because it will complete in whichever thread the
282 last Future completes in.
284 The return type for Future<T> input is a Future<std::vector<Try<T>>>
286 template <class InputIterator>
287 Future<std::vector<Try<
288 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
289 collectAll(InputIterator first, InputIterator last);
291 /// Sugar for the most common case
292 template <class Collection>
293 auto collectAll(Collection&& c) -> decltype(collectAll(c.begin(), c.end())) {
294 return collectAll(c.begin(), c.end());
297 /// This version takes a varying number of Futures instead of an iterator.
298 /// The return type for (Future<T1>, Future<T2>, ...) input
299 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
300 /// The Futures are moved in, so your copies are invalid.
301 template <typename... Fs>
302 typename futures::detail::CollectAllVariadicContext<
303 typename std::decay<Fs>::type::value_type...>::type
304 collectAll(Fs&&... fs);
306 /// Like collectAll, but will short circuit on the first exception. Thus, the
307 /// type of the returned Future is std::vector<T> instead of
308 /// std::vector<Try<T>>
309 template <class InputIterator>
310 Future<typename futures::detail::CollectContext<typename std::iterator_traits<
311 InputIterator>::value_type::value_type>::result_type>
312 collect(InputIterator first, InputIterator last);
314 /// Sugar for the most common case
315 template <class Collection>
316 auto collect(Collection&& c) -> decltype(collect(c.begin(), c.end())) {
317 return collect(c.begin(), c.end());
320 /// Like collectAll, but will short circuit on the first exception. Thus, the
321 /// type of the returned Future is std::tuple<T1, T2, ...> instead of
322 /// std::tuple<Try<T1>, Try<T2>, ...>
323 template <typename... Fs>
324 typename futures::detail::CollectVariadicContext<
325 typename std::decay<Fs>::type::value_type...>::type
328 /** The result is a pair of the index of the first Future to complete and
329 the Try. If multiple Futures complete at the same time (or are already
330 complete when passed in), the "winner" is chosen non-deterministically.
332 This function is thread-safe for Futures running on different threads.
334 template <class InputIterator>
337 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
338 collectAny(InputIterator first, InputIterator last);
340 /// Sugar for the most common case
341 template <class Collection>
342 auto collectAny(Collection&& c) -> decltype(collectAny(c.begin(), c.end())) {
343 return collectAny(c.begin(), c.end());
346 /** Similar to collectAny, collectAnyWithoutException return the first Future to
347 * complete without exceptions. If none of the future complete without
348 * excpetions, the last exception will be returned as a result.
350 template <class InputIterator>
353 typename std::iterator_traits<InputIterator>::value_type::value_type>>
354 collectAnyWithoutException(InputIterator first, InputIterator last);
356 /// Sugar for the most common case
357 template <class Collection>
358 auto collectAnyWithoutException(Collection&& c)
359 -> decltype(collectAnyWithoutException(c.begin(), c.end())) {
360 return collectAnyWithoutException(c.begin(), c.end());
363 /** when n Futures have completed, the Future completes with a vector of
364 the index and Try of those n Futures (the indices refer to the original
365 order, but the result vector will be in an arbitrary order)
369 template <class InputIterator>
370 Future<std::vector<std::pair<
372 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
373 collectN(InputIterator first, InputIterator last, size_t n);
375 /// Sugar for the most common case
376 template <class Collection>
377 auto collectN(Collection&& c, size_t n)
378 -> decltype(collectN(c.begin(), c.end(), n)) {
379 return collectN(c.begin(), c.end(), n);
382 /** window creates up to n Futures using the values
383 in the collection, and then another Future for each Future
386 this is basically a sliding window of Futures of size n
388 func must return a Future for each value in input
393 class ItT = typename std::iterator_traits<
394 typename Collection::iterator>::value_type,
395 class Result = typename futures::detail::resultOf<F, ItT&&>::value_type>
396 std::vector<Future<Result>> window(Collection input, F func, size_t n);
401 class ItT = typename std::iterator_traits<
402 typename Collection::iterator>::value_type,
403 class Result = typename futures::detail::resultOf<F, ItT&&>::value_type>
404 std::vector<Future<Result>>
405 window(Executor* executor, Collection input, F func, size_t n);
407 template <typename F, typename T, typename ItT>
408 using MaybeTryArg = typename std::conditional<
409 futures::detail::callableWith<F, T&&, Try<ItT>&&>::value,
413 template <typename F, typename T, typename Arg>
414 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
416 /** repeatedly calls func on every result, e.g.
417 reduce(reduce(reduce(T initial, result of first), result of second), ...)
419 The type of the final result is a Future of the type of the initial value.
421 Func can either return a T, or a Future<T>
423 func is called in order of the input, see unorderedReduce if that is not
426 template <class It, class T, class F>
427 Future<T> reduce(It first, It last, T&& initial, F&& func);
429 /// Sugar for the most common case
430 template <class Collection, class T, class F>
431 auto reduce(Collection&& c, T&& initial, F&& func)
432 -> decltype(reduce(c.begin(), c.end(), std::forward<T>(initial),
433 std::forward<F>(func))) {
437 std::forward<T>(initial),
438 std::forward<F>(func));
441 /** like reduce, but calls func on finished futures as they complete
442 does NOT keep the order of the input
448 class ItT = typename std::iterator_traits<It>::value_type::value_type,
449 class Arg = MaybeTryArg<F, T, ItT>>
450 Future<T> unorderedReduce(It first, It last, T initial, F func);
452 /// Sugar for the most common case
453 template <class Collection, class T, class F>
454 auto unorderedReduce(Collection&& c, T&& initial, F&& func)
455 -> decltype(unorderedReduce(c.begin(), c.end(), std::forward<T>(initial),
456 std::forward<F>(func))) {
457 return unorderedReduce(
460 std::forward<T>(initial),
461 std::forward<F>(func));