diff options
Diffstat (limited to 'src/tty/tty.zig')
| -rw-r--r-- | src/tty/tty.zig | 311 |
1 files changed, 48 insertions, 263 deletions
diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 2007c6f7..a1a28181 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -156,14 +156,8 @@ pub const Command = struct { replica: posix.fd_t, /// A replica's reader posted: the step boundary takes it in. replica_mail, - /// A replica client's: what the session streamed (replica.Client). - unit: []u8, - /// ...a terminal's delta or rows, before the units after it. - screen: []u8, - /// ...why it let this client go (an Upgrade's exec), the stream's end. - refused: []u8, - /// The session's digest, asked by PARDES_REPLICA_CHECK. - checked: u64, + /// A replica client's: what the session streamed (replica.Link). + said: replica.Said, link_gone, } = .nop; }; @@ -1274,191 +1268,42 @@ pub fn run(init: std.process.Init, opts: pardes.Options, term: Term) !void { try localSession(init, opts, &screen, &loop, &paste_buf); } -/// A replica client's link to its session (`remote`). +/// A replica client's link to its session (`remote`), drawn here. const Remote = struct { - r: *replica.Replica, - fd: posix.fd_t, - quit: bool = false, - /// The session hung up. - gone: bool = false, - /// Something to draw: an input applied, a unit taken. - dirty: bool = true, - /// The last frame was held for the terminal's answer (FrameAck). - owed: bool = false, - /// PARDES_REPLICA_CHECK=<file>: once quiet a while after a change, the - /// session's digest is asked, and whether this replica's agrees is - /// written there, a line a check. - check: ?[:0]const u8 = null, - changed: bool = false, - asked: bool = false, - /// How many of its own inputs the session recorded otherwise when it - /// last drew: a frame after one that writes to the terminal is a - /// rollback that may have been seen (counted so: an upper bound, the - /// frame shows the inputs after it too). - mispredicted: u32 = 0, - visible: u32 = 0, - /// What the session said as it let this client go (owned, the C heap's). - refused: ?[]u8 = null, - /// A line over its frame, until its next key (`notify`): why it joined - /// again. The client's own, never the session's core. - notice_buf: [240]u8 = undefined, - notice_len: usize = 0, - /// PARDES_TEST_DIVERGE=<n>: once quiet after its n-th unit, its core - /// is put off the session's (a digested counter moved), the next unit's - /// digest finds it, and it joins again (test/daemon.py). - test_diverge: u32 = 0, - /// Put off so in this join: its checks are not written (they differ). - put_off: bool = false, - /// How its last join went (replica.Joined's counts), and how long its - /// dial and load took (PARDES_REPLICA_STATS). - join: struct { blobs: u32 = 0, from_memory: u32 = 0, from_disk: u32 = 0, sent_bytes: u64 = 0 } = .{}, - join_ms: u64 = 0, - - /// The replica the dial's dump makes, checked against the session as - /// it was dumped; null, and why in `why`. The dump is let go, a far - /// join's to the thread that keeps the blobs it was sent (`Have.store`). - fn load(gpa: std.mem.Allocator, joined: *replica.Joined, o: pardes.Options, why: []u8, have: ?*replica.Have) ?*replica.Replica { - defer { - if (have) |h| h.store(gpa, joined) else gpa.free(joined.dump); - joined.dump = &.{}; - } - const r = replica.Replica.initDump(gpa, joined.client, joined.view, joined.dump, o) catch |err| { - _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; - return null; - }; - // PARDES_NO_ECHO: no predicted echo (the gates' baseline). - if (std.c.getenv("PARDES_NO_ECHO") != null) r.echo.on = false; - if (!r.loaded(joined.digest)) { - r.deinit(); - _ = std.fmt.bufPrint(why, "the session's dump loaded as another session (a build's dump is not complete)\x00", .{}) catch {}; - return null; - } - return r; - } - - /// A join's link, from its start. - fn reset(c: *Remote, r: *replica.Replica, fd: posix.fd_t) void { - c.r = r; - c.fd = fd; - c.quit = false; - c.gone = false; - c.dirty = true; - c.owed = false; - c.changed = false; - c.asked = false; - c.mispredicted = 0; - c.put_off = false; - } - - fn notify(c: *Remote, comptime fmt: []const u8, args: anytype) void { - const text = std.fmt.bufPrint(&c.notice_buf, fmt, args) catch c.notice_buf[0..]; - for (text) |*b| if (b.* < 0x20 or b.* > 0x7e) { - b.* = '?'; - }; - c.notice_len = text.len; - } - - /// PARDES_REPLICA_STATS=<file>: how its inputs and the session's units - /// went, a line at its end (test/daemon.py, the gates). - fn writeStats(c: *Remote, path: []const u8) void { - const st = &c.r.stats; - var buf: [600]u8 = undefined; - const line = std.fmt.bufPrint(&buf, "inputs {d} at_once {d} stopped {d} units {d} fast {d} neutral {d} mispredicted {d} foreign {d} visible {d} rtt_us {d} spec_us {d}/{d} copy_us {d}/{d} rollback_us {d}/{d} join_ms {d} blobs {d} from_memory {d} from_disk {d} sent_kb {d}\n", .{ - st.inputs, st.speculated, st.stopped, st.units, st.fast, - c.r.neutral, st.mispredicted, st.foreign, c.visible, c.r.rtt_ns / 1000, - pct(st.spec_ns.items, 50) / 1000, pct(st.spec_ns.items, 99) / 1000, pct(st.copy_ns.items, 50) / 1000, pct(st.copy_ns.items, 99) / 1000, pct(st.rollback_ns.items, 50) / 1000, - pct(st.rollback_ns.items, 99) / 1000, c.join_ms, c.join.blobs, c.join.from_memory, c.join.from_disk, - c.join.sent_bytes >> 10, - }) catch return; - var z: [4096]u8 = undefined; - const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return; - const fd = libc.open(pz, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - } - - fn pct(samples: []u64, p: usize) u64 { - if (samples.len == 0) return 0; - std.mem.sort(u64, samples, {}, std.sort.asc(u64)); - return samples[@min(samples.len - 1, samples.len * p / 100)]; - } - - /// The session's digest against this replica's, if it is quiet still. - fn checked(c: *Remote, theirs: u64) void { - c.asked = false; - const path = c.check orelse return; - if (!c.r.quiet() or c.put_off) return; - const mine = c.r.digest(); - var buf: [96]u8 = undefined; - const line = (if (mine == theirs) std.fmt.bufPrint(&buf, "agree {x:0>16}\n", .{mine}) else std.fmt.bufPrint(&buf, "differ {x:0>16} {x:0>16}\n", .{ mine, theirs })) catch return; - const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true, .CLOEXEC = true }, @as(libc.mode_t, 0o644)); - if (fd < 0) return; - _ = libc.write(fd, line.ptr, line.len); - _ = libc.close(fd); - } + link: replica.Link, /// The client's own view drawn on its terminal, outside any step: the /// replica's digest stays the session's (views.drawOne). What the host /// writes in the core as it presents (a frame skipped, one owed) is put /// back, as the frame statistics are this process's. fn draw(c: *Remote, s: *Shell) void { - const core = c.r.core(); + const r = c.link.r; + const core = r.core(); const skipped = core.present_skipped; const needs = core.needs_frame; core.frames.mark_start = pardes.FrameStats.nowNs(); core.frames.mark_update = core.frames.mark_start; - c.r.draw(.{ .ctx = s, .f = Shell.present }); + r.draw(.{ .ctx = s, .f = Shell.present }); core.frames.mark_render = core.frames.mark_update; - if (c.r.stats.mispredicted > c.mispredicted) { - c.mispredicted = c.r.stats.mispredicted; - if (core.frames.bytes > 0) c.visible += 1; - } - c.owed = core.present_skipped; - core.frames.record(pardes.FrameStats.nowNs(), false, c.owed); + const drew = core.frames.bytes > 0; + c.link.owed = core.present_skipped; + core.frames.record(pardes.FrameStats.nowNs(), false, c.link.owed); core.present_skipped = skipped; core.needs_frame = needs; - c.dirty = false; - // The history rows it shows and does not hold (a scroll back), - // asked for: blank until they come. - while (c.r.screenRequest()) |req| if (!replica.sendScreen(c.fd, req)) { - c.quit = true; - break; - }; + c.link.drawn(drew); } }; /// The session's stream, onto the loop: its units, and its end. fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loop: *Loop, done: *std.atomic.Value(bool)) void { defer done.store(true, .release); - const Take = struct { - fn take(l: *Loop, tag: u8, payload: []const u8) bool { - const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; - switch (t) { - .unit => { - const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false; - l.postEvent(.{ .unit = bytes }) catch std.heap.c_allocator.free(bytes); - }, - .check => { - const d = (wire.decodeServer(tag, payload) catch return false).check; - l.postEvent(.{ .checked = d }) catch {}; - }, - .screen => { - const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false; - l.postEvent(.{ .screen = bytes }) catch std.heap.c_allocator.free(bytes); - }, - .refused => { - const words = (wire.decodeServer(tag, payload) catch return false).refused; - const bytes = std.heap.c_allocator.dupe(u8, words) catch return false; - l.postEvent(.{ .refused = bytes }) catch std.heap.c_allocator.free(bytes); - return false; - }, - .pong, .welcome, .dump, .blobs, .zstd => {}, - } + const Post = struct { + fn post(l: *Loop, said: replica.Said) bool { + l.postEvent(.{ .said = said }) catch return false; return true; } }; - replica.readStream(gpa, fd, rest, loop, Take.take); + replica.readLink(gpa, fd, rest, loop, Post.post); loop.postEvent(.link_gone) catch {}; } @@ -1489,7 +1334,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se const have: ?*replica.Have = if (far) &have_store else null; var dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; var joined = replica.dial(gpa, path, session, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); - if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{upgrade_words}); + if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{replica.Link.upgrade_words}); const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); @@ -1504,7 +1349,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se var o = opts; o.image_allocator = allocs.image; o.pdf_allocator = allocs.pdf; - var r = Remote.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + var r = replica.Link.load(gpa, &joined, o, &why, have) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); // Its join's time, the dial and the load (PARDES_REPLICA_STATS). var dial_ms: u64 = @intCast(@divTrunc(std.Io.Clock.awake.now(io).nanoseconds - dial_t0, std.time.ns_per_ms)); @@ -1528,10 +1373,10 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se var loop: Loop = .init(io, &screen.tty, &screen.vx); var frame_arena: std.heap.ArenaAllocator = .init(allocs.frame); defer frame_arena.deinit(); - var link: Remote = .{ .r = r, .fd = joined.fd }; - if (init.environ_map.get("PARDES_REPLICA_CHECK")) |file| link.check = try gpa.dupeSentinel(u8, file, 0); - defer if (link.check) |file| gpa.free(file); - if (init.environ_map.get("PARDES_TEST_DIVERGE")) |n| link.test_diverge = std.fmt.parseInt(u32, n, 10) catch 0; + var remote_link: Remote = .{ .link = .{ .r = r, .fd = joined.fd } }; + const link = &remote_link.link; + try link.fromEnv(gpa, init.environ_map); + defer link.deinit(gpa); var sh: Shell = .{ .io = io, .gpa = gpa, @@ -1543,7 +1388,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se .paste_buf = &paste_buf, .inotify_fd = -1, .from = joined.view, - .remote = &link, + .remote = &remote_link, }; try startInput(&loop, &screen); @@ -1561,18 +1406,18 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se sh.terms[joined.view] = &screen; screen.feed.view = joined.view; link.reset(r, joined.fd); - link.join = .{ .blobs = joined.blobs, .from_memory = joined.from_memory, .from_disk = joined.from_disk, .sent_bytes = joined.sent_bytes }; - link.join_ms = dial_ms; + link.joinedAs(&joined, dial_ms); var reader_done: std.atomic.Value(bool) = .init(false); const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); - // Its size is its view's first input. + // What it is, then its size, are its view's first inputs. + link.input(.{ .frontend = .{ .windowed = false } }); screen.size = null; sh.winched(); screen.vx.queueRefresh(); while (!link.quit) { // Its predicted echo judged and caught up, once a frame. if (r.echoFrame()) link.dirty = true; - if (link.dirty) link.draw(&sh); + if (link.dirty) remote_link.draw(&sh); const first = (loop.tryEvent() catch null) orelse idle: { // Idle, its frame drawn: the next key needs no copy taken. r.ready(); @@ -1596,14 +1441,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se if (link.owed or r.echo.changed) link.dirty = true; // Predictions out: judged a frame at a time while they are. if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms)); - if (link.check != null) { - // Quiet a while after a change: asked once (a wake, then the - // next quiet one). - if (first == .wake and link.changed and !link.asked and r.quiet()) { - link.changed = false; - link.asked = replica.askCheck(joined.fd); - } else if (link.changed and r.quiet()) requestWake(io, 300); - } + if (link.quietCheck()) |ms| requestWake(io, ms); if (r.diverged != null) link.quit = true; } if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); @@ -1616,7 +1454,10 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se while (true) { const ended = reader_done.load(.acquire); while (loop.tryEvent() catch null) |ev| switch (ev) { - .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .said => |said| switch (said) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, + }, .paste => |b| gpa.free(@constCast(b)), else => {}, }; @@ -1627,13 +1468,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se _ = libc.close(joined.fd); joined.rest.deinit(gpa); // Why it joins again, in a line over its frame until a key. - if (r.diverged) |reason| { - link.notify("joined again: this client diverged from the session ({s})", .{reason}); - } else if (link.refused) |words| { - link.notify("joined again: {s}", .{words}); - std.heap.c_allocator.free(words); - link.refused = null; - } else { + if (!link.rejoins()) { // What it made since it joined, kept for its next start. if (have) |h| h.keep(r.core()); r.deinit(); @@ -1644,38 +1479,16 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se return; } // The session again, the core it leaves held meanwhile: its blobs - // are not sent again. An upgrade's takes the time its exec and load - // take, and its daemon's. + // are not sent again. if (have) |h| h.leaving(r.core()); - var tries: u32 = 0; dial_t0 = std.Io.Clock.awake.now(io).nanoseconds; - joined = while (true) : (tries += 1) { - why = @splat(0); - if (replica.dial(gpa, path, session, &why, have)) |j| { - if (j.semantics == wire.semantics) break j; - replica.bye(j.fd); - _ = libc.close(j.fd); - var jj = j; - jj.rest.deinit(gpa); - gpa.free(j.dump); - screen.leave(); - Said.no(io, "{s}", .{upgrade_words}); - } - const words = std.mem.sliceTo(&why, 0); - if (std.mem.indexOf(u8, words, "runs another build") != null) { - screen.leave(); - Said.no(io, "{s}", .{upgrade_words}); - } - if (tries > 200) { - screen.leave(); - Said.no(io, "{s}", .{words}); - } - const ts: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; - _ = libc.nanosleep(&ts, null); + joined = replica.Link.redial(gpa, path, session, &why, have) orelse { + screen.leave(); + Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); }; if (have) |h| h.left(); r.deinit(); - r = Remote.load(gpa, &joined, o, &why, have) orelse { + r = replica.Link.load(gpa, &joined, o, &why, have) orelse { screen.leave(); Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); }; @@ -1683,7 +1496,6 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se } } -const upgrade_words = "session upgraded to a newer pardes: upgrade this client too"; /// A terminal a session draws on, while it has one: entered (raw, the /// alternate screen, mouse and paste reports) and left (all of it put back, @@ -2191,11 +2003,7 @@ const Shell = struct { /// (applied at once there, and sent to the session). fn feed(s: *Shell, ev: pardes.Event) void { const c = s.remote orelse return s.core.update(ev); - // Its notice read: a key of its own puts it away. - if (c.notice_len > 0 and (ev == .key or ev == .paste)) c.notice_len = 0; - const msg = c.r.input(ev) catch return; - if (!replica.sendInput(c.fd, msg)) c.quit = true; - c.dirty = true; + c.link.input(ev); } /// Whether a terminal of this process's shows the session, or @@ -2800,7 +2608,7 @@ const Shell = struct { }, .quit => { if (s.remote) |c| { - c.quit = true; + c.link.quit = true; return true; } // One of several: its view goes with it. @@ -2827,39 +2635,16 @@ const Shell = struct { s.input_seen = true; }, .replica_mail => s.input_seen = true, - .unit => |bytes| { - if (s.remote) |c| { - c.r.confirm(bytes); - if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) { - c.test_diverge = 0; - c.put_off = true; - c.r.core().next_serial +%= 1000; - } - if (c.r.moved) c.dirty = true; - c.r.moved = false; - c.changed = true; - } - std.heap.c_allocator.free(bytes); - }, - .screen => |bytes| { - if (s.remote) |c| { - if (c.r.screen(bytes)) |reply| if (!replica.sendScreen(c.fd, reply)) { - c.quit = true; - }; - c.dirty = true; - } - std.heap.c_allocator.free(bytes); + .said => |said| if (s.remote) |c| { + c.link.take(said); + if (said == .refused) return true; + } else switch (said) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .checked => {}, }, - .checked => |d| if (s.remote) |c| c.checked(d), - .refused => |words| if (s.remote) |c| { - if (c.refused) |old| std.heap.c_allocator.free(old); - c.refused = words; - c.quit = true; - return true; - } else std.heap.c_allocator.free(words), .link_gone => if (s.remote) |c| { - c.quit = true; - c.gone = true; + c.link.quit = true; + c.link.gone = true; return true; }, .focus_in => s.feed(.{ .focus = true }), @@ -3055,7 +2840,7 @@ const Shell = struct { const flashed = sc.flash.apply(s.frame.allocator(), shadowed, s.core, truecolor) catch shadowed; const trailed = sc.trail.apply(s.frame.allocator(), flashed, s.core, truecolor) catch flashed; paintCells(win, trailed.cells, trailed.cols, trailed.rows); - if (s.remote) |c| if (c.notice_len > 0) noticeLine(win, c.notice_buf[0..c.notice_len], trailed.cols, trailed.rows); + if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), trailed.cols, trailed.rows); tz_cells.end(); for (surface.images[0..surface.nimages]) |maybe| { const place = maybe orelse continue; |
