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>
48 static Future<T> makeEmpty(); // equivalent to moved-from
51 Future(Future const&) = delete;
52 Future& operator=(Future const&) = delete;
55 Future(Future&&) noexcept;
56 Future& operator=(Future&&) noexcept;
61 typename std::enable_if<
62 !std::is_same<T, typename std::decay<T2>::type>::value &&
63 std::is_constructible<T, T2&&>::value &&
64 std::is_convertible<T2&&, T>::value,
66 /* implicit */ Future(Future<T2>&&);
69 typename std::enable_if<
70 !std::is_same<T, typename std::decay<T2>::type>::value &&
71 std::is_constructible<T, T2&&>::value &&
72 !std::is_convertible<T2&&, T>::value,
74 explicit Future(Future<T2>&&);
77 typename std::enable_if<
78 !std::is_same<T, typename std::decay<T2>::type>::value &&
79 std::is_constructible<T, T2&&>::value,
81 Future& operator=(Future<T2>&&);
83 /// Construct a Future from a value (perfect forwarding)
84 template <class T2 = T, typename =
85 typename std::enable_if<
86 !isFuture<typename std::decay<T2>::type>::value>::type>
87 /* implicit */ Future(T2&& val);
89 template <class T2 = T>
90 /* implicit */ Future(
91 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
95 /** Return the reference to result. Should not be called if !isReady().
96 Will rethrow the exception if an exception has been
99 typename std::add_lvalue_reference<T>::type
101 typename std::add_lvalue_reference<const T>::type
104 /// Returns an inactive Future which will call back on the other side of
105 /// executor (when it is activated).
107 /// NB remember that Futures activate when they destruct. This is good,
108 /// it means that this will work:
110 /// f.via(e).then(a).then(b);
112 /// a and b will execute in the same context (the far side of e), because
113 /// the Future (temporary variable) created by via(e) does not call back
114 /// until it destructs, which is after then(a) and then(b) have been wired
117 /// But this is still racy:
119 /// f = f.via(e).then(a);
121 // The ref-qualifier allows for `this` to be moved out so we
122 // don't get access-after-free situations in chaining.
123 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
124 inline Future<T> via(
126 int8_t priority = Executor::MID_PRI) &&;
128 /// This variant creates a new future, where the ref-qualifier && version
129 /// moves `this` out. This one is less efficient but avoids confusing users
130 /// when "return f.via(x);" fails.
131 inline Future<T> via(
133 int8_t priority = Executor::MID_PRI) &;
135 /** True when the result (or exception) is ready. */
136 bool isReady() const;
138 /// sugar for getTry().hasValue()
141 /// sugar for getTry().hasException()
144 /** A reference to the Try of the value */
147 /// Call e->drive() repeatedly until the future is fulfilled. Examples
148 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
149 /// reference to the Try of the value.
150 Try<T>& getTryVia(DrivableExecutor* e);
152 /// If the promise has been fulfilled, return an Optional with the Try<T>.
153 /// Otherwise return an empty Optional.
154 /// Note that this moves the Try<T> out.
155 Optional<Try<T>> poll();
157 /// Block until the future is fulfilled. Returns the value (moved out), or
158 /// throws the exception. The future must not already have a callback.
161 /// Block until the future is fulfilled, or until timed out. Returns the
162 /// value (moved out), or throws the exception (which might be a TimedOut
166 /// Call e->drive() repeatedly until the future is fulfilled. Examples
167 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
168 /// value (moved out), or throws the exception.
169 T getVia(DrivableExecutor* e);
171 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
172 /// Future<T> instance.
173 template <class F = T>
174 typename std::enable_if<isFuture<F>::value,
175 Future<typename isFuture<T>::Inner>>::type
178 /** When this Future has completed, execute func which is a function that
188 Func shall return either another Future or a value.
190 A Future for the return type of func is returned.
192 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
194 The Future given to the functor is ready, and the functor may call
195 value(), which may rethrow if this has captured an exception. If func
196 throws, the exception will be captured in the Future that is returned.
198 // gcc 4.8 requires that we cast function reference types to function pointer
199 // types. Fore more details see the comment on FunctionReferenceToPointer
201 // gcc versions 4.9 and above (as well as clang) do not require this hack.
202 // For those, the FF tenplate parameter can be removed and occurences of FF
206 typename FF = typename detail::FunctionReferenceToPointer<F>::type,
207 typename R = detail::callableResult<T, FF>>
208 typename R::Return then(F&& func) {
209 typedef typename R::Arg Arguments;
210 return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
213 /// Variant where func is an member function
215 /// struct Worker { R doWork(Try<T>); }
218 /// Future<R> f2 = f1.then(&Worker::doWork, w);
220 /// This is just sugar for
222 /// f1.then(std::bind(&Worker::doWork, w));
223 template <typename R, typename Caller, typename... Args>
224 Future<typename isFuture<R>::Inner>
225 then(R(Caller::*func)(Args...), Caller *instance);
227 /// Execute the callback via the given Executor. The executor doesn't stick.
231 /// f.via(x).then(b).then(c)
235 /// f.then(x, b).then(c)
237 /// In the former both b and c execute via x. In the latter, only b executes
238 /// via x, and c executes via the same executor (if any) that f had.
239 template <class Executor, class Arg, class... Args>
240 auto then(Executor* x, Arg&& arg, Args&&... args) {
241 auto oldX = getExecutor();
243 return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...)
247 /// Convenience method for ignoring the value and creating a Future<Unit>.
248 /// Exceptions still propagate.
251 /// Set an error callback for this Future. The callback should take a single
252 /// argument of the type that you want to catch, and should return a value of
253 /// the same type as this Future, or a Future of that type (see overload
254 /// below). For instance,
258 /// throw std::runtime_error("oh no!");
261 /// .onError([] (std::runtime_error& e) {
262 /// LOG(INFO) << "std::runtime_error: " << e.what();
263 /// return -1; // or makeFuture<int>(-1)
266 typename std::enable_if<
267 !detail::callableWith<F, exception_wrapper>::value &&
268 !detail::Extract<F>::ReturnsFuture::value,
272 /// Overload of onError where the error callback returns a Future<T>
274 typename std::enable_if<
275 !detail::callableWith<F, exception_wrapper>::value &&
276 detail::Extract<F>::ReturnsFuture::value,
280 /// Overload of onError that takes exception_wrapper and returns Future<T>
282 typename std::enable_if<
283 detail::callableWith<F, exception_wrapper>::value &&
284 detail::Extract<F>::ReturnsFuture::value,
288 /// Overload of onError that takes exception_wrapper and returns T
290 typename std::enable_if<
291 detail::callableWith<F, exception_wrapper>::value &&
292 !detail::Extract<F>::ReturnsFuture::value,
296 /// func is like std::function<void()> and is executed unconditionally, and
297 /// the value/exception is passed through to the resulting Future.
298 /// func shouldn't throw, but if it does it will be captured and propagated,
299 /// and discard any value/exception that this Future has obtained.
301 Future<T> ensure(F&& func);
303 /// Like onError, but for timeouts. example:
305 /// Future<int> f = makeFuture<int>(42)
306 /// .delayed(long_time)
307 /// .onTimeout(short_time,
308 /// []() -> int{ return -1; });
312 /// Future<int> f = makeFuture<int>(42)
313 /// .delayed(long_time)
314 /// .onTimeout(short_time,
315 /// []() { return makeFuture<int>(some_exception); });
317 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
319 /// This is not the method you're looking for.
321 /// This needs to be public because it's used by make* and when*, and it's
322 /// not worth listing all those and their fancy template signatures as
323 /// friends. But it's not for public consumption.
325 void setCallback_(F&& func);
327 /// A Future's callback is executed when all three of these conditions have
328 /// become true: it has a value (set by the Promise), it has a callback (set
329 /// by then), and it is active (active by default).
331 /// Inactive Futures will activate upon destruction.
332 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
336 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
340 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
342 return std::move(*this);
344 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
346 return std::move(*this);
350 return core_->isActive();
354 void raise(E&& exception) {
355 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
356 std::forward<E>(exception)));
359 /// Raise an interrupt. If the promise holder has an interrupt
360 /// handler it will be called and potentially stop asynchronous work from
361 /// being done. This is advisory only - a promise holder may not set an
362 /// interrupt handler, or may do anything including ignore. But, if you know
363 /// your future supports this the most likely result is stopping or
364 /// preventing the asynchronous operation (if in time), and the promise
365 /// holder setting an exception on the future. (That may happen
366 /// asynchronously, of course.)
367 void raise(exception_wrapper interrupt);
370 raise(FutureCancellation());
373 /// Throw TimedOut if this Future does not complete within the given
374 /// duration from now. The optional Timeekeeper is as with futures::sleep().
375 Future<T> within(Duration, Timekeeper* = nullptr);
377 /// Throw the given exception if this Future does not complete within the
378 /// given duration from now. The optional Timeekeeper is as with
379 /// futures::sleep().
381 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
383 /// Delay the completion of this Future for at least this duration from
384 /// now. The optional Timekeeper is as with futures::sleep().
385 Future<T> delayed(Duration, Timekeeper* = nullptr);
387 /// Block until this Future is complete. Returns a reference to this Future.
390 /// Overload of wait() for rvalue Futures
391 Future<T>&& wait() &&;
393 /// Block until this Future is complete or until the given Duration passes.
394 /// Returns a reference to this Future
395 Future<T>& wait(Duration) &;
397 /// Overload of wait(Duration) for rvalue Futures
398 Future<T>&& wait(Duration) &&;
400 /// Call e->drive() repeatedly until the future is fulfilled. Examples
401 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
402 /// reference to this Future so that you can chain calls if desired.
403 /// value (moved out), or throws the exception.
404 Future<T>& waitVia(DrivableExecutor* e) &;
406 /// Overload of waitVia() for rvalue Futures
407 Future<T>&& waitVia(DrivableExecutor* e) &&;
409 /// If the value in this Future is equal to the given Future, when they have
410 /// both completed, the value of the resulting Future<bool> will be true. It
411 /// will be false otherwise (including when one or both Futures have an
413 Future<bool> willEqual(Future<T>&);
415 /// predicate behaves like std::function<bool(T const&)>
416 /// If the predicate does not obtain with the value, the result
417 /// is a folly::PredicateDoesNotObtain exception
419 Future<T> filter(F&& predicate);
421 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
422 /// the result of collect or collectAll
423 template <class I, class F>
424 Future<I> reduce(I&& initial, F&& func);
426 /// Create a Future chain from a sequence of callbacks. i.e.
428 /// f.then(a).then(b).then(c)
430 /// where f is a Future<A> and the result of the chain is a Future<D>
433 /// f.thenMulti(a, b, c);
434 template <class Callback, class... Callbacks>
435 auto thenMulti(Callback&& fn, Callbacks&&... fns) {
436 // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
437 return then(std::forward<Callback>(fn))
438 .thenMulti(std::forward<Callbacks>(fns)...);
441 template <class Callback>
442 auto thenMulti(Callback&& fn) {
443 // thenMulti with one callback is just a then
444 return then(std::forward<Callback>(fn));
447 /// Create a Future chain from a sequence of callbacks. i.e.
449 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
451 /// where f is a Future<A> and the result of the chain is a Future<D>
454 /// f.thenMultiWithExecutor(executor, a, b, c);
455 template <class Callback, class... Callbacks>
456 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) {
457 // thenMultiExecutor with two callbacks is
458 // via(x).then(a).thenMulti(b, ...).via(oldX)
459 auto oldX = getExecutor();
461 return then(std::forward<Callback>(fn))
462 .thenMulti(std::forward<Callbacks>(fns)...)
466 template <class Callback>
467 auto thenMultiWithExecutor(Executor* x, Callback&& fn) {
468 // thenMulti with one callback is just a then with an executor
469 return then(x, std::forward<Callback>(fn));
472 /// Discard a result, but propagate an exception.
473 Future<Unit> unit() {
474 return then([]{ return Unit{}; });
478 typedef detail::Core<T>* corePtr;
480 // shared core state object
484 Future(corePtr obj) : core_(obj) {}
486 explicit Future(detail::EmptyConstruct) noexcept;
490 void throwIfInvalid() const;
492 friend class Promise<T>;
493 template <class> friend class Future;
496 friend Future<T2> makeFuture(Try<T2>&&);
498 /// Repeat the given future (i.e., the computation it contains)
501 /// thunk behaves like std::function<Future<T2>(void)>
503 friend Future<Unit> times(int n, F&& thunk);
505 /// Carry out the computation contained in the given future if
506 /// the predicate holds.
508 /// thunk behaves like std::function<Future<T2>(void)>
510 friend Future<Unit> when(bool p, F&& thunk);
512 /// Carry out the computation contained in the given future if
513 /// while the predicate continues to hold.
515 /// thunk behaves like std::function<Future<T2>(void)>
517 /// predicate behaves like std::function<bool(void)>
518 template <class P, class F>
519 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
521 // Variant: returns a value
522 // e.g. f.then([](Try<T> t){ return t.value(); });
523 template <typename F, typename R, bool isTry, typename... Args>
524 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
525 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
527 // Variant: returns a Future
528 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
529 template <typename F, typename R, bool isTry, typename... Args>
530 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
531 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
533 Executor* getExecutor() { return core_->getExecutor(); }
534 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
535 core_->setExecutor(x, priority);
541 #include <folly/futures/Future-inl.h>