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, typename =
64 typename std::enable_if<
65 std::is_same<Unit, T2>::value>::type>
70 /** Return the reference to result. Should not be called if !isReady().
71 Will rethrow the exception if an exception has been
74 typename std::add_lvalue_reference<T>::type
76 typename std::add_lvalue_reference<const T>::type
79 /// Returns an inactive Future which will call back on the other side of
80 /// executor (when it is activated).
82 /// NB remember that Futures activate when they destruct. This is good,
83 /// it means that this will work:
85 /// f.via(e).then(a).then(b);
87 /// a and b will execute in the same context (the far side of e), because
88 /// the Future (temporary variable) created by via(e) does not call back
89 /// until it destructs, which is after then(a) and then(b) have been wired
92 /// But this is still racy:
94 /// f = f.via(e).then(a);
96 // The ref-qualifier allows for `this` to be moved out so we
97 // don't get access-after-free situations in chaining.
98 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
101 int8_t priority = Executor::MID_PRI) &&;
103 /// This variant creates a new future, where the ref-qualifier && version
104 /// moves `this` out. This one is less efficient but avoids confusing users
105 /// when "return f.via(x);" fails.
106 inline Future<T> via(
108 int8_t priority = Executor::MID_PRI) &;
110 /** True when the result (or exception) is ready. */
111 bool isReady() const;
113 /// sugar for getTry().hasValue()
116 /// sugar for getTry().hasException()
119 /** A reference to the Try of the value */
122 /// If the promise has been fulfilled, return an Optional with the Try<T>.
123 /// Otherwise return an empty Optional.
124 /// Note that this moves the Try<T> out.
125 Optional<Try<T>> poll();
127 /// Block until the future is fulfilled. Returns the value (moved out), or
128 /// throws the exception. The future must not already have a callback.
131 /// Block until the future is fulfilled, or until timed out. Returns the
132 /// value (moved out), or throws the exception (which might be a TimedOut
136 /// Call e->drive() repeatedly until the future is fulfilled. Examples
137 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
138 /// value (moved out), or throws the exception.
139 T getVia(DrivableExecutor* e);
141 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
142 /// Future<T> instance.
143 template <class F = T>
144 typename std::enable_if<isFuture<F>::value,
145 Future<typename isFuture<T>::Inner>>::type
148 /** When this Future has completed, execute func which is a function that
158 Func shall return either another Future or a value.
160 A Future for the return type of func is returned.
162 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
164 The Future given to the functor is ready, and the functor may call
165 value(), which may rethrow if this has captured an exception. If func
166 throws, the exception will be captured in the Future that is returned.
168 template <typename F, typename R = detail::callableResult<T, F>>
169 typename R::Return then(F func) {
170 typedef typename R::Arg Arguments;
171 return thenImplementation<F, R>(std::move(func), Arguments());
174 /// Variant where func is an member function
176 /// struct Worker { R doWork(Try<T>); }
179 /// Future<R> f2 = f1.then(&Worker::doWork, w);
181 /// This is just sugar for
183 /// f1.then(std::bind(&Worker::doWork, w));
184 template <typename R, typename Caller, typename... Args>
185 Future<typename isFuture<R>::Inner>
186 then(R(Caller::*func)(Args...), Caller *instance);
188 /// Execute the callback via the given Executor. The executor doesn't stick.
192 /// f.via(x).then(b).then(c)
196 /// f.then(x, b).then(c)
198 /// In the former both b and c execute via x. In the latter, only b executes
199 /// via x, and c executes via the same executor (if any) that f had.
200 template <class Executor, class Arg, class... Args>
201 auto then(Executor* x, Arg&& arg, Args&&... args)
202 -> decltype(this->then(std::forward<Arg>(arg),
203 std::forward<Args>(args)...));
205 /// Convenience method for ignoring the value and creating a Future<Unit>.
206 /// Exceptions still propagate.
209 /// Set an error callback for this Future. The callback should take a single
210 /// argument of the type that you want to catch, and should return a value of
211 /// the same type as this Future, or a Future of that type (see overload
212 /// below). For instance,
216 /// throw std::runtime_error("oh no!");
219 /// .onError([] (std::runtime_error& e) {
220 /// LOG(INFO) << "std::runtime_error: " << e.what();
221 /// return -1; // or makeFuture<int>(-1)
224 typename std::enable_if<
225 !detail::callableWith<F, exception_wrapper>::value &&
226 !detail::Extract<F>::ReturnsFuture::value,
230 /// Overload of onError where the error callback returns a Future<T>
232 typename std::enable_if<
233 !detail::callableWith<F, exception_wrapper>::value &&
234 detail::Extract<F>::ReturnsFuture::value,
238 /// Overload of onError that takes exception_wrapper and returns Future<T>
240 typename std::enable_if<
241 detail::callableWith<F, exception_wrapper>::value &&
242 detail::Extract<F>::ReturnsFuture::value,
246 /// Overload of onError that takes exception_wrapper and returns T
248 typename std::enable_if<
249 detail::callableWith<F, exception_wrapper>::value &&
250 !detail::Extract<F>::ReturnsFuture::value,
254 /// func is like std::function<void()> and is executed unconditionally, and
255 /// the value/exception is passed through to the resulting Future.
256 /// func shouldn't throw, but if it does it will be captured and propagated,
257 /// and discard any value/exception that this Future has obtained.
259 Future<T> ensure(F func);
261 /// Like onError, but for timeouts. example:
263 /// Future<int> f = makeFuture<int>(42)
264 /// .delayed(long_time)
265 /// .onTimeout(short_time,
266 /// []() -> int{ return -1; });
270 /// Future<int> f = makeFuture<int>(42)
271 /// .delayed(long_time)
272 /// .onTimeout(short_time,
273 /// []() { return makeFuture<int>(some_exception); });
275 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
277 /// This is not the method you're looking for.
279 /// This needs to be public because it's used by make* and when*, and it's
280 /// not worth listing all those and their fancy template signatures as
281 /// friends. But it's not for public consumption.
283 void setCallback_(F&& func);
285 /// A Future's callback is executed when all three of these conditions have
286 /// become true: it has a value (set by the Promise), it has a callback (set
287 /// by then), and it is active (active by default).
289 /// Inactive Futures will activate upon destruction.
290 Future<T>& activate() & DEPRECATED {
294 Future<T>& deactivate() & DEPRECATED {
298 Future<T> activate() && DEPRECATED {
300 return std::move(*this);
302 Future<T> deactivate() && DEPRECATED {
304 return std::move(*this);
308 return core_->isActive();
312 void raise(E&& exception) {
313 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
314 std::move(exception)));
317 /// Raise an interrupt. If the promise holder has an interrupt
318 /// handler it will be called and potentially stop asynchronous work from
319 /// being done. This is advisory only - a promise holder may not set an
320 /// interrupt handler, or may do anything including ignore. But, if you know
321 /// your future supports this the most likely result is stopping or
322 /// preventing the asynchronous operation (if in time), and the promise
323 /// holder setting an exception on the future. (That may happen
324 /// asynchronously, of course.)
325 void raise(exception_wrapper interrupt);
328 raise(FutureCancellation());
331 /// Throw TimedOut if this Future does not complete within the given
332 /// duration from now. The optional Timeekeeper is as with futures::sleep().
333 Future<T> within(Duration, Timekeeper* = nullptr);
335 /// Throw the given exception if this Future does not complete within the
336 /// given duration from now. The optional Timeekeeper is as with
337 /// futures::sleep().
339 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
341 /// Delay the completion of this Future for at least this duration from
342 /// now. The optional Timekeeper is as with futures::sleep().
343 Future<T> delayed(Duration, Timekeeper* = nullptr);
345 /// Block until this Future is complete. Returns a reference to this Future.
348 /// Overload of wait() for rvalue Futures
349 Future<T>&& wait() &&;
351 /// Block until this Future is complete or until the given Duration passes.
352 /// Returns a reference to this Future
353 Future<T>& wait(Duration) &;
355 /// Overload of wait(Duration) for rvalue Futures
356 Future<T>&& wait(Duration) &&;
358 /// Call e->drive() repeatedly until the future is fulfilled. Examples
359 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
360 /// reference to this Future so that you can chain calls if desired.
361 /// value (moved out), or throws the exception.
362 Future<T>& waitVia(DrivableExecutor* e) &;
364 /// Overload of waitVia() for rvalue Futures
365 Future<T>&& waitVia(DrivableExecutor* e) &&;
367 /// If the value in this Future is equal to the given Future, when they have
368 /// both completed, the value of the resulting Future<bool> will be true. It
369 /// will be false otherwise (including when one or both Futures have an
371 Future<bool> willEqual(Future<T>&);
373 /// predicate behaves like std::function<bool(T const&)>
374 /// If the predicate does not obtain with the value, the result
375 /// is a folly::PredicateDoesNotObtain exception
377 Future<T> filter(F predicate);
379 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
380 /// the result of collect or collectAll
381 template <class I, class F>
382 Future<I> reduce(I&& initial, F&& func);
384 /// Create a Future chain from a sequence of callbacks. i.e.
386 /// f.then(a).then(b).then(c)
388 /// where f is a Future<A> and the result of the chain is a Future<D>
391 /// f.thenMulti(a, b, c);
392 template <class Callback, class... Callbacks>
393 auto thenMulti(Callback&& fn, Callbacks&&... fns)
394 -> decltype(this->then(std::forward<Callback>(fn)).
395 thenMulti(std::forward<Callbacks>(fns)...));
397 // Nothing to see here, just thenMulti's base case
398 template <class Callback>
399 auto thenMulti(Callback&& fn)
400 -> decltype(this->then(std::forward<Callback>(fn)));
402 /// Create a Future chain from a sequence of callbacks. i.e.
404 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
406 /// where f is a Future<A> and the result of the chain is a Future<D>
409 /// f.thenMultiWithExecutor(executor, a, b, c);
410 template <class Callback, class... Callbacks>
411 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
412 -> decltype(this->then(std::forward<Callback>(fn)).
413 thenMulti(std::forward<Callbacks>(fns)...));
415 // Nothing to see here, just thenMultiWithExecutor's base case
416 template <class Callback>
417 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
418 -> decltype(this->then(std::forward<Callback>(fn)));
420 /// Discard a result, but propagate an exception.
421 Future<Unit> unit() {
422 return then([]{ return Unit{}; });
426 typedef detail::Core<T>* corePtr;
428 // shared core state object
432 Future(corePtr obj) : core_(obj) {}
436 void throwIfInvalid() const;
438 friend class Promise<T>;
439 template <class> friend class Future;
442 friend Future<T2> makeFuture(Try<T2>&&);
444 // Variant: returns a value
445 // e.g. f.then([](Try<T> t){ return t.value(); });
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 // Variant: returns a Future
451 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
452 template <typename F, typename R, bool isTry, typename... Args>
453 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
454 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
456 Executor* getExecutor() { return core_->getExecutor(); }
457 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
458 core_->setExecutor(x, priority);
464 #include <folly/futures/Future-inl.h>