Do not construct a Future<T> from a Future<Something> value
[folly.git] / folly / futures / Future-inl.h
index 2e942303e2b4b359f8bcc4c109470b3152be3010..927a3142b8ed94a056b3d3f8beac50359d039878 100644 (file)
@@ -19,7 +19,7 @@
 #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>
@@ -44,30 +44,21 @@ Future<T>& Future<T>::operator=(Future<T>&& other) noexcept {
 }
 
 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();
 }
@@ -171,7 +162,7 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, Args...>) {
       if (!isTry && t.hasException()) {
         p->setException(std::move(t.exception()));
       } else {
-        p->fulfil([&]() {
+        p->setWith([&]() {
           return (*funcm)(t.template get<isTry, Args>()...);
         });
       }
@@ -210,7 +201,7 @@ Future<T>::thenImplementation(F func, detail::argResult<isTry, F, 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));
@@ -235,6 +226,19 @@ Future<T>::then(R(Caller::*func)(Args...), Caller *instance) {
   });
 }
 
+// TODO(6838553)
+#ifndef __clang__
+template <class T>
+template <class... Args>
+auto Future<T>::then(Executor* x, Args&&... args)
+  -> decltype(this->then(std::forward<Args>(args)...))
+{
+  auto oldX = getExecutor();
+  setExecutor(x);
+  return this->then(std::forward<Args>(args)...).via(oldX);
+}
+#endif
+
 template <class T>
 Future<void> Future<T>::then() {
   return then([] (Try<T>&& t) {});
@@ -244,6 +248,7 @@ Future<void> Future<T>::then() {
 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) {
@@ -258,11 +263,11 @@ 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));
     }
   });
 
@@ -273,6 +278,7 @@ Future<T>::onError(F&& func) {
 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) {
@@ -290,7 +296,7 @@ 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));
@@ -298,7 +304,7 @@ Future<T>::onError(F&& func) {
             pm->setException(exception_wrapper(std::current_exception()));
           }
         })) {
-      pm->fulfilTry(std::move(t));
+      pm->setTry(std::move(t));
     }
   });
 
@@ -323,6 +329,70 @@ 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();
@@ -370,7 +440,7 @@ inline Future<T> Future<T>::via(Executor* executor) & {
 
   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);
 }
 
@@ -402,12 +472,12 @@ Future<void> makeFuture() {
 }
 
 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)();
     });
@@ -415,9 +485,9 @@ auto makeFutureTry(
 }
 
 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>
@@ -446,7 +516,7 @@ makeFuture(E const& e) {
 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();
 }
 
@@ -470,13 +540,12 @@ Future<void> via(Executor* 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;
 }
@@ -487,8 +556,7 @@ template <class InputIterator>
 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;
 
@@ -506,13 +574,139 @@ whenAll(InputIterator first, InputIterator last)
   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), threw(false) {
+    results.resize(n);
+  }
+
+  Promise<std::vector<T>> p;
+  std::vector<VecT> results;
+  std::atomic<size_t> 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), threw(false) {}
+
+  Promise<void> p;
+  std::atomic<size_t> 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) {
+       auto c = ++ctx->count;
+
+       if (t.hasException()) {
+         if (!ctx->threw.exchange(true)) {
+           ctx->p.setException(std::move(t.exception()));
          }
-       });
+       } else if (!ctx->threw) {
+         ctx->addResult(i, t);
+         if (c == n) {
+           ctx->setValue();
+         }
+       }
+
+       if (c == n) {
+         delete ctx;
+       }
+     });
   }
 
   return f_saved;
@@ -524,7 +718,7 @@ Future<
             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;
 
@@ -547,7 +741,7 @@ whenAny(InputIterator first, InputIterator last) {
 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;
@@ -561,7 +755,7 @@ whenN(InputIterator first, InputIterator last, size_t n) {
   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;
@@ -573,7 +767,7 @@ whenN(InputIterator first, InputIterator last, size_t n) {
         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)));
         }
       }
     });
@@ -589,6 +783,53 @@ whenN(InputIterator first, InputIterator last, size_t n) {
   return ctx->p.getFuture();
 }
 
+template <class It, class T, class F, class ItT, class Arg>
+typename std::enable_if<!isFutureResult<F, T, Arg>::value, Future<T>>::type
+reduce(It first, It last, T initial, F func) {
+  if (first == last) {
+    return makeFuture(std::move(initial));
+  }
+
+  typedef isTry<Arg> IsTry;
+
+  return collectAll(first, last)
+    .then([initial, func](std::vector<Try<ItT>>& vals) mutable {
+      for (auto& val : vals) {
+        initial = func(std::move(initial),
+                       // Either return a ItT&& or a Try<ItT>&& depending
+                       // on the type of the argument of func.
+                       val.template get<IsTry::value, Arg&&>());
+      }
+      return initial;
+    });
+}
+
+template <class It, class T, class F, class ItT, class Arg>
+typename std::enable_if<isFutureResult<F, T, Arg>::value, Future<T>>::type
+reduce(It first, It last, T initial, F func) {
+  if (first == last) {
+    return makeFuture(std::move(initial));
+  }
+
+  typedef isTry<Arg> IsTry;
+
+  auto f = first->then([initial, func](Try<ItT>& head) mutable {
+    return func(std::move(initial),
+                head.template get<IsTry::value, Arg&&>());
+  });
+
+  for (++first; first != last; ++first) {
+    f = collectAll(f, *first).then([func](std::tuple<Try<T>, Try<ItT>>& t) {
+      return func(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&&>());
+    });
+  }
+
+  return f;
+}
+
 template <class T>
 Future<T> Future<T>::within(Duration dur, Timekeeper* tk) {
   return within(dur, TimedOut(), tk);
@@ -623,7 +864,7 @@ Future<T> Future<T>::within(Duration dur, E e, Timekeeper* tk) {
 
   this->then([ctx](Try<T>&& t) {
     if (ctx->token.exchange(true) == false) {
-      ctx->promise.fulfilTry(std::move(t));
+      ctx->promise.setTry(std::move(t));
     }
   });
 
@@ -632,7 +873,7 @@ Future<T> Future<T>::within(Duration dur, E e, Timekeeper* tk) {
 
 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));
@@ -646,7 +887,7 @@ void waitImpl(Future<T>& f) {
   // short-circuit if there's nothing to do
   if (f.isReady()) return;
 
-  Baton<> baton;
+  folly::fibers::Baton baton;
   f = f.then([&](Try<T> t) {
     baton.post();
     return makeFuture(std::move(t));
@@ -666,7 +907,7 @@ void waitImpl(Future<T>& f, Duration dur) {
   // short-circuit if there's nothing to do
   if (f.isReady()) return;
 
-  auto baton = std::make_shared<Baton<>>();
+  auto baton = std::make_shared<folly::fibers::Baton>();
   f = f.then([baton](Try<T> t) {
     baton->post();
     return makeFuture(std::move(t));
@@ -675,7 +916,7 @@ void waitImpl(Future<T>& f, Duration dur) {
   // 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();
     }
@@ -769,7 +1010,7 @@ inline void Future<void>::getVia(DrivableExecutor* e) {
 
 template <class T>
 Future<bool> Future<T>::willEqual(Future<T>& f) {
-  return whenAll(*this, f).then([](const std::tuple<Try<T>, Try<T>>& t) {
+  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 std::get<0>(t).value() == std::get<1>(t).value();
     } else {
@@ -778,6 +1019,19 @@ Future<bool> Future<T>::willEqual(Future<T>& f) {
   });
 }
 
+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>
@@ -797,11 +1051,19 @@ namespace futures {
     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;
+  }
 }
 
 } // namespace folly