summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/fs.zig4
-rw-r--r--src/gui/gui.zig2
-rw-r--r--src/replica.zig86
-rw-r--r--src/tape.zig120
-rw-r--r--src/tui/tui.zig4
-rw-r--r--src/wire.zig8
6 files changed, 207 insertions, 17 deletions
diff --git a/src/fs.zig b/src/fs.zig
index 855beb25..47ee0856 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -726,7 +726,9 @@ fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 {
return pardes.tape.site(.read_file, gpa, readHost, .{ gpa, path_z, limit });
}
-fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 {
+/// The disk's file at `path_z`, whole: the session's read, and a replica
+/// client's of a read it was sent by hash (tape.zig `byHash`).
+pub fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 {
const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .NONBLOCK = true });
if (fd < 0) return switch (libc.errno(fd)) {
.ACCES, .PERM => error.PermissionDenied,
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index 9bd6f5b9..92117c19 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -1483,7 +1483,7 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
reader.join();
client.lock.lockUncancelable(io);
for (client.inbox.items) |msg| switch (msg) {
- .unit, .screen, .refused => |b| std.heap.c_allocator.free(b),
+ .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
.checked => {},
};
client.inbox.clearRetainingCapacity();
diff --git a/src/replica.zig b/src/replica.zig
index 09746377..fa888021 100644
--- a/src/replica.zig
+++ b/src/replica.zig
@@ -689,6 +689,14 @@ pub const Replica = struct {
screen_out: std.ArrayListUnmanaged(u8) = .empty,
/// Its Shadows' rasters, from the session's strips (17.3).
blobs: pardes.Kind.Blobs = .{},
+ /// A record's bytes by hash coming in pieces (`blobPiece`), and how
+ /// many of them came.
+ incoming: ?tape.Big = null,
+ incoming_got: usize = 0,
+ /// A far client's blobs on disk (its Have's), where a file it is sent
+ /// goes for its next join.
+ cache: ?Cache = null,
+ io: std.Io = undefined,
/// Its predicted echo (src/term/echo.zig), drawn over its core's terminals:
/// fed by its keys, its units and its deltas here, and by `echoFrame`.
echo: Echo = .{},
@@ -777,6 +785,7 @@ pub const Replica = struct {
was.end();
}
r.blobs.deinit(r.gpa);
+ if (r.incoming) |b| r.gpa.free(b.bytes);
r.copy.deinit();
for (r.pending.items) |p| r.freePending(p);
r.pending.deinit(r.gpa);
@@ -1261,6 +1270,33 @@ pub const Replica = struct {
return r.screen_out.items;
}
+ /// A piece of a record's bytes by hash (Peer.blob): whole and checked
+ /// against its hash, kept for the unit that names it (tape.keepFile),
+ /// and a file's, a far client's, on disk (`cache`) for its next join.
+ pub fn blobPiece(r: *Replica, msg: []const u8) void {
+ if (msg.len < 49) return r.fail("a short piece of a record by hash");
+ const total = std.math.cast(usize, std.mem.readInt(u64, msg[32..40], .little)) orelse return r.fail("a record by hash too long");
+ const at = std.mem.readInt(u64, msg[40..48], .little);
+ if (at == 0) {
+ if (r.incoming) |b| r.gpa.free(b.bytes);
+ r.incoming = .{ .hash = msg[0..32].*, .bytes = r.gpa.alloc(u8, total) catch return r.fail("out of memory for a record by hash"), .path = msg[48] != 0 };
+ r.incoming_got = 0;
+ }
+ const b = r.incoming orelse return r.fail("a piece of a record by hash out of order");
+ const piece = msg[49..];
+ if (at != r.incoming_got or b.bytes.len != total or piece.len > total - at) return r.fail("a piece of a record by hash out of order");
+ @memcpy(b.bytes[at..][0..piece.len], piece);
+ r.incoming_got += piece.len;
+ if (r.incoming_got < total) return;
+ r.incoming = null;
+ if ((b.path and b.bytes.len < 9) or !std.mem.eql(u8, &tape.Big.hashOf(b.bytes, b.path), &b.hash)) {
+ r.gpa.free(b.bytes);
+ return r.fail("a record by hash came other than its hash");
+ }
+ if (b.path) if (r.cache) |c| if (b.bytes.len - 9 <= c.cap) c.put(r.io, &.{.{ .hash = b.hash, .bytes = b.bytes[9..] }}, &.{});
+ tape.keepFile(&r.t, b);
+ }
+
pub fn digest(r: *Replica) u64 {
const was = Stepping.begin(&r.t, &r.epoch);
defer was.end();
@@ -1697,6 +1733,33 @@ pub const Peer = struct {
peer.cond.signal(io);
}
+ /// A record's bytes by hash (tape.Big) queued for it in pieces, before
+ /// the unit that names them: for a far client, and for one on this
+ /// machine unless they are a file it reads itself (tape.zig `byHash`).
+ /// Never cut off for them: a big file is no lag.
+ fn blob(peer: *Peer, b: tape.Big) void {
+ const io = peer.peers.io;
+ peer.lock.lockUncancelable(io);
+ defer peer.lock.unlock(io);
+ if (peer.cut or peer.closing or (b.path and peer.far == false)) return;
+ var at: usize = 0;
+ while (at < b.bytes.len) : (at += dump_piece) {
+ const piece = b.bytes[at..@min(b.bytes.len, at + dump_piece)];
+ var meta: [49]u8 = undefined;
+ meta[0..32].* = b.hash;
+ std.mem.writeInt(u64, meta[32..40], b.bytes.len, .little);
+ std.mem.writeInt(u64, meta[40..48], at, .little);
+ meta[48] = @intFromBool(b.path);
+ const head = wire.header(@backingInt(wire.ServerTag.blob), meta.len + piece.len);
+ for ([_][]const u8{ &head, &meta, piece }) |part| peer.out.appendSlice(peer.peers.gpa, part) catch {
+ peer.cut = true;
+ _ = libc.shutdown(peer.fd, 2);
+ return;
+ };
+ }
+ peer.cond.signal(io);
+ }
+
fn writeLoop(peer: *Peer) void {
const io = peer.peers.io;
defer peer.done.store(true, .release);
@@ -1912,6 +1975,13 @@ pub const Peers = struct {
const bytes = ps.t.buf.items;
unitHeader(&ps.head, origin, seq);
trace(ps.gpa, "session: unit {d}/{d}, {d} bytes, to {d} clients:\n", .{ origin, seq, bytes.len, ps.count() }, &.{bytes});
+ // Its records by hash first (tape.by_hash_min: a file read), each
+ // whole before the unit that names it.
+ for (ps.t.big.items) |b| {
+ for (ps.list) |slot| if (slot) |peer| peer.blob(b);
+ ps.gpa.free(b.bytes);
+ }
+ ps.t.big.clearRetainingCapacity();
const head = wire.header(@backingInt(wire.ServerTag.unit), unit_head + bytes.len);
for (ps.list) |slot| if (slot) |peer| peer.send(&.{ &head, &ps.head, bytes });
ps.t.buf.clearRetainingCapacity();
@@ -2692,7 +2762,7 @@ pub fn bye(fd: c_int, again: bool) void {
/// What the session streams a client after its dump, as its frontend's loop
/// takes it: a unit's and a terminal message's bytes and a refusal's words
/// on the C heap, the loop's to free.
-pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8 };
+pub const Said = union(enum) { unit: []u8, screen: []u8, checked: u64, refused: []u8, blob: []u8 };
/// 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
@@ -2704,12 +2774,13 @@ pub fn readLink(gpa: Allocator, fd: c_int, rest: *Framer, ctx: anytype, comptime
const msg: Said = switch (t) {
.unit => .{ .unit = std.heap.c_allocator.dupe(u8, payload) catch return false },
.screen => .{ .screen = 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 },
.refused => .{ .refused = std.heap.c_allocator.dupe(u8, (wire.decodeServer(tag, payload) catch return false).refused) catch return false },
.pong, .welcome, .dump, .blobs, .zstd => return true,
};
if (!post(x, msg)) switch (msg) {
- .unit, .screen, .refused => |b| std.heap.c_allocator.free(b),
+ .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
.checked => {},
};
return msg != .refused;
@@ -2766,6 +2837,13 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
return null;
}
r.gmtoff = j.gmtoff;
+ // On the session's machine: a file read sent by hash is read here;
+ // far, it goes to the disk for the next join.
+ r.t.local_files = have == null;
+ if (have) |h| {
+ r.cache = h.cache;
+ r.io = h.io;
+ }
j.ms = (nowNs() - t0) / std.time.ns_per_ms;
return r;
}
@@ -2923,6 +3001,10 @@ pub const Link = struct {
if (c.r.screen(bytes)) |reply| if (!sendScreen(c.fd, reply)) c.cut();
c.dirty = true;
},
+ .blob => |bytes| {
+ defer std.heap.c_allocator.free(bytes);
+ c.r.blobPiece(bytes);
+ },
.checked => |d| c.checked(d),
.refused => |words| {
if (c.refused) |old| std.heap.c_allocator.free(old);
diff --git a/src/tape.zig b/src/tape.zig
index eaae601e..9dca5ee8 100644
--- a/src/tape.zig
+++ b/src/tape.zig
@@ -183,7 +183,27 @@ fn Watched(comptime name: []const u8) type {
return if (@hasField(Pardes.View, name)) @FieldType(Pardes.View, name) else @FieldType(Pardes, name);
}
-const Kind = enum(u8) { input, done, host, ret, set, digest };
+/// `blob`: a record of `by_hash_min` bytes or more, in the replica stream,
+/// as its kind and its bytes' BLAKE3 (`Big`): its bytes go beside the unit.
+const Kind = enum(u8) { input, done, host, ret, set, digest, blob };
+/// A record at least this long crosses to a replica by hash: a unit stays
+/// under the wire's bound (16 MiB) whatever a file read holds.
+pub const by_hash_min = 1 << 20;
+/// A record's bytes by hash: the session's (`Tape.big`), to send; a
+/// replica's (`Tape.files`), to replay. `path`: a file read's answer, which
+/// a replica on the session's machine reads itself, its hash the file's
+/// own bytes' (after the answer's 9: yes, a length), as a dump's text is.
+pub const Big = struct {
+ hash: [32]u8,
+ bytes: []u8,
+ path: bool = false,
+
+ pub fn hashOf(bytes: []const u8, path: bool) [32]u8 {
+ var h: [32]u8 = undefined;
+ std.crypto.hash.Blake3.hash(if (path) bytes[9..] else bytes, &h, .{});
+ return h;
+ }
+};
/// A digest record's kind byte (replica.zig reads a unit's last).
pub const digest_kind: u8 = @backingInt(Kind.digest);
pub const set_kind: u8 = @backingInt(Kind.set);
@@ -275,13 +295,36 @@ pub const Tape = struct {
/// time, so the guess a speculation recorded is what the authority
/// records (a message's millisecond, an edit's second never miss).
stamp: ?Guess = null,
+ /// The replica stream's records by hash (`unit_digests`), until the
+ /// unit is sent (src/replica.zig `Peers.unit`).
+ big: std.ArrayListUnmanaged(Big) = .empty,
+ /// A replica's: the last few records by hash it was sent or read.
+ files: std.ArrayListUnmanaged(Big) = .empty,
+ /// A replica on the session's machine: a file read by hash is read
+ /// here, by its path, and checked.
+ local_files: bool = false,
+ /// The path a `read_file` site reads, while it is recorded or replayed.
+ reading: ?[:0]const u8 = null,
fn record(t: *Tape, kind: Kind, comptime T: type, v: *const T) void {
t.scratch.clearRetainingCapacity();
walk.encode(T, v, &t.scratch.writer) catch @panic("tape: out of memory");
- const payload = t.scratch.written();
+ var payload = t.scratch.written();
+ var kind_ = kind;
+ var by_hash: [34]u8 = undefined;
+ if (t.unit_digests and payload.len >= by_hash_min) {
+ // A file read's yes, by the file's bytes' hash.
+ const path = t.reading != null and kind == .ret and payload[0] == 1;
+ by_hash[0] = @backingInt(kind);
+ by_hash[1..33].* = Big.hashOf(payload, path);
+ by_hash[33] = @intFromBool(path);
+ const bytes = t.gpa.dupe(u8, payload) catch @panic("tape: out of memory");
+ t.big.append(t.gpa, .{ .hash = by_hash[1..33].*, .bytes = bytes, .path = path }) catch @panic("tape: out of memory");
+ payload = &by_hash;
+ kind_ = .blob;
+ }
const len: u32 = @intCast(payload.len);
- t.buf.append(t.gpa, @backingInt(kind)) catch @panic("tape: out of memory");
+ t.buf.append(t.gpa, @backingInt(kind_)) catch @panic("tape: out of memory");
t.buf.appendSlice(t.gpa, std.mem.asBytes(&len)) catch @panic("tape: out of memory");
t.buf.appendSlice(t.gpa, payload) catch @panic("tape: out of memory");
if (t.buf.items.len > 1 << 20) t.flush();
@@ -386,12 +429,45 @@ pub const Tape = struct {
const head = t.in.take(5) catch return null;
const len = std.mem.bytesToValue(u32, head[1..5]);
const payload = t.in.take(len) catch return null;
- return .{ .kind = @fromBackingInt(@intCast(head[0])), .payload = .{ .bytes = payload } };
+ const kind: Kind = @fromBackingInt(@intCast(head[0]));
+ if (kind != .blob) return .{ .kind = kind, .payload = .{ .bytes = payload } };
+ if (payload.len != 34) {
+ t.diverge("a record by hash is short", .{});
+ return null;
+ }
+ const bytes = t.byHash(payload[1..33], payload[33] != 0) orelse {
+ t.diverge("a record by hash {x} is not here", .{payload[1..9]});
+ return null;
+ };
+ return .{ .kind = @fromBackingInt(@intCast(payload[0])), .payload = .{ .bytes = bytes } };
}
fn peek(t: *const Tape) ?Kind {
if (t.in.bytes.len - t.in.at < 5) return null;
- return @fromBackingInt(@intCast(t.in.bytes[t.in.at]));
+ const kind: Kind = @fromBackingInt(@intCast(t.in.bytes[t.in.at]));
+ if (kind == .blob and t.in.bytes.len - t.in.at > 5) return @fromBackingInt(@intCast(t.in.bytes[t.in.at + 5]));
+ return kind;
+ }
+
+ /// The bytes of a record by hash: sent, or read here (a file read's
+ /// answer, on the session's machine), each checked against its hash.
+ fn byHash(t: *Tape, hash: *const [32]u8, is_path: bool) ?[]const u8 {
+ for (t.files.items) |f| if (std.mem.eql(u8, &f.hash, hash)) return f.bytes;
+ const path = t.reading orelse return null;
+ if (!t.local_files or !is_path) return null;
+ const file = pardes.filesystem.readHost(t.gpa, path, pardes.memory.limits.max_file_bytes) catch return null;
+ defer t.gpa.free(file);
+ // The answer as `record` wrote it: an error union's yes, a length, the bytes.
+ const bytes = t.gpa.alloc(u8, 9 + file.len) catch return null;
+ bytes[0] = 1;
+ std.mem.writeInt(u64, bytes[1..9], file.len, .little);
+ @memcpy(bytes[9..], file);
+ if (!std.mem.eql(u8, &Big.hashOf(bytes, true), hash)) {
+ t.gpa.free(bytes);
+ return null;
+ }
+ keepFile(t, .{ .hash = hash.*, .bytes = bytes, .path = true });
+ return bytes;
}
fn diverge(t: *Tape, comptime why: []const u8, args: anytype) void {
@@ -412,7 +488,7 @@ pub const Tape = struct {
.set => t.applySet(&rec.payload),
.host => t.skipHost(),
.digest => t.check(rec.payload.bytes),
- .done => return t.diverge("a host call's records are out of order", .{}),
+ .done, .blob => return t.diverge("a host call's records are out of order", .{}),
}
}
}
@@ -444,7 +520,7 @@ pub const Tape = struct {
.host => if (t.skips_render) t.skipHost() else return t.diverge("the core did not make the host call {d} the tape has", .{std.mem.bytesToValue(u16, rec.payload.bytes[0..2])}),
.input => t.apply(&rec.payload),
.digest => t.check(rec.payload.bytes),
- .ret => return t.diverge("the core's input ended before the recorded one", .{}),
+ .ret, .blob => return t.diverge("the core's input ended before the recorded one", .{}),
}
}
}
@@ -465,7 +541,7 @@ pub const Tape = struct {
.input => t.apply(&rec.payload),
.set => t.applySet(&rec.payload),
.digest => t.check(rec.payload.bytes),
- .host, .done => {
+ .host, .done, .blob => {
t.diverge("a host call's records are out of order", .{});
return false;
},
@@ -917,6 +993,10 @@ fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anyt
// No tape where there is no host to record or replay one.
const t = on orelse return if (yields) out(f, args) else @call(.auto, f, args);
const id: u16 = @as(u16, host_fns.len) + @backingInt(s);
+ if (comptime s == .read_file) t.reading = args[1];
+ defer if (comptime s == .read_file) {
+ t.reading = null;
+ };
if (t.replay) {
// Diverged (said in `diverged`): what a speculation gets, harmless,
// for the rest of the input. A replica joins again; a replay says so.
@@ -955,6 +1035,13 @@ fn call(comptime s: Site, a: ?std.mem.Allocator, comptime f: anytype, args: anyt
pub const Guess = struct { real_ns: i64, mono_ns: i64, gmtoff: i32 };
+/// A record's bytes by hash kept for a replica's replays (`files`, the
+/// tape's allocator's): the last eight, a rollback's units' and the next's.
+pub fn keepFile(t: *Tape, b: Big) void {
+ if (t.files.items.len == 8) t.gpa.free(t.files.orderedRemove(0).bytes);
+ t.files.append(t.gpa, b) catch t.gpa.free(b.bytes);
+}
+
/// A clock read of the session's, as a replica client guesses it: a file's
/// mtime (realtime seconds), a message's clock (monotonic ms), a message's
/// time of day (in the session's zone).
@@ -1129,6 +1216,10 @@ pub fn memory(gpa: std.mem.Allocator) Tape {
/// What a tape in memory holds, given back (its core is gone already).
pub fn release(t: *Tape) void {
+ for (t.big.items) |b| t.gpa.free(b.bytes);
+ t.big.deinit(t.gpa);
+ for (t.files.items) |b| t.gpa.free(b.bytes);
+ t.files.deinit(t.gpa);
t.answers.deinit(t.gpa);
t.buf.deinit(t.gpa);
t.scratch.deinit();
@@ -1154,7 +1245,7 @@ pub fn replayUnit(t: *Tape, bytes: []const u8) ?[]const u8 {
},
.set => t.applySet(&rec.payload),
.digest => t.check(rec.payload.bytes),
- .host, .ret, .done => t.diverge("a {t} record at the top", .{kind}),
+ .host, .ret, .done, .blob => t.diverge("a {t} record at the top", .{kind}),
}
}
return t.diverged;
@@ -1210,7 +1301,16 @@ pub fn describe(bytes: []const u8, w: *std.Io.Writer) void {
while (true) {
const head = r.take(5) catch return;
const payload = r.take(std.mem.bytesToValue(u32, head[1..5])) catch return;
- const kind: Kind = @fromBackingInt(@intCast(head[0]));
+ const raw: Kind = @fromBackingInt(@intCast(head[0]));
+ // A record by hash, as the kind it stands for (its bytes are not here).
+ const kind: Kind = if (raw == .blob and payload.len > 0) @fromBackingInt(@intCast(payload[0])) else raw;
+ if (raw == .blob) {
+ w.splatByteAll(' ', depth * 2) catch {};
+ w.print("{t} by hash\n", .{kind}) catch {};
+ if (kind == .done or kind == .ret) depth -|= 1;
+ if (kind == .input or kind == .host) depth += 1;
+ continue;
+ }
if (kind == .done or kind == .ret) depth -|= 1;
w.splatByteAll(' ', depth * 2) catch {};
switch (kind) {
diff --git a/src/tui/tui.zig b/src/tui/tui.zig
index 349ced56..919eeded 100644
--- a/src/tui/tui.zig
+++ b/src/tui/tui.zig
@@ -805,7 +805,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8,
const ended = reader_done.load(.acquire);
while (loop.tryEvent() catch null) |ev| switch (ev) {
.said => |said| switch (said) {
- .unit, .screen, .refused => |b| std.heap.c_allocator.free(b),
+ .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
.checked => {},
},
.paste => |b| gpa.free(@constCast(b)),
@@ -1732,7 +1732,7 @@ const Shell = struct {
c.link.take(said);
if (said == .refused) return true;
} else switch (said) {
- .unit, .screen, .refused => |b| std.heap.c_allocator.free(b),
+ .unit, .screen, .refused, .blob => |b| std.heap.c_allocator.free(b),
.checked => {},
},
.link_gone => if (s.client) |c| {
diff --git a/src/wire.zig b/src/wire.zig
index 9773d222..864c2fd8 100644
--- a/src/wire.zig
+++ b/src/wire.zig
@@ -183,6 +183,10 @@ pub const ServerTag = enum(u8) {
/// A piece of a far client's stream from here on, zstd-compressed: the
/// messages in it are framed as these are. Opaque here.
zstd = 0x09,
+ /// A piece of a record's bytes by hash (tape.zig `Big`), before the
+ /// unit naming it: the hash, the whole's length and this piece's place
+ /// (u64le each), then at most 1 MiB of it (src/replica.zig).
+ blob = 0x0a,
};
pub const ServerMsg = union(ServerTag) {
@@ -199,6 +203,7 @@ pub const ServerMsg = union(ServerTag) {
check: u64,
blobs: []const u8,
zstd: []const u8,
+ blob: []const u8,
};
/// A message's header, for a payload sent on its own (a unit, a dump's
@@ -233,6 +238,7 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg {
.check => .{ .check = try r.takeInt(u64, .little) },
.blobs => return .{ .blobs = payload },
.zstd => return .{ .zstd = payload },
+ .blob => return .{ .blob = payload },
};
try end(&r);
return msg;
@@ -255,7 +261,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 {
},
.refused => |words| try putSlice16(&w, words),
.pong => |v| try w.writeInt(u64, v, .little),
- .dump, .unit, .screen, .blobs, .zstd => |bytes| try w.writeAll(bytes),
+ .dump, .unit, .screen, .blobs, .zstd, .blob => |bytes| try w.writeAll(bytes),
.check => |v| try w.writeInt(u64, v, .little),
}
try finishMessage(&w, at);