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>::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 /** True when the result (or exception) is ready. */
100 bool isReady() const;
102 /// sugar for getTry().hasValue()
105 /// sugar for getTry().hasException()
108 /** A reference to the Try of the value */
111 /// If the promise has been fulfilled, return an Optional with the Try<T>.
112 /// Otherwise return an empty Optional.
113 /// Note that this moves the Try<T> out.
114 Optional<Try<T>> poll();
116 /// This is not the method you're looking for.
118 /// This needs to be public because it's used by make* and when*, and it's
119 /// not worth listing all those and their fancy template signatures as
120 /// friends. But it's not for public consumption.
122 void setCallback_(F&& func);
125 return core_->isActive();
129 void raise(E&& exception) {
130 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
131 std::forward<E>(exception)));
134 /// Raise an interrupt. If the promise holder has an interrupt
135 /// handler it will be called and potentially stop asynchronous work from
136 /// being done. This is advisory only - a promise holder may not set an
137 /// interrupt handler, or may do anything including ignore. But, if you know
138 /// your future supports this the most likely result is stopping or
139 /// preventing the asynchronous operation (if in time), and the promise
140 /// holder setting an exception on the future. (That may happen
141 /// asynchronously, of course.)
142 void raise(exception_wrapper interrupt);
145 raise(FutureCancellation());
149 friend class Promise<T>;
151 friend class SemiFuture;
155 using corePtr = futures::detail::Core<T>*;
157 // shared core state object
160 explicit FutureBase(corePtr obj) : core_(obj) {}
162 explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
166 void throwIfInvalid() const;
168 template <class FutureType>
169 void assign(FutureType&) noexcept;
171 Executor* getExecutor() {
172 return core_->getExecutor();
175 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
176 core_->setExecutor(x, priority);
179 // Variant: returns a value
180 // e.g. f.then([](Try<T> t){ return t.value(); });
181 template <typename F, typename R, bool isTry, typename... Args>
182 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
183 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
185 // Variant: returns a Future
186 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
187 template <typename F, typename R, bool isTry, typename... Args>
188 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
189 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
191 } // namespace detail
192 } // namespace futures
195 class SemiFuture : private futures::detail::FutureBase<T> {
197 using Base = futures::detail::FutureBase<T>;
198 using DeferredExecutor = futures::detail::DeferredExecutor;
201 static SemiFuture<T> makeEmpty(); // equivalent to moved-from
203 // Export public interface of FutureBase
204 // FutureBase is inherited privately to avoid subclasses being cast to
205 // a FutureBase pointer
206 using typename Base::value_type;
208 /// Construct a Future from a value (perfect forwarding)
211 typename = typename std::enable_if<
212 !isFuture<typename std::decay<T2>::type>::value &&
213 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
214 /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
216 template <class T2 = T>
217 /* implicit */ SemiFuture(
218 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
223 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
225 explicit SemiFuture(in_place_t, Args&&... args)
226 : Base(in_place, std::forward<Args>(args)...) {}
228 SemiFuture(SemiFuture<T> const&) = delete;
230 SemiFuture(SemiFuture<T>&&) noexcept;
231 // safe move-constructabilty from Future
232 /* implicit */ SemiFuture(Future<T>&&) noexcept;
236 using Base::hasException;
237 using Base::hasValue;
238 using Base::isActive;
242 using Base::setCallback_;
245 SemiFuture& operator=(SemiFuture const&) = delete;
246 SemiFuture& operator=(SemiFuture&&) noexcept;
247 SemiFuture& operator=(Future<T>&&) noexcept;
249 /// Block until the future is fulfilled. Returns the value (moved out), or
250 /// throws the exception. The future must not already have a callback.
253 /// Block until the future is fulfilled, or until timed out. Returns the
254 /// value (moved out), or throws the exception (which might be a TimedOut
256 T get(Duration dur) &&;
258 /// Block until this Future is complete. Returns a reference to this Future.
259 SemiFuture<T>& wait() &;
261 /// Overload of wait() for rvalue Futures
262 SemiFuture<T>&& wait() &&;
264 /// Block until this Future is complete or until the given Duration passes.
265 /// Returns a reference to this Future
266 SemiFuture<T>& wait(Duration) &;
268 /// Overload of wait(Duration) for rvalue Futures
269 SemiFuture<T>&& wait(Duration) &&;
271 /// Returns an inactive Future which will call back on the other side of
272 /// executor (when it is activated).
274 /// NB remember that Futures activate when they destruct. This is good,
275 /// it means that this will work:
277 /// f.via(e).then(a).then(b);
279 /// a and b will execute in the same context (the far side of e), because
280 /// the Future (temporary variable) created by via(e) does not call back
281 /// until it destructs, which is after then(a) and then(b) have been wired
284 /// But this is still racy:
286 /// f = f.via(e).then(a);
288 // The ref-qualifier allows for `this` to be moved out so we
289 // don't get access-after-free situations in chaining.
290 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
291 inline Future<T> via(
293 int8_t priority = Executor::MID_PRI) &&;
296 * Defer work to run on the consumer of the future.
297 * This work will be run eithe ron an executor that the caller sets on the
298 * SemiFuture, or inline with the call to .get().
299 * NB: This is a custom method because boost-blocking executors is a
300 * special-case for work deferral in folly. With more general boost-blocking
301 * support all executors would boost block and we would simply use some form
302 * of driveable executor here.
304 template <typename F>
305 SemiFuture<typename futures::detail::callableResult<T, F>::Return::value_type>
308 // Public as for setCallback_
309 // Ensure that a boostable executor performs work to chain deferred work
315 friend class futures::detail::FutureBase;
317 friend class SemiFuture;
319 using typename Base::corePtr;
320 using Base::setExecutor;
321 using Base::throwIfInvalid;
324 friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
326 explicit SemiFuture(corePtr obj) : Base(obj) {}
328 explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
329 : Base(futures::detail::EmptyConstruct{}) {}
333 class Future : private futures::detail::FutureBase<T> {
335 using Base = futures::detail::FutureBase<T>;
338 // Export public interface of FutureBase
339 // FutureBase is inherited privately to avoid subclasses being cast to
340 // a FutureBase pointer
341 using typename Base::value_type;
343 /// Construct a Future from a value (perfect forwarding)
346 typename = typename std::enable_if<
347 !isFuture<typename std::decay<T2>::type>::value &&
348 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
349 /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
351 template <class T2 = T>
352 /* implicit */ Future(
353 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
358 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
360 explicit Future(in_place_t, Args&&... args)
361 : Base(in_place, std::forward<Args>(args)...) {}
363 Future(Future<T> const&) = delete;
365 Future(Future<T>&&) noexcept;
370 typename std::enable_if<
371 !std::is_same<T, typename std::decay<T2>::type>::value &&
372 std::is_constructible<T, T2&&>::value &&
373 std::is_convertible<T2&&, T>::value,
375 /* implicit */ Future(Future<T2>&&);
378 typename std::enable_if<
379 !std::is_same<T, typename std::decay<T2>::type>::value &&
380 std::is_constructible<T, T2&&>::value &&
381 !std::is_convertible<T2&&, T>::value,
383 explicit Future(Future<T2>&&);
386 typename std::enable_if<
387 !std::is_same<T, typename std::decay<T2>::type>::value &&
388 std::is_constructible<T, T2&&>::value,
390 Future& operator=(Future<T2>&&);
394 using Base::hasException;
395 using Base::hasValue;
396 using Base::isActive;
400 using Base::setCallback_;
403 static Future<T> makeEmpty(); // equivalent to moved-from
406 Future& operator=(Future const&) = delete;
409 Future& operator=(Future&&) noexcept;
411 /// Call e->drive() repeatedly until the future is fulfilled. Examples
412 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
413 /// reference to the Try of the value.
414 Try<T>& getTryVia(DrivableExecutor* e);
416 /// Call e->drive() repeatedly until the future is fulfilled. Examples
417 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
418 /// value (moved out), or throws the exception.
419 T getVia(DrivableExecutor* e);
421 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
422 /// Future<T> instance.
423 template <class F = T>
425 enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
428 /// Returns an inactive Future which will call back on the other side of
429 /// executor (when it is activated).
431 /// NB remember that Futures activate when they destruct. This is good,
432 /// it means that this will work:
434 /// f.via(e).then(a).then(b);
436 /// a and b will execute in the same context (the far side of e), because
437 /// the Future (temporary variable) created by via(e) does not call back
438 /// until it destructs, which is after then(a) and then(b) have been wired
441 /// But this is still racy:
443 /// f = f.via(e).then(a);
445 // The ref-qualifier allows for `this` to be moved out so we
446 // don't get access-after-free situations in chaining.
447 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
448 inline Future<T> via(
450 int8_t priority = Executor::MID_PRI) &&;
452 /// This variant creates a new future, where the ref-qualifier && version
453 /// moves `this` out. This one is less efficient but avoids confusing users
454 /// when "return f.via(x);" fails.
455 inline Future<T> via(
457 int8_t priority = Executor::MID_PRI) &;
459 /** When this Future has completed, execute func which is a function that
469 Func shall return either another Future or a value.
471 A Future for the return type of func is returned.
473 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
475 The Future given to the functor is ready, and the functor may call
476 value(), which may rethrow if this has captured an exception. If func
477 throws, the exception will be captured in the Future that is returned.
479 template <typename F, typename R = futures::detail::callableResult<T, F>>
480 typename R::Return then(F&& func) {
481 return this->template thenImplementation<F, R>(
482 std::forward<F>(func), typename R::Arg());
485 /// Variant where func is an member function
487 /// struct Worker { R doWork(Try<T>); }
490 /// Future<R> f2 = f1.then(&Worker::doWork, w);
492 /// This is just sugar for
494 /// f1.then(std::bind(&Worker::doWork, w));
495 template <typename R, typename Caller, typename... Args>
496 Future<typename isFuture<R>::Inner> then(
497 R (Caller::*func)(Args...),
500 /// Execute the callback via the given Executor. The executor doesn't stick.
504 /// f.via(x).then(b).then(c)
508 /// f.then(x, b).then(c)
510 /// In the former both b and c execute via x. In the latter, only b executes
511 /// via x, and c executes via the same executor (if any) that f had.
512 template <class Executor, class Arg, class... Args>
513 auto then(Executor* x, Arg&& arg, Args&&... args) {
514 auto oldX = this->getExecutor();
515 this->setExecutor(x);
516 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
520 /// Convenience method for ignoring the value and creating a Future<Unit>.
521 /// Exceptions still propagate.
522 /// This function is identical to .unit().
525 /// Convenience method for ignoring the value and creating a Future<Unit>.
526 /// Exceptions still propagate.
527 /// This function is identical to parameterless .then().
528 Future<Unit> unit() {
532 /// Set an error callback for this Future. The callback should take a single
533 /// argument of the type that you want to catch, and should return a value of
534 /// the same type as this Future, or a Future of that type (see overload
535 /// below). For instance,
539 /// throw std::runtime_error("oh no!");
542 /// .onError([] (std::runtime_error& e) {
543 /// LOG(INFO) << "std::runtime_error: " << e.what();
544 /// return -1; // or makeFuture<int>(-1)
547 typename std::enable_if<
548 !futures::detail::callableWith<F, exception_wrapper>::value &&
549 !futures::detail::callableWith<F, exception_wrapper&>::value &&
550 !futures::detail::Extract<F>::ReturnsFuture::value,
554 /// Overload of onError where the error callback returns a Future<T>
556 typename std::enable_if<
557 !futures::detail::callableWith<F, exception_wrapper>::value &&
558 !futures::detail::callableWith<F, exception_wrapper&>::value &&
559 futures::detail::Extract<F>::ReturnsFuture::value,
563 /// Overload of onError that takes exception_wrapper and returns Future<T>
565 typename std::enable_if<
566 futures::detail::callableWith<F, exception_wrapper>::value &&
567 futures::detail::Extract<F>::ReturnsFuture::value,
571 /// Overload of onError that takes exception_wrapper and returns T
573 typename std::enable_if<
574 futures::detail::callableWith<F, exception_wrapper>::value &&
575 !futures::detail::Extract<F>::ReturnsFuture::value,
579 /// func is like std::function<void()> and is executed unconditionally, and
580 /// the value/exception is passed through to the resulting Future.
581 /// func shouldn't throw, but if it does it will be captured and propagated,
582 /// and discard any value/exception that this Future has obtained.
584 Future<T> ensure(F&& func);
586 /// Like onError, but for timeouts. example:
588 /// Future<int> f = makeFuture<int>(42)
589 /// .delayed(long_time)
590 /// .onTimeout(short_time,
591 /// []() -> int{ return -1; });
595 /// Future<int> f = makeFuture<int>(42)
596 /// .delayed(long_time)
597 /// .onTimeout(short_time,
598 /// []() { return makeFuture<int>(some_exception); });
600 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
602 /// A Future's callback is executed when all three of these conditions have
603 /// become true: it has a value (set by the Promise), it has a callback (set
604 /// by then), and it is active (active by default).
606 /// Inactive Futures will activate upon destruction.
607 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
608 this->core_->activate();
611 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
612 this->core_->deactivate();
615 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
616 this->core_->activate();
617 return std::move(*this);
619 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
620 this->core_->deactivate();
621 return std::move(*this);
624 /// Throw TimedOut if this Future does not complete within the given
625 /// duration from now. The optional Timeekeeper is as with futures::sleep().
626 Future<T> within(Duration, Timekeeper* = nullptr);
628 /// Throw the given exception if this Future does not complete within the
629 /// given duration from now. The optional Timeekeeper is as with
630 /// futures::sleep().
632 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
634 /// Delay the completion of this Future for at least this duration from
635 /// now. The optional Timekeeper is as with futures::sleep().
636 Future<T> delayed(Duration, Timekeeper* = nullptr);
638 /// Block until the future is fulfilled. Returns the value (moved out), or
639 /// throws the exception. The future must not already have a callback.
642 /// Block until the future is fulfilled, or until timed out. Returns the
643 /// value (moved out), or throws the exception (which might be a TimedOut
647 /// Block until this Future is complete. Returns a reference to this Future.
650 /// Overload of wait() for rvalue Futures
651 Future<T>&& wait() &&;
653 /// Block until this Future is complete or until the given Duration passes.
654 /// Returns a reference to this Future
655 Future<T>& wait(Duration) &;
657 /// Overload of wait(Duration) for rvalue Futures
658 Future<T>&& wait(Duration) &&;
660 /// Call e->drive() repeatedly until the future is fulfilled. Examples
661 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
662 /// reference to this Future so that you can chain calls if desired.
663 /// value (moved out), or throws the exception.
664 Future<T>& waitVia(DrivableExecutor* e) &;
666 /// Overload of waitVia() for rvalue Futures
667 Future<T>&& waitVia(DrivableExecutor* e) &&;
669 /// If the value in this Future is equal to the given Future, when they have
670 /// both completed, the value of the resulting Future<bool> will be true. It
671 /// will be false otherwise (including when one or both Futures have an
673 Future<bool> willEqual(Future<T>&);
675 /// predicate behaves like std::function<bool(T const&)>
676 /// If the predicate does not obtain with the value, the result
677 /// is a folly::PredicateDoesNotObtain exception
679 Future<T> filter(F&& predicate);
681 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
682 /// the result of collect or collectAll
683 template <class I, class F>
684 Future<I> reduce(I&& initial, F&& func);
686 /// Create a Future chain from a sequence of callbacks. i.e.
688 /// f.then(a).then(b).then(c)
690 /// where f is a Future<A> and the result of the chain is a Future<D>
693 /// f.thenMulti(a, b, c);
694 template <class Callback, class... Callbacks>
695 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
696 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
697 return then(std::forward<Callback>(fn))
698 .thenMulti(std::forward<Callbacks>(fns)...);
701 template <class Callback>
702 auto thenMulti(Callback&& fn) {
703 // thenMulti with one callback is just a then
704 return then(std::forward<Callback>(fn));
707 /// Create a Future chain from a sequence of callbacks. i.e.
709 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
711 /// where f is a Future<A> and the result of the chain is a Future<D>
714 /// f.thenMultiWithExecutor(executor, a, b, c);
715 template <class Callback, class... Callbacks>
716 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
717 // thenMultiExecutor with two callbacks is
718 // via(x).then(a).thenMulti(b, ...).via(oldX)
719 auto oldX = this->getExecutor();
720 this->setExecutor(x);
721 return then(std::forward<Callback>(fn))
722 .thenMulti(std::forward<Callbacks>(fns)...)
726 template <class Callback>
727 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
728 // thenMulti with one callback is just a then with an executor
729 return then(x, std::forward<Callback>(fn));
732 // Convert this Future to a SemiFuture to safely export from a library
733 // without exposing a continuation interface
734 SemiFuture<T> semi() {
735 return SemiFuture<T>{std::move(*this)};
739 friend class Promise<T>;
741 friend class futures::detail::FutureBase;
745 friend class SemiFuture;
747 using Base::setExecutor;
748 using Base::throwIfInvalid;
749 using typename Base::corePtr;
751 explicit Future(corePtr obj) : Base(obj) {}
753 explicit Future(futures::detail::EmptyConstruct) noexcept
754 : Base(futures::detail::EmptyConstruct{}) {}
757 friend Future<T2> makeFuture(Try<T2>&&);
759 /// Repeat the given future (i.e., the computation it contains)
762 /// thunk behaves like std::function<Future<T2>(void)>
764 friend Future<Unit> times(int n, F&& thunk);
766 /// Carry out the computation contained in the given future if
767 /// the predicate holds.
769 /// thunk behaves like std::function<Future<T2>(void)>
771 friend Future<Unit> when(bool p, F&& thunk);
773 /// Carry out the computation contained in the given future if
774 /// while the predicate continues to hold.
776 /// thunk behaves like std::function<Future<T2>(void)>
778 /// predicate behaves like std::function<bool(void)>
779 template <class P, class F>
780 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
785 #include <folly/futures/Future-inl.h>