// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! An `Io.Reader` over a `net.Stream` that stops waiting. //! //! It is `net.Stream.Reader` with one difference: each read from the socket is //! a `net_read` operation performed through `Io.operateTimeout` rather than //! `Io.operate`, so a peer that goes quiet ends the read with //! `error.Timeout` instead of holding it forever. The `Io.Reader` interface //! has no room for that error, so, as with every other failure underneath a //! reader, the read returns `error.ReadFailed` and `err` says why. //! //! What `timeout` bounds depends on which kind it is: //! //! * A `.duration` applies afresh to every read from the socket, so it bounds //! *silence*: a slow peer that keeps sending is never cut off, and one that //! stops is cut off that long after its last byte. That is an idle timeout, //! and it is what an FTP control connection wants. //! * A `.deadline` is one instant for every read, so it bounds the whole //! conversation however busy it is. //! * `.none` waits forever and is exactly `net.Stream.Reader`. //! //! **Not every `Io` can do this.** A timed operation goes through //! `Io.Batch.awaitConcurrent`, which `Io.Threaded` implements with `poll` and //! which, as of 0.17.0-dev.2375, `Io.Uring` and `Io.Dispatch` do not: both //! panic on a `net_read` in a batch, and `Io.Threaded` on Windows refuses one //! with `error.ConcurrencyUnavailable`. With `.none` the batch is skipped and //! the read goes straight to `Io.operate`, which every implementation has, so //! leaving the timeout off costs nothing and is safe everywhere. const std = @import("std"); const Io = std.Io; const net = Io.net; const assert = std.debug.assert; const TimeoutReader = @This(); io: Io, interface: Io.Reader, stream: net.Stream, timeout: Io.Timeout, /// Why the last read returned `error.ReadFailed`. err: ?Error, pub const Error = net.Stream.Reader.Error || Io.Timeout.Error || Io.ConcurrentError; /// The most slices handed to one `net_read`, as in `net.Stream.Reader`. const max_iovecs_len = 8; pub fn init(stream: net.Stream, io: Io, buffer: []u8, timeout: Io.Timeout) TimeoutReader { return .{ .io = io, .interface = .{ .vtable = &.{ .stream = streamImpl, .readVec = readVec, }, .buffer = buffer, .seek = 0, .end = 0, }, .stream = stream, .timeout = timeout, .err = null, }; } /// The timeout for "this long without a byte", or none: how a `?Io.Duration` /// in an options struct becomes what `init` takes. pub fn idle(duration: ?Io.Duration) Io.Timeout { const d = duration orelse return .none; return .{ .duration = .{ .raw = d, .clock = .awake } }; } /// Whether the last read failed because the peer said nothing for too long, /// which is the one failure a caller usually wants to answer differently. pub fn timedOut(r: *const TimeoutReader) bool { const err = r.err orelse return false; return err == error.Timeout; } fn streamImpl(io_r: *Io.Reader, io_w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const dest = limit.slice(try io_w.writableSliceGreedy(1)); var data: [1][]u8 = .{dest}; const n = try readVec(io_r, &data); io_w.advance(n); return n; } fn readVec(io_r: *Io.Reader, data: [][]u8) Io.Reader.Error!usize { const r: *TimeoutReader = @alignCast(@fieldParentPtr("interface", io_r)); var iovecs_buffer: [max_iovecs_len][]u8 = undefined; const dest_n, const data_size = try io_r.writableVector(&iovecs_buffer, data); const dest = iovecs_buffer[0..dest_n]; assert(dest[0].len > 0); const result = r.io.operateTimeout(.{ .net_read = .{ .socket_handle = r.stream.socket.handle, .data = dest, } }, r.timeout) catch |err| { r.err = err; return error.ReadFailed; }; const n = result.net_read catch |err| { r.err = err; return error.ReadFailed; }; if (n == 0) return error.EndOfStream; if (n > data_size) { r.interface.end += n - data_size; return data_size; } return n; } const testing = std.testing; /// Two ends of a loopback TCP connection. A socket pair would be simpler, but /// `socketpair` will not make one in `AF_INET`, and this reader is for TCP. fn loopbackPair(io: Io) ![2]net.Stream { const address: net.IpAddress = .{ .ip4 = .loopback(0) }; var listener = try address.listen(io, .{}); defer listener.deinit(io); const far = try listener.socket.address.connect(io, .{ .mode = .stream }); errdefer far.close(io); return .{ try listener.accept(io), far }; } test "reads what arrives, and times out when nothing does" { const io = testing.io; const near, const far = try loopbackPair(io); defer near.close(io); defer far.close(io); var buffer: [64]u8 = undefined; var reader: TimeoutReader = .init(near, io, &buffer, .{ .duration = .{ .raw = .fromMilliseconds(50), .clock = .awake, } }); var write_buffer: [64]u8 = undefined; var writer = far.writer(io, &write_buffer); try writer.interface.writeAll("hello\n"); try writer.interface.flush(); try testing.expectEqualStrings("hello\n", try reader.interface.takeDelimiterInclusive('\n')); try testing.expect(!reader.timedOut()); // Nothing more is coming, so the next read has to give up rather than // wait for it. try testing.expectError(error.ReadFailed, reader.interface.takeByte()); try testing.expect(reader.timedOut()); } test "with no timeout it is an ordinary reader" { const io = testing.io; const near, const far = try loopbackPair(io); defer near.close(io); var buffer: [64]u8 = undefined; var reader: TimeoutReader = .init(near, io, &buffer, .none); var write_buffer: [64]u8 = undefined; var writer = far.writer(io, &write_buffer); try writer.interface.writeAll("bye"); try writer.interface.flush(); far.close(io); var out: [8]u8 = undefined; try testing.expectEqual(@as(usize, 3), try reader.interface.readSliceShort(&out)); try testing.expectEqualStrings("bye", out[0..3]); try testing.expectError(error.EndOfStream, reader.interface.takeByte()); }