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/futures/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 /** Return the reference to result. Should not be called if !isReady().
86 Will rethrow the exception if an exception has been
89 typename std::add_lvalue_reference<T>::type
91 typename std::add_lvalue_reference<const T>::type
94 /// Returns an inactive Future which will call back on the other side of
95 /// executor (when it is activated).
97 /// NB remember that Futures activate when they destruct. This is good,
98 /// it means that this will work:
100 /// f.via(e).then(a).then(b);
102 /// a and b will execute in the same context (the far side of e), because
103 /// the Future (temporary variable) created by via(e) does not call back
104 /// until it destructs, which is after then(a) and then(b) have been wired
107 /// But this is still racy:
109 /// f = f.via(e).then(a);
111 // The ref-qualifier allows for `this` to be moved out so we
112 // don't get access-after-free situations in chaining.
113 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
114 inline Future<T> via(
116 int8_t priority = Executor::MID_PRI) &&;
118 /// This variant creates a new future, where the ref-qualifier && version
119 /// moves `this` out. This one is less efficient but avoids confusing users
120 /// when "return f.via(x);" fails.
121 inline Future<T> via(
123 int8_t priority = Executor::MID_PRI) &;
125 /** True when the result (or exception) is ready. */
126 bool isReady() const;
128 /// sugar for getTry().hasValue()
131 /// sugar for getTry().hasException()
134 /** A reference to the Try of the value */
137 /// If the promise has been fulfilled, return an Optional with the Try<T>.
138 /// Otherwise return an empty Optional.
139 /// Note that this moves the Try<T> out.
140 Optional<Try<T>> poll();
142 /// Block until the future is fulfilled. Returns the value (moved out), or
143 /// throws the exception. The future must not already have a callback.
146 /// Block until the future is fulfilled, or until timed out. Returns the
147 /// value (moved out), or throws the exception (which might be a TimedOut
151 /// Block until this Future is complete. Returns a reference to this Future.
152 SemiFuture<T>& wait() &;
154 /// Overload of wait() for rvalue Futures
155 SemiFuture<T>&& wait() &&;
157 /// Block until this Future is complete or until the given Duration passes.
158 /// Returns a reference to this Future
159 SemiFuture<T>& wait(Duration) &;
161 /// Overload of wait(Duration) for rvalue Futures
162 SemiFuture<T>&& wait(Duration) &&;
164 /// This is not the method you're looking for.
166 /// This needs to be public because it's used by make* and when*, and it's
167 /// not worth listing all those and their fancy template signatures as
168 /// friends. But it's not for public consumption.
170 void setCallback_(F&& func);
173 return core_->isActive();
177 void raise(E&& exception) {
178 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
179 std::forward<E>(exception)));
182 /// Raise an interrupt. If the promise holder has an interrupt
183 /// handler it will be called and potentially stop asynchronous work from
184 /// being done. This is advisory only - a promise holder may not set an
185 /// interrupt handler, or may do anything including ignore. But, if you know
186 /// your future supports this the most likely result is stopping or
187 /// preventing the asynchronous operation (if in time), and the promise
188 /// holder setting an exception on the future. (That may happen
189 /// asynchronously, of course.)
190 void raise(exception_wrapper interrupt);
193 raise(FutureCancellation());
197 typedef futures::detail::Core<T>* corePtr;
199 // shared core state object
202 explicit SemiFuture(corePtr obj) : core_(obj) {}
204 explicit SemiFuture(futures::detail::EmptyConstruct) noexcept;
208 void throwIfInvalid() const;
210 friend class Promise<T>;
212 friend class SemiFuture;
215 friend SemiFuture<T2> makeSemiFuture(Try<T2>&&);
217 Executor* getExecutor() {
218 return core_->getExecutor();
221 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
222 core_->setExecutor(x, priority);
225 // Variant: returns a value
226 // e.g. f.then([](Try<T> t){ return t.value(); });
227 template <typename F, typename R, bool isTry, typename... Args>
228 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
229 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
231 // Variant: returns a Future
232 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
233 template <typename F, typename R, bool isTry, typename... Args>
234 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
235 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
239 class Future : public SemiFuture<T> {
241 typedef T value_type;
243 static Future<T> makeEmpty(); // equivalent to moved-from
246 Future(Future const&) = delete;
247 Future& operator=(Future const&) = delete;
250 Future(Future&&) noexcept;
251 Future& operator=(Future&&) noexcept;
256 typename std::enable_if<
257 !std::is_same<T, typename std::decay<T2>::type>::value &&
258 std::is_constructible<T, T2&&>::value &&
259 std::is_convertible<T2&&, T>::value,
261 /* implicit */ Future(Future<T2>&&);
264 typename std::enable_if<
265 !std::is_same<T, typename std::decay<T2>::type>::value &&
266 std::is_constructible<T, T2&&>::value &&
267 !std::is_convertible<T2&&, T>::value,
269 explicit Future(Future<T2>&&);
272 typename std::enable_if<
273 !std::is_same<T, typename std::decay<T2>::type>::value &&
274 std::is_constructible<T, T2&&>::value,
276 Future& operator=(Future<T2>&&);
278 /// Construct a Future from a value (perfect forwarding)
281 typename = typename std::enable_if<
282 !isFuture<typename std::decay<T2>::type>::value &&
283 !isSemiFuture<typename std::decay<T2>::type>::value>::type>
284 /* implicit */ Future(T2&& val);
286 template <class T2 = T>
287 /* implicit */ Future(
288 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
292 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
294 explicit Future(in_place_t, Args&&... args);
298 /// Call e->drive() repeatedly until the future is fulfilled. Examples
299 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
300 /// reference to the Try of the value.
301 Try<T>& getTryVia(DrivableExecutor* e);
303 /// Call e->drive() repeatedly until the future is fulfilled. Examples
304 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
305 /// value (moved out), or throws the exception.
306 T getVia(DrivableExecutor* e);
308 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
309 /// Future<T> instance.
310 template <class F = T>
311 typename std::enable_if<isFuture<F>::value,
312 Future<typename isFuture<T>::Inner>>::type
315 /** When this Future has completed, execute func which is a function that
325 Func shall return either another Future or a value.
327 A Future for the return type of func is returned.
329 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
331 The Future given to the functor is ready, and the functor may call
332 value(), which may rethrow if this has captured an exception. If func
333 throws, the exception will be captured in the Future that is returned.
335 template <typename F, typename R = futures::detail::callableResult<T, F>>
336 typename R::Return then(F&& func) {
337 return this->template thenImplementation<F, R>(
338 std::forward<F>(func), typename R::Arg());
341 /// Variant where func is an member function
343 /// struct Worker { R doWork(Try<T>); }
346 /// Future<R> f2 = f1.then(&Worker::doWork, w);
348 /// This is just sugar for
350 /// f1.then(std::bind(&Worker::doWork, w));
351 template <typename R, typename Caller, typename... Args>
352 Future<typename isFuture<R>::Inner>
353 then(R(Caller::*func)(Args...), Caller *instance);
355 /// Execute the callback via the given Executor. The executor doesn't stick.
359 /// f.via(x).then(b).then(c)
363 /// f.then(x, b).then(c)
365 /// In the former both b and c execute via x. In the latter, only b executes
366 /// via x, and c executes via the same executor (if any) that f had.
367 template <class Executor, class Arg, class... Args>
368 auto then(Executor* x, Arg&& arg, Args&&... args) {
369 auto oldX = this->getExecutor();
370 this->setExecutor(x);
371 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
375 /// Convenience method for ignoring the value and creating a Future<Unit>.
376 /// Exceptions still propagate.
377 /// This function is identical to .unit().
380 /// Convenience method for ignoring the value and creating a Future<Unit>.
381 /// Exceptions still propagate.
382 /// This function is identical to parameterless .then().
383 Future<Unit> unit() {
387 /// Set an error callback for this Future. The callback should take a single
388 /// argument of the type that you want to catch, and should return a value of
389 /// the same type as this Future, or a Future of that type (see overload
390 /// below). For instance,
394 /// throw std::runtime_error("oh no!");
397 /// .onError([] (std::runtime_error& e) {
398 /// LOG(INFO) << "std::runtime_error: " << e.what();
399 /// return -1; // or makeFuture<int>(-1)
402 typename std::enable_if<
403 !futures::detail::callableWith<F, exception_wrapper>::value &&
404 !futures::detail::callableWith<F, exception_wrapper&>::value &&
405 !futures::detail::Extract<F>::ReturnsFuture::value,
409 /// Overload of onError where the error callback returns a Future<T>
411 typename std::enable_if<
412 !futures::detail::callableWith<F, exception_wrapper>::value &&
413 !futures::detail::callableWith<F, exception_wrapper&>::value &&
414 futures::detail::Extract<F>::ReturnsFuture::value,
418 /// Overload of onError that takes exception_wrapper and returns Future<T>
420 typename std::enable_if<
421 futures::detail::callableWith<F, exception_wrapper>::value &&
422 futures::detail::Extract<F>::ReturnsFuture::value,
426 /// Overload of onError that takes exception_wrapper and returns T
428 typename std::enable_if<
429 futures::detail::callableWith<F, exception_wrapper>::value &&
430 !futures::detail::Extract<F>::ReturnsFuture::value,
434 /// func is like std::function<void()> and is executed unconditionally, and
435 /// the value/exception is passed through to the resulting Future.
436 /// func shouldn't throw, but if it does it will be captured and propagated,
437 /// and discard any value/exception that this Future has obtained.
439 Future<T> ensure(F&& func);
441 /// Like onError, but for timeouts. example:
443 /// Future<int> f = makeFuture<int>(42)
444 /// .delayed(long_time)
445 /// .onTimeout(short_time,
446 /// []() -> int{ return -1; });
450 /// Future<int> f = makeFuture<int>(42)
451 /// .delayed(long_time)
452 /// .onTimeout(short_time,
453 /// []() { return makeFuture<int>(some_exception); });
455 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
457 /// A Future's callback is executed when all three of these conditions have
458 /// become true: it has a value (set by the Promise), it has a callback (set
459 /// by then), and it is active (active by default).
461 /// Inactive Futures will activate upon destruction.
462 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
463 this->core_->activate();
466 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
467 this->core_->deactivate();
470 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
471 this->core_->activate();
472 return std::move(*this);
474 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
475 this->core_->deactivate();
476 return std::move(*this);
479 /// Throw TimedOut if this Future does not complete within the given
480 /// duration from now. The optional Timeekeeper is as with futures::sleep().
481 Future<T> within(Duration, Timekeeper* = nullptr);
483 /// Throw the given exception if this Future does not complete within the
484 /// given duration from now. The optional Timeekeeper is as with
485 /// futures::sleep().
487 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
489 /// Delay the completion of this Future for at least this duration from
490 /// now. The optional Timekeeper is as with futures::sleep().
491 Future<T> delayed(Duration, Timekeeper* = nullptr);
493 /// Block until this Future is complete. Returns a reference to this Future.
496 /// Overload of wait() for rvalue Futures
497 Future<T>&& wait() &&;
499 /// Block until this Future is complete or until the given Duration passes.
500 /// Returns a reference to this Future
501 Future<T>& wait(Duration) &;
503 /// Overload of wait(Duration) for rvalue Futures
504 Future<T>&& wait(Duration) &&;
506 /// Call e->drive() repeatedly until the future is fulfilled. Examples
507 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
508 /// reference to this Future so that you can chain calls if desired.
509 /// value (moved out), or throws the exception.
510 Future<T>& waitVia(DrivableExecutor* e) &;
512 /// Overload of waitVia() for rvalue Futures
513 Future<T>&& waitVia(DrivableExecutor* e) &&;
515 /// If the value in this Future is equal to the given Future, when they have
516 /// both completed, the value of the resulting Future<bool> will be true. It
517 /// will be false otherwise (including when one or both Futures have an
519 Future<bool> willEqual(Future<T>&);
521 /// predicate behaves like std::function<bool(T const&)>
522 /// If the predicate does not obtain with the value, the result
523 /// is a folly::PredicateDoesNotObtain exception
525 Future<T> filter(F&& predicate);
527 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
528 /// the result of collect or collectAll
529 template <class I, class F>
530 Future<I> reduce(I&& initial, F&& func);
532 /// Create a Future chain from a sequence of callbacks. i.e.
534 /// f.then(a).then(b).then(c)
536 /// where f is a Future<A> and the result of the chain is a Future<D>
539 /// f.thenMulti(a, b, c);
540 template <class Callback, class... Callbacks>
541 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
542 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
543 return then(std::forward<Callback>(fn))
544 .thenMulti(std::forward<Callbacks>(fns)...);
547 template <class Callback>
548 auto thenMulti(Callback&& fn) {
549 // thenMulti with one callback is just a then
550 return then(std::forward<Callback>(fn));
553 /// Create a Future chain from a sequence of callbacks. i.e.
555 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
557 /// where f is a Future<A> and the result of the chain is a Future<D>
560 /// f.thenMultiWithExecutor(executor, a, b, c);
561 template <class Callback, class... Callbacks>
562 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
563 // thenMultiExecutor with two callbacks is
564 // via(x).then(a).thenMulti(b, ...).via(oldX)
565 auto oldX = this->getExecutor();
566 this->setExecutor(x);
567 return then(std::forward<Callback>(fn))
568 .thenMulti(std::forward<Callbacks>(fns)...)
572 template <class Callback>
573 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
574 // thenMulti with one callback is just a then with an executor
575 return then(x, std::forward<Callback>(fn));
578 // Convert this Future to a SemiFuture to safely export from a library
579 // without exposing a continuation interface
580 SemiFuture<T> semi() {
581 return SemiFuture<T>{std::move(*this)};
585 typedef futures::detail::Core<T>* corePtr;
587 explicit Future(corePtr obj) : SemiFuture<T>(obj) {}
589 explicit Future(futures::detail::EmptyConstruct) noexcept;
591 friend class Promise<T>;
592 template <class> friend class Future;
593 friend class SemiFuture<T>;
596 friend Future<T2> makeFuture(Try<T2>&&);
598 /// Repeat the given future (i.e., the computation it contains)
601 /// thunk behaves like std::function<Future<T2>(void)>
603 friend Future<Unit> times(int n, F&& thunk);
605 /// Carry out the computation contained in the given future if
606 /// the predicate holds.
608 /// thunk behaves like std::function<Future<T2>(void)>
610 friend Future<Unit> when(bool p, F&& thunk);
612 /// Carry out the computation contained in the given future if
613 /// while the predicate continues to hold.
615 /// thunk behaves like std::function<Future<T2>(void)>
617 /// predicate behaves like std::function<bool(void)>
618 template <class P, class F>
619 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
624 #include <folly/futures/Future-inl.h>