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>
52 static SemiFuture<T> makeEmpty(); // equivalent to moved-from
55 SemiFuture(SemiFuture const&) = delete;
56 SemiFuture& operator=(SemiFuture const&) = delete;
59 SemiFuture(SemiFuture&&) noexcept;
60 SemiFuture& operator=(SemiFuture&&) noexcept;
62 // safe move-constructabilty from Future
63 /* implicit */ SemiFuture(Future<T>&&) noexcept;
64 SemiFuture& operator=(Future<T>&&) noexcept;
66 /// Construct a Future from a value (perfect forwarding)
69 typename = typename std::enable_if<
70 !isFuture<typename std::decay<T2>::type>::value>::type>
71 /* implicit */ SemiFuture(T2&& val);
73 template <class T2 = T>
74 /* implicit */ SemiFuture(
75 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
79 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
81 explicit SemiFuture(in_place_t, Args&&... args);
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 an inactive Future which will call back on the other side of
100 /// executor (when it is activated).
102 /// NB remember that Futures activate when they destruct. This is good,
103 /// it means that this will work:
105 /// f.via(e).then(a).then(b);
107 /// a and b will execute in the same context (the far side of e), because
108 /// the Future (temporary variable) created by via(e) does not call back
109 /// until it destructs, which is after then(a) and then(b) have been wired
112 /// But this is still racy:
114 /// f = f.via(e).then(a);
116 // The ref-qualifier allows for `this` to be moved out so we
117 // don't get access-after-free situations in chaining.
118 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
119 inline Future<T> via(
121 int8_t priority = Executor::MID_PRI) &&;
123 /// This variant creates a new future, where the ref-qualifier && version
124 /// moves `this` out. This one is less efficient but avoids confusing users
125 /// when "return f.via(x);" fails.
126 inline Future<T> via(
128 int8_t priority = Executor::MID_PRI) &;
130 /** True when the result (or exception) is ready. */
131 bool isReady() const;
133 /// sugar for getTry().hasValue()
136 /// sugar for getTry().hasException()
139 /** A reference to the Try of the value */
142 /// If the promise has been fulfilled, return an Optional with the Try<T>.
143 /// Otherwise return an empty Optional.
144 /// Note that this moves the Try<T> out.
145 Optional<Try<T>> poll();
147 /// Block until the future is fulfilled. Returns the value (moved out), or
148 /// throws the exception. The future must not already have a callback.
151 /// Block until the future is fulfilled, or until timed out. Returns the
152 /// value (moved out), or throws the exception (which might be a TimedOut
156 /// Block until this Future is complete. Returns a reference to this Future.
157 SemiFuture<T>& wait() &;
159 /// Overload of wait() for rvalue Futures
160 SemiFuture<T>&& wait() &&;
162 /// Block until this Future is complete or until the given Duration passes.
163 /// Returns a reference to this Future
164 SemiFuture<T>& wait(Duration) &;
166 /// Overload of wait(Duration) for rvalue Futures
167 SemiFuture<T>&& wait(Duration) &&;
169 /// This is not the method you're looking for.
171 /// This needs to be public because it's used by make* and when*, and it's
172 /// not worth listing all those and their fancy template signatures as
173 /// friends. But it's not for public consumption.
175 void setCallback_(F&& func);
178 return core_->isActive();
182 void raise(E&& exception) {
183 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
184 std::forward<E>(exception)));
187 /// Raise an interrupt. If the promise holder has an interrupt
188 /// handler it will be called and potentially stop asynchronous work from
189 /// being done. This is advisory only - a promise holder may not set an
190 /// interrupt handler, or may do anything including ignore. But, if you know
191 /// your future supports this the most likely result is stopping or
192 /// preventing the asynchronous operation (if in time), and the promise
193 /// holder setting an exception on the future. (That may happen
194 /// asynchronously, of course.)
195 void raise(exception_wrapper interrupt);
198 raise(FutureCancellation());
202 typedef futures::detail::Core<T>* corePtr;
204 // shared core state object
207 explicit SemiFuture(corePtr obj) : core_(obj) {}
209 explicit SemiFuture(futures::detail::EmptyConstruct) noexcept;
213 void throwIfInvalid() const;
215 friend class Promise<T>;
217 friend class SemiFuture;
220 friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
222 Executor* getExecutor() {
223 return core_->getExecutor();
226 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
227 core_->setExecutor(x, priority);
230 // Variant: returns a value
231 // e.g. f.then([](Try<T> t){ return t.value(); });
232 template <typename F, typename R, bool isTry, typename... Args>
233 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
234 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
236 // Variant: returns a Future
237 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
238 template <typename F, typename R, bool isTry, typename... Args>
239 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
240 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
244 class Future : public SemiFuture<T> {
246 typedef T value_type;
248 static Future<T> makeEmpty(); // equivalent to moved-from
251 Future(Future const&) = delete;
252 Future& operator=(Future const&) = delete;
255 Future(Future&&) noexcept;
256 Future& operator=(Future&&) noexcept;
261 typename std::enable_if<
262 !std::is_same<T, typename std::decay<T2>::type>::value &&
263 std::is_constructible<T, T2&&>::value &&
264 std::is_convertible<T2&&, T>::value,
266 /* implicit */ Future(Future<T2>&&);
269 typename std::enable_if<
270 !std::is_same<T, typename std::decay<T2>::type>::value &&
271 std::is_constructible<T, T2&&>::value &&
272 !std::is_convertible<T2&&, T>::value,
274 explicit Future(Future<T2>&&);
277 typename std::enable_if<
278 !std::is_same<T, typename std::decay<T2>::type>::value &&
279 std::is_constructible<T, T2&&>::value,
281 Future& operator=(Future<T2>&&);
283 /// Construct a Future from a value (perfect forwarding)
286 typename = typename std::enable_if<
287 !isFuture<typename std::decay<T2>::type>::value &&
288 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
289 /* implicit */ Future(T2&& val);
291 template <class T2 = T>
292 /* implicit */ Future(
293 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
297 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
299 explicit Future(in_place_t, Args&&... args);
303 /// Call e->drive() repeatedly until the future is fulfilled. Examples
304 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
305 /// reference to the Try of the value.
306 Try<T>& getTryVia(DrivableExecutor* e);
308 /// Call e->drive() repeatedly until the future is fulfilled. Examples
309 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
310 /// value (moved out), or throws the exception.
311 T getVia(DrivableExecutor* e);
313 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
314 /// Future<T> instance.
315 template <class F = T>
316 typename std::enable_if<isFuture<F>::value,
317 Future<typename isFuture<T>::Inner>>::type
320 /** When this Future has completed, execute func which is a function that
330 Func shall return either another Future or a value.
332 A Future for the return type of func is returned.
334 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
336 The Future given to the functor is ready, and the functor may call
337 value(), which may rethrow if this has captured an exception. If func
338 throws, the exception will be captured in the Future that is returned.
340 template <typename F, typename R = futures::detail::callableResult<T, F>>
341 typename R::Return then(F&& func) {
342 return this->template thenImplementation<F, R>(
343 std::forward<F>(func), typename R::Arg());
346 /// Variant where func is an member function
348 /// struct Worker { R doWork(Try<T>); }
351 /// Future<R> f2 = f1.then(&Worker::doWork, w);
353 /// This is just sugar for
355 /// f1.then(std::bind(&Worker::doWork, w));
356 template <typename R, typename Caller, typename... Args>
357 Future<typename isFuture<R>::Inner>
358 then(R(Caller::*func)(Args...), Caller *instance);
360 /// Execute the callback via the given Executor. The executor doesn't stick.
364 /// f.via(x).then(b).then(c)
368 /// f.then(x, b).then(c)
370 /// In the former both b and c execute via x. In the latter, only b executes
371 /// via x, and c executes via the same executor (if any) that f had.
372 template <class Executor, class Arg, class... Args>
373 auto then(Executor* x, Arg&& arg, Args&&... args) {
374 auto oldX = this->getExecutor();
375 this->setExecutor(x);
376 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
380 /// Convenience method for ignoring the value and creating a Future<Unit>.
381 /// Exceptions still propagate.
382 /// This function is identical to .unit().
385 /// Convenience method for ignoring the value and creating a Future<Unit>.
386 /// Exceptions still propagate.
387 /// This function is identical to parameterless .then().
388 Future<Unit> unit() {
392 /// Set an error callback for this Future. The callback should take a single
393 /// argument of the type that you want to catch, and should return a value of
394 /// the same type as this Future, or a Future of that type (see overload
395 /// below). For instance,
399 /// throw std::runtime_error("oh no!");
402 /// .onError([] (std::runtime_error& e) {
403 /// LOG(INFO) << "std::runtime_error: " << e.what();
404 /// return -1; // or makeFuture<int>(-1)
407 typename std::enable_if<
408 !futures::detail::callableWith<F, exception_wrapper>::value &&
409 !futures::detail::callableWith<F, exception_wrapper&>::value &&
410 !futures::detail::Extract<F>::ReturnsFuture::value,
414 /// Overload of onError where the error callback returns a Future<T>
416 typename std::enable_if<
417 !futures::detail::callableWith<F, exception_wrapper>::value &&
418 !futures::detail::callableWith<F, exception_wrapper&>::value &&
419 futures::detail::Extract<F>::ReturnsFuture::value,
423 /// Overload of onError that takes exception_wrapper and returns Future<T>
425 typename std::enable_if<
426 futures::detail::callableWith<F, exception_wrapper>::value &&
427 futures::detail::Extract<F>::ReturnsFuture::value,
431 /// Overload of onError that takes exception_wrapper and returns T
433 typename std::enable_if<
434 futures::detail::callableWith<F, exception_wrapper>::value &&
435 !futures::detail::Extract<F>::ReturnsFuture::value,
439 /// func is like std::function<void()> and is executed unconditionally, and
440 /// the value/exception is passed through to the resulting Future.
441 /// func shouldn't throw, but if it does it will be captured and propagated,
442 /// and discard any value/exception that this Future has obtained.
444 Future<T> ensure(F&& func);
446 /// Like onError, but for timeouts. example:
448 /// Future<int> f = makeFuture<int>(42)
449 /// .delayed(long_time)
450 /// .onTimeout(short_time,
451 /// []() -> int{ return -1; });
455 /// Future<int> f = makeFuture<int>(42)
456 /// .delayed(long_time)
457 /// .onTimeout(short_time,
458 /// []() { return makeFuture<int>(some_exception); });
460 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
462 /// A Future's callback is executed when all three of these conditions have
463 /// become true: it has a value (set by the Promise), it has a callback (set
464 /// by then), and it is active (active by default).
466 /// Inactive Futures will activate upon destruction.
467 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
468 this->core_->activate();
471 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
472 this->core_->deactivate();
475 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
476 this->core_->activate();
477 return std::move(*this);
479 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
480 this->core_->deactivate();
481 return std::move(*this);
484 /// Throw TimedOut if this Future does not complete within the given
485 /// duration from now. The optional Timeekeeper is as with futures::sleep().
486 Future<T> within(Duration, Timekeeper* = nullptr);
488 /// Throw the given exception if this Future does not complete within the
489 /// given duration from now. The optional Timeekeeper is as with
490 /// futures::sleep().
492 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
494 /// Delay the completion of this Future for at least this duration from
495 /// now. The optional Timekeeper is as with futures::sleep().
496 Future<T> delayed(Duration, Timekeeper* = nullptr);
498 /// Block until this Future is complete. Returns a reference to this Future.
501 /// Overload of wait() for rvalue Futures
502 Future<T>&& wait() &&;
504 /// Block until this Future is complete or until the given Duration passes.
505 /// Returns a reference to this Future
506 Future<T>& wait(Duration) &;
508 /// Overload of wait(Duration) for rvalue Futures
509 Future<T>&& wait(Duration) &&;
511 /// Call e->drive() repeatedly until the future is fulfilled. Examples
512 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
513 /// reference to this Future so that you can chain calls if desired.
514 /// value (moved out), or throws the exception.
515 Future<T>& waitVia(DrivableExecutor* e) &;
517 /// Overload of waitVia() for rvalue Futures
518 Future<T>&& waitVia(DrivableExecutor* e) &&;
520 /// If the value in this Future is equal to the given Future, when they have
521 /// both completed, the value of the resulting Future<bool> will be true. It
522 /// will be false otherwise (including when one or both Futures have an
524 Future<bool> willEqual(Future<T>&);
526 /// predicate behaves like std::function<bool(T const&)>
527 /// If the predicate does not obtain with the value, the result
528 /// is a folly::PredicateDoesNotObtain exception
530 Future<T> filter(F&& predicate);
532 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
533 /// the result of collect or collectAll
534 template <class I, class F>
535 Future<I> reduce(I&& initial, F&& func);
537 /// Create a Future chain from a sequence of callbacks. i.e.
539 /// f.then(a).then(b).then(c)
541 /// where f is a Future<A> and the result of the chain is a Future<D>
544 /// f.thenMulti(a, b, c);
545 template <class Callback, class... Callbacks>
546 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
547 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
548 return then(std::forward<Callback>(fn))
549 .thenMulti(std::forward<Callbacks>(fns)...);
552 template <class Callback>
553 auto thenMulti(Callback&& fn) {
554 // thenMulti with one callback is just a then
555 return then(std::forward<Callback>(fn));
558 /// Create a Future chain from a sequence of callbacks. i.e.
560 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
562 /// where f is a Future<A> and the result of the chain is a Future<D>
565 /// f.thenMultiWithExecutor(executor, a, b, c);
566 template <class Callback, class... Callbacks>
567 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
568 // thenMultiExecutor with two callbacks is
569 // via(x).then(a).thenMulti(b, ...).via(oldX)
570 auto oldX = this->getExecutor();
571 this->setExecutor(x);
572 return then(std::forward<Callback>(fn))
573 .thenMulti(std::forward<Callbacks>(fns)...)
577 template <class Callback>
578 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
579 // thenMulti with one callback is just a then with an executor
580 return then(x, std::forward<Callback>(fn));
583 // Convert this Future to a SemiFuture to safely export from a library
584 // without exposing a continuation interface
585 SemiFuture<T> semi() {
586 return SemiFuture<T>{std::move(*this)};
590 typedef futures::detail::Core<T>* corePtr;
592 explicit Future(corePtr obj) : SemiFuture<T>(obj) {}
594 explicit Future(futures::detail::EmptyConstruct) noexcept;
596 friend class Promise<T>;
597 template <class> friend class Future;
598 friend class SemiFuture<T>;
601 friend Future<T2> makeFuture(Try<T2>&&);
603 /// Repeat the given future (i.e., the computation it contains)
606 /// thunk behaves like std::function<Future<T2>(void)>
608 friend Future<Unit> times(int n, F&& thunk);
610 /// Carry out the computation contained in the given future if
611 /// the predicate holds.
613 /// thunk behaves like std::function<Future<T2>(void)>
615 friend Future<Unit> when(bool p, F&& thunk);
617 /// Carry out the computation contained in the given future if
618 /// while the predicate continues to hold.
620 /// thunk behaves like std::function<Future<T2>(void)>
622 /// predicate behaves like std::function<bool(void)>
623 template <class P, class F>
624 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
629 #include <folly/futures/Future-inl.h>