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> Future(T2&& val);
61 template <class T2 = T,
62 typename std::enable_if<
63 folly::is_void_or_unit<T2>::value,
69 /** Return the reference to result. Should not be called if !isReady().
70 Will rethrow the exception if an exception has been
73 typename std::add_lvalue_reference<T>::type
75 typename std::add_lvalue_reference<const T>::type
78 /// Returns an inactive Future which will call back on the other side of
79 /// executor (when it is activated).
81 /// NB remember that Futures activate when they destruct. This is good,
82 /// it means that this will work:
84 /// f.via(e).then(a).then(b);
86 /// a and b will execute in the same context (the far side of e), because
87 /// the Future (temporary variable) created by via(e) does not call back
88 /// until it destructs, which is after then(a) and then(b) have been wired
91 /// But this is still racy:
93 /// f = f.via(e).then(a);
95 // The ref-qualifier allows for `this` to be moved out so we
96 // don't get access-after-free situations in chaining.
97 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
98 template <typename Executor>
99 Future<T> via(Executor* executor) &&;
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 template <typename Executor>
105 Future<T> via(Executor* executor) &;
107 /** True when the result (or exception) is ready. */
108 bool isReady() const;
110 /** A reference to the Try of the value */
113 /// If the promise has been fulfilled, return an Optional with the Try<T>.
114 /// Otherwise return an empty Optional.
115 /// Note that this moves the Try<T> out.
116 Optional<Try<T>> poll();
118 /// Block until the future is fulfilled. Returns the value (moved out), or
119 /// throws the exception. The future must not already have a callback.
122 /// Block until the future is fulfilled, or until timed out. Returns the
123 /// value (moved out), or throws the exception (which might be a TimedOut
127 /// Call e->drive() repeatedly until the future is fulfilled. Examples
128 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
129 /// value (moved out), or throws the exception.
130 T getVia(DrivableExecutor* e);
132 /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
133 /// Future<T> instance.
134 template <class F = T>
135 typename std::enable_if<isFuture<F>::value,
136 Future<typename isFuture<T>::Inner>>::type
139 /** When this Future has completed, execute func which is a function that
149 Func shall return either another Future or a value.
151 A Future for the return type of func is returned.
153 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
155 The Future given to the functor is ready, and the functor may call
156 value(), which may rethrow if this has captured an exception. If func
157 throws, the exception will be captured in the Future that is returned.
159 /* TODO n3428 and other async frameworks have something like then(scheduler,
160 Future), we might want to support a similar API which could be
161 implemented a little more efficiently than
162 f.via(executor).then(callback) */
163 template <typename F, typename R = detail::callableResult<T, F>>
164 typename R::Return then(F func) {
165 typedef typename R::Arg Arguments;
166 return thenImplementation<F, R>(std::move(func), Arguments());
169 /// Variant where func is an member function
171 /// struct Worker { R doWork(Try<T>); }
174 /// Future<R> f2 = f1.then(&Worker::doWork, w);
176 /// This is just sugar for
178 /// f1.then(std::bind(&Worker::doWork, w));
179 template <typename R, typename Caller, typename... Args>
180 Future<typename isFuture<R>::Inner>
181 then(R(Caller::*func)(Args...), Caller *instance);
185 /// Execute the callback via the given Executor. The executor doesn't stick.
189 /// f.via(x).then(b).then(c)
193 /// f.then(x, b).then(c)
195 /// In the former both b and c execute via x. In the latter, only b executes
196 /// via x, and c executes via the same executor (if any) that f had.
197 template <class... Args>
198 auto then(Executor* x, Args&&... args)
199 -> decltype(this->then(std::forward<Args>(args)...));
202 /// Convenience method for ignoring the value and creating a Future<void>.
203 /// Exceptions still propagate.
206 /// Set an error callback for this Future. The callback should take a single
207 /// argument of the type that you want to catch, and should return a value of
208 /// the same type as this Future, or a Future of that type (see overload
209 /// below). For instance,
213 /// throw std::runtime_error("oh no!");
216 /// .onError([] (std::runtime_error& e) {
217 /// LOG(INFO) << "std::runtime_error: " << e.what();
218 /// return -1; // or makeFuture<int>(-1)
221 typename std::enable_if<
222 !detail::callableWith<F, exception_wrapper>::value &&
223 !detail::Extract<F>::ReturnsFuture::value,
227 /// Overload of onError where the error callback returns a Future<T>
229 typename std::enable_if<
230 !detail::callableWith<F, exception_wrapper>::value &&
231 detail::Extract<F>::ReturnsFuture::value,
235 /// Overload of onError that takes exception_wrapper and returns Future<T>
237 typename std::enable_if<
238 detail::callableWith<F, exception_wrapper>::value &&
239 detail::Extract<F>::ReturnsFuture::value,
243 /// Overload of onError that takes exception_wrapper and returns T
245 typename std::enable_if<
246 detail::callableWith<F, exception_wrapper>::value &&
247 !detail::Extract<F>::ReturnsFuture::value,
251 /// func is like std::function<void()> and is executed unconditionally, and
252 /// the value/exception is passed through to the resulting Future.
253 /// func shouldn't throw, but if it does it will be captured and propagated,
254 /// and discard any value/exception that this Future has obtained.
256 Future<T> ensure(F func);
258 /// Like onError, but for timeouts. example:
260 /// Future<int> f = makeFuture<int>(42)
261 /// .delayed(long_time)
262 /// .onTimeout(short_time,
263 /// []() -> int{ return -1; });
267 /// Future<int> f = makeFuture<int>(42)
268 /// .delayed(long_time)
269 /// .onTimeout(short_time,
270 /// []() { return makeFuture<int>(some_exception); });
272 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
274 /// This is not the method you're looking for.
276 /// This needs to be public because it's used by make* and when*, and it's
277 /// not worth listing all those and their fancy template signatures as
278 /// friends. But it's not for public consumption.
280 void setCallback_(F&& func);
282 /// A Future's callback is executed when all three of these conditions have
283 /// become true: it has a value (set by the Promise), it has a callback (set
284 /// by then), and it is active (active by default).
286 /// Inactive Futures will activate upon destruction.
287 Future<T>& activate() & {
291 Future<T>& deactivate() & {
295 Future<T> activate() && {
297 return std::move(*this);
299 Future<T> deactivate() && {
301 return std::move(*this);
305 return core_->isActive();
309 void raise(E&& exception) {
310 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
311 std::move(exception)));
314 /// Raise an interrupt. If the promise holder has an interrupt
315 /// handler it will be called and potentially stop asynchronous work from
316 /// being done. This is advisory only - a promise holder may not set an
317 /// interrupt handler, or may do anything including ignore. But, if you know
318 /// your future supports this the most likely result is stopping or
319 /// preventing the asynchronous operation (if in time), and the promise
320 /// holder setting an exception on the future. (That may happen
321 /// asynchronously, of course.)
322 void raise(exception_wrapper interrupt);
325 raise(FutureCancellation());
328 /// Throw TimedOut if this Future does not complete within the given
329 /// duration from now. The optional Timeekeeper is as with futures::sleep().
330 Future<T> within(Duration, Timekeeper* = nullptr);
332 /// Throw the given exception if this Future does not complete within the
333 /// given duration from now. The optional Timeekeeper is as with
334 /// futures::sleep().
336 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
338 /// Delay the completion of this Future for at least this duration from
339 /// now. The optional Timekeeper is as with futures::sleep().
340 Future<T> delayed(Duration, Timekeeper* = nullptr);
342 /// Block until this Future is complete. Returns a reference to this Future.
345 /// Overload of wait() for rvalue Futures
346 Future<T>&& wait() &&;
348 /// Block until this Future is complete or until the given Duration passes.
349 /// Returns a reference to this Future
350 Future<T>& wait(Duration) &;
352 /// Overload of wait(Duration) for rvalue Futures
353 Future<T>&& wait(Duration) &&;
355 /// Call e->drive() repeatedly until the future is fulfilled. Examples
356 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
357 /// reference to this Future so that you can chain calls if desired.
358 /// value (moved out), or throws the exception.
359 Future<T>& waitVia(DrivableExecutor* e) &;
361 /// Overload of waitVia() for rvalue Futures
362 Future<T>&& waitVia(DrivableExecutor* e) &&;
364 /// If the value in this Future is equal to the given Future, when they have
365 /// both completed, the value of the resulting Future<bool> will be true. It
366 /// will be false otherwise (including when one or both Futures have an
368 Future<bool> willEqual(Future<T>&);
370 /// predicate behaves like std::function<bool(T const&)>
371 /// If the predicate does not obtain with the value, the result
372 /// is a folly::PredicateDoesNotObtain exception
374 Future<T> filter(F predicate);
377 typedef detail::Core<T>* corePtr;
379 // shared core state object
383 Future(corePtr obj) : core_(obj) {}
387 void throwIfInvalid() const;
389 friend class Promise<T>;
390 template <class> friend class Future;
392 // Variant: returns a value
393 // e.g. f.then([](Try<T> t){ return t.value(); });
394 template <typename F, typename R, bool isTry, typename... Args>
395 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
396 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
398 // Variant: returns a Future
399 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
400 template <typename F, typename R, bool isTry, typename... Args>
401 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
402 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
404 Executor* getExecutor() { return core_->getExecutor(); }
405 void setExecutor(Executor* x) { core_->setExecutor(x); }
411 #include <folly/futures/Future-inl.h>