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)
59 template <class T2 = T,
60 typename std::enable_if<!isFuture<T2>::value, void*>::type = nullptr>
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 template <typename Executor>
101 Future<T> via(Executor* executor) &&;
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 template <typename Executor>
107 Future<T> via(Executor* executor) &;
109 /** True when the result (or exception) is ready. */
110 bool isReady() const;
112 /** A reference to the Try of the value */
115 /// If the promise has been fulfilled, return an Optional with the Try<T>.
116 /// Otherwise return an empty Optional.
117 /// Note that this moves the Try<T> out.
118 Optional<Try<T>> poll();
120 /// Block until the future is fulfilled. Returns the value (moved out), or
121 /// throws the exception. The future must not already have a callback.
124 /// Block until the future is fulfilled, or until timed out. Returns the
125 /// value (moved out), or throws the exception (which might be a TimedOut
129 /// Call e->drive() repeatedly until the future is fulfilled. Examples
130 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
131 /// value (moved out), or throws the exception.
132 T getVia(DrivableExecutor* e);
134 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
135 /// Future<T> instance.
136 template <class F = T>
137 typename std::enable_if<isFuture<F>::value,
138 Future<typename isFuture<T>::Inner>>::type
141 /** When this Future has completed, execute func which is a function that
151 Func shall return either another Future or a value.
153 A Future for the return type of func is returned.
155 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
157 The Future given to the functor is ready, and the functor may call
158 value(), which may rethrow if this has captured an exception. If func
159 throws, the exception will be captured in the Future that is returned.
161 /* TODO n3428 and other async frameworks have something like then(scheduler,
162 Future), we might want to support a similar API which could be
163 implemented a little more efficiently than
164 f.via(executor).then(callback) */
165 template <typename F, typename R = detail::callableResult<T, F>>
166 typename R::Return then(F func) {
167 typedef typename R::Arg Arguments;
168 return thenImplementation<F, R>(std::move(func), Arguments());
171 /// Variant where func is an member function
173 /// struct Worker { R doWork(Try<T>); }
176 /// Future<R> f2 = f1.then(&Worker::doWork, w);
178 /// This is just sugar for
180 /// f1.then(std::bind(&Worker::doWork, w));
181 template <typename R, typename Caller, typename... Args>
182 Future<typename isFuture<R>::Inner>
183 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... Args>
200 auto then(Executor* x, Args&&... args)
201 -> decltype(this->then(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() & {
293 Future<T>& deactivate() & {
297 Future<T> activate() && {
299 return std::move(*this);
301 Future<T> deactivate() && {
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);
379 typedef detail::Core<T>* corePtr;
381 // shared core state object
385 Future(corePtr obj) : core_(obj) {}
389 void throwIfInvalid() const;
391 friend class Promise<T>;
392 template <class> friend class Future;
394 // Variant: returns a value
395 // e.g. f.then([](Try<T> t){ return t.value(); });
396 template <typename F, typename R, bool isTry, typename... Args>
397 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
398 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
400 // Variant: returns a Future
401 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
402 template <typename F, typename R, bool isTry, typename... Args>
403 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
404 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
406 Executor* getExecutor() { return core_->getExecutor(); }
407 void setExecutor(Executor* x) { core_->setExecutor(x); }
412 #include <folly/futures/Future-inl.h>