diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/abi.zig | 29 | ||||
| -rw-r--r-- | src/abi_hash.zig | 9 | ||||
| -rw-r--r-- | src/host/Console.zig | 308 | ||||
| -rw-r--r-- | src/host/Host.zig | 241 | ||||
| -rw-r--r-- | src/host/Sessions.zig | 1069 | ||||
| -rw-r--r-- | src/host/library.zig | 45 | ||||
| -rw-r--r-- | src/host/memory.zig | 108 | ||||
| -rw-r--r-- | src/host/probe.zig | 2 | ||||
| -rw-r--r-- | src/host/root.zig | 50 | ||||
| -rw-r--r-- | src/host/script.zig | 54 | ||||
| -rw-r--r-- | src/host/timeline.zig | 331 | ||||
| -rw-r--r-- | src/layout.zig | 30 | ||||
| -rw-r--r-- | src/sketch/root.zig | 26 | ||||
| -rw-r--r-- | src/sketch/web.zig | 2 |
14 files changed, 1928 insertions, 376 deletions
diff --git a/src/abi.zig b/src/abi.zig index af106af..f0abdb3 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -5,11 +5,13 @@ //! tagged unions, `std.mem.Allocator`. Two rules keep reloads safe: //! - whatever outlives a call lives in host memory (host code is never //! unloaded, so host allocators and function pointers stay valid); -//! - `hash` covers the layout of every type here, and a host refuses a sketch -//! built against different definitions instead of misreading its memory. +//! - `hash` covers the layout of every type here and the compiler, backend +//! and mode, and a host refuses a sketch built against different +//! definitions or by another build instead of misreading its memory. //! //! Only `Event` and the reflected `Layout` are `extern`: they are written to disk. const std = @import("std"); +const builtin = @import("builtin"); pub const layout = @import("layout.zig"); pub const Key = @import("keys.zig").Key; @@ -776,6 +778,13 @@ pub const Info = struct { store: Layout, /// Console completions offered by the sketch. commands: []const []const u8 = &.{}, + /// What the sketch was built from: its repository's revision ("jj:<commit> + /// <change>", "git:<sha>[+dirty]", or nothing), then `build`. Each + /// stretch of a recorded session keeps it. + source: []const u8 = "", + /// Whether the host records sessions to a file (`App.Options.record`; + /// Debug builds do unless told otherwise). + record: bool = false, }; /// Which memory `sketch_defaults` fills. @@ -818,8 +827,16 @@ pub const Sketch = struct { }; }; -/// Layout hash of everything above. Changes whenever a shared type does. -pub const hash: u64 = blk: { +/// `layout_hash` and `build`: changes whenever a shared type does, or the +/// compiler, backend or optimize mode, since Zig's own calling convention +/// (`Host.VTable`, every `std.mem.Allocator`) differs between them. +/// `layout_hash` costs half a second of comptime, so build.zig has +/// `abi_hash.zig` compute it once per change of these files and hands it +/// over as the module `abi_hash`, instead of every sketch's compile doing it. +pub const hash: u64 = std.hash.Wyhash.hash(@import("abi_hash").layout, build); + +/// Hash of every shared type's name and layout. +pub const layout_hash: u64 = blk: { @setEvalBranchQuota(1_000_000); var h: u64 = 0; for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { @@ -828,6 +845,10 @@ pub const hash: u64 = blk: { break :blk h; }; +/// The compiler, backend and mode of this build, exported by libraries as +/// `sketch_build` so a host can say why it refuses one. +pub const build = builtin.zig_version_string ++ " " ++ @tagName(builtin.zig_backend) ++ " " ++ @tagName(builtin.mode); + test "vertex attributes and std140 checks come from the types" { const Vertex = extern struct { position: [2]f32, color: [4]u8, uv: [2]f32 }; const attrs = gpu.attributes(Vertex); diff --git a/src/abi_hash.zig b/src/abi_hash.zig new file mode 100644 index 0000000..9cd01cf --- /dev/null +++ b/src/abi_hash.zig @@ -0,0 +1,9 @@ +//! Prints `abi.layout_hash` as Zig source: build.zig runs this once per change +//! of the abi sources and hands the result to host and sketches as the module +//! `abi_hash`. +const std = @import("std"); +const abi = @import("abi"); + +pub fn main(init: std.process.Init) !void { + try std.Io.File.stdout().writeStreamingAll(init.io, std.fmt.comptimePrint("pub const layout: u64 = 0x{x};\n", .{abi.layout_hash})); +} diff --git a/src/host/Console.zig b/src/host/Console.zig index 0c44ea2..75da732 100644 --- a/src/host/Console.zig +++ b/src/host/Console.zig @@ -1,22 +1,23 @@ //! The developer console: a line editor, a short log, and the host commands -//! (snapshots, recordings, replay, field inspection). Lines the host does not -//! know go to the sketch's `command`. +//! (marks, clips, replay, sessions, field inspection). Lines the host does +//! not know go to the sketch's `command`. const Console = @This(); const std = @import("std"); const abi = @import("abi"); const Host = @import("Host.zig"); const fields = @import("fields.zig"); const memory = @import("memory.zig"); -const timeline = @import("timeline.zig"); +const Sessions = @import("Sessions.zig"); pub const panel_height = 144; pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, submit }; const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 }; const host_commands = [_][]const u8{ - "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", + "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", "marks", "clips", "play session", "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit", - "overlay timing", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats", + "overlay timing", "sessions", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats", + "export-session", "import", }; visible: bool = false, @@ -24,11 +25,34 @@ buffer: [96]u8 = @splat(0), len: usize = 0, cursor: usize = 0, lines: [5]Line = @splat(.{}), -snapshot: usize = 1, -recording: usize = 0, +/// The mark `save`, `load`, `diff` and `record` use when given none. +snapshot: Name = .of("1"), +/// The clip `record`, `play`, `seek` and `step` use when given none. +recording: Name = .of("0"), overlay_memory: bool = false, overlay_sound: bool = false, +pub const Name = struct { + bytes: [Sessions.max_name]u8 = undefined, + len: usize = 0, + + pub fn of(text_: []const u8) Name { + var n: Name = .{ .len = text_.len }; + @memcpy(n.bytes[0..text_.len], text_); + return n; + } + pub fn get(n: *const Name) []const u8 { + return n.bytes[0..n.len]; + } +}; + +/// A mark or clip name: a word of at most `Sessions.max_name` bytes. +fn nameOr(arg: ?[]const u8, default: *const Name) ![]const u8 { + const n = arg orelse return default.get(); + if (n.len > Sessions.max_name) return error.NameTooLong; + return n; +} + pub fn text(self: *const Console) []const u8 { return self.buffer[0..self.len]; } @@ -134,8 +158,9 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const const rest = words.rest(); if (eq(command, "help")) { - self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|<ms>"); - self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit"); + self.log("save|load|diff [MARK] snapshot MARK marks | record|play [CLIP] recording CLIP clips | stop | pause"); + self.log("step N (frames) | seek start|end|<ms> | sessions | play session S [at SECS] | export-session [S] FILE | import FILE"); + self.log("reset | get|set <field> [<value>] | overlay memory|sound | quit"); self.log("timing [on|off|frame|work|reset|stats] | overlay timing"); if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes."); return &.{}; @@ -172,69 +197,121 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const const path = arg orelse return error.ExpectedField; const leaf = host.state.layout.find(path) orelse return error.UnknownField; if (rest.len == 0) return error.ExpectedValue; - h.stop(now); + try stop(host); try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); } else if (eq(command, "quit") or eq(command, "exit")) { - h.stop(now); + try stop(host); host.quit = true; } else if (eq(command, "reset")) { - h.stop(now); + try stop(host); host.resetState(); self.log("Live state reset. Snapshots are kept."); - } else if (eq(command, "snapshot")) { - self.snapshot = try slot(arg orelse return error.ExpectedSlot, 1, memory.slot_count - 1); - } else if (eq(command, "recording")) { - self.recording = try slot(arg orelse return error.ExpectedSlot, 0, timeline.recording_count - 1); - } else if (eq(command, "save") or eq(command, "load")) { - const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; - if (eq(command, "load") and !h.bank.hasSnapshot(index)) return error.EmptySnapshot; - h.stop(now); - if (eq(command, "save")) { - h.bank.save(index); - self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index}); - } else { - try h.restore(index); - self.print("Loaded snapshot {d}.", .{index}); + } else if (eq(command, "snapshot") or eq(command, "recording")) { + const n = try nameOr(arg orelse return error.ExpectedName, &self.snapshot); + (if (eq(command, "snapshot")) &self.snapshot else &self.recording).* = .of(n); + } else if (eq(command, "save")) { + const n = try nameOr(arg, &self.snapshot); + try stop(host); + _ = try host.sessions.mark(n, .mark, host.live()); + self.print("Saved snapshot {s}.", .{n}); + } else if (eq(command, "load")) { + const n = try nameOr(arg, &self.snapshot); + const key = try loadMark(host, n); + defer key.free(host.gpa); + try stop(host); + try h.restore(key); + self.print("Loaded snapshot {s}.", .{n}); + } else if (eq(command, "record")) { + const n = try nameOr(arg, &self.recording); + const from = self.snapshot.get(); + try stop(host); + // An unused mark captures the current state; an existing one is + // restored, so several clips can branch from exactly those bytes. + const k = if (try host.sessions.findMark(from) == null) try host.sessions.mark(from, .mark, host.live()) else blk: { + const key = try loadMark(host, from); + defer key.free(host.gpa); + try h.restore(key); + break :blk try host.sessions.keyframe(.jump, host.live()); + }; + // The input held now is restored first in the clip (Host.restoredInput). + h.restored = true; + try host.sessions.startClip(n, k); + h.startRecording(); + self.recording = .of(n); + self.print("Started recording {s} from snapshot {s}.", .{ n, from }); + } else if (eq(command, "play") and arg != null and eq(arg.?, "session")) { + var more = std.mem.tokenizeAny(u8, rest, " \t"); + const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession; + var at: ?u64 = null; + if (more.next()) |word| { + if (!eq(word, "at")) return error.UnexpectedArgument; + const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition; + at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s); } - } else if (eq(command, "record") or eq(command, "play")) { - const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording; - if (eq(command, "play")) _ = try h.bank.get(index); - h.stop(now); - if (eq(command, "record")) try h.startRecording(index, self.snapshot, now, host.build) else try h.play(index, now); - self.recording = index; - self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot }); - if (eq(command, "play")) self.warnBuild(host, h.bank.recording(index)); + try stop(host); + return self.playSession(host, index, at, now); + } else if (eq(command, "play")) { + const n = try nameOr(arg, &self.recording); + try stop(host); + try loadClip(host, n); + try h.play(now); + self.recording = .of(n); + self.print("Playing recording {s}.", .{n}); + self.warnBuild(host); } else if (eq(command, "stop")) { - h.stop(now); + try stop(host); } else if (eq(command, "pause")) { if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; h.pause(now); } else if (eq(command, "step") or eq(command, "seek")) { const value = arg orelse return error.ExpectedPosition; - _ = try h.bank.get(if (h.mode == .live or h.mode == .recording) self.recording else h.selected); - if (h.mode == .recording) h.stop(now); - if (h.mode == .live) try h.play(self.recording, now); - const r = try h.bank.get(h.selected); - if (h.mode == .playing and h.cursor == 0) self.warnBuild(host, r); + if (h.mode == .live or h.mode == .recording) { + try stop(host); + try loadClip(host, self.recording.get()); + try h.play(now); + self.warnBuild(host); + } if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); if (eq(value, "start")) return h.seekCount(0); - if (eq(value, "end")) return h.seekCount(r.count); + if (eq(value, "end")) return h.seekCount(h.events.items.len); const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; return h.seekTime(ms *| std.time.ns_per_ms); } else if (eq(command, "diff")) { - const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; - if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot; - const diff = h.bank.compare(0, index); + const n = try nameOr(arg, &self.snapshot); + var arena: std.heap.ArenaAllocator = .init(host.gpa); + defer arena.deinit(); + const saved = try markState(host, arena.allocator(), n); + const diff = memory.compareKept(saved.layout, host.state.layout, host.live(), saved.bytes); if (diff.first) |first| { var buf: [96]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); first.leaf.name(first.offset, &w) catch {}; - self.print("Live vs snapshot {d}: {d} differing values, first {s}", .{ index, diff.count, w.buffered() }); - } else self.print("Live vs snapshot {d}: same", .{index}); + self.print("Live vs snapshot {s}: {d} differing values, first {s}", .{ n, diff.count, w.buffered() }); + } else self.print("Live vs snapshot {s}: same", .{n}); + } else if (eq(command, "sessions")) { + if (arg != null) return error.UnexpectedArgument; + try self.listSessions(host); + } else if (eq(command, "export-session")) { + const s = &host.sessions; + const first = arg orelse return error.ExpectedFile; + const index = if (rest.len == 0) s.session else std.fmt.parseInt(u64, first, 10) catch return error.InvalidSession; + const path = if (rest.len == 0) first else std.mem.trim(u8, rest, " \t"); + try s.exportSession(index, path); + self.print("Exported session {d} to {s}.", .{ index, path }); + } else if (eq(command, "import")) { + const path = arg orelse return error.ExpectedFile; + if (rest.len != 0) return error.UnexpectedArgument; + const s = &host.sessions; + const first = try s.import(path); + const n = try s.count(.sessions); + self.print("Imported {s} as session {d}..{d}; marks and clips are NAME@{s}.", .{ path, first, n - 1, std.fs.path.basename(path) }); + } else if (eq(command, "marks") or eq(command, "clips")) { + if (arg != null) return error.UnexpectedArgument; + try self.listNamed(host, eq(command, "marks")); } else { // Sketch commands edit state outside the recorded input. - h.stop(now); + try stop(host); switch (host.forward(self, line, now)) { .unknown => return error.UnknownCommand, .failed => return error.CommandFailed, @@ -251,8 +328,12 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), const width: f32 = @floatFromInt(host.canvas[0]); const h = &host.timeline; try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } }); - const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {d} | recording {d} (active {d}) | event {d} | {d}ms", .{ - host.name, h.mode, self.snapshot, self.recording, h.selected, h.cursor, h.position / std.time.ns_per_ms, + const s = &host.sessions; + const playing = h.mode == .playing or h.mode == .paused; + const frame = if (playing) (if (h.key) |k| k.frame else 0) + h.fed else s.frames; + const at = (if (playing) h.position else s.last_time -| s.first_time) / std.time.ns_per_s; + const status = try std.fmt.allocPrint(arena, "{s} | {t} | session {d} frame {d} ({d}:{d:0>2}) | mark {s} | clip {s} | rec {t}", .{ + host.name, h.mode, if (playing) h.session orelse s.session else s.session, frame, at / 60, at % 60, self.snapshot.get(), self.recording.get(), s.mode(), }); try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } }); for (&self.lines, 0..) |*line, i| { @@ -262,20 +343,133 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } }); } -/// A replay of a recording made by other code may diverge: say so. -fn warnBuild(self: *Console, host: *const Host, r: *const timeline.Recording) void { - if (r.build() != 0 and host.build != 0 and r.build() != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ."); +/// Where this run records, then the last sessions: index, start, frames, +/// stretches (loads), and how it ended. +fn listSessions(self: *Console, host: *Host) !void { + const s = &host.sessions; + switch (s.mode()) { + .file => self.print("recording to {s}", .{s.path}), + .memory => self.log("recording in memory (scripted run)"), + .off => return self.log("not recording (release build: .record = true collects)"), + } + const n = try s.count(.sessions); + var i = n -| 4; + while (i < n) : (i += 1) { + const m = try s.summary(i); + const secs = std.time.epoch.EpochSeconds{ .secs = m.started / std.time.ns_per_s }; + const day = secs.getEpochDay().calculateYearDay(); + const md = day.calculateMonthDay(); + const ds = secs.getDaySeconds(); + var end_buf: [32]u8 = undefined; + const end = if (i == s.session) "(this run)" else if (m.ended == 0) "(crashed)" else blk: { + const d = (m.ended -| m.started) / std.time.ns_per_s; + break :blk std.fmt.bufPrint(&end_buf, "{d}:{d:0>2}", .{ d / 60, d % 60 }) catch ""; + }; + self.print("{d}: {d:0>4}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2} builds {d} frames {d} {s} {s}", .{ i, day.year, md.month.numeric(), md.day_index + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), m.stretches, m.frames, end, m.from() }); + } +} + +/// Ends a clip being recorded or played: live from here. +fn stop(host: *Host) !void { + if (host.timeline.mode == .recording) try host.sessions.stopClip(); + host.timeline.stop(); +} + +/// The keyframe of the newest mark `n`, or of mark number K for "#K". +pub fn loadMark(host: *Host, n: []const u8) !Sessions.Loaded { + const s = &host.sessions; + const found = if (n.len > 1 and n[0] == '#') + try s.markAt(std.fmt.parseInt(u64, n[1..], 10) catch return error.InvalidName) + else + try s.findMark(n) orelse return error.EmptySnapshot; + return s.load(found.session, found.key); +} + +/// Mark `n`'s State in today's layout (`arena`'s), and the layout it was +/// taken in: compare them over the leaves migration kept (`memory.compareKept`). +pub fn markState(host: *Host, arena: std.mem.Allocator, n: []const u8) !struct { bytes: []u8, layout: memory.Layout } { + const key = try loadMark(host, n); + defer key.free(host.gpa); + const bytes = try arena.alignedAlloc(u8, .fromByteUnits(memory.page), host.state.layout.size); + const layout = try memory.restore(arena, key.layout, key.state, host.state.layout, bytes, host.timeline.defaults); + return .{ .bytes = bytes, .layout = layout }; +} + +/// Makes clip `n` the one the timeline plays: its keyframe and frames. +fn loadClip(host: *Host, n: []const u8) !void { + const s = &host.sessions; + const clip = try s.findClip(n) orelse return error.EmptyRecording; + const key = try s.load(clip.session, clip.key); + errdefer key.free(host.gpa); + var events: std.ArrayList(abi.Event) = .empty; + errdefer events.deinit(host.gpa); + // A clip a crash left open ends where its session does. + const end = if (clip.end != 0) clip.end else (try s.summary(clip.session)).frames; + try s.events(clip.session, key.batch, clip.start, end, &events); + host.timeline.load(key, events); +} + +/// Plays session `index` from its start, or paused `at` nanoseconds into +/// it: from the newest keyframe before then, replayed up to it. +fn playSession(self: *Console, host: *Host, index: u64, at: ?u64, now: u64) ![]const abi.Event { + const s = &host.sessions; + const h = &host.timeline; + if (index == s.session) try s.commit(.none); + const sum = try s.summary(index); + if (sum.keys == 0) return error.EmptyRecording; + const t0 = (try s.keyAt(index, 0)).time; + const k = if (at) |t| try s.keyBefore(index, .time, t0 + t) orelse 0 else 0; + const key = try s.load(index, k); + errdefer key.free(host.gpa); + var events: std.ArrayList(abi.Event) = .empty; + errdefer events.deinit(host.gpa); + try s.events(index, key.batch, key.frame, sum.frames, &events); + var checks: @TypeOf(h.checks) = .empty; + errdefer checks.deinit(host.gpa); + for (k + 1..sum.keys) |j| { + const later = try s.keyAt(index, j); + try checks.append(host.gpa, .{ .frame = later.frame, .key = j, .observed = switch (later.why) { + .periodic, .mark, .before_reload, .exit => true, + else => false, + } }); + } + h.load(key, events); + h.session = index; + h.checks = checks; + try h.play(now); + self.print("Playing session {d} from frame {d}.", .{ index, key.frame }); + if (key.build != host.build or !eq(key.source, host.source)) self.print("session {d} frame {d} was built from {s}; replaying with {s}", .{ index, key.frame, key.source, host.source }); + if (at) |t| return h.seekTime((t0 + t) -| h.base); + return &.{}; +} + +/// A replay of a clip made by other code may diverge: say so. +fn warnBuild(self: *Console, host: *const Host) void { + const key = host.timeline.key orelse return; + if (key.build != 0 and host.build != 0 and key.build != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ."); +} + +/// The last marks or clips: index, name, session and frame. +fn listNamed(self: *Console, host: *Host, marks: bool) !void { + const s = &host.sessions; + const n = try s.count(if (marks) .marks else .clips); + if (n == 0) return self.log(if (marks) "No marks: save NAME makes one." else "No clips: record NAME makes one."); + var i = n -| 5; + while (i < n) : (i += 1) { + const e = if (marks) try s.markAt(i) else try s.clipAt(i); + const key = try s.load(e.session, e.key); + defer key.free(host.gpa); + const label = e.name(); + if (marks) { + self.print("#{d} {s}: session {d} frame {d}", .{ i, label, e.session, key.frame }); + } else self.print("#{d} {s}: session {d} frames {d}..{d}", .{ i, label, e.session, e.start, e.end }); + } } fn eq(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } -fn slot(value: []const u8, min: usize, max: usize) !usize { - const index = std.fmt.parseInt(usize, value, 10) catch return error.InvalidSlot; - if (index < min or index > max) return error.InvalidSlot; - return index; -} test "line editing, completion and submission" { var c: Console = .{}; diff --git a/src/host/Host.zig b/src/host/Host.zig index 035a004..1a75b2a 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -9,7 +9,6 @@ const abi = @import("abi"); const memory = @import("memory.zig"); const playback = @import("timeline.zig"); const Timeline = playback.Timeline; -const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); const Gpu = @import("gpu"); @@ -20,6 +19,7 @@ const Presentation = @import("Presentation.zig"); const timing_marker = @import("timing_marker.zig"); const Control = @import("control.zig").Control; const Library = @import("library.zig").Library; +const Sessions = @import("Sessions.zig"); const Watch = @import("library.zig").Watch; pub const Options = struct { @@ -27,8 +27,12 @@ pub const Options = struct { library: ?[]const u8 = null, /// Local 9P control socket, opt-in. ninep: ?[]const u8 = null, - /// State file; recordings go next to it with an `.inputs` suffix. - state: []const u8 = "sketch.state", + /// State file; the sessions database goes next to it, `<name>.xitdb` + /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.state` + /// (`~/.local/share` without it), for a shipped game. + state: []const u8 = "", + /// Playing a script: from fresh state, sessions go to memory only. + script: bool = false, /// Offscreen video, silent audio, no vsync: for scripts and CI. headless: bool = false, /// Forget the state file's contents: scripts start from a known place. @@ -74,8 +78,9 @@ store: memory.StoreFile, /// Images and buffers the sketch made (`newImage`, `decodeImage`, /// `newBuffer`): Session holds their handles, so they go when it resets. made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList(abi.Buffer) = .empty } = .{}, -recordings: []align(memory.page) u8, timeline: Timeline, +/// This run's session and the ones before it (Sessions.zig). +sessions: Sessions, console: Console = .{}, timing: Timing = .{}, timing_atlas: overlay.TimingAtlas = .{}, @@ -83,12 +88,17 @@ sketch: abi.Sketch, library: ?Library = null, watch: ?Watch = null, reloads: usize = 0, -/// Identifies the running build of the sketch (a hash of its library or -/// executable file): recordings carry it, and `play` warns on a mismatch. +/// Identifies the running build of the sketch (its library or executable +/// file's inode, size and modification time): sessions' stretches carry it, +/// and `play` warns on a mismatch. build: u64 = 0, +/// The state file's path when the host chose it (`Options.state`), `gpa`'s. +state_path: []const u8 = "", /// Copies of the sketch's info strings, replaced on every load. info_arena: std.heap.ArenaAllocator, name: []const u8 = "", +/// The sketch's `Info.source`, for the session's stretches. +source: []const u8 = "", completions: []const []const u8 = &.{}, /// Frame lifetime: sketch scratch and this frame's commands. frame_arena: std.heap.ArenaAllocator, @@ -114,7 +124,8 @@ exported: u64 = 0, dialog: Dialog = .{}, control: ?*Control = null, -pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { +pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, given: Options, linked: ?abi.Sketch) !void { + var options = given; if (options.headless) { // Overriding: a plain hint loses to the environment, and a user's // SDL_VIDEO_DRIVER=wayland would open real windows during tests. @@ -128,7 +139,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std var library: ?Library = null; const sketch = linked orelse blk: { const path = options.library orelse return error.NoSketch; - library = try Library.openCopy(io, path, scratchDir(environ), 0); + library = try Library.openFresh(io, path, scratchDir(environ), 0); break :blk library.?.sketch; }; errdefer if (library) |*l| l.close(); @@ -158,11 +169,18 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std // Colors carry alpha: fills blend, as they do on the web. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); + var data_buf: [std.fs.max_path_bytes]u8 = undefined; + const state_path = if (given.state.len > 0) "" else blk: { + const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."}); + const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.state", .{ data, info.name, info.name }); + errdefer gpa.free(path); + try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?); + break :blk path; + }; + errdefer gpa.free(state_path); + if (state_path.len > 0) options.state = state_path; var state = try memory.StateFile.open(gpa, options.state); errdefer state.close(); - var inputs_buf: [std.fs.max_path_bytes]u8 = undefined; - const recordings = try mapRecordings(try std.mem.print(&inputs_buf, "{s}.inputs", .{options.state})); - errdefer std.posix.munmap(recordings); var store_buf: [std.fs.max_path_bytes]u8 = undefined; var store = memory.StoreFile.open(gpa, try std.mem.print(&store_buf, "{s}.store", .{options.state}), options.fresh) catch |err| { if (err == error.StoreInUse) std.log.err("{s}.store is open in another process", .{options.state}); @@ -184,15 +202,16 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .state = state, .session = .init(gpa), .store = store, - .recordings = recordings, .timeline = undefined, + .sessions = .{ .gpa = gpa, .io = io }, .sketch = sketch, .library = library, + .state_path = state_path, .info_arena = .init(gpa), .frame_arena = .init(gpa), .input = .{ .exporting = options.export_to != null }, }; - self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; + self.timeline = .{ .gpa = gpa, .state = &self.state, .defaults = sketch.defaults }; self.painter.images = &self.images; if (gpu) |device| self.passes = .init(gpa, device); if (options.profile_gpu) if (self.passes) |*g| { @@ -205,13 +224,14 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std const size = options.size orelse [2]u32{ info.width, info.height }; self.setCanvas(size[0], size[1]); _ = c.SDL_StartTextInput(self.window); - self.build = fileHash(options.library orelse "/proc/self/exe"); + self.build = fileId(io, options.library orelse "/proc/self/exe"); try self.adopt(sketch); - if (options.fresh) { - self.state.header().used = 0; - @memset(self.recordings, 0); - self.resetState(); - } + self.openSessions(info.record); + // Before --fresh: it never touches the history. + if (importSnapshots(&self.state, &self.sessions)) |n| { + if (n > 0) self.print("{d} snapshots of {s} are marks now", .{ n, options.state }); + } else |err| self.print("snapshots of {s} kept in it: {t}", .{ options.state, err }); + if (options.fresh) self.resetState(); if (!options.headless and options.export_to == null) { self.presentation = Presentation.init(gpa, self.window) catch null; if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"}); @@ -219,6 +239,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std } pub fn deinit(self: *Host) void { + self.sessions.close(self.live(), wallClock(self.io)); if (self.control) |control| control.deinit(); self.dialog.deinit(); if (self.watch) |w| w.deinit(); @@ -238,7 +259,7 @@ pub fn deinit(self: *Host) void { std.posix.munmap(entry.value_ptr.*); } self.files.deinit(self.gpa); - std.posix.munmap(self.recordings); + self.timeline.deinit(); self.session.deinit(self.gpa); self.store.close(); self.made.images.deinit(self.gpa); @@ -247,6 +268,7 @@ pub fn deinit(self: *Host) void { self.pending.deinit(self.gpa); self.frame_arena.deinit(); self.info_arena.deinit(); + self.gpa.free(self.state_path); if (self.library) |*l| l.close(); c.SDL_Quit(); } @@ -282,7 +304,7 @@ pub fn run(self: *Host) !void { frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items); try self.frame(now); } - self.timeline.stop(c.SDL_GetTicksNS()); + self.timeline.stop(); } // Live animation uses the display clock, but a tick must not predate its input. @@ -325,8 +347,11 @@ pub fn frame(self: *Host, now: u64) !void { self.last_now = now; const h = &self.timeline; switch (h.mode) { - .playing => self.update(h.tick(now)), - .paused => {}, + .playing => { + self.sessions.away = true; + self.update(h.tick(now)); + }, + .paused => self.sessions.away = true, .live, .recording => { // One frame: what was routed since the last one, then its tick. // Recorded first, so `update` sees the times a replay will. @@ -334,12 +359,14 @@ pub fn frame(self: *Host, now: u64) !void { // An export's tick is 1/fps itself, not whole nanoseconds of it. if (self.options.export_to != null and dt != 0) tick.x = 1 / @as(f32, @floatFromInt(self.options.fps)); try self.pending.append(self.gpa, tick); - h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err}); + const why: ?Sessions.Why = if (self.sessions.frames == 0) .start else if (self.reloaded) .after_reload else if (self.jumped or self.sessions.away) .jump else null; + self.sessions.away = false; + self.sessions.frame(self.pending.items, self.live(), why) catch |err| self.print("session: {t}", .{err}); self.update(self.pending.items); }, } self.pending.clearRetainingCapacity(); - const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position, started); + const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.base + h.position, started); const ended = c.SDL_GetTicksNS(); self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work }); self.last_frame_end = ended; @@ -362,10 +389,42 @@ pub fn update(self: *Host, events: []const abi.Event) void { self.started = false; const ctx = self.context(); self.sketch.update(&ctx, self.live().ptr); + if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync(); } self.input.events = &.{}; } +/// After a replayed frame of a past session: at each keyframe it reaches, +/// live state is compared with the keyframe (over the leaves migration +/// kept), any difference said, and the keyframe restored. +fn resync(self: *Host) void { + const h = &self.timeline; + h.fed += 1; + const session = h.session orelse return; + const reached = h.key.?.frame + h.fed; + while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) { + const check = h.checks.items[h.next_check]; + h.next_check += 1; + if (check.frame < reached) continue; + const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err }); + defer key.free(self.gpa); + var arena: std.heap.ArenaAllocator = .init(self.gpa); + defer arena.deinit(); + const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return; + const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err }); + if (check.observed) { + const diff = memory.compareKept(from, self.state.layout, self.live(), saved); + if (diff.first) |first| { + var buf: [96]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + first.leaf.name(first.offset, &w) catch {}; + self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() }); + } + } + @memcpy(self.live(), saved); + } +} + /// After live state was restored from a snapshot: the pointer, buttons and /// keys tracked so far belong to other bytes, so they start over. A new /// recording then begins with events that bring back what is held now, so @@ -380,7 +439,7 @@ fn restoredInput(self: *Host, now: u64) !void { self.input.mouse_y = 0; self.input.buttons = 0; self.input.keys = .empty; - if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return; + if (h.mode != .recording) return; var seed: std.ArrayList(abi.Event) = .empty; defer seed.deinit(self.gpa); if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y }); @@ -636,12 +695,17 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { defer zone.end(); const replay = self.console.execute(self, line, now) catch |err| { // The sketch has printed its own error already. - if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); + if (err == error.NotRecording) { + self.console.log("Not recording (a release build: .record = true collects): no marks or clips."); + } else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); if (self.timeline.restored) self.jumped = true; try self.restoredInput(now); return err; }; - if (self.timeline.restored or movesState(line)) self.jumped = true; + if (self.timeline.restored or movesState(line)) { + self.jumped = true; + self.sessions.noteLine(line); + } try self.restoredInput(now); if (self.timeline.mode == .paused) self.update(replay); } @@ -651,7 +715,7 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { fn movesState(line: []const u8) bool { var words = std.mem.tokenizeAny(u8, line, " \t"); const verb = words.next() orelse return false; - const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" }; + const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit", "sessions", "marks", "clips", "export-session", "import" }; for (still) |w| if (std.mem.eql(u8, verb, w)) return false; return true; } @@ -684,13 +748,16 @@ pub fn reload(self: *Host) !void { /// Replaces the running sketch with the library at `path`, keeping state. pub fn load(self: *Host, path: []const u8) !void { - var library = try Library.openCopy(self.io, path, scratchDir(self.environ), self.reloads + 1); + var library = try Library.openFresh(self.io, path, scratchDir(self.environ), self.reloads + 1); errdefer library.close(); + // The State in the layout it is leaving, before migration drops any of it. + if (self.sessions.mode() != .off) _ = self.sessions.keyframe(.before_reload, self.live()) catch |err| self.print("session: {t}", .{err}); try self.adopt(library.sketch); if (self.library) |*old| old.close(); self.library = library; self.reloads += 1; - self.build = fileHash(path); + self.build = fileId(self.io, path); + self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() }) catch |err| self.print("session: {t}", .{err}); self.print("reload {d}: {s}", .{ self.reloads, path }); } @@ -704,10 +771,12 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { _ = self.info_arena.reset(.retain_capacity); const arena = self.info_arena.allocator(); self.name = try arena.dupe(u8, info.name); + self.source = try arena.dupe(u8, info.source); const completions = try arena.alloc([]const u8, info.commands.len); for (completions, info.commands) |*to, from| to.* = try arena.dupe(u8, from); self.completions = completions; self.sketch = sketch; + self.timeline.defaults = sketch.defaults; self.reloaded = true; switch (adoption) { .unchanged => {}, @@ -868,12 +937,53 @@ fn consoleKey(e: abi.Event) ?Console.Key { }; } -/// A hash of a file's bytes; 0 when it cannot be read. -fn fileHash(path: []const u8) u64 { - const bytes = memory.mapReadOnly(path); - if (bytes.len == 0) return 0; - defer std.posix.munmap(bytes); - return std.hash.Wyhash.hash(0, bytes) | 1; +/// Starts this run's session (Sessions.zig): in a file beside the state +/// file when the build records, in memory for a script from fresh state, +/// nowhere for an export. A database that cannot be opened is said, and +/// the run goes on unrecorded. +fn openSessions(self: *Host, record: bool) void { + const o = self.options; + const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else if (record) .file else .off; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const stem = if (std.mem.endsWith(u8, o.state, ".state")) o.state[0 .. o.state.len - ".state".len] else o.state; + const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{stem}) catch "sketch.xitdb"; + const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() }; + self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: { + self.print("not recording: {s}: {t}", .{ path, err }); + break :blk .{ .gpa = self.gpa, .io = self.io }; + }; + if (o.headless) return; + switch (self.sessions.mode()) { + .file => self.print("recording to {s}", .{path}), + .memory => {}, + .off => if (o.export_to == null) self.print("not recording (release build: .record = true collects)", .{}), + } +} + +/// Snapshots of a state file from before sessions become marks "1".."7", +/// then the file holds live state only. While nothing records, they stay. +fn importSnapshots(state: *memory.StateFile, sessions: *Sessions) !usize { + if (state.slots == 1 or sessions.mode() == .off) return 0; + var n: usize = 0; + for (1..state.slots) |i| if (state.used(i)) { + _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, state.slot(i)); + n += 1; + }; + try state.dropSnapshots(); + return n; +} + +fn wallClock(io: std.Io) u64 { + return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds)); +} + +/// Identifies the file at `path` without reading it (a Debug library is tens +/// of megabytes): a hash of its inode, size and modification time; 0 when +/// there is none. A build replaces the file, so each build gets a new one. +fn fileId(io: std.Io, path: []const u8) u64 { + const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return 0; + const id = [3]u64{ stat.inode, stat.size, @truncate(@as(u96, @bitCast(stat.mtime.nanoseconds))) }; + return std.hash.Wyhash.hash(0, std.mem.asBytes(&id)) | 1; } fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { @@ -1123,3 +1233,60 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 }); try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data")); } + +test "a state file's snapshots from before sessions become marks, and the file one slot" { + const State = extern struct { v: u32 = 0 }; + const D = struct { + fn f(_: abi.Memory, p: [*]u8) callconv(.c) void { + @as(*State, @ptrCast(@alignCast(p))).* = .{}; + } + }; + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path}); + // An eight-slot SKETCH02 file, slots 0, 1 and 3 used: built from a new + // one-slot file's header. + { + var file = try memory.StateFile.open(gpa, path); + defer file.close(); + _ = try file.adopt(gpa, abi.layout.of(State, .state), D.f); + } + const one = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited); + defer gpa.free(one); + const stride = memory.page; + const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride); + defer gpa.free(old); + @memset(old, 0); + @memcpy(old[0..memory.header_len], one[0..memory.header_len]); + const h: *memory.Header = @ptrCast(@alignCast(old.ptr)); + h.magic = memory.file_magic_v2; + h.used = 0b1011; + for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old }); + + var state = try memory.StateFile.open(gpa, path); + defer state.close(); + try std.testing.expectEqual(memory.old_slot_count, state.slots); + var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.layoutBytes() }, 0); + defer sessions.deinit(); + try std.testing.expectEqual(@as(usize, 2), try importSnapshots(&state, &sessions)); + for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| { + const m = (try sessions.findMark(&.{@intCast(want[0])})).?; + const key = try sessions.load(m.session, m.key); + defer key.free(gpa); + try std.testing.expectEqual(Sessions.Why.import, key.why); + try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little)); + } + try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2")); + // One slot now, live state kept, and it reopens so. + try std.testing.expectEqual(@as(usize, 1), state.slots); + try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.slot(0)[0..4], .little)); + var again = try memory.StateFile.open(gpa, path); + defer again.close(); + try std.testing.expectEqualStrings(&memory.file_magic, &again.header().magic); + try std.testing.expectEqual(@as(usize, 1), again.slots); + try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, again.slot(0)[0..4], .little)); +} diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig new file mode 100644 index 0000000..751961d --- /dev/null +++ b/src/host/Sessions.zig @@ -0,0 +1,1069 @@ +//! Every run of a sketch, recorded: one xitdb database per sketch, beside +//! its state file, holding an append-only log of the frames live `update` +//! was fed, and the State at the moments that matter (keyframes). Nothing +//! in it is ever overwritten: marks and clips are names pointing into it. +//! +//! root = map { +//! version 1 +//! sessions list of session, one a run +//! marks list of { name, session, key }: a named keyframe (the newest of a name wins) +//! clips list of { name, session, key, start, end }: frames start..end of a +//! session, played from keyframe `key`; `end` 0 while recording +//! } +//! session = map { +//! started wall-clock ns at open ended ns at a clean exit, else 0 +//! from "" or where it came from ("import <file>") +//! stretches list of { frame, build, source, layout }: one a load (start, reloads); +//! `layout` is the state file's header (memory.readLayout reads it) +//! batches list of bytes: a little-endian u64, the first frame's index, then +//! whole frames of raw `abi.Event`s, each frame ending with its tick +//! keys list of { frame, batch, stretch, why, time, state, line }: the +//! State before frame `frame` is fed, in stretch `stretch`'s layout; +//! `batch` is where reading frames from it starts +//! frames frames committed +//! } +//! +//! One transaction (`commit`) a second of session time, and at once for a +//! reload, a mark, a clip's start or end, and exit: a crash loses less than +//! a second of play; fsync only at exit and for a mark. A file a crash or +//! power loss tore opens at its last whole commit (`mend`); a clean exit +//! compacts one that commits left past twice its contents (`close`). +const Sessions = @This(); +const std = @import("std"); +const xitdb = @import("xitdb"); +const abi = @import("abi"); + +pub const Disk = xitdb.Database(.buffered_file, u64); +pub const Memory = xitdb.Database(.memory, u64); + +/// `file` for interactive runs of a build that records, `memory` for a +/// scripted run from fresh state (time travel, nothing on disk), `off` +/// otherwise (an export, a release build). +pub const Mode = enum { off, memory, file }; +pub const Why = enum(u64) { start, periodic, jump, before_reload, after_reload, mark, exit, import }; + +/// Pending frames are committed once they span a second of session time +/// (less a millisecond: 60 ticks of a 60 Hz clock that rounds down are one). +pub const commit_ns: u64 = std.time.ns_per_s - std.time.ns_per_ms; +/// A keyframe at least this often while the State changes. +pub const periodic_ns: u64 = 60 * std.time.ns_per_s; +/// Mark and clip names: no spaces, at most this long. +pub const max_name = 32; +/// A memory database (a scripted run's) stops recording at this size: ten +/// hours or more of play at 60 Hz. What it holds stays readable. +pub const memory_max: u64 = 256 << 20; + +pub const K = enum(u64) { version = 1, sessions, marks, clips, started, ended, from, stretches, batches, keys, frames, frame, build, source, layout, batch, stretch, why, time, state, line, name, session, key, start, end }; +fn key(k: K) u64 { + return @intFromEnum(k); +} + +pub const Stretch = struct { frame: u64 = 0, build: u64, source: []const u8, layout: []const u8 }; + +const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, state: []u8, line: []u8 }; + +gpa: std.mem.Allocator, +/// Files and the wall clock; a memory database runs on `std.Io.failing`. +io: std.Io, +db: union(Mode) { off, memory: Memory, file: Disk } = .off, +file: ?std.Io.File = null, +/// The database's write buffer, an allocation of its own: the database +/// points at it. +buffer: ?*std.Io.Writer.Allocating = null, +/// The database's path (file mode), owned. +path: []const u8 = "", +/// This run's index in `sessions`. +session: u64 = 0, +/// Frames logged, committed or not, and committed. +frames: u64 = 0, +committed: u64 = 0, +/// This session's committed batches, its stretches and its keyframes +/// (queued ones too). +batches: u64 = 0, +stretches: u64 = 0, +keys: u64 = 0, +/// The frames since the last commit, as the batch they become. +batch: std.ArrayList(u8) = .empty, +/// The first pending frame's tick. +batch_time: u64 = 0, +/// The first and latest event time logged: times never go back. +first_time: u64 = 0, +last_time: u64 = 0, +/// The last keyframe's time, stretch and bytes' hash. +key_time: u64 = 0, +key_stretch: u64 = 0, +key_hash: u64 = 0, +queued: std.ArrayList(Keyframe) = .empty, +/// The clip being recorded, an index into `clips`. +recording: ?u64 = null, +/// State may have changed other than by a logged live frame (a replay ran): +/// the next live frame starts with a keyframe. +away: bool = false, +/// A memory database reached `memory_max`: nothing more is logged. +full: bool = false, +/// The console line that last changed State, for the next keyframe. +line: [256]u8 = undefined, +line_len: usize = 0, + +/// Opens the database at `path` (file mode: created with its directory when +/// missing; one a crash or power loss tore is opened at its last whole +/// commit (`mend`); one still refused is renamed aside, never deleted) and +/// starts this run's session in it. +pub fn open(gpa: std.mem.Allocator, io: std.Io, want: Mode, path: []const u8, first: Stretch, started: u64) !Sessions { + var s: Sessions = .{ .gpa = gpa, .io = io }; + if (want == .off) return s; + errdefer s.deinit(); + const buffer = try gpa.create(std.Io.Writer.Allocating); + buffer.* = .init(gpa); + s.buffer = buffer; + switch (want) { + .off => unreachable, + .memory => s.db = .{ .memory = try Memory.init(std.Io.failing, .{ .buffer = buffer, .file_id = 0, .max_size = memory_max }) }, + .file => { + s.path = try gpa.dupe(u8, path); + const cwd = std.Io.Dir.cwd(); + if (std.fs.path.dirname(path)) |dir| try cwd.createDirPath(io, dir); + var aside = false; + while (true) { + const file = try cwd.createFile(io, path, .{ .read = true, .truncate = false }); + if (Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false })) |db| { + s.db = .{ .file = db }; + s.file = file; + break; + } else |err| { + switch (err) { + error.InvalidDatabase, error.InvalidVersion, error.InvalidHashSize, error.TruncatedDatabase, error.InvalidEnumTag, error.EndOfStream => {}, + else => { + file.close(io); + return err; + }, + } + if (mend(io, file, buffer)) |db| { + s.db = .{ .file = db }; + s.file = file; + std.log.warn("{s} was torn after its last whole commit: opened at it", .{path}); + break; + } + file.close(io); + if (aside) return err; + aside = true; + var buf: [std.fs.max_path_bytes + 32]u8 = undefined; + const to = try std.fmt.bufPrint(&buf, "{s}.broken.{d}", .{ path, started / std.time.ns_per_s }); + try cwd.rename(path, cwd, to, io); + std.log.warn("{s} is no sessions database this host reads: moved to {s}", .{ path, to }); + } + } + }, + } + s.session = try s.count(.sessions); + try s.commit(.{ .open = .{ .started = started, .first = first } }); + s.stretches = 1; + return s; +} + +pub fn deinit(s: *Sessions) void { + s.dropQueued(); + s.queued.deinit(s.gpa); + s.batch.deinit(s.gpa); + if (s.file) |f| f.close(s.io); + if (s.buffer) |b| { + b.deinit(); + s.gpa.destroy(b); + } + s.gpa.free(s.path); + s.* = .{ .gpa = s.gpa, .io = s.io }; +} + +/// The last frames, an exit keyframe of `state`, and the session's end, in +/// one transaction synced to disk; then closed. +pub fn close(s: *Sessions, state: []const u8, ended: u64) void { + defer s.deinit(); + if (s.db == .off) return; + s.stopClip() catch {}; + _ = s.keyframe(.exit, state) catch {}; + s.commitSynced(.{ .end = ended }) catch |err| std.log.warn("sessions: last commit failed: {t}", .{err}); + if (s.db != .file) return; + const size = s.file.?.length(s.io) catch return; + if (size < compact_floor) return; + const live = liveSize(&s.db.file) catch return; + if (size > 2 * live + compact_floor) s.compact() catch |err| std.log.warn("sessions: not compacted: {t}", .{err}); +} + +/// The database's file compacted at a clean exit, once it is past twice what +/// its batches and keyframes hold plus this: every commit leaves the +/// nodes it copied behind. +const compact_floor: u64 = 64 << 20; + +/// Writes what the database holds now, without the nodes commits left +/// behind, to `<path>.new`, synced, and renames it over the file. +fn compact(s: *Sessions) !void { + const cwd = std.Io.Dir.cwd(); + var buf: [std.fs.max_path_bytes + 8]u8 = undefined; + const new = try std.fmt.bufPrint(&buf, "{s}.new", .{s.path}); + const file = try cwd.createFile(s.io, new, .{ .read = true, .truncate = true }); + errdefer cwd.deleteFile(s.io, new) catch {}; + defer file.close(s.io); + var buffer: std.Io.Writer.Allocating = .init(s.gpa); + defer buffer.deinit(); + var offsets: std.AutoHashMap(u64, u64) = .init(s.gpa); + defer offsets.deinit(); + _ = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = &buffer, .fsync = true }, &offsets); + try cwd.rename(new, cwd, s.path, s.io); +} + +/// The bytes of every session's batches and keyframes: what compaction keeps. +/// Reading them all is also what proves a mended file whole. +fn liveSize(db: *Disk) !u64 { + const R = Read(Disk); + const sessions = try R.list(try R.root(db), .sessions) orelse return 0; + var live: u64 = 0; + var it = try sessions.iterator(); + while (try it.next()) |c| { + const session = try R.Map.init(c); + if (try R.list(session, .batches)) |batches| { + var b = try batches.iterator(); + while (try b.next()) |blob| live += try blob.count(); + } + if (try R.list(session, .keys)) |keys| { + var k = try keys.iterator(); + while (try k.next()) |key_cursor| live += try (try R.field(try R.Map.init(key_cursor), .state)).count(); + } + } + return live; +} + +// xitdb's layout, as `mend` reads it (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 because a crash or power loss tore its last commit +/// (its root header written, the commit's bytes not all): opened at the last +/// commit before the tear whose trailer verifies and whose sessions read +/// whole, scanned back from the file's end, its root header put back at it. +/// Null, the file as it was, when none does. +fn mend(io: std.Io, file: std.Io.File, buffer: *std.Io.Writer.Allocating) ?Disk { + 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; + // The 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 db = Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false }) catch continue; + _ = liveSize(&db) catch continue; + file.sync(io) catch {}; + return db; + } + if (start == root_header_end) break; + end = start + trailer_len - 1; + } + file.writePositionalAll(io, head[db_header_len..], db_header_len) catch {}; + return null; +} + +pub fn mode(s: *const Sessions) Mode { + return s.db; +} + +/// Remembers the console line that changed State, for the next keyframe. +pub fn noteLine(s: *Sessions, line: []const u8) void { + s.line_len = @min(line.len, s.line.len); + @memcpy(s.line[0..s.line_len], line[0..s.line_len]); +} + +/// One live frame, its tick last, before `update` is fed it: its times are +/// made never to go back (what `update` then sees is what a replay will), +/// and it is logged, after a keyframe of `state` when `why` says so or the +/// last is a minute old. +pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void { + for (one) |*e| { + e.time = @max(e.time, s.last_time); + s.last_time = e.time; + } + if (s.db == .off or s.full) return; + const tick = one[one.len - 1].time; + if (s.batch.items.len > 0 and tick -| s.batch_time >= commit_ns) try s.commit(.none); + if (why) |w| { + _ = try s.keyframe(w, state); + } else if (tick -| s.key_time >= periodic_ns) _ = try s.keyframe(.periodic, state); + if (s.frames == 0) s.first_time = tick; + if (s.batch.items.len == 0) { + try s.batch.appendSlice(s.gpa, std.mem.asBytes(&std.mem.nativeToLittle(u64, s.frames))); + s.batch_time = tick; + } + try s.batch.appendSlice(s.gpa, std.mem.sliceAsBytes(one)); + s.frames += 1; +} + +/// Queues a keyframe of `state` before the next frame, and returns its +/// index; an unchanged State is the last keyframe again (but for a +/// `before_reload` one: the last word in the old layout). +pub fn keyframe(s: *Sessions, why: Why, state: []const u8) !u64 { + if (s.db == .off) return error.NotRecording; + const hash = std.hash.Wyhash.hash(0, state); + defer s.line_len = 0; + if (s.keys > 0 and why != .before_reload and hash == s.key_hash and s.key_stretch == s.stretches - 1) return s.keys - 1; + const state_copy = try s.gpa.dupe(u8, state); + errdefer s.gpa.free(state_copy); + const line_copy = try s.gpa.dupe(u8, s.line[0..s.line_len]); + errdefer s.gpa.free(line_copy); + try s.queued.append(s.gpa, .{ .frame = s.frames, .batch = s.batches, .stretch = s.stretches - 1, .why = why, .time = s.last_time, .state = state_copy, .line = line_copy }); + s.key_time = s.last_time; + s.key_hash = hash; + s.key_stretch = s.stretches - 1; + s.keys += 1; + return s.keys - 1; +} + +/// A new stretch from the next frame: a reload's build, source and layout. +pub fn stretch(s: *Sessions, st: Stretch) !void { + if (s.db == .off) return; + var with = st; + with.frame = s.frames; + try s.commit(.{ .stretch = with }); + s.stretches += 1; +} + +/// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`), +/// synced to disk. Returns the keyframe's index. +pub fn mark(s: *Sessions, name: []const u8, why: Why, state: []const u8) !u64 { + const k = try s.keyframe(why, state); + try s.commitSynced(.{ .mark = .{ .name = name, .key = k } }); + return k; +} + +/// Starts clip `name` at the next frame, played from keyframe `k`. +pub fn startClip(s: *Sessions, name: []const u8, k: u64) !void { + const index = try s.count(.clips); + try s.commit(.{ .clip = .{ .name = name, .key = k, .start = s.frames } }); + s.recording = index; +} + +/// Ends the clip being recorded after the frames logged so far. +pub fn stopClip(s: *Sessions) !void { + const index = s.recording orelse return; + try s.commit(.{ .clip_end = .{ .index = index, .end = s.frames } }); + s.recording = null; +} + +fn dropQueued(s: *Sessions) void { + for (s.queued.items) |k| { + s.gpa.free(k.state); + s.gpa.free(k.line); + } + s.queued.clearRetainingCapacity(); +} + +const Extra = union(enum) { + none, + open: struct { started: u64, first: Stretch }, + stretch: Stretch, + mark: struct { name: []const u8, key: u64 }, + clip: struct { name: []const u8, key: u64, start: u64 }, + clip_end: struct { index: u64, end: u64 }, + end: u64, +}; + +fn commitSynced(s: *Sessions, extra: Extra) !void { + if (s.db == .file) s.db.file.core.file.fsync = true; + defer if (s.db == .file) { + s.db.file.core.file.fsync = false; + }; + try s.commit(extra); +} + +/// One transaction: the pending frames, the queued keyframes and `extra`. +pub fn commit(s: *Sessions, extra: Extra) !void { + switch (s.db) { + .off => return, + inline .memory, .file => |*db| db.runContext(Commit(@TypeOf(db.*)){ .s = s, .extra = extra }) catch |err| { + // A memory database that cannot grow (`memory_max`, or no + // memory left) stops recording, once. + if (s.db == .memory and !s.full) { + s.full = true; + s.batch.clearRetainingCapacity(); + s.dropQueued(); + std.log.warn("sessions: the memory database cannot grow ({t}; {d} MiB at most): no more frames recorded", .{ err, memory_max >> 20 }); + } + return err; + }, + } + if (s.batch.items.len > 0) { + s.batches += 1; + s.committed = s.frames; + s.batch.clearRetainingCapacity(); + } + s.dropQueued(); +} + +fn Commit(comptime DB: type) type { + return struct { + s: *Sessions, + extra: Extra, + + const Map = DB.HashMap(.read_write); + const List = DB.ArrayList(.read_write); + + pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { + const s = ctx.s; + const root = try Map.init(cursor.*); + const sessions = try List.init(try root.putCursor(key(.sessions))); + if (ctx.extra == .open) { + const o = ctx.extra.open; + try root.put(key(.version), .{ .uint = 1 }); + const session = try Map.init(try sessions.appendCursor()); + try session.put(key(.started), .{ .uint = o.started }); + try session.put(key(.ended), .{ .uint = 0 }); + try session.put(key(.from), .{ .bytes = "" }); + try session.put(key(.frames), .{ .uint = 0 }); + try putStretch(try List.init(try session.putCursor(key(.stretches))), o.first); + return; + } + const session = try Map.init(try sessions.putCursor(@intCast(s.session))); + if (s.batch.items.len > 0) { + try (try List.init(try session.putCursor(key(.batches)))).append(.{ .bytes = s.batch.items }); + try session.put(key(.frames), .{ .uint = s.frames }); + } + if (s.queued.items.len > 0) { + const keys = try List.init(try session.putCursor(key(.keys))); + for (s.queued.items) |q| { + const k = try Map.init(try keys.appendCursor()); + try k.put(key(.frame), .{ .uint = q.frame }); + try k.put(key(.batch), .{ .uint = q.batch }); + try k.put(key(.stretch), .{ .uint = q.stretch }); + try k.put(key(.why), .{ .uint = @intFromEnum(q.why) }); + try k.put(key(.time), .{ .uint = q.time }); + try k.put(key(.state), .{ .bytes = q.state }); + try k.put(key(.line), .{ .bytes = q.line }); + } + } + switch (ctx.extra) { + .none, .open => {}, + .stretch => |st| try putStretch(try List.init(try session.putCursor(key(.stretches))), st), + .mark => |m| { + const item = try Map.init(try (try List.init(try root.putCursor(key(.marks)))).appendCursor()); + try item.put(key(.name), .{ .bytes = m.name }); + try item.put(key(.session), .{ .uint = s.session }); + try item.put(key(.key), .{ .uint = m.key }); + }, + .clip => |c| { + const item = try Map.init(try (try List.init(try root.putCursor(key(.clips)))).appendCursor()); + try item.put(key(.name), .{ .bytes = c.name }); + try item.put(key(.session), .{ .uint = s.session }); + try item.put(key(.key), .{ .uint = c.key }); + try item.put(key(.start), .{ .uint = c.start }); + try item.put(key(.end), .{ .uint = 0 }); + }, + .clip_end => |c| { + const item = try Map.init(try (try List.init(try root.putCursor(key(.clips)))).putCursor(@intCast(c.index))); + try item.put(key(.end), .{ .uint = c.end }); + }, + .end => |t| try session.put(key(.ended), .{ .uint = t }), + } + } + + fn putStretch(list: List, st: Stretch) !void { + const item = try Map.init(try list.appendCursor()); + try item.put(key(.frame), .{ .uint = st.frame }); + try item.put(key(.build), .{ .uint = st.build }); + try item.put(key(.source), .{ .bytes = st.source }); + try item.put(key(.layout), .{ .bytes = st.layout }); + } + }; +} + +// --------------------------------------------------------------------------- +// Reading + +/// A mark (`start` and `end` 0) or a clip. +pub const Entry = struct { + session: u64, + key: u64, + start: u64 = 0, + end: u64 = 0, + bytes: [max_name]u8 = undefined, + len: usize = 0, + + pub fn name(e: *const Entry) []const u8 { + return e.bytes[0..e.len]; + } +}; +/// A keyframe, its bytes `gpa`'s (`free`). +pub const Loaded = struct { + frame: u64, + batch: u64, + why: Why, + time: u64, + state: []const u8, + line: []const u8, + /// Its stretch: the layout of `state`, and the build that wrote it. + stretch: u64, + build: u64, + source: []const u8, + layout: []const u8, + + pub fn free(l: Loaded, gpa: std.mem.Allocator) void { + for ([_][]const u8{ l.state, l.line, l.source, l.layout }) |b| gpa.free(b); + } +}; + +pub fn markAt(s: *Sessions, i: u64) !Entry { + return s.entryAt(.marks, i); +} +pub fn clipAt(s: *Sessions, i: u64) !Entry { + return s.entryAt(.clips, i); +} +/// The newest mark named `name`. +pub fn findMark(s: *Sessions, name: []const u8) !?Entry { + return s.findNamed(.marks, name); +} +/// The newest clip named `name`. +pub fn findClip(s: *Sessions, name: []const u8) !?Entry { + return s.findNamed(.clips, name); +} + +fn findNamed(s: *Sessions, which: K, name: []const u8) !?Entry { + var i = try s.count(which); + while (i > 0) { + i -= 1; + const e = try s.entryAt(which, i); + if (std.mem.eql(u8, e.name(), name)) return e; + } + return null; +} + +fn entryAt(s: *Sessions, which: K, i: u64) !Entry { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const e = try R.at(try R.list(try R.root(db), which) orelse return error.NoSuchEntry, i); + var out: Entry = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) }; + out.len = ((try R.field(e, .name)).readBytes(&out.bytes) catch return error.CorruptSession).len; + if (which == .clips) { + out.start = try R.uint(e, .start); + out.end = try R.uint(e, .end); + } + return out; + }, + } +} + +/// Entries in the root list `which`, or sessions. +pub fn count(s: *Sessions, which: K) !u64 { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + return if (try R.list(try R.root(db), which)) |l| try l.count() else 0; + }, + } +} + +/// Keyframe `k` of `session`, with its stretch. +pub fn load(s: *Sessions, session: u64, k: u64) !Loaded { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const ses = try R.session(db, session); + const e = try R.at(try R.list(ses, .keys) orelse return error.NoSuchKeyframe, k); + const st = try R.uint(e, .stretch); + const stretch_entry = try R.at(try R.list(ses, .stretches) orelse return error.CorruptSession, st); + const why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession; + const state = try R.bytes(e, .state, s.gpa); + errdefer s.gpa.free(state); + const line = try R.bytes(e, .line, s.gpa); + errdefer s.gpa.free(line); + const source = try R.bytes(stretch_entry, .source, s.gpa); + errdefer s.gpa.free(source); + return .{ + .frame = try R.uint(e, .frame), + .batch = try R.uint(e, .batch), + .why = why, + .time = try R.uint(e, .time), + .state = state, + .line = line, + .stretch = st, + .build = try R.uint(stretch_entry, .build), + .source = source, + .layout = try R.bytes(stretch_entry, .layout, s.gpa), + }; + }, + } +} + +/// Keyframe `k`'s frame, time and why, without its bytes. +pub fn keyAt(s: *Sessions, session: u64, k: u64) !struct { frame: u64, time: u64, why: Why } { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const e = try R.at(try R.list(try R.session(db, session), .keys) orelse return error.NoSuchKeyframe, k); + return .{ .frame = try R.uint(e, .frame), .time = try R.uint(e, .time), .why = std.enums.fromInt(Why, try R.uint(e, .why)) orelse return error.CorruptSession }; + }, + } +} + +/// The newest keyframe of `session` whose `by` (`.frame` or `.time`) is at +/// most `value`: a binary search. +pub fn keyBefore(s: *Sessions, session: u64, by: K, value: u64) !?u64 { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const keys = try R.list(try R.session(db, session), .keys) orelse return null; + var lo: u64 = 0; + var hi = try keys.count(); + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (try R.uint(try R.at(keys, mid), by) <= value) lo = mid + 1 else hi = mid; + } + return if (lo == 0) null else lo - 1; + }, + } +} + +/// Appends to `out` the events of frames `start..end` of `session`, read +/// from batch `from` on. +pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out: *std.ArrayList(abi.Event)) !void { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const batches = try R.list(try R.session(db, session), .batches) orelse return; + const n = try batches.count(); + var i = from; + while (i < n) : (i += 1) { + const blob = try (try batches.getCursor(@intCast(i)) orelse return error.CorruptSession).readBytesAlloc(s.gpa, null); + defer s.gpa.free(blob); + if (blob.len < 8 or (blob.len - 8) % @sizeOf(abi.Event) != 0) return error.CorruptSession; + var f = std.mem.readInt(u64, blob[0..8], .little); + if (f >= end) return; + var at: usize = 8; + while (at < blob.len) : (at += @sizeOf(abi.Event)) { + var e: abi.Event = undefined; + @memcpy(std.mem.asBytes(&e), blob[at..][0..@sizeOf(abi.Event)]); + if (f >= start) try out.append(s.gpa, e); + if (e.kind == .tick) f += 1; + if (f >= end) return; + } + } + }, + } +} + +/// Session `i`'s summary. +pub const Summary = struct { + started: u64, + ended: u64, + frames: u64, + stretches: u64, + keys: u64, + /// Where it came from ("import <file name>"), cut short. + from_bytes: [48]u8 = undefined, + from_len: usize = 0, + + pub fn from(m: *const Summary) []const u8 { + return m.from_bytes[0..m.from_len]; + } +}; + +pub fn summary(s: *Sessions, i: u64) !Summary { + switch (s.db) { + .off => return error.NotRecording, + inline .memory, .file => |*db| { + const R = Read(@TypeOf(db.*)); + const ses = try R.session(db, i); + var m: Summary = .{ + .started = try R.uint(ses, .started), + .ended = try R.uint(ses, .ended), + .frames = try R.uint(ses, .frames), + .stretches = if (try R.list(ses, .stretches)) |l| try l.count() else 0, + .keys = if (try R.list(ses, .keys)) |l| try l.count() else 0, + }; + const from = try R.bytes(ses, .from, s.gpa); + defer s.gpa.free(from); + m.from_len = @min(from.len, m.from_bytes.len); + @memcpy(m.from_bytes[0..m.from_len], from[0..m.from_len]); + return m; + }, + } +} + +// --------------------------------------------------------------------------- +// Export and import + +/// Writes session `i`, with the marks and clips in it (now of session 0), to +/// a new database at `path` (written beside it, synced, then renamed): a +/// playtest's sessions to send, which `import` reads. +pub fn exportSession(s: *Sessions, i: u64, path: []const u8) !void { + if (s.db == .off) return error.NotRecording; + if (i == s.session) try s.commit(.none); + if (i >= try s.count(.sessions)) return error.NoSuchSession; + const cwd = std.Io.Dir.cwd(); + var buf: [std.fs.max_path_bytes + 8]u8 = undefined; + const tmp = try std.fmt.bufPrint(&buf, "{s}.tmp", .{path}); + const file = try cwd.createFile(s.io, tmp, .{ .read = true, .truncate = true }); + errdefer cwd.deleteFile(s.io, tmp) catch {}; + defer file.close(s.io); + var buffer: std.Io.Writer.Allocating = .init(s.gpa); + defer buffer.deinit(); + var out = try Disk.init(s.io, .{ .file = file, .buffer = &buffer, .fsync = true }); + switch (s.db) { + .off => unreachable, + inline .memory, .file => |*db| try out.runContext(Transfer(@TypeOf(db.*), Disk){ .gpa = s.gpa, .from = db, .only = i, .label = null }), + } + try cwd.rename(tmp, cwd, path, s.io); +} + +/// Appends the sessions of the database at `path` (an `exportSession`'s) to +/// this one, their `from` "import <file name>", with their marks and clips, +/// named `<name>@<file name>` (cut to `max_name`). Returns the first one's +/// index. +pub fn import(s: *Sessions, path: []const u8) !u64 { + if (s.db == .off) return error.NotRecording; + const file = try std.Io.Dir.cwd().openFile(s.io, path, .{}); + defer file.close(s.io); + if (try file.length(s.io) == 0) return error.NotASessionsDatabase; + var buffer: std.Io.Writer.Allocating = .init(s.gpa); + defer buffer.deinit(); + var in = try Disk.init(s.io, .{ .file = file, .buffer = &buffer, .fsync = false }); + const first = try s.count(.sessions); + switch (s.db) { + .off => unreachable, + inline .memory, .file => |*db| try db.runContext(Transfer(Disk, @TypeOf(db.*)){ .gpa = s.gpa, .from = &in, .only = null, .label = std.fs.path.basename(path) }), + } + return first; +} + +/// A transaction appending database `from`'s sessions (`only` one, else +/// all) to the one it runs in, with the marks and clips pointing into them; +/// `label`, an import's file name, goes in their `from` and names. +fn Transfer(comptime From: type, comptime To: type) type { + return struct { + gpa: std.mem.Allocator, + from: *From, + only: ?u64, + label: ?[]const u8, + + const R = Read(From); + const Map = To.HashMap(.read_write); + const List = To.ArrayList(.read_write); + + pub fn run(ctx: @This(), cursor: *To.Cursor(.read_write)) !void { + const src = try R.root(ctx.from); + if (try R.uint(src, .version) != 1) return error.NotASessionsDatabase; + const all = try R.list(src, .sessions) orelse return error.NotASessionsDatabase; + const root = try Map.init(cursor.*); + try root.put(key(.version), .{ .uint = 1 }); + const sessions = try List.init(try root.putCursor(key(.sessions))); + const base = try sessions.count(); + var buf: [std.fs.max_path_bytes + 8]u8 = undefined; + for (0..try all.count()) |i| { + if (ctx.only) |o| if (o != i) continue; + var to = try sessions.appendCursor(); + try copy(From, To, ctx.gpa, try all.getCursor(@intCast(i)) orelse return error.CorruptSession, &to); + if (ctx.label) |l| try (try Map.init(to)).put(key(.from), .{ .bytes = try std.fmt.bufPrint(&buf, "import {s}", .{l}) }); + } + for ([_]K{ .marks, .clips }) |which| { + const entries = try R.list(src, which) orelse continue; + const list = try List.init(try root.putCursor(key(which))); + var it = try entries.iterator(); + while (try it.next()) |e| { + const session = try R.uint(try R.Map.init(e), .session); + if (ctx.only) |o| if (o != session) continue; + var to = try list.appendCursor(); + try copy(From, To, ctx.gpa, e, &to); + const item = try Map.init(to); + try item.put(key(.session), .{ .uint = base + if (ctx.only == null) session else 0 }); + const l = ctx.label orelse continue; + var name: [max_name]u8 = undefined; + const old = (try R.field(try R.Map.init(e), .name)).readBytes(&name) catch return error.CorruptSession; + const new = std.fmt.bufPrint(&buf, "{s}@{s}", .{ old, l }) catch unreachable; + try item.put(key(.name), .{ .bytes = new[0..@min(new.len, max_name)] }); + } + } + } + }; +} + +/// Copies the value at `from` (a uint, bytes, or a list or map of them) to `to`. +fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write)) anyerror!void { + switch ((try from.slot()).tag) { + .uint => try to.write(.{ .uint = try from.readUint() }), + .bytes, .short_bytes => { + const bytes = try from.readBytesAlloc(gpa, null); + defer gpa.free(bytes); + try to.write(.{ .bytes = bytes }); + }, + .array_list => { + const list = try To.ArrayList(.read_write).init(to.*); + var it = try from.iterator(); + while (try it.next()) |c| { + var next = try list.appendCursor(); + try copy(From, To, gpa, c, &next); + } + }, + .hash_map => { + const map = try To.HashMap(.read_write).init(to.*); + var it = try from.iterator(); + while (try it.next()) |c| { + const kv = try c.readKeyValuePair(); + var next = try map.putCursor(kv.hash); + try copy(From, To, gpa, kv.value_cursor, &next); + } + }, + else => return error.CorruptSession, + } +} + +fn Read(comptime DB: type) type { + return struct { + const Map = DB.HashMap(.read_only); + const List = DB.ArrayList(.read_only); + + fn root(db: *DB) !Map { + return Map.init(db.rootCursor().readOnly()); + } + fn session(db: *DB, i: u64) !Map { + return at(try list(try root(db), .sessions) orelse return error.NoSuchSession, i); + } + fn field(map: Map, k: K) !DB.Cursor(.read_only) { + return try map.getCursor(key(k)) orelse error.CorruptSession; + } + fn uint(map: Map, k: K) !u64 { + return (try field(map, k)).readUint(); + } + fn bytes(map: Map, k: K, gpa: std.mem.Allocator) ![]const u8 { + return (try field(map, k)).readBytesAlloc(gpa, null); + } + fn list(map: Map, k: K) !?List { + return try List.init(try map.getCursor(key(k)) orelse return null); + } + fn at(l: List, i: u64) !Map { + if (i >= try l.count()) return error.NoSuchEntry; + return Map.init(try l.getCursor(@intCast(i)) orelse return error.NoSuchEntry); + } + }; +} + +test "frames written to a session read back byte for byte, in memory and through a reopened file" { + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + const layout = "a layout"; + for ([_]Mode{ .memory, .file }) |m| { + var s = try open(gpa, std.testing.io, m, path, .{ .build = 7, .source = "jj:abc", .layout = layout }, 1000); + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + // Three seconds at 60 Hz, a move in every third frame; the state is + // the frame count, so keyframes differ. + var state: u64 = 0; + for (0..180) |f| { + const t = std.time.ns_per_s + f * std.time.ns_per_s / 60; + var frame_events: [2]abi.Event = .{ .{ .kind = .mouse_move, .time = t, .x = @floatFromInt(f) }, abi.Event.tick(t, std.time.ns_per_s / 60) }; + const one = if (f % 3 == 0) frame_events[0..] else frame_events[1..]; + try s.frame(one, std.mem.asBytes(&state), if (f == 0) .start else if (f == 90) .jump else null); + try live.appendSlice(gpa, one); + state += 1; + } + // Two commits of a second each; the third second is pending. + try std.testing.expectEqual(@as(u64, 2), s.batches); + try s.commit(.none); + try std.testing.expectEqual(@as(u64, 2), s.keys); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try s.events(s.session, 0, 0, 180, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items)); + // From the jump's keyframe: frame 90 on, its state 90. + const k = (try s.keyBefore(s.session, .frame, 100)).?; + try std.testing.expectEqual(@as(u64, 1), k); + const loaded = try s.load(s.session, k); + defer loaded.free(gpa); + try std.testing.expectEqual(@as(u64, 90), loaded.frame); + try std.testing.expectEqual(@as(u64, 90), std.mem.bytesToValue(u64, loaded.state)); + try std.testing.expectEqualStrings(layout, loaded.layout); + try std.testing.expectEqual(@as(u64, 7), loaded.build); + back.clearRetainingCapacity(); + try s.events(s.session, loaded.batch, 90, 92, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[120..][0..3]), std.mem.sliceAsBytes(back.items)); + try std.testing.expectEqual(@as(?u64, 0), try s.keyBefore(s.session, .frame, 0)); + if (m == .memory) { + s.deinit(); + continue; + } + s.close(std.mem.asBytes(&state), 2000); + // Reopened: the first session ended, its frames all there; a new one. + var again = try open(gpa, std.testing.io, .file, path, .{ .build = 8, .source = "", .layout = layout }, 3000); + defer again.deinit(); + try std.testing.expectEqual(@as(u64, 1), again.session); + const first = try again.summary(0); + try std.testing.expectEqual(@as(u64, 180), first.frames); + try std.testing.expectEqual(@as(u64, 2000), first.ended); + back.clearRetainingCapacity(); + try again.events(0, 0, 0, 180, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items)); + } +} + +test "a session database torn inside its last commit opens at the one before, every earlier session and frame in it; one that cannot be mended is kept aside" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + const first: Stretch = .{ .build = 7, .source = "", .layout = "a layout" }; + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + var state: u64 = 0; + // Session 0: 120 frames, closed. Session 1: 180 frames in three commits + // of a second, then the process gone (no exit commit). + var before: u64 = 0; + var whole: u64 = 0; + for ([_]u64{ 120, 180 }, 0..) |frames, session| { + var s = try open(gpa, io, .file, path, first, 1000 + session); + for (0..frames) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + try s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else null); + try live.appendSlice(gpa, &one); + state += 1; + } + if (session == 0) { + s.close(std.mem.asBytes(&state), 2000); + continue; + } + before = try s.file.?.length(io); + try s.commit(.none); + whole = try s.file.?.length(io); + s.deinit(); + } + const bytes = try tmp.dir.readFileAlloc(io, "t.xitdb", gpa, .unlimited); + defer gpa.free(bytes); + try std.testing.expectEqual(whole, bytes.len); + for ([_]u64{ before, before + 1, (before + whole) / 2, whole - trailer_len, whole - 10, whole - 1 }) |cut| { + errdefer std.debug.print("cut at {d} of {d}..{d}\n", .{ cut, before, whole }); + try tmp.dir.writeFile(io, .{ .sub_path = "t.xitdb", .data = bytes[0..cut] }); + var s = try open(gpa, io, .file, path, first, 3000); + defer s.deinit(); + try std.testing.expectEqual(@as(u64, 2), s.session); + const s0 = try s.summary(0); + try std.testing.expectEqual(@as(u64, 120), s0.frames); + try std.testing.expectEqual(@as(u64, 2000), s0.ended); + const s1 = try s.summary(1); + try std.testing.expectEqual(@as(u64, 120), s1.frames); + try std.testing.expectEqual(@as(u64, 0), s1.ended); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try s.events(0, 0, 0, 120, &back); + try s.events(1, 0, 0, 120, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..240]), std.mem.sliceAsBytes(back.items)); + var dir = try tmp.dir.openDir(io, ".", .{ .iterate = true }); + defer dir.close(io); + var it = dir.iterate(); + while (try it.next(io)) |e| try std.testing.expectEqualStrings("t.xitdb", e.name); + } + // Nothing whole to open at: kept aside as it was, a new database begun. + var torn = try gpa.dupe(u8, bytes); + defer gpa.free(torn); + @memset(torn[root_header_end..], 0); + try tmp.dir.writeFile(io, .{ .sub_path = "t.xitdb", .data = torn }); + var s = try open(gpa, io, .file, path, first, 4 * std.time.ns_per_s); + defer s.deinit(); + try std.testing.expectEqual(@as(u64, 0), s.session); + const aside = try tmp.dir.readFileAlloc(io, "t.xitdb.broken.4", gpa, .unlimited); + defer gpa.free(aside); + try std.testing.expectEqualSlices(u8, torn, aside); +} + +test "a compacted session database is smaller and holds every session and frame" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/t.xitdb", .{&tmp.sub_path}); + const first: Stretch = .{ .build = 7, .source = "", .layout = "a layout" }; + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + var s = try open(gpa, io, .file, path, first, 1000); + var state: u64 = 0; + for (0..600) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + try s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else if (f % 100 == 0) .jump else null); + try live.appendSlice(gpa, &one); + state += 1; + } + try s.commit(.none); + const size = try s.file.?.length(io); + const live_size = try liveSize(&s.db.file); + try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 6 * 8), live_size); + try s.compact(); + s.deinit(); + const compacted = (try tmp.dir.statFile(io, "t.xitdb", .{})).size; + try std.testing.expect(compacted < size); + var again = try open(gpa, io, .file, path, first, 2000); + defer again.deinit(); + try std.testing.expectEqual(@as(u64, 600), (try again.summary(0)).frames); + try std.testing.expectEqual(@as(u64, 6), (try again.summary(0)).keys); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try again.events(0, 0, 0, 600, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items), std.mem.sliceAsBytes(back.items)); +} + +test "a memory session stops recording at its bound, and what it holds still reads" { + const gpa = std.testing.allocator; + var s = try open(gpa, std.testing.io, .memory, "", .{ .build = 7, .source = "", .layout = "a layout" }, 0); + defer s.deinit(); + s.db.memory.core.max_size = 64 << 10; + var live: std.ArrayList(abi.Event) = .empty; + defer live.deinit(gpa); + var state: u64 = 0; + var failed: usize = 0; + for (0..60 * 60) |f| { + const t = f * std.time.ns_per_s / 60; + var one = [_]abi.Event{abi.Event.tick(t, std.time.ns_per_s / 60)}; + s.frame(&one, std.mem.asBytes(&state), if (f == 0) .start else null) catch |err| { + try std.testing.expectEqual(error.WriteFailed, err); + failed += 1; + }; + try live.appendSlice(gpa, &one); + state += 1; + } + try std.testing.expectEqual(@as(usize, 1), failed); + const n = (try s.summary(s.session)).frames; + try std.testing.expect(n >= 60 and n < 60 * 60); + var back: std.ArrayList(abi.Event) = .empty; + defer back.deinit(gpa); + try s.events(s.session, 0, 0, n, &back); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(live.items[0..n]), std.mem.sliceAsBytes(back.items)); +} diff --git a/src/host/library.zig b/src/host/library.zig index 6958eec..91b2296 100644 --- a/src/host/library.zig +++ b/src/host/library.zig @@ -1,9 +1,12 @@ //! Loading sketch libraries, and noticing when a build replaces one. //! //! `dlopen` returns the handle it already has for a path it loaded before, so -//! every load goes through a private copy with a fresh name. The copy is -//! deleted right after loading: the mapping keeps the code alive, and nothing -//! is left behind if the host dies. +//! every load goes through a symlink with a fresh name to an fd open on the +//! library: what loads is the file that was opened, whatever a build renames +//! over it meanwhile. The link is deleted right after loading: the mapping +//! keeps the code alive, and nothing is left behind if the host dies. A +//! library rewritten in place instead (same inode) would not load again, and +//! would change the code under the running host. const std = @import("std"); const linux = std.os.linux; const c = @import("c"); @@ -13,7 +16,8 @@ pub const Library = struct { object: *c.SDL_SharedObject, sketch: abi.Sketch, - pub fn open(path: [:0]const u8) !Library { + /// Loads the library at `path`; `source` names it in messages. + pub fn open(path: [:0]const u8, source: []const u8) !Library { const object = c.SDL_LoadObject(path.ptr) orelse return error.LoadLibrary; errdefer c.SDL_UnloadObject(object); var sketch: abi.Sketch = undefined; @@ -22,18 +26,35 @@ pub const Library = struct { const address = c.SDL_LoadFunction(object, symbol) orelse return error.MissingEntryPoint; @field(sketch, name) = @ptrCast(address); } - if (sketch.info().abi != abi.hash) return error.AbiMismatch; + if (sketch.info().abi != abi.hash) { + const address = c.SDL_LoadFunction(object, "sketch_build") orelse { + std.log.err("{s}: built by an older sketchbook: rebuild it", .{source}); + return error.AbiMismatch; + }; + const build = std.mem.span(@as([*:0]const u8, @ptrFromInt(@intFromPtr(address)))); + if (std.mem.eql(u8, build, abi.build)) { + std.log.err("{s}: built against other abi types: restart the host to load it", .{source}); + } else { + const mode = build[std.mem.lastIndexOfScalar(u8, build, ' ').? + 1 ..]; + std.log.err("{s}: built by zig {s}, this host by zig {s}; Zig calls cross the boundary, so both need the same compiler, backend and mode: build the host like the library (`zig build run -Doptimize={s}`) or the library like the host", .{ source, build, abi.build, mode }); + } + return error.AbiMismatch; + } return .{ .object = object, .sketch = sketch }; } - /// Loads `source` through a uniquely named copy in `scratch_dir`. - pub fn openCopy(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library { - var buf: [std.fs.max_path_bytes]u8 = undefined; - const copy = try std.mem.printSentinel(&buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }, 0); + /// Loads `source` through a uniquely named symlink in `scratch_dir`. + pub fn openFresh(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library { const cwd = std.Io.Dir.cwd(); - try cwd.copyFile(source, cwd, copy, io, .{}); - defer cwd.deleteFile(io, copy) catch {}; - return open(copy); + const file = try cwd.openFile(io, source, .{}); + defer file.close(io); + var target_buf: [32]u8 = undefined; + const target = try std.mem.print(&target_buf, "/proc/self/fd/{d}", .{file.handle}); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const link = try std.mem.printSentinel(&buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }, 0); + try cwd.symLink(io, target, link, .{}); + defer cwd.deleteFile(io, link) catch {}; + return open(link, source); } pub fn close(self: *Library) void { diff --git a/src/host/memory.zig b/src/host/memory.zig index 5fbb88f..044fc3b 100644 --- a/src/host/memory.zig +++ b/src/host/memory.zig @@ -1,7 +1,7 @@ //! Sketch memory by lifetime. //! -//! `StateFile`: one `MAP_SHARED` file holding the live state and its snapshot -//! slots, plus a header describing the layout, so the state outlives restarts, +//! `StateFile`: one `MAP_SHARED` file holding the live state, plus a header +//! describing the layout, so the state outlives restarts, //! a probe can read it from another process, and a reload with a changed //! layout can carry the old values over field by field. //! @@ -17,13 +17,16 @@ const abi = @import("abi"); const field_value = @import("fields.zig"); pub const page = std.heap.page_size_min; -/// Slot 0 is live; 1..7 are snapshots. -pub const slot_count = 8; pub const header_len = 64 * 1024; -/// Layouts with element leaves (`list[].x`, `StoredField` with `dims`). -pub const file_magic = "SKETCH02".*; +/// One slot, the live state: snapshots are marks in the sessions database. +pub const file_magic = "SKETCH03".*; +/// Before sessions: slot 0 live and 1..7 snapshots (`old_slot_count`), which +/// the host imports as marks and then drops (`dropSnapshots`). +pub const file_magic_v2 = "SKETCH02".*; +pub const old_slot_count = 8; /// What hosts before element leaves wrote: arrays are whole leaves -/// (`StoredFieldV1`). Read, and rewritten as `file_magic` on adopt. +/// (`StoredFieldV1`), and eight slots. Read, and rewritten as +/// `file_magic_v2` on adopt. pub const file_magic_v1 = "SKETCH01".*; pub const Header = extern struct { @@ -31,7 +34,8 @@ pub const Header = extern struct { size: u64, alignment: u64, hash: u64, - /// Distance between slots, page aligned. + /// The slot's size, page aligned (and the distance between an old + /// file's slots). stride: u64, /// Bit `i`: slot `i` holds state. used: u32, @@ -260,9 +264,14 @@ pub const Diff = struct { /// Compares two copies of state leaf by leaf, so padding (a Debug /// `@Vector`'s spare lane, the gaps between fields) never differs. pub fn compare(layout: Layout, a: []const u8, b: []const u8) Diff { + return compareKept(layout, layout, a, b); +} + +/// `compare` over the leaves `migrate` from `from` keeps (`keeps`). +pub fn compareKept(from: Layout, layout: Layout, a: []const u8, b: []const u8) Diff { var diff: Diff = .{}; for (layout.fields) |leaf| { - if (leaf.whole()) continue; + if (leaf.whole() or (from.hash != layout.hash and !keeps(from, leaf))) continue; var it = leaf.elements(); while (it.next()) |offset| { if (std.mem.eql(u8, a[offset..][0..leaf.size], b[offset..][0..leaf.size])) continue; @@ -285,6 +294,8 @@ fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) boo pub const StateFile = struct { fd: posix.fd_t, map: []align(page) u8, + /// 1, or `old_slot_count` in a file from before sessions. + slots: usize = 1, /// Layout of the bytes in the file, owned by `arena`. layout: Layout, arena: std.heap.ArenaAllocator, @@ -322,8 +333,14 @@ pub const StateFile = struct { return @ptrCast(self.map.ptr); } + /// The header and the layout after it, as `readLayout` reads them back. + pub fn layoutBytes(self: *StateFile) []const u8 { + const h = self.header(); + return self.map[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len]; + } + pub fn slot(self: *StateFile, index: usize) []align(page) u8 { - std.debug.assert(index < slot_count); + std.debug.assert(index < self.slots); const h = self.header(); const start = header_len + index * h.stride; return @alignCast(self.map[start..][0..h.size]); @@ -355,7 +372,7 @@ pub const StateFile = struct { self.arena = .init(gpa); self.layout = try Layout.copy(self.arena.allocator(), new); try writeLayout(self.map[0..header_len], self.layout); - self.header().magic = file_magic; + self.header().magic = file_magic_v2; } return .unchanged; } @@ -365,8 +382,8 @@ pub const StateFile = struct { var old_arena: std.heap.ArenaAllocator = .init(gpa); defer old_arena.deinit(); const old_layout = self.layout; - var old_slots: [slot_count]?[]u8 = @splat(null); - for (&old_slots, 0..) |*copy, i| { + var old_slots: [old_slot_count]?[]u8 = @splat(null); + for (old_slots[0..self.slots], 0..) |*copy, i| { if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i)); } const old_used = self.header().used; @@ -379,7 +396,7 @@ pub const StateFile = struct { const stride = std.mem.alignForward(usize, @max(new.size, 1), page); try self.resize(stride); const h = self.header(); - h.* = .{ .magic = file_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 }; + h.* = .{ .magic = if (self.slots == 1) file_magic else file_magic_v2, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 }; try writeLayout(self.map[0..header_len], self.layout); var total: Migration = .{}; @@ -399,14 +416,29 @@ pub const StateFile = struct { return .{ .migrated = total }; } + /// Makes a file from before sessions one of a single slot, its + /// snapshots (imported as marks by now) dropped. + pub fn dropSnapshots(self: *StateFile) !void { + if (self.slots == 1) return; + const stride = self.header().stride; + self.slots = 1; + try self.resize(stride); + self.header().magic = file_magic; + self.header().used &= 1; + } + fn check(self: *StateFile) !void { const h = self.header(); - if (!std.mem.eql(u8, &h.magic, &file_magic) and !std.mem.eql(u8, &h.magic, &file_magic_v1)) return error.NotAStateFile; - if (self.map.len < header_len + slot_count * h.stride or h.size > h.stride) return error.CorruptStateFile; + if (std.mem.eql(u8, &h.magic, &file_magic)) { + self.slots = 1; + } else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) { + self.slots = old_slot_count; + } else return error.NotAStateFile; + if (self.map.len < header_len + self.slots * h.stride or h.size > h.stride) return error.CorruptStateFile; } fn resize(self: *StateFile, stride: usize) !void { - const len = header_len + slot_count * stride; + const len = header_len + self.slots * stride; if (self.map.len != 0) posix.munmap(self.map); self.map = &.{}; switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) { @@ -417,6 +449,36 @@ pub const StateFile = struct { } }; +/// Fills `live` (laid out as `to`) from `image`, state kept in another +/// layout, described by `layout_bytes` (a header as `StateFile.layoutBytes` +/// gives it): `defaults`, then every leaf `migrate` keeps. Returns the +/// image's layout, `arena`'s. +pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []const u8, to: Layout, live: []u8, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Layout { + const from = try layoutOf(arena, layout_bytes); + if (image.len != from.size) return error.CorruptKeyframe; + @memset(live, 0); + defaults(.state, live.ptr); + _ = migrate(from, image, to, live); + return from; +} + +/// The layout in a header as `StateFile.layoutBytes` gives it, `arena`'s. +pub fn layoutOf(arena: std.mem.Allocator, layout_bytes: []const u8) !Layout { + if (layout_bytes.len < @sizeOf(Header) or layout_bytes.len > header_len) return error.CorruptKeyframe; + const region = try arena.alignedAlloc(u8, .of(Header), header_len); + @memset(region, 0); + @memcpy(region[0..layout_bytes.len], layout_bytes); + return try readLayout(arena, region) orelse .{}; +} + +/// Whether `migrate` from `from` keeps `leaf`'s value: compared on these +/// only, state restored across a layout change differs nowhere it was reset. +pub fn keeps(from: Layout, leaf: Layout.Leaf) bool { + const before = from.pattern(leaf.path) orelse return false; + if (before.dims.len != leaf.dims.len) return false; + return (before.hash == leaf.hash and before.size == leaf.size) or (before.kind == .@"enum" and leaf.kind == .@"enum"); +} + /// Writes `layout`'s leaves after the `Header` at the start of `region`, /// in the current format (`StoredField`); the caller sets the magic. fn writeLayout(region: []u8, layout: Layout) !void { @@ -859,7 +921,7 @@ test "migration keeps unchanged fields and defaults the rest" { try std.testing.expectEqual(@as(usize, 1), m.reset); } -test "state file migrates live state and snapshots, and a reopen reads the layout back" { +test "state file migrates live state, and a reopen reads the layout back" { const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* }; const V2 = extern struct { level: u16 = 1, score: u32 = 0 }; const D = struct { @@ -881,19 +943,13 @@ test "state file migrates live state and snapshots, and a reopen reads the layou try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .state), D.v1)); file.markUsed(0, true); @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99; - @memcpy(file.slot(3), file.slot(0)); - file.markUsed(3, true); } var file = try StateFile.open(gpa, path); defer file.close(); try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash); const adoption = try file.adopt(gpa, abi.layout.of(V2, .state), D.v2); try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset); - for ([_]usize{ 0, 3 }) |i| { - const s: *V2 = @ptrCast(file.slot(i).ptr); - try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, s.*); - } - try std.testing.expect(!file.used(1)); + try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(file.slot(0).ptr)).*); } test "a store keeps its root and what it points to across a reopen, and migrates by field" { @@ -1084,7 +1140,7 @@ test "a state file from before element leaves (drat-meout's) keeps every value" var file = try StateFile.open(gpa, path); defer file.close(); try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f)); - try std.testing.expectEqualStrings(&file_magic, &file.header().magic); + try std.testing.expectEqualStrings(&file_magic_v2, &file.header().magic); } var file = try StateFile.open(gpa, path); defer file.close(); diff --git a/src/host/probe.zig b/src/host/probe.zig index d8ed166..4b61153 100644 --- a/src/host/probe.zig +++ b/src/host/probe.zig @@ -31,7 +31,7 @@ pub fn main(init: std.process.Init) !void { const map = memory.mapReadOnly(file); if (map.len < memory.header_len) fatal("not a sketchbook state file"); const magic = map[0..8]; - if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file"); + if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v2) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file"); defer std.posix.munmap(map); var arena: std.heap.ArenaAllocator = .init(init.gpa); defer arena.deinit(); diff --git a/src/host/root.zig b/src/host/root.zig index 158f894..5889b42 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -2,10 +2,11 @@ //! that it hot-reloads whenever a build replaces it. //! //! sketchbook [options] [LIBRARY] -//! --state FILE persistent state (default: <name>.state) +//! --state FILE persistent state (default: $XDG_DATA_HOME/<name>/<name>.state; +//! sketch.state for a script or an export) //! --headless offscreen video, silent audio //! --script FILE play a script instead of reading devices -//! --fresh start from default state: no snapshots or recordings +//! --fresh start from default state (sessions, marks and clips are kept) //! --timing-marker encode frame ID and draw sample time for video analysis //! --profile-gpu time each GPU command alone, print the times at exit //! --console LINE run a console line once the sketch is loaded (repeatable) @@ -54,6 +55,7 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { try lines.append(gpa, args.next() orelse fatal("--console needs a line")); } else if (std.mem.eql(u8, arg, "--script")) { script_path = args.next() orelse fatal("--script needs a file"); + options.script = true; } else if (std.mem.eql(u8, arg, "--define")) { const pair = args.next() orelse fatal("--define needs NAME=VALUE"); const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE"); @@ -93,15 +95,17 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { // A scripted run from fresh state works on files of its own, moved to // the given path at exit: two runs of one build step (two `zig build`s - // at once share its output path) never share a state, store or - // recordings file, nor fail on the store's lock. An export's are + // at once share its output path) never share a state or store file, + // nor fail on the store's lock (its sessions are in memory). An export's are // removed instead: nothing reads them, and a player may have the given // ones open. var private_buf: [std.fs.max_path_bytes]u8 = undefined; + if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.state"; const given = options.state; const private = (script_path != null or options.export_to != null) and options.fresh; + if (!private) sketchbookDir(init.io, given); if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long"); - defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| { + defer if (private) for ([_][]const u8{ "", ".store" }) |suffix| { var from: [std.fs.max_path_bytes + 16]u8 = undefined; var to: [std.fs.max_path_bytes + 16]u8 = undefined; const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue; @@ -127,10 +131,11 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { const usage = \\usage: sketchbook [options] [LIBRARY] \\ --9p SOCKET local 9P controls: ctl, status, log, screen.png - \\ --state FILE persistent state (default: sketch.state) + \\ --state FILE persistent state; sessions are kept beside it (default: + \\ $XDG_DATA_HOME/<name>/<name>.state, sketch.state for --script, --export) \\ --headless offscreen video, silent audio, no vsync \\ --script FILE play a script instead of reading devices - \\ --fresh start from default state: no snapshots or recordings + \\ --fresh start from default state (sessions, marks and clips are kept) \\ --timing-marker encode frame ID and draw sample time for video analysis \\ --profile-gpu time each GPU command alone, print the times at exit \\ --console LINE run a console line once the sketch is loaded (repeatable) @@ -143,6 +148,36 @@ const usage = \\ ; +/// A state file in a directory named `.sketchbook` (`zig build run`'s): +/// the directory is made, with a `.gitignore` of `*` (its sessions database +/// grows, and a jj snapshot would commit it), and the state and store files +/// an older build kept beside it are moved in, once. A file is never +/// replaced: when both exist, nothing moves. +fn sketchbookDir(io: std.Io, state: []const u8) void { + const dir = std.fs.path.dirname(state) orelse return; + if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return; + const cwd = std.Io.Dir.cwd(); + cwd.createDirPath(io, dir) catch return; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return; + cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {}; + for ([_][]const u8{ "", ".store" }) |suffix| { + var from_buf: [std.fs.max_path_bytes]u8 = undefined; + var to_buf: [std.fs.max_path_bytes]u8 = undefined; + const parent = std.fs.path.dirname(dir) orelse "."; + const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}{s}", .{ parent, std.fs.path.basename(state), suffix }, 0) catch return; + const to = std.fmt.bufPrintSentinel(&to_buf, "{s}{s}", .{ state, suffix }, 0) catch return; + switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) { + .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }), + .EXIST => { + std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to }); + return; + }, + else => {}, + } + } +} + fn fatal(message: []const u8) noreturn { std.debug.print("sketchbook: {s}\n", .{message}); std.process.exit(2); @@ -202,6 +237,7 @@ test { _ = memory; _ = fields; _ = timeline; + _ = @import("Sessions.zig"); _ = @import("audio.zig"); _ = @import("Console.zig"); _ = @import("control.zig"); diff --git a/src/host/script.zig b/src/host/script.zig index 7818c6b..9e1dddf 100644 --- a/src/host/script.zig +++ b/src/host/script.zig @@ -18,8 +18,13 @@ //! await FIELD VALUE [~T] run frames until it holds (a minute at most) //! print FIELD write a field's value to stderr (a vector, //! array or struct: every value in it), no frame -//! expect-snapshot N live state equals snapshot N, leaf by leaf -//! (padding ignored), exactly +//! expect-snapshot NAME live state equals the newest mark NAME, leaf +//! by leaf (padding ignored, and leaves a layout +//! change reset), exactly +//! expect-key WHY FIELD VALUE +//! the newest keyframe of this session taken for +//! WHY (`Sessions.Why`: before_reload, mark...) +//! holds VALUE, read in its own layout //! expect-log TEXT a recent console line contains TEXT //! expect-no-log TEXT no recent console line does //! expect-audio KEY stream KEY has received samples @@ -34,6 +39,7 @@ //! load LIBRARY swap in another build of the sketch //! reload load the watched library again //! await-reload SECONDS run frames until a build replaces the library +//! kill die by SIGKILL, as a crash would //! //! `{name}` is replaced by `--define name=value` from the command line. //! @@ -48,6 +54,8 @@ const abi = @import("abi"); const Host = @import("Host.zig"); const fields = @import("fields.zig"); const memory = @import("memory.zig"); +const Console = @import("Console.zig"); +const Sessions = @import("Sessions.zig"); pub const frame_ns: u64 = std.time.ns_per_s / 60; /// The most frames `await` plays: a minute. @@ -149,10 +157,31 @@ fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []cons } return; } else if (eq(u8, command, "expect-snapshot")) { - const index = std.fmt.parseInt(usize, rest, 10) catch return error.InvalidSlot; - if (!host.timeline.bank.hasSnapshot(index)) return error.EmptySnapshot; - if (!same(host, index)) return error.ExpectationFailed; + const saved = try Console.markState(host, arena, rest); + if (!same(host, saved.layout, saved.bytes, rest)) return error.ExpectationFailed; return; + } else if (eq(u8, command, "expect-key")) { + const why = std.meta.stringToEnum(Sessions.Why, words.next() orelse "") orelse return error.UnknownWhy; + const path = words.next() orelse return error.ExpectedField; + const want = std.mem.trim(u8, words.rest(), " \t"); + const s = &host.sessions; + try s.commit(.none); + var k = s.keys; + while (k > 0) { + k -= 1; + const key = try s.load(s.session, k); + defer key.free(host.gpa); + if (key.why != why) continue; + const leaf = (try memory.layoutOf(arena, key.layout)).find(path) orelse return error.UnknownField; + if (fields.matches(leaf, key.state, want)) return; + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.format(leaf, key.state, &w) catch {}; + std.debug.print(" {s} keyframe {d}: {s} expected {s}, found {s}\n", .{ @tagName(why), k, path, want, w.buffered() }); + return error.ExpectationFailed; + } + std.debug.print(" no {s} keyframe in this session\n", .{@tagName(why)}); + return error.ExpectationFailed; } else if (eq(u8, command, "expect-log") or eq(u8, command, "expect-no-log")) { var found = false; for (&host.console.lines) |*l| { @@ -226,6 +255,10 @@ fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []cons try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); } return; + } else if (eq(u8, command, "kill")) { + // A crash, for tests of what survives one: SIGKILL, no cleanup. + _ = std.os.linux.kill(std.os.linux.getpid(), .KILL); + return; } else if (eq(u8, command, "quit")) { host.quit = true; return; @@ -258,15 +291,14 @@ fn holds(host: *Host, path: []const u8, want: []const u8, tolerance: ?f64) bool return @abs(value - target) <= t; } -/// Live state against snapshot `index`, leaf by leaf; prints the first few -/// differences. -fn same(host: *Host, index: usize) bool { +/// Live state against mark `name`'s (`saved`, taken in layout `from`), leaf +/// by leaf over the leaves migration kept; prints the first few differences. +fn same(host: *Host, from: memory.Layout, saved: []const u8, name: []const u8) bool { const layout = host.state.layout; const live = host.live(); - const saved = host.timeline.bank.slot(index); var count: usize = 0; for (layout.fields) |leaf| { - if (leaf.whole()) continue; + if (leaf.whole() or (from.hash != layout.hash and !memory.keeps(from, leaf))) continue; var it = leaf.elements(); while (it.next()) |offset| { if (std.mem.eql(u8, live[offset..][0..leaf.size], saved[offset..][0..leaf.size])) continue; @@ -277,7 +309,7 @@ fn same(host: *Host, index: usize) bool { leaf.name(offset, &w) catch {}; w.writeAll(": live ") catch {}; fields.format(leaf.at(offset), live, &w) catch {}; - w.print(", snapshot {d} ", .{index}) catch {}; + w.print(", snapshot {s} ", .{name}) catch {}; fields.format(leaf.at(offset), saved, &w) catch {}; std.debug.print(" {s}\n", .{w.buffered()}); } diff --git a/src/host/timeline.zig b/src/host/timeline.zig index b52c74d..c2eeff3 100644 --- a/src/host/timeline.zig +++ b/src/host/timeline.zig @@ -1,47 +1,18 @@ -//! Snapshots, input recordings and replay: generic over state bytes and -//! `abi.Event`s, so any sketch gets time travel for free. +//! Clips and replay: generic over state bytes and `abi.Event`s, so any +//! sketch gets time travel for free. //! //! Playback is host state, not sketch state: wall clocks, modes and cursors //! must not contaminate byte comparisons between two runs of a sketch. //! -//! Recordings are frames: each frame's events, then its `tick`. Playback, -//! seek and step only ever stop between frames, and `frames` cuts a run of -//! events into them, so `update` sees exactly the frames it saw live, one -//! call each. +//! A clip is whole frames of a session (Sessions.zig) and the keyframe they +//! start from: each frame's events, then its `tick`. Playback, seek and step +//! only ever stop between frames, and `frames` cuts a run of events into +//! them, so `update` sees exactly the frames it saw live, one call each, +//! at the times it saw. const std = @import("std"); -const posix = std.posix; const abi = @import("abi"); const memory = @import("memory.zig"); - -pub const recording_len = 4 * 1024 * 1024; -pub const recording_count = 16; -pub const recordings_len = recording_len * recording_count; -const recording_magic = 0x52454305; -pub const capacity = (recording_len - 32) / @sizeOf(abi.Event); - -pub const Recording = extern struct { - duration: u64, - count: u32, - snapshot: u32, - magic: u32, - /// The build that recorded it (`build`, two halves), 0 when unknown. - build_low: u32, - build_high: u32, - reserved: u32, - events: [capacity]abi.Event, - slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8, - - pub fn slice(r: *const Recording) []const abi.Event { - return r.events[0..r.count]; - } - pub fn build(r: *const Recording) u64 { - return @as(u64, r.build_high) << 32 | r.build_low; - } - /// Events up to the end of the last whole frame. - pub fn whole(r: *const Recording) usize { - return frameStart(r.slice(), r.count); - } -}; +const Sessions = @import("Sessions.zig"); /// The largest frame boundary at or before `index`: 0, or just after a tick. pub fn frameStart(events: []const abi.Event, index: usize) usize { @@ -72,119 +43,92 @@ pub const Frames = struct { } }; -comptime { - std.debug.assert(@sizeOf(Recording) == recording_len); -} - -/// Snapshot slots of a state file, and the recordings that start from them. -pub const Bank = struct { - state: *memory.StateFile, - inputs: []align(memory.page) u8, - - pub fn slot(self: Bank, index: usize) []u8 { - return self.state.slot(index); - } - pub fn recording(self: Bank, index: usize) *Recording { - std.debug.assert(index < recording_count); - return @ptrCast(@alignCast(self.inputs[index * recording_len ..].ptr)); - } - pub fn hasSnapshot(self: Bank, index: usize) bool { - return index > 0 and index < memory.slot_count and self.state.used(index); - } - pub fn save(self: Bank, index: usize) void { - std.debug.assert(index > 0 and index < memory.slot_count); - for (0..recording_count) |i| { - const r = self.recording(i); - if (r.snapshot == index) r.magic = 0; - } - @memcpy(self.slot(index), self.slot(0)); - self.state.markUsed(index, true); - } - pub fn restore(self: Bank, index: usize) !void { - if (!self.hasSnapshot(index)) return error.EmptySnapshot; - @memcpy(self.slot(0), self.slot(index)); - } - pub fn get(self: Bank, index: usize) !*Recording { - const r = self.recording(index); - if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording; - return r; - } - /// Leaf by leaf (`memory.compare`): padding never differs. - pub fn compare(self: Bank, a: usize, b: usize) memory.Diff { - return memory.compare(self.state.layout, self.slot(a), self.slot(b)); - } -}; - pub const Timeline = struct { - bank: Bank, + gpa: std.mem.Allocator, + /// Live state is its slot 0. + state: *memory.StateFile, + /// The running sketch's: a restore starts from its defaults. + defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void, mode: abi.Mode = .live, - selected: usize = 0, + /// The clip loaded: its start keyframe and its frames, `gpa`'s. + key: ?Sessions.Loaded = null, + events: std.ArrayList(abi.Event) = .empty, + /// The clip's first tick: positions count from it. + base: u64 = 0, cursor: usize = 0, position: u64 = 0, clock: u64 = 0, - /// Set whenever live state is restored from a snapshot, for the host + /// Set whenever live state is restored from a keyframe, for the host /// to reset the input state that went with the old bytes. restored: bool = false, + /// Frames fed since the keyframe was restored. + fed: u64 = 0, + /// A past session played (`play session`), not a clip: its index, and + /// its keyframes after the one played from, checked against the replay + /// as their frames are reached (Host.resync). + session: ?u64 = null, + checks: std.ArrayList(Check) = .empty, + next_check: usize = 0, - /// Restores a snapshot into live state. - pub fn restore(self: *Timeline, index: usize) !void { - try self.bank.restore(index); + pub const Check = struct { + frame: u64, + key: u64, + /// Taken of what `update` made (periodic, a mark, before a reload, + /// at exit): a replay must match it. Other keyframes follow a jump + /// the log does not hold, and are restored without a word. + observed: bool, + }; + + pub fn deinit(self: *Timeline) void { + if (self.key) |k| k.free(self.gpa); + self.key = null; + self.events.deinit(self.gpa); + self.checks.deinit(self.gpa); + } + + /// Puts a keyframe, in whatever layout it was taken, into live state. + pub fn restore(self: *Timeline, key: Sessions.Loaded) !void { + var arena: std.heap.ArenaAllocator = .init(self.gpa); + defer arena.deinit(); + _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.slot(0), self.defaults); self.restored = true; + self.fed = 0; + self.next_check = 0; + } + + /// Makes a clip, its start keyframe and its frames, the one played; both + /// become the timeline's. + pub fn load(self: *Timeline, key: Sessions.Loaded, events: std.ArrayList(abi.Event)) void { + self.deinit(); + self.key = key; + self.events = events; + self.session = null; + self.checks = .empty; + var it = frames(events.items); + const first = it.next(); + self.base = if (first) |f| f[f.len - 1].time else 0; } - /// `build` identifies the code recording (0: unknown); `play` warns - /// when it differs. - pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: u64) !void { - // An unused snapshot captures the current state; an existing one is - // restored, so several recordings can branch from exactly those bytes. - if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot); - try self.restore(snapshot); - const r = self.bank.recording(index); - @memset(std.mem.asBytes(r)[0..32], 0); - r.magic = recording_magic; - r.snapshot = @intCast(snapshot); - r.build_low = @truncate(build); - r.build_high = @truncate(build >> 32); - self.selected = index; + fn at(self: *const Timeline, i: usize) u64 { + return self.events.items[i].time -| self.base; + } + + /// The last whole frame's tick, from the first. + fn duration(self: *const Timeline) u64 { + const end = frameStart(self.events.items, self.events.items.len); + return if (end == 0) 0 else self.at(end - 1); + } + + pub fn startRecording(self: *Timeline) void { self.cursor = 0; self.position = 0; - self.clock = now; self.mode = .recording; } - /// Records one frame (its events, then its tick) and rewrites their - /// times as recorded, so live `update` sees exactly what a replay will. - /// A frame that does not fit ends the recording before it. - pub fn capture(self: *Timeline, frame: []abi.Event) !void { - if (self.mode != .recording) return; - const r = self.bank.recording(self.selected); - if (frame.len > capacity - r.count) { - self.mode = .live; - return error.RecordingFull; - } - for (frame) |*e| { - // Queued events can predate the start command. Keep insertion - // order and nondecreasing times, including several events at the - // same timestamp. - e.time = @max(e.time -| self.clock, r.duration); - r.events[r.count] = e.*; - r.count += 1; - r.duration = e.time; - } - self.position = r.duration; - self.cursor = r.count; - } - pub fn stop(self: *Timeline, now: u64) void { - if (self.mode == .recording) { - const r = self.bank.recording(self.selected); - r.duration = @max(r.duration, now -| self.clock); - self.position = r.duration; - } + pub fn stop(self: *Timeline) void { self.mode = .live; } - pub fn play(self: *Timeline, index: usize, now: u64) !void { - const r = try self.bank.get(index); - try self.restore(r.snapshot); - self.selected = index; + pub fn play(self: *Timeline, now: u64) !void { + try self.restore(self.key orelse return error.EmptyRecording); self.cursor = 0; self.position = 0; self.clock = now; @@ -203,35 +147,33 @@ pub const Timeline = struct { /// due). Feed them to the same `update` that live input goes through. pub fn tick(self: *Timeline, now: u64) []const abi.Event { if (self.mode != .playing) return &.{}; - const r = self.bank.recording(self.selected); - self.position = @min(r.duration, self.position +| (now -| self.clock)); + const end = self.duration(); + self.position = @min(end, self.position +| (now -| self.clock)); self.clock = now; const start = self.cursor; var i = self.cursor; - while (i < r.count and r.events[i].time <= self.position) : (i += 1) { - if (r.events[i].kind == .tick) self.cursor = i + 1; + while (i < self.events.items.len and self.at(i) <= self.position) : (i += 1) { + if (self.events.items[i].kind == .tick) self.cursor = i + 1; } - if (self.position == r.duration) self.mode = .paused; - return r.events[start..self.cursor]; + if (self.position == end) self.mode = .paused; + return self.events.items[start..self.cursor]; } - /// Restores the snapshot and returns the frames that make up the first - /// `count` events (rounded down to a whole frame) to replay, so seeking - /// backwards works too. + /// Restores the start keyframe and returns the frames that make up the + /// first `count` events (rounded down to a whole frame) to replay, so + /// seeking backwards works too. pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event { - const r = try self.bank.get(self.selected); - try self.restore(r.snapshot); - self.cursor = frameStart(r.slice(), count); - self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time; + try self.restore(self.key orelse return error.EmptyRecording); + self.cursor = frameStart(self.events.items, count); + self.position = if (self.cursor == 0) 0 else self.at(self.cursor - 1); self.mode = .paused; - return r.events[0..self.cursor]; + return self.events.items[0..self.cursor]; } - /// To the last frame whose tick is at or before `time`. + /// To the last frame whose tick is at or before `time` into the clip. pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event { - const r = try self.bank.get(self.selected); - const position = @min(time, r.duration); + const position = @min(time, self.duration()); var count: usize = 0; - for (r.slice(), 0..) |e, i| { - if (e.time > position) break; + for (self.events.items, 0..) |e, i| { + if (self.at(i) > position) break; if (e.kind == .tick) count = i + 1; } const events = try self.seekCount(count); @@ -240,13 +182,12 @@ pub const Timeline = struct { } /// Moves by `steps` frames, forwards or back. pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { - const r = try self.bank.get(self.selected); - const events = r.slice(); + const events = self.events.items; var cursor = frameStart(events, self.cursor); var remaining = @abs(steps); + const end = frameStart(events, events.len); while (remaining > 0) : (remaining -= 1) { if (steps > 0) { - const end = r.whole(); if (cursor == end) break; cursor += 1; while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1; @@ -259,62 +200,46 @@ pub const Timeline = struct { } }; -/// Maps the recordings file next to a state file, creating it when missing. -pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 { - const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); - defer _ = posix.system.close(fd); - if (try memory.fileSize(fd) != recordings_len) switch (posix.errno(posix.system.ftruncate(fd, recordings_len))) { - .SUCCESS => {}, - else => |err| return posix.unexpectedErrno(err), - }; - return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true }); -} - -test "frames are whole: input waits for its tick, live and in playback" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - // A bank on plain memory: one slot of 8 bytes, snapshot 1 used. +test "frames are whole: input waits for its tick, in playback, seek and step" { + const gpa = std.testing.allocator; + // Live state on plain memory: 8 bytes, no fields. var file: memory.StateFile = undefined; - file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page); + file.map = try gpa.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.page); + defer gpa.free(file.map); @memset(file.map, 0); - file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 }; - file.layout = .{}; - const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len); - @memset(inputs, 0); - var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } }; - // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with - // no tick (a frame cut off). - try t.startRecording(0, 1, 1000, 7); - try std.testing.expect(t.restored); + file.slots = 1; + file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 1, .field_count = 0, .strings_len = 0 }; + file.layout = .{ .size = 8, .hash = 1 }; + const D = struct { + fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {} + }; + var t: Timeline = .{ .gpa = gpa, .state = &file, .defaults = D.f }; + defer t.deinit(); + // Frame k: a move at 10k ms, its tick 5 ms later; then a move with no + // tick (a frame cut off). + var events: std.ArrayList(abi.Event) = .empty; for (0..4) |k| { - var frame = [_]abi.Event{ - .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) }, - abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667), - }; - try t.capture(&frame); - // Live update sees the recorded times. - try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time); - try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt()); + try events.append(gpa, .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) }); + try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667)); } - const r = t.bank.recording(0); - r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 }; - r.count += 1; - t.stop(1000 + 41_000_000); - try std.testing.expectEqual(@as(u64, 7), r.build()); + try events.append(gpa, .{ .kind = .mouse_move, .time = 40_000_000 }); + const key: Sessions.Loaded = .{ .frame = 0, .batch = 0, .why = .mark, .time = 0, .stretch = 0, .build = 7, .state = try gpa.dupe(u8, &@as([8]u8, @splat(0))), .line = try gpa.dupe(u8, ""), .source = try gpa.dupe(u8, ""), .layout = try gpa.dupe(u8, file.layoutBytes()) }; + t.load(key, events); - try t.play(0, 0); + try t.play(0); + try std.testing.expect(t.restored); var delivered: usize = 0; // Every moment between 0 and the end, 1 ms apart. var now: u64 = 0; while (t.mode == .playing) : (now += 1_000_000) { - const events = t.tick(now); - if (events.len == 0) continue; - try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind); - var it = frames(events); + const due = t.tick(now); + if (due.len == 0) continue; + try std.testing.expectEqual(abi.Event.Kind.tick, due[due.len - 1].kind); + var it = frames(due); while (it.next()) |frame| { try std.testing.expectEqual(@as(usize, 2), frame.len); - try std.testing.expectEqual(abi.Event.tick(0, 16_666_667).tickDt(), frame[1].tickDt()); + // Fed at the times it was recorded at. + try std.testing.expectEqual(1000 + delivered * 10_000_000 + 5_000_000, frame[1].time); delivered += 1; } } @@ -322,13 +247,13 @@ test "frames are whole: input waits for its tick, live and in playback" { try std.testing.expectEqual(@as(usize, 8), t.cursor); // A seek between a frame's input and its tick stops before the frame. - try std.testing.expectEqual(@as(usize, 4), (try t.seekTime(22_000_000)).len); - try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len); + try std.testing.expectEqual(@as(usize, 6), (try t.seekTime(27_000_000)).len); + try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(t.events.items.len)).len); try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len); try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len); try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len); // The cut-off frame is never fed. - var it = frames(r.slice()); + var it = frames(t.events.items); var n: usize = 0; while (it.next()) |_| n += 1; try std.testing.expectEqual(@as(usize, 4), n); diff --git a/src/layout.zig b/src/layout.zig index 3fb381b..5e60e22 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -101,7 +101,7 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize, com }; const stored = dims[0..dims.len].*; return .{ - .path = std.fmt.comptimePrint("{s}", .{path}), + .path = (path ++ "\x00")[0..path.len :0], .offset = offset, .size = @sizeOf(T), .kind = kind, @@ -176,9 +176,9 @@ fn tags(comptime E: type) [:0]const u8 { var text: []const u8 = ""; const e = @typeInfo(E).@"enum"; for (e.field_names, e.field_values, 0..) |name, value, i| { - text = text ++ (if (i == 0) "" else ",") ++ std.fmt.comptimePrint("{s}={d}", .{ name, value }); + text = text ++ (if (i == 0) "" else ",") ++ name ++ "=" ++ decimal(value); } - return std.fmt.comptimePrint("{s}", .{text}); + return (text ++ "\x00")[0..text.len :0]; } } @@ -191,32 +191,40 @@ pub fn hash(comptime T: type) u64 { }; } +/// `n` in decimal, as `{d}` prints it: `std.fmt.comptimePrint` costs about a +/// millisecond of comptime a call, and a signature makes hundreds. +fn decimal(comptime n: comptime_int) []const u8 { + if (n < 0) return "-" ++ decimal(-n); + if (n < 10) return &[_]u8{'0' + n}; + return decimal(n / 10) ++ &[_]u8{'0' + n % 10}; +} + pub fn signature(comptime T: type) []const u8 { comptime { return switch (@typeInfo(T)) { - .int => |i| std.fmt.comptimePrint("{c}{d}", .{ if (i.signedness == .signed) 'i' else 'u', i.bits }), - .float => |f| std.fmt.comptimePrint("f{d}", .{f.bits}), + .int => |i| (if (i.signedness == .signed) "i" else "u") ++ decimal(i.bits), + .float => |f| "f" ++ decimal(f.bits), .bool => "b", .void => "v", .@"enum" => |e| "e(" ++ signature(e.tag_type) ++ ":" ++ tags(T) ++ ")", - .array => |a| std.fmt.comptimePrint("[{d}]", .{a.len}) ++ signature(a.child), - .vector => |v| std.fmt.comptimePrint("@{d}", .{v.len}) ++ signature(v.child), + .array => |a| "[" ++ decimal(a.len) ++ "]" ++ signature(a.child), + .vector => |v| "@" ++ decimal(v.len) ++ signature(v.child), .optional => |o| "?" ++ signature(o.child), .@"struct" => |s| blk: { - var text: []const u8 = std.fmt.comptimePrint("s{d}{{", .{@sizeOf(T)}); + var text: []const u8 = "s" ++ decimal(@sizeOf(T)) ++ "{"; for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { if (attrs.@"comptime") continue; - text = text ++ std.fmt.comptimePrint("{s}@{d}:", .{ name, @offsetOf(T, name) }) ++ signature(F) ++ ";"; + text = text ++ name ++ "@" ++ decimal(@offsetOf(T, name)) ++ ":" ++ signature(F) ++ ";"; } break :blk text ++ "}"; }, .@"union" => |u| blk: { - var text: []const u8 = std.fmt.comptimePrint("u{d}{{", .{@sizeOf(T)}); + var text: []const u8 = "u" ++ decimal(@sizeOf(T)) ++ "{"; if (u.tag_type) |tag| text = text ++ signature(tag) ++ "|"; for (u.field_names, u.field_types) |name, F| text = text ++ name ++ ":" ++ signature(F) ++ ";"; break :blk text ++ "}"; }, - .pointer => |p| std.fmt.comptimePrint("*{s}:{s}", .{ @tagName(p.size), @typeName(p.child) }), + .pointer => |p| "*" ++ @tagName(p.size) ++ ":" ++ @typeName(p.child), .@"opaque" => "opaque", .@"fn" => @typeName(T), else => @compileError("unsupported type in sketch memory: " ++ @typeName(T)), diff --git a/src/sketch/root.zig b/src/sketch/root.zig index cb20ab9..c70b326 100644 --- a/src/sketch/root.zig +++ b/src/sketch/root.zig @@ -300,15 +300,24 @@ pub const Console = struct { } }; +/// What the build knows of a sketch and passes to `sketch` and +/// `exportSketch` (build.zig's generated roots fill it in). +pub const Build = struct { + /// The repository revision the sketch was built from, "" when unknown. + source: []const u8 = "", + /// Record sessions to a file (`abi.Info.record`). + record: bool = false, +}; + /// The entry points of `App`, for a host that links it statically. -pub fn sketch(comptime App: type) abi.Sketch { - const G = Glue(App); +pub fn sketch(comptime App: type, comptime made: Build) abi.Sketch { + const G = Glue(App, made); return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command }; } /// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library. -pub fn exportSketch(comptime App: type) void { - const G = Glue(App); +pub fn exportSketch(comptime App: type, comptime made: Build) void { + const G = Glue(App, made); const names = abi.Sketch.symbols; @export(&G.info, .{ .name = names.info }); @export(&G.defaults, .{ .name = names.defaults }); @@ -317,14 +326,17 @@ pub fn exportSketch(comptime App: type) void { @export(&G.update, .{ .name = names.update }); @export(&G.draw, .{ .name = names.draw }); @export(&G.command, .{ .name = names.command }); + @export(&G.build, .{ .name = "sketch_build" }); } -pub fn Glue(comptime App: type) type { +pub fn Glue(comptime App: type, comptime made: Build) type { return struct { pub const State = if (@hasDecl(App, "State")) App.State else struct {}; pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {}; pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {}; + const build: [abi.build.len:0]u8 = abi.build.*; + pub const description: abi.Info = .{ .abi = abi.hash, .name = if (@hasDecl(App, "name")) App.name else "sketch", @@ -334,6 +346,8 @@ pub fn Glue(comptime App: type) type { .session = abi.layout.of(Session, .session), .store = abi.layout.of(Store, .store), .commands = if (@hasDecl(App, "commands")) &App.commands else &.{}, + .source = made.source ++ " " ++ abi.build, + .record = made.record, }; /// What a call can offer, by type. @@ -468,7 +482,7 @@ test "setup receives session resources without a Frame and reports errors" { ctx.session_root = std.mem.asBytes(&session); ctx.session = std.testing.allocator; ctx.store = std.testing.allocator; - const app = sketch(App); + const app = sketch(App, .{}); try std.testing.expect(!app.setup(&ctx)); defer std.testing.allocator.free(session.bytes); try std.testing.expectEqualStrings("ready", session.bytes); diff --git a/src/sketch/web.zig b/src/sketch/web.zig index 937b491..6cf165a 100644 --- a/src/sketch/web.zig +++ b/src/sketch/web.zig @@ -76,7 +76,7 @@ pub fn exportWeb(comptime App: type) void { } fn Driver(comptime App: type) type { - const G = root.Glue(App); + const G = root.Glue(App, .{}); const gpa = std.heap.wasm_allocator; return struct { var ready = false; |
