Something went wrong. Try again.
An HTTP library for Zig 0.17, server and client, HTTP/1.0 through HTTP/3, with the protocol in a module that owns no socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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,
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; 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,
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;
// 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); } };
pub fn reader(stream: Stream, buffer: []u8) Reader { return .init(stream, buffer); }
pub fn writer(stream: Stream, buffer: []u8) Writer { return .init(stream, buffer); }};
/// 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, /// §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, };
pub fn waitEstablished(s: Session) bool { return s.vtable.waitEstablished(s.context); }
pub fn accept(s: Session) ?Stream { const id = s.vtable.accept(s.context) orelse return null; return .{ .session = s, .id = id }; }
pub fn openUnidirectional(s: Session) OpenError!Stream { return .{ .session = s, .id = try s.vtable.openUnidirectional(s.context) }; }
pub fn openBidirectional(s: Session) OpenError!Stream { return .{ .session = s, .id = try s.vtable.openBidirectional(s.context) }; }
pub fn resetStream(s: Session, id: quic.stream.Id, code: u64) void { s.vtable.resetStream(s.context, id, code); }
pub fn stopSending(s: Session, id: quic.stream.Id, code: u64) void { s.vtable.stopSending(s.context, id, code); }
pub fn close(s: Session, code: u64, why: []const u8) void { s.vtable.close(s.context, code, 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);}