2 * Copyright 2015 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/MoveWrapper.h>
28 #include <folly/futures/Deprecated.h>
29 #include <folly/futures/DrivableExecutor.h>
30 #include <folly/futures/Promise.h>
31 #include <folly/futures/Try.h>
32 #include <folly/futures/FutureException.h>
33 #include <folly/futures/detail/Types.h>
35 // boring predeclarations and details
36 #include <folly/futures/Future-pre.h>
38 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
39 // Needs to be included after Future-pre.h and before Future-inl.h
40 #include <folly/futures/helpers.h>
50 Future(Future const&) = delete;
51 Future& operator=(Future const&) = delete;
54 Future(Future&&) noexcept;
55 Future& operator=(Future&&) noexcept;
57 /// Construct a Future from a value (perfect forwarding)
58 template <class T2 = T, typename =
59 typename std::enable_if<
60 !isFuture<typename std::decay<T2>::type>::value>::type>
61 /* implicit */ Future(T2&& val);
63 template <class T2 = T,
64 typename std::enable_if<
65 folly::is_void_or_unit<T2>::value,
71 /** Return the reference to result. Should not be called if !isReady().
72 Will rethrow the exception if an exception has been
75 typename std::add_lvalue_reference<T>::type
77 typename std::add_lvalue_reference<const T>::type
80 /// Returns an inactive Future which will call back on the other side of
81 /// executor (when it is activated).
83 /// NB remember that Futures activate when they destruct. This is good,
84 /// it means that this will work:
86 /// f.via(e).then(a).then(b);
88 /// a and b will execute in the same context (the far side of e), because
89 /// the Future (temporary variable) created by via(e) does not call back
90 /// until it destructs, which is after then(a) and then(b) have been wired
93 /// But this is still racy:
95 /// f = f.via(e).then(a);
97 // The ref-qualifier allows for `this` to be moved out so we
98 // don't get access-after-free situations in chaining.
99 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
100 inline Future<T> via(
102 int8_t priority = Executor::MID_PRI) &&;
104 /// This variant creates a new future, where the ref-qualifier && version
105 /// moves `this` out. This one is less efficient but avoids confusing users
106 /// when "return f.via(x);" fails.
107 inline Future<T> via(
109 int8_t priority = Executor::MID_PRI) &;
111 /** True when the result (or exception) is ready. */
112 bool isReady() const;
114 /** A reference to the Try of the value */
117 /// If the promise has been fulfilled, return an Optional with the Try<T>.
118 /// Otherwise return an empty Optional.
119 /// Note that this moves the Try<T> out.
120 Optional<Try<T>> poll();
122 /// Block until the future is fulfilled. Returns the value (moved out), or
123 /// throws the exception. The future must not already have a callback.
126 /// Block until the future is fulfilled, or until timed out. Returns the
127 /// value (moved out), or throws the exception (which might be a TimedOut
131 /// Call e->drive() repeatedly until the future is fulfilled. Examples
132 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
133 /// value (moved out), or throws the exception.
134 T getVia(DrivableExecutor* e);
136 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
137 /// Future<T> instance.
138 template <class F = T>
139 typename std::enable_if<isFuture<F>::value,
140 Future<typename isFuture<T>::Inner>>::type
143 /** When this Future has completed, execute func which is a function that
153 Func shall return either another Future or a value.
155 A Future for the return type of func is returned.
157 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
159 The Future given to the functor is ready, and the functor may call
160 value(), which may rethrow if this has captured an exception. If func
161 throws, the exception will be captured in the Future that is returned.
163 /* TODO n3428 and other async frameworks have something like then(scheduler,
164 Future), we might want to support a similar API which could be
165 implemented a little more efficiently than
166 f.via(executor).then(callback) */
167 template <typename F, typename R = detail::callableResult<T, F>>
168 typename R::Return then(F func) {
169 typedef typename R::Arg Arguments;
170 return thenImplementation<F, R>(std::move(func), Arguments());
173 /// Variant where func is an member function
175 /// struct Worker { R doWork(Try<T>); }
178 /// Future<R> f2 = f1.then(&Worker::doWork, w);
180 /// This is just sugar for
182 /// f1.then(std::bind(&Worker::doWork, w));
183 template <typename R, typename Caller, typename... Args>
184 Future<typename isFuture<R>::Inner>
185 then(R(Caller::*func)(Args...), Caller *instance);
187 /// Execute the callback via the given Executor. The executor doesn't stick.
191 /// f.via(x).then(b).then(c)
195 /// f.then(x, b).then(c)
197 /// In the former both b and c execute via x. In the latter, only b executes
198 /// via x, and c executes via the same executor (if any) that f had.
199 template <class Executor, class Arg, class... Args>
200 auto then(Executor* x, Arg&& arg, Args&&... args)
201 -> decltype(this->then(std::forward<Arg>(arg),
202 std::forward<Args>(args)...));
204 /// Convenience method for ignoring the value and creating a Future<void>.
205 /// Exceptions still propagate.
208 /// Set an error callback for this Future. The callback should take a single
209 /// argument of the type that you want to catch, and should return a value of
210 /// the same type as this Future, or a Future of that type (see overload
211 /// below). For instance,
215 /// throw std::runtime_error("oh no!");
218 /// .onError([] (std::runtime_error& e) {
219 /// LOG(INFO) << "std::runtime_error: " << e.what();
220 /// return -1; // or makeFuture<int>(-1)
223 typename std::enable_if<
224 !detail::callableWith<F, exception_wrapper>::value &&
225 !detail::Extract<F>::ReturnsFuture::value,
229 /// Overload of onError where the error callback returns a Future<T>
231 typename std::enable_if<
232 !detail::callableWith<F, exception_wrapper>::value &&
233 detail::Extract<F>::ReturnsFuture::value,
237 /// Overload of onError that takes exception_wrapper and returns Future<T>
239 typename std::enable_if<
240 detail::callableWith<F, exception_wrapper>::value &&
241 detail::Extract<F>::ReturnsFuture::value,
245 /// Overload of onError that takes exception_wrapper and returns T
247 typename std::enable_if<
248 detail::callableWith<F, exception_wrapper>::value &&
249 !detail::Extract<F>::ReturnsFuture::value,
253 /// func is like std::function<void()> and is executed unconditionally, and
254 /// the value/exception is passed through to the resulting Future.
255 /// func shouldn't throw, but if it does it will be captured and propagated,
256 /// and discard any value/exception that this Future has obtained.
258 Future<T> ensure(F func);
260 /// Like onError, but for timeouts. example:
262 /// Future<int> f = makeFuture<int>(42)
263 /// .delayed(long_time)
264 /// .onTimeout(short_time,
265 /// []() -> int{ return -1; });
269 /// Future<int> f = makeFuture<int>(42)
270 /// .delayed(long_time)
271 /// .onTimeout(short_time,
272 /// []() { return makeFuture<int>(some_exception); });
274 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
276 /// This is not the method you're looking for.
278 /// This needs to be public because it's used by make* and when*, and it's
279 /// not worth listing all those and their fancy template signatures as
280 /// friends. But it's not for public consumption.
282 void setCallback_(F&& func);
284 /// A Future's callback is executed when all three of these conditions have
285 /// become true: it has a value (set by the Promise), it has a callback (set
286 /// by then), and it is active (active by default).
288 /// Inactive Futures will activate upon destruction.
289 Future<T>& activate() & DEPRECATED {
293 Future<T>& deactivate() & DEPRECATED {
297 Future<T> activate() && DEPRECATED {
299 return std::move(*this);
301 Future<T> deactivate() && DEPRECATED {
303 return std::move(*this);
307 return core_->isActive();
311 void raise(E&& exception) {
312 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
313 std::move(exception)));
316 /// Raise an interrupt. If the promise holder has an interrupt
317 /// handler it will be called and potentially stop asynchronous work from
318 /// being done. This is advisory only - a promise holder may not set an
319 /// interrupt handler, or may do anything including ignore. But, if you know
320 /// your future supports this the most likely result is stopping or
321 /// preventing the asynchronous operation (if in time), and the promise
322 /// holder setting an exception on the future. (That may happen
323 /// asynchronously, of course.)
324 void raise(exception_wrapper interrupt);
327 raise(FutureCancellation());
330 /// Throw TimedOut if this Future does not complete within the given
331 /// duration from now. The optional Timeekeeper is as with futures::sleep().
332 Future<T> within(Duration, Timekeeper* = nullptr);
334 /// Throw the given exception if this Future does not complete within the
335 /// given duration from now. The optional Timeekeeper is as with
336 /// futures::sleep().
338 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
340 /// Delay the completion of this Future for at least this duration from
341 /// now. The optional Timekeeper is as with futures::sleep().
342 Future<T> delayed(Duration, Timekeeper* = nullptr);
344 /// Block until this Future is complete. Returns a reference to this Future.
347 /// Overload of wait() for rvalue Futures
348 Future<T>&& wait() &&;
350 /// Block until this Future is complete or until the given Duration passes.
351 /// Returns a reference to this Future
352 Future<T>& wait(Duration) &;
354 /// Overload of wait(Duration) for rvalue Futures
355 Future<T>&& wait(Duration) &&;
357 /// Call e->drive() repeatedly until the future is fulfilled. Examples
358 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
359 /// reference to this Future so that you can chain calls if desired.
360 /// value (moved out), or throws the exception.
361 Future<T>& waitVia(DrivableExecutor* e) &;
363 /// Overload of waitVia() for rvalue Futures
364 Future<T>&& waitVia(DrivableExecutor* e) &&;
366 /// If the value in this Future is equal to the given Future, when they have
367 /// both completed, the value of the resulting Future<bool> will be true. It
368 /// will be false otherwise (including when one or both Futures have an
370 Future<bool> willEqual(Future<T>&);
372 /// predicate behaves like std::function<bool(T const&)>
373 /// If the predicate does not obtain with the value, the result
374 /// is a folly::PredicateDoesNotObtain exception
376 Future<T> filter(F predicate);
378 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
379 /// the result of collect or collectAll
380 template <class I, class F>
381 Future<I> reduce(I&& initial, F&& func);
383 /// Create a Future chain from a sequence of callbacks. i.e.
385 /// f.then(a).then(b).then(c)
387 /// where f is a Future<A> and the result of the chain is a Future<D>
390 /// f.thenMulti(a, b, c);
391 template <class Callback, class... Callbacks>
392 auto thenMulti(Callback&& fn, Callbacks&&... fns)
393 -> decltype(this->then(std::forward<Callback>(fn)).
394 thenMulti(std::forward<Callbacks>(fns)...));
396 // Nothing to see here, just thenMulti's base case
397 template <class Callback>
398 auto thenMulti(Callback&& fn)
399 -> decltype(this->then(std::forward<Callback>(fn)));
401 /// Create a Future chain from a sequence of callbacks. i.e.
403 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
405 /// where f is a Future<A> and the result of the chain is a Future<D>
408 /// f.thenMultiWithExecutor(executor, a, b, c);
409 template <class Callback, class... Callbacks>
410 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
411 -> decltype(this->then(std::forward<Callback>(fn)).
412 thenMulti(std::forward<Callbacks>(fns)...));
414 // Nothing to see here, just thenMultiWithExecutor's base case
415 template <class Callback>
416 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
417 -> decltype(this->then(std::forward<Callback>(fn)));
420 typedef detail::Core<T>* corePtr;
422 // shared core state object
426 Future(corePtr obj) : core_(obj) {}
430 void throwIfInvalid() const;
432 friend class Promise<T>;
433 template <class> friend class Future;
436 friend Future<T2> makeFuture(Try<T2>&&);
438 // Variant: returns a value
439 // e.g. f.then([](Try<T> t){ return t.value(); });
440 template <typename F, typename R, bool isTry, typename... Args>
441 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
442 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
444 // Variant: returns a Future
445 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
446 template <typename F, typename R, bool isTry, typename... Args>
447 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
448 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
450 Executor* getExecutor() { return core_->getExecutor(); }
451 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
452 core_->setExecutor(x, priority);
458 #include <folly/futures/Future-inl.h>