// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The ledger: what has been seen, what has been archived, and where the last //! run of each folder got to. //! //! ## Why there is a database at all //! //! The archive itself cannot answer "what is left to do". It is content //! addressed, so it can say whether it holds a particular message once that //! message has been fetched and hashed — but by then the expensive part, the //! round trip to Graph, has already happened. `/search` is `501`. Nothing on //! that side maps a Graph message id to anything. //! //! So this side keeps the list. A mailbox of tens of thousands of messages is //! not walked in one uninterruptible go: the run is killed, the network drops, //! the token expires, the machine reboots. Every one of those has to cost the //! work in flight and nothing more, which means the answer to "what is left" //! survives the process that was working on it. //! //! ## Change tracking is per folder, so the checkpoint is too //! //! This is the first place the schema stops resembling the Gmail sibling's. //! Gmail has one history id for a whole mailbox; Graph has no mailbox-wide //! change feed at all, so every folder carries its own `@odata.deltaLink` and //! a mailbox is synchronised one folder at a time. `folders` is therefore a //! table of checkpoints rather than the label list it replaces. //! //! A delta link is a whole URL. It is checked against the configured Graph //! endpoint before it is followed — `o365.odata.sameOrigin` does that, and it //! is not decoration: a link is a string that has been out of this program and //! back, and following one to another host would post a bearer token good for //! the whole mailbox to whoever wrote it. //! //! ## A move is a delete and an add //! //! The second place. A message moved between folders **gets a new id**, so it //! arrives in one folder's delta as a removal and in another's as something //! new, with nothing in either to connect them. `internet_message_id` — the //! RFC 5322 `Message-ID:` — is what survives, so it is stored and indexed: //! `takePending` uses it to notice that a "new" message is one whose bytes are //! already archived under another id, which is what stops the pre-check //! skipping the upload that would have added the new folder's tag. //! //! ## The shape of the state //! //! One row per message per account, carrying a `state` that moves one way: //! `pending` when the id is first seen, `archived` once the archive has //! acknowledged the bytes, `failed` when something is wrong with the message //! itself, `gone` when Graph says it is no longer there. Nothing is removed //! from the archive to match; it is append-only by design, and `gone` is a //! note about the mailbox rather than an instruction. //! //! There is deliberately no `duplicate` state. Whether the archive already //! held the bytes is a fact about one run, not about the message — a second //! machine archiving the same mailbox makes every message a duplicate without //! changing what is true — so it is not written down. `archive_hash` being set //! is the whole of "this one is done". //! //! ## Transactions //! //! Every write that a crash could tear is wrapped, and the unit is a page of //! delta or a chunk of fetching rather than a message. Redoing one chunk is //! cheap and redoing one message is not worth a `fsync`. 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. There is one version and no migrations from earlier ones yet; /// when there is a second, this is where the ladder starts. const schema_version = 1; const schema = \\create table schema_version (version integer not null); \\ \\create table accounts ( \\ address text primary key, \\ last_full_walk integer, \\ last_sync integer \\); \\ \\create table folders ( \\ account text not null, \\ folder_id text not null, \\ name text not null, \\ path text not null, \\ tag text not null, \\ parent_folder_id text, \\ skipped integer not null default 0, \\ delta_link text, \\ delta_at integer, \\ seen_at integer not null, \\ primary key (account, folder_id) \\) without rowid; \\ \\create table well_known_folders ( \\ account text not null, \\ name text not null, \\ folder_id text, \\ primary key (account, name) \\) without rowid; \\ \\create table messages ( \\ account text not null, \\ message_id text not null, \\ folder_id text, \\ internet_message_id text, \\ received_at integer, \\ archive_hash text, \\ state text not null, \\ tags_dirty integer not null default 0, \\ attempts integer not null default 0, \\ last_error text, \\ discovered_at integer not null, \\ archived_at integer, \\ primary key (account, message_id) \\) without rowid; \\ \\create index messages_work on messages (account, state, tags_dirty); \\ \\create index messages_by_internet_id \\ on messages (account, internet_message_id); \\ \\create table message_categories ( \\ account text not null, \\ message_id text not null, \\ category text not null, \\ primary key (account, message_id, category) \\) without rowid; ; /// 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 { /// Known to exist in the mailbox; not yet in the archive. pending, /// The archive has the bytes and has acknowledged them. archived, /// Something about this message stops it being archived at all, and /// retrying unchanged will not help. `last_error` says what. failed, /// Graph says it is no longer there — deleted, or moved somewhere this id /// no longer names. Whatever was already archived stays archived. gone, pub fn toString(self: State) []const u8 { return @tagName(self); } pub fn parse(text: []const u8) ?State { return std.meta.stringToEnum(State, text); } }; pub const Account = struct { address: []const u8, last_full_walk: ?i64, last_sync: ?i64, /// Whether a walk of every folder has ever run to completion. Until one /// has, there is no delta link old enough to trust for the folders that /// were never reached. pub fn hasWalked(self: Account) bool { return self.last_full_walk != null; } pub fn deinit(self: Account, gpa: Allocator) void { gpa.free(self.address); } }; /// One folder as the ledger holds it: what it is called, what tag it produces, /// and where its delta walk has reached. pub const Folder = struct { folder_id: []const u8, /// The folder's own display name, in the mailbox's language. name: []const u8, /// The tag path: a well-known folder's conventional name, or a display /// name with every ancestor in front of it. `inbox/zig/mailing list`. path: []const u8, /// The tag itself, prefix included, as `folders.forFolder` built it. tag: []const u8, parent_folder_id: ?[]const u8, /// The configuration says to leave this folder alone. Still recorded, so /// that `folders` can say what is being skipped rather than silently /// omitting it. skipped: bool, /// The `@odata.deltaLink` the last completed walk of this folder ended /// with. Null means the next walk is a full one. delta_link: ?[]const u8, delta_at: ?i64, pub fn deinit(self: Folder, gpa: Allocator) void { gpa.free(self.folder_id); gpa.free(self.name); gpa.free(self.path); gpa.free(self.tag); if (self.parent_folder_id) |p| gpa.free(p); if (self.delta_link) |d| gpa.free(d); } }; /// What `upsertFolder` is given. The same fields without the ownership. pub const FolderRow = struct { folder_id: []const u8, name: []const u8, path: []const u8, tag: []const u8, parent_folder_id: ?[]const u8, skipped: bool, }; /// One message waiting to be fetched, as the fetch loop wants it. pub const Pending = struct { message_id: []const u8, folder_id: ?[]const u8, /// Its tags have drifted: the folder was renamed, a category changed, or /// the archive refused the tags last time. tags_dirty: bool, /// Another id in this account carries the same `Message-ID:` and has /// already been archived — which on Graph means this is almost certainly /// the same message after a move, because a move changes the id. /// /// The fetch loop uses it the way it uses `tags_dirty`: skip the /// `HEAD /message/{hash}` pre-check and post, because the archive holding /// the bytes says nothing about whether it holds the new folder's tag. relocated: bool, attempts: i64, pub fn deinit(self: Pending, gpa: Allocator) void { gpa.free(self.message_id); if (self.folder_id) |f| gpa.free(f); } }; pub const Counts = struct { pending: u64 = 0, archived: u64 = 0, failed: u64 = 0, gone: u64 = 0, tags_dirty: u64 = 0, pub fn total(self: Counts) u64 { return self.pending + self.archived + self.failed + self.gone; } }; /// What `status` says about the folders, without listing them. pub const FolderCounts = struct { known: u64 = 0, skipped: u64 = 0, /// Folders with a delta link, which is to say folders whose next sync is /// an update rather than another full listing. tracked: u64 = 0, }; 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. /// /// It is not a secret in the way a credential is -- there is none in it -- but /// it is a map of somebody's mailbox: every message id, when it arrived, which /// folder it is in and what it is called there. A file describing the shape of /// a person's mail should not be the one thing on the machine that anybody can /// read. /// /// `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 -- a sync started by a timer while one is still // running -- waits rather than failing outright. conn.busyTimeout(5_000) catch return error.Unavailable; // WAL so that a reader (`status`, or somebody with `sqlite3` open) does // not block the writer, and `normal` because the archive is the durable // thing here: this file can be rebuilt from a full walk, and paying for a // `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; // Nothing older exists yet. When it does, the upgrades go here. 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; } /// The schema version in the file, or null if it has none — which means /// either an empty file or one SQLite has just created. fn currentVersion(self: *Database) !?i64 { const exists = try self.conn.row( "select 1 from sqlite_schema where type = 'table' and name = 'schema_version'", .{}, ); if (exists) |r| r.deinit() else return null; const row = try self.conn.row("select version from schema_version", .{}) orelse return null; defer row.deinit(); return row.int(0); } // -- accounts ---------------------------------------------------------------- /// Records that this account is one we sync, without disturbing any checkpoint /// it already has. pub fn ensureAccount(self: *Database, address: []const u8) !void { try self.conn.exec( "insert into accounts (address) values (?1) on conflict (address) do nothing", .{address}, ); } pub fn getAccount(self: *Database, gpa: Allocator, address: []const u8) !?Account { const row = try self.conn.row( "select address, last_full_walk, last_sync from accounts where address = ?1", .{address}, ) orelse return null; defer row.deinit(); return .{ .address = try gpa.dupe(u8, row.text(0)), .last_full_walk = row.nullableInt(1), .last_sync = row.nullableInt(2), }; } /// Every address the ledger knows, in a stable order. pub fn listAccounts(self: *Database, gpa: Allocator) ![]const []const u8 { var found: std.ArrayList([]const u8) = .empty; errdefer { for (found.items) |a| gpa.free(a); found.deinit(gpa); } var rows = try self.conn.rows("select address from accounts order by address", .{}); defer rows.deinit(); while (rows.next()) |row| try found.append(gpa, try gpa.dupe(u8, row.text(0))); if (rows.err) |err| return err; return found.toOwnedSlice(gpa); } /// Marks a pass in which every folder was walked to the end. pub fn finishWalk(self: *Database, address: []const u8, now: i64) !void { try self.conn.exec( "update accounts set last_full_walk = ?2 where address = ?1", .{ address, now }, ); } pub fn setLastSync(self: *Database, address: []const u8, now: i64) !void { try self.conn.exec("update accounts set last_sync = ?2 where address = ?1", .{ address, now }); } // -- folders ----------------------------------------------------------------- /// Writes what is known about one folder, and says whether its **tag** /// changed. /// /// That answer is what a rename costs: the folder is the same folder with the /// same delta link and the same messages, and every one of those messages is /// now carrying a tag naming somewhere that no longer exists. The caller marks /// them so that the next fetch re-submits them with the new tag; nothing is /// fetched again, because the bytes have not changed. /// /// The delta link is deliberately left alone: it belongs to the folder, not to /// its name. pub fn upsertFolder(self: *Database, address: []const u8, row: FolderRow, now: i64) !bool { const previous: ?[]const u8 = blk: { const found = try self.conn.row( "select tag from folders where account = ?1 and folder_id = ?2", .{ address, row.folder_id }, ) orelse break :blk null; defer found.deinit(); // Compared here rather than kept: the row's storage dies with it. break :blk if (std.mem.eql(u8, found.text(0), row.tag)) row.tag else ""; }; const renamed = previous != null and previous.?.len == 0; try self.conn.exec( \\insert into folders \\ (account, folder_id, name, path, tag, parent_folder_id, skipped, seen_at) \\values (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) \\on conflict (account, folder_id) do update set \\ name = ?3, path = ?4, tag = ?5, parent_folder_id = ?6, \\ skipped = ?7, seen_at = ?8 , .{ address, row.folder_id, row.name, row.path, row.tag, row.parent_folder_id, row.skipped, now, }); return renamed; } /// Forgets the folders this pass did not see, which is how one deleted in /// Outlook stops being walked. /// /// The messages that were in it are left exactly as they are: the archive is /// append-only, and a folder going away is a fact about the mailbox rather /// than an instruction about the archive. Returns how many were dropped. pub fn pruneFolders(self: *Database, address: []const u8, seen_at: i64) !usize { try self.conn.exec( "delete from folders where account = ?1 and seen_at < ?2", .{ address, seen_at }, ); return self.conn.changes(); } /// Every folder of an account, parents before children, which is the order a /// tag path has to be built in. pub fn listFolders(self: *Database, gpa: Allocator, address: []const u8) ![]const Folder { var found: std.ArrayList(Folder) = .empty; errdefer { for (found.items) |f| f.deinit(gpa); found.deinit(gpa); } var rows = try self.conn.rows( \\select folder_id, name, path, tag, parent_folder_id, skipped, delta_link, delta_at \\ from folders where account = ?1 order by path, folder_id , .{address}); defer rows.deinit(); while (rows.next()) |row| { const folder_id = try gpa.dupe(u8, row.text(0)); errdefer gpa.free(folder_id); const name = try gpa.dupe(u8, row.text(1)); errdefer gpa.free(name); const path = try gpa.dupe(u8, row.text(2)); errdefer gpa.free(path); const tag = try gpa.dupe(u8, row.text(3)); errdefer gpa.free(tag); const parent: ?[]const u8 = if (row.nullableText(4)) |p| try gpa.dupe(u8, p) else null; errdefer if (parent) |p| gpa.free(p); const delta_link: ?[]const u8 = if (row.nullableText(6)) |d| try gpa.dupe(u8, d) else null; try found.append(gpa, .{ .folder_id = folder_id, .name = name, .path = path, .tag = tag, .parent_folder_id = parent, .skipped = row.int(5) != 0, .delta_link = delta_link, .delta_at = row.nullableInt(7), }); } if (rows.err) |err| return err; return found.toOwnedSlice(gpa); } /// The checkpoint a completed delta walk ended with. Only written at the end: /// Graph's `@odata.nextLink` in the middle of a delta walk is a `$skiptoken`, /// which is not a delta token and expires in hours, so an interrupted walk has /// no resume point and has to be started again. pub fn setDeltaLink( self: *Database, address: []const u8, folder_id: []const u8, link: []const u8, now: i64, ) !void { try self.conn.exec( \\update folders set delta_link = ?3, delta_at = ?4 \\ where account = ?1 and folder_id = ?2 , .{ address, folder_id, link, now }); } /// Throws away one folder's resume point, which sends the next walk of it back /// to a full listing. What `error.ResyncRequired` means. pub fn clearDeltaLink(self: *Database, address: []const u8, folder_id: []const u8) !void { try self.conn.exec( "update folders set delta_link = null, delta_at = null where account = ?1 and folder_id = ?2", .{ address, folder_id }, ); } /// The same for every folder, which is what `sync --full` is. pub fn clearDeltaLinks(self: *Database, address: []const u8) !void { try self.conn.exec( \\update accounts set last_full_walk = null where address = ?1; , .{address}); try self.conn.exec( "update folders set delta_link = null, delta_at = null where account = ?1", .{address}, ); } /// Marks every message in a folder as needing its tags re-sent. What a rename /// costs, and nothing more: the bytes are untouched and nothing is fetched /// again. pub fn markFolderTagsDirty(self: *Database, address: []const u8, folder_id: []const u8) !usize { try self.conn.exec( \\update messages set tags_dirty = 1 \\ where account = ?1 and folder_id = ?2 and state in ('archived', 'pending') , .{ address, folder_id }); return self.conn.changes(); } // -- well-known folders ------------------------------------------------------ /// Whether the well-known folder ids have been resolved for this account. /// /// They are cached because resolving them is a request per name and the answers /// do not change: a mailbox's inbox keeps its id for the life of the mailbox. /// `sync --full` clears the cache, which is the way to pick up a folder that /// has appeared since — an archive folder switched on, say. pub fn hasWellKnown(self: *Database, address: []const u8) !bool { const row = try self.conn.row( "select 1 from well_known_folders where account = ?1 limit 1", .{address}, ) orelse return false; row.deinit(); return true; } /// Records the id of a well-known folder, or that it was asked for and is not /// there — a mailbox need not have an archive folder, and asking again every /// run would be a `404` a run forever. pub fn putWellKnown( self: *Database, address: []const u8, name: []const u8, folder_id: ?[]const u8, ) !void { try self.conn.exec( \\insert into well_known_folders (account, name, folder_id) values (?1, ?2, ?3) \\on conflict (account, name) do update set folder_id = ?3 , .{ address, name, folder_id }); } pub fn clearWellKnown(self: *Database, address: []const u8) !void { try self.conn.exec("delete from well_known_folders where account = ?1", .{address}); } /// One well-known name and the folder it turned out to be. pub const WellKnown = struct { name: []const u8, /// Null for a folder this mailbox does not have. folder_id: ?[]const u8, pub fn deinit(self: WellKnown, gpa: Allocator) void { gpa.free(self.name); if (self.folder_id) |id| gpa.free(id); } }; pub fn listWellKnown(self: *Database, gpa: Allocator, address: []const u8) ![]const WellKnown { var found: std.ArrayList(WellKnown) = .empty; errdefer { for (found.items) |w| w.deinit(gpa); found.deinit(gpa); } var rows = try self.conn.rows( "select name, folder_id from well_known_folders where account = ?1 order by name", .{address}, ); defer rows.deinit(); while (rows.next()) |row| { const name = try gpa.dupe(u8, row.text(0)); errdefer gpa.free(name); const folder_id: ?[]const u8 = if (row.nullableText(1)) |id| try gpa.dupe(u8, id) else null; try found.append(gpa, .{ .name = name, .folder_id = folder_id }); } if (rows.err) |err| return err; return found.toOwnedSlice(gpa); } // -- messages ---------------------------------------------------------------- /// What a delta or a listing said about a message. pub const Seen = struct { message_id: []const u8, folder_id: ?[]const u8, /// The RFC 5322 `Message-ID:`, which is the only identifier that survives /// a move. Absent on a message Outlook composed and never sent. internet_message_id: ?[]const u8 = null, /// When Outlook received it, in Unix seconds. received_at: ?i64 = null, }; /// Records a message id as worth fetching, and says whether it was new. /// /// Already knowing about it is the normal case and not a change: a delta walk /// started from no token reports every message in the folder, and the second /// time must not undo the first. The answer matters because it is what a run /// reports: a resync of a folder that is already archived should say it found /// nothing, not that it discovered forty thousand messages. pub fn discover(self: *Database, address: []const u8, m: Seen, now: i64) !bool { try self.conn.exec( \\insert into messages \\ (account, message_id, folder_id, internet_message_id, received_at, \\ state, discovered_at) \\values (?1, ?2, ?3, ?4, ?5, 'pending', ?6) \\on conflict (account, message_id) do nothing , .{ address, m.message_id, m.folder_id, m.internet_message_id, m.received_at, now }); return self.conn.changes() != 0; } /// Brings an already-known message up to date with what the delta just said, /// and marks its tags stale if the folder it is in has changed. /// /// A folder change on a *fixed* id should not happen — Graph gives a moved /// message a new id — but a mailbox is a live thing and the cost of being /// wrong about that is a tag naming the wrong folder forever, so it is /// checked rather than assumed. The comparison is `is not`, SQLite's /// null-safe inequality, so a folder arriving for the first time counts. pub fn noteSeen(self: *Database, address: []const u8, m: Seen) !void { try self.conn.exec( \\update messages \\ set folder_id = coalesce(?3, folder_id), \\ internet_message_id = coalesce(?4, internet_message_id), \\ received_at = coalesce(?5, received_at), \\ tags_dirty = case \\ when ?3 is not null and folder_id is not ?3 then 1 \\ else tags_dirty end \\ where account = ?1 and message_id = ?2 , .{ address, m.message_id, m.folder_id, m.internet_message_id, m.received_at }); } /// Graph has deleted this message, or moved it somewhere this id no longer /// names. Archived bytes are left where they are. pub fn markGone(self: *Database, address: []const u8, message_id: []const u8) !void { try self.conn.exec( "update messages set state = 'gone' where account = ?1 and message_id = ?2", .{ address, message_id }, ); } /// Whatever tags the archive holds for this message are out of date. /// /// A message that has never been archived is already `pending` and needs /// nothing; one that has been archived is not moved back to `pending`, because /// the bytes are still there and re-fetching them would be wasted. The flag is /// what the fetch loop looks for. pub fn markTagsDirty(self: *Database, address: []const u8, message_id: []const u8, now: i64) !void { try self.conn.exec( \\insert into messages (account, message_id, state, discovered_at, tags_dirty) \\values (?1, ?2, 'pending', ?3, 1) \\on conflict (account, message_id) do update set tags_dirty = 1 , .{ address, message_id, now }); } /// The next messages to fetch: those never archived, and those whose tags have /// drifted. `max_attempts` keeps a message that fails every time from being /// retried forever, which would otherwise make every run permanently busy. pub fn takePending( self: *Database, gpa: Allocator, address: []const u8, limit: usize, max_attempts: i64, ) ![]const Pending { var found: std.ArrayList(Pending) = .empty; errdefer { for (found.items) |p| p.deinit(gpa); found.deinit(gpa); } // The `exists` is what makes a move cheap to notice: an id whose // `Message-ID:` is already archived under a different id is the same // message somewhere else, and the pre-check has to be skipped for it or // the new folder's tag is never sent. The index on // (account, internet_message_id) is what keeps it from being a scan. var rows = try self.conn.rows( \\select m.message_id, m.folder_id, m.tags_dirty, m.attempts, \\ exists (select 1 from messages o \\ where o.account = m.account \\ and o.message_id <> m.message_id \\ and o.internet_message_id is not null \\ and o.internet_message_id = m.internet_message_id \\ and o.archive_hash is not null) \\ from messages m \\ where m.account = ?1 \\ and m.attempts < ?3 \\ and (m.state = 'pending' or (m.state = 'archived' and m.tags_dirty = 1)) \\ order by m.attempts, m.message_id \\ limit ?2 , .{ address, clampToI64(limit), max_attempts }); defer rows.deinit(); while (rows.next()) |row| { const id = try gpa.dupe(u8, row.text(0)); errdefer gpa.free(id); const folder_id: ?[]const u8 = if (row.nullableText(1)) |f| try gpa.dupe(u8, f) else null; errdefer if (folder_id) |f| gpa.free(f); try found.append(gpa, .{ .message_id = id, .folder_id = folder_id, .tags_dirty = row.int(2) != 0, .attempts = row.int(3), .relocated = row.int(4) != 0, }); } if (rows.err) |err| return err; return found.toOwnedSlice(gpa); } /// Everything known about a message once the archive has taken it. pub const Archived = struct { message_id: []const u8, folder_id: ?[]const u8, internet_message_id: ?[]const u8, received_at: ?i64, archive_hash: []const u8, }; /// Writes the result of archiving one message. The caller is expected to have /// a transaction open around a whole chunk of these. /// /// The categories are deliberately not written here: they are what *Graph* /// says about a message rather than what the archive did with it, so they are /// recorded by `setCategories` when a delta hands them over. Writing them at /// both ends would mean the comparison that notices a category change was /// against a copy that only exists once a message has been archived. pub fn recordArchived(self: *Database, address: []const u8, m: Archived, now: i64) !void { try self.conn.exec( \\update messages \\ set folder_id = coalesce(?3, folder_id), \\ internet_message_id = coalesce(?4, internet_message_id), \\ received_at = coalesce(?5, received_at), \\ archive_hash = ?6, \\ state = 'archived', \\ tags_dirty = 0, \\ attempts = 0, \\ last_error = null, \\ archived_at = ?7 \\ where account = ?1 and message_id = ?2 , .{ address, m.message_id, m.folder_id, m.internet_message_id, m.received_at, m.archive_hash, now, }); } /// Replaces the categories recorded for a message with what Graph just said. /// /// A replace rather than a diff: the categories arrive as a whole list on /// every delta record, so a category removed should stop being known, and /// working that out from a diff would be more code for the same answer. pub fn setCategories( self: *Database, address: []const u8, message_id: []const u8, categories: []const []const u8, ) !void { try self.conn.exec( "delete from message_categories where account = ?1 and message_id = ?2", .{ address, message_id }, ); for (categories) |category| { if (category.len == 0) continue; try self.conn.exec( \\insert into message_categories (account, message_id, category) values (?1, ?2, ?3) \\on conflict do nothing , .{ address, message_id, category }); } } /// Records that an attempt did not work. `fatal` is the difference between /// "the network was unhappy, try again next run" and "this message cannot be /// archived as it stands" — the first stays `pending`, the second stops. pub fn recordFailure( self: *Database, address: []const u8, message_id: []const u8, message: []const u8, fatal: bool, ) !void { try self.conn.exec( \\update messages \\ set attempts = attempts + 1, \\ last_error = ?3, \\ state = case when ?4 then 'failed' else state end \\ where account = ?1 and message_id = ?2 , .{ address, message_id, message, fatal }); } /// The categories the archive should be holding for a message, sorted. pub fn categoriesFor( self: *Database, gpa: Allocator, address: []const u8, message_id: []const u8, ) ![]const []const u8 { var found: std.ArrayList([]const u8) = .empty; errdefer { for (found.items) |c| gpa.free(c); found.deinit(gpa); } var rows = try self.conn.rows( \\select category from message_categories \\ where account = ?1 and message_id = ?2 order by category , .{ address, message_id }); defer rows.deinit(); while (rows.next()) |row| try found.append(gpa, try gpa.dupe(u8, row.text(0))); if (rows.err) |err| return err; return found.toOwnedSlice(gpa); } /// Whether the categories on a message differ from what the ledger holds. /// /// Outlook's categories are the only tags on a message that can change without /// its id changing, so this is what a delta reporting an updated message is /// asked. The comparison is by set rather than by order: Graph does not /// promise one and a re-ordering is not a change. pub fn categoriesDiffer( self: *Database, address: []const u8, message_id: []const u8, incoming: []const []const u8, ) !bool { var count: usize = 0; var rows = try self.conn.rows( "select category from message_categories where account = ?1 and message_id = ?2", .{ address, message_id }, ); defer rows.deinit(); while (rows.next()) |row| { count += 1; const stored = row.text(0); var matched = false; for (incoming) |c| { if (std.mem.eql(u8, c, stored)) { matched = true; break; } } if (!matched) return true; } if (rows.err) |err| return err; // A category added is as much a change as one removed, and the loop above // only ever sees what is stored. return count != incoming.len; } pub fn counts(self: *Database, address: []const u8) !Counts { var result: Counts = .{}; var rows = try self.conn.rows( "select state, count(*) from messages where account = ?1 group by state", .{address}, ); defer rows.deinit(); while (rows.next()) |row| { const count: u64 = @intCast(@max(0, row.int(1))); const state = State.parse(row.text(0)) orelse continue; switch (state) { .pending => result.pending = count, .archived => result.archived = count, .failed => result.failed = count, .gone => result.gone = count, } } if (rows.err) |err| return err; const dirty = try self.conn.row( "select count(*) from messages where account = ?1 and tags_dirty = 1", .{address}, ); if (dirty) |row| { defer row.deinit(); result.tags_dirty = @intCast(@max(0, row.int(0))); } return result; } pub fn folderCounts(self: *Database, address: []const u8) !FolderCounts { const row = try self.conn.row( \\select count(*), \\ sum(case when skipped = 1 then 1 else 0 end), \\ sum(case when delta_link is not null then 1 else 0 end) \\ from folders where account = ?1 , .{address}) orelse return .{}; defer row.deinit(); return .{ .known = @intCast(@max(0, row.int(0))), .skipped = @intCast(@max(0, row.nullableInt(1) orelse 0)), .tracked = @intCast(@max(0, row.nullableInt(2) orelse 0)), }; } /// The most recent failures, for `status` to show. Borrowed strings are duped /// into `gpa`; the caller frees both halves of every pair. pub const Failure = struct { message_id: []const u8, attempts: i64, message: []const u8, pub fn deinit(self: Failure, gpa: Allocator) void { gpa.free(self.message_id); gpa.free(self.message); } }; pub fn failures( self: *Database, gpa: Allocator, address: []const u8, limit: usize, ) ![]const Failure { var found: std.ArrayList(Failure) = .empty; errdefer { for (found.items) |f| f.deinit(gpa); found.deinit(gpa); } var rows = try self.conn.rows( \\select message_id, attempts, coalesce(last_error, '') \\ from messages \\ where account = ?1 and last_error is not null \\ order by attempts desc, message_id \\ limit ?2 , .{ address, clampToI64(limit) }); defer rows.deinit(); while (rows.next()) |row| { const id = try gpa.dupe(u8, row.text(0)); errdefer gpa.free(id); const message = try gpa.dupe(u8, row.text(2)); errdefer gpa.free(message); try found.append(gpa, .{ .message_id = id, .attempts = row.int(1), .message = message }); } if (rows.err) |err| return err; return found.toOwnedSlice(gpa); } /// Clears the attempt counter and the `failed` state, so that messages given /// up on are tried once more. What `atm-o365 retry` is. pub fn resetFailures(self: *Database, address: []const u8) !usize { try self.conn.exec( \\update messages \\ set attempts = 0, last_error = null, \\ state = case when state = 'failed' then 'pending' else state end \\ where account = ?1 and (state = 'failed' or attempts > 0) , .{address}); return self.conn.changes(); } pub fn begin(self: *Database) !void { return self.conn.transaction(); } pub fn commit(self: *Database) !void { return self.conn.commit(); } pub fn rollback(self: *Database) void { return self.conn.rollback(); } /// SQLite counts in signed 64-bit integers and a caller asking for "everything" /// says `maxInt(usize)`, which on a 64-bit machine does not fit one. Clamping /// rather than casting is the difference between a limit that means no limit /// and a panic in the middle of a sync. fn clampToI64(value: usize) i64 { return @intCast(@min(value, std.math.maxInt(i64))); } const testing = std.testing; fn testDatabase() !Database { return Database.open(std.testing.io, ":memory:", null); } test "opening creates the schema and is idempotent" { var db = try testDatabase(); defer db.deinit(); try testing.expectEqual(@as(?i64, schema_version), try db.currentVersion()); // The migration is version-gated rather than `if not exists`, so running // it again must be a no-op rather than an error. try db.migrate(null); try testing.expectEqual(@as(?i64, schema_version), try db.currentVersion()); } test "a schema from the future is refused rather than written to" { 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)); // The caller is told what it found, so that it can say so rather than // leaving the operator to open the file themselves. try testing.expectEqual(@as(?i64, schema_version + 1), diagnostics.found_schema_version); } test "an account round-trips, and ensureAccount does not disturb a checkpoint" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("jeff@example.com"); { const account = (try db.getAccount(gpa, "jeff@example.com")).?; defer account.deinit(gpa); try testing.expect(!account.hasWalked()); } try db.finishWalk("jeff@example.com", 1000); // A second run of `sync` calls this again; it must not reset anything. try db.ensureAccount("jeff@example.com"); { const account = (try db.getAccount(gpa, "jeff@example.com")).?; defer account.deinit(gpa); try testing.expect(account.hasWalked()); try testing.expectEqual(@as(?i64, 1000), account.last_full_walk); } try testing.expectEqual(@as(?Account, null), try db.getAccount(gpa, "nobody@example.com")); } const inbox: FolderRow = .{ .folder_id = "f-inbox", .name = "Inbox", .path = "inbox", .tag = "o365/inbox", .parent_folder_id = "f-root", .skipped = false, }; test "a folder round-trips and keeps its delta link across an update" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); try testing.expect(!try db.upsertFolder("a@example.com", inbox, 100)); const link = "https://graph.microsoft.com/v1.0/me/mailFolders/f-inbox/messages/delta?$deltatoken=t1"; try db.setDeltaLink("a@example.com", "f-inbox", link, 110); // Seeing the same folder again on the next run must not throw away where // that folder's walk had got to. try testing.expect(!try db.upsertFolder("a@example.com", inbox, 200)); const listed = try db.listFolders(gpa, "a@example.com"); defer { for (listed) |f| f.deinit(gpa); gpa.free(listed); } try testing.expectEqual(@as(usize, 1), listed.len); try testing.expectEqualStrings("o365/inbox", listed[0].tag); try testing.expectEqualStrings(link, listed[0].delta_link.?); try testing.expectEqual(@as(?i64, 110), listed[0].delta_at); try db.clearDeltaLink("a@example.com", "f-inbox"); { const after = try db.listFolders(gpa, "a@example.com"); defer { for (after) |f| f.deinit(gpa); gpa.free(after); } try testing.expectEqual(@as(?[]const u8, null), after[0].delta_link); } } test "a renamed folder is reported, and its messages are marked rather than refetched" { var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.upsertFolder("a@example.com", inbox, 100); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", }, 100); try db.recordArchived("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", .internet_message_id = "", .received_at = 1000, .archive_hash = &@as([128]u8, @splat('a')), }, 100); // The same folder under a new name, which is the same folder: the delta // link and the messages stay, and only the tag they carry has to change. var renamed = inbox; renamed.name = "Posteingang"; renamed.path = "inbox"; renamed.tag = "o365/inbox"; try testing.expect(!try db.upsertFolder("a@example.com", renamed, 200)); var moved = inbox; moved.path = "correspondence"; moved.tag = "o365/correspondence"; try testing.expect(try db.upsertFolder("a@example.com", moved, 300)); try testing.expectEqual(@as(usize, 1), try db.markFolderTagsDirty("a@example.com", "f-inbox")); const c = try db.counts("a@example.com"); // Still archived: the bytes have not changed, so nothing is fetched again. try testing.expectEqual(@as(u64, 1), c.archived); try testing.expectEqual(@as(u64, 1), c.tags_dirty); } test "a folder this pass did not see is forgotten, and its messages are not" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.upsertFolder("a@example.com", inbox, 100); _ = try db.upsertFolder("a@example.com", .{ .folder_id = "f-old", .name = "Old", .path = "Old", .tag = "o365/Old", .parent_folder_id = "f-root", .skipped = false, }, 100); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-old" }, 100); // The second pass sees only the inbox: `Old` was deleted in Outlook. _ = try db.upsertFolder("a@example.com", inbox, 200); try testing.expectEqual(@as(usize, 1), try db.pruneFolders("a@example.com", 200)); const listed = try db.listFolders(gpa, "a@example.com"); defer { for (listed) |f| f.deinit(gpa); gpa.free(listed); } try testing.expectEqual(@as(usize, 1), listed.len); // The archive is append-only: a folder going away says nothing about the // mail that was in it. try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).pending); } test "well-known ids are cached, absence included" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); try testing.expect(!try db.hasWellKnown("a@example.com")); try db.putWellKnown("a@example.com", "inbox", "f-inbox"); // A mailbox need not have an archive folder. Recording that it has not is // what stops every future run asking again and being told 404. try db.putWellKnown("a@example.com", "archive", null); try testing.expect(try db.hasWellKnown("a@example.com")); const listed = try db.listWellKnown(gpa, "a@example.com"); defer { for (listed) |w| w.deinit(gpa); gpa.free(listed); } try testing.expectEqual(@as(usize, 2), listed.len); try testing.expectEqualStrings("archive", listed[0].name); try testing.expectEqual(@as(?[]const u8, null), listed[0].folder_id); try testing.expectEqualStrings("f-inbox", listed[1].folder_id.?); try db.clearWellKnown("a@example.com"); try testing.expect(!try db.hasWellKnown("a@example.com")); } test "discovery is idempotent and does not undo archiving" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); try testing.expect(try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", .internet_message_id = "", .received_at = 1725148800, }, 100)); // The second time is not a discovery, and must not be reported as one. try testing.expect(!try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", }, 101)); try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).pending); try db.setCategories("a@example.com", "m1", &.{ "zig", "receipts" }); try db.recordArchived("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", .internet_message_id = "", .received_at = 1725148800, .archive_hash = &@as([128]u8, @splat('a')), }, 200); // A resync of the folder sees every message again. It must not move an // archived one back to pending, or every resync would re-upload it. try testing.expect(!try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", }, 300)); const c = try db.counts("a@example.com"); try testing.expectEqual(@as(u64, 1), c.archived); try testing.expectEqual(@as(u64, 0), c.pending); const categories = try db.categoriesFor(gpa, "a@example.com", "m1"); defer { for (categories) |x| gpa.free(x); gpa.free(categories); } try testing.expectEqual(@as(usize, 2), categories.len); try testing.expectEqualStrings("receipts", categories[0]); try testing.expectEqualStrings("zig", categories[1]); } test "a category change is noticed, and a re-ordering is not" { var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f" }, 100); try db.setCategories("a@example.com", "m1", &.{ "zig", "receipts" }); // Graph does not promise an order, so a re-ordering is not a change and // must not cost an upload every run for ever. try testing.expect(!try db.categoriesDiffer("a@example.com", "m1", &.{ "receipts", "zig" })); try testing.expect(try db.categoriesDiffer("a@example.com", "m1", &.{"zig"})); try testing.expect(try db.categoriesDiffer( "a@example.com", "m1", &.{ "zig", "receipts", "new" }, )); try testing.expect(try db.categoriesDiffer("a@example.com", "m1", &.{})); } test "a message seen in a different folder has its tags marked" { var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox" }, 100); try db.recordArchived("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", .internet_message_id = null, .received_at = null, .archive_hash = &@as([128]u8, @splat('a')), }, 100); try testing.expectEqual(@as(u64, 0), (try db.counts("a@example.com")).tags_dirty); // Seeing it where it was is not a change. try db.noteSeen("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox" }); try testing.expectEqual(@as(u64, 0), (try db.counts("a@example.com")).tags_dirty); try db.noteSeen("a@example.com", .{ .message_id = "m1", .folder_id = "f-archive" }); try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).tags_dirty); } test "a move is noticed by its Message-ID, because the id does not survive one" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); // Archived out of the inbox. _ = try db.discover("a@example.com", .{ .message_id = "in-inbox", .folder_id = "f-inbox", .internet_message_id = "", }, 100); try db.recordArchived("a@example.com", .{ .message_id = "in-inbox", .folder_id = "f-inbox", .internet_message_id = "", .received_at = null, .archive_hash = &@as([128]u8, @splat('a')), }, 100); // Moved to the archive folder, which on Graph means a new id entirely. _ = try db.discover("a@example.com", .{ .message_id = "in-archive", .folder_id = "f-archive", .internet_message_id = "", }, 200); try db.markGone("a@example.com", "in-inbox"); const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 1), due.len); try testing.expectEqualStrings("in-archive", due[0].message_id); try testing.expectEqualStrings("f-archive", due[0].folder_id.?); // The whole point: the archive already holds these bytes, so without this // the pre-check would skip the upload and the new folder's tag would // never be sent. try testing.expect(due[0].relocated); try testing.expect(!due[0].tags_dirty); } test "a message nothing else shares a Message-ID with is not a move" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f-inbox", .internet_message_id = "", }, 100); // A second message that has no Message-ID at all -- one Outlook composed // and never sent. Two of those must not look like each other's move. _ = try db.discover("a@example.com", .{ .message_id = "m2", .folder_id = "f-drafts" }, 100); _ = try db.discover("a@example.com", .{ .message_id = "m3", .folder_id = "f-drafts" }, 100); try db.recordArchived("a@example.com", .{ .message_id = "m2", .folder_id = "f-drafts", .internet_message_id = null, .received_at = null, .archive_hash = &@as([128]u8, @splat('b')), }, 100); const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 2), due.len); for (due) |p| try testing.expect(!p.relocated); } test "takePending returns what is due and skips what is done" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); for ([_][]const u8{ "m1", "m2", "m3" }) |id| { _ = try db.discover("a@example.com", .{ .message_id = id, .folder_id = "f" }, 100); } try db.recordArchived("a@example.com", .{ .message_id = "m2", .folder_id = "f", .internet_message_id = null, .received_at = null, .archive_hash = &@as([128]u8, @splat('b')), }, 200); { const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 2), due.len); } // A category change on an archived message brings it back into the queue // without moving it out of `archived`: the bytes are still good, only the // tags are stale. try db.markTagsDirty("a@example.com", "m2", 300); { const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 3), due.len); try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).archived); } } test "markTagsDirty on an unknown message discovers it" { var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); // A folder rename can reach a message a delta has never handed over -- // one discovered by an earlier run of a folder that has since been // renamed. Losing it because there was no row to update would be a hole in // the archive. try db.markTagsDirty("a@example.com", "new", 100); try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).pending); } test "a failure counts up, and a fatal one stops the retrying" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f" }, 100); try db.recordFailure("a@example.com", "m1", "the network said no", false); { const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } // Still due: a transient failure is not a verdict on the message. try testing.expectEqual(@as(usize, 1), due.len); try testing.expectEqual(@as(i64, 1), due[0].attempts); } try db.recordFailure("a@example.com", "m1", "not a message at all", true); { const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 0), due.len); try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).failed); } const listed = try db.failures(gpa, "a@example.com", 10); defer { for (listed) |f| f.deinit(gpa); gpa.free(listed); } try testing.expectEqual(@as(usize, 1), listed.len); try testing.expectEqualStrings("not a message at all", listed[0].message); try testing.expectEqual(@as(usize, 1), try db.resetFailures("a@example.com")); { const due = try db.takePending(gpa, "a@example.com", 10, 5); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 1), due.len); } } test "attempts beyond the cap drop out of the queue" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.discover("a@example.com", .{ .message_id = "m1", .folder_id = "f" }, 100); for (0..3) |_| try db.recordFailure("a@example.com", "m1", "again", false); { const due = try db.takePending(gpa, "a@example.com", 10, 3); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 0), due.len); } { const due = try db.takePending(gpa, "a@example.com", 10, 4); defer { for (due) |p| p.deinit(gpa); gpa.free(due); } try testing.expectEqual(@as(usize, 1), due.len); } } test "the folder counts are what status prints" { var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); try testing.expectEqual(FolderCounts{}, try db.folderCounts("a@example.com")); _ = try db.upsertFolder("a@example.com", inbox, 100); _ = try db.upsertFolder("a@example.com", .{ .folder_id = "f-junk", .name = "Sync Issues", .path = "sync-issues", .tag = "o365/sync-issues", .parent_folder_id = "f-root", .skipped = true, }, 100); try db.setDeltaLink("a@example.com", "f-inbox", "https://graph.microsoft.com/x", 110); const c = try db.folderCounts("a@example.com"); try testing.expectEqual(@as(u64, 2), c.known); try testing.expectEqual(@as(u64, 1), c.skipped); try testing.expectEqual(@as(u64, 1), c.tracked); } test "a full walk clears every delta link and the walked claim with them" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("a@example.com"); _ = try db.upsertFolder("a@example.com", inbox, 100); try db.setDeltaLink("a@example.com", "f-inbox", "https://graph.microsoft.com/x", 110); try db.finishWalk("a@example.com", 120); try db.clearDeltaLinks("a@example.com"); const account = (try db.getAccount(gpa, "a@example.com")).?; defer account.deinit(gpa); try testing.expect(!account.hasWalked()); const listed = try db.listFolders(gpa, "a@example.com"); defer { for (listed) |f| f.deinit(gpa); gpa.free(listed); } try testing.expectEqual(@as(?[]const u8, null), listed[0].delta_link); } test "accounts are listed in a stable order and kept apart" { const gpa = testing.allocator; var db = try testDatabase(); defer db.deinit(); try db.ensureAccount("b@example.com"); try db.ensureAccount("a@example.com"); _ = try db.discover("a@example.com", .{ .message_id = "shared-id", .folder_id = "f" }, 100); const listed = try db.listAccounts(gpa); defer { for (listed) |a| gpa.free(a); gpa.free(listed); } try testing.expectEqual(@as(usize, 2), listed.len); try testing.expectEqualStrings("a@example.com", listed[0]); // The same Graph id in two mailboxes is two rows, not one. _ = try db.discover("b@example.com", .{ .message_id = "shared-id", .folder_id = "f" }, 100); try testing.expectEqual(@as(u64, 1), (try db.counts("a@example.com")).pending); try testing.expectEqual(@as(u64, 1), (try db.counts("b@example.com")).pending); } test "the ledger is created owner-only, and an open one is put back" { 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.fmt.bufPrintSentinel( &path_buffer, ".zig-cache/tmp/{s}/state.db", .{tmp.sub_path}, 0, ); { var db = try Database.open(io, path, null); defer db.deinit(); try db.ensureAccount("a@example.com"); } try testing.expectEqual(@as(std.posix.mode_t, 0o600), try modeOf(io, path)); // A ledger from before this existed, or one somebody chmodded, is put // right the next time it is opened rather than left as it was found. { var file = try Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); try file.setPermissions(io, .fromMode(0o644)); } try testing.expectEqual(@as(std.posix.mode_t, 0o644), try modeOf(io, path)); { var db = try Database.open(io, path, null); defer db.deinit(); // And the data survived: `protect` must never truncate what it finds. const account = (try db.getAccount(testing.allocator, "a@example.com")).?; defer account.deinit(testing.allocator); } 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; }