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>
49 static Future<T> makeEmpty(); // equivalent to moved-from
52 Future(Future const&) = delete;
53 Future& operator=(Future const&) = delete;
56 Future(Future&&) noexcept;
57 Future& operator=(Future&&) noexcept;
62 typename std::enable_if<
63 !std::is_same<T, typename std::decay<T2>::type>::value &&
64 std::is_constructible<T, T2&&>::value &&
65 std::is_convertible<T2&&, T>::value,
67 /* implicit */ Future(Future<T2>&&);
70 typename std::enable_if<
71 !std::is_same<T, typename std::decay<T2>::type>::value &&
72 std::is_constructible<T, T2&&>::value &&
73 !std::is_convertible<T2&&, T>::value,
75 explicit Future(Future<T2>&&);
78 typename std::enable_if<
79 !std::is_same<T, typename std::decay<T2>::type>::value &&
80 std::is_constructible<T, T2&&>::value,
82 Future& operator=(Future<T2>&&);
84 /// Construct a Future from a value (perfect forwarding)
85 template <class T2 = T, typename =
86 typename std::enable_if<
87 !isFuture<typename std::decay<T2>::type>::value>::type>
88 /* implicit */ Future(T2&& val);
90 template <class T2 = T>
91 /* implicit */ Future(
92 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
96 typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
98 explicit Future(in_place_t, Args&&... args);
102 /** Return the reference to result. Should not be called if !isReady().
103 Will rethrow the exception if an exception has been
106 typename std::add_lvalue_reference<T>::type
108 typename std::add_lvalue_reference<const T>::type
111 /// Returns an inactive Future which will call back on the other side of
112 /// executor (when it is activated).
114 /// NB remember that Futures activate when they destruct. This is good,
115 /// it means that this will work:
117 /// f.via(e).then(a).then(b);
119 /// a and b will execute in the same context (the far side of e), because
120 /// the Future (temporary variable) created by via(e) does not call back
121 /// until it destructs, which is after then(a) and then(b) have been wired
124 /// But this is still racy:
126 /// f = f.via(e).then(a);
128 // The ref-qualifier allows for `this` to be moved out so we
129 // don't get access-after-free situations in chaining.
130 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
131 inline Future<T> via(
133 int8_t priority = Executor::MID_PRI) &&;
135 /// This variant creates a new future, where the ref-qualifier && version
136 /// moves `this` out. This one is less efficient but avoids confusing users
137 /// when "return f.via(x);" fails.
138 inline Future<T> via(
140 int8_t priority = Executor::MID_PRI) &;
142 /** True when the result (or exception) is ready. */
143 bool isReady() const;
145 /// sugar for getTry().hasValue()
148 /// sugar for getTry().hasException()
151 /** A reference to the Try of the value */
154 /// Call e->drive() repeatedly until the future is fulfilled. Examples
155 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
156 /// reference to the Try of the value.
157 Try<T>& getTryVia(DrivableExecutor* e);
159 /// If the promise has been fulfilled, return an Optional with the Try<T>.
160 /// Otherwise return an empty Optional.
161 /// Note that this moves the Try<T> out.
162 Optional<Try<T>> poll();
164 /// Block until the future is fulfilled. Returns the value (moved out), or
165 /// throws the exception. The future must not already have a callback.
168 /// Block until the future is fulfilled, or until timed out. Returns the
169 /// value (moved out), or throws the exception (which might be a TimedOut
173 /// Call e->drive() repeatedly until the future is fulfilled. Examples
174 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
175 /// value (moved out), or throws the exception.
176 T getVia(DrivableExecutor* e);
178 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
179 /// Future<T> instance.
180 template <class F = T>
181 typename std::enable_if<isFuture<F>::value,
182 Future<typename isFuture<T>::Inner>>::type
185 /** When this Future has completed, execute func which is a function that
195 Func shall return either another Future or a value.
197 A Future for the return type of func is returned.
199 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
201 The Future given to the functor is ready, and the functor may call
202 value(), which may rethrow if this has captured an exception. If func
203 throws, the exception will be captured in the Future that is returned.
205 template <typename F, typename R = futures::detail::callableResult<T, F>>
206 typename R::Return then(F&& func) {
207 return thenImplementation<F, R>(std::forward<F>(func), typename R::Arg());
210 /// Variant where func is an member function
212 /// struct Worker { R doWork(Try<T>); }
215 /// Future<R> f2 = f1.then(&Worker::doWork, w);
217 /// This is just sugar for
219 /// f1.then(std::bind(&Worker::doWork, w));
220 template <typename R, typename Caller, typename... Args>
221 Future<typename isFuture<R>::Inner>
222 then(R(Caller::*func)(Args...), Caller *instance);
224 /// Execute the callback via the given Executor. The executor doesn't stick.
228 /// f.via(x).then(b).then(c)
232 /// f.then(x, b).then(c)
234 /// In the former both b and c execute via x. In the latter, only b executes
235 /// via x, and c executes via the same executor (if any) that f had.
236 template <class Executor, class Arg, class... Args>
237 auto then(Executor* x, Arg&& arg, Args&&... args) {
238 auto oldX = getExecutor();
240 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
244 /// Convenience method for ignoring the value and creating a Future<Unit>.
245 /// Exceptions still propagate.
248 /// Set an error callback for this Future. The callback should take a single
249 /// argument of the type that you want to catch, and should return a value of
250 /// the same type as this Future, or a Future of that type (see overload
251 /// below). For instance,
255 /// throw std::runtime_error("oh no!");
258 /// .onError([] (std::runtime_error& e) {
259 /// LOG(INFO) << "std::runtime_error: " << e.what();
260 /// return -1; // or makeFuture<int>(-1)
263 typename std::enable_if<
264 !futures::detail::callableWith<F, exception_wrapper>::value &&
265 !futures::detail::Extract<F>::ReturnsFuture::value,
269 /// Overload of onError where the error callback returns a Future<T>
271 typename std::enable_if<
272 !futures::detail::callableWith<F, exception_wrapper>::value &&
273 futures::detail::Extract<F>::ReturnsFuture::value,
277 /// Overload of onError that takes exception_wrapper and returns Future<T>
279 typename std::enable_if<
280 futures::detail::callableWith<F, exception_wrapper>::value &&
281 futures::detail::Extract<F>::ReturnsFuture::value,
285 /// Overload of onError that takes exception_wrapper and returns T
287 typename std::enable_if<
288 futures::detail::callableWith<F, exception_wrapper>::value &&
289 !futures::detail::Extract<F>::ReturnsFuture::value,
293 /// func is like std::function<void()> and is executed unconditionally, and
294 /// the value/exception is passed through to the resulting Future.
295 /// func shouldn't throw, but if it does it will be captured and propagated,
296 /// and discard any value/exception that this Future has obtained.
298 Future<T> ensure(F&& func);
300 /// Like onError, but for timeouts. example:
302 /// Future<int> f = makeFuture<int>(42)
303 /// .delayed(long_time)
304 /// .onTimeout(short_time,
305 /// []() -> int{ return -1; });
309 /// Future<int> f = makeFuture<int>(42)
310 /// .delayed(long_time)
311 /// .onTimeout(short_time,
312 /// []() { return makeFuture<int>(some_exception); });
314 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
316 /// This is not the method you're looking for.
318 /// This needs to be public because it's used by make* and when*, and it's
319 /// not worth listing all those and their fancy template signatures as
320 /// friends. But it's not for public consumption.
322 void setCallback_(F&& func);
324 /// A Future's callback is executed when all three of these conditions have
325 /// become true: it has a value (set by the Promise), it has a callback (set
326 /// by then), and it is active (active by default).
328 /// Inactive Futures will activate upon destruction.
329 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
333 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
337 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
339 return std::move(*this);
341 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
343 return std::move(*this);
347 return core_->isActive();
351 void raise(E&& exception) {
352 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
353 std::forward<E>(exception)));
356 /// Raise an interrupt. If the promise holder has an interrupt
357 /// handler it will be called and potentially stop asynchronous work from
358 /// being done. This is advisory only - a promise holder may not set an
359 /// interrupt handler, or may do anything including ignore. But, if you know
360 /// your future supports this the most likely result is stopping or
361 /// preventing the asynchronous operation (if in time), and the promise
362 /// holder setting an exception on the future. (That may happen
363 /// asynchronously, of course.)
364 void raise(exception_wrapper interrupt);
367 raise(FutureCancellation());
370 /// Throw TimedOut if this Future does not complete within the given
371 /// duration from now. The optional Timeekeeper is as with futures::sleep().
372 Future<T> within(Duration, Timekeeper* = nullptr);
374 /// Throw the given exception if this Future does not complete within the
375 /// given duration from now. The optional Timeekeeper is as with
376 /// futures::sleep().
378 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
380 /// Delay the completion of this Future for at least this duration from
381 /// now. The optional Timekeeper is as with futures::sleep().
382 Future<T> delayed(Duration, Timekeeper* = nullptr);
384 /// Block until this Future is complete. Returns a reference to this Future.
387 /// Overload of wait() for rvalue Futures
388 Future<T>&& wait() &&;
390 /// Block until this Future is complete or until the given Duration passes.
391 /// Returns a reference to this Future
392 Future<T>& wait(Duration) &;
394 /// Overload of wait(Duration) for rvalue Futures
395 Future<T>&& wait(Duration) &&;
397 /// Call e->drive() repeatedly until the future is fulfilled. Examples
398 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
399 /// reference to this Future so that you can chain calls if desired.
400 /// value (moved out), or throws the exception.
401 Future<T>& waitVia(DrivableExecutor* e) &;
403 /// Overload of waitVia() for rvalue Futures
404 Future<T>&& waitVia(DrivableExecutor* e) &&;
406 /// If the value in this Future is equal to the given Future, when they have
407 /// both completed, the value of the resulting Future<bool> will be true. It
408 /// will be false otherwise (including when one or both Futures have an
410 Future<bool> willEqual(Future<T>&);
412 /// predicate behaves like std::function<bool(T const&)>
413 /// If the predicate does not obtain with the value, the result
414 /// is a folly::PredicateDoesNotObtain exception
416 Future<T> filter(F&& predicate);
418 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
419 /// the result of collect or collectAll
420 template <class I, class F>
421 Future<I> reduce(I&& initial, F&& func);
423 /// Create a Future chain from a sequence of callbacks. i.e.
425 /// f.then(a).then(b).then(c)
427 /// where f is a Future<A> and the result of the chain is a Future<D>
430 /// f.thenMulti(a, b, c);
431 template <class Callback, class... Callbacks>
432 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
433 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
434 return then(std::forward<Callback>(fn))
435 .thenMulti(std::forward<Callbacks>(fns)...);
438 template <class Callback>
439 auto thenMulti(Callback&& fn) {
440 // thenMulti with one callback is just a then
441 return then(std::forward<Callback>(fn));
444 /// Create a Future chain from a sequence of callbacks. i.e.
446 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
448 /// where f is a Future<A> and the result of the chain is a Future<D>
451 /// f.thenMultiWithExecutor(executor, a, b, c);
452 template <class Callback, class... Callbacks>
453 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
454 // thenMultiExecutor with two callbacks is
455 // via(x).then(a).thenMulti(b, ...).via(oldX)
456 auto oldX = getExecutor();
458 return then(std::forward<Callback>(fn))
459 .thenMulti(std::forward<Callbacks>(fns)...)
463 template <class Callback>
464 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
465 // thenMulti with one callback is just a then with an executor
466 return then(x, std::forward<Callback>(fn));
469 /// Discard a result, but propagate an exception.
470 Future<Unit> unit() {
471 return then([]{ return Unit{}; });
475 typedef futures::detail::Core<T>* corePtr;
477 // shared core state object
481 Future(corePtr obj) : core_(obj) {}
483 explicit Future(futures::detail::EmptyConstruct) noexcept;
487 void throwIfInvalid() const;
489 friend class Promise<T>;
490 template <class> friend class Future;
493 friend Future<T2> makeFuture(Try<T2>&&);
495 /// Repeat the given future (i.e., the computation it contains)
498 /// thunk behaves like std::function<Future<T2>(void)>
500 friend Future<Unit> times(int n, F&& thunk);
502 /// Carry out the computation contained in the given future if
503 /// the predicate holds.
505 /// thunk behaves like std::function<Future<T2>(void)>
507 friend Future<Unit> when(bool p, F&& thunk);
509 /// Carry out the computation contained in the given future if
510 /// while the predicate continues to hold.
512 /// thunk behaves like std::function<Future<T2>(void)>
514 /// predicate behaves like std::function<bool(void)>
515 template <class P, class F>
516 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
518 // Variant: returns a value
519 // e.g. f.then([](Try<T> t){ return t.value(); });
520 template <typename F, typename R, bool isTry, typename... Args>
521 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
522 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
524 // Variant: returns a Future
525 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
526 template <typename F, typename R, bool isTry, typename... Args>
527 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
528 thenImplementation(F&& func, futures::detail::argResult<isTry, F, Args...>);
530 Executor* getExecutor() { return core_->getExecutor(); }
531 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
532 core_->setExecutor(x, priority);
538 #include <folly/futures/Future-inl.h>