diff options
Diffstat (limited to 'src/dump.zig')
| -rw-r--r-- | src/dump.zig | 275 |
1 files changed, 199 insertions, 76 deletions
diff --git a/src/dump.zig b/src/dump.zig index 3ded45ca..8847152d 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -20,64 +20,29 @@ const Options = pardes.Options; const Pardes = pardes.Pardes; const views = pardes.views; -/// Where the next dump goes. $PARDES_DUMP wins verbatim (the snapshot harness -/// pins it for deterministic goldens); else $XDG_DATA_HOME|~/.local/share -/// /pardes/pardes-<utc>.dump — timestamped so dumps never overwrite each other. -/// Creates the directory and any parent missing (a fresh HOME has no -/// ~/.local/share); a failure surfaces at open. -pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { - if (std.c.getenv("PARDES_DUMP")) |p| - return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; - var dir_buf: [900]u8 = undefined; - const dir = directory(&dir_buf, dir_setting) orelse return null; - _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; +/// A Dump's label in the state file (Db.zig): `pardes-<date>-<time>`, UTC +/// (another in the same second is `-2` and on there), in `buf`. +pub fn label(buf: []u8) []const u8 { var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.REALTIME, &ts); const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; const yd = es.getEpochDay().calculateYearDay(); const md = yd.calculateMonthDay(); const ds = es.getDaySeconds(); - var stamp: [32]u8 = undefined; - const base = std.fmt.bufPrint(&stamp, "pardes-{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{ + return std.fmt.bufPrint(buf, "pardes-{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{ yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), - }) catch return null; - return uniqueIn(buf, dir, base); + }) catch "pardes-dump"; } -/// `<dir>/<base>.dump`, or `<base>-2.dump` and on when two dumps land in one -/// second: a dump never overwrites another. -fn uniqueIn(buf: *[1024:0]u8, dir: []const u8, base: []const u8) ?[:0]const u8 { - var n: usize = 1; - while (n < 1000) : (n += 1) { - const path = (if (n == 1) - std.fmt.bufPrintSentinel(buf, "{s}/{s}.dump", .{ dir, base }, 0) - else - std.fmt.bufPrintSentinel(buf, "{s}/{s}-{d}.dump", .{ dir, base, n }, 0)) catch return null; - if (std.c.access(path.ptr, std.c.F_OK) != 0) return path; - } - return null; -} - -test "two dumps in one second get names of their own" { - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var dir_buf: [900]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var buf: [1024:0]u8 = undefined; - const first = try std.testing.allocator.dupe(u8, uniqueIn(&buf, dir, "pardes-x").?); - defer std.testing.allocator.free(first); - try std.testing.expect(std.mem.endsWith(u8, first, "/pardes-x.dump")); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-x.dump", .data = "" }); - try std.testing.expect(std.mem.endsWith(u8, uniqueIn(&buf, dir, "pardes-x").?, "/pardes-x-2.dump")); -} /// The host's environment. fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { return std.c.getenv(name); } -/// Where dumps go and relative Restore names are looked up: the `DumpDir` -/// setting when set (a leading `~/` is the home directory), else the default. +/// Where the state file is (Db.zig) and relative Restore names are looked +/// up: the `DumpDir` setting when set (a leading `~/` is the home +/// directory), else the default. pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { if (dir_setting.len == 0) return defaultDirectory(buf); var joined: [4096]u8 = undefined; @@ -92,21 +57,6 @@ pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { return std.fmt.bufPrint(buf, "{s}", .{resolved}) catch null; } -test "a dump makes every directory missing on the way to its DumpDir" { - if (std.c.getenv("PARDES_DUMP") != null) return error.SkipZigTest; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var at: [4096]u8 = undefined; - const base = at[0..try tmp.dir.realPath(std.testing.io, &at)]; - var setting: [4200]u8 = undefined; - const dir = try std.fmt.bufPrint(&setting, "{s}/fresh/.local/share/pardes", .{base}); - var out: [1024:0]u8 = undefined; - const path = outPath(&out, dir).?; - try std.testing.expect(std.mem.startsWith(u8, path, dir)); - var made = try tmp.dir.openDir(std.testing.io, "fresh/.local/share/pardes", .{}); - made.close(std.testing.io); -} - test "a DumpDir reads back absolute, however it was written" { var buf: [4096]u8 = undefined; try std.testing.expectEqualStrings("/tmp/dumps", directory(&buf, "/tmp/dumps/").?); @@ -130,11 +80,15 @@ pub var terminal_gpa: ?std.mem.Allocator = null; // ---- a whole session to and from a dump (acme keeps this in rows.c) ---- // -// A dump (src/walk.zig) is everything the session is but what is the -// host's, the frame's or worked out again: its panes with their text and -// undo, terminals with their screens, history and kitty images (ghostty's -// snapshot), registers, places, tags, layout and settings. It crosses -// builds: its fields are matched by name. +// A dump is everything the session is but what is the host's, the frame's +// or worked out again: its panes with their text and undo, terminals with +// their screens, history and kitty images (ghostty's snapshot), registers, +// places, tags, layout and settings. It crosses builds: its fields are +// matched by name. It is an image (Db.zig): a database in memory the walk +// writes by name (walk.Put), which the state file keeps under a label, +// `Dump export` and a handover write as a file, and `-l` and Restore read. +// The byte dump before it (walk.Dump) is still a replica's join, a closed +// pane's, and for one release (0.24) what an old `.dump` file is read as. // // Loading is two halves. `load` makes the core the dump was and nothing // else (a replica joining a session takes that, phase 5); `revivePane` and @@ -166,11 +120,92 @@ pub fn dumpState(p: *Pardes) !void { p.emit(.write_dump); } -/// The session as a dump, gpa-owned. +/// A Dump: into the state file, or (`Dump export`) a file of its own at +/// `to` (`~` the home directory). +pub fn dumpTo(p: *Pardes, to: ?[]const u8) !void { + if (p.dump_export) |old| p.gpa.free(old); + p.dump_export = null; + if (to) |path| { + var home_buf: [4096]u8 = undefined; + p.dump_export = try p.gpa.dupe(u8, filesystem.expandHome(path, &home_buf)); + } + try dumpState(p); +} + +/// The file a Restore of `name` reads, its whole path in `out`: one named +/// with a `/` or `~/` (as it resolves, else as typed: the read says why), +/// or a bare word that names a file in the DumpDir or the directory pardes +/// runs in; null for one that names none: a label of the state file's. +pub fn restoreFile(name: []const u8, dir_setting: []const u8, out: *[4096]u8) ?[]const u8 { + const path = filesystem.restorePath(name, dir_setting, out); + if (std.mem.indexOfScalar(u8, name, '/') != null or std.mem.startsWith(u8, name, "~")) return path; + return if (std.fs.path.isAbsolute(path)) path else null; +} + +/// What a Restore of `name` reads, `gpa`'s: the file it names (an image, +/// or an old byte dump), else the state file's dump of that label. +pub fn restoreBytes(p: *Pardes, gpa: std.mem.Allocator, name: []const u8) ![]u8 { + var buf: [4096]u8 = undefined; + if (restoreFile(name, p.settings.dump_dir.get(), &buf)) |path| return filesystem.readFile(gpa, path); + const got = p.db.getDump(p, gpa, name) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump; + return got orelse error.FileNotFound; +} + +/// The session as a dump's image, gpa-owned (the host puts it in the state +/// file under a label of its own). pub fn dumpBytes(p: *Pardes) ![]u8 { + return image(p, "dump"); +} + +/// The session as a byte dump (walk.Dump), gpa-owned: what a replica's join +/// streams, its blobs in place. +pub fn byteDump(p: *Pardes) ![]u8 { return dumpWith(p, null); } +/// The session as the image of one dump labelled `name` (Db.zig), its +/// roots by name: the core, its 9P mounts, which of its panes' files were +/// on disk, its theme's name and the views not live (see `Session`). +pub fn image(p: *Pardes, name: []const u8) ![]u8 { + const gpa = p.gpa; + var buf: std.Io.Writer.Allocating = .init(gpa); + defer buf.deinit(); + var db = try walk.Mem.init(std.Io.failing, .{ .buffer = &buf, .file_id = 0 }); + var w: walk.Put = .{ .gpa = gpa }; + defer w.deinit(); + const mounts: []const filesystem.Mount = p.fs.mounts.items; + var on_disk: OnDisk = @splat(false); + var panes: u64 = 0; + for (p.panes, &on_disk) |slot, *on| if (slot) |pane| { + on.* = onDisk(pane); + panes += 1; + }; + const theme: []const u8 = colors.themes[@min(p.settings.theme, colors.themes.len - 1)].name; + const others = try views.dumped(p, gpa); + defer { + for (others) |o| gpa.free(o.panes); + gpa.free(others); + } + const kept: []const views.Dumped = others; + try db.runContext(struct { + w: *walk.Put, + p: *Pardes, + mounts: *const []const filesystem.Mount, + on_disk: *const OnDisk, + theme: *const []const u8, + others: *const []const views.Dumped, + pub fn run(ctx: @This(), cursor: *walk.Mem.Cursor(.read_write)) !void { + const root = try walk.Mem.HashMap(.read_write).init(cursor.*); + try ctx.w.member(root, "core", Pardes, ctx.p); + try ctx.w.member(root, "mounts", []const filesystem.Mount, ctx.mounts); + try ctx.w.member(root, "on_disk", OnDisk, ctx.on_disk); + try ctx.w.member(root, "theme", []const u8, ctx.theme); + try ctx.w.member(root, "views", []const views.Dumped, ctx.others); + } + }{ .w = &w, .p = p, .mounts = &mounts, .on_disk = &on_disk, .theme = &theme, .others = &kept }); + return pardes.Db.image(gpa, name, buf.written(), w.blobs.items, panes); +} + /// A dump for a screen-state replica's join (src/replica.zig): its blobs' /// bytes left out and noted in `deferred` (they are the session's, alive /// while pinned: memory.zig `pin`), its terminals' emulators left out (the @@ -213,6 +248,19 @@ fn dumpWith(p: *Pardes, deferred: ?*std.ArrayListUnmanaged(walk.Deferred)) ![]u8 /// Restore asks before it warns about unsaved text or replaces anything. /// Why not is left in `why`, ended by a 0. pub fn check(gpa: std.mem.Allocator, bytes: []const u8, why: []u8) !void { + if (pardes.Db.isImage(bytes)) { + const r = pardes.Db.Read.open(gpa, bytes, null) catch |err| { + const said = std.fmt.bufPrint(why[0 .. why.len - 1], "{s}", .{switch (err) { + error.NoDump => "it holds no dump", + error.OutOfMemory => "out of memory", + else => "it is no dump of pardes's", + }}) catch ""; + why[said.len] = 0; + return err; + }; + r.close(); + return; + } var l = SessionLoad.init(gpa, bytes) catch |err| { const said = std.fmt.bufPrint(why[0 .. why.len - 1], "{s}", .{switch (err) { error.BadDump => "it does not begin as one", @@ -235,6 +283,7 @@ pub fn load(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*s /// `load`, with which panes' files were on disk when it was dumped. fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*std.ArrayList(u8), on_disk: ?*OnDisk) !*Pardes { + if (pardes.Db.isImage(bytes)) return loadImage(gpa, opts, bytes, notes, on_disk); const p = try Pardes.create(gpa, opts); var l = SessionLoad.init(gpa, bytes) catch |err| { p.deinit(); @@ -304,6 +353,70 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: return p; } +/// `loadKnowing` of an image (Db.zig): its roots read by name (walk.Get), +/// as the byte dump's are read in order. +fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*std.ArrayList(u8), on_disk: ?*OnDisk) !*Pardes { + const r = pardes.Db.Read.open(gpa, bytes, null) catch |err| return if (err == error.OutOfMemory) err else error.BadDump; + defer r.close(); + const root = r.root(); + const core_at = (try walk.Get.member(root, "core")) orelse return error.BadDump; + const p = try Pardes.create(gpa, opts); + var l: walk.Get = .init(gpa); + defer l.deinit(); + l.blobs = r.blobs() catch null; + // A load that fails leaves nothing: what it read is freed, and the + // core with it, its fields never torn down one by one. + errdefer { + l.rollback(); + p.fs.deinit(gpa); + gpa.destroy(p); + } + l.allocs = .{ .image = p.image_gpa, .pdf = p.pdf_gpa, .terminal = terminal_gpa }; + try l.into(Pardes, core_at, p); + const read = l.made.items.len; + const mounts: []const filesystem.Mount = if (try walk.Get.member(root, "mounts")) |c| try l.get([]const filesystem.Mount, c) else &.{}; + defer { + for (mounts) |m| { + gpa.free(m.name); + gpa.free(m.dial); + } + gpa.free(mounts); + // Freed here: no rollback of them. + l.made.shrinkRetainingCapacity(read); + } + const was: OnDisk = if (try walk.Get.member(root, "on_disk")) |c| try l.get(OnDisk, c) else @splat(false); + if (on_disk) |out| out.* = was; + const theme: []const u8 = if (try walk.Get.member(root, "theme")) |c| try l.get([]const u8, c) else ""; + defer gpa.free(theme); + p.settings.theme = for (colors.themes, 0..) |t, i| { + if (std.mem.eql(u8, t.name, theme)) break i; + } else if (p.settings.theme < colors.themes.len) p.settings.theme else 0; + for (mounts) |m| { + const existing = for (p.fs.mounts.items) |e| { + if (std.mem.eql(u8, e.name, m.name)) break e; + } else null; + if (existing) |e| { + if (!std.mem.eql(u8, e.dial, m.dial)) return error.MountConflict; + continue; + } + p.fs.mount(gpa, m.name, m.dial) catch |err| l.note("mount {s}: {t}", .{ m.name, err }); + } + if (l.notes.items.len > 0) { + dropMissing(p); + for (p.panes) |slot| if (slot) |pane| try ensureKind(p, pane); + if (notes) |n| try n.appendSlice(gpa, l.notes.items); + } + // The views not live, last: what it moves into the core is never + // rolled back from under it, nothing after it failing. + const at = l.made.items.len; + const others: []const views.Dumped = if (try walk.Get.member(root, "views")) |c| try l.get([]const views.Dumped, c) else &.{}; + try views.undumped(p, others); + for (others) |o| gpa.free(o.panes); + gpa.free(others); + l.made.shrinkRetainingCapacity(at); + return p; +} + /// A pane that is none of its kinds (a terminal kept slim, or one another /// build's dump could not give): a terminal, a new emulator for its shell. fn ensureKind(p: *Pardes, pane: *pardes.panes.Pane) !void { @@ -349,7 +462,7 @@ pub fn restore(p: *Pardes, bytes: []const u8, from: []const u8) !*Pardes { pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8) !*Pardes { pardes.tape.startFromEnv(); const taped = pardes.tape.enter(null, .{ .init_from_dump = .{ .opts = opts, .bytes = bytes } }); - const p = (if (std.mem.startsWith(u8, bytes, Handover.carried_magic)) carriedWindow(gpa, opts, bytes) else loadAndRevive(gpa, opts, bytes, null, null)) catch |err| { + const p = (if (Handover.carries(bytes)) carriedWindow(gpa, opts, bytes) else loadAndRevive(gpa, opts, bytes, null, null)) catch |err| { pardes.tape.leave(null, taped); return err; }; @@ -375,16 +488,6 @@ pub fn resumeFromDump(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, return loadAndRevive(gpa, opts, bytes, null, kept); } -/// Where an upgrade leaves its dump: the DumpDir (a relative Restore finds -/// it there by name), as `pardes-upgrade-<pid>.dump`; never $PARDES_DUMP, -/// which is a Dump's. -pub fn upgradePath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { - var dir_buf: [900]u8 = undefined; - const dir = directory(&dir_buf, dir_setting) orelse return null; - _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; - return std.fmt.bufPrintSentinel(buf, "{s}/pardes-upgrade-{d}.dump", .{ dir, std.c.getpid() }, 0) catch null; -} - fn loadAndRevive(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, previous: ?*Pardes, kept: ?*const [MAX_PANES]bool) !*Pardes { var notes: std.ArrayList(u8) = .empty; defer notes.deinit(gpa); @@ -711,7 +814,7 @@ test "an upgraded session's dump keeps its views and its running terminal as the try std.testing.expect(r.panes[0].?.terminal.?.vt.screens.active_key == .primary); } -test "a session read by name, field by field as another build reads it, is the same session" { +test "a session's image, read by name as every load reads it, is the same session, and dumps to the same bytes again" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); @@ -720,6 +823,26 @@ test "a session read by name, field by field as another build reads it, is the s try std.testing.expect(p.executeBuiltinLine(p.active, "Zerox")); const bytes = try dumpBytes(p); defer gpa.free(bytes); + var notes: std.ArrayList(u8) = .empty; + defer notes.deinit(gpa); + const q = try load(gpa, p.opts, bytes, ¬es); + defer q.deinit(); + try std.testing.expectEqualStrings("", notes.items); + try std.testing.expectEqual(walk.digest(Pardes, p), walk.digest(Pardes, q)); + const again = try dumpBytes(q); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, bytes, again); +} + +test "a session's byte dump read by name, field by field as another build reads it, is the same session" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\n"); + _ = ctlfs.pane.spliceBody(p, pane, 0, 0, "unsaved ").?; + try std.testing.expect(p.executeBuiltinLine(p.active, "Zerox")); + const bytes = try byteDump(p); + defer gpa.free(bytes); const q = try Pardes.create(gpa, p.opts); defer q.deinit(); var l = try SessionLoad.init(gpa, bytes); |
