// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! An `Io.Writer` over a `net.Stream` that stops waiting. //! //! The other half of `TimeoutReader`: each write to the socket is a //! `net_write` operation performed through `Io.operateTimeout`, so a peer that //! stops reading ends the write with `error.Timeout` rather than holding it //! until the peer either reads or goes away. The write returns //! `error.WriteFailed` and `err` says why. `timeout` means what it means for //! `TimeoutReader`: a `.duration` bounds how long the peer may go without //! taking anything, a `.deadline` bounds the whole stream, and `.none` is //! exactly `net.Stream.Writer`. //! //! **A timed write is a small write.** What `Io.Threaded` times is the wait //! for the socket to become writable; the write that follows is an ordinary //! blocking one, and a blocking write larger than the room in the send //! buffer waits for the peer to make more. So with a timeout set, each write //! is at most `max_timed_write` bytes, which on Linux is under the room a //! TCP socket must have before `poll` calls it writable — a third of its send //! buffer, which is at least 16 KiB unless somebody shrank it. That makes the //! write after the wait not block, and costs a `poll` per 4 KiB. With no //! timeout, writes are as large as the buffer and nothing is polled. //! //! The same caveats as `TimeoutReader` apply: `Io.Uring` and `Io.Dispatch` //! panic on a timed socket operation, and `.none` never reaches that path. const std = @import("std"); const Io = std.Io; const net = Io.net; const TimeoutWriter = @This(); io: Io, interface: Io.Writer, stream: net.Stream, timeout: Io.Timeout, /// Why the last write returned `error.WriteFailed`. err: ?Error, pub const Error = net.Stream.Writer.Error || Io.Timeout.Error || Io.ConcurrentError; /// The most one timed write sends. See the top of this file for why. pub const max_timed_write = 4096; pub fn init(stream: net.Stream, io: Io, buffer: []u8, timeout: Io.Timeout) TimeoutWriter { return .{ .io = io, .interface = .{ .vtable = &.{ .drain = drain }, .buffer = buffer, }, .stream = stream, .timeout = timeout, .err = null, }; } /// The timeout for "this long without taking a byte", or none. pub const idle = @import("TimeoutReader.zig").idle; /// Whether the last write failed because the peer took nothing for too long. pub fn timedOut(w: *const TimeoutWriter) bool { const err = w.err orelse return false; return err == error.Timeout; } fn drain(io_w: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize { const w: *TimeoutWriter = @alignCast(@fieldParentPtr("interface", io_w)); const operation: Io.Operation = if (w.timeout == .none) .{ .net_write = .{ .socket_handle = w.stream.socket.handle, .header = io_w.buffered(), .data = data, .splat = splat, } } else .{ .net_write = .{ .socket_handle = w.stream.socket.handle, .header = firstChunk(io_w.buffered(), data, splat) orelse return 0, .data = &.{""}, } }; const result = w.io.operateTimeout(operation, w.timeout) catch |err| { w.err = err; return error.WriteFailed; }; const n = result.net_write catch |err| { w.err = err; return error.WriteFailed; }; // The chunk is a prefix of the buffer followed by the data, so counting // it off the front is right whichever of them it came from. return io_w.consume(n); } /// The first bytes due to be written, at most `max_timed_write` of them. fn firstChunk(buffered: []const u8, data: []const []const u8, splat: usize) ?[]const u8 { const chunk = if (buffered.len != 0) buffered else for (data, 0..) |d, i| { if (i == data.len - 1 and splat == 0) return null; if (d.len != 0) break d; } else return null; return chunk[0..@min(chunk.len, max_timed_write)]; } const testing = std.testing; /// Two ends of a loopback TCP connection. 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 "writes what it is given, and times out on a peer that stops reading" { const io = testing.io; const near, const far = try loopbackPair(io); defer near.close(io); defer far.close(io); var buffer: [256]u8 = undefined; var writer: TimeoutWriter = .init(near, io, &buffer, .{ .duration = .{ .raw = .fromMilliseconds(50), .clock = .awake, } }); try writer.interface.writeAll("hello\n"); try writer.interface.splatByteAll('x', 3); try writer.interface.flush(); var read_buffer: [16]u8 = undefined; var reader = far.reader(io, &read_buffer); try testing.expectEqualStrings("hello\nxxx", try reader.interface.take(9)); // Nobody reads `far` from here on, so the socket buffers fill and a write // has to give up rather than wait for room. const block: [64 * 1024]u8 = @splat('y'); while (true) { writer.interface.writeAll(&block) catch break; } else unreachable; try testing.expect(writer.timedOut()); } test "chunks start where the data does" { try testing.expectEqualStrings("ab", firstChunk("ab", &.{"cd"}, 1).?); try testing.expectEqualStrings("cd", firstChunk("", &.{ "", "cd", "ef" }, 1).?); try testing.expectEqualStrings("ef", firstChunk("", &.{ "", "ef" }, 3).?); try testing.expectEqual(null, firstChunk("", &.{ "", "ef" }, 0)); try testing.expectEqual(null, firstChunk("", &.{""}, 5)); const long: [max_timed_write + 1]u8 = @splat('z'); try testing.expectEqual(max_timed_write, firstChunk(&long, &.{""}, 1).?.len); }