diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/abi.zig | 39 | ||||
| -rw-r--r-- | src/anim/Painter.zig | 12 | ||||
| -rw-r--r-- | src/anim/root.zig | 186 | ||||
| -rw-r--r-- | src/anim/typst.zig | 10 | ||||
| -rw-r--r-- | src/host/Console.zig | 9 | ||||
| -rw-r--r-- | src/host/Host.zig | 308 | ||||
| -rw-r--r-- | src/host/Sessions.zig | 631 | ||||
| -rw-r--r-- | src/host/memory.zig | 558 | ||||
| -rw-r--r-- | src/host/probe.zig | 86 | ||||
| -rw-r--r-- | src/host/root.zig | 67 | ||||
| -rw-r--r-- | src/host/timeline.zig | 22 | ||||
| -rw-r--r-- | src/layout.zig | 36 | ||||
| -rw-r--r-- | src/sketch/request.zig | 2 | ||||
| -rw-r--r-- | src/sketch/root.zig | 33 | ||||
| -rw-r--r-- | src/sketch/web.zig | 12 | ||||
| -rw-r--r-- | src/vector/svg.zig | 96 |
16 files changed, 1272 insertions, 835 deletions
diff --git a/src/abi.zig b/src/abi.zig index 271c6dc..2e80a35 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -321,8 +321,8 @@ pub const Voice = struct { /// Slices must stay alive until the host consumes the frame, right after /// `draw` returns. `sketch.Frame` copies the small ones (text, GPU /// descriptions, uniforms) into scratch memory itself; bulk data (vertices, -/// samples, pixels, uploads) must already live in scratch, session or store -/// memory, or be a literal. +/// samples, pixels, uploads) must already live in scratch or session memory, +/// or be a literal. pub const Command = union(enum) { clear: Color, rect: struct { dst: Rect, color: Color }, @@ -661,7 +661,9 @@ pub const Host = struct { samples: *const fn (*anyopaque, Audio) []const f32, /// The whole file, mapped for the life of the host; empty if missing. readFile: *const fn (*anyopaque, []const u8) []const u8, - env: *const fn (*anyopaque, []const u8) ?[]const u8, + /// See `Host.appendFile`: name, then bytes; `replace` for `writeFile`. + appendFile: *const fn (*anyopaque, [*]const u8, usize, [*]const u8, usize, bool) callconv(.c) [*:0]const u8, + env:*const fn (*anyopaque, []const u8) ?[]const u8, /// A monotonic clock in nanoseconds, for measuring, not for state: /// `update` must use `Input` time to stay replayable. clock: *const fn (*anyopaque) u64, @@ -734,6 +736,21 @@ pub const Host = struct { pub fn readFile(h: Host, path: []const u8) []const u8 { return h.vtable.readFile(h.ctx, path); } + /// Appends `bytes` to the sketch's file `name` (no `/` in it), + /// creating it: `<stem>.<name>`, beside the save `<stem>.xitdb` (in + /// `.sketchbook/` under `zig build run`). Returns the file's path, for + /// `readFile`, or "" when nothing was written, which on the web is + /// always. Only `draw` and `command` can write, and a write is not + /// replayed, like sound. `readFile` maps a file once: what is appended + /// to it afterwards is not in what it returned. + pub fn appendFile(h: Host, name: []const u8, bytes: []const u8) []const u8 { + return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, false)); + } + /// `appendFile` to a new, empty file of that name: what the old one + /// held is gone (a `readFile` of it keeps its bytes). + pub fn writeFile(h: Host, name: []const u8, bytes: []const u8) []const u8 { + return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, true)); + } pub fn env(h: Host, name: []const u8) ?[]const u8 { return h.vtable.env(h.ctx, name); } @@ -753,12 +770,8 @@ pub const Context = struct { /// This process: survives reloads; frees one allocation at a time, and /// releases the rest when Session's layout changes. session: std.mem.Allocator, - /// On disk, next to the state file: survives reloads and restarts, at - /// the same addresses, so Store may point into it. - store: std.mem.Allocator, - /// The sketch's `Session` and `Store` values. + /// The sketch's `Session` value. session_root: [*]u8, - store_root: [*]u8, /// Filled by `draw`, using `scratch`. commands: *std.ArrayList(Command), }; @@ -807,20 +820,19 @@ pub const Info = struct { height: u32, state: Layout, session: Layout, - 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). + /// Whether the save keeps history, or only the present and the marks + /// (`App.Options.record`; Debug builds keep it unless told otherwise). record: bool = false, }; /// Which memory `sketch_defaults` fills. -pub const Memory = enum(u8) { state, session, store }; +pub const Memory = enum(u8) { state, session }; /// The entry points of a sketch, exported from libraries under these names. /// What became of a console line offered to a sketch. @@ -842,8 +854,7 @@ pub const Sketch = struct { setup: *const fn (*const Context) callconv(.c) bool, /// Deterministic: new state from state and input, nothing else. update: *const fn (*const Context, [*]u8) callconv(.c) void, - /// Presentation: reads state, may change session and store, appends - /// commands. + /// Presentation: reads state, may change session, appends commands. draw: *const fn (*const Context, [*]const u8) callconv(.c) void, /// A console line the host did not understand. command: *const fn (*const Context, [*]u8, *const []const u8) callconv(.c) Outcome, diff --git a/src/anim/Painter.zig b/src/anim/Painter.zig index b5d492f..f317dc1 100644 --- a/src/anim/Painter.zig +++ b/src/anim/Painter.zig @@ -56,11 +56,13 @@ pub fn fit(canvas: sk.Rect) f32 { } /// Object `o`'s drawing, centered on its origin, and its bounds. -fn built(p: *Painter, o: anim.Object, svgs: anytype) !Built { +fn built(p: *Painter, o: anim.Object, svgs: anytype) anim.BuildError!Built { const id = o.id(); if (p.drawings.get(id)) |b| return b; const arena = p.arena.?.allocator(); - const d = try anim.build(arena, o, svgs); + // A part, or what is left of an object parts were taken from: shapes + // of a whole drawing, which is built (parsed) once. + const d = if (o.source == .part or o.cut.len > 0) try anim.sift(arena, (try p.built(o.whole(), svgs)).drawing, o) else try anim.build(arena, o, svgs); const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() }; try p.drawings.put(arena, id, b); return b; @@ -122,7 +124,11 @@ fn paintLayers(p: *Painter, layers: anytype, f: *sk.Frame, shot: anim.Shot, svgs // Morphing: from where this object began the transform to where // its target will stand. const morph = shot.morphs[i]; - const target = (try p.built(shot.objects[pose.into], svgs)).drawing; + // Into the whole target, parts and all: parts taken from it + // once it is made stand where they were and show as it does. + var into = shot.objects[pose.into]; + into.cut = &.{}; + const target = (try p.built(into, svgs)).drawing; const between = try vector.morph.between(f.scratch, d, world.mul(model(morph.from)), target, world.mul(model(morph.to)), pose.morph); try r.draw(between, .identity, pose.opacity); shapes += between.shapes.len; diff --git a/src/anim/root.zig b/src/anim/root.zig index 4acecb3..560d71b 100644 --- a/src/anim/root.zig +++ b/src/anim/root.zig @@ -141,6 +141,9 @@ pub const Source = union(enum) { polygon: []const [2]f32, /// Drawn by the scene's own code (`custom`). custom: Custom, + /// The shapes of `of` whose bounds' centre lies in `area` (in `of`'s + /// units), around the area's centre (`part`). + part: struct { of: *const Object, area: vector.geom.Rect }, }; /// An object the scene draws itself with 2D commands (`f.fill`, `sk.draw`, @@ -225,6 +228,8 @@ pub const Object = struct { fill: ?u32 = null, stroke: ?u32 = null, width: f32 = 4, + /// Areas whose shapes parts were taken from it: it draws the rest. + cut: []const vector.geom.Rect = &.{}, /// Identifies what the object looks like (not where it is), to cache /// its drawing by. @@ -238,11 +243,25 @@ pub const Object = struct { .circle => |c| h.update(std.mem.asBytes(&c.r)), .line => |l| h.update(std.mem.asBytes(&[_]f32{ l.dx, l.dy, @floatFromInt(@intFromBool(l.arrow)) })), .custom => |c| h.update(std.mem.asBytes(&[_]usize{ @intFromPtr(c.draw), @intFromPtr(c.ctx) })), + .part => |p| { + h.update(std.mem.asBytes(&p.of.id())); + h.update(std.mem.asBytes(&p.area)); + }, } h.update(std.mem.asBytes(&[_]u64{ o.fill orelse 1 << 32, o.stroke orelse 1 << 32 })); h.update(std.mem.asBytes(&o.width)); + h.update(std.mem.sliceAsBytes(o.cut)); return h.final(); } + + /// What a part or a cut object is drawn from (`sift`): the object + /// without its cut, or the one a part was taken from. + pub fn whole(o: Object) Object { + if (o.cut.len == 0) return o.source.part.of.*; + var w = o; + w.cut = &.{}; + return w; + } }; /// Pose fields to animate towards; the others stay as they are. @@ -526,6 +545,25 @@ const adding = struct { } }; +/// `part`'s area: `.x`, `.y` its centre (0 when left out), `.w`, `.h`. +fn areaOf(spec: anytype) vector.geom.Rect { + const w: f32 = spec.w; + const h: f32 = spec.h; + return .{ .x = number(spec, "x", 0) - w / 2, .y = number(spec, "y", 0) - h / 2, .w = w, .h = h }; +} + +/// Where a part whose origin is `c` in its object's units stands, when the +/// object stands at `p`. +fn partPose(p: Pose, c: vector.geom.Vec) Pose { + var q = p; + const at = vector.geom.Affine.rotate(p.rotation).apply(c * vector.geom.splat(p.scale)); + q.x += at[0]; + q.y += at[1]; + q.into = Pose.none; + q.morph = 0; + return q; +} + fn primitive(source: Source, spec: anytype) Object { var pose: Pose = .{}; inline for (.{ "x", "y", "scale", "rotation", "opacity", "visible" }) |name| { @@ -553,13 +591,36 @@ pub const Builder = struct { values: []const f32 = &.{}, plays: []const Play = &.{}, updaters: []const Updater = &.{}, + /// Parts, each following its object through the plays laid before it + /// was taken. + follows: []const Follow = &.{}, /// Where the next play starts. cursor: f32 = 0, + const Follow = struct { obj: u16, of: u16, plays: usize, at: vector.geom.Vec }; + pub fn add(b: *Builder, o: Object) Obj { b.objects = b.objects ++ .{o}; return @fromBackingInt(@intCast(b.objects.len - 1)); } + + /// The shapes of `of` whose bounds' centre lies in `area` (`.x`, `.y` + /// its centre, `.w`, `.h`, in `of`'s units: those of `s.rect` laid + /// over `of` at the origin, at scale 1), as an object of their own, + /// around the area's centre; `of` draws the rest. It stands where they + /// stood and shows as `of` does after the plays so far; plays after it + /// move one or the other. A shape goes to the first part that takes it. + pub fn part(b: *Builder, of: Obj, area: anytype) Obj { + const i = @backingInt(of); + const r = areaOf(area); + const whole = b.objects[i]; + var cut = whole; + cut.cut = whole.cut ++ .{r}; + b.objects = b.objects[0..i] ++ .{cut} ++ b.objects[i + 1 ..]; + const o = b.add(.{ .source = .{ .part = .{ .of = &whole, .area = r } }, .pose = partPose(whole.pose, r.center()) }); + b.follows = b.follows ++ .{Follow{ .obj = @backingInt(o), .of = i, .plays = b.plays.len, .at = r.center() }}; + return o; + } pub const svg = adding.svg; pub const typst = adding.typst; pub const rect = adding.rect; @@ -620,13 +681,23 @@ pub fn Scene(comptime construct: fn (*Builder) void) type { var value_keys: [recorded.values.len][]const Key(f32) = @splat(&.{}); var camera_keys: []const Key(Camera) = &.{}; var marks: []const f32 = &.{}; - for (recorded.plays) |play| { + for (recorded.plays, 0..) |play, played| { var buf: [2 * play.animations.len]Change = undefined; + var touched: [n]bool = @splat(false); for (changes(&buf, &poses, play.animations)) |c| { const k = play.key(Pose, c.from, c.to, c.ease); keys[c.obj] = keys[c.obj] ++ .{k}; poses[c.obj] = k.at(k.end); + touched[c.obj] = true; } + for (recorded.follows) |f| if (played < f.plays and touched[f.of]) { + var k = keys[f.of][keys[f.of].len - 1]; + k.from = partPose(k.from, f.at); + k.to = partPose(k.to, f.at); + keys[f.obj] = keys[f.obj] ++ .{k}; + poses[f.obj] = k.at(k.end); + touched[f.obj] = true; + }; for (play.animations) |a| if (a == .value) { const i = @backingInt(a.value.value); value_keys[i] = value_keys[i] ++ .{play.key(f32, values[i], a.value.to, null)}; @@ -723,9 +794,12 @@ fn latest(comptime P: type, keys: []const Key(P), t: f32) ?Key(P) { return found; } +pub const BuildError = error{ TypstNotCompiled, CustomHasNoDrawing } || vector.svg.Error; + /// The drawing of an object, centered on its origin, in pixels at scale 1. /// `compiled` has `find(source) ?[]const u8` for Typst objects' SVGs. -pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { +pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) BuildError!Drawing { + if (o.source == .part or o.cut.len > 0) return sift(arena, try build(arena, o.whole(), compiled), o); const document: ?[]const u8 = switch (o.source) { .svg => |bytes| bytes, .typst => |source| compiled.find(source) orelse return error.TypstNotCompiled, @@ -738,8 +812,14 @@ pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { // Keep the SVG's pixel size (Typst's points are 4/3 px), centered. const s = if (d.view.w > 0) d.width / d.view.w else 1; const c = d.view.center(); + const centring = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])); const shapes = try arena.dupe(Drawing.Shape, d.shapes); - for (shapes) |*shape| shape.transform = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])).mul(shape.transform); + for (shapes) |*shape| { + shape.transform = centring.mul(shape.transform); + if (shape.clip) |*q| for (q) |*v| { + v.* = centring.apply(v.*); + }; + } var out = d; out.shapes = shapes; out.view = .{ .x = -d.view.w * s / 2, .y = -d.view.h * s / 2, .w = d.view.w * s, .h = d.view.h * s }; @@ -779,13 +859,43 @@ pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { style.stroke = .none; } }, - .svg, .typst, .custom => unreachable, + .svg, .typst, .custom, .part => unreachable, } try b.endShape(.identity, style); const r = @max(extent(o.source), 1); return b.finish(.{ .x = -r, .y = -r, .w = 2 * r, .h = 2 * r }, 2 * r, 2 * r); } +/// The drawing of a part, or of an object parts were taken from, out of +/// `whole`, the drawing of `o.whole()`: the shapes whose bounds' centre +/// lies in the part's area, around the area's centre; or those in none of +/// the object's `cut`, where they were. Shapes and geometry are shared. +pub fn sift(arena: std.mem.Allocator, whole: Drawing, o: Object) error{OutOfMemory}!Drawing { + const areas: []const vector.geom.Rect = if (o.cut.len > 0) o.cut else &.{o.source.part.area}; + const keep_inside = o.cut.len == 0; + const c: vector.geom.Vec = if (keep_inside) areas[0].center() else .{ 0, 0 }; + const to = vector.geom.Affine.translate(-c[0], -c[1]); + var shapes: std.ArrayList(Drawing.Shape) = .empty; + for (whole.shapes) |shape| { + const b = whole.shapeBounds(shape); + const mid = shape.transform.apply((b.min + b.max) * vector.geom.splat(0.5)); + const inside = for (areas) |a| { + if (mid[0] >= a.x and mid[0] < a.x + a.w and mid[1] >= a.y and mid[1] < a.y + a.h) break true; + } else false; + if (inside != keep_inside) continue; + var kept = shape; + kept.transform = to.mul(shape.transform); + if (kept.clip) |*q| for (q) |*v| { + v.* = to.apply(v.*); + }; + try shapes.append(arena, kept); + } + var out = whole; + out.shapes = shapes.items; + if (keep_inside) out.view = .{ .x = -areas[0].w / 2, .y = -areas[0].h / 2, .w = areas[0].w, .h = areas[0].h }; + return out; +} + fn extent(s: Source) f32 { return switch (s) { .rect => |r| @max(r.w, r.h) / 2, @@ -796,7 +906,7 @@ fn extent(s: Source) f32 { for (pts) |p| m = @max(m, @max(@abs(p[0]), @abs(p[1]))); break :blk m; }, - .svg, .typst, .custom => 0, + .svg, .typst, .custom, .part => 0, }; } @@ -912,6 +1022,19 @@ pub const Frame = struct { pub const polygon = adding.polygon; pub const custom = adding.custom; + /// The shapes of `of` inside `area`, as an object of their own, showing + /// as `of` does now; `of` draws the rest (see `Builder.part`). + pub fn part(s: *Frame, of: Obj, area: anytype) Obj { + const i = @backingInt(of); + const r = areaOf(area); + const whole = s.new(s.objects.items[i]); + s.objects.items[i].cut = std.mem.concat(s.arena, vector.geom.Rect, &.{ whole.cut, &.{r} }) catch @panic("anim: out of memory"); + const o = s.add(.{ .source = .{ .part = .{ .of = whole, .area = r } }, .pose = partPose(whole.pose, r.center()) }); + s.settled.items[@backingInt(o)] = partPose(s.settled.items[i], r.center()); + s.shown.items[@backingInt(o)] = partPose(s.shown.items[i], r.center()); + return o; + } + pub fn value(s: *Frame, initial: f32) Value { s.push(&s.values, .{ .settled = initial, .shown = initial }); return @fromBackingInt(@intCast(s.values.items.len - 1)); @@ -1800,3 +1923,56 @@ test "beside runs alongside the main line; clear fades out what shows" { const gone = try live.shot(arena.allocator(), .{ .t = 2 }); try std.testing.expect(!gone.poses[0].visible and !gone.poses[1].visible and gone.duration == 2); } + +/// Three squares, 100 units each, the middle one red; the right one is +/// taken as a part once the row shows, then each moves its own way. +fn partScene(s: anytype) void { + const row = s.svg( + \\<svg viewBox="0 0 300 100" width="300" height="100"><rect width="100" height="100"/> + \\<rect x="100" width="100" height="100" fill="red"/><rect x="200" width="100" height="100"/></svg> + , .{ .x = 10, .scale = 2 }); + s.play(.{row.fadeIn()}, .{}); + const right = s.part(row, .{ .x = 100, .w = 80, .h = 80 }); + s.play(.{ right.move(.{ .y = 50 }), row.move(.{ .x = 0 }) }, .{}); +} + +test "a part takes its shapes from its object, stands where they stood and follows it until taken" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const compiled = Scene(struct { + fn construct(s: *Builder) void { + partScene(s); + } + }.construct); + const live = Live(struct { + fn frame(s: *Frame) void { + partScene(s); + } + }.frame, struct {}); + for ([_]f32{ 0, 0.5, 1, 1.5, 2, 3 }) |t| { + const a = try compiled.shot(arena.allocator(), .{ .t = t }); + const b = try live.shot(arena.allocator(), .{ .t = t }); + try std.testing.expectEqualSlices(Pose, a.poses, b.poses); + try std.testing.expectEqual(a.objects[0].id(), b.objects[0].id()); + try std.testing.expectEqual(a.objects[1].id(), b.objects[1].id()); + } + // Fading in with the row, before it was taken; where the right square + // stood (10 + 2 * 100) once it was; then on its own. + try std.testing.expectEqual(compiled.pose(0, 0.5).opacity, compiled.pose(1, 0.5).opacity); + try std.testing.expectEqual(Pose{ .x = 210, .scale = 2, .visible = true }, compiled.pose(1, 1)); + try std.testing.expectEqual(@as(f32, 50), compiled.pose(1, 2).y); + try std.testing.expectEqual(@as(f32, 0), compiled.pose(0, 2).x); + try std.testing.expectEqual(@as(f32, 210), compiled.pose(1, 2).x); + // The row keeps two squares; the part is the third, around its centre. + const no_typst = struct { + fn find(_: []const u8) ?[]const u8 { + return null; + } + }; + const rest = try build(arena.allocator(), compiled.objects[0], no_typst); + const taken = try build(arena.allocator(), compiled.objects[1], no_typst); + try std.testing.expectEqual(@as(usize, 2), rest.shapes.len); + try std.testing.expectEqual(@as(usize, 1), taken.shapes.len); + try std.testing.expectEqual(vector.geom.Rect{ .x = -50, .y = -50, .w = 100, .h = 100 }, taken.bounds().rect()); + try std.testing.expectEqual(vector.geom.Rect{ .x = -150, .y = -50, .w = 200, .h = 100 }, rest.bounds().rect()); +} diff --git a/src/anim/typst.zig b/src/anim/typst.zig index d9df734..05a0d4e 100644 --- a/src/anim/typst.zig +++ b/src/anim/typst.zig @@ -50,12 +50,18 @@ pub fn generate(comptime SceneFile: type, comptime sources: []const []const u8, try out.writeFile(io, .{ .sub_path = "typst.zig", .data = module }); } -/// Runs `typst compile` on `preamble ++ source` and caches the SVG. +/// Runs `typst compile` on `preamble ++ source` and caches the SVG. The +/// root is `/`, so an absolute path in a source is the file's own path +/// (`#image("/home/me/manual.pdf", page: 31)`) and a relative one is +/// in the cache. Typst only reads what a source names, and a scene's +/// sources are its author's code, built by a build that can already read +/// anything. A file named this way is not part of the cache key: changed +/// in place, it keeps its old SVG until its entry in the cache goes. fn compile(gpa: std.mem.Allocator, io: std.Io, cache: std.Io.Dir, name: []const u8, preamble: []const u8, source: []const u8) ![]const u8 { const typ = try std.fmt.allocPrint(gpa, "{s}.typ", .{name}); try cache.writeFile(io, .{ .sub_path = typ, .data = try std.mem.concat(gpa, u8, &.{ preamble, "\n", source, "\n" }) }); const result = try std.process.run(gpa, io, .{ - .argv = &.{ "typst", "compile", "--format", "svg", typ, name }, + .argv = &.{ "typst", "compile", "--root", "/", "--format", "svg", typ, name }, .cwd = .{ .dir = cache }, }); if (result.term != .exited or result.term.exited != 0) { diff --git a/src/host/Console.zig b/src/host/Console.zig index 75da732..0d4cda0 100644 --- a/src/host/Console.zig +++ b/src/host/Console.zig @@ -350,7 +350,7 @@ fn listSessions(self: *Console, host: *Host) !void { 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)"), + .off => return self.log("not recording (an export)"), } const n = try s.count(.sessions); var i = n -| 4; @@ -457,10 +457,13 @@ fn listNamed(self: *Console, host: *Host, marks: bool) !void { 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) { + // An older mark of a name may have gone with history. + const key = s.keyAt(e.session, e.key) catch { + self.print("#{d} {s}: session {d}, dropped", .{ i, label, e.session }); + continue; + }; 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 }); } diff --git a/src/host/Host.zig b/src/host/Host.zig index dc21cc0..002c704 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -27,15 +27,17 @@ pub const Options = struct { library: ?[]const u8 = null, /// Local 9P control socket, opt-in. ninep: ?[]const u8 = null, - /// State file; the sessions database goes next to it, `<name>.xitdb` - /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.state` + /// The save, a sessions database: `<stem>.xitdb`, for a path + /// `<stem>.xitdb`, `<stem>.state` (where a state file from before is + /// imported from) or `<stem>`. Empty: `$XDG_DATA_HOME/<name>/<name>.xitdb` /// (`~/.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. + /// Start from State's defaults, not the save's present: scripts start + /// from a known place. fresh: bool = false, /// Time every GPU command alone and print the times at exit. profile_gpu: bool = false, @@ -70,11 +72,10 @@ images: gfx.Images, /// Plays the 2D commands: targets, blend, antialiased shapes. painter: gfx.Painter, audio: sound.Audio, -state: memory.StateFile, +state: memory.State, session: memory.Session, /// A failed resource setup disables app callbacks while keeping host controls alive. session_ready: bool = false, -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 } = .{}, @@ -92,8 +93,11 @@ reloads: usize = 0, /// 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. +/// The save's path when the host chose it (`Options.state`), `gpa`'s. state_path: []const u8 = "", +/// `Options.state` without `.xitdb` or `.state`: the save is +/// `<stem>.xitdb`, the sketch's own files `<stem>.<name>`. +stem: []const u8 = "", /// Copies of the sketch's info strings, replaced on every load. info_arena: std.heap.ArenaAllocator, name: []const u8 = "", @@ -107,6 +111,11 @@ commands: std.ArrayList(abi.Command) = .empty, pending: std.ArrayList(abi.Event) = .empty, input: abi.Input = .{}, files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty, +/// Mappings of files `writeFile` replaced: the sketch may still hold them. +retired: std.ArrayList([]align(memory.page) const u8) = .empty, +/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps +/// them. +written: std.StringHashMapUnmanaged(void) = .empty, canvas: [2]u32 = .{ 0, 0 }, cursor: abi.Cursor = .arrow, quit: bool = false, @@ -172,21 +181,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std 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 }); + const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.xitdb", .{ 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 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}); - return err; - }; - errdefer store.close(); self.* = .{ .gpa = gpa, @@ -199,14 +200,14 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .images = .{ .gpa = gpa, .renderer = renderer.? }, .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null }, .audio = .{ .gpa = gpa }, - .state = state, + .state = .init(gpa), .session = .init(gpa), - .store = store, .timeline = undefined, .sessions = .{ .gpa = gpa, .io = io }, .sketch = sketch, .library = library, .state_path = state_path, + .stem = stemOf(options.state), .info_arena = .init(gpa), .frame_arena = .init(gpa), .input = .{ .exporting = options.export_to != null }, @@ -227,10 +228,8 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std self.build = fileId(io, options.library orelse "/proc/self/exe"); try self.adopt(sketch); 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 }); + // Before --fresh, which never touches the save. + self.openPresent(); if (options.fresh) self.resetState(); if (!options.headless and options.export_to == null) { self.presentation = Presentation.init(gpa, self.window) catch null; @@ -259,12 +258,21 @@ pub fn deinit(self: *Host) void { std.posix.munmap(entry.value_ptr.*); } self.files.deinit(self.gpa); + for (self.retired.items) |bytes| std.posix.munmap(bytes); + self.retired.deinit(self.gpa); + // A scripted run from fresh state, or an export, leaves no files. + const private = (self.options.script or self.options.export_to != null) and self.options.fresh; + var written = self.written.keyIterator(); + while (written.next()) |path| { + if (private) std.Io.Dir.cwd().deleteFile(self.io, path.*) catch {}; + self.gpa.free(path.ptr[0 .. path.len + 1]); + } + self.written.deinit(self.gpa); self.timeline.deinit(); self.session.deinit(self.gpa); - self.store.close(); self.made.images.deinit(self.gpa); self.made.buffers.deinit(self.gpa); - self.state.close(); + self.state.deinit(self.gpa); self.pending.deinit(self.gpa); self.frame_arena.deinit(); self.info_arena.deinit(); @@ -329,7 +337,7 @@ test "timing clock drives ordinary ticks without moving input or replay time" { } pub fn live(self: *Host) []u8 { - return self.state.slot(0); + return self.state.live(); } /// One frame: reload if a build replaced the library, feed input through @@ -657,9 +665,7 @@ fn context(self: *Host) abi.Context { .input = &self.input, .scratch = self.frame_arena.allocator(), .session = self.session.heap.allocator(), - .store = self.store.allocator(), .session_root = self.session.bytes.ptr, - .store_root = self.store.root(), .commands = &self.commands, }; } @@ -702,7 +708,11 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { const replay = self.console.execute(self, line, now) catch |err| { // The sketch has printed its own error already. if (err == error.NotRecording) { - self.console.log("Not recording (a release build: .record = true collects): no marks or clips."); + self.console.log("Not recording (an export): no marks or clips."); + } else if (err == error.HistoryDropped) { + self.console.log("That part of the history is gone: a save keeps 64 MiB, the newest."); + } else if (err == error.SaveFull) { + self.console.log("No room for a new mark: marks and the present fill the save. Save over a mark's name (its older one goes with history), or start another save (--state)."); } 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); @@ -744,7 +754,6 @@ pub fn resetState(self: *Host) void { self.sketch.defaults(.state, bytes.ptr); const ctx = self.context(); self.sketch.init(&ctx, bytes.ptr); - self.state.markUsed(0, true); } /// Loads the watched library again. @@ -763,17 +772,16 @@ pub fn load(self: *Host, path: []const u8) !void { self.library = library; self.reloads += 1; 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.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.header }) catch |err| self.print("session: {t}", .{err}); self.print("reload {d}: {s}", .{ self.reloads, path }); } fn adopt(self: *Host, sketch: abi.Sketch) !void { const info = sketch.info(); if (info.abi != abi.hash) return error.AbiMismatch; - const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults); + const migrated = try self.state.adopt(self.gpa, info.state, sketch.defaults); const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults); if (session_reset) self.releaseMade(); - const stored = try self.store.adopt(self.gpa, info.store, sketch.defaults); _ = self.info_arena.reset(.retain_capacity); const arena = self.info_arena.allocator(); self.name = try arena.dupe(u8, info.name); @@ -784,22 +792,13 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { self.sketch = sketch; self.timeline.defaults = sketch.defaults; self.reloaded = true; - switch (adoption) { - .unchanged => {}, - .created => {}, - .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }), - } - if (!self.state.used(0)) self.resetState(); + if (migrated) |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }); if (session_reset) { const ctx = self.context(); self.session_ready = self.sketch.setup(&ctx); if (!self.session_ready) self.console.visible = true; } if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); - switch (stored) { - .unchanged, .created => {}, - .migrated => |m| self.print("store layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }), - } } /// Frees what the old Session made: its handles are gone with it. @@ -943,42 +942,88 @@ fn consoleKey(e: abi.Event) ?Console.Key { }; } -/// 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. +/// Opens the save (Sessions.zig) and starts this run's session in it: a +/// file, `<stem>.xitdb`; in memory for a script from fresh state; nowhere +/// for an export. A save that cannot be opened is said, and the run goes +/// on unsaved. 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; + const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else .file; 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() }; + const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{self.stem}) catch "sketch.xitdb"; + const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.header }; 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 }); + self.print("not saved: {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)", .{}), - } + // Without `.record`, history is trimmed to the present and the marks. + self.sessions.history = record; + if (o.headless or self.sessions.mode() != .file) return; + self.print("{s} to {s}", .{ if (record) "recording" else "saving", path }); +} + +/// The State this run starts from: the save's present, its newest keyframe +/// and the frames logged after it, replayed; in a new save, a state file +/// from before (`<stem>.state`), imported once and left as it was; else +/// `init`'s. +fn openPresent(self: *Host) void { + var events: std.ArrayList(abi.Event) = .empty; + defer events.deinit(self.gpa); + const found = self.sessions.present(&events) catch |err| blk: { + self.print("the save's present did not read ({t}): starting from defaults", .{err}); + break :blk null; + }; + const key = found orelse { + if (self.sessions.session != 0 or self.sessions.mode() != .file) return self.resetState(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const old = std.fmt.bufPrint(&buf, "{s}.state", .{self.stem}) catch return self.resetState(); + const n = importOld(self.gpa, old, &self.state, &self.sessions, self.sketch.defaults) catch |err| { + if (err != error.FileNotFound) self.print("{s} not imported ({t}): kept as it was", .{ old, err }); + return self.resetState(); + }; + return self.print("{s} imported: its State, and {d} snapshots as marks; the file is kept as it was", .{ old, n }); + }; + defer key.free(self.gpa); + self.timeline.restore(key) catch |err| { + self.print("the save's present did not restore ({t}): starting from defaults", .{err}); + return self.resetState(); + }; + self.timeline.restored = false; + var frames: usize = 0; + for (events.items) |e| frames += @intFromBool(e.kind == .tick); + if (frames == 0) return; + if (key.build != self.build) return self.print("{d} frames played after the save's last keyframe not replayed: another build", .{frames}); + // As they were fed: `started` only for a run's first frame. + self.started = key.frame == 0; + self.update(events.items); + self.started = true; } -/// 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; +/// A state file from before (`path`) into a new save: its live State into +/// `state`, its snapshots (slots 1..7) marks "1".."7", in `state`'s layout; +/// the file is left as it was. Returns the number of marks. +fn importOld(gpa: std.mem.Allocator, path: []const u8, state: *memory.State, sessions: *Sessions, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !usize { + const old = try memory.OldState.open(path); + defer old.close(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const scratch = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), state.layout.size); 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)); + for (1..old.slots) |i| if (old.slot(i)) |image| { + _ = try memory.restore(arena.allocator(), old.layoutBytes(), image, state.layout, scratch, defaults); + _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, scratch); n += 1; }; - try state.dropSnapshots(); + _ = try memory.restore(arena.allocator(), old.layoutBytes(), old.slot(0) orelse return error.CorruptStateFile, state.layout, state.live(), defaults); return n; } +/// `path` without `.xitdb` or `.state`. +pub fn stemOf(path: []const u8) []const u8 { + for ([_][]const u8{ ".xitdb", ".state" }) |suffix| if (std.mem.endsWith(u8, path, suffix)) return path[0 .. path.len - suffix.len]; + return path; +} + fn wallClock(io: std.Io) u64 { return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds)); } @@ -1019,6 +1064,7 @@ const api: abi.Host.VTable = .{ .newSound = apiNewSound, .samples = apiSamples, .readFile = apiReadFile, + .appendFile = apiAppendFile, .env = apiEnv, .clock = apiClock, }; @@ -1095,6 +1141,47 @@ fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 { self.files.put(self.gpa, key, bytes) catch self.gpa.free(key); return bytes; } +fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize, replace: bool) callconv(.c) [*:0]const u8 { + const self = hostOf(ctx); + const name = name_ptr[0..name_len]; + if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) { + self.print("appendFile: {s}: a name, not a path", .{name}); + return ""; + } + var buf: [std.fs.max_path_bytes]u8 = undefined; + const o = self.options; + const private = (o.script or o.export_to != null) and o.fresh; + // A scripted run from fresh state, or an export, writes files of its own + // (two runs of one build step may share a directory), gone at exit. + const path = (if (private) std.mem.print(&buf, "{s}.{d}.{s}", .{ self.stem, std.os.linux.getpid(), name }) else std.mem.print(&buf, "{s}.{s}", .{ self.stem, name })) catch return ""; + if (replace) { + // A new file: a mapping of the old one stays valid. + std.Io.Dir.cwd().deleteFile(self.io, path) catch {}; + if (self.files.fetchRemove(path)) |old| { + self.gpa.free(old.key); + self.retired.append(self.gpa, old.value) catch {}; + } + } + const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| { + self.print("appendFile: {s}: {t}", .{ path, err }); + return ""; + }; + defer file.close(self.io); + const end = file.length(self.io) catch return ""; + file.writePositionalAll(self.io, bytes[0..len], end) catch |err| { + self.print("appendFile: {s}: {t}", .{ path, err }); + return ""; + }; + const kept = self.written.getOrPut(self.gpa, path) catch return ""; + if (!kept.found_existing) { + const copy = self.gpa.dupeSentinel(u8, path, 0) catch { + self.written.removeByPtr(kept.key_ptr); + return ""; + }; + kept.key_ptr.* = copy; + } + return @ptrCast(kept.key_ptr.*.ptr); +} fn apiClock(_: *anyopaque) u64 { return c.SDL_GetTicksNS(); } @@ -1124,11 +1211,10 @@ test "session setup runs for restored state and layout reset, not same-layout re const State = extern struct { value: u32 = 1 }; const Session1 = extern struct { ready: u32 = 0 }; const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 }; - const Store = struct {}; var setup_calls: usize = 0; var init_calls: usize = 0; var fail_setup = false; - const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) }; + const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session) }; const changed: abi.Info = blk: { var value = description; value.session = abi.layout.of(Session2, .session); @@ -1144,7 +1230,6 @@ test "session setup runs for restored state and layout reset, not same-layout re switch (kind) { .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{}, - .store => {}, } } fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { @@ -1169,26 +1254,11 @@ test "session setup runs for restored state and layout reset, not same-layout re Fixture.init_calls = 0; Fixture.fail_setup = false; const a = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var state_buf: [std.fs.max_path_bytes]u8 = undefined; - var store_buf: [std.fs.max_path_bytes]u8 = undefined; - const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path}); - const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&tmp.sub_path}); - { - var state = try memory.StateFile.open(a, state_path); - defer state.close(); - _ = try state.adopt(a, Fixture.description.state, Fixture.defaults); - @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77; - state.markUsed(0, true); - } - // Exercise adoption with real persisted memory, without opening SDL devices. + // Exercise adoption without opening SDL devices. var host: Host = undefined; host.gpa = a; - host.state = try memory.StateFile.open(a, state_path); - defer host.state.close(); - host.store = try memory.StoreFile.open(a, store_path, false); - defer host.store.close(); + host.state = .init(a); + defer host.state.deinit(a); host.session = .init(a); defer host.session.deinit(a); host.info_arena = .init(a); @@ -1203,7 +1273,8 @@ test "session setup runs for restored state and layout reset, not same-layout re host.input = .{}; host.commands = .empty; try host.adopt(Fixture.sketch); - try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value); + // Defaults: the present or `init` comes after (openPresent). + try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value); try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls); try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); const session_ptr = host.session.bytes.ptr; @@ -1244,7 +1315,7 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload 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" { +test "a state file from before imports into a new save: its State live, its snapshots marks, the file as it was" { const State = extern struct { v: u32 = 0 }; const D = struct { fn f(_: abi.Memory, p: [*]u8) callconv(.c) void { @@ -1257,32 +1328,24 @@ test "a state file's snapshots from before sessions become marks, and the file o 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); + var state: memory.State = .init(gpa); + defer state.deinit(gpa); + _ = try state.adopt(gpa, abi.layout.of(State, .state), D.f); + // An eight-slot SKETCH02 file, slots 0, 1 and 3 used, its header State's. 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]); + @memcpy(old[0..state.header.len], state.header); 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); + var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.header }, 0); defer sessions.deinit(); - try std.testing.expectEqual(@as(usize, 2), try importSnapshots(&state, &sessions)); + try std.testing.expectEqual(@as(usize, 2), try importOld(gpa, path, &state, &sessions, D.f)); 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); @@ -1291,12 +1354,39 @@ test "a state file's snapshots from before sessions become marks, and the file o 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)); + try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.live()[0..4], .little)); + const after = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited); + defer gpa.free(after); + try std.testing.expectEqualSlices(u8, old, after); +} + +test "appendFile appends to a file beside the save and names it for readFile" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + var host: Host = undefined; + host.gpa = std.testing.allocator; + host.io = io; + host.written = .empty; + host.files = .empty; + host.options = .{}; + host.stem = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t", .{&tmp.sub_path}); + defer { + var written = host.written.keyIterator(); + while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]); + host.written.deinit(host.gpa); + } + const name = "take-1.f32"; + const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false)); + try std.testing.expect(std.mem.endsWith(u8, path, "/t.take-1.f32")); + try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false)); + const bytes = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited); + defer host.gpa.free(bytes); + try std.testing.expectEqualStrings("abcd", bytes); + // writeFile: a new file, its old bytes gone. + _ = apiAppendFile(&host, name, name.len, "e", 1, true); + const again = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited); + defer host.gpa.free(again); + try std.testing.expectEqualStrings("e", again); } diff --git a/src/host/Sessions.zig b/src/host/Sessions.zig index 751961d..cf0ab24 100644 --- a/src/host/Sessions.zig +++ b/src/host/Sessions.zig @@ -1,7 +1,8 @@ -//! 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. +//! A sketch's save: one xitdb database holding every run of it, an +//! append-only log of the frames live `update` was fed, and the State at +//! the moments that matter (keyframes). The newest keyframe and the frames +//! after it are the present a run starts from (`present`). Nothing in it +//! is ever overwritten: marks and clips are names pointing into it. //! //! root = map { //! version 1 @@ -14,20 +15,33 @@ //! 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) +//! `layout` is State's header (memory.State.header, read by memory.layoutOf) //! 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 +//! keys list of { frame, batch, stretch, why, time, size, pages, written, line }: +//! the State before frame `frame` is fed, in stretch `stretch`'s +//! layout; `batch` is where reading frames from it starts //! frames frames committed //! } //! +//! A keyframe's State is `size` bytes in `pages`, a list of `page`-byte +//! blobs (the last one shorter), an all-zero page an empty slot. A keyframe +//! starts from the list of the one before it and writes only the pages +//! whose hash changed (`written` bytes), so every page another keyframe +//! holds unchanged is shared, never written twice. (Keyframes from before +//! pages hold their State whole, as `state` bytes; `load` reads both.) +//! //! 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`). +//! power loss tore opens at its last whole commit (`mend`). +//! +//! A save is at most `max_save`: a commit that leaves the file past it +//! drops history oldest first and compacts the file to three quarters of +//! it (`trim`); the present, the newest mark of each name and the newest +//! clip of each name are never dropped. A build that does not record +//! (`history` false) drops all it may at every keyframe, and compacts at +//! exit: what it keeps is the present and the marks. const Sessions = @This(); const std = @import("std"); const xitdb = @import("xitdb"); @@ -36,9 +50,8 @@ 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). +/// `file` for every run but two: `memory` for a scripted run from fresh +/// state (time travel, nothing on disk), `off` for an export. pub const Mode = enum { off, memory, file }; pub const Why = enum(u64) { start, periodic, jump, before_reload, after_reload, mark, exit, import }; @@ -52,15 +65,27 @@ 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; +/// The most a save's file holds (State is at most half of it, +/// `abi.layout.max_state`, so history has room). +pub const max_save: u64 = 64 << 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 }; +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, pages, size, written }; 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 }; +/// A keyframe's page: the OS page, the grain of sharing. +pub const page = 4096; + +/// A keyframe: `session`'s keyframe `key`. +const At = struct { session: u64, key: u64 }; + +/// A keyframe queued: the pages of its State that differ from keyframe +/// `from`'s (`indices`, ascending; their bytes one after the other in +/// `pages`, `page` apart). +const Keyframe = struct { frame: u64, batch: u64, stretch: u64, why: Why, time: u64, size: u64, from: ?At, indices: []u64, pages: []u8, line: []u8 }; gpa: std.mem.Allocator, /// Files and the wall clock; a memory database runs on `std.Io.failing`. @@ -89,10 +114,13 @@ 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. +/// The last keyframe's time and stretch. key_time: u64 = 0, key_stretch: u64 = 0, -key_hash: u64 = 0, +/// The keyframe the next one starts from (the last one, or the one a run +/// started from), and the hashes of its pages. +last: ?At = null, +hashes: []u64 = &.{}, queued: std.ArrayList(Keyframe) = .empty, /// The clip being recorded, an index into `clips`. recording: ?u64 = null, @@ -104,6 +132,8 @@ full: bool = false, /// The console line that last changed State, for the next keyframe. line: [256]u8 = undefined, line_len: usize = 0, +/// Keep history, up to `max_save`; else only the present and the marks. +history: bool = true, /// 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 @@ -165,6 +195,7 @@ pub fn deinit(s: *Sessions) void { s.dropQueued(); s.queued.deinit(s.gpa); s.batch.deinit(s.gpa); + s.gpa.free(s.hashes); if (s.file) |f| f.close(s.io); if (s.buffer) |b| { b.deinit(); @@ -175,43 +206,212 @@ pub fn deinit(s: *Sessions) void { } /// The last frames, an exit keyframe of `state`, and the session's end, in -/// one transaction synced to disk; then closed. +/// one transaction synced to disk; then closed. Without history the file is +/// compacted, so the frames it dropped are gone from the disk too. 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}); + if (s.db == .file and !s.history) 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. +/// behind, to `<path>.new`, synced, renames it over the file, and goes on +/// in it. 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(); + errdefer { + file.close(s.io); + cwd.deleteFile(s.io, new) catch {}; + } + const buffer = try s.gpa.create(std.Io.Writer.Allocating); + buffer.* = .init(s.gpa); + errdefer { + buffer.deinit(); + s.gpa.destroy(buffer); + } 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); + var db = try s.db.file.compact(.buffered_file, .{ .file = file, .buffer = buffer, .fsync = true }, &offsets); + db.core.file.fsync = false; try cwd.rename(new, cwd, s.path, s.io); + s.file.?.close(s.io); + s.buffer.?.deinit(); + s.gpa.destroy(s.buffer.?); + s.file = file; + s.buffer = buffer; + s.db = .{ .file = db }; +} + +/// Drops history oldest first, then compacts the file: until its keyframes' +/// pages and frames are under three quarters of `max_save`, or, without +/// history, all it may (compacted only past `max_save`; `close` does it +/// at exit). A few rounds at most: what a dropped keyframe wrote may still +/// be shared by one kept, so a round can free less than it counted. +fn trim(s: *Sessions) !void { + const goal = max_save / 4 * 3; + var keep: u64 = if (s.history) goal else 0; + for (0..4) |_| { + var dropped: u64 = 0; + var left: u64 = 0; + try s.db.file.runContext(Trim(Disk){ .s = s, .keep = keep, .dropped = &dropped, .left = &left }); + var size = try s.file.?.length(s.io); + if (!s.history and size <= max_save) return; + try s.compact(); + size = try s.file.?.length(s.io); + if (size <= goal or dropped == 0) return; + // What the count leaves out (lists, maps, stretches) is the rest. + keep = left -| (size - goal); + } +} + +/// A keyframe's pages or a batch of frames, for `trim`. +const Item = struct { session: u64, index: u64, frame: u64, bytes: u64, batch: bool, keep: bool }; + +/// The transaction of `trim`: drops a keyframe by removing its pages (its +/// fields stay, so keyframe numbers and searches by frame still work) and +/// a batch by emptying its slot, oldest first, until what is left counts at +/// most `keep` bytes; a session left with nothing loses its keyframes, +/// batches and stretches. Never the present (the newest keyframe and the +/// batches from its own on), the keyframe of the newest mark or clip of a +/// name, or a batch holding a frame of such a clip. +fn Trim(comptime DB: type) type { + return struct { + s: *Sessions, + keep: u64, + /// Bytes dropped, and counted after. + dropped: *u64, + left: *u64, + + const R = Read(DB); + const Map = DB.HashMap(.read_write); + const List = DB.ArrayList(.read_write); + + pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { + var arena: std.heap.ArenaAllocator = .init(ctx.s.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const root = try Map.init(cursor.*); + const all = try R.list(root.readOnly(), .sessions) orelse return; + const n = try all.count(); + var pinned: std.AutoHashMapUnmanaged(At, void) = .empty; + const Clip = struct { session: u64, start: u64, end: u64 }; + var clips: std.ArrayList(Clip) = .empty; + for ([_]K{ .marks, .clips }) |which| { + const list = try R.list(root.readOnly(), which) orelse continue; + var names: std.StringHashMapUnmanaged(void) = .empty; + var i = try list.count(); + while (i > 0) { + i -= 1; + const e = try R.at(list, i); + var buf: [max_name]u8 = undefined; + const name = (try R.field(e, .name)).readBytes(&buf) catch return error.CorruptSession; + if ((try names.getOrPut(a, try a.dupe(u8, name))).found_existing) continue; + const at: At = .{ .session = try R.uint(e, .session), .key = try R.uint(e, .key) }; + try pinned.put(a, at, {}); + const end = if (which == .clips) try R.uint(e, .end) else continue; + try clips.append(a, .{ .session = at.session, .start = try R.uint(e, .start), .end = if (end == 0) std.math.maxInt(u64) else end }); + } + } + // The present: the newest keyframe, and the batches from its own on. + var now: At = undefined; + var now_batch: u64 = 0; + var i = n; + while (true) { + if (i == 0) return; + i -= 1; + const keys = try R.list(try R.at(all, i), .keys) orelse continue; + const n_keys = try keys.count(); + if (n_keys == 0) continue; + now = .{ .session = i, .key = n_keys - 1 }; + now_batch = try R.uint(try R.at(keys, n_keys - 1), .batch); + break; + } + try pinned.put(a, now, {}); + // What is not dropped yet, each session's in frame order. + var items: std.ArrayList(Item) = .empty; + var total: u64 = 0; + for (0..n) |si| { + const ses = try R.at(all, si); + const start = items.items.len; + if (try R.list(ses, .keys)) |keys| for (0..try keys.count()) |k| { + const e = try R.at(keys, k); + if (try e.getCursor(key(.pages)) == null) continue; + const written = if (try e.getCursor(key(.written))) |w| try w.readUint() else 0; + try items.append(a, .{ .session = si, .index = k, .frame = try R.uint(e, .frame), .bytes = written, .batch = false, .keep = pinned.contains(.{ .session = si, .key = k }) }); + }; + if (try R.list(ses, .batches)) |batches| for (0..try batches.count()) |b| { + var c = try batches.getCursor(@intCast(b)) orelse continue; + if ((try c.slot()).tag == .none) continue; + var buf: [8]u8 = undefined; + var reader = try c.reader(&buf); + var head: [8]u8 = undefined; + try reader.interface.readSliceAll(&head); + try items.append(a, .{ .session = si, .index = b, .frame = std.mem.readInt(u64, &head, .little), .bytes = reader.size, .batch = true, .keep = si == now.session and b >= now_batch }); + }; + const mine = items.items[start..]; + std.mem.sort(Item, mine, {}, struct { + fn lessThan(_: void, x: Item, y: Item) bool { + return x.frame < y.frame or (x.frame == y.frame and !x.batch and y.batch); + } + }.lessThan); + // A batch holds frames up to the next batch's first. + const frames = try R.uint(ses, .frames); + var end: u64 = std.math.maxInt(u64); + var j = mine.len; + while (j > 0) { + j -= 1; + const it = &mine[j]; + if (!it.batch) continue; + const last = @min(end, frames); + for (clips.items) |clip| if (clip.session == si and clip.start < last and it.frame < clip.end) { + it.keep = true; + }; + end = it.frame; + } + for (mine) |it| total += it.bytes; + } + // Dropped oldest first. + const sessions = try List.init(try root.putCursor(key(.sessions))); + var left: std.ArrayList(u64) = .empty; + try left.appendNTimes(a, 0, n); + for (items.items) |it| { + if (it.keep or total <= ctx.keep) { + left.items[it.session] += 1; + continue; + } + const ses = try Map.init(try sessions.putCursor(@intCast(it.session))); + if (it.batch) { + try (try List.init(try ses.putCursor(key(.batches)))).put(@intCast(it.index), .{ .slot = null }); + } else { + const k = try Map.init(try (try List.init(try ses.putCursor(key(.keys)))).putCursor(@intCast(it.index))); + _ = try k.remove(key(.pages)); + try k.put(key(.written), .{ .uint = 0 }); + } + total -= it.bytes; + ctx.dropped.* += it.bytes; + } + ctx.left.* = total; + for (left.items, 0..) |kept, si| { + if (kept > 0 or si >= now.session) continue; + var any = false; + var it = pinned.keyIterator(); + while (it.next()) |at| any = any or at.session == si; + if (any) continue; + const ses = try Map.init(try sessions.putCursor(@intCast(si))); + for ([_]K{ .keys, .batches, .stretches }) |k| _ = try ses.remove(key(k)); + } + } + }; } -/// The bytes of every session's batches and keyframes: what compaction keeps. +/// The bytes of every session's batches and keyframes' pages (each written +/// once): what compaction keeps. /// Reading them all is also what proves a mended file whole. fn liveSize(db: *Disk) !u64 { const R = Read(Disk); @@ -222,11 +422,14 @@ fn liveSize(db: *Disk) !u64 { 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(); + while (try b.next()) |blob| live += if ((try blob.slot()).tag == .none) 0 else 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(); + while (try k.next()) |key_cursor| { + const e = try R.Map.init(key_cursor); + live += if (try e.getCursor(key(.written))) |w| try w.readUint() else try (try R.field(e, .state)).count(); + } } } return live; @@ -320,19 +523,38 @@ pub fn frame(s: *Sessions, one: []abi.Event, state: []const u8, why: ?Why) !void /// 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). +/// `before_reload` one: the last word in the old layout). Only the pages +/// whose hash differs from the last keyframe's are copied, and written. 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 hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, state.len, page) catch unreachable); + errdefer s.gpa.free(hashes); + var changed: std.ArrayList(u64) = .empty; + defer changed.deinit(s.gpa); + for (hashes, 0..) |*h, i| { + h.* = std.hash.Wyhash.hash(0, state[i * page .. @min(state.len, (i + 1) * page)]); + if (i >= s.hashes.len or s.hashes[i] != h.*) try changed.append(s.gpa, i); + } + if (s.keys > 0 and why != .before_reload and changed.items.len == 0 and hashes.len == s.hashes.len and s.key_stretch == s.stretches - 1) { + s.gpa.free(hashes); + return s.keys - 1; + } + const pages = try s.gpa.alloc(u8, changed.items.len * page); + errdefer s.gpa.free(pages); + for (changed.items, 0..) |i, k| { + const bytes = state[i * page .. @min(state.len, (i + 1) * page)]; + @memcpy(pages[k * page ..][0..bytes.len], bytes); + } + const indices = try changed.toOwnedSlice(s.gpa); + errdefer s.gpa.free(indices); 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 }); + try s.queued.append(s.gpa, .{ .frame = s.frames, .batch = s.batches, .stretch = s.stretches - 1, .why = why, .time = s.last_time, .size = state.len, .from = s.last, .indices = indices, .pages = pages, .line = line_copy }); + s.gpa.free(s.hashes); + s.hashes = hashes; + s.last = .{ .session = s.session, .key = s.keys }; s.key_time = s.last_time; - s.key_hash = hash; s.key_stretch = s.stretches - 1; s.keys += 1; return s.keys - 1; @@ -348,8 +570,15 @@ pub fn stretch(s: *Sessions, st: Stretch) !void { } /// Mark `name`: a keyframe of `state` (`why`: `.mark`, or `.import`), -/// synced to disk. Returns the keyframe's index. +/// synced to disk. Returns the keyframe's index. A mark of a new name needs +/// room for a whole State under `max_save`, history dropped to make it +/// (`trim`): without, it is refused (`error.SaveFull`). A mark over an +/// existing name lets the older one go with history. pub fn mark(s: *Sessions, name: []const u8, why: Why, state: []const u8) !u64 { + if (s.db == .file and try s.file.?.length(s.io) + state.len > max_save and try s.findMark(name) == null) { + try s.trim(); + if (try s.file.?.length(s.io) + state.len > max_save) return error.SaveFull; + } const k = try s.keyframe(why, state); try s.commitSynced(.{ .mark = .{ .name = name, .key = k } }); return k; @@ -371,7 +600,8 @@ pub fn stopClip(s: *Sessions) !void { fn dropQueued(s: *Sessions) void { for (s.queued.items) |k| { - s.gpa.free(k.state); + s.gpa.free(k.indices); + s.gpa.free(k.pages); s.gpa.free(k.line); } s.queued.clearRetainingCapacity(); @@ -416,7 +646,10 @@ pub fn commit(s: *Sessions, extra: Extra) !void { s.committed = s.frames; s.batch.clearRetainingCapacity(); } + const keyed = s.queued.items.len > 0; s.dropQueued(); + if (s.db != .file) return; + if ((try s.file.?.length(s.io)) > max_save or (!s.history and keyed)) s.trim() catch |err| std.log.warn("sessions: history not trimmed: {t}", .{err}); } fn Commit(comptime DB: type) type { @@ -456,8 +689,28 @@ fn Commit(comptime DB: type) type { 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(.size), .{ .uint = q.size }); try k.put(key(.line), .{ .bytes = q.line }); + // From the keyframe before's pages, copied as the + // transaction writes on (it may be in it too). + var from = try k.putCursor(key(.pages)); + if (q.from) |at| if (try pagesSlot(root, at)) |slot| { + try from.write(.{ .slot = slot }); + try from.freeze(); + }; + const pages = try List.init(from); + const had = try pages.count(); + var written: u64 = 0; + for (q.indices, 0..) |i, j| { + const bytes = q.pages[j * page ..][0..@min(page, q.size - i * page)]; + const zero = std.mem.allEqual(u8, bytes, 0); + if (!zero) written += bytes.len; + const data: DB.WriteableData = if (zero) .{ .slot = null } else .{ .bytes = bytes }; + if (i < had) try pages.put(@intCast(i), data) else try pages.append(data); + } + const n = std.math.divCeil(u64, q.size, page) catch unreachable; + if (had > n) try pages.slice(n); + try k.put(key(.written), .{ .uint = written }); } } switch (ctx.extra) { @@ -485,6 +738,13 @@ fn Commit(comptime DB: type) type { } } + /// The slot of keyframe `at`'s pages; null for one from before pages. + fn pagesSlot(root: Map, at: At) !?xitdb.Slot { + const R = Read(DB); + const ses = try R.at(try R.list(root.readOnly(), .sessions) orelse return null, at.session); + return (try R.at(try R.list(ses, .keys) orelse return null, at.key)).getSlot(key(.pages)); + } + fn putStretch(list: List, st: Stretch) !void { const item = try Map.init(try list.appendCursor()); try item.put(key(.frame), .{ .uint = st.frame }); @@ -513,6 +773,8 @@ pub const Entry = struct { }; /// A keyframe, its bytes `gpa`'s (`free`). pub const Loaded = struct { + /// Stored in pages (not whole, from before them). + paged: bool = true, frame: u64, batch: u64, why: Why, @@ -594,13 +856,15 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded { 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); + const pages = try R.list(e, .pages); + const state = if (pages) |list| try R.pages(list, try R.uint(e, .size), s.gpa) else if (try e.getCursor(key(.state))) |whole| try whole.readBytesAlloc(s.gpa, null) else return error.HistoryDropped; 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 .{ + .paged = pages != null, .frame = try R.uint(e, .frame), .batch = try R.uint(e, .batch), .why = why, @@ -616,6 +880,32 @@ pub fn load(s: *Sessions, session: u64, k: u64) !Loaded { } } +/// The State a run starts from, the present: the newest keyframe of the +/// sessions before this one, with the frames logged after it appended to +/// `out` (replayed, they bring it to where that run stopped). Null in a +/// new database. This run's first keyframe starts from its pages. +pub fn present(s: *Sessions, out: *std.ArrayList(abi.Event)) !?Loaded { + if (s.db == .off) return null; + var i = s.session; + while (i > 0) { + i -= 1; + const sum = try s.summary(i); + if (sum.keys == 0) continue; + const newest = try s.load(i, sum.keys - 1); + errdefer newest.free(s.gpa); + try s.events(i, newest.batch, newest.frame, sum.frames, out); + if (newest.paged) { + const hashes = try s.gpa.alloc(u64, std.math.divCeil(usize, newest.state.len, page) catch unreachable); + for (hashes, 0..) |*h, j| h.* = std.hash.Wyhash.hash(0, newest.state[j * page .. @min(newest.state.len, (j + 1) * page)]); + s.gpa.free(s.hashes); + s.hashes = hashes; + s.last = .{ .session = i, .key = sum.keys - 1 }; + } + return newest; + } + return null; +} + /// 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) { @@ -658,7 +948,9 @@ pub fn events(s: *Sessions, session: u64, from: u64, start: u64, end: u64, out: 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); + const cursor = try batches.getCursor(@intCast(i)) orelse return error.CorruptSession; + if ((try cursor.slot()).tag == .none) return error.HistoryDropped; + const blob = try cursor.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); @@ -775,6 +1067,8 @@ fn Transfer(comptime From: type, comptime To: type) type { const List = To.ArrayList(.read_write); pub fn run(ctx: @This(), cursor: *To.Cursor(.read_write)) !void { + var copied: std.AutoHashMap(u64, xitdb.Slot) = .init(ctx.gpa); + defer copied.deinit(); 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; @@ -786,7 +1080,7 @@ fn Transfer(comptime From: type, comptime To: type) type { 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); + try copy(From, To, ctx.gpa, try all.getCursor(@intCast(i)) orelse return error.CorruptSession, &to, &copied); 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| { @@ -797,7 +1091,7 @@ fn Transfer(comptime From: type, comptime To: type) type { 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); + try copy(From, To, ctx.gpa, e, &to, &copied); 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; @@ -811,21 +1105,27 @@ fn Transfer(comptime From: type, comptime To: type) type { }; } -/// 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) { +/// Copies the value at `from` (a uint, bytes, or a list or map of them) to +/// `to`. Bytes `copied` already (a page keyframes share) are written once: +/// it maps their place in `from` to their slot in `to`. +fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: From.Cursor(.read_only), to: *To.Cursor(.read_write), copied: *std.AutoHashMap(u64, xitdb.Slot)) anyerror!void { + const slot = try from.slot(); + switch (slot.tag) { + .none => try to.write(.{ .slot = null }), .uint => try to.write(.{ .uint = try from.readUint() }), .bytes, .short_bytes => { + if (slot.tag == .bytes) if (copied.get(slot.value)) |done| return to.write(.{ .slot = done }); const bytes = try from.readBytesAlloc(gpa, null); defer gpa.free(bytes); try to.write(.{ .bytes = bytes }); + if (slot.tag == .bytes) try copied.put(slot.value, try to.slot()); }, .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); + try copy(From, To, gpa, c, &next, copied); } }, .hash_map => { @@ -834,7 +1134,7 @@ fn copy(comptime From: type, comptime To: type, gpa: std.mem.Allocator, from: Fr 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); + try copy(From, To, gpa, kv.value_cursor, &next, copied); } }, else => return error.CorruptSession, @@ -861,6 +1161,19 @@ fn Read(comptime DB: type) type { fn bytes(map: Map, k: K, gpa: std.mem.Allocator) ![]const u8 { return (try field(map, k)).readBytesAlloc(gpa, null); } + /// `size` bytes from a keyframe's pages, `gpa`'s. + fn pages(l: List, size: u64, gpa: std.mem.Allocator) ![]u8 { + const out = try gpa.alloc(u8, size); + errdefer gpa.free(out); + @memset(out, 0); + for (0..try l.count()) |i| { + const c = try l.getCursor(@intCast(i)) orelse continue; + if ((try c.slot()).tag == .none) continue; + const into = out[@min(size, i * page)..@min(size, (i + 1) * page)]; + if ((c.readBytes(into) catch return error.CorruptSession).len != into.len) return error.CorruptSession; + } + return out; + } fn list(map: Map, k: K) !?List { return try List.init(try map.getCursor(key(k)) orelse return null); } @@ -1025,7 +1338,8 @@ test "a compacted session database is smaller and holds every session and frame" 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); + // Six keyframes of 8 bytes, the first all zeros: an empty page. + try std.testing.expectEqual(@as(u64, 600 * @sizeOf(abi.Event) + 10 * 8 + 5 * 8), live_size); try s.compact(); s.deinit(); const compacted = (try tmp.dir.statFile(io, "t.xitdb", .{})).size; @@ -1067,3 +1381,206 @@ test "a memory session stops recording at its bound, and what it holds still rea 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)); } + +test "a session's keyframes write only the pages that changed: a State of megabytes edited each minute, and one never changed" { + 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}); + // 4 MiB, every page holding something, one u64 edited a minute. + const state = try gpa.alloc(u8, 4 << 20); + defer gpa.free(state); + for (state, 0..) |*b, i| b.* = @truncate(i *% 7 + 1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + const minutes = 10; + var sizes: [minutes + 1]u64 = undefined; + for (0..minutes * 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)}; + if (f % 3600 == 1800) std.mem.writeInt(u64, state[(f / 3600) * 300_000 ..][0..8], f, .little); + try s.frame(&one, state, if (f == 0) .start else null); + if (f % 3600 == 0) { + try s.commit(.none); + sizes[f / 3600] = try s.file.?.length(io); + } + } + try s.commit(.none); + sizes[minutes] = try s.file.?.length(io); + // One keyframe a minute: at 0 s, 60 s, ... + try std.testing.expectEqual(@as(u64, minutes), s.keys); + // A minute is 216,000 bytes of ticks and a keyframe of one page with + // its copied path: under 230 KB a minute, where a whole State a + // keyframe was 4 MiB. + for (1..minutes) |m| try std.testing.expect(sizes[m + 1] - sizes[m] < 230_000); + // Every keyframe reads back whole: the edits made before it, and none after. + const want = try gpa.alloc(u8, state.len); + defer gpa.free(want); + for (0..minutes) |k| { + for (want, 0..) |*b, i| b.* = @truncate(i *% 7 + 1); + for (0..k) |m| std.mem.writeInt(u64, want[m * 300_000 ..][0..8], m * 3600 + 1800, .little); + const loaded = try s.load(s.session, k); + defer loaded.free(gpa); + try std.testing.expectEqual(@as(u64, k * 3600), loaded.frame); + try std.testing.expectEqualSlices(u8, want, loaded.state); + } + // A keyframe alone, in a commit of its own: one changed page is that + // page, its copied path and the keyframe's fields; no changed page (one + // kept before a reload) is the fields alone. + for ([_]bool{ true, false }) |edit| { + if (edit) state[123] +%= 1; + const before = try s.file.?.length(io); + _ = try s.keyframe(if (edit) .jump else .before_reload, state); + try s.commit(.none); + try std.testing.expect(try s.file.?.length(io) - before < @as(u64, if (edit) 12 << 10 else 8 << 10)); + } + const last = try s.load(s.session, s.keys - 1); + defer last.free(gpa); + try std.testing.expectEqualSlices(u8, state, last.state); +} + +test "an exported session keeps its keyframes' shared pages shared" { + 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}); + var out_buf: [std.fs.max_path_bytes]u8 = undefined; + const out = try std.fmt.bufPrint(&out_buf, ".zig-cache/tmp/{s}/one.xitdb", .{&tmp.sub_path}); + const state = try gpa.alloc(u8, 1 << 20); + defer gpa.free(state); + for (state, 0..) |*b, i| b.* = @truncate(i *% 13 + 1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + // Ten keyframes a byte apart. + 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)}; + if (f % 60 == 0) state[f * 100] +%= 1; + try s.frame(&one, state, if (f == 0) .start else if (f % 60 == 0) .jump else null); + } + try s.exportSession(0, out); + const size = (try std.Io.Dir.cwd().statFile(io, out, .{})).size; + // One State and nine pages, not ten States. + try std.testing.expect(size < state.len + state.len / 8); + var again = try open(gpa, io, .file, out, .{ .build = 7, .source = "", .layout = "a layout" }, 2000); + defer again.deinit(); + const loaded = try again.load(0, 9); + defer loaded.free(gpa); + try std.testing.expectEqualSlices(u8, state, loaded.state); +} + +test "a session database past max_save drops its oldest history: the present and the marks stay, the file under it" { + 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}); + // 2 MiB of State, its first half rewritten each second: a keyframe + // writes 1 MiB, so the cap is reached at about the 60th. + const state = try gpa.alloc(u8, 2 << 20); + defer gpa.free(state); + @memset(state, 1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + for (0..100) |k| { + @memset(state[0 .. 1 << 20], @truncate(k + 2)); + var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)}; + try s.frame(&one, state, if (k == 0) .start else .jump); + if (k == 5) _ = try s.mark("a", .mark, state); + if (k == 20) _ = try s.mark("b", .mark, state); + try std.testing.expect(try s.file.?.length(io) <= max_save); + } + try s.commit(.none); + // The oldest keyframes and frames are gone; the marks and the newest + // keyframe read back whole. + try std.testing.expectError(error.HistoryDropped, s.load(0, 1)); + var log: std.ArrayList(abi.Event) = .empty; + defer log.deinit(gpa); + try std.testing.expectError(error.HistoryDropped, s.events(0, 0, 0, 2, &log)); + for ([_]struct { []const u8, u8 }{ .{ "a", 7 }, .{ "b", 22 } }) |want| { + const m = (try s.findMark(want[0])).?; + const loaded = try s.load(m.session, m.key); + defer loaded.free(gpa); + try std.testing.expectEqual(want[1], loaded.state[0]); + try std.testing.expectEqual(@as(u8, 1), loaded.state[1 << 20]); + } + const newest = try s.load(0, s.keys - 1); + defer newest.free(gpa); + try std.testing.expectEqualSlices(u8, state, newest.state); + try s.events(0, newest.batch, newest.frame, s.frames, &log); +} + +test "a session database without history keeps the present and the marks, and leaves nothing else at exit" { + 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}); + var state: [64 << 10]u8 = @splat(1); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + s.history = false; + for (0..20) |k| { + @memset(state[0 .. 32 << 10], @truncate(k + 2)); + var one = [_]abi.Event{abi.Event.tick(k * std.time.ns_per_s, std.time.ns_per_s)}; + try s.frame(&one, &state, if (k == 0) .start else .jump); + if (k == 3) _ = try s.mark("a", .mark, &state); + } + try s.commit(.none); + try std.testing.expectError(error.HistoryDropped, s.load(0, 1)); + const m = (try s.findMark("a")).?; + const loaded = try s.load(m.session, m.key); + loaded.free(gpa); + s.close(&state, 2000); + // At exit: compacted to the present, the mark and the session's fields. + try std.testing.expect((try tmp.dir.statFile(io, "t.xitdb", .{})).size < 3 * state.len); + var again = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 3000); + defer again.deinit(); + var log: std.ArrayList(abi.Event) = .empty; + defer log.deinit(gpa); + const now = (try again.present(&log)).?; + defer now.free(gpa); + try std.testing.expectEqualSlices(u8, &state, now.state); +} + +test "a session database full of marks refuses a mark of a new name, and takes one over an old name" { + 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}); + // 2 MiB of State, all of it changed for each mark. + const state = try gpa.alloc(u8, 2 << 20); + defer gpa.free(state); + var s = try open(gpa, io, .file, path, .{ .build = 7, .source = "", .layout = "a layout" }, 1000); + defer s.deinit(); + var name: [8]u8 = undefined; + var k: u8 = 0; + while (true) : (k += 1) { + @memset(state, k + 1); + _ = s.mark(try std.fmt.bufPrint(&name, "m{d}", .{k}), .mark, state) catch |err| { + try std.testing.expectEqual(error.SaveFull, err); + break; + }; + try std.testing.expect(k < 40 and try s.file.?.length(io) <= max_save); + } + try std.testing.expect(k > 20); + @memset(state, 99); + try std.testing.expectError(error.SaveFull, s.mark("new", .mark, state)); + _ = try s.mark("m3", .mark, state); + try s.commit(.none); + try std.testing.expect(try s.file.?.length(io) <= max_save); + // Every mark's newest keyframe is whole. + for (0..k) |i| { + const m = (try s.findMark(try std.fmt.bufPrint(&name, "m{d}", .{i}))).?; + const loaded = try s.load(m.session, m.key); + defer loaded.free(gpa); + try std.testing.expectEqual(@as(u8, if (i == 3) 99 else @intCast(i + 1)), loaded.state[state.len - 1]); + } +} diff --git a/src/host/memory.zig b/src/host/memory.zig index 044fc3b..2749ea1 100644 --- a/src/host/memory.zig +++ b/src/host/memory.zig @@ -1,13 +1,12 @@ //! Sketch memory by lifetime. //! -//! `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. +//! `State`: process memory in the layout the sketch declares; a reload +//! with a changed layout carries the old values over field by field. It +//! outlives the process in the sessions database (Sessions.zig), whose +//! stretches keep its layout in the header format below. //! -//! `StoreFile`: a heap in a file, mapped at the same address in every run, -//! so what it holds may point into it: the sketch's `Store` and everything -//! allocated for it outlive restarts. +//! `OldState`: a state file from before the database held the present, +//! read once to import it. //! //! `Session`: this process's memory, kept across reloads. const std = @import("std"); @@ -18,7 +17,7 @@ const field_value = @import("fields.zig"); pub const page = std.heap.page_size_min; pub const header_len = 64 * 1024; -/// One slot, the live state: snapshots are marks in the sessions database. +/// A layout header, and an old file's one slot, the live state. 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`). @@ -291,167 +290,93 @@ fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) boo return true; } -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, +/// Live State: page aligned, in the running sketch's layout; `header` is +/// that layout as `layoutOf` reads it back, for the sessions' stretches. +pub const State = struct { + bytes: []align(page) u8 = &.{}, + layout: Layout = .{}, + header: []const u8 = "", + /// Owns `layout` and `header`. arena: std.heap.ArenaAllocator, - /// Opens or creates `path`. A new (empty) file has no layout and no used - /// slots: the first `adopt` fills it. A file that is not a state file - /// this host can read is refused, never truncated: it may be someone's - /// work, written by another build. - pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile { - const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); - errdefer _ = posix.system.close(fd); - var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) }; - errdefer self.arena.deinit(); - const len = try fileSize(fd); - if (len > 0) { - if (len < header_len) return error.NotAStateFile; - self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true }); - errdefer posix.munmap(self.map); - try self.check(); - self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{}; - return self; - } - try self.resize(0); - self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; - return self; + pub fn init(gpa: std.mem.Allocator) State { + return .{ .arena = .init(gpa) }; } - pub fn close(self: *StateFile) void { - if (self.map.len != 0) posix.munmap(self.map); - _ = posix.system.close(self.fd); + pub fn deinit(self: *State, gpa: std.mem.Allocator) void { + gpa.free(self.bytes); self.arena.deinit(); } - pub fn header(self: *StateFile) *Header { - 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 live(self: *State) []align(page) u8 { + return self.bytes[0..self.layout.size]; } - pub fn slot(self: *StateFile, index: usize) []align(page) u8 { - 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]); + /// Makes State hold `new`'s layout: a new allocation of its defaults + /// (`defaults`), then every leaf `migrate` keeps of the old State. Null + /// when the layout is unchanged, or there was none. + pub fn adopt(self: *State, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !?Migration { + const first = self.bytes.len == 0; + if (!first and self.layout.hash == new.hash and self.layout.size == new.size) return null; + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const layout = try Layout.copy(arena.allocator(), new); + const region = try arena.allocator().alignedAlloc(u8, .of(Header), header_len); + @memset(region, 0); + const h: *Header = @ptrCast(region.ptr); + h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = std.mem.alignForward(usize, @max(new.size, 1), page), .used = 1, .field_count = 0, .strings_len = 0 }; + try writeLayout(region, layout); + const bytes = try gpa.alignedAlloc(u8, .fromByteUnits(page), @max(new.size, 1)); + @memset(bytes, 0); + defaults(.state, bytes.ptr); + const m = if (first) null else migrate(self.layout, self.live(), layout, bytes); + self.deinit(gpa); + self.* = .{ .bytes = bytes, .layout = layout, .header = region[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len], .arena = arena }; + return m; } +}; - pub fn used(self: *StateFile, index: usize) bool { - return self.header().used & (@as(u32, 1) << @intCast(index)) != 0; - } - - pub fn markUsed(self: *StateFile, index: usize, value: bool) void { - const bit = @as(u32, 1) << @intCast(index); - if (value) self.header().used |= bit else self.header().used &= ~bit; - } - - pub const Adoption = union(enum) { - unchanged, - created, - migrated: Migration, - }; - - /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults` - /// writes the new default values, then unchanged fields are copied over. - pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption { - if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) { - // Same type, older header: describe it again, bytes untouched. - if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) { - var kept = self.arena; - defer kept.deinit(); - 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_v2; - } - return .unchanged; - } - const had_state = self.header().used & 1 != 0; - - // Keep the old bytes and layout while the file is rebuilt. - var old_arena: std.heap.ArenaAllocator = .init(gpa); - defer old_arena.deinit(); - const old_layout = self.layout; - 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; - // `old_layout` points into `self.arena`: move it aside before resetting. - var kept = self.arena; - defer kept.deinit(); - self.arena = .init(gpa); - - self.layout = try Layout.copy(self.arena.allocator(), new); - const stride = std.mem.alignForward(usize, @max(new.size, 1), page); - try self.resize(stride); - const h = self.header(); - 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); +/// A state file from before the sessions database held the present: a +/// layout header, then one slot (`file_magic`), or eight (`file_magic_v2`, +/// `file_magic_v1`), the first live State and the others snapshots. Mapped +/// read-only: imported once, never changed. +pub const OldState = struct { + map: []align(page) const u8, + slots: usize, - var total: Migration = .{}; - for (old_slots, 0..) |maybe_old, i| { - const old = maybe_old orelse continue; - const bytes = self.slot(i); - @memset(bytes, 0); - defaults(.state, bytes.ptr); - const m = migrate(old_layout, old, self.layout, bytes); - total.kept += m.kept; - if (i == 0) total.reset = m.reset; - } - if (!had_state) { - self.markUsed(0, false); - return .created; - } - return .{ .migrated = total }; + /// error.FileNotFound when `path` is missing or empty; a file that is + /// no state file this host reads is refused. + pub fn open(path: []const u8) !OldState { + const map = mapReadOnly(path); + if (map.len == 0) return error.FileNotFound; + errdefer posix.munmap(map); + if (map.len < header_len) return error.NotAStateFile; + const h: *const Header = @ptrCast(map.ptr); + const slots: usize = if (std.mem.eql(u8, &h.magic, &file_magic)) 1 else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) old_slot_count else return error.NotAStateFile; + if (map.len < header_len + slots * h.stride or h.size > h.stride) return error.CorruptStateFile; + return .{ .map = map, .slots = slots }; } - /// 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; + pub fn close(self: OldState) void { + posix.munmap(self.map); } - fn check(self: *StateFile) !void { - const h = self.header(); - 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; + /// The header and layout, as `restore` and `layoutOf` take them. + pub fn layoutBytes(self: OldState) []const u8 { + return self.map[0..header_len]; } - fn resize(self: *StateFile, stride: usize) !void { - 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)))) { - .SUCCESS => {}, - else => |err| return posix.unexpectedErrno(err), - } - self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true }); + /// Slot `i`'s State, null when the slot is unused. + pub fn slot(self: OldState, i: usize) ?[]const u8 { + const h: *const Header = @ptrCast(self.map.ptr); + if (h.used & (@as(u32, 1) << @intCast(i)) == 0) return null; + return self.map[header_len + i * h.stride ..][0..h.size]; } }; /// 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 +/// layout, described by `layout_bytes` (a header as `State.header` holds +/// 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); @@ -462,7 +387,7 @@ pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []cons return from; } -/// The layout in a header as `StateFile.layoutBytes` gives it, `arena`'s. +/// The layout in a header as `State.header` holds 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); @@ -515,14 +440,14 @@ fn writeLayout(region: []u8, layout: Layout) !void { h.strings_len = @intCast(strings); } -/// The layout stored in a state or store file's header, or null if it has -/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`, -/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole -/// leaves only, which migrate while their type is unchanged. +/// The layout stored in a state file's header, or null if it has none. +/// Reads both formats, by magic: a v1 header (`file_magic_v1`) has no +/// element leaves, so its arrays are whole leaves only, which migrate while +/// their type is unchanged. pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { const h: *const Header = @ptrCast(@alignCast(map.ptr)); if (h.hash == 0 and h.field_count == 0) return null; - const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1); + const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1); const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField); const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride; if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader; @@ -560,10 +485,6 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves }; } -pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 { - return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0); -} - pub fn fileSize(fd: posix.fd_t) !u64 { var stat: linux.Statx = undefined; switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) { @@ -582,208 +503,6 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 { return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{}; } -/// Where every store is mapped, in every process: far from where Linux puts -/// executables (0x55...) and mappings (0x7f...). -pub const store_base: usize = 0x2000_0000_0000; -/// The most a store can grow to. Only reserved: pages exist as they are used. -pub const store_reserve: usize = 64 << 30; -/// The allocator's record (`Meta`); unchanged by the layout format. -pub const store_magic = "SKSTORE1".*; -/// The store's layout header, like `file_magic` and `file_magic_v1`. -pub const store_layout_magic = "SKSTORE2".*; -pub const store_layout_magic_v1 = "SKSTORE1".*; -/// The layout region is a state file header; the allocator's own record -/// follows, then the heap. -const meta_offset = header_len; -const heap_offset = 2 * header_len; - -/// A heap in a file, with the sketch's `Store` at its root. Mapped at -/// `store_base` in every run, so pointers it holds into itself stay valid -/// across restarts. Not crash-safe: a crash in the middle of an allocation -/// can leave it inconsistent (`--fresh` starts over). -/// -/// Blocks come in power-of-two sizes, each class with a free list threaded -/// through the free blocks, so growing a list by doubling reuses what it -/// frees. The file grows by mapping more of it in place: nothing moves. -pub const StoreFile = struct { - fd: posix.fd_t, - /// Bytes of the file mapped at `store_base`. - len: usize, - /// The root's layout, owned by `arena`. - layout: Layout, - arena: std.heap.ArenaAllocator, - - const Meta = extern struct { - magic: [8]u8 = store_magic, - base: u64 = store_base, - /// Offset of the first byte never handed out. - top: u64 = heap_offset, - /// Offset of the sketch's Store, or 0 before the first adopt. - root: u64 = 0, - /// Offsets of the first free block of each size class (2^i bytes), 0 - /// when none; a free block's first 8 bytes hold the next one's. - free: [64]u64 = @splat(0), - }; - - pub fn open(gpa: std.mem.Allocator, path: []const u8, fresh: bool) !StoreFile { - const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); - errdefer _ = posix.system.close(fd); - // The same file mapped by two processes would be two heaps writing - // over each other. - if (linux.errno(linux.flock(fd, posix.LOCK.EX | posix.LOCK.NB)) != .SUCCESS) return error.StoreInUse; - const reserved = posix.mmap(@ptrFromInt(store_base), store_reserve, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED_NOREPLACE = true }, -1, 0) catch return error.StoreAddressTaken; - // Old kernels treat FIXED_NOREPLACE as a hint. - if (@intFromPtr(reserved.ptr) != store_base) { - posix.munmap(reserved); - return error.StoreAddressTaken; - } - errdefer posix.munmap(reserved); - var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) }; - errdefer self.arena.deinit(); - const size: usize = @intCast(try fileSize(fd)); - if (!fresh and size > 0) { - // Checked before mapping, which may lengthen the file: a file - // that is not a store is refused untouched, never wiped. - var m: Meta = undefined; - const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset); - if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile; - try self.grow(size); - self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{}; - return self; - } - try self.wipe(); - return self; - } - - pub fn close(self: *StoreFile) void { - posix.munmap(@as([*]align(page) u8, @ptrFromInt(store_base))[0..store_reserve]); - _ = posix.system.close(self.fd); - self.arena.deinit(); - } - - /// Empties the store: no root, nothing allocated. - fn wipe(self: *StoreFile) !void { - // Mapped pages past the new end would fault: map the reserve back. - if (self.len > heap_offset) { - _ = try posix.mmap(@ptrFromInt(store_base + heap_offset), self.len - heap_offset, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED = true }, -1, 0); - self.len = heap_offset; - } - try truncate(self.fd, heap_offset); - try self.grow(heap_offset); - @memset(self.region(), 0); - self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; - self.meta().* = .{}; - self.layout = .{}; - } - - /// Maps the file up to `need` bytes, growing it when it is shorter. - fn grow(self: *StoreFile, need: usize) !void { - if (need <= self.len) return; - const len = std.mem.alignForward(usize, @max(need, self.len * 2, 1 << 20), page); - if (len > store_reserve) return error.StoreFull; - if (try fileSize(self.fd) < len) try truncate(self.fd, len); - _ = try posix.mmap(@ptrFromInt(store_base + self.len), len - self.len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .SHARED, .FIXED = true }, self.fd, self.len); - self.len = len; - } - - fn region(_: *StoreFile) []u8 { - return @as([*]u8, @ptrFromInt(store_base))[0..header_len]; - } - fn header(_: *StoreFile) *Header { - return @ptrFromInt(store_base); - } - fn meta(_: *StoreFile) *Meta { - return @ptrFromInt(store_base + meta_offset); - } - - /// The sketch's Store. - pub fn root(self: *StoreFile) [*]u8 { - const offset = self.meta().root; - return @ptrFromInt(store_base + if (offset == 0) heap_offset else offset); - } - - pub const Adoption = StateFile.Adoption; - - /// Makes the root hold `new`'s layout: the new defaults, then every field - /// whose path and type are unchanged, copied over. Pointer fields keep - /// pointing where they did, since the store never moves. - pub fn adopt(self: *StoreFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption { - const m = self.meta(); - if (m.root != 0 and self.layout.hash == new.hash and self.layout.size == new.size) return .unchanged; - const a = self.allocator(); - const alignment: std.mem.Alignment = .fromByteUnits(@max(new.alignment, 1)); - const fresh = a.rawAlloc(@max(new.size, 1), alignment, @returnAddress()) orelse return error.StoreFull; - @memset(fresh[0..@max(new.size, 1)], 0); - defaults(.store, fresh); - - var kept = self.arena; - defer kept.deinit(); - self.arena = .init(gpa); - const old_layout = self.layout; - self.layout = try Layout.copy(self.arena.allocator(), new); - var result: Adoption = .created; - if (m.root != 0) { - const old: [*]u8 = @ptrFromInt(store_base + m.root); - result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) }; - a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress()); - } - self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 }; - try writeLayout(self.region(), self.layout); - m.root = @intFromPtr(fresh) - store_base; - return result; - } - - pub fn allocator(self: *StoreFile) std.mem.Allocator { - return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; - } - - fn class(len: usize, alignment: std.mem.Alignment) u6 { - return @intCast(std.math.log2_int_ceil(usize, @max(len, alignment.toByteUnits(), 16))); - } - - fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - const self: *StoreFile = @ptrCast(@alignCast(ctx)); - const m = self.meta(); - const c = class(len, alignment); - const size = @as(usize, 1) << c; - if (m.free[c] != 0) { - const block: [*]u8 = @ptrFromInt(store_base + m.free[c]); - if (alignment.check(@intFromPtr(block))) { - m.free[c] = @as(*const u64, @ptrCast(@alignCast(block))).*; - return block; - } - } - const offset = std.mem.alignForward(usize, m.top, @max(@min(size, page), alignment.toByteUnits())); - self.grow(offset + size) catch return null; - m.top = offset + size; - return @ptrFromInt(store_base + offset); - } - - /// In place within the block's size class. - fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool { - return class(memory.len, alignment) == class(new_len, alignment); - } - - fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret: usize) ?[*]u8 { - return if (resize(ctx, memory, alignment, new_len, ret)) memory.ptr else null; - } - - fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, _: usize) void { - const self: *StoreFile = @ptrCast(@alignCast(ctx)); - const m = self.meta(); - const c = class(memory.len, alignment); - @as(*u64, @ptrCast(@alignCast(memory.ptr))).* = m.free[c]; - m.free[c] = @intFromPtr(memory.ptr) - store_base; - } -}; - -fn truncate(fd: posix.fd_t, len: usize) !void { - switch (posix.errno(posix.system.ftruncate(fd, @intCast(len)))) { - .SUCCESS => {}, - else => |err| return posix.unexpectedErrno(err), - } -} - /// Session memory: survives reloads while its layout hash is unchanged. /// Everything allocated from `heap` is released with it. pub const Session = struct { @@ -921,7 +640,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 a reopen reads the layout back" { +test "State migrates to a changed layout, and keeps itself when it is unchanged" { const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* }; const V2 = extern struct { level: u16 = 1, score: u32 = 0 }; const D = struct { @@ -932,65 +651,20 @@ test "state file migrates live state, and a reopen reads the layout back" { @as(*V2, @ptrCast(@alignCast(p))).* = .{}; } }; - 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}/test.state", .{&tmp.sub_path}); const gpa = std.testing.allocator; - { - var file = try StateFile.open(gpa, path); - defer file.close(); - 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; - } - 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); - 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" { - const V1 = struct { list: std.ArrayList(u32) = .empty, count: u32 = 0 }; - const V2 = struct { added: u8 = 7, list: std.ArrayList(u32) = .empty }; - const D = struct { - fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void { - @as(*V1, @ptrCast(@alignCast(p))).* = .{}; - } - fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void { - @as(*V2, @ptrCast(@alignCast(p))).* = .{}; - } - }; - 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}/test.store", .{&tmp.sub_path}); - const gpa = std.testing.allocator; - { - var store = try StoreFile.open(gpa, path, false); - defer store.close(); - try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1)); - const v: *V1 = @ptrCast(@alignCast(store.root())); - for (0..10_000) |i| try v.list.append(store.allocator(), @intCast(i)); - v.count = 3; - try std.testing.expectError(error.StoreInUse, StoreFile.open(gpa, path, false)); - } - { - var store = try StoreFile.open(gpa, path, false); - defer store.close(); - try std.testing.expectEqual(StoreFile.Adoption.unchanged, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1)); - const adoption = try store.adopt(gpa, abi.layout.of(V2, .store), D.v2); - try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset); - const v: *V2 = @ptrCast(@alignCast(store.root())); - try std.testing.expectEqual(@as(u8, 7), v.added); - try std.testing.expectEqual(@as(u32, 9999), v.list.items[9999]); - v.list.deinit(store.allocator()); - } - var store = try StoreFile.open(gpa, path, true); - defer store.close(); - try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2)); + var state: State = .init(gpa); + defer state.deinit(gpa); + try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1)); + @as(*V1, @ptrCast(state.live().ptr)).score = 99; + try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1)); + try std.testing.expectEqual(@as(u32, 99), @as(*V1, @ptrCast(state.live().ptr)).score); + const m = (try state.adopt(gpa, abi.layout.of(V2, .state), D.v2)).?; + try std.testing.expectEqual(@as(usize, 1), m.reset); + try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(@alignCast(state.live().ptr))).*); + // The header reads back as the layout. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + try std.testing.expectEqual(abi.layout.hash(V2), (try layoutOf(arena.allocator(), state.header)).hash); } test "arrays migrate element by element: fields, enums by name, shrink and growth" { @@ -1105,14 +779,15 @@ test "a file that is not a state file is refused, untouched" { defer std.testing.allocator.free(text); @memset(text, 'x'); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }); - try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path)); + try std.testing.expectError(error.NotAStateFile, OldState.open(path)); const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited); defer std.testing.allocator.free(after); try std.testing.expectEqualSlices(u8, text, after); } + try std.testing.expectError(error.FileNotFound, OldState.open(try testPath(&buf, tmp, "none.state"))); } -test "a state file from before element leaves (drat-meout's) keeps every value" { +test "a state file from before element leaves (drat-meout's) imports with every value" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); @@ -1132,30 +807,29 @@ test "a state file from before element leaves (drat-meout's) keeps every value" const h: *const Header = @ptrCast(@alignCast(original.ptr)); const live = original[header_len..][0..h.size]; - // The layout the game had when it wrote the file, as a sketch would - // describe it: unchanged, so nothing migrates and the header is - // rewritten in the new format. - const same = try asSketchLayout(a, old, &.{}); - { - 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_v2, &file.header().magic); - } - var file = try StateFile.open(gpa, path); + const file = try OldState.open(path); defer file.close(); - try std.testing.expectEqual(old.fields.len, file.layout.fields.len); - try std.testing.expectEqualSlices(u8, live, file.slot(0)); - - // A changed layout (one field gone, one new): every other leaf keeps - // its value, the songs included (an unchanged array type, so whole). - const changed = try asSketchLayout(a, old, "scene"); - _ = try file.adopt(gpa, changed, NoDefaults.f); - for (old.fields) |leaf| { - if (std.mem.eql(u8, leaf.path, "scene")) continue; - try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0))); + try std.testing.expectEqual(@as(usize, old_slot_count), file.slots); + // Into the layout the game had when it wrote the file, as a sketch would + // describe it: every byte; then into a changed one (one field gone, one + // new): every other leaf keeps its value, the songs included (an + // unchanged array type, so whole). + for ([_][]const u8{ "", "scene" }) |drop| { + var state: State = .init(gpa); + defer state.deinit(gpa); + _ = try state.adopt(gpa, try asSketchLayout(a, old, drop), NoDefaults.f); + @memset(state.live(), 0); + _ = try restore(a, file.layoutBytes(), file.slot(0).?, state.layout, state.live(), NoDefaults.f); + if (drop.len == 0) try std.testing.expectEqualSlices(u8, live, state.live()); + for (old.fields) |leaf| { + if (drop.len > 0 and std.mem.eql(u8, leaf.path, drop)) continue; + try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(state.live())); + } } - try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]); + // The file is as it was. + const after = try tmp.dir.readFileAlloc(io, "game.state", gpa, .unlimited); + defer gpa.free(after); + try std.testing.expectEqualSlices(u8, original, after); } const NoDefaults = struct { diff --git a/src/host/probe.zig b/src/host/probe.zig deleted file mode 100644 index 4b61153..0000000 --- a/src/host/probe.zig +++ /dev/null @@ -1,86 +0,0 @@ -//! sketchbook-probe: prints the live state of any running sketch, from its -//! state file alone. The file header carries the layout, so the probe needs -//! no knowledge of the sketch: it maps the same pages read-only. -const std = @import("std"); -const memory = @import("memory.zig"); -const fields = @import("fields.zig"); - -const usage = - \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE - \\Prints every field of the live state; --watch prints again on change. - \\ -; - -pub fn main(init: std.process.Init) !void { - var path: ?[]const u8 = null; - var watch = false; - var interval_ms: i64 = 100; - var args = init.minimal.args.iterate(); - _ = args.skip(); - while (args.next()) |arg| { - if (std.mem.eql(u8, arg, "--watch")) { - watch = true; - } else if (std.mem.eql(u8, arg, "--interval")) { - interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds"); - } else if (std.mem.startsWith(u8, arg, "-")) { - std.debug.print("{s}", .{usage}); - return; - } else path = arg; - } - const file = path orelse fatal("no state file given"); - 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_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(); - const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet"); - const header: *const memory.Header = @ptrCast(@alignCast(map.ptr)); - const live = map[memory.header_len..][0..header.size]; - - const shown = try arena.allocator().dupe(u8, live); - show(file, layout, live); - while (watch) { - try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake); - if (std.mem.eql(u8, shown, live)) continue; - @memcpy(shown, live); - show(file, layout, live); - } -} - -fn show(path: []const u8, layout: memory.Layout, live: []const u8) void { - var buf: [4096]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash }); - for (layout.fields) |leaf| { - // Whole arrays are shown by their elements' leaves. - if (leaf.whole()) continue; - w.end = 0; - if (leaf.dims.len == 0) { - fields.format(leaf, live, &w) catch {}; - } else { - // Elements in index order, the first few. - var it = leaf.elements(); - var n: usize = 0; - while (it.next()) |offset| : (n += 1) { - if (n == 8) { - w.writeAll(" ...") catch {}; - break; - } - if (n > 0) w.writeAll(" ") catch {}; - fields.format(leaf.at(offset), live, &w) catch {}; - } - } - var name: [128]u8 = undefined; - var nw: std.Io.Writer = .fixed(&name); - nw.writeAll(leaf.path) catch {}; - for (leaf.dims) |d| nw.print(" [{d}]", .{d.count}) catch {}; - std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, nw.buffered(), w.buffered() }); - } -} - -fn fatal(message: []const u8) noreturn { - std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage }); - std.process.exit(2); -} diff --git a/src/host/root.zig b/src/host/root.zig index 5889b42..9c7ad77 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -2,11 +2,11 @@ //! that it hot-reloads whenever a build replaces it. //! //! sketchbook [options] [LIBRARY] -//! --state FILE persistent state (default: $XDG_DATA_HOME/<name>/<name>.state; -//! sketch.state for a script or an export) +//! --state FILE the save (default: $XDG_DATA_HOME/<name>/<name>.xitdb; +//! sketch.xitdb 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 (sessions, marks and clips are kept) +//! --fresh start from default state (the save's history is 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) @@ -93,25 +93,9 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg"); } - // 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 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{ "", ".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; - const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue; - _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr); - }; + if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb"; + // A scripted run from fresh state, or an export, touches no save. + if (!((script_path != null or options.export_to != null) and options.fresh)) sketchbookDir(init.io, options.state); sdl_heap.install(); { @@ -131,11 +115,12 @@ 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; sessions are kept beside it (default: - \\ $XDG_DATA_HOME/<name>/<name>.state, sketch.state for --script, --export) + \\ --state FILE the save, one file: FILE, or FILE.xitdb for a FILE.state (where a + \\ state file from before is imported from, once); default: + \\ $XDG_DATA_HOME/<name>/<name>.xitdb, sketch.xitdb for --script, --export \\ --headless offscreen video, silent audio, no vsync \\ --script FILE play a script instead of reading devices - \\ --fresh start from default state (sessions, marks and clips are kept) + \\ --fresh start from default state (the save's history is 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) @@ -148,10 +133,10 @@ 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 +/// A save in a directory named `.sketchbook` (`zig build run`'s): the +/// directory is made, with a `.gitignore` of `*` (the save grows, and a jj +/// snapshot would commit it), and the state file an older build kept beside +/// it (`<stem>.state`) is moved in, once, to be imported. 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; @@ -161,20 +146,16 @@ fn sketchbookDir(io: std.Io, state: []const u8) void { 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 => {}, - } + 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 stem = Host.stemOf(std.fs.path.basename(state)); + const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}.state", .{ parent, stem }, 0) catch return; + const to = std.fmt.bufPrintSentinel(&to_buf, "{s}/{s}.state", .{ dir, stem }, 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 }), + else => {}, } } diff --git a/src/host/timeline.zig b/src/host/timeline.zig index c2eeff3..e755433 100644 --- a/src/host/timeline.zig +++ b/src/host/timeline.zig @@ -45,8 +45,8 @@ pub const Frames = struct { pub const Timeline = struct { gpa: std.mem.Allocator, - /// Live state is its slot 0. - state: *memory.StateFile, + /// Live State. + state: *memory.State, /// The running sketch's: a restore starts from its defaults. defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void, mode: abi.Mode = .live, @@ -90,7 +90,7 @@ pub const Timeline = struct { 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); + _ = try memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, self.state.live(), self.defaults); self.restored = true; self.fed = 0; self.next_check = 0; @@ -202,18 +202,14 @@ pub const Timeline = struct { 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 gpa.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.page); - defer gpa.free(file.map); - @memset(file.map, 0); - 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 }; + // Live State: 8 bytes, no fields. const D = struct { fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {} }; - var t: Timeline = .{ .gpa = gpa, .state = &file, .defaults = D.f }; + var state: memory.State = .init(gpa); + defer state.deinit(gpa); + _ = try state.adopt(gpa, .{ .size = 8, .alignment = 1, .hash = 1, .fields = &.{} }, D.f); + var t: Timeline = .{ .gpa = gpa, .state = &state, .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). @@ -223,7 +219,7 @@ test "frames are whole: input waits for its tick, in playback, seek and step" { try events.append(gpa, abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667)); } 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()) }; + 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, state.header) }; t.load(key, events); try t.play(0); diff --git a/src/layout.zig b/src/layout.zig index 5e60e22..c585d71 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -13,23 +13,28 @@ //! against a leaf's pattern at lookup time. //! //! What each kind of sketch memory may hold: -//! - State is saved to disk and snapshotted: no pointers, and no host -//! handles (images, sounds, buffers), which only mean something in the -//! process that made them. +//! - State is saved, the one thing a sketch keeps, in keyframes of its +//! save: no pointers, and no host handles (images, sounds, buffers), +//! which only mean something in the process that made them; at most +//! `max_state` bytes. //! - Session lives in this process: anything, as long as pointers go into //! memory the host owns (its heaps, mapped files), never into the sketch //! library, which a reload unmaps. -//! - Store is a file mapped at the same address in every run: pointers into -//! the store itself, but no host handles. const std = @import("std"); const abi = @import("abi.zig"); +/// The most a State may be, in bytes: half of the 64 MiB a save holds, so +/// history has room (Sessions.max_save). +pub const max_state = 32 << 20; + pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout { return comptime blk: { @setEvalBranchQuota(1_000_000); switch (memory) { - .state => check(T, "State", @typeName(T), false), - .store => check(T, "Store", @typeName(T), true), + .state => { + check(T, @typeName(T)); + if (@sizeOf(T) > max_state) @compileError(std.fmt.comptimePrint("State is {d} bytes, and may be {d} MiB, half of a save, so history has room: lower a capacity (an array, an sk.List), or keep what need not be saved in Session.", .{ @sizeOf(T), max_state >> 20 })); + }, .session => {}, } const Leaves = struct { @@ -155,17 +160,16 @@ pub fn resolve(fields: []const abi.Field, path: []const u8) ?Resolved { return null; } -fn check(comptime T: type, comptime memory: []const u8, comptime path: []const u8, comptime pointers: bool) void { +fn check(comptime T: type, comptime path: []const u8) void { comptime { - if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError(memory ++ " cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session."); + if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError("State cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session."); switch (@typeInfo(T)) { - // Not followed: types can point to themselves. - .pointer => if (!pointers) @compileError(memory ++ " cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Store or Session."), - .array => |a| check(a.child, memory, path ++ "[]", pointers), - .vector => |v| check(v.child, memory, path ++ "[]", pointers), - .optional => |o| check(o.child, memory, path, pointers), - .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers), - .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, memory, path ++ "." ++ name, pointers), + .pointer => @compileError("State cannot hold pointers (" ++ path ++ "): it is saved to disk and outlives every address. Keep indices or offsets, or put it in Session."), + .array => |a| check(a.child, path ++ "[]"), + .vector => |v| check(v.child, path ++ "[]"), + .optional => |o| check(o.child, path), + .@"struct" => |s| for (s.field_names, s.field_types) |name, F| check(F, path ++ "." ++ name), + .@"union" => |u| for (u.field_names, u.field_types) |name, F| check(F, path ++ "." ++ name), else => {}, } } diff --git a/src/sketch/request.zig b/src/sketch/request.zig index 0b8b400..4a8e414 100644 --- a/src/sketch/request.zig +++ b/src/sketch/request.zig @@ -1,5 +1,5 @@ //! Requests from `update` that `draw` carries out once. `update` sees only -//! State and input, so when a key should do something to Session or Store +//! State and input, so when a key should do something to Session //! (start the microphone, open a dialog, seek a stream), State holds the //! request and Session remembers which ones it has handled: //! diff --git a/src/sketch/root.zig b/src/sketch/root.zig index 0ab04a7..2a7c64a 100644 --- a/src/sketch/root.zig +++ b/src/sketch/root.zig @@ -7,19 +7,18 @@ //! pub const height = 600; //! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers //! pub const Session = struct { ... }; // this process: survives reloads -//! pub const Store = struct { ... }; // on disk: survives restarts too //! pub const commands = .{"hello"}; // console completions //! pub fn init(state: *State, host: sk.Host) void //! pub fn setup(session: *Session, init: *sk.Init) !void //! pub fn update(state: *State, in: *const sk.Input) void -//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void -//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool +//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void +//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool //! //! Functions take the parameters they name, by type, in any order: `draw` -//! may ask for `*Session`, `*Store`, both or neither. `update` must be +//! may ask for `*Session` or not. `update` must be //! deterministic, so it gets `State` and `Input` only: the host replays //! recorded input through it. `draw` presents state as pictures and sound, -//! and changes only Session and Store. Geometry and colors are duck-typed: +//! and changes only Session. Geometry and colors are duck-typed: //! see `shape`. const std = @import("std"); pub const abi = @import("abi"); @@ -67,7 +66,6 @@ pub const Face = abi.Face; pub const Init = struct { host: Host, session: std.mem.Allocator, - store: std.mem.Allocator, }; /// What `draw` receives: input, host services, memory by lifetime and the @@ -82,14 +80,12 @@ pub const Frame = struct { scratch: std.mem.Allocator, /// For Session: this process. session: std.mem.Allocator, - /// For Store: on disk, across restarts. - store: std.mem.Allocator, /// A library's own state for this frame (canim's table of places), in /// `scratch`: null at each frame's start. user: ?*anyopaque = null, pub fn init(ctx: *const abi.Context) Frame { - return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store }; + return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session }; } pub fn emit(f: *Frame, command: abi.Command) void { @@ -298,12 +294,11 @@ fn paint(value: anytype) Color { } /// What `command` receives: somewhere to answer, the current input, and the -/// allocators for Session and Store. +/// allocator for Session. pub const Console = struct { host: Host, in: *const Input, session: std.mem.Allocator, - store: std.mem.Allocator, pub fn log(c: *Console, message: []const u8) void { c.host.log(message); @@ -318,7 +313,7 @@ pub const Console = struct { 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`). + /// Keep history in the save (`abi.Info.record`). record: bool = false, }; @@ -346,7 +341,6 @@ 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.*; @@ -357,7 +351,6 @@ pub fn Glue(comptime App: type, comptime made: Build) type { .height = if (@hasDecl(App, "height")) App.height else 600, .state = abi.layout.of(State, .state), .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, @@ -384,10 +377,10 @@ pub fn Glue(comptime App: type, comptime made: Build) type { return std.mem.eql(u8, name, n); } }; - if (comptime is.named("update") and (T == *Session or T == *Store)) + if (comptime is.named("update") and T == *Session) @compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it"); if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input)) - @compileError("setup initializes resources: it gets Session, Store, Init and Host only"); + @compileError("setup initializes resources: it gets Session, Init and Host only"); if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does"); if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State"); if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does"); @@ -396,8 +389,6 @@ pub fn Glue(comptime App: type, comptime made: Build) type { @ptrCast(@alignCast(offer.state)) else if (T == *Session or T == *const Session) @ptrCast(@alignCast(offer.ctx.session_root)) - else if (T == *Store or T == *const Store) - @ptrCast(@alignCast(offer.ctx.store_root)) else if (T == *const Input) offer.ctx.input else if (T == Host) @@ -423,7 +414,6 @@ pub fn Glue(comptime App: type, comptime made: Build) type { switch (which) { .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, .session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{}, - .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{}, } } pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { @@ -431,7 +421,7 @@ pub fn Glue(comptime App: type, comptime made: Build) type { } pub fn setup(ctx: *const abi.Context) callconv(.c) bool { if (!@hasDecl(App, "setup")) return true; - var resource_init: Init = .{ .host = ctx.host, .session = ctx.session, .store = ctx.store }; + var resource_init: Init = .{ .host = ctx.host, .session = ctx.session }; const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init }); if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| { ctx.host.print("session setup failed: {t}", .{err}); @@ -449,7 +439,7 @@ pub fn Glue(comptime App: type, comptime made: Build) type { } pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome { if (!@hasDecl(App, "command")) return .unknown; - var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store }; + var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session }; const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| { c.print("{t}. Type help for usage.", .{err}); return .failed; @@ -495,7 +485,6 @@ test "setup receives session resources without a Frame and reports errors" { ctx.host = .{ .ctx = &seen, .vtable = &vtable }; ctx.session_root = std.mem.asBytes(&session); ctx.session = std.testing.allocator; - ctx.store = std.testing.allocator; const app = sketch(App, .{}); try std.testing.expect(!app.setup(&ctx)); defer std.testing.allocator.free(session.bytes); diff --git a/src/sketch/web.zig b/src/sketch/web.zig index a035117..804a4df 100644 --- a/src/sketch/web.zig +++ b/src/sketch/web.zig @@ -2,7 +2,7 @@ //! the imports below: drawing on a 2D canvas, GPU work on WebGPU, sound and //! the microphone on Web Audio, files through the page. State, `update` and //! `draw` are the same Zig as on native. There is no timeline, and nothing -//! persists: Store lasts as long as the page. +//! persists. const std = @import("std"); const abi = @import("abi"); const root = @import("root.zig"); @@ -84,8 +84,6 @@ fn Driver(comptime App: type) type { var ready = false; var state: G.State = undefined; var session: G.Session = undefined; - // No disk on the web: the store lasts as long as the page. - var store: G.Store = undefined; var events: [1024]abi.Event = undefined; var event_count: usize = 0; var input: abi.Input = .{}; @@ -107,9 +105,7 @@ fn Driver(comptime App: type) type { .input = &input, .scratch = scratch.allocator(), .session = gpa, - .store = gpa, .session_root = std.mem.asBytes(&session), - .store_root = std.mem.asBytes(&store), .commands = &commands, }; } @@ -117,7 +113,6 @@ fn Driver(comptime App: type) type { fn init() callconv(.c) void { G.defaults(.state, std.mem.asBytes(&state)); G.defaults(.session, std.mem.asBytes(&session)); - G.defaults(.store, std.mem.asBytes(&store)); input.width = G.description.width; input.height = G.description.height; if (input.window_width == 0) { @@ -420,6 +415,7 @@ fn Driver(comptime App: type) type { .newSound = newSound, .samples = samples, .readFile = readFile, + .appendFile = appendFile, .env = env, .clock = clock, }; @@ -484,6 +480,10 @@ fn Driver(comptime App: type) type { fn readFile(_: *anyopaque, _: []const u8) []const u8 { return &.{}; } + /// No files on the web: nothing is written, and the path is "". + fn appendFile(_: *anyopaque, _: [*]const u8, _: usize, _: [*]const u8, _: usize, _: bool) callconv(.c) [*:0]const u8 { + return ""; + } fn env(_: *anyopaque, _: []const u8) ?[]const u8 { return null; } diff --git a/src/vector/svg.zig b/src/vector/svg.zig index 31d9b15..f1b7daf 100644 --- a/src/vector/svg.zig +++ b/src/vector/svg.zig @@ -4,11 +4,12 @@ //! `ellipse`, `line`, `polyline`, `polygon`. Styling: presentation //! attributes and `style="..."`, inherited as SVG specifies; solid colors, //! linear and radial gradients; fill rules; stroke width, caps, joins, miter -//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. +//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. Images +//! that are SVG documents in base64 data URIs (Typst's SVG and PDF images). //! //! Not supported: text (Typst outlines it), filters, masks, clipping, -//! patterns, markers, images, CSS stylesheets. Group opacity is approximated -//! by multiplying it into each shape. +//! patterns, markers, raster images, CSS stylesheets. Group opacity is +//! approximated by multiplying it into each shape. const std = @import("std"); const geom = @import("math"); const Drawing = @import("Drawing.zig"); @@ -23,23 +24,26 @@ pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing { const root = doc.root orelse return error.InvalidSvg; if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return error.InvalidSvg; - var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = .{} }; - const n = doc.nodes.items[root]; - const w = doc.attr(n, "width"); - const h = doc.attr(n, "height"); + const port = viewport(&doc, doc.nodes.items[root]); + var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = port.view }; + try p.children(root, .identity, .{}); + return p.b.finish(port.view, port.width, port.height); +} + +/// A root `svg` element's view box and size in pixels, each standing in +/// for the other when missing. +fn viewport(doc: *const Document, n: Node) struct { view: geom.Rect, width: f32, height: f32 } { var view: geom.Rect = .{}; if (doc.attr(n, "viewBox")) |vb| { var nums = Numbers{ .text = vb }; view = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; } - var width = if (w) |v| lengthPx(v, view.w) else view.w; - var height = if (h) |v| lengthPx(v, view.h) else view.h; + var width = if (doc.attr(n, "width")) |v| lengthPx(v, view.w) else view.w; + var height = if (doc.attr(n, "height")) |v| lengthPx(v, view.h) else view.h; if (view.w <= 0 or view.h <= 0) view = .{ .w = width, .h = height }; if (width <= 0) width = view.w; if (height <= 0) height = view.h; - p.view = view; - try p.children(root, .identity, .{}); - return p.b.finish(view, width, height); + return .{ .view = view, .width = width, .height = height }; } // --------------------------------------------------------------------------- @@ -183,7 +187,7 @@ const Parser = struct { fn element(p: *Parser, index: u32, parent_transform: Affine, parent: Inherited) Error!void { const n = p.doc.nodes.items[index]; const name = n.name; - const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "image", "foreignObject" }; + const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "foreignObject" }; for (skip) |s| if (std.mem.eql(u8, name, s)) return; if (p.depth > 64) return; var inherited = parent; @@ -229,6 +233,52 @@ const Parser = struct { } return p.element(target, transform, inherited); } + if (std.mem.eql(u8, name, "image")) { + // An SVG as a base64 data URI, Typst's way to place an SVG or a + // PDF page: its document, mapped into the image's box. Raster + // images draw nothing. + const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return; + const prefix = "data:image/svg+xml;base64,"; + if (!std.mem.startsWith(u8, href, prefix)) return; + const decoder = std.base64.standard.Decoder; + const bytes = try p.arena.alloc(u8, decoder.calcSizeForSlice(href[prefix.len..]) catch return); + decoder.decode(bytes, href[prefix.len..]) catch return; + var doc = Document.parse(p.arena, bytes) catch |err| switch (err) { + error.OutOfMemory => return err, + error.InvalidSvg => return, + }; + const root = doc.root orelse return; + if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return; + const port = viewport(&doc, doc.nodes.items[root]); + const v = port.view; + const w = if (p.doc.attr(n, "width")) |a| lengthPx(a, p.view.w) else port.width; + const h = if (p.doc.attr(n, "height")) |a| lengthPx(a, p.view.h) else port.height; + if (v.w <= 0 or v.h <= 0 or w <= 0 or h <= 0) return; + transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); + // Stretched with `preserveAspectRatio="none"`, else centered at + // the largest scale that fits; drawn unclipped. + if (std.mem.startsWith(u8, std.mem.trim(u8, p.doc.attr(n, "preserveAspectRatio") orelse "", " "), "none")) { + transform = transform.mul(.scale(w / v.w, h / v.h)); + } else { + const s = @min(w / v.w, h / v.h); + transform = transform.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s)); + } + transform = transform.mul(.translate(-v.x, -v.y)); + // A document of its own: its ids, gradients and percentages, and + // nothing inherited but opacity. + const outer = p.*; + defer { + p.doc = outer.doc; + p.view = outer.view; + p.gradients = outer.gradients; + } + p.doc = &doc; + p.view = v; + p.gradients = .empty; + p.depth += 1; + defer p.depth -= 1; + return p.children(root, transform, .{ .style = .{ .opacity = inherited.style.opacity } }); + } const b = &p.b; if (std.mem.eql(u8, name, "path")) { @@ -766,3 +816,23 @@ test "colors and lengths" { try std.testing.expectEqual(@as(f32, 20), parseLength("15pt")); try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%")); } + +test "an SVG image in a data URI: its own ids, placed, stretched or fitted" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + // <svg viewBox="0 0 10 20"><defs><path id="p" d="M0 0h10v20h-10z"/></defs><use href="#p" fill="#00ff00"/></svg> + const inner = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdGggaWQ9InAiIGQ9Ik0wIDBoMTB2MjBoLTEweiIvPjwvZGVmcz48dXNlIGhyZWY9IiNwIiBmaWxsPSIjMDBmZjAwIi8+PC9zdmc+"; + const d = try parse(arena.allocator(), "<svg viewBox=\"0 0 100 100\"><defs><path id=\"p\" d=\"M0 0h1v1z\"/></defs>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" preserveAspectRatio=\"none\" href=\"" ++ inner ++ "\"/>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" xlink:href=\"" ++ inner ++ "\"/>" ++ + "<image href=\"data:image/png;base64,AAAA\"/></svg>"); + try std.testing.expectEqual(@as(usize, 2), d.shapes.len); + for (d.shapes) |shape| try std.testing.expectEqual(Drawing.Color{ 0, 1, 0, 1 }, shape.style.fill.color); + // The far corner (10, 20) of the image's own path: stretched to the + // box's corner, or fitted into its middle. + for (d.shapes, [_]geom.Vec{ .{ 25, 25 }, .{ 20, 25 } }) |shape, corner| { + const far = d.cubicsOf(d.subpathsOf(shape)[0])[1][3]; + try std.testing.expectEqual(geom.vec(10, 20), far); + try std.testing.expectEqual(corner, shape.transform.apply(far)); + } +} |
