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_TEST_RUN_BLOCKING_HPP
12 : #define BOOST_CAPY_TEST_RUN_BLOCKING_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/concept/execution_context.hpp>
16 : #include <boost/capy/concept/executor.hpp>
17 : #include <boost/capy/error.hpp>
18 : #include <boost/capy/ex/run_async.hpp>
19 :
20 : #include <coroutine>
21 : #include <exception>
22 : #include <stop_token>
23 : #include <system_error>
24 : #include <type_traits>
25 : #include <utility>
26 :
27 : namespace boost {
28 : namespace capy {
29 : namespace test {
30 :
31 : class blocking_context;
32 :
33 : /** Dispatches work inline for symmetric transfer, or enqueues it into the owning `blocking_context`.
34 :
35 : This executor is used internally by @ref run_blocking to
36 : execute coroutine tasks on the calling thread. Work submitted
37 : via `dispatch()` from within the context's event loop is
38 : returned for symmetric transfer; from elsewhere it is queued. Work
39 : submitted via `post()` is enqueued and processed by the
40 : @ref blocking_context event loop.
41 :
42 : Users do not construct this type directly. It is obtained
43 : from @ref blocking_context::get_executor.
44 :
45 : @par Thread Safety
46 : All member functions are safe to call from any thread.
47 :
48 : @see @ref blocking_context, @ref run_blocking
49 : */
50 : struct BOOST_CAPY_DECL blocking_executor
51 : {
52 : /** Construct from a context pointer.
53 :
54 : @param ctx The owning execution context.
55 : */
56 HIT 1118 : explicit blocking_executor(
57 : blocking_context* ctx) noexcept
58 1118 : : ctx_(ctx)
59 : {
60 1118 : }
61 :
62 : /** Compare two blocking executors for equality.
63 :
64 : Two executors are equal if they share the same context.
65 :
66 : @param other The executor to compare against.
67 :
68 : @return `true` if both executors share the same context.
69 : */
70 : bool
71 : operator==(blocking_executor const& other) const noexcept;
72 :
73 : /** Return the associated execution context.
74 :
75 : @return A reference to the owning `blocking_context`.
76 : */
77 : blocking_context&
78 : context() const noexcept;
79 :
80 : /// Called when work is submitted (no-op).
81 : void on_work_started() const noexcept;
82 :
83 : /// Called when work completes (no-op).
84 : void on_work_finished() const noexcept;
85 :
86 : /** Dispatch work, running it inline when already in the loop.
87 :
88 : Called from within the context's event loop, returns the
89 : handle for the caller to resume by symmetric transfer.
90 : Called from anywhere else, including while the context is
91 : shutting down, queues the continuation as @ref post does.
92 :
93 : @param c The continuation to execute.
94 :
95 : @return `c.h` for symmetric transfer, or
96 : `std::noop_coroutine()` if the continuation was queued.
97 : */
98 : std::coroutine_handle<>
99 : dispatch(continuation& c) const;
100 :
101 : /** Post work for deferred execution.
102 :
103 : Enqueues the coroutine handle into the context's work
104 : queue. The handle is resumed when the blocking event
105 : loop processes it.
106 :
107 : @param c The continuation to enqueue.
108 : */
109 : void
110 : post(continuation& c) const;
111 :
112 : private:
113 : blocking_context* ctx_;
114 : };
115 :
116 : /** Runs a work queue and event loop on the calling thread until the task completes.
117 :
118 : Provides a work queue and event loop that runs on the
119 : calling thread. Coroutines dispatched through the
120 : associated @ref blocking_executor have their `post()`
121 : calls enqueued and processed by @ref run, which blocks
122 : until @ref signal_done or @ref signal_abandoned is called.
123 :
124 : This context is created internally by @ref run_blocking.
125 : Users do not interact with it directly.
126 :
127 : Coroutines still queued when the context is destroyed are
128 : passed to @ref abandon rather than resumed.
129 :
130 : @par Thread Safety
131 : The event loop runs on the thread that calls `run()`.
132 : `signal_done()`, `signal_abandoned()`, and `enqueue()` are safe
133 : to call from any thread.
134 :
135 : @see @ref blocking_executor, @ref run_blocking
136 : */
137 : class BOOST_CAPY_DECL blocking_context
138 : : public execution_context
139 : {
140 : struct impl;
141 : impl* impl_;
142 :
143 : public:
144 : /// Names `blocking_executor` as the type `get_executor()` returns.
145 : using executor_type = blocking_executor;
146 :
147 : /** Construct a blocking context.
148 :
149 : Allocates the internal work queue and
150 : synchronization state.
151 : */
152 : blocking_context();
153 :
154 : /// Destroy the blocking context.
155 : ~blocking_context();
156 :
157 : /** Return an executor bound to this context.
158 :
159 : @return A `blocking_executor` that enqueues work
160 : into this context's queue.
161 : */
162 : blocking_executor
163 : get_executor() noexcept;
164 :
165 : /** Signal that the task has completed.
166 :
167 : Wakes the event loop so that @ref run returns.
168 : */
169 : void
170 : signal_done() noexcept;
171 :
172 : /** Signal that the task has completed with an error.
173 :
174 : Stores the exception and wakes the event loop
175 : so that @ref run rethrows it.
176 :
177 : @param ep The exception to propagate.
178 : */
179 : void
180 : signal_done(std::exception_ptr ep) noexcept;
181 :
182 : /** Signal that the task was abandoned without a result.
183 :
184 : Wakes the event loop so that @ref run throws
185 : `std::system_error` with `error::canceled`.
186 : */
187 : void
188 : signal_abandoned() noexcept;
189 :
190 : /** Run the event loop until done.
191 :
192 : Blocks the calling thread, processing posted
193 : coroutine handles until @ref signal_done or
194 : @ref signal_abandoned is called.
195 : After draining remaining work, rethrows any stored
196 : exception.
197 :
198 : @par Exception Safety
199 : Basic guarantee. If the completed task stored an
200 : exception via `signal_done(ep)`, it is rethrown.
201 : */
202 : void
203 : run();
204 :
205 : /** Enqueue a continuation for processing.
206 :
207 : A copy is queued, so the owner it carries reaches @ref abandon
208 : if the context is destroyed first.
209 :
210 : @param c The continuation to enqueue.
211 : */
212 : void
213 : enqueue(continuation const& c);
214 : };
215 :
216 : /** Forward a task's outcome to its handlers, then signal the blocking context.
217 :
218 : Forwards invocations to the contained handlers, then
219 : signals the `blocking_context` so that its event loop
220 : unblocks. Exceptions thrown by the handlers are captured
221 : and stored for later rethrow.
222 :
223 : @par Thread Safety
224 : Safe to invoke from any thread.
225 :
226 : @tparam H1 The success handler type.
227 : @tparam H2 The error handler type.
228 :
229 : @see @ref run_blocking, @ref blocking_context
230 : */
231 : template<class H1, class H2>
232 : struct blocking_handler_wrapper
233 : {
234 : /// The context signalled once the handler returns.
235 : blocking_context* ctx_;
236 :
237 : /// The success and error handlers to forward to.
238 : detail::handler_pair<H1, H2> handlers_;
239 :
240 : /** Destroy the wrapper.
241 :
242 : A wrapper destroyed without being invoked belongs to an
243 : abandoned chain, which delivers no result. The context is
244 : signalled with `error::canceled`, so its loop neither waits
245 : forever nor reports success.
246 : */
247 5525 : ~blocking_handler_wrapper()
248 : {
249 5525 : if(ctx_)
250 1 : ctx_->signal_abandoned();
251 5525 : }
252 :
253 : /** Construct from a context and handlers.
254 :
255 : @param ctx The context to signal.
256 :
257 : @param handlers The handlers to forward to.
258 : */
259 1105 : blocking_handler_wrapper(
260 : blocking_context* ctx,
261 : detail::handler_pair<H1, H2> handlers)
262 1105 : : ctx_(ctx)
263 1105 : , handlers_(std::move(handlers))
264 : {
265 1105 : }
266 :
267 : /** Construct by moving, leaving `other` unable to signal.
268 :
269 : @param other The wrapper to move from.
270 : */
271 4420 : blocking_handler_wrapper(blocking_handler_wrapper&& other) noexcept
272 4420 : : ctx_(std::exchange(other.ctx_, nullptr))
273 4420 : , handlers_(std::move(other.handlers_))
274 : {
275 4420 : }
276 :
277 : /** Invoke the handler with a non-void result.
278 :
279 : @param v The result value to forward to the handler.
280 : */
281 : template<class T>
282 48 : void operator()(T&& v)
283 : {
284 : try
285 : {
286 48 : handlers_(std::forward<T>(v));
287 : }
288 : catch(...)
289 : {
290 : std::exchange(ctx_, nullptr)->signal_done(
291 : std::current_exception());
292 : return;
293 : }
294 48 : std::exchange(ctx_, nullptr)->signal_done();
295 : }
296 :
297 : /** Invoke the handler for a void result. */
298 720 : void operator()()
299 : {
300 : try
301 : {
302 720 : handlers_();
303 : }
304 : catch(...)
305 : {
306 : std::exchange(ctx_, nullptr)->signal_done(
307 : std::current_exception());
308 : return;
309 : }
310 720 : std::exchange(ctx_, nullptr)->signal_done();
311 : }
312 :
313 : /** Invoke the handler with an exception.
314 :
315 : @param ep The exception to forward to the error handler.
316 : */
317 336 : void operator()(std::exception_ptr ep)
318 : {
319 : try
320 : {
321 669 : handlers_(ep);
322 : }
323 333 : catch(...)
324 : {
325 333 : std::exchange(ctx_, nullptr)->signal_done(
326 : std::current_exception());
327 333 : return;
328 : }
329 3 : std::exchange(ctx_, nullptr)->signal_done();
330 : }
331 : };
332 :
333 : /** Starts a `blocking_context`, runs the task on it, and pumps the event loop until it completes.
334 :
335 : Holds the handlers and optional stop token. When invoked
336 : with a task, creates a @ref blocking_context, starts
337 : the task via `run_async`, and pumps the event loop until
338 : the task completes.
339 :
340 : The rvalue ref-qualifier on `operator()` restricts invocation
341 : to rvalues, so `run_blocking(h)(task)` is the supported spelling.
342 : `operator()` moves `h1_` out of the wrapper, and `h2_` too unless
343 : `H2` is `default_handler`. The stop token is copied, not moved.
344 : The wrapper is single-use regardless. A stored wrapper needs an
345 : explicit `std::move` to invoke:
346 : `auto w = run_blocking(h); std::move(w)(task);`. That explicit
347 : `std::move` surfaces the single-use hazard that a bare `w(task)`
348 : on an lvalue would otherwise hide.
349 :
350 : @pre `H1` and `H2` are nothrow move constructible.
351 :
352 : @par Thread Safety
353 : The wrapper itself should only be used from one thread.
354 : The calling thread blocks until the task completes.
355 :
356 : @par Example
357 : @code
358 : task<int> compute();
359 :
360 : int result = 0;
361 : run_blocking([&](int v) { result = v; })(compute());
362 : @endcode
363 :
364 : @tparam H1 The success handler type.
365 : @tparam H2 The error handler type.
366 :
367 : @see @ref run_blocking, @ref run_async
368 : */
369 : template<class H1, class H2>
370 : class [[nodiscard]] run_blocking_wrapper
371 : {
372 : std::stop_token st_;
373 : H1 h1_;
374 : H2 h2_;
375 :
376 : public:
377 : /** Construct wrapper with stop token and handlers.
378 :
379 : @param st The stop token for cooperative cancellation.
380 : @param h1 The success handler.
381 : @param h2 The error handler.
382 : */
383 1105 : run_blocking_wrapper(
384 : std::stop_token st,
385 : H1 h1,
386 : H2 h2)
387 1105 : : st_(std::move(st))
388 1105 : , h1_(std::move(h1))
389 1105 : , h2_(std::move(h2))
390 : {
391 1105 : }
392 :
393 : /** Copy construction is disabled; the wrapper is single-use.
394 :
395 : @param other The wrapper that would be copied.
396 : */
397 : run_blocking_wrapper(run_blocking_wrapper const& other) = delete;
398 :
399 : /** Move construction is disabled; the wrapper is single-use.
400 :
401 : @param other The wrapper that would be moved from.
402 : */
403 : run_blocking_wrapper(run_blocking_wrapper&& other) = delete;
404 :
405 : /** Copy assignment is disabled; the wrapper is single-use.
406 :
407 : @param other The wrapper that would be assigned from.
408 :
409 : @return A reference to `*this`.
410 : */
411 : run_blocking_wrapper& operator=(run_blocking_wrapper const& other) = delete;
412 :
413 : /** Move assignment is disabled; the wrapper is single-use.
414 :
415 : @param other The wrapper that would be moved from.
416 :
417 : @return A reference to `*this`.
418 : */
419 : run_blocking_wrapper& operator=(run_blocking_wrapper&& other) = delete;
420 :
421 : /** Start the task and block until completion.
422 :
423 : Creates a blocking_context with a single-threaded
424 : event loop, starts the task via `run_async`, then
425 : pumps the loop until the task completes or throws.
426 :
427 : @throws std::system_error with `error::canceled` if the task
428 : is abandoned before it completes.
429 :
430 : @throws Any exception the task exits with that no error
431 : handler consumes, or any exception a handler throws.
432 :
433 : @param t The task to execute.
434 : */
435 : template<ContextRunnable Task>
436 : void
437 1105 : operator()(Task t) &&
438 : {
439 1105 : blocking_context ctx;
440 :
441 2210 : auto make_handlers = [&]() {
442 : if constexpr(
443 : std::is_same_v<H2, detail::default_handler>)
444 : return detail::handler_pair<H1, H2>{
445 1100 : std::move(h1_)};
446 : else
447 : return detail::handler_pair<H1, H2>{
448 5 : std::move(h1_), std::move(h2_)};
449 : };
450 :
451 1105 : run_async(
452 : ctx.get_executor(),
453 1105 : st_,
454 : blocking_handler_wrapper<H1, H2>{
455 : &ctx, make_handlers()}
456 1105 : )(std::move(t));
457 :
458 1105 : ctx.run();
459 1105 : }
460 : };
461 :
462 : /** Create a wrapper that runs a task to completion and discards its result.
463 :
464 : Invoking the returned wrapper with a task executes it on a
465 : single-threaded event loop. The call blocks the calling thread
466 : until the task completes or throws.
467 :
468 : @par Exception Safety
469 : Basic guarantee. If the task throws, the exception is
470 : rethrown to the caller.
471 : If the task is abandoned before it completes, the call throws
472 : `std::system_error` with `error::canceled`.
473 :
474 : @par Example
475 : @par !example example_2
476 :
477 :
478 : @return A wrapper that accepts a task for blocking execution.
479 :
480 : @see @ref run_async
481 : */
482 : [[nodiscard]] inline auto
483 1046 : run_blocking()
484 : {
485 : return run_blocking_wrapper<
486 : detail::default_handler,
487 : detail::default_handler>(
488 2092 : std::stop_token{},
489 : detail::default_handler{},
490 1046 : detail::default_handler{});
491 : }
492 :
493 : /** Create a wrapper that runs a task to completion and passes its result to a handler.
494 :
495 : Invoking the returned wrapper with a task executes it on a
496 : single-threaded event loop and blocks until completion. The
497 : handler `h1` is called with the result on success. If `h1` is
498 : also invocable with `std::exception_ptr`, it handles exceptions
499 : too. Otherwise, exceptions are rethrown.
500 :
501 : @pre `H1` is nothrow move constructible.
502 :
503 : @par Exception Safety
504 : Basic guarantee. Exceptions from the task are passed
505 : to `h1` if it accepts `std::exception_ptr`, otherwise
506 : rethrown.
507 : If the task is abandoned before it completes, the call throws
508 : `std::system_error` with `error::canceled`.
509 :
510 : @par Example
511 : @par !example example_3
512 :
513 :
514 : @param h1 Handler invoked with the result on success,
515 : and optionally with `std::exception_ptr` on failure.
516 :
517 : @return A wrapper that accepts a task for blocking execution.
518 :
519 : @see @ref run_async
520 : */
521 : template<class H1>
522 : [[nodiscard]] auto
523 44 : run_blocking(H1 h1)
524 : {
525 : return run_blocking_wrapper<
526 : H1,
527 : detail::default_handler>(
528 88 : std::stop_token{},
529 44 : std::move(h1),
530 44 : detail::default_handler{});
531 : }
532 :
533 : /** Create a wrapper that runs a task to completion with separate handlers.
534 :
535 : Invoking the returned wrapper with a task executes it on a
536 : single-threaded event loop and blocks until completion. The
537 : handler `h1` is called on success, `h2` on failure.
538 :
539 : @pre `H1` and `H2` are nothrow move constructible.
540 :
541 : @par Exception Safety
542 : Basic guarantee. Exceptions from the task are passed
543 : to `h2`.
544 : If the task is abandoned before it completes, the call throws
545 : `std::system_error` with `error::canceled`.
546 :
547 : @par Example
548 : @par !example example_1
549 :
550 :
551 : @param h1 Handler invoked with the result on success.
552 : @param h2 Handler invoked with the exception on failure.
553 :
554 : @return A wrapper that accepts a task for blocking execution.
555 :
556 : @see @ref run_async
557 : */
558 : template<class H1, class H2>
559 : [[nodiscard]] auto
560 4 : run_blocking(H1 h1, H2 h2)
561 : {
562 : return run_blocking_wrapper<
563 : H1,
564 : H2>(
565 8 : std::stop_token{},
566 4 : std::move(h1),
567 8 : std::move(h2));
568 : }
569 :
570 : /** Create a wrapper that runs a task to completion under a stop token.
571 :
572 : Invoking the returned wrapper with a task executes it on a
573 : single-threaded event loop with the given stop token. The call
574 : blocks until completion.
575 :
576 : @par Exception Safety
577 : Basic guarantee. If the task throws, the exception is
578 : rethrown to the caller.
579 : If the task is abandoned before it completes, the call throws
580 : `std::system_error` with `error::canceled`.
581 :
582 : @param st The stop token for cooperative cancellation.
583 :
584 : @return A wrapper that accepts a task for blocking execution.
585 :
586 : @see @ref run_async
587 : */
588 : [[nodiscard]] inline auto
589 7 : run_blocking(std::stop_token st)
590 : {
591 : return run_blocking_wrapper<
592 : detail::default_handler,
593 : detail::default_handler>(
594 7 : std::move(st),
595 : detail::default_handler{},
596 7 : detail::default_handler{});
597 : }
598 :
599 : /** Create a wrapper that runs a task to completion under a stop token, passing its result to a handler.
600 :
601 : Invoking the returned wrapper with a task executes it on a
602 : single-threaded event loop with the given stop token, and
603 : blocks until completion. The handler `h1` is called with the
604 : result on success. If `h1` is also invocable with
605 : `std::exception_ptr`, it handles exceptions too. Otherwise,
606 : exceptions are rethrown.
607 :
608 : @pre `H1` is nothrow move constructible.
609 :
610 : @par Exception Safety
611 : Basic guarantee. Exceptions from the task are passed
612 : to `h1` if it accepts `std::exception_ptr`, otherwise
613 : rethrown.
614 : If the task is abandoned before it completes, the call throws
615 : `std::system_error` with `error::canceled`.
616 :
617 : @param st The stop token for cooperative cancellation.
618 : @param h1 Handler invoked with the result on success.
619 :
620 : @return A wrapper that accepts a task for blocking execution.
621 :
622 : @see @ref run_async
623 : */
624 : template<class H1>
625 : [[nodiscard]] auto
626 3 : run_blocking(std::stop_token st, H1 h1)
627 : {
628 : return run_blocking_wrapper<
629 : H1,
630 : detail::default_handler>(
631 3 : std::move(st),
632 3 : std::move(h1),
633 3 : detail::default_handler{});
634 : }
635 :
636 : /** Create a wrapper that runs a task to completion under a stop token with separate handlers.
637 :
638 : Invoking the returned wrapper with a task executes it on a
639 : single-threaded event loop with the given stop token, and
640 : blocks until completion. The handler `h1` is called on
641 : success, `h2` on failure.
642 :
643 : @pre `H1` and `H2` are nothrow move constructible.
644 :
645 : @par Exception Safety
646 : Basic guarantee. Exceptions from the task are passed
647 : to `h2`.
648 : If the task is abandoned before it completes, the call throws
649 : `std::system_error` with `error::canceled`.
650 :
651 : @param st The stop token for cooperative cancellation.
652 : @param h1 Handler invoked with the result on success.
653 : @param h2 Handler invoked with the exception on failure.
654 :
655 : @return A wrapper that accepts a task for blocking execution.
656 :
657 : @see @ref run_async
658 : */
659 : template<class H1, class H2>
660 : [[nodiscard]] auto
661 1 : run_blocking(std::stop_token st, H1 h1, H2 h2)
662 : {
663 : return run_blocking_wrapper<
664 : H1,
665 : H2>(
666 1 : std::move(st),
667 1 : std::move(h1),
668 2 : std::move(h2));
669 : }
670 :
671 : } // namespace test
672 : } // namespace capy
673 : } // namespace boost
674 :
675 : #endif
|