// 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, pub fn init(stream: Stream, buffer: []u8) Reader { return .{ .interface = .{ .vtable = &.{ .stream = streamImpl }, .buffer = buffer, .seek = 0, .end = 0, }, .stream = stream, }; } 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, pub fn init(stream: Stream, buffer: []u8) Writer { return .{ .interface = .{ .vtable = &vtable, .buffer = buffer }, .stream = stream, }; } 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; } /// §4.5: says there is nothing more, which puts a FIN on the frame /// carrying the last octet. 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); } }; pub fn reader(stream: Stream, buffer: []u8) Reader { return .init(stream, buffer); } pub fn writer(stream: Stream, buffer: []u8) Writer { return .init(stream, buffer); } /// Whether everything the peer will send on this stream has arrived. 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); }