Debian Codegraph @

src/core/lib/promise/try_concurrently.h

raw
1 // Copyright 2022 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_CORE_LIB_PROMISE_TRY_CONCURRENTLY_H
16 #define GRPC_CORE_LIB_PROMISE_TRY_CONCURRENTLY_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <stddef.h>
21
22 #include <cstdint>
23 #include <utility>
24
25 #include "absl/types/variant.h"
26
27 #include <grpc/support/log.h>
28
29 #include "src/core/lib/gprpp/construct_destruct.h"
30 #include "src/core/lib/promise/detail/promise_like.h"
31 #include "src/core/lib/promise/detail/status.h"
32 #include "src/core/lib/promise/poll.h"
33
34 namespace grpc_core {
35
36 namespace promise_detail {
37
38 template <typename Promise>
39 struct Necessary {
40 PromiseLike<Promise> promise;
41 static constexpr bool must_complete() { return true; }
42 };
43
44 template <typename Promise>
45 struct Helper {
46 PromiseLike<Promise> promise;
47 static constexpr bool must_complete() { return false; }
48 };
49
50 // A set of promises that can be polled concurrently.
51 // Fuses them when completed (that is, destroys the promise and records it
52 // completed).
53 // Relies on an external bit field to handle the recording: this saves a bunch
54 // of space, but means the implementation of this type is weird: it's really
55 // super tied to TryConcurrently and no attempt should be made to use this
56 // independently.
57 template <typename... Ts>
58 class FusedSet;
59
60 template <typename T, typename... Ts>
61 class FusedSet<T, Ts...> : public FusedSet<Ts...> {
62 public:
63 explicit FusedSet(T&& x, Ts&&... xs)
64 : FusedSet<Ts...>(std::forward<T>(xs)...) {
65 Construct(&wrapper_, std::forward<T>(x));
66 }
67 explicit FusedSet(T&& x, FusedSet<Ts...>&& xs)
68 : FusedSet<Ts...>(std::forward<FusedSet<Ts...>>(xs)) {
69 Construct(&wrapper_, std::forward<T>(x));
70 }
71 // Empty destructor: consumers must call Destroy() to ensure cleanup occurs
72 ~FusedSet() {}
73
74 FusedSet(const FusedSet&) = delete;
75 FusedSet& operator=(const FusedSet&) = delete;
76
77 // Assumes all 'done_bits' for other are 0 and will be set to 1
78 FusedSet(FusedSet&& other) noexcept : FusedSet<Ts...>(std::move(other)) {
79 Construct(&wrapper_, std::move(other.wrapper_));
80 Destruct(&other.wrapper_);
81 }
82
83 static constexpr size_t Size() { return 1 + sizeof...(Ts); }
84
85 static constexpr uint8_t NecessaryBits() {
86 return (T::must_complete() ? 1 : 0) |
87 (FusedSet<Ts...>::NecessaryBits() << 1);
88 }
89
90 template <int kDoneBit>
91 void Destroy(uint8_t done_bits) {
92 if ((done_bits & (1 << kDoneBit)) == 0) {
93 Destruct(&wrapper_);
94 }
95 FusedSet<Ts...>::template Destroy<kDoneBit + 1>(done_bits);
96 }
97
98 template <typename Result, int kDoneBit>
99 Poll<Result> Run(uint8_t& done_bits) {
100 if ((done_bits & (1 << kDoneBit)) == 0) {
101 auto p = wrapper_.promise();
102 if (auto* status = absl::get_if<kPollReadyIdx>(&p)) {
103 done_bits |= (1 << kDoneBit);
104 Destruct(&wrapper_);
105 if (!IsStatusOk(*status)) {
106 return StatusCast<Result>(std::move(*status));
107 }
108 }
109 }
110 return FusedSet<Ts...>::template Run<Result, kDoneBit + 1>(done_bits);
111 }
112
113 template <typename P>
114 FusedSet<P, T, Ts...> With(P x) {
115 return FusedSet<P, T, Ts...>(std::move(x), std::move(*this));
116 }
117
118 private:
119 union {
120 T wrapper_;
121 };
122 };
123
124 template <>
125 class FusedSet<> {
126 public:
127 static constexpr size_t Size() { return 0; }
128 static constexpr uint8_t NecessaryBits() { return 0; }
129
130 template <typename Result, int kDoneBit>
131 Poll<Result> Run(uint8_t) {
132 return Pending{};
133 }
134 template <int kDoneBit>
135 void Destroy(uint8_t) {}
136
137 template <typename P>
138 FusedSet<P> With(P x) {
139 return FusedSet<P>(std::move(x));
140 }
141 };
142
143 template <typename Main, typename PreMain, typename PostMain>
144 class TryConcurrently {
145 public:
146 TryConcurrently(Main main, PreMain pre_main, PostMain post_main)
147 : done_bits_(0),
148 pre_main_(std::move(pre_main)),
149 post_main_(std::move(post_main)) {
150 Construct(&main_, std::move(main));
151 }
152
153 TryConcurrently(const TryConcurrently&) = delete;
154 TryConcurrently& operator=(const TryConcurrently&) = delete;
155 TryConcurrently(TryConcurrently&& other) noexcept
156 : done_bits_(0),
157 pre_main_(std::move(other.pre_main_)),
158 post_main_(std::move(other.post_main_)) {
159 GPR_DEBUG_ASSERT(other.done_bits_ == 0);
160 other.done_bits_ = HelperBits();
161 Construct(&main_, std::move(other.main_));
162 }
163 TryConcurrently& operator=(TryConcurrently&& other) noexcept {
164 GPR_DEBUG_ASSERT(other.done_bits_ == 0);
165 done_bits_ = 0;
166 other.done_bits_ = HelperBits();
167 pre_main_ = std::move(other.pre_main_);
168 post_main_ = std::move(other.post_main_);
169 Construct(&main_, std::move(other.main_));
170 return *this;
171 }
172
173 ~TryConcurrently() {
174 if (done_bits_ & 1) {
175 Destruct(&result_);
176 } else {
177 Destruct(&main_);
178 }
179 pre_main_.template Destroy<1>(done_bits_);
180 post_main_.template Destroy<1 + PreMain::Size()>(done_bits_);
181 }
182
183 using Result =
184 typename PollTraits<decltype(std::declval<PromiseLike<Main>>()())>::Type;
185
186 Poll<Result> operator()() {
187 auto r = pre_main_.template Run<Result, 1>(done_bits_);
188 if (auto* status = absl::get_if<Result>(&r)) {
189 GPR_DEBUG_ASSERT(!IsStatusOk(*status));
190 return std::move(*status);
191 }
192 if ((done_bits_ & 1) == 0) {
193 auto p = main_();
194 if (auto* status = absl::get_if<kPollReadyIdx>(&p)) {
195 done_bits_ |= 1;
196 Destruct(&main_);
197 Construct(&result_, std::move(*status));
198 }
199 }
200 r = post_main_.template Run<Result, 1 + PreMain::Size()>(done_bits_);
201 if (auto* status = absl::get_if<Result>(&r)) {
202 GPR_DEBUG_ASSERT(!IsStatusOk(*status));
203 return std::move(*status);
204 }
205 if ((done_bits_ & NecessaryBits()) == NecessaryBits()) {
206 return std::move(result_);
207 }
208 return Pending{};
209 }
210
211 template <typename P>
212 auto NecessaryPush(P p);
213 template <typename P>
214 auto NecessaryPull(P p);
215 template <typename P>
216 auto Push(P p);
217 template <typename P>
218 auto Pull(P p);
219
220 private:
221 // Bitmask for done_bits_ specifying which promises must be completed prior to
222 // returning ok.
223 constexpr uint8_t NecessaryBits() {
224 return 1 | (PreMain::NecessaryBits() << 1) |
225 (PostMain::NecessaryBits() << (1 + PreMain::Size()));
226 }
227 // Bitmask for done_bits_ specifying what all of the promises being complete
228 // would look like.
229 constexpr uint8_t AllBits() {
230 return (1 << (1 + PreMain::Size() + PostMain::Size())) - 1;
231 }
232 // Bitmask of done_bits_ specifying which bits correspond to helper promises -
233 // that is all promises that are not the main one.
234 constexpr uint8_t HelperBits() { return AllBits() ^ 1; }
235
236 // done_bits signifies which operations have completed.
237 // Bit 0 is set if main_ has completed.
238 // The next higher bits correspond one per pre-main promise.
239 // The next higher bits correspond one per post-main promise.
240 // So, going from most significant bit to least significant:
241 // +--------------+-------------+--------+
242 // |post_main bits|pre_main bits|main bit|
243 // +--------------+-------------+--------+
244 uint8_t done_bits_;
245 PreMain pre_main_;
246 union {
247 PromiseLike<Main> main_;
248 Result result_;
249 };
250 PostMain post_main_;
251 };
252
253 template <typename Main, typename PreMain, typename PostMain>
254 auto MakeTryConcurrently(Main&& main, PreMain&& pre_main,
255 PostMain&& post_main) {
256 return TryConcurrently<Main, PreMain, PostMain>(
257 std::forward<Main>(main), std::forward<PreMain>(pre_main),
258 std::forward<PostMain>(post_main));
259 }
260
261 template <typename Main, typename PreMain, typename PostMain>
262 template <typename P>
263 auto TryConcurrently<Main, PreMain, PostMain>::NecessaryPush(P p) {
264 GPR_DEBUG_ASSERT(done_bits_ == 0);
265 done_bits_ = HelperBits();
266 return MakeTryConcurrently(std::move(main_),
267 pre_main_.With(Necessary<P>{std::move(p)}),
268 std::move(post_main_));
269 }
270
271 template <typename Main, typename PreMain, typename PostMain>
272 template <typename P>
273 auto TryConcurrently<Main, PreMain, PostMain>::NecessaryPull(P p) {
274 GPR_DEBUG_ASSERT(done_bits_ == 0);
275 done_bits_ = HelperBits();
276 return MakeTryConcurrently(std::move(main_), std::move(pre_main_),
277 post_main_.With(Necessary<P>{std::move(p)}));
278 }
279
280 template <typename Main, typename PreMain, typename PostMain>
281 template <typename P>
282 auto TryConcurrently<Main, PreMain, PostMain>::Push(P p) {
283 GPR_DEBUG_ASSERT(done_bits_ == 0);
284 done_bits_ = HelperBits();
285 return MakeTryConcurrently(std::move(main_),
286 pre_main_.With(Helper<P>{std::move(p)}),
287 std::move(post_main_));
288 }
289
290 template <typename Main, typename PreMain, typename PostMain>
291 template <typename P>
292 auto TryConcurrently<Main, PreMain, PostMain>::Pull(P p) {
293 GPR_DEBUG_ASSERT(done_bits_ == 0);
294 done_bits_ = HelperBits();
295 return MakeTryConcurrently(std::move(main_), std::move(pre_main_),
296 post_main_.With(Helper<P>{std::move(p)}));
297 }
298
299 } // namespace promise_detail
300
301 // TryConcurrently runs a set of promises concurrently.
302 // There is a structure to the promises:
303 // - A 'main' promise dominates the others - it must complete before the
304 // overall promise successfully completes. Its result is chosen in the event
305 // of successful completion.
306 // - A set of (optional) push and pull promises to aid main. Push promises are
307 // polled before main, pull promises are polled after. In this way we can
308 // avoid overall wakeup churn - sending a message will tend to push things
309 // down the promise tree as its polled, so that send should be in a push
310 // promise - then as the main promise is polled and it calls into things
311 // lower in the stack they'll already see things there (this reasoning holds
312 // for receiving things and the pull promises too!).
313 // - Each push and pull promise is either necessary or optional.
314 // Necessary promises must complete successfully before the overall promise
315 // completes. Optional promises will just be cancelled once the main promise
316 // completes and any necessary helpers.
317 // - If any of the promises fail, the overall promise fails immediately.
318 // API:
319 // This function, TryConcurrently, is used to create a TryConcurrently promise.
320 // It takes a single argument, being the main promise. That promise also has
321 // a set of methods for attaching push and pull promises. The act of attachment
322 // returns a new TryConcurrently promise with previous contained promises moved
323 // out.
324 // The methods exposed:
325 // - Push, NecessaryPush: attach a push promise (with the first variant being
326 // optional, the second necessary).
327 // - Pull, NecessaryPull: attach a pull promise, with variants as above.
328 // Example:
329 // TryConcurrently(call_next_filter(std::move(call_args)))
330 // .Push(send_messages_promise)
331 // .Pull(recv_messages_promise)
332 template <typename Main>
333 auto TryConcurrently(Main main) {
334 return promise_detail::MakeTryConcurrently(std::move(main),
335 promise_detail::FusedSet<>(),
336 promise_detail::FusedSet<>());
337 }
338
339 } // namespace grpc_core
340
341 #endif // GRPC_CORE_LIB_PROMISE_TRY_CONCURRENTLY_H