2 * Copyright 2014 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/MoveWrapper.h>
27 #include <folly/futures/Deprecated.h>
28 #include <folly/futures/Promise.h>
29 #include <folly/futures/Try.h>
30 #include <folly/futures/FutureException.h>
31 #include <folly/futures/detail/Types.h>
35 template <class> struct Promise;
39 template <class> struct Core;
40 template <class...> struct VariadicContext;
44 typedef typename std::conditional<
45 std::is_same<T, void>::value,
52 struct IsFuture : std::integral_constant<bool, false> {
56 template <template <typename T> class Future, typename T>
57 struct IsFuture<Future<T>> : std::integral_constant<bool, true> {
61 template <typename...>
64 template <typename Arg, typename... Args>
65 struct ArgType<Arg, Args...> {
71 typedef void FirstArg;
75 struct Extract : Extract<decltype(&L::operator())> { };
77 template <typename Class, typename R, typename... Args>
78 struct Extract<R(Class::*)(Args...) const> {
79 typedef IsFuture<R> ReturnsFuture;
80 typedef Future<typename ReturnsFuture::Inner> Return;
81 typedef typename ReturnsFuture::Inner RawReturn;
82 typedef typename ArgType<Args...>::FirstArg FirstArg;
85 template <typename Class, typename R, typename... Args>
86 struct Extract<R(Class::*)(Args...)> {
87 typedef IsFuture<R> ReturnsFuture;
88 typedef Future<typename ReturnsFuture::Inner> Return;
89 typedef typename ReturnsFuture::Inner RawReturn;
90 typedef typename ArgType<Args...>::FirstArg FirstArg;
98 template <typename T> struct isFuture;
100 /// This namespace is for utility functions that would usually be static
101 /// members of Future, except they don't make sense there because they don't
102 /// depend on the template type (rather, on the type of their arguments in
103 /// some cases). This is the least-bad naming scheme we could think of. Some
104 /// of the functions herein have really-likely-to-collide names, like "map"
107 /// Returns a Future that will complete after the specified duration. The
108 /// Duration typedef of a `std::chrono` duration type indicates the
109 /// resolution you can expect to be meaningful (milliseconds at the time of
110 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
111 /// use the global futures timekeeper (we run a thread whose job it is to
112 /// keep time for futures timeouts) but we provide the option for power
115 /// The Timekeeper thread will be lazily created the first time it is
116 /// needed. If your program never uses any timeouts or other time-based
117 /// Futures you will pay no Timekeeper thread overhead.
118 Future<void> sleep(Duration, Timekeeper* = nullptr);
124 typedef T value_type;
127 Future(Future const&) = delete;
128 Future& operator=(Future const&) = delete;
131 Future(Future&&) noexcept;
132 Future& operator=(Future&&);
136 /** Return the reference to result. Should not be called if !isReady().
137 Will rethrow the exception if an exception has been
140 This function is not thread safe - the returned Future can only
141 be executed from the thread that the executor runs it in.
142 See below for a thread safe version
144 typename std::add_lvalue_reference<T>::type
146 typename std::add_lvalue_reference<const T>::type
149 /// Returns an inactive Future which will call back on the other side of
150 /// executor (when it is activated).
152 /// NB remember that Futures activate when they destruct. This is good,
153 /// it means that this will work:
155 /// f.via(e).then(a).then(b);
157 /// a and b will execute in the same context (the far side of e), because
158 /// the Future (temporary variable) created by via(e) does not call back
159 /// until it destructs, which is after then(a) and then(b) have been wired
162 /// But this is still racy:
164 /// f = f.via(e).then(a);
166 // The ref-qualifier allows for `this` to be moved out so we
167 // don't get access-after-free situations in chaining.
168 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
169 template <typename Executor>
170 Future<T> via(Executor* executor) &&;
172 /// This variant creates a new future, where the ref-qualifier && version
173 /// moves `this` out. This one is less efficient but avoids confusing users
174 /// when "return f.via(x);" fails.
175 template <typename Executor>
176 Future<T> via(Executor* executor) &;
178 /** True when the result (or exception) is ready. */
179 bool isReady() const;
181 /** A reference to the Try of the value */
184 /// Block until the future is fulfilled. Returns the value (moved out), or
185 /// throws the exception. The future must not already have a callback.
188 /// Block until the future is fulfilled, or until timed out. Returns the
189 /// value (moved out), or throws the exception (which might be a TimedOut
193 /** When this Future has completed, execute func which is a function that
194 takes a Try<T>&&. A Future for the return type of func is
197 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
199 The Future given to the functor is ready, and the functor may call
200 value(), which may rethrow if this has captured an exception. If func
201 throws, the exception will be captured in the Future that is returned.
203 /* TODO n3428 and other async frameworks have something like then(scheduler,
204 Future), we might want to support a similar API which could be
205 implemented a little more efficiently than
206 f.via(executor).then(callback) */
208 typename std::enable_if<
209 !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
210 Future<typename std::result_of<F(Try<T>&&)>::type> >::type
213 /// Variant where func takes a T directly, bypassing a try. Any exceptions
214 /// will be implicitly passed on to the resultant Future.
216 /// Future<int> f = makeFuture<int>(42).then([](int i) { return i+1; });
218 typename std::enable_if<
219 !std::is_same<T, void>::value &&
220 !isFuture<typename std::result_of<
221 F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
222 Future<typename std::result_of<
223 F(typename detail::AliasIfVoid<T>::type&&)>::type> >::type
226 /// Like the above variant, but for void futures. That is, func takes no
229 /// Future<int> f = makeFuture().then([] { return 42; });
231 typename std::enable_if<
232 std::is_same<T, void>::value &&
233 !isFuture<typename std::result_of<F()>::type>::value,
234 Future<typename std::result_of<F()>::type> >::type
237 /// Variant where func returns a Future<T> instead of a T. e.g.
239 /// Future<string> f2 = f1.then(
240 /// [](Try<T>&&) { return makeFuture<string>("foo"); });
242 typename std::enable_if<
243 isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
244 Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
247 /// Variant where func returns a Future<T2> and takes a T directly, bypassing
248 /// a Try. Any exceptions will be implicitly passed on to the resultant
249 /// Future. For example,
251 /// Future<int> f = makeFuture<int>(42).then(
252 /// [](int i) { return makeFuture<int>(i+1); });
254 typename std::enable_if<
255 !std::is_same<T, void>::value &&
256 isFuture<typename std::result_of<
257 F(typename detail::AliasIfVoid<T>::type&&)>::type>::value,
258 Future<typename std::result_of<
259 F(typename detail::AliasIfVoid<T>::type&&)>::type::value_type> >::type
262 /// Like the above variant, but for void futures. That is, func takes no
263 /// argument and returns a future.
265 /// Future<int> f = makeFuture().then(
266 /// [] { return makeFuture<int>(42); });
268 typename std::enable_if<
269 std::is_same<T, void>::value &&
270 isFuture<typename std::result_of<F()>::type>::value,
271 Future<typename std::result_of<F()>::type::value_type> >::type
274 /// Variant where func is an ordinary function (static method, method)
276 /// R doWork(Try<T>&&);
278 /// Future<R> f2 = f1.then(doWork);
283 /// static R doWork(Try<T>&&); }
285 /// Future<R> f2 = f1.then(&Worker::doWork);
286 template <class = T, class R = std::nullptr_t>
287 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
288 inline then(R(*func)(Try<T>&&)) {
289 return then([func](Try<T>&& t) {
290 return (*func)(std::move(t));
294 /// Variant where func returns a Future<R> instead of a R. e.g.
297 /// Future<R> doWork(Try<T>&&); }
299 /// Future<R> f2 = f1.then(&Worker::doWork);
300 template <class = T, class R = std::nullptr_t>
301 typename std::enable_if<isFuture<R>::value, R>::type
302 inline then(R(*func)(Try<T>&&)) {
303 return then([func](Try<T>&& t) {
304 return (*func)(std::move(t));
308 /// Variant where func is an member function
311 /// R doWork(Try<T>&&); }
314 /// Future<R> f2 = f1.then(w, &Worker::doWork);
315 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
316 typename std::enable_if<!isFuture<R>::value, Future<R>>::type
317 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
318 return then([instance, func](Try<T>&& t) {
319 return (instance->*func)(std::move(t));
323 // Same as above, but func takes void instead of Try<void>&&
324 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
325 typename std::enable_if<
326 std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
327 inline then(Caller *instance, R(Caller::*func)()) {
328 return then([instance, func]() {
329 return (instance->*func)();
333 // Same as above, but func takes T&& instead of Try<T>&&
334 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
335 typename std::enable_if<
336 !std::is_same<T, void>::value && !isFuture<R>::value, Future<R>>::type
339 R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
340 return then([instance, func](T&& t) {
341 return (instance->*func)(std::move(t));
345 /// Variant where func returns a Future<R> instead of a R. e.g.
348 /// Future<R> doWork(Try<T>&&); }
351 /// Future<R> f2 = f1.then(w, &Worker::doWork);
352 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
353 typename std::enable_if<isFuture<R>::value, R>::type
354 inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
355 return then([instance, func](Try<T>&& t) {
356 return (instance->*func)(std::move(t));
360 // Same as above, but func takes void instead of Try<void>&&
361 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
362 typename std::enable_if<
363 std::is_same<T, void>::value && isFuture<R>::value, R>::type
364 inline then(Caller *instance, R(Caller::*func)()) {
365 return then([instance, func]() {
366 return (instance->*func)();
370 // Same as above, but func takes T&& instead of Try<T>&&
371 template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
372 typename std::enable_if<
373 !std::is_same<T, void>::value && isFuture<R>::value, R>::type
376 R(Caller::*func)(typename detail::AliasIfVoid<T>::type&&)) {
377 return then([instance, func](T&& t) {
378 return (instance->*func)(std::move(t));
382 /// Convenience method for ignoring the value and creating a Future<void>.
383 /// Exceptions still propagate.
386 /// Set an error callback for this Future. The callback should take a single
387 /// argument of the type that you want to catch, and should return a value of
388 /// the same type as this Future, or a Future of that type (see overload
389 /// below). For instance,
393 /// throw std::runtime_error("oh no!");
396 /// .onError([] (std::runtime_error& e) {
397 /// LOG(INFO) << "std::runtime_error: " << e.what();
398 /// return -1; // or makeFuture<int>(-1)
401 typename std::enable_if<
402 !detail::Extract<F>::ReturnsFuture::value,
406 /// Overload of onError where the error callback returns a Future<T>
408 typename std::enable_if<
409 detail::Extract<F>::ReturnsFuture::value,
413 /// This is not the method you're looking for.
415 /// This needs to be public because it's used by make* and when*, and it's
416 /// not worth listing all those and their fancy template signatures as
417 /// friends. But it's not for public consumption.
419 void setCallback_(F&& func);
421 /// A Future's callback is executed when all three of these conditions have
422 /// become true: it has a value (set by the Promise), it has a callback (set
423 /// by then), and it is active (active by default).
425 /// Inactive Futures will activate upon destruction.
426 Future<T>& activate() & {
430 Future<T>& deactivate() & {
434 Future<T> activate() && {
436 return std::move(*this);
438 Future<T> deactivate() && {
440 return std::move(*this);
444 return core_->isActive();
448 void raise(E&& exception) {
449 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
450 std::move(exception)));
453 /// Raise an interrupt. If the promise holder has an interrupt
454 /// handler it will be called and potentially stop asynchronous work from
455 /// being done. This is advisory only - a promise holder may not set an
456 /// interrupt handler, or may do anything including ignore. But, if you know
457 /// your future supports this the most likely result is stopping or
458 /// preventing the asynchronous operation (if in time), and the promise
459 /// holder setting an exception on the future. (That may happen
460 /// asynchronously, of course.)
461 void raise(exception_wrapper interrupt);
464 raise(FutureCancellation());
467 /// Throw TimedOut if this Future does not complete within the given
468 /// duration from now. The optional Timeekeeper is as with futures::sleep().
469 Future<T> within(Duration, Timekeeper* = nullptr);
471 /// Throw the given exception if this Future does not complete within the
472 /// given duration from now. The optional Timeekeeper is as with
473 /// futures::sleep().
475 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
477 /// Delay the completion of this Future for at least this duration from
478 /// now. The optional Timekeeper is as with futures::sleep().
479 Future<T> delayed(Duration, Timekeeper* = nullptr);
481 /// Block until this Future is complete. Returns a new Future containing the
485 /// Block until this Future is complete or until the given Duration passes.
486 /// Returns a new Future which either contains the result or is incomplete,
487 /// depending on whether the Duration passed.
488 Future<T> wait(Duration);
491 typedef detail::Core<T>* corePtr;
493 // shared core state object
497 Future(corePtr obj) : core_(obj) {}
501 void throwIfInvalid() const;
503 friend class Promise<T>;
507 Make a completed Future by moving in a value. e.g.
510 auto f = makeFuture(std::move(foo));
514 auto f = makeFuture<string>("foo");
517 Future<typename std::decay<T>::type> makeFuture(T&& t);
519 /** Make a completed void Future. */
520 Future<void> makeFuture();
522 /** Make a completed Future by executing a function. If the function throws
523 we capture the exception, otherwise we capture the result. */
527 typename std::enable_if<
528 !std::is_reference<F>::value, bool>::type sdf = false)
529 -> Future<decltype(func())>;
534 -> Future<decltype(func())>;
536 /// Make a failed Future from an exception_ptr.
537 /// Because the Future's type cannot be inferred you have to specify it, e.g.
539 /// auto f = makeFuture<string>(std::current_exception());
541 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
543 /// Make a failed Future from an exception_wrapper.
545 Future<T> makeFuture(exception_wrapper ew);
547 /** Make a Future from an exception type E that can be passed to
548 std::make_exception_ptr(). */
549 template <class T, class E>
550 typename std::enable_if<std::is_base_of<std::exception, E>::value,
552 makeFuture(E const& e);
554 /** Make a Future out of a Try */
556 Future<T> makeFuture(Try<T>&& t);
559 * Return a new Future that will call back on the given Executor.
560 * This is just syntactic sugar for makeFuture().via(executor)
562 * @param executor the Executor to call back on
564 * @returns a void Future that will call back on the given executor
566 template <typename Executor>
567 Future<void> via(Executor* executor);
569 /** When all the input Futures complete, the returned Future will complete.
570 Errors do not cause early termination; this Future will always succeed
571 after all its Futures have finished (whether successfully or with an
574 The Futures are moved in, so your copies are invalid. If you need to
575 chain further from these Futures, use the variant with an output iterator.
577 XXX is this still true?
578 This function is thread-safe for Futures running on different threads.
580 The return type for Future<T> input is a Future<std::vector<Try<T>>>
582 template <class InputIterator>
583 Future<std::vector<Try<
584 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
585 whenAll(InputIterator first, InputIterator last);
587 /// This version takes a varying number of Futures instead of an iterator.
588 /// The return type for (Future<T1>, Future<T2>, ...) input
589 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
590 /// The Futures are moved in, so your copies are invalid.
591 template <typename... Fs>
592 typename detail::VariadicContext<
593 typename std::decay<Fs>::type::value_type...>::type
596 /** The result is a pair of the index of the first Future to complete and
597 the Try. If multiple Futures complete at the same time (or are already
598 complete when passed in), the "winner" is chosen non-deterministically.
600 This function is thread-safe for Futures running on different threads.
602 template <class InputIterator>
605 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
606 whenAny(InputIterator first, InputIterator last);
608 /** when n Futures have completed, the Future completes with a vector of
609 the index and Try of those n Futures (the indices refer to the original
610 order, but the result vector will be in an arbitrary order)
614 template <class InputIterator>
615 Future<std::vector<std::pair<
617 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
618 whenN(InputIterator first, InputIterator last, size_t n);
622 #include <folly/futures/Future-inl.h>