Future.h 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  1. /*
  2. * Copyright 2014-present 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. #pragma once
  17. #include <algorithm>
  18. #include <exception>
  19. #include <functional>
  20. #include <memory>
  21. #include <type_traits>
  22. #include <vector>
  23. #include <folly/Optional.h>
  24. #include <folly/Portability.h>
  25. #include <folly/ScopeGuard.h>
  26. #include <folly/Try.h>
  27. #include <folly/Unit.h>
  28. #include <folly/Utility.h>
  29. #include <folly/executors/DrivableExecutor.h>
  30. #include <folly/executors/TimedDrivableExecutor.h>
  31. #include <folly/functional/Invoke.h>
  32. #include <folly/futures/Promise.h>
  33. #include <folly/futures/detail/Types.h>
  34. #include <folly/lang/Exception.h>
  35. #if FOLLY_HAS_COROUTINES
  36. #include <experimental/coroutine>
  37. #endif
  38. // boring predeclarations and details
  39. #include <folly/futures/Future-pre.h>
  40. // not-boring helpers, e.g. all in folly::futures, makeFuture variants, etc.
  41. // Needs to be included after Future-pre.h and before Future-inl.h
  42. #include <folly/futures/helpers.h>
  43. namespace folly {
  44. class FOLLY_EXPORT FutureException : public std::logic_error {
  45. public:
  46. using std::logic_error::logic_error;
  47. };
  48. class FOLLY_EXPORT FutureInvalid : public FutureException {
  49. public:
  50. FutureInvalid() : FutureException("Future invalid") {}
  51. };
  52. /// At most one continuation may be attached to any given Future.
  53. ///
  54. /// If a continuation is attached to a future to which another continuation has
  55. /// already been attached, then an instance of FutureAlreadyContinued will be
  56. /// thrown instead.
  57. class FOLLY_EXPORT FutureAlreadyContinued : public FutureException {
  58. public:
  59. FutureAlreadyContinued() : FutureException("Future already continued") {}
  60. };
  61. class FOLLY_EXPORT FutureNotReady : public FutureException {
  62. public:
  63. FutureNotReady() : FutureException("Future not ready") {}
  64. };
  65. class FOLLY_EXPORT FutureCancellation : public FutureException {
  66. public:
  67. FutureCancellation() : FutureException("Future was cancelled") {}
  68. };
  69. class FOLLY_EXPORT FutureTimeout : public FutureException {
  70. public:
  71. FutureTimeout() : FutureException("Timed out") {}
  72. };
  73. class FOLLY_EXPORT FuturePredicateDoesNotObtain : public FutureException {
  74. public:
  75. FuturePredicateDoesNotObtain()
  76. : FutureException("Predicate does not obtain") {}
  77. };
  78. class FOLLY_EXPORT FutureNoTimekeeper : public FutureException {
  79. public:
  80. FutureNoTimekeeper() : FutureException("No timekeeper available") {}
  81. };
  82. class FOLLY_EXPORT FutureNoExecutor : public FutureException {
  83. public:
  84. FutureNoExecutor() : FutureException("No executor provided to via") {}
  85. };
  86. template <class T>
  87. class Future;
  88. template <class T>
  89. class SemiFuture;
  90. template <class T>
  91. class FutureSplitter;
  92. namespace futures {
  93. namespace detail {
  94. template <class T>
  95. class FutureBase {
  96. public:
  97. typedef T value_type;
  98. /// Construct from a value (perfect forwarding)
  99. ///
  100. /// Postconditions:
  101. ///
  102. /// - `valid() == true`
  103. /// - `isReady() == true`
  104. /// - `hasValue() == true`
  105. template <
  106. class T2 = T,
  107. typename = typename std::enable_if<
  108. !isFuture<typename std::decay<T2>::type>::value &&
  109. !isSemiFuture<typename std::decay<T2>::type>::value>::type>
  110. /* implicit */ FutureBase(T2&& val);
  111. /// Construct a (logical) FutureBase-of-void.
  112. ///
  113. /// Postconditions:
  114. ///
  115. /// - `valid() == true`
  116. /// - `isReady() == true`
  117. /// - `hasValue() == true`
  118. template <class T2 = T>
  119. /* implicit */ FutureBase(
  120. typename std::enable_if<std::is_same<Unit, T2>::value>::type*);
  121. template <
  122. class... Args,
  123. typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
  124. type = 0>
  125. explicit FutureBase(in_place_t, Args&&... args);
  126. FutureBase(FutureBase<T> const&) = delete;
  127. FutureBase(SemiFuture<T>&&) noexcept;
  128. FutureBase(Future<T>&&) noexcept;
  129. // not copyable
  130. FutureBase(Future<T> const&) = delete;
  131. FutureBase(SemiFuture<T> const&) = delete;
  132. ~FutureBase();
  133. /// true if this has a shared state;
  134. /// false if this has been either moved-out or created without a shared state.
  135. bool valid() const noexcept {
  136. return core_ != nullptr;
  137. }
  138. /// Returns a reference to the result value if it is ready, with a reference
  139. /// category and const-qualification like those of the future.
  140. ///
  141. /// Does not `wait()`; see `get()` for that.
  142. ///
  143. /// Preconditions:
  144. ///
  145. /// - `valid() == true` (else throws FutureInvalid)
  146. /// - `isReady() == true` (else throws FutureNotReady)
  147. ///
  148. /// Postconditions:
  149. ///
  150. /// - If an exception has been captured (i.e., if `hasException() == true`),
  151. /// throws that exception.
  152. /// - This call does not mutate the future's value.
  153. /// - However calling code may mutate that value (including moving it out by
  154. /// move-constructing or move-assigning another value from it), for
  155. /// example, via the `&` or the `&&` overloads or via casts.
  156. T& value() &;
  157. T const& value() const&;
  158. T&& value() &&;
  159. T const&& value() const&&;
  160. /// Returns a reference to the result's Try if it is ready, with a reference
  161. /// category and const-qualification like those of the future.
  162. ///
  163. /// Does not `wait()`; see `get()` for that.
  164. ///
  165. /// Preconditions:
  166. ///
  167. /// - `valid() == true` (else throws FutureInvalid)
  168. /// - `isReady() == true` (else throws FutureNotReady)
  169. ///
  170. /// Postconditions:
  171. ///
  172. /// - This call does not mutate the future's result.
  173. /// - However calling code may mutate that result (including moving it out by
  174. /// move-constructing or move-assigning another result from it), for
  175. /// example, via the `&` or the `&&` overloads or via casts.
  176. Try<T>& result() &;
  177. Try<T> const& result() const&;
  178. Try<T>&& result() &&;
  179. Try<T> const&& result() const&&;
  180. /// True when the result (or exception) is ready; see value(), result(), etc.
  181. ///
  182. /// Preconditions:
  183. ///
  184. /// - `valid() == true` (else throws FutureInvalid)
  185. bool isReady() const;
  186. /// True if the result is a value (not an exception) on a future for which
  187. /// isReady returns true.
  188. ///
  189. /// Equivalent to result().hasValue()
  190. ///
  191. /// Preconditions:
  192. ///
  193. /// - `valid() == true` (else throws FutureInvalid)
  194. /// - `isReady() == true` (else throws FutureNotReady)
  195. bool hasValue() const;
  196. /// True if the result is an exception (not a value) on a future for which
  197. /// isReady returns true.
  198. ///
  199. /// Equivalent to result().hasException()
  200. ///
  201. /// Preconditions:
  202. ///
  203. /// - `valid() == true` (else throws FutureInvalid)
  204. /// - `isReady() == true` (else throws FutureNotReady)
  205. bool hasException() const;
  206. /// Returns either an Optional holding the result or an empty Optional
  207. /// depending on whether or not (respectively) the promise has been
  208. /// fulfilled (i.e., `isReady() == true`).
  209. ///
  210. /// Preconditions:
  211. ///
  212. /// - `valid() == true` (else throws FutureInvalid)
  213. ///
  214. /// Postconditions:
  215. ///
  216. /// - `valid() == true` (note however that this moves-out the result when
  217. /// it returns a populated `Try<T>`, which effects any subsequent use of
  218. /// that result, e.g., `poll()`, `result()`, `value()`, `get()`, etc.)
  219. Optional<Try<T>> poll();
  220. /// This is not the method you're looking for.
  221. ///
  222. /// This needs to be public because it's used by make* and when*, and it's
  223. /// not worth listing all those and their fancy template signatures as
  224. /// friends. But it's not for public consumption.
  225. template <class F>
  226. void setCallback_(F&& func);
  227. template <class F>
  228. void setCallback_(F&& func, std::shared_ptr<folly::RequestContext> context);
  229. /// Provides a threadsafe back-channel so the consumer's thread can send an
  230. /// interrupt-object to the producer's thread.
  231. ///
  232. /// If the promise-holder registers an interrupt-handler and consumer thread
  233. /// raises an interrupt early enough (details below), the promise-holder
  234. /// will typically halt its work, fulfilling the future with an exception
  235. /// or some special non-exception value.
  236. ///
  237. /// However this interrupt request is voluntary, asynchronous, & advisory:
  238. ///
  239. /// - Voluntary: the producer will see the interrupt only if the producer uses
  240. /// a `Promise` object and registers an interrupt-handler;
  241. /// see `Promise::setInterruptHandler()`.
  242. /// - Asynchronous: the producer will see the interrupt only if `raise()` is
  243. /// called before (or possibly shortly after) the producer is done producing
  244. /// its result, which is asynchronous with respect to the call to `raise()`.
  245. /// - Advisory: the producer's interrupt-handler can do whatever it wants,
  246. /// including ignore the interrupt or perform some action other than halting
  247. /// its producer-work.
  248. ///
  249. /// Guidelines:
  250. ///
  251. /// - It is ideal if the promise-holder can both halt its work and fulfill the
  252. /// promise early, typically with the same exception that was delivered to
  253. /// the promise-holder in the form of an interrupt.
  254. /// - If the promise-holder does not do this, and if it holds the promise
  255. /// alive for a long time, then the whole continuation chain will not be
  256. /// invoked and the whole future chain will be kept alive for that long time
  257. /// as well.
  258. /// - It is also ideal if the promise-holder can invalidate the promise.
  259. /// - The promise-holder must also track whether it has set a result in the
  260. /// interrupt handler so that it does not attempt to do so outside the
  261. /// interrupt handler, and must track whether it has set a result in its
  262. /// normal flow so that it does not attempt to do so in the interrupt
  263. /// handler, since setting a result twice is an error. Because the interrupt
  264. /// handler can be invoked in some other thread, this tracking may have to
  265. /// be done with some form of concurrency control.
  266. ///
  267. /// Preconditions:
  268. ///
  269. /// - `valid() == true` (else throws FutureInvalid)
  270. ///
  271. /// Postconditions:
  272. ///
  273. /// - has no visible effect if `raise()` was previously called on `this` or
  274. /// any other Future/SemiFuture that uses the same shared state as `this`.
  275. /// - has no visible effect if the producer never (either in the past or in
  276. /// the future) registers an interrupt-handler.
  277. /// - has no visible effect if the producer fulfills its promise (sets the
  278. /// result) before (or possibly also shortly after) receiving the interrupt.
  279. /// - otherwise the promise-holder's interrupt-handler is called, passing the
  280. /// exception (within an `exception_wrapper`).
  281. ///
  282. /// The specific thread used to invoke the producer's interrupt-handler (if
  283. /// it is called at all) depends on timing:
  284. ///
  285. /// - if the interrupt-handler is registered prior to `raise()` (or possibly
  286. /// concurrently within the call to `raise()`), the interrupt-handler will
  287. /// be executed using this current thread within the call to `raise()`.
  288. /// - if the interrupt-handler is registered after `raise()` (and possibly
  289. /// concurrently within the call to `raise()`), the interrupt-handler will
  290. /// be executed using the producer's thread within the call to
  291. /// `Promise::setInterruptHandler()`.
  292. ///
  293. /// Synchronizes between `raise()` (in the consumer's thread)
  294. /// and `Promise::setInterruptHandler()` (in the producer's thread).
  295. void raise(exception_wrapper interrupt);
  296. /// Raises the specified exception-interrupt.
  297. /// See `raise(exception_wrapper)` for details.
  298. template <class E>
  299. void raise(E&& exception) {
  300. raise(make_exception_wrapper<typename std::remove_reference<E>::type>(
  301. std::forward<E>(exception)));
  302. }
  303. /// Raises a FutureCancellation interrupt.
  304. /// See `raise(exception_wrapper)` for details.
  305. void cancel() {
  306. raise(FutureCancellation());
  307. }
  308. // Returns this future's executor priority.
  309. int8_t getPriority() const {
  310. return getCore().getPriority();
  311. }
  312. protected:
  313. friend class Promise<T>;
  314. template <class>
  315. friend class SemiFuture;
  316. template <class>
  317. friend class Future;
  318. using Core = futures::detail::Core<T>;
  319. // Throws FutureInvalid if there is no shared state object; else returns it
  320. // by ref.
  321. //
  322. // Implementation methods should usually use this instead of `this->core_`.
  323. // The latter should be used only when you need the possibly-null pointer.
  324. Core& getCore() {
  325. return getCoreImpl(*this);
  326. }
  327. Core const& getCore() const {
  328. return getCoreImpl(*this);
  329. }
  330. template <typename Self>
  331. static decltype(auto) getCoreImpl(Self& self) {
  332. if (!self.core_) {
  333. throw_exception<FutureInvalid>();
  334. }
  335. return *self.core_;
  336. }
  337. Try<T>& getCoreTryChecked() {
  338. return getCoreTryChecked(*this);
  339. }
  340. Try<T> const& getCoreTryChecked() const {
  341. return getCoreTryChecked(*this);
  342. }
  343. template <typename Self>
  344. static decltype(auto) getCoreTryChecked(Self& self) {
  345. auto& core = self.getCore();
  346. if (!core.hasResult()) {
  347. throw_exception<FutureNotReady>();
  348. }
  349. return core.getTry();
  350. }
  351. // shared core state object
  352. // usually you should use `getCore()` instead of directly accessing `core_`.
  353. Core* core_;
  354. explicit FutureBase(Core* obj) : core_(obj) {}
  355. explicit FutureBase(futures::detail::EmptyConstruct) noexcept;
  356. void detach();
  357. void throwIfInvalid() const;
  358. void throwIfContinued() const;
  359. void assign(FutureBase<T>&& other) noexcept;
  360. Executor* getExecutor() const {
  361. return getCore().getExecutor();
  362. }
  363. // Sets the Executor within the Core state object of `this`.
  364. // Must be called either before attaching a callback or after the callback
  365. // has already been invoked, but not concurrently with anything which might
  366. // trigger invocation of the callback.
  367. void setExecutor(Executor* x, int8_t priority = Executor::MID_PRI) {
  368. getCore().setExecutor(x, priority);
  369. }
  370. void setExecutor(
  371. Executor::KeepAlive<> x,
  372. int8_t priority = Executor::MID_PRI) {
  373. getCore().setExecutor(std::move(x), priority);
  374. }
  375. // Variant: returns a value
  376. // e.g. f.thenTry([](Try<T> t){ return t.value(); });
  377. template <typename F, typename R>
  378. typename std::enable_if<!R::ReturnsFuture::value, typename R::Return>::type
  379. thenImplementation(F&& func, R);
  380. // Variant: returns a Future
  381. // e.g. f.thenTry([](Try<T> t){ return makeFuture<T>(t); });
  382. template <typename F, typename R>
  383. typename std::enable_if<R::ReturnsFuture::value, typename R::Return>::type
  384. thenImplementation(F&& func, R);
  385. template <typename E>
  386. SemiFuture<T> withinImplementation(Duration dur, E e, Timekeeper* tk) &&;
  387. };
  388. template <class T>
  389. void convertFuture(SemiFuture<T>&& sf, Future<T>& f);
  390. class DeferredExecutor;
  391. template <typename T>
  392. DeferredExecutor* getDeferredExecutor(SemiFuture<T>& future);
  393. template <typename T>
  394. folly::Executor::KeepAlive<DeferredExecutor> stealDeferredExecutor(
  395. SemiFuture<T>& future);
  396. } // namespace detail
  397. } // namespace futures
  398. /// The interface (along with Future) for the consumer-side of a
  399. /// producer/consumer pair.
  400. ///
  401. /// Future vs. SemiFuture:
  402. ///
  403. /// - The consumer-side should generally start with a SemiFuture, not a Future.
  404. /// - Example, when a library creates and returns a future, it should usually
  405. /// return a `SemiFuture`, not a Future.
  406. /// - Reason: so the thread policy for continuations (`.thenValue`, etc.) can be
  407. /// specified by the library's caller (using `.via()`).
  408. /// - A SemiFuture is converted to a Future using `.via()`.
  409. /// - Use `makePromiseContract()` when creating both a Promise and an associated
  410. /// SemiFuture/Future.
  411. ///
  412. /// When practical, prefer SemiFuture/Future's nonblocking style/pattern:
  413. ///
  414. /// - the nonblocking style uses continuations, e.g., `.thenValue`, etc.; the
  415. /// continuations are deferred until the result is available.
  416. /// - the blocking style blocks until complete, e.g., `.wait()`, `.get()`, etc.
  417. /// - the two styles cannot be mixed within the same future; use one or the
  418. /// other.
  419. ///
  420. /// SemiFuture/Future also provide a back-channel so an interrupt can
  421. /// be sent from consumer to producer; see SemiFuture/Future's `raise()`
  422. /// and Promise's `setInterruptHandler()`.
  423. ///
  424. /// The consumer-side SemiFuture/Future objects should generally be accessed
  425. /// via a single thread. That thread is referred to as the 'consumer thread.'
  426. template <class T>
  427. class SemiFuture : private futures::detail::FutureBase<T> {
  428. private:
  429. using Base = futures::detail::FutureBase<T>;
  430. using DeferredExecutor = futures::detail::DeferredExecutor;
  431. using TimePoint = std::chrono::system_clock::time_point;
  432. public:
  433. ~SemiFuture();
  434. /// Creates/returns an invalid SemiFuture, that is, one with no shared state.
  435. ///
  436. /// Postcondition:
  437. ///
  438. /// - `RESULT.valid() == false`
  439. static SemiFuture<T> makeEmpty();
  440. /// Type of the value that the producer, when successful, produces.
  441. using typename Base::value_type;
  442. /// Construct a SemiFuture from a value (perfect forwarding)
  443. ///
  444. /// Postconditions:
  445. ///
  446. /// - `valid() == true`
  447. /// - `isReady() == true`
  448. /// - `hasValue() == true`
  449. /// - `hasException() == false`
  450. /// - `value()`, `get()`, `result()` will return the forwarded `T`
  451. template <
  452. class T2 = T,
  453. typename = typename std::enable_if<
  454. !isFuture<typename std::decay<T2>::type>::value &&
  455. !isSemiFuture<typename std::decay<T2>::type>::value>::type>
  456. /* implicit */ SemiFuture(T2&& val) : Base(std::forward<T2>(val)) {}
  457. /// Construct a (logical) SemiFuture-of-void.
  458. ///
  459. /// Postconditions:
  460. ///
  461. /// - `valid() == true`
  462. /// - `isReady() == true`
  463. /// - `hasValue() == true`
  464. template <class T2 = T>
  465. /* implicit */ SemiFuture(
  466. typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
  467. : Base(p) {}
  468. /// Construct a SemiFuture from a `T` constructed from `args`
  469. ///
  470. /// Postconditions:
  471. ///
  472. /// - `valid() == true`
  473. /// - `isReady() == true`
  474. /// - `hasValue() == true`
  475. /// - `hasException() == false`
  476. /// - `value()`, `get()`, `result()` will return the newly constructed `T`
  477. template <
  478. class... Args,
  479. typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
  480. type = 0>
  481. explicit SemiFuture(in_place_t, Args&&... args)
  482. : Base(in_place, std::forward<Args>(args)...) {}
  483. SemiFuture(SemiFuture<T> const&) = delete;
  484. // movable
  485. SemiFuture(SemiFuture<T>&&) noexcept;
  486. // safe move-constructabilty from Future
  487. /* implicit */ SemiFuture(Future<T>&&) noexcept;
  488. using Base::cancel;
  489. using Base::getPriority;
  490. using Base::hasException;
  491. using Base::hasValue;
  492. using Base::isReady;
  493. using Base::poll;
  494. using Base::raise;
  495. using Base::result;
  496. using Base::setCallback_;
  497. using Base::valid;
  498. using Base::value;
  499. SemiFuture& operator=(SemiFuture const&) = delete;
  500. SemiFuture& operator=(SemiFuture&&) noexcept;
  501. SemiFuture& operator=(Future<T>&&) noexcept;
  502. /// Blocks until the promise is fulfilled, either by value (which is returned)
  503. /// or exception (which is thrown).
  504. ///
  505. /// Preconditions:
  506. ///
  507. /// - `valid() == true` (else throws FutureInvalid)
  508. /// - must not have a continuation, e.g., via `.thenValue()` or similar
  509. ///
  510. /// Postconditions:
  511. ///
  512. /// - `valid() == false`
  513. T get() &&;
  514. [[deprecated("must be rvalue-qualified, e.g., std::move(future).get()")]] T
  515. get() & = delete;
  516. /// Blocks until the semifuture is fulfilled, or until `dur` elapses. Returns
  517. /// the value (moved-out), or throws the exception (which might be a
  518. /// FutureTimeout exception).
  519. ///
  520. /// Preconditions:
  521. ///
  522. /// - `valid() == true` (else throws FutureInvalid)
  523. ///
  524. /// Postconditions:
  525. ///
  526. /// - `valid() == false`
  527. T get(Duration dur) &&;
  528. [[deprecated("must be rvalue-qualified, e.g., std::move(future).get(dur)")]] T
  529. get(Duration dur) & = delete;
  530. /// Blocks until the future is fulfilled. Returns the Try of the result
  531. /// (moved-out).
  532. ///
  533. /// Preconditions:
  534. ///
  535. /// - `valid() == true` (else throws FutureInvalid)
  536. ///
  537. /// Postconditions:
  538. ///
  539. /// - `valid() == false`
  540. Try<T> getTry() &&;
  541. /// Blocks until the future is fulfilled, or until `dur` elapses.
  542. /// Returns the Try of the result (moved-out), or throws FutureTimeout
  543. /// exception.
  544. ///
  545. /// Preconditions:
  546. ///
  547. /// - `valid() == true` (else throws FutureInvalid)
  548. ///
  549. /// Postconditions:
  550. ///
  551. /// - `valid() == false`
  552. Try<T> getTry(Duration dur) &&;
  553. /// Blocks the caller's thread until this Future `isReady()`, i.e., until the
  554. /// asynchronous producer has stored a result or exception.
  555. ///
  556. /// Preconditions:
  557. ///
  558. /// - `valid() == true` (else throws FutureInvalid)
  559. ///
  560. /// Postconditions:
  561. ///
  562. /// - `valid() == true`
  563. /// - `isReady() == true`
  564. /// - `&RESULT == this`
  565. SemiFuture<T>& wait() &;
  566. /// Blocks the caller's thread until this Future `isReady()`, i.e., until the
  567. /// asynchronous producer has stored a result or exception.
  568. ///
  569. /// Preconditions:
  570. ///
  571. /// - `valid() == true` (else throws FutureInvalid)
  572. ///
  573. /// Postconditions:
  574. ///
  575. /// - `valid() == true` (but the calling code can trivially move-out `*this`
  576. /// by assigning or constructing the result into a distinct object).
  577. /// - `&RESULT == this`
  578. /// - `isReady() == true`
  579. SemiFuture<T>&& wait() &&;
  580. /// Blocks until the future is fulfilled, or `dur` elapses.
  581. /// Returns true if the future was fulfilled.
  582. ///
  583. /// Preconditions:
  584. ///
  585. /// - `valid() == true` (else throws FutureInvalid)
  586. ///
  587. /// Postconditions:
  588. ///
  589. /// - `valid() == false`
  590. bool wait(Duration dur) &&;
  591. /// Returns a Future which will call back on the other side of executor.
  592. Future<T> via(Executor* executor, int8_t priority = Executor::MID_PRI) &&;
  593. Future<T> via(
  594. Executor::KeepAlive<> executor,
  595. int8_t priority = Executor::MID_PRI) &&;
  596. /// Defer work to run on the consumer of the future.
  597. /// Function must take a Try as a parameter.
  598. /// This work will be run either on an executor that the caller sets on the
  599. /// SemiFuture, or inline with the call to .get().
  600. ///
  601. /// NB: This is a custom method because boost-blocking executors is a
  602. /// special-case for work deferral in folly. With more general boost-blocking
  603. /// support all executors would boost block and we would simply use some form
  604. /// of driveable executor here.
  605. ///
  606. /// Preconditions:
  607. ///
  608. /// - `valid() == true` (else throws FutureInvalid)
  609. ///
  610. /// Postconditions:
  611. ///
  612. /// - `valid() == false`
  613. /// - `RESULT.valid() == true`
  614. template <typename F>
  615. SemiFuture<typename futures::detail::tryCallableResult<T, F>::value_type>
  616. defer(F&& func) &&;
  617. template <typename R, typename... Args>
  618. auto defer(R (&func)(Args...)) && {
  619. return std::move(*this).defer(&func);
  620. }
  621. /// Defer for functions taking a T rather than a Try<T>.
  622. ///
  623. /// Preconditions:
  624. ///
  625. /// - `valid() == true` (else throws FutureInvalid)
  626. ///
  627. /// Postconditions:
  628. ///
  629. /// - `valid() == false`
  630. /// - `RESULT.valid() == true`
  631. template <typename F>
  632. SemiFuture<typename futures::detail::valueCallableResult<T, F>::value_type>
  633. deferValue(F&& func) &&;
  634. template <typename R, typename... Args>
  635. auto deferValue(R (&func)(Args...)) && {
  636. return std::move(*this).deferValue(&func);
  637. }
  638. /// Set an error continuation for this SemiFuture where the continuation can
  639. /// be called with a known exception type and returns a `T`, `Future<T>`, or
  640. /// `SemiFuture<T>`.
  641. ///
  642. /// Example:
  643. ///
  644. /// ```
  645. /// makeSemiFuture()
  646. /// .defer([] {
  647. /// throw std::runtime_error("oh no!");
  648. /// return 42;
  649. /// })
  650. /// .deferError<std::runtime_error>([] (auto const& e) {
  651. /// LOG(INFO) << "std::runtime_error: " << e.what();
  652. /// return -1; // or makeFuture<int>(-1) or makeSemiFuture<int>(-1)
  653. /// });
  654. /// ```
  655. ///
  656. /// Preconditions:
  657. ///
  658. /// - `valid() == true` (else throws FutureInvalid)
  659. ///
  660. /// Postconditions:
  661. ///
  662. /// - `valid() == false`
  663. /// - `RESULT.valid() == true`
  664. template <class ExceptionType, class F>
  665. SemiFuture<T> deferError(F&& func) &&;
  666. template <class ExceptionType, class R, class... Args>
  667. SemiFuture<T> deferError(R (&func)(Args...)) && {
  668. return std::move(*this).template deferError<ExceptionType>(&func);
  669. }
  670. /// Set an error continuation for this SemiFuture where the continuation can
  671. /// be called with `exception_wrapper&&` and returns a `T`, `Future<T>`, or
  672. /// `SemiFuture<T>`.
  673. ///
  674. /// Example:
  675. ///
  676. /// makeSemiFuture()
  677. /// .defer([] {
  678. /// throw std::runtime_error("oh no!");
  679. /// return 42;
  680. /// })
  681. /// .deferError([] (exception_wrapper&& e) {
  682. /// LOG(INFO) << e.what();
  683. /// return -1; // or makeFuture<int>(-1) or makeSemiFuture<int>(-1)
  684. /// });
  685. ///
  686. /// Preconditions:
  687. ///
  688. /// - `valid() == true` (else throws FutureInvalid)
  689. ///
  690. /// Postconditions:
  691. ///
  692. /// - `valid() == false`
  693. /// - `RESULT.valid() == true`
  694. template <class F>
  695. SemiFuture<T> deferError(F&& func) &&;
  696. template <class R, class... Args>
  697. SemiFuture<T> deferError(R (&func)(Args...)) && {
  698. return std::move(*this).deferError(&func);
  699. }
  700. SemiFuture<T> within(Duration dur, Timekeeper* tk = nullptr) && {
  701. return std::move(*this).within(dur, FutureTimeout(), tk);
  702. }
  703. template <class E>
  704. SemiFuture<T> within(Duration dur, E e, Timekeeper* tk = nullptr) && {
  705. return this->isReady() ? std::move(*this)
  706. : std::move(*this).withinImplementation(dur, e, tk);
  707. }
  708. /// Delay the completion of this SemiFuture for at least this duration from
  709. /// now. The optional Timekeeper is as with futures::sleep().
  710. ///
  711. /// Preconditions:
  712. ///
  713. /// - `valid() == true` (else throws FutureInvalid)
  714. ///
  715. /// Postconditions:
  716. ///
  717. /// - `valid() == false`
  718. /// - `RESULT.valid() == true`
  719. SemiFuture<T> delayed(Duration dur, Timekeeper* tk = nullptr) &&;
  720. /// Returns a future that completes inline, as if the future had no executor.
  721. /// Intended for porting legacy code without behavioral change, and for rare
  722. /// cases where this is really the intended behavior.
  723. /// Future is unsafe in the sense that the executor it completes on is
  724. /// non-deterministic in the standard case.
  725. /// For new code, or to update code that temporarily uses this, please
  726. /// use via and pass a meaningful executor.
  727. ///
  728. /// Preconditions:
  729. ///
  730. /// - `valid() == true` (else throws FutureInvalid)
  731. ///
  732. /// Postconditions:
  733. ///
  734. /// - `valid() == false`
  735. /// - `RESULT.valid() == true`
  736. Future<T> toUnsafeFuture() &&;
  737. #if FOLLY_HAS_COROUTINES
  738. class promise_type {
  739. public:
  740. SemiFuture get_return_object() {
  741. return promise_.getSemiFuture();
  742. }
  743. std::experimental::suspend_never initial_suspend() {
  744. return {};
  745. }
  746. std::experimental::suspend_never final_suspend() {
  747. return {};
  748. }
  749. void return_value(const T& value) {
  750. promise_.setValue(value);
  751. }
  752. void return_value(T& value) {
  753. promise_.setValue(std::move(value));
  754. }
  755. void unhandled_exception() {
  756. try {
  757. std::rethrow_exception(std::current_exception());
  758. } catch (std::exception& e) {
  759. promise_.setException(exception_wrapper(std::current_exception(), e));
  760. } catch (...) {
  761. promise_.setException(exception_wrapper(std::current_exception()));
  762. }
  763. }
  764. private:
  765. folly::Promise<T> promise_;
  766. };
  767. template <typename Awaitable>
  768. static SemiFuture fromAwaitable(Awaitable&& awaitable) {
  769. return [](Awaitable awaitable) -> SemiFuture {
  770. co_return co_await std::forward<Awaitable>(awaitable);
  771. }(std::forward<Awaitable>(awaitable));
  772. }
  773. // Customise the co_viaIfAsync() operator so that SemiFuture<T> can be
  774. // directly awaited within a folly::coro::Task coroutine.
  775. friend Future<T> co_viaIfAsync(
  776. folly::Executor* executor,
  777. SemiFuture<T>&& future) noexcept {
  778. return std::move(future).via(executor);
  779. }
  780. #endif
  781. private:
  782. friend class Promise<T>;
  783. template <class>
  784. friend class futures::detail::FutureBase;
  785. template <class>
  786. friend class SemiFuture;
  787. template <class>
  788. friend class Future;
  789. friend folly::Executor::KeepAlive<DeferredExecutor>
  790. futures::detail::stealDeferredExecutor<T>(SemiFuture&);
  791. friend DeferredExecutor* futures::detail::getDeferredExecutor<T>(SemiFuture&);
  792. using Base::setExecutor;
  793. using Base::throwIfInvalid;
  794. using typename Base::Core;
  795. template <class T2>
  796. friend SemiFuture<T2> makeSemiFuture(Try<T2>);
  797. explicit SemiFuture(Core* obj) : Base(obj) {}
  798. explicit SemiFuture(futures::detail::EmptyConstruct) noexcept
  799. : Base(futures::detail::EmptyConstruct{}) {}
  800. // Throws FutureInvalid if !this->core_
  801. DeferredExecutor* getDeferredExecutor() const;
  802. // Throws FutureInvalid if !this->core_
  803. folly::Executor::KeepAlive<DeferredExecutor> stealDeferredExecutor() const;
  804. /// Blocks until the future is fulfilled, or `dur` elapses.
  805. ///
  806. /// Preconditions:
  807. ///
  808. /// - `valid() == true` (else throws FutureInvalid)
  809. ///
  810. /// Postconditions:
  811. ///
  812. /// - `valid() == true`
  813. /// - `&RESULT == this`
  814. /// - `isReady()` will be indeterminate - may or may not be true
  815. SemiFuture<T>& wait(Duration dur) &;
  816. static void releaseDeferredExecutor(Core* core);
  817. };
  818. template <class T>
  819. std::pair<Promise<T>, SemiFuture<T>> makePromiseContract() {
  820. auto p = Promise<T>();
  821. auto f = p.getSemiFuture();
  822. return std::make_pair(std::move(p), std::move(f));
  823. }
  824. /// The interface (along with SemiFuture) for the consumer-side of a
  825. /// producer/consumer pair.
  826. ///
  827. /// Future vs. SemiFuture:
  828. ///
  829. /// - The consumer-side should generally start with a SemiFuture, not a Future.
  830. /// - Example, when a library creates and returns a future, it should usually
  831. /// return a `SemiFuture`, not a Future.
  832. /// - Reason: so the thread policy for continuations (`.thenValue`, etc.) can be
  833. /// specified by the library's caller (using `.via()`).
  834. /// - A SemiFuture is converted to a Future using `.via()`.
  835. /// - Use `makePromiseContract()` when creating both a Promise and an associated
  836. /// SemiFuture/Future.
  837. ///
  838. /// When practical, prefer SemiFuture/Future's nonblocking style/pattern:
  839. ///
  840. /// - the nonblocking style uses continuations, e.g., `.thenValue`, etc.; the
  841. /// continuations are deferred until the result is available.
  842. /// - the blocking style blocks until complete, e.g., `.wait()`, `.get()`, etc.
  843. /// - the two styles cannot be mixed within the same future; use one or the
  844. /// other.
  845. ///
  846. /// SemiFuture/Future also provide a back-channel so an interrupt can
  847. /// be sent from consumer to producer; see SemiFuture/Future's `raise()`
  848. /// and Promise's `setInterruptHandler()`.
  849. ///
  850. /// The consumer-side SemiFuture/Future objects should generally be accessed
  851. /// via a single thread. That thread is referred to as the 'consumer thread.'
  852. template <class T>
  853. class Future : private futures::detail::FutureBase<T> {
  854. private:
  855. using Base = futures::detail::FutureBase<T>;
  856. public:
  857. /// Type of the value that the producer, when successful, produces.
  858. using typename Base::value_type;
  859. /// Construct a Future from a value (perfect forwarding)
  860. ///
  861. /// Postconditions:
  862. ///
  863. /// - `valid() == true`
  864. /// - `isReady() == true`
  865. /// - `hasValue() == true`
  866. /// - `value()`, `get()`, `result()` will return the forwarded `T`
  867. template <
  868. class T2 = T,
  869. typename = typename std::enable_if<
  870. !isFuture<typename std::decay<T2>::type>::value &&
  871. !isSemiFuture<typename std::decay<T2>::type>::value>::type>
  872. /* implicit */ Future(T2&& val) : Base(std::forward<T2>(val)) {}
  873. /// Construct a (logical) Future-of-void.
  874. ///
  875. /// Postconditions:
  876. ///
  877. /// - `valid() == true`
  878. /// - `isReady() == true`
  879. /// - `hasValue() == true`
  880. template <class T2 = T>
  881. /* implicit */ Future(
  882. typename std::enable_if<std::is_same<Unit, T2>::value>::type* p = nullptr)
  883. : Base(p) {}
  884. /// Construct a Future from a `T` constructed from `args`
  885. ///
  886. /// Postconditions:
  887. ///
  888. /// - `valid() == true`
  889. /// - `isReady() == true`
  890. /// - `hasValue() == true`
  891. /// - `hasException() == false`
  892. /// - `value()`, `get()`, `result()` will return the newly constructed `T`
  893. template <
  894. class... Args,
  895. typename std::enable_if<std::is_constructible<T, Args&&...>::value, int>::
  896. type = 0>
  897. explicit Future(in_place_t, Args&&... args)
  898. : Base(in_place, std::forward<Args>(args)...) {}
  899. Future(Future<T> const&) = delete;
  900. // movable
  901. Future(Future<T>&&) noexcept;
  902. // converting move
  903. template <
  904. class T2,
  905. typename std::enable_if<
  906. !std::is_same<T, typename std::decay<T2>::type>::value &&
  907. std::is_constructible<T, T2&&>::value &&
  908. std::is_convertible<T2&&, T>::value,
  909. int>::type = 0>
  910. /* implicit */ Future(Future<T2>&&);
  911. template <
  912. class T2,
  913. typename std::enable_if<
  914. !std::is_same<T, typename std::decay<T2>::type>::value &&
  915. std::is_constructible<T, T2&&>::value &&
  916. !std::is_convertible<T2&&, T>::value,
  917. int>::type = 0>
  918. explicit Future(Future<T2>&&);
  919. template <
  920. class T2,
  921. typename std::enable_if<
  922. !std::is_same<T, typename std::decay<T2>::type>::value &&
  923. std::is_constructible<T, T2&&>::value,
  924. int>::type = 0>
  925. Future& operator=(Future<T2>&&);
  926. using Base::cancel;
  927. using Base::getPriority;
  928. using Base::hasException;
  929. using Base::hasValue;
  930. using Base::isReady;
  931. using Base::poll;
  932. using Base::raise;
  933. using Base::result;
  934. using Base::setCallback_;
  935. using Base::valid;
  936. using Base::value;
  937. /// Creates/returns an invalid Future, that is, one with no shared state.
  938. ///
  939. /// Postcondition:
  940. ///
  941. /// - `RESULT.valid() == false`
  942. static Future<T> makeEmpty();
  943. // not copyable
  944. Future& operator=(Future const&) = delete;
  945. // movable
  946. Future& operator=(Future&&) noexcept;
  947. /// Call e->drive() repeatedly until the future is fulfilled.
  948. ///
  949. /// Examples of DrivableExecutor include EventBase and ManualExecutor.
  950. ///
  951. /// Returns the fulfilled value (moved-out) or throws the fulfilled exception.
  952. T getVia(DrivableExecutor* e);
  953. /// Call e->drive() repeatedly until the future is fulfilled, or `dur`
  954. /// elapses.
  955. ///
  956. /// Returns the fulfilled value (moved-out), throws the fulfilled exception,
  957. /// or on timeout throws FutureTimeout.
  958. T getVia(TimedDrivableExecutor* e, Duration dur);
  959. /// Call e->drive() repeatedly until the future is fulfilled. Examples
  960. /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
  961. /// reference to the Try of the value.
  962. Try<T>& getTryVia(DrivableExecutor* e);
  963. /// getTryVia but will wait only until `dur` elapses. Returns the
  964. /// Try of the value (moved-out) or may throw a FutureTimeout exception.
  965. Try<T>& getTryVia(TimedDrivableExecutor* e, Duration dur);
  966. /// Unwraps the case of a Future<Future<T>> instance, and returns a simple
  967. /// Future<T> instance.
  968. ///
  969. /// Preconditions:
  970. ///
  971. /// - `valid() == true` (else throws FutureInvalid)
  972. ///
  973. /// Postconditions:
  974. ///
  975. /// - Calling code should act as if `valid() == false`,
  976. /// i.e., as if `*this` was moved into RESULT.
  977. /// - `RESULT.valid() == true`
  978. template <class F = T>
  979. typename std::
  980. enable_if<isFuture<F>::value, Future<typename isFuture<T>::Inner>>::type
  981. unwrap() &&;
  982. /// Returns a Future which will call back on the other side of executor.
  983. ///
  984. /// Preconditions:
  985. ///
  986. /// - `valid() == true` (else throws FutureInvalid)
  987. ///
  988. /// Postconditions:
  989. ///
  990. /// - `valid() == false`
  991. /// - `RESULT.valid() == true`
  992. Future<T> via(Executor* executor, int8_t priority = Executor::MID_PRI) &&;
  993. Future<T> via(
  994. Executor::KeepAlive<> executor,
  995. int8_t priority = Executor::MID_PRI) &&;
  996. /// Returns a Future which will call back on the other side of executor.
  997. ///
  998. /// When practical, use the rvalue-qualified overload instead - it's faster.
  999. ///
  1000. /// Preconditions:
  1001. ///
  1002. /// - `valid() == true` (else throws FutureInvalid)
  1003. ///
  1004. /// Postconditions:
  1005. ///
  1006. /// - `valid() == true`
  1007. /// - `RESULT.valid() == true`
  1008. /// - when `this` gets fulfilled, it automatically fulfills RESULT
  1009. Future<T> via(Executor* executor, int8_t priority = Executor::MID_PRI) &;
  1010. Future<T> via(
  1011. Executor::KeepAlive<> executor,
  1012. int8_t priority = Executor::MID_PRI) &;
  1013. /// When this Future has completed, execute func which is a function that
  1014. /// can be called with either `T&&` or `Try<T>&&`.
  1015. ///
  1016. /// Func shall return either another Future or a value.
  1017. ///
  1018. /// A Future for the return type of func is returned.
  1019. ///
  1020. /// Future<string> f2 = f1.thenTry([](Try<T>&&) { return string("foo"); });
  1021. ///
  1022. /// Preconditions:
  1023. ///
  1024. /// - `valid() == true` (else throws FutureInvalid)
  1025. ///
  1026. /// Postconditions:
  1027. ///
  1028. /// - Calling code should act as if `valid() == false`,
  1029. /// i.e., as if `*this` was moved into RESULT.
  1030. /// - `RESULT.valid() == true`
  1031. /// NOTE: All three of these variations are deprecated and deprecation
  1032. /// attributes will be added in the near future. Please prefer thenValue,
  1033. /// thenTry or thenError rather than then and onError as they avoid ambiguity
  1034. /// when using polymorphic lambdas.
  1035. template <typename F, typename R = futures::detail::callableResult<T, F>>
  1036. [[deprecated("use thenValue instead")]] typename std::enable_if<
  1037. !is_invocable<F>::value && is_invocable<F, T&&>::value,
  1038. typename R::Return>::type
  1039. then(F&& func) && {
  1040. return std::move(*this).thenValue(std::forward<F>(func));
  1041. }
  1042. template <typename F, typename R = futures::detail::callableResult<T, F>>
  1043. [[deprecated("use thenTry instead")]] typename std::enable_if<
  1044. !is_invocable<F, T&&>::value && !is_invocable<F>::value,
  1045. typename R::Return>::type
  1046. then(F&& func) && {
  1047. return std::move(*this).thenTry(std::forward<F>(func));
  1048. }
  1049. template <typename F, typename R = futures::detail::callableResult<T, F>>
  1050. [[deprecated("use thenValue(auto&&) or thenValue(folly::Unit) instead")]]
  1051. typename std::enable_if<is_invocable<F>::value, typename R::Return>::type
  1052. then(F&& func) && {
  1053. return this->thenImplementation(std::forward<F>(func), R{});
  1054. }
  1055. // clang-format off
  1056. template <typename F, typename R = futures::detail::callableResult<T, F>>
  1057. [[deprecated(
  1058. "must be rvalue-qualified, e.g., std::move(future).thenValue(...)")]]
  1059. typename R::Return then(F&& func) & = delete;
  1060. // clang-format on
  1061. /// Variant where func is an member function
  1062. ///
  1063. /// struct Worker { R doWork(Try<T>); }
  1064. ///
  1065. /// Worker *w;
  1066. /// Future<R> f2 = f1.thenTry(&Worker::doWork, w);
  1067. ///
  1068. /// This is just sugar for
  1069. ///
  1070. /// f1.thenTry(std::bind(&Worker::doWork, w));
  1071. ///
  1072. /// Preconditions:
  1073. ///
  1074. /// - `valid() == true` (else throws FutureInvalid)
  1075. ///
  1076. /// Postconditions:
  1077. ///
  1078. /// - Calling code should act as if `valid() == false`,
  1079. /// i.e., as if `*this` was moved into RESULT.
  1080. /// - `RESULT.valid() == true`
  1081. template <typename R, typename Caller, typename... Args>
  1082. Future<typename isFuture<R>::Inner> then(
  1083. R (Caller::*func)(Args...),
  1084. Caller* instance) &&;
  1085. // clang-format off
  1086. template <typename R, typename Caller, typename... Args>
  1087. [[deprecated(
  1088. "must be rvalue-qualified, e.g., std::move(future).then(...)")]]
  1089. Future<typename isFuture<R>::Inner>
  1090. then(R (Caller::*func)(Args...), Caller* instance) & = delete;
  1091. // clang-format on
  1092. /// Execute the callback via the given Executor. The executor doesn't stick.
  1093. ///
  1094. /// Contrast
  1095. ///
  1096. /// f.via(x).then(b).then(c)
  1097. ///
  1098. /// with
  1099. ///
  1100. /// f.then(x, b).then(c)
  1101. ///
  1102. /// In the former both b and c execute via x. In the latter, only b executes
  1103. /// via x, and c executes via the same executor (if any) that f had.
  1104. ///
  1105. /// Preconditions:
  1106. ///
  1107. /// - `valid() == true` (else throws FutureInvalid)
  1108. ///
  1109. /// Postconditions:
  1110. ///
  1111. /// - Calling code should act as if `valid() == false`,
  1112. /// i.e., as if `*this` was moved into RESULT.
  1113. /// - `RESULT.valid() == true`
  1114. template <class Arg>
  1115. auto then(Executor* x, Arg&& arg) && {
  1116. auto oldX = this->getExecutor();
  1117. this->setExecutor(x);
  1118. // TODO(T29171940): thenImplementation here is ambiguous
  1119. // as then used to be but that is better than keeping then in the public
  1120. // API.
  1121. using R = futures::detail::callableResult<T, Arg&&>;
  1122. return std::move(*this)
  1123. .thenImplementation(std::forward<Arg>(arg), R{})
  1124. .via(oldX);
  1125. }
  1126. template <class R, class Caller, class... Args>
  1127. auto then(Executor* x, R (Caller::*func)(Args...), Caller* instance) && {
  1128. auto oldX = this->getExecutor();
  1129. this->setExecutor(x);
  1130. return std::move(*this).then(func, instance).via(oldX);
  1131. }
  1132. template <class Arg, class... Args>
  1133. [[deprecated(
  1134. "must be rvalue-qualified, e.g., std::move(future).then(...)")]] auto
  1135. then(Executor* x, Arg&& arg, Args&&... args) & = delete;
  1136. /// When this Future has completed, execute func which is a function that
  1137. /// can be called with `Try<T>&&` (often a lambda with parameter type
  1138. /// `auto&&` or `auto`).
  1139. ///
  1140. /// Func shall return either another Future or a value.
  1141. ///
  1142. /// A Future for the return type of func is returned.
  1143. ///
  1144. /// Future<string> f2 = std::move(f1).thenTry([](auto&& t) {
  1145. /// ...
  1146. /// return string("foo");
  1147. /// });
  1148. ///
  1149. /// Preconditions:
  1150. ///
  1151. /// - `valid() == true` (else throws FutureInvalid)
  1152. ///
  1153. /// Postconditions:
  1154. ///
  1155. /// - `valid() == false`
  1156. /// - `RESULT.valid() == true`
  1157. template <typename F>
  1158. Future<typename futures::detail::tryCallableResult<T, F>::value_type> thenTry(
  1159. F&& func) &&;
  1160. template <typename R, typename... Args>
  1161. auto thenTry(R (&func)(Args...)) && {
  1162. return std::move(*this).thenTry(&func);
  1163. }
  1164. /// When this Future has completed, execute func which is a function that
  1165. /// can be called with `T&&` (often a lambda with parameter type
  1166. /// `auto&&` or `auto`).
  1167. ///
  1168. /// Func shall return either another Future or a value.
  1169. ///
  1170. /// A Future for the return type of func is returned.
  1171. ///
  1172. /// Future<string> f2 = f1.thenValue([](auto&& v) {
  1173. /// ...
  1174. /// return string("foo");
  1175. /// });
  1176. ///
  1177. /// Preconditions:
  1178. ///
  1179. /// - `valid() == true` (else throws FutureInvalid)
  1180. ///
  1181. /// Postconditions:
  1182. ///
  1183. /// - `valid() == false`
  1184. /// - `RESULT.valid() == true`
  1185. template <typename F>
  1186. Future<typename futures::detail::valueCallableResult<T, F>::value_type>
  1187. thenValue(F&& func) &&;
  1188. template <typename R, typename... Args>
  1189. auto thenValue(R (&func)(Args...)) && {
  1190. return std::move(*this).thenValue(&func);
  1191. }
  1192. /// Set an error continuation for this Future where the continuation can
  1193. /// be called with a known exception type and returns a `T`, `Future<T>`, or
  1194. /// `SemiFuture<T>`.
  1195. ///
  1196. /// Example:
  1197. ///
  1198. /// makeFuture()
  1199. /// .thenTry([] {
  1200. /// throw std::runtime_error("oh no!");
  1201. /// return 42;
  1202. /// })
  1203. /// .thenError<std::runtime_error>([] (auto const& e) {
  1204. /// LOG(INFO) << "std::runtime_error: " << e.what();
  1205. /// return -1; // or makeFuture<int>(-1) or makeSemiFuture<int>(-1)
  1206. /// });
  1207. ///
  1208. /// Preconditions:
  1209. ///
  1210. /// - `valid() == true` (else throws FutureInvalid)
  1211. ///
  1212. /// Postconditions:
  1213. ///
  1214. /// - `valid() == false`
  1215. /// - `RESULT.valid() == true`
  1216. template <class ExceptionType, class F>
  1217. Future<T> thenError(F&& func) &&;
  1218. template <class ExceptionType, class R, class... Args>
  1219. Future<T> thenError(R (&func)(Args...)) && {
  1220. return std::move(*this).template thenError<ExceptionType>(&func);
  1221. }
  1222. /// Set an error continuation for this Future where the continuation can
  1223. /// be called with `exception_wrapper&&` and returns a `T`, `Future<T>`, or
  1224. /// `SemiFuture<T>`.
  1225. ///
  1226. /// Example:
  1227. ///
  1228. /// makeFuture()
  1229. /// .thenTry([] {
  1230. /// throw std::runtime_error("oh no!");
  1231. /// return 42;
  1232. /// })
  1233. /// .thenError([] (exception_wrapper&& e) {
  1234. /// LOG(INFO) << e.what();
  1235. /// return -1; // or makeFuture<int>(-1) or makeSemiFuture<int>(-1)
  1236. /// });
  1237. ///
  1238. /// Preconditions:
  1239. ///
  1240. /// - `valid() == true` (else throws FutureInvalid)
  1241. ///
  1242. /// Postconditions:
  1243. ///
  1244. /// - `valid() == false`
  1245. /// - `RESULT.valid() == true`
  1246. template <class F>
  1247. Future<T> thenError(F&& func) &&;
  1248. template <class R, class... Args>
  1249. Future<T> thenError(R (&func)(Args...)) && {
  1250. return std::move(*this).thenError(&func);
  1251. }
  1252. /// Convenience method for ignoring the value and creating a Future<Unit>.
  1253. /// Exceptions still propagate.
  1254. /// This function is identical to .unit().
  1255. ///
  1256. /// Preconditions:
  1257. ///
  1258. /// - `valid() == true` (else throws FutureInvalid)
  1259. ///
  1260. /// Postconditions:
  1261. ///
  1262. /// - Calling code should act as if `valid() == false`,
  1263. /// i.e., as if `*this` was moved into RESULT.
  1264. /// - `RESULT.valid() == true`
  1265. Future<Unit> then() &&;
  1266. // clang-format off
  1267. [[deprecated(
  1268. "must be rvalue-qualified, e.g., std::move(future).thenValue()")]]
  1269. Future<Unit> then() & = delete;
  1270. // clang-format on
  1271. /// Convenience method for ignoring the value and creating a Future<Unit>.
  1272. /// Exceptions still propagate.
  1273. /// This function is identical to parameterless .then().
  1274. ///
  1275. /// Preconditions:
  1276. ///
  1277. /// - `valid() == true` (else throws FutureInvalid)
  1278. ///
  1279. /// Postconditions:
  1280. ///
  1281. /// - Calling code should act as if `valid() == false`,
  1282. /// i.e., as if `*this` was moved into RESULT.
  1283. /// - `RESULT.valid() == true`
  1284. Future<Unit> unit() && {
  1285. return std::move(*this).then();
  1286. }
  1287. /// Set an error continuation for this Future. The continuation should take an
  1288. /// argument of the type that you want to catch, and should return a value of
  1289. /// the same type as this Future, or a Future of that type (see overload
  1290. /// below).
  1291. ///
  1292. /// Example:
  1293. ///
  1294. /// makeFuture()
  1295. /// .thenValue([] {
  1296. /// throw std::runtime_error("oh no!");
  1297. /// return 42;
  1298. /// })
  1299. /// .thenError<std::runtime_error>([] (std::runtime_error& e) {
  1300. /// LOG(INFO) << "std::runtime_error: " << e.what();
  1301. /// return -1; // or makeFuture<int>(-1)
  1302. /// });
  1303. ///
  1304. /// Preconditions:
  1305. ///
  1306. /// - `valid() == true` (else throws FutureInvalid)
  1307. ///
  1308. /// Postconditions:
  1309. ///
  1310. /// - Calling code should act as if `valid() == false`,
  1311. /// i.e., as if `*this` was moved into RESULT.
  1312. /// - `RESULT.valid() == true`
  1313. template <class F>
  1314. typename std::enable_if<
  1315. !is_invocable<F, exception_wrapper>::value &&
  1316. !futures::detail::Extract<F>::ReturnsFuture::value,
  1317. Future<T>>::type
  1318. onError(F&& func) &&;
  1319. /// Overload of onError where the error continuation returns a Future<T>
  1320. ///
  1321. /// Preconditions:
  1322. ///
  1323. /// - `valid() == true` (else throws FutureInvalid)
  1324. ///
  1325. /// Postconditions:
  1326. ///
  1327. /// - Calling code should act as if `valid() == false`,
  1328. /// i.e., as if `*this` was moved into RESULT.
  1329. /// - `RESULT.valid() == true`
  1330. template <class F>
  1331. typename std::enable_if<
  1332. !is_invocable<F, exception_wrapper>::value &&
  1333. futures::detail::Extract<F>::ReturnsFuture::value,
  1334. Future<T>>::type
  1335. onError(F&& func) &&;
  1336. /// Overload of onError that takes exception_wrapper and returns Future<T>
  1337. ///
  1338. /// Preconditions:
  1339. ///
  1340. /// - `valid() == true` (else throws FutureInvalid)
  1341. ///
  1342. /// Postconditions:
  1343. ///
  1344. /// - Calling code should act as if `valid() == false`,
  1345. /// i.e., as if `*this` was moved into RESULT.
  1346. /// - `RESULT.valid() == true`
  1347. template <class F>
  1348. typename std::enable_if<
  1349. is_invocable<F, exception_wrapper>::value &&
  1350. futures::detail::Extract<F>::ReturnsFuture::value,
  1351. Future<T>>::type
  1352. onError(F&& func) &&;
  1353. /// Overload of onError that takes exception_wrapper and returns T
  1354. ///
  1355. /// Preconditions:
  1356. ///
  1357. /// - `valid() == true` (else throws FutureInvalid)
  1358. ///
  1359. /// Postconditions:
  1360. ///
  1361. /// - Calling code should act as if `valid() == false`,
  1362. /// i.e., as if `*this` was moved into RESULT.
  1363. /// - `RESULT.valid() == true`
  1364. template <class F>
  1365. typename std::enable_if<
  1366. is_invocable<F, exception_wrapper>::value &&
  1367. !futures::detail::Extract<F>::ReturnsFuture::value,
  1368. Future<T>>::type
  1369. onError(F&& func) &&;
  1370. // clang-format off
  1371. template <class F>
  1372. [[deprecated("use rvalue-qualified fn, eg, std::move(future).onError(...)")]]
  1373. Future<T> onError(F&& func) & {
  1374. return std::move(*this).onError(std::forward<F>(func));
  1375. }
  1376. /// func is like std::function<void()> and is executed unconditionally, and
  1377. /// the value/exception is passed through to the resulting Future.
  1378. /// func shouldn't throw, but if it does it will be captured and propagated,
  1379. /// and discard any value/exception that this Future has obtained.
  1380. ///
  1381. /// Preconditions:
  1382. ///
  1383. /// - `valid() == true` (else throws FutureInvalid)
  1384. ///
  1385. /// Postconditions:
  1386. ///
  1387. /// - Calling code should act as if `valid() == false`,
  1388. /// i.e., as if `*this` was moved into RESULT.
  1389. /// - `RESULT.valid() == true`
  1390. template <class F>
  1391. Future<T> ensure(F&& func) &&;
  1392. // clang-format on
  1393. /// Like onError, but for timeouts. example:
  1394. ///
  1395. /// Future<int> f = makeFuture<int>(42)
  1396. /// .delayed(long_time)
  1397. /// .onTimeout(short_time,
  1398. /// [] { return -1; });
  1399. ///
  1400. /// or perhaps
  1401. ///
  1402. /// Future<int> f = makeFuture<int>(42)
  1403. /// .delayed(long_time)
  1404. /// .onTimeout(short_time,
  1405. /// [] { return makeFuture<int>(some_exception); });
  1406. ///
  1407. /// Preconditions:
  1408. ///
  1409. /// - `valid() == true` (else throws FutureInvalid)
  1410. ///
  1411. /// Postconditions:
  1412. ///
  1413. /// - Calling code should act as if `valid() == false`,
  1414. /// i.e., as if `*this` was moved into RESULT.
  1415. /// - `RESULT.valid() == true`
  1416. template <class F>
  1417. Future<T> onTimeout(Duration, F&& func, Timekeeper* = nullptr) &&;
  1418. /// Throw FutureTimeout if this Future does not complete within the given
  1419. /// duration from now. The optional Timekeeper is as with futures::sleep().
  1420. ///
  1421. /// Preconditions:
  1422. ///
  1423. /// - `valid() == true` (else throws FutureInvalid)
  1424. ///
  1425. /// Postconditions:
  1426. ///
  1427. /// - Calling code should act as if `valid() == false`,
  1428. /// i.e., as if `*this` was moved into RESULT.
  1429. /// - `RESULT.valid() == true`
  1430. Future<T> within(Duration dur, Timekeeper* tk = nullptr) &&;
  1431. /// Throw the given exception if this Future does not complete within the
  1432. /// given duration from now. The optional Timekeeper is as with
  1433. /// futures::sleep().
  1434. ///
  1435. /// Preconditions:
  1436. ///
  1437. /// - `valid() == true` (else throws FutureInvalid)
  1438. ///
  1439. /// Postconditions:
  1440. ///
  1441. /// - Calling code should act as if `valid() == false`,
  1442. /// i.e., as if `*this` was moved into RESULT.
  1443. /// - `RESULT.valid() == true`
  1444. template <class E>
  1445. Future<T> within(Duration dur, E exception, Timekeeper* tk = nullptr) &&;
  1446. /// Delay the completion of this Future for at least this duration from
  1447. /// now. The optional Timekeeper is as with futures::sleep().
  1448. ///
  1449. /// Preconditions:
  1450. ///
  1451. /// - `valid() == true` (else throws FutureInvalid)
  1452. ///
  1453. /// Postconditions:
  1454. ///
  1455. /// - `valid() == false`
  1456. /// - `RESULT.valid() == true`
  1457. Future<T> delayed(Duration, Timekeeper* = nullptr) &&;
  1458. /// Delay the completion of this Future for at least this duration from
  1459. /// now. The optional Timekeeper is as with futures::sleep().
  1460. /// NOTE: Deprecated
  1461. /// WARNING: Returned future may complete on Timekeeper thread.
  1462. Future<T> delayedUnsafe(Duration, Timekeeper* = nullptr);
  1463. /// Blocks until the future is fulfilled. Returns the value (moved-out), or
  1464. /// throws the exception. The future must not already have a continuation.
  1465. ///
  1466. /// Preconditions:
  1467. ///
  1468. /// - `valid() == true` (else throws FutureInvalid)
  1469. ///
  1470. /// Postconditions:
  1471. ///
  1472. /// - `valid() == false`
  1473. T get() &&;
  1474. [[deprecated("must be rvalue-qualified, e.g., std::move(future).get()")]] T
  1475. get() & = delete;
  1476. /// Blocks until the future is fulfilled, or until `dur` elapses. Returns the
  1477. /// value (moved-out), or throws the exception (which might be a FutureTimeout
  1478. /// exception).
  1479. ///
  1480. /// Preconditions:
  1481. ///
  1482. /// - `valid() == true` (else throws FutureInvalid)
  1483. ///
  1484. /// Postconditions:
  1485. ///
  1486. /// - `valid() == false`
  1487. T get(Duration dur) &&;
  1488. [[deprecated("must be rvalue-qualified, e.g., std::move(future).get(dur)")]] T
  1489. get(Duration dur) & = delete;
  1490. /// A reference to the Try of the value
  1491. ///
  1492. /// Preconditions:
  1493. ///
  1494. /// - `valid() == true` (else throws FutureInvalid)
  1495. /// - `isReady() == true` (else throws FutureNotReady)
  1496. Try<T>& getTry();
  1497. /// Blocks until this Future is complete.
  1498. ///
  1499. /// Preconditions:
  1500. ///
  1501. /// - `valid() == true` (else throws FutureInvalid)
  1502. ///
  1503. /// Postconditions:
  1504. ///
  1505. /// - `valid() == true`
  1506. /// - `&RESULT == this`
  1507. /// - `isReady() == true`
  1508. Future<T>& wait() &;
  1509. /// Blocks until this Future is complete.
  1510. ///
  1511. /// Preconditions:
  1512. ///
  1513. /// - `valid() == true` (else throws FutureInvalid)
  1514. ///
  1515. /// Postconditions:
  1516. ///
  1517. /// - `valid() == true` (but the calling code can trivially move-out `*this`
  1518. /// by assigning or constructing the result into a distinct object).
  1519. /// - `&RESULT == this`
  1520. /// - `isReady() == true`
  1521. Future<T>&& wait() &&;
  1522. /// Blocks until this Future is complete, or `dur` elapses.
  1523. ///
  1524. /// Preconditions:
  1525. ///
  1526. /// - `valid() == true` (else throws FutureInvalid)
  1527. ///
  1528. /// Postconditions:
  1529. ///
  1530. /// - `valid() == true` (so you may call `wait(...)` repeatedly)
  1531. /// - `&RESULT == this`
  1532. /// - `isReady()` will be indeterminate - may or may not be true
  1533. Future<T>& wait(Duration dur) &;
  1534. /// Blocks until this Future is complete or until `dur` passes.
  1535. ///
  1536. /// Preconditions:
  1537. ///
  1538. /// - `valid() == true` (else throws FutureInvalid)
  1539. ///
  1540. /// Postconditions:
  1541. ///
  1542. /// - `valid() == true` (but the calling code can trivially move-out `*this`
  1543. /// by assigning or constructing the result into a distinct object).
  1544. /// - `&RESULT == this`
  1545. /// - `isReady()` will be indeterminate - may or may not be true
  1546. Future<T>&& wait(Duration dur) &&;
  1547. /// Call e->drive() repeatedly until the future is fulfilled. Examples
  1548. /// of DrivableExecutor include EventBase and ManualExecutor. Returns a
  1549. /// reference to this Future so that you can chain calls if desired.
  1550. /// value (moved-out), or throws the exception.
  1551. ///
  1552. /// Preconditions:
  1553. ///
  1554. /// - `valid() == true` (else throws FutureInvalid)
  1555. ///
  1556. /// Postconditions:
  1557. ///
  1558. /// - `valid() == true` (does not move-out `*this`)
  1559. /// - `&RESULT == this`
  1560. Future<T>& waitVia(DrivableExecutor* e) &;
  1561. /// Overload of waitVia() for rvalue Futures
  1562. ///
  1563. /// Preconditions:
  1564. ///
  1565. /// - `valid() == true` (else throws FutureInvalid)
  1566. ///
  1567. /// Postconditions:
  1568. ///
  1569. /// - `valid() == true` (but the calling code can trivially move-out `*this`
  1570. /// by assigning or constructing the result into a distinct object).
  1571. /// - `&RESULT == this`
  1572. Future<T>&& waitVia(DrivableExecutor* e) &&;
  1573. /// As waitVia but may return early after dur passes.
  1574. ///
  1575. /// Preconditions:
  1576. ///
  1577. /// - `valid() == true` (else throws FutureInvalid)
  1578. ///
  1579. /// Postconditions:
  1580. ///
  1581. /// - `valid() == true` (does not move-out `*this`)
  1582. /// - `&RESULT == this`
  1583. Future<T>& waitVia(TimedDrivableExecutor* e, Duration dur) &;
  1584. /// Overload of waitVia() for rvalue Futures
  1585. /// As waitVia but may return early after dur passes.
  1586. ///
  1587. /// Preconditions:
  1588. ///
  1589. /// - `valid() == true` (else throws FutureInvalid)
  1590. ///
  1591. /// Postconditions:
  1592. ///
  1593. /// - `valid() == true` (but the calling code can trivially move-out `*this`
  1594. /// by assigning or constructing the result into a distinct object).
  1595. /// - `&RESULT == this`
  1596. Future<T>&& waitVia(TimedDrivableExecutor* e, Duration dur) &&;
  1597. /// If the value in this Future is equal to the given Future, when they have
  1598. /// both completed, the value of the resulting Future<bool> will be true. It
  1599. /// will be false otherwise (including when one or both Futures have an
  1600. /// exception)
  1601. Future<bool> willEqual(Future<T>&);
  1602. /// predicate behaves like std::function<bool(T const&)>
  1603. /// If the predicate does not obtain with the value, the result
  1604. /// is a folly::FuturePredicateDoesNotObtain exception
  1605. ///
  1606. /// Preconditions:
  1607. ///
  1608. /// - `valid() == true` (else throws FutureInvalid)
  1609. ///
  1610. /// Postconditions:
  1611. ///
  1612. /// - Calling code should act as if `valid() == false`,
  1613. /// i.e., as if `*this` was moved into RESULT.
  1614. /// - `RESULT.valid() == true`
  1615. template <class F>
  1616. Future<T> filter(F&& predicate) &&;
  1617. /// Like reduce, but works on a Future<std::vector<T / Try<T>>>, for example
  1618. /// the result of collect or collectAll
  1619. ///
  1620. /// Preconditions:
  1621. ///
  1622. /// - `valid() == true` (else throws FutureInvalid)
  1623. ///
  1624. /// Postconditions:
  1625. ///
  1626. /// - Calling code should act as if `valid() == false`,
  1627. /// i.e., as if `*this` was moved into RESULT.
  1628. /// - `RESULT.valid() == true`
  1629. template <class I, class F>
  1630. Future<I> reduce(I&& initial, F&& func) &&;
  1631. /// Create a Future chain from a sequence of continuations. i.e.
  1632. ///
  1633. /// f.then(a).then(b).then(c)
  1634. ///
  1635. /// where f is a Future<A> and the result of the chain is a Future<D>
  1636. /// becomes
  1637. ///
  1638. /// std::move(f).thenMulti(a, b, c);
  1639. ///
  1640. /// Preconditions:
  1641. ///
  1642. /// - `valid() == true` (else throws FutureInvalid)
  1643. ///
  1644. /// Postconditions:
  1645. ///
  1646. /// - Calling code should act as if `valid() == false`,
  1647. /// i.e., as if `*this` was moved into RESULT.
  1648. /// - `RESULT.valid() == true`
  1649. template <class Callback, class... Callbacks>
  1650. auto thenMulti(Callback&& fn, Callbacks&&... fns) && {
  1651. // thenMulti with two callbacks is just then(a).thenMulti(b, ...)
  1652. // TODO(T29171940): Switch to thenImplementation here. It is ambiguous
  1653. // as then used to be but that is better than keeping then in the public
  1654. // API.
  1655. using R = futures::detail::callableResult<T, decltype(fn)>;
  1656. return std::move(*this)
  1657. .thenImplementation(std::forward<Callback>(fn), R{})
  1658. .thenMulti(std::forward<Callbacks>(fns)...);
  1659. }
  1660. /// Create a Future chain from a sequence of callbacks.
  1661. ///
  1662. /// Preconditions:
  1663. ///
  1664. /// - `valid() == true` (else throws FutureInvalid)
  1665. ///
  1666. /// Postconditions:
  1667. ///
  1668. /// - Calling code should act as if `valid() == false`,
  1669. /// i.e., as if `*this` was moved into RESULT.
  1670. /// - `RESULT.valid() == true`
  1671. template <class Callback>
  1672. auto thenMulti(Callback&& fn) && {
  1673. // thenMulti with one callback is just a then
  1674. // TODO(T29171940): Switch to thenImplementation here. It is ambiguous
  1675. // as then used to be but that is better than keeping then in the public
  1676. // API.
  1677. using R = futures::detail::callableResult<T, decltype(fn)>;
  1678. return std::move(*this).thenImplementation(std::forward<Callback>(fn), R{});
  1679. }
  1680. template <class Callback>
  1681. auto thenMulti(Callback&& fn) & {
  1682. return std::move(*this).thenMulti(std::forward<Callback>(fn));
  1683. }
  1684. /// Create a Future chain from a sequence of callbacks. i.e.
  1685. ///
  1686. /// f.via(executor).then(a).then(b).then(c).via(oldExecutor)
  1687. ///
  1688. /// where f is a Future<A> and the result of the chain is a Future<D>
  1689. /// becomes
  1690. ///
  1691. /// std::move(f).thenMultiWithExecutor(executor, a, b, c);
  1692. ///
  1693. /// Preconditions:
  1694. ///
  1695. /// - `valid() == true` (else throws FutureInvalid)
  1696. ///
  1697. /// Postconditions:
  1698. ///
  1699. /// - Calling code should act as if `valid() == false`,
  1700. /// i.e., as if `*this` was moved into RESULT.
  1701. /// - `RESULT.valid() == true`
  1702. template <class Callback, class... Callbacks>
  1703. auto
  1704. thenMultiWithExecutor(Executor* x, Callback&& fn, Callbacks&&... fns) && {
  1705. // thenMultiExecutor with two callbacks is
  1706. // via(x).then(a).thenMulti(b, ...).via(oldX)
  1707. auto oldX = this->getExecutor();
  1708. this->setExecutor(x);
  1709. // TODO(T29171940): Switch to thenImplementation here. It is ambiguous
  1710. // as then used to be but that is better than keeping then in the public
  1711. // API.
  1712. using R = futures::detail::callableResult<T, decltype(fn)>;
  1713. return std::move(*this)
  1714. .thenImplementation(std::forward<Callback>(fn), R{})
  1715. .thenMulti(std::forward<Callbacks>(fns)...)
  1716. .via(oldX);
  1717. }
  1718. template <class Callback>
  1719. auto thenMultiWithExecutor(Executor* x, Callback&& fn) && {
  1720. // thenMulti with one callback is just a then with an executor
  1721. return std::move(*this).then(x, std::forward<Callback>(fn));
  1722. }
  1723. /// Moves-out `*this`, creating/returning a corresponding SemiFuture.
  1724. /// Result will behave like `*this` except result won't have an Executor.
  1725. ///
  1726. /// Postconditions:
  1727. ///
  1728. /// - `RESULT.valid() ==` the original value of `this->valid()`
  1729. /// - RESULT will not have an Executor regardless of whether `*this` had one
  1730. SemiFuture<T> semi() && {
  1731. return SemiFuture<T>{std::move(*this)};
  1732. }
  1733. #if FOLLY_HAS_COROUTINES
  1734. // Overload needed to customise behaviour of awaiting a Future<T>
  1735. // inside a folly::coro::Task coroutine.
  1736. friend Future<T> co_viaIfAsync(
  1737. folly::Executor* executor,
  1738. Future<T>&& future) noexcept {
  1739. return std::move(future).via(executor);
  1740. }
  1741. #endif
  1742. protected:
  1743. friend class Promise<T>;
  1744. template <class>
  1745. friend class futures::detail::FutureBase;
  1746. template <class>
  1747. friend class Future;
  1748. template <class>
  1749. friend class SemiFuture;
  1750. template <class>
  1751. friend class FutureSplitter;
  1752. using Base::setExecutor;
  1753. using Base::throwIfContinued;
  1754. using Base::throwIfInvalid;
  1755. using typename Base::Core;
  1756. explicit Future(Core* obj) : Base(obj) {}
  1757. explicit Future(futures::detail::EmptyConstruct) noexcept
  1758. : Base(futures::detail::EmptyConstruct{}) {}
  1759. template <class T2>
  1760. friend Future<T2> makeFuture(Try<T2>);
  1761. /// Repeat the given future (i.e., the computation it contains) n times.
  1762. ///
  1763. /// thunk behaves like std::function<Future<T2>(void)>
  1764. template <class F>
  1765. friend Future<Unit> times(int n, F&& thunk);
  1766. /// Carry out the computation contained in the given future if
  1767. /// the predicate holds.
  1768. ///
  1769. /// thunk behaves like std::function<Future<T2>(void)>
  1770. template <class F>
  1771. friend Future<Unit> when(bool p, F&& thunk);
  1772. /// Carry out the computation contained in the given future if
  1773. /// while the predicate continues to hold.
  1774. ///
  1775. /// thunk behaves like std::function<Future<T2>(void)>
  1776. ///
  1777. /// predicate behaves like std::function<bool(void)>
  1778. template <class P, class F>
  1779. friend Future<Unit> whileDo(P&& predicate, F&& thunk);
  1780. template <class FT>
  1781. friend void futures::detail::convertFuture(
  1782. SemiFuture<FT>&& sf,
  1783. Future<FT>& f);
  1784. };
  1785. /// A Timekeeper handles the details of keeping time and fulfilling delay
  1786. /// promises. The returned Future<Unit> will either complete after the
  1787. /// elapsed time, or in the event of some kind of exceptional error may hold
  1788. /// an exception. These Futures respond to cancellation. If you use a lot of
  1789. /// Delays and many of them ultimately are unneeded (as would be the case for
  1790. /// Delays that are used to trigger timeouts of async operations), then you
  1791. /// can and should cancel them to reclaim resources.
  1792. ///
  1793. /// Users will typically get one of these via Future::sleep(Duration dur) or
  1794. /// use them implicitly behind the scenes by passing a timeout to some Future
  1795. /// operation.
  1796. ///
  1797. /// Although we don't formally alias Delay = Future<Unit>,
  1798. /// that's an appropriate term for it. People will probably also call these
  1799. /// Timeouts, and that's ok I guess, but that term is so overloaded I thought
  1800. /// it made sense to introduce a cleaner term.
  1801. ///
  1802. /// Remember that Duration is a std::chrono duration (millisecond resolution
  1803. /// at the time of writing). When writing code that uses specific durations,
  1804. /// prefer using the explicit std::chrono type, e.g. std::chrono::milliseconds
  1805. /// over Duration. This makes the code more legible and means you won't be
  1806. /// unpleasantly surprised if we redefine Duration to microseconds, or
  1807. /// something.
  1808. ///
  1809. /// timekeeper.after(std::chrono::duration_cast<Duration>(someNanoseconds))
  1810. class Timekeeper {
  1811. public:
  1812. virtual ~Timekeeper() = default;
  1813. /// Returns a future that will complete after the given duration with the
  1814. /// elapsed time. Exceptional errors can happen but they must be
  1815. /// exceptional. Use the steady (monotonic) clock.
  1816. ///
  1817. /// The consumer thread may cancel this Future to reclaim resources.
  1818. ///
  1819. /// This future probably completes on the timer thread. You should almost
  1820. /// certainly follow it with a via() call or the accuracy of other timers
  1821. /// will suffer.
  1822. virtual Future<Unit> after(Duration dur) = 0;
  1823. /// Returns a future that will complete at the requested time.
  1824. ///
  1825. /// You may cancel this Future to reclaim resources.
  1826. ///
  1827. /// NB This is sugar for `after(when - now)`, so while you are welcome to
  1828. /// use a std::chrono::system_clock::time_point it will not track changes to
  1829. /// the system clock but rather execute that many milliseconds in the future
  1830. /// according to the steady clock.
  1831. template <class Clock>
  1832. Future<Unit> at(std::chrono::time_point<Clock> when);
  1833. };
  1834. template <class T>
  1835. std::pair<Promise<T>, Future<T>> makePromiseContract(Executor* e) {
  1836. auto p = Promise<T>();
  1837. auto f = p.getSemiFuture().via(e);
  1838. return std::make_pair(std::move(p), std::move(f));
  1839. }
  1840. } // namespace folly
  1841. #if FOLLY_HAS_COROUTINES
  1842. namespace folly {
  1843. namespace detail {
  1844. template <typename T>
  1845. class FutureAwaitable {
  1846. public:
  1847. explicit FutureAwaitable(folly::Future<T>&& future) noexcept
  1848. : future_(std::move(future)) {}
  1849. bool await_ready() const {
  1850. return future_.isReady();
  1851. }
  1852. T await_resume() {
  1853. return std::move(result_).value();
  1854. }
  1855. void await_suspend(std::experimental::coroutine_handle<> h) {
  1856. future_.setCallback_([this, h](Try<T>&& result) mutable {
  1857. result_ = std::move(result);
  1858. h.resume();
  1859. });
  1860. }
  1861. private:
  1862. folly::Try<T> result_;
  1863. folly::Future<T> future_;
  1864. };
  1865. } // namespace detail
  1866. template <typename T>
  1867. inline detail::FutureAwaitable<T>
  1868. /* implicit */ operator co_await(Future<T>&& future) noexcept {
  1869. return detail::FutureAwaitable<T>(std::move(future));
  1870. }
  1871. } // namespace folly
  1872. #endif
  1873. #include <folly/futures/Future-inl.h>