Add element construction/destruction hooks to IndexedMemPool
[folly.git] / folly / futures / Future.h
1 /*
2  * Copyright 2017 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/Optional.h>
27 #include <folly/Portability.h>
28 #include <folly/futures/DrivableExecutor.h>
29 #include <folly/futures/Promise.h>
30 #include <folly/Try.h>
31 #include <folly/futures/FutureException.h>
32 #include <folly/futures/detail/Types.h>
33
34 // boring predeclarations and details
35 #include <folly/futures/Future-pre.h>
36
37 // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
38 // Needs to be included after Future-pre.h and before Future-inl.h
39 #include <folly/futures/helpers.h>
40
41 namespace folly {
42
43 template <class T>
44 class Future {
45  public:
46   typedef T value_type;
47
48   // not copyable
49   Future(Future const&) = delete;
50   Future& operator=(Future const&) = delete;
51
52   // movable
53   Future(Future&&) noexcept;
54   Future& operator=(Future&&) noexcept;
55
56   /// Construct a Future from a value (perfect forwarding)
57   template <class T2 = T, typename =
58             typename std::enable_if<
59               !isFuture<typename std::decay<T2>::type>::value>::type>
60   /* implicit */ Future(T2&& val);
61
62   template <class T2 = T>
63   /* implicit */ Future(
64       typename std::enable_if<std::is_same<Unit, T2>::value>::type* = nullptr);
65
66   ~Future();
67
68   /** Return the reference to result. Should not be called if !isReady().
69     Will rethrow the exception if an exception has been
70     captured.
71     */
72   typename std::add_lvalue_reference<T>::type
73   value();
74   typename std::add_lvalue_reference<const T>::type
75   value() const;
76
77   /// Returns an inactive Future which will call back on the other side of
78   /// executor (when it is activated).
79   ///
80   /// NB remember that Futures activate when they destruct. This is good,
81   /// it means that this will work:
82   ///
83   ///   f.via(e).then(a).then(b);
84   ///
85   /// a and b will execute in the same context (the far side of e), because
86   /// the Future (temporary variable) created by via(e) does not call back
87   /// until it destructs, which is after then(a) and then(b) have been wired
88   /// up.
89   ///
90   /// But this is still racy:
91   ///
92   ///   f = f.via(e).then(a);
93   ///   f.then(b);
94   // The ref-qualifier allows for `this` to be moved out so we
95   // don't get access-after-free situations in chaining.
96   // https://akrzemi1.wordpress.com/2014/06/02/ref-qualifiers/
97   inline Future<T> via(
98       Executor* executor,
99       int8_t priority = Executor::MID_PRI) &&;
100
101   /// This variant creates a new future, where the ref-qualifier && version
102   /// moves `this` out. This one is less efficient but avoids confusing users
103   /// when "return f.via(x);" fails.
104   inline Future<T> via(
105       Executor* executor,
106       int8_t priority = Executor::MID_PRI) &;
107
108   /** True when the result (or exception) is ready. */
109   bool isReady() const;
110
111   /// sugar for getTry().hasValue()
112   bool hasValue();
113
114   /// sugar for getTry().hasException()
115   bool hasException();
116
117   /** A reference to the Try of the value */
118   Try<T>& getTry();
119
120   /// Call e->drive() repeatedly until the future is fulfilled. Examples
121   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
122   /// reference to the Try of the value.
123   Try<T>& getTryVia(DrivableExecutor* e);
124
125   /// If the promise has been fulfilled, return an Optional with the Try<T>.
126   /// Otherwise return an empty Optional.
127   /// Note that this moves the Try<T> out.
128   Optional<Try<T>> poll();
129
130   /// Block until the future is fulfilled. Returns the value (moved out), or
131   /// throws the exception. The future must not already have a callback.
132   T get();
133
134   /// Block until the future is fulfilled, or until timed out. Returns the
135   /// value (moved out), or throws the exception (which might be a TimedOut
136   /// exception).
137   T get(Duration dur);
138
139   /// Call e->drive() repeatedly until the future is fulfilled. Examples
140   /// of DrivableExecutor include EventBase and ManualExecutor. Returns the
141   /// value (moved out), or throws the exception.
142   T getVia(DrivableExecutor* e);
143
144   /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
145   /// Future<T> instance.
146   template <class F = T>
147   typename std::enable_if<isFuture<F>::value,
148                           Future<typename isFuture<T>::Inner>>::type
149   unwrap();
150
151   /** When this Future has completed, execute func which is a function that
152     takes one of:
153       (const) Try<T>&&
154       (const) Try<T>&
155       (const) Try<T>
156       (const) T&&
157       (const) T&
158       (const) T
159       (void)
160
161     Func shall return either another Future or a value.
162
163     A Future for the return type of func is returned.
164
165     Future<string> f2 = f1.then([](Try<T>&&) { return string("foo"); });
166
167     The Future given to the functor is ready, and the functor may call
168     value(), which may rethrow if this has captured an exception. If func
169     throws, the exception will be captured in the Future that is returned.
170     */
171   // gcc 4.8 requires that we cast function reference types to function pointer
172   // types. Fore more details see the comment on FunctionReferenceToPointer
173   // in Future-pre.h.
174   // gcc versions 4.9 and above (as well as clang) do not require this hack.
175   // For those, the FF tenplate parameter can be removed and occurences of FF
176   // replaced with F.
177   template <
178       typename F,
179       typename FF = typename detail::FunctionReferenceToPointer<F>::type,
180       typename R = detail::callableResult<T, FF>>
181   typename R::Return then(F&& func) {
182     typedef typename R::Arg Arguments;
183     return thenImplementation<FF, R>(std::forward<FF>(func), Arguments());
184   }
185
186   /// Variant where func is an member function
187   ///
188   ///   struct Worker { R doWork(Try<T>); }
189   ///
190   ///   Worker *w;
191   ///   Future<R> f2 = f1.then(&Worker::doWork, w);
192   ///
193   /// This is just sugar for
194   ///
195   ///   f1.then(std::bind(&Worker::doWork, w));
196   template <typename R, typename Caller, typename... Args>
197   Future<typename isFuture<R>::Inner>
198   then(R(Caller::*func)(Args...), Caller *instance);
199
200   /// Execute the callback via the given Executor. The executor doesn't stick.
201   ///
202   /// Contrast
203   ///
204   ///   f.via(x).then(b).then(c)
205   ///
206   /// with
207   ///
208   ///   f.then(x, b).then(c)
209   ///
210   /// In the former both b and c execute via x. In the latter, only b executes
211   /// via x, and c executes via the same executor (if any) that f had.
212   template <class Executor, class Arg, class... Args>
213   auto then(Executor* x, Arg&& arg, Args&&... args)
214     -> decltype(this->then(std::forward<Arg>(arg),
215                            std::forward<Args>(args)...));
216
217   /// Convenience method for ignoring the value and creating a Future<Unit>.
218   /// Exceptions still propagate.
219   Future<Unit> then();
220
221   /// Set an error callback for this Future. The callback should take a single
222   /// argument of the type that you want to catch, and should return a value of
223   /// the same type as this Future, or a Future of that type (see overload
224   /// below). For instance,
225   ///
226   /// makeFuture()
227   ///   .then([] {
228   ///     throw std::runtime_error("oh no!");
229   ///     return 42;
230   ///   })
231   ///   .onError([] (std::runtime_error& e) {
232   ///     LOG(INFO) << "std::runtime_error: " << e.what();
233   ///     return -1; // or makeFuture<int>(-1)
234   ///   });
235   template <class F>
236   typename std::enable_if<
237     !detail::callableWith<F, exception_wrapper>::value &&
238     !detail::Extract<F>::ReturnsFuture::value,
239     Future<T>>::type
240   onError(F&& func);
241
242   /// Overload of onError where the error callback returns a Future<T>
243   template <class F>
244   typename std::enable_if<
245     !detail::callableWith<F, exception_wrapper>::value &&
246     detail::Extract<F>::ReturnsFuture::value,
247     Future<T>>::type
248   onError(F&& func);
249
250   /// Overload of onError that takes exception_wrapper and returns Future<T>
251   template <class F>
252   typename std::enable_if<
253     detail::callableWith<F, exception_wrapper>::value &&
254     detail::Extract<F>::ReturnsFuture::value,
255     Future<T>>::type
256   onError(F&& func);
257
258   /// Overload of onError that takes exception_wrapper and returns T
259   template <class F>
260   typename std::enable_if<
261     detail::callableWith<F, exception_wrapper>::value &&
262     !detail::Extract<F>::ReturnsFuture::value,
263     Future<T>>::type
264   onError(F&& func);
265
266   /// func is like std::function<void()> and is executed unconditionally, and
267   /// the value/exception is passed through to the resulting Future.
268   /// func shouldn't throw, but if it does it will be captured and propagated,
269   /// and discard any value/exception that this Future has obtained.
270   template <class F>
271   Future<T> ensure(F&& func);
272
273   /// Like onError, but for timeouts. example:
274   ///
275   ///   Future<int> f = makeFuture<int>(42)
276   ///     .delayed(long_time)
277   ///     .onTimeout(short_time,
278   ///       []() -> int{ return -1; });
279   ///
280   /// or perhaps
281   ///
282   ///   Future<int> f = makeFuture<int>(42)
283   ///     .delayed(long_time)
284   ///     .onTimeout(short_time,
285   ///       []() { return makeFuture<int>(some_exception); });
286   template <class F>
287   Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr);
288
289   /// This is not the method you're looking for.
290   ///
291   /// This needs to be public because it's used by make* and when*, and it's
292   /// not worth listing all those and their fancy template signatures as
293   /// friends. But it's not for public consumption.
294   template <class F>
295   void setCallback_(F&& func);
296
297   /// A Future's callback is executed when all three of these conditions have
298   /// become true: it has a value (set by the Promise), it has a callback (set
299   /// by then), and it is active (active by default).
300   ///
301   /// Inactive Futures will activate upon destruction.
302   FOLLY_DEPRECATED("do not use") Future<T>& activate() & {
303     core_->activate();
304     return *this;
305   }
306   FOLLY_DEPRECATED("do not use") Future<T>& deactivate() & {
307     core_->deactivate();
308     return *this;
309   }
310   FOLLY_DEPRECATED("do not use") Future<T> activate() && {
311     core_->activate();
312     return std::move(*this);
313   }
314   FOLLY_DEPRECATED("do not use") Future<T> deactivate() && {
315     core_->deactivate();
316     return std::move(*this);
317   }
318
319   bool isActive() {
320     return core_->isActive();
321   }
322
323   template <class E>
324   void raise(E&& exception) {
325     raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
326         std::forward<E>(exception)));
327   }
328
329   /// Raise an interrupt. If the promise holder has an interrupt
330   /// handler it will be called and potentially stop asynchronous work from
331   /// being done. This is advisory only - a promise holder may not set an
332   /// interrupt handler, or may do anything including ignore. But, if you know
333   /// your future supports this the most likely result is stopping or
334   /// preventing the asynchronous operation (if in time), and the promise
335   /// holder setting an exception on the future. (That may happen
336   /// asynchronously, of course.)
337   void raise(exception_wrapper interrupt);
338
339   void cancel() {
340     raise(FutureCancellation());
341   }
342
343   /// Throw TimedOut if this Future does not complete within the given
344   /// duration from now. The optional Timeekeeper is as with futures::sleep().
345   Future<T> within(Duration, Timekeeper* = nullptr);
346
347   /// Throw the given exception if this Future does not complete within the
348   /// given duration from now. The optional Timeekeeper is as with
349   /// futures::sleep().
350   template <class E>
351   Future<T> within(Duration, E exception, Timekeeper* = nullptr);
352
353   /// Delay the completion of this Future for at least this duration from
354   /// now. The optional Timekeeper is as with futures::sleep().
355   Future<T> delayed(Duration, Timekeeper* = nullptr);
356
357   /// Block until this Future is complete. Returns a reference to this Future.
358   Future<T>& wait() &;
359
360   /// Overload of wait() for rvalue Futures
361   Future<T>&& wait() &&;
362
363   /// Block until this Future is complete or until the given Duration passes.
364   /// Returns a reference to this Future
365   Future<T>& wait(Duration) &;
366
367   /// Overload of wait(Duration) for rvalue Futures
368   Future<T>&& wait(Duration) &&;
369
370   /// Call e->drive() repeatedly until the future is fulfilled. Examples
371   /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
372   /// reference to this Future so that you can chain calls if desired.
373   /// value (moved out), or throws the exception.
374   Future<T>& waitVia(DrivableExecutor* e) &;
375
376   /// Overload of waitVia() for rvalue Futures
377   Future<T>&& waitVia(DrivableExecutor* e) &&;
378
379   /// If the value in this Future is equal to the given Future, when they have
380   /// both completed, the value of the resulting Future<bool> will be true. It
381   /// will be false otherwise (including when one or both Futures have an
382   /// exception)
383   Future<bool> willEqual(Future<T>&);
384
385   /// predicate behaves like std::function<bool(T const&)>
386   /// If the predicate does not obtain with the value, the result
387   /// is a folly::PredicateDoesNotObtain exception
388   template <class F>
389   Future<T> filter(F&& predicate);
390
391   /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
392   /// the result of collect or collectAll
393   template <class I, class F>
394   Future<I> reduce(I&& initial, F&& func);
395
396   /// Create a Future chain from a sequence of callbacks. i.e.
397   ///
398   ///   f.then(a).then(b).then(c)
399   ///
400   /// where f is a Future<A> and the result of the chain is a Future<D>
401   /// becomes
402   ///
403   ///   f.thenMulti(a, b, c);
404   template <class Callback, class... Callbacks>
405   auto thenMulti(Callback&& fn, Callbacks&&... fns)
406     -> decltype(this->then(std::forward<Callback>(fn)).
407                       thenMulti(std::forward<Callbacks>(fns)...));
408
409   // Nothing to see here, just thenMulti's base case
410   template <class Callback>
411   auto thenMulti(Callback&& fn)
412     -> decltype(this->then(std::forward<Callback>(fn)));
413
414   /// Create a Future chain from a sequence of callbacks. i.e.
415   ///
416   ///   f.via(executor).then(a).then(b).then(c).via(oldExecutor)
417   ///
418   /// where f is a Future<A> and the result of the chain is a Future<D>
419   /// becomes
420   ///
421   ///   f.thenMultiWithExecutor(executor, a, b, c);
422   template <class Callback, class... Callbacks>
423   auto thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns)
424     -> decltype(this->then(std::forward<Callback>(fn)).
425                       thenMulti(std::forward<Callbacks>(fns)...));
426
427   // Nothing to see here, just thenMultiWithExecutor's base case
428   template <class Callback>
429   auto thenMultiWithExecutor(Executor* x, Callback&& fn)
430     -> decltype(this->then(std::forward<Callback>(fn)));
431
432   /// Discard a result, but propagate an exception.
433   Future<Unit> unit() {
434     return then([]{ return Unit{}; });
435   }
436
437  protected:
438   typedef detail::Core<T>* corePtr;
439
440   // shared core state object
441   corePtr core_;
442
443   explicit
444   Future(corePtr obj) : core_(obj) {}
445
446   void detach();
447
448   void throwIfInvalid() const;
449
450   friend class Promise<T>;
451   template <class> friend class Future;
452
453   template <class T2>
454   friend Future<T2> makeFuture(Try<T2>&&);
455
456   /// Repeat the given future (i.e., the computation it contains)
457   /// n times.
458   ///
459   /// thunk behaves like std::function<Future<T2>(void)>
460   template <class F>
461   friend Future<Unit> times(int n, F&& thunk);
462
463   /// Carry out the computation contained in the given future if
464   /// the predicate holds.
465   ///
466   /// thunk behaves like std::function<Future<T2>(void)>
467   template <class F>
468   friend Future<Unit> when(bool p, F&& thunk);
469
470   /// Carry out the computation contained in the given future if
471   /// while the predicate continues to hold.
472   ///
473   /// thunk behaves like std::function<Future<T2>(void)>
474   ///
475   /// predicate behaves like std::function<bool(void)>
476   template <class P, class F>
477   friend Future<Unit> whileDo(P&& predicate, F&& thunk);
478
479   // Variant: returns a value
480   // e.g. f.then([](Try<T> t){ return t.value(); });
481   template <typename F, typename R, bool isTry, typename... Args>
482   typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
483   thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
484
485   // Variant: returns a Future
486   // e.g. f.then([](Try<T> t){ return makeFuture<T>(t); });
487   template <typename F, typename R, bool isTry, typename... Args>
488   typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
489   thenImplementation(F&& func, detail::argResult<isTry, F, Args...>);
490
491   Executor* getExecutor() { return core_->getExecutor(); }
492   void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
493     core_->setExecutor(x, priority);
494   }
495 };
496
497 } // folly
498
499 #include <folly/futures/Future-inl.h>