Debian Codegraph @

src/core/lib/promise/detail/basic_seq.h

raw
1 // Copyright 2021 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_DETAIL_BASIC_SEQ_H
16 #define GRPC_CORE_LIB_PROMISE_DETAIL_BASIC_SEQ_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <array>
21 #include <cassert>
22 #include <new>
23 #include <tuple>
24 #include <utility>
25
26 #include "absl/meta/type_traits.h"
27 #include "absl/types/variant.h"
28 #include "absl/utility/utility.h"
29
30 #include "src/core/lib/gprpp/construct_destruct.h"
31 #include "src/core/lib/promise/detail/promise_factory.h"
32 #include "src/core/lib/promise/detail/promise_like.h"
33 #include "src/core/lib/promise/detail/switch.h"
34 #include "src/core/lib/promise/poll.h"
35
36 namespace grpc_core {
37 namespace promise_detail {
38
39 // Helper for SeqState to evaluate some common types to all partial
40 // specializations.
41 template <template <typename> class Traits, typename FPromise, typename FNext>
42 struct SeqStateTypes {
43 // Our current promise.
44 using Promise = FPromise;
45 // The result of our current promise.
46 using PromiseResult = typename Promise::Result;
47 // Traits around the result of our promise.
48 using PromiseResultTraits = Traits<PromiseResult>;
49 // Wrap the factory callable in our factory wrapper to deal with common edge
50 // cases. We use the 'unwrapped type' from the traits, so for instance, TrySeq
51 // can pass back a T from a StatusOr<T>.
52 using Next = promise_detail::OncePromiseFactory<
53 typename PromiseResultTraits::UnwrappedType, FNext>;
54 };
55
56 // One state in a sequence.
57 // A state contains the current promise, and the promise factory to turn the
58 // result of the current promise into the next state's promise. We play a shell
59 // game such that the prior state and our current promise are kept in a union,
60 // and the next promise factory is kept alongside in the state struct.
61 // Recursively this guarantees that the next functions get initialized once, and
62 // destroyed once, and don't need to be moved around in between, which avoids a
63 // potential O(n**2) loop of next factory moves had we used a variant of states
64 // here. The very first state does not have a prior state, and so that state has
65 // a partial specialization below. The final state does not have a next state;
66 // that state is inlined in BasicSeq since that was simpler to type.
67 template <template <typename> class Traits, char I, typename... Fs>
68 struct SeqState {
69 // The state evaluated before this state.
70 using PriorState = SeqState<Traits, I - 1, Fs...>;
71 // Initialization from callables.
72 explicit SeqState(std::tuple<Fs*...> fs)
73 : next_factory(std::move(*std::get<I + 1>(fs))) {
74 new (&prior) PriorState(fs);
75 }
76 // Move constructor - assumes we're in the initial state (move prior) as it's
77 // illegal to move a promise after polling it.
78 SeqState(SeqState&& other) noexcept
79 : next_factory(std::move(other.next_factory)) {
80 new (&prior) PriorState(std::move(other.prior));
81 }
82 // Copy constructor - assumes we're in the initial state (move prior) as it's
83 // illegal to move a promise after polling it.
84 SeqState(const SeqState& other) : next_factory(other.next_factory) {
85 new (&prior) PriorState(std::move(other.prior));
86 }
87 // Empty destructor - we instead destruct the innards in BasicSeq manually
88 // depending on state.
89 ~SeqState() {}
90 // Evaluate the current promise, next promise factory types for this state.
91 // The current promise is the next promise from the prior state.
92 // The next factory callable is from the callables passed in:
93 // Fs[0] is the initial promise, Fs[1] is the state 0 next factory, Fs[2] is
94 // the state 1 next factory, etc...
95 using Types = SeqStateTypes<
96 Traits, typename PriorState::Types::Next::Promise,
97 typename std::tuple_element<I + 1, std::tuple<Fs...>>::type>;
98 // Storage for either the current promise or the prior state.
99 union {
100 // If we're in the prior state.
101 GPR_NO_UNIQUE_ADDRESS PriorState prior;
102 // The callables representing our promise.
103 GPR_NO_UNIQUE_ADDRESS typename Types::Promise current_promise;
104 };
105 // Storage for the next promise factory.
106 GPR_NO_UNIQUE_ADDRESS typename Types::Next next_factory;
107 };
108
109 // Partial specialization of SeqState above for the first state - it has no
110 // prior state, so we take the first callable from the template arg list and use
111 // it as a promise.
112 template <template <typename> class Traits, typename... Fs>
113 struct SeqState<Traits, 0, Fs...> {
114 // Initialization from callables.
115 explicit SeqState(std::tuple<Fs*...> args)
116 : current_promise(std::move(*std::get<0>(args))),
117 next_factory(std::move(*std::get<1>(args))) {}
118 // Move constructor - it's assumed we're in this state (see above).
119 SeqState(SeqState&& other) noexcept
120 : current_promise(std::move(other.current_promise)),
121 next_factory(std::move(other.next_factory)) {}
122 // Copy constructor - it's assumed we're in this state (see above).
123 SeqState(const SeqState& other)
124 : current_promise(other.current_promise),
125 next_factory(other.next_factory) {}
126 // Empty destructor - we instead destruct the innards in BasicSeq manually
127 // depending on state.
128 ~SeqState() {}
129 // Evaluate the current promise, next promise factory types for this state.
130 // Our callable is the first element of Fs, wrapped in PromiseLike to handle
131 // some common edge cases. The next factory is the second element.
132 using Types = SeqStateTypes<
133 Traits,
134 PromiseLike<typename std::tuple_element<0, std::tuple<Fs...>>::type>,
135 typename std::tuple_element<1, std::tuple<Fs...>>::type>;
136 GPR_NO_UNIQUE_ADDRESS typename Types::Promise current_promise;
137 GPR_NO_UNIQUE_ADDRESS typename Types::Next next_factory;
138 };
139
140 // Helper to get a specific state index.
141 // Calls the prior state, unless it's this state, in which case it returns
142 // that.
143 template <char I, template <typename> class Traits, char J, typename... Fs>
144 struct GetSeqStateInner {
145 static SeqState<Traits, I, Fs...>* f(SeqState<Traits, J, Fs...>* p) {
146 return GetSeqStateInner<I, Traits, J - 1, Fs...>::f(&p->prior);
147 }
148 };
149
150 template <char I, template <typename> class Traits, typename... Fs>
151 struct GetSeqStateInner<I, Traits, I, Fs...> {
152 static SeqState<Traits, I, Fs...>* f(SeqState<Traits, I, Fs...>* p) {
153 return p;
154 }
155 };
156
157 template <char I, template <typename> class Traits, char J, typename... Fs>
158 absl::enable_if_t<I <= J, SeqState<Traits, I, Fs...>*> GetSeqState(
159 SeqState<Traits, J, Fs...>* p) {
160 return GetSeqStateInner<I, Traits, J, Fs...>::f(p);
161 }
162
163 template <template <typename> class Traits, char I, typename... Fs, typename T>
164 auto CallNext(SeqState<Traits, I, Fs...>* state, T&& arg)
165 -> decltype(SeqState<Traits, I, Fs...>::Types::PromiseResultTraits::
166 CallFactory(&state->next_factory, std::forward<T>(arg))) {
167 return SeqState<Traits, I, Fs...>::Types::PromiseResultTraits::CallFactory(
168 &state->next_factory, std::forward<T>(arg));
169 }
170
171 // A sequence under stome traits for some set of callables Fs.
172 // Fs[0] should be a promise-like object that yields a value.
173 // Fs[1..] should be promise-factory-like objects that take the value from the
174 // previous step and yield a promise. Note that most of the machinery in
175 // PromiseFactory exists to make it possible for those promise-factory-like
176 // objects to be anything that's convenient. Traits defines how we move from one
177 // step to the next. Traits sets up the wrapping and escape handling for the
178 // sequence. Promises return wrapped values that the trait can inspect and
179 // unwrap before passing them to the next element of the sequence. The trait can
180 // also interpret a wrapped value as an escape value, which terminates
181 // evaluation of the sequence immediately yielding a result. Traits for type T
182 // have the members:
183 // * type UnwrappedType - the type after removing wrapping from T (i.e. for
184 // TrySeq, T=StatusOr<U> yields UnwrappedType=U).
185 // * type WrappedType - the type after adding wrapping if it doesn't already
186 // exist (i.e. for TrySeq if T is not Status/StatusOr/void, then
187 // WrappedType=StatusOr<T>; if T is Status then WrappedType=Status (it's
188 // already wrapped!))
189 // * template <typename Next> void CallFactory(Next* next_factory, T&& value) -
190 // call promise factory next_factory with the result of unwrapping value, and
191 // return the resulting promise.
192 // * template <typename Result, typename RunNext> Poll<Result>
193 // CheckResultAndRunNext(T prior, RunNext run_next) - examine the value of
194 // prior, and decide to escape or continue. If escaping, return the final
195 // sequence value of type Poll<Result>. If continuing, return the value of
196 // run_next(std::move(prior)).
197 template <template <typename> class Traits, typename... Fs>
198 class BasicSeq {
199 private:
200 // Number of states in the sequence - we'll refer to this some!
201 static constexpr char N = sizeof...(Fs);
202
203 // Current state.
204 static_assert(N < 128, "Long sequence... please revisit BasicSeq");
205 char state_ = 0;
206 // The penultimate state contains all the preceding states too.
207 using PenultimateState = SeqState<Traits, N - 2, Fs...>;
208 // The final state is simply the final promise, which is the next promise from
209 // the penultimate state.
210 using FinalPromise = typename PenultimateState::Types::Next::Promise;
211 union {
212 GPR_NO_UNIQUE_ADDRESS PenultimateState penultimate_state_;
213 GPR_NO_UNIQUE_ADDRESS FinalPromise final_promise_;
214 };
215 using FinalPromiseResult = typename FinalPromise::Result;
216 using Result = typename Traits<FinalPromiseResult>::WrappedType;
217
218 // Get a state by index.
219 template <char I>
220 absl::enable_if_t < I<N - 2, SeqState<Traits, I, Fs...>*> state() {
221 return GetSeqState<I>(&penultimate_state_);
222 }
223
224 template <char I>
225 absl::enable_if_t<I == N - 2, PenultimateState*> state() {
226 return &penultimate_state_;
227 }
228
229 // Get the next state's promise.
230 template <char I>
231 auto next_promise() -> absl::enable_if_t<
232 I != N - 2,
233 decltype(&GetSeqState<I + 1>(static_cast<PenultimateState*>(nullptr))
234 ->current_promise)> {
235 return &GetSeqState<I + 1>(&penultimate_state_)->current_promise;
236 }
237
238 template <char I>
239 absl::enable_if_t<I == N - 2, FinalPromise*> next_promise() {
240 return &final_promise_;
241 }
242
243 // Callable to advance the state to the next one after I given the result from
244 // state I.
245 template <char I>
246 struct RunNext {
247 BasicSeq* s;
248 template <typename T>
249 Poll<Result> operator()(T&& value) {
250 auto* prior = s->state<I>();
251 using StateType = absl::remove_reference_t<decltype(*prior)>;
252 // Destroy the promise that just completed.
253 Destruct(&prior->current_promise);
254 // Construct the next promise by calling the next promise factory.
255 // We need to ask the traits to do this to deal with value
256 // wrapping/unwrapping.
257 auto n = StateType::Types::PromiseResultTraits::CallFactory(
258 &prior->next_factory, std::forward<T>(value));
259 // Now we also no longer need the factory, so we can destroy that.
260 Destruct(&prior->next_factory);
261 // Constructing the promise for the new state will use the memory
262 // previously occupied by the promise & next factory of the old state.
263 Construct(s->next_promise<I>(), std::move(n));
264 // Store the state counter.
265 s->state_ = I + 1;
266 // Recursively poll the new current state.
267 return s->RunState<I + 1>();
268 }
269 };
270
271 // Poll the current state, advance it if necessary.
272 template <char I>
273 absl::enable_if_t<I != N - 1, Poll<Result>> RunState() {
274 // Get a pointer to the state object.
275 auto* s = state<I>();
276 // Poll the current promise in this state.
277 auto r = s->current_promise();
278 // If we are still pending, say so by returning.
279 if (absl::holds_alternative<Pending>(r)) {
280 return Pending();
281 }
282 // Current promise is ready, as the traits to do the next thing.
283 // That may be returning - eg if TrySeq sees an error.
284 // Or it may be by calling the callable we hand down - RunNext - which
285 // will advance the state and call the next promise.
286 return Traits<
287 typename absl::remove_reference_t<decltype(*s)>::Types::PromiseResult>::
288 template CheckResultAndRunNext<Result>(
289 std::move(absl::get<kPollReadyIdx>(std::move(r))),
290 RunNext<I>{this});
291 }
292
293 // Specialization of RunState to run the final state.
294 template <char I>
295 absl::enable_if_t<I == N - 1, Poll<Result>> RunState() {
296 // Poll the final promise.
297 auto r = final_promise_();
298 // If we are still pending, say so by returning.
299 if (absl::holds_alternative<Pending>(r)) {
300 return Pending();
301 }
302 // We are complete, return the (wrapped) result.
303 return Result(std::move(absl::get<kPollReadyIdx>(std::move(r))));
304 }
305
306 // For state numbered I, destruct the current promise and the next promise
307 // factory, and recursively destruct the next promise factories for future
308 // states (since they also still exist).
309 template <char I>
310 absl::enable_if_t<I != N - 1, void>
311 DestructCurrentPromiseAndSubsequentFactories() {
312 Destruct(&GetSeqState<I>(&penultimate_state_)->current_promise);
313 DestructSubsequentFactories<I>();
314 }
315
316 template <char I>
317 absl::enable_if_t<I == N - 1, void>
318 DestructCurrentPromiseAndSubsequentFactories() {
319 Destruct(&final_promise_);
320 }
321
322 // For state I, destruct the next promise factory, and recursively the next
323 // promise factories after.
324 template <char I>
325 absl::enable_if_t<I != N - 1, void> DestructSubsequentFactories() {
326 Destruct(&GetSeqState<I>(&penultimate_state_)->next_factory);
327 DestructSubsequentFactories<I + 1>();
328 }
329
330 template <char I>
331 absl::enable_if_t<I == N - 1, void> DestructSubsequentFactories() {}
332
333 // Placate older compilers by wrapping RunState in a struct so that their
334 // parameter unpacking can work.
335 template <char I>
336 struct RunStateStruct {
337 BasicSeq* s;
338 Poll<Result> operator()() { return s->RunState<I>(); }
339 };
340
341 // Similarly placate those compilers for
342 // DestructCurrentPromiseAndSubsequentFactories
343 template <char I>
344 struct DestructCurrentPromiseAndSubsequentFactoriesStruct {
345 BasicSeq* s;
346 void operator()() {
347 return s->DestructCurrentPromiseAndSubsequentFactories<I>();
348 }
349 };
350
351 // Run the current state (and possibly later states if that one finishes).
352 // Single argument is a type that encodes the integer sequence 0, 1, 2, ...,
353 // N-1 as a type, but which uses no memory. This is used to expand out
354 // RunState instances using a template unpack to pass to Switch, which encodes
355 // a switch statement over the various cases. This ultimately gives us a
356 // Duff's device like mechanic for evaluating sequences.
357 template <char... I>
358 Poll<Result> Run(absl::integer_sequence<char, I...>) {
359 return Switch<Poll<Result>>(state_, RunStateStruct<I>{this}...);
360 }
361
362 // Run the appropriate destructors for a given state.
363 // Single argument is a type that encodes the integer sequence 0, 1, 2, ...,
364 // N-1 as a type, but which uses no memory. This is used to expand out
365 // DestructCurrentPromiseAndSubsequentFactories instances to pass to Switch,
366 // which can choose the correct instance at runtime to destroy everything.
367 template <char... I>
368 void RunDestruct(absl::integer_sequence<char, I...>) {
369 Switch<void>(
370 state_, DestructCurrentPromiseAndSubsequentFactoriesStruct<I>{this}...);
371 }
372
373 public:
374 // Construct a sequence given the callables that will control it.
375 explicit BasicSeq(Fs... fs) : penultimate_state_(std::make_tuple(&fs...)) {}
376 // No assignment... we don't need it (but if we ever find a good case, then
377 // it's ok to implement).
378 BasicSeq& operator=(const BasicSeq&) = delete;
379 // Copy construction - only for state 0.
380 // It's illegal to copy a Promise after polling it - if we are in state>0 we
381 // *must* have been polled.
382 BasicSeq(const BasicSeq& other) {
383 assert(other.state_ == 0);
384 new (&penultimate_state_) PenultimateState(other.penultimate_state_);
385 }
386 // Move construction - only for state 0.
387 // It's illegal to copy a Promise after polling it - if we are in state>0 we
388 // *must* have been polled.
389 BasicSeq(BasicSeq&& other) noexcept {
390 assert(other.state_ == 0);
391 new (&penultimate_state_)
392 PenultimateState(std::move(other.penultimate_state_));
393 }
394 // Destruct based on current state.
395 ~BasicSeq() { RunDestruct(absl::make_integer_sequence<char, N>()); }
396
397 // Poll the sequence once.
398 Poll<Result> operator()() {
399 return Run(absl::make_integer_sequence<char, N>());
400 }
401 };
402
403 // As above, but models a sequence of unknown size
404 // At each element, the accumulator A and the current value V is passed to some
405 // function of type IterTraits::Factory as f(V, IterTraits::Argument); f is
406 // expected to return a promise that resolves to IterTraits::Wrapped.
407 template <class IterTraits>
408 class BasicSeqIter {
409 private:
410 using Traits = typename IterTraits::Traits;
411 using Iter = typename IterTraits::Iter;
412 using Factory = typename IterTraits::Factory;
413 using Argument = typename IterTraits::Argument;
414 using IterValue = typename IterTraits::IterValue;
415 using StateCreated = typename IterTraits::StateCreated;
416 using State = typename IterTraits::State;
417 using Wrapped = typename IterTraits::Wrapped;
418
419 public:
420 BasicSeqIter(Iter begin, Iter end, Factory f, Argument arg)
421 : cur_(begin), end_(end), f_(std::move(f)) {
422 if (cur_ == end_) {
423 Construct(&result_, std::move(arg));
424 } else {
425 Construct(&state_, f_(*cur_, std::move(arg)));
426 }
427 }
428
429 ~BasicSeqIter() {
430 if (cur_ == end_) {
431 Destruct(&result_);
432 } else {
433 Destruct(&state_);
434 }
435 }
436
437 BasicSeqIter(const BasicSeqIter& other) = delete;
438 BasicSeqIter& operator=(const BasicSeqIter&) = delete;
439
440 BasicSeqIter(BasicSeqIter&& other) noexcept
441 : cur_(other.cur_), end_(other.end_), f_(std::move(other.f_)) {
442 if (cur_ == end_) {
443 Construct(&result_, std::move(other.result_));
444 } else {
445 Construct(&state_, std::move(other.state_));
446 }
447 }
448 BasicSeqIter& operator=(BasicSeqIter&& other) noexcept {
449 cur_ = other.cur_;
450 end_ = other.end_;
451 if (cur_ == end_) {
452 Construct(&result_, std::move(other.result_));
453 } else {
454 Construct(&state_, std::move(other.state_));
455 }
456 return *this;
457 }
458
459 Poll<Wrapped> operator()() {
460 if (cur_ == end_) {
461 return std::move(result_);
462 }
463 return PollNonEmpty();
464 }
465
466 private:
467 Poll<Wrapped> PollNonEmpty() {
468 Poll<Wrapped> r = state_();
469 if (absl::holds_alternative<Pending>(r)) return r;
470 return Traits::template CheckResultAndRunNext<Wrapped>(
471 std::move(absl::get<Wrapped>(r)), [this](Wrapped arg) -> Poll<Wrapped> {
472 auto next = cur_;
473 ++next;
474 if (next == end_) {
475 return std::move(arg);
476 }
477 cur_ = next;
478 state_.~State();
479 Construct(&state_,
480 Traits::template CallSeqFactory(f_, *cur_, std::move(arg)));
481 return PollNonEmpty();
482 });
483 }
484
485 Iter cur_;
486 const Iter end_;
487 GPR_NO_UNIQUE_ADDRESS Factory f_;
488 union {
489 GPR_NO_UNIQUE_ADDRESS State state_;
490 GPR_NO_UNIQUE_ADDRESS Argument result_;
491 };
492 };
493
494 } // namespace promise_detail
495 } // namespace grpc_core
496
497 #endif // GRPC_CORE_LIB_PROMISE_DETAIL_BASIC_SEQ_H