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.
23 #include <type_traits>
26 #include <folly/Optional.h>
27 #include <folly/MoveWrapper.h>
28 #include <folly/futures/Deprecated.h>
29 #include <folly/futures/DrivableExecutor.h>
30 #include <folly/futures/Promise.h>
31 #include <folly/futures/Try.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/detail/Types.h>
37 template <class> struct Promise;
40 struct isFuture : std::false_type {
45 struct isFuture<Future<T>> : std::true_type {
50 struct isTry : std::false_type {};
53 struct isTry<Try<T>> : std::true_type {};
57 template <class> struct Core;
58 template <class...> struct VariadicContext;
59 template <class> struct CollectContext;
61 template<typename F, typename... Args>
62 using resultOf = decltype(std::declval<F>()(std::declval<Args>()...));
64 template <typename...>
67 template <typename Arg, typename... Args>
68 struct ArgType<Arg, Args...> {
74 typedef void FirstArg;
77 template <bool isTry, typename F, typename... Args>
79 typedef resultOf<F, Args...> Result;
82 template<typename F, typename... Args>
85 typename = detail::resultOf<T, Args...>>
86 static constexpr std::true_type
87 check(std::nullptr_t) { return std::true_type{}; };
90 static constexpr std::false_type
91 check(...) { return std::false_type{}; };
93 typedef decltype(check<F>(nullptr)) type;
94 static constexpr bool value = type::value;
97 template<typename T, typename F>
98 struct callableResult {
99 typedef typename std::conditional<
100 callableWith<F>::value,
101 detail::argResult<false, F>,
102 typename std::conditional<
103 callableWith<F, T&&>::value,
104 detail::argResult<false, F, T&&>,
105 typename std::conditional<
106 callableWith<F, T&>::value,
107 detail::argResult<false, F, T&>,
108 typename std::conditional<
109 callableWith<F, Try<T>&&>::value,
110 detail::argResult<true, F, Try<T>&&>,
111 detail::argResult<true, F, Try<T>&>>::type>::type>::type>::type Arg;
112 typedef isFuture<typename Arg::Result> ReturnsFuture;
113 typedef Future<typename ReturnsFuture::Inner> Return;
117 struct callableResult<void, F> {
118 typedef typename std::conditional<
119 callableWith<F>::value,
120 detail::argResult<false, F>,
121 typename std::conditional<
122 callableWith<F, Try<void>&&>::value,
123 detail::argResult<true, F, Try<void>&&>,
124 detail::argResult<true, F, Try<void>&>>::type>::type Arg;
125 typedef isFuture<typename Arg::Result> ReturnsFuture;
126 typedef Future<typename ReturnsFuture::Inner> Return;
129 template <typename L>
130 struct Extract : Extract<decltype(&L::operator())> { };
132 template <typename Class, typename R, typename... Args>
133 struct Extract<R(Class::*)(Args...) const> {
134 typedef isFuture<R> ReturnsFuture;
135 typedef Future<typename ReturnsFuture::Inner> Return;
136 typedef typename ReturnsFuture::Inner RawReturn;
137 typedef typename ArgType<Args...>::FirstArg FirstArg;
140 template <typename Class, typename R, typename... Args>
141 struct Extract<R(Class::*)(Args...)> {
142 typedef isFuture<R> ReturnsFuture;
143 typedef Future<typename ReturnsFuture::Inner> Return;
144 typedef typename ReturnsFuture::Inner RawReturn;
145 typedef typename ArgType<Args...>::FirstArg FirstArg;
152 /// This namespace is for utility functions that would usually be static
153 /// members of Future, except they don't make sense there because they don't
154 /// depend on the template type (rather, on the type of their arguments in
155 /// some cases). This is the least-bad naming scheme we could think of. Some
156 /// of the functions herein have really-likely-to-collide names, like "map"
159 /// Returns a Future that will complete after the specified duration. The
160 /// Duration typedef of a `std::chrono` duration type indicates the
161 /// resolution you can expect to be meaningful (milliseconds at the time of
162 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
163 /// use the global futures timekeeper (we run a thread whose job it is to
164 /// keep time for futures timeouts) but we provide the option for power
167 /// The Timekeeper thread will be lazily created the first time it is
168 /// needed. If your program never uses any timeouts or other time-based
169 /// Futures you will pay no Timekeeper thread overhead.
170 Future<void> sleep(Duration, Timekeeper* = nullptr);
172 /// Create a Future chain from a sequence of callbacks. i.e.
174 /// f.then(a).then(b).then(c);
176 /// where f is a Future<A> and the result of the chain is a Future<Z>
179 /// f.then(chain<A,Z>(a, b, c));
180 // If anyone figures how to get chain to deduce A and Z, I'll buy you a drink.
181 template <class A, class Z, class... Callbacks>
182 std::function<Future<Z>(Try<A>)>
183 chain(Callbacks... fns);
186 * Set func as the callback for each input Future and return a vector of
187 * Futures containing the results in the input order.
189 template <class It, class F,
190 class ItT = typename std::iterator_traits<It>::value_type,
191 class Result = decltype(std::declval<ItT>().then(std::declval<F>()))>
192 std::vector<Future<Result>> map(It first, It last, F func);
199 typedef T value_type;
202 Future(Future const&) = delete;
203 Future& operator=(Future const&) = delete;
206 Future(Future&&) noexcept;
207 Future& operator=(Future&&) noexcept;
210 template <class F = T>
212 Future(const typename std::enable_if<!std::is_void<F>::value, F>::type& val);
214 template <class F = T>
216 Future(typename std::enable_if<!std::is_void<F>::value, F>::type&& val);
218 template <class F = T,
219 typename std::enable_if<std::is_void<F>::value, int>::type = 0>
224 /** Return the reference to result. Should not be called if !isReady().
225 Will rethrow the exception if an exception has been
228 typename std::add_lvalue_reference<T>::type
230 typename std::add_lvalue_reference<const T>::type
233 /// Returns an inactive Future which will call back on the other side of
234 /// executor (when it is activated).
236 /// NB remember that Futures activate when they destruct. This is good,
237 /// it means that this will work:
239 /// f.via(e).then(a).then(b);
241 /// a and b will execute in the same context (the far side of e), because
242 /// the Future (temporary variable) created by via(e) does not call back
243 /// until it destructs, which is after then(a) and then(b) have been wired
246 /// But this is still racy:
248 /// f = f.via(e).then(a);
250 // The ref-qualifier allows for `this` to be moved out so we
251 // don't get access-after-free situations in chaining.
252 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
253 template <typename Executor>
254 Future<T> via(Executor* executor) &&;
256 /// This variant creates a new future, where the ref-qualifier && version
257 /// moves `this` out. This one is less efficient but avoids confusing users
258 /// when "return f.via(x);" fails.
259 template <typename Executor>
260 Future<T> via(Executor* executor) &;
262 /** True when the result (or exception) is ready. */
263 bool isReady() const;
265 /** A reference to the Try of the value */
268 /// If the promise has been fulfilled, return an Optional with the Try<T>.
269 /// Otherwise return an empty Optional.
270 /// Note that this moves the Try<T> out.
271 Optional<Try<T>> poll();
273 /// Block until the future is fulfilled. Returns the value (moved out), or
274 /// throws the exception. The future must not already have a callback.
277 /// Block until the future is fulfilled, or until timed out. Returns the
278 /// value (moved out), or throws the exception (which might be a TimedOut
282 /// Call e->drive() repeatedly until the future is fulfilled. Examples
283 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
284 /// value (moved out), or throws the exception.
285 T getVia(DrivableExecutor* e);
287 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
288 /// Future<T> instance.
289 template <class F = T>
290 typename std::enable_if<isFuture<F>::value,
291 Future<typename isFuture<T>::Inner>>::type
294 /** When this Future has completed, execute func which is a function that
304 Func shall return either another Future or a value.
306 A Future for the return type of func is returned.
308 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
310 The Future given to the functor is ready, and the functor may call
311 value(), which may rethrow if this has captured an exception. If func
312 throws, the exception will be captured in the Future that is returned.
314 /* TODO n3428 and other async frameworks have something like then(scheduler,
315 Future), we might want to support a similar API which could be
316 implemented a little more efficiently than
317 f.via(executor).then(callback) */
318 template <typename F, typename R = detail::callableResult<T, F>>
319 typename R::Return then(F func) {
320 typedef typename R::Arg Arguments;
321 return thenImplementation<F, R>(std::move(func), Arguments());
324 /// Variant where func is an member function
326 /// struct Worker { R doWork(Try<T>); }
329 /// Future<R> f2 = f1.then(&Worker::doWork, w);
331 /// This is just sugar for
333 /// f1.then(std::bind(&Worker::doWork, w));
334 template <typename R, typename Caller, typename... Args>
335 Future<typename isFuture<R>::Inner>
336 then(R(Caller::*func)(Args...), Caller *instance);
340 /// Execute the callback via the given Executor. The executor doesn't stick.
344 /// f.via(x).then(b).then(c)
348 /// f.then(x, b).then(c)
350 /// In the former both b and c execute via x. In the latter, only b executes
351 /// via x, and c executes via the same executor (if any) that f had.
352 template <class... Args>
353 auto then(Executor* x, Args&&... args)
354 -> decltype(this->then(std::forward<Args>(args)...));
357 /// Convenience method for ignoring the value and creating a Future<void>.
358 /// Exceptions still propagate.
361 /// Set an error callback for this Future. The callback should take a single
362 /// argument of the type that you want to catch, and should return a value of
363 /// the same type as this Future, or a Future of that type (see overload
364 /// below). For instance,
368 /// throw std::runtime_error("oh no!");
371 /// .onError([] (std::runtime_error& e) {
372 /// LOG(INFO) << "std::runtime_error: " << e.what();
373 /// return -1; // or makeFuture<int>(-1)
376 typename std::enable_if<
377 !detail::callableWith<F, exception_wrapper>::value &&
378 !detail::Extract<F>::ReturnsFuture::value,
382 /// Overload of onError where the error callback returns a Future<T>
384 typename std::enable_if<
385 !detail::callableWith<F, exception_wrapper>::value &&
386 detail::Extract<F>::ReturnsFuture::value,
390 /// Overload of onError that takes exception_wrapper and returns Future<T>
392 typename std::enable_if<
393 detail::callableWith<F, exception_wrapper>::value &&
394 detail::Extract<F>::ReturnsFuture::value,
398 /// Overload of onError that takes exception_wrapper and returns T
400 typename std::enable_if<
401 detail::callableWith<F, exception_wrapper>::value &&
402 !detail::Extract<F>::ReturnsFuture::value,
406 /// func is like std::function<void()> and is executed unconditionally, and
407 /// the value/exception is passed through to the resulting Future.
408 /// func shouldn't throw, but if it does it will be captured and propagated,
409 /// and discard any value/exception that this Future has obtained.
411 Future<T> ensure(F func);
413 /// Like onError, but for timeouts. example:
415 /// Future<int> f = makeFuture<int>(42)
416 /// .delayed(long_time)
417 /// .onTimeout(short_time,
418 /// []() -> int{ return -1; });
422 /// Future<int> f = makeFuture<int>(42)
423 /// .delayed(long_time)
424 /// .onTimeout(short_time,
425 /// []() { return makeFuture<int>(some_exception); });
427 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
429 /// This is not the method you're looking for.
431 /// This needs to be public because it's used by make* and when*, and it's
432 /// not worth listing all those and their fancy template signatures as
433 /// friends. But it's not for public consumption.
435 void setCallback_(F&& func);
437 /// A Future's callback is executed when all three of these conditions have
438 /// become true: it has a value (set by the Promise), it has a callback (set
439 /// by then), and it is active (active by default).
441 /// Inactive Futures will activate upon destruction.
442 Future<T>& activate() & {
446 Future<T>& deactivate() & {
450 Future<T> activate() && {
452 return std::move(*this);
454 Future<T> deactivate() && {
456 return std::move(*this);
460 return core_->isActive();
464 void raise(E&& exception) {
465 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
466 std::move(exception)));
469 /// Raise an interrupt. If the promise holder has an interrupt
470 /// handler it will be called and potentially stop asynchronous work from
471 /// being done. This is advisory only - a promise holder may not set an
472 /// interrupt handler, or may do anything including ignore. But, if you know
473 /// your future supports this the most likely result is stopping or
474 /// preventing the asynchronous operation (if in time), and the promise
475 /// holder setting an exception on the future. (That may happen
476 /// asynchronously, of course.)
477 void raise(exception_wrapper interrupt);
480 raise(FutureCancellation());
483 /// Throw TimedOut if this Future does not complete within the given
484 /// duration from now. The optional Timeekeeper is as with futures::sleep().
485 Future<T> within(Duration, Timekeeper* = nullptr);
487 /// Throw the given exception if this Future does not complete within the
488 /// given duration from now. The optional Timeekeeper is as with
489 /// futures::sleep().
491 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
493 /// Delay the completion of this Future for at least this duration from
494 /// now. The optional Timekeeper is as with futures::sleep().
495 Future<T> delayed(Duration, Timekeeper* = nullptr);
497 /// Block until this Future is complete. Returns a reference to this Future.
500 /// Overload of wait() for rvalue Futures
501 Future<T>&& wait() &&;
503 /// Block until this Future is complete or until the given Duration passes.
504 /// Returns a reference to this Future
505 Future<T>& wait(Duration) &;
507 /// Overload of wait(Duration) for rvalue Futures
508 Future<T>&& wait(Duration) &&;
510 /// Call e->drive() repeatedly until the future is fulfilled. Examples
511 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
512 /// reference to this Future so that you can chain calls if desired.
513 /// value (moved out), or throws the exception.
514 Future<T>& waitVia(DrivableExecutor* e) &;
516 /// Overload of waitVia() for rvalue Futures
517 Future<T>&& waitVia(DrivableExecutor* e) &&;
519 /// If the value in this Future is equal to the given Future, when they have
520 /// both completed, the value of the resulting Future<bool> will be true. It
521 /// will be false otherwise (including when one or both Futures have an
523 Future<bool> willEqual(Future<T>&);
525 /// predicate behaves like std::function<bool(T const&)>
526 /// If the predicate does not obtain with the value, the result
527 /// is a folly::PredicateDoesNotObtain exception
529 Future<T> filter(F predicate);
532 typedef detail::Core<T>* corePtr;
534 // shared core state object
538 Future(corePtr obj) : core_(obj) {}
542 void throwIfInvalid() const;
544 friend class Promise<T>;
545 template <class> friend class Future;
547 // Variant: returns a value
548 // e.g. f.then([](Try<T> t){ return t.value(); });
549 template <typename F, typename R, bool isTry, typename... Args>
550 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
551 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
553 // Variant: returns a Future
554 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
555 template <typename F, typename R, bool isTry, typename... Args>
556 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
557 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
559 Executor* getExecutor() { return core_->getExecutor(); }
560 void setExecutor(Executor* x) { core_->setExecutor(x); }
564 Make a completed Future by moving in a value. e.g.
567 auto f = makeFuture(std::move(foo));
571 auto f = makeFuture<string>("foo");
574 Future<typename std::decay<T>::type> makeFuture(T&& t);
576 /** Make a completed void Future. */
577 Future<void> makeFuture();
579 /** Make a completed Future by executing a function. If the function throws
580 we capture the exception, otherwise we capture the result. */
584 typename std::enable_if<
585 !std::is_reference<F>::value, bool>::type sdf = false)
586 -> Future<decltype(func())>;
591 -> Future<decltype(func())>;
593 /// Make a failed Future from an exception_ptr.
594 /// Because the Future's type cannot be inferred you have to specify it, e.g.
596 /// auto f = makeFuture<string>(std::current_exception());
598 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
600 /// Make a failed Future from an exception_wrapper.
602 Future<T> makeFuture(exception_wrapper ew);
604 /** Make a Future from an exception type E that can be passed to
605 std::make_exception_ptr(). */
606 template <class T, class E>
607 typename std::enable_if<std::is_base_of<std::exception, E>::value,
609 makeFuture(E const& e);
611 /** Make a Future out of a Try */
613 Future<T> makeFuture(Try<T>&& t);
616 * Return a new Future that will call back on the given Executor.
617 * This is just syntactic sugar for makeFuture().via(executor)
619 * @param executor the Executor to call back on
621 * @returns a void Future that will call back on the given executor
623 template <typename Executor>
624 Future<void> via(Executor* executor);
626 /** When all the input Futures complete, the returned Future will complete.
627 Errors do not cause early termination; this Future will always succeed
628 after all its Futures have finished (whether successfully or with an
631 The Futures are moved in, so your copies are invalid. If you need to
632 chain further from these Futures, use the variant with an output iterator.
634 This function is thread-safe for Futures running on different threads. But
635 if you are doing anything non-trivial after, you will probably want to
636 follow with `via(executor)` because it will complete in whichever thread the
637 last Future completes in.
639 The return type for Future<T> input is a Future<std::vector<Try<T>>>
641 template <class InputIterator>
642 Future<std::vector<Try<
643 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
644 collectAll(InputIterator first, InputIterator last);
646 /// This version takes a varying number of Futures instead of an iterator.
647 /// The return type for (Future<T1>, Future<T2>, ...) input
648 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
649 /// The Futures are moved in, so your copies are invalid.
650 template <typename... Fs>
651 typename detail::VariadicContext<
652 typename std::decay<Fs>::type::value_type...>::type
653 collectAll(Fs&&... fs);
655 /// Like collectAll, but will short circuit on the first exception. Thus, the
656 /// type of the returned Future is std::vector<T> instead of
657 /// std::vector<Try<T>>
658 template <class InputIterator>
659 Future<typename detail::CollectContext<
660 typename std::iterator_traits<InputIterator>::value_type::value_type
662 collect(InputIterator first, InputIterator last);
664 /** The result is a pair of the index of the first Future to complete and
665 the Try. If multiple Futures complete at the same time (or are already
666 complete when passed in), the "winner" is chosen non-deterministically.
668 This function is thread-safe for Futures running on different threads.
670 template <class InputIterator>
673 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
674 collectAny(InputIterator first, InputIterator last);
676 /** when n Futures have completed, the Future completes with a vector of
677 the index and Try of those n Futures (the indices refer to the original
678 order, but the result vector will be in an arbitrary order)
682 template <class InputIterator>
683 Future<std::vector<std::pair<
685 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
686 collectN(InputIterator first, InputIterator last, size_t n);
688 template <typename F, typename T, typename ItT>
689 using MaybeTryArg = typename std::conditional<
690 detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
692 template<typename F, typename T, typename Arg>
693 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
695 /** repeatedly calls func on every result, e.g.
696 reduce(reduce(reduce(T initial, result of first), result of second), ...)
698 The type of the final result is a Future of the type of the initial value.
700 Func can either return a T, or a Future<T>
702 template <class It, class T, class F,
703 class ItT = typename std::iterator_traits<It>::value_type::value_type,
704 class Arg = MaybeTryArg<F, T, ItT>>
705 typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
706 reduce(It first, It last, T initial, F func);
708 template <class It, class T, class F,
709 class ItT = typename std::iterator_traits<It>::value_type::value_type,
710 class Arg = MaybeTryArg<F, T, ItT>>
711 typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
712 reduce(It first, It last, T initial, F func);
716 #include <folly/futures/Future-inl.h>