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>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-sqlite",
|
||||
"version": "4.13.2",
|
||||
"version": "4.14.0",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Database } from 'bun:sqlite';
|
||||
import type { VaultLogEntry, VaultStore } from '@shade/vault';
|
||||
import type { VaultLogEntry, VaultPrunePlan, VaultPruneResult, VaultStore } from '@shade/vault';
|
||||
|
||||
/**
|
||||
* SQLite-backed VaultStore for the V4.13 encrypted file store.
|
||||
@@ -9,6 +9,13 @@ import type { VaultLogEntry, VaultStore } from '@shade/vault';
|
||||
* never decrypts anything — it enforces auth, verifies that an object's bytes
|
||||
* hash to its name, and refuses a commit whose objects are not all present.
|
||||
*
|
||||
* A fourth table, `shade_vault_refs`, records which objects each version
|
||||
* references (the commit's signed hashes plus its manifest). The relay cannot
|
||||
* read manifests, so this is what prune computes garbage from. Versions from
|
||||
* before it existed have `refs_known = 0`, and every object that was in the
|
||||
* database when the columns were added is `pinned` — see `VaultPrunePlan` for
|
||||
* why that is the safe reading and how the pins are eventually released.
|
||||
*
|
||||
* Objects are stored as BLOBs rather than base64 text. A workspace backup is
|
||||
* a few hundred files where the blob primitive holds one small profile, so the
|
||||
* 33% base64 overhead stops being a rounding error.
|
||||
@@ -31,6 +38,8 @@ export class SqliteVaultStore implements VaultStore {
|
||||
log: ReturnType<Database['prepare']>;
|
||||
logLimit: ReturnType<Database['prepare']>;
|
||||
appendLog: ReturnType<Database['prepare']>;
|
||||
appendRef: ReturnType<Database['prepare']>;
|
||||
pinAll: ReturnType<Database['prepare']>;
|
||||
usage: ReturnType<Database['prepare']>;
|
||||
};
|
||||
|
||||
@@ -56,18 +65,48 @@ export class SqliteVaultStore implements VaultStore {
|
||||
bytes BLOB NOT NULL,
|
||||
size INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
pinned INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (vault_id, hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shade_vault_log (
|
||||
vault_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
manifest TEXT NOT NULL,
|
||||
at INTEGER NOT NULL,
|
||||
bytes INTEGER NOT NULL,
|
||||
vault_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
manifest TEXT NOT NULL,
|
||||
at INTEGER NOT NULL,
|
||||
bytes INTEGER NOT NULL,
|
||||
refs_known INTEGER NOT NULL DEFAULT 1,
|
||||
PRIMARY KEY (vault_id, seq)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shade_vault_refs (
|
||||
vault_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
PRIMARY KEY (vault_id, seq, hash)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS shade_vault_refs_by_hash ON shade_vault_refs (vault_id, hash);
|
||||
`);
|
||||
|
||||
// Databases from before ref tracking. The defaults here are the whole
|
||||
// migration: every existing log row becomes untracked (refs_known = 0),
|
||||
// and every existing object pinned (pinned = 1), because any of them may
|
||||
// be referenced by one of those rows. New rows always set both columns
|
||||
// explicitly, so these defaults only ever apply to the old ones.
|
||||
const has = (table: string, column: string): boolean =>
|
||||
(this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some(
|
||||
(c) => c.name === column,
|
||||
);
|
||||
this.db.transaction(() => {
|
||||
if (!has('shade_vault_log', 'refs_known')) {
|
||||
this.db.exec(
|
||||
'ALTER TABLE shade_vault_log ADD COLUMN refs_known INTEGER NOT NULL DEFAULT 0',
|
||||
);
|
||||
}
|
||||
if (!has('shade_vault_objects', 'pinned')) {
|
||||
this.db.exec('ALTER TABLE shade_vault_objects ADD COLUMN pinned INTEGER NOT NULL DEFAULT 1');
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
private prepareStatements() {
|
||||
@@ -82,7 +121,7 @@ export class SqliteVaultStore implements VaultStore {
|
||||
// An object's name IS its content hash, so a repeat upload is the same
|
||||
// bytes by definition — ignoring it is correct, not lossy.
|
||||
putObject: this.db.prepare(
|
||||
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at) VALUES (?, ?, ?, ?, ?)',
|
||||
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at, pinned) VALUES (?, ?, ?, ?, ?, 0)',
|
||||
),
|
||||
getObject: this.db.prepare(
|
||||
'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||
@@ -95,8 +134,12 @@ export class SqliteVaultStore implements VaultStore {
|
||||
'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC',
|
||||
),
|
||||
appendLog: this.db.prepare(
|
||||
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes) VALUES (?, ?, ?, ?, ?)',
|
||||
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes, refs_known) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
),
|
||||
appendRef: this.db.prepare(
|
||||
'INSERT OR IGNORE INTO shade_vault_refs (vault_id, seq, hash) VALUES (?, ?, ?)',
|
||||
),
|
||||
pinAll: this.db.prepare('UPDATE shade_vault_objects SET pinned = 1 WHERE vault_id = ?'),
|
||||
usage: this.db.prepare(
|
||||
'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?',
|
||||
),
|
||||
@@ -139,8 +182,100 @@ export class SqliteVaultStore implements VaultStore {
|
||||
return rows;
|
||||
}
|
||||
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry): Promise<void> {
|
||||
this.stmts.appendLog.run(vaultId, entry.seq, entry.manifest, entry.at, entry.bytes);
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||
this.db.transaction(() => {
|
||||
this.stmts.appendLog.run(
|
||||
vaultId,
|
||||
entry.seq,
|
||||
entry.manifest,
|
||||
entry.at,
|
||||
entry.bytes,
|
||||
refs ? 1 : 0,
|
||||
);
|
||||
if (refs) {
|
||||
for (const h of refs) this.stmts.appendRef.run(vaultId, entry.seq, h);
|
||||
} else {
|
||||
// Untracked: it can reference anything stored so far, so pin all of it.
|
||||
this.stmts.pinAll.run(vaultId);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
* One transaction, so a commit cannot interleave between deciding what is
|
||||
* garbage and deleting it. bun:sqlite is synchronous, and a write
|
||||
* transaction holds the database lock for its whole duration.
|
||||
*/
|
||||
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
|
||||
return this.db.transaction((): VaultPruneResult => {
|
||||
const keep = new Set(plan.keep);
|
||||
const rows = this.db
|
||||
.prepare('SELECT seq, refs_known FROM shade_vault_log WHERE vault_id = ?')
|
||||
.all(vaultId) as Array<{ seq: number; refs_known: number }>;
|
||||
const removed = rows.filter((r) => r.seq <= plan.upTo && !keep.has(r.seq)).map((r) => r.seq);
|
||||
const untrackedRemains = rows.some(
|
||||
(r) => r.refs_known === 0 && !(r.seq <= plan.upTo && !keep.has(r.seq)),
|
||||
);
|
||||
|
||||
// The removed seqs go into a temp table so every query below can say
|
||||
// "the log as it will be" without string-building an IN list.
|
||||
this.db.exec(
|
||||
'CREATE TEMP TABLE IF NOT EXISTS shade_vault_prune_removed (seq INTEGER PRIMARY KEY)',
|
||||
);
|
||||
this.db.exec('DELETE FROM shade_vault_prune_removed');
|
||||
const addRemoved = this.db.prepare('INSERT INTO shade_vault_prune_removed (seq) VALUES (?)');
|
||||
for (const seq of removed) addRemoved.run(seq);
|
||||
|
||||
if (!untrackedRemains) {
|
||||
// No version with an unknown reference set is left, so nothing can
|
||||
// depend on a pin any more.
|
||||
this.db.prepare('UPDATE shade_vault_objects SET pinned = 0 WHERE vault_id = ?').run(vaultId);
|
||||
}
|
||||
|
||||
// Garbage: not pinned, not used by a remaining version, and — if no
|
||||
// version ever used it — older than the grace for in-flight uploads.
|
||||
const garbage = this.db
|
||||
.prepare(
|
||||
`SELECT o.hash AS hash, o.size AS size FROM shade_vault_objects o
|
||||
WHERE o.vault_id = ?1
|
||||
AND o.pinned = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM shade_vault_refs r
|
||||
WHERE r.vault_id = ?1 AND r.hash = o.hash
|
||||
AND r.seq NOT IN (SELECT seq FROM shade_vault_prune_removed))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM shade_vault_log l
|
||||
WHERE l.vault_id = ?1 AND l.manifest = o.hash
|
||||
AND l.seq NOT IN (SELECT seq FROM shade_vault_prune_removed))
|
||||
AND (
|
||||
o.created_at <= ?2
|
||||
OR EXISTS (SELECT 1 FROM shade_vault_refs r WHERE r.vault_id = ?1 AND r.hash = o.hash)
|
||||
OR EXISTS (SELECT 1 FROM shade_vault_log l WHERE l.vault_id = ?1 AND l.manifest = o.hash))`,
|
||||
)
|
||||
.all(vaultId, plan.protectSince) as Array<{ hash: string; size: number }>;
|
||||
|
||||
const delObject = this.db.prepare(
|
||||
'DELETE FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||
);
|
||||
let freedBytes = 0;
|
||||
for (const g of garbage) {
|
||||
delObject.run(vaultId, g.hash);
|
||||
freedBytes += g.size;
|
||||
}
|
||||
this.db
|
||||
.prepare(
|
||||
'DELETE FROM shade_vault_refs WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)',
|
||||
)
|
||||
.run(vaultId);
|
||||
this.db
|
||||
.prepare(
|
||||
'DELETE FROM shade_vault_log WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)',
|
||||
)
|
||||
.run(vaultId);
|
||||
this.db.exec('DELETE FROM shade_vault_prune_removed');
|
||||
|
||||
return { removedVersions: removed.length, removedObjects: garbage.length, freedBytes };
|
||||
})();
|
||||
}
|
||||
|
||||
async usage(vaultId: string): Promise<number> {
|
||||
|
||||
@@ -118,3 +118,134 @@ describe('semantics', () => {
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('prune', () => {
|
||||
const h = (c: string) => c.repeat(64);
|
||||
|
||||
test('removes unkept versions and only the objects nothing else uses', async () => {
|
||||
const store = new SqliteVaultStore(scratch('prune'));
|
||||
await store.putObject(VAULT, h('1'), new Uint8Array(10)); // manifest 1
|
||||
await store.putObject(VAULT, h('2'), new Uint8Array(20)); // manifest 2
|
||||
await store.putObject(VAULT, h('a'), new Uint8Array(30)); // shared file
|
||||
await store.putObject(VAULT, h('b'), new Uint8Array(40)); // only in v1
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1'), h('a'), h('b')]);
|
||||
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2'), h('a')]);
|
||||
|
||||
const res = await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||
expect(res).toEqual({ removedVersions: 1, removedObjects: 2, freedBytes: 50 });
|
||||
expect(await store.hasObject(VAULT, h('a'))).toBe(true);
|
||||
expect(await store.hasObject(VAULT, h('b'))).toBe(false);
|
||||
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('a fresh, never-committed upload survives; a stale one does not', async () => {
|
||||
const store = new SqliteVaultStore(scratch('grace'));
|
||||
await store.putObject(VAULT, h('1'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1')]);
|
||||
await store.putObject(VAULT, h('c'), new Uint8Array(5));
|
||||
|
||||
const kept = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() - 60_000 });
|
||||
expect(kept.removedObjects).toBe(0);
|
||||
const gone = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() + 1 });
|
||||
expect(gone.removedObjects).toBe(1);
|
||||
expect(await store.hasObject(VAULT, h('c'))).toBe(false);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('never removes an entry above upTo, even when it is not in keep', async () => {
|
||||
const store = new SqliteVaultStore(scratch('upto'));
|
||||
for (let seq = 1; seq <= 3; seq++) {
|
||||
await store.appendLog(VAULT, { seq, manifest: `${seq}`.repeat(64), at: seq, bytes: 0 }, []);
|
||||
}
|
||||
await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: 0 });
|
||||
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2, 3]);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('untracked entries pin what existed when they were appended, until they are gone', async () => {
|
||||
const store = new SqliteVaultStore(scratch('pin'));
|
||||
await store.putObject(VAULT, h('1'), new Uint8Array(1));
|
||||
await store.putObject(VAULT, h('b'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }); // no refs
|
||||
await store.putObject(VAULT, h('2'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]);
|
||||
await store.putObject(VAULT, h('3'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 3, manifest: h('3'), at: 3, bytes: 0 }, [h('3')]);
|
||||
|
||||
const first = await store.prune(VAULT, { keep: [1, 3], upTo: 3, protectSince: Date.now() });
|
||||
expect(first.removedObjects).toBe(1); // only manifest 2
|
||||
expect(await store.hasObject(VAULT, h('b'))).toBe(true);
|
||||
|
||||
const second = await store.prune(VAULT, { keep: [3], upTo: 3, protectSince: Date.now() });
|
||||
expect(second.removedObjects).toBe(2); // manifest 1 and b, unpinned
|
||||
expect(await store.hasObject(VAULT, h('3'))).toBe(true);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('a database from before ref tracking migrates with everything pinned', async () => {
|
||||
// The exact pre-v2 schema, with a version and its objects in it.
|
||||
const path = scratch('migrate');
|
||||
const { Database } = await import('bun:sqlite');
|
||||
const old = new Database(path, { create: true });
|
||||
old.exec(`
|
||||
CREATE TABLE shade_vault_objects (vault_id TEXT NOT NULL, hash TEXT NOT NULL, bytes BLOB NOT NULL,
|
||||
size INTEGER NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (vault_id, hash));
|
||||
CREATE TABLE shade_vault_log (vault_id TEXT NOT NULL, seq INTEGER NOT NULL, manifest TEXT NOT NULL,
|
||||
at INTEGER NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY (vault_id, seq));
|
||||
`);
|
||||
old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('1'), new Uint8Array(1), 1, 0);
|
||||
old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('a'), new Uint8Array(1), 1, 0);
|
||||
old.prepare('INSERT INTO shade_vault_log VALUES (?, ?, ?, ?, ?)').run(VAULT, 1, h('1'), 1, 2);
|
||||
old.close();
|
||||
|
||||
const store = new SqliteVaultStore(path);
|
||||
// A tracked version on top, then drop nothing but nothing referenced by it:
|
||||
// the old file object must survive because version 1 may use it.
|
||||
await store.putObject(VAULT, h('2'), new Uint8Array(1));
|
||||
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]);
|
||||
const res = await store.prune(VAULT, { keep: [1, 2], upTo: 2, protectSince: Date.now() });
|
||||
expect(res.removedObjects).toBe(0);
|
||||
expect(await store.hasObject(VAULT, h('a'))).toBe(true);
|
||||
store.close();
|
||||
|
||||
// Reopening runs the migration check again and must be a no-op.
|
||||
const again = new SqliteVaultStore(path);
|
||||
expect((await again.log(VAULT)).map((e) => e.seq)).toEqual([1, 2]);
|
||||
const final = await again.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||
expect(final).toMatchObject({ removedVersions: 1, removedObjects: 2 });
|
||||
again.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('through the real routes and client', () => {
|
||||
test('v2 push, index reuse, multi-part and prune all work on SQLite', async () => {
|
||||
const { SubtleCryptoProvider } = await import('@shade/crypto-web');
|
||||
const { createVaultRoutes } = await import('@shade/vault/server');
|
||||
const { HttpVaultTransport, VaultClient, deriveVaultKeys } = await import('@shade/vault');
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const store = new SqliteVaultStore(scratch('e2e'));
|
||||
const routes = createVaultRoutes(store, crypto, { pruneGraceMs: 0 });
|
||||
const transport = new HttpVaultTransport('http://v', (i, init) => routes.fetch(new Request(i, init)));
|
||||
const keys = await deriveVaultKeys(new Uint8Array(32).fill(5), 'scaffold');
|
||||
const client = new VaultClient(crypto, keys, transport, { chunkSize: 512 });
|
||||
|
||||
const big = new Uint8Array(2000);
|
||||
globalThis.crypto.getRandomValues(big);
|
||||
const text = new TextEncoder().encode('linje\n'.repeat(500));
|
||||
const first = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 1);
|
||||
const same = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 2, undefined, {
|
||||
index: first.index,
|
||||
});
|
||||
expect(same.unchanged).toBe(true);
|
||||
await client.push([{ path: 't.md', bytes: text }], 3, undefined, { index: same.index });
|
||||
|
||||
const pruned = await client.prune([2]);
|
||||
expect(pruned.removedVersions).toBe(1);
|
||||
expect(pruned.removedObjects).toBe(5); // big.bin's 4 parts + manifest 1
|
||||
const { files } = await client.pull();
|
||||
expect(files.get('t.md')).toEqual(text);
|
||||
expect(files.has('big.bin')).toBe(false);
|
||||
store.close();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user