From 6753d41e80f2227c0cf56cc03fa5b6e0e116db27 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 4 Nov 2026 23:30:25 -0300 Subject: 9p_io Client: readWith and writeWith, one body twice, are one fetch the verbs call; land takes a ?*Taker and says a refused Tversion itself, so the anytype sink, NoSink and landChecked go; walkTo answers the fid its two callers read; forget is one function, not a wrapper of kept.forget; the Listener's of(ctx) cast is written where it is used, and nowMs and nap are the file's, not aliased in the Listener and borrowed from the Client Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/9p_io.zig | 154 +++++++++++++++++++++++----------------------------------- 1 file changed, 61 insertions(+), 93 deletions(-) diff --git a/src/9p_io.zig b/src/9p_io.zig index 62b6c37e..50c7fb95 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -12,6 +12,12 @@ pub const quic_enabled = false; const log = std.log.scoped(.ninep); +const nowMs = transport.nowMs; + +fn nap(ms: c_int) void { + _ = libc.poll(&[0]libc.pollfd{}, 0, ms); +} + pub const darwin = builtin.os.tag.isDarwin(); pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd or darwin; pub const sun_path_len = @typeInfo(@FieldType(libc.sockaddr.un, "path")).array.len; @@ -147,10 +153,6 @@ pub const Listener = struct { return l.path_buf[0..l.path_len]; } - fn of(ctx: ?*anyopaque) *Listener { - return @ptrCast(@alignCast(ctx.?)); - } - /// The runner's handler, on the connection's task: takes the turn and /// answers. A request that would change a pane while the editor is out /// in a syscall mid-step is parked in the engine instead, and retried @@ -158,13 +160,13 @@ pub const Listener = struct { /// On the accepting task, without the turn: counted, and logged with /// the turn (`answerHeld`). fn onRefused(ctx: ?*anyopaque) void { - const l = of(ctx); + const l: *Listener = @ptrCast(@alignCast(ctx.?)); _ = l.refused.fetchAdd(1, .acq_rel); l.kick(); } fn onOpened(ctx: ?*anyopaque, conn: *Runner.Conn) void { - const l = of(ctx); + const l: *Listener = @ptrCast(@alignCast(ctx.?)); l.accepted[conn.index].store(l.accepts.fetchAdd(1, .acq_rel) + 1, .release); } @@ -174,7 +176,7 @@ pub const Listener = struct { } fn onServe(ctx: ?*anyopaque, conn: *Runner.Conn, req: pardes.ctlfs.Req) void { - const l = of(ctx); + const l: *Listener = @ptrCast(@alignCast(ctx.?)); if (req.op == .write) _ = l.writes_out.fetchAdd(1, .acq_rel); defer if (req.op == .write) { _ = l.writes_out.fetchSub(1, .acq_rel); @@ -351,7 +353,7 @@ pub const Listener = struct { /// on any of them would be lost to the reader that comes next. fn answerHeld(ctx: ?*anyopaque) void { if (comptime !supported) return; - const l = of(ctx); + const l: *Listener = @ptrCast(@alignCast(ctx.?)); if (l.stopping.load(.acquire)) return; const core = l.core; const refused = l.refused.swap(0, .acq_rel); @@ -423,7 +425,7 @@ pub const Listener = struct { /// The turn was given up quiet with a request parked: every connection /// retries what it parked. fn wakeParked(ctx: ?*anyopaque) void { - const l = of(ctx); + const l: *Listener = @ptrCast(@alignCast(ctx.?)); if (l.stopping.load(.acquire)) return; if (comptime supported) l.runner.wakeAll(); } @@ -437,8 +439,6 @@ pub const Listener = struct { pub const greet_deadline_ms: i64 = 5000; - const nowMs = transport.nowMs; - /// What a frontend's poll of the listener did; the runner's own tasks /// serve every connection, so there is never more to do at once. pub const Polled = struct { count: usize = 0, pending: bool = false }; @@ -487,7 +487,7 @@ pub const Listener = struct { if (n != 0) break true; } else false; if (!pending) break; - Client.nap(1); + nap(1); } for (&l.runner.conns) |*conn| if (l.cutting(conn)) conn.close(); const deadline = nowMs() +| 2000; @@ -496,7 +496,7 @@ pub const Listener = struct { if (l.cutting(conn)) break true; } else false; if (!left) break; - Client.nap(1); + nap(1); } pardes.turn.wake(); l.cut_before = 0; @@ -643,9 +643,9 @@ pub const Listener = struct { if (n != 0) break true; } else false; if (!pending) break; - Client.nap(1); + nap(1); } - Client.nap(1); // the last bytes leave the stream's own buffer + nap(1); // the last bytes leave the stream's own buffer } pub fn deinit(l: *Listener, gpa: std.mem.Allocator) void { @@ -794,7 +794,7 @@ fn claim(sock: []const u8, buf: *[lock_path_len:0]u8) ?c_int { if (fd < 0) return null; if (libc.flock(fd, std.posix.LOCK.EX | std.posix.LOCK.NB) != 0) { _ = libc.close(fd); - Client.nap(1); + nap(1); continue; } const io = std.Io.Threaded.global_single_threaded.io(); @@ -1409,17 +1409,17 @@ test "Unix and TCP share one listener through reads writes reconnects and reset" defer thread.join(); // The editor rests while the client works: its requests are // answered on the runner's tasks, not by this thread. - const deadline = Client.nowMs() + 3 * Client.budget_ms; + const deadline = nowMs() + 3 * Client.budget_ms; pardes.turn.rest(); - while (!worker.done.load(.acquire) and Client.nowMs() < deadline) Client.nap(1); + while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1); // The client has hung up, but its connection's task may not have // seen that yet. The releases it then owes are refused once // `reset` starts cutting (they name the old editor's opens), and // this test's "replacement" is the same editor, so they would // stay in `p.fs.opens`. Let the hangup pay them first, resting // so the task can take the turn: that is what is under test here. - const settle_by = Client.nowMs() + 3 * Client.budget_ms; - while (l.runner.count() != 0 and Client.nowMs() < settle_by) Client.nap(1); + const settle_by = nowMs() + 3 * Client.budget_ms; + while (l.runner.count() != 0 and nowMs() < settle_by) nap(1); pardes.turn.wake(); try testing.expect(worker.done.load(.acquire)); if (worker.failure) |err| return err; @@ -1471,7 +1471,7 @@ test "a change waits while the editor is out mid-step, a read does not, and the pardes.turn.yield(); const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer}); defer thread.join(); - Client.nap(150); + nap(150); try testing.expect(!writer.done.load(.acquire)); const seen = try Client.readLimit(gpa, l.path(), body, body, 64); defer gpa.free(seen); @@ -1483,17 +1483,17 @@ test "a change waits while the editor is out mid-step, a read does not, and the // Resting is what lets it in: the parked write is retried, served, and // the client hears back. pardes.turn.rest(); - const deadline = Client.nowMs() + Client.budget_ms; - while (!writer.done.load(.acquire) and Client.nowMs() < deadline) Client.nap(1); + const deadline = nowMs() + Client.budget_ms; + while (!writer.done.load(.acquire) and nowMs() < deadline) nap(1); pardes.turn.wake(); try testing.expect(writer.done.load(.acquire)); if (writer.failure) |err| return err; // Its bytes are held until its open is let go (pane.zig `batchFor`), and // the client lets it go without waiting: rested again until that lands, // the body read only while the editor has the turn. - while (!std.mem.eql(u8, pane.file.?.content, "after\n") and Client.nowMs() < deadline) { + while (!std.mem.eql(u8, pane.file.?.content, "after\n") and nowMs() < deadline) { pardes.turn.rest(); - Client.nap(1); + nap(1); pardes.turn.wake(); } try testing.expectEqualStrings("after\n", pane.file.?.content); @@ -1551,8 +1551,8 @@ test "a mount's connection is kept between operations, and one the peer hung up // The peer hangs up (a Restore cuts its clients): the next // operation dials again and is answered. for (&w.l.runner.conns) |*conn| if (conn.live()) conn.close(); - const by = Client.nowMs() + Client.budget_ms; - while (w.l.runner.count() != 0 and Client.nowMs() < by) Client.nap(1); + const by = nowMs() + Client.budget_ms; + while (w.l.runner.count() != 0 and nowMs() < by) nap(1); try w.read(w.long); try testing.expectEqual(@as(u64, 2), w.l.accepts.load(.acquire)); } @@ -1560,12 +1560,12 @@ test "a mount's connection is kept between operations, and one the peer hung up var worker: Worker = .{ .l = l, .body = body, .long = long }; pardes.turn.rest(); const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker}); - const deadline = Client.nowMs() + 3 * Client.budget_ms; - while (!worker.done.load(.acquire) and Client.nowMs() < deadline) Client.nap(1); + const deadline = nowMs() + 3 * Client.budget_ms; + while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1); thread.join(); // Forgotten: the kept connection is closed, and its task sees it. - const settle_by = Client.nowMs() + Client.budget_ms; - while (l.runner.count() != 0 and Client.nowMs() < settle_by) Client.nap(1); + const settle_by = nowMs() + Client.budget_ms; + while (l.runner.count() != 0 and nowMs() < settle_by) nap(1); pardes.turn.wake(); if (worker.failure) |err| return err; try testing.expectEqual(@as(usize, 0), l.runner.count()); @@ -1597,7 +1597,7 @@ test "a held read is answered when the log has news, and a flushed one spends no // it does so that the runner's tasks can take the turn and answer. const s = try gpa.create(Client.Session); defer gpa.destroy(s); - s.* = .{ .fd = -1, .deadline = Client.nowMs() + 3 * Client.budget_ms, .display_path = "/log" }; + s.* = .{ .fd = -1, .deadline = nowMs() + 3 * Client.budget_ms, .display_path = "/log" }; var sock_buf: [sun_path_len]u8 = undefined; pardes.turn.rest(); defer pardes.turn.wake(); @@ -1620,14 +1620,14 @@ test "a held read is answered when the log has news, and a flushed one spends no const heldNow = struct { /// Waits until the core holds `n` reads. fn count(core: *pardes.Pardes, n: usize) !void { - const deadline = Client.nowMs() + Client.budget_ms; - while (Client.nowMs() < deadline) { + const deadline = nowMs() + Client.budget_ms; + while (nowMs() < deadline) { pardes.turn.wake(); var got: usize = 0; for (core.fs.opens) |o| got += @intFromBool(o.held != null); pardes.turn.rest(); if (got == n) return; - Client.nap(1); + nap(1); } return error.Timeout; } @@ -1897,20 +1897,23 @@ pub const Client = struct { } pub fn readLimit(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { - return readWith(false, gpa, dial, path, display_path, max_bytes); + return fetch(false, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); } /// readLimit through a mount: its connection kept for the next (`kept`). pub fn readMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { - return readWith(true, gpa, dial, path, display_path, max_bytes); + return fetch(true, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); } - fn readWith(keep: bool, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { + /// One operation on `path`, a read of up to `read_limit` or a write of + /// `write_bytes`, on the connection kept for `dial` when `keep`: the + /// peer's words, when it refuses, kept for lastSaid. + fn fetch(keep: bool, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, write_bytes: ?[]const u8, read_limit: usize) ![]u8 { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); var remote: RemoteError = .{}; - return fetchBytes(gpa, dial, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes), keep) catch |err| { + return fetchBytes(gpa, dial, names[0..n], &remote, write_bytes, display_path, read_limit, keep) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -1936,7 +1939,7 @@ pub const Client = struct { } fn probeWith(keep: bool, gpa: std.mem.Allocator, dial: []const u8) !void { - const got = readWith(keep, gpa, dial, "", "", 0) catch |err| switch (err) { + const got = fetch(keep, gpa, dial, "", "", null, 0) catch |err| switch (err) { error.IsDirectory, error.NotFound, error.Remote, error.FileTooLarge => return, else => return err, }; @@ -1944,24 +1947,12 @@ pub const Client = struct { } pub fn write(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { - return writeWith(false, gpa, dial, path, bytes); + gpa.free(try fetch(false, gpa, dial, path, path, bytes, limits.max_file_bytes)); } /// write through a mount: its connection kept for the next (`kept`). pub fn writeMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { - return writeWith(true, gpa, dial, path, bytes); - } - - fn writeWith(keep: bool, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { - if (comptime !supported) return error.Unsupported; - var names: [max_depth][]const u8 = undefined; - const n = try elements(path, &names); - var remote: RemoteError = .{}; - const result = fetchBytes(gpa, dial, names[0..n], &remote, bytes, path, limits.max_file_bytes, keep) catch |err| { - if (err == error.Remote) said = remote; - return err; - }; - gpa.free(result); + gpa.free(try fetch(true, gpa, dial, path, path, bytes, limits.max_file_bytes)); } const RemoteError = struct { @@ -2134,10 +2125,11 @@ pub const Client = struct { } /// Sends the flight and takes every answer of it, a read's bytes - /// into `sink` as they come (each valid only until the next), so + /// into `taker` as they come (each valid only until the next), so /// that the connection is left with nothing out but its clunks. A - /// refused Tversion is Remote at once: nothing after it is answered. - fn land(s: *Session, f: *Flight, sink: anytype) Error!void { + /// refused Tversion is its words at once: nothing after it is + /// answered. + fn land(s: *Session, f: *Flight, taker: ?*Taker, remote: *RemoteError) Error!void { if (f.get(.version) != null) s.cl.versioning = true; while (f.open()) { const done = try s.settle(); @@ -2147,7 +2139,7 @@ pub const Client = struct { .fail => |words| { item.failed = true; item.said.keep(words); - if (item.step == .version) return Error.Remote; + if (item.step == .version) return remote.set(words); }, .version => { if (item.step != .version or s.cl.msize == 0) return Error.Botch; @@ -2173,7 +2165,7 @@ pub const Client = struct { .read => |data| { if (item.step != .read) return Error.Botch; item.n = data.len; - sink.take(item, data); + if (taker) |t| t.take(item, data); // A read is timed by its progress, as a long write // is: each answer gives the rest the budget again, so // a large file over a slow link is not cut off. @@ -2277,32 +2269,19 @@ pub const Client = struct { const read_ahead = ninep.Client.window - 2; /// Version and attach on a new connection, and a walk to `names`, in - /// one flight: the fid there and its qid. - fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !struct { fid: u32, qid: ninep.Qid } { + /// one flight: the fid there. + fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !u32 { var f: Flight = .{}; try s.greet(&f); const fid = try s.walkNew(&f, names); - try landChecked(s, &f, NoSink{}, remote); + try s.land(&f, null, remote); f.check(remote) catch |err| { if (f.made()) s.dropNoWait(fid); return err; }; - return .{ .fid = fid, .qid = f.qid(s.root_qid) }; + return fid; } - /// `land`, saying a refused Tversion in its own words: nothing else of - /// that flight is answered. - fn landChecked(s: *Session, f: *Flight, sink: anytype, remote: *RemoteError) Error!void { - s.land(f, sink) catch |err| { - if (err == Error.Remote) try f.check(remote); - return err; - }; - } - - const NoSink = struct { - fn take(_: NoSink, _: *Flight.Item, _: []const u8) void {} - }; - /// A read's bytes taken in order: a file's as they are, a directory's /// entries as rows of names. A read ahead that came back out of order, /// or past one that came back short, is not taken: what it held is @@ -2407,7 +2386,7 @@ pub const Client = struct { item.count = s.cl.maxRead(); } var taker: Taker = .{ .out = out, .display_path = s.display_path, .limit = read_limit, .flight = &f, .s = s }; - try landChecked(s, &f, &taker, remote); + try s.land(&f, &taker, remote); defer if (f.made()) s.dropNoWait(fid); try f.check(remote); if (taker.err) |err| return err; @@ -2462,7 +2441,7 @@ pub const Client = struct { off += count; } taker.short = false; - try s.land(&batch, &taker); + try s.land(&batch, &taker, remote); if (taker.err) |err| return err; for (batch.items[0..batch.len]) |item| if (item.failed and item.off == taker.end and !taker.short) return remote.set(item.said.buf[0..item.said.len]); @@ -2603,17 +2582,12 @@ pub const Client = struct { }; return false; } - - /// Closes what is kept for `dial` (an Unmount). - fn forget(dial: []const u8) void { - while (take(dial)) |s| endSession(s, false); - } }; - /// Lets go of a connection kept for `dial`: its mount is gone. + /// Lets go of a connection kept for `dial` (an Unmount): its mount is gone. pub fn forget(dial: []const u8) void { if (comptime !supported) return; - kept.forget(dial); + while (kept.take(dial)) |s| endSession(s, false); } /// Writes `request`, then `more`, to `path` and reads the answer on the @@ -2629,7 +2603,7 @@ pub const Client = struct { errdefer said = remote; const s = try startSession(dial, path); defer endSession(s, false); - const fid = (try walkTo(s, names[0..n], &remote)).fid; + const fid = try walkTo(s, names[0..n], &remote); _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); var written: usize = 0; while (written < request.len + more.len) { @@ -2671,7 +2645,7 @@ pub const Client = struct { _ = gpa; const s = try startSession(dial, path); defer endSession(s, false); - const fid = (try walkTo(s, names[0..n], &remote)).fid; + const fid = try walkTo(s, names[0..n], &remote); _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = first } }, &remote); if (ready(ctx)) return; @@ -2691,15 +2665,9 @@ pub const Client = struct { return transport.connectFd(address, deadline) catch return Error.Dial; } - const nowMs = transport.nowMs; - const poll_in: i16 = @intCast(libc.POLL.IN); const poll_out: i16 = @intCast(libc.POLL.OUT); - fn nap(ms: c_int) void { - _ = libc.poll(&[0]libc.pollfd{}, 0, ms); - } - test "a path becomes walk elements, normalised the way a shell would" { var out: [max_depth][]const u8 = undefined; try testing.expectEqual(@as(usize, 3), try elements("/pane/1/body", &out)); -- cgit v1.3