diff options
| -rw-r--r-- | abi/addon.zig | 24 | ||||
| -rw-r--r-- | abi/wire.zig | 12 | ||||
| -rw-r--r-- | addons/pdf/pdf.zig | 57 | ||||
| -rw-r--r-- | build/addons.zig | 9 | ||||
| -rw-r--r-- | build/core.zig | 15 | ||||
| -rw-r--r-- | build/tests.zig | 1 | ||||
| -rw-r--r-- | core/Addon.zig | 2 | ||||
| -rw-r--r-- | core/Kind.zig | 17 | ||||
| -rw-r--r-- | core/hunks.zig | 49 | ||||
| -rw-r--r-- | core/jj.zig | 333 | ||||
| -rw-r--r-- | core/mouse.zig | 6 | ||||
| -rw-r--r-- | core/plumbing | 9 | ||||
| -rw-r--r-- | core/replica.zig | 1053 | ||||
| -rw-r--r-- | core/root.zig | 2 | ||||
| -rw-r--r-- | core/surface.zig | 3 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 35 | ||||
| -rw-r--r-- | docs/typ/cheatsheet.typ | 2 | ||||
| -rw-r--r-- | docs/typ/guide.typ | 23 | ||||
| -rw-r--r-- | runtime/client.zig | 47 | ||||
| -rw-r--r-- | runtime/daemon.zig | 16 | ||||
| -rw-r--r-- | runtime/upgrade.zig | 26 | ||||
| -rw-r--r-- | test/behaviour/addons_pdf.zig | 16 | ||||
| -rw-r--r-- | test/daemon.py | 249 | ||||
| -rw-r--r-- | test/replicas.zig | 122 |
24 files changed, 1713 insertions, 415 deletions
diff --git a/abi/addon.zig b/abi/addon.zig index 1fa2279a..059e016d 100644 --- a/abi/addon.zig +++ b/abi/addon.zig @@ -248,8 +248,14 @@ pub fn loadBytes(s: anytype, bytes: []const u8, version: u32) bool { pub const body_max = 4096; var body_cut = false; -fn span(p: [*c]const u8, n: u64) []const u8 { - return if (p == null) "" else p[0..n]; +/// A C pointer and its count as a slice; NULL is none, whatever the count: +/// C says none with a NULL (a page's search without a hit, a selection +/// over no text, an outline of no entries), and a NULL C pointer sliced +/// is a safety panic even at length 0 (a release build's abort). Every +/// pointer a C struct or a C caller hands with its count is read through +/// it: pdf.zig's test holds the bridge's to it. +pub fn cSlice(ptr: anytype, n: usize) []const std.meta.Child(@TypeOf(ptr)) { + return if (ptr == null) &.{} else ptr[0..n]; } /// `pardes_addon` exported, when built as a library alone: the kind is its @@ -282,7 +288,7 @@ pub fn ops(comptime T: type) c.pa_ops { fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque { const s = arena.create(T) catch return null; s.* = std.mem.zeroInit(T, .{}); - if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else bytes[0..len]); + if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else cSlice(bytes, len)); return s; } fn close(st: ?*anyopaque) callconv(.c) void { @@ -329,7 +335,7 @@ pub fn ops(comptime T: type) c.pa_ops { return @intCast(from.len); } fn address(st: ?*anyopaque, t: [*c]const u8, n: u32) callconv(.c) c_int { - return @intFromBool(T.address(self(st) orelse return 0, span(t, n))); + return @intFromBool(T.address(self(st) orelse return 0, cSlice(t, n))); } fn where(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { return write(T.where, self(st) orelse return 0, buf, n); @@ -337,26 +343,26 @@ pub fn ops(comptime T: type) c.pa_ops { fn ctl(st: ?*anyopaque, line: [*c]const u8, n: u32, reply: [*c]u8, cap: u32) callconv(.c) c_int { var w: std.Io.Writer = .fixed(reply[0..cap -| 1]); defer reply[w.end] = 0; - return if (T.ctl(self(st) orelse return 1, span(line, n), &w)) c.PA_OK else 1; + return if (T.ctl(self(st) orelse return 1, cSlice(line, n), &w)) c.PA_OK else 1; } fn ctl_read(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { return write(T.ctlRead, self(st) orelse return 0, buf, n); } fn job_run(in: [*c]const u8, n: u32, out: [*c]c.pa_out) callconv(.c) u32 { const gpa: Allocator = .{ .ptr = out, .vtable = &.{ .alloc = jobAlloc, .resize = Allocator.noResize, .remap = Allocator.noRemap, .free = Allocator.noFree } }; - return @intCast((T.jobRun(span(in, n), gpa) orelse return 0).len); + return @intCast((T.jobRun(cSlice(in, n), gpa) orelse return 0).len); } fn job_done(st: ?*anyopaque, token: u32, out: [*c]const u8, n: u32) callconv(.c) void { - T.jobDone(self(st) orelse return, token, span(out, n)); + T.jobDone(self(st) orelse return, token, cSlice(out, n)); } fn dump(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 { return @intCast(T.dump(self(st) orelse return 0, buf[0..n])); } fn load(st: ?*anyopaque, buf: [*c]const u8, n: u32, version: u32) callconv(.c) c_int { - return @intFromBool(!T.load(self(st) orelse return 1, span(buf, n), version)); + return @intFromBool(!T.load(self(st) orelse return 1, cSlice(buf, n), version)); } fn search(st: ?*anyopaque, pat: [*c]const u8, n: u32) callconv(.c) void { - T.search(self(st) orelse return, span(pat, n)); + T.search(self(st) orelse return, cSlice(pat, n)); } }; if (T.head.name.len > 15) @compileError(@typeName(T) ++ "'s name " ++ T.head.name ++ " is over 15 bytes"); diff --git a/abi/wire.zig b/abi/wire.zig index 8949edff..7b6a22f1 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -12,9 +12,12 @@ const build_info = @import("build_info"); /// 31: where a view stands in a terminal's history is the view's: a pane's /// `scrolled_to` (and its share's in each view) in the dump and the digest, -/// the emulator's own view out of both (its `Parts.view` gone); and the +/// the emulator's own view out of both (its `Parts.view` gone); the /// core's count of its emulators' writes (`outside`) in both, which the -/// replica engine's one question of a unit reads; +/// replica engine's one question of a unit reads; and a client whose link +/// is up joins again over it (its bye's `again`, then its hello there: +/// core/replica.zig `Peers.joinAgain`), as one whose load was refused asks +/// once more; /// 30: the terminals' one road: the screen-state messages are retired (a /// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps), /// a welcome says no road (its `bytes` byte gone), and a pane's @@ -324,8 +327,9 @@ pub fn helloVersion(payload: []const u8) Error!u16 { /// one call and no longer. pub const ClientMsg = union(enum) { hello: Hello, - /// The client's end: `again`, it joins again for its view at once; - /// `close`, its window was closed (a pair's session ends at its last). + /// The client's end: `again`, it joins again for its view at once (its + /// hello next, on this link while it is up); `close`, its window was + /// closed (a pair's session ends at its last). bye: struct { again: bool = false, close: bool = false }, /// A round trip's probe, answered `pong` with the same value. ping: u64, diff --git a/addons/pdf/pdf.zig b/addons/pdf/pdf.zig index 8f314bbe..79d79219 100644 --- a/addons/pdf/pdf.zig +++ b/addons/pdf/pdf.zig @@ -759,7 +759,7 @@ pub const Pdf = extern struct { const found = in.n > 0 and m.pardes_pdf_search_page(ld, @intCast(in.page), &q, &r) == ok; defer if (found) m.pardes_pdf_drop_search_result(ld, r.handle); res.ok, res.n, res.hits = .{ 1, @intCast(t.len), if (found) @intCast(r.hit_count) else 0 }; - return answer(gpa, res, std.mem.concat(gpa, u8, &.{ t.data[0..t.len], if (found) std.mem.sliceAsBytes(r.quads[0..r.quad_count]) else "" }) catch return null); + return answer(gpa, res, std.mem.concat(gpa, u8, &.{ addon.cSlice(t.data, t.len), if (found) std.mem.sliceAsBytes(addon.cSlice(r.quads, r.quad_count)) else "" }) catch return null); } // each page's count of hits, then the rows var shown = @min(in.n, 200); @@ -1011,7 +1011,7 @@ fn pageText(o: *Own, page: u32) []const u8 { var t: m.pardes_pdf_text = undefined; if (m.pardes_pdf_page_text(d.base, @intCast(page), &t) != ok) return ""; defer m.pardes_pdf_drop_text(d.base, t.handle); - o.read.bytes = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + o.read.bytes = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{}; return o.read.bytes; } @@ -1030,7 +1030,7 @@ fn hitsOf(st: *const Pdf, o: *Own) []const m.pardes_pdf_search_quad { var r: m.pardes_pdf_search_result = undefined; if (m.pardes_pdf_search_page(d.base, @intCast(f.hits_page), &q, &r) != ok) return &.{}; defer m.pardes_pdf_drop_search_result(d.base, r.handle); - o.hits = heap.dupe(m.pardes_pdf_search_quad, r.quads[0..r.quad_count]) catch &.{}; + o.hits = heap.dupe(m.pardes_pdf_search_quad, addon.cSlice(r.quads, r.quad_count)) catch &.{}; return o.hits; } @@ -1073,8 +1073,8 @@ fn selectHere(o: *Own, page: u32, from: Point, to: Point) ?usize { var t: m.pardes_pdf_owned_text = undefined; if (m.pardes_pdf_copy_selection(base, @intCast(page), sel.start, sel.end, &t) != ok) return null; defer m.pardes_pdf_drop_owned_text(base, t.handle); - o.sel_quads = heap.dupe(Quad, sel.quads[0..sel.quad_count]) catch &.{}; - o.sel_text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + o.sel_quads = heap.dupe(Quad, addon.cSlice(sel.quads, sel.quad_count)) catch &.{}; + o.sel_text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{}; return sel.quad_count; } @@ -1691,11 +1691,11 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad const uri = struct { var buf: [1024]u8 = undefined; }; - @memcpy(uri.buf[0..link.uri_len], link.uri[0..link.uri_len]); + @memcpy(uri.buf[0..link.uri_len], addon.cSlice(link.uri, link.uri_len)); link.uri = &uri.buf; var text: []u8 = &.{}; if (m.pardes_pdf_copy_rectangle(base, @intCast(at.page), link.quad, &t) == ok) { - text = heap.dupe(u8, t.data[0..t.len]) catch &.{}; + text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{}; m.pardes_pdf_drop_owned_text(base, t.handle); } return .{ .page = at.page, .quad = link.quad, .text = text, .link = link }; @@ -1706,7 +1706,7 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad if (sel.quad_count == 0 or m.pardes_pdf_copy_selection(base, @intCast(at.page), sel.start, sel.end, &t) != ok) return null; defer m.pardes_pdf_drop_owned_text(base, t.handle); if (t.len == 0) return null; - return .{ .page = at.page, .quad = sel.quads[0], .text = heap.dupe(u8, t.data[0..t.len]) catch return null, .link = null }; + return .{ .page = at.page, .quad = addon.cSlice(sel.quads, sel.quad_count)[0], .text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch return null, .link = null }; } /// A link followed: a place in the document scrolled to, else looked at @@ -1714,7 +1714,7 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad /// both, a +Links. fn follow(st: *Pdf, link: m.pardes_pdf_link, text: []const u8) void { if (link.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return goToXY(st, @intCast(link.page), link.has_x != 0, link.x, link.has_y != 0, link.y); - const uri = link.uri[0..link.uri_len]; + const uri = addon.cSlice(link.uri, link.uri_len); var shown: [512]u8 = undefined; var k: usize = 0; for (text) |ch| if (ch > ' ' and k < shown.len) { @@ -1749,10 +1749,10 @@ fn goToXY(st: *Pdf, page: u32, has_x: bool, x: f32, has_y: bool, y: f32) void { /// from 1), indented by depth; an entry with nowhere to go takes its first /// child's that has, and an http(s) one is its URI. fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool { - const it = o.items[i]; + const it = addon.cSlice(o.items, o.item_count)[i]; if (it.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return true; if (it.destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL or it.uri_len == 0 or it.uri_len > 256) return false; - const u = o.bytes[it.uri_offset..][0..it.uri_len]; + const u = addon.cSlice(o.bytes, o.bytes_len)[it.uri_offset..][0..it.uri_len]; return (std.mem.startsWith(u8, u, "http://") or std.mem.startsWith(u8, u, "https://")) and for (u) |ch| { if (ch <= 0x20 or ch == 0x7f) break false; } else true; @@ -1760,9 +1760,10 @@ fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool { /// Entry `i`'s place: its own, else the first usable one below it. fn resolve(o: *const m.pardes_pdf_outline_result, i: usize) ?usize { - if (o.items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null; + const items = addon.cSlice(o.items, o.item_count); + if (items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null; var k = i + 1; - while (k < o.item_count and o.items[k].depth > o.items[i].depth) : (k += 1) if (usable(o, k)) return k; + while (k < items.len and items[k].depth > items[i].depth) : (k += 1) if (usable(o, k)) return k; return null; } @@ -1774,13 +1775,15 @@ fn sections(st: *Pdf) void { const rows = heap.alloc(u8, o.item_count * 300 + 1) catch return; defer heap.free(rows); var w: std.Io.Writer = .fixed(rows); - for (o.items[0..o.item_count], 0..) |it, i| { - const to = o.items[resolve(&o, i) orelse continue]; - if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(st).name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{o.bytes[to.uri_offset..][0..to.uri_len]}) catch {}; + const items = addon.cSlice(o.items, o.item_count); + const bytes = addon.cSlice(o.bytes, o.bytes_len); + for (items, 0..) |it, i| { + const to = items[resolve(&o, i) orelse continue]; + if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(st).name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{bytes[to.uri_offset..][0..to.uri_len]}) catch {}; w.splatByteAll(' ', 2 * it.depth) catch {}; // the title on one line: control and invalid characters a space // between words, none at either end - const t = o.bytes[it.title_offset..][0..it.title_len]; + const t = bytes[it.title_offset..][0..it.title_len]; const start = w.end; var gap = false; var i_: usize = 0; @@ -1811,9 +1814,9 @@ fn section(st: *Pdf, page: u32, ord: u32) bool { defer if (o.handle != null) m.pardes_pdf_drop_outline_result(base, o.handle); var said: [200]u8 = undefined; const r = if (m.pardes_pdf_load_outline(base, &o) == ok and ord > 0 and ord <= o.item_count) resolve(&o, ord - 1) else null; - const to = o.items[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(st).name, ord }))]; + const to = addon.cSlice(o.items, o.item_count)[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(st).name, ord }))]; if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) { - addon.look(o.bytes[to.uri_offset..][0..@min(to.uri_len, 256)]); + addon.look(addon.cSlice(o.bytes, o.bytes_len)[to.uri_offset..][0..@min(to.uri_len, 256)]); return true; } if (to.page + 1 != page) return miss(std.fmt.bufPrint(&said, "PdfSections: section {d} of {s} is on page {d}, not {d}", .{ ord, ownOf(st).name, to.page + 1, page })); @@ -1831,3 +1834,19 @@ fn miss(said: anyerror![]const u8) bool { fn noText() bool { return miss("has no text to address; its address is a page, :N"); } + +test "every pointer the bridge's structs hand back is read through addon.cSlice: none of them sliced or indexed bare (a NULL for none sliced at 0 was a release build's abort)" { + var src: []const u8 = @embedFile("pdf.zig"); // (searched at run time: at comptime it is over the branch quota) + _ = &src; + @setEvalBranchQuota(1_000_000); // (the translated header's every declaration) + inline for (@typeInfo(m).@"struct".decl_names) |name| { + if (comptime !std.mem.startsWith(u8, name, "pardes_pdf_") or @TypeOf(@field(m, name)) != type or @typeInfo(@field(m, name)) != .@"struct") continue; + const S = @typeInfo(@field(m, name)).@"struct"; + inline for (S.field_names, S.field_types) |field, F| if (comptime @typeInfo(F) == .pointer and @typeInfo(F).pointer.size == .c) { + if (std.mem.indexOf(u8, src, "." ++ field ++ "[")) |at| { + std.debug.print("pdf.zig:{d}: {s}.{s} read bare: addon.cSlice(ptr, count)\n", .{ std.mem.count(u8, src[0..at], "\n") + 1, name, field }); + return error.BareCPointer; + } + }; + } +} diff --git a/build/addons.zig b/build/addons.zig index 38b02dff..a1bdb43b 100644 --- a/build/addons.zig +++ b/build/addons.zig @@ -52,6 +52,9 @@ pub const Pdf = struct { /// `pardes_addon` alone. pub fn pdf(b: *std.Build, c: struct { addon_mod: *std.Build.Module, + /// pdf.zig's and the bridge's (core.zig's `addon_optimize`); MuPDF's + /// and the rest of the C's `c_optimize`. + addon_optimize: std.lang.Optimize, c_optimize: std.lang.Optimize, enable_jpx: bool, freetype: ?*std.Build.Step.Compile, @@ -83,7 +86,7 @@ pub fn pdf(b: *std.Build, c: struct { // The bridge's header translated here for pdf.zig (Zig 0.17 has no // @cImport), as the kinds' header is for the core. const bridge_mod = b.addTranslateC(.{ .root_source_file = b.path("addons/pdf/pdf_bridge.h"), .target = c.target, .optimize = c.c_optimize }).createModule(); - const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.c_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); + const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.addon_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } }); mupdf.linkTo(pdf_mod); pdf_mod.addIncludePath(b.path("addons/pdf")); pdf_mod.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} }); @@ -105,8 +108,8 @@ pub fn pdf(b: *std.Build, c: struct { /// The image addon (addons/image/image.zig over stb_image, stb.c), /// installed by its step and handed by path to every test that opens a /// picture. -pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile { - const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); +pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile { + const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} }); image_mod.addIncludePath(zstbi_dep.path("libs/stbi")); image_mod.addCSourceFile(.{ .file = b.path("addons/image/stb.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } }); const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = image_mod }); diff --git a/build/core.zig b/build/core.zig index e8150843..f9cb450f 100644 --- a/build/core.zig +++ b/build/core.zig @@ -310,8 +310,10 @@ pub const Parts = struct { pdf: ?*std.Build.Module, term: *std.Build.Module, plain: *std.Build.Module, - /// The kinds' C ABI (abi/pardes_addon.h), translated. + /// The kinds' C ABI (abi/pardes_addon.h), translated, and what an addon + /// in Zig imports over it (abi/addon.zig: the core's `cSlice` too). kind: *std.Build.Module, + addon: *std.Build.Module, themes: *std.Build.Module, ts: TreeSitter, mvzr: *std.Build.Module, @@ -401,6 +403,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules { if (c.terminal) x.addImport("term", p.term); x.addImport("plain", p.plain); x.addImport("pardes_addon", p.kind); + x.addImport("addon", p.addon); x.addImport("generated_themes", p.themes); x.addImport("tree-sitter", p.ts.mod); x.addImport("ts_queries", ts_queries); @@ -514,8 +517,15 @@ pub fn assemble(b: *std.Build, c: struct { const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("abi/pardes_addon.h"), .target = target, .optimize = optimize }).createModule(); // ...and what an addon in Zig imports over it (abi/addon.zig). const addon_mod = b.createModule(.{ .root_source_file = b.path("abi/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); + // The C-backed addons' own Zig and bridge at the C's speed, with the + // checks a release keeps: ReleaseSafe in a Debug build, as in the + // user's (a page's search without a hit sliced a NULL: only a release + // build aborted, Debug's addons ran ReleaseFast); MuPDF and stb stay + // at c_optimize. + const addon_optimize: std.lang.Optimize = if (optimize == .debug) .safe else c_optimize; const pdf_built = addons.pdf(b, .{ .addon_mod = addon_mod, + .addon_optimize = addon_optimize, .c_optimize = c_optimize, .enable_jpx = c.enable_jpx, .freetype = freetype, @@ -602,7 +612,7 @@ pub fn assemble(b: *std.Build, c: struct { // library and no allocator hook of its own (it takes Zig allocators). const xitdb_mod = b.dependency("xitdb", .{ .target = target, .optimize = optimize }).module("xitdb"); - const image_addon = addons.image(b, target, c_optimize, addon_mod, zstbi_dep); + const image_addon = addons.image(b, target, addon_optimize, addon_mod, zstbi_dep); // The records the core and the terminal both name (abi/plain.zig). const plain_mod = b.createModule(.{ .root_source_file = b.path("abi/plain.zig"), .target = target, .optimize = optimize }); // The terminal, a module of its own (core/term/term.zig): the emulator and @@ -625,6 +635,7 @@ pub fn assemble(b: *std.Build, c: struct { .term = term_mod, .plain = plain_mod, .kind = kind_mod, + .addon = addon_mod, .themes = themes_mod, .ts = ts, .mvzr = mvzr_mod, diff --git a/build/tests.zig b/build/tests.zig index e0b33911..5e913501 100644 --- a/build/tests.zig +++ b/build/tests.zig @@ -162,6 +162,7 @@ pub fn add(b: *std.Build, c: struct { run_replicas.has_side_effects = true; b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step); for ([_]*std.Build.Module{ snake_mod, life_mod, liar_mod, c.parts.image }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + if (c.pdf_addon) |lib| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lib.root_module })).step); // ...and the pdf addon's, which mupdf-check runs too (its script // opens docs/design.pdf, from the build root). const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ c.snake_shader_lib, "addons/snake_shader/snake_shader" }, .{ life_lib, "addons/life/life" }, .{ c.pdf_addon, "addons/pdf/pdf" } }; diff --git a/core/Addon.zig b/core/Addon.zig index aa3195f9..e93a43dc 100644 --- a/core/Addon.zig +++ b/core/Addon.zig @@ -532,7 +532,7 @@ pub const LoadedWord = struct { name: []const u8, leader: []const u8 = "", arg: /// `ops`'s head as a `Loaded` (its words borrowed from it, in `words`). pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[64]LoadedWord) Loaded { const h = &ops.head; - const head_words = if (h.nwords == 0 or h.words == null) &.{} else h.words[0..@min(h.nwords, words.len)]; + const head_words = @import("addon").cSlice(h.words, @min(h.nwords, words.len)); for (head_words, words[0..head_words.len]) |*w, *out| out.* = .{ .name = if (w.name == null) "" else std.mem.span(w.name), .leader = if (w.leader == null) "" else std.mem.span(w.leader), diff --git a/core/Kind.zig b/core/Kind.zig index 49076f78..5d2dcdb0 100644 --- a/core/Kind.zig +++ b/core/Kind.zig @@ -17,6 +17,7 @@ const std = @import("std"); const builtin = @import("builtin"); pub const c = @import("pardes_addon"); +const cSlice = @import("addon").cSlice; const pardes = @import("root.zig"); const walk = @import("walk.zig"); const surface = @import("surface.zig"); @@ -1130,7 +1131,7 @@ pub const api: c.pa_api = .{ .look = struct { fn f(text: [*c]const u8, n: u32) callconv(.c) void { const cl = current orelse return; - if (!cl.quiet and text != null) cl.look.set(text[0..n]); + if (!cl.quiet and text != null) cl.look.set(cSlice(text, n)); } }.f, .say = struct { @@ -1138,8 +1139,8 @@ pub const api: c.pa_api = .{ const cl = current orelse return; if (cl.quiet or text == null) return; // Refusing its open: the opener says why. - if (err != 0 and cl.opening) return cl.refused.set(text[0..n]); - cl.said.set(text[0..n]); + if (err != 0 and cl.opening) return cl.refused.set(cSlice(text, n)); + cl.said.set(cSlice(text, n)); cl.err = err != 0; } }.f, @@ -1149,8 +1150,8 @@ pub const api: c.pa_api = .{ const cl = current orelse return 0; const p = cl.p orelse return 0; if (cl.quiet or name == null or cl.pane_name.len > 0) return 0; - cl.pane_name.set(name[0..name_len]); - cl.pane_text = p.scratch.allocator().dupe(u8, if (bytes == null) "" else bytes[0..n]) catch ""; + cl.pane_name.set(cSlice(name, name_len)); + cl.pane_text = p.scratch.allocator().dupe(u8, cSlice(bytes, n)) catch ""; return p.next_serial + 1; } }.f, @@ -1181,7 +1182,7 @@ pub const api: c.pa_api = .{ .exec = struct { fn f(text: [*c]const u8, n: u32) callconv(.c) void { const cl = current orelse return; - if (!cl.quiet and text != null) cl.exec.set(text[0..n]); + if (!cl.quiet and text != null) cl.exec.set(cSlice(text, n)); } }.f, .select = struct { @@ -1189,7 +1190,7 @@ pub const api: c.pa_api = .{ const cl = current orelse return; if (cl.quiet) return; const p = cl.p orelse return; - cl.selected = p.scratch.allocator().dupe(u8, if (text == null) "" else text[0..n]) catch return; + cl.selected = p.scratch.allocator().dupe(u8, cSlice(text, n)) catch return; } }.f, .cancel = struct { @@ -1234,7 +1235,7 @@ pub const api: c.pa_api = .{ const cl = current orelse return; const p = cl.p orelse return; if (cl.quiet or rows == null) return; - cl.rows = std.mem.concat(p.scratch.allocator(), u8, &.{ cl.rows, rows[0..n] }) catch return; + cl.rows = std.mem.concat(p.scratch.allocator(), u8, &.{ cl.rows, cSlice(rows, n) }) catch return; } }.f, }; diff --git a/core/hunks.zig b/core/hunks.zig index bee06cc2..e109b788 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -701,7 +701,9 @@ fn trimmedWidth(ctx: *const Ctx, section: []const u8) usize { /// (a .diff, a .patch: relative to the pane's directory), its hunks /// stacked so; with a revision (7 to 40 lowercase hex digits, a letter and /// a digit among them), `git show` of it, paged into a +Pager that stacks -/// its hunks (ctl.fillPager), run in the pane's git work tree. A plumbing +/// its hunks (ctl.fillPager), run in the pane's git work tree; with a jj +/// change (`Diff wrnnmymq [path[:line]]`: jj.diffChange), its patch, header +/// and all, the cursor at that place in it. A plumbing /// rule's Diff that cannot (no hunk, no work tree) declines, saying /// nothing (Pardes.plumb_declined), and the look looks itself. pub fn word(c: pardes.builtins.Ctx) void { @@ -731,6 +733,9 @@ pub fn word(c: pardes.builtins.Ctx) void { if (p.panes[dst]) |cp| cp.command_pages = true; return; } + // A jj change (its letters k to z), with a place in its patch to stand at. + if (@import("jj.zig").diffChange(p, c.id, arg)) return; + if (@import("jj.zig").isChangeId(arg[0 .. std.mem.indexOfAny(u8, arg, " \t") orelse arg.len])) return declined(p, c.id, "Diff: no such change"); var buf: [4096]u8 = undefined; const path = if (arg[0] == '/') arg else std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, Pardes.paneDir(c.pane), "/"), arg }) catch arg; const bytes = pardes.filesystem.read(p, path) catch |err| { @@ -1072,6 +1077,48 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); } +test "a log of several changes keeps each one's header and whole message above its own hunks: git log -p, jj show's header" { + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); + const log = + \\commit 1111111111111111111111111111111111111111 + \\Author: A <a@a> + \\Date: Mon Nov 23 10:00:00 2026 -0300 + \\ + \\ second + \\ + \\ its body, a line + \\ + \\diff --git a/x.txt b/x.txt + \\index 1..2 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-b + \\+c + \\ + \\commit 2222222222222222222222222222222222222222 + \\Author: A <a@a> + \\Date: Mon Nov 23 09:00:00 2026 -0300 + \\ + \\ first + \\ + \\diff --git a/x.txt b/x.txt + \\index 0..1 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-a + \\+b + \\ + ; + const result = try paneResult(testing.allocator, try format(&t.ctx, "/pardes-surely-missing-dir", log)); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); + try testing.expectEqualStrings("commit 1111111111111111111111111111111111111111\nAuthor: A <a@a>\nDate: Mon Nov 23 10:00:00 2026 -0300\n\n second\n\n its body, a line\n\nx.txt:1\n-b\n+c\n\ncommit 2222222222222222222222222222222222222222\nAuthor: A <a@a>\nDate: Mon Nov 23 09:00:00 2026 -0300\n\n first\n\nx.txt:1\n-a\n+b\n", result.content); +} + test "a .patch looked at opens its +Diff, and Diff goes to the text and back" { const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); defer p.deinit(); diff --git a/core/jj.zig b/core/jj.zig index 59e0e21d..1ec1a0dc 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -369,9 +369,10 @@ pub const Hunk = struct { /// A row a view shows that is not a line of the text (PARDES.md "Changes on /// the source view": a ghost row): a line a pin took away whole, drawn where /// it stood, red across; or a pin's description (`id title author age`), -/// after its last line, in its lane's colour. No number, the cursor steps -/// over it, search and selection do not see it; a Look on it goes to its -/// line in the revision it came from (`lookGhost`). A line a pin CHANGED +/// after its last line, its lane an arrow to it. No number, the cursor +/// steps over it, search and selection do not see it; a Look on it looks at +/// its word as anywhere, on a description's id its change's patch +/// (`lookGhost`). A line a pin CHANGED /// is a ghost row too: its old text right above the line, the words that /// went in red, the line with the words that came in green. pub const Ghost = struct { @@ -1425,10 +1426,12 @@ fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize) [levels]PinI } /// A ghost row's cells: a line taken away whole red across, its text in -/// the line numbers' grey (dimmer than the text's ink); a description in -/// its lane's colour, its author and age grey; `said`, the row's text as -/// the body shows it (a description `fitted`). -fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: []const [2]u32, colours: []const [3]u8, x: u16, y: u16, w: u16) void { +/// the line numbers' grey (dimmer than the text's ink); a description's id +/// and title in its lane's colour `lane`, or with one change pinned (no one +/// colour a lane) its id in the theme's keyword ink; its author and age +/// grey; `said`, the row's text as the body shows it (a description +/// `fitted`). +fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: []const [2]u32, lane: ?[3]u8, x: u16, y: u16, w: u16) void { const th = p.theme(); switch (g.kind) { .deleted => s.tint(x, y, w, pardes.colors.Grounds.of(th).del.row, th.lineno), @@ -1445,9 +1448,13 @@ fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: [ // `id title author age`: the last two words grey. var grey = said.len; for (0..2) |_| grey = std.mem.lastIndexOfScalar(u8, said[0..grey], ' ') orelse 0; - const lane_cells = File.displayWidth(p.settings.tab, said[0..grey]); + const id_cells = if (lane != null) File.displayWidth(p.settings.tab, said) else std.mem.indexOfScalar(u8, said, ' ') orelse said.len; + const title_cells = File.displayWidth(p.settings.tab, said[0..grey]); const cells = @min(w, File.displayWidth(p.settings.tab, said)); - for (0..cells) |c| s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = if (c < lane_cells) colours[g.pin % colours.len] else th.lineno }; + for (0..cells) |c| { + if (c >= id_cells and c < title_cells) continue; + s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = if (c >= title_cells) th.lineno else lane orelse th.kw }; + } }, } } @@ -1491,21 +1498,104 @@ pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool) ?us return best; } -/// A Look on body row `vr` of pane `id` when it is a ghost row (mouse.zig, -/// a B3 click): the line it shows in the revision it came from, as the -/// address `path@rev:line` opens it (a line taken away: its pin's parent's; -/// a description: its pin's first line). False on any other row. -pub fn lookGhost(p: *Pardes, id: usize, vr: i32) bool { +/// A Look (B3) at column `col` of body row `vr` of pane `id` when it is a +/// ghost row (mouse.zig): a regular Look of the word there, as the same +/// text anywhere is looked at; on a description's id, its change's patch at +/// the row for the last line of its this file has (`Diff <id> <path>:<line>`, +/// what a user could type). False on any other row. +pub fn lookGhost(p: *Pardes, id: usize, vr: i32, col: i32) bool { const pane = p.panes[id].?; if (pane.layers.lanes == 0 or !pane.wrapAt(p.settings.tab, vr).ghost) return false; const ch = answered(p, pane.serial) orelse return false; const gi: usize = @intCast(-1 - pane.wrap_col[@intCast(vr)]); if (gi >= pane.ghosts.len) return false; const g = pane.ghosts[gi]; - const f = &pane.file.?; - const path = if (of(f)) |r| r.path else f.path; - const rev: [9]u8 = ch.pins[g.pin].id ++ "-".*; - _ = open(p, id, path, rev[0 .. if (g.kind == .description) 8 else 9], .{ .line = g.line }, false); + const said = pane.ghost_text[g.text..][0..g.len]; + const at = File.rawAtDisplay(p.settings.tab, said, @intCast(@max(0, col - @as(i32, File.gutterWidth(pane))))); + const what = wordAt(said, at) orelse return true; + const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len; + if (g.kind == .description and what.ptr == said.ptr and what.len == id_end) { + const f = &pane.file.?; + const path = if (of(f)) |r| r.path else f.path; + var last: u32 = g.line; + for (ch.hunks) |h| if (h.pin == g.pin) { + last = @max(last, h.new_start + h.new_len -| 1); + }; + var line: [4200]u8 = undefined; + const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ ch.pins[g.pin].id, path, last }) catch return true; + pardes.exec.runBuiltin(p, .Diff, id, "Diff", arg); + return true; + } + pardes.look.lookAt(p, id, what); + return true; +} + +/// The word of a ghost row's text at byte `at`: a run of what a path, a +/// name, an address or an id is made of. +fn wordAt(text: []const u8, at: usize) ?[]const u8 { + const part = struct { + fn of(c: u8) bool { + return std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "_./:@-+~", c) != null or c >= 0x80; + } + }.of; + if (at >= text.len or !part(text[at])) return null; + var lo = at; + while (lo > 0 and part(text[lo - 1])) lo -= 1; + var hi = at; + while (hi < text.len and part(text[hi])) hi += 1; + return std.mem.trimEnd(u8, text[lo..hi], ".:"); +} + +/// A jj change id as jj writes one: its letters, k to z. +pub fn isChangeId(text: []const u8) bool { + if (text.len < 4 or text.len > 32) return false; + for (text) |c| if (c < 'k' or c > 'z') return false; + return true; +} + +/// `Diff <change> [path[:line]]` (hunks.zig): change `change` of the +/// repository pane `id`'s directory is in, its patch as `jj show --git` +/// prints it (its ids, author, dates and whole message above its hunks), +/// stacked in its +Diff (one a change: a second goes to it); the cursor on +/// the patch's row for `path`'s line `line` (that file's first row +/// without one; none of it: the top). False when it names no change. +pub fn diffChange(p: *Pardes, id: usize, arg: []const u8) bool { + var words = std.mem.tokenizeAny(u8, arg, " \t"); + const change = words.next() orelse return false; + if (!isChangeId(change)) return false; + const dir = pardes.filesystem.localPath(Pardes.paneDir(p.panes[id].?)) orelse return false; + var buf: [64]u8 = undefined; + const revset = std.fmt.bufPrint(&buf, "change_id({s})", .{change}) catch return false; + const shown = p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dir, @as([]const []const u8, &.{ "show", "--git", "-r", revset }) }); + const bytes = switch (shown) { + .refused => |why| { + p.gpa.free(why); + return false; + }, + .bytes => |b| b, + }; + defer p.gpa.free(bytes); + var name: [4200]u8 = undefined; + const hid = @import("hunks.zig").openDiff(p, id, std.fmt.bufPrint(&name, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), change }) catch return false, bytes) catch return false; + p.view().active = hid; + const place = look.parsePathLine(words.next() orelse return true); + const pane = p.panes[hid].?; + const rows = pane.file.?.location_rows; + const want = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, place.path }) catch return true; + var best: ?usize = null; + for (rows, 0..) |row, i| { + if (!std.mem.endsWith(u8, want, row.path) or row.path.len == 0) continue; + if (best == null) best = i; + if (row.at.line == place.at.line) { + best = i; + break; + } + } + if (best) |i| { + pane.body.cur_row = @intCast(i); + pane.body.cur_col = 0; + pane.ensureCursorVisible(p.settings.tab); + } return true; } @@ -1539,6 +1629,26 @@ fn nest(lines: []Line, npins: usize) void { } } +/// A diff's two inks (one change pinned, `paintLanes`): its lane's colour +/// says the kind of the row it stands beside (the user's rulings of +/// 2026-11-23), `added` beside a row it wrote (a line added whole, a changed +/// line's new text), `taken` beside a row it took away (a line taken away, a +/// changed line's old text). +pub const Inks = struct { added: [3]u8, taken: [3]u8 }; + +/// The diff's own two colours: the theme's green and its red (the grounds' +/// and the changed words' hues), each pushed toward the ink until it reads +/// 3:1 on the page (or nearly as the ink does, where the ink reads less). +pub fn laneInks(th: *const pardes.Theme) Inks { + var inks: [2][3]u8 = .{ if (th.palette) |c| c[2] else .{ 0x2e, 0xa0, 0x43 }, themeRed(th) }; + const page = th.bg orelse th.tag_bg; + for (&inks) |*ink| { + var step: usize = 0; + while (step < 8 and pardes.colors.contrast(ink.*, page) < 3) : (step += 1) ink.* = pardes.colors.mixOklab(ink.*, th.fg orelse th.tag_fg, 0.4); + } + return .{ .added = inks[0], .taken = inks[1] }; +} + /// The lanes' colours, a pin's the `pin % len`th, oldest first: the /// theme's accents but the two that mean written and taken away (its green /// and red), in hue order from the top, each a hue `hue_apart` or more from @@ -1666,6 +1776,9 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u var buf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &buf); if (colours.len == 0) return; + // One change pinned is a diff: its lane in the diff's own two colours, + // by the row's kind; several, a colour a change, to tell them apart. + const one: ?Inks = if (ch.pins.len == 1) laneInks(p.theme()) else null; const gutter = File.gutterWidth(pane); const cells = File.laneCells(pane); if (gutter >= tw or cells == 0) return; @@ -1677,13 +1790,18 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u var vr: u16 = pane.context_rows; while (vr < body_h) : (vr += 1) { const y = body_y + vr; + var taken = false; + // On a description row, its change's lane: an arrow to it. + var points: PinIndex = .none; const lanes: [levels]PinIndex = if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) ghost: { const gi: usize = @intCast(-1 - pane.wrap_col[vr]); if (gi >= pane.ghosts.len) continue; const g = pane.ghosts[gi]; const said = pane.ghost_text[g.text..][0..g.len]; var fit: [row_max]u8 = undefined; - inkGhost(p, s, g, if (g.kind == .description) fitted(p.settings.tab, said, File.bodyWidth(pane), &fit) else said, ch.marks, colours, tx + gutter, y, tw - gutter); + inkGhost(p, s, g, if (g.kind == .description) fitted(p.settings.tab, said, File.bodyWidth(pane), &fit) else said, ch.marks, if (one == null) colours[g.pin % colours.len] else null, tx + gutter, y, tw - gutter); + if (g.kind == .description) points = @enumFromInt(g.pin); + taken = g.kind != .description or takenAbove(pane.ghosts, gi); break :ghost ghostLanes(ch, pane.ghosts, gi); } else line: { const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; @@ -1695,20 +1813,38 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u }; for (lanes, 0..) |lane, level| { if (lane == .none) break; - const rgb = colours[@intFromEnum(lane) % colours.len]; + const arrow = lane == points; + const rgb = if (one) |d| (if (taken) d.taken else d.added) else colours[@intFromEnum(lane) % colours.len]; if (windowed) { // A body a pixel shell draws as a layer is painted on a // temporary surface first: its lanes are not drawn yet. - if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb }) catch {}; + if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb, .arrow = if (arrow) @intCast(cells) else 0 }) catch {}; } else if (level < cells) { var style = s.at(first + @as(u16, @intCast(level)), y).style; style.fg = .{ .rgb = rgb }; - s.set(first + @as(u16, @intCast(level)), y, "\u{258e}", style); + // An arrow: the lane bent into a shaft and a head at the text + // (`╰─→`, the user's choice of 2026-11-23 over `▎─→`); from + // the last level, where there is one cell, a bent arrow. + const at: u16 = @intCast(level); + s.set(first + at, y, if (!arrow) "\u{258e}" else if (at + 1 == cells) "\u{21b3}" else "\u{2570}", style); + if (arrow) for (at + 1..cells) |c| s.set(first + @as(u16, @intCast(c)), y, if (c + 1 == cells) "\u{2192}" else "\u{2500}", style); } } } } +/// Whether the row above description `ghosts[gi]` is one its lanes stand +/// beside as taken away: a ghost row of a line at its place, not a line. +fn takenAbove(ghosts: []const Ghost, gi: usize) bool { + var j = gi; + while (j > 0) { + j -= 1; + if (ghosts[j].at != ghosts[gi].at) return false; + if (ghosts[j].kind != .description) return true; + } + return false; +} + // ---- tests ---- const testing = std.testing; @@ -2143,6 +2279,19 @@ test "Changes draws a lane a pinned change after the line number, nested ones a } } +test "a diff's two lane inks in every theme: its green and its red, never one colour, each read on the page" { + for (&pardes.colors.themes) |*th| { + const inks = laneInks(th); + errdefer std.debug.print("{s}: added {any} taken {any}\n", .{ th.name, inks.added, inks.taken }); + try testing.expect(!std.meta.eql(inks.added, inks.taken)); + const page = th.bg orelse th.tag_bg; + // 3:1, or as near the theme's own ink's as it reads (hex_poison's). + const floor = @min(3, pardes.colors.contrast(th.fg orelse th.tag_fg, page)) - 0.1; + try testing.expect(pardes.colors.contrast(inks.added, page) >= floor); + try testing.expect(pardes.colors.contrast(inks.taken, page) >= floor); + } +} + /// A function `fn` wrote, two of its lines `cut` took away whole, and one /// `mid` rewrote as two (one changed, one added whole). const Ghosts = struct { @@ -2183,7 +2332,7 @@ fn saidOf(arena: std.mem.Allocator, ch: *const Changes) ![3][]const u8 { return said; } -test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour; no number, their lanes, the rows below moved down in this view alone" { +test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour, its lane an arrow to it; no number, their lanes; one change pinned, its lane green beside what it wrote and red beside what it took away; the rows below moved down in this view alone" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2220,19 +2369,27 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line const lanes = [_][]const u8{ "0", "0", "02", "02", "02", "02", "01", "01", "01", "0", "0", "0" }; const Ground = enum { none, add, del }; const ground = [_]Ground{ .add, .add, .none, .none, .add, .none, .del, .del, .none, .add, .add, .none }; - for (lanes, ground, 0..) |pins, gr, row| { + // On a description row the level its change's arrow leaves from. + const arrows = [_]?usize{ null, null, null, null, null, 1, null, null, 1, null, null, 0 }; + for (lanes, ground, arrows, 0..) |pins, gr, arrow, row| { const y = body.y + @as(u16, @intCast(row)); if (windowed) { var n: usize = 0; for (s.lanes.items) |lane| if (lane.y == y) { + try testing.expect(lane.level < pins.len); try testing.expectEqual(colours[pins[lane.level] - '0'], lane.rgb); + try testing.expectEqual(@as(u8, if (arrow == lane.level) @intCast(File.laneCells(pane)) else 0), lane.arrow); n += 1; }; try testing.expectEqual(pins.len, n); - } else for (pins, 0..) |pin, level| { + } else for (0..levels) |level| { + // `â–Ž` a lane; an arrow: its lane bent, a shaft, a head (`╰─→`). const cell = s.at(first + @as(u16, @intCast(level)), y); - try testing.expectEqualStrings("\u{258e}", cell.grapheme()); - try testing.expectEqual(pardes.Color{ .rgb = colours[pin - '0'] }, cell.style.fg); + const bent = arrow != null and arrow.? == level; + const glyph = if (level < pins.len) (if (!bent) "\u{258e}" else if (level + 1 == levels) "\u{21b3}" else "\u{2570}") else if (arrow == null) " " else if (level + 1 == levels) "\u{2192}" else "\u{2500}"; + try testing.expectEqualStrings(glyph, cell.grapheme()); + const pin = if (level < pins.len) pins[level] - '0' else pins[arrow orelse 0] - '0'; + if (!std.mem.eql(u8, glyph, " ")) try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, cell.style.fg); } const cell = s.at(body.x + File.gutterWidth(pane) + 1, y); const bg: ?[3]u8 = switch (gr) { @@ -2247,8 +2404,10 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line } // A description's id and title in its lane's colour; a line taken // away in the numbers' grey. - for ([_]u16{ 5, 8, 11 }, [_]usize{ 2, 1, 0 }) |row, pin| + for ([_]u16{ 5, 8, 11 }, [_]usize{ 2, 1, 0 }) |row, pin| { try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane), body.y + row).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(body.x + File.gutterWidth(pane) + 5, body.y + row).style.fg); + } try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(body.x + File.gutterWidth(pane) + 4, body.y + 6).style.fg); // The changed line: on its old text the word that went (`b`) red, // on it the word that came (`b2`) green; the rest of each neither. @@ -2262,10 +2421,35 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line for (plain[0..6]) |row| try testing.expectEqualStrings(lines.next().?, Ghosts.text(pane, row)); p.toView(.at(0)); try testing.expectEqualStrings(said[2], Ghosts.text(pane, (try Ghosts.rows(p, pane, arena.allocator(), &buf))[5])); + // One change pinned, mid: a diff. Its rows `b();` (its old text), + // `b2();`, `x();`, its description: the lane red beside the first, + // green beside the lines, green into its arrow; its id the + // keyword's ink, its title the text's. + var one: [64]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&one, "Changes {s}", .{ch.pins[2].id}) }); + p.sync(); + const s1 = try p.render(arena.allocator()); + const top = s1.region(.body, id).?.rect.y; + const at = body.x + File.gutterWidth(pane) - File.laneCells(pane); + const inks = laneInks(p.theme()); + try testing.expect(!std.meta.eql(inks.added, inks.taken)); + for ([_]u16{ 2, 3, 4, 5 }, [_]bool{ true, false, false, false }) |row, red| { + const ink = if (red) inks.taken else inks.added; + if (windowed) { + var n: usize = 0; + for (s1.lanes.items) |lane| if (lane.y == top + row) { + try testing.expectEqual(ink, lane.rgb); + n += 1; + }; + try testing.expectEqual(@as(usize, 1), n); + } else try testing.expectEqual(pardes.Color{ .rgb = ink }, s1.at(at, top + row).style.fg); + } + try testing.expectEqual(pardes.Color{ .rgb = p.theme().kw }, s1.at(text_x, top + 5).style.fg); + try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().kw }, s1.at(text_x + 5, top + 5).style.fg)); } } -test "the cursor steps over ghost rows and selection does not see them; ]g and [g go from change to change; a Look on one opens its line in the revision it came from" { +test "the cursor steps over ghost rows and selection does not see them; ]g and [g go from change to change; a Look on one looks at its word as anywhere" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2309,18 +2493,84 @@ test "the cursor steps over ghost rows and selection does not see them; ]g and [ key(p, "[g"); try testing.expectEqual(want, pane.body.cur_row); } - // A Look (B3) on `c();`'s ghost row: fn's revision (cut's parent) at its line 4. + // A Look (B3) on `c();`'s ghost row is a Look of `c`, as `Look c` + // typed in the pane: no file at a revision opens. + p.update(.{ .command = "Look a.zig:1" }); p.sync(); s = try p.render(arena.allocator()); body = s.region(.body, id).?.rect; - p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 6 } }); - p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 6 } }); - const shown = p.view().active; - try testing.expect(shown != id); - const f = &p.panes[shown].?.file.?; - try testing.expect(of(f) != null); - try testing.expectEqualStrings(Ghosts.fn_text, f.content); - try testing.expectEqual(@as(i32, 3), p.panes[shown].?.body.cur_row); + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = body.x + File.gutterWidth(pane) + 4, .row = body.y + 6 } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = body.x + File.gutterWidth(pane) + 4, .row = body.y + 6 } }); + try testing.expectEqual(id, p.view().active); + for (p.panes) |slot| if (slot) |q| if (q.file) |*f| try testing.expect(of(f) == null); + const clicked: [2]i32 = .{ pane.body.cur_row, pane.body.cur_col }; + p.update(.{ .command = "Look a.zig:1" }); + look.lookAt(p, id, "c"); + try testing.expectEqual(clicked, [2]i32{ pane.body.cur_row, pane.body.cur_col }); +} + +test "a Look on a change's id opens its patch, its header and whole message at the top: on a description row, at the row of that change's last line in this file; in any text, at the top; a word that names no change is looked as any word" { + const gpa = testing.allocator; + var repo = try Ghosts.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + for ([_]bool{ false, true }) |windowed| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = windowed }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = "Changes ::@" }); + const ch = answered(p, pane.serial).?; + const mid = ch.pins[2].id; + p.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + // mid's description (row 5): a B3 on its id. + const x = body.x + File.gutterWidth(pane) + 1; + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 5 } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 5 } }); + const hid = p.view().active; + try testing.expect(hid != id); + const patch = p.panes[hid].?; + const f = &patch.file.?; + try testing.expectStringStartsWith(f.path, try std.fmt.allocPrint(arena.allocator(), "{s}/+Diff-", .{repo.dir})); + // jj show's header, the whole message, above the hunks. + var rows = std.mem.splitScalar(u8, f.content, '\n'); + try testing.expectStringStartsWith(rows.next().?, "Commit ID: "); + try testing.expectStringStartsWith(rows.next().?, try std.fmt.allocPrint(arena.allocator(), "Change ID: {s}", .{mid})); + try testing.expectStringStartsWith(rows.next().?, "Author : t <t@t>"); + try testing.expect(std.mem.indexOf(u8, f.content, "\n mid\n") != null); + // The cursor on mid's last line in a.zig, `x();` (its line 4). + try testing.expectEqualStrings("a.zig:4", try std.fmt.allocPrint(arena.allocator(), "{s}:{d}", .{ std.Io.Dir.path.basename(f.location_rows[@intCast(patch.body.cur_row)].path), f.location_rows[@intCast(patch.body.cur_row)].at.line })); + // The same, typed: one pane a change, the cursor moved there. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:2", .{mid}) }); + try testing.expectEqual(hid, p.view().active); + try testing.expectEqual(@as(usize, 2), f.location_rows[@intCast(patch.body.cur_row)].at.line); + // In running text: the patch at its top. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{ch.pins[1].id}) }); + const cut = p.panes[p.view().active].?; + try testing.expectStringStartsWith(cut.file.?.content, "Commit ID: "); + try testing.expect(std.mem.indexOf(u8, cut.file.?.content, "\n cut\n") != null); + try testing.expectEqual(@as(i32, 0), cut.body.cur_row); + // A word of k to z that names no change: no patch. + const patches = struct { + fn count(q: *Pardes) usize { + var n: usize = 0; + for (q.panes) |slot| if (slot) |o| if (o.file) |*of_| { + n += @intFromBool(std.mem.indexOf(u8, of_.path, "+Diff-") != null); + }; + return n; + } + }.count; + const before = patches(p); + p.update(.{ .command = "Look zzzzzzzz" }); + try testing.expectEqual(before, patches(p)); + } } test "ghost rows ride with the text: a line deleted above moves them up, a line they stood before deleted puts them before the next; a client replays it equal" { @@ -2385,14 +2635,13 @@ test "a description's ghost row keeps its author and age: in a pane narrower tha try testing.expect(File.displayWidth(p.settings.tab, row) <= room); try testing.expectStringStartsWith(row, try std.fmt.allocPrint(arena.allocator(), "{s} a title long", .{ch.pins[0].id[0..4]})); try testing.expectStringEndsWith(row, "\u{2026} t now"); - // Drawn: the id and the title in its lane's colour, the author and - // the age grey, at the row's end. + // Drawn: the id in the keyword's ink, the author and the age grey, + // at the row's end. p.sync(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const x = body.x + File.gutterWidth(pane); - var cbuf: [8][3]u8 = undefined; - try testing.expectEqual(pardes.Color{ .rgb = laneColours(p.theme(), &cbuf)[0] }, s.at(x, body.y + 3).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().kw }, s.at(x, body.y + 3).style.fg); const age_x = x + @as(u16, @intCast(File.displayWidth(p.settings.tab, row))) - 1; try testing.expectEqualStrings("w", s.at(age_x, body.y + 3).grapheme()); try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(age_x, body.y + 3).style.fg); diff --git a/core/mouse.zig b/core/mouse.zig index 91d2932c..7c9007a1 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1250,10 +1250,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } } else { const clk = pane.sel[b]; - // A right-click on a ghost row (jj.zig) looks at its line - // in the revision it came from. + // A right-click on a ghost row (jj.zig) looks at the word + // there, as anywhere. if (s.button == config.look_button and clk.r0 >= pane.tag_rows and clk.r0 == clk.r1 and clk.c0 == clk.c1 and - pane.layers.lanes > 0 and @import("jj.zig").lookGhost(p, s.id, clk.r0 - pane.tag_rows)) + pane.layers.lanes > 0 and @import("jj.zig").lookGhost(p, s.id, clk.r0 - pane.tag_rows, clk.c0)) { pane.sel[b].state = .none; return; diff --git a/core/plumbing b/core/plumbing index 4e8cd702..7292577f 100644 --- a/core/plumbing +++ b/core/plumbing @@ -43,6 +43,15 @@ data matches '[0-9a-f]*[0-9][0-9a-f]*' data matches '[0-9a-f]*[a-f][0-9a-f]*' plumb start Diff $0 +# a jj change id looked at in the editor (eight or more of its letters, +# k to z, as jj log shows them), in a jj repository: jj show, its header +# and its hunks, stacked in a +Diff (a word that names no change: Diff +# declines and the word is searched for) +type is text +src is pardes +data matches '[k-z]{8,32}' +plumb start Diff $0 + # a diff paged (git show, git log -p) is shown stacked in a +Diff in # its +Pager's place type is text/x-diff diff --git a/core/replica.zig b/core/replica.zig index 214cc34e..6c4f0b2c 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -1295,6 +1295,20 @@ pub const Framer = struct { } } + /// A join's welcome a link's reader stopped at (`readLink`), first again + /// for the join's reader, what was read past it after it; the stream it + /// ends lets its decompressor go (the join's is a frame of its own). + fn putBack(fr: *Framer, gpa: Allocator, msg: []const u8) bool { + if (fr.buf.items.len < fr.len + msg.len) fr.buf.resize(gpa, fr.len + msg.len) catch return false; + std.mem.copyBackwards(u8, fr.buf.items[msg.len..][0..fr.len], fr.buf.items[0..fr.len]); + @memcpy(fr.buf.items[0..msg.len], msg); + fr.len += msg.len; + fr.inner.clearRetainingCapacity(); + if (fr.z) |z| _ = zstd.ZSTD_freeDCtx(z); + fr.z = null; + return true; + } + /// An envelope's bytes onto `inner`. Its writer flushed at most /// `zstd.piece` of input into it, so it unpacks to no more than that. fn unpack(fr: *Framer, gpa: Allocator, payload: []const u8) bool { @@ -1340,8 +1354,10 @@ pub const Peer = struct { view: Pardes.View.Id, /// Its process (its socket's peer), for `--ps`; 0 not known. pid: libc.pid_t = 0, - /// Its bye said it joins again for its view (a divergence's rejoin): - /// kept for it (views.away), not closed. Its reader's, read after its end. + /// Its bye said it joins again for its view: its hello comes next on + /// this link (`Peers.joinAgain`), or the link's end (a client of another + /// build gone to exec this one's: `sameBuild`), its view kept for it then + /// (views.away), not closed. Its reader's, read after its end. again: bool = false, /// ...or that its window was closed (Peers.closed). close: bool = false, @@ -1366,9 +1382,15 @@ pub const Peer = struct { /// What may wait in `out` before it is cut off (a test's less). limit: usize = lag_max, closing: bool = false, - /// Cut off (`send`): the words why are the last it is sent, and its - /// view is kept for it (views.away), as for a bye's `again`. + /// Cut off (`send`): the words why, then nothing until its client's + /// hello again on this link (`Peers.joinAgain`); its view is kept for it + /// (views.away) if the link ends first, as for a bye's `again`. cut: bool = false, + /// Its joins on this link the session has dumped (`Peers.join`, + /// `Peers.joinAgain`), and how many its writer has written whole: one not + /// written is the writer's next (`writeLoop`). Under `lock`. + gen: u32 = 1, + written: u32 = 0, /// Its client's join again for its view, come before this link's end /// was heard: judged once it is let go (`Peers.join`, `letGo`). rejoin: ?Peers.Joining = null, @@ -1399,22 +1421,36 @@ pub const Peer = struct { zin: usize = 0, fn writeJoin(peer: *Peer) bool { + // Again over this link: the old stream's frame ended and its + // compressor let go; the join's is a frame of its own. + if (peer.z) |z| { + if (!peer.zWrite(&.{}, .end)) return false; + _ = zstd.ZSTD_freeCCtx(z); + peer.z = null; + peer.zout.clearRetainingCapacity(); + peer.zin = 0; + } if (!writeAll(peer.fd, peer.welcome[0..peer.welcome_len])) return false; const io = peer.peers.io; peer.lock.lockUncancelable(io); while (peer.far == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const far = peer.far; + // A pair's word on its first join alone. const boot = peer.boot; + peer.boot = null; peer.lock.unlock(io); - if (far orelse return false) return peer.farJoin(); - // Its client made this core itself (a pair's): nothing to send. - if (boot == peer.digest) return true; - var pos: usize = 0; - for (peer.blobs.items) |b| { - if (!writePieces(peer.fd, peer.dump[pos..b.at]) or !writePieces(peer.fd, b.bytes)) return false; - pos = b.at; + if (far orelse return false) { + if (!peer.farJoin()) return false; + } else if (boot != peer.digest) { + // (Its client made this core itself, a pair's: nothing to send.) + var pos: usize = 0; + for (peer.blobs.items) |b| { + if (!writePieces(peer.fd, peer.dump[pos..b.at]) or !writePieces(peer.fd, b.bytes)) return false; + pos = b.at; + } + if (!writePieces(peer.fd, peer.dump[pos..])) return false; } - return writePieces(peer.fd, peer.dump[pos..]); + return true; } /// A far client's join, in one zstd frame: the list of the dump's blobs @@ -1455,6 +1491,11 @@ pub const Peer = struct { for (peer.blobs.items, 0..) |b, i| if (bits[i / 8] >> @intCast(i % 8) & 1 != 0) { if (!peer.zPieces(b.bytes)) return false; }; + // This join's answer, used: a join again over this link asks its own. + peer.lock.lockUncancelable(io); + peer.want = null; + peer.lock.unlock(io); + peer.peers.gpa.free(bits); } if (!peer.zWrite(&.{}, .end)) return false; _ = zstd.ZSTD_freeCCtx(peer.z); @@ -1520,8 +1561,9 @@ pub const Peer = struct { /// `parts` queued for it, in order; never waits. A client whose queue /// passes its limit is cut off: what waits for it is let go and the - /// words why queued in its place, after which its writer ends its link - /// (`writeLoop`); it joins again from a dump, for its view (`leave`). + /// words why queued in its place, and nothing after them: it says its + /// goodbye and its hello again on this link and is dumped there, for + /// its view (`Peers.joinAgain`). fn send(peer: *Peer, parts: []const []const u8) void { const io = peer.peers.io; peer.lock.lockUncancelable(io); @@ -1596,45 +1638,90 @@ pub const Peer = struct { peer.lock.unlock(io); } + /// Its join, then what it is sent; a join again over this link + /// (`Peers.joinAgain`) next whenever one is dumped, what was queued before + /// it let go. Ends once it is let go and has written what it holds. fn writeLoop(peer: *Peer) void { const io = peer.peers.io; defer peer.done.store(true, .release); - if (!peer.writeJoin()) { - _ = libc.shutdown(peer.fd, 2); - return; - } - // Its pins let go at the next boundary. - peer.peers.post(.{ .joined = peer }); while (true) { peer.lock.lockUncancelable(io); - while (peer.out.items.len == 0 and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); - if (peer.out.items.len == 0) { + while (peer.out.items.len == 0 and !peer.closing and peer.written == peer.gen) peer.cond.waitUncancelable(io, &peer.lock); + const gen = peer.gen; + const joining = peer.written != gen; + if (!joining and peer.out.items.len == 0) { peer.lock.unlock(io); return; } - std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); - // Cut off: the words why came last, and its link ends after them. - const cut_off = peer.cut; + if (!joining) std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); peer.lock.unlock(io); - const ok = if (peer.z != null) peer.zWrite(peer.sending.items, .flush) else writeAll(peer.fd, peer.sending.items); - peer.sending.clearRetainingCapacity(); - if (!ok or cut_off) { + const ok = if (joining) peer.writeJoin() else peer.writeOut(); + if (!ok) { _ = libc.shutdown(peer.fd, 2); return; } + if (!joining) continue; + peer.lock.lockUncancelable(io); + peer.written = gen; + peer.lock.unlock(io); + // Its pins let go at the next boundary. + peer.peers.post(.{ .joined = .{ .peer = peer, .gen = gen } }); } } + /// What it was sent (`sending`), a MiB at most a write and at a + /// message's end: a join due again over this link waits for no more of + /// the stream it leaves than that, the rest let go. + fn writeOut(peer: *Peer) bool { + defer peer.sending.clearRetainingCapacity(); + const all = peer.sending.items; + var at: usize = 0; + while (at < all.len) { + var end = at; + while (wire.framed(all[end..]) catch null) |f| { + if (end > at and end + f.total - at > dump_piece) break; + end += f.total; + } + if (end == at) end = all.len; + if (!(if (peer.z != null) peer.zWrite(all[at..end], .flush) else writeAll(peer.fd, all[at..end]))) return false; + at = end; + if (at < all.len and peer.joinDue()) return true; + } + return true; + } + + fn joinDue(peer: *Peer) bool { + const io = peer.peers.io; + peer.lock.lockUncancelable(io); + defer peer.lock.unlock(io); + return peer.written != peer.gen; + } + 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, + // Its hello again on this link, its goodbye saying it joins + // again just before (runtime/client.zig `run`): the session's + // state dumped for it here (`Peers.joinAgain`), its inputs numbered + // afresh. A hello anywhere else ends the link. + .hello => { + if (!peer.bye or !peer.again) return false; + _ = wire.decodeClient(tag, payload) catch return false; + peer.again = false; + peer.close = false; + peer.bye = false; + peer.seq = 0; + peer.stamped = false; + peer.peers.post(.{ .again = peer }); + return true; + }, + // Read on after one that says it joins again: its hello. .bye => { const b = (wire.decodeClient(tag, payload) catch return false).bye; peer.again = b.again; peer.close = b.close; peer.bye = true; - return false; + return b.again; }, .ping => { var out: [16]u8 = undefined; @@ -1746,7 +1833,10 @@ pub const Peers = struct { seq: u32 = 0, lock: std.Io.Mutex = .init, inbox: std.ArrayListUnmanaged(Note) = .empty, + /// The batch `boundary` takes, and the note it is at: a client let go + /// there (`letGo`) takes its notes after that one out too. taken: std.ArrayListUnmanaged(Note) = .empty, + taking: usize = 0, /// A reader posted: the loop's one test a step while nothing is attached. mail: std.atomic.Value(bool) = .init(false), /// ...and what it posted was a client's input or a join, which the @@ -1792,6 +1882,8 @@ pub const Peers = struct { input_ns: std.ArrayListUnmanaged(u64) = .empty, boundary_ns: std.ArrayListUnmanaged(u64) = .empty, cut: u32 = 0, + /// Joins again over a client's own link (`joinAgain`): no dial, no daemon. + again_here: u32 = 0, head: [unit_head]u8 = undefined, /// 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 @@ -1799,7 +1891,9 @@ pub const Peers = struct { /// (`Peer.take`, then `.gone` posted) are its driver's to do. threads: bool = true, - pub const Note = union(enum) { join: Joining, input: Msg, gone: *Peer, check: *Peer, joined: *Peer }; + pub const Note = union(enum) { join: Joining, input: Msg, gone: *Peer, check: *Peer, joined: Written, again: *Peer }; + /// A join its writer wrote whole: the `gen`-th on its link (`Peer.gen`). + pub const Written = struct { peer: *Peer, gen: u32 }; /// A connection to join, and the view it joins again for, if it does. pub const Joining = daemon.Joining; pub const Msg = struct { peer: *Peer, msg: []u8 }; @@ -1821,6 +1915,8 @@ pub const Peers = struct { switch (note) { .join => |j| _ = libc.close(j.fd), .input => |in| ps.gpa.free(in.msg), + // Never dumped again: its link ended, as the session lets it go. + .again => |peer| _ = libc.shutdown(peer.fd, 2), .gone, .check, .joined => {}, } return; @@ -1874,14 +1970,17 @@ pub const Peers = struct { std.mem.swap(std.ArrayListUnmanaged(Note), &ps.inbox, &ps.taken); ps.mail.store(false, .release); ps.lock.unlock(ps.io); - for (ps.taken.items) |note| switch (note) { + ps.taking = 0; + while (ps.taking < ps.taken.items.len) : (ps.taking += 1) switch (ps.taken.items[ps.taking]) { .join => |j| ps.join(core, j), .input => |in| { ps.input(core, in.peer, in.msg); ps.gpa.free(in.msg); }, .gone => |peer| ps.leave(core, peer), - .joined => |peer| released(peer), + // One dumped again over its link since holds that join's pins. + .joined => |w| if (w.gen == w.peer.gen) released(w.peer), + .again => |peer| ps.joinAgain(core, peer), .check => |peer| { var out: [16]u8 = undefined; peer.send(&.{wire.encodeServer(&out, .{ .check = tape.digestOf(core) }) catch unreachable}); @@ -1969,14 +2068,8 @@ pub const Peers = struct { var why: [128]u8 = undefined; return daemon.refuseReplica(fd, if (left == 0) full else std.fmt.bufPrint(&why, full ++ " (one is kept {d} s more for a client joining again)", .{(left + std.time.ns_per_s - 1) / std.time.ns_per_s}) catch full); }; - ps.seq += 1; - ps.unit(0, ps.seq); - // The session's mutable state, dumped now; its blobs (file texts, - // undo, registers) left out, pinned, and streamed by the client's - // writer thread: the step pays for the state, not for the text. var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; - const dumped = pardes.dump.dumpJoin(core, &blobs) catch |err| { - blobs.deinit(core.gpa); + const got = ps.dumped(core, &blobs) catch |err| { core.undrawn &= ~(@as(u8, 1) << @intCast(k)); core.closeView(.at(k)); ps.unit(0, ps.seq); @@ -1984,31 +2077,17 @@ pub const Peers = struct { var why: [96]u8 = undefined; return daemon.refuseReplica(fd, std.fmt.bufPrint(&why, "that session could not be dumped: {t}", .{err}) catch "that session could not be dumped"); }; - const bytes = dumped.bytes; - var whole = bytes.len; - for (blobs.items) |b| { - pardes.memory.pin(b.bytes); - whole += b.bytes.len; - } - ps.dump_bytes = whole; - ps.state_bytes = bytes.len; - // The joiner's core is the dump's: the host this tape wraps, and - // what the host wrote in the core, are said again at the next input. - tape.resync(&ps.t); + const bytes = got.bytes; const peer = ps.gpa.create(Peer) catch { for (blobs.items) |b| pardes.memory.unpin(b.bytes); blobs.deinit(core.gpa); core.gpa.free(bytes); return daemon.refuseReplica(fd, "out of memory"); }; - peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa, .pair = joining.own }; + peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump_gpa = core.gpa, .pair = joining.own }; ps.next_id +%= 1; if (ps.next_id == 0) ps.next_id = 1; - // The session's digest as dumped, for the joiner to check its load by - // (a pair's client, its own boot: `writeJoin`). - const digest = dumped.digest; - peer.digest = digest; - 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 = peer.view, .dump_len = whole, .gmtoff = gmtoff(), .digest = digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; + ps.welcome(peer, bytes, got.digest, blobs); 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)) { @@ -2021,10 +2100,90 @@ pub const Peers = struct { slot.* = peer; peer.pid = peerPid(fd); ps.tellClients(); - log.info("client {d} joined '{s}' as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, k, whole >> 10, bytes.len >> 10, (nowNs() - t0) / 1000 }); + log.info("client {d} joined '{s}' as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, k, ps.dump_bytes >> 10, ps.state_bytes >> 10, (nowNs() - t0) / 1000 }); if (std.c.getenv("PARDES_REPLICA_TRACE") != null) std.debug.print("session: client {d} joined after unit {d}\n", .{ peer.id, ps.seq }); } + /// What was recorded sent as a unit, then the session's mutable state + /// dumped for a join; its blobs (file texts, undo, registers) left out, + /// pinned, and streamed by the client's writer thread: the step pays for + /// the state, not for the text. The joiner's core is the dump's: the host + /// this tape wraps, and what the host wrote in the core, are said again + /// at the next input. With the session's digest taken with the dump + /// (`dumpJoin`: one moment). + fn dumped(ps: *Peers, core: *Pardes, blobs: *std.ArrayListUnmanaged(walk.Deferred)) !struct { bytes: []u8, digest: u64 } { + ps.seq += 1; + ps.unit(0, ps.seq); + const got = pardes.dump.dumpJoin(core, blobs) catch |err| { + blobs.deinit(core.gpa); + return err; + }; + var whole = got.bytes.len; + for (blobs.items) |b| { + pardes.memory.pin(b.bytes); + whole += b.bytes.len; + } + ps.dump_bytes = whole; + ps.state_bytes = got.bytes.len; + tape.resync(&ps.t); + return .{ .bytes = got.bytes, .digest = got.digest }; + } + + /// `peer`'s join made of the dump `bytes`: its welcome, with the + /// session's `digest` as dumped for the joiner to check its load by (a + /// pair's client, its own boot: `writeJoin`). + fn welcome(ps: *Peers, peer: *Peer, bytes: []u8, digest: u64, blobs: std.ArrayListUnmanaged(walk.Deferred)) void { + peer.dump = bytes; + peer.blobs = blobs; + peer.digest = digest; + 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 = peer.view, .dump_len = ps.dump_bytes, .gmtoff = gmtoff(), .digest = peer.digest, .semantics = wire.semantics, .blobs = @intCast(blobs.items.len) } }) catch unreachable).len; + } + + /// Its client's goodbye and hello again on its link (`Peer.take`: it + /// diverged, fell behind, or was cut off): the session's state dumped + /// for it there, for its view, away a moment and its own again in one + /// step (one connection, in order: no other client can take it + /// meanwhile), what was queued for it before let go, its writer's next + /// a join (`writeLoop`). The daemon is not asked. Its last join not + /// written whole yet (no client's road), its link let go meanwhile, or + /// no dump: its link ends (it dials again, `replica.join`). + fn joinAgain(ps: *Peers, core: *Pardes, peer: *Peer) void { + if (!ps.dumpAgain(core, peer)) _ = libc.shutdown(peer.fd, 2); + } + + /// `joinAgain`'s dump; false when its link is to end. + fn dumpAgain(ps: *Peers, core: *Pardes, peer: *Peer) bool { + const io = ps.io; + peer.lock.lockUncancelable(io); + const ok = !peer.closing and peer.written == peer.gen; + peer.lock.unlock(io); + if (!ok) return false; + const t0 = nowNs(); + defer { + ps.join_ns = @max(ps.join_ns, nowNs() - t0); + if (ps.samples) ps.each_join.append(ps.gpa, nowNs() - t0) catch {}; + } + // The last join's pins, if its note has not come yet (it is written). + released(peer); + // Its view away a moment and its own again, as a client that left + // and joined for it (`leave`, `join`): every side's terminals + // reloaded in that step (Core.rejoinView), as the dump's are. + core.awayView(peer.view); + peer.view = .at(viewFor(core, peer.view.index(), false) orelse return false); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + const got = ps.dumped(core, &blobs) catch return false; + peer.lock.lockUncancelable(io); + ps.welcome(peer, got.bytes, got.digest, blobs); + peer.out.clearRetainingCapacity(); + peer.cut = false; + peer.gen += 1; + peer.cond.signal(io); + peer.lock.unlock(io); + ps.again_here += 1; + log.info("client {d} joined '{s}' again on its link as view {d}: a {d} KB dump ({d} KB of state) in {d} us", .{ peer.id, ps.name, peer.view.index(), ps.dump_bytes >> 10, ps.state_bytes >> 10, (nowNs() - t0) / 1000 }); + return true; + } + /// A joiner's view in `core`: the one kept for it since it left /// (views.away), or one new; someone looks at the session now (its /// messages go by keys, not the clock), and that view is its own @@ -2108,28 +2267,35 @@ pub const Peers = struct { if (peer.want) |b| ps.gpa.free(b); if (peer.z) |z| _ = zstd.ZSTD_freeCCtx(z); peer.zout.deinit(ps.gpa); - // What its reader posted after it was let go (its end) is nobody's. + // What it posted and is not taken yet is nobody's: its reader's + // after it was let go (its end), and its writer's last (`.joined`) + // in the next batch or after this note in the one taken now. ps.lock.lockUncancelable(io); - var i: usize = 0; - while (i < ps.inbox.items.len) { - const mine = switch (ps.inbox.items[i]) { + ps.dropNotes(&ps.inbox, 0, peer); + ps.lock.unlock(io); + ps.dropNotes(&ps.taken, ps.taking + 1, peer); + if (peer.rejoin) |j| ps.post(.{ .join = j }); + ps.gpa.destroy(peer); + } + + /// `peer`'s notes in `list` from `from` on taken out, in order (an + /// input's bytes freed). + fn dropNotes(ps: *Peers, list: *std.ArrayListUnmanaged(Note), from: usize, peer: *const Peer) void { + var i = from; + while (i < list.items.len) { + const mine = switch (list.items[i]) { .input => |in| in.peer == peer, - .gone, .check, .joined => |p| p == peer, + .gone, .check, .again => |p| p == peer, + .joined => |w| w.peer == peer, .join => false, }; if (!mine) { i += 1; continue; } - switch (ps.inbox.items[i]) { - .input => |in| ps.gpa.free(in.msg), - else => {}, - } - _ = ps.inbox.orderedRemove(i); + if (list.items[i] == .input) ps.gpa.free(list.items[i].input.msg); + _ = list.orderedRemove(i); } - ps.lock.unlock(io); - if (peer.rejoin) |j| ps.post(.{ .join = j }); - ps.gpa.destroy(peer); } /// Every client told the session is upgrading and let go, its view with @@ -2271,7 +2437,7 @@ pub const Peers = struct { for (ps.inbox.items) |note| switch (note) { .join => |j| _ = libc.close(j.fd), .input => |in| ps.gpa.free(in.msg), - .gone, .check, .joined => {}, + .gone, .check, .joined, .again => {}, }; ps.inbox.clearRetainingCapacity(); ps.lock.unlock(ps.io); @@ -2289,10 +2455,11 @@ pub const Peers = struct { fn writeStats(ps: *Peers, path: []const u8) void { var buf: [400]u8 = undefined; - const line = std.fmt.bufPrint(&buf, "session inputs {d} input_us {d}/{d}/{d} boundaries {d} boundary_us {d}/{d}/{d} join_us {d} dump_kb {d} state_kb {d} cut {d}\n", .{ + const line = std.fmt.bufPrint(&buf, "session inputs {d} input_us {d}/{d}/{d} boundaries {d} boundary_us {d}/{d}/{d} join_us {d} dump_kb {d} state_kb {d} cut {d} again {d}\n", .{ ps.input_ns.items.len, pctOf(ps.input_ns.items, 50) / 1000, pctOf(ps.input_ns.items, 99) / 1000, pctOf(ps.input_ns.items, 100) / 1000, ps.boundary_ns.items.len, pctOf(ps.boundary_ns.items, 50) / 1000, pctOf(ps.boundary_ns.items, 99) / 1000, pctOf(ps.boundary_ns.items, 100) / 1000, ps.join_ns / 1000, ps.dump_bytes >> 10, ps.state_bytes >> 10, ps.cut, + ps.again_here, }) catch return; var z: [4096]u8 = undefined; const pz = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return; @@ -2361,15 +2528,17 @@ pub fn dial(gpa: Allocator, path: []const u8, session: []const u8, why: []u8, ha _ = libc.close(fd); return said(why, "nothing answers at {s}", .{path}); } - return joinOn(gpa, fd, session, why, have, view, null); + return joinOn(gpa, fd, session, why, have, view, null, .{}); } -/// `dial`'s, on a connection made: the hello, then the join. The -/// connection is closed if the join fails. No session named: no hello, a -/// pair's (Options.pair), whose session took it as its first client. `boot`: -/// a pair's client that made its core itself and said so (`boot`): nothing -/// said here, and its welcome's digest the same, no dump comes. -fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8, boot_digest: ?u64) ?Joined { +/// `dial`'s, on a connection made: the hello, then the join, read on from +/// `rest` (what its reader read already). The connection is closed if the +/// join fails. No session named: no hello said here: a pair's +/// (Options.pair), whose session took it as its first client, or one +/// joining again over its link, its hello said there (`comeBack`). `boot`: +/// a pair's client that made its core itself and said so (`boot`): +/// nothing said here, and its welcome's digest the same, no dump comes. +fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Have, view: ?u8, boot_digest: ?u64, rest: Framer) ?Joined { var out: [wire.hello_max + 16]u8 = undefined; const hello = if (session) |name| wire.encodeClient(&out, .{ .hello = .{ .session = name, .view = view } }) catch { _ = libc.close(fd); @@ -2377,7 +2546,7 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha } else out[0..0]; // Its first word, in the same write: whether it is far. const far = wire.encodeClient(out[hello.len..], .{ .far = have != null }) catch unreachable; - var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{} }; + var j: Joined = .{ .fd = fd, .pid = 0, .client = 0, .view = 0, .gmtoff = 0, .dump = &.{}, .rest = rest }; const Read = struct { j: *Joined, gpa: Allocator, @@ -2462,6 +2631,9 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha r.done = true; return false; }, + // What the stream it leaves still brings, joining again over + // its link (`loadAgain`): let go until the welcome. + .unit, .blob, .check, .pong => return !r.welcomed or r.fail("the session sent a unit before its dump"), else => return r.fail("the session sent a unit before its dump"), } } @@ -2515,6 +2687,7 @@ fn joinOn(gpa: Allocator, fd: c_int, session: ?[]const u8, why: []u8, have: ?*Ha const maxInt = std.math.maxInt(usize); }; if (boot_digest == null and !writeAll(fd, out[0 .. hello.len + far.len])) { + j.rest.deinit(gpa); _ = libc.close(fd); return said(why, "the session hung up", .{}); } @@ -2698,6 +2871,17 @@ pub fn bye(fd: c_int, how: @FieldType(wire.ClientMsg, "bye")) void { if (wire.encodeClient(&out, .{ .bye = how })) |b| _ = writeAll(fd, b) else |_| {} } +/// Its goodbye that says it joins again and its hello for `view`, said on +/// its link in one write: the session dumps its state for it there +/// (`Peers.joinAgain`); its first word after them is the join's (`joinOn`). +/// False: the link is gone. +pub fn comeBack(fd: c_int, session: []const u8, view: u8) bool { + var out: [wire.hello_max + 16]u8 = undefined; + const said_bye = wire.encodeClient(&out, .{ .bye = .{ .again = true } }) catch unreachable; // fits + const hello = wire.encodeClient(out[said_bye.len..], .{ .hello = .{ .session = session[0..@min(session.len, wire.max_name)], .view = view } }) catch unreachable; // fits + return writeAll(fd, out[0 .. said_bye.len + hello.len]); +} + /// What the session streams a client after its dump, as its frontend's loop /// takes it: a unit's bytes and a refusal's words on the C heap, the loop's /// to free. @@ -2705,21 +2889,46 @@ pub const Said = union(enum) { unit: []u8, checked: u64, refused: []u8, blob: [] /// The session's stream off `fd`, each message handed to `post` until the /// link ends (a refusal ends it too); `post` says whether it took it (one -/// it did not is freed here). -pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime post: fn (@TypeOf(ctx), Said) bool) void { - const Take = struct { - fn take(x: @TypeOf(ctx), tag: u8, payload: []const u8) bool { +/// it did not is freed here). Once `link` comes back over it (`Link.back`): +/// what the stream it leaves still brings is let go, a last word is the +/// link's own (`Link.take`; a cut's words are followed by the welcome), and +/// the session's welcome there ends it, put back for the join's reader +/// (`join`). +pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, link: *Link, ctx: anytype, comptime post: fn (@TypeOf(ctx), Said) bool) void { + const Reading = struct { + ctx: @TypeOf(ctx), + link: *Link, + welcome: [wire.hello_max + 64]u8 = undefined, + welcome_len: usize = 0, + + fn take(x: *@This(), tag: u8, payload: []const u8) bool { const t = std.enums.fromInt(wire.ServerTag, tag) orelse return false; + const back = x.link.back.load(.acquire); + if (t == .welcome and back) { + if (wire.header_len + payload.len > x.welcome.len) return false; + x.welcome[0..wire.header_len].* = wire.header(tag, payload.len); + @memcpy(x.welcome[wire.header_len..][0..payload.len], payload); + x.welcome_len = wire.header_len + payload.len; + return false; + } const msg: Said = switch (t) { - .unit => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, - .blob => .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false }, - .check => .{ .checked = (wire.decodeServer(tag, payload) catch return false).check }, + .unit => if (back) return true else .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false }, + .blob => if (back) return true else .{ .blob = std.heap.c_allocator.dupe(u8, payload) catch return false }, + .check => if (back) return true else .{ .checked = (wire.decodeServer(tag, payload) catch return false).check }, .refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false }, .ended => .{ .ended = (wire.decodeServer(tag, payload) catch return false).ended }, .left => .left, .pong, .welcome, .dump, .blobs, .zstd => return true, }; - if (!post(x, msg)) switch (msg) { + return x.said(msg); + } + + fn said(x: *@This(), msg: Said) bool { + if (x.link.back.load(.acquire)) { + x.link.take(msg); + return msg == .refused; + } + if (!post(x.ctx, msg)) switch (msg) { .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), .checked, .ended, .left => {}, }; @@ -2727,11 +2936,16 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime return msg == .unit or msg == .checked or msg == .blob; } }; - rest.run(gpa, fd, ctx, Take.take); + var x: Reading = .{ .ctx = ctx, .link = link }; + rest.run(gpa, fd, &x, Reading.take); + if (x.welcome_len > 0) { + if (!rest.putBack(gpa, x.welcome[0..x.welcome_len])) rest.bad = true; + return; + } // A message past the wire's bound: said, never a hangup. const n = rest.overlong() orelse return; const words = std.fmt.allocPrint(std.heap.c_allocator, "the session sent a {d} MB message, over the {d} MiB bound", .{ n >> 20, wire.max_payload >> 20 }) catch return; - if (!post(ctx, .{ .refused = words })) std.heap.c_allocator.free(words); + _ = x.said(.{ .refused = words }); } /// A join's failure that is its session's end, whenever it came (the @@ -2786,18 +3000,28 @@ pub fn otherBuild(why: []const u8) bool { /// `runClient`): the session at `path` dialled (or, first, the one on its /// pair, `o.pair`), its build checked to be this /// one's, and its dump loaded into a replica checked against the session -/// as it was dumped. Or, `old` given, joined again once old's link has -/// ended, for old's view (`redial`): the core it leaves held meanwhile so -/// that its blobs are not sent again (`Have.leaving`), and let go before -/// the new one loads. The dump is let go, a far join's to the thread that -/// keeps the blobs it was sent (`Have.store`), and how long it all took is -/// `j.ms`. Null, and why in `why`. -pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o: pardes.Options, have: ?*Have, why: *[600]u8, old: ?*Replica) ?*Replica { +/// as it was dumped. Or, `old` given, joined again for old's view: over +/// old's link when its hello was said there (`here`: `comeBack`), the join +/// read on from what its reader left (`j.rest`); else, or that link ending +/// first, dialled again once it has ended (`redial`); the core it leaves +/// held meanwhile so that its blobs are not sent again (`Have.leaving`), +/// and let go before the new one loads. The dump is let go, a far join's to +/// the thread that keeps the blobs it was sent (`Have.store`), and how long +/// it all took is `j.ms`. Null, and why in `why`. +pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o: pardes.Options, have: ?*Have, why: *[600]u8, old: ?*Replica, here: bool) ?*Replica { if (old == null) if (o.pair) |fd| return ownBoot(gpa, j, fd, o, why); if (old) |prev| if (have) |h| h.leaving(prev.core()); const t0 = nowNs(); if (old) |prev| { - j.* = redial(gpa, path, session, why, have, prev.diverged == null, j.view) orelse { + const view = j.view; + const over = if (here) over: { + const rest = j.rest; + j.rest = .{}; + break :over joinOn(gpa, j.fd, null, why, have, null, null, rest); + } else null; + if (here and over == null) log.info("its link ended before the session's welcome there ({s}): dialled again", .{std.mem.sliceTo(why, 0)}); + const back = if (over) |got| sameBuild(gpa, got, why, true) else null; + j.* = back orelse redial(gpa, path, session, why, have, prev.diverged == null, view) orelse { if (ended(why)) return null; var words: [600]u8 = undefined; const said_ = std.mem.sliceTo(why, 0); @@ -2818,27 +3042,48 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o if (have) |h| h.store(gpa, j) else gpa.free(j.dump); j.dump = &.{}; } - return fromDump(gpa, j, o, have, why, t0); + return fromDump(gpa, j, o, have, why, t0, session); } /// The replica of the dump `j` brought, its load checked by the session's -/// digest (its emulators' among it), and what it takes of `j`; null, and -/// why in `why`, when it does not load as the session. -fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64) ?*Replica { - const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| { - _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; - return null; - }; - if (!r.loaded(j.digest)) { +/// digest (its emulators' among it), and what it takes of `j`. One that +/// does not load as the session names the fields that differ (the digest a +/// field at a time each join's dump ends with: `loadDiffers`) in the log +/// and asks once more over its link (`loadAgain`); a second that does not +/// either, or a link that cannot ask, is given up, the fields named in +/// `why`. Null, and why in `why`. +fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64, session: []const u8) ?*Replica { + var twice = false; + while (true) { + const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| { + _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {}; + return null; + }; + if (r.loaded(j.digest)) { + takeJoined(r, j, have, t0); + return r; + } var named: [400]u8 = undefined; const fields = loadDiffers(r, j.dump, &named); r.deinit(); - log.warn("client {d}: the session's dump loaded as another session: {s}", .{ j.client, fields }); - _ = std.fmt.bufPrint(why, "the session's dump loaded as another session: {s}differs\x00", .{fields}) catch {}; - return null; + log.warn("client {d}: the session's dump loaded as another session{s}: {s}", .{ j.client, if (twice) " twice" else "", fields }); + _ = said(why, "the session's dump loaded as another session{s}: {s}differs", .{ if (twice) " twice" else "", fields }); + if (twice or !loadAgain(gpa, j, have, why, session)) return null; + twice = true; } - takeJoined(r, j, have, t0); - return r; +} + +/// Its link asks for the session's state once more: the dump it had let +/// go, the join read on that link into `j`. False when the link is gone +/// (`why` and `j` kept) or the join ended first (why in `why`). +fn loadAgain(gpa: Allocator, j: *Joined, have: ?*Have, why: []u8, session: []const u8) bool { + if (!comeBack(j.fd, session, j.view)) return false; + if (have) |h| h.store(gpa, j) else gpa.free(j.dump); + j.dump = &.{}; + const rest = j.rest; + j.rest = .{}; + j.* = joinOn(gpa, j.fd, null, why, have, null, null, rest) orelse return false; + return true; } /// The fields a replica loaded from the join's dump `bytes` has other than @@ -2909,7 +3154,7 @@ fn ownBoot(gpa: Allocator, j: *Joined, fd: c_int, o: pardes.Options, why: *[600] pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, why: *[600]u8) ?*Replica { const t0 = nowNs(); const digest = j.digest; - j.* = sameBuild(gpa, joinOn(gpa, j.fd, null, why, null, null, digest) orelse return null, why, false) orelse return null; + j.* = sameBuild(gpa, joinOn(gpa, j.fd, null, why, null, null, digest, .{}) orelse return null, why, false) orelse return null; if (j.dump.len == 0) { r.id = j.client; r.view = j.view; @@ -2919,7 +3164,7 @@ pub fn confirmBoot(gpa: Allocator, j: *Joined, r: *Replica, o: pardes.Options, w gpa.free(j.dump); j.dump = &.{}; } - const loaded = fromDump(gpa, j, o, null, why, t0) orelse return null; + const loaded = fromDump(gpa, j, o, null, why, t0, "") orelse return null; r.deinit(); return loaded; } @@ -3057,9 +3302,16 @@ pub const Link = struct { fresh: bool = true, /// How far behind it was as it let its link go (`rejoins` says so). lagged: u64 = 0, + /// Its link crosses machines (a `Have`: ssh's forward, a relay): fallen + /// behind, it dials again (`backHere`). + far: bool = false, /// A pair's first join, its own boot not confirmed yet: its inputs /// kept here, not sent (`release`; client.zig `confirm`). held: ?std.ArrayListUnmanaged(u8) = null, + /// It comes back over this link (`backHere`, `comeBack`): its reader lets + /// the stream it leaves go and stops at the session's welcome there + /// (`readLink`). Set by the client's loop, read by its link's reader. + back: std.atomic.Value(bool) = .init(false), fn time(c: *const Link) u64 { return c.now orelse nowNs(); @@ -3093,6 +3345,7 @@ pub const Link = struct { c.put_off = false; c.behind = 0; c.fresh = true; + c.back.store(false, .release); if (r.core().views[r.view]) |v| { c.yanks = v.yanks; c.pastes = v.pastes; @@ -3281,6 +3534,23 @@ pub const Link = struct { appendTo(std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return, w.buffered()); } + /// Its loop ended with its link up and a reason to take the session's + /// state again (it diverged, fell behind, or the session's words came: + /// a cut's keep the link, an Upgrade's and a Restore's end it, which the + /// join there finds): its goodbye and hello are said on it (`comeBack`). + /// One that is gone, or a last word, is not. + /// THE SECOND ROAD: a far client that fell behind dials again (a new + /// connection; the one it leaves is shut): over its own link it would + /// first read through all that link holds for it, which a relay or a + /// forward buffers without bound (test/daemon.py `far_flood`: 49-68 s + /// to agree after the flood against 22.7 s by a dial). Bounded flight + /// (the session never more than a window past what its client has + /// taken) replaces it, and this line goes. + pub fn backHere(c: *const Link) bool { + if (c.far and c.lagged != 0) return false; + return !c.gone and c.ended == null and !c.left and (c.r.diverged != null or c.lagged != 0 or c.refused != null); + } + /// The link ended: whether the client joins again, and why in its /// notice (it diverged, it fell too far behind, or the session let it /// go: to upgrade, or cut off). @@ -3423,7 +3693,7 @@ fn farJoinOnce(ps: *Peers, core: *Pardes, have: ?*Have) !Joined { peer.reader = try std.Thread.spawn(.{}, Serve.run, .{peer}); defer ps.letGo(peer); var why: [300]u8 = @splat(0); - return joinOn(std.testing.allocator, fds[1], "t", &why, have, null, null) orelse { + return joinOn(std.testing.allocator, fds[1], "t", &why, have, null, null, .{}) orelse { std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; @@ -3541,7 +3811,7 @@ test "a client joining again after a divergence is told at once that its session var fds: [2]c_int = undefined; try std.testing.expectEqual(0, libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &fds)); _ = libc.close(fds[1]); - try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1, null) == null); + try std.testing.expect(joinOn(std.testing.allocator, fds[0], "gone", &why, null, 1, null, .{}) == null); try std.testing.expect(ended(&why)); } @@ -4421,7 +4691,7 @@ test "a Restore tells its clients so before it lets them go (each joins again, s defer ps.dropAll(core); ps.join(core, .{ .fd = fds[0] }); var why: [600]u8 = @splat(0); - var j = joinOn(gpa, fds[1], null, &why, null, null, null) orelse return error.JoinFailed; + var j = joinOn(gpa, fds[1], null, &why, null, null, null, .{}) orelse return error.JoinFailed; gpa.free(j.dump); defer j.rest.deinit(gpa); // A client dialling again, handed over before the Restore lets the first go. @@ -4439,7 +4709,9 @@ test "a Restore tells its clients so before it lets them go (each joins again, s } }; var last: Last = .{}; - readLink(gpa, fds[1], &j.rest, &last, Last.post); + // Its stream as a client that does not come back takes it. + var no_link: Link = .{ .r = undefined, .fd = fds[1] }; + readLink(gpa, fds[1], &j.rest, &no_link, &last, Last.post); const words = last.words orelse return error.NoLastWord; defer std.heap.c_allocator.free(words); try std.testing.expectEqualStrings(restore_words, words); @@ -4505,7 +4777,7 @@ fn ownBootAgainst(edited: bool) !void { o.pair = fds[1]; var j: Joined = undefined; var why: [600]u8 = @splat(0); - const booted = join(gpa, &j, "", "", o, null, &why, null) orelse return error.JoinFailed; + const booted = join(gpa, &j, "", "", o, null, &why, null, false) orelse return error.JoinFailed; const r = confirmBoot(gpa, &j, booted, o, &why) orelse { std.debug.print("the welcome: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; @@ -4558,9 +4830,9 @@ fn firstOnPair(by_dump: bool) !void { var why: [600]u8 = @splat(0); const r = if (by_dump) r: { // Joined by its dump as any client loads one (`fromDump`). - j = joinOn(gpa, fds[1], null, &why, null, null, null) orelse return error.JoinFailed; + j = joinOn(gpa, fds[1], null, &why, null, null, null, .{}) orelse return error.JoinFailed; defer gpa.free(j.dump); - break :r fromDump(gpa, &j, opts, null, &why, nowNs()) orelse { + break :r fromDump(gpa, &j, opts, null, &why, nowNs(), "") orelse { std.debug.print("the join: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; @@ -4569,7 +4841,7 @@ fn firstOnPair(by_dump: bool) !void { o.pair = fds[1]; // Its own core, from the same options, before any byte of the // session's; the welcome then says it is the session's: no dump. - const booted = join(gpa, &j, "", "", o, null, &why, null) orelse { + const booted = join(gpa, &j, "", "", o, null, &why, null, false) orelse { std.debug.print("the join failed: {s}\n", .{std.mem.sliceTo(&why, 0)}); return error.JoinFailed; }; @@ -5322,66 +5594,129 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it try agrees(a, back); } -test "a client cut off for what it left unread is told why and joins again for its view, kept for it meanwhile: it loads the session's dump and agrees" { - // A session's side of its clients' links in memory (`Peers.threads` - // false, the soak's): a connection handed to it and joined at its next - // boundary, the replica loaded from what its writer would write (the - // welcome, the dump with its blobs in place); and what it queued for one, - // down its link in order, the link's end after it if it was cut off. - const MemoryLinks = struct { - /// `old`: the link it had, whose end the session hears after this - /// join came: held until then. - fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int, old: ?*Peer) !struct { r: *Replica, peer: *Peer } { - const gpa = std.testing.allocator; - var fds: [2]c_int = undefined; - if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; - fd.* = fds[1]; - ps.handed(fds[0], view); +/// A session's side of its clients' links in memory (`Peers.threads` +/// false, the soak's): a connection handed to it and joined at its next +/// boundary, the replica loaded from what its writer would write (the +/// welcome, the dump with its blobs in place); what a client wrote, taken +/// by its peer's reader; and what the session queued for one, down its +/// link in order. +const MemoryLinks = struct { + /// `old`: the link it had, whose end the session hears after this + /// join came: held until then. + fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int, old: ?*Peer) !struct { r: *Replica, peer: *Peer } { + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + fd.* = fds[1]; + ps.handed(fds[0], view); + ps.boundary(core); + if (old) |o| { + for (ps.list) |slot| if (slot) |p| if (p.fd == fds[0]) return error.NotHeld; + ps.post(.{ .gone = o }); + ps.boundary(core); ps.boundary(core); - if (old) |o| { - for (ps.list) |slot| if (slot) |p| if (p.fd == fds[0]) return error.NotHeld; - ps.post(.{ .gone = o }); - ps.boundary(core); - ps.boundary(core); - } - const peer = for (ps.list) |slot| { - if (slot) |p| if (p.fd == fds[0]) break p; - } else return error.Refused; - const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; - const w = (try wire.decodeServer(f.tag, f.payload)).welcome; - var whole: std.ArrayListUnmanaged(u8) = .empty; - defer 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 wire.encodeClient(&word, .{ .far = false }); - _ = peer.take(far[0], far[wire.header_len..]); - ps.post(.{ .joined = peer }); - const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 }); - if (!r.loaded(w.digest)) return error.LoadedAnother; - return .{ .r = r, .peer = peer }; } + const peer = for (ps.list) |slot| { + if (slot) |p| if (p.fd == fds[0]) break p; + } else return error.Refused; + var word: [16]u8 = undefined; + const far = try wire.encodeClient(&word, .{ .far = false }); + _ = peer.take(far[0], far[wire.header_len..]); + return .{ .r = try load(ps, peer), .peer = peer }; + } - fn down(peer: *Peer, link: *Link) !void { - var at: usize = 0; - while (try wire.framed(peer.out.items[at..])) |f| : (at += f.total) { - link.take(switch (std.enums.fromInt(wire.ServerTag, f.tag) orelse return error.BadFrame) { - .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, f.payload) }, - .refused => .{ .refused = try std.heap.c_allocator.dupe(u8, (try wire.decodeServer(f.tag, f.payload)).refused) }, - else => return error.UnexpectedFrame, - }); - } - peer.out.clearRetainingCapacity(); - if (!peer.cut) return; - link.quit = true; - link.gone = true; + /// `peer`'s join as its writer writes it, loaded: written whole, its + /// pins let go at the next boundary. + fn load(ps: *Peers, peer: *Peer) !*Replica { + const gpa = std.testing.allocator; + const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + const w = (try wire.decodeServer(f.tag, f.payload)).welcome; + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer 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..]); + peer.written = peer.gen; + ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } }); + const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 }); + if (!r.loaded(w.digest)) { + r.deinit(); + return error.LoadedAnother; + } + return r; + } + + /// What its client wrote on its link, taken by its reader. + fn up(peer: *Peer) !void { + var buf: [4096]u8 = undefined; + const n = libc.read(peer.fd, &buf, buf.len); + if (n <= 0) return error.NothingWritten; + var at: usize = 0; + while (try wire.framed(buf[at..@intCast(n)])) |f| : (at += f.total) if (!peer.take(f.tag, f.payload)) return error.LinkEnded; + } + + fn down(peer: *Peer, link: *Link) !void { + var at: usize = 0; + while (try wire.framed(peer.out.items[at..])) |f| : (at += f.total) { + link.take(switch (std.enums.fromInt(wire.ServerTag, f.tag) orelse return error.BadFrame) { + .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, f.payload) }, + .refused => .{ .refused = try std.heap.c_allocator.dupe(u8, (try wire.decodeServer(f.tag, f.payload)).refused) }, + else => return error.UnexpectedFrame, + }); + } + peer.out.clearRetainingCapacity(); + } +}; + +/// A session whose client is cut off: queued past its bound with its link +/// stalled, told why, nothing more sent it. +fn cutOff(core: *Pardes, ps: *Peers, peer: *Peer, link: *Link) !void { + core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + try core.pump(core.host); + ps.boundary(core); + try MemoryLinks.down(peer, link); + try std.testing.expect(!link.quit and link.r.diverged == null); + peer.limit = 16 << 10; + const text: [6000]u8 = @splat('t'); + for (0..3) |_| { + core.update(.{ .paste = &text }); + try core.pump(core.host); + ps.boundary(core); + } + try std.testing.expect(peer.cut); + try MemoryLinks.down(peer, link); + try std.testing.expect(link.quit and !link.gone); +} + +test "a client's end and its writer's note after it, taken in one batch, let the client go once: nothing reads it freed" { + const gpa = std.testing.allocator; + const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer core.deinit(); + core.host = TestHost.host(); + try core.pump(core.host); + // The session's own allocations a page each: a client let go is + // unmapped, and a read of it after faults where it reads. + var ps: Peers = .{ .gpa = std.heap.page_allocator, .io = std.testing.io, .threads = false }; + defer ps.deinit(); + defer ps.dropAll(core); + var fd: c_int = -1; + const first = try MemoryLinks.join(&ps, core, null, &fd, null); + defer _ = libc.close(fd); + first.r.deinit(); + ps.boundary(core); + // Its reader's end, then its writer's note that its join is written + // whole (the writer descheduled between its last write and its post): + // one boundary's batch. + ps.post(.{ .gone = first.peer }); + ps.post(.{ .joined = .{ .peer = first.peer, .gen = first.peer.gen } }); + ps.boundary(core); + try std.testing.expectEqual(@as(usize, 0), ps.count()); +} + +test "a client cut off for what it left unread is told why and comes back over its own link: its goodbye and its hello there, the session's dump there in the view it has, no other connection; it loads it and agrees" { const gpa = std.testing.allocator; const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); defer core.deinit(); @@ -5396,37 +5731,59 @@ test "a client cut off for what it left unread is told why and joins again for i var link: Link = .{ .r = first.r, .fd = fd }; defer link.deinit(gpa); const view = first.peer.view; - // The session's own input, taken by the client. - core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + const conn = first.peer.fd; + try cutOff(core, &ps, first.peer, &link); + // Its link is up: it comes back over it (runtime/client.zig `run`). + try std.testing.expect(link.backHere()); + try std.testing.expect(comeBack(fd, "t", view.index())); + try MemoryLinks.up(first.peer); + try std.testing.expect(link.rejoins()); + try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); + ps.boundary(core); + // Dumped there: the same peer on the same connection, its view as it + // was, the cut over, the daemon not asked (nothing handed). + try std.testing.expectEqual(@as(usize, 1), ps.count()); + try std.testing.expect(ps.list[0] == first.peer and first.peer.fd == conn and !first.peer.cut); + try std.testing.expectEqual(view, first.peer.view); + try std.testing.expectEqual(@as(u32, 1), ps.again_here); + const back = try MemoryLinks.load(&ps, first.peer); + defer back.deinit(); + first.r.deinit(); + try std.testing.expectEqual(view.index(), back.view); + link.reset(back, &.{ .fd = fd, .pid = 0, .client = back.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); + core.update(.{ .paste = "back" }); try core.pump(core.host); ps.boundary(core); try MemoryLinks.down(first.peer, &link); - try std.testing.expect(!link.quit and first.r.diverged == null); - // Its link stalls; the session goes on, and what waits for it passes - // the bound: it is cut off. - first.peer.limit = 16 << 10; - const text: [6000]u8 = @splat('t'); - for (0..3) |_| { - core.update(.{ .paste = &text }); - try core.pump(core.host); - ps.boundary(core); - } - try std.testing.expect(first.peer.cut); - try std.testing.expectEqual(@as(u32, 1), ps.cut); - try MemoryLinks.down(first.peer, &link); - try std.testing.expect(link.quit); - // It was told why, and joins again (as a divergence's client does)... - try std.testing.expect(link.rejoins()); - try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); - // ...its old link shut, at once (runtime/client.zig `run`): a join that - // comes before that link's end is heard, on another connection, waits - // for it, its view kept for it meanwhile. + try std.testing.expect(!link.quit and back.diverged == null and back.quiet()); + try std.testing.expectEqual(tape.digestOf(core), back.digest()); +} + +test "a client that says it joins again and shuts its link (one of another build, gone to exec this one: sameBuild), dialled again before the session heard that link's end: its join waits for it, its view kept for it meanwhile" { + const gpa = std.testing.allocator; + const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer core.deinit(); + core.host = TestHost.host(); + try core.pump(core.host); + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; + defer ps.deinit(); + defer ps.dropAll(core); + var fd: c_int = -1; + const first = try MemoryLinks.join(&ps, core, null, &fd, null); + defer _ = libc.close(fd); + const view = first.peer.view; + // Its goodbye, then its link shut at once, before the session's reader + // has heard the end; the join comes on another connection. + var out: [16]u8 = undefined; + const said_bye = try wire.encodeClient(&out, .{ .bye = .{ .again = true } }); + try std.testing.expect(first.peer.take(said_bye[0], said_bye[wire.header_len..])); first.r.deinit(); _ = libc.close(fd); const back = try MemoryLinks.join(&ps, core, view.index(), &fd, first.peer); defer back.r.deinit(); try std.testing.expectEqual(view, back.peer.view); - link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); + var link: Link = .{ .r = back.r, .fd = fd }; + defer link.deinit(gpa); core.update(.{ .paste = "back" }); try core.pump(core.host); ps.boundary(core); @@ -5435,6 +5792,280 @@ test "a client cut off for what it left unread is told why and joins again for i try std.testing.expectEqual(tape.digestOf(core), back.r.digest()); } +/// A session's links with their threads (the runtime's), its steps a thread +/// of their own (`Peers.boundary`, the session's loop), until `stop`. +const LiveLinks = struct { + core: *Pardes, + ps: Peers, + stop: std.atomic.Value(bool) = .init(false), + thread: ?std.Thread = null, + + fn init(l: *LiveLinks, name: []const u8) !void { + const gpa = std.testing.allocator; + l.* = .{ .core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }), .ps = .{ .gpa = gpa, .io = std.testing.io, .name = name } }; + l.core.host = TestHost.host(); + try l.core.pump(l.core.host); + } + + fn start(l: *LiveLinks) !void { + l.thread = try std.Thread.spawn(.{}, run, .{l}); + } + + fn run(l: *LiveLinks) void { + while (!l.stop.load(.acquire)) { + l.ps.boundary(l.core); + const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + } + + fn halt(l: *LiveLinks) void { + l.stop.store(true, .release); + if (l.thread) |t| t.join(); + l.thread = null; + } + + fn deinit(l: *LiveLinks) void { + l.halt(); + l.ps.dropAll(l.core); + l.ps.deinit(); + live_peers = null; + l.core.deinit(); + } +}; + +/// A far client's blobs on disk, the test's own. +const TestHave = struct { + tmp: std.testing.TmpDir, + buf: [4200]u8 = undefined, + have: Have, + + fn init(h: *TestHave, far: bool) !?*Have { + h.tmp = std.testing.tmpDir(.{}); + h.have = .{ .io = std.testing.io }; + if (!far) return null; + h.have.cache = try testCache(&h.tmp, &h.buf, 64 << 20); + return &h.have; + } + + fn deinit(h: *TestHave) void { + h.have.deinit(); + h.tmp.cleanup(); + } +}; + +/// A join's dump let go as `replica.join` lets it go. +fn dumpDone(j: *Joined, have: ?*Have) void { + if (have) |h| { + h.store(std.testing.allocator, j); + h.wait(); + } else std.testing.allocator.free(j.dump); + j.dump = &.{}; +} + +fn backOverLink(far: bool) !void { + const gpa = std.testing.allocator; + var live: LiveLinks = undefined; + try live.init("back"); + defer live.deinit(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer _ = libc.close(fds[1]); + live.ps.handed(fds[0], null); + try live.start(); + var th: TestHave = undefined; + const have = try th.init(far); + defer th.deinit(); + var why: [600]u8 = @splat(0); + const o: pardes.Options = .{ .cols = 80, .rows = 24 }; + var j = joinOn(gpa, fds[1], null, &why, have, null, null, .{}) orelse return error.JoinFailed; + defer j.rest.deinit(gpa); + const r = fromDump(gpa, &j, o, have, &why, 0, "back") orelse return error.LoadFailed; + dumpDone(&j, have); + var link: Link = .{ .r = r, .fd = fds[1] }; + defer link.deinit(gpa); + link.reset(r, &j); + const view = r.view; + // Its stream on a reader thread, as its loop has it (client.zig `read`). + const Sink = struct { + units: std.atomic.Value(u32) = .init(0), + fn post(x: *@This(), msg: Said) bool { + if (msg == .unit) _ = x.units.fetchAdd(1, .monotonic); + switch (msg) { + .unit, .refused, .blob => |b| std.heap.c_allocator.free(b), + .checked, .ended, .left => {}, + } + return true; + } + fn read(fd: c_int, rest: *Framer, l: *Link, x: *@This()) void { + readLink(std.testing.allocator, fd, rest, l, x, post); + } + }; + var sink: Sink = .{}; + const reader = try std.Thread.spawn(.{}, Sink.read, .{ fds[1], &j.rest, &link, &sink }); + // Keys go in, and their units come back (raw: a replica stepping beside + // the session's thread would share the process's tape globals). + for ("abc") |cp| { + var out: [64]u8 = undefined; + try std.testing.expect(writeAll(fds[1], try wire.encodeClient(&out, .{ .event = .{ .key = .{ .cp = cp, .text = &[1]u8{cp} } } }))); + } + var waited: u32 = 0; + while (sink.units.load(.monotonic) < 3) : (waited += 1) { + if (waited > 10_000) return error.NoUnits; + const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + // Put off the session's state: its link up, it comes back over it. + r.fail("put off by the test"); + link.quit = true; + try std.testing.expect(link.backHere()); + link.back.store(true, .release); + try std.testing.expect(comeBack(fds[1], "back", view)); + reader.join(); + try std.testing.expect(link.rejoins()); + // Its dump made (the session's step), loaded here after it. + const peer = live.ps.list[0] orelse return error.Gone; + waited = 0; + while (true) : (waited += 1) { + peer.lock.lockUncancelable(std.testing.io); + const dumped_ = peer.gen == 2; + peer.lock.unlock(std.testing.io); + if (dumped_) break; + if (waited > 10_000) return error.NoDump; + const ts: libc.timespec = .{ .sec = 0, .nsec = std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + } + const back = join(gpa, &j, "/nowhere/no.sock", "back", o, have, &why, r, true) orelse { + std.debug.print("joined again: {s}\n", .{std.mem.sliceTo(&why, 0)}); + return error.JoinFailed; + }; + defer back.deinit(); + if (have) |h| h.wait(); + live.halt(); + // The same connection, the view it had, a dump there; the daemon (no + // socket at that path) never asked. + try std.testing.expectEqual(fds[1], j.fd); + try std.testing.expectEqual(view, back.view); + try std.testing.expectEqual(@as(u32, 1), live.ps.again_here); + try std.testing.expectEqual(@as(usize, 1), live.ps.count()); + // Far: what it held came from the core it left, not over the link. + if (far) try std.testing.expect(j.from_memory + 1 >= j.blobs); +} + +test "a client that diverged comes back over its own link, with the session's threads: its goodbye and hello there, the stream it leaves let go up to the session's welcome, the dump there for the view it had; the same connection, nothing dialled" { + try backOverLink(false); +} + +test "a far client that diverged comes back over its own link: the stream's frame it leaves ended, the join's a frame of its own, its blobs from the core it leaves" { + try backOverLink(true); +} + +/// A first join whose welcome's digest is not the session's at the dump +/// (as a dump that does not carry what the digest covers: the upgrade +/// round's fault D): its load is refused, and it asks once more over its +/// link, which the session answers with a right one. +fn askedOnceMore(far: bool) !void { + const gpa = std.testing.allocator; + var live: LiveLinks = undefined; + try live.init("once"); + defer live.deinit(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer _ = libc.close(fds[1]); + live.ps.threads = false; + live.ps.join(live.core, .{ .fd = fds[0] }); + live.ps.threads = true; + const peer = live.ps.list[0] orelse return error.Refused; + const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + var w = (try wire.decodeServer(f.tag, f.payload)).welcome; + w.digest +%= 1; + var copy: [wire.hello_max + 64]u8 = undefined; + const said_ = try wire.encodeServer(©, .{ .welcome = w }); + @memcpy(peer.welcome[0..said_.len], said_); + peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); + peer.reader = try std.Thread.spawn(.{}, Peer.readLoop, .{peer}); + try live.start(); + var th: TestHave = undefined; + const have = try th.init(far); + defer th.deinit(); + var why: [600]u8 = @splat(0); + var j = joinOn(gpa, fds[1], null, &why, have, null, null, .{}) orelse return error.JoinFailed; + defer j.rest.deinit(gpa); + const r = fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, have, &why, 0, "once") orelse { + std.debug.print("asked once more: {s}\n", .{std.mem.sliceTo(&why, 0)}); + return error.LoadFailed; + }; + defer r.deinit(); + dumpDone(&j, have); + live.halt(); + try std.testing.expectEqual(fds[1], j.fd); + try std.testing.expectEqual(@as(u32, 1), live.ps.again_here); +} + +test "a client whose load of the session's dump is refused asks once more over its link, the session's digest a word a field after the second dump, and goes on with the second" { + try askedOnceMore(false); +} + +test "a far client whose load is refused asks once more over its link: the stream's frame ended before the second join's" { + try askedOnceMore(true); +} + +test "a client whose load is refused twice gives up, naming the fields that differ by the digest a field at a time its dump ends with" { + const gpa = std.testing.allocator; + const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer core.deinit(); + core.host = TestHost.host(); + try core.pump(core.host); + var blobs: std.ArrayListUnmanaged(walk.Deferred) = .empty; + defer blobs.deinit(core.gpa); + const state = (try pardes.dump.dumpJoin(core, &blobs)).bytes; + defer core.gpa.free(state); + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (blobs.items) |b| { + try whole.appendSlice(gpa, state[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, state[pos..]); + // The session's digest a field at a time the dump ends with + // (dump.joinParts), its first field's word not what the dump loads. + const theirs = pardes.dump.joinParts(gpa, whole.items) orelse return error.NoParts; + defer gpa.free(theirs); + whole.items[whole.items.len - 16 - theirs.len * 8] +%= 1; + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer _ = libc.close(fds[0]); + // A session played by hand: a welcome whose digest is not its dump's, + // twice. + const Play = struct { + fn run(fd: c_int, dump: []const u8) void { + var welcome: [wire.hello_max + 64]u8 = undefined; + const w = wire.encodeServer(&welcome, .{ .welcome = .{ .pid = 1, .session = "named", .client = 1, .dump_len = dump.len, .digest = 1 } }) catch return; + var heard: [256]u8 = undefined; + for (0..2) |_| { + // Its far word (both times), then its goodbye and hello. + if (libc.read(fd, &heard, heard.len) <= 0) return; + if (!writeAll(fd, w) or !writePieces(fd, dump)) return; + } + _ = libc.read(fd, &heard, heard.len); + } + }; + const player = try std.Thread.spawn(.{}, Play.run, .{ fds[0], whole.items }); + defer player.join(); + var why: [600]u8 = @splat(0); + var j = joinOn(gpa, fds[1], null, &why, null, null, null, .{}) orelse return error.JoinFailed; + defer j.rest.deinit(gpa); + defer gpa.free(j.dump); + try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, 0, "named") == null); + _ = libc.close(j.fd); + const words = std.mem.sliceTo(&why, 0); + try std.testing.expect(std.mem.startsWith(u8, words, "the session's dump loaded as another session twice")); + const first = comptime walk.fieldNames(Pardes)[0]; + try std.testing.expect(std.mem.indexOf(u8, words, first) != null); +} + test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host()); @@ -5468,6 +6099,11 @@ test "a client whose session's units come more than two seconds later than its q // core is behind on purpose, no divergence. link.take(.{ .checked = digestOf(a) +% 1 }); try std.testing.expect(r.diverged == null); + // It comes back over its link; far, it dials again (`backHere`). + try std.testing.expect(link.backHere()); + link.far = true; + try std.testing.expect(!link.backHere()); + link.far = false; try std.testing.expect(link.rejoins()); try std.testing.expectEqualStrings("joined again: 2.1 s behind", link.notice()); try std.testing.expect(!link.rejoins()); @@ -5483,7 +6119,7 @@ test "a client whose session's units come more than two seconds later than its q try std.testing.expect(!link.quit and back.diverged == null); } -test "a client's writer, the client cut off while it waits on the socket, writes what it has in hand, then the words why, and ends the link" { +test "a client's writer, the client cut off while it waits on the socket, writes what it has in hand, then the words why, and nothing after them: its link stays up for its client's goodbye and hello again there" { const gpa = std.testing.allocator; var ps: Peers = .{ .gpa = gpa, .io = std.testing.io }; defer ps.deinit(); @@ -5528,11 +6164,16 @@ test "a client's writer, the client cut off while it waits on the socket, writes var heard: Heard = .{}; var rest: Framer = .{}; defer rest.deinit(gpa); - readLink(gpa, fds[1], &rest, &heard, Heard.post); + var no_link: Link = .{ .r = undefined, .fd = fds[1] }; + readLink(gpa, fds[1], &rest, &no_link, &heard, Heard.post); const words = heard.last orelse return error.NotTold; defer std.heap.c_allocator.free(words); try std.testing.expectEqualStrings("0 MB behind the session", words); try std.testing.expect(heard.units > 0 and heard.units < sent); + // Its link not shut after them, as it was when a cut ended it. + const wait: libc.timespec = .{ .sec = 0, .nsec = 100 * std.time.ns_per_ms }; + _ = libc.nanosleep(&wait, null); + try std.testing.expect(!hungUp(fds[1])); } test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" { @@ -6086,7 +6727,7 @@ test "a step of the session's own that reads a terminal right after its output, var word: [16]u8 = undefined; const far = try wire.encodeClient(&word, .{ .far = false }); _ = peer.take(far[0], far[wire.header_len..]); - ps.post(.{ .joined = peer }); + ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } }); var whole: std.ArrayListUnmanaged(u8) = .empty; defer whole.deinit(gpa); var pos: usize = 0; @@ -7808,7 +8449,7 @@ test "a client whose load is not the session says which field, in its words and try spliced.appendSlice(gpa, after.dump[Tail.at(after.dump)..]); var j: Joined = .{ .fd = -1, .pid = 0, .client = 1, .view = before.view, .gmtoff = 0, .dump = spliced.items, .digest = after.digest, .semantics = wire.semantics }; var why: [600]u8 = @splat(0); - try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, nowNs()) == null); + try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, nowNs(), "") == null); try std.testing.expectEqualStrings("the session's dump loaded as another session: fs differs", std.mem.sliceTo(&why, 0)); } diff --git a/core/root.zig b/core/root.zig index a476f90f..2f3e4494 100644 --- a/core/root.zig +++ b/core/root.zig @@ -637,7 +637,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "jj.zig", 11, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input, with the wall clock it was made at (tape.value(.clock) on the loop) for its descriptions' ages; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, - .{ "replica.zig", 76, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, + .{ "replica.zig", 89, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, .{ "rollback.zig", 1, "a test helper's directory" }, .{ "root.zig", 4, "dev's modules re-exported (host_io, file_watch, glide, fonts)" }, .{ "selection_pipe.zig", 14, "a pipe's child processes and their files: the host's `pipe` entry" }, diff --git a/core/surface.zig b/core/surface.zig index 3452bc77..5b381958 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -155,6 +155,9 @@ pub const Lane = struct { y: u16, level: u8, rgb: [3]u8, + /// On its change's description row, the lane's end: an arrow to the + /// text, which stands this many cells from `x` (0: a strip). + arrow: u8 = 0, /// The levels a row shows at most: the ruled gutter fits three. pub const levels = 3; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index 88ba023b..76af0ec8 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -5028,17 +5028,36 @@ fn laneDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, la const LaneRide = struct { x0: u16, x1: u16, y0: u16, y1: u16, dy: f32, top: f32, bottom: f32 }; /// `lane`'s strip, `w` pixels wide, on grid row `row`, riding a scroll's -/// rows when given one. +/// rows when given one; on its description row an arrow to the text: the +/// strip down to the row's middle, a shaft along it, a head half a strip +/// short of the text. fn laneStrip(g: *Gui, gpa: std.mem.Allocator, lane: pardes.Lane, row: i32, ride: ?*const LaneRide, w: f32, layout: CellLayout, win_w: f32, win_h: f32) !void { const x0 = @round(@as(f32, @floatFromInt(lane.x)) * layout.w + w / 2 + @as(f32, @floatFromInt(lane.level)) * (w + w / 2)); - var y0 = @as(f32, @floatFromInt(row)) * layout.h; - var y1 = y0 + layout.h; - if (ride) |r| { - y0 = @max(y0 - r.dy, r.top); - y1 = @min(y1 - r.dy, r.bottom); - if (y1 <= y0) return; + const top = @as(f32, @floatFromInt(row)) * layout.h; + const Piece = struct { + fn add(gu: *Gui, alloc: std.mem.Allocator, rd: ?*const LaneRide, rgb: [3]u8, x_0: f32, y_0: f32, x_1: f32, y_1: f32, ww: f32, wh: f32) !void { + var a = y_0; + var b = y_1; + if (rd) |r| { + a = @max(a - r.dy, r.top); + b = @min(b - r.dy, r.bottom); + } + if (b > a and x_1 > x_0) try addDecor(gu, alloc, x_0, a, x_1, b, rgb, 1, ww, wh); + } + }; + if (lane.arrow == 0) return Piece.add(g, gpa, ride, lane.rgb, x0, top, x0 + w, top + layout.h, win_w, win_h); + const mid = @round(top + (layout.h - w) / 2); + const tip = @round(@as(f32, @floatFromInt(lane.x + lane.arrow)) * layout.w - w / 2); + const head = @round(w * 1.5); + try Piece.add(g, gpa, ride, lane.rgb, x0, top, x0 + w, mid + w, win_w, win_h); + try Piece.add(g, gpa, ride, lane.rgb, x0 + w, mid, tip - head, mid + w, win_w, win_h); + // The head: a pixel row each, narrowing to the tip. + var dy: f32 = -head; + while (dy < head) : (dy += 1) { + const y = mid + w / 2 + dy; + const len = @round(head * (1 - @abs(dy + 0.5) / head)); + try Piece.add(g, gpa, ride, lane.rgb, tip - head, @round(y), tip - head + len, @round(y) + 1, win_w, win_h); } - try addDecor(g, gpa, x0, y0, x0 + w, y1, lane.rgb, 1, win_w, win_h); } /// Each pane's rule between its tag and body, and its scroll rail: a page diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index d65ca6d9..a590e402 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -119,7 +119,7 @@ Helix-style: motions *select*, then an edit acts on the selection. Mode box: bla == Reviewing diffs `git diff` output is a diff: #btn("B3") on a file line, an `@@` or a line's `+`/`-` jumps there. #doc("tags", section: "reviewing-diffs") -#word("Changes") `revset` on a file's pane: a lane a change, ghost rows for what it took away, #keys("] g", "[ g") from change to change; #word("Churn") `3m`: each declaration's changes, grey to red; `a.zig@main:12` is a file at a revision. #doc("guide", section: "changes") +#word("Changes") `revset` on a file's pane: a lane a change (one change: green beside what it wrote, red beside what it took away), an arrow to its description, ghost rows for what it took away, #keys("] g", "[ g") from change to change; #btn("B3") on a change id: its patch, header first; #word("Churn") `3m`: each declaration's changes, grey to red; `a.zig@main:12` is a file at a revision. #doc("guide", section: "changes") == Finding things - A query pane under the pane: line 1 the query, its first word the source: `/pat`, `Find name` (fuzzy), `Grep text` (literal), `Recent`, `Panes`, `Symbols`, `All`. #keys("Ctrl-n", "Ctrl-p") step, #key("Enter") lands and keeps the rows, #key("Esc") puts things back. #word("Help"), #word("Tutor"). diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index e73eabaf..985d324d 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -307,13 +307,18 @@ Nothing is shown, and nothing asked of jj, until a word is run. [#word("Churn") `window` (#key("SPC t u"))], [counts, for each declaration, the window's changes that touched it, and shows them in this view; the window a revset, or a span of time back from now (`3d`, `2w`, `6m`, `1y`). Bare: hidden or shown again; with none counted yet, the file's whole history], [#keys("] g", "[ g")], [the next and the previous change's first line], [`path@rev`, `path@rev:line`], [the file at a revision (#doc("guide", section: "revision")): a #word("Look") anywhere opens it], + [#word("Diff") `change` `path:line`], [a jj change's patch, its header (ids, author, dates, the whole message) above its hunks, in its own `+Diff`, the cursor on `path`'s line in it; a #word("Look") on a change id (eight of its letters, `k` to `z`, as `jj log` shows them) anywhere opens it at its top], ) *Lanes.* Each pinned change gets a lane after the line number, from its -first line to its last, in the theme's accents in hue order (a colour too -close to the one before it skipped), oldest first; a change that rewrote -lines inside another's steps a lane to the right on those rows. A line -one added whole is green across the line. +first line to its last; a change that rewrote lines inside another's +steps a lane to the right on those rows. With one change pinned (bare +`Changes`, a diff) its lane is the diff's own colours: green beside the +lines it wrote, red beside what it took away; with several, each its own +of the theme's accents in hue order (a colour too close to the one before +it skipped), oldest first, so they are told apart. At a change's +description its lane ends in an arrow to it. A line one added whole is +green across the line. *Ghost rows.* What the file no longer has is drawn where it stood, a row of its own with no number: a line a change took away whole, red across; @@ -321,10 +326,12 @@ a line a change changed, its old text right above it with the words that went red, and on the line the words that came green (the patch view's alignment says which lines are one line changed); each change's description, `id title author age` (`3w`, `4m`), after its last line, in -its lane's colour, at one place after that change's own ghost rows. A -ghost row is not text: the cursor steps over it, search, selection and -the line numbers do not see it, and a #btn("B3") on one opens its line in -the revision it came from (`path@id-:line`; a description, `path@id`). It +its lane's colour (one change pinned: its id in the theme's keyword +colour), at one place after that change's own +ghost rows. The cursor steps over a ghost row, and search, selection and +the line numbers do not see it; a #btn("B3") on one looks at the word +there as anywhere, and on a description's id opens that change's patch +at the row for its last line here (`Diff id path:line`). It moves the rows below down in this view alone. It is one row, cut where the pane ends (never wrapped); in a narrow pane a description's title is cut, its author and age kept. A hunk that took away more than 1,024 diff --git a/runtime/client.zig b/runtime/client.zig index 43fdf98d..1d348aea 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -95,7 +95,7 @@ pub const Start = struct { s.o.frames = &s.frames; // Exec'd at an Upgrade (`execAgain`): for the view it had. if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null; - s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false; + s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null, false) orelse return false; return true; } @@ -175,7 +175,7 @@ pub fn Loop(comptime Frontend: type) type { frames: *pardes.FrameStats, pub fn init(fe: *Frontend, s: *Start) !L { - var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd }, .fe = fe, .frames = &s.frames }; + var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd, .far = s.have != null }, .fe = fe, .frames = &s.frames }; try l.link.fromEnv(s.gpa, s.env); return l; } @@ -209,11 +209,23 @@ pub fn Loop(comptime Frontend: type) type { l.after(); } if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close }); - // The link's reader ends with the link, posting as it goes: - // what it posted is let go until it has (a terminal's queue - // is bounded: a reader blocked on it would never end). - _ = libc.shutdown(s.joined.fd, 2); + // Its link up and the session's state to take again: its + // goodbye and its hello said on it, the session's dump comes + // there (`replica.comeBack`); its reader reads on to the welcome, + // letting the stream it leaves go. Only a link that is gone + // is dialled again. + const here = link.backHere() and s.joined.rest.overlong() == null and back: { + link.back.store(true, .release); + break :back replica.comeBack(s.joined.fd, s.dial.session, s.r.view); + }; + if (!here) { + if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close }); + _ = libc.shutdown(s.joined.fd, 2); + } + // The link's reader ends with the link (or at the welcome), + // posting as it goes: what it posted is let go until it has + // (a terminal's queue is bounded: a reader blocked on it + // would never end). while (true) { const ended = done.load(.acquire); l.fe.drop(); @@ -221,14 +233,23 @@ pub fn Loop(comptime Frontend: type) type { std.Thread.yield() catch {}; } reader.join(); - _ = libc.close(s.joined.fd); - s.joined.rest.deinit(s.gpa); + if (!here) { + _ = libc.close(s.joined.fd); + s.joined.rest.deinit(s.gpa); + } // Its link cut with no word by a session that is there still // (an Upgrade's exec): joined again, as when told so. if (link.gone and link.refused == null and link.ended == null and !link.left and replica.cutListed("the session hung up", s.dial.session, s.have != null)) link.refused = std.heap.c_allocator.dupe(u8, replica.upgrading) catch null; - // Why it joins again is in its notice until a key. - if (!link.rejoins()) { + // A last word goes first, one read after it said it comes + // back too (a Detach in it, the session's end). Why it joins + // again is in its notice until a key. + const goes = link.ended != null or link.left; + if (here and goes) { + _ = libc.close(s.joined.fd); + s.joined.rest.deinit(s.gpa); + } + if (goes or !link.rejoins()) { // What it made since it joined, kept for its next start. if (s.have) |h| h.keep(s.r.core()); s.r.deinit(); @@ -238,7 +259,7 @@ pub fn Loop(comptime Frontend: type) type { } // The session again, the core it leaves held meanwhile: its // blobs are not sent again. - s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse { + s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r, here) orelse { if (replica.ended(&s.why)) return .gone; if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view }; return .failed; @@ -272,7 +293,7 @@ pub fn Loop(comptime Frontend: type) type { /// and its end. fn read(l: *L, s: *Start, done: *std.atomic.Value(bool)) void { defer done.store(true, .release); - replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, l.fe, Frontend.said); + replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, &l.link, l.fe, Frontend.said); l.fe.ended(); } diff --git a/runtime/daemon.zig b/runtime/daemon.zig index 595d5107..97941a12 100644 --- a/runtime/daemon.zig +++ b/runtime/daemon.zig @@ -241,9 +241,8 @@ extern "c" fn close_range(first: c_uint, last: c_uint, flags: c_int) c_int; /// twice), on the listener and the lock as fds 3 and 4. fn spawn(listener: c_int, lock: c_int) bool { var exe_buf: [4096:0]u8 = undefined; - const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch return false; - exe_buf[n] = 0; - const argv = [_:null]?[*:0]const u8{ &exe_buf, "--daemon", null }; + const exe = upgrade.startPath(&exe_buf) orelse return false; + const argv = [_:null]?[*:0]const u8{ exe, "--daemon", null }; const first = libc.fork(); if (first < 0) return false; if (first == 0) { @@ -268,7 +267,7 @@ fn spawn(listener: c_int, lock: c_int) bool { }; if (null_fd > 4) _ = libc.close(null_fd); _ = libc.chdir("/"); - _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ)); + _ = libc.execve(exe, &argv, @ptrCast(libc.environ)); libc._exit(127); } var status: c_int = 0; @@ -677,8 +676,13 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn { if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); if (libc.W.IFSIGNALED(s)) { const sig = libc.W.TERMSIG(s); - const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; - posix.sigaction(sig, &default, null); + // A KILL's action is its default already and cannot be set + // (EINVAL: posix.sigaction's unreachable, the stub aborting with a + // trace on the terminal); any other is put back to it first. + if (sig != .KILL) { + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(sig, &default, null); + } _ = libc.raise(sig); } libc._exit(1); diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig index f59117ee..510c50ea 100644 --- a/runtime/upgrade.zig +++ b/runtime/upgrade.zig @@ -58,18 +58,28 @@ pub fn remember(args: []const [:0]const u8) void { }; } -/// Its path asked of the system (a readlink) and the file there now (a +/// Its path asked of the system (a readlink) and the file it runs (a /// stat), once: after the first frame, off a startup's way (the hosts' -/// loops; nothing is reinstalled within a frame of a start). +/// loops). A build can be installed at that path before then (a pair's +/// session, whose first pass comes after its client's first frame; a +/// loaded machine): Linux then names the path "PATH (deleted)", and the +/// file at the path is not the one it started from, the one it runs is. pub fn locate() void { if (located) return; located = true; - if (exe_len == 0) { - const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch 0; - exe_buf[n] = 0; - exe_len = n; - } - if (exe()) |path| started_inode = inodeOf(path); + if (exe_len == 0) exe_len = if (startPath(&exe_buf)) |path| path.len else 0; + started_inode = if (builtin.os.tag == .linux) inodeOf("/proc/self/exe") else if (exe()) |path| inodeOf(path) else null; +} + +/// The path this process was started from, as the system names it, less +/// the " (deleted)" Linux adds once the file there was replaced (a +/// reinstall): the path is the path (what an Upgrade execs, and a daemon +/// started from here: daemon.zig `spawn`). +pub fn startPath(buf: *[4096:0]u8) ?[:0]const u8 { + const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), buf) catch return null; + const len = if (std.mem.endsWith(u8, buf[0..n], " (deleted)")) n - " (deleted)".len else n; + buf[len] = 0; + return buf[0..len :0]; } fn inodeOf(path: [:0]const u8) ?u64 { diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig index cf5c8009..18fa503c 100644 --- a/test/behaviour/addons_pdf.zig +++ b/test/behaviour/addons_pdf.zig @@ -132,6 +132,22 @@ test "addons: a PDF's / lists its hits as file.pdf:P:H rows in a +Search, n walk try std.testing.expect(try s.focused() != n); } +test "addons: a PDF's / of what its page has not, and f on a PDF with no outline, each say so and the session goes on (the bridge's none is a NULL with a count of 0: a safe build's abort before)" { + var s = try Session.initFile(std.testing.allocator, "x\n"); + defer s.deinit(); + const n = try s.lookFile("docs/design.pdf"); + // No page has it: page 1's hits of it asked, none; a hit of it a miss. + try s.keys("/zzqxv\r"); + try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]); + _ = try s.refused(s.at("/pane/{d}/look", .{n}), ":1:1\n"); + try std.testing.expect(has(try s.read("/log"), "design.pdf has no search hit 1 on page 1")); + // tall.pdf has no outline. + const t = try s.lookFile("test/pdf-fixtures/tall.pdf"); + try s.keys("f"); + try std.testing.expect(has(try s.read("/log"), "PdfSections: this PDF has no outline")); + try std.testing.expectEqual(t, try s.focused()); +} + test "addons: a PDF's f is its PdfSections, its outline as places a Look in it goes to (none once the PDF is gone), and a jump back over a far one is Ctrl-o's, Forward's on, two places on a page a window apart two" { var s = try Session.initFile(std.testing.allocator, "x\n"); defer s.deinit(); diff --git a/test/daemon.py b/test/daemon.py index ca59449c..f456837b 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -288,6 +288,31 @@ def links(pid): return out +def sockets(pid): + """The sockets process `pid` holds (`socket:[inode]`): a client's link + among them, the same one while it joins again over it.""" + out = set() + for fd in os.listdir(f'/proc/{pid}/fd'): + try: + link = os.readlink(f'/proc/{pid}/fd/{fd}') + except OSError: + continue + if link.startswith('socket:'): + out.add(link) + return out + + +def session_stats(path): + """A session's PARDES_REPLICA_STATS line, its words a dict, and its joins' + count (`joins_us`'s).""" + text = path.read_text() if path.exists() else '' + line = next((l for l in text.splitlines() if l.startswith('session inputs')), '') + w = line.split() + d = {w[i]: w[i + 1] for i in range(1, len(w) - 1, 2)} + joins = next((len(l.split()) - 2 for l in text.splitlines() if l.startswith('session joins_us')), 0) + return d, joins + + def state_fds(pid): """Its fds on the state file, which a session keeps open (Db.zig).""" return sum(1 for path in links(pid) if path.endswith('/pardes.xitdb')) @@ -491,8 +516,10 @@ def clients(binary): started = [] terms = [] try: - sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + # Its joins counted at its end (PARDES_REPLICA_STATS): those over a + # client's own link (`again`) and all of them (`joins_us`). + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')), + cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) @@ -538,6 +565,7 @@ def clients(binary): started.append(d.pid) wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20) made_live(td, root / 'd.check') + d_links = sockets(d.pid) shown = view_panes(nine) nine.write('/exec', b'New\n') mine = wait_for('a pane in client D\'s view', lambda: view_panes(nine) - shown).pop() @@ -548,6 +576,9 @@ def clients(binary): os.write(ta.master, b'jk') time.sleep(.2) assert d.poll() is None + # Over its own link: the same connection, no hand-over (counted at + # the session's end). + assert sockets(d.pid) == d_links, ('client D joined again over its own link', d_links, sockets(d.pid)) made_live(td, root / 'd.check') assert mine in view_panes(nine), ('client D in its own view again', mine, nine.read('/layout')) seen = len(checks(root / 'd.check')) @@ -601,8 +632,12 @@ def clients(binary): exit_session(nine, pane) sess.wait(timeout=60) nine.socket.close() + said, joins = session_stats(root / 'session.stats') + here = int(said.get('again', '-1')) + assert here >= 1, ('the session joined client D again over its link', said) wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) - print('daemon: replica clients\' session ended, nothing left behind') + print(f'daemon: replica clients\' session ended, nothing left behind; its joins: {joins}, of them over a ' + f'client\'s own link {here}, handed by the daemon {joins - here}') finally: for t in terms: t.close() @@ -951,6 +986,86 @@ def pair_rows(binary): shutil.rmtree(root, ignore_errors=True) +def pair_back(binary): + """A pair with no daemon (PARDES_DAEMON=off, the pair's default-to-be + with none reachable): its client put off the session's state + (PARDES_TEST_DIVERGE), and apart from that stopped 3 s while the + session's file is edited over 9P (SIGSTOP: past replica.behind_max_ms): + each time it joins again over its own link ("joined again" on its + screen, its socket the same), the session lives on with the text typed + in it, unsaved, and the client agrees; its terminal closed, the session + ends with its last link. Before pardes-link-1 its rejoin dialled the + daemon's socket, nothing took it, and the whole session went (the + client exit 1: reports/pardes-pair-12.md, 2b).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rb-', dir=scratch)) + env = base_env() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color', + SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1', PARDES_DAEMON='off') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + terms = [] + try: + for how in ('diverged', 'behind'): + t = Term(30, 100) + terms.append(t) + check = root / f'{how}.check' + e = dict(env, PARDES_REPLICA_CHECK=str(check), **({'PARDES_TEST_DIVERGE': '3'} if how == 'diverged' else {})) + c = t.spawn([binary, f'--9p={how}', str(notes)], e) + wait_for('the socket', (root / f'pardes-9p-{how}.sock').exists) + nine = Client(root / f'pardes-9p-{how}.sock') + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + links = sockets(c.pid) + mark = len(t.text()) + words = f'unsaved-{how}'.encode() + os.write(t.master, b'O' + words + b'\x1b') + wait_for('its keys in the session\'s text', lambda: words in nine.read(f'/pane/{pane}/body')) + if how == 'behind': + os.kill(c.pid, signal.SIGSTOP) + for k in range(30): + nine.write(f'/pane/{pane}/exec', f'Edit 3a/ edit {k} /\n'.encode()) + time.sleep(.1) + os.kill(c.pid, signal.SIGCONT) + deadline = time.monotonic() + 30 + while b'joined again' not in t.text()[mark:]: + went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone] + assert not went, (f'{how}: {" and ".join(went)} went (client exit {c.poll()}); ' + f'its terminal\'s last bytes: {t.text()[-600:]!r}') + assert time.monotonic() < deadline, f'{how}: the client joined again' + os.write(t.master, b'jk') + time.sleep(.2) + said = b'this client diverged' if how == 'diverged' else b' s behind' + wait_for(f'{how}: its notice says why', lambda: said in t.text()[mark:], timeout=10) + assert c.poll() is None and alive(session), (how, c.poll()) + assert sockets(c.pid) == links, (f'{how}: joined again over its own link', links, sockets(c.pid)) + assert words in nine.read(f'/pane/{pane}/body'), how + seen = len(checks(check)) + os.write(t.master, b'jj') + wait_for(f'{how}: the client agrees after it', lambda: agreed(check, seen), timeout=30) + nine.socket.close() + t.close() + terms.remove(t) + c.wait(timeout=20) + wait_for(f'{how}: the session ended with its last link', lambda: not alive(session), timeout=20) + print(f'pair back: no daemon, its client {how}: joined again over its own link, the session alive, ' + f'its unsaved text there, agreed; its terminal closed, the session ended') + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + for t in terms: + t.close() + shutil.rmtree(root, ignore_errors=True) + + def attach_upgrading(binary, rounds=6, dump=True): """`pardes attach` as its session upgrades: started at once after the Upgrade's word, it is handed to the session before the exec; told the @@ -1220,12 +1335,18 @@ def pair_upgrade_views(binary): shutil.rmtree(root, ignore_errors=True) -def pair_exec_reaps(old, new): +def pair_exec_reaps(old, new, early=False): """PARDES_PAIR across builds: a pair started from `root/bin` (old), its session upgraded to the build installed there since (new): its client, the session's parent, execs that build (the blink) and is still its parent; Exit typed then: the client returns once the session is gone, - reaped, its status the session's (0), as before the exec.""" + reaped, its status the session's (0), as before the exec. `early`: old + and new the same build, installed again at once, before the session's + first pass round its loop, where it first looks its start path up + (upgrade.zig `locate`), and as the client starts the daemon from its + own (daemon.zig `spawn`): the path is the path, not Linux's "PATH + (deleted)", so the daemon starts and the session execs it; the client, + its build the session's still, joins again in place (no exec).""" scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch)) @@ -1240,36 +1361,48 @@ def pair_exec_reaps(old, new): notes = root / 'notes.txt' notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) terms = [] + sock = root / 'pardes-9p-px.sock' + c = session = None try: t = Term(30, 100) terms.append(t) c = t.spawn([str(binary), '--9p=px', str(notes)], env) - sock = root / 'pardes-9p-px.sock' + if early: + install(new, binary) wait_for('the socket', sock.exists) nine = Client(sock) session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) assert ppid(session) == c.pid wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) - install(new, binary) + if not early: + install(new, binary) ino = sock.stat().st_ino # Before the Upgrade: the exec'd client can draw before its exec is seen. mark = len(t.text()) nine.write('/ctl', b'Upgrade\n') nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) - wait_for('the client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) + if early: + wait_for('joined again in place', lambda: b'joined again' in t.text()[mark:], timeout=30) + else: + wait_for('the client on the new build', lambda: on_build(c, binary), timeout=30) nine = reconnect(sock) assert ppid(session) == c.pid # The blink: its screen left and entered again, the notes drawn there. - wait_for('drawn again', lambda: (lambda x: x.rfind(b'\x1b[?1049h') > x.rfind(b'\x1b[?1049l') > mark - and b'line 3 of the notes' in x[x.rfind(b'\x1b[?1049h'):])(t.text()), timeout=30) + if not early: + wait_for('drawn again', lambda: b'line 3 of the notes' in (entered_again(t.text(), mark) or b''), timeout=30) nine.write('/ctl', b'Exit\n') nine.socket.close() assert c.wait(timeout=30) == 0, c.returncode # Its parent's wait returned: the session reaped, not a zombie left # to whoever takes it in. assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read() - print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0') + print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0' + + (' (the same build installed again before the session looked its path up: joined again in place)' if early else '')) + except (TimeoutError, AssertionError, OSError, EOFError, subprocess.TimeoutExpired) as err: + kept = keep_evidence('pair-exec', root, env, binary, sock, [('session', session)] if session else [], + [('client', t, c, root / 'client.check', root / 'client.stats')] if c else []) + raise AssertionError(f'{type(err).__name__}: {err} (kept: {kept})') from None finally: for p in processes(root): try: @@ -1327,8 +1460,8 @@ def far_exec(old, new): nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) nine = reconnect(sock) - wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) - wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) + wait_for('the far client on the new build', lambda: on_build(c, binary), timeout=30) + wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30) # Its environment read once the new image runs (it entered the # screen): an exec names the new file in /proc/PID/exe before it has # written where the environment is, and a read between gets nothing @@ -1406,7 +1539,7 @@ def pair_window_geometry(gui_binary, new_gui): nine.write('/ctl', b'Upgrade\n') nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) - wait_for('the window on the new build', lambda: exe_of(p.pid) == (str(gui), True), timeout=30) + wait_for('the window on the new build', lambda: on_build(p, gui), timeout=30) nine = reconnect(sock) time.sleep(3) assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain) @@ -2232,8 +2365,8 @@ def far_flood(binary): started = [] terms = [] try: - sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')), + cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) started.append(sess.pid) sock = root / 'pardes-replica.sock' wait_for('the replica socket', sock.exists) @@ -2257,13 +2390,24 @@ def far_flood(binary): dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats))) started.append(c.pid) wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) + links = sockets(c.pid) nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) + ended_at = time.monotonic() seen = len(checks(check)) wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) # Queued behind the flood, let go for its lag, joined again from a # dump: a link of its ended (its stats line), and its notice says why. assert joins(stats), ('no link of the far client ended under the flood', checks(stats)) + # Fallen behind, a far client dials again (core/replica.zig + # `Link.backHere`: the second road until bounded flight): a new + # connection, not what the old one holds for it read through; each + # join's time and the KB it was sent; the flood's end to its agreement. + same = sockets(c.pid) == links + print(f'far flood: the far client\'s link {"the same" if same else "another"} after {len(joins(stats))} joins again ' + f'(join ms {[j.get("join_ms") for j in joins(stats)]}, sent KB {[j.get("sent_kb") for j in joins(stats)]}); ' + f'agreed {time.monotonic() - ended_at:.1f} s after yes ended') + assert not same, ('the far client behind dialled again: another connection', links, sockets(c.pid)) wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30) os.write(t.master, b'echo from-far\r') wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) @@ -2725,6 +2869,46 @@ def cpu_ticks(pid): return int(stat[11]) + int(stat[12]) +def killed_session(binary): + """A terminal's session killed outright (KILL, as the OOM killer does): + the job its terminal waits on ends with it, and says nothing of its own + (no trace): the own path's stub dead of the same signal, as a job is + (daemon.zig `stubWait`, which aborted re-raising a KILL); a pair's + client let go of its session, 1.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch)) + env = base_env() + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30))) + t = Term(30, 100) + try: + c = t.spawn([binary, '--9p=k', str(notes)], env) + sock = root / 'pardes-9p-k.sock' + wait_for('the socket', sock.exists) + with Client(sock) as nine: + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) + os.kill(session, signal.SIGKILL) + code = c.wait(timeout=30) + said = t.last() + assert b'panic' not in said and b'unreachable' not in said, said[-1500:] + assert code == (1 if WITH_PAIR else -signal.SIGKILL), (code, said[-600:]) + print(f'killed session: its terminal\'s job ended {code} with it, no trace') + finally: + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + t.close() + shutil.rmtree(root, ignore_errors=True) + + def kitty_image(binary, secs=5): """A plain attach watching a terminal in which a program shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it @@ -2824,6 +3008,7 @@ def main(binary, cycles): launch(binary) pair(binary) pair_rows(binary) + pair_back(binary) attach_upgrading(binary) kept_views(binary) pair_upgrade_views(binary) @@ -3263,7 +3448,10 @@ def exe_of(pid): if not procfs: rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines() return (rows[-1].split()[-1] if len(rows) > 1 else ''), None - link = os.readlink(f'/proc/{pid}/exe') + try: + link = os.readlink(f'/proc/{pid}/exe') + except OSError: # gone, or a zombie: it runs nothing + return '', False try: same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino except OSError: @@ -3271,6 +3459,22 @@ def exe_of(pid): return link, same +def entered_again(text, mark): + """The blink of a client exec'd at an Upgrade: its terminal's screen + left at or after `mark` (the text's length before the Upgrade: when the + reader had read all the old client wrote, the leave is its very next + byte) and entered again. What was drawn since that enter, or None.""" + enter, leave = text.rfind(b'\x1b[?1049h'), text.rfind(b'\x1b[?1049l') + return text[enter:] if enter > leave >= mark else None + + +def on_build(proc, binary): + """Whether the test's child `proc` runs `binary` now (exe_of); one that + ended says so with its status at once, not as a wait run out.""" + assert proc.poll() is None, f'pid {proc.pid} ended ({proc.returncode}) before it ran {binary}' + return exe_of(proc.pid) == (str(binary), True) + + def ppid(pid): if not procfs: return int(ps('-o', 'ppid=', '-p', str(pid))) @@ -3758,7 +3962,7 @@ def upgrade_clients(old, new): wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30) wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30) # The blink: its screen left, and entered again. - wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30) + wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30) assert tc.poll() is None and w.p.poll() is None for (key, check), pane, theirs in zip(owners, mine, reversed(mine)): if knows_exec(new): @@ -3905,6 +4109,9 @@ if __name__ == '__main__': far_exec(old, new) else: print('far exec: skipped: the old build\'s far client, cut at the Upgrade with no last word, takes it for its session\'s end (no PARDES_JOIN_SIZE)') + # A reinstall of the new build before the pair's first look: the + # new build's own, whatever the old one does. + pair_exec_reaps(new, new, early=True) # With a pardes-gui beside each: the clients carried too. if all(a.with_name('pardes-gui').exists() for a in (old, new)): upgrade_clients(old, new) @@ -3924,8 +4131,11 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--pair']: pair(sys.argv[2]) pair_rows(sys.argv[2]) + pair_back(sys.argv[2]) attach_upgrading(sys.argv[2], dump=False) pair_upgrade_views(sys.argv[2]) + elif sys.argv[1:2] == ['--pair-back']: + pair_back(sys.argv[2]) elif sys.argv[1:2] == ['--attach-upgrading']: attach_upgrading(sys.argv[2]) elif sys.argv[1:2] == ['--relink']: @@ -3938,6 +4148,8 @@ if __name__ == '__main__': far_flood(sys.argv[2]) by_hash(sys.argv[2]) far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--far-flood']: + far_flood(sys.argv[2]) elif sys.argv[1:2] == ['--far-find']: far_find(sys.argv[2]) elif sys.argv[1:2] == ['--kitty-image']: @@ -3957,3 +4169,4 @@ if __name__ == '__main__': gui_pair(args[0]) else: main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50) + killed_session(sys.argv[1]) diff --git a/test/replicas.zig b/test/replicas.zig index 8f3e5ca5..3aa9263e 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -251,6 +251,8 @@ const Totals = struct { /// Joins from a dump, refused, again after a divergence put on it /// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks. joins: u64 = 0, + /// ...of them again over the client's own link (no dial). + here: u64 = 0, refused: u64 = 0, /// A pair's client's own boot the session's core at its join (`--pair`), /// or not (its dump loaded instead, the fields that differ said). @@ -527,11 +529,10 @@ const Client = struct { stops: @FieldType(replica.Stats, "stops") = @splat(.{}), /// Its Peer's writer's (`Soak.write`): the batch swapped out of the /// session's queue for it (the Peers' allocator's), how much of it went - /// down the link, whether a cut's words end it, a wake asked for room; - /// how much of the queue carries the soak's clock (`Soak.stamp`). + /// down the link, a wake asked for room; how much of the queue carries + /// the soak's clock (`Soak.stamp`). sending: std.ArrayListUnmanaged(u8) = .empty, at: usize = 0, - last: bool = false, draining: bool = false, marked: usize = 0, /// The session's unit its last join's dump came after. @@ -752,14 +753,17 @@ fn describe(buf: []u8, ev: pardes.Event) []const u8 { } catch "?"; } -/// Its link ended (it diverged, or it quits): its bye, and its join again -/// for its view after a divergence (`Link.rejoins`), the core it leaves -/// held until the dump comes, as `replica.join` holds it. +/// Its link ended (it diverged, fell behind, was cut off, or it quits): +/// its join again for its view (`Link.rejoins`), over its link while that +/// is up (its goodbye and hello said there: runtime/client.zig `run`), the +/// core it leaves held until the dump comes, as `replica.join` holds it; +/// else its bye. fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, typing: *usize) !void { const r = cl.r.?; const link = &cl.loop.link; + const here = link.backHere() and replica.comeBack(link.fd, "soak", r.view); // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); + if (!here and !link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); try drain(cl, c, net, now); cl.live = 0; if (link.lagged != 0) { @@ -775,6 +779,10 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, if (link.rejoins()) { cl.back = r.view; cl.dialling = true; + if (here) { + totals.here += 1; + return; + } return net.send(.{ .at = net.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } try totals.add(&r.stats); @@ -1435,10 +1443,8 @@ const Soak = struct { 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. + // closed, daemon.refuseReplica): its writer's join first (`joinDown`), + // its far word read (`far` false: on this machine). for (s.clients, 0..) |*cl, c| if (cl.handed >= 0) { defer cl.handed = -1; const peer = for (ps.list) |slot| { @@ -1448,44 +1454,17 @@ const Soak = struct { 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.join_seq = ps.seq; - cl.sending.clearRetainingCapacity(); - cl.at = 0; - cl.last = false; - cl.marked = 0; - // What the join cost the session's step (Peers.join's measure). - s.join_worst = @max(s.join_worst, ps.join_ns); - try s.totals.join_session_ns.append(gpa, ps.join_ns); - ps.join_ns = 0; - cl.gen += 1; - cl.id = welcome.client; - cl.view = welcome.view.index(); - cl.digest = welcome.digest; - s.totals.joins += 1; - Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); - try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); + try s.joinDown(cl, c, peer); }; - // 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). + // A join again over a client's own link (Peers.joinAgain): its writer's + // next, the stream it leaves let go. + for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| if (peer.written != peer.gen) try s.joinDown(cl, c, peer); + // A Detach typed in a client's view: 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.index() == k and !cl.shut) { cl.shut = true; }; @@ -1513,6 +1492,44 @@ const Soak = struct { s.echo.clearRetainingCapacity(); } + /// Client `c`'s Peer's writer's join (Peer.writeJoin): the welcome, then + /// the dump with the session's blobs put back where they go, down its + /// link, what was queued before it let go; its pins let go at the next + /// boundary. + fn joinDown(s: *Soak, cl: *Client, c: usize, peer: *replica.Peer) !void { + const ps = &s.l.peers; + 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..]); + peer.written = peer.gen; + ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } }); + cl.peer = peer; + cl.shut = false; + cl.read_done = false; + cl.join_seq = ps.seq; + cl.sending.clearRetainingCapacity(); + cl.at = 0; + cl.marked = 0; + // What the join cost the session's step (Peers.join's measure). + s.join_worst = @max(s.join_worst, ps.join_ns); + try s.totals.join_session_ns.append(gpa, ps.join_ns); + ps.join_ns = 0; + cl.gen += 1; + cl.id = welcome.client; + cl.view = welcome.view.index(); + cl.digest = welcome.digest; + s.totals.joins += 1; + Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); + try s.net.toClient(c, s.now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); + } /// The units the session queued for client `cl` since, their heads /// carrying the soak's clock, the session's here (its host's `now`): /// what the client's lag is measured by. Its replica guesses no clock @@ -1534,7 +1551,7 @@ const Soak = struct { /// frame a message. The far link takes no more than `throttle_window` /// ahead of what has crossed: the rest waits in the queue, as it does /// for a writer blocked on its socket, until room comes (`.drain`). A - /// cut's words end a batch, and its link after them. + /// cut's words are its last until its client's hello again there. fn write(s: *Soak, cl: *Client, c: usize) !void { const peer = cl.peer orelse return; const net = s.net; @@ -1543,11 +1560,9 @@ const Soak = struct { if (cl.at == cl.sending.items.len) { cl.sending.clearRetainingCapacity(); cl.at = 0; - if (cl.last) return s.shut(cl, c); const io = s.l.peers.io; peer.lock.lockUncancelable(io); std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending); - cl.last = peer.cut; peer.lock.unlock(io); cl.marked = 0; if (cl.sending.items.len == 0) return; @@ -1590,11 +1605,10 @@ const Soak = struct { } /// Client `c`'s link ended at the session's side (a Detach typed in its - /// view, or the words of a cut sent): it hears its end and nothing after, - /// and its reader's end is said (the next boundary lets it go). + /// view): it hears its end and nothing after, and its reader's end is + /// said (the next boundary lets it go). fn shut(s: *Soak, cl: *Client, c: usize) !void { cl.shut = true; - cl.last = false; if (cl.read_done) return; cl.read_done = true; s.l.peers.post(.{ .gone = cl.peer.? }); @@ -3400,7 +3414,7 @@ pub fn main(init: std.process.Init) !void { try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] }); for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); try stop_lines.append(gpa, '\n'); - try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); + try join_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.here, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{ rtt, t.far_joins, t.far_lags, secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)), @@ -3419,8 +3433,8 @@ pub fn main(init: std.process.Init) !void { } std.debug.print("terminals: a peer's unit bytes a second under the flood (the pty's bytes ride in them); KB of units sent to the peers in all\n", .{}); std.debug.print(" rtt unit B/s units KB\n{s}", .{term_lines.items}); - std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); - std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); + std.debug.print("clients: joins from a dump (here: of them again over the client's own link, no dial), refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{}); + std.debug.print(" rtt joins here refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{}); |
