/*
- * Copyright 2014 Facebook, Inc.
+ * Copyright 2015 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <chrono>
#include <thread>
-#include <folly/Baton.h>
+#include <folly/experimental/fibers/Baton.h>
+#include <folly/Optional.h>
#include <folly/futures/detail/Core.h>
#include <folly/futures/Timekeeper.h>
}
template <class T>
-Future<T>::Future(Future<T>&& other) noexcept : core_(nullptr) {
- *this = std::move(other);
+Future<T>::Future(Future<T>&& other) noexcept : core_(other.core_) {
+ other.core_ = nullptr;
}
template <class T>
-Future<T>& Future<T>::operator=(Future<T>&& other) {
+Future<T>& Future<T>::operator=(Future<T>&& other) noexcept {
std::swap(core_, other.core_);
return *this;
}
template <class T>
-template <class F>
-Future<T>::Future(
- const typename std::enable_if<!std::is_void<F>::value, F>::type& val)
- : core_(nullptr) {
- Promise<F> p;
- p.setValue(val);
+template <class T2,
+ typename std::enable_if<!isFuture<T2>::value, void*>::type>
+Future<T>::Future(T2&& val) : core_(nullptr) {
+ Promise<T> p;
+ p.setValue(std::forward<T2>(val));
*this = p.getFuture();
}
template <class T>
-template <class F>
-Future<T>::Future(
- typename std::enable_if<!std::is_void<F>::value, F>::type&& val)
- : core_(nullptr) {
- Promise<F> p;
- p.setValue(std::forward<F>(val));
- *this = p.getFuture();
-}
-
-template <>
-template <class F,
- typename std::enable_if<std::is_void<F>::value, int>::type>
-Future<void>::Future() : core_(nullptr) {
- Promise<void> p;
+template <class T2,
+ typename std::enable_if<
+ folly::is_void_or_unit<T2>::value,
+ int>::type>
+Future<T>::Future() : core_(nullptr) {
+ Promise<T> p;
p.setValue();
*this = p.getFuture();
}
core_->setCallback(std::move(func));
}
+// unwrap
+
+template <class T>
+template <class F>
+typename std::enable_if<isFuture<F>::value,
+ Future<typename isFuture<T>::Inner>>::type
+Future<T>::unwrap() {
+ return then([](Future<typename isFuture<T>::Inner> internal_future) {
+ return internal_future;
+ });
+}
+
+// then
+
// Variant: returns a value
// e.g. f.then([](Try<T>&& t){ return t.value(); });
template <class T>
if (!isTry && t.hasException()) {
p->setException(std::move(t.exception()));
} else {
- p->fulfil([&]() {
+ p->setWith([&]() {
return (*funcm)(t.template get<isTry, Args>()...);
});
}
auto f2 = (*funcm)(t.template get<isTry, Args>()...);
// that didn't throw, now we can steal p
f2.setCallback_([p](Try<B>&& b) mutable {
- p->fulfilTry(std::move(b));
+ p->setTry(std::move(b));
});
} catch (const std::exception& e) {
p->setException(exception_wrapper(std::current_exception(), e));
});
}
+template <class T>
+template <class Executor, class Arg, class... Args>
+auto Future<T>::then(Executor* x, Arg&& arg, Args&&... args)
+ -> decltype(this->then(std::forward<Arg>(arg),
+ std::forward<Args>(args)...))
+{
+ auto oldX = getExecutor();
+ setExecutor(x);
+ return this->then(std::forward<Arg>(arg), std::forward<Args>(args)...).
+ via(oldX);
+}
+
template <class T>
Future<void> Future<T>::then() {
return then([] (Try<T>&& t) {});
template <class T>
template <class F>
typename std::enable_if<
+ !detail::callableWith<F, exception_wrapper>::value &&
!detail::Extract<F>::ReturnsFuture::value,
Future<T>>::type
Future<T>::onError(F&& func) {
auto funcm = folly::makeMoveWrapper(std::move(func));
setCallback_([pm, funcm](Try<T>&& t) mutable {
if (!t.template withException<Exn>([&] (Exn& e) {
- pm->fulfil([&]{
+ pm->setWith([&]{
return (*funcm)(e);
});
})) {
- pm->fulfilTry(std::move(t));
+ pm->setTry(std::move(t));
}
});
template <class T>
template <class F>
typename std::enable_if<
+ !detail::callableWith<F, exception_wrapper>::value &&
detail::Extract<F>::ReturnsFuture::value,
Future<T>>::type
Future<T>::onError(F&& func) {
try {
auto f2 = (*funcm)(e);
f2.setCallback_([pm](Try<T>&& t2) mutable {
- pm->fulfilTry(std::move(t2));
+ pm->setTry(std::move(t2));
});
} catch (const std::exception& e2) {
pm->setException(exception_wrapper(std::current_exception(), e2));
pm->setException(exception_wrapper(std::current_exception()));
}
})) {
- pm->fulfilTry(std::move(t));
+ pm->setTry(std::move(t));
}
});
return f;
}
+template <class T>
+template <class F>
+Future<T> Future<T>::ensure(F func) {
+ MoveWrapper<F> funcw(std::move(func));
+ return this->then([funcw](Try<T>&& t) {
+ (*funcw)();
+ return makeFuture(std::move(t));
+ });
+}
+
template <class T>
template <class F>
Future<T> Future<T>::onTimeout(Duration dur, F&& func, Timekeeper* tk) {
.onError([funcw](TimedOut const&) { return (*funcw)(); });
}
+template <class T>
+template <class F>
+typename std::enable_if<
+ detail::callableWith<F, exception_wrapper>::value &&
+ detail::Extract<F>::ReturnsFuture::value,
+ Future<T>>::type
+Future<T>::onError(F&& func) {
+ static_assert(
+ std::is_same<typename detail::Extract<F>::Return, Future<T>>::value,
+ "Return type of onError callback must be T or Future<T>");
+
+ Promise<T> p;
+ auto f = p.getFuture();
+ auto pm = folly::makeMoveWrapper(std::move(p));
+ auto funcm = folly::makeMoveWrapper(std::move(func));
+ setCallback_([pm, funcm](Try<T> t) mutable {
+ if (t.hasException()) {
+ try {
+ auto f2 = (*funcm)(std::move(t.exception()));
+ f2.setCallback_([pm](Try<T> t2) mutable {
+ pm->setTry(std::move(t2));
+ });
+ } catch (const std::exception& e2) {
+ pm->setException(exception_wrapper(std::current_exception(), e2));
+ } catch (...) {
+ pm->setException(exception_wrapper(std::current_exception()));
+ }
+ } else {
+ pm->setTry(std::move(t));
+ }
+ });
+
+ return f;
+}
+
+// onError(exception_wrapper) that returns T
+template <class T>
+template <class F>
+typename std::enable_if<
+ detail::callableWith<F, exception_wrapper>::value &&
+ !detail::Extract<F>::ReturnsFuture::value,
+ Future<T>>::type
+Future<T>::onError(F&& func) {
+ static_assert(
+ std::is_same<typename detail::Extract<F>::Return, Future<T>>::value,
+ "Return type of onError callback must be T or Future<T>");
+
+ Promise<T> p;
+ auto f = p.getFuture();
+ auto pm = folly::makeMoveWrapper(std::move(p));
+ auto funcm = folly::makeMoveWrapper(std::move(func));
+ setCallback_([pm, funcm](Try<T> t) mutable {
+ if (t.hasException()) {
+ pm->setWith([&]{
+ return (*funcm)(std::move(t.exception()));
+ });
+ } else {
+ pm->setTry(std::move(t));
+ }
+ });
+
+ return f;
+}
+
template <class T>
typename std::add_lvalue_reference<T>::type Future<T>::value() {
throwIfInvalid();
}
template <class T>
-template <typename Executor>
+Optional<Try<T>> Future<T>::poll() {
+ Optional<Try<T>> o;
+ if (core_->ready()) {
+ o = std::move(core_->getTry());
+ }
+ return o;
+}
+
+template <class T>
inline Future<T> Future<T>::via(Executor* executor) && {
throwIfInvalid();
}
template <class T>
-template <typename Executor>
inline Future<T> Future<T>::via(Executor* executor) & {
throwIfInvalid();
MoveWrapper<Promise<T>> p;
auto f = p->getFuture();
- then([p](Try<T>&& t) mutable { p->fulfilTry(std::move(t)); });
+ then([p](Try<T>&& t) mutable { p->setTry(std::move(t)); });
return std::move(f).via(executor);
}
}
template <class F>
-auto makeFutureTry(
+auto makeFutureWith(
F&& func,
typename std::enable_if<!std::is_reference<F>::value, bool>::type sdf)
-> Future<decltype(func())> {
Promise<decltype(func())> p;
- p.fulfil(
+ p.setWith(
[&func]() {
return (func)();
});
}
template <class F>
-auto makeFutureTry(F const& func) -> Future<decltype(func())> {
+auto makeFutureWith(F const& func) -> Future<decltype(func())> {
F copy = func;
- return makeFutureTry(std::move(copy));
+ return makeFutureWith(std::move(copy));
}
template <class T>
template <class T>
Future<T> makeFuture(Try<T>&& t) {
Promise<typename std::decay<T>::type> p;
- p.fulfilTry(std::move(t));
+ p.setTry(std::move(t));
return p.getFuture();
}
}
// via
-template <typename Executor>
-Future<void> via(Executor* executor) {
+inline Future<void> via(Executor* executor) {
return makeFuture().via(executor);
}
template <typename... Fs>
typename detail::VariadicContext<
typename std::decay<Fs>::type::value_type...>::type
-whenAll(Fs&&... fs)
-{
+collectAll(Fs&&... fs) {
auto ctx =
new detail::VariadicContext<typename std::decay<Fs>::type::value_type...>();
ctx->total = sizeof...(fs);
auto f_saved = ctx->p.getFuture();
- detail::whenAllVariadicHelper(ctx,
+ detail::collectAllVariadicHelper(ctx,
std::forward<typename std::decay<Fs>::type>(fs)...);
return f_saved;
}
Future<
std::vector<
Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
-whenAll(InputIterator first, InputIterator last)
-{
+collectAll(InputIterator first, InputIterator last) {
typedef
typename std::iterator_traits<InputIterator>::value_type::value_type T;
for (size_t i = 0; first != last; ++first, ++i) {
assert(i < n);
auto& f = *first;
- f.setCallback_([ctx, i, n](Try<T>&& t) {
- ctx->results[i] = std::move(t);
- if (++ctx->count == n) {
- ctx->p.setValue(std::move(ctx->results));
- delete ctx;
+ f.setCallback_([ctx, i, n](Try<T> t) {
+ ctx->results[i] = std::move(t);
+ if (++ctx->count == n) {
+ ctx->p.setValue(std::move(ctx->results));
+ delete ctx;
+ }
+ });
+ }
+
+ return f_saved;
+}
+
+namespace detail {
+
+template <class, class, typename = void> struct CollectContextHelper;
+
+template <class T, class VecT>
+struct CollectContextHelper<T, VecT,
+ typename std::enable_if<std::is_same<T, VecT>::value>::type> {
+ static inline std::vector<T>&& getResults(std::vector<VecT>& results) {
+ return std::move(results);
+ }
+};
+
+template <class T, class VecT>
+struct CollectContextHelper<T, VecT,
+ typename std::enable_if<!std::is_same<T, VecT>::value>::type> {
+ static inline std::vector<T> getResults(std::vector<VecT>& results) {
+ std::vector<T> finalResults;
+ finalResults.reserve(results.size());
+ for (auto& opt : results) {
+ finalResults.push_back(std::move(opt.value()));
+ }
+ return finalResults;
+ }
+};
+
+template <typename T>
+struct CollectContext {
+
+ typedef typename std::conditional<
+ std::is_default_constructible<T>::value,
+ T,
+ Optional<T>
+ >::type VecT;
+
+ explicit CollectContext(int n) : count(0), success_count(0), threw(false) {
+ results.resize(n);
+ }
+
+ Promise<std::vector<T>> p;
+ std::vector<VecT> results;
+ std::atomic<size_t> count, success_count;
+ std::atomic_bool threw;
+
+ typedef std::vector<T> result_type;
+
+ static inline Future<std::vector<T>> makeEmptyFuture() {
+ return makeFuture(std::vector<T>());
+ }
+
+ inline void setValue() {
+ p.setValue(CollectContextHelper<T, VecT>::getResults(results));
+ }
+
+ inline void addResult(int i, Try<T>& t) {
+ results[i] = std::move(t.value());
+ }
+};
+
+template <>
+struct CollectContext<void> {
+
+ explicit CollectContext(int n) : count(0), success_count(0), threw(false) {}
+
+ Promise<void> p;
+ std::atomic<size_t> count, success_count;
+ std::atomic_bool threw;
+
+ typedef void result_type;
+
+ static inline Future<void> makeEmptyFuture() {
+ return makeFuture();
+ }
+
+ inline void setValue() {
+ p.setValue();
+ }
+
+ inline void addResult(int i, Try<void>& t) {
+ // do nothing
+ }
+};
+
+} // detail
+
+template <class InputIterator>
+Future<typename detail::CollectContext<
+ typename std::iterator_traits<InputIterator>::value_type::value_type
+>::result_type>
+collect(InputIterator first, InputIterator last) {
+ typedef
+ typename std::iterator_traits<InputIterator>::value_type::value_type T;
+
+ if (first >= last) {
+ return detail::CollectContext<T>::makeEmptyFuture();
+ }
+
+ size_t n = std::distance(first, last);
+ auto ctx = new detail::CollectContext<T>(n);
+ auto f_saved = ctx->p.getFuture();
+
+ for (size_t i = 0; first != last; ++first, ++i) {
+ assert(i < n);
+ auto& f = *first;
+ f.setCallback_([ctx, i, n](Try<T> t) {
+
+ if (t.hasException()) {
+ if (!ctx->threw.exchange(true)) {
+ ctx->p.setException(std::move(t.exception()));
}
- });
+ } else if (!ctx->threw) {
+ ctx->addResult(i, t);
+ if (++ctx->success_count == n) {
+ ctx->setValue();
+ }
+ }
+
+ if (++ctx->count == n) {
+ delete ctx;
+ }
+ });
}
return f_saved;
Try<
typename
std::iterator_traits<InputIterator>::value_type::value_type> > >
-whenAny(InputIterator first, InputIterator last) {
+collectAny(InputIterator first, InputIterator last) {
typedef
typename std::iterator_traits<InputIterator>::value_type::value_type T;
template <class InputIterator>
Future<std::vector<std::pair<size_t, Try<typename
std::iterator_traits<InputIterator>::value_type::value_type>>>>
-whenN(InputIterator first, InputIterator last, size_t n) {
+collectN(InputIterator first, InputIterator last, size_t n) {
typedef typename
std::iterator_traits<InputIterator>::value_type::value_type T;
typedef std::vector<std::pair<size_t, Try<T>>> V;
ctx->completed = 0;
// for each completed Future, increase count and add to vector, until we
- // have n completed futures at which point we fulfil our Promise with the
+ // have n completed futures at which point we fulfill our Promise with the
// vector
auto it = first;
size_t i = 0;
assert(ctx->v.size() < n);
v.push_back(std::make_pair(i, std::move(t)));
if (c == n) {
- ctx->p.fulfilTry(Try<V>(std::move(v)));
+ ctx->p.setTry(Try<V>(std::move(v)));
}
}
});
return ctx->p.getFuture();
}
-namespace {
- template <class T>
- void getWaitHelper(Future<T>* f) {
- // If we already have a value do the cheap thing
- if (f->isReady()) {
- return;
- }
-
- folly::Baton<> baton;
- f->then([&](Try<T> const&) {
- baton.post();
- });
- baton.wait();
+template <class It, class T, class F>
+Future<T> reduce(It first, It last, T&& initial, F&& func) {
+ if (first == last) {
+ return makeFuture(std::move(initial));
}
- template <class T>
- Future<T> getWaitTimeoutHelper(Future<T>* f, Duration dur) {
- // TODO make and use variadic whenAny #5877971
- Promise<T> p;
- auto token = std::make_shared<std::atomic<bool>>();
- folly::Baton<> baton;
-
- folly::detail::getTimekeeperSingleton()->after(dur)
- .then([&,token](Try<void> const& t) {
- if (token->exchange(true) == false) {
- if (t.hasException()) {
- p.setException(std::move(t.exception()));
- } else {
- p.setException(TimedOut());
- }
- baton.post();
- }
- });
+ typedef typename std::iterator_traits<It>::value_type::value_type ItT;
+ typedef typename std::conditional<
+ detail::callableWith<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type Arg;
+ typedef isTry<Arg> IsTry;
- f->then([&, token](Try<T>&& t) {
- if (token->exchange(true) == false) {
- p.fulfilTry(std::move(t));
- baton.post();
- }
- });
+ folly::MoveWrapper<T> minitial(std::move(initial));
+ auto sfunc = std::make_shared<F>(std::move(func));
- baton.wait();
- return p.getFuture();
- }
-}
-
-template <class T>
-T Future<T>::get() {
- getWaitHelper(this);
-
- // Big assumption here: the then() call above, since it doesn't move out
- // the value, leaves us with a value to return here. This would be a big
- // no-no in user code, but I'm invoking internal developer privilege. This
- // is slightly more efficient (save a move()) especially if there's an
- // exception (save a throw).
- return std::move(value());
-}
-
-template <>
-inline void Future<void>::get() {
- getWaitHelper(this);
- value();
-}
+ auto f = first->then([minitial, sfunc](Try<ItT>& head) mutable {
+ return (*sfunc)(std::move(*minitial),
+ head.template get<IsTry::value, Arg&&>());
+ });
-template <class T>
-T Future<T>::get(Duration dur) {
- return std::move(getWaitTimeoutHelper(this, dur).value());
-}
+ for (++first; first != last; ++first) {
+ f = collectAll(f, *first).then([sfunc](std::tuple<Try<T>, Try<ItT>>& t) {
+ return (*sfunc)(std::move(std::get<0>(t).value()),
+ // Either return a ItT&& or a Try<ItT>&& depending
+ // on the type of the argument of func.
+ std::get<1>(t).template get<IsTry::value, Arg&&>());
+ });
+ }
-template <>
-inline void Future<void>::get(Duration dur) {
- getWaitTimeoutHelper(this, dur).value();
+ return f;
}
template <class T>
-T Future<T>::getVia(DrivableExecutor* e) {
- while (!isReady()) {
- e->drive();
- }
- return std::move(value());
-}
-
-template <>
-inline void Future<void>::getVia(DrivableExecutor* e) {
- while (!isReady()) {
- e->drive();
- }
- value();
+template <class I, class F>
+Future<I> Future<T>::reduce(I&& initial, F&& func) {
+ folly::MoveWrapper<I> minitial(std::move(initial));
+ folly::MoveWrapper<F> mfunc(std::move(func));
+ return then([minitial, mfunc](T& vals) mutable {
+ auto ret = std::move(*minitial);
+ for (auto& val : vals) {
+ ret = (*mfunc)(std::move(ret), std::move(val));
+ }
+ return ret;
+ });
}
template <class T>
this->then([ctx](Try<T>&& t) {
if (ctx->token.exchange(true) == false) {
- ctx->promise.fulfilTry(std::move(t));
+ ctx->promise.setTry(std::move(t));
}
});
template <class T>
Future<T> Future<T>::delayed(Duration dur, Timekeeper* tk) {
- return whenAll(*this, futures::sleep(dur, tk))
+ return collectAll(*this, futures::sleep(dur, tk))
.then([](std::tuple<Try<T>, Try<void>> tup) {
Try<T>& t = std::get<0>(tup);
return makeFuture<T>(std::move(t));
template <class T>
void waitImpl(Future<T>& f) {
- Baton<> baton;
+ // short-circuit if there's nothing to do
+ if (f.isReady()) return;
+
+ folly::fibers::Baton baton;
f = f.then([&](Try<T> t) {
baton.post();
return makeFuture(std::move(t));
});
baton.wait();
+
// There's a race here between the return here and the actual finishing of
// the future. f is completed, but the setup may not have finished on done
// after the baton has posted.
template <class T>
void waitImpl(Future<T>& f, Duration dur) {
- auto baton = std::make_shared<Baton<>>();
+ // short-circuit if there's nothing to do
+ if (f.isReady()) return;
+
+ auto baton = std::make_shared<folly::fibers::Baton>();
f = f.then([baton](Try<T> t) {
baton->post();
return makeFuture(std::move(t));
});
+
// Let's preserve the invariant that if we did not timeout (timed_wait returns
// true), then the returned Future is complete when it is returned to the
// caller. We need to wait out the race for that Future to complete.
- if (baton->timed_wait(std::chrono::system_clock::now() + dur)) {
+ if (baton->timed_wait(dur)) {
while (!f.isReady()) {
std::this_thread::yield();
}
return std::move(*this);
}
-namespace futures {
+template <class T>
+T Future<T>::get() {
+ return std::move(wait().value());
+}
+
+template <>
+inline void Future<void>::get() {
+ wait().value();
+}
+
+template <class T>
+T Future<T>::get(Duration dur) {
+ wait(dur);
+ if (isReady()) {
+ return std::move(value());
+ } else {
+ throw TimedOut();
+ }
+}
+
+template <>
+inline void Future<void>::get(Duration dur) {
+ wait(dur);
+ if (isReady()) {
+ return;
+ } else {
+ throw TimedOut();
+ }
+}
+
+template <class T>
+T Future<T>::getVia(DrivableExecutor* e) {
+ return std::move(waitVia(e).value());
+}
+template <>
+inline void Future<void>::getVia(DrivableExecutor* e) {
+ waitVia(e).value();
+}
+
+namespace detail {
+ template <class T>
+ struct TryEquals {
+ static bool equals(const Try<T>& t1, const Try<T>& t2) {
+ return t1.value() == t2.value();
+ }
+ };
+
+ template <>
+ struct TryEquals<void> {
+ static bool equals(const Try<void>& t1, const Try<void>& t2) {
+ return true;
+ }
+ };
+}
+
+template <class T>
+Future<bool> Future<T>::willEqual(Future<T>& f) {
+ return collectAll(*this, f).then([](const std::tuple<Try<T>, Try<T>>& t) {
+ if (std::get<0>(t).hasValue() && std::get<1>(t).hasValue()) {
+ return detail::TryEquals<T>::equals(std::get<0>(t), std::get<1>(t));
+ } else {
+ return false;
+ }
+ });
+}
+
+template <class T>
+template <class F>
+Future<T> Future<T>::filter(F predicate) {
+ auto p = folly::makeMoveWrapper(std::move(predicate));
+ return this->then([p](T val) {
+ T const& valConstRef = val;
+ if (!(*p)(valConstRef)) {
+ throw PredicateDoesNotObtain();
+ }
+ return val;
+ });
+}
+
+namespace futures {
namespace {
template <class Z>
Future<Z> chainHelper(Future<Z> f) {
MoveWrapper<Promise<A>> pw;
MoveWrapper<Future<Z>> fw(chainHelper<Z>(pw->getFuture(), fns...));
return [=](Try<A> t) mutable {
- pw->fulfilTry(std::move(t));
+ pw->setTry(std::move(t));
return std::move(*fw);
};
}
+ template <class It, class F, class ItT, class Result>
+ std::vector<Future<Result>> map(It first, It last, F func) {
+ std::vector<Future<Result>> results;
+ for (auto it = first; it != last; it++) {
+ results.push_back(it->then(func));
+ }
+ return results;
+ }
}
+// Instantiate the most common Future types to save compile time
+extern template class Future<void>;
+extern template class Future<bool>;
+extern template class Future<int>;
+extern template class Future<int64_t>;
+extern template class Future<std::string>;
+extern template class Future<double>;
+
} // namespace folly
// I haven't included a Future<T&> specialization because I don't forsee us