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;
60 template<typename F, typename... Args>
61 using resultOf = decltype(std::declval<F>()(std::declval<Args>()...));
63 template <typename...>
66 template <typename Arg, typename... Args>
67 struct ArgType<Arg, Args...> {
73 typedef void FirstArg;
76 template <bool isTry, typename F, typename... Args>
78 typedef resultOf<F, Args...> Result;
81 template<typename F, typename... Args>
84 typename = detail::resultOf<T, Args...>>
85 static constexpr std::true_type
86 check(std::nullptr_t) { return std::true_type{}; };
89 static constexpr std::false_type
90 check(...) { return std::false_type{}; };
92 typedef decltype(check<F>(nullptr)) type;
93 static constexpr bool value = type::value;
96 template<typename T, typename F>
97 struct callableResult {
98 typedef typename std::conditional<
99 callableWith<F>::value,
100 detail::argResult<false, F>,
101 typename std::conditional<
102 callableWith<F, Try<T>&&>::value,
103 detail::argResult<true, F, Try<T>&&>,
104 typename std::conditional<
105 callableWith<F, Try<T>&>::value,
106 detail::argResult<true, F, Try<T>&>,
107 typename std::conditional<
108 callableWith<F, T&&>::value,
109 detail::argResult<false, F, T&&>,
110 detail::argResult<false, F, T&>>::type>::type>::type>::type Arg;
111 typedef isFuture<typename Arg::Result> ReturnsFuture;
112 typedef Future<typename ReturnsFuture::Inner> Return;
116 struct callableResult<void, F> {
117 typedef typename std::conditional<
118 callableWith<F>::value,
119 detail::argResult<false, F>,
120 typename std::conditional<
121 callableWith<F, Try<void>&&>::value,
122 detail::argResult<true, F, Try<void>&&>,
123 detail::argResult<true, F, Try<void>&>>::type>::type Arg;
124 typedef isFuture<typename Arg::Result> ReturnsFuture;
125 typedef Future<typename ReturnsFuture::Inner> Return;
128 template <typename L>
129 struct Extract : Extract<decltype(&L::operator())> { };
131 template <typename Class, typename R, typename... Args>
132 struct Extract<R(Class::*)(Args...) const> {
133 typedef isFuture<R> ReturnsFuture;
134 typedef Future<typename ReturnsFuture::Inner> Return;
135 typedef typename ReturnsFuture::Inner RawReturn;
136 typedef typename ArgType<Args...>::FirstArg FirstArg;
139 template <typename Class, typename R, typename... Args>
140 struct Extract<R(Class::*)(Args...)> {
141 typedef isFuture<R> ReturnsFuture;
142 typedef Future<typename ReturnsFuture::Inner> Return;
143 typedef typename ReturnsFuture::Inner RawReturn;
144 typedef typename ArgType<Args...>::FirstArg FirstArg;
151 /// This namespace is for utility functions that would usually be static
152 /// members of Future, except they don't make sense there because they don't
153 /// depend on the template type (rather, on the type of their arguments in
154 /// some cases). This is the least-bad naming scheme we could think of. Some
155 /// of the functions herein have really-likely-to-collide names, like "map"
158 /// Returns a Future that will complete after the specified duration. The
159 /// Duration typedef of a `std::chrono` duration type indicates the
160 /// resolution you can expect to be meaningful (milliseconds at the time of
161 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
162 /// use the global futures timekeeper (we run a thread whose job it is to
163 /// keep time for futures timeouts) but we provide the option for power
166 /// The Timekeeper thread will be lazily created the first time it is
167 /// needed. If your program never uses any timeouts or other time-based
168 /// Futures you will pay no Timekeeper thread overhead.
169 Future<void> sleep(Duration, Timekeeper* = nullptr);
171 /// Create a Future chain from a sequence of callbacks. i.e.
173 /// f.then(a).then(b).then(c);
175 /// where f is a Future<A> and the result of the chain is a Future<Z>
178 /// f.then(chain<A,Z>(a, b, c));
179 // If anyone figures how to get chain to deduce A and Z, I'll buy you a drink.
180 template <class A, class Z, class... Callbacks>
181 std::function<Future<Z>(Try<A>)>
182 chain(Callbacks... fns);
188 typedef T value_type;
191 Future(Future const&) = delete;
192 Future& operator=(Future const&) = delete;
195 Future(Future&&) noexcept;
196 Future& operator=(Future&&) noexcept;
199 template <class F = T>
201 Future(const typename std::enable_if<!std::is_void<F>::value, F>::type& val);
203 template <class F = T>
205 Future(typename std::enable_if<!std::is_void<F>::value, F>::type&& val);
207 template <class F = T,
208 typename std::enable_if<std::is_void<F>::value, int>::type = 0>
213 /** Return the reference to result. Should not be called if !isReady().
214 Will rethrow the exception if an exception has been
217 typename std::add_lvalue_reference<T>::type
219 typename std::add_lvalue_reference<const T>::type
222 /// Returns an inactive Future which will call back on the other side of
223 /// executor (when it is activated).
225 /// NB remember that Futures activate when they destruct. This is good,
226 /// it means that this will work:
228 /// f.via(e).then(a).then(b);
230 /// a and b will execute in the same context (the far side of e), because
231 /// the Future (temporary variable) created by via(e) does not call back
232 /// until it destructs, which is after then(a) and then(b) have been wired
235 /// But this is still racy:
237 /// f = f.via(e).then(a);
239 // The ref-qualifier allows for `this` to be moved out so we
240 // don't get access-after-free situations in chaining.
241 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
242 template <typename Executor>
243 Future<T> via(Executor* executor) &&;
245 /// This variant creates a new future, where the ref-qualifier && version
246 /// moves `this` out. This one is less efficient but avoids confusing users
247 /// when "return f.via(x);" fails.
248 template <typename Executor>
249 Future<T> via(Executor* executor) &;
251 /** True when the result (or exception) is ready. */
252 bool isReady() const;
254 /** A reference to the Try of the value */
257 /// If the promise has been fulfilled, return an Optional with the Try<T>.
258 /// Otherwise return an empty Optional.
259 /// Note that this moves the Try<T> out.
260 Optional<Try<T>> poll();
262 /// Block until the future is fulfilled. Returns the value (moved out), or
263 /// throws the exception. The future must not already have a callback.
266 /// Block until the future is fulfilled, or until timed out. Returns the
267 /// value (moved out), or throws the exception (which might be a TimedOut
271 /// Call e->drive() repeatedly until the future is fulfilled. Examples
272 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
273 /// value (moved out), or throws the exception.
274 T getVia(DrivableExecutor* e);
276 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
277 /// Future<T> instance.
278 template <class F = T>
279 typename std::enable_if<isFuture<F>::value,
280 Future<typename isFuture<T>::Inner>>::type
283 /** When this Future has completed, execute func which is a function that
293 Func shall return either another Future or a value.
295 A Future for the return type of func is returned.
297 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
299 The Future given to the functor is ready, and the functor may call
300 value(), which may rethrow if this has captured an exception. If func
301 throws, the exception will be captured in the Future that is returned.
303 /* TODO n3428 and other async frameworks have something like then(scheduler,
304 Future), we might want to support a similar API which could be
305 implemented a little more efficiently than
306 f.via(executor).then(callback) */
307 template <typename F, typename R = detail::callableResult<T, F>>
308 typename R::Return then(F func) {
309 typedef typename R::Arg Arguments;
310 return thenImplementation<F, R>(std::move(func), Arguments());
313 /// Variant where func is an member function
315 /// struct Worker { R doWork(Try<T>); }
318 /// Future<R> f2 = f1.then(&Worker::doWork, w);
320 /// This is just sugar for
322 /// f1.then(std::bind(&Worker::doWork, w));
323 template <typename R, typename Caller, typename... Args>
324 Future<typename isFuture<R>::Inner>
325 then(R(Caller::*func)(Args...), Caller *instance);
327 /// Convenience method for ignoring the value and creating a Future<void>.
328 /// Exceptions still propagate.
331 /// Set an error callback for this Future. The callback should take a single
332 /// argument of the type that you want to catch, and should return a value of
333 /// the same type as this Future, or a Future of that type (see overload
334 /// below). For instance,
338 /// throw std::runtime_error("oh no!");
341 /// .onError([] (std::runtime_error& e) {
342 /// LOG(INFO) << "std::runtime_error: " << e.what();
343 /// return -1; // or makeFuture<int>(-1)
346 typename std::enable_if<
347 !detail::Extract<F>::ReturnsFuture::value,
351 /// Overload of onError where the error callback returns a Future<T>
353 typename std::enable_if<
354 detail::Extract<F>::ReturnsFuture::value,
358 /// func is like std::function<void()> and is executed unconditionally, and
359 /// the value/exception is passed through to the resulting Future.
360 /// func shouldn't throw, but if it does it will be captured and propagated,
361 /// and discard any value/exception that this Future has obtained.
363 Future<T> ensure(F func);
365 /// Like onError, but for timeouts. example:
367 /// Future<int> f = makeFuture<int>(42)
368 /// .delayed(long_time)
369 /// .onTimeout(short_time,
370 /// []() -> int{ return -1; });
374 /// Future<int> f = makeFuture<int>(42)
375 /// .delayed(long_time)
376 /// .onTimeout(short_time,
377 /// []() { return makeFuture<int>(some_exception); });
379 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
381 /// This is not the method you're looking for.
383 /// This needs to be public because it's used by make* and when*, and it's
384 /// not worth listing all those and their fancy template signatures as
385 /// friends. But it's not for public consumption.
387 void setCallback_(F&& func);
389 /// A Future's callback is executed when all three of these conditions have
390 /// become true: it has a value (set by the Promise), it has a callback (set
391 /// by then), and it is active (active by default).
393 /// Inactive Futures will activate upon destruction.
394 Future<T>& activate() & {
398 Future<T>& deactivate() & {
402 Future<T> activate() && {
404 return std::move(*this);
406 Future<T> deactivate() && {
408 return std::move(*this);
412 return core_->isActive();
416 void raise(E&& exception) {
417 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
418 std::move(exception)));
421 /// Raise an interrupt. If the promise holder has an interrupt
422 /// handler it will be called and potentially stop asynchronous work from
423 /// being done. This is advisory only - a promise holder may not set an
424 /// interrupt handler, or may do anything including ignore. But, if you know
425 /// your future supports this the most likely result is stopping or
426 /// preventing the asynchronous operation (if in time), and the promise
427 /// holder setting an exception on the future. (That may happen
428 /// asynchronously, of course.)
429 void raise(exception_wrapper interrupt);
432 raise(FutureCancellation());
435 /// Throw TimedOut if this Future does not complete within the given
436 /// duration from now. The optional Timeekeeper is as with futures::sleep().
437 Future<T> within(Duration, Timekeeper* = nullptr);
439 /// Throw the given exception if this Future does not complete within the
440 /// given duration from now. The optional Timeekeeper is as with
441 /// futures::sleep().
443 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
445 /// Delay the completion of this Future for at least this duration from
446 /// now. The optional Timekeeper is as with futures::sleep().
447 Future<T> delayed(Duration, Timekeeper* = nullptr);
449 /// Block until this Future is complete. Returns a reference to this Future.
452 /// Overload of wait() for rvalue Futures
453 Future<T>&& wait() &&;
455 /// Block until this Future is complete or until the given Duration passes.
456 /// Returns a reference to this Future
457 Future<T>& wait(Duration) &;
459 /// Overload of wait(Duration) for rvalue Futures
460 Future<T>&& wait(Duration) &&;
462 /// Call e->drive() repeatedly until the future is fulfilled. Examples
463 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
464 /// reference to this Future so that you can chain calls if desired.
465 /// value (moved out), or throws the exception.
466 Future<T>& waitVia(DrivableExecutor* e) &;
468 /// Overload of waitVia() for rvalue Futures
469 Future<T>&& waitVia(DrivableExecutor* e) &&;
471 /// If the value in this Future is equal to the given Future, when they have
472 /// both completed, the value of the resulting Future<bool> will be true. It
473 /// will be false otherwise (including when one or both Futures have an
475 Future<bool> willEqual(Future<T>&);
477 /// predicate behaves like std::function<bool(T const&)>
478 /// If the predicate does not obtain with the value, the result
479 /// is a folly::PredicateDoesNotObtain exception
481 Future<T> filter(F predicate);
484 typedef detail::Core<T>* corePtr;
486 // shared core state object
490 Future(corePtr obj) : core_(obj) {}
494 void throwIfInvalid() const;
496 friend class Promise<T>;
497 template <class> friend class Future;
499 // Variant: returns a value
500 // e.g. f.then([](Try<T> t){ return t.value(); });
501 template <typename F, typename R, bool isTry, typename... Args>
502 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
503 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
505 // Variant: returns a Future
506 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
507 template <typename F, typename R, bool isTry, typename... Args>
508 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
509 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
511 Executor* getExecutor() { return core_->getExecutor(); }
512 void setExecutor(Executor* x) { core_->setExecutor(x); }
516 Make a completed Future by moving in a value. e.g.
519 auto f = makeFuture(std::move(foo));
523 auto f = makeFuture<string>("foo");
526 Future<typename std::decay<T>::type> makeFuture(T&& t);
528 /** Make a completed void Future. */
529 Future<void> makeFuture();
531 /** Make a completed Future by executing a function. If the function throws
532 we capture the exception, otherwise we capture the result. */
536 typename std::enable_if<
537 !std::is_reference<F>::value, bool>::type sdf = false)
538 -> Future<decltype(func())>;
543 -> Future<decltype(func())>;
545 /// Make a failed Future from an exception_ptr.
546 /// Because the Future's type cannot be inferred you have to specify it, e.g.
548 /// auto f = makeFuture<string>(std::current_exception());
550 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
552 /// Make a failed Future from an exception_wrapper.
554 Future<T> makeFuture(exception_wrapper ew);
556 /** Make a Future from an exception type E that can be passed to
557 std::make_exception_ptr(). */
558 template <class T, class E>
559 typename std::enable_if<std::is_base_of<std::exception, E>::value,
561 makeFuture(E const& e);
563 /** Make a Future out of a Try */
565 Future<T> makeFuture(Try<T>&& t);
568 * Return a new Future that will call back on the given Executor.
569 * This is just syntactic sugar for makeFuture().via(executor)
571 * @param executor the Executor to call back on
573 * @returns a void Future that will call back on the given executor
575 template <typename Executor>
576 Future<void> via(Executor* executor);
578 /** When all the input Futures complete, the returned Future will complete.
579 Errors do not cause early termination; this Future will always succeed
580 after all its Futures have finished (whether successfully or with an
583 The Futures are moved in, so your copies are invalid. If you need to
584 chain further from these Futures, use the variant with an output iterator.
586 This function is thread-safe for Futures running on different threads. But
587 if you are doing anything non-trivial after, you will probably want to
588 follow with `via(executor)` because it will complete in whichever thread the
589 last Future completes in.
591 The return type for Future<T> input is a Future<std::vector<Try<T>>>
593 template <class InputIterator>
594 Future<std::vector<Try<
595 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
596 whenAll(InputIterator first, InputIterator last);
598 /// This version takes a varying number of Futures instead of an iterator.
599 /// The return type for (Future<T1>, Future<T2>, ...) input
600 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
601 /// The Futures are moved in, so your copies are invalid.
602 template <typename... Fs>
603 typename detail::VariadicContext<
604 typename std::decay<Fs>::type::value_type...>::type
607 /** The result is a pair of the index of the first Future to complete and
608 the Try. If multiple Futures complete at the same time (or are already
609 complete when passed in), the "winner" is chosen non-deterministically.
611 This function is thread-safe for Futures running on different threads.
613 template <class InputIterator>
616 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
617 whenAny(InputIterator first, InputIterator last);
619 /** when n Futures have completed, the Future completes with a vector of
620 the index and Try of those n Futures (the indices refer to the original
621 order, but the result vector will be in an arbitrary order)
625 template <class InputIterator>
626 Future<std::vector<std::pair<
628 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
629 whenN(InputIterator first, InputIterator last, size_t n);
631 template <typename F, typename T, typename ItT>
632 using MaybeTryArg = typename std::conditional<
633 detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type;
635 template<typename F, typename T, typename Arg>
636 using isFutureResult = isFuture<typename std::result_of<F(T&&, Arg&&)>::type>;
638 /** repeatedly calls func on every result, e.g.
639 reduce(reduce(reduce(T initial, result of first), result of second), ...)
641 The type of the final result is a Future of the type of the initial value.
643 Func can either return a T, or a Future<T>
645 template <class It, class T, class F,
646 class ItT = typename std::iterator_traits<It>::value_type::value_type,
647 class Arg = MaybeTryArg<F, T, ItT>>
648 typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
649 reduce(It first, It last, T initial, F func);
651 template <class It, class T, class F,
652 class ItT = typename std::iterator_traits<It>::value_type::value_type,
653 class Arg = MaybeTryArg<F, T, ItT>>
654 typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
655 reduce(It first, It last, T initial, F func);
659 #include <folly/futures/Future-inl.h>