(wangle) cold via
[folly.git] / folly / wangle / Later.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <folly/wangle/Executor.h>
20 #include <folly/wangle/Future.h>
21 #include <folly/Optional.h>
22
23 namespace folly { namespace wangle {
24
25 template <typename T> struct isLaterOrFuture;
26 template <typename T> struct isLater;
27
28 /*
29  * Later is like a cold Future, but makes it easier to avoid triggering until
30  * later, because it must be triggered explicitly. An equivalence example will
31  * help differentiate:
32  *
33  *   Later<Foo> later =
34  *     Later<Foo>(std::move(foo))
35  *     .then(cb1)
36  *     .via(ex1)
37  *     .then(cb2)
38  *     .then(cb3)
39  *     .via(ex2)
40  *     .then(cb4)
41  *     .then(cb5);
42  *   ...
43  *   later.launch();
44  *
45  *   Future<Foo> coldFuture = makeFuture(std::move(foo));
46  *   coldFuture.deactivate();
47  *   coldFuture
48  *     .then(cb1)
49  *     .via(ex1)
50  *     .then(cb2)
51  *     .then(cb3)
52  *     .via(ex2)
53  *     .then(cb4)
54  *     .then(cb5);
55  *   ...
56  *   coldFuture.activate();
57  *
58  * Using a Later means you don't have to grab a handle to the first Future and
59  * deactivate it.
60  *
61  * Later used to be a workaround to the thread-unsafe nature of Future
62  * chaining, but that has changed and there is no need to use Later if your
63  * only goal is to traverse thread boundaries with executors. In that case,
64  * just use Future::via().
65  *
66  * Here is an example of a workflow:
67  *
68  * Later<ClientRequest> later(std::move(request));
69  *
70  * auto future = later.
71  *   .via(cpuExecutor)
72  *   .then([=](Try<ClientRequest>&& t) { return doCpuWork(t.value()); })
73  *   .via(diskExecutor)
74  *   .then([=](Try<CpuResponse>&& t) { return doDiskWork(t.value()); })
75  *   .via(serverExecutor)
76  *   .then([=]Try<DiskResponse>&& t) { return sendClientResponse(t.value()); })
77  *   .launch();
78  */
79 template <class T>
80 class Later {
81  public:
82   typedef T value_type;
83
84   /*
85    * This default constructor is used to build an asynchronous workflow that
86    * takes no input.
87    */
88   template <class U = void,
89             class = typename std::enable_if<std::is_void<U>::value>::type,
90             class = typename std::enable_if<std::is_same<T, U>::value>::type>
91   Later();
92
93   /*
94    * Lift a Future into a Later
95    */
96   /* implicit */ Later(Future<T>&& f);
97
98   /*
99    * This constructor is used to build an asynchronous workflow that takes a
100    * value as input, and that value is passed in.
101    */
102   template <class U,
103             class = typename std::enable_if<!std::is_void<U>::value>::type,
104             class = typename std::enable_if<std::is_same<T, U>::value>::type>
105   explicit Later(U&& input);
106
107   /*
108    * This constructor is used to wrap a pre-existing cob-style asynchronous api
109    * so that it can be used in wangle. wangle provides the callback to this
110    * pre-existing api, and this callback will fulfill a promise so as to
111    * incorporate this api into the workflow.
112    *
113    * Example usage:
114    *
115    * // This adds two ints asynchronously. cob is called in another thread.
116    * void addAsync(int a, int b, std::function<void(int&&)>&& cob);
117    *
118    * Later<int> asyncWrapper([=](std::function<void(int&&)>&& fn) {
119    *   addAsync(1, 2, std::move(fn));
120    * });
121    */
122   // TODO we should implement a makeFuture-ish with this pattern too, now.
123   template <class U,
124             class = typename std::enable_if<!std::is_void<U>::value>::type,
125             class = typename std::enable_if<std::is_same<T, U>::value>::type>
126   explicit Later(std::function<void(std::function<void(U&&)>&&)>&& fn);
127
128   /*
129    * then() adds additional work to the end of the workflow. If the lambda
130    * provided to then() returns a future, that future must be fulfilled in the
131    * same thread of the last set executor (either at constructor or from a call
132    * to via()).
133    */
134   template <class F>
135   typename std::enable_if<
136     !isLaterOrFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
137     Later<typename std::result_of<F(Try<T>&&)>::type> >::type
138   then(F&& fn);
139
140   template <class F>
141   typename std::enable_if<
142     isFuture<typename std::result_of<F(Try<T>&&)>::type>::value,
143     Later<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
144   then(F&& fn);
145
146   /*
147    * If the function passed to then() returns a Later<T>, calls to then() will
148    * be chained to the new Later before launching the new Later.
149    *
150    * This can be used to build asynchronous modules that can be called from a
151    * user thread and completed in a callback thread.
152    *
153    * Using the Later(std::function<void(std::function<void(T&&)>)>&& fn)
154    * constructor, you can wrap existing asynchronous modules with a Later and
155    * can chain it to wangle asynchronous workflows via this call.
156    */
157   template <class F>
158   typename std::enable_if<
159     isLater<typename std::result_of<F(Try<T>&&)>::type>::value,
160     Later<typename std::result_of<F(Try<T>&&)>::type::value_type> >::type
161   then(F&& fn);
162
163   /*
164    * Resets the executor - all then() calls made after the call to via() will be
165    * made in the new executor. The Executor must outlive.
166    */
167   Later<T> via(Executor* executor);
168
169   /*
170    * Starts the workflow. The function provided in the constructor will be
171    * called in the executor provided in the constructor. Subsequent then()
172    * calls will be made, potentially changing threads if a via() call is made.
173    * The future returned will be fulfilled in the last executor.
174    */
175   Future<T> launch();
176
177   /*
178    * Deprecated. Use launch()
179    */
180   void fireAndForget() __attribute__ ((deprecated)) { launch(); }
181
182  private:
183   Promise<void> starter_;
184   folly::Optional<Future<T>> future_;
185
186   struct hide { };
187
188   explicit Later(Promise<void>&& starter);
189
190   template <class U>
191   friend class Later;
192 };
193
194 }}
195
196 #include "Later-inl.h"