diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 22:03:14 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 22:23:51 -0300 |
| commit | 99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (patch) | |
| tree | 813596ea84318a7bae4fd7416ba463de8e3b7107 /core/Db.zig | |
| parent | 92d553123673376adf6126ab90d49a22c5b833d2 (diff) | |
| download | pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.tar.gz pardes-99f5b10eccd95aa0066ea6fe6bb75f367ab56a47.zip | |
core: src/ becomes core/, pardes.zig its root.zig (the reorganisation's tree, step 2d), and every mention of a src/ path follows: the build's paths, the core's imports of its root, the tests that read the repository's files by path (lspbench's, look.zig's spans over core/look.zig), the comments that cite files, the documents and the manual (the typst corpus reads core/tutor.txt and core/plumbing); left as they were: the /src tree's served names (src/pardes.zig and the rest are the 9P tree's, not the repository's), the CHANGELOG's history, fixtures that are only strings; fs-unit-test runs from the core's root (a module of the core rooted at fs.zig had the runtime's and the devices' `core` be fs.zig); nothing else changes: the ledger (pardes.test.* now root.test.*), frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/Db.zig')
| -rw-r--r-- | core/Db.zig | 1432 |
1 files changed, 1432 insertions, 0 deletions
diff --git a/core/Db.zig b/core/Db.zig new file mode 100644 index 00000000..e8d606ec --- /dev/null +++ b/core/Db.zig @@ -0,0 +1,1432 @@ +//! What pardes keeps on disk, through xitdb (docs/next-store.md): the +//! user's state file, `pardes.xitdb` in the DumpDir ($XDG_DATA_HOME/pardes, +//! else ~/.local/share/pardes), which every session of the user's shares. +//! Its root is a map: +//! +//! recent Recent's list (recent.zig), a line a file, the newest first +//! +//! A session reads Recent at its start, and again on use (Recent, /recent) +//! when the file's committed size says another session committed since. A +//! step that changed it writes it at its end in one transaction under the +//! file's lock, what another session committed since read and merged under +//! this session's changes first (`recent.List.merge`). Held by another +//! session, the lock is tried again at the next step: a frame never waits +//! for one. Recent's commits are not fsynced, as its file never was: a crash +//! keeps every one committed, a power loss may tear the last (its root +//! header on disk, its bytes not), and the file is then opened at the commit +//! before it (`mend`): the dumps outlive it. +//! +//! A file there that is no database of pardes's (another program's, one +//! with no commit left whole) is kept beside it as `pardes.xitdb.broken` and +//! a new one started: pardes always starts. The test host's is a `.memory` database, +//! the same code (`Kind.memory`). +const Db = @This(); + +const std = @import("std"); +const xitdb = @import("xitdb"); +const pardes = @import("root.zig"); +const recent = @import("recent.zig"); +const Pardes = pardes.Pardes; + +pub const Disk = xitdb.Database(.buffered_file, u256); +pub const Memory = xitdb.Database(.memory, u256); + +/// Where a session keeps what outlives it: nowhere (a unit test, a replica, +/// a replay), its user's state file, or memory (the test host's). +pub const Kind = enum { off, disk, memory }; + +pub const file_name = "pardes.xitdb"; +/// The hash every key of these databases is: a field's or a label's name +/// hashed, a blob keyed by its content's. +const hash_id = xitdb.HashId.fromBytes("blk3"); +/// Recent's lines are read this far at most (200 of the longest paths). +const recent_max = 1 << 20; + +kind: Kind = .off, +open: ?*Open = null, +/// The state file's committed size when this session last read or wrote +/// Recent: another session's commit moves it. +seen: u64 = 0, +/// Recent was read (or there was none): only then is it written, so a +/// session never writes over a list it did not read. +loaded: bool = false, + +/// The open database. Its own allocation: a database points at its buffer, +/// and a Restore's new core takes it over from the old one. +pub const Open = struct { + gpa: std.mem.Allocator, + buffer: std.Io.Writer.Allocating, + where: union(enum) { + disk: struct { db: Disk, file: std.Io.File, path: []u8 }, + memory: struct { db: Memory }, + }, +}; + +fn ioOf() std.Io { + return std.Io.Threaded.global_single_threaded.io(); +} + +/// A name's key: its BLAKE3 hash. +pub fn key(name: []const u8) u256 { + var out: [32]u8 = undefined; + std.crypto.hash.Blake3.hash(name, &out, .{}); + return std.mem.readInt(u256, &out, .big); +} + +pub fn deinit(db: *Db) void { + const o = db.open orelse return; + db.open = null; + switch (o.where) { + .disk => |*d| { + d.file.close(ioOf()); + o.gpa.free(d.path); + }, + .memory => {}, + } + o.buffer.deinit(); + o.gpa.destroy(o); +} + +/// The state file's path for the DumpDir setting `dir_setting`, made in +/// `buf`; null with no home to keep it in. +pub fn statePath(buf: []u8, dir_setting: []const u8) ?[]const u8 { + var dir_buf: [4096]u8 = undefined; + const dir = pardes.dump.directory(&dir_buf, dir_setting) orelse return null; + return std.fmt.bufPrint(buf, "{s}/" ++ file_name, .{dir}) catch null; +} + +/// The state file at `path`, its directory made: a new one is written under +/// the file's lock (two sessions starting at once write one header), one a +/// power loss tore is opened at its last whole commit (`mend`), and a file +/// that is no database of pardes's is put aside for a new one. +fn openDisk(gpa: std.mem.Allocator, path: []const u8) !*Open { + pardes.turn.yield(); + defer pardes.turn.back(); + const io = ioOf(); + const cwd = std.Io.Dir.cwd(); + if (std.Io.Dir.path.dirname(path)) |dir| try cwd.createDirPath(io, dir); + const o = try gpa.create(Open); + errdefer gpa.destroy(o); + o.* = .{ .gpa = gpa, .buffer = .init(gpa), .where = undefined }; + errdefer o.buffer.deinit(); + const own = try gpa.dupe(u8, path); + errdefer gpa.free(own); + var tried_aside = false; + while (true) { + const file = try cwd.createFile(io, path, .{ .read = true, .truncate = false }); + const fresh = (file.length(io) catch 0) == 0; + // Another session making it now: it has its header in a moment. + if (fresh and !(file.tryLock(io, .exclusive) catch false)) { + file.close(io); + return error.WouldBlock; + } + const made = Disk.init(io, .{ .file = file, .buffer = &o.buffer, .fsync = false, .hash_id = hash_id }); + if (fresh) file.unlock(io); + if (made) |d| { + o.where = .{ .disk = .{ .db = d, .file = file, .path = own } }; + return o; + } else |err| { + switch (err) { + error.InvalidDatabase, error.InvalidVersion, error.InvalidHashSize, error.TruncatedDatabase, error.InvalidEnumTag, error.EndOfStream => {}, + else => { + file.close(io); + return err; + }, + } + if (!fresh) if (mend(io, file, &o.buffer)) |d| { + o.where = .{ .disk = .{ .db = d, .file = file, .path = own } }; + return o; + }; + file.close(io); + if (tried_aside) return err; + tried_aside = true; + var aside_buf: [4300]u8 = undefined; + try cwd.rename(path, cwd, try std.fmt.bufPrint(&aside_buf, "{s}.broken", .{path}), io); + } + } +} + +// xitdb's layout, which a mend reads (zig-pkg's xitdb src/lib.zig): the +// database header (its file id the last 8 of its 20 bytes, big endian), +// the root header (the root slot's 9 bytes, then the committed size's 8), +// and the trailer ending every commit (the root slot's 9 bytes, the commit +// id's 8, and their CRC-64/XZ's 8, with the file id and its own position). +const db_header_len = 20; +const root_header_end = db_header_len + 17; +const trailer_len = 25; +const hash_map_tag = 4; + +/// A file xitdb refused, a power loss having torn its last commit (its +/// root header written, the commit's bytes not all): opened at the last +/// commit before it whose trailer verifies and whose maps read whole, +/// scanned back from the file's end, its root header put back at it (what +/// came after, a Recent's change or two, is lost; the dumps before it are +/// not). Null, the file as it was, when none does: it is no database of +/// pardes's, or none of its commits outlived the tear. +fn mend(io: std.Io, file: std.Io.File, buffer: *std.Io.Writer.Allocating) ?Disk { + file.lock(io, .exclusive) catch return null; + defer file.unlock(io); + // Another session mended it first. + if (Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false, .hash_id = hash_id })) |d| return d else |_| {} + var head: [root_header_end]u8 = undefined; + if ((file.readPositionalAll(io, &head, 0) catch return null) != head.len or !std.mem.eql(u8, head[0..3], "xit")) return null; + const file_id = std.mem.readInt(u64, head[db_header_len - 8 .. db_header_len], .big); + var chunk: [64 << 10]u8 = undefined; + var end = file.length(io) catch return null; + while (end >= root_header_end + trailer_len) { + const start = @max(root_header_end, end - @min(end, chunk.len)); + const got = file.readPositionalAll(io, chunk[0 .. end - start], start) catch return null; + if (got != end - start) return null; + var i = got; + while (i >= trailer_len) : (i -= 1) { + const t = chunk[i - trailer_len ..][0..trailer_len]; + const at = start + i - trailer_len; + // A pardes root is a map, at a slot written before its trailer. + if (t[0] & 0x7f != hash_map_tag or std.mem.readInt(u64, t[1..9], .big) >= at) continue; + var sum: [33]u8 = undefined; + std.mem.writeInt(u64, sum[0..8], file_id, .big); + std.mem.writeInt(u64, sum[8..16], at, .big); + @memcpy(sum[16..33], t[0..17]); + if (std.hash.crc.@"CRC-64/XZ".hash(&sum) != std.mem.readInt(u64, t[17..25], .big)) continue; + var root: [17]u8 = undefined; + @memcpy(root[0..9], t[0..9]); + std.mem.writeInt(u64, root[9..17], at + trailer_len, .big); + file.writePositionalAll(io, &root, db_header_len) catch return null; + var d = Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false, .hash_id = hash_id }) catch continue; + _ = liveSize(&d) catch continue; + file.sync(io) catch {}; + return d; + } + if (start == root_header_end) break; + end = start + trailer_len - 1; + } + file.writePositionalAll(io, head[db_header_len..], db_header_len) catch {}; + return null; +} + +/// Whether the file at the open one's path is another now (a compaction's). +fn replaced(o: *Open) bool { + const d = o.where.disk; + pardes.turn.yield(); + defer pardes.turn.back(); + const io = ioOf(); + const open_st = d.file.stat(io) catch return false; + const path_st = std.Io.Dir.cwd().statFile(io, d.path, .{}) catch return false; + return open_st.inode != path_st.inode; +} + +fn committed(o: *Open) !u64 { + pardes.turn.yield(); + defer pardes.turn.back(); + return switch (o.where) { + inline else => |*w| w.db.committedSize(), + }; +} + +/// The file's lock, taken (`wait`: waited for): false when another session +/// holds it. A database in memory is this process's alone. +fn lock(o: *Open, wait: bool) bool { + const file = switch (o.where) { + .disk => |d| d.file, + .memory => return true, + }; + pardes.turn.yield(); + defer pardes.turn.back(); + if (wait) { + file.lock(ioOf(), .exclusive) catch return false; + return true; + } + return file.tryLock(ioOf(), .exclusive) catch false; +} + +/// The database, its file locked for a transaction (`wait`: waited for). A +/// file a compaction replaced while this waited is let go, and the new one +/// opened and locked. +fn locked(db: *Db, p: *Pardes, wait: bool) error{ NoStateFile, Busy }!*Open { + for (0..2) |_| { + const o = db.opened(p) orelse return error.NoStateFile; + if (!lock(o, wait)) return error.Busy; + if (o.where == .memory or !replaced(o)) return o; + unlock(o); + db.deinit(); + db.seen = 0; + } + return error.Busy; +} + +fn unlock(o: *Open) void { + switch (o.where) { + .disk => |d| d.file.unlock(ioOf()), + .memory => {}, + } +} + +// ---- Recent ---- + +/// Recent's lines, `gpa`'s; null when the database holds none. +fn recentText(o: *Open, gpa: std.mem.Allocator) !?[]const u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + switch (o.where) { + inline else => |*w| { + const DB = @TypeOf(w.db); + const root = try DB.HashMap(.read_only).init(w.db.rootCursor().readOnly()); + const c = (try root.getCursor(key("recent"))) orelse return null; + return try c.readBytesAlloc(gpa, recent_max); + }, + } +} + +fn putRecent(o: *Open, text: []const u8) !void { + pardes.turn.yield(); + defer pardes.turn.back(); + switch (o.where) { + inline else => |*w| { + const DB = @TypeOf(w.db); + try w.db.runContext(struct { + text: []const u8, + pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { + const root = try DB.HashMap(.read_write).init(cursor.*); + try root.put(key("recent"), .{ .bytes = ctx.text }); + } + }{ .text = text }); + }, + } +} + +/// What other sessions committed to Recent since this one last read or +/// wrote it, read under this session's changes: at the start, and on use. +pub fn readRecent(db: *Db, p: *Pardes) void { + const o = db.opened(p) orelse return; + const first = !db.loaded; + db.loaded = true; + const held = db.mergeRecent(p, o); + // A state file that holds no Recent yet: the files before it, once. + if (first and held != null and !held.?) if (p.opts.recent_import) |dir| importRecent(p, dir); +} + +/// Whether the database holds Recent; null when nothing was read (nothing +/// committed since the last read, or it could not be). +fn mergeRecent(db: *Db, p: *Pardes, o: *Open) ?bool { + const size = committed(o) catch return null; + if (size == db.seen) return null; + const gpa = p.recentGpa(); + const text = recentText(o, gpa) catch return null; + defer if (text) |t| gpa.free(t); + p.recent.merge(gpa, text orelse ""); + db.seen = size; + return text != null; +} + +/// Recent as the files before the state file kept it, in `dir`: 0.24's +/// `recent` (200 lines, the newest first), else the `store` before it (a +/// log whose `@r` records are such lines, the oldest first). Both are left +/// where they are. ponytail: for a release or two, while those files are +/// about. +fn importRecent(p: *Pardes, dir: []const u8) void { + const gpa = p.recentGpa(); + const io = ioOf(); + var path_buf: [4200]u8 = undefined; + if (dir.len + "/recent".len >= std.Io.Dir.max_path_bytes) { + var said: [160]u8 = undefined; + return p.setMessage(p.view().active, std.fmt.bufPrint(&said, "Recent: the files before the state file were not read: their directory's path is {d} bytes, too long", .{dir.len}) catch unreachable); // a number fits 160 + } + pardes.turn.yield(); + const listed = std.Io.Dir.cwd().readFileAlloc(io, std.fmt.bufPrint(&path_buf, "{s}/recent", .{dir}) catch "", gpa, .limited(recent_max)) catch null; + const logged = if (listed == null) std.Io.Dir.cwd().readFileAlloc(io, std.fmt.bufPrint(&path_buf, "{s}/store", .{dir}) catch "", gpa, .limited(128 << 20)) catch null else null; + pardes.turn.back(); + if (listed) |text| { + defer gpa.free(text); + p.recent.merge(gpa, text); + // Written to the state file at the next step: read once. + for (p.recent.entries.items) |*e| e.changed = true; + p.recent.dirty = p.recent.entries.items.len > 0; + } else if (logged) |text| { + defer gpa.free(text); + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + const e = recent.List.parseLine(line) orelse continue; + const open = if (p.recent.get(e.path)) |here| here.open else false; + p.recent.opened(gpa, e.path); + p.recent.closed(gpa, e.path, e.nums[0], e.nums[1], e.nums[2], e.nums[3]); + // Open here, it stays open: the cap never drops it. + if (open) p.recent.opened(gpa, e.path); + } + } +} + +/// Recent written when it changed, at the end of a step and at the end +/// (`wait`: the lock is waited for there, never in a step). +pub fn writeRecent(db: *Db, p: *Pardes, wait: bool) void { + if (!p.recent.dirty) return; + if (db.kind != .off) written: { + if (!db.loaded) return; + const o = db.locked(p, wait) catch |err| switch (err) { + // Another session's lock: the next step tries again. + error.Busy => return, + error.NoStateFile => break :written, + }; + defer unlock(o); + _ = db.mergeRecent(p, o); + p.recent.changedFirst(); + const gpa = p.recentGpa(); + var text: std.Io.Writer.Allocating = .init(gpa); + defer text.deinit(); + const entries = p.recent.entries.items; + for (entries[0..@min(entries.len, recent.cap)]) |e| recent.List.writeEntry(e, &text.writer) catch break :written; + // The disk refused it: kept for no one, as before. + putRecent(o, text.written()) catch break :written; + db.seen = committed(o) catch 0; + } + for (p.recent.entries.items) |*e| e.changed = false; + p.recent.dirty = false; +} + +// ---- the dumps ---- +// +// Each Dump is a labelled entry of the state file's `dumps`, written in one +// transaction, fsynced (a dump is worth the wait; Recent's commits are not): +// a full disk or a kill in the middle leaves the dump before it whole, as +// xitdb writes its header last. +// +// dumps/<label> seq, date (seconds, UTC), panes, size, the session (a +// database of its own: walk.Put's maps, its bytes one +// value) and the hashes of the texts it keeps beside it +// blobs/<hash> each such text once, by its BLAKE3 hash: an unchanged +// text is written once, however many dumps keep it +// last the newest dump's label +// seq the next dump's number +// +// A Dump is labelled `pardes-<date>-<time>` (UTC; `-2` and on for another +// in the same second), an Upgrade's `upgrade-<pid>`. The newest `kept` are +// kept: one more drops the oldest, and the texts no kept dump names, in +// the same transaction. A dump travels as an image, a database in memory +// holding it alone in the same shape (`image`): what a Dump hands its host, +// what a Restore of a label is read into (`imageOf`), what `Dump export` +// and a handover write as a file, and what `-l` and `Restore <path>` read. + +/// How many dumps the state file keeps, the newest. +pub const kept = 32; +/// The text of a dump's blob is its BLAKE3 hash's key. +fn blobKey(hash: *const [32]u8) u256 { + return std.mem.readInt(u256, hash, .big); +} + +const session_tag = "db".*; + +/// A dump's image: the one dump `label` (its session's bytes, the texts it +/// keeps beside it and its pane count) in a database in memory, `last` +/// naming it, `gpa`'s. Of the same session, the same bytes: its ids are +/// std.Io.failing's zeros, never random ones. +pub fn image(gpa: std.mem.Allocator, label: []const u8, session: []const u8, blobs: []const pardes.walk.Blob, panes: u64, names: []const u8) ![]u8 { + var buf: std.Io.Writer.Allocating = .init(gpa); + errdefer buf.deinit(); + var db = try Memory.init(std.Io.failing, .{ .buffer = &buf, .hash_id = hash_id, .file_id = 0 }); + try db.runContext(struct { + label: []const u8, + session: []const u8, + blobs: []const pardes.walk.Blob, + panes: u64, + names: []const u8, + pub fn run(ctx: @This(), cursor: *Memory.Cursor(.read_write)) !void { + const root = try Memory.HashMap(.read_write).init(cursor.*); + try root.put(key("last"), .{ .bytes = ctx.label }); + const dumps = try Memory.HashMap(.read_write).init(try root.putCursor(key("dumps"))); + try dumps.putKey(key(ctx.label), .{ .bytes = ctx.label }); + const entry = try Memory.HashMap(.read_write).init(try dumps.putCursor(key(ctx.label))); + try entry.put(key("session"), .{ .bytes_object = .{ .value = ctx.session, .format_tag = session_tag } }); + try entry.put(key("panes"), .{ .uint = ctx.panes }); + try entry.put(key("names"), .{ .bytes = ctx.names }); + const hashes = try Memory.ArrayList(.read_write).init(try entry.putCursor(key("blobs"))); + const texts = try Memory.HashMap(.read_write).init(try root.putCursor(key("blobs"))); + for (ctx.blobs) |*b| { + try hashes.append(.{ .bytes = &b.hash }); + try texts.put(blobKey(&b.hash), .{ .bytes = b.bytes }); + } + } + }{ .label = label, .session = session, .blobs = blobs, .panes = panes, .names = names }); + return buf.toOwnedSlice(); +} + +/// Whether `bytes` are a database of xitdb's (an image, a state file): +/// what `-l` and `Restore <path>` tell from an old dump by. +pub fn isImage(bytes: []const u8) bool { + return std.mem.startsWith(u8, bytes, "xit"); +} + +/// A dump's image opened for a load: the session's database, and the +/// texts its blobs are. The image's bytes are the caller's while it is open. +pub const Read = struct { + gpa: std.mem.Allocator, + image_buf: std.Io.Writer.Allocating, + image: Memory, + session_buf: std.Io.Writer.Allocating, + session: Memory, + label: []u8, + panes: u64, + /// What its panes show, a word each (dump.image); "" in an old image. + names: []u8, + + /// The image `bytes` at its dump `label`, else its last one. + pub fn open(gpa: std.mem.Allocator, bytes: []const u8, label: ?[]const u8) !*Read { + if (!isImage(bytes)) return error.NotADump; + const r = try gpa.create(Read); + errdefer gpa.destroy(r); + // Read, never written: the bytes are borrowed, never freed here. + var borrowed: std.ArrayList(u8) = .fromOwnedSlice(@constCast(bytes)); + r.* = .{ .gpa = gpa, .image_buf = .fromArrayList(gpa, &borrowed), .image = undefined, .session_buf = undefined, .session = undefined, .label = &.{}, .panes = 0, .names = &.{} }; + r.image = Memory.init(std.Io.failing, .{ .buffer = &r.image_buf }) catch return error.NotADump; + const top = Memory.HashMap(.read_only).init(r.image.rootCursor().readOnly()) catch return error.NotADump; + r.label = if (label) |l| try gpa.dupe(u8, l) else last: { + const c = (top.getCursor(key("last")) catch return error.NotADump) orelse return error.NoDump; + break :last @constCast(c.readBytesAlloc(gpa, 4096) catch return error.NotADump); + }; + errdefer gpa.free(r.label); + const entry = try entryOf(Memory, top, r.label) orelse return error.NoDump; + r.panes = if (entry.getCursor(key("panes")) catch null) |c| c.readUint() catch 0 else 0; + r.names = if (entry.getCursor(key("names")) catch null) |c| @constCast(c.readBytesAlloc(gpa, 4096) catch &.{}) else &.{}; + errdefer if (r.names.len > 0) gpa.free(r.names); + const at = (entry.getCursor(key("session")) catch return error.NotADump) orelse return error.NotADump; + const session: []u8 = @constCast(at.readBytesAlloc(gpa, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.NotADump); + var owned: std.ArrayList(u8) = .fromOwnedSlice(session); + r.session_buf = .fromArrayList(gpa, &owned); + errdefer r.session_buf.deinit(); + r.session = Memory.init(std.Io.failing, .{ .buffer = &r.session_buf }) catch return error.NotADump; + return r; + } + + pub fn close(r: *Read) void { + r.session_buf.deinit(); + if (r.names.len > 0) r.gpa.free(r.names); + r.gpa.free(r.label); + r.gpa.destroy(r); + } + + /// The session's roots. + pub fn root(r: *Read) Memory.Cursor(.read_only) { + return r.session.rootCursor().readOnly(); + } + + /// The texts the session's blobs are, by hash. + pub fn blobs(r: *Read) !Memory.HashMap(.read_only) { + const root_map = try Memory.HashMap(.read_only).init(r.image.rootCursor().readOnly()); + return Memory.HashMap(.read_only).init((try root_map.getCursor(key("blobs"))) orelse return error.NotADump); + } +}; + +/// The entry of dump `label` in the root map `root`; null when there is none. +fn entryOf(comptime DB: type, root: DB.HashMap(.read_only), label: []const u8) !?DB.HashMap(.read_only) { + const dumps = (try root.getCursor(key("dumps"))) orelse return null; + const at = (try (try DB.HashMap(.read_only).init(dumps)).getCursor(key(label))) orelse return null; + return try DB.HashMap(.read_only).init(at); +} + +/// The dump `label` of `o` as an image, `gpa`'s; null when it keeps none +/// of that label. +fn imageOf(o: *Open, gpa: std.mem.Allocator, label: []const u8) !?[]u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + switch (o.where) { + inline else => |*w| { + const DB = @TypeOf(w.db); + const root = try DB.HashMap(.read_only).init(w.db.rootCursor().readOnly()); + const entry = (try entryOf(DB, root, label)) orelse return null; + const session = try (try entry.getCursor(key("session")) orelse return error.NotADump).readBytesAlloc(gpa, null); + defer gpa.free(session); + const panes = if (try entry.getCursor(key("panes"))) |c| try c.readUint() else 0; + var blobs: std.ArrayList(pardes.walk.Blob) = .empty; + defer { + for (blobs.items) |b| gpa.free(b.bytes); + blobs.deinit(gpa); + } + const texts = try DB.HashMap(.read_only).init((try root.getCursor(key("blobs"))) orelse return error.NotADump); + if (try entry.getCursor(key("blobs"))) |list_at| { + var it = try (try DB.ArrayList(.read_only).init(list_at)).iterator(); + while (try it.next()) |h| { + var hash: [32]u8 = undefined; + if ((try h.readBytes(&hash)).len != 32) return error.NotADump; + const text = try (try texts.getCursor(blobKey(&hash)) orelse return error.NotADump).readBytesAlloc(gpa, null); + errdefer gpa.free(text); + try blobs.append(gpa, .{ .hash = hash, .bytes = text }); + } + } + return try image(gpa, label, session, blobs.items, panes, ""); + }, + } +} + +/// The dump `label` (bare: the newest) of this session's state file, as +/// an image, `gpa`'s; null when it keeps none of that label. +pub fn getDump(db: *Db, p: *Pardes, gpa: std.mem.Allocator, label: ?[]const u8) !?[]u8 { + const o = db.opened(p) orelse return error.NoStateFile; + var last_buf: [4096]u8 = undefined; + const name = label orelse (try lastLabel(o, &last_buf)) orelse return null; + return imageOf(o, gpa, name); +} + +/// The dump `label` of the state file at `path` as an image, `gpa`'s: an +/// upgraded process's (its record names both), read before it has a core. +pub fn readDumpAt(gpa: std.mem.Allocator, path: []const u8, label: []const u8) ![]u8 { + var db: Db = .{ .kind = .disk, .open = try openDisk(gpa, path) }; + defer db.deinit(); + return (try imageOf(db.open.?, gpa, label)) orelse error.NoDump; +} + +/// The newest dump's label, in `buf`; null when there is none. +fn lastLabel(o: *Open, buf: []u8) !?[]const u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + switch (o.where) { + inline else => |*w| { + const DB = @TypeOf(w.db); + const root = try DB.HashMap(.read_only).init(w.db.rootCursor().readOnly()); + const c = (try root.getCursor(key("last"))) orelse return null; + return try c.readBytes(buf); + }, + } +} + +/// The label of the state file's dump `label` (bare: its newest), in `buf`; +/// null when it keeps none of that label. A step asks it of the authority +/// (tape.authority): a replica keeps no state file. +pub fn labelled(db: *Db, p: *Pardes, label: ?[]const u8, buf: []u8) ?[]const u8 { + const o = db.opened(p) orelse return null; + const name = if (label) |l| (std.fmt.bufPrint(buf, "{s}", .{l}) catch return null) else ((lastLabel(o, buf) catch return null) orelse return null); + pardes.turn.yield(); + defer pardes.turn.back(); + switch (o.where) { + inline else => |*w| { + const DB = @TypeOf(w.db); + const root = DB.HashMap(.read_only).init(w.db.rootCursor().readOnly()) catch return null; + return if ((entryOf(DB, root, name) catch return null) != null) name else null; + }, + } +} + +/// The dump in the image `bytes` put in this session's state file under a +/// label of its own (`label`, else with `-2` and on), in one fsynced +/// transaction that also drops the oldest past `kept` and the texts no kept +/// dump names; waits for another session's transaction. The label, `buf`'s. +pub fn putDump(db: *Db, p: *Pardes, bytes: []const u8, label: []const u8, buf: []u8) ![]const u8 { + const r = try Read.open(p.recentGpa(), bytes, null); + defer r.close(); + const o = try db.locked(p, true); + defer unlock(o); + const before = committed(o) catch 0; + const name = try putLocked(o, r, label, buf); + if (db.seen == before) db.seen = committed(o) catch 0; + return name; +} + +fn putLocked(o: *Open, r: *Read, label: []const u8, buf: []u8) ![]const u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.REALTIME, &ts); + switch (o.where) { + inline else => |*w, kind| { + const DB = @TypeOf(w.db); + if (kind == .disk) w.db.core.file.fsync = true; + defer if (kind == .disk) { + w.db.core.file.fsync = false; + }; + var name: []const u8 = label; + try w.db.runContext(struct { + r: *Read, + label: []const u8, + buf: []u8, + name: *[]const u8, + date: u64, + gpa: std.mem.Allocator, + pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { + const root = try DB.HashMap(.read_write).init(cursor.*); + const seq = if (try root.getCursor(key("seq"))) |c| try c.readUint() else 0; + try root.put(key("seq"), .{ .uint = seq + 1 }); + const dumps = try DB.HashMap(.read_write).init(try root.putCursor(key("dumps"))); + // A label of its own: a second dump in a second is `-2`. + var n: usize = 1; + var label_now: []const u8 = ctx.label; + while (try dumps.getCursor(key(label_now)) != null) { + n += 1; + label_now = try std.fmt.bufPrint(ctx.buf, "{s}-{d}", .{ ctx.label, n }); + } + if (n == 1) label_now = try std.fmt.bufPrint(ctx.buf, "{s}", .{ctx.label}); + ctx.name.* = label_now; + // The image's one entry, copied: its session, its texts + // the state file does not have yet, the numbers. + const image_root = try Memory.HashMap(.read_only).init(ctx.r.image.rootCursor().readOnly()); + const from = (try entryOf(Memory, image_root, ctx.r.label)) orelse return error.NoDump; + const image_texts = try ctx.r.blobs(); + try dumps.putKey(key(label_now), .{ .bytes = label_now }); + const entry = try DB.HashMap(.read_write).init(try dumps.putCursor(key(label_now))); + try entry.put(key("seq"), .{ .uint = seq }); + try entry.put(key("date"), .{ .uint = ctx.date }); + try entry.put(key("panes"), .{ .uint = ctx.r.panes }); + try entry.put(key("names"), .{ .bytes = ctx.r.names }); + var session_at = (try from.getCursor(key("session"))) orelse return error.NoDump; + var size = try session_at.count(); + try copyBytes(DB, &session_at, try entry.putCursor(key("session")), session_tag); + const texts = try DB.HashMap(.read_write).init(try root.putCursor(key("blobs"))); + const hashes = try DB.ArrayList(.read_write).init(try entry.putCursor(key("blobs"))); + if (try from.getCursor(key("blobs"))) |list_at| { + var it = try (try Memory.ArrayList(.read_only).init(list_at)).iterator(); + while (try it.next()) |h| { + var hash: [32]u8 = undefined; + if ((try h.readBytes(&hash)).len != 32) return error.NotADump; + try hashes.append(.{ .bytes = &hash }); + var text_at = (try image_texts.getCursor(blobKey(&hash))) orelse return error.NotADump; + size += try text_at.count(); + if (try texts.getCursor(blobKey(&hash)) == null) try copyBytes(DB, &text_at, try texts.putCursor(blobKey(&hash)), null); + } + } + try entry.put(key("size"), .{ .uint = size }); + try root.put(key("last"), .{ .bytes = label_now }); + try trim(DB, ctx.gpa, dumps, texts); + } + }{ .r = r, .label = label, .buf = buf, .name = &name, .date = @intCast(@max(0, ts.sec)), .gpa = r.gpa }); + return name; + }, + } +} + +/// The bytes at `from` (an image's, read while it is open) written at `to`, +/// streamed. +fn copyBytes(comptime DB: type, from: *Memory.Cursor(.read_only), to: DB.Cursor(.read_write), tag: ?[2]u8) !void { + var at = to; + var in_buf: [64 << 10]u8 = undefined; + var reader = try from.reader(&in_buf); + var out_buf: [64 << 10]u8 = undefined; + var writer = try at.writer(&out_buf); + _ = try reader.interface.streamRemaining(&writer.interface); + writer.format_tag = tag; + try writer.finish(); +} + +/// The newest `kept` dumps kept, the older dropped, and every text no kept +/// dump names (one replaced or dropped) dropped with them. +fn trim(comptime DB: type, gpa: std.mem.Allocator, dumps: DB.HashMap(.read_write), texts: DB.HashMap(.read_write)) !void { + const Dumped = struct { seq: u64, hash: u256 }; + var all: std.ArrayList(Dumped) = .empty; + defer all.deinit(gpa); + var it = try dumps.iterator(); + while (try it.next()) |kv_at| { + const kv = try kv_at.readKeyValuePair(); + const entry = try DB.HashMap(.read_only).init(kv.value_cursor); + const seq = if (try entry.getCursor(key("seq"))) |c| try c.readUint() else 0; + try all.append(gpa, .{ .seq = seq, .hash = kv.hash }); + } + std.mem.sort(Dumped, all.items, {}, struct { + fn newer(_: void, a: Dumped, b: Dumped) bool { + return a.seq > b.seq; + } + }.newer); + if (all.items.len > kept) for (all.items[kept..]) |d| { + _ = try dumps.remove(d.hash); + }; + // The texts the kept ones name; every other one goes. + var named: std.AutoHashMapUnmanaged(u256, void) = .empty; + defer named.deinit(gpa); + for (all.items[0..@min(all.items.len, kept)]) |d| { + const entry = try DB.HashMap(.read_only).init((try dumps.getCursor(d.hash)) orelse continue); + const list_at = (try entry.getCursor(key("blobs"))) orelse continue; + var hashes = try (try DB.ArrayList(.read_only).init(list_at)).iterator(); + while (try hashes.next()) |h| { + var hash: [32]u8 = undefined; + if ((try h.readBytes(&hash)).len == 32) try named.put(gpa, blobKey(&hash), {}); + } + } + var gone: std.ArrayList(u256) = .empty; + defer gone.deinit(gpa); + var texts_it = try texts.iterator(); + while (try texts_it.next()) |kv_at| { + const kv = try kv_at.readKeyValuePair(); + if (!named.contains(kv.hash)) try gone.append(gpa, kv.hash); + } + for (gone.items) |h| _ = try texts.remove(h); +} + +/// The dumps the state file keeps, a line each, the newest first: its +/// label, its date (UTC), its size in bytes, its pane count and what its +/// panes showed, a word each. +pub fn listDumps(db: *Db, p: *Pardes, w: *std.Io.Writer) !void { + const o = db.opened(p) orelse return; + pardes.turn.yield(); + defer pardes.turn.back(); + const gpa = p.recentGpa(); + const Row = struct { seq: u64, date: u64, size: u64, panes: u64, label: []u8, names: []u8 }; + var rows: std.ArrayList(Row) = .empty; + defer { + for (rows.items) |r| { + gpa.free(r.label); + gpa.free(r.names); + } + rows.deinit(gpa); + } + switch (o.where) { + inline else => |*d| { + const DB = @TypeOf(d.db); + const root = try DB.HashMap(.read_only).init(d.db.rootCursor().readOnly()); + const dumps_at = (try root.getCursor(key("dumps"))) orelse return; + var it = try (try DB.HashMap(.read_only).init(dumps_at)).iterator(); + while (try it.next()) |kv_at| { + const kv = try kv_at.readKeyValuePair(); + const entry = try DB.HashMap(.read_only).init(kv.value_cursor); + var row: Row = .{ .seq = 0, .date = 0, .size = 0, .panes = 0, .label = @constCast(try kv.key_cursor.readBytesAlloc(gpa, 4096)), .names = &.{} }; + errdefer gpa.free(row.label); + inline for (.{ "seq", "date", "size", "panes" }) |field| if (try entry.getCursor(key(field))) |c| { + @field(row, field) = c.readUint() catch 0; + }; + row.names = if (try entry.getCursor(key("names"))) |c| @constCast(try c.readBytesAlloc(gpa, 4096)) else try gpa.dupe(u8, ""); + errdefer gpa.free(row.names); + try rows.append(gpa, row); + } + }, + } + std.mem.sort(Row, rows.items, {}, struct { + fn newer(_: void, a: Row, b: Row) bool { + return a.seq > b.seq; + } + }.newer); + for (rows.items) |r| { + const es: std.time.epoch.EpochSeconds = .{ .secs = r.date }; + const yd = es.getEpochDay().calculateYearDay(); + const md = yd.calculateMonthDay(); + const ds = es.getDaySeconds(); + try w.print("{s} {d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z {d} {d}{s}{s}\n", .{ + r.label, yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, + ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), r.size, + r.panes, if (r.names.len > 0) " " else "", r.names, + }); + } +} + +/// At a session's end: the state file compacted (into `<path>.new`, +/// renamed over it) once it is past twice what its dumps and Recent hold, +/// plus 64 MiB. Under the file's lock: no session commits to the old file +/// meanwhile, and one that opened it reopens the new one (`opened`). +pub fn compact(db: *Db, p: *Pardes) void { + if (db.kind != .disk or db.open == null) return; + const size = db.open.?.where.disk.file.length(ioOf()) catch return; + if (size < 64 << 20) return; + const o = db.locked(p, true) catch return; + defer unlock(o); + const d = &o.where.disk; + const io = ioOf(); + const live = liveSize(&d.db) catch return; + if (size <= 2 * live + (64 << 20)) return; + var buf: [4300]u8 = undefined; + const new = std.fmt.bufPrint(&buf, "{s}.new", .{d.path}) catch return; + const cwd = std.Io.Dir.cwd(); + const file = cwd.createFile(io, new, .{ .read = true, .truncate = true }) catch return; + var new_buf: std.Io.Writer.Allocating = .init(p.recentGpa()); + defer new_buf.deinit(); + var offsets: std.AutoHashMap(u64, u64) = .init(p.recentGpa()); + defer offsets.deinit(); + _ = d.db.compact(.buffered_file, .{ .file = file, .buffer = &new_buf, .hash_id = hash_id }, &offsets) catch { + file.close(io); + cwd.deleteFile(io, new) catch {}; + return; + }; + file.close(io); + cwd.rename(new, cwd, d.path, io) catch cwd.deleteFile(io, new) catch {}; +} + +/// What the state file's latest moment holds: Recent, each dump's +/// session, each text once. +fn liveSize(db: *Disk) !u64 { + const root = try Disk.HashMap(.read_only).init(db.rootCursor().readOnly()); + var live: u64 = 0; + if (try root.getCursor(key("recent"))) |c| live += try c.count(); + if (try root.getCursor(key("dumps"))) |at| { + var it = try (try Disk.HashMap(.read_only).init(at)).iterator(); + while (try it.next()) |kv_at| { + const entry = try Disk.HashMap(.read_only).init((try kv_at.readKeyValuePair()).value_cursor); + if (try entry.getCursor(key("session"))) |c| live += try c.count(); + } + } + if (try root.getCursor(key("blobs"))) |at| { + var it = try (try Disk.HashMap(.read_only).init(at)).iterator(); + while (try it.next()) |kv_at| live += try (try kv_at.readKeyValuePair()).value_cursor.count(); + } + return live; +} + +// ---- a far client's blob cache ---- + +/// A far replica client's blob cache (replica.zig `Have`): `cache.xitdb` in +/// $XDG_CACHE_HOME/pardes (else ~/.cache/pardes), the texts a join was +/// sent, by their BLAKE3 hash, so a client started again or a second one on +/// this machine is not sent them again. Expendable, and up to a gigabyte, so +/// a file of its own, never the state file's: +/// +/// blobs/<hash> the text +/// seqs/<hash> its number in `seen` +/// seen a sorted map, a number (big endian) to its blob's hash: +/// the least recently used first (a hit takes a new number) +/// size, next the texts' bytes, the next number +/// +/// Past the cap (PARDES_BLOB_CACHE_MB, else 1 GiB) the most recently used +/// that fit stay and the rest go, and the file is compacted into +/// `cache.xitdb.new` and renamed over it: one transaction and one +/// compaction, at a far client's end (`trim`), never on a frame. A text read back is hashed again: one torn or changed is a miss +/// and goes, never wrong content; a file that is no database is started +/// afresh (it holds nothing a join cannot send again). Each use opens the +/// file for itself: a client's reader, its storing thread and its end each +/// have a database of their own, as xitdb asks. +pub const Cache = struct { + path_buf: [4096]u8 = undefined, + path_len: usize = 0, + /// Bytes it keeps at most. + cap: u64, + + pub const name = "cache.xitdb"; + + /// The cache's place, its directory made: null with no home for it. + pub fn open(io: std.Io) ?Cache { + var c: Cache = .{ .cap = (if (std.c.getenv("PARDES_BLOB_CACHE_MB")) |v| std.fmt.parseInt(u64, std.mem.span(v), 10) catch 1024 else 1024) << 20 }; + const base = if (std.c.getenv("XDG_CACHE_HOME")) |x| std.mem.span(x) else ""; + const where = (if (base.len > 0 and base[0] == '/') + std.fmt.bufPrint(&c.path_buf, "{s}/pardes/" ++ name, .{base}) + else if (std.c.getenv("HOME")) |home| + std.fmt.bufPrint(&c.path_buf, "{s}/.cache/pardes/" ++ name, .{std.mem.span(home)}) + else + return null) catch return null; + std.Io.Dir.cwd().createDirPath(io, std.Io.Dir.path.dirname(where).?) catch return null; + c.path_len = where.len; + return c; + } + + /// The cache at `where` (a test's). + pub fn of(where: []const u8, cap: u64) Cache { + var c: Cache = .{ .cap = cap, .path_len = where.len }; + @memcpy(c.path_buf[0..where.len], where); + return c; + } + + pub fn path(c: *const Cache) []const u8 { + return c.path_buf[0..c.path_len]; + } + + /// The cache open for one use. + const Use = struct { + file: std.Io.File, + buffer: std.Io.Writer.Allocating, + db: Disk, + }; + + fn use(c: *const Cache, io: std.Io, u: *Use) !void { + const cwd = std.Io.Dir.cwd(); + u.buffer = .init(std.heap.c_allocator); + errdefer u.buffer.deinit(); + for (0..2) |_| { + u.file = try cwd.createFile(io, c.path(), .{ .read = true, .truncate = false }); + u.db = Disk.init(io, .{ .file = u.file, .buffer = &u.buffer, .fsync = false, .hash_id = hash_id }) catch |err| { + u.file.close(io); + // No database: started afresh, as nothing in it is precious. + cwd.deleteFile(io, c.path()) catch return err; + continue; + }; + return; + } + return error.InvalidDatabase; + } + + fn done(u: *Use, io: std.Io) void { + u.file.close(io); + u.buffer.deinit(); + } + + fn mapAt(root: Disk.HashMap(.read_only), field: []const u8) !?Disk.HashMap(.read_only) { + const c = (try root.getCursor(key(field))) orelse return null; + return try Disk.HashMap(.read_only).init(c); + } + + /// The text of `hash` read into `out` (its length) and hashed again. + /// One of another length or content is a miss, and goes. + pub fn get(c: *const Cache, io: std.Io, hash: *const [32]u8, out: []u8) bool { + var u: Use = undefined; + c.use(io, &u) catch return false; + defer done(&u, io); + const ok = ok: { + const root = Disk.HashMap(.read_only).init(u.db.rootCursor().readOnly()) catch break :ok false; + const blobs = (mapAt(root, "blobs") catch break :ok false) orelse return false; + const at = (blobs.getCursor(blobKey(hash)) catch break :ok false) orelse return false; + if ((at.count() catch break :ok false) != out.len) break :ok false; + _ = at.readBytes(out) catch break :ok false; + var d: [32]u8 = undefined; + std.crypto.hash.Blake3.hash(out, &d, .{}); + break :ok std.mem.eql(u8, &d, hash); + }; + if (!ok) drop(&u, io, hash); + return ok; + } + + /// Whether a text of `len` bytes is there under `hash` (not read). + pub fn has(c: *const Cache, io: std.Io, hash: *const [32]u8, len: usize) bool { + var u: Use = undefined; + c.use(io, &u) catch return false; + defer done(&u, io); + const root = Disk.HashMap(.read_only).init(u.db.rootCursor().readOnly()) catch return false; + const blobs = (mapAt(root, "blobs") catch return false) orelse return false; + const at = (blobs.getCursor(blobKey(hash)) catch return false) orelse return false; + return (at.count() catch return false) == len; + } + + /// The text of `hash`, gone (one read back wrong). + fn drop(u: *Use, io: std.Io, hash: *const [32]u8) void { + u.file.lock(io, .exclusive) catch return; + defer u.file.unlock(io); + u.db.runContext(struct { + hash: *const [32]u8, + pub fn run(ctx: @This(), cursor: *Disk.Cursor(.read_write)) !void { + const root = try Disk.HashMap(.read_write).init(cursor.*); + const blobs = try Disk.HashMap(.read_write).init(try root.putCursor(key("blobs"))); + const at = (try blobs.getCursor(blobKey(ctx.hash))) orelse return; + const len = try at.count(); + _ = try blobs.remove(blobKey(ctx.hash)); + const size = if (try root.getCursor(key("size"))) |s| try s.readUint() else 0; + try root.put(key("size"), .{ .uint = size -| len }); + const seqs = try Disk.HashMap(.read_write).init(try root.putCursor(key("seqs"))); + if (try seqs.getCursor(blobKey(ctx.hash))) |s| { + const was = try s.readUint(); + _ = try seqs.remove(blobKey(ctx.hash)); + const seen = try Disk.SortedMap(.read_write).init(try root.putCursor(key("seen"))); + _ = try seen.remove(&seqKey(was)); + } + } + }{ .hash = hash }) catch {}; + } + + fn seqKey(seq: u64) [8]u8 { + var k: [8]u8 = undefined; + std.mem.writeInt(u64, &k, seq, .big); + return k; + } + + /// `blobs` kept (each text not there yet, under its hash) and `hits`, + /// texts read from here, made the most recently used: one transaction, + /// the file's lock waited for (a storing thread's, a client's end's). + pub fn put(c: *const Cache, io: std.Io, blobs: []const pardes.walk.Blob, hits: []const [32]u8) void { + if (blobs.len == 0 and hits.len == 0) return; + var u: Use = undefined; + c.use(io, &u) catch return; + defer done(&u, io); + u.file.lock(io, .exclusive) catch return; + defer u.file.unlock(io); + u.db.runContext(struct { + blobs: []const pardes.walk.Blob, + hits: []const [32]u8, + pub fn run(ctx: @This(), cursor: *Disk.Cursor(.read_write)) !void { + const root = try Disk.HashMap(.read_write).init(cursor.*); + const texts = try Disk.HashMap(.read_write).init(try root.putCursor(key("blobs"))); + const seqs = try Disk.HashMap(.read_write).init(try root.putCursor(key("seqs"))); + const seen = try Disk.SortedMap(.read_write).init(try root.putCursor(key("seen"))); + var next = if (try root.getCursor(key("next"))) |n| try n.readUint() else 0; + var size = if (try root.getCursor(key("size"))) |s| try s.readUint() else 0; + for (ctx.blobs) |*b| { + if (try texts.getCursor(blobKey(&b.hash)) != null) continue; + try texts.put(blobKey(&b.hash), .{ .bytes = b.bytes }); + try seqs.put(blobKey(&b.hash), .{ .uint = next }); + try seen.put(&seqKey(next), .{ .bytes = &b.hash }); + next += 1; + size += b.bytes.len; + } + for (ctx.hits) |*h| { + const at = (try seqs.getCursor(blobKey(h))) orelse continue; + _ = try seen.remove(&seqKey(try at.readUint())); + try seqs.put(blobKey(h), .{ .uint = next }); + try seen.put(&seqKey(next), .{ .bytes = h }); + next += 1; + } + try root.put(key("next"), .{ .uint = next }); + try root.put(key("size"), .{ .uint = size }); + } + }{ .blobs = blobs, .hits = hits }) catch {}; + } + + /// Under the cap: the most recently used texts kept while they fit, the + /// newest first, and the rest gone, in one transaction (one past the cap + /// alone goes without taking the older ones with it); then the file + /// compacted into `<path>.new` and renamed over it once any went (what + /// no moment holds is the file's growth). + pub fn trim(c: *const Cache, io: std.Io) void { + var u: Use = undefined; + c.use(io, &u) catch return; + defer done(&u, io); + u.file.lock(io, .exclusive) catch return; + defer u.file.unlock(io); + var went = false; + u.db.runContext(struct { + cap: u64, + went: *bool, + pub fn run(ctx: @This(), cursor: *Disk.Cursor(.read_write)) !void { + const root = try Disk.HashMap(.read_write).init(cursor.*); + const size = if (try root.getCursor(key("size"))) |s| try s.readUint() else 0; + if (size <= ctx.cap) return; + const texts = try Disk.HashMap(.read_write).init(try root.putCursor(key("blobs"))); + const seqs = try Disk.HashMap(.read_write).init(try root.putCursor(key("seqs"))); + const seen = try Disk.SortedMap(.read_write).init(try root.putCursor(key("seen"))); + // Every text, the least recently used first, read before any goes. + const Text = struct { seq: [8]u8, hash: [32]u8, len: ?u64, kept: bool = false }; + var all: std.ArrayList(Text) = .empty; + defer all.deinit(std.heap.c_allocator); + var it = try seen.iterator(); + while (try it.next()) |kv_at| { + const kv = try kv_at.readKeyValuePair(); + var t: Text = .{ .seq = undefined, .hash = undefined, .len = null }; + if ((try kv.key_cursor.readBytes(&t.seq)).len != 8 or (try kv.value_cursor.readBytes(&t.hash)).len != 32) continue; + t.len = if (try texts.getCursor(blobKey(&t.hash))) |at| try at.count() else null; + try all.append(std.heap.c_allocator, t); + } + var room = ctx.cap; + var i = all.items.len; + while (i > 0) { + i -= 1; + const t = &all.items[i]; + t.kept = if (t.len) |len| len <= room else false; + if (t.kept) room -= t.len.?; + } + for (all.items) |*t| if (!t.kept) { + _ = try texts.remove(blobKey(&t.hash)); + _ = try seqs.remove(blobKey(&t.hash)); + _ = try seen.remove(&t.seq); + ctx.went.* = true; + }; + try root.put(key("size"), .{ .uint = ctx.cap - room }); + } + }{ .cap = c.cap, .went = &went }) catch return; + if (!went) return; + var new_buf: [c.path_buf.len + ".new".len]u8 = undefined; + const new = std.fmt.bufPrint(&new_buf, "{s}.new", .{c.path()}) catch unreachable; // path_buf's [4096]u8 and ".new" fit + const cwd = std.Io.Dir.cwd(); + const file = cwd.createFile(io, new, .{ .read = true, .truncate = true }) catch return; + var buffer: std.Io.Writer.Allocating = .init(std.heap.c_allocator); + defer buffer.deinit(); + var offsets: std.AutoHashMap(u64, u64) = .init(std.heap.c_allocator); + defer offsets.deinit(); + _ = u.db.compact(.buffered_file, .{ .file = file, .buffer = &buffer, .fsync = false, .hash_id = hash_id }, &offsets) catch { + file.close(io); + cwd.deleteFile(io, new) catch {}; + return; + }; + file.close(io); + cwd.rename(new, cwd, c.path(), io) catch cwd.deleteFile(io, new) catch {}; + } +}; + +// ---- tests ---- + +const testing = std.testing; + +/// The database, opened (made, when its file is not there) at its first use +/// and again once the DumpDir names another: null when this session keeps +/// none, or it cannot be had now (the next use tries again). +fn opened(db: *Db, p: *Pardes) ?*Open { + switch (db.kind) { + .off => return null, + .disk => { + var buf: [4200]u8 = undefined; + const path = statePath(&buf, p.settings.dump_dir.get()) orelse return null; + if (db.open) |o| { + // The same file still: another session's compaction renames + // a new one over it, which this one then opens. + if (std.mem.eql(u8, o.where.disk.path, path) and !replaced(o)) return o; + // The DumpDir moved: its own file, read afresh. + db.deinit(); + db.seen = 0; + } + db.open = openDisk(p.recentGpa(), path) catch return null; + }, + .memory => if (db.open == null) { + const gpa = p.recentGpa(); + const o = gpa.create(Open) catch return null; + o.* = .{ .gpa = gpa, .buffer = .init(gpa), .where = undefined }; + o.where = .{ .memory = .{ .db = Memory.init(ioOf(), .{ .buffer = &o.buffer, .hash_id = hash_id }) catch { + o.buffer.deinit(); + gpa.destroy(o); + return null; + } } }; + db.open = o; + }, + } + return db.open; +} + +/// A window keeping its state in `dir` (never the user's DumpDir). +fn testWindow(dir: []const u8) !*Pardes { + var config: [4200]u8 = undefined; + return Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48, .state = .disk, .startup_config = try std.fmt.bufPrint(&config, "DumpDir {s}\n", .{dir}) }); +} + +fn testDir(tmp: *std.testing.TmpDir, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 { + return buf[0..try tmp.dir.realPath(testing.io, buf)]; +} + +fn fileSize(dir: []const u8) u64 { + var buf: [4200]u8 = undefined; + const path = std.fmt.bufPrint(&buf, "{s}/" ++ file_name, .{dir}) catch return 0; + const st = std.Io.Dir.cwd().statFile(testing.io, path, .{}) catch return 0; + return st.size; +} + +test "state file: two windows share Recent, each reading the other's commits on use; a busy lock delays, never loses" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = try testDir(&tmp, &dir_buf); + const a = try testWindow(dir); + defer a.deinit(); + const b = try testWindow(dir); + defer b.deinit(); + a.recent.opened(a.recentGpa(), "/w/a.zig"); + a.saveRecent(); + b.recent.opened(b.recentGpa(), "/w/b.zig"); + b.saveRecent(); + a.recent.closed(a.recentGpa(), "/w/a.zig", 7, 3, 0, 0); + a.saveRecent(); + // Each has both, in the order they were written: a closed last, then b. + a.db.readRecent(a); + b.db.readRecent(b); + for ([_]*Pardes{ a, b }) |w| { + try testing.expectEqual(@as(usize, 2), w.recent.entries.items.len); + try testing.expectEqualStrings("/w/a.zig", w.recent.entries.items[0].path); + try testing.expectEqualStrings("/w/b.zig", w.recent.entries.items[1].path); + try testing.expectEqual(@as(u32, 7), w.recent.get("/w/a.zig").?.line); + } + // Another window holding the file's lock: b's change waits in memory... + var path_buf: [4200]u8 = undefined; + const lock_file = try std.Io.Dir.cwd().openFile(testing.io, try std.fmt.bufPrint(&path_buf, "{s}/" ++ file_name, .{dir}), .{ .mode = .read_write }); + try lock_file.lock(testing.io, .exclusive); + b.recent.opened(b.recentGpa(), "/w/c.zig"); + const size = fileSize(dir); + b.saveRecent(); + try testing.expectEqual(size, fileSize(dir)); + try testing.expect(b.recent.dirty); + // ...and is written at the next step after it is let go. + lock_file.close(testing.io); + b.saveRecent(); + try testing.expect(fileSize(dir) > size); + a.db.readRecent(a); + try testing.expectEqualStrings("/w/c.zig", a.recent.entries.items[0].path); + // A window started now reads the same list. + const c = try testWindow(dir); + defer c.deinit(); + try testing.expectEqual(@as(usize, 3), c.recent.entries.items.len); + for (a.recent.entries.items, c.recent.entries.items) |x, y| try testing.expectEqualStrings(x.path, y.path); +} + +test "state file: Recent holds the newest 200, the newest first, and a window started on it reads them so" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = try testDir(&tmp, &dir_buf); + const a = try testWindow(dir); + defer a.deinit(); + var name: [32]u8 = undefined; + for (0..recent.cap + 100) |i| { + const file = std.fmt.bufPrint(&name, "/w/file{d}.zig", .{i}) catch unreachable; + a.recent.opened(a.recentGpa(), file); + a.recent.closed(a.recentGpa(), file, 1, 1, 0, 0); + a.saveRecent(); + } + try testing.expectEqual(@as(usize, recent.cap), a.recent.entries.items.len); + const text = (try recentText(a.db.open.?, testing.allocator)).?; + defer testing.allocator.free(text); + try testing.expectEqual(@as(usize, recent.cap), std.mem.count(u8, text, "\n")); + try testing.expect(std.mem.startsWith(u8, text, "1 1 0 0 /w/file299.zig\n")); + const b = try testWindow(dir); + defer b.deinit(); + try testing.expectEqual(@as(usize, recent.cap), b.recent.entries.items.len); + try testing.expectEqualStrings("/w/file299.zig", b.recent.entries.items[0].path); + try testing.expectEqualStrings("/w/file100.zig", b.recent.entries.items[recent.cap - 1].path); +} + +test "state file: one that is no database of pardes's never stops pardes: it is kept aside, and a new one started" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = try testDir(&tmp, &dir_buf); + try tmp.dir.writeFile(testing.io, .{ .sub_path = file_name, .data = "\x00\xffnot a database at all\n7 3 0 0 /w/ok.zig\n" }); + const a = try testWindow(dir); + defer a.deinit(); + try testing.expectEqual(@as(usize, 0), a.recent.entries.items.len); + a.recent.opened(a.recentGpa(), "/w/a.zig"); + a.saveRecent(); + const aside = try tmp.dir.readFileAlloc(testing.io, file_name ++ ".broken", testing.allocator, .limited(1 << 20)); + defer testing.allocator.free(aside); + try testing.expect(std.mem.startsWith(u8, aside, "\x00\xffnot a database")); + const b = try testWindow(dir); + defer b.deinit(); + try testing.expectEqual(@as(usize, 1), b.recent.entries.items.len); + try testing.expectEqualStrings("/w/a.zig", b.recent.entries.items[0].path); +} + +test "state file: one a power loss tore is opened at its last whole commit, the dumps before it kept; it is set aside only when none is whole" { + if (std.c.getenv("PARDES_DUMP") != null) return error.SkipZigTest; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = try testDir(&tmp, &dir_buf); + var label_buf: [64]u8 = undefined; + var label: []const u8 = undefined; + var dumped: u64 = undefined; + { + // A Dump, then a Recent's change committed after it. + const a = try testWindow(dir); + defer a.deinit(); + _ = try a.setTestFile("kept through a tear\n"); + try pardes.dump.dumpState(a); + pardes.host_io.writeDump(a, a.dump_out.?); + label = try std.fmt.bufPrint(&label_buf, "{s}", .{a.last_dump.?}); + dumped = fileSize(dir); + a.recent.opened(a.recentGpa(), "/w/after.zig"); + a.saveRecent(); + } + const whole = try tmp.dir.readFileAlloc(testing.io, file_name, testing.allocator, .limited(64 << 20)); + defer testing.allocator.free(whole); + try testing.expect(whole.len > dumped); + const torn = try testing.allocator.alloc(u8, whole.len + 4096); + defer testing.allocator.free(torn); + const cases = [_]struct { what: []const u8, len: usize, after: ?bool }{ + // Its last commit cut short: the file ends before its root header says. + .{ .what = "cut short", .len = whole.len - 10, .after = null }, + // A commit after the last whole one, its root header written, its + // bytes garbage: the last whole one's Recent is there. + .{ .what = "garbage after", .len = whole.len + 4096, .after = true }, + // Recent's commit after the Dump never reached the disk (zeros where + // it would be) but its root header did: the Dump is there, the + // change gone. + .{ .what = "Recent's commit torn", .len = whole.len, .after = false }, + }; + for (cases) |case| { + @memcpy(torn[0..whole.len], whole); + @memset(torn[whole.len..], 0x5a); + if (std.mem.eql(u8, case.what, "garbage after")) std.mem.writeInt(u64, torn[root_header_end - 8 .. root_header_end], torn.len, .big); + if (std.mem.eql(u8, case.what, "Recent's commit torn")) @memset(torn[dumped..whole.len], 0); + try tmp.dir.writeFile(testing.io, .{ .sub_path = file_name, .data = torn[0..case.len] }); + const b = try testWindow(dir); + defer b.deinit(); + errdefer std.debug.print("case: {s}\n", .{case.what}); + try testing.expectError(error.FileNotFound, tmp.dir.statFile(testing.io, file_name ++ ".broken", .{})); + var buf: [64]u8 = undefined; + try testing.expect(b.db.labelled(b, label, &buf) != null); + if (case.after) |after| try testing.expectEqual(after, b.recent.get("/w/after.zig") != null); + // The Dump read back whole, its text with it. + const img = (try b.db.getDump(b, testing.allocator, label)).?; + defer testing.allocator.free(img); + const q = try pardes.dump.initFromDump(testing.allocator, .{ .tty_only = true }, img); + defer q.deinit(); + const text = for (q.panes) |slot| { + if (slot) |pane| if (pane.file) |f| if (f.output == null) break f.content; + } else return error.FileLost; + try testing.expectEqualStrings("kept through a tear\n", text); + } + // No commit whole: set aside, the bytes as they were, and a new one started. + @memcpy(torn[0..whole.len], whole); + @memset(torn[root_header_end..whole.len], 0); + try tmp.dir.writeFile(testing.io, .{ .sub_path = file_name, .data = torn[0..whole.len] }); + const c = try testWindow(dir); + defer c.deinit(); + var buf: [64]u8 = undefined; + try testing.expect(c.db.labelled(c, label, &buf) == null); + const aside = try tmp.dir.readFileAlloc(testing.io, file_name ++ ".broken", testing.allocator, .limited(64 << 20)); + defer testing.allocator.free(aside); + try testing.expectEqualSlices(u8, torn[0..whole.len], aside); +} + +test "state file: two dumps with one label get labels of their own" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .state = .memory }); + defer p.deinit(); + const bytes = try pardes.dump.dumpBytes(p); + defer testing.allocator.free(bytes); + var buf: [64]u8 = undefined; + try testing.expectEqualStrings("pardes-x", try p.db.putDump(p, bytes, "pardes-x", &buf)); + try testing.expectEqualStrings("pardes-x-2", try p.db.putDump(p, bytes, "pardes-x", &buf)); + try testing.expectEqualStrings("pardes-x-3", try p.db.putDump(p, bytes, "pardes-x", &buf)); + var label_buf: [64]u8 = undefined; + try testing.expectEqualStrings("pardes-x-3", p.db.labelled(p, null, &label_buf).?); +} + +test "state file: a Dump makes every directory missing on the way to its DumpDir, and the file there" { + if (std.c.getenv("PARDES_DUMP") != null) return error.SkipZigTest; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const base = try testDir(&tmp, &dir_buf); + var setting: [4200]u8 = undefined; + const dir = try std.fmt.bufPrint(&setting, "{s}/fresh/.local/share/pardes", .{base}); + const p = try testWindow(dir); + defer p.deinit(); + try pardes.dump.dumpState(p); + pardes.host_io.writeDump(p, p.dump_out.?); + try testing.expect(std.mem.startsWith(u8, p.last_dump.?, "pardes-")); + try testing.expect(fileSize(dir) > 0); + var label_buf: [64]u8 = undefined; + try testing.expect(p.db.labelled(p, p.last_dump.?, &label_buf) != null); +} + +test "state file: Recent is read once from the file it replaced, else from the store before that, both left where they are" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = try testDir(&tmp, &dir_buf); + try tmp.dir.createDirPath(testing.io, "old"); + try tmp.dir.createDirPath(testing.io, "older"); + try tmp.dir.createDirPath(testing.io, "a"); + try tmp.dir.createDirPath(testing.io, "b"); + // 0.24's Recent: 200 lines, the newest first. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "old/recent", .data = "7 3 0 0 /w/newest.zig\n1 1 0 0 /w/older.zig\n" }); + // Before it, the store: its `@r` records' bodies the same lines, oldest + // first, a closed pane's record between them. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "older/store", .data = "@h 31 3c6ce28a\npardes-store 1 ca2a9583be7d1ba3\n@r 20 0\n1 1 0 0 /w/old.zig\n@c 12 0\n0 1 7 0 0 0 0 9\t/w/x\n.{}\n@r 21 0\n2 2 0 0 /w/both.zig\n@r 20 0\n9 9 0 0 /w/old.zig\n" }); + var buf: [3][4200]u8 = undefined; + const old = try std.fmt.bufPrint(&buf[0], "{s}/old", .{dir}); + const older = try std.fmt.bufPrint(&buf[1], "{s}/older", .{dir}); + const window = struct { + fn of(state: []const u8, import: []const u8) !*Pardes { + var config: [4200]u8 = undefined; + return Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48, .state = .disk, .recent_import = import, .startup_config = try std.fmt.bufPrint(&config, "DumpDir {s}\n", .{state}) }); + } + }.of; + { + const a = try window(try std.fmt.bufPrint(&buf[2], "{s}/a", .{dir}), old); + defer a.deinit(); + try testing.expectEqual(@as(usize, 2), a.recent.entries.items.len); + try testing.expectEqualStrings("/w/newest.zig", a.recent.entries.items[0].path); + try testing.expectEqual(@as(u32, 7), a.recent.get("/w/newest.zig").?.line); + a.saveRecent(); + } + // Read once: what the old file says after is not the state file's. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "old/recent", .data = "5 5 0 0 /w/later.zig\n" }); + { + const a = try window(try std.fmt.bufPrint(&buf[2], "{s}/a", .{dir}), old); + defer a.deinit(); + try testing.expectEqual(@as(usize, 2), a.recent.entries.items.len); + try testing.expect(a.recent.get("/w/later.zig") == null); + } + // No `recent` there: the store's, its newest records first. + { + const b = try window(try std.fmt.bufPrint(&buf[2], "{s}/b", .{dir}), older); + defer b.deinit(); + try testing.expectEqual(@as(usize, 2), b.recent.entries.items.len); + try testing.expectEqualStrings("/w/old.zig", b.recent.entries.items[0].path); + try testing.expectEqual(@as(u32, 9), b.recent.entries.items[0].line); + try testing.expectEqualStrings("/w/both.zig", b.recent.entries.items[1].path); + } + // A directory whose path is past the room for its files' names: none + // read, and said so. + { + try tmp.dir.createDirPath(testing.io, "c"); + var long: [4200]u8 = undefined; + @memset(&long, 'd'); + long[0] = '/'; + const c = try window(try std.fmt.bufPrint(&buf[2], "{s}/c", .{dir}), &long); + defer c.deinit(); + try testing.expectEqual(@as(usize, 0), c.recent.entries.items.len); + const pane = c.panes[c.view().active].?; + try testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "Recent: the files before the state file were not read") != null); + } + // Both left where they were. + _ = try tmp.dir.statFile(testing.io, "old/recent", .{}); + _ = try tmp.dir.statFile(testing.io, "older/store", .{}); +} |
