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/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>
75 /* implicit */ Future(
76 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
80 /** Return the reference to result. Should not be called if !isReady().
81 Will rethrow the exception if an exception has been
84 typename std::add_lvalue_reference<T>::type
86 typename std::add_lvalue_reference<const T>::type
89 /// Returns an inactive Future which will call back on the other side of
90 /// executor (when it is activated).
92 /// NB remember that Futures activate when they destruct. This is good,
93 /// it means that this will work:
95 /// f.via(e).then(a).then(b);
97 /// a and b will execute in the same context (the far side of e), because
98 /// the Future (temporary variable) created by via(e) does not call back
99 /// until it destructs, which is after then(a) and then(b) have been wired
102 /// But this is still racy:
104 /// f = f.via(e).then(a);
106 // The ref-qualifier allows for `this` to be moved out so we
107 // don't get access-after-free situations in chaining.
108 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
109 inline Future<T> via(
111 int8_t priority = Executor::MID_PRI) &&;
113 /// This variant creates a new future, where the ref-qualifier && version
114 /// moves `this` out. This one is less efficient but avoids confusing users
115 /// when "return f.via(x);" fails.
116 inline Future<T> via(
118 int8_t priority = Executor::MID_PRI) &;
120 /** True when the result (or exception) is ready. */
121 bool isReady() const;
123 /// sugar for getTry().hasValue()
126 /// sugar for getTry().hasException()
129 /** A reference to the Try of the value */
132 /// If the promise has been fulfilled, return an Optional with the Try<T>.
133 /// Otherwise return an empty Optional.
134 /// Note that this moves the Try<T> out.
135 Optional<Try<T>> poll();
137 /// Block until the future is fulfilled. Returns the value (moved out), or
138 /// throws the exception. The future must not already have a callback.
141 /// Block until the future is fulfilled, or until timed out. Returns the
142 /// value (moved out), or throws the exception (which might be a TimedOut
146 /// Call e->drive() repeatedly until the future is fulfilled. Examples
147 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
148 /// value (moved out), or throws the exception.
149 T getVia(DrivableExecutor* e);
151 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
152 /// Future<T> instance.
153 template <class F = T>
154 typename std::enable_if<isFuture<F>::value,
155 Future<typename isFuture<T>::Inner>>::type
158 /** When this Future has completed, execute func which is a function that
168 Func shall return either another Future or a value.
170 A Future for the return type of func is returned.
172 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
174 The Future given to the functor is ready, and the functor may call
175 value(), which may rethrow if this has captured an exception. If func
176 throws, the exception will be captured in the Future that is returned.
178 // gcc 4.8 requires that we cast function reference types to function pointer
179 // types. Fore more details see the comment on FunctionReferenceToPointer
181 // gcc versions 4.9 and above (as well as clang) do not require this hack.
182 // For those, the FF tenplate parameter can be removed and occurences of FF
186 typename FF = typename detail::FunctionReferenceToPointer<F>::type,
187 typename R = detail::callableResult<T, FF>>
188 typename R::Return then(F&& func) {
189 typedef typename R::Arg Arguments;
190 return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
193 /// Variant where func is an member function
195 /// struct Worker { R doWork(Try<T>); }
198 /// Future<R> f2 = f1.then(&Worker::doWork, w);
200 /// This is just sugar for
202 /// f1.then(std::bind(&Worker::doWork, w));
203 template <typename R, typename Caller, typename... Args>
204 Future<typename isFuture<R>::Inner>
205 then(R(Caller::*func)(Args...), Caller *instance);
207 /// Execute the callback via the given Executor. The executor doesn't stick.
211 /// f.via(x).then(b).then(c)
215 /// f.then(x, b).then(c)
217 /// In the former both b and c execute via x. In the latter, only b executes
218 /// via x, and c executes via the same executor (if any) that f had.
219 template <class Executor, class Arg, class... Args>
220 auto then(Executor* x, Arg&& arg, Args&&... args)
221 -> decltype(this->then(std::forward<Arg>(arg),
222 std::forward<Args>(args)...));
224 /// Convenience method for ignoring the value and creating a Future<Unit>.
225 /// Exceptions still propagate.
228 /// Set an error callback for this Future. The callback should take a single
229 /// argument of the type that you want to catch, and should return a value of
230 /// the same type as this Future, or a Future of that type (see overload
231 /// below). For instance,
235 /// throw std::runtime_error("oh no!");
238 /// .onError([] (std::runtime_error& e) {
239 /// LOG(INFO) << "std::runtime_error: " << e.what();
240 /// return -1; // or makeFuture<int>(-1)
243 typename std::enable_if<
244 !detail::callableWith<F, exception_wrapper>::value &&
245 !detail::Extract<F>::ReturnsFuture::value,
249 /// Overload of onError where the error callback returns a Future<T>
251 typename std::enable_if<
252 !detail::callableWith<F, exception_wrapper>::value &&
253 detail::Extract<F>::ReturnsFuture::value,
257 /// Overload of onError that takes exception_wrapper and returns Future<T>
259 typename std::enable_if<
260 detail::callableWith<F, exception_wrapper>::value &&
261 detail::Extract<F>::ReturnsFuture::value,
265 /// Overload of onError that takes exception_wrapper and returns T
267 typename std::enable_if<
268 detail::callableWith<F, exception_wrapper>::value &&
269 !detail::Extract<F>::ReturnsFuture::value,
273 /// func is like std::function<void()> and is executed unconditionally, and
274 /// the value/exception is passed through to the resulting Future.
275 /// func shouldn't throw, but if it does it will be captured and propagated,
276 /// and discard any value/exception that this Future has obtained.
278 Future<T> ensure(F&& func);
280 /// Like onError, but for timeouts. example:
282 /// Future<int> f = makeFuture<int>(42)
283 /// .delayed(long_time)
284 /// .onTimeout(short_time,
285 /// []() -> int{ return -1; });
289 /// Future<int> f = makeFuture<int>(42)
290 /// .delayed(long_time)
291 /// .onTimeout(short_time,
292 /// []() { return makeFuture<int>(some_exception); });
294 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
296 /// This is not the method you're looking for.
298 /// This needs to be public because it's used by make* and when*, and it's
299 /// not worth listing all those and their fancy template signatures as
300 /// friends. But it's not for public consumption.
302 void setCallback_(F&& func);
304 /// A Future's callback is executed when all three of these conditions have
305 /// become true: it has a value (set by the Promise), it has a callback (set
306 /// by then), and it is active (active by default).
308 /// Inactive Futures will activate upon destruction.
309 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
313 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
317 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
319 return std::move(*this);
321 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
323 return std::move(*this);
327 return core_->isActive();
331 void raise(E&& exception) {
332 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
333 std::forward<E>(exception)));
336 /// Raise an interrupt. If the promise holder has an interrupt
337 /// handler it will be called and potentially stop asynchronous work from
338 /// being done. This is advisory only - a promise holder may not set an
339 /// interrupt handler, or may do anything including ignore. But, if you know
340 /// your future supports this the most likely result is stopping or
341 /// preventing the asynchronous operation (if in time), and the promise
342 /// holder setting an exception on the future. (That may happen
343 /// asynchronously, of course.)
344 void raise(exception_wrapper interrupt);
347 raise(FutureCancellation());
350 /// Throw TimedOut if this Future does not complete within the given
351 /// duration from now. The optional Timeekeeper is as with futures::sleep().
352 Future<T> within(Duration, Timekeeper* = nullptr);
354 /// Throw the given exception if this Future does not complete within the
355 /// given duration from now. The optional Timeekeeper is as with
356 /// futures::sleep().
358 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
360 /// Delay the completion of this Future for at least this duration from
361 /// now. The optional Timekeeper is as with futures::sleep().
362 Future<T> delayed(Duration, Timekeeper* = nullptr);
364 /// Block until this Future is complete. Returns a reference to this Future.
367 /// Overload of wait() for rvalue Futures
368 Future<T>&& wait() &&;
370 /// Block until this Future is complete or until the given Duration passes.
371 /// Returns a reference to this Future
372 Future<T>& wait(Duration) &;
374 /// Overload of wait(Duration) for rvalue Futures
375 Future<T>&& wait(Duration) &&;
377 /// Call e->drive() repeatedly until the future is fulfilled. Examples
378 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
379 /// reference to this Future so that you can chain calls if desired.
380 /// value (moved out), or throws the exception.
381 Future<T>& waitVia(DrivableExecutor* e) &;
383 /// Overload of waitVia() for rvalue Futures
384 Future<T>&& waitVia(DrivableExecutor* e) &&;
386 /// If the value in this Future is equal to the given Future, when they have
387 /// both completed, the value of the resulting Future<bool> will be true. It
388 /// will be false otherwise (including when one or both Futures have an
390 Future<bool> willEqual(Future<T>&);
392 /// predicate behaves like std::function<bool(T const&)>
393 /// If the predicate does not obtain with the value, the result
394 /// is a folly::PredicateDoesNotObtain exception
396 Future<T> filter(F&& predicate);
398 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
399 /// the result of collect or collectAll
400 template <class I, class F>
401 Future<I> reduce(I&& initial, F&& func);
403 /// Create a Future chain from a sequence of callbacks. i.e.
405 /// f.then(a).then(b).then(c)
407 /// where f is a Future<A> and the result of the chain is a Future<D>
410 /// f.thenMulti(a, b, c);
411 template <class Callback, class... Callbacks>
412 auto thenMulti(Callback&& fn, Callbacks&&... fns)
413 -> decltype(this->then(std::forward<Callback>(fn)).
414 thenMulti(std::forward<Callbacks>(fns)...));
416 // Nothing to see here, just thenMulti's base case
417 template <class Callback>
418 auto thenMulti(Callback&& fn)
419 -> decltype(this->then(std::forward<Callback>(fn)));
421 /// Create a Future chain from a sequence of callbacks. i.e.
423 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
425 /// where f is a Future<A> and the result of the chain is a Future<D>
428 /// f.thenMultiWithExecutor(executor, a, b, c);
429 template <class Callback, class... Callbacks>
430 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
431 -> decltype(this->then(std::forward<Callback>(fn)).
432 thenMulti(std::forward<Callbacks>(fns)...));
434 // Nothing to see here, just thenMultiWithExecutor's base case
435 template <class Callback>
436 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
437 -> decltype(this->then(std::forward<Callback>(fn)));
439 /// Discard a result, but propagate an exception.
440 Future<Unit> unit() {
441 return then([]{ return Unit{}; });
445 typedef detail::Core<T>* corePtr;
447 // shared core state object
451 Future(corePtr obj) : core_(obj) {}
455 void throwIfInvalid() const;
457 friend class Promise<T>;
458 template <class> friend class Future;
461 friend Future<T2> makeFuture(Try<T2>&&);
463 /// Repeat the given future (i.e., the computation it contains)
466 /// thunk behaves like std::function<Future<T2>(void)>
468 friend Future<Unit> times(int n, F&& thunk);
470 /// Carry out the computation contained in the given future if
471 /// the predicate holds.
473 /// thunk behaves like std::function<Future<T2>(void)>
475 friend Future<Unit> when(bool p, F&& thunk);
477 /// Carry out the computation contained in the given future if
478 /// while the predicate continues to hold.
480 /// thunk behaves like std::function<Future<T2>(void)>
482 /// predicate behaves like std::function<bool(void)>
483 template <class P, class F>
484 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
486 // Variant: returns a value
487 // e.g. f.then([](Try<T> t){ return t.value(); });
488 template <typename F, typename R, bool isTry, typename... Args>
489 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
490 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
492 // Variant: returns a Future
493 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
494 template <typename F, typename R, bool isTry, typename... Args>
495 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
496 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
498 Executor* getExecutor() { return core_->getExecutor(); }
499 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
500 core_->setExecutor(x, priority);
506 #include <folly/futures/Future-inl.h>