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 /// Construct a Future from a value (perfect forwarding)
57 template <class T2 = T, typename =
58 typename std::enable_if<
59 !isFuture<typename std::decay<T2>::type>::value>::type>
60 /* implicit */ Future(T2&& val);
62 template <class T2 = T>
63 /* implicit */ Future(
64 typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
68 /** Return the reference to result. Should not be called if !isReady().
69 Will rethrow the exception if an exception has been
72 typename std::add_lvalue_reference<T>::type
74 typename std::add_lvalue_reference<const T>::type
77 /// Returns an inactive Future which will call back on the other side of
78 /// executor (when it is activated).
80 /// NB remember that Futures activate when they destruct. This is good,
81 /// it means that this will work:
83 /// f.via(e).then(a).then(b);
85 /// a and b will execute in the same context (the far side of e), because
86 /// the Future (temporary variable) created by via(e) does not call back
87 /// until it destructs, which is after then(a) and then(b) have been wired
90 /// But this is still racy:
92 /// f = f.via(e).then(a);
94 // The ref-qualifier allows for `this` to be moved out so we
95 // don't get access-after-free situations in chaining.
96 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
99 int8_t priority = Executor::MID_PRI) &&;
101 /// This variant creates a new future, where the ref-qualifier && version
102 /// moves `this` out. This one is less efficient but avoids confusing users
103 /// when "return f.via(x);" fails.
104 inline Future<T> via(
106 int8_t priority = Executor::MID_PRI) &;
108 /** True when the result (or exception) is ready. */
109 bool isReady() const;
111 /// sugar for getTry().hasValue()
114 /// sugar for getTry().hasException()
117 /** A reference to the Try of the value */
120 /// Call e->drive() repeatedly until the future is fulfilled. Examples
121 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
122 /// reference to the Try of the value.
123 Try<T>& getTryVia(DrivableExecutor* e);
125 /// If the promise has been fulfilled, return an Optional with the Try<T>.
126 /// Otherwise return an empty Optional.
127 /// Note that this moves the Try<T> out.
128 Optional<Try<T>> poll();
130 /// Block until the future is fulfilled. Returns the value (moved out), or
131 /// throws the exception. The future must not already have a callback.
134 /// Block until the future is fulfilled, or until timed out. Returns the
135 /// value (moved out), or throws the exception (which might be a TimedOut
139 /// Call e->drive() repeatedly until the future is fulfilled. Examples
140 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
141 /// value (moved out), or throws the exception.
142 T getVia(DrivableExecutor* e);
144 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
145 /// Future<T> instance.
146 template <class F = T>
147 typename std::enable_if<isFuture<F>::value,
148 Future<typename isFuture<T>::Inner>>::type
151 /** When this Future has completed, execute func which is a function that
161 Func shall return either another Future or a value.
163 A Future for the return type of func is returned.
165 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
167 The Future given to the functor is ready, and the functor may call
168 value(), which may rethrow if this has captured an exception. If func
169 throws, the exception will be captured in the Future that is returned.
171 // gcc 4.8 requires that we cast function reference types to function pointer
172 // types. Fore more details see the comment on FunctionReferenceToPointer
174 // gcc versions 4.9 and above (as well as clang) do not require this hack.
175 // For those, the FF tenplate parameter can be removed and occurences of FF
179 typename FF = typename detail::FunctionReferenceToPointer<F>::type,
180 typename R = detail::callableResult<T, FF>>
181 typename R::Return then(F&& func) {
182 typedef typename R::Arg Arguments;
183 return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
186 /// Variant where func is an member function
188 /// struct Worker { R doWork(Try<T>); }
191 /// Future<R> f2 = f1.then(&Worker::doWork, w);
193 /// This is just sugar for
195 /// f1.then(std::bind(&Worker::doWork, w));
196 template <typename R, typename Caller, typename... Args>
197 Future<typename isFuture<R>::Inner>
198 then(R(Caller::*func)(Args...), Caller *instance);
200 /// Execute the callback via the given Executor. The executor doesn't stick.
204 /// f.via(x).then(b).then(c)
208 /// f.then(x, b).then(c)
210 /// In the former both b and c execute via x. In the latter, only b executes
211 /// via x, and c executes via the same executor (if any) that f had.
212 template <class Executor, class Arg, class... Args>
213 auto then(Executor* x, Arg&& arg, Args&&... args)
214 -> decltype(this->then(std::forward<Arg>(arg),
215 std::forward<Args>(args)...));
217 /// Convenience method for ignoring the value and creating a Future<Unit>.
218 /// Exceptions still propagate.
221 /// Set an error callback for this Future. The callback should take a single
222 /// argument of the type that you want to catch, and should return a value of
223 /// the same type as this Future, or a Future of that type (see overload
224 /// below). For instance,
228 /// throw std::runtime_error("oh no!");
231 /// .onError([] (std::runtime_error& e) {
232 /// LOG(INFO) << "std::runtime_error: " << e.what();
233 /// return -1; // or makeFuture<int>(-1)
236 typename std::enable_if<
237 !detail::callableWith<F, exception_wrapper>::value &&
238 !detail::Extract<F>::ReturnsFuture::value,
242 /// Overload of onError where the error callback returns a Future<T>
244 typename std::enable_if<
245 !detail::callableWith<F, exception_wrapper>::value &&
246 detail::Extract<F>::ReturnsFuture::value,
250 /// Overload of onError that takes exception_wrapper and returns 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 T
260 typename std::enable_if<
261 detail::callableWith<F, exception_wrapper>::value &&
262 !detail::Extract<F>::ReturnsFuture::value,
266 /// func is like std::function<void()> and is executed unconditionally, and
267 /// the value/exception is passed through to the resulting Future.
268 /// func shouldn't throw, but if it does it will be captured and propagated,
269 /// and discard any value/exception that this Future has obtained.
271 Future<T> ensure(F&& func);
273 /// Like onError, but for timeouts. example:
275 /// Future<int> f = makeFuture<int>(42)
276 /// .delayed(long_time)
277 /// .onTimeout(short_time,
278 /// []() -> int{ return -1; });
282 /// Future<int> f = makeFuture<int>(42)
283 /// .delayed(long_time)
284 /// .onTimeout(short_time,
285 /// []() { return makeFuture<int>(some_exception); });
287 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
289 /// This is not the method you're looking for.
291 /// This needs to be public because it's used by make* and when*, and it's
292 /// not worth listing all those and their fancy template signatures as
293 /// friends. But it's not for public consumption.
295 void setCallback_(F&& func);
297 /// A Future's callback is executed when all three of these conditions have
298 /// become true: it has a value (set by the Promise), it has a callback (set
299 /// by then), and it is active (active by default).
301 /// Inactive Futures will activate upon destruction.
302 FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
306 FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
310 FOLLY_DEPRECATED("do not use") Future<T> activate() && {
312 return std::move(*this);
314 FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
316 return std::move(*this);
320 return core_->isActive();
324 void raise(E&& exception) {
325 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
326 std::forward<E>(exception)));
329 /// Raise an interrupt. If the promise holder has an interrupt
330 /// handler it will be called and potentially stop asynchronous work from
331 /// being done. This is advisory only - a promise holder may not set an
332 /// interrupt handler, or may do anything including ignore. But, if you know
333 /// your future supports this the most likely result is stopping or
334 /// preventing the asynchronous operation (if in time), and the promise
335 /// holder setting an exception on the future. (That may happen
336 /// asynchronously, of course.)
337 void raise(exception_wrapper interrupt);
340 raise(FutureCancellation());
343 /// Throw TimedOut if this Future does not complete within the given
344 /// duration from now. The optional Timeekeeper is as with futures::sleep().
345 Future<T> within(Duration, Timekeeper* = nullptr);
347 /// Throw the given exception if this Future does not complete within the
348 /// given duration from now. The optional Timeekeeper is as with
349 /// futures::sleep().
351 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
353 /// Delay the completion of this Future for at least this duration from
354 /// now. The optional Timekeeper is as with futures::sleep().
355 Future<T> delayed(Duration, Timekeeper* = nullptr);
357 /// Block until this Future is complete. Returns a reference to this Future.
360 /// Overload of wait() for rvalue Futures
361 Future<T>&& wait() &&;
363 /// Block until this Future is complete or until the given Duration passes.
364 /// Returns a reference to this Future
365 Future<T>& wait(Duration) &;
367 /// Overload of wait(Duration) for rvalue Futures
368 Future<T>&& wait(Duration) &&;
370 /// Call e->drive() repeatedly until the future is fulfilled. Examples
371 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
372 /// reference to this Future so that you can chain calls if desired.
373 /// value (moved out), or throws the exception.
374 Future<T>& waitVia(DrivableExecutor* e) &;
376 /// Overload of waitVia() for rvalue Futures
377 Future<T>&& waitVia(DrivableExecutor* e) &&;
379 /// If the value in this Future is equal to the given Future, when they have
380 /// both completed, the value of the resulting Future<bool> will be true. It
381 /// will be false otherwise (including when one or both Futures have an
383 Future<bool> willEqual(Future<T>&);
385 /// predicate behaves like std::function<bool(T const&)>
386 /// If the predicate does not obtain with the value, the result
387 /// is a folly::PredicateDoesNotObtain exception
389 Future<T> filter(F&& predicate);
391 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
392 /// the result of collect or collectAll
393 template <class I, class F>
394 Future<I> reduce(I&& initial, F&& func);
396 /// Create a Future chain from a sequence of callbacks. i.e.
398 /// f.then(a).then(b).then(c)
400 /// where f is a Future<A> and the result of the chain is a Future<D>
403 /// f.thenMulti(a, b, c);
404 template <class Callback, class... Callbacks>
405 auto thenMulti(Callback&& fn, Callbacks&&... fns)
406 -> decltype(this->then(std::forward<Callback>(fn)).
407 thenMulti(std::forward<Callbacks>(fns)...));
409 // Nothing to see here, just thenMulti's base case
410 template <class Callback>
411 auto thenMulti(Callback&& fn)
412 -> decltype(this->then(std::forward<Callback>(fn)));
414 /// Create a Future chain from a sequence of callbacks. i.e.
416 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
418 /// where f is a Future<A> and the result of the chain is a Future<D>
421 /// f.thenMultiWithExecutor(executor, a, b, c);
422 template <class Callback, class... Callbacks>
423 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
424 -> decltype(this->then(std::forward<Callback>(fn)).
425 thenMulti(std::forward<Callbacks>(fns)...));
427 // Nothing to see here, just thenMultiWithExecutor's base case
428 template <class Callback>
429 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
430 -> decltype(this->then(std::forward<Callback>(fn)));
432 /// Discard a result, but propagate an exception.
433 Future<Unit> unit() {
434 return then([]{ return Unit{}; });
438 typedef detail::Core<T>* corePtr;
440 // shared core state object
444 Future(corePtr obj) : core_(obj) {}
448 void throwIfInvalid() const;
450 friend class Promise<T>;
451 template <class> friend class Future;
454 friend Future<T2> makeFuture(Try<T2>&&);
456 /// Repeat the given future (i.e., the computation it contains)
459 /// thunk behaves like std::function<Future<T2>(void)>
461 friend Future<Unit> times(int n, F&& thunk);
463 /// Carry out the computation contained in the given future if
464 /// the predicate holds.
466 /// thunk behaves like std::function<Future<T2>(void)>
468 friend Future<Unit> when(bool p, F&& thunk);
470 /// Carry out the computation contained in the given future if
471 /// while the predicate continues to hold.
473 /// thunk behaves like std::function<Future<T2>(void)>
475 /// predicate behaves like std::function<bool(void)>
476 template <class P, class F>
477 friend Future<Unit> whileDo(P&& predicate, F&& thunk);
479 // Variant: returns a value
480 // e.g. f.then([](Try<T> t){ return t.value(); });
481 template <typename F, typename R, bool isTry, typename... Args>
482 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
483 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
485 // Variant: returns a Future
486 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
487 template <typename F, typename R, bool isTry, typename... Args>
488 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
489 thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
491 Executor* getExecutor() { return core_->getExecutor(); }
492 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
493 core_->setExecutor(x, priority);
499 #include <folly/futures/Future-inl.h>