import type { Database } from "./db.js"; import { tableExists } from "./schema-lookups.js"; /* * When an op a device writes enters its stream. Peers page a device's ops in (created_at, * op_id) order and continue after the last one they received. An op ID is random, so an op * must sort after every op already committed when it commits, or a peer that has paged past * that point never receives it. A wall-clock timestamp doesn't give that: two ops can share a * millisecond, a writer can read the clock and then wait for the write lock while another * process commits, and the clock can step back. * * So each op a device writes is stamped while it holds the write lock, at the later of the * time it asks for and just after the device's newest op. The newest op is read on the * connection that then inserts, inside the transaction that holds the lock. A transaction that * read before another process committed can't then write, because SQLite refuses it, so the * stamp never comes from a stale read. * * The stamp is only the op's place in the stream. The memory's conflict clock (revision, * updated_at, device) is set separately, from real time. */ /** Runs `write` holding the write lock: in the caller's transaction, or a new immediate one. */ export function withOwnOpWriteLock(db: Database, write: () => T): T { return db.inTransaction ? write() : db.transaction(write).immediate(); } /** * The created_at for the next op `deviceId` writes: `requested`, unless that doesn't sort after * its newest op or the retained floor, and then just after the later of those. Call it inside * the transaction that inserts the op, holding the write lock (withOwnOpWriteLock). */ export function nextOwnOpStamp(db: Database, deviceId: string, requested: string): string { const newest = newestOwnOp(db, deviceId); // Once every op up to the floor is pruned, the floor is the newest position a peer may have // reached, so a later op must sort after it even with none of this device's ops left. const bounds = [newest, retainedFloorTimestamp(db)].filter( (bound): bound is string => typeof bound === "string" && bound.length > 0, ); return bounds.reduce( (stamp, bound) => (stamp > bound ? stamp : stampAfter(bound, stamp)), requested, ); } /** The op types a device writes. The status index orders each one's ops by device and time. */ const OWN_OP_TYPES = ["upsert", "delete", "reassign_scope", "access_cleanup"]; const STATUS_INDEX = "idx_replication_ops_type_device_created"; /** * When the device's newest op was stamped. Rows from before devices had IDs are served with the * device's own, so they count too. With the status index each op type is one index lookup. * Without it, which schema setup only skips on a store it can't change, the newest ops are read * back until one is the device's. */ function newestOwnOp(db: Database, deviceId: string): string | null { const devices = [deviceId, "local"]; const indexed = db .prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?") .get(STATUS_INDEX); if (!indexed) { const newest = db .prepare(`SELECT created_at FROM replication_ops WHERE device_id IN (?, ?) ORDER BY created_at DESC LIMIT 1`) .pluck() .get(...devices); return typeof newest === "string" ? newest : null; } const lookup = db .prepare("SELECT MAX(created_at) FROM replication_ops WHERE op_type = ? AND device_id = ?") .pluck(); const stamps = OWN_OP_TYPES.flatMap((type) => devices.map((device) => lookup.get(type, device))); const newest = stamps .filter((stamp): stamp is string => typeof stamp === "string") .sort() .at(-1); return newest ?? null; } function retainedFloorTimestamp(db: Database): string | null { const tables = ["sync_reset_state_v2", "sync_reset_state"].filter((name) => tableExists(db, name), ); const floors = tables.map((table) => db.prepare(`SELECT MAX(retained_floor_cursor) FROM ${table}`).pluck().get(), ); const floor = floors .filter((value): value is string => typeof value === "string") .sort() .at(-1); if (!floor) return null; const separator = floor.indexOf("|"); return separator < 0 ? floor : floor.slice(0, separator); } /** * The first ISO timestamp after `bound`, both in time and as text, because the stream orders * by text. Stored values without milliseconds ("...:00Z") sort after the same second with them * ("...:00.001Z"), so the next whole second is used then. A bound that isn't a time keeps * `fallback`, as before stamping. */ function stampAfter(bound: string, fallback: string): string { const time = Date.parse(bound); if (Number.isNaN(time)) return fallback; const nextMillisecond = new Date(time + 1).toISOString(); if (nextMillisecond > bound) return nextMillisecond; const nextSecond = new Date(Math.floor(time / 1000) * 1000 + 1000).toISOString(); return nextSecond > bound ? nextSecond : fallback; }