diff --git a/build.zig b/build.zig index af2f37d..3818d5f 100644 --- a/build.zig +++ b/build.zig @@ -6,7 +6,7 @@ pub fn build(b: *std.Build) void { const glowcap = b.dependency("glowcap", .{ .target = target, .optimize = optimize }); const test_step = b.step("test", "Run the unit tests and the in-memory client/canister round trip"); - for ([_][]const u8{ "src/pair_test.zig", "src/candid.zig", "src/principal.zig" }) |root| { + for ([_][]const u8{ "src/pair_test.zig", "src/candid.zig", "src/principal.zig", "src/stable_log.zig" }) |root| { const t = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path(root), .target = target, diff --git a/src/stable_log.zig b/src/stable_log.zig new file mode 100644 index 0000000..e98f9fe --- /dev/null +++ b/src/stable_log.zig @@ -0,0 +1,308 @@ +//! A Loam storage engine whose rows live in the Wasm heap and whose every +//! committed transaction is also appended to a log in stable memory, the +//! part of a canister's state that survives a code upgrade. Opening replays +//! the log, so a store comes back after an upgrade as a disk engine's does +//! after a restart. +//! +//! On the Internet Computer a trap rolls back stable memory with the heap, +//! so a message either commits its log records and rows together or neither. +//! +//! Log layout at `base`: the 8-byte magic, then the little-endian offset one +//! past the last record. Each record is a transaction: a `u32` entry count, +//! then per entry a `u8` key length, the key, a `u32` value length +//! (`removed` for a removal), and the value. + +const std = @import("std"); +const glowcap = @import("glowcap"); + +const core = glowcap.loam.core; +const Volatile = glowcap.loam.Volatile; + +const magic = "LOAMLOG1"; +const header_len = magic.len + 8; +const removed = std.math.maxInt(u32); + +/// `Memory` is stable memory or a stand-in for it, with +/// `size() u64`, `grow(min_size: u64) !void`, `read(offset, []u8)`, and +/// `write(offset, []const u8)`; sizes and offsets are in bytes. +pub fn StableLog(comptime Memory: type) type { + return struct { + const Self = @This(); + + inner: Volatile, + memory: *Memory, + base: u64, + /// One past the last record. + end: u64, + + /// The store logged at `base`, replayed into the heap, or a new one + /// with identity `id` if nothing is logged there yet. + pub fn init(allocator: std.mem.Allocator, memory: *Memory, base: u64, id: core.StoreId, max_bytes: usize) !Self { + var self: Self = .{ + .inner = try Volatile.init(allocator, id, max_bytes), + .memory = memory, + .base = base, + .end = base + header_len, + }; + errdefer self.inner.deinit(); + var header: [header_len]u8 = undefined; + if (memory.size() >= base + header_len) memory.read(base, &header); + if (memory.size() < base + header_len or !std.mem.eql(u8, header[0..magic.len], magic)) { + try self.writeHeader(); + return self; + } + self.end = std.mem.readInt(u64, header[magic.len..], .little); + try self.replay(); + return self; + } + + pub fn deinit(self: *Self) void { + self.inner.deinit(); + self.* = undefined; + } + + /// Open the store, logging the claim so the next replay starts from it. + pub fn open(self: *Self) !core.Metadata { + const metadata = try self.inner.open(); + var record: std.ArrayList(u8) = .empty; + defer record.deinit(self.inner.allocator); + const gpa = self.inner.allocator; + try record.appendSlice(gpa, &std.mem.toBytes(std.mem.nativeToLittle(u32, 1))); + try appendEntry(gpa, &record, core.metadata_key, &metadata.encode()); + try self.append(record.items); + return metadata; + } + + pub fn close(self: *Self) !void { + return self.inner.close(); + } + + pub fn read(self: *Self, request: core.Read) core.ReadResult { + return core.backend.read(self, request); + } + + pub fn commit(self: *Self, batch: core.Batch) core.Outcome { + return core.backend.commit(self, batch); + } + + pub fn lookup(self: *Self, request: core.NameLookup) core.NameResult { + return core.backend.lookup(self, request); + } + + pub fn recover(self: *Self, batch: core.Batch) !core.Resolution { + return core.backend.recover(self, batch); + } + + pub fn readerCapacity(self: *const Self) usize { + return self.inner.readerCapacity(); + } + + pub const ReadTransaction = Volatile.ReadTransaction; + + pub fn beginRead(self: *Self) !ReadTransaction { + return self.inner.beginRead(); + } + + pub fn beginWrite(self: *Self) !WriteTransaction { + return .{ .log = self, .inner = try self.inner.beginWrite() }; + } + + /// A Volatile transaction whose puts and removes are also encoded, + /// to be appended to the log when the rows install. + pub const WriteTransaction = struct { + log: *Self, + inner: Volatile.WriteTransaction, + record: std.ArrayList(u8) = .empty, + count: u32 = 0, + + pub fn get(self: *WriteTransaction, key: []const u8) !?[]const u8 { + return self.inner.get(key); + } + + pub fn next(self: *WriteTransaction, prefix: []const u8, after: ?[]const u8) !?core.CollectionRow { + return self.inner.next(prefix, after); + } + + pub fn put(self: *WriteTransaction, key: []const u8, value: []const u8) !void { + errdefer self.drop(); + try self.inner.put(key, value); + try appendEntry(self.log.inner.allocator, &self.record, key, value); + self.count += 1; + } + + pub fn remove(self: *WriteTransaction, key: []const u8) !void { + errdefer self.drop(); + try self.inner.remove(key); + try appendEntry(self.log.inner.allocator, &self.record, key, null); + self.count += 1; + } + + /// Make room in stable memory first, so that once the rows + /// install, appending their record cannot fail. + pub fn commit(self: *WriteTransaction) !core.backend.Commit { + if (self.inner.state == .committed) return .committed; + errdefer self.drop(); + const len = 4 + self.record.items.len; + try self.log.reserve(len); + const outcome = try self.inner.commit(); + var count: [4]u8 = undefined; + std.mem.writeInt(u32, &count, self.count, .little); + self.log.memory.write(self.log.end, &count); + self.log.memory.write(self.log.end + 4, self.record.items); + self.log.end += len; + self.log.writeHeader() catch unreachable; // reserve covered the header + self.drop(); + return outcome; + } + + pub fn abort(self: *WriteTransaction) void { + self.inner.abort(); + self.drop(); + } + + fn drop(self: *WriteTransaction) void { + self.record.deinit(self.log.inner.allocator); + self.record = .empty; + } + }; + + fn reserve(self: *Self, len: usize) !void { + const need = try std.math.add(u64, self.end, len); + if (self.memory.size() < need) try self.memory.grow(need); + } + + fn append(self: *Self, record: []const u8) !void { + try self.reserve(record.len); + self.memory.write(self.end, record); + self.end += record.len; + try self.writeHeader(); + } + + fn writeHeader(self: *Self) !void { + if (self.memory.size() < self.base + header_len) try self.memory.grow(self.base + header_len); + var header: [header_len]u8 = undefined; + @memcpy(header[0..magic.len], magic); + std.mem.writeInt(u64, header[magic.len..], self.end, .little); + self.memory.write(self.base, &header); + } + + /// Apply every logged transaction to the heap rows, then adopt the + /// metadata the last one left. + fn replay(self: *Self) !void { + const gpa = self.inner.allocator; + const log_len = std.math.cast(usize, self.end - self.base - header_len) orelse return error.Corrupt; + const bytes = try gpa.alloc(u8, log_len); + defer gpa.free(bytes); + self.memory.read(self.base + header_len, bytes); + var reader: std.Io.Reader = .fixed(bytes); + _ = try self.inner.open(); + while (reader.seek < bytes.len) { + var txn = try self.inner.beginWrite(); + errdefer txn.abort(); + const count = reader.takeInt(u32, .little) catch return error.Corrupt; + for (0..count) |_| { + const key_len = reader.takeByte() catch return error.Corrupt; + const key = reader.take(key_len) catch return error.Corrupt; + const value_len = reader.takeInt(u32, .little) catch return error.Corrupt; + if (value_len == removed) { + try txn.remove(key); + } else { + try txn.put(key, reader.take(value_len) catch return error.Corrupt); + } + } + _ = try txn.commit(); + } + // Reopening claims from the replayed metadata, as a disk engine does. + try self.inner.close(); + } + }; +} + +fn appendEntry(gpa: std.mem.Allocator, record: *std.ArrayList(u8), key: []const u8, value: ?[]const u8) !void { + const key_len = std.math.cast(u8, key.len) orelse return error.Corrupt; + try record.append(gpa, key_len); + try record.appendSlice(gpa, key); + var len: [4]u8 = undefined; + if (value) |bytes| { + std.mem.writeInt(u32, &len, std.math.cast(u32, bytes.len) orelse return error.RecordTooLarge, .little); + try record.appendSlice(gpa, &len); + try record.appendSlice(gpa, bytes); + } else { + std.mem.writeInt(u32, &len, removed, .little); + try record.appendSlice(gpa, &len); + } +} + +/// Stable memory as a growable byte array, for tests. +pub const TestMemory = struct { + bytes: std.ArrayList(u8) = .empty, + gpa: std.mem.Allocator, + + pub fn size(self: *const TestMemory) u64 { + return self.bytes.items.len; + } + pub fn grow(self: *TestMemory, min_size: u64) !void { + try self.bytes.appendNTimes(self.gpa, 0, @intCast(min_size - self.bytes.items.len)); + } + pub fn read(self: *const TestMemory, offset: u64, out: []u8) void { + @memcpy(out, self.bytes.items[@intCast(offset)..][0..out.len]); + } + pub fn write(self: *TestMemory, offset: u64, bytes: []const u8) void { + @memcpy(self.bytes.items[@intCast(offset)..][0..bytes.len], bytes); + } +}; + +const testing = std.testing; +const Log = StableLog(TestMemory); +const test_id: core.StoreId = @fromBackingInt(9); + +/// Create a rooted record holding `payload`, in one transaction. +fn create(store: *core.Store, log: *Log, payload: []const u8) !core.ObjectId { + try store.begin(); + const id = try store.allocateId(); + try store.putCopying(.{ .id = id, .revision = 0, .schema = 1, .payload = payload, .rooted = true }, null); + const ticket = try store.prepare(); + const outcome = log.commit(try store.beginWrite(ticket)); + try store.completeWrite(ticket, outcome); + if (outcome != .committed) return error.CommitFailed; + return id; +} + +const schemas = [_]core.Schema{.{ .id = 1, .version = 1, .max_payload = 8, .max_edges = 0 }}; +const limits: core.Store.Limits = .{ + .records = .{ .max_record_bytes = 256, .max_edges = 1 }, + .cache_slots = 2, + .max_leases = 2, + .resident_bytes = 1024, + .max_changes = 4, + .staging_bytes = 2048, +}; + +test "a committed record comes back when the log is reopened" { + var memory: TestMemory = .{ .gpa = testing.allocator }; + defer memory.bytes.deinit(testing.allocator); + const base = 4096; + + const id, const incarnation = first: { + var log = try Log.init(testing.allocator, &memory, base, test_id, core.backend.min_capacity_bytes); + defer log.deinit(); + var store = try core.Store.init(testing.allocator, try log.open(), &schemas, limits); + defer store.deinit() catch unreachable; + break :first .{ try create(&store, &log, "seven!!!"), store.metadata.incarnation }; + }; + + var log = try Log.init(testing.allocator, &memory, base, test_id, core.backend.min_capacity_bytes); + defer log.deinit(); + var store = try core.Store.init(testing.allocator, try log.open(), &schemas, limits); + defer store.deinit() catch unreachable; + try testing.expect(store.metadata.incarnation > incarnation); + const lease = switch (try store.acquire(id)) { + .ready => |lease| lease, + .read => |read| blk: { + try store.completeRead(read.ticket, log.read(read)); + break :blk (try store.acquire(id)).ready; + }, + }; + defer store.release(lease) catch unreachable; + try testing.expectEqualStrings("seven!!!", (try store.currentView(lease)).payload); +}