/** * Relay-side storage for a vault. * * The interface is deliberately dumb: put bytes under a hash, list a log, * append to it. Nothing here can decrypt, and nothing needs to — which is * what makes a SQLite, Postgres or object-store implementation equivalent. */ import type { VaultLogEntry, VaultPruneResult } from './types.js'; /** * What the relay is asked to forget, already checked by the route. * * The relay cannot read a manifest, so it cannot know on its own which * objects a version uses. It knows because every commit since prune existed * hands the store its `refs` — the signed `hashes` plus the manifest object — * and that list is what garbage collection is computed from. * * **Versions committed before ref tracking have no list.** Their objects are * "pinned": every object present when such an entry was appended (or, for a * SQLite database, when it was migrated) is treated as referenced for as long * as any untracked entry remains in the log. Pinning is coarse — it protects * objects the old entry may not use — but it is the only safe reading of "we * do not know", and it is self-limiting: once the last untracked version has * been pruned, no unknown reference set is left, the pins are dropped and * those objects are collected like any other. */ export interface VaultPrunePlan { /** Sequence numbers to keep. The route has checked that the head is among them. */ keep: readonly number[]; /** * Only entries with `seq <= upTo` may be removed — the head the route saw. * A commit that lands between that check and the prune is newer, and must * survive even though it is not in `keep`. */ upTo: number; /** * Epoch millis. An object no version has ever referenced, stored after * this, is left alone: it is most likely an upload whose commit is still * on its way, and deleting it would fail that push with MISSING_OBJECTS. * Objects that a removed version referenced get no such grace. */ protectSince: number; } export interface VaultStore { /** Ed25519 pubkey pinned on first write (TOFU), or null for a fresh vault. */ getOwner(vaultId: string): Promise; setOwner(vaultId: string, publicKey: Uint8Array): Promise; hasObject(vaultId: string, hash: string): Promise; putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise; getObject(vaultId: string, hash: string): Promise; /** Highest committed seq, or 0 when empty. */ head(vaultId: string): Promise; /** Newest last. `limit` counts back from the head. */ log(vaultId: string, limit?: number): Promise; /** * Append a version. `refs` is every object hash it references, manifest * included; the routes always pass it. Omitting it records the entry as * untracked, with the pinning described on `VaultPrunePlan` — that is how * entries from before ref tracking behave, and how tests simulate them. */ appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise; /** * Remove log entries and garbage-collect the objects nothing left uses. * Must be atomic with respect to other writes to the same vault. */ prune(vaultId: string, plan: VaultPrunePlan): Promise; /** Total stored bytes, for quota decisions. */ usage(vaultId: string): Promise; } /** * In-memory store. Real for tests, a footgun in production — the same shape * as `MemoryBlobStore`, and the same warning applies: a restart loses * everything, and it will do so without an error. */ export class MemoryVaultStore implements VaultStore { private owners = new Map(); private objects = new Map>(); private logs = new Map(); /** Per vault: seq → referenced hashes, or null for an untracked entry. */ private refs = new Map | null>>(); /** Per vault: objects an untracked entry may reference. */ private pinned = new Map>(); /** Per vault: when each object was first stored, for the prune grace. */ private storedAt = new Map>(); async getOwner(vaultId: string): Promise { return this.owners.get(vaultId) ?? null; } async setOwner(vaultId: string, publicKey: Uint8Array): Promise { this.owners.set(vaultId, publicKey); } private bucket(vaultId: string): Map { let b = this.objects.get(vaultId); if (!b) { b = new Map(); this.objects.set(vaultId, b); } return b; } async hasObject(vaultId: string, hash: string): Promise { return this.bucket(vaultId).has(hash); } async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise { const bucket = this.bucket(vaultId); if (bucket.has(hash)) return; bucket.set(hash, bytes); let times = this.storedAt.get(vaultId); if (!times) { times = new Map(); this.storedAt.set(vaultId, times); } times.set(hash, Date.now()); } async getObject(vaultId: string, hash: string): Promise { return this.bucket(vaultId).get(hash) ?? null; } async head(vaultId: string): Promise { const l = this.logs.get(vaultId); return l && l.length > 0 ? l[l.length - 1]!.seq : 0; } async log(vaultId: string, limit?: number): Promise { const l = this.logs.get(vaultId) ?? []; return limit === undefined ? [...l] : l.slice(Math.max(0, l.length - limit)); } async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise { const l = this.logs.get(vaultId) ?? []; if (l.some((e) => e.seq === entry.seq)) { // Mirrors the SQLite primary key: two rows with one seq would make // history ambiguous, and prune would not know which refs to drop. throw new Error(`vault ${vaultId} already has seq ${entry.seq}`); } l.push(entry); this.logs.set(vaultId, l); let byseq = this.refs.get(vaultId); if (!byseq) { byseq = new Map(); this.refs.set(vaultId, byseq); } if (refs) { byseq.set(entry.seq, new Set(refs)); } else { // An untracked entry can only reference what was here when it was // committed — so pin exactly that. byseq.set(entry.seq, null); const pins = this.pinned.get(vaultId) ?? new Set(); for (const h of this.bucket(vaultId).keys()) pins.add(h); this.pinned.set(vaultId, pins); } } async prune(vaultId: string, plan: VaultPrunePlan): Promise { // No await anywhere below: the whole prune runs in one turn of the event // loop, which is what makes it atomic against a concurrent commit. const keep = new Set(plan.keep); const log = this.logs.get(vaultId) ?? []; const byseq = this.refs.get(vaultId) ?? new Map | null>(); const bucket = this.bucket(vaultId); const times = this.storedAt.get(vaultId) ?? new Map(); const removed = log.filter((e) => e.seq <= plan.upTo && !keep.has(e.seq)); const remaining = log.filter((e) => !(e.seq <= plan.upTo && !keep.has(e.seq))); const everReferenced = new Set(); for (const e of log) { everReferenced.add(e.manifest); for (const h of byseq.get(e.seq) ?? []) everReferenced.add(h); } const inUse = new Set(); let untrackedRemains = false; for (const e of remaining) { inUse.add(e.manifest); const r = byseq.get(e.seq); if (r === undefined || r === null) untrackedRemains = true; else for (const h of r) inUse.add(h); } if (!untrackedRemains) this.pinned.delete(vaultId); const pins = this.pinned.get(vaultId) ?? new Set(); let removedObjects = 0; let freedBytes = 0; for (const [hash, bytes] of [...bucket]) { if (inUse.has(hash) || pins.has(hash)) continue; if (!everReferenced.has(hash) && (times.get(hash) ?? 0) > plan.protectSince) continue; bucket.delete(hash); times.delete(hash); removedObjects++; freedBytes += bytes.length; } for (const e of removed) byseq.delete(e.seq); this.logs.set(vaultId, remaining); return { removedVersions: removed.length, removedObjects, freedBytes }; } async usage(vaultId: string): Promise { let total = 0; for (const bytes of this.bucket(vaultId).values()) total += bytes.length; return total; } }