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 folly::is_void_or_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 /* TODO n3428 and other async frameworks have something like then(scheduler,
169 Future), we might want to support a similar API which could be
170 implemented a little more efficiently than
171 f.via(executor).then(callback) */
172 template <typename F, typename R = detail::callableResult<T, F>>
173 typename R::Return then(F func) {
174 typedef typename R::Arg Arguments;
175 return thenImplementation<F, R>(std::move(func), Arguments());
178 /// Variant where func is an member function
180 /// struct Worker { R doWork(Try<T>); }
183 /// Future<R> f2 = f1.then(&Worker::doWork, w);
185 /// This is just sugar for
187 /// f1.then(std::bind(&Worker::doWork, w));
188 template <typename R, typename Caller, typename... Args>
189 Future<typename isFuture<R>::Inner>
190 then(R(Caller::*func)(Args...), Caller *instance);
192 /// Execute the callback via the given Executor. The executor doesn't stick.
196 /// f.via(x).then(b).then(c)
200 /// f.then(x, b).then(c)
202 /// In the former both b and c execute via x. In the latter, only b executes
203 /// via x, and c executes via the same executor (if any) that f had.
204 template <class Executor, class Arg, class... Args>
205 auto then(Executor* x, Arg&& arg, Args&&... args)
206 -> decltype(this->then(std::forward<Arg>(arg),
207 std::forward<Args>(args)...));
209 /// Convenience method for ignoring the value and creating a Future<void>.
210 /// Exceptions still propagate.
213 /// Set an error callback for this Future. The callback should take a single
214 /// argument of the type that you want to catch, and should return a value of
215 /// the same type as this Future, or a Future of that type (see overload
216 /// below). For instance,
220 /// throw std::runtime_error("oh no!");
223 /// .onError([] (std::runtime_error& e) {
224 /// LOG(INFO) << "std::runtime_error: " << e.what();
225 /// return -1; // or makeFuture<int>(-1)
228 typename std::enable_if<
229 !detail::callableWith<F, exception_wrapper>::value &&
230 !detail::Extract<F>::ReturnsFuture::value,
234 /// Overload of onError where the error callback returns a Future<T>
236 typename std::enable_if<
237 !detail::callableWith<F, exception_wrapper>::value &&
238 detail::Extract<F>::ReturnsFuture::value,
242 /// Overload of onError that takes exception_wrapper and returns 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 T
252 typename std::enable_if<
253 detail::callableWith<F, exception_wrapper>::value &&
254 !detail::Extract<F>::ReturnsFuture::value,
258 /// func is like std::function<void()> and is executed unconditionally, and
259 /// the value/exception is passed through to the resulting Future.
260 /// func shouldn't throw, but if it does it will be captured and propagated,
261 /// and discard any value/exception that this Future has obtained.
263 Future<T> ensure(F func);
265 /// Like onError, but for timeouts. example:
267 /// Future<int> f = makeFuture<int>(42)
268 /// .delayed(long_time)
269 /// .onTimeout(short_time,
270 /// []() -> int{ return -1; });
274 /// Future<int> f = makeFuture<int>(42)
275 /// .delayed(long_time)
276 /// .onTimeout(short_time,
277 /// []() { return makeFuture<int>(some_exception); });
279 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
281 /// This is not the method you're looking for.
283 /// This needs to be public because it's used by make* and when*, and it's
284 /// not worth listing all those and their fancy template signatures as
285 /// friends. But it's not for public consumption.
287 void setCallback_(F&& func);
289 /// A Future's callback is executed when all three of these conditions have
290 /// become true: it has a value (set by the Promise), it has a callback (set
291 /// by then), and it is active (active by default).
293 /// Inactive Futures will activate upon destruction.
294 Future<T>& activate() & DEPRECATED {
298 Future<T>& deactivate() & DEPRECATED {
302 Future<T> activate() && DEPRECATED {
304 return std::move(*this);
306 Future<T> deactivate() && DEPRECATED {
308 return std::move(*this);
312 return core_->isActive();
316 void raise(E&& exception) {
317 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
318 std::move(exception)));
321 /// Raise an interrupt. If the promise holder has an interrupt
322 /// handler it will be called and potentially stop asynchronous work from
323 /// being done. This is advisory only - a promise holder may not set an
324 /// interrupt handler, or may do anything including ignore. But, if you know
325 /// your future supports this the most likely result is stopping or
326 /// preventing the asynchronous operation (if in time), and the promise
327 /// holder setting an exception on the future. (That may happen
328 /// asynchronously, of course.)
329 void raise(exception_wrapper interrupt);
332 raise(FutureCancellation());
335 /// Throw TimedOut if this Future does not complete within the given
336 /// duration from now. The optional Timeekeeper is as with futures::sleep().
337 Future<T> within(Duration, Timekeeper* = nullptr);
339 /// Throw the given exception if this Future does not complete within the
340 /// given duration from now. The optional Timeekeeper is as with
341 /// futures::sleep().
343 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
345 /// Delay the completion of this Future for at least this duration from
346 /// now. The optional Timekeeper is as with futures::sleep().
347 Future<T> delayed(Duration, Timekeeper* = nullptr);
349 /// Block until this Future is complete. Returns a reference to this Future.
352 /// Overload of wait() for rvalue Futures
353 Future<T>&& wait() &&;
355 /// Block until this Future is complete or until the given Duration passes.
356 /// Returns a reference to this Future
357 Future<T>& wait(Duration) &;
359 /// Overload of wait(Duration) for rvalue Futures
360 Future<T>&& wait(Duration) &&;
362 /// Call e->drive() repeatedly until the future is fulfilled. Examples
363 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
364 /// reference to this Future so that you can chain calls if desired.
365 /// value (moved out), or throws the exception.
366 Future<T>& waitVia(DrivableExecutor* e) &;
368 /// Overload of waitVia() for rvalue Futures
369 Future<T>&& waitVia(DrivableExecutor* e) &&;
371 /// If the value in this Future is equal to the given Future, when they have
372 /// both completed, the value of the resulting Future<bool> will be true. It
373 /// will be false otherwise (including when one or both Futures have an
375 Future<bool> willEqual(Future<T>&);
377 /// predicate behaves like std::function<bool(T const&)>
378 /// If the predicate does not obtain with the value, the result
379 /// is a folly::PredicateDoesNotObtain exception
381 Future<T> filter(F predicate);
383 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
384 /// the result of collect or collectAll
385 template <class I, class F>
386 Future<I> reduce(I&& initial, F&& func);
388 /// Create a Future chain from a sequence of callbacks. i.e.
390 /// f.then(a).then(b).then(c)
392 /// where f is a Future<A> and the result of the chain is a Future<D>
395 /// f.thenMulti(a, b, c);
396 template <class Callback, class... Callbacks>
397 auto thenMulti(Callback&& fn, Callbacks&&... fns)
398 -> decltype(this->then(std::forward<Callback>(fn)).
399 thenMulti(std::forward<Callbacks>(fns)...));
401 // Nothing to see here, just thenMulti's base case
402 template <class Callback>
403 auto thenMulti(Callback&& fn)
404 -> decltype(this->then(std::forward<Callback>(fn)));
406 /// Create a Future chain from a sequence of callbacks. i.e.
408 /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
410 /// where f is a Future<A> and the result of the chain is a Future<D>
413 /// f.thenMultiWithExecutor(executor, a, b, c);
414 template <class Callback, class... Callbacks>
415 auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
416 -> decltype(this->then(std::forward<Callback>(fn)).
417 thenMulti(std::forward<Callbacks>(fns)...));
419 // Nothing to see here, just thenMultiWithExecutor's base case
420 template <class Callback>
421 auto thenMultiWithExecutor(Executor* x, Callback&& fn)
422 -> decltype(this->then(std::forward<Callback>(fn)));
424 /// Discard a result, but propagate an exception.
425 Future<Unit> unit() {
426 return then([]{ return Unit{}; });
430 typedef detail::Core<T>* corePtr;
432 // shared core state object
436 Future(corePtr obj) : core_(obj) {}
440 void throwIfInvalid() const;
442 friend class Promise<T>;
443 template <class> friend class Future;
446 friend Future<T2> makeFuture(Try<T2>&&);
448 // Variant: returns a value
449 // e.g. f.then([](Try<T> t){ return t.value(); });
450 template <typename F, typename R, bool isTry, typename... Args>
451 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
452 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
454 // Variant: returns a Future
455 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
456 template <typename F, typename R, bool isTry, typename... Args>
457 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
458 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
460 Executor* getExecutor() { return core_->getExecutor(); }
461 void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
462 core_->setExecutor(x, priority);
468 #include <folly/futures/Future-inl.h>