// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The ledger: which messages out of which mailboxes are already in the //! archive. //! //! ## Why there is a database at all //! //! Not to say what is left to do. Unlike a mailbox reached over an API, the //! source here is a file: working out what is in it costs a read of the file //! and nothing else, and it has to be read anyway because an mbox has no index //! and no way to ask. Every run reads every configured mailbox from the //! beginning, and that is the design rather than a shortcoming — see //! `Archiver`. //! //! What the ledger saves is the *other* side. Without it, a re-run over an //! already-archived mailbox is one `POST /archive` per message: forty thousand //! uploads of bytes the archive already holds, to be told so forty thousand //! times. With it, the same run is forty thousand SQLite point lookups and no //! network at all. //! //! It is the only thing that saves them, which is why it is the ledger and not //! a cache. `Archiver` explains why the `HEAD /message/{hash}` pre-check the //! sibling programs lean on is not a substitute here: it can say the archive //! has the bytes, and skipping an upload on that answer would skip the tags //! and properties that go with it. Losing this file therefore costs the //! bandwidth of one re-import, and never any mail: the archive is content //! addressed, so everything re-uploaded lands on the file that is already //! there. //! //! It is also where the failures live, which is the part that cannot be //! recomputed: how many times a message has been refused, and what was said //! about it the last time. //! //! ## Identity //! //! The hash of the message's canonical bytes, and nothing else. An mbox has no //! message ids, no UIDs, no sequence numbers — nothing that survives the file //! being rewritten, which is what every deletion from an mbox is. The offset //! is recorded because it is useful for finding a message again by hand, and //! it is deliberately not part of the key: a message that moved because //! something ahead of it was deleted is the same message. //! //! One consequence worth stating: two identical messages in one mailbox are //! one row. The archive would store them as one file anyway — it is content //! addressed — so the ledger counts them in `copies` rather than pretending //! they are separable. //! //! ## Transactions //! //! Every write that a crash could tear is wrapped, and the unit is a chunk of //! messages rather than one. Redoing a chunk costs a re-read of part of a //! local file; paying for an `fsync` per message would cost more than that. const Database = @This(); const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const zqlite = @import("zqlite"); const log = std.log.scoped(.database); /// Bumped when the schema below changes in a way an existing file cannot be /// read with. `schema` is what a new ledger is created with; `upgradeFrom` is /// how one written by an older version is brought to it, and the two have to /// be kept saying the same thing. const schema_version = 1; const schema = \\create table schema_version (version integer not null); \\ \\create table mailboxes ( \\ name text primary key, \\ path text not null, \\ file_size integer, \\ file_mtime integer, \\ last_run integer \\); \\ \\create table messages ( \\ mailbox text not null, \\ hash text not null, \\ file_offset integer not null, \\ size integer not null, \\ envelope_from text, \\ delivered text, \\ copies integer not null default 1, \\ state text not null, \\ attempts integer not null default 0, \\ last_error text, \\ first_seen integer not null, \\ archived_at integer, \\ primary key (mailbox, hash) \\) without rowid; \\ \\create index messages_work on messages (mailbox, state); ; /// Where a message has got to. /// /// Stored as text rather than an integer so that somebody reading the database /// with `sqlite3` can see what it says. pub const State = enum { /// Read out of the mailbox and written down, but not yet acknowledged by /// the archive. /// /// A message is only ever in this state between a `--dry-run` and a real /// one, or because a run was interrupted after the chunk was recorded and /// before the archive answered. Either way the next run picks it up. pending, /// The archive has the bytes and has acknowledged them. archived, /// Something stops this message being archived, and retrying unchanged /// will not help. `last_error` says what. failed, pub fn toString(self: State) []const u8 { return @tagName(self); } pub fn parse(text: []const u8) ?State { return std.meta.stringToEnum(State, text); } }; /// What a mailbox looked like the last time it was read. Reported by `status`; /// nothing is decided by it. /// /// Deliberately not used to skip a mailbox whose size and mtime have not /// changed. An mbox is rewritten in place by every tool that removes a message /// from one, and a rewrite that happens to land on the same length within the /// same second is a mailbox this program would then never look at again. The /// saving would be a file read; the cost would be lost mail. pub const MailboxRow = struct { name: []const u8, path: []const u8, file_size: ?i64, file_mtime: ?i64, last_run: ?i64, pub fn deinit(self: MailboxRow, gpa: Allocator) void { gpa.free(self.name); gpa.free(self.path); } }; /// What is known about one message before it is archived, as the scan hands it /// over. pub const Seen = struct { hash: []const u8, offset: u64, size: u64, /// The postmark's envelope sender, or null when it had none — which is /// what a bounce looks like. envelope_from: ?[]const u8, /// The postmark's date, exactly as written and undecoded. delivered: ?[]const u8, }; pub const Counts = struct { pending: u64 = 0, archived: u64 = 0, failed: u64 = 0, /// Messages whose bytes appeared more than once in the mailbox, counted /// as the extra appearances rather than the rows. repeats: u64 = 0, /// Failures that have not yet used up `max_attempts`, so a later run will /// try them again without being asked. retryable: u64 = 0, pub fn total(self: Counts) u64 { return self.pending + self.archived + self.failed; } }; conn: zqlite.Conn, pub const OpenError = error{ /// SQLite would not open the file, or the file is not a database. Unavailable, /// The file was written by a newer version of this program. SchemaTooNew, } || Allocator.Error; /// What `open` found, for the caller to report. An out-parameter rather than a /// log line because `error.SchemaTooNew` is worth a sentence naming both /// versions, and only the caller knows whether it is writing to a terminal. pub const Diagnostics = struct { /// The version in the file, when there was one to read. Set whether or not /// the open succeeded. found_schema_version: ?i64 = null, /// The version this program writes and understands. pub const expected: i64 = schema_version; }; /// Permissions the ledger is created with, and put back to if it is found with /// others. /// /// There is no credential in it, but it is a description of somebody's mail: /// every message's size, when it was delivered, who it came from, and which /// file it was in. That is not the thing on the machine that should be /// world-readable. /// /// `Io.File.Permissions` is the POSIX mode on POSIX and a platform default /// elsewhere, and only the POSIX one can be built from a mode, so this asks /// rather than assuming: on a platform with no mode there is nothing to set. const owner_only: Io.File.Permissions = if (@hasDecl(Io.File.Permissions, "fromMode")) .fromMode(0o600) else .default_file; /// Creates the ledger file owner-only, or puts an existing one back to /// owner-only, *before* SQLite opens it. /// /// Before rather than after, so there is no window in which it exists /// world-readable — and because SQLite gives the `-wal` and `-shm` files it /// creates the same permissions as the database, so getting this right once /// here is what makes all three right. /// /// An empty file is a valid empty database, which is what makes creating it /// here rather than leaving it to SQLite safe. Every failure is ignored: this /// is a precaution, and the open that follows is what reports a path that /// cannot be used. fn protect(io: Io, path: []const u8) void { // SQLite spells an in-memory database several ways and none of them is a // file. Creating one would put a stray file on disk named `:memory:`. if (path.len == 0) return; if (std.mem.eql(u8, path, ":memory:")) return; if (std.mem.startsWith(u8, path, "file:")) return; const dir: Io.Dir = .cwd(); if (dir.createFile(io, path, .{ .exclusive = true, // The one that matters: an existing ledger must not be emptied. .truncate = false, .permissions = owner_only, })) |file| { file.close(io); } else |err| switch (err) { error.PathAlreadyExists => { var file = dir.openFile(io, path, .{}) catch return; defer file.close(io); file.setPermissions(io, owner_only) catch {}; }, else => {}, } } /// Opens the ledger, creating and initialising it if it is not there. /// /// `path` is NUL-terminated because that is what SQLite wants. `:memory:` is a /// valid path and is what the tests use. pub fn open(io: Io, path: [:0]const u8, diagnostics: ?*Diagnostics) OpenError!Database { protect(io, path); // Extended result codes, because without them a constraint violation and a // disk error are the same integer and `zqlite.isUnique` cannot tell them // apart. const flags = zqlite.OpenFlags.Create | zqlite.OpenFlags.EXResCode; const conn = zqlite.open(path.ptr, flags) catch return error.Unavailable; errdefer conn.close(); // A second process -- somebody running `atm-mbox archive` in one terminal // and `status` in another -- waits rather than failing outright. conn.busyTimeout(5_000) catch return error.Unavailable; // WAL so that a reader does not block the writer, and `normal` because the // archive is the durable thing here: this file can be rebuilt by reading // the mailboxes again, and paying for an `fsync` per transaction to // protect a cache is the wrong trade. conn.execNoArgs("pragma journal_mode = wal") catch return error.Unavailable; conn.execNoArgs("pragma synchronous = normal") catch return error.Unavailable; conn.execNoArgs("pragma foreign_keys = on") catch return error.Unavailable; var self: Database = .{ .conn = conn }; try self.migrate(diagnostics); return self; } pub fn deinit(self: *Database) void { self.conn.close(); self.* = undefined; } /// Creates the schema, or checks that what is there is one this program can /// read. Wrapped, so that a process killed part way through leaves either a /// database or an empty file and never half a schema. fn migrate(self: *Database, diagnostics: ?*Diagnostics) OpenError!void { const found = self.currentVersion() catch return error.Unavailable; if (diagnostics) |d| d.found_schema_version = found; if (found) |version| { if (version > schema_version) return error.SchemaTooNew; if (version < schema_version) return self.upgradeFrom(version); return; } self.conn.transaction() catch return error.Unavailable; errdefer self.conn.rollback(); // `execNoArgs` rather than `exec`: this is many statements, and `exec` // refuses anything with a tail. self.conn.execNoArgs(schema) catch |err| { log.err("creating the schema: {t}: {s}", .{ err, self.conn.lastError() }); return error.Unavailable; }; self.conn.exec("insert into schema_version (version) values (?1)", .{ @as(i64, schema_version), }) catch return error.Unavailable; self.conn.commit() catch return error.Unavailable; } /// Brings a ledger written by an older version up to `schema_version`. /// /// There is only one version so far, so nothing reaches here. The ladder is /// written out anyway, and the steps will fall through rather than switch, so /// that a ledger several versions behind is caught up in one pass and the /// whole thing is one transaction. fn upgradeFrom(self: *Database, version: i64) OpenError!void { self.conn.transaction() catch return error.Unavailable; errdefer self.conn.rollback(); switch (version) { // Unreachable while `schema_version` is 1: `migrate` only calls this // for a version strictly below it, and there is nothing below 1. else => return error.Unavailable, } self.conn.exec("update schema_version set version = ?1", .{ @as(i64, schema_version), }) catch return error.Unavailable; self.conn.commit() catch return error.Unavailable; } fn currentVersion(self: *Database) !?i64 { const exists = blk: { var row = (try self.conn.row( "select 1 from sqlite_master where type = 'table' and name = 'schema_version'", .{}, )) orelse break :blk false; row.deinit(); break :blk true; }; if (!exists) return null; var row = (try self.conn.row("select version from schema_version", .{})) orelse return null; defer row.deinit(); return row.int(0); } // -- mailboxes --------------------------------------------------------------- /// Notes that a mailbox exists and where it was last found. /// /// The path is written every time rather than only on insert: a mailbox that /// was moved keeps its name and its history, which is the whole reason the /// name is the key and the path is not. pub fn recordMailbox( self: *Database, name: []const u8, path: []const u8, file_size: ?u64, file_mtime: ?i64, now: i64, ) !void { try self.conn.exec( \\insert into mailboxes (name, path, file_size, file_mtime, last_run) \\values (?1, ?2, ?3, ?4, ?5) \\on conflict (name) do update set \\ path = excluded.path, \\ file_size = excluded.file_size, \\ file_mtime = excluded.file_mtime, \\ last_run = excluded.last_run , .{ name, path, optionalI64(file_size), file_mtime, now }); } pub fn getMailbox(self: *Database, gpa: Allocator, name: []const u8) !?MailboxRow { var row = (try self.conn.row( "select name, path, file_size, file_mtime, last_run from mailboxes where name = ?1", .{name}, )) orelse return null; defer row.deinit(); const stored_name = try gpa.dupe(u8, row.text(0)); errdefer gpa.free(stored_name); const path = try gpa.dupe(u8, row.text(1)); return .{ .name = stored_name, .path = path, .file_size = row.nullableInt(2), .file_mtime = row.nullableInt(3), .last_run = row.nullableInt(4), }; } /// Every mailbox the ledger knows about, in name order. The caller owns the /// names and the slice. pub fn listMailboxes(self: *Database, gpa: Allocator) ![]const []const u8 { var names: std.ArrayList([]const u8) = .empty; errdefer { for (names.items) |n| gpa.free(n); names.deinit(gpa); } var rows = try self.conn.rows("select name from mailboxes order by name", .{}); defer rows.deinit(); while (rows.next()) |row| try names.append(gpa, try gpa.dupe(u8, row.text(0))); if (rows.err) |err| return err; return names.toOwnedSlice(gpa); } // -- messages ---------------------------------------------------------------- /// What the ledger already knows about a message the scan has just read. pub const Known = struct { state: State, attempts: i64, /// Whether this one still has to be offered to the archive: either it has /// never been accepted, or it failed and has attempts left. pub fn outstanding(self: Known, max_attempts: i64) bool { return switch (self.state) { .archived => false, .pending => true, .failed => self.attempts < max_attempts, }; } }; /// What the ledger has on this message, or null if it has never seen it. /// /// One point lookup per message read, which is the whole of what the ledger /// buys: the alternative is a round trip to the archive to ask the same /// question. pub fn lookup(self: *Database, mailbox: []const u8, hash: []const u8) !?Known { var row = (try self.conn.row( "select state, attempts from messages where mailbox = ?1 and hash = ?2", .{ mailbox, hash }, )) orelse return null; defer row.deinit(); return .{ .state = State.parse(row.text(0)) orelse .pending, .attempts = row.int(1), }; } /// Writes down a message the scan has read, as `pending` if it is new. /// /// Returns true when this was the first time these bytes were seen in this /// mailbox. A second appearance bumps `copies` and leaves everything else /// alone — in particular it does not move an `archived` row back to `pending`, /// because the archive holds one file for both of them and always did. /// /// `returning` rather than a second query, because SQLite's upsert has no /// other way to say which of the two branches it took and the alternative is /// one more statement per message over a mailbox of forty thousand. pub fn see(self: *Database, mailbox: []const u8, m: Seen, now: i64) !bool { var row = (try self.conn.row( \\insert into messages \\ (mailbox, hash, file_offset, size, envelope_from, delivered, state, first_seen) \\values (?1, ?2, ?3, ?4, ?5, ?6, 'pending', ?7) \\on conflict (mailbox, hash) do update set copies = copies + 1 \\returning copies , .{ mailbox, m.hash, clampToI64(m.offset), clampToI64(m.size), m.envelope_from, m.delivered, now, })) orelse return false; defer row.deinit(); return row.int(0) == 1; } /// The archive has these bytes. Clears the failure, if there was one. pub fn recordArchived(self: *Database, mailbox: []const u8, hash: []const u8, now: i64) !void { try self.conn.exec( \\update messages \\set state = 'archived', archived_at = ?3, last_error = null \\where mailbox = ?1 and hash = ?2 , .{ mailbox, hash, now }); } /// Something went wrong with this message. /// /// `fatal` spends every remaining attempt at once, for a verdict no later run /// could change — the archive saying the bytes are not a message, for /// instance. Everything else counts one attempt, so a mailbox that failed /// because the archive was down is tried again by the next run rather than /// being written off. pub fn recordFailure( self: *Database, mailbox: []const u8, hash: []const u8, message: []const u8, fatal: bool, max_attempts: i64, ) !void { try self.conn.exec( \\update messages \\set state = 'failed', \\ attempts = case when ?4 then ?5 else attempts + 1 end, \\ last_error = ?3 \\where mailbox = ?1 and hash = ?2 , .{ mailbox, hash, message, fatal, max_attempts }); } pub fn counts(self: *Database, mailbox: []const u8, max_attempts: i64) !Counts { var result: Counts = .{}; { var rows = try self.conn.rows( "select state, count(*) from messages where mailbox = ?1 group by state", .{mailbox}, ); defer rows.deinit(); while (rows.next()) |row| { const n: u64 = @intCast(@max(0, row.int(1))); switch (State.parse(row.text(0)) orelse continue) { .pending => result.pending = n, .archived => result.archived = n, .failed => result.failed = n, } } if (rows.err) |err| return err; } { var row = (try self.conn.row( \\select \\ coalesce(sum(copies - 1), 0), \\ coalesce(sum(state = 'failed' and attempts < ?2), 0) \\from messages where mailbox = ?1 , .{ mailbox, max_attempts })) orelse return result; defer row.deinit(); result.repeats = @intCast(@max(0, row.int(0))); result.retryable = @intCast(@max(0, row.int(1))); } return result; } /// One failure, for `status` to print. pub const Failure = struct { hash: []const u8, offset: i64, attempts: i64, last_error: []const u8, pub fn deinit(self: Failure, gpa: Allocator) void { gpa.free(self.hash); gpa.free(self.last_error); } }; /// The most-attempted failures first, which is the order somebody looking at /// them wants: the ones that have been failing longest are the ones a later /// run will not fix. pub fn failures( self: *Database, gpa: Allocator, mailbox: []const u8, limit: usize, ) ![]const Failure { var list: std.ArrayList(Failure) = .empty; errdefer { for (list.items) |f| f.deinit(gpa); list.deinit(gpa); } var rows = try self.conn.rows( \\select hash, file_offset, attempts, coalesce(last_error, '') \\from messages where mailbox = ?1 and state = 'failed' \\order by attempts desc, file_offset asc limit ?2 , .{ mailbox, clampToI64(limit) }); defer rows.deinit(); while (rows.next()) |row| { const hash = try gpa.dupe(u8, row.text(0)); errdefer gpa.free(hash); const last_error = try gpa.dupe(u8, row.text(3)); try list.append(gpa, .{ .hash = hash, .offset = row.int(1), .attempts = row.int(2), .last_error = last_error, }); } if (rows.err) |err| return err; return list.toOwnedSlice(gpa); } /// Clears the attempt counters so failed messages are offered again. /// /// They go back to `pending` rather than being deleted: what was learned about /// them — where they are, how big they are, what the postmark said — is still /// true, and `first_seen` is worth keeping. pub fn resetFailures(self: *Database, mailbox: []const u8) !usize { try self.conn.exec( \\update messages set state = 'pending', attempts = 0, last_error = null \\where mailbox = ?1 and state = 'failed' , .{mailbox}); return self.conn.changes(); } // -- transactions ------------------------------------------------------------ pub fn begin(self: *Database) !void { try self.conn.transaction(); } pub fn commit(self: *Database) !void { try self.conn.commit(); } pub fn rollback(self: *Database) void { self.conn.rollback(); } /// A count that cannot be negative, as the integer SQLite stores. /// /// Saturating rather than wrapping. A mailbox is not going to be eight /// exabytes, and if one somehow is then a number that is merely too large is a /// better thing to have written down than one that is negative. fn clampToI64(value: u64) i64 { return std.math.cast(i64, value) orelse std.math.maxInt(i64); } fn optionalI64(value: ?u64) ?i64 { return if (value) |v| clampToI64(v) else null; } const testing = std.testing; fn testDatabase() !Database { return open(std.testing.io, ":memory:", null); } fn seen(hash: []const u8, offset: u64) Seen { return .{ .hash = hash, .offset = offset, .size = 100, .envelope_from = "jeff@example.com", .delivered = "Mon Jan 1 00:00:00 2024", }; } test "a new ledger is at the current schema version" { var diagnostics: Diagnostics = .{}; var db = try open(std.testing.io, ":memory:", &diagnostics); defer db.deinit(); try testing.expectEqual(@as(?i64, null), diagnostics.found_schema_version); try testing.expectEqual(@as(?i64, schema_version), try db.currentVersion()); } test "a message is seen, archived, and known about afterwards" { var db = try testDatabase(); defer db.deinit(); try db.recordMailbox("lists/zig", "/srv/zig.mbox", 4096, 1700000000, 1); try testing.expect(try db.see("lists/zig", seen("aaa", 0), 1)); try testing.expectEqual(State.pending, (try db.lookup("lists/zig", "aaa")).?.state); try db.recordArchived("lists/zig", "aaa", 2); const known = (try db.lookup("lists/zig", "aaa")).?; try testing.expectEqual(State.archived, known.state); // The whole point of the ledger: this one need not be offered again. try testing.expect(!known.outstanding(5)); const c = try db.counts("lists/zig", 5); try testing.expectEqual(@as(u64, 1), c.archived); try testing.expectEqual(@as(u64, 0), c.pending); try testing.expectEqual(@as(u64, 1), c.total()); } test "a message the ledger has never seen is null rather than an error" { var db = try testDatabase(); defer db.deinit(); try testing.expectEqual(@as(?Known, null), try db.lookup("lists/zig", "nope")); } test "the same bytes twice in one mailbox is one row and two copies" { var db = try testDatabase(); defer db.deinit(); // The archive is content addressed, so it would hold one file for these // two whatever the ledger said. Counting them is the honest thing to do. try testing.expect(try db.see("lists/zig", seen("aaa", 0), 1)); try testing.expect(!try db.see("lists/zig", seen("aaa", 900), 1)); const c = try db.counts("lists/zig", 5); try testing.expectEqual(@as(u64, 1), c.total()); try testing.expectEqual(@as(u64, 1), c.repeats); } test "a second appearance does not move an archived message back to pending" { var db = try testDatabase(); defer db.deinit(); try testing.expect(try db.see("lists/zig", seen("aaa", 0), 1)); try db.recordArchived("lists/zig", "aaa", 2); try testing.expect(!try db.see("lists/zig", seen("aaa", 900), 3)); // Without this the second copy would be uploaded again on every run, for // ever, and the archive would answer "already held" every time. try testing.expectEqual(State.archived, (try db.lookup("lists/zig", "aaa")).?.state); } test "the same bytes in two mailboxes are two rows" { var db = try testDatabase(); defer db.deinit(); // A message cross-posted to two lists, or one mailbox split in two. The // archive holds one file; this side records that it was found twice, in // two places, which is what makes `source` worth recording. try testing.expect(try db.see("lists/zig", seen("aaa", 0), 1)); try testing.expect(try db.see("lists/nix", seen("aaa", 0), 1)); try testing.expectEqual(@as(u64, 1), (try db.counts("lists/zig", 5)).total()); try testing.expectEqual(@as(u64, 1), (try db.counts("lists/nix", 5)).total()); } test "a failure counts an attempt and is retried until it runs out" { var db = try testDatabase(); defer db.deinit(); _ = try db.see("lists/zig", seen("aaa", 0), 1); try db.recordFailure("lists/zig", "aaa", "the archive: Unavailable", false, 3); var known = (try db.lookup("lists/zig", "aaa")).?; try testing.expectEqual(State.failed, known.state); try testing.expectEqual(@as(i64, 1), known.attempts); try testing.expect(known.outstanding(3)); try db.recordFailure("lists/zig", "aaa", "again", false, 3); try db.recordFailure("lists/zig", "aaa", "again", false, 3); known = (try db.lookup("lists/zig", "aaa")).?; try testing.expectEqual(@as(i64, 3), known.attempts); // Out of attempts: one message the archive will not take must not make // every future run busy and noisy. try testing.expect(!known.outstanding(3)); const c = try db.counts("lists/zig", 3); try testing.expectEqual(@as(u64, 1), c.failed); try testing.expectEqual(@as(u64, 0), c.retryable); } test "a fatal failure spends every attempt at once" { var db = try testDatabase(); defer db.deinit(); _ = try db.see("lists/zig", seen("aaa", 0), 1); // `not_a_message` from the archive: no later run changes that verdict, so // spending four more attempts on it would only be four more uploads. try db.recordFailure("lists/zig", "aaa", "HTTP 400 not_a_message", true, 5); const known = (try db.lookup("lists/zig", "aaa")).?; try testing.expectEqual(@as(i64, 5), known.attempts); try testing.expect(!known.outstanding(5)); } test "retry puts failures back and archiving clears the error" { var db = try testDatabase(); defer db.deinit(); _ = try db.see("lists/zig", seen("aaa", 0), 1); try db.recordFailure("lists/zig", "aaa", "the archive: Unavailable", false, 5); const failed = try db.failures(testing.allocator, "lists/zig", 10); defer { for (failed) |f| f.deinit(testing.allocator); testing.allocator.free(failed); } try testing.expectEqual(@as(usize, 1), failed.len); try testing.expectEqualStrings("aaa", failed[0].hash); try testing.expectEqualStrings("the archive: Unavailable", failed[0].last_error); try testing.expectEqual(@as(usize, 1), try db.resetFailures("lists/zig")); const known = (try db.lookup("lists/zig", "aaa")).?; try testing.expectEqual(State.pending, known.state); try testing.expectEqual(@as(i64, 0), known.attempts); // And what was learned about the message survives the reset: where it is // and what its postmark said are still true. try db.recordArchived("lists/zig", "aaa", 9); const after = try db.failures(testing.allocator, "lists/zig", 10); defer testing.allocator.free(after); try testing.expectEqual(@as(usize, 0), after.len); } test "a mailbox that moved keeps its name, its history and its path is updated" { var db = try testDatabase(); defer db.deinit(); try db.recordMailbox("lists/zig", "/old/zig.mbox", 100, 1, 1); _ = try db.see("lists/zig", seen("aaa", 0), 1); try db.recordArchived("lists/zig", "aaa", 1); // The whole reason the name is the key and the path is not. try db.recordMailbox("lists/zig", "/new/zig.mbox", 200, 2, 2); const row = (try db.getMailbox(testing.allocator, "lists/zig")).?; defer row.deinit(testing.allocator); try testing.expectEqualStrings("/new/zig.mbox", row.path); try testing.expectEqual(@as(?i64, 200), row.file_size); try testing.expectEqual(@as(u64, 1), (try db.counts("lists/zig", 5)).archived); } test "the mailboxes are listed in name order" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.recordMailbox("lists/zig", "/a", null, null, 1); try db.recordMailbox("inbox", "/b", null, null, 1); const names = try db.listMailboxes(gpa); defer { for (names) |n| gpa.free(n); gpa.free(names); } try testing.expectEqual(@as(usize, 2), names.len); try testing.expectEqualStrings("inbox", names[0]); try testing.expectEqualStrings("lists/zig", names[1]); } test "a ledger from the future is refused rather than read" { var db = try testDatabase(); defer db.deinit(); try db.conn.exec("update schema_version set version = ?1", .{@as(i64, schema_version + 1)}); var diagnostics: Diagnostics = .{}; try testing.expectError(error.SchemaTooNew, db.migrate(&diagnostics)); try testing.expectEqual(@as(?i64, schema_version + 1), diagnostics.found_schema_version); } test "a ledger on disk is owner-only, and is put back if it is not" { if (!@hasDecl(Io.File.Permissions, "fromMode")) return error.SkipZigTest; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); // `tmpDir` puts its directory at a known place under the cache, and // `Database.open` resolves against the working directory, so the path is // spelled out rather than taken from the handle. var path_buffer: [std.Io.Dir.max_path_bytes]u8 = undefined; const path = try std.mem.printSentinel( &path_buffer, ".zig-cache/tmp/{s}/state.db", .{tmp.sub_path}, 0, ); { var db = try open(io, path, null); defer db.deinit(); try db.recordMailbox("lists/zig", "/a", null, null, 1); } try testing.expectEqual(@as(std.posix.mode_t, 0o600), try modeOf(io, path)); // It is a map of somebody's mail, so it is put back rather than warned // about. And the `-wal` and `-shm` files SQLite makes inherit from it, // which is why doing this before the open is what makes all three right. var file = try Io.Dir.cwd().openFile(io, path, .{}); try file.setPermissions(io, .fromMode(0o644)); file.close(io); { var db = try open(io, path, null); defer db.deinit(); // And the data survived: `protect` must never truncate what it finds. const row = (try db.getMailbox(testing.allocator, "lists/zig")).?; defer row.deinit(testing.allocator); try testing.expectEqualStrings("/a", row.path); } try testing.expectEqual(@as(std.posix.mode_t, 0o600), try modeOf(io, path)); } fn modeOf(io: Io, path: []const u8) !std.posix.mode_t { var file = try Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); const stat = try file.stat(io); return stat.permissions.toMode() & 0o777; }