2 * Copyright 2016 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/futures/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;
56 // conversion constructors
59 typename = typename std::enable_if<std::is_convertible<U, T>::value &&
60 sizeof(U) == sizeof(T)>::type>
61 /* implicit */ Future(Future<U>&&) noexcept;
64 typename = typename std::enable_if<std::is_convertible<U, T>::value &&
65 sizeof(U) == sizeof(T)>::type>
66 /* implicit */ Future& operator=(Future<U>&&) noexcept;
68 /// Construct a Future from a value (perfect forwarding)
69 template <class T2 = T, typename =
70 typename std::enable_if<
71 !isFuture<typename std::decay<T2>::type>::value>::type>
72 /* implicit */ Future(T2&& val);
74 template <class T2 = T, typename =
75 typename std::enable_if<
76 std::is_same<Unit, T2>::value>::type>
81 /** Return the reference to result. Should not be called if !isReady().
82 Will rethrow the exception if an exception has been
85 typename std::add_lvalue_reference<T>::type
87 typename std::add_lvalue_reference<const T>::type
90 /// Returns an inactive Future which will call back on the other side of
91 /// executor (when it is activated).
93 /// NB remember that Futures activate when they destruct. This is good,
94 /// it means that this will work:
96 /// f.via(e).then(a).then(b);
98 /// a and b will execute in the same context (the far side of e), because
99 /// the Future (temporary variable) created by via(e) does not call back
100 /// until it destructs, which is after then(a) and then(b) have been wired
103 /// But this is still racy:
105 /// f = f.via(e).then(a);
107 // The ref-qualifier allows for `this` to be moved out so we
108 // don't get access-after-free situations in chaining.
109 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
110 inline Future<T> via(
112 int8_t priority = Executor::MID_PRI) &&;
114 /// This variant creates a new future, where the ref-qualifier && version
115 /// moves `this` out. This one is less efficient but avoids confusing users
116 /// when "return f.via(x);" fails.
117 inline Future<T> via(
119 int8_t priority = Executor::MID_PRI) &;
121 /** True when the result (or exception) is ready. */
122 bool isReady() const;
124 /// sugar for getTry().hasValue()
127 /// sugar for getTry().hasException()
130 /** A reference to the Try of the value */
133 /// If the promise has been fulfilled, return an Optional with the Try<T>.
134 /// Otherwise return an empty Optional.
135 /// Note that this moves the Try<T> out.
136 Optional<Try<T>> poll();
138 /// Block until the future is fulfilled. Returns the value (moved out), or
139 /// throws the exception. The future must not already have a callback.
142 /// Block until the future is fulfilled, or until timed out. Returns the
143 /// value (moved out), or throws the exception (which might be a TimedOut
147 /// Call e->drive() repeatedly until the future is fulfilled. Examples
148 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
149 /// value (moved out), or throws the exception.
150 T getVia(DrivableExecutor* e);
152 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
153 /// Future<T> instance.
154 template <class F = T>
155 typename std::enable_if<isFuture<F>::value,
156 Future<typename isFuture<T>::Inner>>::type
159 /** When this Future has completed, execute func which is a function that
169 Func shall return either another Future or a value.
171 A Future for the return type of func is returned.
173 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
175 The Future given to the functor is ready, and the functor may call
176 value(), which may rethrow if this has captured an exception. If func
177 throws, the exception will be captured in the Future that is returned.
179 // gcc 4.8 requires that we cast function reference types to function pointer
180 // types. Fore more details see the comment on FunctionReferenceToPointer
182 // gcc versions 4.9 and above (as well as clang) do not require this hack.
183 // For those, the FF tenplate parameter can be removed and occurences of FF
187 typename FF = typename detail::FunctionReferenceToPointer<F>::type,
188 typename R = detail::callableResult<T, FF>>
189 typename R::Return then(F&& func) {
190 typedef typename R::Arg Arguments;
191 return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
194 /// Variant where func is an member function
196 /// struct Worker { R doWork(Try<T>); }
199 /// Future<R> f2 = f1.then(&Worker::doWork, w);
201 /// This is just sugar for
203 /// f1.then(std::bind(&Worker::doWork, w));
204 template <typename R, typename Caller, typename... Args>
205 Future<typename isFuture<R>::Inner>
206 then(R(Caller::*func)(Args...), Caller *instance);
208 /// Execute the callback via the given Executor. The executor doesn't stick.
212 /// f.via(x).then(b).then(c)
216 /// f.then(x, b).then(c)
218 /// In the former both b and c execute via x. In the latter, only b executes
219 /// via x, and c executes via the same executor (if any) that f had.
220 template <class Executor, class Arg, class... Args>
221 auto then(Executor* x, Arg&& arg, Args&&... args)
222 -> decltype(this->then(std::forward<Arg>(arg),
223 std::forward<Args>(args)...));
225 /// Convenience method for ignoring the value and creating a Future<Unit>.
226 /// Exceptions still propagate.
229 /// Set an error callback for this Future. The callback should take a single
230 /// argument of the type that you want to catch, and should return a value of
231 /// the same type as this Future, or a Future of that type (see overload
232 /// below). For instance,
236 /// throw std::runtime_error("oh no!");
239 /// .onError([] (std::runtime_error& e) {
240 /// LOG(INFO) << "std::runtime_error: " << e.what();
241 /// return -1; // or makeFuture<int>(-1)
244 typename std::enable_if<
245 !detail::callableWith<F, exception_wrapper>::value &&
246 !detail::Extract<F>::ReturnsFuture::value,
250 /// Overload of onError where the error callback returns a Future<T>
252 typename std::enable_if<
253 !detail::callableWith<F, exception_wrapper>::value &&
254 detail::Extract<F>::ReturnsFuture::value,
258 /// Overload of onError that takes exception_wrapper and returns Future<T>
260 typename std::enable_if<
261 detail::callableWith<F, exception_wrapper>::value &&
262 detail::Extract<F>::ReturnsFuture::value,
266 /// Overload of onError that takes exception_wrapper and returns T
268 typename std::enable_if<
269 detail::callableWith<F, exception_wrapper>::value &&
270 !detail::Extract<F>::ReturnsFuture::value,
274 /// func is like std::function<void()> and is executed unconditionally, and
275 /// the value/exception is passed through to the resulting Future.
276 /// func shouldn't throw, but if it does it will be captured and propagated,
277 /// and discard any value/exception that this Future has obtained.
279 Future<T> ensure(F&& func);
281 /// Like onError, but for timeouts. example:
283 /// Future<int> f = makeFuture<int>(42)
284 /// .delayed(long_time)
285 /// .onTimeout(short_time,
286 /// []() -> int{ return -1; });
290 /// Future<int> f = makeFuture<int>(42)
291 /// .delayed(long_time)
292 /// .onTimeout(short_time,
293 /// []() { return makeFuture<int>(some_exception); });
295 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
297 /// This is not the method you're looking for.
299 /// This needs to be public because it's used by make* and when*, and it's
300 /// not worth listing all those and their fancy template signatures as
301 /// friends. But it's not for public consumption.
303 void setCallback_(F&& func);
305 /// A Future's callback is executed when all three of these conditions have
306 /// become true: it has a value (set by the Promise), it has a callback (set
307 /// by then), and it is active (active by default).
309 /// Inactive Futures will activate upon destruction.
310 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
314 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
318 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
320 return std::move(*this);
322 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
324 return std::move(*this);
328 return core_->isActive();
332 void raise(E&& exception) {
333 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
334 std::forward<E>(exception)));
337 /// Raise an interrupt. If the promise holder has an interrupt
338 /// handler it will be called and potentially stop asynchronous work from
339 /// being done. This is advisory only - a promise holder may not set an
340 /// interrupt handler, or may do anything including ignore. But, if you know
341 /// your future supports this the most likely result is stopping or
342 /// preventing the asynchronous operation (if in time), and the promise
343 /// holder setting an exception on the future. (That may happen
344 /// asynchronously, of course.)
345 void raise(exception_wrapper interrupt);
348 raise(FutureCancellation());
351 /// Throw TimedOut if this Future does not complete within the given
352 /// duration from now. The optional Timeekeeper is as with futures::sleep().
353 Future<T> within(Duration, Timekeeper* = nullptr);
355 /// Throw the given exception if this Future does not complete within the
356 /// given duration from now. The optional Timeekeeper is as with
357 /// futures::sleep().
359 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
361 /// Delay the completion of this Future for at least this duration from
362 /// now. The optional Timekeeper is as with futures::sleep().
363 Future<T> delayed(Duration, Timekeeper* = nullptr);
365 /// Block until this Future is complete. Returns a reference to this Future.
368 /// Overload of wait() for rvalue Futures
369 Future<T>&& wait() &&;
371 /// Block until this Future is complete or until the given Duration passes.
372 /// Returns a reference to this Future
373 Future<T>& wait(Duration) &;
375 /// Overload of wait(Duration) for rvalue Futures
376 Future<T>&& wait(Duration) &&;
378 /// Call e->drive() repeatedly until the future is fulfilled. Examples
379 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
380 /// reference to this Future so that you can chain calls if desired.
381 /// value (moved out), or throws the exception.
382 Future<T>& waitVia(DrivableExecutor* e) &;
384 /// Overload of waitVia() for rvalue Futures
385 Future<T>&& waitVia(DrivableExecutor* e) &&;
387 /// If the value in this Future is equal to the given Future, when they have
388 /// both completed, the value of the resulting Future<bool> will be true. It
389 /// will be false otherwise (including when one or both Futures have an
391 Future<bool> willEqual(Future<T>&);
393 /// predicate behaves like std::function<bool(T const&)>
394 /// If the predicate does not obtain with the value, the result
395 /// is a folly::PredicateDoesNotObtain exception
397 Future<T> filter(F&& predicate);
399 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
400 /// the result of collect or collectAll
401 template <class I, class F>
402 Future<I> reduce(I&& initial, F&& func);
404 /// Create a Future chain from a sequence of callbacks. i.e.
406 /// f.then(a).then(b).then(c)
408 /// where f is a Future<A> and the result of the chain is a Future<D>
411 /// f.thenMulti(a, b, c);
412 template <class Callback, class... Callbacks>
413 auto thenMulti(Callback&& fn, Callbacks&&... fns)
414 -> decltype(this->then(std::forward<Callback>(fn)).
415 thenMulti(std::forward<Callbacks>(fns)...));
417 // Nothing to see here, just thenMulti's base case
418 template <class Callback>
419 auto thenMulti(Callback&& fn)
420 -> decltype(this->then(std::forward<Callback>(fn)));
422 /// Create a Future chain from a sequence of callbacks. i.e.
424 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
426 /// where f is a Future<A> and the result of the chain is a Future<D>
429 /// f.thenMultiWithExecutor(executor, a, b, c);
430 template <class Callback, class... Callbacks>
431 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
432 -> decltype(this->then(std::forward<Callback>(fn)).
433 thenMulti(std::forward<Callbacks>(fns)...));
435 // Nothing to see here, just thenMultiWithExecutor's base case
436 template <class Callback>
437 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
438 -> decltype(this->then(std::forward<Callback>(fn)));
440 /// Discard a result, but propagate an exception.
441 Future<Unit> unit() {
442 return then([]{ return Unit{}; });
446 typedef detail::Core<T>* corePtr;
448 // shared core state object
452 Future(corePtr obj) : core_(obj) {}
456 void throwIfInvalid() const;
458 friend class Promise<T>;
459 template <class> friend class Future;
462 friend Future<T2> makeFuture(Try<T2>&&);
464 /// Repeat the given future (i.e., the computation it contains)
467 /// thunk behaves like std::function<Future<T2>(void)>
469 friend Future<Unit> times(int n, F&& thunk);
471 /// Carry out the computation contained in the given future if
472 /// the predicate holds.
474 /// thunk behaves like std::function<Future<T2>(void)>
476 friend Future<Unit> when(bool p, F&& thunk);
478 /// Carry out the computation contained in the given future if
479 /// while the predicate continues to hold.
481 /// thunk behaves like std::function<Future<T2>(void)>
483 /// predicate behaves like std::function<bool(void)>
484 template <class P, class F>
485 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
487 // Variant: returns a value
488 // e.g. f.then([](Try<T> t){ return t.value(); });
489 template <typename F, typename R, bool isTry, typename... Args>
490 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
491 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
493 // Variant: returns a Future
494 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
495 template <typename F, typename R, bool isTry, typename... Args>
496 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
497 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
499 Executor* getExecutor() { return core_->getExecutor(); }
500 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
501 core_->setExecutor(x, priority);
507 #include <folly/futures/Future-inl.h>