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;
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 /// Call e->drive() repeatedly until the future is fulfilled. Examples
133 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
134 /// reference to the Try of the value.
135 Try<T>& getTryVia(DrivableExecutor* e);
137 /// If the promise has been fulfilled, return an Optional with the Try<T>.
138 /// Otherwise return an empty Optional.
139 /// Note that this moves the Try<T> out.
140 Optional<Try<T>> poll();
142 /// Block until the future is fulfilled. Returns the value (moved out), or
143 /// throws the exception. The future must not already have a callback.
146 /// Block until the future is fulfilled, or until timed out. Returns the
147 /// value (moved out), or throws the exception (which might be a TimedOut
151 /// Call e->drive() repeatedly until the future is fulfilled. Examples
152 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
153 /// value (moved out), or throws the exception.
154 T getVia(DrivableExecutor* e);
156 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
157 /// Future<T> instance.
158 template <class F = T>
159 typename std::enable_if<isFuture<F>::value,
160 Future<typename isFuture<T>::Inner>>::type
163 /** When this Future has completed, execute func which is a function that
173 Func shall return either another Future or a value.
175 A Future for the return type of func is returned.
177 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
179 The Future given to the functor is ready, and the functor may call
180 value(), which may rethrow if this has captured an exception. If func
181 throws, the exception will be captured in the Future that is returned.
183 // gcc 4.8 requires that we cast function reference types to function pointer
184 // types. Fore more details see the comment on FunctionReferenceToPointer
186 // gcc versions 4.9 and above (as well as clang) do not require this hack.
187 // For those, the FF tenplate parameter can be removed and occurences of FF
191 typename FF = typename detail::FunctionReferenceToPointer<F>::type,
192 typename R = detail::callableResult<T, FF>>
193 typename R::Return then(F&& func) {
194 typedef typename R::Arg Arguments;
195 return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
198 /// Variant where func is an member function
200 /// struct Worker { R doWork(Try<T>); }
203 /// Future<R> f2 = f1.then(&Worker::doWork, w);
205 /// This is just sugar for
207 /// f1.then(std::bind(&Worker::doWork, w));
208 template <typename R, typename Caller, typename... Args>
209 Future<typename isFuture<R>::Inner>
210 then(R(Caller::*func)(Args...), Caller *instance);
212 /// Execute the callback via the given Executor. The executor doesn't stick.
216 /// f.via(x).then(b).then(c)
220 /// f.then(x, b).then(c)
222 /// In the former both b and c execute via x. In the latter, only b executes
223 /// via x, and c executes via the same executor (if any) that f had.
224 template <class Executor, class Arg, class... Args>
225 auto then(Executor* x, Arg&& arg, Args&&... args)
226 -> decltype(this->then(std::forward<Arg>(arg),
227 std::forward<Args>(args)...));
229 /// Convenience method for ignoring the value and creating a Future<Unit>.
230 /// Exceptions still propagate.
233 /// Set an error callback for this Future. The callback should take a single
234 /// argument of the type that you want to catch, and should return a value of
235 /// the same type as this Future, or a Future of that type (see overload
236 /// below). For instance,
240 /// throw std::runtime_error("oh no!");
243 /// .onError([] (std::runtime_error& e) {
244 /// LOG(INFO) << "std::runtime_error: " << e.what();
245 /// return -1; // or makeFuture<int>(-1)
248 typename std::enable_if<
249 !detail::callableWith<F, exception_wrapper>::value &&
250 !detail::Extract<F>::ReturnsFuture::value,
254 /// Overload of onError where the error callback returns a Future<T>
256 typename std::enable_if<
257 !detail::callableWith<F, exception_wrapper>::value &&
258 detail::Extract<F>::ReturnsFuture::value,
262 /// Overload of onError that takes exception_wrapper and returns Future<T>
264 typename std::enable_if<
265 detail::callableWith<F, exception_wrapper>::value &&
266 detail::Extract<F>::ReturnsFuture::value,
270 /// Overload of onError that takes exception_wrapper and returns T
272 typename std::enable_if<
273 detail::callableWith<F, exception_wrapper>::value &&
274 !detail::Extract<F>::ReturnsFuture::value,
278 /// func is like std::function<void()> and is executed unconditionally, and
279 /// the value/exception is passed through to the resulting Future.
280 /// func shouldn't throw, but if it does it will be captured and propagated,
281 /// and discard any value/exception that this Future has obtained.
283 Future<T> ensure(F&& func);
285 /// Like onError, but for timeouts. example:
287 /// Future<int> f = makeFuture<int>(42)
288 /// .delayed(long_time)
289 /// .onTimeout(short_time,
290 /// []() -> int{ return -1; });
294 /// Future<int> f = makeFuture<int>(42)
295 /// .delayed(long_time)
296 /// .onTimeout(short_time,
297 /// []() { return makeFuture<int>(some_exception); });
299 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
301 /// This is not the method you're looking for.
303 /// This needs to be public because it's used by make* and when*, and it's
304 /// not worth listing all those and their fancy template signatures as
305 /// friends. But it's not for public consumption.
307 void setCallback_(F&& func);
309 /// A Future's callback is executed when all three of these conditions have
310 /// become true: it has a value (set by the Promise), it has a callback (set
311 /// by then), and it is active (active by default).
313 /// Inactive Futures will activate upon destruction.
314 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
318 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
322 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
324 return std::move(*this);
326 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
328 return std::move(*this);
332 return core_->isActive();
336 void raise(E&& exception) {
337 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
338 std::forward<E>(exception)));
341 /// Raise an interrupt. If the promise holder has an interrupt
342 /// handler it will be called and potentially stop asynchronous work from
343 /// being done. This is advisory only - a promise holder may not set an
344 /// interrupt handler, or may do anything including ignore. But, if you know
345 /// your future supports this the most likely result is stopping or
346 /// preventing the asynchronous operation (if in time), and the promise
347 /// holder setting an exception on the future. (That may happen
348 /// asynchronously, of course.)
349 void raise(exception_wrapper interrupt);
352 raise(FutureCancellation());
355 /// Throw TimedOut if this Future does not complete within the given
356 /// duration from now. The optional Timeekeeper is as with futures::sleep().
357 Future<T> within(Duration, Timekeeper* = nullptr);
359 /// Throw the given exception if this Future does not complete within the
360 /// given duration from now. The optional Timeekeeper is as with
361 /// futures::sleep().
363 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
365 /// Delay the completion of this Future for at least this duration from
366 /// now. The optional Timekeeper is as with futures::sleep().
367 Future<T> delayed(Duration, Timekeeper* = nullptr);
369 /// Block until this Future is complete. Returns a reference to this Future.
372 /// Overload of wait() for rvalue Futures
373 Future<T>&& wait() &&;
375 /// Block until this Future is complete or until the given Duration passes.
376 /// Returns a reference to this Future
377 Future<T>& wait(Duration) &;
379 /// Overload of wait(Duration) for rvalue Futures
380 Future<T>&& wait(Duration) &&;
382 /// Call e->drive() repeatedly until the future is fulfilled. Examples
383 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
384 /// reference to this Future so that you can chain calls if desired.
385 /// value (moved out), or throws the exception.
386 Future<T>& waitVia(DrivableExecutor* e) &;
388 /// Overload of waitVia() for rvalue Futures
389 Future<T>&& waitVia(DrivableExecutor* e) &&;
391 /// If the value in this Future is equal to the given Future, when they have
392 /// both completed, the value of the resulting Future<bool> will be true. It
393 /// will be false otherwise (including when one or both Futures have an
395 Future<bool> willEqual(Future<T>&);
397 /// predicate behaves like std::function<bool(T const&)>
398 /// If the predicate does not obtain with the value, the result
399 /// is a folly::PredicateDoesNotObtain exception
401 Future<T> filter(F&& predicate);
403 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
404 /// the result of collect or collectAll
405 template <class I, class F>
406 Future<I> reduce(I&& initial, F&& func);
408 /// Create a Future chain from a sequence of callbacks. i.e.
410 /// f.then(a).then(b).then(c)
412 /// where f is a Future<A> and the result of the chain is a Future<D>
415 /// f.thenMulti(a, b, c);
416 template <class Callback, class... Callbacks>
417 auto thenMulti(Callback&& fn, Callbacks&&... fns)
418 -> decltype(this->then(std::forward<Callback>(fn)).
419 thenMulti(std::forward<Callbacks>(fns)...));
421 // Nothing to see here, just thenMulti's base case
422 template <class Callback>
423 auto thenMulti(Callback&& fn)
424 -> decltype(this->then(std::forward<Callback>(fn)));
426 /// Create a Future chain from a sequence of callbacks. i.e.
428 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
430 /// where f is a Future<A> and the result of the chain is a Future<D>
433 /// f.thenMultiWithExecutor(executor, a, b, c);
434 template <class Callback, class... Callbacks>
435 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
436 -> decltype(this->then(std::forward<Callback>(fn)).
437 thenMulti(std::forward<Callbacks>(fns)...));
439 // Nothing to see here, just thenMultiWithExecutor's base case
440 template <class Callback>
441 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
442 -> decltype(this->then(std::forward<Callback>(fn)));
444 /// Discard a result, but propagate an exception.
445 Future<Unit> unit() {
446 return then([]{ return Unit{}; });
450 typedef detail::Core<T>* corePtr;
452 // shared core state object
456 Future(corePtr obj) : core_(obj) {}
460 void throwIfInvalid() const;
462 friend class Promise<T>;
463 template <class> friend class Future;
466 friend Future<T2> makeFuture(Try<T2>&&);
468 /// Repeat the given future (i.e., the computation it contains)
471 /// thunk behaves like std::function<Future<T2>(void)>
473 friend Future<Unit> times(int n, F&& thunk);
475 /// Carry out the computation contained in the given future if
476 /// the predicate holds.
478 /// thunk behaves like std::function<Future<T2>(void)>
480 friend Future<Unit> when(bool p, F&& thunk);
482 /// Carry out the computation contained in the given future if
483 /// while the predicate continues to hold.
485 /// thunk behaves like std::function<Future<T2>(void)>
487 /// predicate behaves like std::function<bool(void)>
488 template <class P, class F>
489 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
491 // Variant: returns a value
492 // e.g. f.then([](Try<T> t){ return t.value(); });
493 template <typename F, typename R, bool isTry, typename... Args>
494 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
495 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
497 // Variant: returns a Future
498 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
499 template <typename F, typename R, bool isTry, typename... Args>
500 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
501 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
503 Executor* getExecutor() { return core_->getExecutor(); }
504 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
505 core_->setExecutor(x, priority);
511 #include <folly/futures/Future-inl.h>