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/futures/DrivableExecutor.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/Try.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/detail/Types.h>
34 // boring predeclarations and details
35 #include <folly/futures/Future-pre.h>
37 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
38 // Needs to be included after Future-pre.h and before Future-inl.h
39 #include <folly/futures/helpers.h>
49 Future(Future const&) = delete;
50 Future& operator=(Future const&) = delete;
53 Future(Future&&) noexcept;
54 Future& operator=(Future&&) noexcept;
59 typename std::enable_if<
60 !std::is_same<T, typename std::decay<T2>::type>::value &&
61 std::is_constructible<T, T2&&>::value &&
62 std::is_convertible<T2&&, T>::value,
64 /* implicit */ Future(Future<T2>&&);
67 typename std::enable_if<
68 !std::is_same<T, typename std::decay<T2>::type>::value &&
69 std::is_constructible<T, T2&&>::value &&
70 !std::is_convertible<T2&&, T>::value,
72 explicit Future(Future<T2>&&);
75 typename std::enable_if<
76 !std::is_same<T, typename std::decay<T2>::type>::value &&
77 std::is_constructible<T, T2&&>::value,
79 Future& operator=(Future<T2>&&);
81 /// Construct a Future from a value (perfect forwarding)
82 template <class T2 = T, typename =
83 typename std::enable_if<
84 !isFuture<typename std::decay<T2>::type>::value>::type>
85 /* implicit */ Future(T2&& val);
87 template <class T2 = T>
88 /* implicit */ Future(
89 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
93 /** Return the reference to result. Should not be called if !isReady().
94 Will rethrow the exception if an exception has been
97 typename std::add_lvalue_reference<T>::type
99 typename std::add_lvalue_reference<const T>::type
102 /// Returns an inactive Future which will call back on the other side of
103 /// executor (when it is activated).
105 /// NB remember that Futures activate when they destruct. This is good,
106 /// it means that this will work:
108 /// f.via(e).then(a).then(b);
110 /// a and b will execute in the same context (the far side of e), because
111 /// the Future (temporary variable) created by via(e) does not call back
112 /// until it destructs, which is after then(a) and then(b) have been wired
115 /// But this is still racy:
117 /// f = f.via(e).then(a);
119 // The ref-qualifier allows for `this` to be moved out so we
120 // don't get access-after-free situations in chaining.
121 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
122 inline Future<T> via(
124 int8_t priority = Executor::MID_PRI) &&;
126 /// This variant creates a new future, where the ref-qualifier && version
127 /// moves `this` out. This one is less efficient but avoids confusing users
128 /// when "return f.via(x);" fails.
129 inline Future<T> via(
131 int8_t priority = Executor::MID_PRI) &;
133 /** True when the result (or exception) is ready. */
134 bool isReady() const;
136 /// sugar for getTry().hasValue()
139 /// sugar for getTry().hasException()
142 /** A reference to the Try of the value */
145 /// Call e->drive() repeatedly until the future is fulfilled. Examples
146 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
147 /// reference to the Try of the value.
148 Try<T>& getTryVia(DrivableExecutor* e);
150 /// If the promise has been fulfilled, return an Optional with the Try<T>.
151 /// Otherwise return an empty Optional.
152 /// Note that this moves the Try<T> out.
153 Optional<Try<T>> poll();
155 /// Block until the future is fulfilled. Returns the value (moved out), or
156 /// throws the exception. The future must not already have a callback.
159 /// Block until the future is fulfilled, or until timed out. Returns the
160 /// value (moved out), or throws the exception (which might be a TimedOut
164 /// Call e->drive() repeatedly until the future is fulfilled. Examples
165 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
166 /// value (moved out), or throws the exception.
167 T getVia(DrivableExecutor* e);
169 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
170 /// Future<T> instance.
171 template <class F = T>
172 typename std::enable_if<isFuture<F>::value,
173 Future<typename isFuture<T>::Inner>>::type
176 /** When this Future has completed, execute func which is a function that
186 Func shall return either another Future or a value.
188 A Future for the return type of func is returned.
190 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
192 The Future given to the functor is ready, and the functor may call
193 value(), which may rethrow if this has captured an exception. If func
194 throws, the exception will be captured in the Future that is returned.
196 // gcc 4.8 requires that we cast function reference types to function pointer
197 // types. Fore more details see the comment on FunctionReferenceToPointer
199 // gcc versions 4.9 and above (as well as clang) do not require this hack.
200 // For those, the FF tenplate parameter can be removed and occurences of FF
204 typename FF = typename detail::FunctionReferenceToPointer<F>::type,
205 typename R = detail::callableResult<T, FF>>
206 typename R::Return then(F&& func) {
207 typedef typename R::Arg Arguments;
208 return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
211 /// Variant where func is an member function
213 /// struct Worker { R doWork(Try<T>); }
216 /// Future<R> f2 = f1.then(&Worker::doWork, w);
218 /// This is just sugar for
220 /// f1.then(std::bind(&Worker::doWork, w));
221 template <typename R, typename Caller, typename... Args>
222 Future<typename isFuture<R>::Inner>
223 then(R(Caller::*func)(Args...), Caller *instance);
225 /// Execute the callback via the given Executor. The executor doesn't stick.
229 /// f.via(x).then(b).then(c)
233 /// f.then(x, b).then(c)
235 /// In the former both b and c execute via x. In the latter, only b executes
236 /// via x, and c executes via the same executor (if any) that f had.
237 template <class Executor, class Arg, class... Args>
238 auto then(Executor* x, Arg&& arg, Args&&... args) {
239 auto oldX = getExecutor();
241 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
245 /// Convenience method for ignoring the value and creating a Future<Unit>.
246 /// Exceptions still propagate.
249 /// Set an error callback for this Future. The callback should take a single
250 /// argument of the type that you want to catch, and should return a value of
251 /// the same type as this Future, or a Future of that type (see overload
252 /// below). For instance,
256 /// throw std::runtime_error("oh no!");
259 /// .onError([] (std::runtime_error& e) {
260 /// LOG(INFO) << "std::runtime_error: " << e.what();
261 /// return -1; // or makeFuture<int>(-1)
264 typename std::enable_if<
265 !detail::callableWith<F, exception_wrapper>::value &&
266 !detail::Extract<F>::ReturnsFuture::value,
270 /// Overload of onError where the error callback returns a Future<T>
272 typename std::enable_if<
273 !detail::callableWith<F, exception_wrapper>::value &&
274 detail::Extract<F>::ReturnsFuture::value,
278 /// Overload of onError that takes exception_wrapper and returns Future<T>
280 typename std::enable_if<
281 detail::callableWith<F, exception_wrapper>::value &&
282 detail::Extract<F>::ReturnsFuture::value,
286 /// Overload of onError that takes exception_wrapper and returns T
288 typename std::enable_if<
289 detail::callableWith<F, exception_wrapper>::value &&
290 !detail::Extract<F>::ReturnsFuture::value,
294 /// func is like std::function<void()> and is executed unconditionally, and
295 /// the value/exception is passed through to the resulting Future.
296 /// func shouldn't throw, but if it does it will be captured and propagated,
297 /// and discard any value/exception that this Future has obtained.
299 Future<T> ensure(F&& func);
301 /// Like onError, but for timeouts. example:
303 /// Future<int> f = makeFuture<int>(42)
304 /// .delayed(long_time)
305 /// .onTimeout(short_time,
306 /// []() -> int{ return -1; });
310 /// Future<int> f = makeFuture<int>(42)
311 /// .delayed(long_time)
312 /// .onTimeout(short_time,
313 /// []() { return makeFuture<int>(some_exception); });
315 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
317 /// This is not the method you're looking for.
319 /// This needs to be public because it's used by make* and when*, and it's
320 /// not worth listing all those and their fancy template signatures as
321 /// friends. But it's not for public consumption.
323 void setCallback_(F&& func);
325 /// A Future's callback is executed when all three of these conditions have
326 /// become true: it has a value (set by the Promise), it has a callback (set
327 /// by then), and it is active (active by default).
329 /// Inactive Futures will activate upon destruction.
330 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
334 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
338 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
340 return std::move(*this);
342 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
344 return std::move(*this);
348 return core_->isActive();
352 void raise(E&& exception) {
353 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
354 std::forward<E>(exception)));
357 /// Raise an interrupt. If the promise holder has an interrupt
358 /// handler it will be called and potentially stop asynchronous work from
359 /// being done. This is advisory only - a promise holder may not set an
360 /// interrupt handler, or may do anything including ignore. But, if you know
361 /// your future supports this the most likely result is stopping or
362 /// preventing the asynchronous operation (if in time), and the promise
363 /// holder setting an exception on the future. (That may happen
364 /// asynchronously, of course.)
365 void raise(exception_wrapper interrupt);
368 raise(FutureCancellation());
371 /// Throw TimedOut if this Future does not complete within the given
372 /// duration from now. The optional Timeekeeper is as with futures::sleep().
373 Future<T> within(Duration, Timekeeper* = nullptr);
375 /// Throw the given exception if this Future does not complete within the
376 /// given duration from now. The optional Timeekeeper is as with
377 /// futures::sleep().
379 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
381 /// Delay the completion of this Future for at least this duration from
382 /// now. The optional Timekeeper is as with futures::sleep().
383 Future<T> delayed(Duration, Timekeeper* = nullptr);
385 /// Block until this Future is complete. Returns a reference to this Future.
388 /// Overload of wait() for rvalue Futures
389 Future<T>&& wait() &&;
391 /// Block until this Future is complete or until the given Duration passes.
392 /// Returns a reference to this Future
393 Future<T>& wait(Duration) &;
395 /// Overload of wait(Duration) for rvalue Futures
396 Future<T>&& wait(Duration) &&;
398 /// Call e->drive() repeatedly until the future is fulfilled. Examples
399 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
400 /// reference to this Future so that you can chain calls if desired.
401 /// value (moved out), or throws the exception.
402 Future<T>& waitVia(DrivableExecutor* e) &;
404 /// Overload of waitVia() for rvalue Futures
405 Future<T>&& waitVia(DrivableExecutor* e) &&;
407 /// If the value in this Future is equal to the given Future, when they have
408 /// both completed, the value of the resulting Future<bool> will be true. It
409 /// will be false otherwise (including when one or both Futures have an
411 Future<bool> willEqual(Future<T>&);
413 /// predicate behaves like std::function<bool(T const&)>
414 /// If the predicate does not obtain with the value, the result
415 /// is a folly::PredicateDoesNotObtain exception
417 Future<T> filter(F&& predicate);
419 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
420 /// the result of collect or collectAll
421 template <class I, class F>
422 Future<I> reduce(I&& initial, F&& func);
424 /// Create a Future chain from a sequence of callbacks. i.e.
426 /// f.then(a).then(b).then(c)
428 /// where f is a Future<A> and the result of the chain is a Future<D>
431 /// f.thenMulti(a, b, c);
432 template <class Callback, class... Callbacks>
433 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
434 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
435 return then(std::forward<Callback>(fn))
436 .thenMulti(std::forward<Callbacks>(fns)...);
439 template <class Callback>
440 auto thenMulti(Callback&& fn) {
441 // thenMulti with one callback is just a then
442 return then(std::forward<Callback>(fn));
445 /// Create a Future chain from a sequence of callbacks. i.e.
447 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
449 /// where f is a Future<A> and the result of the chain is a Future<D>
452 /// f.thenMultiWithExecutor(executor, a, b, c);
453 template <class Callback, class... Callbacks>
454 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
455 // thenMultiExecutor with two callbacks is
456 // via(x).then(a).thenMulti(b, ...).via(oldX)
457 auto oldX = getExecutor();
459 return then(std::forward<Callback>(fn))
460 .thenMulti(std::forward<Callbacks>(fns)...)
464 template <class Callback>
465 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
466 // thenMulti with one callback is just a then with an executor
467 return then(x, std::forward<Callback>(fn));
470 /// Discard a result, but propagate an exception.
471 Future<Unit> unit() {
472 return then([]{ return Unit{}; });
476 typedef detail::Core<T>* corePtr;
478 // shared core state object
482 Future(corePtr obj) : core_(obj) {}
486 void throwIfInvalid() const;
488 friend class Promise<T>;
489 template <class> friend class Future;
492 friend Future<T2> makeFuture(Try<T2>&&);
494 /// Repeat the given future (i.e., the computation it contains)
497 /// thunk behaves like std::function<Future<T2>(void)>
499 friend Future<Unit> times(int n, F&& thunk);
501 /// Carry out the computation contained in the given future if
502 /// the predicate holds.
504 /// thunk behaves like std::function<Future<T2>(void)>
506 friend Future<Unit> when(bool p, F&& thunk);
508 /// Carry out the computation contained in the given future if
509 /// while the predicate continues to hold.
511 /// thunk behaves like std::function<Future<T2>(void)>
513 /// predicate behaves like std::function<bool(void)>
514 template <class P, class F>
515 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
517 // Variant: returns a value
518 // e.g. f.then([](Try<T> t){ return t.value(); });
519 template <typename F, typename R, bool isTry, typename... Args>
520 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
521 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
523 // Variant: returns a Future
524 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
525 template <typename F, typename R, bool isTry, typename... Args>
526 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
527 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
529 Executor* getExecutor() { return core_->getExecutor(); }
530 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
531 core_->setExecutor(x, priority);
537 #include <folly/futures/Future-inl.h>