2 * Copyright 2014-present 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 <type_traits>
25 #include <folly/Optional.h>
26 #include <folly/Portability.h>
27 #include <folly/ScopeGuard.h>
28 #include <folly/Try.h>
29 #include <folly/Utility.h>
30 #include <folly/executors/DrivableExecutor.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/Promise.h>
33 #include <folly/futures/detail/Types.h>
35 // boring predeclarations and details
36 #include <folly/futures/Future-pre.h>
38 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
39 // Needs to be included after Future-pre.h and before Future-inl.h
40 #include <folly/futures/helpers.h>
57 /// Construct a Future from a value (perfect forwarding)
60 typename = typename std::enable_if<
61 !isFuture<typename std::decay<T2>::type>::value &&
62 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
63 /* implicit */ FutureBase(T2&& val);
65 template <class T2 = T>
66 /* implicit */ FutureBase(
67 typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
71 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
73 explicit FutureBase(in_place_t, Args&&... args);
75 FutureBase(FutureBase<T> const&) = delete;
76 FutureBase(SemiFuture<T>&&) noexcept;
77 FutureBase(Future<T>&&) noexcept;
80 FutureBase(Future<T> const&) = delete;
81 FutureBase(SemiFuture<T> const&) = delete;
85 /// Returns a reference to the result, with a reference category and const-
86 /// qualification equivalent to the reference category and const-qualification
89 /// If moved-from, throws NoState.
91 /// If !isReady(), throws FutureNotReady.
93 /// If an exception has been captured, throws that exception.
95 T const& value() const&;
97 T const&& value() const&&;
99 /// Returns a reference to the try of the result. Throws as for value if
100 /// future is not valid.
102 Try<T> const& result() const&;
103 Try<T>&& result() &&;
104 Try<T> const&& result() const&&;
106 /** True when the result (or exception) is ready. */
107 bool isReady() const;
109 /// sugar for getTry().hasValue()
112 /// sugar for getTry().hasException()
115 /// If the promise has been fulfilled, return an Optional with the Try<T>.
116 /// Otherwise return an empty Optional.
117 /// Note that this moves the Try<T> out.
118 Optional<Try<T>> poll();
120 /// This is not the method you're looking for.
122 /// This needs to be public because it's used by make* and when*, and it's
123 /// not worth listing all those and their fancy template signatures as
124 /// friends. But it's not for public consumption.
126 void setCallback_(F&& func);
129 return core_->isActive();
133 void raise(E&& exception) {
134 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
135 std::forward<E>(exception)));
138 /// Raise an interrupt. If the promise holder has an interrupt
139 /// handler it will be called and potentially stop asynchronous work from
140 /// being done. This is advisory only - a promise holder may not set an
141 /// interrupt handler, or may do anything including ignore. But, if you know
142 /// your future supports this the most likely result is stopping or
143 /// preventing the asynchronous operation (if in time), and the promise
144 /// holder setting an exception on the future. (That may happen
145 /// asynchronously, of course.)
146 void raise(exception_wrapper interrupt);
149 raise(FutureCancellation());
153 friend class Promise<T>;
155 friend class SemiFuture;
159 using corePtr = futures::detail::Core<T>*;
161 // shared core state object
164 explicit FutureBase(corePtr obj) : core_(obj) {}
166 explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
170 void throwIfInvalid() const;
172 template <class FutureType>
173 void assign(FutureType&) noexcept;
175 Executor* getExecutor() {
176 return core_->getExecutor();
179 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
180 core_->setExecutor(x, priority);
183 // Variant: returns a value
184 // e.g. f.then([](Try<T> t){ return t.value(); });
185 template <typename F, typename R, bool isTry, typename... Args>
186 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
187 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
189 // Variant: returns a Future
190 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
191 template <typename F, typename R, bool isTry, typename... Args>
192 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
193 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
195 } // namespace detail
196 } // namespace futures
199 class SemiFuture : private futures::detail::FutureBase<T> {
201 using Base = futures::detail::FutureBase<T>;
202 using DeferredExecutor = futures::detail::DeferredExecutor;
205 static SemiFuture<T> makeEmpty(); // equivalent to moved-from
207 // Export public interface of FutureBase
208 // FutureBase is inherited privately to avoid subclasses being cast to
209 // a FutureBase pointer
210 using typename Base::value_type;
212 /// Construct a Future from a value (perfect forwarding)
215 typename = typename std::enable_if<
216 !isFuture<typename std::decay<T2>::type>::value &&
217 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
218 /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
220 template <class T2 = T>
221 /* implicit */ SemiFuture(
222 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
227 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
229 explicit SemiFuture(in_place_t, Args&&... args)
230 : Base(in_place, std::forward<Args>(args)...) {}
232 SemiFuture(SemiFuture<T> const&) = delete;
234 SemiFuture(SemiFuture<T>&&) noexcept;
235 // safe move-constructabilty from Future
236 /* implicit */ SemiFuture(Future<T>&&) noexcept;
239 using Base::hasException;
240 using Base::hasValue;
241 using Base::isActive;
245 using Base::setCallback_;
249 SemiFuture& operator=(SemiFuture const&) = delete;
250 SemiFuture& operator=(SemiFuture&&) noexcept;
251 SemiFuture& operator=(Future<T>&&) noexcept;
253 /// Block until the future is fulfilled. Returns the value (moved out), or
254 /// throws the exception. The future must not already have a callback.
257 /// Block until the future is fulfilled, or until timed out. Returns the
258 /// value (moved out), or throws the exception (which might be a TimedOut
260 T get(Duration dur) &&;
262 /// Block until the future is fulfilled, or until timed out. Returns the
263 /// Try of the value (moved out).
266 /// Block until the future is fulfilled, or until timed out. Returns the
267 /// Try of the value (moved out) or may throw a TimedOut exception.
268 Try<T> getTry(Duration dur) &&;
270 /// Call e->drive() repeatedly until the future is fulfilled. Examples
271 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
272 /// value (moved out), or throws the exception.
273 T getVia(DrivableExecutor* e) &&;
275 /// Call e->drive() repeatedly until the future is fulfilled. Examples
276 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
277 /// Try of the value (moved out).
278 Try<T> getTryVia(DrivableExecutor* e) &&;
280 /// Block until this Future is complete. Returns a reference to this Future.
281 SemiFuture<T>& wait() &;
283 /// Overload of wait() for rvalue Futures
284 SemiFuture<T>&& wait() &&;
286 /// Block until this Future is complete or until the given Duration passes.
287 /// Returns a reference to this Future
288 SemiFuture<T>& wait(Duration) &;
290 /// Overload of wait(Duration) for rvalue Futures
291 SemiFuture<T>&& wait(Duration) &&;
293 /// Call e->drive() repeatedly until the future is fulfilled. Examples
294 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
295 /// reference to this SemiFuture so that you can chain calls if desired.
296 /// value (moved out), or throws the exception.
297 SemiFuture<T>& waitVia(DrivableExecutor* e) &;
299 /// Overload of waitVia() for rvalue Futures
300 SemiFuture<T>&& waitVia(DrivableExecutor* e) &&;
302 /// Returns an inactive Future which will call back on the other side of
303 /// executor (when it is activated).
305 /// NB remember that Futures activate when they destruct. This is good,
306 /// it means that this will work:
308 /// f.via(e).then(a).then(b);
310 /// a and b will execute in the same context (the far side of e), because
311 /// the Future (temporary variable) created by via(e) does not call back
312 /// until it destructs, which is after then(a) and then(b) have been wired
315 /// But this is still racy:
317 /// f = f.via(e).then(a);
319 // The ref-qualifier allows for `this` to be moved out so we
320 // don't get access-after-free situations in chaining.
321 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
322 inline Future<T> via(
324 int8_t priority = Executor::MID_PRI) &&;
327 * Defer work to run on the consumer of the future.
328 * This work will be run eithe ron an executor that the caller sets on the
329 * SemiFuture, or inline with the call to .get().
330 * NB: This is a custom method because boost-blocking executors is a
331 * special-case for work deferral in folly. With more general boost-blocking
332 * support all executors would boost block and we would simply use some form
333 * of driveable executor here.
335 template <typename F>
336 SemiFuture<typename futures::detail::callableResult<T, F>::Return::value_type>
339 // Public as for setCallback_
340 // Ensure that a boostable executor performs work to chain deferred work
345 friend class Promise<T>;
347 friend class futures::detail::FutureBase;
349 friend class SemiFuture;
351 using typename Base::corePtr;
352 using Base::setExecutor;
353 using Base::throwIfInvalid;
356 friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
358 explicit SemiFuture(corePtr obj) : Base(obj) {}
360 explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
361 : Base(futures::detail::EmptyConstruct{}) {}
365 class Future : private futures::detail::FutureBase<T> {
367 using Base = futures::detail::FutureBase<T>;
370 // Export public interface of FutureBase
371 // FutureBase is inherited privately to avoid subclasses being cast to
372 // a FutureBase pointer
373 using typename Base::value_type;
375 /// Construct a Future from a value (perfect forwarding)
378 typename = typename std::enable_if<
379 !isFuture<typename std::decay<T2>::type>::value &&
380 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
381 /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
383 template <class T2 = T>
384 /* implicit */ Future(
385 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
390 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
392 explicit Future(in_place_t, Args&&... args)
393 : Base(in_place, std::forward<Args>(args)...) {}
395 Future(Future<T> const&) = delete;
397 Future(Future<T>&&) noexcept;
402 typename std::enable_if<
403 !std::is_same<T, typename std::decay<T2>::type>::value &&
404 std::is_constructible<T, T2&&>::value &&
405 std::is_convertible<T2&&, T>::value,
407 /* implicit */ Future(Future<T2>&&);
410 typename std::enable_if<
411 !std::is_same<T, typename std::decay<T2>::type>::value &&
412 std::is_constructible<T, T2&&>::value &&
413 !std::is_convertible<T2&&, T>::value,
415 explicit Future(Future<T2>&&);
418 typename std::enable_if<
419 !std::is_same<T, typename std::decay<T2>::type>::value &&
420 std::is_constructible<T, T2&&>::value,
422 Future& operator=(Future<T2>&&);
425 using Base::hasException;
426 using Base::hasValue;
427 using Base::isActive;
431 using Base::setCallback_;
435 static Future<T> makeEmpty(); // equivalent to moved-from
438 Future& operator=(Future const&) = delete;
441 Future& operator=(Future&&) noexcept;
443 /// Call e->drive() repeatedly until the future is fulfilled. Examples
444 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
445 /// value (moved out), or throws the exception.
446 T getVia(DrivableExecutor* e);
448 /// Call e->drive() repeatedly until the future is fulfilled. Examples
449 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
450 /// reference to the Try of the value.
451 Try<T>& getTryVia(DrivableExecutor* e);
453 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
454 /// Future<T> instance.
455 template <class F = T>
457 enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
460 /// Returns an inactive Future which will call back on the other side of
461 /// executor (when it is activated).
463 /// NB remember that Futures activate when they destruct. This is good,
464 /// it means that this will work:
466 /// f.via(e).then(a).then(b);
468 /// a and b will execute in the same context (the far side of e), because
469 /// the Future (temporary variable) created by via(e) does not call back
470 /// until it destructs, which is after then(a) and then(b) have been wired
473 /// But this is still racy:
475 /// f = f.via(e).then(a);
477 // The ref-qualifier allows for `this` to be moved out so we
478 // don't get access-after-free situations in chaining.
479 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
480 inline Future<T> via(
482 int8_t priority = Executor::MID_PRI) &&;
484 /// This variant creates a new future, where the ref-qualifier && version
485 /// moves `this` out. This one is less efficient but avoids confusing users
486 /// when "return f.via(x);" fails.
487 inline Future<T> via(
489 int8_t priority = Executor::MID_PRI) &;
491 /** When this Future has completed, execute func which is a function that
501 Func shall return either another Future or a value.
503 A Future for the return type of func is returned.
505 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
507 The Future given to the functor is ready, and the functor may call
508 value(), which may rethrow if this has captured an exception. If func
509 throws, the exception will be captured in the Future that is returned.
511 template <typename F, typename R = futures::detail::callableResult<T, F>>
512 typename R::Return then(F&& func) {
513 return this->template thenImplementation<F, R>(
514 std::forward<F>(func), typename R::Arg());
517 /// Variant where func is an member function
519 /// struct Worker { R doWork(Try<T>); }
522 /// Future<R> f2 = f1.then(&Worker::doWork, w);
524 /// This is just sugar for
526 /// f1.then(std::bind(&Worker::doWork, w));
527 template <typename R, typename Caller, typename... Args>
528 Future<typename isFuture<R>::Inner> then(
529 R (Caller::*func)(Args...),
532 /// Execute the callback via the given Executor. The executor doesn't stick.
536 /// f.via(x).then(b).then(c)
540 /// f.then(x, b).then(c)
542 /// In the former both b and c execute via x. In the latter, only b executes
543 /// via x, and c executes via the same executor (if any) that f had.
544 template <class Executor, class Arg, class... Args>
545 auto then(Executor* x, Arg&& arg, Args&&... args) {
546 auto oldX = this->getExecutor();
547 this->setExecutor(x);
548 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
552 /// Convenience method for ignoring the value and creating a Future<Unit>.
553 /// Exceptions still propagate.
554 /// This function is identical to .unit().
557 /// Convenience method for ignoring the value and creating a Future<Unit>.
558 /// Exceptions still propagate.
559 /// This function is identical to parameterless .then().
560 Future<Unit> unit() {
564 /// Set an error callback for this Future. The callback should take a single
565 /// argument of the type that you want to catch, and should return a value of
566 /// the same type as this Future, or a Future of that type (see overload
567 /// below). For instance,
571 /// throw std::runtime_error("oh no!");
574 /// .onError([] (std::runtime_error& e) {
575 /// LOG(INFO) << "std::runtime_error: " << e.what();
576 /// return -1; // or makeFuture<int>(-1)
579 typename std::enable_if<
580 !futures::detail::callableWith<F, exception_wrapper>::value &&
581 !futures::detail::callableWith<F, exception_wrapper&>::value &&
582 !futures::detail::Extract<F>::ReturnsFuture::value,
586 /// Overload of onError where the error callback returns a Future<T>
588 typename std::enable_if<
589 !futures::detail::callableWith<F, exception_wrapper>::value &&
590 !futures::detail::callableWith<F, exception_wrapper&>::value &&
591 futures::detail::Extract<F>::ReturnsFuture::value,
595 /// Overload of onError that takes exception_wrapper and returns Future<T>
597 typename std::enable_if<
598 futures::detail::callableWith<F, exception_wrapper>::value &&
599 futures::detail::Extract<F>::ReturnsFuture::value,
603 /// Overload of onError that takes exception_wrapper and returns T
605 typename std::enable_if<
606 futures::detail::callableWith<F, exception_wrapper>::value &&
607 !futures::detail::Extract<F>::ReturnsFuture::value,
611 /// func is like std::function<void()> and is executed unconditionally, and
612 /// the value/exception is passed through to the resulting Future.
613 /// func shouldn't throw, but if it does it will be captured and propagated,
614 /// and discard any value/exception that this Future has obtained.
616 Future<T> ensure(F&& func);
618 /// Like onError, but for timeouts. example:
620 /// Future<int> f = makeFuture<int>(42)
621 /// .delayed(long_time)
622 /// .onTimeout(short_time,
623 /// []() -> int{ return -1; });
627 /// Future<int> f = makeFuture<int>(42)
628 /// .delayed(long_time)
629 /// .onTimeout(short_time,
630 /// []() { return makeFuture<int>(some_exception); });
632 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
634 /// A Future's callback is executed when all three of these conditions have
635 /// become true: it has a value (set by the Promise), it has a callback (set
636 /// by then), and it is active (active by default).
638 /// Inactive Futures will activate upon destruction.
639 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
640 this->core_->activate();
643 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
644 this->core_->deactivate();
647 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
648 this->core_->activate();
649 return std::move(*this);
651 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
652 this->core_->deactivate();
653 return std::move(*this);
656 /// Throw TimedOut if this Future does not complete within the given
657 /// duration from now. The optional Timeekeeper is as with futures::sleep().
658 Future<T> within(Duration, Timekeeper* = nullptr);
660 /// Throw the given exception if this Future does not complete within the
661 /// given duration from now. The optional Timeekeeper is as with
662 /// futures::sleep().
664 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
666 /// Delay the completion of this Future for at least this duration from
667 /// now. The optional Timekeeper is as with futures::sleep().
668 Future<T> delayed(Duration, Timekeeper* = nullptr);
670 /// Block until the future is fulfilled. Returns the value (moved out), or
671 /// throws the exception. The future must not already have a callback.
674 /// Block until the future is fulfilled, or until timed out. Returns the
675 /// value (moved out), or throws the exception (which might be a TimedOut
679 /** A reference to the Try of the value */
682 /// Block until this Future is complete. Returns a reference to this Future.
685 /// Overload of wait() for rvalue Futures
686 Future<T>&& wait() &&;
688 /// Block until this Future is complete or until the given Duration passes.
689 /// Returns a reference to this Future
690 Future<T>& wait(Duration) &;
692 /// Overload of wait(Duration) for rvalue Futures
693 Future<T>&& wait(Duration) &&;
695 /// Call e->drive() repeatedly until the future is fulfilled. Examples
696 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
697 /// reference to this Future so that you can chain calls if desired.
698 /// value (moved out), or throws the exception.
699 Future<T>& waitVia(DrivableExecutor* e) &;
701 /// Overload of waitVia() for rvalue Futures
702 Future<T>&& waitVia(DrivableExecutor* e) &&;
704 /// If the value in this Future is equal to the given Future, when they have
705 /// both completed, the value of the resulting Future<bool> will be true. It
706 /// will be false otherwise (including when one or both Futures have an
708 Future<bool> willEqual(Future<T>&);
710 /// predicate behaves like std::function<bool(T const&)>
711 /// If the predicate does not obtain with the value, the result
712 /// is a folly::PredicateDoesNotObtain exception
714 Future<T> filter(F&& predicate);
716 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
717 /// the result of collect or collectAll
718 template <class I, class F>
719 Future<I> reduce(I&& initial, F&& func);
721 /// Create a Future chain from a sequence of callbacks. i.e.
723 /// f.then(a).then(b).then(c)
725 /// where f is a Future<A> and the result of the chain is a Future<D>
728 /// f.thenMulti(a, b, c);
729 template <class Callback, class... Callbacks>
730 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
731 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
732 return then(std::forward<Callback>(fn))
733 .thenMulti(std::forward<Callbacks>(fns)...);
736 template <class Callback>
737 auto thenMulti(Callback&& fn) {
738 // thenMulti with one callback is just a then
739 return then(std::forward<Callback>(fn));
742 /// Create a Future chain from a sequence of callbacks. i.e.
744 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
746 /// where f is a Future<A> and the result of the chain is a Future<D>
749 /// f.thenMultiWithExecutor(executor, a, b, c);
750 template <class Callback, class... Callbacks>
751 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
752 // thenMultiExecutor with two callbacks is
753 // via(x).then(a).thenMulti(b, ...).via(oldX)
754 auto oldX = this->getExecutor();
755 this->setExecutor(x);
756 return then(std::forward<Callback>(fn))
757 .thenMulti(std::forward<Callbacks>(fns)...)
761 template <class Callback>
762 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
763 // thenMulti with one callback is just a then with an executor
764 return then(x, std::forward<Callback>(fn));
767 // Convert this Future to a SemiFuture to safely export from a library
768 // without exposing a continuation interface
769 SemiFuture<T> semi() {
770 return SemiFuture<T>{std::move(*this)};
774 friend class Promise<T>;
776 friend class futures::detail::FutureBase;
780 friend class SemiFuture;
782 using Base::setExecutor;
783 using Base::throwIfInvalid;
784 using typename Base::corePtr;
786 explicit Future(corePtr obj) : Base(obj) {}
788 explicit Future(futures::detail::EmptyConstruct) noexcept
789 : Base(futures::detail::EmptyConstruct{}) {}
792 friend Future<T2> makeFuture(Try<T2>&&);
794 /// Repeat the given future (i.e., the computation it contains)
797 /// thunk behaves like std::function<Future<T2>(void)>
799 friend Future<Unit> times(int n, F&& thunk);
801 /// Carry out the computation contained in the given future if
802 /// the predicate holds.
804 /// thunk behaves like std::function<Future<T2>(void)>
806 friend Future<Unit> when(bool p, F&& thunk);
808 /// Carry out the computation contained in the given future if
809 /// while the predicate continues to hold.
811 /// thunk behaves like std::function<Future<T2>(void)>
813 /// predicate behaves like std::function<bool(void)>
814 template <class P, class F>
815 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
820 #include <folly/futures/Future-inl.h>