Files
Shade/packages/shade-vault/src/store.ts
Sterister b82a803e0c
Some checks failed
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
feat(vault): v2 — compressed entries, chunked objects, index pushes, lazy reads, prune (4.14.0)
Entries are deflate-raw compressed when it pays, split into 4 MiB sealed
parts, and manifests are compressed (SVM2). A push with a local index
reuses unchanged files without downloading anything, and a push with no
changes commits nothing. Readers fetch one manifest and only the entries
they need. The relay records what each version references and can prune
old versions signed by the owner. Cross-language vectors in
test-vectors/vault-v2.json.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 01:38:45 +02:00

218 lines
8.4 KiB
TypeScript

/**
* 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<Uint8Array | null>;
setOwner(vaultId: string, publicKey: Uint8Array): Promise<void>;
hasObject(vaultId: string, hash: string): Promise<boolean>;
putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void>;
getObject(vaultId: string, hash: string): Promise<Uint8Array | null>;
/** Highest committed seq, or 0 when empty. */
head(vaultId: string): Promise<number>;
/** Newest last. `limit` counts back from the head. */
log(vaultId: string, limit?: number): Promise<VaultLogEntry[]>;
/**
* 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<void>;
/**
* 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<VaultPruneResult>;
/** Total stored bytes, for quota decisions. */
usage(vaultId: string): Promise<number>;
}
/**
* 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<string, Uint8Array>();
private objects = new Map<string, Map<string, Uint8Array>>();
private logs = new Map<string, VaultLogEntry[]>();
/** Per vault: seq → referenced hashes, or null for an untracked entry. */
private refs = new Map<string, Map<number, Set<string> | null>>();
/** Per vault: objects an untracked entry may reference. */
private pinned = new Map<string, Set<string>>();
/** Per vault: when each object was first stored, for the prune grace. */
private storedAt = new Map<string, Map<string, number>>();
async getOwner(vaultId: string): Promise<Uint8Array | null> {
return this.owners.get(vaultId) ?? null;
}
async setOwner(vaultId: string, publicKey: Uint8Array): Promise<void> {
this.owners.set(vaultId, publicKey);
}
private bucket(vaultId: string): Map<string, Uint8Array> {
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<boolean> {
return this.bucket(vaultId).has(hash);
}
async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void> {
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<Uint8Array | null> {
return this.bucket(vaultId).get(hash) ?? null;
}
async head(vaultId: string): Promise<number> {
const l = this.logs.get(vaultId);
return l && l.length > 0 ? l[l.length - 1]!.seq : 0;
}
async log(vaultId: string, limit?: number): Promise<VaultLogEntry[]> {
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<void> {
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<string>();
for (const h of this.bucket(vaultId).keys()) pins.add(h);
this.pinned.set(vaultId, pins);
}
}
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
// 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<number, Set<string> | null>();
const bucket = this.bucket(vaultId);
const times = this.storedAt.get(vaultId) ?? new Map<string, number>();
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<string>();
for (const e of log) {
everReferenced.add(e.manifest);
for (const h of byseq.get(e.seq) ?? []) everReferenced.add(h);
}
const inUse = new Set<string>();
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<string>();
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<number> {
let total = 0;
for (const bytes of this.bucket(vaultId).values()) total += bytes.length;
return total;
}
}