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 inline Future<T> via(Executor* executor) &&;
102 /// This variant creates a new future, where the ref-qualifier && version
103 /// moves `this` out. This one is less efficient but avoids confusing users
104 /// when "return f.via(x);" fails.
105 inline 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);
183 /// Execute the callback via the given Executor. The executor doesn't stick.
187 /// f.via(x).then(b).then(c)
191 /// f.then(x, b).then(c)
193 /// In the former both b and c execute via x. In the latter, only b executes
194 /// via x, and c executes via the same executor (if any) that f had.
195 template <class Executor, class Arg, class... Args>
196 auto then(Executor* x, Arg&& arg, Args&&... args)
197 -> decltype(this->then(std::forward<Arg>(arg),
198 std::forward<Args>(args)...));
200 /// Convenience method for ignoring the value and creating a Future<void>.
201 /// Exceptions still propagate.
204 /// Set an error callback for this Future. The callback should take a single
205 /// argument of the type that you want to catch, and should return a value of
206 /// the same type as this Future, or a Future of that type (see overload
207 /// below). For instance,
211 /// throw std::runtime_error("oh no!");
214 /// .onError([] (std::runtime_error& e) {
215 /// LOG(INFO) << "std::runtime_error: " << e.what();
216 /// return -1; // or makeFuture<int>(-1)
219 typename std::enable_if<
220 !detail::callableWith<F, exception_wrapper>::value &&
221 !detail::Extract<F>::ReturnsFuture::value,
225 /// Overload of onError where the error callback returns a Future<T>
227 typename std::enable_if<
228 !detail::callableWith<F, exception_wrapper>::value &&
229 detail::Extract<F>::ReturnsFuture::value,
233 /// Overload of onError that takes exception_wrapper and returns Future<T>
235 typename std::enable_if<
236 detail::callableWith<F, exception_wrapper>::value &&
237 detail::Extract<F>::ReturnsFuture::value,
241 /// Overload of onError that takes exception_wrapper and returns T
243 typename std::enable_if<
244 detail::callableWith<F, exception_wrapper>::value &&
245 !detail::Extract<F>::ReturnsFuture::value,
249 /// func is like std::function<void()> and is executed unconditionally, and
250 /// the value/exception is passed through to the resulting Future.
251 /// func shouldn't throw, but if it does it will be captured and propagated,
252 /// and discard any value/exception that this Future has obtained.
254 Future<T> ensure(F func);
256 /// Like onError, but for timeouts. example:
258 /// Future<int> f = makeFuture<int>(42)
259 /// .delayed(long_time)
260 /// .onTimeout(short_time,
261 /// []() -> int{ return -1; });
265 /// Future<int> f = makeFuture<int>(42)
266 /// .delayed(long_time)
267 /// .onTimeout(short_time,
268 /// []() { return makeFuture<int>(some_exception); });
270 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
272 /// This is not the method you're looking for.
274 /// This needs to be public because it's used by make* and when*, and it's
275 /// not worth listing all those and their fancy template signatures as
276 /// friends. But it's not for public consumption.
278 void setCallback_(F&& func);
280 /// A Future's callback is executed when all three of these conditions have
281 /// become true: it has a value (set by the Promise), it has a callback (set
282 /// by then), and it is active (active by default).
284 /// Inactive Futures will activate upon destruction.
285 Future<T>& activate() & {
289 Future<T>& deactivate() & {
293 Future<T> activate() && {
295 return std::move(*this);
297 Future<T> deactivate() && {
299 return std::move(*this);
303 return core_->isActive();
307 void raise(E&& exception) {
308 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
309 std::move(exception)));
312 /// Raise an interrupt. If the promise holder has an interrupt
313 /// handler it will be called and potentially stop asynchronous work from
314 /// being done. This is advisory only - a promise holder may not set an
315 /// interrupt handler, or may do anything including ignore. But, if you know
316 /// your future supports this the most likely result is stopping or
317 /// preventing the asynchronous operation (if in time), and the promise
318 /// holder setting an exception on the future. (That may happen
319 /// asynchronously, of course.)
320 void raise(exception_wrapper interrupt);
323 raise(FutureCancellation());
326 /// Throw TimedOut if this Future does not complete within the given
327 /// duration from now. The optional Timeekeeper is as with futures::sleep().
328 Future<T> within(Duration, Timekeeper* = nullptr);
330 /// Throw the given exception if this Future does not complete within the
331 /// given duration from now. The optional Timeekeeper is as with
332 /// futures::sleep().
334 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
336 /// Delay the completion of this Future for at least this duration from
337 /// now. The optional Timekeeper is as with futures::sleep().
338 Future<T> delayed(Duration, Timekeeper* = nullptr);
340 /// Block until this Future is complete. Returns a reference to this Future.
343 /// Overload of wait() for rvalue Futures
344 Future<T>&& wait() &&;
346 /// Block until this Future is complete or until the given Duration passes.
347 /// Returns a reference to this Future
348 Future<T>& wait(Duration) &;
350 /// Overload of wait(Duration) for rvalue Futures
351 Future<T>&& wait(Duration) &&;
353 /// Call e->drive() repeatedly until the future is fulfilled. Examples
354 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
355 /// reference to this Future so that you can chain calls if desired.
356 /// value (moved out), or throws the exception.
357 Future<T>& waitVia(DrivableExecutor* e) &;
359 /// Overload of waitVia() for rvalue Futures
360 Future<T>&& waitVia(DrivableExecutor* e) &&;
362 /// If the value in this Future is equal to the given Future, when they have
363 /// both completed, the value of the resulting Future<bool> will be true. It
364 /// will be false otherwise (including when one or both Futures have an
366 Future<bool> willEqual(Future<T>&);
368 /// predicate behaves like std::function<bool(T const&)>
369 /// If the predicate does not obtain with the value, the result
370 /// is a folly::PredicateDoesNotObtain exception
372 Future<T> filter(F predicate);
374 /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
375 /// the result of collect or collectAll
376 template <class I, class F>
377 Future<I> reduce(I&& initial, F&& func);
380 typedef detail::Core<T>* corePtr;
382 // shared core state object
386 Future(corePtr obj) : core_(obj) {}
390 void throwIfInvalid() const;
392 friend class Promise<T>;
393 template <class> friend class Future;
395 // Variant: returns a value
396 // e.g. f.then([](Try<T> t){ return t.value(); });
397 template <typename F, typename R, bool isTry, typename... Args>
398 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
399 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
401 // Variant: returns a Future
402 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
403 template <typename F, typename R, bool isTry, typename... Args>
404 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
405 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
407 Executor* getExecutor() { return core_->getExecutor(); }
408 void setExecutor(Executor* x) { core_->setExecutor(x); }
413 #include <folly/futures/Future-inl.h>