// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One QUIC stream, as an `Io.Reader` and an `Io.Writer`. //! //! This is the whole point of the module. A `quic.Connection` offers //! `readable`, `consume`, `write` and `finishStream`, which are the right //! interface for a state machine and the wrong one for an application: code //! that wants to parse a request wants a reader, and code that wants to write //! a response wants a writer, and neither wants to know that the octets //! arrive in a datagram somebody else is holding a lock over. //! //! Both halves block. A read with nothing to read waits on the session's //! condition until a datagram arrives; a write pushes into the connection and //! then flushes it to the socket itself, which is how output gets out without //! anything having to wake the pump. const std = @import("std"); const Io = std.Io; const quic = @import("quic"); const Session = @import("Session.zig"); const Stream = @This(); session: *Session, id: quic.stream.Id, /// A reader over what the peer sends on this stream. /// /// Holds its own small buffer because `Io.Reader` needs somewhere to put what /// it is given, and because the alternative -- handing out a slice of the /// connection's reassembly window -- is a borrow that `consume` invalidates. /// That rule is written on `Connection.readable` and is exactly the kind of /// thing an adapter exists to stop a caller having to know. pub const Reader = struct { interface: Io.Reader, stream: Stream, /// Whether the peer has ended the stream and everything it sent has been /// handed over. finished: bool = false, /// A reader over `stream`, keeping what it has been handed but not yet /// given out in `buffer`. /// /// Read through `interface`, and keep the `Reader` where it is while /// doing so: the vtable finds it from `interface` by its address. A read /// with nothing to read blocks until a datagram brings some, so something /// else has to be pumping the socket -- the endpoint's `pump`, or /// `Client.run` on a task of its own. The end of the stream is /// `error.EndOfStream` and sets `finished`; a connection that has closed, /// or a wait that was canceled, is `error.ReadFailed`. pub fn init(stream: Stream, buffer: []u8) Reader { return .{ .interface = .{ .vtable = &.{ .stream = streamImpl }, .buffer = buffer, .seek = 0, .end = 0, }, .stream = stream, }; } test init { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); // The test pair's server sends back whatever a stream carried. const stream = try pair.session().openBidirectional(); var w: Writer = .init(stream, &.{}); try w.interface.writeAll("hello"); try w.finish(); var buffer: [64]u8 = undefined; var r: Reader = .init(stream, &buffer); var answer: [64]u8 = undefined; const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("hello", answer[0..n]); try testing.expect(r.finished); } fn streamImpl(io_reader: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const r: *Reader = @alignCast(@fieldParentPtr("interface", io_reader)); const s = r.stream.session; s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); while (true) { const available = s.connection.readable(r.stream.id); if (available.len > 0) { const take = @min(available.len, limit.toInt() orelse available.len); // Written out before `consume`, which slides the reassembly // window down underneath the slice. const n = w.write(available[0..take]) catch |err| switch (err) { error.WriteFailed => return error.WriteFailed, }; s.connection.consume(r.stream.id, n); // The credit that just came free is worth sending now rather // than at the next datagram: a peer waiting on flow control // is a peer that has stopped talking, and nothing else will // happen to make it start. s.flushLocked(); return n; } if (s.connection.streamFinished(r.stream.id)) { r.finished = true; return error.EndOfStream; } if (s.done or s.connection.closeState() != null) return error.ReadFailed; // `ReadFailed` is all an `Io.Reader` may say; the cancelation // itself is re-armed for the caller to hear. See `waitArrived`. if (!s.waitArrived()) return error.ReadFailed; } } }; /// A writer for what this endpoint sends on this stream. /// /// `drain` pushes into the connection and flushes the connection to the /// socket before returning, so an application that writes and then blocks /// reading has already sent what it wrote. Nothing wakes a pump, because /// nothing needs to: see the note on `Session.flush`. pub const Writer = struct { interface: Io.Writer, stream: Stream, /// A writer onto `stream`, gathering octets in `buffer` until it is full /// or flushed. /// /// Write through `interface`, and keep the `Writer` where it is while /// doing so, as with `Reader.init`. An empty `buffer` is allowed and hands /// every write straight to the connection. A write blocks while the /// stream has no room -- until the peer acknowledges and extends credit -- /// and is `error.WriteFailed` once the connection has closed. `finish` ends /// the stream; `interface.flush` sends what is buffered and leaves it open. pub fn init(stream: Stream, buffer: []u8) Writer { return .{ .interface = .{ .vtable = &vtable, .buffer = buffer }, .stream = stream, }; } test init { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const stream = try pair.session().openBidirectional(); var buffer: [64]u8 = undefined; var w: Writer = .init(stream, &buffer); // Gathered in `buffer` and not yet sent... try w.interface.print("{d} + {d}", .{ 2, 2 }); try testing.expectEqualStrings("2 + 2", w.interface.buffered()); // ...until the stream is finished, which sends it with the FIN. try w.finish(); var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("2 + 2", answer[0..n]); } const vtable: Io.Writer.VTable = .{ .drain = drain }; fn drain(io_writer: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize { const w: *Writer = @alignCast(@fieldParentPtr("interface", io_writer)); const s = w.stream.session; // `Session.writeStream` takes the lock itself, and waits for room // rather than failing when the per-stream buffer is full -- which is // what makes a body larger than that buffer expressible at all. const buffered = io_writer.buffered(); if (buffered.len > 0) { // First, or the stream would carry the octets out of order. try s.writeStream(w.stream.id, buffered); io_writer.end = 0; } var written: usize = 0; for (data, 0..) |slice, i| { const times = if (i == data.len - 1) splat else 1; for (0..times) |_| { if (slice.len == 0) continue; try s.writeStream(w.stream.id, slice); written += slice.len; } } return written; } /// §3.1: ends this endpoint's sending half of the stream, sending /// whatever is still buffered and the FIN together. /// /// The FIN rides on the frame carrying the last buffered octet. When /// nothing is buffered -- a writer with no buffer, or one just flushed -- /// the octets have already gone, and the FIN follows in a STREAM frame of /// its own carrying no data, which §19.8 allows. `error.WriteFailed` when /// the connection has closed or the stream cannot be ended, as when it /// has been reset. Nothing may be written afterwards. pub fn finish(w: *Writer) Io.Writer.Error!void { // Whatever is still buffered goes out *with* the FIN rather than // ahead of it -- see `Session.writeStreamFinished`, which is where the // reason is written down. A writer given a buffer large enough for // what it is about to say therefore sends one packet where this used // to send two, and a writer given no buffer at all has already had its // octets drained and still ends the stream correctly, in an empty // frame, because there is nothing left for the FIN to ride on. const buffered = w.interface.buffered(); w.interface.end = 0; const s = w.stream.session; return s.writeStreamFinished(w.stream.id, buffered); } test finish { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); // The test pair's server answers once the request has ended, so // without the FIN this would wait for ever. const stream = try pair.session().openBidirectional(); var buffer: [64]u8 = undefined; var w = stream.writer(&buffer); try w.interface.writeAll("the whole request"); try w.finish(); var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("the whole request", answer[0..n]); } }; /// A reader over this stream, buffering in `buffer`. See `Reader.init`. pub fn reader(stream: Stream, buffer: []u8) Reader { return .init(stream, buffer); } test reader { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const stream = try pair.session().openBidirectional(); var w = stream.writer(&.{}); try w.interface.writeAll("one line\n"); try w.finish(); // An `Io.Reader` like any other, so a line-oriented protocol reads lines. var buffer: [64]u8 = undefined; var r = stream.reader(&buffer); const line = try r.interface.takeDelimiterInclusive('\n'); try testing.expectEqualStrings("one line\n", line); } /// A writer onto this stream, buffering in `buffer`. See `Writer.init`. pub fn writer(stream: Stream, buffer: []u8) Writer { return .init(stream, buffer); } test writer { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const stream = try pair.session().openBidirectional(); var w = stream.writer(&.{}); try w.interface.print("{s}, {s}", .{ "hello", "world" }); try w.finish(); var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("hello, world", answer[0..n]); } /// Whether everything the peer will send on this stream has arrived, though /// not necessarily been read -- or the peer has reset it, after which nothing /// more will. It does not wait. pub fn received(stream: Stream) bool { const s = stream.session; s.mutex.lockUncancelable(s.io); defer s.mutex.unlock(s.io); return s.connection.streamReceived(stream.id); } test received { var pair: test_pair.Pair = undefined; try pair.start(.{}); defer pair.stop(); const stream = try pair.session().openBidirectional(); var w = stream.writer(&.{}); try w.interface.writeAll("ping"); try w.finish(); // Not waited for here: a caller polling it is one that has something else // to be doing meanwhile. var turns: usize = 0; while (!stream.received()) : (turns += 1) { if (turns > 1000) return error.NoAnswer; try testing.io.sleep(.fromMilliseconds(1), .awake); } var answer: [64]u8 = undefined; var r = stream.reader(&.{}); const n = try r.interface.readSliceShort(&answer); try testing.expectEqualStrings("ping", answer[0..n]); } const testing = std.testing; const test_pair = @import("test_pair.zig");