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/DrivableExecutor.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/futures/Try.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/detail/Types.h>
36 template <class> struct Promise;
39 struct isFuture : std::false_type {
44 struct isFuture<Future<T>> : std::true_type {
49 struct isTry : std::false_type {};
52 struct isTry<Try<T>> : std::true_type {};
56 template <class> struct Core;
57 template <class...> struct VariadicContext;
59 template<typename F, typename... Args>
60 using resultOf = decltype(std::declval<F>()(std::declval<Args>()...));
62 template <typename...>
65 template <typename Arg, typename... Args>
66 struct ArgType<Arg, Args...> {
72 typedef void FirstArg;
75 template <bool isTry, typename F, typename... Args>
77 typedef resultOf<F, Args...> Result;
80 template<typename F, typename... Args>
83 typename = detail::resultOf<T, Args...>>
84 static constexpr std::true_type
85 check(std::nullptr_t) { return std::true_type{}; };
88 static constexpr std::false_type
89 check(...) { return std::false_type{}; };
91 typedef decltype(check<F>(nullptr)) type;
92 static constexpr bool value = type::value;
95 template<typename T, typename F>
96 struct callableResult {
97 typedef typename std::conditional<
98 callableWith<F>::value,
99 detail::argResult<false, F>,
100 typename std::conditional<
101 callableWith<F, Try<T>&&>::value,
102 detail::argResult<true, F, Try<T>&&>,
103 typename std::conditional<
104 callableWith<F, Try<T>&>::value,
105 detail::argResult<true, F, Try<T>&>,
106 typename std::conditional<
107 callableWith<F, T&&>::value,
108 detail::argResult<false, F, T&&>,
109 detail::argResult<false, F, T&>>::type>::type>::type>::type Arg;
110 typedef isFuture<typename Arg::Result> ReturnsFuture;
111 typedef Future<typename ReturnsFuture::Inner> Return;
115 struct callableResult<void, F> {
116 typedef typename std::conditional<
117 callableWith<F>::value,
118 detail::argResult<false, F>,
119 typename std::conditional<
120 callableWith<F, Try<void>&&>::value,
121 detail::argResult<true, F, Try<void>&&>,
122 detail::argResult<true, F, Try<void>&>>::type>::type Arg;
123 typedef isFuture<typename Arg::Result> ReturnsFuture;
124 typedef Future<typename ReturnsFuture::Inner> Return;
127 template <typename L>
128 struct Extract : Extract<decltype(&L::operator())> { };
130 template <typename Class, typename R, typename... Args>
131 struct Extract<R(Class::*)(Args...) const> {
132 typedef isFuture<R> ReturnsFuture;
133 typedef Future<typename ReturnsFuture::Inner> Return;
134 typedef typename ReturnsFuture::Inner RawReturn;
135 typedef typename ArgType<Args...>::FirstArg FirstArg;
138 template <typename Class, typename R, typename... Args>
139 struct Extract<R(Class::*)(Args...)> {
140 typedef isFuture<R> ReturnsFuture;
141 typedef Future<typename ReturnsFuture::Inner> Return;
142 typedef typename ReturnsFuture::Inner RawReturn;
143 typedef typename ArgType<Args...>::FirstArg FirstArg;
150 /// This namespace is for utility functions that would usually be static
151 /// members of Future, except they don't make sense there because they don't
152 /// depend on the template type (rather, on the type of their arguments in
153 /// some cases). This is the least-bad naming scheme we could think of. Some
154 /// of the functions herein have really-likely-to-collide names, like "map"
157 /// Returns a Future that will complete after the specified duration. The
158 /// Duration typedef of a `std::chrono` duration type indicates the
159 /// resolution you can expect to be meaningful (milliseconds at the time of
160 /// writing). Normally you wouldn't need to specify a Timekeeper, we will
161 /// use the global futures timekeeper (we run a thread whose job it is to
162 /// keep time for futures timeouts) but we provide the option for power
165 /// The Timekeeper thread will be lazily created the first time it is
166 /// needed. If your program never uses any timeouts or other time-based
167 /// Futures you will pay no Timekeeper thread overhead.
168 Future<void> sleep(Duration, Timekeeper* = nullptr);
170 /// Create a Future chain from a sequence of callbacks. i.e.
172 /// f.then(a).then(b).then(c);
174 /// where f is a Future<A> and the result of the chain is a Future<Z>
177 /// f.then(chain<A,Z>(a, b, c));
178 // If anyone figures how to get chain to deduce A and Z, I'll buy you a drink.
179 template <class A, class Z, class... Callbacks>
180 std::function<Future<Z>(Try<A>)>
181 chain(Callbacks... fns);
187 typedef T value_type;
190 Future(Future const&) = delete;
191 Future& operator=(Future const&) = delete;
194 Future(Future&&) noexcept;
195 Future& operator=(Future&&);
198 template <class F = T>
200 Future(const typename std::enable_if<!std::is_void<F>::value, F>::type& val);
202 template <class F = T>
204 Future(typename std::enable_if<!std::is_void<F>::value, F>::type&& val);
206 template <class F = T,
207 typename std::enable_if<std::is_void<F>::value, int>::type = 0>
212 /** Return the reference to result. Should not be called if !isReady().
213 Will rethrow the exception if an exception has been
216 typename std::add_lvalue_reference<T>::type
218 typename std::add_lvalue_reference<const T>::type
221 /// Returns an inactive Future which will call back on the other side of
222 /// executor (when it is activated).
224 /// NB remember that Futures activate when they destruct. This is good,
225 /// it means that this will work:
227 /// f.via(e).then(a).then(b);
229 /// a and b will execute in the same context (the far side of e), because
230 /// the Future (temporary variable) created by via(e) does not call back
231 /// until it destructs, which is after then(a) and then(b) have been wired
234 /// But this is still racy:
236 /// f = f.via(e).then(a);
238 // The ref-qualifier allows for `this` to be moved out so we
239 // don't get access-after-free situations in chaining.
240 // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
241 template <typename Executor>
242 Future<T> via(Executor* executor) &&;
244 /// This variant creates a new future, where the ref-qualifier && version
245 /// moves `this` out. This one is less efficient but avoids confusing users
246 /// when "return f.via(x);" fails.
247 template <typename Executor>
248 Future<T> via(Executor* executor) &;
250 /** True when the result (or exception) is ready. */
251 bool isReady() const;
253 /** A reference to the Try of the value */
256 /// Block until the future is fulfilled. Returns the value (moved out), or
257 /// throws the exception. The future must not already have a callback.
260 /// Block until the future is fulfilled, or until timed out. Returns the
261 /// value (moved out), or throws the exception (which might be a TimedOut
265 /// Call e->drive() repeatedly until the future is fulfilled. Examples
266 /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
267 /// value (moved out), or throws the exception.
268 T getVia(DrivableExecutor* e);
270 /** When this Future has completed, execute func which is a function that
280 Func shall return either another Future or a value.
282 A Future for the return type of func is returned.
284 Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
286 The Future given to the functor is ready, and the functor may call
287 value(), which may rethrow if this has captured an exception. If func
288 throws, the exception will be captured in the Future that is returned.
290 /* TODO n3428 and other async frameworks have something like then(scheduler,
291 Future), we might want to support a similar API which could be
292 implemented a little more efficiently than
293 f.via(executor).then(callback) */
294 template <typename F, typename R = detail::callableResult<T, F>>
295 typename R::Return then(F func) {
296 typedef typename R::Arg Arguments;
297 return thenImplementation<F, R>(std::move(func), Arguments());
300 /// Variant where func is an member function
303 /// R doWork(Try<T>&&); }
306 /// Future<R> f2 = f1.then(w, &Worker::doWork);
307 template <typename Caller, typename R, typename... Args>
308 Future<typename isFuture<R>::Inner>
309 then(Caller *instance, R(Caller::*func)(Args...));
311 /// Convenience method for ignoring the value and creating a Future<void>.
312 /// Exceptions still propagate.
315 /// Set an error callback for this Future. The callback should take a single
316 /// argument of the type that you want to catch, and should return a value of
317 /// the same type as this Future, or a Future of that type (see overload
318 /// below). For instance,
322 /// throw std::runtime_error("oh no!");
325 /// .onError([] (std::runtime_error& e) {
326 /// LOG(INFO) << "std::runtime_error: " << e.what();
327 /// return -1; // or makeFuture<int>(-1)
330 typename std::enable_if<
331 !detail::Extract<F>::ReturnsFuture::value,
335 /// Overload of onError where the error callback returns a Future<T>
337 typename std::enable_if<
338 detail::Extract<F>::ReturnsFuture::value,
342 /// Like onError, but for timeouts. example:
344 /// Future<int> f = makeFuture<int>(42)
345 /// .delayed(long_time)
346 /// .onTimeout(short_time,
347 /// []() -> int{ return -1; });
351 /// Future<int> f = makeFuture<int>(42)
352 /// .delayed(long_time)
353 /// .onTimeout(short_time,
354 /// []() { return makeFuture<int>(some_exception); });
356 Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
358 /// This is not the method you're looking for.
360 /// This needs to be public because it's used by make* and when*, and it's
361 /// not worth listing all those and their fancy template signatures as
362 /// friends. But it's not for public consumption.
364 void setCallback_(F&& func);
366 /// A Future's callback is executed when all three of these conditions have
367 /// become true: it has a value (set by the Promise), it has a callback (set
368 /// by then), and it is active (active by default).
370 /// Inactive Futures will activate upon destruction.
371 Future<T>& activate() & {
375 Future<T>& deactivate() & {
379 Future<T> activate() && {
381 return std::move(*this);
383 Future<T> deactivate() && {
385 return std::move(*this);
389 return core_->isActive();
393 void raise(E&& exception) {
394 raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
395 std::move(exception)));
398 /// Raise an interrupt. If the promise holder has an interrupt
399 /// handler it will be called and potentially stop asynchronous work from
400 /// being done. This is advisory only - a promise holder may not set an
401 /// interrupt handler, or may do anything including ignore. But, if you know
402 /// your future supports this the most likely result is stopping or
403 /// preventing the asynchronous operation (if in time), and the promise
404 /// holder setting an exception on the future. (That may happen
405 /// asynchronously, of course.)
406 void raise(exception_wrapper interrupt);
409 raise(FutureCancellation());
412 /// Throw TimedOut if this Future does not complete within the given
413 /// duration from now. The optional Timeekeeper is as with futures::sleep().
414 Future<T> within(Duration, Timekeeper* = nullptr);
416 /// Throw the given exception if this Future does not complete within the
417 /// given duration from now. The optional Timeekeeper is as with
418 /// futures::sleep().
420 Future<T> within(Duration, E exception, Timekeeper* = nullptr);
422 /// Delay the completion of this Future for at least this duration from
423 /// now. The optional Timekeeper is as with futures::sleep().
424 Future<T> delayed(Duration, Timekeeper* = nullptr);
426 /// Block until this Future is complete. Returns a reference to this Future.
429 /// Overload of wait() for rvalue Futures
430 Future<T>&& wait() &&;
432 /// Block until this Future is complete or until the given Duration passes.
433 /// Returns a reference to this Future
434 Future<T>& wait(Duration) &;
436 /// Overload of wait(Duration) for rvalue Futures
437 Future<T>&& wait(Duration) &&;
439 /// Call e->drive() repeatedly until the future is fulfilled. Examples
440 /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
441 /// reference to this Future so that you can chain calls if desired.
442 /// value (moved out), or throws the exception.
443 Future<T>& waitVia(DrivableExecutor* e) &;
445 /// Overload of waitVia() for rvalue Futures
446 Future<T>&& waitVia(DrivableExecutor* e) &&;
449 typedef detail::Core<T>* corePtr;
451 // shared core state object
455 Future(corePtr obj) : core_(obj) {}
459 void throwIfInvalid() const;
461 friend class Promise<T>;
463 // Variant: returns a value
464 // e.g. f.then([](Try<T> t){ return t.value(); });
465 template <typename F, typename R, bool isTry, typename... Args>
466 typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
467 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
469 // Variant: returns a Future
470 // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
471 template <typename F, typename R, bool isTry, typename... Args>
472 typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
473 thenImplementation(F func, detail::argResult<isTry, F, Args...>);
477 Make a completed Future by moving in a value. e.g.
480 auto f = makeFuture(std::move(foo));
484 auto f = makeFuture<string>("foo");
487 Future<typename std::decay<T>::type> makeFuture(T&& t);
489 /** Make a completed void Future. */
490 Future<void> makeFuture();
492 /** Make a completed Future by executing a function. If the function throws
493 we capture the exception, otherwise we capture the result. */
497 typename std::enable_if<
498 !std::is_reference<F>::value, bool>::type sdf = false)
499 -> Future<decltype(func())>;
504 -> Future<decltype(func())>;
506 /// Make a failed Future from an exception_ptr.
507 /// Because the Future's type cannot be inferred you have to specify it, e.g.
509 /// auto f = makeFuture<string>(std::current_exception());
511 Future<T> makeFuture(std::exception_ptr const& e) DEPRECATED;
513 /// Make a failed Future from an exception_wrapper.
515 Future<T> makeFuture(exception_wrapper ew);
517 /** Make a Future from an exception type E that can be passed to
518 std::make_exception_ptr(). */
519 template <class T, class E>
520 typename std::enable_if<std::is_base_of<std::exception, E>::value,
522 makeFuture(E const& e);
524 /** Make a Future out of a Try */
526 Future<T> makeFuture(Try<T>&& t);
529 * Return a new Future that will call back on the given Executor.
530 * This is just syntactic sugar for makeFuture().via(executor)
532 * @param executor the Executor to call back on
534 * @returns a void Future that will call back on the given executor
536 template <typename Executor>
537 Future<void> via(Executor* executor);
539 /** When all the input Futures complete, the returned Future will complete.
540 Errors do not cause early termination; this Future will always succeed
541 after all its Futures have finished (whether successfully or with an
544 The Futures are moved in, so your copies are invalid. If you need to
545 chain further from these Futures, use the variant with an output iterator.
547 This function is thread-safe for Futures running on different threads. But
548 if you are doing anything non-trivial after, you will probably want to
549 follow with `via(executor)` because it will complete in whichever thread the
550 last Future completes in.
552 The return type for Future<T> input is a Future<std::vector<Try<T>>>
554 template <class InputIterator>
555 Future<std::vector<Try<
556 typename std::iterator_traits<InputIterator>::value_type::value_type>>>
557 whenAll(InputIterator first, InputIterator last);
559 /// This version takes a varying number of Futures instead of an iterator.
560 /// The return type for (Future<T1>, Future<T2>, ...) input
561 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
562 /// The Futures are moved in, so your copies are invalid.
563 template <typename... Fs>
564 typename detail::VariadicContext<
565 typename std::decay<Fs>::type::value_type...>::type
568 /** The result is a pair of the index of the first Future to complete and
569 the Try. If multiple Futures complete at the same time (or are already
570 complete when passed in), the "winner" is chosen non-deterministically.
572 This function is thread-safe for Futures running on different threads.
574 template <class InputIterator>
577 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
578 whenAny(InputIterator first, InputIterator last);
580 /** when n Futures have completed, the Future completes with a vector of
581 the index and Try of those n Futures (the indices refer to the original
582 order, but the result vector will be in an arbitrary order)
586 template <class InputIterator>
587 Future<std::vector<std::pair<
589 Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
590 whenN(InputIterator first, InputIterator last, size_t n);
594 #include <folly/futures/Future-inl.h>