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);
189 typedef T value_type;
192 Future(Future const&) = delete;
193 Future& operator=(Future const&) = delete;
196 Future(Future&&) noexcept;
197 Future& operator=(Future&&) noexcept;
200 template <class F = T>
202 Future(const typename std::enable_if<!std::is_void<F>::value, F>::type& val);
204 template <class F = T>
206 Future(typename std::enable_if<!std::is_void<F>::value, F>::type&& val);
208 template <class F = T,
209 typename std::enable_if<std::is_void<F>::value, int>::type = 0>
214 /** Return the reference to result. Should not be called if !isReady().
215 Will rethrow the exception if an exception has been
218 typename std::add_lvalue_reference<T>::type
220 typename std::add_lvalue_reference<const T>::type
223 /// Returns an inactive Future which will call back on the other side of
224 /// executor (when it is activated).
226 /// NB remember that Futures activate when they destruct. This is good,
227 /// it means that this will work:
229 /// f.via(e).then(a).then(b);
231 /// a and b will execute in the same context (the far side of e), because
232 /// the Future (temporary variable) created by via(e) does not call back
233 /// until it destructs, which is after then(a) and then(b) have been wired
236 /// But this is still racy:
238 /// f = f.via(e).then(a);
240 // The ref-qualifier allows for `this` to be moved out so we
241 // don't get access-after-free situations in chaining.
242 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
243 template <typename Executor>
244 Future<T> via(Executor* executor) &&;
246 /// This variant creates a new future, where the ref-qualifier && version
247 /// moves `this` out. This one is less efficient but avoids confusing users
248 /// when "return f.via(x);" fails.
249 template <typename Executor>
250 Future<T> via(Executor* executor) &;
252 /** True when the result (or exception) is ready. */
253 bool isReady() const;
255 /** A reference to the Try of the value */
258 /// If the promise has been fulfilled, return an Optional with the Try<T>.
259 /// Otherwise return an empty Optional.
260 /// Note that this moves the Try<T> out.
261 Optional<Try<T>> poll();
263 /// Block until the future is fulfilled. Returns the value (moved out), or
264 /// throws the exception. The future must not already have a callback.
267 /// Block until the future is fulfilled, or until timed out. Returns the
268 /// value (moved out), or throws the exception (which might be a TimedOut
272 /// Call e->drive() repeatedly until the future is fulfilled. Examples
273 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
274 /// value (moved out), or throws the exception.
275 T getVia(DrivableExecutor* e);
277 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
278 /// Future<T> instance.
279 template <class F = T>
280 typename std::enable_if<isFuture<F>::value,
281 Future<typename isFuture<T>::Inner>>::type
284 /** When this Future has completed, execute func which is a function that
294 Func shall return either another Future or a value.
296 A Future for the return type of func is returned.
298 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
300 The Future given to the functor is ready, and the functor may call
301 value(), which may rethrow if this has captured an exception. If func
302 throws, the exception will be captured in the Future that is returned.
304 /* TODO n3428 and other async frameworks have something like then(scheduler,
305 Future), we might want to support a similar API which could be
306 implemented a little more efficiently than
307 f.via(executor).then(callback) */
308 template <typename F, typename R = detail::callableResult<T, F>>
309 typename R::Return then(F func) {
310 typedef typename R::Arg Arguments;
311 return thenImplementation<F, R>(std::move(func), Arguments());
314 /// Variant where func is an member function
316 /// struct Worker { R doWork(Try<T>); }
319 /// Future<R> f2 = f1.then(&Worker::doWork, w);
321 /// This is just sugar for
323 /// f1.then(std::bind(&Worker::doWork, w));
324 template <typename R, typename Caller, typename... Args>
325 Future<typename isFuture<R>::Inner>
326 then(R(Caller::*func)(Args...), Caller *instance);
328 /// Execute the callback via the given Executor. The executor doesn't stick.
332 /// f.via(x).then(b).then(c)
336 /// f.then(x, b).then(c)
338 /// In the former both b and c execute via x. In the latter, only b executes
339 /// via x, and c executes via the same executor (if any) that f had.
340 template <class... Args>
341 auto then(Executor* x, Args&&... args)
342 -> decltype(this->then(std::forward<Args>(args)...));
344 /// Convenience method for ignoring the value and creating a Future<void>.
345 /// Exceptions still propagate.
348 /// Set an error callback for this Future. The callback should take a single
349 /// argument of the type that you want to catch, and should return a value of
350 /// the same type as this Future, or a Future of that type (see overload
351 /// below). For instance,
355 /// throw std::runtime_error("oh no!");
358 /// .onError([] (std::runtime_error& e) {
359 /// LOG(INFO) << "std::runtime_error: " << e.what();
360 /// return -1; // or makeFuture<int>(-1)
363 typename std::enable_if<
364 !detail::callableWith<F, exception_wrapper>::value &&
365 !detail::Extract<F>::ReturnsFuture::value,
369 /// Overload of onError where the error callback returns a Future<T>
371 typename std::enable_if<
372 !detail::callableWith<F, exception_wrapper>::value &&
373 detail::Extract<F>::ReturnsFuture::value,
377 /// Overload of onError that takes exception_wrapper and returns Future<T>
379 typename std::enable_if<
380 detail::callableWith<F, exception_wrapper>::value &&
381 detail::Extract<F>::ReturnsFuture::value,
385 /// Overload of onError that takes exception_wrapper and returns T
387 typename std::enable_if<
388 detail::callableWith<F, exception_wrapper>::value &&
389 !detail::Extract<F>::ReturnsFuture::value,
393 /// func is like std::function<void()> and is executed unconditionally, and
394 /// the value/exception is passed through to the resulting Future.
395 /// func shouldn't throw, but if it does it will be captured and propagated,
396 /// and discard any value/exception that this Future has obtained.
398 Future<T> ensure(F func);
400 /// Like onError, but for timeouts. example:
402 /// Future<int> f = makeFuture<int>(42)
403 /// .delayed(long_time)
404 /// .onTimeout(short_time,
405 /// []() -> int{ return -1; });
409 /// Future<int> f = makeFuture<int>(42)
410 /// .delayed(long_time)
411 /// .onTimeout(short_time,
412 /// []() { return makeFuture<int>(some_exception); });
414 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
416 /// This is not the method you're looking for.
418 /// This needs to be public because it's used by make* and when*, and it's
419 /// not worth listing all those and their fancy template signatures as
420 /// friends. But it's not for public consumption.
422 void setCallback_(F&& func);
424 /// A Future's callback is executed when all three of these conditions have
425 /// become true: it has a value (set by the Promise), it has a callback (set
426 /// by then), and it is active (active by default).
428 /// Inactive Futures will activate upon destruction.
429 Future<T>& activate() & {
433 Future<T>& deactivate() & {
437 Future<T> activate() && {
439 return std::move(*this);
441 Future<T> deactivate() && {
443 return std::move(*this);
447 return core_->isActive();
451 void raise(E&& exception) {
452 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
453 std::move(exception)));
456 /// Raise an interrupt. If the promise holder has an interrupt
457 /// handler it will be called and potentially stop asynchronous work from
458 /// being done. This is advisory only - a promise holder may not set an
459 /// interrupt handler, or may do anything including ignore. But, if you know
460 /// your future supports this the most likely result is stopping or
461 /// preventing the asynchronous operation (if in time), and the promise
462 /// holder setting an exception on the future. (That may happen
463 /// asynchronously, of course.)
464 void raise(exception_wrapper interrupt);
467 raise(FutureCancellation());
470 /// Throw TimedOut if this Future does not complete within the given
471 /// duration from now. The optional Timeekeeper is as with futures::sleep().
472 Future<T> within(Duration, Timekeeper* = nullptr);
474 /// Throw the given exception if this Future does not complete within the
475 /// given duration from now. The optional Timeekeeper is as with
476 /// futures::sleep().
478 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
480 /// Delay the completion of this Future for at least this duration from
481 /// now. The optional Timekeeper is as with futures::sleep().
482 Future<T> delayed(Duration, Timekeeper* = nullptr);
484 /// Block until this Future is complete. Returns a reference to this Future.
487 /// Overload of wait() for rvalue Futures
488 Future<T>&& wait() &&;
490 /// Block until this Future is complete or until the given Duration passes.
491 /// Returns a reference to this Future
492 Future<T>& wait(Duration) &;
494 /// Overload of wait(Duration) for rvalue Futures
495 Future<T>&& wait(Duration) &&;
497 /// Call e->drive() repeatedly until the future is fulfilled. Examples
498 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
499 /// reference to this Future so that you can chain calls if desired.
500 /// value (moved out), or throws the exception.
501 Future<T>& waitVia(DrivableExecutor* e) &;
503 /// Overload of waitVia() for rvalue Futures
504 Future<T>&& waitVia(DrivableExecutor* e) &&;
506 /// If the value in this Future is equal to the given Future, when they have
507 /// both completed, the value of the resulting Future<bool> will be true. It
508 /// will be false otherwise (including when one or both Futures have an
510 Future<bool> willEqual(Future<T>&);
512 /// predicate behaves like std::function<bool(T const&)>
513 /// If the predicate does not obtain with the value, the result
514 /// is a folly::PredicateDoesNotObtain exception
516 Future<T> filter(F predicate);
519 typedef detail::Core<T>* corePtr;
521 // shared core state object
525 Future(corePtr obj) : core_(obj) {}
529 void throwIfInvalid() const;
531 friend class Promise<T>;
532 template <class> friend class Future;
534 // Variant: returns a value
535 // e.g. f.then([](Try<T> t){ return t.value(); });
536 template <typename F, typename R, bool isTry, typename... Args>
537 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
538 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
540 // Variant: returns a Future
541 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
542 template <typename F, typename R, bool isTry, typename... Args>
543 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
544 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
546 Executor* getExecutor() { return core_->getExecutor(); }
547 void setExecutor(Executor* x) { core_->setExecutor(x); }
551 Make a completed Future by moving in a value. e.g.
554 auto f = makeFuture(std::move(foo));
558 auto f = makeFuture<string>("foo");
561 Future<typename std::decay<T>::type> makeFuture(T&& t);
563 /** Make a completed void Future. */
564 Future<void> makeFuture();
566 /** Make a completed Future by executing a function. If the function throws
567 we capture the exception, otherwise we capture the result. */
571 typename std::enable_if<
572 !std::is_reference<F>::value, bool>::type sdf = false)
573 -> Future<decltype(func())>;
578 -> Future<decltype(func())>;
580 /// Make a failed Future from an exception_ptr.
581 /// Because the Future's type cannot be inferred you have to specify it, e.g.
583 /// auto f = makeFuture<string>(std::current_exception());
585 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
587 /// Make a failed Future from an exception_wrapper.
589 Future<T> makeFuture(exception_wrapper ew);
591 /** Make a Future from an exception type E that can be passed to
592 std::make_exception_ptr(). */
593 template <class T, class E>
594 typename std::enable_if<std::is_base_of<std::exception, E>::value,
596 makeFuture(E const& e);
598 /** Make a Future out of a Try */
600 Future<T> makeFuture(Try<T>&& t);
603 * Return a new Future that will call back on the given Executor.
604 * This is just syntactic sugar for makeFuture().via(executor)
606 * @param executor the Executor to call back on
608 * @returns a void Future that will call back on the given executor
610 template <typename Executor>
611 Future<void> via(Executor* executor);
613 /** When all the input Futures complete, the returned Future will complete.
614 Errors do not cause early termination; this Future will always succeed
615 after all its Futures have finished (whether successfully or with an
618 The Futures are moved in, so your copies are invalid. If you need to
619 chain further from these Futures, use the variant with an output iterator.
621 This function is thread-safe for Futures running on different threads. But
622 if you are doing anything non-trivial after, you will probably want to
623 follow with `via(executor)` because it will complete in whichever thread the
624 last Future completes in.
626 The return type for Future<T> input is a Future<std::vector<Try<T>>>
628 template <class InputIterator>
629 Future<std::vector<Try<
630 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
631 whenAll(InputIterator first, InputIterator last);
633 /// This version takes a varying number of Futures instead of an iterator.
634 /// The return type for (Future<T1>, Future<T2>, ...) input
635 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
636 /// The Futures are moved in, so your copies are invalid.
637 template <typename... Fs>
638 typename detail::VariadicContext<
639 typename std::decay<Fs>::type::value_type...>::type
642 /// Like whenAll, but will short circuit on the first exception. Thus, the
643 /// type of the returned Future is std::vector<T> instead of
644 /// std::vector<Try<T>>
645 template <class InputIterator>
646 Future<typename detail::CollectContext<
647 typename std::iterator_traits<InputIterator>::value_type::value_type
649 collect(InputIterator first, InputIterator last);
651 /** The result is a pair of the index of the first Future to complete and
652 the Try. If multiple Futures complete at the same time (or are already
653 complete when passed in), the "winner" is chosen non-deterministically.
655 This function is thread-safe for Futures running on different threads.
657 template <class InputIterator>
660 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
661 whenAny(InputIterator first, InputIterator last);
663 /** when n Futures have completed, the Future completes with a vector of
664 the index and Try of those n Futures (the indices refer to the original
665 order, but the result vector will be in an arbitrary order)
669 template <class InputIterator>
670 Future<std::vector<std::pair<
672 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
673 whenN(InputIterator first, InputIterator last, size_t n);
675 template <typename F, typename T, typename ItT>
676 using MaybeTryArg = typename std::conditional<
677 detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
679 template<typename F, typename T, typename Arg>
680 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
682 /** repeatedly calls func on every result, e.g.
683 reduce(reduce(reduce(T initial, result of first), result of second), ...)
685 The type of the final result is a Future of the type of the initial value.
687 Func can either return a T, or a Future<T>
689 template <class It, class T, class F,
690 class ItT = typename std::iterator_traits<It>::value_type::value_type,
691 class Arg = MaybeTryArg<F, T, ItT>>
692 typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
693 reduce(It first, It last, T initial, F func);
695 template <class It, class T, class F,
696 class ItT = typename std::iterator_traits<It>::value_type::value_type,
697 class Arg = MaybeTryArg<F, T, ItT>>
698 typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
699 reduce(It first, It last, T initial, F func);
703 #include <folly/futures/Future-inl.h>