summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--abi/addon.zig24
-rw-r--r--abi/term.zig4
-rw-r--r--abi/wire.zig12
-rw-r--r--addons/pdf/pdf.zig57
-rw-r--r--build/addons.zig9
-rw-r--r--build/core.zig15
-rw-r--r--build/tests.zig1
-rw-r--r--core/Addon.zig2
-rw-r--r--core/Core.zig2
-rw-r--r--core/Kind.zig17
-rw-r--r--core/jj.zig12
-rw-r--r--core/ninep/pty.zig81
-rw-r--r--core/panes.zig4
-rw-r--r--core/replica.zig1053
-rw-r--r--core/root.zig2
-rw-r--r--core/term/terminal.zig12
-rw-r--r--docs/typ/reference.typ3
-rw-r--r--runtime/client.zig47
-rw-r--r--runtime/daemon.zig16
-rw-r--r--runtime/upgrade.zig26
-rw-r--r--test/behaviour/addons_pdf.zig16
-rw-r--r--test/daemon.py304
-rw-r--r--test/process/look_and_exec.zig14
-rw-r--r--test/process/terminals.zig17
-rw-r--r--test/replicas.zig122
25 files changed, 1449 insertions, 423 deletions
diff --git a/abi/addon.zig b/abi/addon.zig
index 1fa2279a..059e016d 100644
--- a/abi/addon.zig
+++ b/abi/addon.zig
@@ -248,8 +248,14 @@ pub fn loadBytes(s: anytype, bytes: []const u8, version: u32) bool {
pub const body_max = 4096;
var body_cut = false;
-fn span(p: [*c]const u8, n: u64) []const u8 {
- return if (p == null) "" else p[0..n];
+/// A C pointer and its count as a slice; NULL is none, whatever the count:
+/// C says none with a NULL (a page's search without a hit, a selection
+/// over no text, an outline of no entries), and a NULL C pointer sliced
+/// is a safety panic even at length 0 (a release build's abort). Every
+/// pointer a C struct or a C caller hands with its count is read through
+/// it: pdf.zig's test holds the bridge's to it.
+pub fn cSlice(ptr: anytype, n: usize) []const std.meta.Child(@TypeOf(ptr)) {
+ return if (ptr == null) &.{} else ptr[0..n];
}
/// `pardes_addon` exported, when built as a library alone: the kind is its
@@ -282,7 +288,7 @@ pub fn ops(comptime T: type) c.pa_ops {
fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque {
const s = arena.create(T) catch return null;
s.* = std.mem.zeroInit(T, .{});
- if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else bytes[0..len]);
+ if (@hasDecl(T, "open")) T.open(s, if (path == null) null else std.mem.span(path), if (bytes == null) null else cSlice(bytes, len));
return s;
}
fn close(st: ?*anyopaque) callconv(.c) void {
@@ -329,7 +335,7 @@ pub fn ops(comptime T: type) c.pa_ops {
return @intCast(from.len);
}
fn address(st: ?*anyopaque, t: [*c]const u8, n: u32) callconv(.c) c_int {
- return @intFromBool(T.address(self(st) orelse return 0, span(t, n)));
+ return @intFromBool(T.address(self(st) orelse return 0, cSlice(t, n)));
}
fn where(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
return write(T.where, self(st) orelse return 0, buf, n);
@@ -337,26 +343,26 @@ pub fn ops(comptime T: type) c.pa_ops {
fn ctl(st: ?*anyopaque, line: [*c]const u8, n: u32, reply: [*c]u8, cap: u32) callconv(.c) c_int {
var w: std.Io.Writer = .fixed(reply[0..cap -| 1]);
defer reply[w.end] = 0;
- return if (T.ctl(self(st) orelse return 1, span(line, n), &w)) c.PA_OK else 1;
+ return if (T.ctl(self(st) orelse return 1, cSlice(line, n), &w)) c.PA_OK else 1;
}
fn ctl_read(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
return write(T.ctlRead, self(st) orelse return 0, buf, n);
}
fn job_run(in: [*c]const u8, n: u32, out: [*c]c.pa_out) callconv(.c) u32 {
const gpa: Allocator = .{ .ptr = out, .vtable = &.{ .alloc = jobAlloc, .resize = Allocator.noResize, .remap = Allocator.noRemap, .free = Allocator.noFree } };
- return @intCast((T.jobRun(span(in, n), gpa) orelse return 0).len);
+ return @intCast((T.jobRun(cSlice(in, n), gpa) orelse return 0).len);
}
fn job_done(st: ?*anyopaque, token: u32, out: [*c]const u8, n: u32) callconv(.c) void {
- T.jobDone(self(st) orelse return, token, span(out, n));
+ T.jobDone(self(st) orelse return, token, cSlice(out, n));
}
fn dump(st: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
return @intCast(T.dump(self(st) orelse return 0, buf[0..n]));
}
fn load(st: ?*anyopaque, buf: [*c]const u8, n: u32, version: u32) callconv(.c) c_int {
- return @intFromBool(!T.load(self(st) orelse return 1, span(buf, n), version));
+ return @intFromBool(!T.load(self(st) orelse return 1, cSlice(buf, n), version));
}
fn search(st: ?*anyopaque, pat: [*c]const u8, n: u32) callconv(.c) void {
- T.search(self(st) orelse return, span(pat, n));
+ T.search(self(st) orelse return, cSlice(pat, n));
}
};
if (T.head.name.len > 15) @compileError(@typeName(T) ++ "'s name " ++ T.head.name ++ " is over 15 bytes");
diff --git a/abi/term.zig b/abi/term.zig
index 31f155e8..e84d6998 100644
--- a/abi/term.zig
+++ b/abi/term.zig
@@ -78,7 +78,9 @@ pub const Prompt = struct {
finished: ?Finished = null,
/// The cursor is at a prompt's input, on either screen.
input_ready: bool = false,
- /// ...and nothing is typed on its line up to the cursor.
+ /// ...and nothing is typed on its line up to the cursor, nor on the
+ /// line above when a newline in the input began this one (a line taken
+ /// whose command has not started yet).
input_empty: bool = false,
/// The cursor is on a prompt's row or at its input, on the primary
/// screen.
diff --git a/abi/wire.zig b/abi/wire.zig
index 8949edff..7b6a22f1 100644
--- a/abi/wire.zig
+++ b/abi/wire.zig
@@ -12,9 +12,12 @@ const build_info = @import("build_info");
/// 31: where a view stands in a terminal's history is the view's: a pane's
/// `scrolled_to` (and its share's in each view) in the dump and the digest,
-/// the emulator's own view out of both (its `Parts.view` gone); and the
+/// the emulator's own view out of both (its `Parts.view` gone); the
/// core's count of its emulators' writes (`outside`) in both, which the
-/// replica engine's one question of a unit reads;
+/// replica engine's one question of a unit reads; and a client whose link
+/// is up joins again over it (its bye's `again`, then its hello there:
+/// core/replica.zig `Peers.joinAgain`), as one whose load was refused asks
+/// once more;
/// 30: the terminals' one road: the screen-state messages are retired (a
/// replica's `screen_ack`, 0x04, and the session's `screen`, 0x06: gaps),
/// a welcome says no road (its `bytes` byte gone), and a pane's
@@ -324,8 +327,9 @@ pub fn helloVersion(payload: []const u8) Error!u16 {
/// one call and no longer.
pub const ClientMsg = union(enum) {
hello: Hello,
- /// The client's end: `again`, it joins again for its view at once;
- /// `close`, its window was closed (a pair's session ends at its last).
+ /// The client's end: `again`, it joins again for its view at once (its
+ /// hello next, on this link while it is up); `close`, its window was
+ /// closed (a pair's session ends at its last).
bye: struct { again: bool = false, close: bool = false },
/// A round trip's probe, answered `pong` with the same value.
ping: u64,
diff --git a/addons/pdf/pdf.zig b/addons/pdf/pdf.zig
index 8f314bbe..79d79219 100644
--- a/addons/pdf/pdf.zig
+++ b/addons/pdf/pdf.zig
@@ -759,7 +759,7 @@ pub const Pdf = extern struct {
const found = in.n > 0 and m.pardes_pdf_search_page(ld, @intCast(in.page), &q, &r) == ok;
defer if (found) m.pardes_pdf_drop_search_result(ld, r.handle);
res.ok, res.n, res.hits = .{ 1, @intCast(t.len), if (found) @intCast(r.hit_count) else 0 };
- return answer(gpa, res, std.mem.concat(gpa, u8, &.{ t.data[0..t.len], if (found) std.mem.sliceAsBytes(r.quads[0..r.quad_count]) else "" }) catch return null);
+ return answer(gpa, res, std.mem.concat(gpa, u8, &.{ addon.cSlice(t.data, t.len), if (found) std.mem.sliceAsBytes(addon.cSlice(r.quads, r.quad_count)) else "" }) catch return null);
}
// each page's count of hits, then the rows
var shown = @min(in.n, 200);
@@ -1011,7 +1011,7 @@ fn pageText(o: *Own, page: u32) []const u8 {
var t: m.pardes_pdf_text = undefined;
if (m.pardes_pdf_page_text(d.base, @intCast(page), &t) != ok) return "";
defer m.pardes_pdf_drop_text(d.base, t.handle);
- o.read.bytes = heap.dupe(u8, t.data[0..t.len]) catch &.{};
+ o.read.bytes = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{};
return o.read.bytes;
}
@@ -1030,7 +1030,7 @@ fn hitsOf(st: *const Pdf, o: *Own) []const m.pardes_pdf_search_quad {
var r: m.pardes_pdf_search_result = undefined;
if (m.pardes_pdf_search_page(d.base, @intCast(f.hits_page), &q, &r) != ok) return &.{};
defer m.pardes_pdf_drop_search_result(d.base, r.handle);
- o.hits = heap.dupe(m.pardes_pdf_search_quad, r.quads[0..r.quad_count]) catch &.{};
+ o.hits = heap.dupe(m.pardes_pdf_search_quad, addon.cSlice(r.quads, r.quad_count)) catch &.{};
return o.hits;
}
@@ -1073,8 +1073,8 @@ fn selectHere(o: *Own, page: u32, from: Point, to: Point) ?usize {
var t: m.pardes_pdf_owned_text = undefined;
if (m.pardes_pdf_copy_selection(base, @intCast(page), sel.start, sel.end, &t) != ok) return null;
defer m.pardes_pdf_drop_owned_text(base, t.handle);
- o.sel_quads = heap.dupe(Quad, sel.quads[0..sel.quad_count]) catch &.{};
- o.sel_text = heap.dupe(u8, t.data[0..t.len]) catch &.{};
+ o.sel_quads = heap.dupe(Quad, addon.cSlice(sel.quads, sel.quad_count)) catch &.{};
+ o.sel_text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{};
return sel.quad_count;
}
@@ -1691,11 +1691,11 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad
const uri = struct {
var buf: [1024]u8 = undefined;
};
- @memcpy(uri.buf[0..link.uri_len], link.uri[0..link.uri_len]);
+ @memcpy(uri.buf[0..link.uri_len], addon.cSlice(link.uri, link.uri_len));
link.uri = &uri.buf;
var text: []u8 = &.{};
if (m.pardes_pdf_copy_rectangle(base, @intCast(at.page), link.quad, &t) == ok) {
- text = heap.dupe(u8, t.data[0..t.len]) catch &.{};
+ text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch &.{};
m.pardes_pdf_drop_owned_text(base, t.handle);
}
return .{ .page = at.page, .quad = link.quad, .text = text, .link = link };
@@ -1706,7 +1706,7 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad
if (sel.quad_count == 0 or m.pardes_pdf_copy_selection(base, @intCast(at.page), sel.start, sel.end, &t) != ok) return null;
defer m.pardes_pdf_drop_owned_text(base, t.handle);
if (t.len == 0) return null;
- return .{ .page = at.page, .quad = sel.quads[0], .text = heap.dupe(u8, t.data[0..t.len]) catch return null, .link = null };
+ return .{ .page = at.page, .quad = addon.cSlice(sel.quads, sel.quad_count)[0], .text = heap.dupe(u8, addon.cSlice(t.data, t.len)) catch return null, .link = null };
}
/// A link followed: a place in the document scrolled to, else looked at
@@ -1714,7 +1714,7 @@ fn probeAt(st: *Pdf, id: u8, col: u16, row: u16) ?struct { page: u32, quad: Quad
/// both, a +Links.
fn follow(st: *Pdf, link: m.pardes_pdf_link, text: []const u8) void {
if (link.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return goToXY(st, @intCast(link.page), link.has_x != 0, link.x, link.has_y != 0, link.y);
- const uri = link.uri[0..link.uri_len];
+ const uri = addon.cSlice(link.uri, link.uri_len);
var shown: [512]u8 = undefined;
var k: usize = 0;
for (text) |ch| if (ch > ' ' and k < shown.len) {
@@ -1749,10 +1749,10 @@ fn goToXY(st: *Pdf, page: u32, has_x: bool, x: f32, has_y: bool, y: f32) void {
/// from 1), indented by depth; an entry with nowhere to go takes its first
/// child's that has, and an http(s) one is its URI.
fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool {
- const it = o.items[i];
+ const it = addon.cSlice(o.items, o.item_count)[i];
if (it.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) return true;
if (it.destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL or it.uri_len == 0 or it.uri_len > 256) return false;
- const u = o.bytes[it.uri_offset..][0..it.uri_len];
+ const u = addon.cSlice(o.bytes, o.bytes_len)[it.uri_offset..][0..it.uri_len];
return (std.mem.startsWith(u8, u, "http://") or std.mem.startsWith(u8, u, "https://")) and for (u) |ch| {
if (ch <= 0x20 or ch == 0x7f) break false;
} else true;
@@ -1760,9 +1760,10 @@ fn usable(o: *const m.pardes_pdf_outline_result, i: usize) bool {
/// Entry `i`'s place: its own, else the first usable one below it.
fn resolve(o: *const m.pardes_pdf_outline_result, i: usize) ?usize {
- if (o.items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null;
+ const items = addon.cSlice(o.items, o.item_count);
+ if (items[i].destination_kind != m.PARDES_PDF_OUTLINE_DESTINATION_NONE) return if (usable(o, i)) i else null;
var k = i + 1;
- while (k < o.item_count and o.items[k].depth > o.items[i].depth) : (k += 1) if (usable(o, k)) return k;
+ while (k < items.len and items[k].depth > items[i].depth) : (k += 1) if (usable(o, k)) return k;
return null;
}
@@ -1774,13 +1775,15 @@ fn sections(st: *Pdf) void {
const rows = heap.alloc(u8, o.item_count * 300 + 1) catch return;
defer heap.free(rows);
var w: std.Io.Writer = .fixed(rows);
- for (o.items[0..o.item_count], 0..) |it, i| {
- const to = o.items[resolve(&o, i) orelse continue];
- if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(st).name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{o.bytes[to.uri_offset..][0..to.uri_len]}) catch {};
+ const items = addon.cSlice(o.items, o.item_count);
+ const bytes = addon.cSlice(o.bytes, o.bytes_len);
+ for (items, 0..) |it, i| {
+ const to = items[resolve(&o, i) orelse continue];
+ if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_INTERNAL) w.print("{s}:{d}:{d} ", .{ ownOf(st).name, to.page + 1, i + 1 }) catch {} else w.print("{s} ", .{bytes[to.uri_offset..][0..to.uri_len]}) catch {};
w.splatByteAll(' ', 2 * it.depth) catch {};
// the title on one line: control and invalid characters a space
// between words, none at either end
- const t = o.bytes[it.title_offset..][0..it.title_len];
+ const t = bytes[it.title_offset..][0..it.title_len];
const start = w.end;
var gap = false;
var i_: usize = 0;
@@ -1811,9 +1814,9 @@ fn section(st: *Pdf, page: u32, ord: u32) bool {
defer if (o.handle != null) m.pardes_pdf_drop_outline_result(base, o.handle);
var said: [200]u8 = undefined;
const r = if (m.pardes_pdf_load_outline(base, &o) == ok and ord > 0 and ord <= o.item_count) resolve(&o, ord - 1) else null;
- const to = o.items[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(st).name, ord }))];
+ const to = addon.cSlice(o.items, o.item_count)[r orelse return miss(std.fmt.bufPrint(&said, "PdfSections: {s} has no section {d}", .{ ownOf(st).name, ord }))];
if (to.destination_kind == m.PARDES_PDF_OUTLINE_DESTINATION_EXTERNAL) {
- addon.look(o.bytes[to.uri_offset..][0..@min(to.uri_len, 256)]);
+ addon.look(addon.cSlice(o.bytes, o.bytes_len)[to.uri_offset..][0..@min(to.uri_len, 256)]);
return true;
}
if (to.page + 1 != page) return miss(std.fmt.bufPrint(&said, "PdfSections: section {d} of {s} is on page {d}, not {d}", .{ ord, ownOf(st).name, to.page + 1, page }));
@@ -1831,3 +1834,19 @@ fn miss(said: anyerror![]const u8) bool {
fn noText() bool {
return miss("has no text to address; its address is a page, :N");
}
+
+test "every pointer the bridge's structs hand back is read through addon.cSlice: none of them sliced or indexed bare (a NULL for none sliced at 0 was a release build's abort)" {
+ var src: []const u8 = @embedFile("pdf.zig"); // (searched at run time: at comptime it is over the branch quota)
+ _ = &src;
+ @setEvalBranchQuota(1_000_000); // (the translated header's every declaration)
+ inline for (@typeInfo(m).@"struct".decl_names) |name| {
+ if (comptime !std.mem.startsWith(u8, name, "pardes_pdf_") or @TypeOf(@field(m, name)) != type or @typeInfo(@field(m, name)) != .@"struct") continue;
+ const S = @typeInfo(@field(m, name)).@"struct";
+ inline for (S.field_names, S.field_types) |field, F| if (comptime @typeInfo(F) == .pointer and @typeInfo(F).pointer.size == .c) {
+ if (std.mem.indexOf(u8, src, "." ++ field ++ "[")) |at| {
+ std.debug.print("pdf.zig:{d}: {s}.{s} read bare: addon.cSlice(ptr, count)\n", .{ std.mem.count(u8, src[0..at], "\n") + 1, name, field });
+ return error.BareCPointer;
+ }
+ };
+ }
+}
diff --git a/build/addons.zig b/build/addons.zig
index 38b02dff..a1bdb43b 100644
--- a/build/addons.zig
+++ b/build/addons.zig
@@ -52,6 +52,9 @@ pub const Pdf = struct {
/// `pardes_addon` alone.
pub fn pdf(b: *std.Build, c: struct {
addon_mod: *std.Build.Module,
+ /// pdf.zig's and the bridge's (core.zig's `addon_optimize`); MuPDF's
+ /// and the rest of the C's `c_optimize`.
+ addon_optimize: std.lang.Optimize,
c_optimize: std.lang.Optimize,
enable_jpx: bool,
freetype: ?*std.Build.Step.Compile,
@@ -83,7 +86,7 @@ pub fn pdf(b: *std.Build, c: struct {
// The bridge's header translated here for pdf.zig (Zig 0.17 has no
// @cImport), as the kinds' header is for the core.
const bridge_mod = b.addTranslateC(.{ .root_source_file = b.path("addons/pdf/pdf_bridge.h"), .target = c.target, .optimize = c.c_optimize }).createModule();
- const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.c_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } });
+ const pdf_mod = b.createModule(.{ .root_source_file = b.path("addons/pdf/pdf.zig"), .target = c.target, .optimize = c.addon_optimize, .link_libc = true, .imports = &.{ .{ .name = "addon", .module = c.addon_mod }, .{ .name = "pdf_bridge", .module = bridge_mod } } });
mupdf.linkTo(pdf_mod);
pdf_mod.addIncludePath(b.path("addons/pdf"));
pdf_mod.addCSourceFile(.{ .file = b.path("addons/pdf/pdf_bridge.c"), .flags = &.{"-std=gnu11"} });
@@ -105,8 +108,8 @@ pub fn pdf(b: *std.Build, c: struct {
/// The image addon (addons/image/image.zig over stb_image, stb.c),
/// installed by its step and handed by path to every test that opens a
/// picture.
-pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile {
- const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = c_optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} });
+pub fn image(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, addon_mod: *std.Build.Module, zstbi_dep: *std.Build.Dependency) *std.Build.Step.Compile {
+ const image_mod = b.createModule(.{ .root_source_file = b.path("addons/image/image.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "addon", .module = addon_mod }} });
image_mod.addIncludePath(zstbi_dep.path("libs/stbi"));
image_mod.addCSourceFile(.{ .file = b.path("addons/image/stb.c"), .flags = &.{ "-std=c11", "-Wall", "-Wextra", "-Werror" } });
const image_addon = b.addLibrary(.{ .name = "image", .linkage = .dynamic, .root_module = image_mod });
diff --git a/build/core.zig b/build/core.zig
index e8150843..f9cb450f 100644
--- a/build/core.zig
+++ b/build/core.zig
@@ -310,8 +310,10 @@ pub const Parts = struct {
pdf: ?*std.Build.Module,
term: *std.Build.Module,
plain: *std.Build.Module,
- /// The kinds' C ABI (abi/pardes_addon.h), translated.
+ /// The kinds' C ABI (abi/pardes_addon.h), translated, and what an addon
+ /// in Zig imports over it (abi/addon.zig: the core's `cSlice` too).
kind: *std.Build.Module,
+ addon: *std.Build.Module,
themes: *std.Build.Module,
ts: TreeSitter,
mvzr: *std.Build.Module,
@@ -401,6 +403,7 @@ pub fn module(b: *std.Build, p: Parts, c: Core) Modules {
if (c.terminal) x.addImport("term", p.term);
x.addImport("plain", p.plain);
x.addImport("pardes_addon", p.kind);
+ x.addImport("addon", p.addon);
x.addImport("generated_themes", p.themes);
x.addImport("tree-sitter", p.ts.mod);
x.addImport("ts_queries", ts_queries);
@@ -514,8 +517,15 @@ pub fn assemble(b: *std.Build, c: struct {
const kind_mod = b.addTranslateC(.{ .root_source_file = b.path("abi/pardes_addon.h"), .target = target, .optimize = optimize }).createModule();
// ...and what an addon in Zig imports over it (abi/addon.zig).
const addon_mod = b.createModule(.{ .root_source_file = b.path("abi/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} });
+ // The C-backed addons' own Zig and bridge at the C's speed, with the
+ // checks a release keeps: ReleaseSafe in a Debug build, as in the
+ // user's (a page's search without a hit sliced a NULL: only a release
+ // build aborted, Debug's addons ran ReleaseFast); MuPDF and stb stay
+ // at c_optimize.
+ const addon_optimize: std.lang.Optimize = if (optimize == .debug) .safe else c_optimize;
const pdf_built = addons.pdf(b, .{
.addon_mod = addon_mod,
+ .addon_optimize = addon_optimize,
.c_optimize = c_optimize,
.enable_jpx = c.enable_jpx,
.freetype = freetype,
@@ -602,7 +612,7 @@ pub fn assemble(b: *std.Build, c: struct {
// library and no allocator hook of its own (it takes Zig allocators).
const xitdb_mod = b.dependency("xitdb", .{ .target = target, .optimize = optimize }).module("xitdb");
- const image_addon = addons.image(b, target, c_optimize, addon_mod, zstbi_dep);
+ const image_addon = addons.image(b, target, addon_optimize, addon_mod, zstbi_dep);
// The records the core and the terminal both name (abi/plain.zig).
const plain_mod = b.createModule(.{ .root_source_file = b.path("abi/plain.zig"), .target = target, .optimize = optimize });
// The terminal, a module of its own (core/term/term.zig): the emulator and
@@ -625,6 +635,7 @@ pub fn assemble(b: *std.Build, c: struct {
.term = term_mod,
.plain = plain_mod,
.kind = kind_mod,
+ .addon = addon_mod,
.themes = themes_mod,
.ts = ts,
.mvzr = mvzr_mod,
diff --git a/build/tests.zig b/build/tests.zig
index e0b33911..5e913501 100644
--- a/build/tests.zig
+++ b/build/tests.zig
@@ -162,6 +162,7 @@ pub fn add(b: *std.Build, c: struct {
run_replicas.has_side_effects = true;
b.step("replicas", "one authority and several replicas in process, each client typing over a delayed link: digests at quiescence, rollback rate and costs per RTT (-- [--seeds N] [--steps M] [--clients C] [--rtt 30,80,207])").dependOn(&run_replicas.step);
for ([_]*std.Build.Module{ snake_mod, life_mod, liar_mod, c.parts.image }) |m| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step);
+ if (c.pdf_addon) |lib| addon_test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lib.root_module })).step);
// ...and the pdf addon's, which mupdf-check runs too (its script
// opens docs/design.pdf, from the build root).
const libs = [_]struct { ?*std.Build.Step.Compile, []const u8 }{ .{ fake_addon_lib.?, "addons/fake/fake" }, .{ snake_lib, "addons/snake/snake" }, .{ c.snake_shader_lib, "addons/snake_shader/snake_shader" }, .{ life_lib, "addons/life/life" }, .{ c.pdf_addon, "addons/pdf/pdf" } };
diff --git a/core/Addon.zig b/core/Addon.zig
index aa3195f9..e93a43dc 100644
--- a/core/Addon.zig
+++ b/core/Addon.zig
@@ -532,7 +532,7 @@ pub const LoadedWord = struct { name: []const u8, leader: []const u8 = "", arg:
/// `ops`'s head as a `Loaded` (its words borrowed from it, in `words`).
pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[64]LoadedWord) Loaded {
const h = &ops.head;
- const head_words = if (h.nwords == 0 or h.words == null) &.{} else h.words[0..@min(h.nwords, words.len)];
+ const head_words = @import("addon").cSlice(h.words, @min(h.nwords, words.len));
for (head_words, words[0..head_words.len]) |*w, *out| out.* = .{
.name = if (w.name == null) "" else std.mem.span(w.name),
.leader = if (w.leader == null) "" else std.mem.span(w.leader),
diff --git a/core/Core.zig b/core/Core.zig
index 2c6567ed..f5ed28bd 100644
--- a/core/Core.zig
+++ b/core/Core.zig
@@ -1070,6 +1070,7 @@ fn acknowledgeShellInner(p: *Pardes, id: Pane.Id, executable: []const u8, prompt
if (id.index() < MAX_PANES) if (p.panes[id.index()]) |pane| {
ctlfs.pty.shellGone(p, pane, true); // a respawn replaced whatever ran
pane.shell_failed = false;
+ pane.greeted = false;
pane.had_shell = true;
pane.fs.unmarked = !prompt_marks;
// The tag's Term word names the shell the host ran, and a click
@@ -2010,6 +2011,7 @@ pub fn sync(p: *Pardes) void {
p.emit(.{ .resize_pty = .{ .pane = .at(id), .cols = pane.cols, .rows = pane.rows } });
p.emitWrite(id, "ls\r");
pane.greet = false;
+ pane.greeted = true;
},
};
}
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/jj.zig b/core/jj.zig
index ed4d7e2a..1ec1a0dc 100644
--- a/core/jj.zig
+++ b/core/jj.zig
@@ -1822,10 +1822,11 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u
} else if (level < cells) {
var style = s.at(first + @as(u16, @intCast(level)), y).style;
style.fg = .{ .rgb = rgb };
- // An arrow: the lane, a shaft, a head at the text (`▎─→`);
- // from the last level, a bent one.
+ // 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{258e}", style);
+ 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);
}
}
@@ -2382,9 +2383,10 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line
};
try testing.expectEqual(pins.len, n);
} else for (0..levels) |level| {
- // `▎` a lane; an arrow: its lane, a shaft, a head (`▎─→`).
+ // `▎` a lane; an arrow: its lane bent, a shaft, a head (`╰─→`).
const cell = s.at(first + @as(u16, @intCast(level)), y);
- const glyph = if (level < pins.len) "\u{258e}" else if (arrow == null) " " else if (level + 1 == levels) "\u{2192}" else "\u{2500}";
+ 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);
diff --git a/core/ninep/pty.zig b/core/ninep/pty.zig
index 43973491..2dd7f7f3 100644
--- a/core/ninep/pty.zig
+++ b/core/ninep/pty.zig
@@ -135,11 +135,12 @@ pub const status_len: u64 = 36;
pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
// Busy is what a run written now would be told: a command is running
- // or a line is typed at the prompt. Before the shell's first prompt a
- // run waits for it rather than answer busy, so that is not busy.
+ // or a line is typed at the prompt. Before the shell's first prompt, or
+ // the one after its greeting, a run waits for it rather than answer
+ // busy, so that is not busy.
const marks = pardes.Term.prompt(pane.terminal);
const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or
- (marks.prompts > 0 and (marks.phase != .input or !marks.input_empty))));
+ (marks.prompts > 0 and !greeting(pane, marks) and (marks.phase != .input or !marks.input_empty))));
const out = p.fs.stage(p.gpa);
const size = winsize(pane);
out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch return Reply.fail(req.tag, E.NOMEM);
@@ -230,8 +231,8 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
answer(p, slot, "error {s}", .{if (pane.command_done) "command done; not a shell" else "a command runs here, not a shell"});
} else if (pf.unmarked) {
answer(p, slot, "error no prompt marks", .{});
- } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or
- !marks.input_empty or p.hostTtyTaken(id))))
+ } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and !greeting(pane, marks) and
+ (marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id))))
{
// Something is running or someone has typed at the prompt: sending
// now would type into the middle of it. The phase is pardes's own
@@ -248,7 +249,8 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply {
answer(p, slot, "busy", .{});
} else {
// Sent now if the shell is at its prompt, or at its first prompt
- // when it has not drawn one yet (noteMarks).
+ // when it has not drawn one yet, or the one after its greeting
+ // (noteMarks).
slot.line = p.gpa.dupe(u8, line) catch return Reply.fail(req.tag, E.NOMEM);
slot.phase = .waiting;
pf.run = req.handle;
@@ -296,7 +298,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
pf.run = null;
return;
}
- if (marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)) return;
+ if (greeting(pane, marks) or marks.phase != .input or !marks.input_empty or p.hostTtyTaken(id)) return;
slot.want = marks.started +% 1;
slot.prompts = marks.prompts;
slot.declined = marks.declined;
@@ -361,6 +363,15 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void {
finish(p, slot, pane, done.status);
}
+/// The greeting typed at a new terminal's first prompt (Pane.greeted) is
+/// its shell's first command until the prompt after it: its echo not back
+/// yet, the prompt looks empty, and a line sent then would be typed behind
+/// the `ls`, its start taken for the run's (the run answered with what ls
+/// printed). `ls` always starts, so the wait ends.
+fn greeting(pane: *const Pane, marks: pardes.Term.Prompt) bool {
+ return pane.greeted and (marks.started == 0 or (marks.started == 1 and marks.phase != .input));
+}
+
/// The shell's marks as the session's emulator has them (taped), as a
/// run's step reads them: a screen-state replica's emulator is the last
/// delta's, which comes at a frame and can be a unit behind the one it
@@ -785,6 +796,62 @@ test "a run waiting for a new terminal's first prompt is the only line typed the
try testing.expectEqualStrings("true\r", sent[0..len]);
}
+test "a prompt redrawn under a run's line, the line taken, is the line run: never `error not run`" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ const node = Node.of(serialOf(p), .pty_run);
+ const out = struct {
+ fn put(pp: *Pardes, bytes: []const u8) void {
+ pp.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } });
+ while (pp.nextEffect()) |_| {}
+ }
+ };
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ // A window's first terminal: bash's first prompt, then the window's
+ // first size (its rows a row shorter), which readline answers by
+ // drawing its prompt again: with the run's line on it when it had read
+ // it, its Enter not yet. Then the line taken: its newline, and in the
+ // next read PS0's C (bash writes them apart): bytes as pty/data read
+ // them off a ReleaseSafe window session's start.
+ out.put(p, "\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle;
+ try testing.expectEqualStrings("echo $$\r", call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "echo $$\n" }).pty());
+ out.put(p, "\r\x1b[K\r" ++ prompt ++ "echo $$");
+ out.put(p, "\r\n\x1b[?2004l\r");
+ try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }).reply.status);
+ out.put(p, "\x1b]133;C;aid=pardes\x074242\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt);
+ try testing.expectEqualStrings("exit 0\n4242\n", call(p, .{ .tag = 4, .op = .read, .node = node, .handle = h, .size = 64 }).bytes);
+}
+
+test "a run written just after a new terminal's greeting is typed is not answered with the greeting's output" {
+ const gpa = testing.allocator;
+ const p = try withTerm(gpa);
+ defer p.deinit();
+ p.panes[0].?.greet = true; // a Term's, in a window (resized)
+ p.update(.{ .resize = .{ .cols = 80, .rows = 24 } });
+ while (p.nextEffect()) |_| {}
+ const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07";
+ // The first prompt: the greeting typed at it, its echo not back yet.
+ p.update(.{ .output = .{ .pane = .at(0), .bytes = prompt } });
+ var greeted: [16]u8 = undefined;
+ var len: usize = 0;
+ while (p.nextEffect()) |e| if (e == .write) {
+ const b = e.write.bytes.slice();
+ @memcpy(greeted[len..][0..b.len], b);
+ len += b.len;
+ };
+ try testing.expectEqualStrings("ls\r", greeted[0..len]);
+ const node = Node.of(serialOf(p), .pty_run);
+ const h = call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle;
+ _ = call(p, .{ .tag = 2, .op = .write, .node = node, .handle = h, .data = "true\n" });
+ for ([_][]const u8{ "ls\r\n\x1b]133;C;aid=pardes\x07notes.txt\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt, "true\r\n\x1b]133;C;aid=pardes\x07\x1b]133;D;0;aid=pardes\x07" ++ prompt }) |bytes| {
+ p.update(.{ .output = .{ .pane = .at(0), .bytes = bytes } });
+ while (p.nextEffect()) |_| {}
+ }
+ try testing.expectEqualStrings("exit 0\n", call(p, .{ .tag = 3, .op = .read, .node = node, .handle = h, .size = 64 }).bytes);
+}
+
test "run answers how its command ended once the shell is back at a prompt" {
const gpa = testing.allocator;
const p = try withTerm(gpa);
diff --git a/core/panes.zig b/core/panes.zig
index 5bf6992a..4116c3e8 100644
--- a/core/panes.zig
+++ b/core/panes.zig
@@ -160,6 +160,10 @@ pub const Pane = struct {
cols: u16,
rows: u16,
greet: bool = false,
+ /// Its greeting was typed (Pardes.layout): that `ls` is its shell's
+ /// first command, and a run written until the prompt after it waits for
+ /// that prompt (ninep/pty.zig `greeting`), as for the first.
+ greeted: bool = false,
/// Its shell could not be started (Pardes.shellFailed): a run hears
/// `error shell gone` at once.
shell_failed: bool = false,
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(&copy, .{ .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/term/terminal.zig b/core/term/terminal.zig
index 45c01841..88eb1443 100644
--- a/core/term/terminal.zig
+++ b/core/term/terminal.zig
@@ -927,9 +927,19 @@ pub fn prompt(state: ?*State) Term.Prompt {
// Nothing further right counts: that is where fish draws a right
// prompt, and fish suggests nothing on an empty line.
const empty = ready and empty: {
+ var prompted = false;
const row = cursor.page_pin.cells(.all);
- for (row[0..@min(cursor.x + 1, row.len)]) |cell|
+ for (row[0..@min(cursor.x + 1, row.len)]) |cell| {
if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false;
+ prompted = prompted or cell.semantic_content == .prompt;
+ }
+ // A row with no prompt on it, begun by a newline in the input: the
+ // line above was taken, its Enter echoed and the command's C still
+ // to come (bash writes them apart), so it is typed still.
+ if (!prompted and cursor.page_row.semantic_prompt == .prompt_continuation) if (cursor.page_pin.up(1)) |above| {
+ for (above.cells(.all)) |cell|
+ if (cell.semantic_content == .input and !cell.isEmpty()) break :empty false;
+ };
break :empty true;
};
return .{
diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ
index ac61ca74..fac705c6 100644
--- a/docs/typ/reference.typ
+++ b/docs/typ/reference.typ
@@ -914,7 +914,8 @@ Terminal panes also have #file("pty/"):
the clear onward). Or: `busy: <program> is running` (bare `busy` when text is typed at the prompt, `busy alternate screen` on the alternate screen with no prompt drawn),
`exit ?` (no status reported, not a success), `error not run` (the shell
refused the line, e.g. a fish syntax error), `error shell gone`, `error no prompt marks`, and on a command pane `error a command runs here, not a shell` (`error command done; not a shell` once it ended). A line written
- before a fresh terminal's first prompt waits for it. One line per run; a
+ before a fresh terminal's first prompt waits for it, and for the prompt
+ after the `ls` a new terminal in a directory greets with. One line per run; a
second line before the answer is refused.
#file("pty/run") relies on the OSC 133 marks pardes injects into bash and
diff --git a/runtime/client.zig b/runtime/client.zig
index 43fdf98d..1d348aea 100644
--- a/runtime/client.zig
+++ b/runtime/client.zig
@@ -95,7 +95,7 @@ pub const Start = struct {
s.o.frames = &s.frames;
// Exec'd at an Upgrade (`execAgain`): for the view it had.
if (init.environ_map.get("PARDES_JOIN_VIEW")) |v| s.o.join_view = std.fmt.parseInt(u8, v, 10) catch null;
- s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null) orelse return false;
+ s.r = replica.join(s.gpa, &s.joined, dial.path, dial.session, s.o, s.have, &s.why, null, false) orelse return false;
return true;
}
@@ -175,7 +175,7 @@ pub fn Loop(comptime Frontend: type) type {
frames: *pardes.FrameStats,
pub fn init(fe: *Frontend, s: *Start) !L {
- var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd }, .fe = fe, .frames = &s.frames };
+ var l: L = .{ .link = .{ .r = s.r, .fd = s.joined.fd, .far = s.have != null }, .fe = fe, .frames = &s.frames };
try l.link.fromEnv(s.gpa, s.env);
return l;
}
@@ -209,11 +209,23 @@ pub fn Loop(comptime Frontend: type) type {
l.after();
}
if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file);
- if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close });
- // The link's reader ends with the link, posting as it goes:
- // what it posted is let go until it has (a terminal's queue
- // is bounded: a reader blocked on it would never end).
- _ = libc.shutdown(s.joined.fd, 2);
+ // Its link up and the session's state to take again: its
+ // goodbye and its hello said on it, the session's dump comes
+ // there (`replica.comeBack`); its reader reads on to the welcome,
+ // letting the stream it leaves go. Only a link that is gone
+ // is dialled again.
+ const here = link.backHere() and s.joined.rest.overlong() == null and back: {
+ link.back.store(true, .release);
+ break :back replica.comeBack(s.joined.fd, s.dial.session, s.r.view);
+ };
+ if (!here) {
+ if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close });
+ _ = libc.shutdown(s.joined.fd, 2);
+ }
+ // The link's reader ends with the link (or at the welcome),
+ // posting as it goes: what it posted is let go until it has
+ // (a terminal's queue is bounded: a reader blocked on it
+ // would never end).
while (true) {
const ended = done.load(.acquire);
l.fe.drop();
@@ -221,14 +233,23 @@ pub fn Loop(comptime Frontend: type) type {
std.Thread.yield() catch {};
}
reader.join();
- _ = libc.close(s.joined.fd);
- s.joined.rest.deinit(s.gpa);
+ if (!here) {
+ _ = libc.close(s.joined.fd);
+ s.joined.rest.deinit(s.gpa);
+ }
// Its link cut with no word by a session that is there still
// (an Upgrade's exec): joined again, as when told so.
if (link.gone and link.refused == null and link.ended == null and !link.left and replica.cutListed("the session hung up", s.dial.session, s.have != null))
link.refused = std.heap.c_allocator.dupe(u8, replica.upgrading) catch null;
- // Why it joins again is in its notice until a key.
- if (!link.rejoins()) {
+ // A last word goes first, one read after it said it comes
+ // back too (a Detach in it, the session's end). Why it joins
+ // again is in its notice until a key.
+ const goes = link.ended != null or link.left;
+ if (here and goes) {
+ _ = libc.close(s.joined.fd);
+ s.joined.rest.deinit(s.gpa);
+ }
+ if (goes or !link.rejoins()) {
// What it made since it joined, kept for its next start.
if (s.have) |h| h.keep(s.r.core());
s.r.deinit();
@@ -238,7 +259,7 @@ pub fn Loop(comptime Frontend: type) type {
}
// The session again, the core it leaves held meanwhile: its
// blobs are not sent again.
- s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r) orelse {
+ s.r = replica.join(s.gpa, &s.joined, s.dial.path, s.dial.session, s.o, s.have, &s.why, s.r, here) orelse {
if (replica.ended(&s.why)) return .gone;
if (replica.otherBuild(&s.why) and upgrade.replaced()) return .{ .upgrade = s.joined.view };
return .failed;
@@ -272,7 +293,7 @@ pub fn Loop(comptime Frontend: type) type {
/// and its end.
fn read(l: *L, s: *Start, done: *std.atomic.Value(bool)) void {
defer done.store(true, .release);
- replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, l.fe, Frontend.said);
+ replica.readLink(s.gpa, s.joined.fd, &s.joined.rest, &l.link, l.fe, Frontend.said);
l.fe.ended();
}
diff --git a/runtime/daemon.zig b/runtime/daemon.zig
index 595d5107..97941a12 100644
--- a/runtime/daemon.zig
+++ b/runtime/daemon.zig
@@ -241,9 +241,8 @@ extern "c" fn close_range(first: c_uint, last: c_uint, flags: c_int) c_int;
/// twice), on the listener and the lock as fds 3 and 4.
fn spawn(listener: c_int, lock: c_int) bool {
var exe_buf: [4096:0]u8 = undefined;
- const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch return false;
- exe_buf[n] = 0;
- const argv = [_:null]?[*:0]const u8{ &exe_buf, "--daemon", null };
+ const exe = upgrade.startPath(&exe_buf) orelse return false;
+ const argv = [_:null]?[*:0]const u8{ exe, "--daemon", null };
const first = libc.fork();
if (first < 0) return false;
if (first == 0) {
@@ -268,7 +267,7 @@ fn spawn(listener: c_int, lock: c_int) bool {
};
if (null_fd > 4) _ = libc.close(null_fd);
_ = libc.chdir("/");
- _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ));
+ _ = libc.execve(exe, &argv, @ptrCast(libc.environ));
libc._exit(127);
}
var status: c_int = 0;
@@ -677,8 +676,13 @@ fn stubWait(session: libc.pid_t, pipe: c_int) noreturn {
if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s)));
if (libc.W.IFSIGNALED(s)) {
const sig = libc.W.TERMSIG(s);
- const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
- posix.sigaction(sig, &default, null);
+ // A KILL's action is its default already and cannot be set
+ // (EINVAL: posix.sigaction's unreachable, the stub aborting with a
+ // trace on the terminal); any other is put back to it first.
+ if (sig != .KILL) {
+ const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 };
+ posix.sigaction(sig, &default, null);
+ }
_ = libc.raise(sig);
}
libc._exit(1);
diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig
index f59117ee..510c50ea 100644
--- a/runtime/upgrade.zig
+++ b/runtime/upgrade.zig
@@ -58,18 +58,28 @@ pub fn remember(args: []const [:0]const u8) void {
};
}
-/// Its path asked of the system (a readlink) and the file there now (a
+/// Its path asked of the system (a readlink) and the file it runs (a
/// stat), once: after the first frame, off a startup's way (the hosts'
-/// loops; nothing is reinstalled within a frame of a start).
+/// loops). A build can be installed at that path before then (a pair's
+/// session, whose first pass comes after its client's first frame; a
+/// loaded machine): Linux then names the path "PATH (deleted)", and the
+/// file at the path is not the one it started from, the one it runs is.
pub fn locate() void {
if (located) return;
located = true;
- if (exe_len == 0) {
- const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch 0;
- exe_buf[n] = 0;
- exe_len = n;
- }
- if (exe()) |path| started_inode = inodeOf(path);
+ if (exe_len == 0) exe_len = if (startPath(&exe_buf)) |path| path.len else 0;
+ started_inode = if (builtin.os.tag == .linux) inodeOf("/proc/self/exe") else if (exe()) |path| inodeOf(path) else null;
+}
+
+/// The path this process was started from, as the system names it, less
+/// the " (deleted)" Linux adds once the file there was replaced (a
+/// reinstall): the path is the path (what an Upgrade execs, and a daemon
+/// started from here: daemon.zig `spawn`).
+pub fn startPath(buf: *[4096:0]u8) ?[:0]const u8 {
+ const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), buf) catch return null;
+ const len = if (std.mem.endsWith(u8, buf[0..n], " (deleted)")) n - " (deleted)".len else n;
+ buf[len] = 0;
+ return buf[0..len :0];
}
fn inodeOf(path: [:0]const u8) ?u64 {
diff --git a/test/behaviour/addons_pdf.zig b/test/behaviour/addons_pdf.zig
index cf5c8009..18fa503c 100644
--- a/test/behaviour/addons_pdf.zig
+++ b/test/behaviour/addons_pdf.zig
@@ -132,6 +132,22 @@ test "addons: a PDF's / lists its hits as file.pdf:P:H rows in a +Search, n walk
try std.testing.expect(try s.focused() != n);
}
+test "addons: a PDF's / of what its page has not, and f on a PDF with no outline, each say so and the session goes on (the bridge's none is a NULL with a count of 0: a safe build's abort before)" {
+ var s = try Session.initFile(std.testing.allocator, "x\n");
+ defer s.deinit();
+ const n = try s.lookFile("docs/design.pdf");
+ // No page has it: page 1's hits of it asked, none; a hit of it a miss.
+ try s.keys("/zzqxv\r");
+ try std.testing.expectEqual(@as(u32, 1), (try s.pdfPage(n))[0]);
+ _ = try s.refused(s.at("/pane/{d}/look", .{n}), ":1:1\n");
+ try std.testing.expect(has(try s.read("/log"), "design.pdf has no search hit 1 on page 1"));
+ // tall.pdf has no outline.
+ const t = try s.lookFile("test/pdf-fixtures/tall.pdf");
+ try s.keys("f");
+ try std.testing.expect(has(try s.read("/log"), "PdfSections: this PDF has no outline"));
+ try std.testing.expectEqual(t, try s.focused());
+}
+
test "addons: a PDF's f is its PdfSections, its outline as places a Look in it goes to (none once the PDF is gone), and a jump back over a far one is Ctrl-o's, Forward's on, two places on a page a window apart two" {
var s = try Session.initFile(std.testing.allocator, "x\n");
defer s.deinit();
diff --git a/test/daemon.py b/test/daemon.py
index dc1abcbc..f456837b 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -188,14 +188,16 @@ def run(client, serial, line):
client.close(fid)
-def adopted_pid(client, pane):
- """An adopted shell's `echo $$`, once it answers: sized twice at its
- adoption (dev/Ptys.zig `take`), it draws its prompt again, and a run
- sent into a prompt redrawn under it reads as not run (core/ninep/pty.zig
- `noteMarks`)."""
- wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n')
+def pid_in(client, pane):
+ """The pid of terminal `pane`'s shell, its `echo $$` by pty/run, asked
+ at once: a run written before its first prompt (or before the prompt
+ after its greeting) waits for it, and one under a prompt drawn again
+ (a window's first size, an adoption's two) is still the line run
+ (core/ninep/pty.zig). Any other answer is said whole."""
said = run(client, pane, b'echo $$\n')
- return said.split(b'\n')[1], said
+ pid = re.fullmatch(rb'exit 0\n([0-9]+)\n', said)
+ assert pid, f'pane {pane}: `echo $$` answered {said!r}'
+ return int(pid[1])
# FreeBSD has no /proc: ps and procstat answer instead.
@@ -286,6 +288,31 @@ def links(pid):
return out
+def sockets(pid):
+ """The sockets process `pid` holds (`socket:[inode]`): a client's link
+ among them, the same one while it joins again over it."""
+ out = set()
+ for fd in os.listdir(f'/proc/{pid}/fd'):
+ try:
+ link = os.readlink(f'/proc/{pid}/fd/{fd}')
+ except OSError:
+ continue
+ if link.startswith('socket:'):
+ out.add(link)
+ return out
+
+
+def session_stats(path):
+ """A session's PARDES_REPLICA_STATS line, its words a dict, and its joins'
+ count (`joins_us`'s)."""
+ text = path.read_text() if path.exists() else ''
+ line = next((l for l in text.splitlines() if l.startswith('session inputs')), '')
+ w = line.split()
+ d = {w[i]: w[i + 1] for i in range(1, len(w) - 1, 2)}
+ joins = next((len(l.split()) - 2 for l in text.splitlines() if l.startswith('session joins_us')), 0)
+ return d, joins
+
+
def state_fds(pid):
"""Its fds on the state file, which a session keeps open (Db.zig)."""
return sum(1 for path in links(pid) if path.endswith('/pardes.xitdb'))
@@ -489,8 +516,10 @@ def clients(binary):
started = []
terms = []
try:
- sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ # Its joins counted at its end (PARDES_REPLICA_STATS): those over a
+ # client's own link (`again`) and all of them (`joins_us`).
+ sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')),
+ cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
@@ -536,6 +565,7 @@ def clients(binary):
started.append(d.pid)
wait_for('client D\'s first frame', lambda: b'line 3 of the notes' in td.text(), timeout=20)
made_live(td, root / 'd.check')
+ d_links = sockets(d.pid)
shown = view_panes(nine)
nine.write('/exec', b'New\n')
mine = wait_for('a pane in client D\'s view', lambda: view_panes(nine) - shown).pop()
@@ -546,6 +576,9 @@ def clients(binary):
os.write(ta.master, b'jk')
time.sleep(.2)
assert d.poll() is None
+ # Over its own link: the same connection, no hand-over (counted at
+ # the session's end).
+ assert sockets(d.pid) == d_links, ('client D joined again over its own link', d_links, sockets(d.pid))
made_live(td, root / 'd.check')
assert mine in view_panes(nine), ('client D in its own view again', mine, nine.read('/layout'))
seen = len(checks(root / 'd.check'))
@@ -580,7 +613,8 @@ def clients(binary):
c = tc.spawn([binary, f'--attach={sock}:files'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check')))
started.append(c.pid)
wait_for('client C\'s first frame', lambda: b'$' in tc.text(), timeout=20)
- run(nine, shell, b'echo from-the-session\n')
+ said = run(nine, shell, b'echo from-the-session\n')
+ assert said == b'exit 0\nfrom-the-session\n', said
os.write(tc.master, b'echo from-C\r')
wait_for('client C\'s keys in the shell', lambda: b'from-C' in nine.read(f'/pane/{shell}/body'))
wait_for('client C agrees with a shell\'s output', lambda: agreed(root / 'c.check', 0))
@@ -598,8 +632,12 @@ def clients(binary):
exit_session(nine, pane)
sess.wait(timeout=60)
nine.socket.close()
+ said, joins = session_stats(root / 'session.stats')
+ here = int(said.get('again', '-1'))
+ assert here >= 1, ('the session joined client D again over its link', said)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10)
- print('daemon: replica clients\' session ended, nothing left behind')
+ print(f'daemon: replica clients\' session ended, nothing left behind; its joins: {joins}, of them over a '
+ f'client\'s own link {here}, handed by the daemon {joins - here}')
finally:
for t in terms:
t.close()
@@ -948,6 +986,86 @@ def pair_rows(binary):
shutil.rmtree(root, ignore_errors=True)
+def pair_back(binary):
+ """A pair with no daemon (PARDES_DAEMON=off, the pair's default-to-be
+ with none reachable): its client put off the session's state
+ (PARDES_TEST_DIVERGE), and apart from that stopped 3 s while the
+ session's file is edited over 9P (SIGSTOP: past replica.behind_max_ms):
+ each time it joins again over its own link ("joined again" on its
+ screen, its socket the same), the session lives on with the text typed
+ in it, unsaved, and the client agrees; its terminal closed, the session
+ ends with its last link. Before pardes-link-1 its rejoin dialled the
+ daemon's socket, nothing took it, and the whole session went (the
+ client exit 1: reports/pardes-pair-12.md, 2b)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rb-', dir=scratch))
+ env = base_env()
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), TERM='xterm-256color',
+ SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_PAIR='1', PARDES_DAEMON='off')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ terms = []
+ try:
+ for how in ('diverged', 'behind'):
+ t = Term(30, 100)
+ terms.append(t)
+ check = root / f'{how}.check'
+ e = dict(env, PARDES_REPLICA_CHECK=str(check), **({'PARDES_TEST_DIVERGE': '3'} if how == 'diverged' else {}))
+ c = t.spawn([binary, f'--9p={how}', str(notes)], e)
+ wait_for('the socket', (root / f'pardes-9p-{how}.sock').exists)
+ nine = Client(root / f'pardes-9p-{how}.sock')
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ links = sockets(c.pid)
+ mark = len(t.text())
+ words = f'unsaved-{how}'.encode()
+ os.write(t.master, b'O' + words + b'\x1b')
+ wait_for('its keys in the session\'s text', lambda: words in nine.read(f'/pane/{pane}/body'))
+ if how == 'behind':
+ os.kill(c.pid, signal.SIGSTOP)
+ for k in range(30):
+ nine.write(f'/pane/{pane}/exec', f'Edit 3a/ edit {k} /\n'.encode())
+ time.sleep(.1)
+ os.kill(c.pid, signal.SIGCONT)
+ deadline = time.monotonic() + 30
+ while b'joined again' not in t.text()[mark:]:
+ went = [w for w, gone in (('the client', c.poll() is not None), ('the session', not alive(session))) if gone]
+ assert not went, (f'{how}: {" and ".join(went)} went (client exit {c.poll()}); '
+ f'its terminal\'s last bytes: {t.text()[-600:]!r}')
+ assert time.monotonic() < deadline, f'{how}: the client joined again'
+ os.write(t.master, b'jk')
+ time.sleep(.2)
+ said = b'this client diverged' if how == 'diverged' else b' s behind'
+ wait_for(f'{how}: its notice says why', lambda: said in t.text()[mark:], timeout=10)
+ assert c.poll() is None and alive(session), (how, c.poll())
+ assert sockets(c.pid) == links, (f'{how}: joined again over its own link', links, sockets(c.pid))
+ assert words in nine.read(f'/pane/{pane}/body'), how
+ seen = len(checks(check))
+ os.write(t.master, b'jj')
+ wait_for(f'{how}: the client agrees after it', lambda: agreed(check, seen), timeout=30)
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ c.wait(timeout=20)
+ wait_for(f'{how}: the session ended with its last link', lambda: not alive(session), timeout=20)
+ print(f'pair back: no daemon, its client {how}: joined again over its own link, the session alive, '
+ f'its unsaved text there, agreed; its terminal closed, the session ended')
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def attach_upgrading(binary, rounds=6, dump=True):
"""`pardes attach` as its session upgrades: started at once after the
Upgrade's word, it is handed to the session before the exec; told the
@@ -1217,12 +1335,18 @@ def pair_upgrade_views(binary):
shutil.rmtree(root, ignore_errors=True)
-def pair_exec_reaps(old, new):
+def pair_exec_reaps(old, new, early=False):
"""PARDES_PAIR across builds: a pair started from `root/bin` (old), its
session upgraded to the build installed there since (new): its client,
the session's parent, execs that build (the blink) and is still its
parent; Exit typed then: the client returns once the session is gone,
- reaped, its status the session's (0), as before the exec."""
+ reaped, its status the session's (0), as before the exec. `early`: old
+ and new the same build, installed again at once, before the session's
+ first pass round its loop, where it first looks its start path up
+ (upgrade.zig `locate`), and as the client starts the daemon from its
+ own (daemon.zig `spawn`): the path is the path, not Linux's "PATH
+ (deleted)", so the daemon starts and the session execs it; the client,
+ its build the session's still, joins again in place (no exec)."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rpx-', dir=scratch))
@@ -1237,36 +1361,48 @@ def pair_exec_reaps(old, new):
notes = root / 'notes.txt'
notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
terms = []
+ sock = root / 'pardes-9p-px.sock'
+ c = session = None
try:
t = Term(30, 100)
terms.append(t)
c = t.spawn([str(binary), '--9p=px', str(notes)], env)
- sock = root / 'pardes-9p-px.sock'
+ if early:
+ install(new, binary)
wait_for('the socket', sock.exists)
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
assert ppid(session) == c.pid
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
- install(new, binary)
+ if not early:
+ install(new, binary)
ino = sock.stat().st_ino
# Before the Upgrade: the exec'd client can draw before its exec is seen.
mark = len(t.text())
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
- wait_for('the client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30)
+ if early:
+ wait_for('joined again in place', lambda: b'joined again' in t.text()[mark:], timeout=30)
+ else:
+ wait_for('the client on the new build', lambda: on_build(c, binary), timeout=30)
nine = reconnect(sock)
assert ppid(session) == c.pid
# The blink: its screen left and entered again, the notes drawn there.
- wait_for('drawn again', lambda: (lambda x: x.rfind(b'\x1b[?1049h') > x.rfind(b'\x1b[?1049l') > mark
- and b'line 3 of the notes' in x[x.rfind(b'\x1b[?1049h'):])(t.text()), timeout=30)
+ if not early:
+ wait_for('drawn again', lambda: b'line 3 of the notes' in (entered_again(t.text(), mark) or b''), timeout=30)
nine.write('/ctl', b'Exit\n')
nine.socket.close()
assert c.wait(timeout=30) == 0, c.returncode
# Its parent's wait returned: the session reaped, not a zombie left
# to whoever takes it in.
assert not os.path.exists(f'/proc/{session}') if procfs else not alive(session), open(f'/proc/{session}/stat').read()
- print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0')
+ print('pair exec reaps: a pair\'s client exec\'d at its session\'s Upgrade still reaps it at Exit, status 0'
+ + (' (the same build installed again before the session looked its path up: joined again in place)' if early else ''))
+ except (TimeoutError, AssertionError, OSError, EOFError, subprocess.TimeoutExpired) as err:
+ kept = keep_evidence('pair-exec', root, env, binary, sock, [('session', session)] if session else [],
+ [('client', t, c, root / 'client.check', root / 'client.stats')] if c else [])
+ raise AssertionError(f'{type(err).__name__}: {err} (kept: {kept})') from None
finally:
for p in processes(root):
try:
@@ -1324,8 +1460,8 @@ def far_exec(old, new):
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
nine = reconnect(sock)
- wait_for('the far client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30)
- wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ wait_for('the far client on the new build', lambda: on_build(c, binary), timeout=30)
+ wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30)
# Its environment read once the new image runs (it entered the
# screen): an exec names the new file in /proc/PID/exe before it has
# written where the environment is, and a read between gets nothing
@@ -1403,7 +1539,7 @@ def pair_window_geometry(gui_binary, new_gui):
nine.write('/ctl', b'Upgrade\n')
nine.socket.close()
wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60)
- wait_for('the window on the new build', lambda: exe_of(p.pid) == (str(gui), True), timeout=30)
+ wait_for('the window on the new build', lambda: on_build(p, gui), timeout=30)
nine = reconnect(sock)
time.sleep(3)
assert grid(nine) == sized, ('the exec\'d window the size it had', grid(nine), sized, plain)
@@ -1458,8 +1594,7 @@ def manage(binary):
c.write('/pane/1/exec', b'Term\n')
wait_for(f'session {name}\'s shell', lambda: terminals(c))
shell = terminals(c)[0]
- wait_for(f'session {name}\'s shell answers', lambda: run(c, shell, b'true\n') == b'exit 0\n')
- shells[name] = int(run(c, shell, b'echo $$\n').split(b'\n')[1])
+ shells[name] = pid_in(c, shell)
started.append(shells[name])
daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
started.append(daemon)
@@ -1563,8 +1698,7 @@ def relink(binary):
work.write('/pane/1/exec', b'Term\n')
wait_for('its shell', lambda: terminals(work))
shell = terminals(work)[0]
- wait_for('its shell answers', lambda: run(work, shell, b'true\n') == b'exit 0\n')
- shell_pid = int(run(work, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(work, shell)
started.append(shell_pid)
term = Term()
terms.append(term)
@@ -1576,7 +1710,7 @@ def relink(binary):
started.append(own_pid)
wait_for('its first frame', lambda: b'\x1b[?1049h' in term.text())
own_shell = terminals(own)[0]
- own_shell_pid = int(run(own, own_shell, b'echo $$\n').split(b'\n')[1])
+ own_shell_pid = pid_in(own, own_shell)
started.append(own_shell_pid)
expected = [f'session work {session} {listed_as("detached")}', f'session own {own_pid} {listed_as("has a frontend")}',
f'shell {shell_pid}', f'shell {own_shell_pid}']
@@ -1608,8 +1742,7 @@ def relink(binary):
before = set(terminals(own))
own.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop()
- pid, said = adopted_pid(own, pane)
- assert pid == str(shell_pid).encode(), (said, shell_pid)
+ assert (pid := pid_in(own, pane)) == shell_pid, (pid, shell_pid)
print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted')
exit_session(own, pane)
stub.wait(timeout=10)
@@ -1659,7 +1792,7 @@ def answer_late(binary):
one = Client(root / 'pardes-9p-one.sock')
session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
started.append(session)
- shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(one, terminals(one)[0])
started.append(shell_pid)
daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
started.append(daemon)
@@ -1683,8 +1816,7 @@ def answer_late(binary):
two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
took = time.monotonic() - asked
pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
- pid, said = adopted_pid(two, pane)
- assert pid == str(shell_pid).encode(), (said, shell_pid)
+ assert (pid := pid_in(two, pane)) == shell_pid, (pid, shell_pid)
print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
f'and shell {shell_pid} was adopted')
exit_session(two, pane)
@@ -2233,8 +2365,8 @@ def far_flood(binary):
started = []
terms = []
try:
- sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ sess = subprocess.Popen([binary, '--detach=files', str(notes)], env=dict(env, PARDES_REPLICA_STATS=str(root / 'session.stats')),
+ cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
started.append(sess.pid)
sock = root / 'pardes-replica.sock'
wait_for('the replica socket', sock.exists)
@@ -2258,13 +2390,24 @@ def far_flood(binary):
dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check), PARDES_REPLICA_STATS=str(stats)))
started.append(c.pid)
wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60)
+ links = sockets(c.pid)
nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r')
wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60)
+ ended_at = time.monotonic()
seen = len(checks(check))
wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120)
# Queued behind the flood, let go for its lag, joined again from a
# dump: a link of its ended (its stats line), and its notice says why.
assert joins(stats), ('no link of the far client ended under the flood', checks(stats))
+ # Fallen behind, a far client dials again (core/replica.zig
+ # `Link.backHere`: the second road until bounded flight): a new
+ # connection, not what the old one holds for it read through; each
+ # join's time and the KB it was sent; the flood's end to its agreement.
+ same = sockets(c.pid) == links
+ print(f'far flood: the far client\'s link {"the same" if same else "another"} after {len(joins(stats))} joins again '
+ f'(join ms {[j.get("join_ms") for j in joins(stats)]}, sent KB {[j.get("sent_kb") for j in joins(stats)]}); '
+ f'agreed {time.monotonic() - ended_at:.1f} s after yes ended')
+ assert not same, ('the far client behind dialled again: another connection', links, sockets(c.pid))
wait_for('the far client\'s notice of its join again', lambda: b'joined again: ' in t.text() and b' s behind' in t.text(), timeout=30)
os.write(t.master, b'echo from-far\r')
wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30)
@@ -2726,6 +2869,46 @@ def cpu_ticks(pid):
return int(stat[11]) + int(stat[12])
+def killed_session(binary):
+ """A terminal's session killed outright (KILL, as the OOM killer does):
+ the job its terminal waits on ends with it, and says nothing of its own
+ (no trace): the own path's stub dead of the same signal, as a job is
+ (daemon.zig `stubWait`, which aborted re-raising a KILL); a pair's
+ client let go of its session, 1."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rk-', dir=scratch))
+ env = base_env()
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ t = Term(30, 100)
+ try:
+ c = t.spawn([binary, '--9p=k', str(notes)], env)
+ sock = root / 'pardes-9p-k.sock'
+ wait_for('the socket', sock.exists)
+ with Client(sock) as nine:
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ os.kill(session, signal.SIGKILL)
+ code = c.wait(timeout=30)
+ said = t.last()
+ assert b'panic' not in said and b'unreachable' not in said, said[-1500:]
+ assert code == (1 if WITH_PAIR else -signal.SIGKILL), (code, said[-600:])
+ print(f'killed session: its terminal\'s job ended {code} with it, no trace')
+ finally:
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def kitty_image(binary, secs=5):
"""A plain attach watching a terminal in which a program
shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it
@@ -2825,6 +3008,7 @@ def main(binary, cycles):
launch(binary)
pair(binary)
pair_rows(binary)
+ pair_back(binary)
attach_upgrading(binary)
kept_views(binary)
pair_upgrade_views(binary)
@@ -2833,7 +3017,7 @@ def main(binary, cycles):
answer_late(binary)
kitty_image(binary)
shell = terminals(client)[0]
- shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(client, shell)
started.append(shell_pid)
# Detach in the terminal it was born with: the stub ends (exit 0,
# its words), the terminal put back; the session runs on detached,
@@ -2974,8 +3158,7 @@ def main(binary, cycles):
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before)
pane = adopted.pop()
- pid, said = adopted_pid(client, pane)
- assert pid == str(shell_pid).encode(), said
+ assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid)
print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted')
# Attached again: a client. (After the runs: a pty/run under a
# client puts it off the session's state, and it joins again; one
@@ -3265,7 +3448,10 @@ def exe_of(pid):
if not procfs:
rows = subprocess.run(['procstat', '-b', str(pid)], capture_output=True).stdout.decode().splitlines()
return (rows[-1].split()[-1] if len(rows) > 1 else ''), None
- link = os.readlink(f'/proc/{pid}/exe')
+ try:
+ link = os.readlink(f'/proc/{pid}/exe')
+ except OSError: # gone, or a zombie: it runs nothing
+ return '', False
try:
same = os.stat(f'/proc/{pid}/exe').st_ino == os.stat(link).st_ino
except OSError:
@@ -3273,6 +3459,22 @@ def exe_of(pid):
return link, same
+def entered_again(text, mark):
+ """The blink of a client exec'd at an Upgrade: its terminal's screen
+ left at or after `mark` (the text's length before the Upgrade: when the
+ reader had read all the old client wrote, the leave is its very next
+ byte) and entered again. What was drawn since that enter, or None."""
+ enter, leave = text.rfind(b'\x1b[?1049h'), text.rfind(b'\x1b[?1049l')
+ return text[enter:] if enter > leave >= mark else None
+
+
+def on_build(proc, binary):
+ """Whether the test's child `proc` runs `binary` now (exe_of); one that
+ ended says so with its status at once, not as a wait run out."""
+ assert proc.poll() is None, f'pid {proc.pid} ended ({proc.returncode}) before it ran {binary}'
+ return exe_of(proc.pid) == (str(binary), True)
+
+
def ppid(pid):
if not procfs:
return int(ps('-o', 'ppid=', '-p', str(pid)))
@@ -3382,7 +3584,7 @@ def upgrades(old, new):
daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0]
started.append(daemon)
shell = terminals(client)[0]
- shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(client, shell)
started.append(shell_pid)
client.write(f'/pane/{shell}/look', f'{notes}\n'.encode())
text = int(client.read('/look'))
@@ -3572,7 +3774,7 @@ def upgrades(old, new):
assert os.stat(f'/proc/{session}/exe').st_ino == running, 'back on the build that ran'
assert alive(shell_pid) and ppid(shell_pid) == session and stub.poll() is None
assert client.read(f'/pane/{text}/body') == b'one\ntwo\n'
- assert run(client, shell, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ assert (pid := pid_in(client, shell)) == shell_pid, (pid, shell_pid)
print('upgrade: a build that refused the dump fell back to the one running; the shell ran on')
# One that refuses it everywhere: a fresh session, the shells adopted.
@@ -3585,8 +3787,8 @@ def upgrades(old, new):
kept = client.read('/dumps').decode()
assert any(line.split()[0].startswith(f'upgrade-{session}') for line in kept.splitlines()), kept
assert alive(shell_pid) and ppid(shell_pid) == session, ('the shell under the fresh session', shell_pid, alive(shell_pid) and ppid(shell_pid), session)
- pids = {p: run(client, p, b'echo $$\n') for p in terminals(client)}
- adopted = [p for p, out in pids.items() if out.split(b'\n')[1:2] == [str(shell_pid).encode()]]
+ pids = {p: pid_in(client, p) for p in terminals(client)}
+ adopted = [p for p, pid in pids.items() if pid == shell_pid]
assert adopted, ('the shell is a pane of the fresh session', shell_pid, pids, client.read('/index'))
print(f'upgrade: a build that refused it everywhere started afresh, shell {shell_pid} adopted, the dump kept')
@@ -3623,8 +3825,7 @@ def upgrades(old, new):
before = set(terminals(client))
client.write(f'/pane/{min(before)}/exec', b'Adopt\n')
pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop()
- pid, said = adopted_pid(client, pane)
- assert pid == str(shell_pid).encode(), (said, shell_pid)
+ assert (pid := pid_in(client, pane)) == shell_pid, (pid, shell_pid)
print(f'upgrade: the upgraded daemon kept shell {shell_pid} through kill -9 of its session, and it was adopted')
exit_session(client, pane)
stub.wait(timeout=10)
@@ -3723,7 +3924,7 @@ def upgrade_clients(old, new):
nine = Client(sock)
session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
shell = terminals(nine)[0]
- shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(nine, shell)
t = Term(30, 100)
terms.append(t)
tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
@@ -3761,7 +3962,7 @@ def upgrade_clients(old, new):
wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
# The blink: its screen left, and entered again.
- wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ wait_for('the terminal entered again', lambda: entered_again(t.text(), mark), timeout=30)
assert tc.poll() is None and w.p.poll() is None
for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
if knows_exec(new):
@@ -3828,7 +4029,7 @@ def gui_upgrades(old, new):
daemon = wait_for('the daemon', lambda: [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']])[0]
started.append(daemon)
shell = terminals(client)[0]
- shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
+ shell_pid = pid_in(client, shell)
started.append(shell_pid)
client.write(f'/pane/{shell}/look', f'{notes}\n'.encode())
text = int(client.read('/look'))
@@ -3908,6 +4109,9 @@ if __name__ == '__main__':
far_exec(old, new)
else:
print('far exec: skipped: the old build\'s far client, cut at the Upgrade with no last word, takes it for its session\'s end (no PARDES_JOIN_SIZE)')
+ # A reinstall of the new build before the pair's first look: the
+ # new build's own, whatever the old one does.
+ pair_exec_reaps(new, new, early=True)
# With a pardes-gui beside each: the clients carried too.
if all(a.with_name('pardes-gui').exists() for a in (old, new)):
upgrade_clients(old, new)
@@ -3927,8 +4131,11 @@ if __name__ == '__main__':
elif sys.argv[1:2] == ['--pair']:
pair(sys.argv[2])
pair_rows(sys.argv[2])
+ pair_back(sys.argv[2])
attach_upgrading(sys.argv[2], dump=False)
pair_upgrade_views(sys.argv[2])
+ elif sys.argv[1:2] == ['--pair-back']:
+ pair_back(sys.argv[2])
elif sys.argv[1:2] == ['--attach-upgrading']:
attach_upgrading(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
@@ -3941,6 +4148,8 @@ if __name__ == '__main__':
far_flood(sys.argv[2])
by_hash(sys.argv[2])
far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--far-flood']:
+ far_flood(sys.argv[2])
elif sys.argv[1:2] == ['--far-find']:
far_find(sys.argv[2])
elif sys.argv[1:2] == ['--kitty-image']:
@@ -3960,3 +4169,4 @@ if __name__ == '__main__':
gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
+ killed_session(sys.argv[1])
diff --git a/test/process/look_and_exec.zig b/test/process/look_and_exec.zig
index 9829797b..8ba52534 100644
--- a/test/process/look_and_exec.zig
+++ b/test/process/look_and_exec.zig
@@ -118,18 +118,8 @@ fn canary(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
// A terminal: pty/run failing then passing.
const term = try f.madeBy(1, "Term\n");
- {
- const deadline = process.nowMs() + 10_000;
- while (true) {
- const answer = try f.run(term, "true\n");
- if (std.mem.eql(u8, answer, "exit 0\n")) break;
- if (process.nowMs() > deadline) {
- std.debug.print("pty/run answered {s}\n", .{answer});
- return error.Timeout;
- }
- process.nap(50);
- }
- }
+ // Asked at once: a run waits for its first prompt and its greeting.
+ try std.testing.expectEqualStrings("exit 0\n", try f.run(term, "true\n"));
try std.testing.expectEqualStrings("exit 1\n", try f.run(term, "false\n"));
try std.testing.expectEqualStrings("exit 0\npassed\n", try f.run(term, "echo passed\n"));
// (A run's answer is its record: the log has no err for these.)
diff --git a/test/process/terminals.zig b/test/process/terminals.zig
index 151b221b..8d595120 100644
--- a/test/process/terminals.zig
+++ b/test/process/terminals.zig
@@ -111,15 +111,6 @@ fn sizeLines(a: std.mem.Allocator, c: *process.Conn, n: u32) ![]const []const u8
return out.items;
}
-/// A shell takes runs: its first prompt, or the one started again.
-fn prompted(a: std.mem.Allocator, c: *process.Conn, term: u32) !void {
- const deadline = eh.nowMs() + 10_000;
- while (!std.mem.eql(u8, try run(a, c, term, "true\n"), "exit 0\n")) {
- if (eh.nowMs() > deadline) return error.NoPrompt;
- process.sleep(50);
- }
-}
-
fn sizedFork(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
var d = try process.Detached.start(gpa, exe, "sized", .{});
defer d.deinit();
@@ -135,7 +126,7 @@ fn sizedFork(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
// the screen's 160x50.
try c.write("/exec", "Term\n");
const term = try c.newest(gpa);
- try prompted(a, c, term);
+ // Asked at once: a run waits for its first prompt and its greeting.
var got = try sttySize(a, c, term);
try expect(!std.mem.eql(u8, got[1], "50 160"));
try expectEqualStrings(got[1], got[0]);
@@ -200,11 +191,7 @@ fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
const serial = try std.fmt.parseInt(u32, w.next().?, 10);
if (std.mem.eql(u8, w.next().?, "term")) term = @max(term, serial);
}
- const deadline = eh.nowMs() + 10_000;
- while (std.mem.eql(u8, try run(a, c, term, "true\n"), "busy\n")) { // deadline its first prompt
- if (eh.nowMs() > deadline) return error.NoPrompt;
- process.sleep(50);
- }
+ try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); // asked at once: it waits for the first prompt, and the greeting's
try expectEqualStrings("exit 1\n", try run(a, c, term, "false\n"));
try expectEqualStrings("exit 0\none\ntwo\n", try run(a, c, term, "printf \"one\\ntwo\\n\"\n")); // then what it printed
try expectEqualStrings("exit 7\n", try run(a, c, term, "sh -c \"exit 7\"\n"));
diff --git a/test/replicas.zig b/test/replicas.zig
index 8f3e5ca5..3aa9263e 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -251,6 +251,8 @@ const Totals = struct {
/// Joins from a dump, refused, again after a divergence put on it
/// (PARDES_TEST_DIVERGE's), and clients that left; quiet checks.
joins: u64 = 0,
+ /// ...of them again over the client's own link (no dial).
+ here: u64 = 0,
refused: u64 = 0,
/// A pair's client's own boot the session's core at its join (`--pair`),
/// or not (its dump loaded instead, the fields that differ said).
@@ -527,11 +529,10 @@ const Client = struct {
stops: @FieldType(replica.Stats, "stops") = @splat(.{}),
/// Its Peer's writer's (`Soak.write`): the batch swapped out of the
/// session's queue for it (the Peers' allocator's), how much of it went
- /// down the link, whether a cut's words end it, a wake asked for room;
- /// how much of the queue carries the soak's clock (`Soak.stamp`).
+ /// down the link, a wake asked for room; how much of the queue carries
+ /// the soak's clock (`Soak.stamp`).
sending: std.ArrayListUnmanaged(u8) = .empty,
at: usize = 0,
- last: bool = false,
draining: bool = false,
marked: usize = 0,
/// The session's unit its last join's dump came after.
@@ -752,14 +753,17 @@ fn describe(buf: []u8, ev: pardes.Event) []const u8 {
} catch "?";
}
-/// Its link ended (it diverged, or it quits): its bye, and its join again
-/// for its view after a divergence (`Link.rejoins`), the core it leaves
-/// held until the dump comes, as `replica.join` holds it.
+/// Its link ended (it diverged, fell behind, was cut off, or it quits):
+/// its join again for its view (`Link.rejoins`), over its link while that
+/// is up (its goodbye and hello said there: runtime/client.zig `run`), the
+/// core it leaves held until the dump comes, as `replica.join` holds it;
+/// else its bye.
fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, typing: *usize) !void {
const r = cl.r.?;
const link = &cl.loop.link;
+ const here = link.backHere() and replica.comeBack(link.fd, "soak", r.view);
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 });
+ if (!here and !link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 });
try drain(cl, c, net, now);
cl.live = 0;
if (link.lagged != 0) {
@@ -775,6 +779,10 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
if (link.rejoins()) {
cl.back = r.view;
cl.dialling = true;
+ if (here) {
+ totals.here += 1;
+ return;
+ }
return net.send(.{ .at = net.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} });
}
try totals.add(&r.stats);
@@ -1435,10 +1443,8 @@ const Soak = struct {
if (!there) cl.peer = null;
};
// A join taken (its Peer holds the dup handed) or refused (its dup
- // closed, daemon.refuseReplica): its writer's join first (the
- // welcome, then the dump with the session's blobs put back where
- // they go: Peer.writeJoin), its far word read (`far` false: on
- // this machine), and its pins let go at the next boundary.
+ // closed, daemon.refuseReplica): its writer's join first (`joinDown`),
+ // its far word read (`far` false: on this machine).
for (s.clients, 0..) |*cl, c| if (cl.handed >= 0) {
defer cl.handed = -1;
const peer = for (ps.list) |slot| {
@@ -1448,44 +1454,17 @@ const Soak = struct {
try net.toClient(c, now, .refused, cl.gen, &.{});
continue;
};
- const f = (try pardes.wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome;
- const welcome = (try pardes.wire.decodeServer(f.tag, f.payload)).welcome;
- var whole: std.ArrayListUnmanaged(u8) = .empty;
- errdefer whole.deinit(gpa);
- var pos: usize = 0;
- for (peer.blobs.items) |b| {
- try whole.appendSlice(gpa, peer.dump[pos..b.at]);
- try whole.appendSlice(gpa, b.bytes);
- pos = b.at;
- }
- try whole.appendSlice(gpa, peer.dump[pos..]);
var word: [16]u8 = undefined;
const far = try pardes.wire.encodeClient(&word, .{ .far = false });
_ = peer.take(far[0], far[pardes.wire.header_len..]);
- ps.post(.{ .joined = peer });
- cl.peer = peer;
- cl.shut = false;
- cl.read_done = false;
- cl.join_seq = ps.seq;
- cl.sending.clearRetainingCapacity();
- cl.at = 0;
- cl.last = false;
- cl.marked = 0;
- // What the join cost the session's step (Peers.join's measure).
- s.join_worst = @max(s.join_worst, ps.join_ns);
- try s.totals.join_session_ns.append(gpa, ps.join_ns);
- ps.join_ns = 0;
- cl.gen += 1;
- cl.id = welcome.client;
- cl.view = welcome.view.index();
- cl.digest = welcome.digest;
- s.totals.joins += 1;
- Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq);
- try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa));
+ try s.joinDown(cl, c, peer);
};
- // A Detach typed in a client's view, or one cut off for its lag: its
- // link shut, it hears its end and nothing after; its reader's end
- // said (the next boundary lets it go).
+ // A join again over a client's own link (Peers.joinAgain): its writer's
+ // next, the stream it leaves let go.
+ for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| if (peer.written != peer.gen) try s.joinDown(cl, c, peer);
+ // A Detach typed in a client's view: its link shut, it hears its end
+ // and nothing after; its reader's end said (the next boundary lets
+ // it go).
if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view.index() == k and !cl.shut) {
cl.shut = true;
};
@@ -1513,6 +1492,44 @@ const Soak = struct {
s.echo.clearRetainingCapacity();
}
+ /// Client `c`'s Peer's writer's join (Peer.writeJoin): the welcome, then
+ /// the dump with the session's blobs put back where they go, down its
+ /// link, what was queued before it let go; its pins let go at the next
+ /// boundary.
+ fn joinDown(s: *Soak, cl: *Client, c: usize, peer: *replica.Peer) !void {
+ const ps = &s.l.peers;
+ const f = (try pardes.wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome;
+ const welcome = (try pardes.wire.decodeServer(f.tag, f.payload)).welcome;
+ var whole: std.ArrayListUnmanaged(u8) = .empty;
+ errdefer whole.deinit(gpa);
+ var pos: usize = 0;
+ for (peer.blobs.items) |b| {
+ try whole.appendSlice(gpa, peer.dump[pos..b.at]);
+ try whole.appendSlice(gpa, b.bytes);
+ pos = b.at;
+ }
+ try whole.appendSlice(gpa, peer.dump[pos..]);
+ peer.written = peer.gen;
+ ps.post(.{ .joined = .{ .peer = peer, .gen = peer.gen } });
+ cl.peer = peer;
+ cl.shut = false;
+ cl.read_done = false;
+ cl.join_seq = ps.seq;
+ cl.sending.clearRetainingCapacity();
+ cl.at = 0;
+ cl.marked = 0;
+ // What the join cost the session's step (Peers.join's measure).
+ s.join_worst = @max(s.join_worst, ps.join_ns);
+ try s.totals.join_session_ns.append(gpa, ps.join_ns);
+ ps.join_ns = 0;
+ cl.gen += 1;
+ cl.id = welcome.client;
+ cl.view = welcome.view.index();
+ cl.digest = welcome.digest;
+ s.totals.joins += 1;
+ Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq);
+ try s.net.toClient(c, s.now, .dump, cl.gen, try whole.toOwnedSlice(gpa));
+ }
/// The units the session queued for client `cl` since, their heads
/// carrying the soak's clock, the session's here (its host's `now`):
/// what the client's lag is measured by. Its replica guesses no clock
@@ -1534,7 +1551,7 @@ const Soak = struct {
/// frame a message. The far link takes no more than `throttle_window`
/// ahead of what has crossed: the rest waits in the queue, as it does
/// for a writer blocked on its socket, until room comes (`.drain`). A
- /// cut's words end a batch, and its link after them.
+ /// cut's words are its last until its client's hello again there.
fn write(s: *Soak, cl: *Client, c: usize) !void {
const peer = cl.peer orelse return;
const net = s.net;
@@ -1543,11 +1560,9 @@ const Soak = struct {
if (cl.at == cl.sending.items.len) {
cl.sending.clearRetainingCapacity();
cl.at = 0;
- if (cl.last) return s.shut(cl, c);
const io = s.l.peers.io;
peer.lock.lockUncancelable(io);
std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending);
- cl.last = peer.cut;
peer.lock.unlock(io);
cl.marked = 0;
if (cl.sending.items.len == 0) return;
@@ -1590,11 +1605,10 @@ const Soak = struct {
}
/// Client `c`'s link ended at the session's side (a Detach typed in its
- /// view, or the words of a cut sent): it hears its end and nothing after,
- /// and its reader's end is said (the next boundary lets it go).
+ /// view): it hears its end and nothing after, and its reader's end is
+ /// said (the next boundary lets it go).
fn shut(s: *Soak, cl: *Client, c: usize) !void {
cl.shut = true;
- cl.last = false;
if (cl.read_done) return;
cl.read_done = true;
s.l.peers.post(.{ .gone = cl.peer.? });
@@ -3400,7 +3414,7 @@ pub fn main(init: std.process.Init) !void {
try stop_lines.print(gpa, "{d:>4} {d:>8} {d:>6} {d:>6} {d:>3}/{d}/{d} ", .{ rtt, t.unlisted, t.wakes, t.draws, t.asked[0], t.asked[1], t.asked[2] });
for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n });
try stop_lines.append(gpa, '\n');
- try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] });
+ try join_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.here, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] });
try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{
rtt, t.far_joins, t.far_lags,
secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)),
@@ -3419,8 +3433,8 @@ pub fn main(init: std.process.Init) !void {
}
std.debug.print("terminals: a peer's unit bytes a second under the flood (the pty's bytes ride in them); KB of units sent to the peers in all\n", .{});
std.debug.print(" rtt unit B/s units KB\n{s}", .{term_lines.items});
- std.debug.print("clients: joins from a dump, refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{});
- std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items});
+ std.debug.print("clients: joins from a dump (here: of them again over the client's own link, no dial), refused (every view taken), joined again after a divergence put on them, left (of them by a Detach); quiet checks of the session's digest agreed/differed; the digests the clients compared (units and quiet), of the units they took; resizes the windows posted; the kinds' panes the session opened (image/life/pdf)\n", .{});
+ std.debug.print(" rtt joins here refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items});
std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{});
std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items});
std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{});