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/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>::type>
62 /* implicit */ FutureBase(T2&& val);
64 template <class T2 = T>
65 /* implicit */ FutureBase(
66 typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
70 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
72 explicit FutureBase(in_place_t, Args&&... args);
74 FutureBase(FutureBase<T> const&) = delete;
75 FutureBase(SemiFuture<T>&&) noexcept;
76 FutureBase(Future<T>&&) noexcept;
79 FutureBase(Future<T> const&) = delete;
80 FutureBase(SemiFuture<T> const&) = delete;
84 /// Returns a reference to the result, with a reference category and const-
85 /// qualification equivalent to the reference category and const-qualification
88 /// If moved-from, throws NoState.
90 /// If !isReady(), throws FutureNotReady.
92 /// If an exception has been captured, throws that exception.
94 T const& value() const&;
96 T const&& value() const&&;
98 /// Returns an inactive Future which will call back on the other side of
99 /// executor (when it is activated).
101 /// NB remember that Futures activate when they destruct. This is good,
102 /// it means that this will work:
104 /// f.via(e).then(a).then(b);
106 /// a and b will execute in the same context (the far side of e), because
107 /// the Future (temporary variable) created by via(e) does not call back
108 /// until it destructs, which is after then(a) and then(b) have been wired
111 /// But this is still racy:
113 /// f = f.via(e).then(a);
115 // The ref-qualifier allows for `this` to be moved out so we
116 // don't get access-after-free situations in chaining.
117 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
118 inline Future<T> via(
120 int8_t priority = Executor::MID_PRI) &&;
122 /** True when the result (or exception) is ready. */
123 bool isReady() const;
125 /// sugar for getTry().hasValue()
128 /// sugar for getTry().hasException()
131 /** A reference to the Try of the value */
134 /// If the promise has been fulfilled, return an Optional with the Try<T>.
135 /// Otherwise return an empty Optional.
136 /// Note that this moves the Try<T> out.
137 Optional<Try<T>> poll();
139 /// This is not the method you're looking for.
141 /// This needs to be public because it's used by make* and when*, and it's
142 /// not worth listing all those and their fancy template signatures as
143 /// friends. But it's not for public consumption.
145 void setCallback_(F&& func);
148 return core_->isActive();
152 void raise(E&& exception) {
153 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
154 std::forward<E>(exception)));
157 /// Raise an interrupt. If the promise holder has an interrupt
158 /// handler it will be called and potentially stop asynchronous work from
159 /// being done. This is advisory only - a promise holder may not set an
160 /// interrupt handler, or may do anything including ignore. But, if you know
161 /// your future supports this the most likely result is stopping or
162 /// preventing the asynchronous operation (if in time), and the promise
163 /// holder setting an exception on the future. (That may happen
164 /// asynchronously, of course.)
165 void raise(exception_wrapper interrupt);
168 raise(FutureCancellation());
172 friend class Promise<T>;
174 friend class SemiFuture;
178 using corePtr = futures::detail::Core<T>*;
180 // shared core state object
183 explicit FutureBase(corePtr obj) : core_(obj) {}
185 explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
189 void throwIfInvalid() const;
191 template <class FutureType>
192 void assign(FutureType&) noexcept;
194 Executor* getExecutor() {
195 return core_->getExecutor();
198 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
199 core_->setExecutor(x, priority);
202 // Variant: returns a value
203 // e.g. f.then([](Try<T> t){ return t.value(); });
204 template <typename F, typename R, bool isTry, typename... Args>
205 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
206 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
208 // Variant: returns a Future
209 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
210 template <typename F, typename R, bool isTry, typename... Args>
211 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
212 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
214 } // namespace detail
215 } // namespace futures
218 class SemiFuture : private futures::detail::FutureBase<T> {
220 using Base = futures::detail::FutureBase<T>;
223 static SemiFuture<T> makeEmpty(); // equivalent to moved-from
225 // Export public interface of FutureBase
226 // FutureBase is inherited privately to avoid subclasses being cast to
227 // a FutureBase pointer
228 using typename Base::value_type;
230 /// Construct a Future from a value (perfect forwarding)
233 typename = typename std::enable_if<
234 !isFuture<typename std::decay<T2>::type>::value>::type>
235 /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
237 template <class T2 = T>
238 /* implicit */ SemiFuture(
239 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
244 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
246 explicit SemiFuture(in_place_t, Args&&... args)
247 : Base(in_place, std::forward<Args>(args)...) {}
249 SemiFuture(SemiFuture<T> const&) = delete;
251 SemiFuture(SemiFuture<T>&&) noexcept;
252 // safe move-constructabilty from Future
253 /* implicit */ SemiFuture(Future<T>&&) noexcept;
257 using Base::hasException;
258 using Base::hasValue;
259 using Base::isActive;
263 using Base::setCallback_;
267 SemiFuture& operator=(SemiFuture const&) = delete;
268 SemiFuture& operator=(SemiFuture&&) noexcept;
269 SemiFuture& operator=(Future<T>&&) noexcept;
271 /// Block until the future is fulfilled. Returns the value (moved out), or
272 /// throws the exception. The future must not already have a callback.
275 /// Block until the future is fulfilled, or until timed out. Returns the
276 /// value (moved out), or throws the exception (which might be a TimedOut
278 T get(Duration dur) &&;
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) &&;
295 friend class futures::detail::FutureBase;
297 using typename Base::corePtr;
300 friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
302 explicit SemiFuture(corePtr obj) : Base(obj) {}
304 explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
305 : Base(futures::detail::EmptyConstruct{}) {}
309 class Future : private futures::detail::FutureBase<T> {
311 using Base = futures::detail::FutureBase<T>;
314 // Export public interface of FutureBase
315 // FutureBase is inherited privately to avoid subclasses being cast to
316 // a FutureBase pointer
317 using typename Base::value_type;
319 /// Construct a Future from a value (perfect forwarding)
322 typename = typename std::enable_if<
323 !isFuture<typename std::decay<T2>::type>::value>::type>
324 /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
326 template <class T2 = T>
327 /* implicit */ Future(
328 typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
333 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
335 explicit Future(in_place_t, Args&&... args)
336 : Base(in_place, std::forward<Args>(args)...) {}
338 Future(Future<T> const&) = delete;
340 Future(Future<T>&&) noexcept;
345 typename std::enable_if<
346 !std::is_same<T, typename std::decay<T2>::type>::value &&
347 std::is_constructible<T, T2&&>::value &&
348 std::is_convertible<T2&&, T>::value,
350 /* implicit */ Future(Future<T2>&&);
353 typename std::enable_if<
354 !std::is_same<T, typename std::decay<T2>::type>::value &&
355 std::is_constructible<T, T2&&>::value &&
356 !std::is_convertible<T2&&, T>::value,
358 explicit Future(Future<T2>&&);
361 typename std::enable_if<
362 !std::is_same<T, typename std::decay<T2>::type>::value &&
363 std::is_constructible<T, T2&&>::value,
365 Future& operator=(Future<T2>&&);
369 using Base::hasException;
370 using Base::hasValue;
371 using Base::isActive;
375 using Base::setCallback_;
379 static Future<T> makeEmpty(); // equivalent to moved-from
382 Future& operator=(Future const&) = delete;
385 Future& operator=(Future&&) noexcept;
387 /// Call e->drive() repeatedly until the future is fulfilled. Examples
388 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
389 /// reference to the Try of the value.
390 Try<T>& getTryVia(DrivableExecutor* e);
392 /// Call e->drive() repeatedly until the future is fulfilled. Examples
393 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
394 /// value (moved out), or throws the exception.
395 T getVia(DrivableExecutor* e);
397 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
398 /// Future<T> instance.
399 template <class F = T>
401 enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
404 /// This variant creates a new future, where the ref-qualifier && version
405 /// moves `this` out. This one is less efficient but avoids confusing users
406 /// when "return f.via(x);" fails.
407 inline Future<T> via(
409 int8_t priority = Executor::MID_PRI) &;
411 /** When this Future has completed, execute func which is a function that
421 Func shall return either another Future or a value.
423 A Future for the return type of func is returned.
425 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
427 The Future given to the functor is ready, and the functor may call
428 value(), which may rethrow if this has captured an exception. If func
429 throws, the exception will be captured in the Future that is returned.
431 template <typename F, typename R = futures::detail::callableResult<T, F>>
432 typename R::Return then(F&& func) {
433 return this->template thenImplementation<F, R>(
434 std::forward<F>(func), typename R::Arg());
437 /// Variant where func is an member function
439 /// struct Worker { R doWork(Try<T>); }
442 /// Future<R> f2 = f1.then(&Worker::doWork, w);
444 /// This is just sugar for
446 /// f1.then(std::bind(&Worker::doWork, w));
447 template <typename R, typename Caller, typename... Args>
448 Future<typename isFuture<R>::Inner> then(
449 R (Caller::*func)(Args...),
452 /// Execute the callback via the given Executor. The executor doesn't stick.
456 /// f.via(x).then(b).then(c)
460 /// f.then(x, b).then(c)
462 /// In the former both b and c execute via x. In the latter, only b executes
463 /// via x, and c executes via the same executor (if any) that f had.
464 template <class Executor, class Arg, class... Args>
465 auto then(Executor* x, Arg&& arg, Args&&... args) {
466 auto oldX = this->getExecutor();
467 this->setExecutor(x);
468 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
472 /// Convenience method for ignoring the value and creating a Future<Unit>.
473 /// Exceptions still propagate.
474 /// This function is identical to .unit().
477 /// Convenience method for ignoring the value and creating a Future<Unit>.
478 /// Exceptions still propagate.
479 /// This function is identical to parameterless .then().
480 Future<Unit> unit() {
484 /// Set an error callback for this Future. The callback should take a single
485 /// argument of the type that you want to catch, and should return a value of
486 /// the same type as this Future, or a Future of that type (see overload
487 /// below). For instance,
491 /// throw std::runtime_error("oh no!");
494 /// .onError([] (std::runtime_error& e) {
495 /// LOG(INFO) << "std::runtime_error: " << e.what();
496 /// return -1; // or makeFuture<int>(-1)
499 typename std::enable_if<
500 !futures::detail::callableWith<F, exception_wrapper>::value &&
501 !futures::detail::callableWith<F, exception_wrapper&>::value &&
502 !futures::detail::Extract<F>::ReturnsFuture::value,
506 /// Overload of onError where the error callback returns a Future<T>
508 typename std::enable_if<
509 !futures::detail::callableWith<F, exception_wrapper>::value &&
510 !futures::detail::callableWith<F, exception_wrapper&>::value &&
511 futures::detail::Extract<F>::ReturnsFuture::value,
515 /// Overload of onError that takes exception_wrapper and returns Future<T>
517 typename std::enable_if<
518 futures::detail::callableWith<F, exception_wrapper>::value &&
519 futures::detail::Extract<F>::ReturnsFuture::value,
523 /// Overload of onError that takes exception_wrapper and returns T
525 typename std::enable_if<
526 futures::detail::callableWith<F, exception_wrapper>::value &&
527 !futures::detail::Extract<F>::ReturnsFuture::value,
531 /// func is like std::function<void()> and is executed unconditionally, and
532 /// the value/exception is passed through to the resulting Future.
533 /// func shouldn't throw, but if it does it will be captured and propagated,
534 /// and discard any value/exception that this Future has obtained.
536 Future<T> ensure(F&& func);
538 /// Like onError, but for timeouts. example:
540 /// Future<int> f = makeFuture<int>(42)
541 /// .delayed(long_time)
542 /// .onTimeout(short_time,
543 /// []() -> int{ return -1; });
547 /// Future<int> f = makeFuture<int>(42)
548 /// .delayed(long_time)
549 /// .onTimeout(short_time,
550 /// []() { return makeFuture<int>(some_exception); });
552 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
554 /// A Future's callback is executed when all three of these conditions have
555 /// become true: it has a value (set by the Promise), it has a callback (set
556 /// by then), and it is active (active by default).
558 /// Inactive Futures will activate upon destruction.
559 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
560 this->core_->activate();
563 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
564 this->core_->deactivate();
567 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
568 this->core_->activate();
569 return std::move(*this);
571 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
572 this->core_->deactivate();
573 return std::move(*this);
576 /// Throw TimedOut if this Future does not complete within the given
577 /// duration from now. The optional Timeekeeper is as with futures::sleep().
578 Future<T> within(Duration, Timekeeper* = nullptr);
580 /// Throw the given exception if this Future does not complete within the
581 /// given duration from now. The optional Timeekeeper is as with
582 /// futures::sleep().
584 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
586 /// Delay the completion of this Future for at least this duration from
587 /// now. The optional Timekeeper is as with futures::sleep().
588 Future<T> delayed(Duration, Timekeeper* = nullptr);
590 /// Block until the future is fulfilled. Returns the value (moved out), or
591 /// throws the exception. The future must not already have a callback.
594 /// Block until the future is fulfilled, or until timed out. Returns the
595 /// value (moved out), or throws the exception (which might be a TimedOut
599 /// Block until this Future is complete. Returns a reference to this Future.
602 /// Overload of wait() for rvalue Futures
603 Future<T>&& wait() &&;
605 /// Block until this Future is complete or until the given Duration passes.
606 /// Returns a reference to this Future
607 Future<T>& wait(Duration) &;
609 /// Overload of wait(Duration) for rvalue Futures
610 Future<T>&& wait(Duration) &&;
612 /// Call e->drive() repeatedly until the future is fulfilled. Examples
613 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
614 /// reference to this Future so that you can chain calls if desired.
615 /// value (moved out), or throws the exception.
616 Future<T>& waitVia(DrivableExecutor* e) &;
618 /// Overload of waitVia() for rvalue Futures
619 Future<T>&& waitVia(DrivableExecutor* e) &&;
621 /// If the value in this Future is equal to the given Future, when they have
622 /// both completed, the value of the resulting Future<bool> will be true. It
623 /// will be false otherwise (including when one or both Futures have an
625 Future<bool> willEqual(Future<T>&);
627 /// predicate behaves like std::function<bool(T const&)>
628 /// If the predicate does not obtain with the value, the result
629 /// is a folly::PredicateDoesNotObtain exception
631 Future<T> filter(F&& predicate);
633 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
634 /// the result of collect or collectAll
635 template <class I, class F>
636 Future<I> reduce(I&& initial, F&& func);
638 /// Create a Future chain from a sequence of callbacks. i.e.
640 /// f.then(a).then(b).then(c)
642 /// where f is a Future<A> and the result of the chain is a Future<D>
645 /// f.thenMulti(a, b, c);
646 template <class Callback, class... Callbacks>
647 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
648 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
649 return then(std::forward<Callback>(fn))
650 .thenMulti(std::forward<Callbacks>(fns)...);
653 template <class Callback>
654 auto thenMulti(Callback&& fn) {
655 // thenMulti with one callback is just a then
656 return then(std::forward<Callback>(fn));
659 /// Create a Future chain from a sequence of callbacks. i.e.
661 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
663 /// where f is a Future<A> and the result of the chain is a Future<D>
666 /// f.thenMultiWithExecutor(executor, a, b, c);
667 template <class Callback, class... Callbacks>
668 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
669 // thenMultiExecutor with two callbacks is
670 // via(x).then(a).thenMulti(b, ...).via(oldX)
671 auto oldX = this->getExecutor();
672 this->setExecutor(x);
673 return then(std::forward<Callback>(fn))
674 .thenMulti(std::forward<Callbacks>(fns)...)
678 template <class Callback>
679 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
680 // thenMulti with one callback is just a then with an executor
681 return then(x, std::forward<Callback>(fn));
684 // Convert this Future to a SemiFuture to safely export from a library
685 // without exposing a continuation interface
686 SemiFuture<T> semi() {
687 return SemiFuture<T>{std::move(*this)};
691 friend class Promise<T>;
693 friend class futures::detail::FutureBase;
697 using typename Base::corePtr;
699 explicit Future(corePtr obj) : Base(obj) {}
701 explicit Future(futures::detail::EmptyConstruct) noexcept
702 : Base(futures::detail::EmptyConstruct{}) {}
705 friend Future<T2> makeFuture(Try<T2>&&);
707 /// Repeat the given future (i.e., the computation it contains)
710 /// thunk behaves like std::function<Future<T2>(void)>
712 friend Future<Unit> times(int n, F&& thunk);
714 /// Carry out the computation contained in the given future if
715 /// the predicate holds.
717 /// thunk behaves like std::function<Future<T2>(void)>
719 friend Future<Unit> when(bool p, F&& thunk);
721 /// Carry out the computation contained in the given future if
722 /// while the predicate continues to hold.
724 /// thunk behaves like std::function<Future<T2>(void)>
726 /// predicate behaves like std::function<bool(void)>
727 template <class P, class F>
728 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
733 #include <folly/futures/Future-inl.h>