// 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, and allocates the /// read buffer and the output from `gpa`. 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), // An empty reader until `connection` makes the real one, so that // `consumed` has something to ask before then. .reader = .fixed(&.{}), .output = .init(gpa), .info = options.info, .write_shutdown = false, }; } test init { var c: Connection = try .init(std.testing.allocator, "GET / HTTP/1.1\r\n\r\n", .{ .read_buffer_len = 64, .chunk = 1, .info = .{ .secure = true }, }); defer c.deinit(); const conn = c.connection(); try std.testing.expectEqualStrings("https", conn.scheme()); // One octet per read underneath, and still the whole line on top. try std.testing.expectEqualStrings("GET / HTTP/1.1\r\n", try conn.input.takeDelimiterInclusive('\n')); } /// Frees the read buffer and everything written. This, not /// `transport.Connection.close`, is what releases them, so that a test /// can still read `written` after the server has closed the connection. pub fn deinit(c: *Connection) void { c.gpa.free(c.read_buffer); c.output.deinit(); c.* = undefined; } test deinit { var c: Connection = try .init(std.testing.allocator, "", .{}); c.deinit(); } /// The transport-level view. Must be called after the connection has come /// to rest, because it points into it. /// /// Each call starts a fresh reader over the same read buffer, so whatever /// the previous view had buffered and not yet consumed is lost; take one /// view per connection. 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, }; } test connection { var c: Connection = try .init(std.testing.allocator, "ping", .{}); defer c.deinit(); var conn = c.connection(); try std.testing.expectEqualStrings("ping", try conn.input.take(4)); try conn.output.writeAll("pong"); try std.testing.expectEqualStrings("pong", c.written()); } /// Everything written so far, flushed or not: the output is a growable /// buffer, so there is nowhere further for a flush to send it. pub fn written(c: *const Connection) []const u8 { return c.output.writer.buffered(); } test written { var c: Connection = try .init(std.testing.allocator, "", .{}); defer c.deinit(); var conn = c.connection(); try conn.output.writeAll("HTTP/1.1 204 No Content\r\n"); try conn.output.writeAll("\r\n"); try std.testing.expectEqualStrings("HTTP/1.1 204 No Content\r\n\r\n", c.written()); } /// 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. /// /// Octets the reader has buffered but nobody has taken are not counted. /// Zero until `connection` has been called. pub fn consumed(c: *const Connection) usize { return c.pos - c.reader.bufferedLen(); } test consumed { var c: Connection = try .init(std.testing.allocator, "first\nsecond\n", .{}); defer c.deinit(); try std.testing.expectEqual(@as(usize, 0), c.consumed()); var conn = c.connection(); _ = try conn.input.takeDelimiterInclusive('\n'); // The reader may have pulled in all of it, but only the first line // was taken. try std.testing.expectEqual(@as(usize, "first\n".len), c.consumed()); } 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()); }