// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A connection made of a slice of bytes going in and a growable buffer //! coming out. //! //! This is how the server is tested, and it is worth being explicit about why //! it is in `src` rather than in `tests`: a transport-agnostic server whose //! only transport is a socket is not transport-agnostic, it is a socket //! server with an interface in front of it. Having a second real //! implementation is what keeps the seam honest — every assumption about //! sockets that leaked upwards shows up here as something that will not //! compile or will not run. //! //! What it buys in return is a test suite with no ports, no scheduling and no //! waiting: a whole keep-alive sequence is a string literal, and the fuzzer //! gets through hundreds of thousands of requests a second because there is //! nothing underneath but `@memcpy`. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const transport = @import("../transport.zig"); pub const Connection = struct { gpa: Allocator, source: []const u8, pos: usize, /// The most a single read will hand over, or zero for no limit. chunk: usize, read_buffer: []u8, reader: Io.Reader, output: Io.Writer.Allocating, info: transport.Connection.Info, /// Whether the writing half was shut down, which is what an HTTP/1.0 /// response of unknown length ends with. write_shutdown: bool, pub const Options = struct { /// The read buffer, which bounds how long a single header line may /// be, exactly as a socket's would. read_buffer_len: usize = 8192, /// Hand over at most this many octets per read, or zero for as many /// as are asked for. /// /// A real socket returns whatever happens to have arrived, so a /// parser that only ever sees its whole input at once has not been /// tested. Setting this to 1 delivers a request one octet at a time, /// which is the cheapest way to find a parser that assumed /// otherwise. chunk: usize = 0, info: transport.Connection.Info = .{}, }; /// Borrows `source`, which must outlive the connection. pub fn init(gpa: Allocator, source: []const u8, options: Options) Allocator.Error!Connection { return .{ .gpa = gpa, .source = source, .pos = 0, .chunk = options.chunk, .read_buffer = try gpa.alloc(u8, options.read_buffer_len), .reader = undefined, .output = .init(gpa), .info = options.info, .write_shutdown = false, }; } pub fn deinit(c: *Connection) void { c.gpa.free(c.read_buffer); c.output.deinit(); c.* = undefined; } /// The transport-level view. Must be called after the connection has come /// to rest, because it points into it. pub fn connection(c: *Connection) transport.Connection { c.reader = .{ .vtable = &reader_vtable, .buffer = c.read_buffer, .seek = 0, .end = 0, }; return .{ .input = &c.reader, .output = &c.output.writer, .info = c.info, .context = c, .vtable = &vtable, }; } /// Everything written so far. pub fn written(c: *const Connection) []const u8 { return c.output.writer.buffered(); } /// How much of the input has been read, which is how a test checks that a /// server consumed exactly one request and left the next one alone. pub fn consumed(c: *const Connection) usize { return c.pos - c.reader.bufferedLen(); } const reader_vtable: Io.Reader.VTable = .{ .stream = streamImpl }; fn streamImpl(r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const c: *Connection = @alignCast(@fieldParentPtr("reader", r)); const remaining = c.source[c.pos..]; if (remaining.len == 0) return error.EndOfStream; const dest = limit.slice(try w.writableSliceGreedy(1)); var n = @min(dest.len, remaining.len); if (c.chunk != 0) n = @min(n, c.chunk); @memcpy(dest[0..n], remaining[0..n]); w.advance(n); c.pos += n; return n; } const vtable: transport.Connection.VTable = .{ .close = closeImpl, .shutdownWrite = shutdownWriteImpl, }; fn closeImpl(context: ?*anyopaque, io: Io, gpa: Allocator) void { // Nothing to release: `deinit` owns the buffers, so that a test can // read what was written after the server has closed the connection. _ = .{ context, io, gpa }; } fn shutdownWriteImpl(context: ?*anyopaque, io: Io) void { _ = io; const c: *Connection = @ptrCast(@alignCast(context.?)); c.write_shutdown = true; } }; test "reads what it was given and keeps what was written" { const gpa = std.testing.allocator; var c: Connection = try .init(gpa, "GET / HTTP/1.1\r\n\r\n", .{}); defer c.deinit(); var conn = c.connection(); try std.testing.expectEqualStrings("GET / HTTP/1.1\r\n", try conn.input.takeDelimiterInclusive('\n')); try conn.output.writeAll("HTTP/1.1 204 No Content\r\n\r\n"); try conn.output.flush(); try std.testing.expectEqualStrings("HTTP/1.1 204 No Content\r\n\r\n", c.written()); } test "a chunk limit delivers the input a little at a time" { const gpa = std.testing.allocator; var c: Connection = try .init(gpa, "abcdef", .{ .chunk = 1 }); defer c.deinit(); var conn = c.connection(); // Asking for all six still works; it just takes six reads underneath. try std.testing.expectEqualStrings("abcdef", try conn.input.take(6)); try std.testing.expectError(error.EndOfStream, conn.input.takeByte()); }