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_STREAM_HPP
12 : #define BOOST_CAPY_TEST_STREAM_HPP
13 :
14 : #include <boost/capy/detail/config.hpp>
15 : #include <boost/capy/buffers.hpp>
16 : #include <boost/capy/buffers/buffer_copy.hpp>
17 : #include <boost/capy/buffers/make_buffer.hpp>
18 : #include <boost/capy/continuation.hpp>
19 : #include <coroutine>
20 : #include <boost/capy/ex/await_context.hpp>
21 : #include <boost/capy/results.hpp>
22 : #include <boost/capy/error.hpp>
23 : #include <boost/capy/read.hpp>
24 : #include <boost/capy/task.hpp>
25 : #include <boost/capy/test/fuse.hpp>
26 : #include <boost/capy/test/run_blocking.hpp>
27 :
28 : #include <atomic>
29 : #include <memory>
30 : #include <new>
31 : #include <stop_token>
32 : #include <string>
33 : #include <string_view>
34 : #include <utility>
35 :
36 : namespace boost {
37 : namespace capy {
38 : namespace test {
39 :
40 : /** Suspends a reader until its paired end writes, or the shared fuse injects an error.
41 :
42 : Streams are created in pairs via @ref make_stream_pair.
43 : Data written to one end becomes available for reading on
44 : the other. If no data is available when @ref read_some
45 : is called, the calling coroutine suspends until the peer
46 : calls @ref write_some. The shared @ref fuse enables error
47 : injection at controlled points in both directions.
48 :
49 : When the fuse injects an error or throws on one end, the
50 : pair is automatically closed. Any suspended reader on
51 : either end is resumed with `error::eof`, and subsequent
52 : operations on both ends return `error::eof`. Calling
53 : @ref close on one end signals eof to the peer's reads
54 : after draining any buffered data, while the peer may
55 : still write.
56 :
57 : @par Thread Safety
58 : Single-threaded only. Both ends of the pair must be
59 : accessed from the same thread. Concurrent access is
60 : undefined behavior. The exception is a stop request on the
61 : stop token of a suspended read. That request may come from
62 : another thread, and the read resumes through its executor.
63 :
64 : @par Example
65 : @par !example example
66 :
67 :
68 : @see @ref make_stream_pair, @ref fuse
69 : */
70 : class stream
71 : {
72 : // Single-threaded only. No concurrent access to either
73 : // end of the pair. Both streams and all operations must
74 : // run on the same thread.
75 :
76 : struct half
77 : {
78 : std::string buf;
79 : std::size_t max_read_size = std::size_t(-1);
80 : // The parked read's own continuation: an executor may queue it
81 : // in place, so it is never copied or changed once posted.
82 : continuation* pending_cont_ = nullptr;
83 : executor_ref pending_ex;
84 : // Points at the suspended reader's claim flag (owned by the
85 : // read awaitable). Lets a peer wake coordinate with a stop
86 : // callback so the parked read is resumed exactly once.
87 : std::atomic<bool>* pending_claimed = nullptr;
88 : bool eof = false;
89 : };
90 :
91 : struct state
92 : {
93 : fuse f;
94 : bool closed = false;
95 : half sides[2];
96 :
97 HIT 321 : explicit state(fuse f_) noexcept
98 963 : : f(std::move(f_))
99 : {
100 321 : }
101 :
102 : // Resume a suspended reader on this side, if any. Claims the
103 : // reader's atomic so it is never double-resumed by a racing
104 : // stop callback; the loser of the race skips the post.
105 741 : static void wake(half& side)
106 : {
107 741 : auto* c = std::exchange(side.pending_cont_, nullptr);
108 741 : if(! c)
109 698 : return;
110 43 : auto ex = std::exchange(side.pending_ex, {});
111 43 : auto* claimed = std::exchange(side.pending_claimed, nullptr);
112 86 : if(! claimed ||
113 43 : ! claimed->exchange(true, std::memory_order_acq_rel))
114 : {
115 43 : ex.post(*c);
116 : }
117 : }
118 :
119 : // Set closed and resume any suspended readers
120 : // with eof on both sides.
121 214 : void close()
122 : {
123 214 : closed = true;
124 642 : for(auto& side : sides)
125 428 : wake(side);
126 214 : }
127 : };
128 :
129 : // Wraps the maybe_fail() call. If the guard is
130 : // not disarmed before destruction (fuse returned
131 : // an error, or threw an exception), closes both
132 : // ends so any suspended peer gets eof.
133 : struct close_guard
134 : {
135 : state* st;
136 : bool armed = true;
137 363 : void disarm() noexcept { armed = false; }
138 577 : ~close_guard() noexcept(false) { if(armed) st->close(); }
139 : };
140 :
141 : std::shared_ptr<state> state_;
142 : int index_;
143 :
144 642 : stream(
145 : std::shared_ptr<state> sp,
146 : int index) noexcept
147 642 : : state_(std::move(sp))
148 642 : , index_(index)
149 : {
150 642 : }
151 :
152 : friend std::pair<stream, stream>
153 : make_stream_pair(fuse);
154 :
155 : public:
156 : /** Copy construction is disabled; a stream end is move-only.
157 :
158 : @param other The stream end that would be copied.
159 : */
160 : stream(stream const& other) = delete;
161 :
162 : /** Copy assignment is disabled; a stream end is move-only.
163 :
164 : @param other The stream end that would be assigned from.
165 :
166 : @return A reference to `*this`.
167 : */
168 : stream& operator=(stream const& other) = delete;
169 :
170 : /** Construct by moving from another stream end.
171 :
172 : @param other The stream end to move from.
173 : */
174 744 : stream(stream&& other) = default;
175 :
176 : /** Assign by moving from another stream end.
177 :
178 : @param other The stream end to move from.
179 :
180 : @return A reference to `*this`.
181 : */
182 : stream& operator=(stream&& other) = default;
183 :
184 : /** Signal end-of-stream to the peer.
185 :
186 : Marks the peer's read direction as closed.
187 : If the peer is suspended in @ref read_some,
188 : it is resumed. The peer drains any buffered
189 : data before receiving `error::eof`. Writes
190 : from the peer are unaffected.
191 : */
192 : void
193 24 : close()
194 : {
195 24 : int peer = 1 - index_;
196 24 : auto& side = state_->sides[peer];
197 24 : side.eof = true;
198 24 : state::wake(side);
199 24 : }
200 :
201 : /** Set the maximum bytes returned per read.
202 :
203 : Limits how many bytes @ref read_some returns in
204 : a single call, simulating chunked network delivery.
205 : The default is unlimited.
206 :
207 : @param n Maximum bytes per read.
208 : */
209 : void
210 54 : set_max_read_size(std::size_t n) noexcept
211 : {
212 54 : state_->sides[index_].max_read_size = n;
213 54 : }
214 :
215 : /** Asynchronously read data from the stream.
216 :
217 : Transfers up to `buffer_size(buffers)` bytes from
218 : data written by the peer. If no data is available,
219 : the calling coroutine suspends until the peer calls
220 : @ref write_some. Before transferring data, the attached
221 : @ref fuse is consulted to possibly inject an error.
222 : If the fuse fires, the pair is automatically closed.
223 : If the stream is closed, returns `error::eof`.
224 : The returned `std::size_t` is the number of bytes
225 : transferred.
226 :
227 : The fuse is not consulted for an empty buffer sequence, a
228 : canceled read, a closed pair, or a read after the peer
229 : called @ref close.
230 :
231 : @par Cancellation
232 : Cancellation applies only to a read that would otherwise suspend.
233 : If no data is available and the environment's stop token is
234 : requested, before or during the wait, the read resumes with
235 : `error::canceled`. A read that can complete immediately from
236 : buffered data is unaffected by the stop token.
237 :
238 : @par Exception Safety
239 : Injected I/O conditions are reported via the `error_code`
240 : component of the result. Throws `std::system_error` when the
241 : attached @ref fuse is in exception mode and reaches its failure
242 : point. The pair is closed before the exception propagates.
243 :
244 : @throws std::system_error When the attached @ref fuse is in
245 : exception mode and reaches its failure point.
246 :
247 : @param buffers The mutable buffer sequence to receive data.
248 :
249 : @return An awaitable that await-returns `(error_code,std::size_t)`.
250 :
251 : @see @ref fuse, @ref close
252 : */
253 : template<MutableBufferSequence MB>
254 : auto
255 345 : read_some(MB buffers)
256 : {
257 : // The read suspends when no data is available, parking its
258 : // continuation on the side until the peer writes/closes. To
259 : // support cancellation it follows the same pattern as
260 : // async_waker::wait_awaiter: a stop callback claims the resume
261 : // (racing the peer wake via an atomic) and posts the continuation
262 : // through the executor. Because it owns a std::atomic and a
263 : // std::stop_callback, the awaitable needs explicit move and
264 : // destruction (the task promise moves it into its
265 : // context_awaiter before awaiting).
266 : struct awaitable
267 : {
268 : stream* self_;
269 : MB buffers_;
270 :
271 : // Declared before stop_cb_buf_: the stop callback reads
272 : // these, so they must outlive a blocking stop_cb_ destructor.
273 : continuation cont_;
274 : executor_ref ex_;
275 : half* side_ = nullptr;
276 : std::atomic<bool> claimed_{false};
277 : bool canceled_ = false;
278 : bool stop_cb_active_ = false;
279 :
280 : struct cancel_fn
281 : {
282 : awaitable* self_;
283 :
284 14 : void operator()() const noexcept
285 : {
286 14 : if(! self_->claimed_.exchange(
287 : true, std::memory_order_acq_rel))
288 : {
289 2 : self_->canceled_ = true;
290 2 : self_->ex_.post(self_->cont_);
291 : }
292 14 : }
293 : };
294 :
295 : using stop_cb_t = std::stop_callback<cancel_fn>;
296 :
297 : // Declared last: its destructor may block while the callback
298 : // accesses the members above. A union gives correct alignment
299 : // for stop_cb_t without an alignas specifier, which avoids
300 : // MSVC's C4324 padding warning on this function-local class
301 : // (the member-level pragma used by async_waker::wait_awaiter
302 : // does not suppress it here). Lifetime is managed manually:
303 : // placement new in await_suspend, explicit destruction once done.
304 : union { stop_cb_t stop_cb_; };
305 :
306 345 : awaitable(stream* self, MB buffers) noexcept
307 345 : : self_(self)
308 345 : , buffers_(buffers)
309 : {
310 345 : }
311 :
312 : /// @pre Not yet awaited (no active stop callback).
313 339 : awaitable(awaitable&& o) noexcept
314 339 : : self_(o.self_)
315 339 : , buffers_(o.buffers_)
316 339 : , cont_(o.cont_)
317 339 : , ex_(o.ex_)
318 339 : , side_(o.side_)
319 339 : , claimed_(o.claimed_.load(std::memory_order_relaxed))
320 339 : , canceled_(o.canceled_)
321 339 : , stop_cb_active_(std::exchange(o.stop_cb_active_, false))
322 : {
323 339 : }
324 :
325 684 : ~awaitable()
326 : {
327 684 : if(stop_cb_active_)
328 1 : stop_cb_.~stop_cb_t();
329 : // Unlink from the side if still parked (e.g. the
330 : // coroutine was destroyed while suspended), so a later
331 : // peer wake does not dereference a freed claim flag.
332 684 : if(side_ && side_->pending_claimed == &claimed_)
333 : {
334 1 : side_->pending_cont_ = nullptr;
335 1 : side_->pending_ex = {};
336 1 : side_->pending_claimed = nullptr;
337 : }
338 684 : }
339 :
340 : awaitable(awaitable const&) = delete;
341 : awaitable& operator=(awaitable const&) = delete;
342 : awaitable& operator=(awaitable&&) = delete;
343 :
344 345 : bool await_ready() const noexcept
345 : {
346 345 : if(buffers_empty(buffers_))
347 8 : return true;
348 337 : auto* st = self_->state_.get();
349 337 : auto& side = st->sides[self_->index_];
350 648 : return st->closed || side.eof ||
351 648 : !side.buf.empty();
352 : }
353 :
354 48 : bool await_suspend(
355 : std::coroutine_handle<> h,
356 : await_context const* env) noexcept
357 : {
358 : // A callback registered after stop was requested would
359 : // fire inline and post this coroutine, which could then be
360 : // resumed and finished before the registration returns.
361 48 : if(env->stop_token.stop_requested())
362 : {
363 2 : canceled_ = true;
364 2 : return false;
365 : }
366 46 : auto& side = self_->state_->sides[
367 46 : self_->index_];
368 46 : cont_.h = h;
369 46 : cont_.owner = env->owner;
370 46 : ex_ = env->executor;
371 46 : side_ = &side;
372 46 : side.pending_cont_ = &cont_;
373 46 : side.pending_ex = env->executor;
374 46 : side.pending_claimed = &claimed_;
375 :
376 46 : ::new(static_cast<void*>(&stop_cb_)) stop_cb_t(
377 46 : env->stop_token, cancel_fn{this});
378 46 : stop_cb_active_ = true;
379 :
380 46 : return true;
381 : }
382 :
383 : [[nodiscard]] results<std::size_t>
384 344 : await_resume()
385 : {
386 344 : if(stop_cb_active_)
387 : {
388 45 : stop_cb_.~stop_cb_t();
389 45 : stop_cb_active_ = false;
390 : }
391 :
392 344 : if(buffers_empty(buffers_))
393 8 : return {std::error_code(), 0};
394 :
395 336 : if(canceled_)
396 : {
397 : // The stop callback posted us but left the side
398 : // untouched; unlink if a peer wake has not already.
399 4 : if(side_ && side_->pending_claimed == &claimed_)
400 : {
401 2 : side_->pending_cont_ = nullptr;
402 2 : side_->pending_ex = {};
403 2 : side_->pending_claimed = nullptr;
404 : }
405 4 : return {error::canceled, 0};
406 : }
407 :
408 332 : auto* st = self_->state_.get();
409 332 : auto& side = st->sides[
410 332 : self_->index_];
411 :
412 332 : if(st->closed)
413 12 : return {error::eof, 0};
414 :
415 320 : if(side.eof && side.buf.empty())
416 24 : return {error::eof, 0};
417 :
418 296 : if(!side.eof)
419 : {
420 276 : close_guard g{st};
421 276 : auto ec = st->f.maybe_fail();
422 222 : if(ec)
423 54 : return {ec, 0};
424 168 : g.disarm();
425 276 : }
426 :
427 564 : std::size_t const n = buffer_copy(
428 188 : buffers_, make_buffer(side.buf),
429 : side.max_read_size);
430 188 : side.buf.erase(0, n);
431 188 : return {std::error_code(), n};
432 : }
433 : };
434 345 : return awaitable{this, buffers};
435 : }
436 :
437 : /** Asynchronously write data to the stream.
438 :
439 : Transfers up to `buffer_size(buffers)` bytes to the
440 : peer's incoming buffer. If the peer is suspended in
441 : @ref read_some, it is resumed. Before transferring data,
442 : the attached @ref fuse is consulted to possibly inject
443 : an error. If the fuse fires, the pair is automatically
444 : closed. If the stream is closed, returns `error::eof`.
445 : The returned `std::size_t` is the number of bytes
446 : transferred.
447 :
448 : The fuse is not consulted for an empty buffer sequence, a
449 : canceled write, or a closed pair.
450 :
451 : @par Cancellation
452 : If the environment's stop token is requested, the write
453 : completes immediately with `error::canceled` and transfers no
454 : data. An empty buffer sequence is a no-op that completes
455 : successfully regardless of the stop token.
456 :
457 : @par Exception Safety
458 : Injected I/O conditions are reported via the `error_code`
459 : component of the result. Throws `std::system_error` when the
460 : attached @ref fuse is in exception mode and reaches its failure
461 : point. The pair is closed before the exception propagates.
462 :
463 : @throws std::system_error When the attached @ref fuse is in
464 : exception mode and reaches its failure point.
465 :
466 : @param buffers The const buffer sequence containing
467 : data to write.
468 :
469 : @return An awaitable that await-returns `(error_code,std::size_t)`.
470 :
471 : @see @ref fuse, @ref close
472 : */
473 : template<ConstBufferSequence CB>
474 : auto
475 306 : write_some(CB buffers)
476 : {
477 : struct awaitable
478 : {
479 : stream* self_;
480 : CB buffers_;
481 : bool canceled_ = false;
482 :
483 306 : bool await_ready() const noexcept { return false; }
484 :
485 : // The write completes synchronously; await_suspend is only
486 : // used to observe the environment's stop token. Returning
487 : // false means the coroutine does not actually suspend.
488 : bool
489 306 : await_suspend(
490 : std::coroutine_handle<>,
491 : await_context const* env) noexcept
492 : {
493 306 : canceled_ = env->stop_token.stop_requested();
494 306 : return false;
495 : }
496 :
497 : [[nodiscard]] results<std::size_t>
498 306 : await_resume()
499 : {
500 306 : std::size_t n = buffer_size(buffers_);
501 306 : if(n == 0)
502 4 : return {std::error_code(), 0};
503 :
504 302 : if(canceled_)
505 1 : return {error::canceled, 0};
506 :
507 301 : auto* st = self_->state_.get();
508 :
509 301 : if(st->closed)
510 MIS 0 : return {error::eof, 0};
511 :
512 HIT 301 : close_guard g{st};
513 301 : auto ec = st->f.maybe_fail();
514 248 : if(ec)
515 53 : return {ec, 0};
516 195 : g.disarm();
517 :
518 195 : int peer = 1 - self_->index_;
519 195 : auto& side = st->sides[peer];
520 :
521 195 : std::size_t const old_size = side.buf.size();
522 195 : side.buf.resize(old_size + n);
523 195 : buffer_copy(make_buffer(
524 195 : side.buf.data() + old_size, n),
525 195 : buffers_, n);
526 :
527 195 : state::wake(side);
528 :
529 195 : return {std::error_code(), n};
530 301 : }
531 : };
532 306 : return awaitable{this, buffers};
533 : }
534 :
535 : /** Inject data into this stream's peer for reading.
536 :
537 : Appends data directly to the peer's incoming buffer,
538 : bypassing the fuse. If the peer is suspended in
539 : @ref read_some, it is resumed. This is test setup,
540 : not an operation under test.
541 :
542 : @param sv The data to inject.
543 :
544 : @see @ref make_stream_pair
545 : */
546 : void
547 94 : provide(std::string_view sv)
548 : {
549 94 : int peer = 1 - index_;
550 94 : auto& side = state_->sides[peer];
551 94 : side.buf.append(sv);
552 94 : state::wake(side);
553 94 : }
554 :
555 : /** Read from this stream and verify the content.
556 :
557 : Reads exactly `expected.size()` bytes from the stream
558 : and compares against the expected string. The read goes
559 : through the normal path including the fuse. The call
560 : blocks the calling thread until the read completes.
561 :
562 : The error code is set if a read error occurs, for example
563 : a fuse injection. The bool is true if the data matches.
564 :
565 : @pre At least `expected.size()` bytes are buffered, or the
566 : pair is closed, or the peer called @ref close. Otherwise
567 : the read waits for a write that cannot happen on the
568 : blocked thread, and the call never returns.
569 :
570 : @throws std::system_error When the attached @ref fuse is in
571 : exception mode and reaches its failure point.
572 :
573 : @param expected The expected content.
574 :
575 : @return A pair of `(error_code, bool)`.
576 :
577 : @see @ref provide
578 : */
579 : std::pair<std::error_code, bool>
580 38 : expect(std::string_view expected)
581 : {
582 38 : std::error_code result;
583 38 : bool match = false;
584 141 : run_blocking()([](
585 : stream& self,
586 : std::string_view expected,
587 : std::error_code& result,
588 : bool& match) -> task<>
589 : {
590 : std::string buf(expected.size(), '\0');
591 : auto [ec, n] = co_await read(
592 : self, mutable_buffer(
593 : buf.data(), buf.size()));
594 : if(ec)
595 : {
596 : result = ec;
597 : co_return;
598 : }
599 : match = (std::string_view(
600 : buf.data(), n) == expected);
601 161 : }(*this, expected, result, match));
602 58 : return {result, match};
603 : }
604 :
605 : /** Return the stream's pending read data.
606 :
607 : Returns a view of the data waiting to be read
608 : from this stream. This is a direct peek at the
609 : internal buffer, bypassing the fuse.
610 :
611 : @return A view of the pending data.
612 :
613 : @see @ref provide, @ref expect
614 : */
615 : std::string_view
616 4 : data() const noexcept
617 : {
618 4 : return state_->sides[index_].buf;
619 : }
620 : };
621 :
622 : /** Create a connected pair of test streams.
623 :
624 : Data written to one stream becomes readable on the other.
625 : If a coroutine calls @ref stream::read_some when no data
626 : is available, it suspends until the peer writes. Before
627 : a read or write transfers data, the @ref fuse is consulted
628 : to possibly inject an error for testing fault scenarios.
629 : When the fuse fires, the pair is automatically closed.
630 : Empty, canceled and closed-pair operations, and reads after
631 : the peer called @ref stream::close, skip the fuse.
632 :
633 : @param f The fuse used to inject errors during operations.
634 :
635 : @return A pair of connected streams.
636 :
637 : @see @ref stream, @ref fuse
638 : */
639 : inline std::pair<stream, stream>
640 321 : make_stream_pair(fuse f = {})
641 : {
642 321 : auto sp = std::make_shared<stream::state>(std::move(f));
643 642 : return {stream(sp, 0), stream(sp, 1)};
644 321 : }
645 :
646 : } // test
647 : } // capy
648 : } // boost
649 :
650 : #endif
|