2 * Copyright 2017 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/Portability.h>
28 #include <folly/ScopeGuard.h>
29 #include <folly/Try.h>
30 #include <folly/Utility.h>
31 #include <folly/executors/DrivableExecutor.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/Promise.h>
34 #include <folly/futures/detail/Types.h>
36 // boring predeclarations and details
37 #include <folly/futures/Future-pre.h>
39 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
40 // Needs to be included after Future-pre.h and before Future-inl.h
41 #include <folly/futures/helpers.h>
58 /// Construct a Future from a value (perfect forwarding)
61 typename = typename std::enable_if<
62 !isFuture<typename std::decay<T2>::type>::value &&
63 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
64 /* implicit */ FutureBase(T2&& val);
66 template <class T2 = T>
67 /* implicit */ FutureBase(
68 typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
72 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
74 explicit FutureBase(in_place_t, Args&&... args);
76 FutureBase(FutureBase<T> const&) = delete;
77 FutureBase(SemiFuture<T>&&) noexcept;
78 FutureBase(Future<T>&&) noexcept;
81 FutureBase(Future<T> const&) = delete;
82 FutureBase(SemiFuture<T> const&) = delete;
86 /// Returns a reference to the result, with a reference category and const-
87 /// qualification equivalent to the reference category and const-qualification
90 /// If moved-from, throws NoState.
92 /// If !isReady(), throws FutureNotReady.
94 /// If an exception has been captured, throws that exception.
96 T const& value() const&;
98 T const&& value() const&&;
100 /** True when the result (or exception) is ready. */
101 bool isReady() const;
103 /// sugar for getTry().hasValue()
106 /// sugar for getTry().hasException()
109 /// If the promise has been fulfilled, return an Optional with the Try<T>.
110 /// Otherwise return an empty Optional.
111 /// Note that this moves the Try<T> out.
112 Optional<Try<T>> poll();
114 /// This is not the method you're looking for.
116 /// This needs to be public because it's used by make* and when*, and it's
117 /// not worth listing all those and their fancy template signatures as
118 /// friends. But it's not for public consumption.
120 void setCallback_(F&& func);
123 return core_->isActive();
127 void raise(E&& exception) {
128 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
129 std::forward<E>(exception)));
132 /// Raise an interrupt. If the promise holder has an interrupt
133 /// handler it will be called and potentially stop asynchronous work from
134 /// being done. This is advisory only - a promise holder may not set an
135 /// interrupt handler, or may do anything including ignore. But, if you know
136 /// your future supports this the most likely result is stopping or
137 /// preventing the asynchronous operation (if in time), and the promise
138 /// holder setting an exception on the future. (That may happen
139 /// asynchronously, of course.)
140 void raise(exception_wrapper interrupt);
143 raise(FutureCancellation());
147 friend class Promise<T>;
149 friend class SemiFuture;
153 using corePtr = futures::detail::Core<T>*;
155 // shared core state object
158 explicit FutureBase(corePtr obj) : core_(obj) {}
160 explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
164 void throwIfInvalid() const;
166 template <class FutureType>
167 void assign(FutureType&) noexcept;
169 Executor* getExecutor() {
170 return core_->getExecutor();
173 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
174 core_->setExecutor(x, priority);
177 // Variant: returns a value
178 // e.g. f.then([](Try<T> t){ return t.value(); });
179 template <typename F, typename R, bool isTry, typename... Args>
180 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
181 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
183 // Variant: returns a Future
184 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
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 } // namespace detail
190 } // namespace futures
193 class SemiFuture : private futures::detail::FutureBase<T> {
195 using Base = futures::detail::FutureBase<T>;
196 using DeferredExecutor = futures::detail::DeferredExecutor;
199 static SemiFuture<T> makeEmpty(); // equivalent to moved-from
201 // Export public interface of FutureBase
202 // FutureBase is inherited privately to avoid subclasses being cast to
203 // a FutureBase pointer
204 using typename Base::value_type;
206 /// Construct a Future from a value (perfect forwarding)
209 typename = typename std::enable_if<
210 !isFuture<typename std::decay<T2>::type>::value &&
211 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
212 /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
214 template <class T2 = T>
215 /* implicit */ SemiFuture(
216 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
221 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
223 explicit SemiFuture(in_place_t, Args&&... args)
224 : Base(in_place, std::forward<Args>(args)...) {}
226 SemiFuture(SemiFuture<T> const&) = delete;
228 SemiFuture(SemiFuture<T>&&) noexcept;
229 // safe move-constructabilty from Future
230 /* implicit */ SemiFuture(Future<T>&&) noexcept;
233 using Base::hasException;
234 using Base::hasValue;
235 using Base::isActive;
239 using Base::setCallback_;
242 SemiFuture& operator=(SemiFuture const&) = delete;
243 SemiFuture& operator=(SemiFuture&&) noexcept;
244 SemiFuture& operator=(Future<T>&&) noexcept;
246 /// Block until the future is fulfilled. Returns the value (moved out), or
247 /// throws the exception. The future must not already have a callback.
250 /// Block until the future is fulfilled, or until timed out. Returns the
251 /// value (moved out), or throws the exception (which might be a TimedOut
253 T get(Duration dur) &&;
255 /// Block until the future is fulfilled, or until timed out. Returns the
256 /// Try of the value (moved out).
259 /// Call e->drive() repeatedly until the future is fulfilled. Examples
260 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
261 /// value (moved out), or throws the exception.
262 T getVia(DrivableExecutor* e) &&;
264 /// Call e->drive() repeatedly until the future is fulfilled. Examples
265 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
266 /// Try of the value (moved out).
267 Try<T> getTryVia(DrivableExecutor* e) &&;
269 /// Block until this Future is complete. Returns a reference to this Future.
270 SemiFuture<T>& wait() &;
272 /// Overload of wait() for rvalue Futures
273 SemiFuture<T>&& wait() &&;
275 /// Block until this Future is complete or until the given Duration passes.
276 /// Returns a reference to this Future
277 SemiFuture<T>& wait(Duration) &;
279 /// Overload of wait(Duration) for rvalue Futures
280 SemiFuture<T>&& wait(Duration) &&;
282 /// Call e->drive() repeatedly until the future is fulfilled. Examples
283 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
284 /// reference to this SemiFuture so that you can chain calls if desired.
285 /// value (moved out), or throws the exception.
286 SemiFuture<T>& waitVia(DrivableExecutor* e) &;
288 /// Overload of waitVia() for rvalue Futures
289 SemiFuture<T>&& waitVia(DrivableExecutor* e) &&;
291 /// Returns an inactive Future which will call back on the other side of
292 /// executor (when it is activated).
294 /// NB remember that Futures activate when they destruct. This is good,
295 /// it means that this will work:
297 /// f.via(e).then(a).then(b);
299 /// a and b will execute in the same context (the far side of e), because
300 /// the Future (temporary variable) created by via(e) does not call back
301 /// until it destructs, which is after then(a) and then(b) have been wired
304 /// But this is still racy:
306 /// f = f.via(e).then(a);
308 // The ref-qualifier allows for `this` to be moved out so we
309 // don't get access-after-free situations in chaining.
310 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
311 inline Future<T> via(
313 int8_t priority = Executor::MID_PRI) &&;
316 * Defer work to run on the consumer of the future.
317 * This work will be run eithe ron an executor that the caller sets on the
318 * SemiFuture, or inline with the call to .get().
319 * NB: This is a custom method because boost-blocking executors is a
320 * special-case for work deferral in folly. With more general boost-blocking
321 * support all executors would boost block and we would simply use some form
322 * of driveable executor here.
324 template <typename F>
325 SemiFuture<typename futures::detail::callableResult<T, F>::Return::value_type>
328 // Public as for setCallback_
329 // Ensure that a boostable executor performs work to chain deferred work
334 friend class Promise<T>;
336 friend class futures::detail::FutureBase;
338 friend class SemiFuture;
340 using typename Base::corePtr;
341 using Base::setExecutor;
342 using Base::throwIfInvalid;
345 friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
347 explicit SemiFuture(corePtr obj) : Base(obj) {}
349 explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
350 : Base(futures::detail::EmptyConstruct{}) {}
354 class Future : private futures::detail::FutureBase<T> {
356 using Base = futures::detail::FutureBase<T>;
359 // Export public interface of FutureBase
360 // FutureBase is inherited privately to avoid subclasses being cast to
361 // a FutureBase pointer
362 using typename Base::value_type;
364 /// Construct a Future from a value (perfect forwarding)
367 typename = typename std::enable_if<
368 !isFuture<typename std::decay<T2>::type>::value &&
369 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
370 /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
372 template <class T2 = T>
373 /* implicit */ Future(
374 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
379 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
381 explicit Future(in_place_t, Args&&... args)
382 : Base(in_place, std::forward<Args>(args)...) {}
384 Future(Future<T> const&) = delete;
386 Future(Future<T>&&) noexcept;
391 typename std::enable_if<
392 !std::is_same<T, typename std::decay<T2>::type>::value &&
393 std::is_constructible<T, T2&&>::value &&
394 std::is_convertible<T2&&, T>::value,
396 /* implicit */ Future(Future<T2>&&);
399 typename std::enable_if<
400 !std::is_same<T, typename std::decay<T2>::type>::value &&
401 std::is_constructible<T, T2&&>::value &&
402 !std::is_convertible<T2&&, T>::value,
404 explicit Future(Future<T2>&&);
407 typename std::enable_if<
408 !std::is_same<T, typename std::decay<T2>::type>::value &&
409 std::is_constructible<T, T2&&>::value,
411 Future& operator=(Future<T2>&&);
414 using Base::hasException;
415 using Base::hasValue;
416 using Base::isActive;
420 using Base::setCallback_;
423 static Future<T> makeEmpty(); // equivalent to moved-from
426 Future& operator=(Future const&) = delete;
429 Future& operator=(Future&&) noexcept;
431 /// Call e->drive() repeatedly until the future is fulfilled. Examples
432 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
433 /// value (moved out), or throws the exception.
434 T getVia(DrivableExecutor* e);
436 /// Call e->drive() repeatedly until the future is fulfilled. Examples
437 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
438 /// reference to the Try of the value.
439 Try<T>& getTryVia(DrivableExecutor* e);
441 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
442 /// Future<T> instance.
443 template <class F = T>
445 enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
448 /// Returns an inactive Future which will call back on the other side of
449 /// executor (when it is activated).
451 /// NB remember that Futures activate when they destruct. This is good,
452 /// it means that this will work:
454 /// f.via(e).then(a).then(b);
456 /// a and b will execute in the same context (the far side of e), because
457 /// the Future (temporary variable) created by via(e) does not call back
458 /// until it destructs, which is after then(a) and then(b) have been wired
461 /// But this is still racy:
463 /// f = f.via(e).then(a);
465 // The ref-qualifier allows for `this` to be moved out so we
466 // don't get access-after-free situations in chaining.
467 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
468 inline Future<T> via(
470 int8_t priority = Executor::MID_PRI) &&;
472 /// This variant creates a new future, where the ref-qualifier && version
473 /// moves `this` out. This one is less efficient but avoids confusing users
474 /// when "return f.via(x);" fails.
475 inline Future<T> via(
477 int8_t priority = Executor::MID_PRI) &;
479 /** When this Future has completed, execute func which is a function that
489 Func shall return either another Future or a value.
491 A Future for the return type of func is returned.
493 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
495 The Future given to the functor is ready, and the functor may call
496 value(), which may rethrow if this has captured an exception. If func
497 throws, the exception will be captured in the Future that is returned.
499 template <typename F, typename R = futures::detail::callableResult<T, F>>
500 typename R::Return then(F&& func) {
501 return this->template thenImplementation<F, R>(
502 std::forward<F>(func), typename R::Arg());
505 /// Variant where func is an member function
507 /// struct Worker { R doWork(Try<T>); }
510 /// Future<R> f2 = f1.then(&Worker::doWork, w);
512 /// This is just sugar for
514 /// f1.then(std::bind(&Worker::doWork, w));
515 template <typename R, typename Caller, typename... Args>
516 Future<typename isFuture<R>::Inner> then(
517 R (Caller::*func)(Args...),
520 /// Execute the callback via the given Executor. The executor doesn't stick.
524 /// f.via(x).then(b).then(c)
528 /// f.then(x, b).then(c)
530 /// In the former both b and c execute via x. In the latter, only b executes
531 /// via x, and c executes via the same executor (if any) that f had.
532 template <class Executor, class Arg, class... Args>
533 auto then(Executor* x, Arg&& arg, Args&&... args) {
534 auto oldX = this->getExecutor();
535 this->setExecutor(x);
536 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
540 /// Convenience method for ignoring the value and creating a Future<Unit>.
541 /// Exceptions still propagate.
542 /// This function is identical to .unit().
545 /// Convenience method for ignoring the value and creating a Future<Unit>.
546 /// Exceptions still propagate.
547 /// This function is identical to parameterless .then().
548 Future<Unit> unit() {
552 /// Set an error callback for this Future. The callback should take a single
553 /// argument of the type that you want to catch, and should return a value of
554 /// the same type as this Future, or a Future of that type (see overload
555 /// below). For instance,
559 /// throw std::runtime_error("oh no!");
562 /// .onError([] (std::runtime_error& e) {
563 /// LOG(INFO) << "std::runtime_error: " << e.what();
564 /// return -1; // or makeFuture<int>(-1)
567 typename std::enable_if<
568 !futures::detail::callableWith<F, exception_wrapper>::value &&
569 !futures::detail::callableWith<F, exception_wrapper&>::value &&
570 !futures::detail::Extract<F>::ReturnsFuture::value,
574 /// Overload of onError where the error callback returns a Future<T>
576 typename std::enable_if<
577 !futures::detail::callableWith<F, exception_wrapper>::value &&
578 !futures::detail::callableWith<F, exception_wrapper&>::value &&
579 futures::detail::Extract<F>::ReturnsFuture::value,
583 /// Overload of onError that takes exception_wrapper and returns Future<T>
585 typename std::enable_if<
586 futures::detail::callableWith<F, exception_wrapper>::value &&
587 futures::detail::Extract<F>::ReturnsFuture::value,
591 /// Overload of onError that takes exception_wrapper and returns T
593 typename std::enable_if<
594 futures::detail::callableWith<F, exception_wrapper>::value &&
595 !futures::detail::Extract<F>::ReturnsFuture::value,
599 /// func is like std::function<void()> and is executed unconditionally, and
600 /// the value/exception is passed through to the resulting Future.
601 /// func shouldn't throw, but if it does it will be captured and propagated,
602 /// and discard any value/exception that this Future has obtained.
604 Future<T> ensure(F&& func);
606 /// Like onError, but for timeouts. example:
608 /// Future<int> f = makeFuture<int>(42)
609 /// .delayed(long_time)
610 /// .onTimeout(short_time,
611 /// []() -> int{ return -1; });
615 /// Future<int> f = makeFuture<int>(42)
616 /// .delayed(long_time)
617 /// .onTimeout(short_time,
618 /// []() { return makeFuture<int>(some_exception); });
620 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
622 /// A Future's callback is executed when all three of these conditions have
623 /// become true: it has a value (set by the Promise), it has a callback (set
624 /// by then), and it is active (active by default).
626 /// Inactive Futures will activate upon destruction.
627 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
628 this->core_->activate();
631 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
632 this->core_->deactivate();
635 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
636 this->core_->activate();
637 return std::move(*this);
639 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
640 this->core_->deactivate();
641 return std::move(*this);
644 /// Throw TimedOut if this Future does not complete within the given
645 /// duration from now. The optional Timeekeeper is as with futures::sleep().
646 Future<T> within(Duration, Timekeeper* = nullptr);
648 /// Throw the given exception if this Future does not complete within the
649 /// given duration from now. The optional Timeekeeper is as with
650 /// futures::sleep().
652 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
654 /// Delay the completion of this Future for at least this duration from
655 /// now. The optional Timekeeper is as with futures::sleep().
656 Future<T> delayed(Duration, Timekeeper* = nullptr);
658 /// Block until the future is fulfilled. Returns the value (moved out), or
659 /// throws the exception. The future must not already have a callback.
662 /// Block until the future is fulfilled, or until timed out. Returns the
663 /// value (moved out), or throws the exception (which might be a TimedOut
667 /** A reference to the Try of the value */
670 /// Block until this Future is complete. Returns a reference to this Future.
673 /// Overload of wait() for rvalue Futures
674 Future<T>&& wait() &&;
676 /// Block until this Future is complete or until the given Duration passes.
677 /// Returns a reference to this Future
678 Future<T>& wait(Duration) &;
680 /// Overload of wait(Duration) for rvalue Futures
681 Future<T>&& wait(Duration) &&;
683 /// Call e->drive() repeatedly until the future is fulfilled. Examples
684 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
685 /// reference to this Future so that you can chain calls if desired.
686 /// value (moved out), or throws the exception.
687 Future<T>& waitVia(DrivableExecutor* e) &;
689 /// Overload of waitVia() for rvalue Futures
690 Future<T>&& waitVia(DrivableExecutor* e) &&;
692 /// If the value in this Future is equal to the given Future, when they have
693 /// both completed, the value of the resulting Future<bool> will be true. It
694 /// will be false otherwise (including when one or both Futures have an
696 Future<bool> willEqual(Future<T>&);
698 /// predicate behaves like std::function<bool(T const&)>
699 /// If the predicate does not obtain with the value, the result
700 /// is a folly::PredicateDoesNotObtain exception
702 Future<T> filter(F&& predicate);
704 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
705 /// the result of collect or collectAll
706 template <class I, class F>
707 Future<I> reduce(I&& initial, F&& func);
709 /// Create a Future chain from a sequence of callbacks. i.e.
711 /// f.then(a).then(b).then(c)
713 /// where f is a Future<A> and the result of the chain is a Future<D>
716 /// f.thenMulti(a, b, c);
717 template <class Callback, class... Callbacks>
718 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
719 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
720 return then(std::forward<Callback>(fn))
721 .thenMulti(std::forward<Callbacks>(fns)...);
724 template <class Callback>
725 auto thenMulti(Callback&& fn) {
726 // thenMulti with one callback is just a then
727 return then(std::forward<Callback>(fn));
730 /// Create a Future chain from a sequence of callbacks. i.e.
732 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
734 /// where f is a Future<A> and the result of the chain is a Future<D>
737 /// f.thenMultiWithExecutor(executor, a, b, c);
738 template <class Callback, class... Callbacks>
739 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
740 // thenMultiExecutor with two callbacks is
741 // via(x).then(a).thenMulti(b, ...).via(oldX)
742 auto oldX = this->getExecutor();
743 this->setExecutor(x);
744 return then(std::forward<Callback>(fn))
745 .thenMulti(std::forward<Callbacks>(fns)...)
749 template <class Callback>
750 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
751 // thenMulti with one callback is just a then with an executor
752 return then(x, std::forward<Callback>(fn));
755 // Convert this Future to a SemiFuture to safely export from a library
756 // without exposing a continuation interface
757 SemiFuture<T> semi() {
758 return SemiFuture<T>{std::move(*this)};
762 friend class Promise<T>;
764 friend class futures::detail::FutureBase;
768 friend class SemiFuture;
770 using Base::setExecutor;
771 using Base::throwIfInvalid;
772 using typename Base::corePtr;
774 explicit Future(corePtr obj) : Base(obj) {}
776 explicit Future(futures::detail::EmptyConstruct) noexcept
777 : Base(futures::detail::EmptyConstruct{}) {}
780 friend Future<T2> makeFuture(Try<T2>&&);
782 /// Repeat the given future (i.e., the computation it contains)
785 /// thunk behaves like std::function<Future<T2>(void)>
787 friend Future<Unit> times(int n, F&& thunk);
789 /// Carry out the computation contained in the given future if
790 /// the predicate holds.
792 /// thunk behaves like std::function<Future<T2>(void)>
794 friend Future<Unit> when(bool p, F&& thunk);
796 /// Carry out the computation contained in the given future if
797 /// while the predicate continues to hold.
799 /// thunk behaves like std::function<Future<T2>(void)>
801 /// predicate behaves like std::function<bool(void)>
802 template <class P, class F>
803 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
808 #include <folly/futures/Future-inl.h>