TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : // Copyright (c) 2026 Michael Vandeberg
4 : //
5 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 : //
8 : // Official repository: https://github.com/cppalliance/capy
9 : //
10 :
11 : #ifndef BOOST_CAPY_EX_CONTEXT_AWAITABLE_PROMISE_BASE_HPP
12 : #define BOOST_CAPY_EX_CONTEXT_AWAITABLE_PROMISE_BASE_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/ex/abandon.hpp>
16 : #include <boost/capy/ex/await_context.hpp>
17 : #include <boost/capy/detail/context_awaiter.hpp>
18 : #include <boost/capy/ex/frame_alloc_mixin.hpp>
19 : #include <boost/capy/ex/frame_allocator.hpp>
20 : #include <boost/capy/ex/this_coro.hpp>
21 :
22 : #include <coroutine>
23 : #include <memory_resource>
24 : #include <stop_token>
25 : #include <type_traits>
26 :
27 : namespace boost {
28 : namespace capy {
29 :
30 : /** CRTP mixin that adds I/O awaitable support to a promise type.
31 :
32 : Inherit from this class to enable these capabilities in your coroutine:
33 :
34 : 1. **Frame allocation** — The mixin provides `operator new/delete` that
35 : use the thread-local frame allocator set by `run_async`.
36 :
37 : 2. **Environment storage** — The mixin stores a pointer to the `await_context`
38 : containing the executor, stop token, and allocator for this coroutine.
39 :
40 : 3. **Environment access** — Coroutine code can retrieve the environment
41 : via `co_await this_coro::environment`, or individual fields via
42 : `co_await this_coro::executor`, `co_await this_coro::stop_token`,
43 : and `co_await this_coro::frame_allocator`.
44 :
45 : 4. **Environment propagation** — Each @ref ContextAwaitable the
46 : coroutine awaits receives that environment.
47 :
48 : @tparam Derived The derived promise type (CRTP pattern).
49 :
50 : @par Basic Usage
51 :
52 : For coroutines that need to access their execution environment:
53 :
54 : @par !example example_1
55 :
56 :
57 : @par Custom Awaitable Transformation
58 :
59 : If your promise needs to transform awaitables (e.g., for affinity or
60 : logging), override `transform_awaitable` instead of `await_transform`,
61 : and hand @ref ContextAwaitable types on to the base's
62 : `transform_awaitable` so they still receive the environment:
63 :
64 : @par !example example_2
65 :
66 :
67 : The mixin's `await_transform` intercepts @ref this_coro::environment_tag
68 : and the fine-grained tag types (@ref this_coro::executor_tag,
69 : @ref this_coro::stop_token_tag, @ref this_coro::frame_allocator_tag),
70 : then delegates all other awaitables to your `transform_awaitable`.
71 :
72 : @par Making Your Coroutine a ContextAwaitable
73 :
74 : The mixin handles the "inside the coroutine" part—accessing the
75 : environment. To receive the environment when your coroutine is awaited
76 : (satisfying @ref ContextAwaitable), implement the `await_suspend` overload
77 : on your coroutine return type:
78 :
79 : @par !example example_3
80 :
81 :
82 : @par Ownership
83 : A coroutine's frame is owned by the object that awaits it, such as
84 : the parent's `task`, so a chain is destroyed from its top down, each
85 : frame freeing the one it awaits. The suspended coroutine at the
86 : bottom is held by whoever will resume it: an operation, queue or
87 : primitive. A holder that will never resume it calls @ref abandon,
88 : which unwinds the chain's segment from its owner (see
89 : @ref chain_owner) rather than destroying the bottom frame.
90 : Destroying a frame that is still awaited, other than in that
91 : unwind, calls `std::terminate`.
92 :
93 : @par Thread Safety
94 : The environment is stored before the coroutine's body runs, from
95 : `await_suspend` or the promise's constructor, and read during
96 : `co_await this_coro::environment`. These occur on the same logical
97 : thread of execution, so no synchronization is required.
98 :
99 : @note A chain waiting on a primitive stored in its own frames owns
100 : itself through that primitive; it is freed only by a stop request or
101 : by the primitive being signalled. A mutex must outlive every
102 : coroutine holding or handed its lock. A cross-thread `wake()` racing
103 : the teardown of an armed waker's frame on its executor thread is a
104 : precondition violation.
105 :
106 : @see @ref this_coro::environment, @ref this_coro::executor,
107 : @ref this_coro::stop_token, @ref this_coro::frame_allocator
108 : @see @ref await_context
109 : @see @ref ContextAwaitable
110 : */
111 : template<typename Derived>
112 : class context_awaitable_promise_base
113 : : public frame_alloc_mixin
114 : {
115 : await_context const* env_ = nullptr;
116 : mutable std::coroutine_handle<> cont_{std::noop_coroutine()};
117 :
118 : public:
119 : //----------------------------------------------------------
120 : // Continuation support
121 : //----------------------------------------------------------
122 :
123 : /** Store the continuation to resume on completion.
124 :
125 : Call this from your coroutine type's `await_suspend` overload
126 : to set up the completion path. The `final_suspend` awaiter
127 : returns this handle via unconditional symmetric transfer.
128 :
129 : @param cont The continuation to resume on completion.
130 : */
131 HIT 108114 : void set_continuation(std::coroutine_handle<> cont) noexcept
132 : {
133 108114 : cont_ = cont;
134 108114 : }
135 :
136 : /** Return and consume the stored continuation handle.
137 :
138 : Resets the stored handle to `noop_coroutine()` so the
139 : destructor does not double-destroy it.
140 :
141 : @return The continuation for symmetric transfer.
142 : */
143 5554 : std::coroutine_handle<> continuation() const noexcept
144 : {
145 5554 : return std::exchange(cont_, std::noop_coroutine());
146 : }
147 :
148 : //----------------------------------------------------------
149 : // Environment support
150 : //----------------------------------------------------------
151 :
152 : /** Store a pointer to the execution environment.
153 :
154 : Call this before the coroutine's body runs to make the
155 : environment available via `co_await this_coro::environment` and
156 : to each awaited @ref ContextAwaitable: from your coroutine
157 : type's `await_suspend` overload when it receives the
158 : environment from the awaiting coroutine, or from the promise's
159 : constructor when the promise holds its own. The pointed-to
160 : `await_context` must outlive this coroutine.
161 :
162 : @param env The environment to store.
163 : */
164 108201 : void set_environment(await_context const* env) noexcept
165 : {
166 108201 : env_ = env;
167 108201 : }
168 :
169 : /** Return the stored execution environment.
170 :
171 : @return The environment.
172 : */
173 222690 : await_context const* environment() const noexcept
174 : {
175 222690 : BOOST_CAPY_ASSERT(env_);
176 222690 : return env_;
177 : }
178 :
179 : /** Transform an awaitable before co_await.
180 :
181 : The default wraps a @ref ContextAwaitable so that it receives
182 : this coroutine's environment when the coroutine suspends on it,
183 : and the frame allocator is reinstalled when it resumes. The
184 : awaitable is moved or copied into the wrapper, so an lvalue is
185 : awaited as a copy, and a move-only one must be passed as an
186 : rvalue. The wrapper also works around compilers that miscompile
187 : symmetric transfer, so a promise relying on the default need
188 : not. Any other awaitable passes through unchanged. Override
189 : this in your derived promise type to customize how awaitables
190 : are transformed; an override that still awaits
191 : @ref ContextAwaitable types passes them to this function.
192 :
193 : @par Preconditions
194 : @ref set_environment has been called, if `A` satisfies
195 : @ref ContextAwaitable. A promise that receives its environment
196 : when awaited calls it from its `await_suspend`, before the body
197 : runs; one that holds its own environment calls it from its
198 : constructor.
199 :
200 : @note An exception from a wrapped awaitable's `await_ready` or
201 : `await_suspend` calls `std::terminate`.
202 :
203 : @param a The awaitable expression from `co_await a`.
204 :
205 : @return The transformed awaitable.
206 : */
207 : template<typename A>
208 4 : decltype(auto) transform_awaitable(A&& a)
209 : {
210 : if constexpr (ContextAwaitable<std::decay_t<A>>)
211 : return detail::context_awaiter<
212 : std::decay_t<A>, context_awaitable_promise_base>{
213 3 : std::forward<A>(a), this};
214 : else
215 1 : return std::forward<A>(a);
216 : }
217 :
218 : /** Intercept co_await expressions.
219 :
220 : This function handles @ref this_coro::environment_tag and
221 : the fine-grained tags (@ref this_coro::executor_tag,
222 : @ref this_coro::stop_token_tag, @ref this_coro::frame_allocator_tag)
223 : specially, returning an awaiter that yields the stored value.
224 : All other awaitables are delegated to @ref transform_awaitable.
225 :
226 : @param t The awaited expression.
227 :
228 : @return An awaiter for the expression.
229 : */
230 : template<typename T>
231 108302 : auto await_transform(T&& t)
232 : {
233 : using Tag = std::decay_t<T>;
234 :
235 : if constexpr (std::is_same_v<Tag, this_coro::environment_tag>)
236 : {
237 24 : BOOST_CAPY_ASSERT(env_);
238 : struct awaiter
239 : {
240 : await_context const* env_;
241 22 : bool await_ready() const noexcept { return true; }
242 2 : void await_suspend(std::coroutine_handle<>) const noexcept { }
243 21 : await_context const* await_resume() const noexcept { return env_; }
244 : };
245 24 : return awaiter{env_};
246 : }
247 : else if constexpr (std::is_same_v<Tag, this_coro::executor_tag>)
248 : {
249 4 : BOOST_CAPY_ASSERT(env_);
250 : struct awaiter
251 : {
252 : executor_ref executor_;
253 3 : bool await_ready() const noexcept { return true; }
254 : void await_suspend(std::coroutine_handle<>) const noexcept { } // LCOV_EXCL_LINE await_ready() always true, never suspends
255 3 : executor_ref await_resume() const noexcept { return executor_; }
256 : };
257 4 : return awaiter{env_->executor};
258 : }
259 : else if constexpr (std::is_same_v<Tag, this_coro::stop_token_tag>)
260 : {
261 24 : BOOST_CAPY_ASSERT(env_);
262 : struct awaiter
263 : {
264 : std::stop_token token_;
265 23 : bool await_ready() const noexcept { return true; }
266 : void await_suspend(std::coroutine_handle<>) const noexcept { } // LCOV_EXCL_LINE await_ready() always true, never suspends
267 23 : std::stop_token await_resume() const noexcept { return token_; }
268 : };
269 24 : return awaiter{env_->stop_token};
270 : }
271 : else if constexpr (std::is_same_v<Tag, this_coro::frame_allocator_tag>)
272 : {
273 8 : BOOST_CAPY_ASSERT(env_);
274 : struct awaiter
275 : {
276 : std::pmr::memory_resource* frame_allocator_;
277 6 : bool await_ready() const noexcept { return true; }
278 : void await_suspend(std::coroutine_handle<>) const noexcept { } // LCOV_EXCL_LINE await_ready() always true, never suspends
279 7 : std::pmr::memory_resource* await_resume() const noexcept { return frame_allocator_; }
280 : };
281 8 : return awaiter{env_->frame_allocator};
282 : }
283 : else
284 : {
285 2516 : return static_cast<Derived*>(this)->transform_awaitable(
286 108242 : std::forward<T>(t));
287 : }
288 : }
289 : };
290 :
291 : } // namespace capy
292 : } // namespace boost
293 :
294 : #endif
|