diff options
Diffstat (limited to 'core')
| -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 |
9 files changed, 1212 insertions, 262 deletions
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; |
