summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
Diffstat (limited to 'core')
-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
9 files changed, 956 insertions, 229 deletions
diff --git a/core/Addon.zig b/core/Addon.zig
index aa3195f9..e93a43dc 100644
--- a/core/Addon.zig
+++ b/core/Addon.zig
@@ -532,7 +532,7 @@ pub const LoadedWord = struct { name: []const u8, leader: []const u8 = "", arg:
/// `ops`'s head as a `Loaded` (its words borrowed from it, in `words`).
pub fn loadedOf(ops: *const Kind.Ops, path: []const u8, hash: [32]u8, words: *[64]LoadedWord) Loaded {
const h = &ops.head;
- const head_words = if (h.nwords == 0 or h.words == null) &.{} else h.words[0..@min(h.nwords, words.len)];
+ const head_words = @import("addon").cSlice(h.words, @min(h.nwords, words.len));
for (head_words, words[0..head_words.len]) |*w, *out| out.* = .{
.name = if (w.name == null) "" else std.mem.span(w.name),
.leader = if (w.leader == null) "" else std.mem.span(w.leader),
diff --git a/core/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 .{