diff options
| -rw-r--r-- | src/detached/wire.zig | 6 | ||||
| -rw-r--r-- | src/host_io.zig | 3 | ||||
| -rw-r--r-- | src/pardes.zig | 8 | ||||
| -rw-r--r-- | src/replica.zig | 36 | ||||
| -rw-r--r-- | src/tty/tty.zig | 305 | ||||
| -rw-r--r-- | src/upgrade.zig | 15 | ||||
| -rw-r--r-- | test/daemon.py | 56 |
7 files changed, 332 insertions, 97 deletions
diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 347d45d1..78f6e76e 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -134,7 +134,7 @@ pub const ServerMsg = union(ServerTag) { /// Who the client is now (its id and view in the session), how long the /// dump that follows is, and the session's offset from UTC (a replica /// guesses the session's time of day). - welcome: struct { pid: u32, session: []const u8, client: u16 = 0, view: u8 = 0, dump_len: u64 = 0, gmtoff: i32 = 0, digest: u64 = 0 }, + welcome: struct { pid: u32, session: []const u8, client: u16 = 0, view: u8 = 0, dump_len: u64 = 0, gmtoff: i32 = 0, digest: u64 = 0, semantics: u64 = 0 }, refused: []const u8, pong: u64, dump: []const u8, @@ -164,6 +164,7 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { .dump_len = try r.takeInt(u64, .little), .gmtoff = try r.takeInt(i32, .little), .digest = try r.takeInt(u64, .little), + .semantics = try r.takeInt(u64, .little), } }, .refused => .{ .refused = try r.take(try r.takeInt(u16, .little)) }, .pong => .{ .pong = try r.takeInt(u64, .little) }, @@ -188,6 +189,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { try w.writeInt(u64, h.dump_len, .little); try w.writeInt(i32, h.gmtoff, .little); try w.writeInt(u64, h.digest, .little); + try w.writeInt(u64, h.semantics, .little); }, .refused => |words| try putSlice16(&w, words), .pong => |v| try w.writeInt(u64, v, .little), @@ -620,7 +622,7 @@ test "detached wire: every Event variant round-trips" { const bytes = try encodeServer(&buf, .{ .welcome = .{ .pid = 42, .session = "work" } }); const f = (try framed(bytes)).?; try testing.expectEqual(@as(u8, 0x01), f.tag); - try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, f.payload); + try testing.expectEqualSlices(u8, &.{ 42, 0, 0, 0, 4, 0, 'w', 'o', 'r', 'k', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, f.payload); const back = (try decodeServer(f.tag, f.payload)).welcome; try testing.expectEqualStrings("work", back.session); try testing.expectEqual(@as(u32, 42), back.pid); diff --git a/src/host_io.zig b/src/host_io.zig index c627d4ab..b1ed8b4b 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -32,6 +32,9 @@ pub const Host = struct { /// Upgrade: this process exec'd as the pardes installed since, at /// the step's end (upgrade.zig); `pane` hears why if it cannot be. upgrade: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null, + /// Whether a newer pardes is installed at the path this process + /// started from, to be said once (upgrade.zig): asked at a focus-in. + newer_build: ?*const fn (ctx: ?*anyopaque) bool = null, spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null, pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null, pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null, diff --git a/src/pardes.zig b/src/pardes.zig index cc55d695..6e01f8cd 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3670,6 +3670,9 @@ pub const CellPixels = if (pdf_enabled) struct { h: u16 = 16, } else struct {}; +/// Said at a focus-in when the Host's `newer_build` answers yes (upgrade.zig). +pub const newer_build_words = "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"; + pub const Event = union(enum) { key: Key, mouse: Mouse, @@ -6338,7 +6341,10 @@ pub const Pardes = struct { .command => |line| _ = p.executeBuiltinLine(p.active, line), .pinch => |scale| p.ov_pinch_scale = scale, .touch_scroll => |delta| p.ov_touch_scroll_delta = delta, - .focus => |focused| p.window_focused = focused, + .focus => |focused| { + p.window_focused = focused; + if (focused) if (p.host.vtable.newer_build) |f| if (f(p.host.ctx)) p.setMessage(p.active, newer_build_words); + }, .handed => |h| p.handover.finish(p, h.seq, h.to, h.failure), .pointer_leave => { p.pointer_inside = false; diff --git a/src/replica.zig b/src/replica.zig index 7bf0574f..95135307 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -1140,6 +1140,8 @@ pub const Peer = struct { limit: usize = 64 << 20, closing: bool = false, cut: bool = false, + /// Its writer has ended (what it was sent, written). + done: std.atomic.Value(bool) = .init(false), /// `parts` queued for it, in order; never waits. A client whose queue /// passes its limit is cut off: its link is shut down, and its reader @@ -1169,6 +1171,7 @@ pub const Peer = struct { fn writeLoop(peer: *Peer) void { const io = peer.peers.io; + defer peer.done.store(true, .release); while (true) { peer.lock.lockUncancelable(io); while (peer.out.items.len == 0 and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); @@ -1457,7 +1460,7 @@ pub const Peers = struct { var out: [wire.hello_max + 64]u8 = undefined; // The session's digest as dumped, for the joiner to check its load by. const digest = tape.digestOf(core); - const welcome = wire.encodeServer(&out, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = k, .dump_len = bytes.len, .gmtoff = gmtoff(), .digest = digest } }) catch unreachable; + const welcome = wire.encodeServer(&out, .{ .welcome = .{ .pid = @intCast(libc.getpid()), .session = ps.name[0..@min(ps.name.len, wire.max_name)], .client = peer.id, .view = k, .dump_len = bytes.len, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics } }) catch unreachable; peer.send(&.{welcome}); var at: usize = 0; while (at < bytes.len) : (at += dump_piece) { @@ -1535,6 +1538,33 @@ pub const Peers = struct { ps.gpa.destroy(peer); } + /// Every client told `why` and let go, its view with it: an Upgrade's + /// exec is next (tty.zig `upgradeNow`). What each was sent goes first, + /// for up to 200 ms; a client then dials the session again. + pub fn refuseAll(ps: *Peers, core: *Pardes, why: []const u8) void { + if (ps.count() == 0) return; + var out: [600]u8 = undefined; + const words = wire.encodeServer(&out, .{ .refused = why }) catch return; + const io = ps.io; + for (ps.list) |slot| if (slot) |peer| { + peer.send(&.{words}); + peer.lock.lockUncancelable(io); + peer.closing = true; + peer.cond.signal(io); + peer.lock.unlock(io); + }; + const until = nowNs() + 200 * std.time.ns_per_ms; + while (nowNs() < until) { + const busy = for (ps.list) |slot| { + if (slot) |peer| if (!peer.done.load(.acquire)) break true; + } else false; + if (!busy) break; + const ts: libc.timespec = .{ .sec = 0, .nsec = 2 * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + ps.dropAll(core); + } + /// Detach typed in client view `k`'s: its link ends (its reader says /// it is gone, and the next boundary lets it go). pub fn detach(ps: *Peers, k: u8) bool { @@ -1612,6 +1642,9 @@ pub const Joined = struct { dump: []u8, /// The session's digest as dumped (`Replica.loaded`). digest: u64 = 0, + /// Its build's (wire.semantics): the daemon judged the hello by what it + /// last heard, which an upgrade under way may not have said yet. + semantics: u64 = 0, /// What was read past the dump: the stream's (`readStream`). rest: Framer = .{}, }; @@ -1657,6 +1690,7 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8) ?J r.j.view = w.view; r.j.gmtoff = w.gmtoff; r.j.digest = w.digest; + r.j.semantics = w.semantics; r.j.dump = r.gpa.alloc(u8, @intCast(w.dump_len)) catch { r.failed = "out of memory for the session's dump"; return false; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 2eafc785..e62da55c 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -160,6 +160,8 @@ pub const Command = struct { 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, link_gone, @@ -1295,6 +1297,59 @@ const Remote = struct { /// 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, + + /// 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. + fn load(gpa: std.mem.Allocator, joined: *replica.Joined, o: pardes.Options, why: []u8) ?*replica.Replica { + defer { + 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; + }; + 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). @@ -1324,7 +1379,7 @@ const Remote = struct { fn checked(c: *Remote, theirs: u64) void { c.asked = false; const path = c.check orelse return; - if (!c.r.quiet()) 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; @@ -1383,7 +1438,12 @@ fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loo const bytes = std.heap.c_allocator.dupe(u8, payload) catch return false; l.postEvent(.{ .screen = bytes }) catch std.heap.c_allocator.free(bytes); }, - .refused => return false, + .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 => {}, } return true; @@ -1402,14 +1462,16 @@ fn linkReader(gpa: std.mem.Allocator, fd: posix.fd_t, rest: *replica.Framer, loo pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, session: []const u8) !void { const io = init.io; const gpa = init.gpa; - var why: [600]u8 = @splat(0); - var joined = replica.dial(gpa, path, session, &why) orelse { - var said: [700]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: {s}\n", .{std.mem.sliceTo(&why, 0)}) catch "pardes: --attach failed\n") catch {}; - std.process.exit(1); + const Said = struct { + fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn { + var said: [800]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&said, "pardes: --attach: " ++ fmt ++ "\n", args) catch "pardes: --attach failed\n") catch {}; + std.process.exit(1); + } }; - defer _ = libc.close(joined.fd); - defer joined.rest.deinit(gpa); + var why: [600]u8 = @splat(0); + var joined = replica.dial(gpa, path, session, &why) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); + if (joined.semantics != wire.semantics) Said.no(io, "{s}", .{upgrade_words}); const allocs = pardes.memory.init(gpa); defer pardes.memory.deinit(); @@ -1424,19 +1486,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; - const r = replica.Replica.initDump(gpa, joined.client, joined.view, joined.dump, o) catch |err| { - gpa.free(joined.dump); - var said: [200]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: the session's dump would not load: {t}\n", .{err}) catch "pardes: --attach: the dump would not load\n") catch {}; - std.process.exit(1); - }; - gpa.free(joined.dump); - defer r.deinit(); - r.gmtoff = joined.gmtoff; - if (!r.loaded(joined.digest)) { - std.Io.File.stderr().writeStreamingAll(io, "pardes: --attach: the session's dump loaded as another session (a build's dump is not complete)\n") catch {}; - std.process.exit(1); - } + var r = Remote.load(gpa, &joined, o, &why) orelse Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); var winch_set = posix.sigemptyset(); posix.sigaddset(&winch_set, posix.SIG.WINCH); @@ -1449,7 +1499,6 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se try screen.enter(try vaxis.Tty.init(io, &tty_buf)); defer screen.leave(); defer screen.glide.deinit(gpa); - screen.feed.view = joined.view; var paste_buf: std.Io.Writer.Allocating = .init(gpa); defer paste_buf.deinit(); var loop: Loop = .init(io, &screen.tty, &screen.vx); @@ -1458,6 +1507,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se 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 sh: Shell = .{ .io = io, .gpa = gpa, @@ -1471,77 +1521,130 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se .from = joined.view, .remote = &link, }; - sh.terms[joined.view] = &screen; try startInput(&loop, &screen); defer stopInput(io, &screen.thread); (try std.Thread.spawn(.{}, winchWatch, .{&loop})).detach(); - var reader_done: std.atomic.Value(bool) = .init(false); - const reader = try std.Thread.spawn(.{}, linkReader, .{ gpa, joined.fd, &joined.rest, &loop, &reader_done }); if (link.check != null) (try std.Thread.spawn(.{}, wakeWatch, .{ io, &loop })).detach(); try screen.vx.queryTerminalSend(screen.tty.writer()); - // Its size is its view's first input. - sh.winched(); - while (!link.quit) { - if (link.dirty) link.draw(&sh); - const first = (loop.tryEvent() catch null) orelse idle: { - // Idle, its frame drawn: the next key needs no copy taken. - r.ready(); - break :idle loop.nextEvent() catch break; - }; - var ev = first; - var batch: usize = 1; - while (true) { - _ = sh.apply(ev); - if (link.quit or (!sh.in_paste and batch >= 64)) break; - ev = (loop.tryEvent() catch null) orelse break; - batch += 1; - } - r.settle(); - if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { - screen.caps_pending = false; - screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; - screen.vx.queueRefresh(); - link.dirty = true; + // A join a pass: the first, and one after the replica diverged or the + // session let it go to upgrade. The terminal stays as it is. + while (true) { + r.gmtoff = joined.gmtoff; + sh.core = r.core(); + sh.from = joined.view; + sh.terms = @splat(null); + sh.terms[joined.view] = &screen; + screen.feed.view = joined.view; + link.reset(r, joined.fd); + 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. + screen.size = null; + sh.winched(); + screen.vx.queueRefresh(); + while (!link.quit) { + if (link.dirty) link.draw(&sh); + const first = (loop.tryEvent() catch null) orelse idle: { + // Idle, its frame drawn: the next key needs no copy taken. + r.ready(); + break :idle loop.nextEvent() catch break; + }; + var ev = first; + var batch: usize = 1; + while (true) { + _ = sh.apply(ev); + if (link.quit or (!sh.in_paste and batch >= 64)) break; + ev = (loop.tryEvent() catch null) orelse break; + batch += 1; + } + r.settle(); + if (screen.caps_pending and screen.vx.queries_done.load(.unordered)) { + screen.caps_pending = false; + screen.vx.enableDetectedFeatures(screen.tty.writer()) catch {}; + screen.vx.queueRefresh(); + link.dirty = true; + } + if (link.owed) link.dirty = true; + 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 (r.diverged != null) link.quit = true; } - if (link.owed) link.dirty = true; - 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 (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); + if (!link.gone) replica.bye(joined.fd); + // The link's reader ends with the link, posting as it goes: what it + // and the terminal posted is let go until it has. + _ = libc.shutdown(joined.fd, 2); + while (true) { + while (loop.tryEvent() catch null) |ev| switch (ev) { + .unit, .screen, .refused => |b| std.heap.c_allocator.free(b), + .paste => |b| gpa.free(@constCast(b)), + else => {}, + }; + if (reader_done.load(.acquire)) break; + std.Thread.yield() catch {}; } + reader.join(); + _ = 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| { - screen.leave(); - var said: [700]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: this replica diverged from '{s}': {s}\n", .{ session, reason }) catch "pardes: --attach: diverged\n") catch {}; - std.process.exit(1); + 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 { + r.deinit(); + if (link.gone) { + screen.leave(); + Said.no(io, "'{s}' let this client go (a Detach in it, or the session's end)", .{session}); + } + return; } - } - if (init.environ_map.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(joined.fd); - // The link's reader ends with the link, posting as it goes: what it - // and the terminal posted is let go until it has. - _ = libc.shutdown(joined.fd, 2); - while (true) { - while (loop.tryEvent() catch null) |ev| switch (ev) { - .unit, .screen => |b| std.heap.c_allocator.free(b), - .paste => |b| gpa.free(@constCast(b)), - else => {}, + r.deinit(); + // The session again: an upgrade's takes the time its exec and load + // take, and its daemon's. + var tries: u32 = 0; + joined = while (true) : (tries += 1) { + why = @splat(0); + if (replica.dial(gpa, path, session, &why)) |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); + }; + r = Remote.load(gpa, &joined, o, &why) orelse { + screen.leave(); + Said.no(io, "{s}", .{std.mem.sliceTo(&why, 0)}); }; - if (reader_done.load(.acquire)) break; - std.Thread.yield() catch {}; - } - reader.join(); - if (link.gone) { - screen.leave(); - var said: [300]u8 = undefined; - std.Io.File.stderr().writeStreamingAll(io, std.fmt.bufPrint(&said, "pardes: --attach: '{s}' let this client go (a Detach in it, or the session's end)\n", .{session}) catch "pardes: --attach: the session let this client go\n") catch {}; } } +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, /// the terminal closed) at the session's start and end, and at a detach and @@ -2048,6 +2151,8 @@ 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; @@ -2093,6 +2198,7 @@ const Shell = struct { .detach = detach, .adopt = adopt, .upgrade = upgradeAsked, + .newer_build = newerBuild, .spawn = spawn, .pty_write = ptyWrite, .pty_resize = ptyResize, @@ -2268,6 +2374,12 @@ const Shell = struct { daemon.adopt(); } + /// A client's own build is not the session's to say (its core's host + /// is the session's, through the tape). + fn newerBuild(ctx: ?*anyopaque) bool { + return of(ctx).remote == null and upgrade.newer(); + } + fn upgradeAsked(ctx: ?*anyopaque, pane: u8) void { const s = of(ctx); if (comptime !upgrade.supported) return s.core.reportFailure(pane, "Upgrade: this system cannot move a session to another build in place"); @@ -2301,6 +2413,9 @@ const Shell = struct { for (s.terms) |slot| if (slot) |sc| stopInput(s.io, &sc.thread); while (s.loop.tryEvent() catch null) |ev| _ = s.apply(ev); core.settle(); + // Its replica clients told, their views gone before the dump: each + // dials the session again once it is back. + s.peers.refuseAll(core, "the session is upgrading to another build of pardes"); var rec: upgrade.Record = .{ .link = daemon.link, .stub = daemon.stub, .exe = path }; for (s.ptys, 0..) |slot, id| if (slot) |pt| rec.addPty(id, pt.pid, pt.file.handle); for (s.terms, 0..) |slot, k| if (slot) |sc| if (sc.on) rec.addTty(.{ @@ -2668,6 +2783,11 @@ const Shell = struct { .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; @@ -2684,17 +2804,18 @@ const Shell = struct { std.heap.c_allocator.free(bytes); }, .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; return true; }, - .focus_in => { - s.feed(.{ .focus = true }); - // A client's core is the session's: the notice is the session's to give. - // ponytail: not while clients replicate it (set outside a step). - if (s.remote == null and !s.peers.recording) upgrade.noticeNewer(core); - }, + .focus_in => s.feed(.{ .focus = true }), .focus_out => { s.feed(.pointer_leave); s.feed(.{ .focus = false }); @@ -2887,6 +3008,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); tz_cells.end(); for (surface.images[0..surface.nimages]) |maybe| { const place = maybe orelse continue; @@ -3641,6 +3763,17 @@ test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 } } +/// A replica client's own line over its frame's last row (`Remote.notify`), +/// reversed. `text` is printable ASCII and outlives the render (vaxis keeps +/// the slices). +fn noticeLine(win: vaxis.Window, text: []const u8, cols: u16, rows: u16) void { + if (rows == 0) return; + for (0..cols) |x| win.writeCell(@intCast(x), rows - 1, .{ + .char = .{ .grapheme = if (x < text.len) text[x..][0..1] else " " }, + .style = .{ .reverse = true }, + }); +} + /// A blank whose ink alone changed is not sent: vaxis's render skips it /// (pardes's patch to Vaxis.zig in build.zig), since a blank's ink shows /// nowhere. Deciding that here cost every cell of every frame a look at the diff --git a/src/upgrade.zig b/src/upgrade.zig index 49e8aff5..37c79991 100644 --- a/src/upgrade.zig +++ b/src/upgrade.zig @@ -74,11 +74,18 @@ fn inodeOf(path: [:0]const u8) ?u64 { /// rebuilding (a stat). ponytail: explicit only, no watch and no automatic /// upgrade. pub fn noticeNewer(core: *pardes.Pardes) void { - const was = started_inode orelse return; - const now = inodeOf(exe() orelse return) orelse return; - if (now == was or told_inode == now) return; + if (newer()) core.setMessage(core.active, pardes.newer_build_words); +} + +/// Whether to say a newer build is installed now (`noticeNewer`): the +/// tty's Host answers the core's focus step with it, so its replica +/// clients take the line from the tape. +pub fn newer() bool { + const was = started_inode orelse return false; + const now = inodeOf(exe() orelse return false) orelse return false; + if (now == was or told_inode == now) return false; told_inode = now; - core.setMessage(core.active, "a newer pardes is installed: Upgrade (SPC s U) moves this session onto it"); + return true; } pub fn exe() ?[:0]const u8 { diff --git a/test/daemon.py b/test/daemon.py index b54b2b54..273c29e0 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -337,6 +337,26 @@ def clients(binary): and b'from-B' in nine.read(f'/pane/{pane}/body')) wait_for('client A agrees once quiet', lambda: agreed(root / 'a.check', 0)) wait_for('client B agrees once quiet', lambda: agreed(root / 'b.check', 0)) + # One put off the session's state (PARDES_TEST_DIVERGE): the next + # unit's digest finds it, it says so in a line and joins again, and + # its keys after go in and it agrees. + td = Term(24, 90) + terms.append(td) + d = td.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'd.check'), PARDES_TEST_DIVERGE='1')) + started.append(d.pid) + wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20) + os.write(td.master, b'jj') + time.sleep(.5) + # Another's unit, replayed on D's core: its digest finds it. + os.write(ta.master, b'jj') + wait_for('client D diverged and joined again', lambda: b'joined again' in td.text(), timeout=20) + assert d.poll() is None + seen = len(checks(root / 'd.check')) + os.write(td.master, b'Oafter-rejoin-D\x1b') + wait_for('client D\'s keys after its rejoin', lambda: b'after-rejoin-D' in nine.read(f'/pane/{pane}/body')) + wait_for('client D agrees after its rejoin', lambda: agreed(root / 'd.check', seen)) + os.write(td.master, b' sD') + wait_for('client D let go', lambda: d.poll() is not None, timeout=10) # Killed outright: the session and the other client carry on. os.kill(b.pid, signal.SIGKILL) b.wait(timeout=10) @@ -373,6 +393,7 @@ def clients(binary): wait_for('the session\'s fds level', lambda: fds(sess.pid) == alone, timeout=10) print(f'daemon: two replica clients (one through a 40 ms relay) typed into a detached session; ' f'digests agreed {len(checks(root / "a.check"))} and {len(checks(root / "b.check"))} times; ' + f'one put off the session\'s state joined again and agreed {len(checks(root / "d.check"))} times; ' f'one killed, the other typed on and detached; a third typed into a shell, agreed ' f'{len(checks(root / "c.check"))} times, and was hung up') try: @@ -767,6 +788,12 @@ def upgrades(old, new): old_build = semantics(old) replica = Replica(root / 'pardes-replica.sock') assert replica.hello('work', old_build)[0] == 'welcome' + # A replica client of the old build: let go at the upgrade, it dials + # again and is told to upgrade too. + term3 = Term(24, 90) + stale = term3.spawn([str(old), f'--attach={root / "pardes-replica.sock"}:work'], env) + started.append(stale.pid) + wait_for('the old build\'s client drawn', lambda: b'\x1b[?1049h' in term3.text() and b'one' in term3.text()) before = len(term.text()), len(term2.text()) install(new, binary) @@ -794,16 +821,23 @@ def upgrades(old, new): else: wait_for('the daemon exec\'d again', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(daemon))) assert alive(daemon) and stub.poll() is None and stub2.poll() is None - # A replica of the old build is told why it is let go. + # A replica of the old build is told why it is let go, after what it + # was sent (units, terminals). tag, body = replica.read() + while tag in (0x05, 0x06, 0x07): + tag, body = replica.read() assert tag == 0x02 and b'upgrading to another build' in body, (tag, body) replica.close() + stale.wait(timeout=30) + assert b'upgrade this client too' in term3.text(), term3.text()[-400:] + term3.close() + print('upgrade: a replica client of the old build was let go, dialled again and was told to upgrade too') # The old image's prompt files swept, the new one's made. wait_for('the prompt files level', lambda: len(list(Path('/tmp').glob(f'pardes-osc133-*-{session}-*'))) == len(rcs)) assert sorted(Path('/tmp').glob(f'pardes-osc133-*-{session}-*')) != rcs or not rcs # Nothing kept that was not: the old binary let go, every fd back. - # (The replica's connection is the one fewer.) - level = fds_before[0] - 1, fds_before[1] + # (The replicas' connections are two fewer.) + level = fds_before[0] - 2, fds_before[1] try: wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level, timeout=5) except TimeoutError: @@ -842,10 +876,26 @@ def upgrades(old, new): install(refuser, binary) if procfs: running = os.stat(f'/proc/{session}/exe').st_ino + # A replica client of the build running: let go at the upgrade, + # it joins again once the session is back, says so, and agrees. + term4 = Term(24, 90) + again = term4.spawn([str(new), f'--attach={root / "pardes-replica.sock"}:work'], + dict(env, PARDES_REPLICA_CHECK=str(root / 'e.check'))) + started.append(again.pid) + wait_for('the client of the build running drawn', lambda: b'\x1b[?1049h' in term4.text() and b'one' in term4.text()) refusing('1') client.write(f'/pane/{shell}/exec', b'Upgrade\n') client.socket.close() client = saying(sock, 'it goes on as') + wait_for('the client joined again', lambda: b'joined again: the session is upgrading' in term4.text(), timeout=30) + assert again.poll() is None + seen = len(checks(root / 'e.check')) + os.write(term4.master, b'gg') + wait_for('the client agrees after it joined again', lambda: agreed(root / 'e.check', seen), timeout=20) + again.send_signal(signal.SIGHUP) + again.wait(timeout=10) + term4.close() + print('upgrade: a replica client of the build running joined again after the upgrade, said so and agreed') assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran' assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' |
