// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A connection that carries many independent streams, which is what HTTP/3 //! is served over. //! //! `transport.Connection` is one ordered byte stream, and HTTP/1.1 and //! HTTP/2 are both that. HTTP/3 is not: RFC 9114 §4.1 puts each request on a //! stream of its own and §4.6 hands stream limits, flow control and //! cancellation to QUIC, so a driver written against a single reader and //! writer cannot express it. This is the seam for that shape -- accept a //! stream, open one, read it, write it, cancel it -- and nothing in it names //! a socket, a datagram or a QUIC connection. //! //! The point is the same as for `Connection`: what is above this seam is the //! protocol, and what is below it is the machinery. `quic_io` is one //! implementation and a scripted set of streams in a test is another, so the //! HTTP/3 driver can be exercised without a port in the same way the HTTP/1.1 //! one can. //! //! ## Why the vtable is shaped like `Io.Reader` and `Io.Writer` //! //! A stream is read and written through the ordinary `Io` interfaces, and the //! two operations that actually move octets -- `Io.Reader.VTable.stream` and //! `Io.Writer.VTable.drain` -- are what this delegates. Anything narrower //! would cost a copy: an implementation that hands out a borrowed slice of //! its own reassembly window can write it straight into the caller's writer, //! where a `read(buffer)` shape would have to copy it first and then deal //! with a writer that accepted only part of it. const std = @import("std"); const Io = std.Io; const quic = @import("quic"); const memory_session = @import("memory_session.zig"); /// One stream, as a reader and a writer. /// /// A value rather than a handle: it is a session and an identifier, so it /// costs nothing to copy and there is nothing to free. pub const Stream = struct { session: Session, id: quic.stream.Id, /// A reader over what the peer sends on this stream. /// /// Holds its own buffer because `Io.Reader` needs somewhere to put what /// it is given, and because the alternative -- handing out a slice of the /// session's own window -- is a borrow the session invalidates as soon as /// it is told the octets were taken. pub const Reader = struct { interface: Io.Reader, stream: Stream, /// A reader over `stream` that buffers through `buffer`. The reader /// points into itself, so read through `interface` where the /// `Reader` will stay rather than through a copy of it. pub fn init(stream: Stream, buffer: []u8) Reader { return .{ .interface = .{ .vtable = &.{ .stream = streamImpl }, .buffer = buffer, .seek = 0, .end = 0, }, .stream = stream, }; } test init { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{ .{ .id = .{ .value = 0 }, .data = "a request" }, } }; defer scripted.deinit(gpa); const stream = scripted.session(gpa).accept().?; var buffer: [64]u8 = undefined; var r: Reader = .init(stream, &buffer); const got = try r.interface.allocRemaining(gpa, .unlimited); defer gpa.free(got); try std.testing.expectEqualStrings("a request", got); } 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; return s.vtable.streamIn(s.context, r.stream.id, w, limit); } }; /// A writer for what this endpoint sends on this stream. pub const Writer = struct { interface: Io.Writer, stream: Stream, /// A writer for `stream` that buffers through `buffer`. Like /// `Reader.init`, the result points into itself and is written /// through `interface` where it stays. /// /// Flushing puts the octets on the stream but does not end it; that /// is `finish`. pub fn init(stream: Stream, buffer: []u8) Writer { return .{ .interface = .{ .vtable = &vtable, .buffer = buffer }, .stream = stream, }; } test init { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); const stream = try scripted.session(gpa).openUnidirectional(); var buffer: [64]u8 = undefined; var w: Writer = .init(stream, &buffer); try w.interface.writeAll("settings"); try w.interface.flush(); try std.testing.expectEqualStrings("settings", scripted.wrote(stream.id).?); // Flushed, and still open. try std.testing.expect(!scripted.find(stream.id).?.finished); } 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; // Whatever is already buffered goes first, or the stream would // carry the octets out of order. const buffered = io_writer.buffered(); if (buffered.len > 0) { try s.vtable.writeOut(s.context, 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.vtable.writeOut(s.context, w.stream.id, slice); written += slice.len; } } return written; } /// §4.5 of RFC 9000: says there is nothing more, which puts a FIN on /// the frame carrying the last octet. /// /// "The frame carrying the last octet" is the part worth insisting on. /// An implementation that can end a stream and send its last octets in /// one operation says so with `VTable.finishWith`, and this hands the /// buffered tail to it rather than flushing first -- because flushing /// first leaves the FIN nothing to travel with, and a frame carrying /// only the FIN bit is a frame some peers ignore. See /// `quic_io.Session.writeStreamFinished` for the server that taught us. pub fn finish(w: *Writer) Io.Writer.Error!void { const s = w.stream.session; if (s.vtable.finishWith) |with| { const buffered = w.interface.buffered(); w.interface.end = 0; return with(s.context, w.stream.id, buffered); } try w.interface.flush(); return s.vtable.finish(s.context, w.stream.id); } test finish { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); const stream = try scripted.session(gpa).openBidirectional(); var buffer: [64]u8 = undefined; var w: Writer = .init(stream, &buffer); try w.interface.writeAll("the last of it"); try w.finish(); const state = scripted.find(stream.id).?; try std.testing.expect(state.finished); // The buffered tail travelled with the FIN, not ahead of it. try std.testing.expectEqual(@as(usize, "the last of it".len), state.fin_carried); } }; /// `Reader.init`, for a stream in hand. pub fn reader(stream: Stream, buffer: []u8) Reader { return .init(stream, buffer); } test reader { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{ .{ .id = .{ .value = 0 }, .data = "GET\n" }, } }; defer scripted.deinit(gpa); const stream = scripted.session(gpa).accept().?; var buffer: [64]u8 = undefined; var r = stream.reader(&buffer); try std.testing.expectEqualStrings("GET\n", try r.interface.takeDelimiterInclusive('\n')); } /// `Writer.init`, for a stream in hand. pub fn writer(stream: Stream, buffer: []u8) Writer { return .init(stream, buffer); } test writer { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); const stream = try scripted.session(gpa).openBidirectional(); var buffer: [64]u8 = undefined; var w = stream.writer(&buffer); try w.interface.writeAll("hello"); try w.finish(); try std.testing.expectEqualStrings("hello", scripted.wrote(stream.id).?); } }; /// The connection the streams belong to. pub const Session = struct { context: ?*anyopaque, vtable: *const VTable, pub const OpenError = error{ /// The peer has not granted room for another stream, or the /// connection is closing. §4.6 of RFC 9114 leaves this to QUIC. StreamUnavailable, }; pub const VTable = struct { /// Blocks until the handshake finishes. False when it never will. /// /// §6.2 of RFC 9114 is why a driver has to wait: the control streams /// cannot be opened before the peer has said how many streams this /// endpoint may open, and it says so in transport parameters that /// arrive with the handshake. waitEstablished: *const fn (context: ?*anyopaque) bool, /// The next stream the peer opened, or null when there will be no /// more -- which is how a driver's accept loop ends. accept: *const fn (context: ?*anyopaque) ?quic.stream.Id, /// Opens a stream this endpoint will only write to. openUnidirectional: *const fn (context: ?*anyopaque) OpenError!quic.stream.Id, /// Opens a stream this endpoint will write to and read from, which is /// what a request is: §4.1 of RFC 9114 puts each one on its own /// bidirectional stream, opened by the client. openBidirectional: *const fn (context: ?*anyopaque) OpenError!quic.stream.Id, /// Moves up to `limit` octets from a stream into `w`, blocking until /// there is something to move. `error.EndOfStream` when the peer has /// finished the stream and everything it sent has been handed over. streamIn: *const fn ( context: ?*anyopaque, id: quic.stream.Id, w: *Io.Writer, limit: Io.Limit, ) Io.Reader.StreamError!usize, /// Puts octets on a stream, blocking until there is room for them /// rather than failing -- which is what makes a body larger than any /// one buffer expressible at all. writeOut: *const fn ( context: ?*anyopaque, id: quic.stream.Id, bytes: []const u8, ) Io.Writer.Error!void, /// Ends this endpoint's half of a stream. finish: *const fn (context: ?*anyopaque, id: quic.stream.Id) Io.Writer.Error!void, /// Writes the last octets and ends this endpoint's half, together. /// /// Optional, and what it buys is one packet rather than two: a FIN set /// while the octets are still unsent travels on the frame that carries /// them. An implementation that leaves it null is driven through /// `writeOut` and then `finish`, which is correct and is what some /// peers quietly refuse to answer. finishWith: ?*const fn ( context: ?*anyopaque, id: quic.stream.Id, bytes: []const u8, ) Io.Writer.Error!void = null, /// Whether everything the peer will send on a stream has arrived, /// without waiting for any of it -- which is to say whether its FIN /// is in, whatever has or has not been read yet. /// /// Optional, and null answers false: "not known to be finished" is /// always a safe answer, since what asks is deciding whether the peer /// might still be waiting for something. received: ?*const fn (context: ?*anyopaque, id: quic.stream.Id) bool = null, /// §4.1 of RFC 9114: abandons a stream in this direction. resetStream: *const fn (context: ?*anyopaque, id: quic.stream.Id, code: u64) void, /// Asks the peer to stop sending on a stream, because what it is /// sending will not be read. stopSending: *const fn (context: ?*anyopaque, id: quic.stream.Id, code: u64) void, /// Ends the whole connection with an application error code. close: *const fn (context: ?*anyopaque, code: u64, why: []const u8) void, }; /// Blocks until the handshake finishes, and says whether it did. See /// `VTable.waitEstablished`. pub fn waitEstablished(s: Session) bool { return s.vtable.waitEstablished(s.context); } test waitEstablished { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); // A scripted session has no handshake, so it is established at once. try std.testing.expect(scripted.session(gpa).waitEstablished()); } /// The next stream the peer opened, or null when there will be no more. pub fn accept(s: Session) ?Stream { const id = s.vtable.accept(s.context) orelse return null; return .{ .session = s, .id = id }; } test accept { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{ .{ .id = .{ .value = 0 }, .data = "first" }, .{ .id = .{ .value = 4 }, .data = "second" }, } }; defer scripted.deinit(gpa); const s = scripted.session(gpa); try std.testing.expectEqual(@as(u64, 0), s.accept().?.id.value); try std.testing.expectEqual(@as(u64, 4), s.accept().?.id.value); // The end of the accept loop. try std.testing.expect(s.accept() == null); } /// Opens a stream this endpoint will only write to: an HTTP/3 control or /// QPACK stream. pub fn openUnidirectional(s: Session) OpenError!Stream { return .{ .session = s, .id = try s.vtable.openUnidirectional(s.context) }; } test openUnidirectional { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); const control = try scripted.session(gpa).openUnidirectional(); // §2.1 of RFC 9000: a server's first unidirectional stream is 3. try std.testing.expectEqual(@as(u64, 3), control.id.value); } /// Opens a stream this endpoint will write to and read from, which is /// what a client puts each request on. pub fn openBidirectional(s: Session) OpenError!Stream { return .{ .session = s, .id = try s.vtable.openBidirectional(s.context) }; } test openBidirectional { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{}, .answer = "the answer" }; defer scripted.deinit(gpa); const stream = try scripted.session(gpa).openBidirectional(); var buffer: [64]u8 = undefined; var r = stream.reader(&buffer); try std.testing.expectEqualStrings("the answer", try r.interface.take(10)); } /// Whether the peer has finished the stream, without waiting. See /// `VTable.received`; a transport that leaves it null answers false. pub fn received(s: Session, id: quic.stream.Id) bool { const f = s.vtable.received orelse return false; return f(s.context, id); } test received { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{ .{ .id = .{ .value = 0 }, .data = "done" }, .{ .id = .{ .value = 4 }, .data = "more to come", .received = false }, } }; defer scripted.deinit(gpa); const s = scripted.session(gpa); const done = s.accept().?; const waiting = s.accept().?; try std.testing.expect(s.received(done.id)); try std.testing.expect(!s.received(waiting.id)); } /// Abandons this endpoint's sending half of a stream with an application /// error code -- QUIC's `RESET_STREAM`. pub fn resetStream(s: Session, id: quic.stream.Id, code: u64) void { s.vtable.resetStream(s.context, id, code); } test resetStream { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); const s = scripted.session(gpa); const stream = try s.openBidirectional(); s.resetStream(stream.id, 0x10c); // H3_REQUEST_CANCELLED try std.testing.expectEqual(@as(?u64, 0x10c), scripted.find(stream.id).?.reset); } /// Asks the peer to stop sending on a stream, because what it is sending /// will not be read -- QUIC's `STOP_SENDING`. pub fn stopSending(s: Session, id: quic.stream.Id, code: u64) void { s.vtable.stopSending(s.context, id, code); } test stopSending { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{ .{ .id = .{ .value = 0 }, .data = "an unwanted body" }, } }; defer scripted.deinit(gpa); const s = scripted.session(gpa); const stream = s.accept().?; s.stopSending(stream.id, 0x100); // H3_NO_ERROR try std.testing.expectEqual(@as(?u64, 0x100), scripted.find(stream.id).?.stopped); } /// Ends the whole connection with an application error code and a /// reason, which the transport may pass to the peer. pub fn close(s: Session, code: u64, why: []const u8) void { s.vtable.close(s.context, code, why); } test close { const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); scripted.session(gpa).close(0x100, "done"); try std.testing.expectEqual(@as(u64, 0x100), scripted.closed.?.code); try std.testing.expectEqualStrings("done", scripted.closed.?.why); } }; test "a writer's last octets go out with the FIN, not ahead of it" { // The seam's half of what `quic_io.Session.writeStreamFinished` is for: a // driver that writes into its buffer and calls `finish` must reach the // transport in *one* operation, because an implementation that sends the // octets first has nothing left to put the FIN on -- and a frame carrying // only the FIN bit is one some peers ignore. Quad9's DNS-over-HTTP/3 server // is the one that taught us; here the count is the assertion. const gpa = std.testing.allocator; var scripted: memory_session.Scripted = .{ .incoming = &.{} }; defer scripted.deinit(gpa); const s = scripted.session(gpa); const stream = try s.openBidirectional(); var buffer: [64]u8 = undefined; var w = stream.writer(&buffer); try w.interface.writeAll("a request, entire"); try w.finish(); const state = scripted.find(stream.id) orelse return error.NoStream; try std.testing.expectEqualStrings("a request, entire", state.written.items); try std.testing.expect(state.finished); // Nothing reached the transport before the FIN did. try std.testing.expectEqual(@as(usize, 0), state.writes); }