2 * Copyright 2014 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/MoveWrapper.h>
27 #include <folly/futures/Deprecated.h>
28 #include <folly/futures/DrivableExecutor.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/futures/Try.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/detail/Types.h>
36 template <class> struct Promise;
40 template <class> struct Core;
41 template <class...> struct VariadicContext;
45 typedef typename std::conditional<
46 std::is_same<T, void>::value,
53 struct IsFuture : std::integral_constant<bool, false> {
57 template <template <typename T> class Future, typename T>
58 struct IsFuture<Future<T>> : std::integral_constant<bool, true> {
62 template <typename...>
65 template <typename Arg, typename... Args>
66 struct ArgType<Arg, Args...> {
72 typedef void FirstArg;
76 struct Extract : Extract<decltype(&L::operator())> { };
78 template <typename Class, typename R, typename... Args>
79 struct Extract<R(Class::*)(Args...) const> {
80 typedef IsFuture<R> ReturnsFuture;
81 typedef Future<typename ReturnsFuture::Inner> Return;
82 typedef typename ReturnsFuture::Inner RawReturn;
83 typedef typename ArgType<Args...>::FirstArg FirstArg;
86 template <typename Class, typename R, typename... Args>
87 struct Extract<R(Class::*)(Args...)> {
88 typedef IsFuture<R> ReturnsFuture;
89 typedef Future<typename ReturnsFuture::Inner> Return;
90 typedef typename ReturnsFuture::Inner RawReturn;
91 typedef typename ArgType<Args...>::FirstArg FirstArg;
98 template <typename T> struct isFuture;
100 /// This namespace is for utility functions that would usually be static
101 /// members of Future, except they don't make sense there because they don't
102 /// depend on the template type (rather, on the type of their arguments in
103 /// some cases). This is the least-bad naming scheme we could think of. Some
104 /// of the functions herein have really-likely-to-collide names, like "map"
107 /// Returns a Future that will complete after the specified duration. The
108 /// Duration typedef of a `std::chrono` duration type indicates the
109 /// resolution you can expect to be meaningful (milliseconds at the time of
110 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
111 /// use the global futures timekeeper (we run a thread whose job it is to
112 /// keep time for futures timeouts) but we provide the option for power
115 /// The Timekeeper thread will be lazily created the first time it is
116 /// needed. If your program never uses any timeouts or other time-based
117 /// Futures you will pay no Timekeeper thread overhead.
118 Future<void> sleep(Duration, Timekeeper* = nullptr);
124 typedef T value_type;
127 Future(Future const&) = delete;
128 Future& operator=(Future const&) = delete;
131 Future(Future&&) noexcept;
132 Future& operator=(Future&&);
136 /** Return the reference to result. Should not be called if !isReady().
137 Will rethrow the exception if an exception has been
140 This function is not thread safe - the returned Future can only
141 be executed from the thread that the executor runs it in.
142 See below for a thread safe version
144 typename std::add_lvalue_reference<T>::type
146 typename std::add_lvalue_reference<const T>::type
149 /// Returns an inactive Future which will call back on the other side of
150 /// executor (when it is activated).
152 /// NB remember that Futures activate when they destruct. This is good,
153 /// it means that this will work:
155 /// f.via(e).then(a).then(b);
157 /// a and b will execute in the same context (the far side of e), because
158 /// the Future (temporary variable) created by via(e) does not call back
159 /// until it destructs, which is after then(a) and then(b) have been wired
162 /// But this is still racy:
164 /// f = f.via(e).then(a);
166 // The ref-qualifier allows for `this` to be moved out so we
167 // don't get access-after-free situations in chaining.
168 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
169 template <typename Executor>
170 Future<T> via(Executor* executor) &&;
172 /// This variant creates a new future, where the ref-qualifier && version
173 /// moves `this` out. This one is less efficient but avoids confusing users
174 /// when "return f.via(x);" fails.
175 template <typename Executor>
176 Future<T> via(Executor* executor) &;
178 /** True when the result (or exception) is ready. */
179 bool isReady() const;
181 /** A reference to the Try of the value */
184 /// Block until the future is fulfilled. Returns the value (moved out), or
185 /// throws the exception. The future must not already have a callback.
188 /// Block until the future is fulfilled, or until timed out. Returns the
189 /// value (moved out), or throws the exception (which might be a TimedOut
193 /// Call e->drive() repeatedly until the future is fulfilled. Examples
194 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
195 /// value (moved out), or throws the exception.
196 T getVia(DrivableExecutor* e);
198 /** When this Future has completed, execute func which is a function that
199 takes a Try<T>&&. A Future for the return type of func is
202 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
204 The Future given to the functor is ready, and the functor may call
205 value(), which may rethrow if this has captured an exception. If func
206 throws, the exception will be captured in the Future that is returned.
208 /* TODO n3428 and other async frameworks have something like then(scheduler,
209 Future), we might want to support a similar API which could be
210 implemented a little more efficiently than
211 f.via(executor).then(callback) */
213 typename std::enable_if<
214 !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
215 Future<typename std::result_of<F(Try<T>&&)>::type> >::type
218 /// Variant where func takes a T directly, bypassing a try. Any exceptions
219 /// will be implicitly passed on to the resultant Future.
221 /// Future<int> f = makeFuture<int>(42).then([](int i) { return i+1; });
223 typename std::enable_if<
224 !std::is_same<T, void>::value &&
225 !isFuture<typename std::result_of<
226 F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
227 Future<typename std::result_of<
228 F(typename detail::AliasIfVoid<T>::type&&)>::type> >::type
231 /// Like the above variant, but for void futures. That is, func takes no
234 /// Future<int> f = makeFuture().then([] { return 42; });
236 typename std::enable_if<
237 std::is_same<T, void>::value &&
238 !isFuture<typename std::result_of<F()>::type>::value,
239 Future<typename std::result_of<F()>::type> >::type
242 /// Variant where func returns a Future<T> instead of a T. e.g.
244 /// Future<string> f2 = f1.then(
245 /// [](Try<T>&&) { return makeFuture<string>("foo"); });
247 typename std::enable_if<
248 isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
249 Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
252 /// Variant where func returns a Future<T2> and takes a T directly, bypassing
253 /// a Try. Any exceptions will be implicitly passed on to the resultant
254 /// Future. For example,
256 /// Future<int> f = makeFuture<int>(42).then(
257 /// [](int i) { return makeFuture<int>(i+1); });
259 typename std::enable_if<
260 !std::is_same<T, void>::value &&
261 isFuture<typename std::result_of<
262 F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
263 Future<typename std::result_of<
264 F(typename detail::AliasIfVoid<T>::type&&)>::type::value_type> >::type
267 /// Like the above variant, but for void futures. That is, func takes no
268 /// argument and returns a future.
270 /// Future<int> f = makeFuture().then(
271 /// [] { return makeFuture<int>(42); });
273 typename std::enable_if<
274 std::is_same<T, void>::value &&
275 isFuture<typename std::result_of<F()>::type>::value,
276 Future<typename std::result_of<F()>::type::value_type> >::type
279 /// Variant where func is an ordinary function (static method, method)
281 /// R doWork(Try<T>&&);
283 /// Future<R> f2 = f1.then(doWork);
288 /// static R doWork(Try<T>&&); }
290 /// Future<R> f2 = f1.then(&Worker::doWork);
291 template <class = T, class R = std::nullptr_t>
292 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
293 inline then(R(*func)(Try<T>&&)) {
294 return then([func](Try<T>&& t) {
295 return (*func)(std::move(t));
299 /// Variant where func returns a Future<R> instead of a R. e.g.
302 /// Future<R> doWork(Try<T>&&); }
304 /// Future<R> f2 = f1.then(&Worker::doWork);
305 template <class = T, class R = std::nullptr_t>
306 typename std::enable_if<isFuture<R>::value, R>::type
307 inline then(R(*func)(Try<T>&&)) {
308 return then([func](Try<T>&& t) {
309 return (*func)(std::move(t));
313 /// Variant where func is an member function
316 /// R doWork(Try<T>&&); }
319 /// Future<R> f2 = f1.then(w, &Worker::doWork);
320 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
321 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
322 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
323 return then([instance, func](Try<T>&& t) {
324 return (instance->*func)(std::move(t));
328 // Same as above, but func takes void instead of Try<void>&&
329 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
330 typename std::enable_if<
331 std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
332 inline then(Caller *instance, R(Caller::*func)()) {
333 return then([instance, func]() {
334 return (instance->*func)();
338 // Same as above, but func takes T&& instead of Try<T>&&
339 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
340 typename std::enable_if<
341 !std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
344 R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
345 return then([instance, func](T&& t) {
346 return (instance->*func)(std::move(t));
350 /// Variant where func returns a Future<R> instead of a R. e.g.
353 /// Future<R> doWork(Try<T>&&); }
356 /// Future<R> f2 = f1.then(w, &Worker::doWork);
357 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
358 typename std::enable_if<isFuture<R>::value, R>::type
359 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
360 return then([instance, func](Try<T>&& t) {
361 return (instance->*func)(std::move(t));
365 // Same as above, but func takes void instead of Try<void>&&
366 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
367 typename std::enable_if<
368 std::is_same<T, void>::value && isFuture<R>::value, R>::type
369 inline then(Caller *instance, R(Caller::*func)()) {
370 return then([instance, func]() {
371 return (instance->*func)();
375 // Same as above, but func takes T&& instead of Try<T>&&
376 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
377 typename std::enable_if<
378 !std::is_same<T, void>::value && isFuture<R>::value, R>::type
381 R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
382 return then([instance, func](T&& t) {
383 return (instance->*func)(std::move(t));
387 /// Convenience method for ignoring the value and creating a Future<void>.
388 /// Exceptions still propagate.
391 /// Set an error callback for this Future. The callback should take a single
392 /// argument of the type that you want to catch, and should return a value of
393 /// the same type as this Future, or a Future of that type (see overload
394 /// below). For instance,
398 /// throw std::runtime_error("oh no!");
401 /// .onError([] (std::runtime_error& e) {
402 /// LOG(INFO) << "std::runtime_error: " << e.what();
403 /// return -1; // or makeFuture<int>(-1)
406 typename std::enable_if<
407 !detail::Extract<F>::ReturnsFuture::value,
411 /// Overload of onError where the error callback returns a Future<T>
413 typename std::enable_if<
414 detail::Extract<F>::ReturnsFuture::value,
418 /// This is not the method you're looking for.
420 /// This needs to be public because it's used by make* and when*, and it's
421 /// not worth listing all those and their fancy template signatures as
422 /// friends. But it's not for public consumption.
424 void setCallback_(F&& func);
426 /// A Future's callback is executed when all three of these conditions have
427 /// become true: it has a value (set by the Promise), it has a callback (set
428 /// by then), and it is active (active by default).
430 /// Inactive Futures will activate upon destruction.
431 Future<T>& activate() & {
435 Future<T>& deactivate() & {
439 Future<T> activate() && {
441 return std::move(*this);
443 Future<T> deactivate() && {
445 return std::move(*this);
449 return core_->isActive();
453 void raise(E&& exception) {
454 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
455 std::move(exception)));
458 /// Raise an interrupt. If the promise holder has an interrupt
459 /// handler it will be called and potentially stop asynchronous work from
460 /// being done. This is advisory only - a promise holder may not set an
461 /// interrupt handler, or may do anything including ignore. But, if you know
462 /// your future supports this the most likely result is stopping or
463 /// preventing the asynchronous operation (if in time), and the promise
464 /// holder setting an exception on the future. (That may happen
465 /// asynchronously, of course.)
466 void raise(exception_wrapper interrupt);
469 raise(FutureCancellation());
472 /// Throw TimedOut if this Future does not complete within the given
473 /// duration from now. The optional Timeekeeper is as with futures::sleep().
474 Future<T> within(Duration, Timekeeper* = nullptr);
476 /// Throw the given exception if this Future does not complete within the
477 /// given duration from now. The optional Timeekeeper is as with
478 /// futures::sleep().
480 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
482 /// Delay the completion of this Future for at least this duration from
483 /// now. The optional Timekeeper is as with futures::sleep().
484 Future<T> delayed(Duration, Timekeeper* = nullptr);
486 /// Block until this Future is complete. Returns a new Future containing the
490 /// Block until this Future is complete or until the given Duration passes.
491 /// Returns a new Future which either contains the result or is incomplete,
492 /// depending on whether the Duration passed.
493 Future<T> wait(Duration);
495 /// Call e->drive() repeatedly until the future is fulfilled. Examples
496 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
497 /// reference to this Future so that you can chain calls if desired.
498 /// value (moved out), or throws the exception.
499 Future<T>& waitVia(DrivableExecutor* e) &;
501 /// Overload of waitVia() for rvalue Futures
502 Future<T> waitVia(DrivableExecutor* e) &&;
505 typedef detail::Core<T>* corePtr;
507 // shared core state object
511 Future(corePtr obj) : core_(obj) {}
515 void throwIfInvalid() const;
517 friend class Promise<T>;
521 Make a completed Future by moving in a value. e.g.
524 auto f = makeFuture(std::move(foo));
528 auto f = makeFuture<string>("foo");
531 Future<typename std::decay<T>::type> makeFuture(T&& t);
533 /** Make a completed void Future. */
534 Future<void> makeFuture();
536 /** Make a completed Future by executing a function. If the function throws
537 we capture the exception, otherwise we capture the result. */
541 typename std::enable_if<
542 !std::is_reference<F>::value, bool>::type sdf = false)
543 -> Future<decltype(func())>;
548 -> Future<decltype(func())>;
550 /// Make a failed Future from an exception_ptr.
551 /// Because the Future's type cannot be inferred you have to specify it, e.g.
553 /// auto f = makeFuture<string>(std::current_exception());
555 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
557 /// Make a failed Future from an exception_wrapper.
559 Future<T> makeFuture(exception_wrapper ew);
561 /** Make a Future from an exception type E that can be passed to
562 std::make_exception_ptr(). */
563 template <class T, class E>
564 typename std::enable_if<std::is_base_of<std::exception, E>::value,
566 makeFuture(E const& e);
568 /** Make a Future out of a Try */
570 Future<T> makeFuture(Try<T>&& t);
573 * Return a new Future that will call back on the given Executor.
574 * This is just syntactic sugar for makeFuture().via(executor)
576 * @param executor the Executor to call back on
578 * @returns a void Future that will call back on the given executor
580 template <typename Executor>
581 Future<void> via(Executor* executor);
583 /** When all the input Futures complete, the returned Future will complete.
584 Errors do not cause early termination; this Future will always succeed
585 after all its Futures have finished (whether successfully or with an
588 The Futures are moved in, so your copies are invalid. If you need to
589 chain further from these Futures, use the variant with an output iterator.
591 XXX is this still true?
592 This function is thread-safe for Futures running on different threads.
594 The return type for Future<T> input is a Future<std::vector<Try<T>>>
596 template <class InputIterator>
597 Future<std::vector<Try<
598 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
599 whenAll(InputIterator first, InputIterator last);
601 /// This version takes a varying number of Futures instead of an iterator.
602 /// The return type for (Future<T1>, Future<T2>, ...) input
603 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
604 /// The Futures are moved in, so your copies are invalid.
605 template <typename... Fs>
606 typename detail::VariadicContext<
607 typename std::decay<Fs>::type::value_type...>::type
610 /** The result is a pair of the index of the first Future to complete and
611 the Try. If multiple Futures complete at the same time (or are already
612 complete when passed in), the "winner" is chosen non-deterministically.
614 This function is thread-safe for Futures running on different threads.
616 template <class InputIterator>
619 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
620 whenAny(InputIterator first, InputIterator last);
622 /** when n Futures have completed, the Future completes with a vector of
623 the index and Try of those n Futures (the indices refer to the original
624 order, but the result vector will be in an arbitrary order)
628 template <class InputIterator>
629 Future<std::vector<std::pair<
631 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
632 whenN(InputIterator first, InputIterator last, size_t n);
636 #include <folly/futures/Future-inl.h>