diff options
| -rw-r--r-- | core/Kind.zig | 5 | ||||
| -rw-r--r-- | core/replica.zig | 19 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 330 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 268 | ||||
| -rw-r--r-- | runtime/main.zig | 35 | ||||
| -rw-r--r-- | runtime/root.zig | 2 | ||||
| -rw-r--r-- | runtime/session.zig | 155 | ||||
| -rw-r--r-- | test/replicas.zig | 1458 |
8 files changed, 1359 insertions, 913 deletions
diff --git a/core/Kind.zig b/core/Kind.zig index 500319a5..13ef8edd 100644 --- a/core/Kind.zig +++ b/core/Kind.zig @@ -1253,9 +1253,12 @@ var ready: std.ArrayListUnmanaged(*host_io.KindJob) = .empty; /// A draw done on a worker, back on the loop: kept for its pane's next /// paint, a frame owed. One of another core's (a client joined again -/// since) is dropped: the new core's pane asked its own. +/// since), or of a pane closed since, is dropped: the new core's pane asked +/// its own. pub fn landDraw(p: *Pardes, j: *host_io.KindJob) void { if (j.draw != p) return j.drop(); + // Its pane closed meanwhile: no paint of it would ever take it. + if (if (p.panes[j.pane]) |pane| pane.serial != j.serial else true) return j.drop(); ready.append(heap, j) catch return j.drop(); p.needs_frame = true; } diff --git a/core/replica.zig b/core/replica.zig index ae2616b7..fb3a81c4 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1900,7 +1900,7 @@ pub const Peer = struct { } } - fn take(peer: *Peer, tag: u8, payload: []const u8) bool { + pub fn take(peer: *Peer, tag: u8, payload: []const u8) bool { const t = std.enums.fromInt(wire.ClientTag, tag) orelse return false; switch (t) { .hello => return false, @@ -2047,6 +2047,14 @@ pub const Peers = struct { /// it records: what each was sent. screens: Screens = undefined, msgs: std.ArrayListUnmanaged([]u8) = .empty, + /// False: its clients' links are in this process's memory, a thread + /// for none of them (the soak's, test/replicas.zig): what a client's + /// writer would write (its join, then `out`) and its reader read + /// (`Peer.take`, then `.gone` posted) are its driver's to do. + threads: bool = true, + /// After each flush of a client's terminals, told: the soak's record + /// of each terminal as each version left it (test/replicas.zig). + flushed: ?struct { ctx: *anyopaque, f: *const fn (*anyopaque, *Pardes, *Screens) void } = null, pub const Note = union(enum) { join: Joining, input: Msg, screen: Msg, gone: *Peer, check: *Peer, joined: *Peer }; /// A connection to join, and the view it joins again for, if it does. @@ -2059,7 +2067,7 @@ pub const Peers = struct { return n; } - fn post(ps: *Peers, note: Note) void { + pub fn post(ps: *Peers, note: Note) void { ps.lock.lockUncancelable(ps.io); ps.inbox.append(ps.gpa, note) catch { ps.lock.unlock(ps.io); @@ -2186,6 +2194,7 @@ pub const Peers = struct { .flush => ps.screens.flush(core, peer.sid, peer.view, &ps.msgs), .fill => ps.screens.fill(core, peer.sid, &ps.msgs), }) catch return; + if (what == .flush) if (ps.flushed) |h| h.f(h.ctx, core, &ps.screens); for (ps.msgs.items) |m| { const head = wire.header(@backingInt(wire.ServerTag.screen), m.len); peer.send(&.{ &head, m }); @@ -2270,9 +2279,9 @@ pub const Peers = struct { // The session's digest as dumped, for the joiner to check its load by. const digest = tape.digestOf(core); peer.welcome_len = (wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = k, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; - peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null; - peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null; - if (peer.writer == null or peer.reader == null) { + if (ps.threads) peer.writer = std.Thread.spawn(.{}, Peer.writeLoop, .{peer}) catch null; + if (ps.threads) peer.reader = std.Thread.spawn(.{}, Peer.readLoop, .{peer}) catch null; + if (ps.threads and (peer.writer == null or peer.reader == null)) { ps.letGo(peer); core.undrawn &= ~(@as(u8, 1) << @intCast(k)); core.closeView(k); diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 237b7b85..798368e3 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -31,6 +31,7 @@ const ninep_io = @import("runtime").ninep_io; const daemon = @import("runtime").daemon; const client_loop = @import("runtime").client; +const session_loop = @import("runtime").session; const upgrade = @import("runtime").upgrade; const replica = @import("core").replica; const tracy = @import("core").tracy; @@ -984,7 +985,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, detached: bool, di if (!test_mode and !c.SDL_SetWindowHitTest(window, hitTest, &g)) log.warn("SDL_SetWindowHitTest: {s}", .{c.SDL_GetError()}); if (dial) |to| return clientSession(init, &g, opts_in, test_mode, to); - try localSession(init, &g, opts_in, test_mode, detached); + var own: Own = .{ .g = &g, .test_mode = test_mode, .detached = detached }; + try session_loop.Loop(Own).run(init, opts_in, &own); } /// Detach: the window closed (and with it its swapchain or renderer); the @@ -1019,195 +1021,173 @@ fn reopenWindow(g: *Gui) bool { return true; } -fn localSession( - init: std.process.Init, +/// The session's own window (`runNative`): the frontend of the session loop +/// (runtime/session.zig), its devices the `Shell`'s, which draws it. +const Own = struct { g: *Gui, - opts_in: pardes.Options, test_mode: bool, detached: bool, -) !void { - const io = init.io; - const gpa = init.gpa; - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - host_io.startWorkers(allocs); - defer host_io.stopWorkers(); - var opts = opts_in; - opts.addons = pardes.Addon.scan(); - // Its frame timings, the window's to write as it draws (Pardes.frames). - var frames: pardes.FrameStats = .{}; - opts.frames = &frames; - opts.image_allocator = allocs.image; - opts.tree_sitter_allocator = allocs.tree_sitter; - opts.frame_allocator = allocs.frame; - var pw: c_int = 0; - var ph: c_int = 0; - if (opts.load_path != null) { - _ = c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph); - opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), g.cell_w))); - opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), g.cell_h))); + ptys: [pardes.MAX_PANES]?Pty = @splat(null), + gens: [pardes.MAX_PANES]u32 = @splat(0), + queue: Queue = undefined, + pipe_tasks: PipeTasks = .{}, + inotify_fd: c_int = -1, + watch_reader: ?std.Thread = null, + watch_stop: [2]c_int = .{ -1, -1 }, + watches: file_watch.Table = @splat(null), + shell: Shell = undefined, + + const Session = session_loop.Loop(Own); + + /// A dump's layout is laid out at the window's size. + pub fn options(o: *Own, opts: *pardes.Options) void { + if (opts.load_path == null) return; + var pw: c_int = 0; + var ph: c_int = 0; + _ = c.SDL_GetWindowSizeInPixels(o.g.window, &pw, &ph); + opts.cols = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(pw, 1))), o.g.cell_w))); + opts.rows = @intCast(@max(1, @divTrunc(@as(u32, @intCast(@max(ph, 1))), o.g.cell_h))); } - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, opts, rec) - else if (opts.load_path) |lp| blk: { - const bytes = try @import("core").filesystem.readFile(&pardes.tape.none, gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); - } else try pardes.Pardes.init(allocs.pardes, opts); - defer core.deinit(); - g.hit_core = core; - defer g.hit_core = null; - core.view().frontend.windowed = true; - core.view().frontend.native_images = true; - core.view().frontend.native_image_patches = true; - observeGuiFont(g, core); - syncTaglineFont(g, core); - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); + pub fn open(o: *Own, l: *Session) !pardes.Host { + const g = o.g; + const core = l.core; + g.hit_core = core; + core.view().frontend.windowed = true; + core.view().frontend.native_images = true; + core.view().frontend.native_image_patches = true; + observeGuiFont(g, core); + syncTaglineFont(g, core); + o.queue = .{ + .io = l.io, + .gpa = l.gpa, + .lsp_allocator = l.allocs.lsp, + .wake_fn = sdlWake, + }; + o.inotify_fd = file_watch.init(true); + o.shell = .{ + .core = core, + .gui = g, + .io = l.io, + .gpa = l.gpa, + .lsp_allocator = l.allocs.lsp, + .prompt_rcs = &l.prompt_rcs, + .ptys = &o.ptys, + .gens = &o.gens, + .queue = &o.queue, + .pipe_tasks = &o.pipe_tasks, + .inotify_fd = o.inotify_fd, + .watches = &o.watches, + .fs = l.fs, + .test_mode = o.test_mode, + .test_clock = if (o.test_mode) host_io.testClock() else null, + .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, + .peers = &l.peers, + }; + // A virtual clock never blinks: goldens and feel series hold still. + g.no_blink = o.shell.test_clock != null; + frame_probe = &l.frames; + frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; + const host = o.shell.host(); + core.host = host; + pardes.Kind.drawer = .{ .ctx = &o.shell, .go = kindDraw }; + l.peers.wake = sdlWake; + l.peers.detached = o.detached; + return host; + } - var ptys: [pardes.MAX_PANES]?Pty = @splat(null); - var gens: [pardes.MAX_PANES]u32 = @splat(0); - var queue: Queue = .{ - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .wake_fn = sdlWake, - }; - defer { - if (queue.lsp_task) |*task| task.future.cancel(io); + pub fn close(o: *Own, l: *Session) void { + const io = l.io; + o.shell.fs = null; + host_io.setExitWake(null, null); + pardes.lsp.setStatusSink(null, null); + pardes.Kind.drawer = null; + o.shell.shutdownPtys(); + o.shell.job_tasks.cancelAll(io); + if (o.inotify_fd >= 0) { + if (o.watch_reader) |thread| { + _ = host_io.writeFd(o.watch_stop[1], "x"); + thread.join(); + } + for (o.watch_stop) |fd| if (fd >= 0) { + _ = libc.close(fd); + }; + file_watch.stop(o.inotify_fd); + _ = libc.close(o.inotify_fd); + o.inotify_fd = -1; + } + o.pipe_tasks.cancelAll(io); + if (o.queue.lsp_task) |*task| task.future.cancel(io); // Its worker may be waiting on the queue for room. - core.stream.cancelTask(); - queue.deinit(); + l.core.stream.cancelTask(); + o.queue.deinit(); + o.g.hit_core = null; } - var pipe_tasks: PipeTasks = .{}; - defer pipe_tasks.cancelAll(io); - var inotify_fd: c_int = file_watch.init(true); - var watch_reader: ?std.Thread = null; - var watch_stop: [2]c_int = .{ -1, -1 }; - defer if (inotify_fd >= 0) { - if (watch_reader) |thread| { - _ = host_io.writeFd(watch_stop[1], "x"); - thread.join(); - } - for (watch_stop) |fd| if (fd >= 0) { - _ = libc.close(fd); + + pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void { + o.shell.resumePtys(rec); + } + + pub fn start(o: *Own, l: *Session) !void { + for (&o.ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = try o.queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), o.gens[id]); }; - file_watch.stop(inotify_fd); - _ = libc.close(inotify_fd); - inotify_fd = -1; - }; - var watches: file_watch.Table = @splat(null); - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); + if (o.inotify_fd >= 0) { + o.watch_stop = try stopPipe(); + o.watch_reader = try std.Thread.spawn(.{}, watchThread, .{ o.inotify_fd, o.watch_stop[0], &o.queue }); + } + if (l.fs) |f| try f.watch(&o.queue, wakeFs); - var shell: Shell = .{ - .core = core, - .gui = g, - .io = io, - .gpa = gpa, - .lsp_allocator = allocs.lsp, - .prompt_rcs = &prompt_rcs, - .ptys = &ptys, - .gens = &gens, - .queue = &queue, - .pipe_tasks = &pipe_tasks, - .inotify_fd = inotify_fd, - .watches = &watches, - .fs = fs, - .test_mode = test_mode, - .test_clock = if (test_mode) host_io.testClock() else null, - .test_hz = if (std.c.getenv("PARDES_TEST_HZ")) |hz| @max(1, std.fmt.parseInt(u64, std.mem.span(hz), 10) catch 60) else 60, - }; - defer shell.job_tasks.cancelAll(io); - defer shell.shutdownPtys(); - // A virtual clock never blinks: goldens and feel series hold still. - g.no_blink = shell.test_clock != null; - frame_probe = &frames; - frame_capture_dir = if (std.c.getenv("PARDES_FRAMES_CAPTURE")) |dir| std.mem.span(dir) else null; - const host = shell.host(); - core.host = host; - pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; - defer pardes.Kind.drawer = null; - shell.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake = sdlWake, .detached = detached }; - defer shell.peers.deinit(); - // Before the core goes: each client sees its link end. - defer shell.peers.dropAll(shell.core); + _ = c.SDL_StartTextInput(o.g.window); + // An upgraded session's window, its view's again. + if (upgrade.resumed) |*rec| if (!rec.fresh and !o.detached) o.shell.resumeWindow(); - while (core.nextEffect()) |e| core.perform(e); - // An upgraded session's shells, once a fresh session's own has a - // directory to adopt them in. - if (upgrade.resumed) |*rec| { - shell.resumePtys(rec); - while (core.nextEffect()) |e| core.perform(e); + if (o.test_mode) setStdinRaw() catch {}; + o.shell.threads_ok = true; + pardes.lsp.setStatusSink(&o.queue, Queue.lspStatus); + host_io.setExitWake(&o.queue, Queue.wakeForExit); + if (o.detached) { + o.shell.closeTheWindow(); + // Nothing else may wake the first wait. + l.watch(); + } } - for (&ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try queue.startReader(.{ .handle = pt.fd, .flags = .{ .nonblocking = false } }, @intCast(id), gens[id]); - }; - if (inotify_fd >= 0) { - watch_stop = try stopPipe(); - watch_reader = try std.Thread.spawn(.{}, watchThread, .{ inotify_fd, watch_stop[0], &queue }); + + pub fn sent(_: *Own) void {} + + pub fn upgradeAsked(o: *Own) void { + if (o.shell.upgrade_asked) |pane| o.shell.upgradeNow(pane); } - if (fs) |f| try f.watch(&queue, wakeFs); - _ = c.SDL_StartTextInput(g.window); - // An upgraded session's window, its view's again. - if (upgrade.resumed) |*rec| if (!rec.fresh and !detached) shell.resumeWindow(); + pub fn note(o: *Own, n: daemon.Note) void { + deliverNote(&o.shell, n); + } - if (test_mode) setStdinRaw() catch {}; - shell.threads_ok = true; - pardes.lsp.setStatusSink(&queue, Queue.lspStatus); - defer pardes.lsp.setStatusSink(null, null); - host_io.setExitWake(&queue, Queue.wakeForExit); - defer host_io.setExitWake(null, null); - if (detached) { - shell.closeTheWindow(); - // Nothing else may wake the first wait. - daemon.watch(&shell, deliverNote); + pub fn watched(o: *Own) session_loop.Watched { + return .{ .fd = o.inotify_fd, .table = &o.watches }; } - while (!core.quit) { - pardes.turn.bump(&pardes.turn.restores); - try core.pump(host); - // Its unit to each replica client, and theirs taken in. - shell.peers.boundary(core); - upgrade.locate(); - // Asked in the step (the word), done between steps: the session whole. - if (shell.upgrade_asked) |pane| shell.upgradeNow(pane); - // A window asked for again, or an adopted shell, from the daemon's - // thread through the queue; started after the first frame. - daemon.watch(&shell, deliverNote); - if (core.quit) break; // a session that ended does not restore into one - if (core.takeRestore()) |rp| blk: { - const nc = host_io.restoreCore(gpa, core, rp, &shell.peers, inotify_fd, &watches) orelse break :blk; - pipe_tasks.cancelAll(io); - queue.discardCompletions(); - // One view, the window's (host_io.restoreCore). - shell.gview = 0; - shell.stopPtys(); - g.cells.clearImages(); - g.prepared_images.clearRetainingCapacity(); - nc.view().frontend.native_images = true; - nc.view().frontend.native_image_patches = true; - nc.host = host; - if (fs) |f| f.reset(nc); - nc.view().frontend.windowed = true; - core.deinit(); - core = nc; - g.hit_core = nc; - shell.core = nc; - shell.surface = null; - observeGuiFont(g, core); - syncTaglineFont(g, core); - } + pub fn restoring(o: *Own, nc: *pardes.Pardes) void { + o.pipe_tasks.cancelAll(o.shell.io); + o.queue.discardCompletions(); + // One view, the window's (host_io.restoreCore). + o.shell.gview = 0; + o.shell.stopPtys(); + o.g.cells.clearImages(); + o.g.prepared_images.clearRetainingCapacity(); + nc.view().frontend.native_images = true; + nc.view().frontend.native_image_patches = true; + nc.view().frontend.windowed = true; } - if (fs) |f| { - f.deinit(gpa); - fs = null; - shell.fs = null; + pub fn restored(o: *Own, l: *Session) void { + o.g.hit_core = l.core; + o.shell.core = l.core; + o.shell.surface = null; + observeGuiFont(o.g, l.core); + syncTaglineFont(o.g, l.core); } -} +}; /// A window's loop as a client of a session elsewhere (runtime/client.zig), /// over the window (`Client`). @@ -1525,6 +1505,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ var pipe_tasks: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); const prompt_rcs: host_io.Shell.PromptFiles = .{}; + var no_peers: replica.Peers = .{}; var shell: Shell = .{ .core = start.r.core(), .gui = g, @@ -1540,6 +1521,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .watches = &watches, .test_mode = test_mode, .client = &window, + .peers = &no_peers, }; window.shell = &shell; pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; @@ -2490,8 +2472,9 @@ const Shell = struct { /// This window a replica client of a session elsewhere (`runClient`). client: ?*Client = null, /// The session's replica clients (core/replica.zig), on sockets: views - /// of their own with no window here. - peers: replica.Peers = .{}, + /// of their own with no window here; the session loop's + /// (runtime/session.zig), a client's none. + peers: *replica.Peers, /// This wait took only a replica's post (its input, its join): the pump /// after it reads no new time, so it moves nothing the replicas' /// speculations stand on (tui.zig's `mail_only`). @@ -8173,7 +8156,8 @@ test "a detached GUI authority follows terminal directory changes with no window const rcs: host_io.Shell.PromptFiles = .{}; var pipes: PipeTasks = .{}; var watches: file_watch.Table = @splat(null); - var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches }; + var no_peers: replica.Peers = .{}; + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .prompt_rcs = &rcs, .ptys = &ptys, .gens = &gens, .queue = &queue, .pipe_tasks = &pipes, .inotify_fd = -1, .watches = &watches, .peers = &no_peers }; defer shell.shutdownPtys(); const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); ptys[0] = .{ .fd = child.file.handle, .pid = child.pid, .serial = core.panes[0].?.serial }; diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 5a42ae5e..70ea3295 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -17,6 +17,7 @@ const selection_pipe = @import("core").selection_pipe; const ninep_io = @import("runtime").ninep_io; const daemon = @import("runtime").daemon; const client_loop = @import("runtime").client; +const session_loop = @import("runtime").session; const host_io = @import("../host_io.zig"); const upgrade = @import("runtime").upgrade; const replica = @import("core").replica; @@ -617,7 +618,8 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { defer paste_buf.deinit(); var loop: Loop = .init(io, &screen.tty, &screen.vx); - try localSession(init, opts, &screen, &loop, &paste_buf); + var own: Own = .{ .screen = &screen, .loop = &loop, .paste_buf = &paste_buf }; + try session_loop.Loop(Own).run(init, opts, &own); } /// A replica client's terminal (`runClient`): the frontend of the client @@ -774,6 +776,8 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, var tty: Tty = undefined; var c = try Client.init(&tty, &start); defer c.link.deinit(gpa); + // A client has no clients of its own. + var no_peers: replica.Peers = .{}; var sh: Shell = .{ .io = io, .gpa = gpa, @@ -788,6 +792,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, .own = start.joined.view, .screen = &screen, .client = &c, + .peers = &no_peers, }; tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start }; @@ -935,72 +940,61 @@ const Killed = struct { } }; -fn localSession( - init: std.process.Init, - opts: pardes.Options, +/// The session's own terminal (`run`): the frontend of the session loop +/// (runtime/session.zig), its devices the `Shell`'s, which draws it. +const Own = struct { screen: *Screen, loop: *Loop, paste_buf: *std.Io.Writer.Allocating, -) !void { - const io = init.io; - const gpa = init.gpa; - - const allocs = pardes.memory.init(gpa); - defer pardes.memory.deinit(); - var options = opts; - options.image_allocator = allocs.image; - options.tree_sitter_allocator = allocs.tree_sitter; - options.frame_allocator = allocs.frame; - // Its frame timings, the terminal's to write as it draws (Pardes.frames). - var frames: pardes.FrameStats = .{}; - options.frames = &frames; - - host_io.startWorkers(allocs); - defer host_io.stopWorkers(); - options.addons = pardes.Addon.scan(); - - var core = if (upgrade.resumed) |*rec| - try upgrade.load(gpa, allocs.pardes, options, rec) - else if (options.load_path) |lp| blk: { - const bytes = try filesystem.readFile(&pardes.tape.none, gpa, lp); - defer gpa.free(bytes); - break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); - } else try pardes.Pardes.init(allocs.pardes, options); - defer core.deinit(); + frame_arena: std.heap.ArenaAllocator = undefined, + sh: Shell = undefined, - var prompt_rcs = host_io.Shell.prepare(); - defer prompt_rcs.deinit(); + const Session = session_loop.Loop(Own); - var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); - defer frame_arena.deinit(); + pub fn options(_: *Own, _: *pardes.Options) void {} - var fs = ninep_io.start(io, gpa, core); - defer if (fs) |f| f.deinit(gpa); + pub fn open(o: *Own, l: *Session) !pardes.Host { + o.frame_arena = .init(l.allocs.frame); + o.sh = .{ + .io = l.io, + .gpa = l.gpa, + .lsp_gpa = l.allocs.lsp, + .core = l.core, + .frames = &l.frames, + .prompt_rcs = &l.prompt_rcs, + .loop = o.loop, + .frame = &o.frame_arena, + .paste_buf = o.paste_buf, + .inotify_fd = file_watch.init(false), + .fs = l.fs, + .test_clock = host_io.testClock(), + .peers = &l.peers, + }; + const sh = &o.sh; + sh.screen = o.screen; + l.peers.wake_ctx = o.loop; + l.peers.wake = wakeForReplica; + pardes.lsp.setStatusSink(sh, lspStatusSink); + host_io.setExitWake(o.loop, wakeForExit); + const host = sh.host(); + l.core.host = host; + pardes.Kind.drawer = .{ .ctx = sh, .go = Shell.draw }; + // An upgraded session's terminals, its own again. + if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec); + // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). + sh.setAttended(!sh.detached()); + return host; + } - var sh: Shell = .{ - .io = io, - .gpa = gpa, - .lsp_gpa = allocs.lsp, - .core = core, - .frames = &frames, - .prompt_rcs = &prompt_rcs, - .loop = loop, - .frame = &frame_arena, - .paste_buf = paste_buf, - .inotify_fd = file_watch.init(false), - .fs = fs, - .test_clock = host_io.testClock(), - }; - sh.screen = screen; - sh.peers = .{ .gpa = gpa, .io = io, .name = daemon.name(), .wake_ctx = loop, .wake = wakeForReplica }; - defer sh.peers.deinit(); - // Before the core goes: each client sees its link end. - defer sh.peers.dropAll(sh.core); - pardes.lsp.setStatusSink(&sh, lspStatusSink); - host_io.setExitWake(loop, wakeForExit); - defer screen.glide.deinit(gpa); - defer screen.art.deinit(gpa); - defer { + pub fn close(o: *Own, l: *Session) void { + const io = l.io; + const gpa = l.gpa; + const sh = &o.sh; + const loop = o.loop; + sh.fs = null; + unlinkKittyShm(); + stopInput(io, &o.screen.thread); + pardes.Kind.drawer = null; host_io.setExitWake(null, null); pardes.lsp.setStatusSink(null, null); for (&sh.ptys) |*slot| if (slot.*) |*pt| { @@ -1016,7 +1010,7 @@ fn localSession( sh.pipe_tasks.cancelAll(io); sh.job_tasks.cancelAll(io); // Its worker may be waiting on the loop's queue for room. - core.stream.cancelTask(); + sh.core.stream.cancelTask(); file_watch.stop(sh.inotify_fd); if (sh.watch_task) |*t| { t.cancel(io); @@ -1032,8 +1026,8 @@ fn localSession( gpa.free(pr.bytes); }, .paste => |b| gpa.free(@constCast(b)), - .lsp_done => |d| if (d.rows) |rows| allocs.lsp.free(rows), - .lsp_status => |text| allocs.lsp.free(text), + .lsp_done => |d| if (d.rows) |rows| sh.lsp_gpa.free(rows), + .lsp_status => |text| sh.lsp_gpa.free(text), .pipe_done => |response_value| { var response = response_value; response.deinit(gpa); @@ -1047,87 +1041,82 @@ fn localSession( .adopted => |a| _ = libc.close(a.fd), else => {}, }; + o.screen.art.deinit(gpa); + o.screen.glide.deinit(gpa); + o.frame_arena.deinit(); } - const host = sh.host(); - core.host = host; - pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; - defer pardes.Kind.drawer = null; - // An upgraded session's terminals, its own again. - if (comptime !builtin.is_test) if (upgrade.resumed) |*rec| sh.resumeTerminals(rec); - // Nobody to see it, and nobody to size it: `size` sets it (ctl.zig). - sh.setAttended(!sh.detached()); - while (core.nextEffect()) |effect| core.perform(effect); - // ...and its shells, once a fresh session's own has a directory to - // adopt them in. - if (upgrade.resumed) |*rec| { - sh.resumePtys(rec); - while (core.nextEffect()) |effect| core.perform(effect); + pub fn resumePtys(o: *Own, rec: *const upgrade.Record) void { + o.sh.resumePtys(rec); } - if (screen.on) try startInput(loop, screen); - defer stopInput(io, &screen.thread); - (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); - (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); - if (fs) |f| try f.watch(loop, wakeFs); - if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); - // Detached from the start, nothing else may wake the first wait. - if (!screen.on) daemon.watch(loop, deliverNote); + pub fn start(o: *Own, l: *Session) !void { + const io = l.io; + const sh = &o.sh; + const screen = o.screen; + const loop = o.loop; + if (screen.on) try startInput(loop, screen); + (try std.Thread.spawn(.{}, winchWatch, .{loop})).detach(); + (try std.Thread.spawn(.{}, wakeWatch, .{ io, loop })).detach(); + if (l.fs) |f| try f.watch(loop, wakeFs); + if (screen.on) try screen.vx.queryTerminalSend(screen.tty.writer()); + // Detached from the start, nothing else may wake the first wait. + if (!screen.on) l.watch(); - sh.threads_ok = true; - for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { - pt.reader = try io.concurrent(readPty, .{ io, gpa, pt.file, id, sh.gens[id], loop }); - }; - if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; + sh.threads_ok = true; + for (&sh.ptys, 0..) |*slot, id| if (slot.*) |*pt| { + pt.reader = try io.concurrent(readPty, .{ io, l.gpa, pt.file, id, sh.gens[id], loop }); + }; + if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; + } - defer unlinkKittyShm(); - while (!core.quit) { - pardes.turn.bump(&pardes.turn.restores); - try core.pump(host); - // Its unit to each replica client, and theirs taken in. - sh.peers.boundary(core); - // Detached, the unit is its clients' frame: its output is paced to - // it as a terminal's frame paces it (waitInput), a unit a frame, not - // a unit and a delta for every read of a flood. - if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(io).nanoseconds); - upgrade.locate(); - // Asked in the step (the word), done between steps: the session whole. - if (sh.upgrade_asked) |pane| sh.upgradeNow(pane); - // A terminal (`pardes --attach`) or an adopted shell, handed on by - // the daemon's thread to this loop; started after the first frame, - // off a startup's way. - daemon.watch(loop, deliverNote); - if (core.takeRestore()) |rp| blk: { - const nc = host_io.restoreCore(gpa, core, rp, &sh.peers, sh.inotify_fd, &sh.watches) orelse break :blk; - if (sh.lsp_task) |*task| { - task.future.cancel(io); - sh.lsp_task = null; - } - sh.pipe_tasks.cancelAll(io); - for (&sh.gens) |*generation| generation.* +%= 1; - for (0..pardes.MAX_PANES) |pane| Shell.closePty(&sh, @intCast(pane)); - // One view, the terminal's (host_io.restoreCore). - const live = screen; - stopInput(io, &live.thread); - sh.own = 0; - if (live.on) startInput(loop, live) catch {}; - if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); - nc.view().frontend.native_images = live.on and live.vx.caps.kitty_graphics; - nc.unattended = !live.on; - sh.peers.detached = !live.on; - if (fs) |f| f.reset(nc); - core.deinit(); - core = nc; - sh.core = nc; - if (live.on) core.update(.{ .resize = terminalSize(live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix) }); + /// Detached, the unit is its clients' frame: its output is paced to it + /// as a terminal's frame paces it (waitInput), a unit a frame, not a + /// unit and a delta for every read of a flood. + pub fn sent(o: *Own) void { + const sh = &o.sh; + if (sh.peers.recording and sh.detached()) sh.drawn_ns = @intCast(std.Io.Clock.awake.now(sh.io).nanoseconds); + } + + pub fn upgradeAsked(o: *Own) void { + if (o.sh.upgrade_asked) |pane| o.sh.upgradeNow(pane); + } + + pub fn note(o: *Own, n: daemon.Note) void { + deliverNote(o.loop, n); + } + + pub fn watched(o: *Own) session_loop.Watched { + return .{ .fd = o.sh.inotify_fd, .table = &o.sh.watches }; + } + + pub fn restoring(o: *Own, nc: *pardes.Pardes) void { + const sh = &o.sh; + const io = sh.io; + if (sh.lsp_task) |*task| { + task.future.cancel(io); + sh.lsp_task = null; } + sh.pipe_tasks.cancelAll(io); + for (&sh.gens) |*generation| generation.* +%= 1; + for (0..pardes.MAX_PANES) |pane| Shell.closePty(sh, @intCast(pane)); + // One view, the terminal's (host_io.restoreCore). + const live = o.screen; + stopInput(io, &live.thread); + sh.own = 0; + if (live.on) startInput(o.loop, live) catch {}; + if (live.on) clearNativeImages(&live.kitty, &live.vx, &live.tty); + nc.view().frontend.native_images = live.on and live.vx.caps.kitty_graphics; + nc.unattended = !live.on; + sh.peers.detached = !live.on; } - if (fs) |f| { - f.deinit(gpa); - fs = null; - sh.fs = null; + + pub fn restored(o: *Own, l: *Session) void { + o.sh.core = l.core; + const live = o.screen; + if (live.on) l.core.update(.{ .resize = terminalSize(live.vx.screen.width, live.vx.screen.height, live.vx.screen.width_pix, live.vx.screen.height_pix) }); } -} +}; fn clearNativeImages( kitty_handles: *std.AutoHashMap(u64, vaxis.Image), @@ -1220,8 +1209,9 @@ const Shell = struct { upgrade_asked: ?u8 = null, /// Its pty readers stopped for it: their end of file is not a shell's. upgrading: bool = false, - /// The session's replica clients (core/replica.zig), on sockets. - peers: replica.Peers = .{}, + /// The session's replica clients (core/replica.zig), on sockets: the + /// session loop's (runtime/session.zig); a client's, none. + peers: *replica.Peers, /// This wait took only a replica's post (its input, its join): the /// pump after it reads no new time, so it moves nothing the replicas' /// speculations stand on (a replica takes such a unit as is). @@ -2999,6 +2989,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer core.deinit(); + var no_peers: replica.Peers = .{}; var shell: Shell = .{ .io = std.testing.io, .gpa = gpa, @@ -3010,6 +3001,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { .frame = undefined, .paste_buf = undefined, .inotify_fd = -1, + .peers = &no_peers, }; shell.gens[0] = 2; _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); @@ -3045,6 +3037,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), }); + var no_peers: replica.Peers = .{}; var shell: Shell = .{ .io = failing_io, .gpa = failing.allocator(), @@ -3057,6 +3050,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { .paste_buf = undefined, .inotify_fd = -1, .threads_ok = true, + .peers = &no_peers, }; core.lspRequest(core.view().active, .status, ""); const req: host_io.Lsp.Request = .{ diff --git a/runtime/main.zig b/runtime/main.zig index 92821c8a..2b600d63 100644 --- a/runtime/main.zig +++ b/runtime/main.zig @@ -595,6 +595,9 @@ const Here = struct { core: *pardes.Pardes, engine: Engine, fd: c_int, + /// Its serve thread, which reads the core until the other end hangs up + /// (`Tree.close` joins it). + thread: std.Thread, in: [@import("runtime").ninep.msize]u8, out: [2 * @import("runtime").ninep.msize]u8, buf: [@import("runtime").ninep.msize]u8, @@ -649,12 +652,23 @@ const Tree = struct { var fds: [2]std.c.fd_t = undefined; if (socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocketPair; h.fd = fds[1]; - (try std.Thread.spawn(.{}, Here.serve, .{h})).detach(); + h.thread = try std.Thread.spawn(.{}, Here.serve, .{h}); t.here = h; try t.f.init(io, .{ .socket = .{ .handle = fds[0], .address = undefined } }, "pardes"); return t; } + /// Let go (a test's; a command's process just ends). A core made here + /// is served to the end of what was sent it (a clunk, which the client + /// never waits for: Fsys.clunk) before its memory may go: its thread + /// sees the hangup and is joined. + fn close(t: *Tree) void { + t.f.close(); + const h = t.here orelse return; + h.thread.join(); + _ = std.c.close(h.fd); + } + /// The whole file at `path`. fn read(t: *Tree, gpa: std.mem.Allocator, path: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); @@ -1861,7 +1875,7 @@ test "cli: docs/typ/command-line.txt is what pardes help --all prints" { defer arena.deinit(); const a = arena.allocator(); const t = try Tree.open(std.testing.io, a, null); - defer t.f.close(); + defer t.close(); var out: std.Io.Writer.Allocating = .init(a); try writeHelpAll(&out.writer, t); var dir = try std.Io.Dir.cwd().openDir(std.testing.io, @import("doc_typ").dir, .{}); @@ -1873,6 +1887,23 @@ test "cli: docs/typ/command-line.txt is what pardes help --all prints" { } } +test "cli: a core made here is let go only once its serve thread has ended: read, closed and freed at once, again and again" { + if (comptime !ninep_io.supported) return error.SkipZigTest; + // Each read ends with a clunk the client never waits for (Fsys.clunk): + // the serve thread is still answering it as the tree is closed and the + // core's memory let go (the page allocator's: unmapped, so a read of + // it after is a fault, not a stale value). + for (0..300) |_| { + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const t = try Tree.open(std.testing.io, arena.allocator(), null); + defer t.close(); + var out: std.Io.Writer.Allocating = .init(arena.allocator()); + try t.f.readFile("README", &out.writer); + try std.testing.expect(out.written().len > 0); + } +} + test "cli: the first screen names every command, and every flag has its help" { var buf: [8192]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); diff --git a/runtime/root.zig b/runtime/root.zig index 61db8cbe..ec89e734 100644 --- a/runtime/root.zig +++ b/runtime/root.zig @@ -5,6 +5,7 @@ //! and `core`. pub const daemon = @import("daemon.zig"); pub const client = @import("client.zig"); +pub const session = @import("session.zig"); pub const upgrade = @import("upgrade.zig"); pub const crash = @import("crash.zig"); pub const addon_test = @import("addon_test.zig"); @@ -14,6 +15,7 @@ pub const ninep = @import("9p.zig"); test { _ = daemon; _ = client; + _ = session; _ = upgrade; _ = ninep_io; _ = ninep_io.Client; diff --git a/runtime/session.zig b/runtime/session.zig new file mode 100644 index 00000000..f401c85a --- /dev/null +++ b/runtime/session.zig @@ -0,0 +1,155 @@ +//! A session's loop: the terminal's (dev/tui `run`) and the window's +//! (dev/gui `runNative`) alike, each with a frontend of its own. It holds +//! the session's allocators and workers, its core (an upgrade's, a dump's +//! or a new one), the prompt files its shells start with, its 9P listener +//! and its replica clients (`Peers`): a step, its unit to the clients and +//! theirs taken in, an Upgrade or a Restore between steps; and the order +//! its parts end in. Its devices (the ptys and their readers, the files +//! watched, the LSP's and the pipes' and addons' jobs, the queue they post +//! to, the session's own input) are still its frontend's (each `Shell`, +//! the services step's to make one). What a frontend does is: +//! +//! - `options(o)`: before the core: what it gives the core it starts (a +//! window's size, for a dump's layout). +//! - `open(l) Host`: its devices made over the session's core and parts, +//! the host the core steps with (the core's, set there); what it does +//! before the core's first effects (an upgraded terminal's panes its +//! own again, whether anyone looks). +//! - `close(l)`: its devices stopped, after the clients are let go and +//! before the core goes. +//! - `resumePtys(rec)`: an upgraded session's shells, its own again. +//! - `start(l)`: after the first effects: its input, its readers, the +//! listener's wake, a detached session's first wait (`l.watch`). +//! - `sent()`: after each step's unit went to the clients. +//! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs). +//! - `note(n)`: what the daemon says (a terminal, an adopted shell, a +//! client's connection), onto its queue. +//! - `watched()`: the files it watches (a Restore stops watching them). +//! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it +//! replaces the old one (its devices let go, what it is told of the +//! frontend) and after (its own view of it again). +const std = @import("std"); +const pardes = @import("core"); +const replica = pardes.replica; +const host_io = @import("dev").host_io; +const file_watch = @import("dev").file_watch; +const daemon = @import("daemon.zig"); +const upgrade = @import("upgrade.zig"); +const ninep_io = @import("9p_io.zig"); + +/// The files a frontend watches (host_io.restoreCore lets them go). +pub const Watched = struct { fd: c_int, table: *file_watch.Table }; + +pub fn Loop(comptime Frontend: type) type { + return struct { + const L = @This(); + + io: std.Io, + gpa: std.mem.Allocator, + allocs: pardes.memory.Allocators, + /// Its frame timings, the frontend's to write as it draws + /// (Pardes.frames). + frames: pardes.FrameStats = .{}, + core: *pardes.Pardes = undefined, + prompt_rcs: host_io.Shell.PromptFiles = undefined, + fs: ?*ninep_io.Listener = null, + peers: replica.Peers = .{}, + host: pardes.Host = undefined, + fe: *Frontend, + + /// The session, from its start to its end. + pub fn run(init: std.process.Init, opts: pardes.Options, fe: *Frontend) !void { + var l: L = .{ .io = init.io, .gpa = init.gpa, .allocs = pardes.memory.init(init.gpa), .fe = fe }; + defer pardes.memory.deinit(); + host_io.startWorkers(l.allocs); + defer host_io.stopWorkers(); + var o = opts; + o.addons = pardes.Addon.scan(); + o.frames = &l.frames; + o.image_allocator = l.allocs.image; + o.tree_sitter_allocator = l.allocs.tree_sitter; + o.frame_allocator = l.allocs.frame; + fe.options(&o); + l.core = if (upgrade.resumed) |*rec| + try upgrade.load(l.gpa, l.allocs.pardes, o, rec) + else if (o.load_path) |lp| blk: { + const bytes = try pardes.filesystem.readFile(&pardes.tape.none, l.gpa, lp); + defer l.gpa.free(bytes); + break :blk try pardes.dump.initFromDump(l.allocs.pardes, o, bytes); + } else try pardes.Pardes.init(l.allocs.pardes, o); + defer l.core.deinit(); + l.prompt_rcs = host_io.Shell.prepare(); + defer l.prompt_rcs.deinit(); + l.fs = ninep_io.start(l.io, l.gpa, l.core); + defer if (l.fs) |f| f.deinit(l.gpa); + l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() }; + + l.host = try fe.open(&l); + defer fe.close(&l); + defer l.peers.deinit(); + // Before the core goes: each client sees its link end. + defer l.peers.dropAll(l.core); + l.effects(); + // ...and its shells, once a fresh session's own has a directory + // to adopt them in. + if (upgrade.resumed) |*rec| { + fe.resumePtys(rec); + l.effects(); + } + try fe.start(&l); + + while (!l.core.quit) { + pardes.turn.bump(&pardes.turn.restores); + try l.core.pump(l.host); + // Its unit to each replica client, and theirs taken in. + l.peers.boundary(l.core); + fe.sent(); + upgrade.locate(); + // Asked in the step (the word), done between steps: the + // session whole. + fe.upgradeAsked(); + // A terminal (`pardes --attach`), a window asked for again, + // an adopted shell or a client's connection, handed on by + // the daemon's thread; started after the first frame, off a + // start's way. + l.watch(); + // A session that ended does not restore into one. + if (l.core.quit) break; + if (l.core.takeRestore()) |rp| l.restore(rp); + } + // Its serve threads read the core: they end first. + if (l.fs) |f| { + f.deinit(l.gpa); + l.fs = null; + } + } + + fn effects(l: *L) void { + while (l.core.nextEffect()) |e| l.core.perform(e); + } + + /// What the daemon says, onto the frontend's queue (once: its + /// reader is started by the first call). + pub fn watch(l: *L) void { + daemon.watch(l.fe, note); + } + + fn note(ctx: *anyopaque, n: daemon.Note) void { + const fe: *Frontend = @ptrCast(@alignCast(ctx)); + fe.note(n); + } + + /// A Restore: the core its dump makes replaces this one, its clients + /// let go (host_io.restoreCore); the frontend's devices with it. + fn restore(l: *L, path: []const u8) void { + const w = l.fe.watched(); + const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, w.fd, w.table) orelse return; + l.fe.restoring(nc); + nc.host = l.host; + if (l.fs) |f| f.reset(nc); + l.core.deinit(); + l.core = nc; + l.fe.restored(l); + } + }; +} diff --git a/test/replicas.zig b/test/replicas.zig index 69207970..7f7ca0b3 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1,6 +1,8 @@ //! pardes-replicas: a session and its clients in one process -//! (core/replica.zig): the session's own frontend typing in its view and -//! drawing it, and each client (THE client loop, runtime/client.zig, over a +//! (core/replica.zig): the session THE session loop (runtime/session.zig, +//! the terminal's and the window's) over a frontend of the soak's, its +//! clients' links in memory and its devices answered from memory, its own +//! frontend typing in its view and drawing it, and each client (THE client loop, runtime/client.zig, over a //! terminal's frontend or a window's, by turns, drawing no pixels) joined from //! the session's dump for a view of its own, typing at once over its own //! delayed, jittered link, as monkey.zig's scripts type at a tty, through @@ -41,11 +43,14 @@ const libc = std.c; const pardes = @import("pardes"); const replica = pardes.replica; const client_loop = @import("runtime").client; +const session_loop = @import("runtime").session; const screen_state = @import("term").screen_state; const Echo = pardes.Echo; const Key = pardes.Key; const gpa = std.heap.c_allocator; +/// Its session's joins and leaves, said at `info`, are no news here. +pub const std_options: std.Options = .{ .log_level = .warn }; extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; var trace = false; /// The PDF the soak opens (`--pdf`), absolute. @@ -163,6 +168,10 @@ const Kind = enum { gone, /// A picture's draw done on a worker, onto its loop (`Draws`). draw, + /// A frame a client wrote, up its link to its Peer; a blob of the + /// session's down it. + up, + blob, }; const Msg = struct { @@ -430,24 +439,33 @@ fn screenHash(t: *screen_state.Terminal) u64 { /// counts its frames and keeps the facts a window reads beside them, and /// its wait is the delayed link's next message for it (a wake it asks for /// goes through the net). Its link is the real `replica.Link` on a socket -/// pair whose other end the soak reads as the session's Peer does -/// (`drain`). It joins from the session's dump, may be refused (every view -/// taken), leaves, and joins again for its view after a divergence. +/// pair, a new one a dial, whose other end the session's Peer holds (a dup) +/// and the soak reads as that Peer's reader would (`drain`). It joins from +/// the session's dump, may be refused (every view taken), leaves, and joins +/// again for its view after a divergence. const Client = struct { kind: enum { tty, window }, loop: ClientLoop = undefined, r: ?*replica.Replica = null, - fds: [2]c_int = .{ -1, -1 }, + /// Its link's socket pair: its own end (its Link's) and the session's, + /// which the soak reads (`drain`); the dup of the session's end handed + /// at its dial (`Peers.handed`), until the session's boundary took it. + cfd: c_int = -1, + sfd: c_int = -1, + handed: c_int = -1, + /// The session's Peer for it while that link is the session's; what + /// it is sent taken from its queue as its writer would (`Soak.sent`). + peer: ?*replica.Peer = null, + /// That link ended at the session's side: shut by it (a Detach typed + /// in its view, cut off) or its reader's end posted (`Soak.up`). + shut: bool = false, + read_done: bool = false, check: [:0]u8 = undefined, - /// The session's side of its socket: bytes not yet a whole frame, the - /// stamp before an input, and the inputs it took (Peer.seq). + /// What it wrote, read off the session's end: bytes not yet a frame. got: std.ArrayListUnmanaged(u8) = .empty, - stamp: std.ArrayListUnmanaged(u8) = .empty, - seq: u32 = 0, - /// Its id and its terminals' peer at the session, and the view the - /// session made or keeps for it (`back`, joining again). + /// Its id and view at the session (its welcome's), and the view it + /// joins again for (`back`, after a divergence). id: u16 = 0, - sid: u16 = 0, view: u8 = 0, back: ?u8 = null, digest: u64 = 0, @@ -455,7 +473,6 @@ const Client = struct { /// is of (0: none, its link ended). gen: u32 = 0, live: u32 = 0, - joined: bool = false, dialling: bool = false, /// Refusals in a row, until it gives up (a person would). tries: u32 = 0, @@ -565,6 +582,15 @@ const Client = struct { pub fn open(cl: *Client, _: []const u8) void { cl.asked[2] += 1; } + + /// Its link's socket pair let go (the link it had is over). + fn closeLink(cl: *Client) void { + for ([_]*c_int{ &cl.cfd, &cl.sfd }) |fd| if (fd.* >= 0) { + _ = libc.close(fd.*); + fd.* = -1; + }; + cl.got.clearRetainingCapacity(); + } }; const ClientLoop = client_loop.Loop(Client); @@ -593,53 +619,21 @@ const Net = struct { } }; -/// What client `c` wrote to its socket since (its inputs, its terminal -/// messages, a check asked, its bye), read off the other end as the -/// session's Peer reads it (`Peer.take`), up its link. +/// What client `c` wrote to its socket since (its inputs and their stamps, +/// its terminal messages, a check asked, its bye), read off the session's +/// end, a frame a message up its link: the session's Peer takes each as it +/// comes (`Soak.up`), as its reader thread would. fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { + if (cl.sfd < 0) return; var buf: [1 << 16]u8 = undefined; while (true) { - const k = libc.read(cl.fds[0], &buf, buf.len); + const k = libc.read(cl.sfd, &buf, buf.len); if (k <= 0) break; try cl.got.appendSlice(gpa, buf[0..@intCast(k)]); } - const wire = pardes.wire; var at: usize = 0; - while (try wire.framed(cl.got.items[at..])) |f| : (at += f.total) { - const frame = cl.got.items[at..][0..f.total]; - const kind: Kind = switch (std.enums.fromInt(wire.ClientTag, f.tag) orelse return error.BadFrame) { - .stamp => { - cl.stamp.clearRetainingCapacity(); - try cl.stamp.appendSlice(gpa, frame); - continue; - }, - .screen_ack => .screen_up, - .check => .check_up, - .bye => .bye_up, - else => .to_authority, - }; - var seq: u32 = 0; - const bytes: []u8 = switch (kind) { - .to_authority => in: { - // Its head (its id and seq at the session), its stamp, its event. - cl.seq += 1; - const msg = try gpa.alloc(u8, 6 + cl.stamp.items.len + frame.len); - std.mem.writeInt(u16, msg[0..2], cl.id, .little); - std.mem.writeInt(u32, msg[2..6], cl.seq, .little); - @memcpy(msg[6..][0..cl.stamp.items.len], cl.stamp.items); - @memcpy(msg[6 + cl.stamp.items.len ..], frame); - cl.stamp.clearRetainingCapacity(); - if (replica.parseInput(msg) == null) return error.BadInput; - break :in msg; - }, - .screen_up => try gpa.dupe(u8, f.payload), - .bye_up => bye: { - seq = @intFromBool((try wire.decodeClient(f.tag, f.payload)).bye.again); - break :bye &.{}; - }, - else => &.{}, - }; - try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .seq = seq, .gen = cl.gen }); + while (try pardes.wire.framed(cl.got.items[at..])) |f| : (at += f.total) { + try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); } std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]); cl.got.shrinkRetainingCapacity(cl.got.items.len - at); @@ -696,7 +690,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, const r = cl.r.?; const link = &cl.loop.link; // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(cl.fds[1], r.diverged != null); + if (!link.gone) replica.bye(link.fd, r.diverged != null); try drain(cl, c, net, now); cl.live = 0; if (r.diverged) |why| { @@ -722,15 +716,797 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, } } -fn run(r: Run, dir: []const u8, totals: *Totals) !void { +/// When the session's shell's program prints (`.output`): a full-screen +/// program, a shell's session, then the flood. +const tui_at: u64 = 400_000; +const session_at: u64 = 1_000_000; +const flood_at: u64 = 2_500_000; + +const SessionLoop = session_loop.Loop(Soak); + +/// The session's own frontend, a terminal's with its devices answered from +/// memory: THE session loop (runtime/session.zig, the terminal's and the +/// window's) runs over it. Its clients' links are in memory +/// (`Peers.threads` false): the soak is each Peer's reader (`up`) and +/// writer (`sent`). Its host is the soak's, and the host's wait +/// (`waitInput`) is the soak's net: the session's own typist, its shell's +/// program and echoes, its frames and its workers' draws, the clients' +/// dials and messages up their links end the wait as a terminal's events +/// do (tui.zig `waitInput`); every client's own loop runs inside it on what +/// comes down its link. The run ends inside its last wait, when nothing is +/// in flight: every client checked against the session there, its core +/// still whole. +const Soak = struct { + r: Run, + totals: *Totals, + random: std.Random, + net: *Net, + clients: []Client, + looks: []const []const u8, + with_pdf: bool, + /// What the shell's program prints (`.output`). + tui: []const u8, + shell_session: []const u8, + yes: []const u8, + l: *SessionLoop = undefined, + /// What failed inside the loop (its wait returns nothing): the run's. + err: ?anyerror = null, + + // ---- its host ---- + /// A pty that echoes what it is written, 2 ms later, as a shell's. + echo: std.ArrayListUnmanaged(struct { pane: u8, bytes: []u8 }) = .empty, + /// The session's clock (tui.zig `clockNow`): the soak's time at a + /// frame, an input of its own frontend's, a pty's read or a worker's + /// draw; a pump woken by a client's mail alone reads the last again. + now_ns: u64 = std.time.ns_per_s, + /// A client's view whose Detach a step took (tui.zig `detach`: + /// `Peers.detach` shut its link; the session's own view's is its + /// terminal's, which the soak has none of). + detach_view: ?u8 = null, + + // ---- the soak ---- + /// The soak's time (us): the last message's. + now: u64 = 0, + aim: Aim = .{ .shell = null, .pdf = null }, + shell: u8 = 0, + own_left: usize, + own_script: Script = .{}, + /// Typists not done: the session's own and every client's. + typing: usize, + frames_left: u32 = 0, + flood_end: u64 = 0, + program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{}, + /// The session's version of each terminal, as its screen showed then. + versions: std.AutoHashMapUnmanaged(u64, u64) = .empty, + flood_deltas: [8]u64 = @splat(0), + kinds_seen: u32 = 0, + /// Each client's link made (its first join), and its replica's. + has_link: [8]bool = @splat(false), + /// An input of its own frontend's held for the next wait, a pty's + /// output taken in this one (tui.zig `split`). + held: ?Msg = null, + /// The step boundary after a frame's wake under the flood: what its + /// encoding cost. + framed: bool = false, + encode_ns: u64 = 0, + /// A Peer's queue, swapped out as its writer swaps it (the Peers' + /// allocator's). + sending: std.ArrayListUnmanaged(u8) = .empty, + /// This wait ended at its frame's tick: its pump draws. + at_frame: bool = false, + + fn of(ctx: ?*anyopaque) *Soak { + return @ptrCast(@alignCast(ctx.?)); + } + + /// Its own view drawn at its frame's tick (`.frame`), as the soak's + /// session always drew it; not after every pump, as a terminal's is: + /// drawn so, the soak finds a client's step replayed with a kind's call + /// more than the session's (reports/pardes-runners-d.md). + fn watchedHost(ctx: ?*anyopaque) bool { + return of(ctx).at_frame; + } + + fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const s = of(ctx); + s.echo.append(gpa, .{ .pane = pane, .bytes = gpa.dupe(u8, bytes) catch return }) catch {}; + } + + fn nowHost(ctx: ?*anyopaque) u64 { + return of(ctx).now_ns; + } + + fn detach(ctx: ?*anyopaque) void { + const s = of(ctx); + const k = s.l.core.live; + if (s.l.peers.detach(k)) s.detach_view = k; + } + + /// A kind's job on a worker, as tui.zig's `job` runs one: its answer + /// the session's own step `draw_us` later (`.draw`), as a worker's is + /// its loop's event (with no `job`, Effect.perform runs it at once on + /// the core's side, inside the perform that asked it, where no tape + /// records it: a client replays that perform without it). + fn job(ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void { + const core = of(ctx).l.core; + const j = pardes.host_io.KindJob.take(core, pane, serial, token) orelse return; + if (Draws.go(null, j)) return; + j.run(); + j.land(core); + } + + /// The wait inside the session's pump (tui.zig `waitInput`), until + /// what a terminal's loop would wake for: the soak's net. What its + /// clients' steps leave process-wide (the tape stepped, its core's + /// field, the held trees a rollback epoch selects: replica.zig + /// `Stepping.end` puts no epoch back) is the session's again before + /// it returns. + fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { + const s = of(ctx); + const core = s.l.core; + const on = pardes.tape.on; + const field = core.tape; + const trees = pardes.syntax.held_trees; + const done = s.wait(timeout_ms) catch |err| fail: { + s.err = err; + break :fail true; + }; + pardes.tape.on = on; + core.tape = field; + pardes.syntax.held_trees = trees; + if (!done) return; + // Nothing in flight: the run's end, every client checked against + // the session as it is now. + if (s.err == null) s.finish() catch |err| { + s.err = err; + }; + core.quit = true; + } + + const vtable = replica.everyEntry(.{ .watched = watchedHost, .pty_write = ptyWrite, .now = nowHost, .detach = detach, .job = job, .wait_input = waitInput }); + + // ---- the session loop's frontend ---- + + pub fn options(_: *Soak, _: *pardes.Options) void {} + + pub fn open(s: *Soak, l: *SessionLoop) !pardes.Host { + s.l = l; + l.peers.threads = false; + l.peers.flushed = .{ .ctx = s, .f = flushed }; + const host: pardes.Host = .{ .ctx = s, .vtable = &vtable }; + l.core.host = host; + return host; + } + + /// After the clients were let go: the clients' processes end, and what + /// is still in flight goes. + pub fn close(s: *Soak, _: *SessionLoop) void { + for (Draws.jobs.items) |j| j.drop(); + Draws.jobs.clearRetainingCapacity(); + for (s.clients, s.has_link[0..s.clients.len]) |*cl, made| { + if (cl.r) |rp| rp.deinit(); + cl.r = null; + cl.closeLink(); + cl.got.deinit(gpa); + gpa.free(cl.check); + if (made) { + cl.loop.link.check = null; + cl.loop.link.deinit(gpa); + } + } + while (s.net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); + if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); + for (s.echo.items) |e| gpa.free(e.bytes); + s.echo.deinit(gpa); + s.versions.deinit(gpa); + s.sending.deinit(s.l.peers.gpa); + } + + pub fn resumePtys(_: *Soak, _: anytype) void {} + + /// The tty's own boot (a raw shell, a text pane under it), then three + /// files looked at, and the picture and the PDF in a column of their + /// own (plain kinds' panes every client joins with, loaded from its + /// dump, the file read by its path): the session's own frontend shows + /// the first view and types in it; each client joins from a dump for + /// a view of its own. Then everyone starts. + pub fn start(s: *Soak, l: *SessionLoop) !void { + const core = l.core; + for (s.looks[0..3]) |look| s.setup(.{ .command = look }); + if (s.looks.len > 3) { + s.setup(.{ .command = "Newcol" }); + s.setup(.{ .command = s.looks[3] }); + } + if (s.with_pdf) s.setup(.{ .command = s.looks[4] }); + s.shell = for (core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + // Where a wheel over the shell lands in the session's view, which a + // client's view is a copy of as it joins; and the PDF's body there. + const sr = core.view().rects[s.shell]; + const pr = if (s.with_pdf) core.view().rects[core.view().active] else pardes.Rect{}; + s.aim = .{ + .shell = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null, + .pdf = if (pr.h > 4 and pr.w > 8) .{ pr.x + 4, pr.y + 2, pr.w - 8, pr.h - 4 } else null, + }; + const net = s.net; + // The clients: terminals and windows by turns. The first two dial at + // once, the third late (the shell's program on), more later still + // (refused while every view is taken, dialling again until one is + // let go); the first leaves when it is done; the second is put off + // the session once (PARDES_TEST_DIVERGE) and joins again for its view. + for (s.clients, 0..) |*cl, c| { + cl.dialling = true; + const at: u64 = switch (c) { + 0, 1 => s.random.uintLessThan(u64, 100_000), + 2 => 1_200_000, + else => 2_000_000 + c * 100_000, + }; + try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); + } + try net.send(.{ .at = s.random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }); + try net.send(.{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} }); + try net.send(.{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} }); + try net.send(.{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} }); + try net.send(.{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); + } + + /// A setup's command, before anyone looks: no tape, no client. + fn setup(s: *Soak, ev: pardes.Event) void { + s.l.core.update(ev); + s.l.core.settle(); + } + + /// After each step boundary (`Peers.boundary`: the pump's unit, the + /// clients' inputs, joins and leaves taken in): what a Peer's writer + /// would write, down each link; a join taken or refused; a link the + /// session shut; the echoes its steps asked of the shell. + pub fn sent(s: *Soak) void { + s.sentOrFail() catch |err| { + if (s.err == null) s.err = err; + s.l.core.quit = true; + }; + } + + fn sentOrFail(s: *Soak) !void { + const ps = &s.l.peers; + const core = s.l.core; + const net = s.net; + const now = s.now; + // Those let go in the boundary (Peers.leave, letGo): gone. + for (s.clients) |*cl| if (cl.peer) |was| { + const there = for (ps.list) |slot| { + if (slot) |p| if (p == was and p.id == cl.id) break true; + } else false; + if (!there) cl.peer = null; + }; + // A join taken (its Peer holds the dup handed) or refused (its dup + // closed, daemon.refuseReplica): its writer's join first (the + // welcome, then the dump with the session's blobs put back where + // they go: Peer.writeJoin), its far word read (`far` false: on + // this machine), and its pins let go at the next boundary. + for (s.clients, 0..) |*cl, c| if (cl.handed >= 0) { + defer cl.handed = -1; + const peer = for (ps.list) |slot| { + if (slot) |p| if (p.fd == cl.handed) break p; + } else { + s.totals.refused += 1; + try net.toClient(c, now, .refused, cl.gen, &.{}); + continue; + }; + const f = (try pardes.wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + const welcome = (try pardes.wire.decodeServer(f.tag, f.payload)).welcome; + var whole: std.ArrayListUnmanaged(u8) = .empty; + errdefer whole.deinit(gpa); + var pos: usize = 0; + for (peer.blobs.items) |b| { + try whole.appendSlice(gpa, peer.dump[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, peer.dump[pos..]); + var word: [16]u8 = undefined; + const far = try pardes.wire.encodeClient(&word, .{ .far = false }); + _ = peer.take(far[0], far[pardes.wire.header_len..]); + ps.post(.{ .joined = peer }); + cl.peer = peer; + cl.shut = false; + cl.read_done = false; + cl.gen += 1; + cl.id = welcome.client; + cl.view = welcome.view; + cl.digest = welcome.digest; + s.totals.joins += 1; + try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); + }; + // A Detach typed in a client's view, or one cut off for its lag: its + // link shut, it hears its end and nothing after; its reader's end + // said (the next boundary lets it go). + if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view == k and !cl.shut) { + cl.shut = true; + }; + s.detach_view = null; + const flooding = now >= flood_at and s.flood_end == 0; + for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| { + if (peer.cut) cl.shut = true; + const io = ps.io; + peer.lock.lockUncancelable(io); + std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &s.sending); + peer.lock.unlock(io); + defer s.sending.clearRetainingCapacity(); + if (cl.shut) { + if (!cl.read_done) { + cl.read_done = true; + ps.post(.{ .gone = peer }); + try net.toClient(c, now, .gone, cl.gen, &.{}); + } + continue; + } + var at: usize = 0; + while (try pardes.wire.framed(s.sending.items[at..])) |f| : (at += f.total) { + const tag = std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame; + switch (tag) { + .unit => { + s.totals.unit_bytes += f.payload.len; + if (flooding) s.totals.flood_unit_bytes += f.payload.len; + try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .screen => { + if (f.payload[5] == 1) { + s.totals.deltas += 1; + s.totals.delta_bytes += f.payload.len; + if (flooding) s.totals.flood_delta_bytes += f.payload.len; + } else s.totals.filled_bytes += f.payload.len; + try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .check => { + const d = try gpa.alloc(u8, 8); + std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); + try net.toClient(c, now, .checked, cl.gen, d); + }, + .blob => try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)), + else => return error.UnexpectedFrame, + } + } + if (at != s.sending.items.len) return error.TornFrame; + }; + // The kinds' panes it has opened, each counted once. + for (core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen) { + s.kinds_seen = pane.serial; + for ([_][]const u8{ "image", "life", "pdf" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); + }; + for (s.echo.items) |e| try net.send(.{ .at = now + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); + s.echo.clearRetainingCapacity(); + if (s.framed) { + s.framed = false; + if (now >= flood_at and (s.flood_end == 0 or now <= s.flood_end)) try s.totals.frame_ns.append(gpa, ps.screens.encode_ns - s.encode_ns); + } + } + + /// Each terminal at its version as the session's screen shows it now + /// (after a flush: `Peers.flushed`). + fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { + const s: *Soak = @ptrCast(@alignCast(ctx)); + for (&screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| { + const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; + if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue; + _ = core.panes[id] orelse continue; + s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)) catch |err| { + s.err = err; + }; + }; + } + + pub fn upgradeAsked(_: *Soak) void {} + pub fn note(_: *Soak, _: anytype) void {} + /// No Restore is typed here (host_io.restoreCore is the session's own). + pub fn watched(_: *Soak) session_loop.Watched { + unreachable; + } + pub fn restoring(_: *Soak, _: *pardes.Pardes) void {} + pub fn restored(_: *Soak, _: *SessionLoop) void {} + + /// The session's clock moved to the soak's time. + fn clock(s: *Soak) void { + s.now_ns = std.time.ns_per_s + s.now * 1000; + } + + /// The net until the session's loop would wake: true when nothing is + /// in flight any more (the run's end). + fn wait(s: *Soak, timeout_ms: u32) !bool { + const core = s.l.core; + const net = s.net; + // An input of its own held while a pty's output was taken: the step + // after reads the terminal as the clients' deltas bring it. + if (s.held) |m| { + s.held = null; + try s.own(m); + return false; + } + var took_output = false; + s.at_frame = false; + // What its boundary took is old news. + _ = s.l.peers.urgent.swap(false, .acq_rel); + while (true) { + const next = net.q.peek() orelse return !took_output; + // Every typist done, the flood over and its frames' two seconds + // past: what is in flight is delivered and the run ends. The + // session's own wakes (a blink, a game of life's tick) and the + // clients' (their quiet checks) go on in a real session; here + // they are no longer taken. Each idle client's check wakes the + // session, whose pump's unit is a change that asks the next + // check: they would never stop. + const ending = s.typing == 0 and s.flood_end != 0 and s.frames_left == 0; + // The core's next wake (its timeout), on the soak's clock. + if (!ending and timeout_ms != 0 and next.at > s.now + @as(u64, timeout_ms) * 1000) { + s.now += @as(u64, timeout_ms) * 1000; + s.clock(); + return false; + } + const m = net.q.pop().?; + var kept = false; + defer if (!kept and m.bytes.len > 0) gpa.free(m.bytes); + s.now = m.at; + Draws.now = m.at; + // A client's message, but an echo's and an output's `who` (a pane, + // a program). + const c: usize = if (m.who == 0 or m.kind == .echo or m.kind == .output) 0 else m.who - 1; + const cl = &s.clients[c]; + // A client's own process steps nothing of the session's: no + // tape is stepped in it between its steps (tape.enter's check), + // and no rollback epoch's trees are held. + const in_client = switch (m.kind) { + .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => true, + .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), + else => false, + }; + const session_on = pardes.tape.on; + const session_trees = pardes.syntax.held_trees; + if (in_client) { + pardes.tape.on = null; + pardes.syntax.held_trees = null; + } + defer if (in_client) { + pardes.tape.on = session_on; + pardes.syntax.held_trees = session_trees; + }; + switch (m.kind) { + // ---- the session ---- + .own => { + if (took_output) { + kept = true; + s.held = m; + return false; + } + try s.own(m); + return false; + }, + // A pty's read: its echo drawn at once (an input's), the + // program's output a frame a tick (tui.zig `waitInput`). + .echo => { + s.clock(); + core.update(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } }); + return false; + }, + .output => { + s.clock(); + // The program's next read, 4 KB, then the next a + // fraction of a millisecond on (ghostty's pace). + if (s.program.at == s.program.bytes.len) { + s.program = .{ .bytes = switch (m.who) { + 0 => s.tui, + 1 => s.yes, + else => s.shell_session, + } }; + } + const k = @min(s.program.bytes.len - s.program.at, if (m.who == 1) @as(usize, 4096) else 700); + const chunk = s.program.bytes[s.program.at..][0..k]; + s.program.at += k; + if (s.program.at < s.program.bytes.len) + try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) + else if (m.who == 1) s.flood_end = m.at; + core.update(.{ .output = .{ .pane = s.shell, .bytes = chunk } }); + took_output = true; + }, + .frame => { + // Its own frontend's frame: its loop woken when output + // came, a frame is owed or the core's next wake is due. + s.clock(); + // Frames go on while anyone types or the flood runs, and + // two seconds after (a session with a clock wakes on: a + // blink, a kind's tick; what is in flight still comes). + const busy = s.typing > 0 or s.flood_end == 0; + s.frames_left = if (busy) 120 else s.frames_left -| 1; + if (s.frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); + if (took_output or core.needs_frame or (core.nextWake() orelse std.math.maxInt(u64)) <= s.now_ns) { + s.at_frame = true; + s.framed = true; + s.encode_ns = s.l.peers.screens.encode_ns; + return false; + } + }, + // A client's connection, handed over by the daemon (tui.zig + // `.replica`): joined at the session's next step boundary, + // on a socket pair of its own. + .dial => { + cl.closeLink(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + _ = libc.fcntl(fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); + cl.sfd = fds[0]; + cl.cfd = fds[1]; + cl.handed = libc.dup(fds[0]); + if (cl.handed < 0) return error.NoSocket; + s.l.peers.handed(cl.handed, cl.back); + return false; + }, + // What a client wrote, at the session's end of its link: its + // Peer's reader takes it (Peer.take), and a link it ends + // (its bye) is gone (its reader's end, posted). + .up => { + const peer = cl.peer orelse continue; + if (m.gen != cl.gen or cl.read_done or cl.shut) continue; + const f = (try pardes.wire.framed(m.bytes)) orelse return error.BadFrame; + if (ending and f.tag == @backingInt(pardes.wire.ClientTag.check)) continue; + if (f.tag == @backingInt(pardes.wire.ClientTag.screen_ack) and f.payload.len >= 22 and f.payload[5] == 2) + s.totals.fetched += std.mem.readInt(u64, f.payload[14..22], .little) - std.mem.readInt(u64, f.payload[6..14], .little); + if (!peer.take(f.tag, f.payload)) { + cl.read_done = true; + s.l.peers.post(.{ .gone = peer }); + } + // A reader's post wakes the loop (tui.zig `.replica_mail`): + // an input, a join, a check or a leave at once; a + // terminal's acknowledgement as a pty's output does, + // at the frame when output came in this wait. + if (s.l.peers.urgent.swap(false, .acq_rel)) return false; + if (s.l.peers.mail.load(.acquire) and !took_output) return false; + }, + .draw => { + // A worker's draw done, onto the loop of the core that + // asked it (tui.zig `.kind_job`): kept for its pane's + // next paint, a frame owed; one of a core gone since is + // let go. + const j = Draws.jobs.orderedRemove(0); + j.run(); + // A state job's answer: a step of the session's own. + if (j.draw == null) { + s.clock(); + core.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); + j.drop(); + return false; + } + if (j.draw == @as(?*const pardes.Pardes, core)) { + s.clock(); + pardes.Kind.landDraw(core, j); + return false; + } + const k = for (s.clients, 0..) |*dc, k| { + if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k; + } else { + j.drop(); + continue; + }; + const dc = &s.clients[k]; + pardes.Kind.landDraw(dc.r.?.core(), j); + // Into the core it holds while it joins again: its loop + // is not running (replica.join waits for the dump). + if (dc.live == 0) continue; + dc.loop.link.dirty = true; + try woke(dc, k, net, m.at, s.totals, s.r); + if (dc.loop.link.quit) try ended(dc, k, net, m.at, s.totals, s.r, &s.typing); + }, + // ---- a client ---- + .refused => { + if (!cl.dialling) continue; + // Said and gone; started again a while later (a person + // does), while it has keys left to type. + cl.back = null; + if (cl.r) |old| { + try s.totals.add(&old.stats); + old.deinit(); + cl.r = null; + } + cl.tries += 1; + if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(s.random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { + // Given up on: its keys are never typed. + cl.dialling = false; + if (cl.left > 0) s.typing -= 1; + cl.left = 0; + } + }, + .dump => try s.joined(cl, c, m), + .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => { + if (m.kind == .input and cl.left == 0) continue; + const rp = cl.r orelse if (m.kind == .input and cl.dialling) { + try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + continue; + } else continue; + if (m.kind == .input) { + // A key typed while it joins again waits for the link. + if (cl.live == 0) { + try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + continue; + } + } else if (m.kind != .quit and m.gen != cl.live) continue; + rp.echo.now = m.at * 1000; + cl.now = m.at; + cl.loop.link.now = m.at * 1000; + switch (m.kind) { + .input => { + var buf: [64]u8 = undefined; + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script); + cl.loop.input(ev); + cl.left -= 1; + if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { + s.typing -= 1; + // The first leaves once it is done. + if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); + } + }, + .to_replica => cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }), + .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), + .screen_down => { + const pane = m.bytes[0]; + const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0; + cl.loop.take(.{ .screen = try std.heap.c_allocator.dupe(u8, m.bytes) }); + if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| { + const now_seq = replicaOf(sc.rep).seq; + if (now_seq == was) s.totals.resets += 1 else { + // Applied: the screen is the session's at that version. + s.totals.screens_checked += 1; + const want = s.versions.get(@as(u64, sc.serial) << 32 | now_seq); + const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; + if (want == null or want.? != screenHash(vt)) { + s.totals.screens_wrong += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the session's\n", .{ s.r.seed, s.r.rtt_ms, m.who, pane, now_seq }); + } + // Deltas while the flood runs (an RTT/2 behind it). + if (m.at >= flood_at + net.one_way and (s.flood_end == 0 or m.at <= s.flood_end + net.one_way)) s.flood_deltas[c] += 1; + } + }; + }, + .checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), + .wake => { + // One the next replaced is no wake. + if (m.at != cl.wake_at or ending) continue; + cl.wake_at = 0; + }, + .quit => cl.loop.link.quit = true, + .gone => { + cl.loop.link.quit = true; + cl.loop.link.gone = true; + }, + else => unreachable, + } + try woke(cl, c, net, m.at, s.totals, s.r); + if (cl.loop.link.quit) try ended(cl, c, net, m.at, s.totals, s.r, &s.typing); + }, + .to_authority, .screen_up, .client_frame, .check_up, .bye_up => unreachable, + } + } + } + + /// An input of its own frontend's, in the view it shows (the first: + /// tui.zig `Shell.apply` goes into `s.own`). + fn own(s: *Soak, m: Msg) !void { + const core = s.l.core; + s.clock(); + var buf: [64]u8 = undefined; + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script); + core.toView(0); + core.update(ev); + s.own_left -= 1; + if (s.own_left > 0) try s.net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else s.typing -= 1; + } + + /// Its dump at the client (replica.join): the core it left let go once + /// the new one is here, the dump loaded and checked by the digest, + /// then the loop's join (Loop.run): its first inputs, a pass up to its + /// wait. + fn joined(s: *Soak, cl: *Client, c: usize, m: Msg) !void { + const net = s.net; + cl.dialling = false; + cl.tries = 0; + if (cl.r) |old| { + try s.totals.add(&old.stats); + old.deinit(); + } + const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); + cl.r = rp; + rp.stats.samples = true; + rp.t.local_files = true; + rp.echo.now = m.at * 1000; + if (!rp.loaded(cl.digest)) { + s.totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ s.r.seed, s.r.rtt_ms, m.who }); + } + cl.live = m.gen; + var j: replica.Joined = .{ .fd = cl.cfd, .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} }; + if (!s.has_link[c]) { + cl.loop = .{ .link = .{ .r = rp, .fd = cl.cfd, .check = cl.check }, .fe = cl, .frames = &cl.frames }; + s.has_link[c] = true; + if (c == 1) cl.loop.link.test_diverge = 40; + } + cl.c = c; + cl.net = net; + cl.now = m.at; + cl.wake_at = 0; + cl.stops = rp.stats.stops; + cl.loop.link.now = m.at * 1000; + cl.loop.link.reset(rp, &j); + cl.posted = null; + cl.start(&cl.loop); + _ = cl.loop.pass(); + judgeStops(cl, c, s.totals, s.r); + try drain(cl, c, net, m.at); + if (cl.left > 0 and cl.left == s.r.steps) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); + } + + /// At quiescence: every client's digest the session's, its terminals + /// the session's cell for cell, its files' texts byte for byte. + fn finish(s: *Soak) !void { + const totals = s.totals; + const core = s.l.core; + totals.flood_us += s.flood_end -| flood_at; + for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; + const want = pardes.tape.digestOf(core); + for (s.clients, 1..) |*cl, id| { + totals.resizes += cl.resizes; + totals.wakes += cl.wakes; + for (&totals.asked, cl.asked) |*t, n| t.* += n; + if (s.has_link[id - 1]) totals.draws += cl.loop.link.draws; + // Its quiet checks: what the session's digest was against its own. + if (readAll(cl.check)) |said| { + defer gpa.free(said); + var lines = std.mem.tokenizeScalar(u8, said, '\n'); + while (lines.next()) |line| if (std.mem.startsWith(u8, line, "agree")) { + totals.agree += 1; + } else { + totals.differ += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s quiet check: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, line }); + }; + } + const rp = cl.r orelse continue; + try totals.add(&rp.stats); + if (cl.live == 0) continue; + if (rp.diverged) |why| { + totals.divergences += 1; + std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, why }); + } else if (!rp.quiet() or rp.digest() != want) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" }); + } + // At quiescence, every terminal the session's, cell for cell. + for (core.panes, 0..) |slot, pid| { + const pane = slot orelse continue; + const state = pane.terminal orelse continue; + const mine = (rp.core().panes[pid] orelse { + totals.unequal += 1; + continue; + }).terminal orelse continue; + if (screenHash(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); + } + } + // ...and every file's text the session's, byte for byte: a digest + // takes a text of 4 KiB and up by its length (core/walk.zig). + for (core.panes, 0..) |slot, pid| { + const f = (slot orelse continue).file orelse continue; + const mine = if (rp.core().panes[pid]) |pane| pane.file else null; + if (mine == null or !std.mem.eql(u8, f.content, mine.?.content)) { + totals.unequal += 1; + std.debug.print("seed {d} rtt {d} ms: client {d}'s text {d} at quiescence is not the session's\n", .{ s.r.seed, s.r.rtt_ms, id, pid }); + } + } + } + } +}; + +fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms }); var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); - var host: Host = .{}; - defer { - for (host.echo.items) |e| gpa.free(e.bytes); - host.echo.deinit(gpa); - } var paths: [3][256:0]u8 = undefined; var look_lines: [8][300]u8 = undefined; var looks_buf: [8][]const u8 = undefined; @@ -763,89 +1539,22 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { looks_buf[nlooks] = try std.fmt.bufPrint(&look_lines[nlooks], "Look {s}{s}", .{ pdf_path.?, at }); nlooks += 1; }; - const looks = looks_buf[0..nlooks]; - // The tty's own boot (a raw shell, a text pane under it), then three - // files looked at: the session's own frontend shows the first view - // and types in it; each client joins from a dump for a view of its own. - host.clocked = true; - host.now_ns = std.time.ns_per_s; - const a = try replica.Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty, .addons = kinds }, host.host(), true); - defer a.deinit(); - host.core = a.core; - var screens: replica.Screens = .init(gpa); - defer screens.deinit(a.core); - for (&paths) |*path| { - var line: [300]u8 = undefined; - _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{std.mem.sliceTo(path, 0)}) }); - } - // The picture and the PDF in a column of their own: every client joins - // with them (a plain kind's pane loaded from a dump, its file read by - // its path), its keys go to the one it is in when it has them. - if (looks.len > 3) { - _ = try a.local(.{ .command = "Newcol" }); - _ = try a.local(.{ .command = looks[3] }); - } - if (with_pdf) _ = try a.local(.{ .command = looks[4] }); - const shell: u8 = for (a.core.panes, 0..) |slot, id| { - if (slot) |pane| if (pane.isTerminal()) break @intCast(id); - } else return error.NoShell; - // Where a wheel over the shell lands in the session's view, which a - // client's view is a copy of as it joins; and the PDF's body there. - const sr = a.core.view().rects[shell]; - const pr = if (with_pdf) a.core.view().rects[a.core.view().active] else pardes.Rect{}; - const aim: Aim = .{ - .shell = if (sr.h > 2) .{ sr.x + sr.w / 2, sr.y + sr.h / 2 } else null, - .pdf = if (pr.h > 4 and pr.w > 8) .{ pr.x + 4, pr.y + 2, pr.w - 8, pr.h - 4 } else null, - }; var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 }; - defer { - while (net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); - net.q.deinit(gpa); - } + defer net.q.deinit(gpa); pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; Draws.net = &net; defer { pardes.Kind.drawer = null; Draws.net = null; - for (Draws.jobs.items) |j| j.drop(); - Draws.jobs.clearRetainingCapacity(); } - // The clients: terminals and windows by turns. The first two dial at - // once, the third late (the shell's program on), more later still - // (refused while every view is taken, dialling again until one is - // let go); the first leaves when it is done; the second is put off - // the session once (PARDES_TEST_DIVERGE) and joins again for its view. var clients: [8]Client = undefined; for (clients[0..r.clients], 0..) |*cl, c| { cl.* = .{ .kind = if (c % 2 == 0) .tty else .window, .left = r.steps, .cols = @intCast(random.intRangeAtMost(u16, 60, 120)), .rows = @intCast(random.intRangeAtMost(u16, 16, 40)) }; - if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &cl.fds) != 0) return error.NoSocket; - _ = libc.fcntl(cl.fds[0], libc.F.SETFL, @as(c_int, @bitCast(libc.O{ .NONBLOCK = true }))); var name: [300]u8 = undefined; cl.check = try gpa.dupeSentinel(u8, try std.fmt.bufPrint(&name, "{s}/check-{d}", .{ dir, c }), 0); _ = libc.unlink(cl.check); - cl.dialling = true; - const at: u64 = switch (c) { - 0, 1 => random.uintLessThan(u64, 100_000), - 2 => 1_200_000, - else => 2_000_000 + c * 100_000, - }; - try net.send(.{ .at = at, .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } - defer for (clients[0..r.clients]) |*cl| { - if (cl.r) |rp| rp.deinit(); - _ = libc.close(cl.fds[0]); - _ = libc.close(cl.fds[1]); - cl.got.deinit(gpa); - cl.stamp.deinit(gpa); - gpa.free(cl.check); - }; - // The link is made at the first join (its replica the dump's). - var has_link: [8]bool = @splat(false); - defer for (clients[0..r.clients], has_link[0..r.clients]) |*cl, made| if (made) { - cl.loop.link.check = null; - cl.loop.link.deinit(gpa); - }; // What the shell's program prints: a full-screen program, a shell's // session (prompts, titles, directories, a clear now and then), then a @@ -856,472 +1565,24 @@ fn run(r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(shell_session); const yes = try screen_state.yesStream(gpa, @intCast(r.flood_mb * (1 << 20) / 3)); defer gpa.free(yes); - const tui_at: u64 = 400_000; - const session_at: u64 = 1_000_000; - const flood_at: u64 = 2_500_000; - var flood_end: u64 = 0; - var program: struct { bytes: []const u8 = &.{}, at: usize = 0 } = .{}; - // The authority's version of each terminal, as its screen showed then. - var versions: std.AutoHashMapUnmanaged(u64, u64) = .empty; - defer versions.deinit(gpa); - var flood_deltas: [8]u64 = @splat(0); - - // The session's own typist, and every client's, until each is done. - var own_left = r.steps; - var own_script: Script = .{}; - var typing: usize = r.clients + 1; - var next_id: u16 = 1; - try net.send(.{ .at = random.uintLessThan(u64, 200_000), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }); - try net.send(.{ .at = tui_at, .n = 0, .kind = .output, .who = 0, .bytes = &.{} }); - try net.send(.{ .at = session_at, .n = 0, .kind = .output, .who = 2, .bytes = &.{} }); - try net.send(.{ .at = flood_at, .n = 0, .kind = .output, .who = 1, .bytes = &.{} }); - try net.send(.{ .at = frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); - var frames_left: u32 = 0; - - var owed: std.ArrayListUnmanaged([]u8) = .empty; - defer owed.deinit(gpa); - const Session = struct { - a: *replica.Authority, - screens: *replica.Screens, - clients: []Client, - net: *Net, - owed: *std.ArrayListUnmanaged([]u8), - versions: *std.AutoHashMapUnmanaged(u64, u64), - totals: *Totals, - host: *Host, - kinds_seen: *u32, - - /// A Detach its step took (Host.detach) in a client's view: that - /// client's link shut inside the step, before its unit goes - /// (Peers.detach), so it hears its end and not the unit; which it is. - fn detaching(s: @This(), now: u64) !?usize { - const k = s.host.detach_view orelse return null; - s.host.detach_view = null; - for (s.clients, 0..) |*cl, c| if (cl.joined and cl.view == k) { - cl.joined = false; - s.screens.dropPeer(cl.sid); - try s.net.toClient(c, now, .gone, cl.gen, &.{}); - return c; - }; - return null; - } - - /// ...and let go at the next boundary, its view closed (Peers.leave). - fn detached(s: @This(), c: ?usize, now: u64) !void { - const gone = c orelse return; - try s.unit(try s.a.leave(s.clients[gone].id, false), now, false); - } - - /// The batch of its own steps as a unit, if any (`Authority.pending`). - fn pending(s: @This(), now: u64, flooding: bool) !void { - if (try s.a.pending()) |batch| try s.unit(batch, now, flooding); - } - - /// A unit to every client joined (Peers.unit), after the rows of - /// its terminals its steps read that a client holds as holes. - fn unit(s: @This(), u: []const u8, now: u64, flooding: bool) !void { - // The kinds' panes it has opened, each counted once. - for (s.a.core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen.*) { - s.kinds_seen.* = pane.serial; - for ([_][]const u8{ "image", "life", "pdf" }, &s.totals.kind_panes) |name, *n| n.* += @intFromBool(k.is(name)); - }; - var rows: std.ArrayListUnmanaged([]u8) = .empty; - defer rows.deinit(gpa); - for (s.clients, 0..) |*cl, c| if (cl.joined) { - rows.clearRetainingCapacity(); - try s.screens.fill(s.a.core, cl.sid, &rows); - for (rows.items) |bytes| { - s.totals.filled_bytes += bytes.len; - try s.net.toClient(c, now, .screen_down, cl.gen, bytes); - } - }; - s.screens.filled(s.a.core); - // The sizes its steps gave terminals, after their rows. - pardes.panes.resizeDeferred(s.a.core); - for (s.clients, 0..) |*cl, c| if (cl.joined) { - s.totals.unit_bytes += u.len; - if (flooding) s.totals.flood_unit_bytes += u.len; - try s.net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, u)); - }; - } - /// What each client is owed of the terminals (`Screens.flush`). - fn flush(s: @This(), now: u64, only: ?usize) !void { - for (s.clients, 0..) |*cl, c| if (cl.joined and (only == null or only.? == c)) { - s.owed.clearRetainingCapacity(); - try s.screens.flush(s.a.core, cl.sid, 0, s.owed); - for (s.owed.items) |bytes| { - s.totals.deltas += 1; - s.totals.delta_bytes += bytes.len; - try s.net.toClient(c, now, .screen_down, cl.gen, bytes); - } - }; - // Each version as the authority's screen showed it. - for (&s.screens.tracks, 0..) |*slot, id| if (slot.*) |*tr| { - const key = @as(u64, tr.serial) << 32 | trackOf(tr.track).version; - if (trackOf(tr.track).version == 0 or s.versions.contains(key)) continue; - _ = s.a.core.panes[id] orelse continue; - try s.versions.put(gpa, key, screenHash(&pardes.Term.emulatorOf(tr.state).vt)); - }; - } + var soak: Soak = .{ + .r = r, + .totals = totals, + .random = random, + .net = &net, + .clients = clients[0..r.clients], + .looks = looks_buf[0..nlooks], + .with_pdf = with_pdf, + .tui = tui, + .shell_session = shell_session, + .yes = yes, + .own_left = r.steps, + .typing = r.clients + 1, }; - var kinds_seen: u32 = 0; - - const ses: Session = .{ .a = a, .screens = &screens, .clients = clients[0..r.clients], .net = &net, .owed = &owed, .versions = &versions, .totals = totals, .host = &host, .kinds_seen = &kinds_seen }; - - while (net.q.pop()) |m| { - defer if (m.bytes.len > 0) gpa.free(m.bytes); - Draws.now = m.at; - const flooding = m.at >= flood_at and flood_end == 0; - // A client's message, but an echo's and an output's `who` (a pane, - // a program). - const c: usize = if (m.who == 0 or m.kind == .echo or m.kind == .output) 0 else m.who - 1; - const cl = &clients[c]; - switch (m.kind) { - // ---- the session ---- - .own => { - host.now_ns = std.time.ns_per_s + m.at * 1000; - var buf: [64]u8 = undefined; - const ev = nextEvent(random, &buf, aim, looks, &own_script); - try ses.pending(m.at, flooding); - try ses.flush(m.at, null); - const u = try a.own(ev); - // Its own view's Detach is its terminal's: none here. - host.detach_view = null; - try ses.unit(u, m.at, false); - try ses.flush(m.at, null); - for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); - host.echo.clearRetainingCapacity(); - own_left -= 1; - if (own_left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .own, .who = 0, .bytes = &.{} }) else typing -= 1; - }, - .to_authority, .echo, .output => { - // A pty's read wakes its loop as an input does; a client's - // mail alone leaves the clock where it was. - if (m.kind != .to_authority) host.now_ns = std.time.ns_per_s + m.at * 1000; - const unit = switch (m.kind) { - .echo => echo: { - a.output(.{ .output = .{ .pane = @intCast(m.who), .bytes = m.bytes } }); - break :echo null; - }, - .output => out: { - // The program's next read, 4 KB, then the next a - // fraction of a millisecond on (ghostty's pace). - if (program.at == program.bytes.len) { - program = .{ .bytes = switch (m.who) { - 0 => tui, - 1 => yes, - else => shell_session, - } }; - } - const k = @min(program.bytes.len - program.at, if (m.who == 1) @as(usize, 4096) else 700); - const chunk = program.bytes[program.at..][0..k]; - program.at += k; - if (program.at < program.bytes.len) - try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) - else if (m.who == 1) flood_end = m.at; - a.output(.{ .output = .{ .pane = shell, .bytes = chunk } }); - break :out null; - }, - else => in: { - if (!cl.joined or m.gen != cl.gen) break :in null; - // The authority's own steps since the last unit, and - // the terminals as they are: what the input's step - // reads, before it is stepped (Peers.input). - try ses.pending(m.at, flooding); - try ses.flush(m.at, null); - break :in try a.take(m.bytes); - }, - }; - if (unit) |u| { - const gone = try ses.detaching(m.at); - try ses.unit(u, m.at, false); - try ses.detached(gone, m.at); - try ses.flush(m.at, null); - } - for (host.echo.items) |e| try net.send(.{ .at = m.at + 2_000, .n = 0, .kind = .echo, .who = e.pane, .bytes = e.bytes }); - host.echo.clearRetainingCapacity(); - }, - .frame => { - // Its own frontend's frame: its loop woken when a frame is - // owed or the core's next wake is due, a pump that advances - // its clock (what is due ticks: messages, glides, a kind's - // tick) and draws its view, as its host's loop paces it. - host.now_ns = std.time.ns_per_s + m.at * 1000; - if (a.core.needs_frame or (a.core.nextWake() orelse std.math.maxInt(u64)) <= host.now_ns) { - host.draws = true; - a.pump(); - host.draws = false; - } - try ses.pending(m.at, flooding); - const t0 = screens.encode_ns; - const before = totals.delta_bytes; - try ses.flush(m.at, null); - if (m.at >= flood_at and (flood_end == 0 or m.at <= flood_end)) { - totals.flood_delta_bytes += totals.delta_bytes - before; - try totals.frame_ns.append(gpa, screens.encode_ns - t0); - } - // Frames go on while anyone types or the flood runs, and two - // seconds after (a session with a clock wakes on: a blink, a - // kind's tick; what is in flight still comes, unpumped). - const busy = typing > 0 or flood_end == 0; - frames_left = if (busy) 120 else frames_left -| 1; - if (frames_left > 0) try net.send(.{ .at = m.at + frame_us, .n = 0, .kind = .frame, .who = 0, .bytes = &.{} }); - }, - .dial => { - // Peers.join at the session's next boundary: its view kept - // for it, or a new one, or refused when all are taken. - try ses.pending(m.at, flooding); - const id = next_id; - const j = (try a.join(id, cl.back)) orelse { - totals.refused += 1; - try net.toClient(c, m.at, .refused, cl.gen, &.{}); - continue; - }; - next_id += 1; - try ses.unit(j.unit, m.at, false); - cl.joined = true; - cl.gen += 1; - cl.id = id; - cl.seq = 0; - cl.view = j.view; - cl.digest = j.digest; - cl.sid = try screens.addPeer(); - totals.joins += 1; - try net.toClient(c, m.at, .dump, cl.gen, j.dump); - // Its terminals afresh, after its dump and before any unit. - try ses.flush(m.at, c); - }, - .check_up => { - if (!cl.joined or m.gen != cl.gen) continue; - try ses.pending(m.at, flooding); - const d = try gpa.alloc(u8, 8); - std.mem.writeInt(u64, d[0..8], replica.digestOf(a), .little); - try net.toClient(c, m.at, .checked, cl.gen, d); - }, - .bye_up => { - // Peers.leave: its view kept for it (`again`) or closed. - if (!cl.joined or m.gen != cl.gen) continue; - try ses.pending(m.at, flooding); - cl.joined = false; - screens.dropPeer(cl.sid); - try ses.unit(try a.leave(cl.id, m.seq != 0), m.at, false); - }, - .screen_up => { - if (!cl.joined or m.gen != cl.gen) continue; - if (m.bytes[5] == 2) totals.fetched += std.mem.readInt(u64, m.bytes[14..22], .little) - std.mem.readInt(u64, m.bytes[6..14], .little); - if (try screens.take(a.core, cl.sid, m.bytes)) |answer| try net.toClient(c, m.at, .screen_down, cl.gen, answer); - }, - // ---- a client ---- - .refused => { - if (!cl.dialling) continue; - // Said and gone; started again a while later (a person - // does), while it has keys left to type. - cl.back = null; - if (cl.r) |old| { - try totals.add(&old.stats); - old.deinit(); - cl.r = null; - } - cl.tries += 1; - if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { - // Given up on: its keys are never typed. - cl.dialling = false; - if (cl.left > 0) typing -= 1; - cl.left = 0; - } - }, - .dump => { - cl.dialling = false; - cl.tries = 0; - // replica.join: the core it left let go once the new one - // is here, the dump loaded and checked by the digest. - if (cl.r) |old| { - try totals.add(&old.stats); - old.deinit(); - } - const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); - cl.r = rp; - rp.stats.samples = true; - rp.t.local_files = true; - rp.echo.now = m.at * 1000; - if (!rp.loaded(cl.digest)) { - totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s dump loaded as another session\n", .{ r.seed, r.rtt_ms, m.who }); - } - cl.live = m.gen; - var j: replica.Joined = .{ .fd = cl.fds[1], .pid = 0, .client = cl.id, .view = cl.view, .gmtoff = 0, .dump = &.{} }; - if (!has_link[c]) { - cl.loop = .{ .link = .{ .r = rp, .fd = cl.fds[1], .check = cl.check }, .fe = cl, .frames = &cl.frames }; - has_link[c] = true; - if (c == 1) cl.loop.link.test_diverge = 40; - } - cl.c = c; - cl.net = &net; - cl.now = m.at; - cl.wake_at = 0; - cl.stops = rp.stats.stops; - cl.loop.link.now = m.at * 1000; - cl.loop.link.reset(rp, &j); - cl.posted = null; - // The loop's join (Loop.run): its first inputs, then a pass - // up to its wait. - cl.start(&cl.loop); - _ = cl.loop.pass(); - judgeStops(cl, c, totals, r); - try drain(cl, c, &net, m.at); - if (cl.left > 0 and cl.left == r.steps) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); - }, - .draw => { - // A worker's draw done, onto the loop of the core that asked - // it (tui.zig `.kind_job`): kept for its pane's next paint, - // a frame owed; one of a core gone since is let go. - const j = Draws.jobs.orderedRemove(0); - j.run(); - // A state job's answer: a step of the session's own. - if (j.draw == null) { - host.now_ns = std.time.ns_per_s + m.at * 1000; - a.output(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } }); - j.drop(); - continue; - } - if (j.draw == @as(?*const pardes.Pardes, a.core)) { - pardes.Kind.landDraw(a.core, j); - continue; - } - const k = for (clients[0..r.clients], 0..) |*dc, k| { - if (dc.r) |rp| if (j.draw == @as(?*const pardes.Pardes, rp.core())) break k; - } else { - j.drop(); - continue; - }; - const dc = &clients[k]; - pardes.Kind.landDraw(dc.r.?.core(), j); - dc.loop.link.dirty = true; - try woke(dc, k, &net, m.at, totals, r); - if (dc.loop.link.quit) try ended(dc, k, &net, m.at, totals, r, &typing); - }, - .input, .to_replica, .screen_down, .checked, .wake, .quit, .gone => { - if (m.kind == .input and cl.left == 0) continue; - const rp = cl.r orelse if (m.kind == .input and cl.dialling) { - try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); - continue; - } else continue; - if (m.kind == .input) { - // A key typed while it joins again waits for the link. - if (cl.live == 0) { - try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); - continue; - } - } else if (m.kind != .quit and m.gen != cl.live) continue; - rp.echo.now = m.at * 1000; - cl.now = m.at; - cl.loop.link.now = m.at * 1000; - switch (m.kind) { - .input => { - var buf: [64]u8 = undefined; - const ev = nextEvent(random, &buf, aim, looks, &cl.script); - cl.loop.input(ev); - cl.left -= 1; - if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { - typing -= 1; - // The first leaves once it is done. - if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); - } - }, - .to_replica => cl.loop.take(.{ .unit = try gpa.dupe(u8, m.bytes) }), - .screen_down => { - const pane = m.bytes[0]; - const was = if (rp.screens[pane]) |sc| replicaOf(sc.rep).seq else 0; - cl.loop.take(.{ .screen = try gpa.dupe(u8, m.bytes) }); - if (m.bytes[5] == 1) if (rp.screens[pane]) |sc| { - const now_seq = replicaOf(sc.rep).seq; - if (now_seq == was) totals.resets += 1 else { - // Applied: the screen is the authority's at that version. - totals.screens_checked += 1; - const want = versions.get(@as(u64, sc.serial) << 32 | now_seq); - const vt = &pardes.Term.emulatorOf(rp.core().panes[pane].?.terminal.?).vt; - if (want == null or want.? != screenHash(vt)) { - totals.screens_wrong += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at version {d} is not the authority's\n", .{ r.seed, r.rtt_ms, m.who, pane, now_seq }); - } - // Deltas while the flood runs (an RTT/2 behind it). - if (m.at >= flood_at + net.one_way and (flood_end == 0 or m.at <= flood_end + net.one_way)) flood_deltas[c] += 1; - } - }; - }, - .checked => cl.loop.take(.{ .checked = std.mem.readInt(u64, m.bytes[0..8], .little) }), - .wake => { - // One the next replaced is no wake. - if (m.at != cl.wake_at) continue; - cl.wake_at = 0; - }, - .quit => cl.loop.link.quit = true, - .gone => { - cl.loop.link.quit = true; - cl.loop.link.gone = true; - }, - else => unreachable, - } - try woke(cl, c, &net, m.at, totals, r); - if (cl.loop.link.quit) try ended(cl, c, &net, m.at, totals, r, &typing); - }, - .client_frame => {}, - } - } - totals.flood_us += flood_end -| flood_at; - for (flood_deltas[0..r.clients]) |d| totals.flood_deltas += d; - const want = replica.digestOf(a); - for (clients[0..r.clients], 1..) |*cl, id| { - totals.resizes += cl.resizes; - totals.wakes += cl.wakes; - for (&totals.asked, cl.asked) |*t, n| t.* += n; - if (has_link[id - 1]) totals.draws += cl.loop.link.draws; - // Its quiet checks: what the session's digest was against its own. - if (readAll(cl.check)) |said| { - defer gpa.free(said); - var lines = std.mem.tokenizeScalar(u8, said, '\n'); - while (lines.next()) |line| if (std.mem.startsWith(u8, line, "agree")) { - totals.agree += 1; - } else { - totals.differ += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s quiet check: {s}\n", .{ r.seed, r.rtt_ms, id, line }); - }; - } - const rp = cl.r orelse continue; - try totals.add(&rp.stats); - if (cl.live == 0) continue; - if (rp.diverged) |why| { - totals.divergences += 1; - std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ r.seed, r.rtt_ms, id, why }); - } else if (!rp.quiet() or rp.digest() != want) { - totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: client {d} at quiescence: {s}\n", .{ r.seed, r.rtt_ms, id, if (rp.quiet()) "another digest" else "inputs still pending" }); - } - // At quiescence, every terminal the authority's, cell for cell. - for (a.core.panes, 0..) |slot, pid| { - const pane = slot orelse continue; - const state = pane.terminal orelse continue; - const mine = (rp.core().panes[pid] orelse { - totals.unequal += 1; - continue; - }).terminal orelse continue; - if (screenHash(&pardes.Term.emulatorOf(state).vt) != screenHash(&pardes.Term.emulatorOf(mine).vt)) { - totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s terminal {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); - } - } - // ...and every file's text the authority's, byte for byte: a digest - // takes a text of 4 KiB and up by its length (core/walk.zig). - for (a.core.panes, 0..) |slot, pid| { - const f = (slot orelse continue).file orelse continue; - const mine = if (rp.core().panes[pid]) |pane| pane.file else null; - if (mine == null or !std.mem.eql(u8, f.content, mine.?.content)) { - totals.unequal += 1; - std.debug.print("seed {d} rtt {d} ms: client {d}'s text {d} at quiescence is not the authority's\n", .{ r.seed, r.rtt_ms, id, pid }); - } - } - } + // The session: THE session loop, from its start to its end. + try SessionLoop.run(init, .{ .cols = 100, .rows = 30, .boot = .tty }, &soak); + if (soak.err) |err| return err; } /// A typist: keys 50-200 ms apart, a pause now and then. @@ -2169,7 +2430,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .screen_up => { if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); }, - .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob => {}, } } const s = rp.echo.stats; @@ -2486,6 +2747,9 @@ pub fn main(init: std.process.Init) !void { const tmp = std.mem.span(libc.getenv("TMPDIR") orelse "/tmp"); const dir = try std.fmt.bufPrint(&dir_buf, "{s}/replicas-{d}", .{ tmp, @as(u32, @intCast(libc.getpid())) }); try std.Io.Dir.createDirAbsolute(init.io, dir, .default_dir); + // Its session's socket goes there: a directory of its own alone. + var dir_z: [256]u8 = undefined; + _ = libc.chmod(try std.fmt.bufPrintSentinel(&dir_z, "{s}", .{dir}, 0), 0o700); defer std.Io.Dir.cwd().deleteTree(init.io, dir) catch {}; // Its own data directory, the only one its addon scan reads (never the // user's): the libraries it was given (`--addon`), as a user's are @@ -2510,6 +2774,10 @@ pub fn main(init: std.process.Init) !void { var failed = !try diffCase(dir); if (!try plumbCase(dir)) failed = true; if (!try corpusCase(dir)) failed = true; + // ...and its own runtime directory: its session's 9P socket and prompt + // files (runtime/session.zig opens them), never the user's. + var runtime_buf: [300]u8 = undefined; + if (setenv("XDG_RUNTIME_DIR", try std.fmt.bufPrintSentinel(&runtime_buf, "{s}", .{dir}, 0), 1) != 0) return error.NoRuntimeDir; std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); std.debug.print(" rtt inputs at-once stopped units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{}); var term_lines: std.ArrayList(u8) = .empty; @@ -2520,7 +2788,7 @@ pub fn main(init: std.process.Init) !void { defer stop_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; - for (first..first + seeds) |seed| try run(.{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); + for (first..first + seeds) |seed| try run(init, .{ .seed = seed, .rtt_ms = rtt, .steps = steps, .clients = clients, .flood_mb = flood_mb }, dir, &t); const rollbacks = t.mispredicted + t.foreign; std.debug.print("{d:>4} {d:>6} {d:>7} {d:>7} {d:>6} {d:>6} {d:>6} ({d}+{d}) {d:>5.1}% {d:>6} {d:>5}/{d:<6} {d:>5}/{d:<5} ({d}) {d:>7}/{d:<7} {d:>8} {d:>7}\n", .{ rtt, t.inputs, t.speculated, |
