Really fix the clang warning in Format-inl.h
[folly.git] / folly / wangle / Future.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <algorithm>
20 #include <exception>
21 #include <functional>
22 #include <memory>
23 #include <type_traits>
24 #include <vector>
25
26 #include <folly/MoveWrapper.h>
27 #include <folly/wangle/Promise.h>
28 #include <folly/wangle/Try.h>
29
30 namespace folly { namespace wangle {
31
32 namespace detail {
33   template <class> struct Core;
34   template <class...> struct VariadicContext;
35 }
36 template <class> struct Promise;
37
38 template <typename T> struct isFuture;
39
40 template <class T>
41 class Future {
42  public:
43   typedef T value_type;
44
45   // not copyable
46   Future(Future const&) = delete;
47   Future& operator=(Future const&) = delete;
48
49   // movable
50   Future(Future&&) noexcept;
51   Future& operator=(Future&&);
52
53   ~Future();
54
55   /** Return the reference to result. Should not be called if !isReady().
56     Will rethrow the exception if an exception has been
57     captured.
58
59     This function is not thread safe - the returned Future can only
60     be executed from the thread that the executor runs it in.
61     See below for a thread safe version
62     */
63   typename std::add_lvalue_reference<T>::type
64   value();
65   typename std::add_lvalue_reference<const T>::type
66   value() const;
67
68   /// Returns an inactive Future which will call back on the other side of
69   /// executor (when it is activated).
70   ///
71   /// NB remember that Futures activate when they destruct. This is good,
72   /// it means that this will work:
73   ///
74   ///   f.via(e).then(a).then(b);
75   ///
76   /// a and b will execute in the same context (the far side of e), because
77   /// the Future (temporary variable) created by via(e) does not call back
78   /// until it destructs, which is after then(a) and then(b) have been wired
79   /// up.
80   ///
81   /// But this is still racy:
82   ///
83   ///   f = f.via(e).then(a);
84   ///   f.then(b);
85   ///
86   /// If you need something like that, use a Later.
87   template <typename Executor>
88   Future<T> via(Executor* executor);
89
90   /** True when the result (or exception) is ready. */
91   bool isReady() const;
92
93   /** A reference to the Try of the value */
94   Try<T>& getTry();
95
96   /** When this Future has completed, execute func which is a function that
97     takes a Try<T>&&. A Future for the return type of func is
98     returned. e.g.
99
100     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
101
102     The Future given to the functor is ready, and the functor may call
103     value(), which may rethrow if this has captured an exception. If func
104     throws, the exception will be captured in the Future that is returned.
105     */
106   /* TODO n3428 and other async frameworks have something like then(scheduler,
107      Future), we might want to support a similar API which could be
108      implemented a little more efficiently than
109      f.via(executor).then(callback) */
110   template <class F>
111   typename std::enable_if<
112     !isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
113     Future<typename std::result_of<F(Try<T>&&)>::type> >::type
114   then(F&& func);
115
116   /// Variant where func returns a Future<T> instead of a T. e.g.
117   ///
118   ///   Future<string> f2 = f1.then(
119   ///     [](Try<T>&&) { return makeFuture<string>("foo"); });
120   template <class F>
121   typename std::enable_if<
122     isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
123     Future<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
124   then(F&& func);
125
126   /// Variant where func is an ordinary function (static method, method)
127   ///
128   ///   R doWork(Try<T>&&);
129   ///
130   ///   Future<R> f2 = f1.then(doWork);
131   ///
132   /// or
133   ///
134   ///   struct Worker {
135   ///     static R doWork(Try<T>&&); }
136   ///
137   ///   Future<R> f2 = f1.then(&Worker::doWork);
138   template <class = T, class R = std::nullptr_t>
139   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
140   inline then(R(*func)(Try<T>&&)) {
141     return then([func](Try<T>&& t) {
142       return (*func)(std::move(t));
143     });
144   }
145
146   /// Variant where func returns a Future<R> instead of a R. e.g.
147   ///
148   ///   struct Worker {
149   ///     Future<R> doWork(Try<T>&&); }
150   ///
151   ///   Future<R> f2 = f1.then(&Worker::doWork);
152   template <class = T, class R = std::nullptr_t>
153   typename std::enable_if<isFuture<R>::value, R>::type
154   inline then(R(*func)(Try<T>&&)) {
155     return then([func](Try<T>&& t) {
156       return (*func)(std::move(t));
157     });
158   }
159
160   /// Variant where func is an member function
161   ///
162   ///   struct Worker {
163   ///     R doWork(Try<T>&&); }
164   ///
165   ///   Worker *w;
166   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
167   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
168   typename std::enable_if<!isFuture<R>::value, Future<R>>::type
169   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
170     return then([instance, func](Try<T>&& t) {
171       return (instance->*func)(std::move(t));
172     });
173   }
174
175   /// Variant where func returns a Future<R> instead of a R. e.g.
176   ///
177   ///   struct Worker {
178   ///     Future<R> doWork(Try<T>&&); }
179   ///
180   ///   Worker *w;
181   ///   Future<R> f2 = f1.then(w, &Worker::doWork);
182   template <class = T, class R = std::nullptr_t, class Caller = std::nullptr_t>
183   typename std::enable_if<isFuture<R>::value, R>::type
184   inline then(Caller *instance, R(Caller::*func)(Try<T>&&)) {
185     return then([instance, func](Try<T>&& t) {
186       return (instance->*func)(std::move(t));
187     });
188   }
189
190   /// Convenience method for ignoring the value and creating a Future<void>.
191   /// Exceptions still propagate.
192   Future<void> then();
193
194   /// This is not the method you're looking for.
195   ///
196   /// This needs to be public because it's used by make* and when*, and it's
197   /// not worth listing all those and their fancy template signatures as
198   /// friends. But it's not for public consumption.
199   template <class F>
200   void setCallback_(F&& func);
201
202   /// A Future's callback is executed when all three of these conditions have
203   /// become true: it has a value (set by the Promise), it has a callback (set
204   /// by then), and it is active (active by default).
205   ///
206   /// Inactive Futures will activate upon destruction.
207   void activate() {
208     core_->activate();
209   }
210   void deactivate() {
211     core_->deactivate();
212   }
213   bool isActive() {
214     return core_->isActive();
215   }
216
217   template <class E>
218   void raise(E&& exception) {
219     raise(std::make_exception_ptr(std::forward<E>(exception)));
220   }
221
222   /// Raise an interrupt. If the promise holder has an interrupt
223   /// handler it will be called and potentially stop asynchronous work from
224   /// being done. This is advisory only - a promise holder may not set an
225   /// interrupt handler, or may do anything including ignore. But, if you know
226   /// your future supports this the most likely result is stopping or
227   /// preventing the asynchronous operation (if in time), and the promise
228   /// holder setting an exception on the future. (That may happen
229   /// asynchronously, of course.)
230   void raise(std::exception_ptr interrupt);
231
232   void cancel() {
233     raise(FutureCancellation());
234   }
235
236  private:
237   typedef detail::Core<T>* corePtr;
238
239   // shared core state object
240   corePtr core_;
241
242   explicit
243   Future(corePtr obj) : core_(obj) {}
244
245   void detach();
246
247   void throwIfInvalid() const;
248
249   friend class Promise<T>;
250 };
251
252 /**
253   Make a completed Future by moving in a value. e.g.
254
255     string foo = "foo";
256     auto f = makeFuture(std::move(foo));
257
258   or
259
260     auto f = makeFuture<string>("foo");
261 */
262 template <class T>
263 Future<typename std::decay<T>::type> makeFuture(T&& t);
264
265 /** Make a completed void Future. */
266 Future<void> makeFuture();
267
268 /** Make a completed Future by executing a function. If the function throws
269   we capture the exception, otherwise we capture the result. */
270 template <class F>
271 auto makeFutureTry(
272   F&& func,
273   typename std::enable_if<
274     !std::is_reference<F>::value, bool>::type sdf = false)
275   -> Future<decltype(func())>;
276
277 template <class F>
278 auto makeFutureTry(
279   F const& func)
280   -> Future<decltype(func())>;
281
282 /// Make a failed Future from an exception_ptr.
283 /// Because the Future's type cannot be inferred you have to specify it, e.g.
284 ///
285 ///   auto f = makeFuture<string>(std::current_exception());
286 template <class T>
287 Future<T> makeFuture(std::exception_ptr const& e);
288
289 /** Make a Future from an exception type E that can be passed to
290   std::make_exception_ptr(). */
291 template <class T, class E>
292 typename std::enable_if<std::is_base_of<std::exception, E>::value,
293                         Future<T>>::type
294 makeFuture(E const& e);
295
296 /** Make a Future out of a Try */
297 template <class T>
298 Future<T> makeFuture(Try<T>&& t);
299
300 /** When all the input Futures complete, the returned Future will complete.
301   Errors do not cause early termination; this Future will always succeed
302   after all its Futures have finished (whether successfully or with an
303   error).
304
305   The Futures are moved in, so your copies are invalid. If you need to
306   chain further from these Futures, use the variant with an output iterator.
307
308   XXX is this still true?
309   This function is thread-safe for Futures running on different threads.
310
311   The return type for Future<T> input is a Future<std::vector<Try<T>>>
312   */
313 template <class InputIterator>
314 Future<std::vector<Try<
315   typename std::iterator_traits<InputIterator>::value_type::value_type>>>
316 whenAll(InputIterator first, InputIterator last);
317
318 /// This version takes a varying number of Futures instead of an iterator.
319 /// The return type for (Future<T1>, Future<T2>, ...) input
320 /// is a Future<std::tuple<Try<T1>, Try<T2>, ...>>.
321 /// The Futures are moved in, so your copies are invalid.
322 template <typename... Fs>
323 typename detail::VariadicContext<
324   typename std::decay<Fs>::type::value_type...>::type
325 whenAll(Fs&&... fs);
326
327 /** The result is a pair of the index of the first Future to complete and
328   the Try. If multiple Futures complete at the same time (or are already
329   complete when passed in), the "winner" is chosen non-deterministically.
330
331   This function is thread-safe for Futures running on different threads.
332   */
333 template <class InputIterator>
334 Future<std::pair<
335   size_t,
336   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>
337 whenAny(InputIterator first, InputIterator last);
338
339 /** when n Futures have completed, the Future completes with a vector of
340   the index and Try of those n Futures (the indices refer to the original
341   order, but the result vector will be in an arbitrary order)
342
343   Not thread safe.
344   */
345 template <class InputIterator>
346 Future<std::vector<std::pair<
347   size_t,
348   Try<typename std::iterator_traits<InputIterator>::value_type::value_type>>>>
349 whenN(InputIterator first, InputIterator last, size_t n);
350
351 /** Wait for the given future to complete on a semaphore. Returns a completed
352  * future containing the result.
353  *
354  * NB if the promise for the future would be fulfilled in the same thread that
355  * you call this, it will deadlock.
356  */
357 template <class T>
358 Future<T> waitWithSemaphore(Future<T>&& f);
359
360 /** Wait for up to `timeout` for the given future to complete. Returns a future
361  * which may or may not be completed depending whether the given future
362  * completed in time
363  *
364  * Note: each call to this starts a (short-lived) thread and allocates memory.
365  */
366 template <typename T, class Duration>
367 Future<T> waitWithSemaphore(Future<T>&& f, Duration timeout);
368
369 }} // folly::wangle
370
371 #include <folly/wangle/Future-inl.h>