zerobucket 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,2506 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { createHash } from "crypto";
5
+ import { existsSync as existsSync2, readFileSync } from "fs";
6
+ import { parseArgs } from "util";
7
+
8
+ // src/errors.ts
9
+ var ZeroBucketError = class extends Error {
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.name = new.target.name;
13
+ }
14
+ };
15
+ var StorageError = class extends ZeroBucketError {
16
+ };
17
+
18
+ // src/adapters/shared.ts
19
+ var DEFAULT_STREAM_CHUNK_SIZE = 1024 * 1024;
20
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
+ function isValidId(id) {
22
+ return typeof id === "string" && UUID_RE.test(id);
23
+ }
24
+ function msg(exc) {
25
+ return exc instanceof Error ? exc.message : String(exc);
26
+ }
27
+ function wrap(prefix, exc) {
28
+ return exc instanceof StorageError ? exc : new StorageError(`${prefix}: ${msg(exc)}`, { cause: exc });
29
+ }
30
+ function sleep(ms) {
31
+ return new Promise((resolve) => setTimeout(resolve, ms));
32
+ }
33
+ async function mapLimit(items, limit, fn) {
34
+ const out = new Array(items.length);
35
+ let next = 0;
36
+ await Promise.all(
37
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
38
+ while (next < items.length) {
39
+ const i = next++;
40
+ out[i] = await fn(items[i]);
41
+ }
42
+ })
43
+ );
44
+ return out;
45
+ }
46
+ function tieredWithoutStorage(id, key) {
47
+ return new StorageError(
48
+ `Image ${JSON.stringify(id)} is stored in object storage (key=${JSON.stringify(key)}) but this ZeroBucket was constructed without \`objectStorage\`. Configure it with the same bucket and credentials that were used to tier this image.`
49
+ );
50
+ }
51
+ async function hydrateRow(row, id, os) {
52
+ let data;
53
+ if (row.storage_backend === "object_storage") {
54
+ if (!os) throw tieredWithoutStorage(id, row.object_storage_key);
55
+ data = await os.download(row.object_storage_key);
56
+ if (data.length !== row.size_bytes) {
57
+ throw new StorageError(
58
+ `Object ${JSON.stringify(row.object_storage_key)} for image ${JSON.stringify(id)} has ${data.length} bytes but the database records ${row.size_bytes}. The stored object is corrupted or was replaced.`
59
+ );
60
+ }
61
+ } else {
62
+ data = row.data;
63
+ }
64
+ return {
65
+ id: String(row.id),
66
+ data,
67
+ mimeType: row.mime_type,
68
+ originalFilename: row.original_filename,
69
+ sizeBytes: row.size_bytes,
70
+ width: row.width,
71
+ height: row.height,
72
+ checksumSha256: row.checksum_sha256
73
+ };
74
+ }
75
+ async function* streamFromObjectStorage(os, id, key, start, end, chunkSize) {
76
+ let offset = start;
77
+ while (offset <= end) {
78
+ const last = Math.min(offset + chunkSize - 1, end);
79
+ const expected = last - offset + 1;
80
+ const chunk = await os.downloadRange(key, offset, last);
81
+ if (chunk.length !== expected) {
82
+ throw new StorageError(
83
+ `Object ${JSON.stringify(key)} for image ${JSON.stringify(id)} returned ${chunk.length} bytes for a ${expected}-byte range; the stored object is shorter than the database records.`
84
+ );
85
+ }
86
+ yield chunk;
87
+ offset = last + 1;
88
+ }
89
+ }
90
+ function prettySize(bytes) {
91
+ if (bytes < 1024) return `${bytes} bytes`;
92
+ const units = ["kB", "MB", "GB", "TB"];
93
+ let v = bytes / 1024;
94
+ let i = 0;
95
+ while (v >= 1024 && i < units.length - 1) {
96
+ v /= 1024;
97
+ i += 1;
98
+ }
99
+ return `${v.toFixed(1)} ${units[i]}`;
100
+ }
101
+
102
+ // src/adapters/postgres.ts
103
+ var SCHEMA = `
104
+ CREATE TABLE IF NOT EXISTS zerobucket_images (
105
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
106
+ data BYTEA NOT NULL,
107
+ mime_type TEXT NOT NULL,
108
+ original_filename TEXT,
109
+ size_bytes INTEGER NOT NULL,
110
+ width INTEGER,
111
+ height INTEGER,
112
+ checksum_sha256 CHAR(64) NOT NULL,
113
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
114
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
115
+ );
116
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_checksum ON zerobucket_images (checksum_sha256);
117
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_created_at ON zerobucket_images (created_at);
118
+
119
+ -- Object-storage tiering columns (additive; identical to the Python package).
120
+ ALTER TABLE zerobucket_images ALTER COLUMN data DROP NOT NULL;
121
+ ALTER TABLE zerobucket_images
122
+ ADD COLUMN IF NOT EXISTS storage_backend TEXT NOT NULL DEFAULT 'postgres';
123
+ ALTER TABLE zerobucket_images ADD COLUMN IF NOT EXISTS object_storage_bucket TEXT;
124
+ ALTER TABLE zerobucket_images ADD COLUMN IF NOT EXISTS object_storage_key TEXT;
125
+ DO $$
126
+ BEGIN
127
+ IF NOT EXISTS (
128
+ SELECT 1 FROM pg_constraint WHERE conname = 'zerobucket_storage_location_check'
129
+ ) THEN
130
+ ALTER TABLE zerobucket_images ADD CONSTRAINT zerobucket_storage_location_check
131
+ CHECK (
132
+ (storage_backend = 'postgres'
133
+ AND data IS NOT NULL
134
+ AND object_storage_key IS NULL
135
+ AND object_storage_bucket IS NULL)
136
+ OR
137
+ (storage_backend = 'object_storage'
138
+ AND data IS NULL
139
+ AND object_storage_key IS NOT NULL
140
+ AND object_storage_bucket IS NOT NULL)
141
+ );
142
+ END IF;
143
+ END $$;
144
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_storage_backend
145
+ ON zerobucket_images (storage_backend) WHERE storage_backend != 'postgres';
146
+ `;
147
+ var INSERT = `
148
+ INSERT INTO zerobucket_images
149
+ (data, mime_type, original_filename, size_bytes, width, height, checksum_sha256)
150
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
151
+ RETURNING id;`;
152
+ var SELECT_FULL = `
153
+ SELECT id, data, mime_type, original_filename, size_bytes, width, height,
154
+ checksum_sha256, storage_backend, object_storage_bucket, object_storage_key
155
+ FROM zerobucket_images WHERE id = $1;`;
156
+ var SELECT_MANY = `
157
+ SELECT id, data, mime_type, original_filename, size_bytes, width, height,
158
+ checksum_sha256, storage_backend, object_storage_bucket, object_storage_key
159
+ FROM zerobucket_images WHERE id = ANY($1::uuid[]);`;
160
+ var SELECT_METADATA = `
161
+ SELECT id, mime_type, original_filename, size_bytes, width, height, checksum_sha256
162
+ FROM zerobucket_images WHERE id = $1;`;
163
+ var SELECT_CHUNK = `SELECT substring(data FROM $1::int FOR $2::int) AS chunk FROM zerobucket_images WHERE id = $3;`;
164
+ var SELECT_STREAM_INFO = `SELECT size_bytes, storage_backend, object_storage_key FROM zerobucket_images WHERE id = $1;`;
165
+ var DELETE_RETURNING = `DELETE FROM zerobucket_images WHERE id = $1 RETURNING storage_backend, object_storage_key;`;
166
+ var DELETE_MANY = `DELETE FROM zerobucket_images WHERE id = ANY($1::uuid[]) RETURNING id, storage_backend, object_storage_key;`;
167
+ var EXISTS = `SELECT 1 FROM zerobucket_images WHERE id = $1;`;
168
+ var SELECT_FOR_TIERING = `SELECT data, mime_type, size_bytes, storage_backend FROM zerobucket_images WHERE id = $1 FOR UPDATE;`;
169
+ var UPDATE_AFTER_TIERING = `UPDATE zerobucket_images SET data = NULL, storage_backend = 'object_storage', object_storage_bucket = $1, object_storage_key = $2, updated_at = now() WHERE id = $3;`;
170
+ var DEDUP_SCHEMA = `
171
+ CREATE TABLE IF NOT EXISTS zerobucket_blobs (
172
+ checksum_sha256 CHAR(64) PRIMARY KEY,
173
+ data BYTEA NOT NULL,
174
+ mime_type TEXT NOT NULL,
175
+ size_bytes INTEGER NOT NULL,
176
+ width INTEGER,
177
+ height INTEGER,
178
+ ref_count INTEGER NOT NULL DEFAULT 0,
179
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
180
+ );
181
+ CREATE TABLE IF NOT EXISTS zerobucket_image_refs (
182
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
183
+ checksum_sha256 CHAR(64) NOT NULL REFERENCES zerobucket_blobs(checksum_sha256),
184
+ original_filename TEXT,
185
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
186
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
187
+ );
188
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_image_refs_checksum ON zerobucket_image_refs (checksum_sha256);
189
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_image_refs_created_at ON zerobucket_image_refs (created_at);
190
+ `;
191
+ var D_UPSERT_BLOB = `
192
+ INSERT INTO zerobucket_blobs (checksum_sha256, data, mime_type, size_bytes, width, height, ref_count)
193
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
194
+ ON CONFLICT (checksum_sha256) DO UPDATE SET ref_count = zerobucket_blobs.ref_count + EXCLUDED.ref_count;`;
195
+ var D_INSERT_REF = `INSERT INTO zerobucket_image_refs (checksum_sha256, original_filename) VALUES ($1, $2) RETURNING id;`;
196
+ var D_COLS = `r.id, b.data, b.mime_type, r.original_filename, b.size_bytes, b.width, b.height, r.checksum_sha256,
197
+ 'postgres'::text AS storage_backend, NULL::text AS object_storage_bucket, NULL::text AS object_storage_key`;
198
+ var D_FROM = `FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256`;
199
+ var D_DELETE_REF = `DELETE FROM zerobucket_image_refs WHERE id = $1 RETURNING checksum_sha256;`;
200
+ var D_DELETE_REFS = `DELETE FROM zerobucket_image_refs WHERE id = ANY($1::uuid[]) RETURNING id, checksum_sha256;`;
201
+ var D_DECREMENT = `UPDATE zerobucket_blobs SET ref_count = ref_count - $1 WHERE checksum_sha256 = $2 RETURNING ref_count;`;
202
+ var D_DELETE_EMPTY = `DELETE FROM zerobucket_blobs WHERE checksum_sha256 = ANY($1::text[]) AND ref_count <= 0;`;
203
+ var CLASSIC_SQL = {
204
+ schema: SCHEMA,
205
+ selectFull: SELECT_FULL,
206
+ selectMany: SELECT_MANY,
207
+ selectMetadata: SELECT_METADATA,
208
+ selectStreamInfo: SELECT_STREAM_INFO,
209
+ selectChunk: SELECT_CHUNK,
210
+ exists: EXISTS
211
+ };
212
+ var DEDUP_SQL = {
213
+ schema: DEDUP_SCHEMA,
214
+ selectFull: `SELECT ${D_COLS} ${D_FROM} WHERE r.id = $1;`,
215
+ selectMany: `SELECT ${D_COLS} ${D_FROM} WHERE r.id = ANY($1::uuid[]);`,
216
+ selectMetadata: `SELECT r.id, b.mime_type, r.original_filename, b.size_bytes, b.width, b.height, r.checksum_sha256 ${D_FROM} WHERE r.id = $1;`,
217
+ selectStreamInfo: `SELECT b.size_bytes, 'postgres'::text AS storage_backend, NULL::text AS object_storage_key ${D_FROM} WHERE r.id = $1;`,
218
+ selectChunk: `SELECT substring(b.data FROM $1::int FOR $2::int) AS chunk ${D_FROM} WHERE r.id = $3;`,
219
+ exists: `SELECT 1 FROM zerobucket_image_refs WHERE id = $1;`
220
+ };
221
+ var RETRYABLE_SQLSTATES = /* @__PURE__ */ new Set([
222
+ "40001",
223
+ // serialization_failure
224
+ "40P01",
225
+ // deadlock_detected
226
+ "08000",
227
+ // connection_exception
228
+ "08003",
229
+ // connection_does_not_exist
230
+ "08006",
231
+ // connection_failure
232
+ "08001",
233
+ // sqlclient_unable_to_establish_sqlconnection
234
+ "08004",
235
+ // sqlserver_rejected_establishment_of_sqlconnection
236
+ "57P01",
237
+ // admin_shutdown
238
+ "57P02",
239
+ // crash_shutdown
240
+ "57P03",
241
+ // cannot_connect_now
242
+ "53000",
243
+ // insufficient_resources
244
+ "53300"
245
+ // too_many_connections
246
+ ]);
247
+ var RETRYABLE_NODE_CODES = /* @__PURE__ */ new Set([
248
+ "ECONNRESET",
249
+ "ECONNREFUSED",
250
+ "ETIMEDOUT",
251
+ "EPIPE",
252
+ "ECONNABORTED"
253
+ ]);
254
+ var CONNECTION_MESSAGE_RE = /connection terminated|connection timeout|timeout exceeded when trying to connect|client has encountered a connection error/i;
255
+ function isRetryable(exc) {
256
+ if (!(exc instanceof Error)) return false;
257
+ const code = exc.code;
258
+ if (typeof code === "string") {
259
+ if (RETRYABLE_SQLSTATES.has(code) || RETRYABLE_NODE_CODES.has(code))
260
+ return true;
261
+ }
262
+ return CONNECTION_MESSAGE_RE.test(exc.message);
263
+ }
264
+ function isConnectionLevel(exc) {
265
+ if (!(exc instanceof Error)) return false;
266
+ const code = exc.code;
267
+ if (typeof code === "string" && (RETRYABLE_NODE_CODES.has(code) || code.startsWith("08") || code.startsWith("57"))) {
268
+ return true;
269
+ }
270
+ return CONNECTION_MESSAGE_RE.test(exc.message);
271
+ }
272
+ var MAX_BACKOFF_MS = 2e3;
273
+ function backoffDelayMs(attempt, baseDelayMs) {
274
+ const exponential = baseDelayMs * 2 ** (attempt - 1);
275
+ const jitter = Math.random() * baseDelayMs;
276
+ return Math.min(exponential + jitter, MAX_BACKOFF_MS);
277
+ }
278
+ var PostgresBackend = class {
279
+ constructor(opts) {
280
+ this.opts = opts;
281
+ if (!opts.connectionString && !opts.pool) {
282
+ throw new TypeError(
283
+ "PostgresBackend requires either `connectionString` or `pool`"
284
+ );
285
+ }
286
+ this.ownsPool = !opts.pool;
287
+ this.pool = opts.pool;
288
+ this.maxRetries = opts.maxRetries ?? 3;
289
+ this.retryBaseDelayMs = opts.retryBaseDelayMs ?? 100;
290
+ this.autoMigrate = opts.autoMigrate ?? true;
291
+ this.dedup = opts.dedup ?? false;
292
+ if (this.dedup && opts.objectStorage) {
293
+ throw new TypeError(
294
+ "objectStorage is not supported together with dedup: true (same restriction as the Python package). Tiering moves one image's bytes, but a deduplicated blob can be shared by many images."
295
+ );
296
+ }
297
+ this.sql = this.dedup ? DEDUP_SQL : CLASSIC_SQL;
298
+ }
299
+ opts;
300
+ pool;
301
+ ownsPool;
302
+ readyPromise;
303
+ closed = false;
304
+ maxRetries;
305
+ retryBaseDelayMs;
306
+ autoMigrate;
307
+ dedup;
308
+ sql;
309
+ // ---- lifecycle -------------------------------------------------------
310
+ ready() {
311
+ if (this.closed)
312
+ return Promise.reject(
313
+ new StorageError("This ZeroBucket instance has been closed")
314
+ );
315
+ this.readyPromise ??= this.init().catch((exc) => {
316
+ this.readyPromise = void 0;
317
+ throw exc;
318
+ });
319
+ return this.readyPromise;
320
+ }
321
+ async init() {
322
+ if (!this.pool) {
323
+ let pg;
324
+ try {
325
+ const mod = await import("pg");
326
+ pg = mod.default ?? mod;
327
+ } catch (cause) {
328
+ throw new StorageError(
329
+ "PostgresBackend requires the 'pg' package. Install it with: npm install pg",
330
+ { cause }
331
+ );
332
+ }
333
+ const config = {
334
+ connectionString: this.opts.connectionString,
335
+ min: this.opts.poolMinSize ?? 1,
336
+ max: this.opts.poolMaxSize ?? 5,
337
+ connectionTimeoutMillis: this.opts.poolTimeoutMs ?? 1e4
338
+ };
339
+ this.pool = new pg.Pool(config);
340
+ this.pool.on("error", () => {
341
+ });
342
+ }
343
+ try {
344
+ if (this.autoMigrate) await this.migrate();
345
+ else await this.pool.query("SELECT 1");
346
+ } catch (exc) {
347
+ if (this.ownsPool) {
348
+ await this.pool.end().catch(() => {
349
+ });
350
+ this.pool = void 0;
351
+ }
352
+ throw exc instanceof StorageError ? exc : new StorageError(`Could not connect to PostgreSQL: ${msg(exc)}`, {
353
+ cause: exc
354
+ });
355
+ }
356
+ }
357
+ /** Create the schema if missing. Serialized across processes with an advisory lock. */
358
+ async migrate() {
359
+ const pool = this.pool;
360
+ let client;
361
+ try {
362
+ client = await pool.connect();
363
+ } catch (exc) {
364
+ throw new StorageError(`Could not connect to PostgreSQL: ${msg(exc)}`, {
365
+ cause: exc
366
+ });
367
+ }
368
+ try {
369
+ await client.query("BEGIN");
370
+ await client.query(
371
+ "SELECT pg_advisory_xact_lock(hashtext('zerobucket_migrate'))"
372
+ );
373
+ await client.query(this.sql.schema);
374
+ await client.query("COMMIT");
375
+ client.release();
376
+ } catch (exc) {
377
+ await client.query("ROLLBACK").catch(() => {
378
+ });
379
+ client.release(true);
380
+ throw new StorageError(`Migration failed: ${msg(exc)}`, { cause: exc });
381
+ }
382
+ }
383
+ async close() {
384
+ this.closed = true;
385
+ const pool = this.pool;
386
+ this.pool = void 0;
387
+ this.readyPromise = void 0;
388
+ if (pool && this.ownsPool) await pool.end();
389
+ }
390
+ // ---- execution core --------------------------------------------------
391
+ emit(operation, start, success, error, retryCount) {
392
+ const cb = this.opts.onOperation;
393
+ if (!cb) return;
394
+ try {
395
+ cb({
396
+ operation,
397
+ durationMs: performance.now() - start,
398
+ success,
399
+ error,
400
+ retryCount
401
+ });
402
+ } catch {
403
+ }
404
+ }
405
+ /**
406
+ * Run `work` and return its result, emitting exactly one OperationEvent.
407
+ *
408
+ * connection given -> run once on it, no BEGIN/COMMIT, no retry.
409
+ * connection absent -> pooled; `tx` wraps the work in BEGIN/COMMIT; transient
410
+ * failures retry the WHOLE closure on a fresh connection.
411
+ */
412
+ async run(operation, connection, work, { tx = false } = {}) {
413
+ if (connection) {
414
+ if (!isQueryable(connection)) {
415
+ throw new TypeError(
416
+ "PostgresBackend expects a pg client/pool client as `connection` (an object with query()), not a SQLite Database."
417
+ );
418
+ }
419
+ const start2 = performance.now();
420
+ try {
421
+ const result = tx ? await this.atomic(connection, work) : await work(connection);
422
+ this.emit(operation, start2, true, null, 0);
423
+ return result;
424
+ } catch (exc) {
425
+ this.emit(operation, start2, false, msg(exc), 0);
426
+ throw exc;
427
+ }
428
+ }
429
+ await this.ready();
430
+ const start = performance.now();
431
+ let attempt = 0;
432
+ for (; ; ) {
433
+ let client;
434
+ let destroy = false;
435
+ try {
436
+ client = await this.pool.connect();
437
+ if (tx) await client.query("BEGIN");
438
+ const result = await work(client);
439
+ if (tx) await client.query("COMMIT");
440
+ this.emit(operation, start, true, null, attempt);
441
+ return result;
442
+ } catch (exc) {
443
+ if (client && tx) {
444
+ try {
445
+ await client.query("ROLLBACK");
446
+ } catch {
447
+ destroy = true;
448
+ }
449
+ }
450
+ if (isConnectionLevel(exc)) destroy = true;
451
+ attempt += 1;
452
+ if (attempt > this.maxRetries || !isRetryable(exc)) {
453
+ this.emit(operation, start, false, msg(exc), attempt - 1);
454
+ throw exc;
455
+ }
456
+ } finally {
457
+ client?.release(destroy);
458
+ }
459
+ await sleep(backoffDelayMs(attempt, this.retryBaseDelayMs));
460
+ }
461
+ }
462
+ /**
463
+ * Make multi-statement work all-or-nothing on a CALLER-supplied connection.
464
+ * - Caller has an open transaction -> SAVEPOINT: a failure rolls back only our work and the
465
+ * caller's transaction stays usable; success joins their transaction.
466
+ * - No open transaction (an autocommit pg.Client) -> open and commit our own, so a failure
467
+ * can never leave half-applied state (e.g. an inflated dedup ref_count).
468
+ */
469
+ async atomic(conn, work) {
470
+ let ownTx = false;
471
+ try {
472
+ await conn.query("SAVEPOINT zerobucket_atomic");
473
+ } catch (exc) {
474
+ if (exc.code !== "25P01") throw exc;
475
+ ownTx = true;
476
+ await conn.query("BEGIN");
477
+ }
478
+ try {
479
+ const result = await work(conn);
480
+ await conn.query(
481
+ ownTx ? "COMMIT" : "RELEASE SAVEPOINT zerobucket_atomic"
482
+ );
483
+ return result;
484
+ } catch (exc) {
485
+ try {
486
+ await conn.query(
487
+ ownTx ? "ROLLBACK" : "ROLLBACK TO SAVEPOINT zerobucket_atomic"
488
+ );
489
+ } catch {
490
+ }
491
+ throw exc;
492
+ }
493
+ }
494
+ // ---- StorageBackend --------------------------------------------------
495
+ async put(row, { connection } = {}) {
496
+ try {
497
+ if (this.dedup) {
498
+ return await this.run(
499
+ "put",
500
+ connection,
501
+ async (q) => {
502
+ await q.query(D_UPSERT_BLOB, blobParams(row, 1));
503
+ return String(
504
+ (await q.query(D_INSERT_REF, [
505
+ row.checksumSha256,
506
+ row.originalFilename
507
+ ])).rows[0].id
508
+ );
509
+ },
510
+ { tx: true }
511
+ );
512
+ }
513
+ return await this.run("put", connection, async (q) => {
514
+ const res = await q.query(INSERT, rowParams(row));
515
+ return String(res.rows[0].id);
516
+ });
517
+ } catch (exc) {
518
+ throw wrap("Failed to store image", exc);
519
+ }
520
+ }
521
+ async putMany(rows, { connection } = {}) {
522
+ if (rows.length === 0) return [];
523
+ try {
524
+ if (this.dedup) {
525
+ return await this.run(
526
+ "put_many",
527
+ connection,
528
+ async (q) => {
529
+ const groups = /* @__PURE__ */ new Map();
530
+ for (const r of rows) {
531
+ const g = groups.get(r.checksumSha256);
532
+ if (g) g.n += 1;
533
+ else groups.set(r.checksumSha256, { row: r, n: 1 });
534
+ }
535
+ for (const checksum of [...groups.keys()].sort()) {
536
+ const g = groups.get(checksum);
537
+ await q.query(D_UPSERT_BLOB, blobParams(g.row, g.n));
538
+ }
539
+ const ids = [];
540
+ for (const r of rows) {
541
+ ids.push(
542
+ String(
543
+ (await q.query(D_INSERT_REF, [
544
+ r.checksumSha256,
545
+ r.originalFilename
546
+ ])).rows[0].id
547
+ )
548
+ );
549
+ }
550
+ return ids;
551
+ },
552
+ { tx: true }
553
+ );
554
+ }
555
+ return await this.run(
556
+ "put_many",
557
+ connection,
558
+ async (q) => {
559
+ const ids = [];
560
+ for (const r of rows)
561
+ ids.push(String((await q.query(INSERT, rowParams(r))).rows[0].id));
562
+ return ids;
563
+ },
564
+ { tx: true }
565
+ );
566
+ } catch (exc) {
567
+ throw wrap("Failed to store image batch", exc);
568
+ }
569
+ }
570
+ async get(id, { connection } = {}) {
571
+ if (!isValidId(id)) return null;
572
+ let row;
573
+ try {
574
+ row = await this.run(
575
+ "get",
576
+ connection,
577
+ async (q) => (await q.query(this.sql.selectFull, [id])).rows[0]
578
+ );
579
+ } catch (exc) {
580
+ throw wrap("Failed to retrieve image", exc);
581
+ }
582
+ return row ? this.hydrate(row, id) : null;
583
+ }
584
+ async getMany(ids, { connection } = {}) {
585
+ const valid = ids.filter(isValidId);
586
+ if (valid.length === 0) return [];
587
+ let rows;
588
+ try {
589
+ rows = await this.run(
590
+ "get_many",
591
+ connection,
592
+ async (q) => (await q.query(this.sql.selectMany, [valid])).rows
593
+ );
594
+ } catch (exc) {
595
+ throw wrap("Failed to retrieve image batch", exc);
596
+ }
597
+ return mapLimit(rows, 4, (r) => this.hydrate(r, String(r.id)));
598
+ }
599
+ async getMetadata(id, { connection } = {}) {
600
+ if (!isValidId(id)) return null;
601
+ let row;
602
+ try {
603
+ row = await this.run(
604
+ "get_metadata",
605
+ connection,
606
+ async (q) => (await q.query(this.sql.selectMetadata, [id])).rows[0]
607
+ );
608
+ } catch (exc) {
609
+ throw wrap("Failed to retrieve image metadata", exc);
610
+ }
611
+ if (!row) return null;
612
+ return {
613
+ id: String(row.id),
614
+ mimeType: row.mime_type,
615
+ originalFilename: row.original_filename,
616
+ sizeBytes: row.size_bytes,
617
+ width: row.width,
618
+ height: row.height,
619
+ checksumSha256: row.checksum_sha256
620
+ };
621
+ }
622
+ async getStream(id, opts) {
623
+ if (!isValidId(id)) return null;
624
+ const { connection, chunkSize } = opts;
625
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0)
626
+ throw new RangeError("chunkSize must be a positive integer");
627
+ let info;
628
+ try {
629
+ info = await this.run(
630
+ "get_metadata",
631
+ connection,
632
+ async (q) => (await q.query(this.sql.selectStreamInfo, [id])).rows[0]
633
+ );
634
+ } catch (exc) {
635
+ throw wrap("Failed to retrieve image metadata", exc);
636
+ }
637
+ if (!info) return null;
638
+ const totalSize = info.size_bytes;
639
+ const start = opts.range?.start ?? 0;
640
+ const end = Math.min(opts.range?.end ?? totalSize - 1, totalSize - 1);
641
+ if (info.storage_backend === "object_storage") {
642
+ const os = this.opts.objectStorage;
643
+ if (!os) throw tieredWithoutStorage(id, info.object_storage_key);
644
+ return streamFromObjectStorage(
645
+ os,
646
+ id,
647
+ info.object_storage_key,
648
+ start,
649
+ end,
650
+ chunkSize
651
+ );
652
+ }
653
+ const self = this;
654
+ async function* generate() {
655
+ let offset = start;
656
+ let delivered = 0;
657
+ const wanted = Math.max(0, end - start + 1);
658
+ while (delivered < wanted) {
659
+ const length = Math.min(chunkSize, wanted - delivered);
660
+ let row;
661
+ try {
662
+ row = await self.run(
663
+ "get_stream",
664
+ connection,
665
+ async (q) => (await q.query(self.sql.selectChunk, [offset + 1, length, id])).rows[0]
666
+ );
667
+ } catch (exc) {
668
+ throw wrap("Failed to stream image", exc);
669
+ }
670
+ if (!row) {
671
+ throw new StorageError(
672
+ `Image ${JSON.stringify(id)} was deleted while streaming (delivered ${delivered} of ${wanted} bytes). Pass connection with your own open transaction if you need a consistent read across concurrent writers.`
673
+ );
674
+ }
675
+ const chunk = row.chunk;
676
+ if (!chunk || chunk.length === 0) {
677
+ throw new StorageError(
678
+ `Image ${JSON.stringify(id)} ended early while streaming (delivered ${delivered} of ${wanted} bytes).`
679
+ );
680
+ }
681
+ yield chunk;
682
+ offset += chunk.length;
683
+ delivered += chunk.length;
684
+ }
685
+ }
686
+ return generate();
687
+ }
688
+ async delete(id, { connection } = {}) {
689
+ if (!isValidId(id)) return false;
690
+ if (this.dedup) return this.deleteDedup(id, connection);
691
+ try {
692
+ const row = await this.run(
693
+ "delete",
694
+ connection,
695
+ async (q) => (await q.query(DELETE_RETURNING, [id])).rows[0]
696
+ );
697
+ if (row?.storage_backend === "object_storage")
698
+ await this.cleanupObject([row.object_storage_key], connection);
699
+ return row !== void 0;
700
+ } catch (exc) {
701
+ throw wrap("Failed to delete image", exc);
702
+ }
703
+ }
704
+ async deleteMany(ids, { connection } = {}) {
705
+ const valid = ids.filter(isValidId);
706
+ if (valid.length === 0) return [];
707
+ if (this.dedup) return this.deleteManyDedup(valid, connection);
708
+ try {
709
+ const rows = await this.run(
710
+ "delete_many",
711
+ connection,
712
+ async (q) => (await q.query(DELETE_MANY, [valid])).rows
713
+ );
714
+ await this.cleanupObject(
715
+ rows.filter((r) => r.storage_backend === "object_storage").map((r) => r.object_storage_key),
716
+ connection
717
+ );
718
+ return rows.map((r) => String(r.id));
719
+ } catch (exc) {
720
+ throw wrap("Failed to delete image batch", exc);
721
+ }
722
+ }
723
+ async exists(id, { connection } = {}) {
724
+ if (!isValidId(id)) return false;
725
+ try {
726
+ return await this.run(
727
+ "exists",
728
+ connection,
729
+ async (q) => ((await q.query(this.sql.exists, [id])).rowCount ?? 0) > 0
730
+ );
731
+ } catch (exc) {
732
+ throw wrap("Failed to check image existence", exc);
733
+ }
734
+ }
735
+ // ---- maintenance (CLI) -----------------------------------------------
736
+ async getInfo() {
737
+ try {
738
+ return await this.run("info", void 0, async (q) => {
739
+ const imgTable = this.dedup ? "zerobucket_image_refs" : "zerobucket_images";
740
+ const present = await q.query(
741
+ "SELECT to_regclass($1) AS a, to_regclass('zerobucket_blobs') AS b",
742
+ [imgTable]
743
+ );
744
+ if (!present.rows[0].a || this.dedup && !present.rows[0].b)
745
+ return null;
746
+ const j = this.dedup ? "FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256" : "FROM zerobucket_images";
747
+ const size = this.dedup ? "b.size_bytes" : "size_bytes";
748
+ const created = this.dedup ? "r.created_at" : "created_at";
749
+ const mime = this.dedup ? "b.mime_type" : "mime_type";
750
+ const tot = (await q.query(
751
+ `SELECT count(*)::int AS n, coalesce(sum(${size}), 0)::text AS bytes, min(${created})::text AS oldest, max(${created})::text AS newest ${j}`
752
+ )).rows[0];
753
+ const disk = (await q.query(
754
+ this.dedup ? "SELECT pg_size_pretty(pg_total_relation_size('zerobucket_blobs') + pg_total_relation_size('zerobucket_image_refs')) AS s" : "SELECT pg_size_pretty(pg_total_relation_size('zerobucket_images')) AS s"
755
+ )).rows[0].s;
756
+ const fmt = (await q.query(
757
+ `SELECT ${mime} AS m, count(*)::int AS n, coalesce(sum(${size}), 0)::text AS bytes ${j} GROUP BY ${mime} ORDER BY count(*) DESC, ${mime}`
758
+ )).rows;
759
+ const info = {
760
+ mode: this.dedup ? "dedup" : "classic",
761
+ count: tot.n,
762
+ totalBytes: Number(tot.bytes),
763
+ // Postgres prints the offset as "+00"; Python's CLI (and ISO-8601) print "+00:00". Normalise so output is identical.
764
+ oldest: tot.oldest && tot.oldest.replace(/([+-]\d\d)$/, "$1:00"),
765
+ newest: tot.newest && tot.newest.replace(/([+-]\d\d)$/, "$1:00"),
766
+ onDisk: disk,
767
+ byFormat: fmt.map((r) => ({
768
+ mimeType: r.m,
769
+ count: r.n,
770
+ bytes: Number(r.bytes)
771
+ }))
772
+ };
773
+ if (this.dedup) {
774
+ const b = (await q.query(
775
+ "SELECT count(*)::int AS n, coalesce(sum(size_bytes), 0)::text AS bytes FROM zerobucket_blobs"
776
+ )).rows[0];
777
+ info.dedup = { blobs: b.n, storedBytes: Number(b.bytes) };
778
+ } else {
779
+ const t = (await q.query(
780
+ "SELECT count(*)::int AS n, coalesce(sum(size_bytes), 0)::text AS bytes FROM zerobucket_images WHERE storage_backend = 'object_storage'"
781
+ )).rows[0];
782
+ info.tiered = { count: t.n, bytes: Number(t.bytes) };
783
+ }
784
+ return info;
785
+ });
786
+ } catch (exc) {
787
+ throw wrap("Failed to read storage info", exc);
788
+ }
789
+ }
790
+ async listImages(o = {}) {
791
+ const where = [];
792
+ const params = [];
793
+ const add = (sql2, v) => (params.push(v), where.push(sql2.replace("$?", `$${params.length}`)));
794
+ if (o.minSize !== void 0)
795
+ add(`${this.dedup ? "b.size_bytes" : "size_bytes"} >= $?`, o.minSize);
796
+ if (o.olderThanDays !== void 0)
797
+ add(
798
+ `${this.dedup ? "r.created_at" : "created_at"} <= now() - make_interval(days => $?::int)`,
799
+ o.olderThanDays
800
+ );
801
+ if (o.onlyUntiered && !this.dedup)
802
+ where.push("storage_backend = 'postgres'");
803
+ const from = this.dedup ? "FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256" : "FROM zerobucket_images";
804
+ const idCol = this.dedup ? "r.id" : "id";
805
+ const tierCol = this.dedup ? "false AS tiered" : "(storage_backend = 'object_storage') AS tiered";
806
+ const order = o.sample !== void 0 ? "ORDER BY random()" : `ORDER BY ${this.dedup ? "r.created_at" : "created_at"}, ${idCol}`;
807
+ const lim = o.sample ?? o.limit;
808
+ let sql = `SELECT ${idCol} AS id, ${tierCol} ${from}${where.length ? " WHERE " + where.join(" AND ") : ""} ${order}`;
809
+ if (lim !== void 0) {
810
+ params.push(lim);
811
+ sql += ` LIMIT $${params.length}`;
812
+ }
813
+ try {
814
+ const rows = await this.run(
815
+ "list_images",
816
+ void 0,
817
+ async (q) => (await q.query(sql, params)).rows
818
+ );
819
+ return rows.map((r) => ({ id: String(r.id), tiered: Boolean(r.tiered) }));
820
+ } catch (exc) {
821
+ throw wrap("Failed to list images", exc);
822
+ }
823
+ }
824
+ // ---- dedup deletes / migration ---------------------------------------
825
+ async deleteDedup(id, connection) {
826
+ try {
827
+ return await this.run(
828
+ "delete",
829
+ connection,
830
+ async (q) => {
831
+ const ref = (await q.query(D_DELETE_REF, [id])).rows[0];
832
+ if (!ref) return false;
833
+ const checksum = ref.checksum_sha256;
834
+ const dec = (await q.query(D_DECREMENT, [1, checksum])).rows[0];
835
+ if (dec && dec.ref_count <= 0)
836
+ await q.query(D_DELETE_EMPTY, [[checksum]]);
837
+ return true;
838
+ },
839
+ { tx: true }
840
+ );
841
+ } catch (exc) {
842
+ throw wrap("Failed to delete image", exc);
843
+ }
844
+ }
845
+ async deleteManyDedup(ids, connection) {
846
+ try {
847
+ return await this.run(
848
+ "delete_many",
849
+ connection,
850
+ async (q) => {
851
+ const deleted = (await q.query(D_DELETE_REFS, [ids])).rows;
852
+ if (deleted.length === 0) return [];
853
+ const counts = /* @__PURE__ */ new Map();
854
+ for (const r of deleted)
855
+ counts.set(
856
+ r.checksum_sha256,
857
+ (counts.get(r.checksum_sha256) ?? 0) + 1
858
+ );
859
+ const emptied = [];
860
+ for (const checksum of [...counts.keys()].sort()) {
861
+ const dec = (await q.query(D_DECREMENT, [counts.get(checksum), checksum])).rows[0];
862
+ if (dec && dec.ref_count <= 0) emptied.push(checksum);
863
+ }
864
+ if (emptied.length > 0) await q.query(D_DELETE_EMPTY, [emptied]);
865
+ return deleted.map((r) => String(r.id));
866
+ },
867
+ { tx: true }
868
+ );
869
+ } catch (exc) {
870
+ throw wrap("Failed to delete image batch", exc);
871
+ }
872
+ }
873
+ /**
874
+ * One-time, NON-DESTRUCTIVE copy of every row in the classic `zerobucket_images` table into this
875
+ * dedup instance's tables, preserving every id (external references keep working) and
876
+ * deduplicating identical content on the way. The classic table is never modified.
877
+ *
878
+ * Differences from the Python version, all deliberate: rows are copied in small batches (bounded
879
+ * memory instead of loading the whole table); re-running is safe (already-migrated ids are
880
+ * skipped and reported, not an error); and classic rows already tiered to object storage are
881
+ * refused up front with a clear message (their bytes are not in the database to copy).
882
+ * Still all-or-nothing: one transaction.
883
+ */
884
+ async migrateClassicToDedup() {
885
+ if (!this.dedup) {
886
+ throw new StorageError(
887
+ "migrateClassicToDedup() must be called on an instance created with dedup: true."
888
+ );
889
+ }
890
+ await this.ready();
891
+ const client = await this.pool.connect();
892
+ let destroy = false;
893
+ try {
894
+ await client.query("BEGIN");
895
+ await client.query(
896
+ "SELECT pg_advisory_xact_lock(hashtext('zerobucket_migrate_dedup'))"
897
+ );
898
+ if (!(await client.query("SELECT to_regclass('zerobucket_images') AS t")).rows[0].t) {
899
+ throw new StorageError(
900
+ "No classic zerobucket_images table found in this database -- nothing to migrate."
901
+ );
902
+ }
903
+ const hasTierCol = (await client.query(
904
+ "SELECT 1 FROM information_schema.columns WHERE table_name = 'zerobucket_images' AND column_name = 'storage_backend'"
905
+ )).rowCount;
906
+ if (hasTierCol) {
907
+ const tiered = (await client.query(
908
+ "SELECT count(*)::int AS n FROM zerobucket_images WHERE storage_backend <> 'postgres'"
909
+ )).rows[0].n;
910
+ if (tiered > 0) {
911
+ throw new StorageError(
912
+ `${tiered} classic image(s) are tiered to object storage, so their bytes are not in the database to migrate. Dedup mode does not support tiering. Migrate only an un-tiered table, or bring those images back first.`
913
+ );
914
+ }
915
+ }
916
+ const seen = /* @__PURE__ */ new Set();
917
+ let migrated = 0;
918
+ let already = 0;
919
+ let cursor = null;
920
+ const BATCH = 20;
921
+ for (; ; ) {
922
+ const page = cursor ? await client.query(
923
+ `SELECT id, data, mime_type, original_filename, size_bytes, width, height, checksum_sha256, created_at::text AS created_at_txt
924
+ FROM zerobucket_images WHERE (created_at, id) > ($1::timestamptz, $2::uuid) ORDER BY created_at, id LIMIT ${BATCH}`,
925
+ [cursor.createdAt, cursor.id]
926
+ ) : await client.query(
927
+ `SELECT id, data, mime_type, original_filename, size_bytes, width, height, checksum_sha256, created_at::text AS created_at_txt
928
+ FROM zerobucket_images ORDER BY created_at, id LIMIT ${BATCH}`
929
+ );
930
+ if (page.rows.length === 0) break;
931
+ const last = page.rows[page.rows.length - 1];
932
+ if (cursor && cursor.createdAt === last.created_at_txt && cursor.id === last.id) {
933
+ throw new StorageError(
934
+ "Migration made no progress (keyset cursor did not advance); aborting instead of looping."
935
+ );
936
+ }
937
+ cursor = { createdAt: last.created_at_txt, id: last.id };
938
+ const have = new Set(
939
+ (await client.query(
940
+ "SELECT id FROM zerobucket_image_refs WHERE id = ANY($1::uuid[])",
941
+ [page.rows.map((r) => r.id)]
942
+ )).rows.map((r) => String(r.id))
943
+ );
944
+ const fresh = page.rows.filter((r) => !have.has(String(r.id)));
945
+ already += page.rows.length - fresh.length;
946
+ const groups = /* @__PURE__ */ new Map();
947
+ for (const r of fresh) {
948
+ const g = groups.get(r.checksum_sha256);
949
+ if (g) g.n += 1;
950
+ else groups.set(r.checksum_sha256, { row: r, n: 1 });
951
+ }
952
+ for (const checksum of [...groups.keys()].sort()) {
953
+ const { row, n } = groups.get(checksum);
954
+ await client.query(D_UPSERT_BLOB, [
955
+ checksum,
956
+ row.data,
957
+ row.mime_type,
958
+ row.size_bytes,
959
+ row.width,
960
+ row.height,
961
+ n
962
+ ]);
963
+ }
964
+ for (const r of fresh) {
965
+ await client.query(
966
+ "INSERT INTO zerobucket_image_refs (id, checksum_sha256, original_filename, created_at) VALUES ($1, $2, $3, $4::timestamptz)",
967
+ [r.id, r.checksum_sha256, r.original_filename, r.created_at_txt]
968
+ );
969
+ seen.add(r.checksum_sha256);
970
+ migrated += 1;
971
+ }
972
+ }
973
+ await client.query("COMMIT");
974
+ return {
975
+ imagesMigrated: migrated,
976
+ distinctBlobsCreated: seen.size,
977
+ duplicateReferencesFound: migrated - seen.size,
978
+ alreadyMigrated: already
979
+ };
980
+ } catch (exc) {
981
+ try {
982
+ await client.query("ROLLBACK");
983
+ } catch {
984
+ destroy = true;
985
+ }
986
+ throw exc instanceof StorageError ? exc : new StorageError(`Migration to dedup failed: ${msg(exc)}`, {
987
+ cause: exc
988
+ });
989
+ } finally {
990
+ client.release(destroy);
991
+ }
992
+ }
993
+ // ---- helpers ---------------------------------------------------------
994
+ hydrate(row, id) {
995
+ return hydrateRow(row, id, this.opts.objectStorage);
996
+ }
997
+ /**
998
+ * Remove tiered objects AFTER their rows are gone. Ordering is deliberate:
999
+ * once the row is deleted the image is correctly "not found" to everyone, so
1000
+ * a failed object delete only leaves a harmless orphan, whereas deleting the
1001
+ * object first and then failing the row delete would leave a row pointing at nothing.
1002
+ *
1003
+ * Never runs inside a caller-owned transaction (`connection`): we cannot know
1004
+ * whether it will commit, and destroying data before the commit outcome is known
1005
+ * could leave a rolled-back row pointing at a deleted object. In that case the
1006
+ * object stays until you remove it yourself after committing (objectStorage.delete(id)).
1007
+ * Failures are reported through onOperation and never fail the delete itself.
1008
+ */
1009
+ async cleanupObject(keys, connection) {
1010
+ const os = this.opts.objectStorage;
1011
+ if (!os || connection || keys.length === 0) return;
1012
+ await Promise.all(
1013
+ keys.map(async (key) => {
1014
+ const start = performance.now();
1015
+ try {
1016
+ await os.delete(key);
1017
+ this.emit("object_storage_delete", start, true, null, 0);
1018
+ } catch (exc) {
1019
+ this.emit("object_storage_delete", start, false, msg(exc), 0);
1020
+ }
1021
+ })
1022
+ );
1023
+ }
1024
+ /**
1025
+ * Move an image's bytes out of Postgres into object storage, replacing the
1026
+ * row's `data` with a pointer. Returns:
1027
+ * null - no such image
1028
+ * false - already tiered (a safe no-op, so backfills can be re-run)
1029
+ * true - tiered just now
1030
+ *
1031
+ * SAFETY: the upload happens INSIDE the same transaction as the row lock
1032
+ * (SELECT ... FOR UPDATE) and the UPDATE that flips the row. If the upload
1033
+ * fails, the transaction rolls back and the row is untouched: there is no
1034
+ * moment when the bytes exist nowhere, or when a row claims to be tiered
1035
+ * without a completed upload.
1036
+ *
1037
+ * TRADEOFF: the row lock is held for the whole upload. Concurrent writes
1038
+ * to THIS image (delete, tier) wait; every other row is unaffected, and plain
1039
+ * reads are never blocked (Postgres MVCC). Meant for explicit maintenance, not hot paths.
1040
+ *
1041
+ * Retry is safe: a transient error replays the whole closure, and the
1042
+ * deterministic key (the image id) makes the re-upload an idempotent overwrite.
1043
+ */
1044
+ async tierToObjectStorage(id, { connection } = {}) {
1045
+ if (this.dedup) {
1046
+ throw new StorageError(
1047
+ "tierToObjectStorage() is not supported in dedup mode (a blob may be shared by many images)."
1048
+ );
1049
+ }
1050
+ const os = this.opts.objectStorage;
1051
+ if (!os) {
1052
+ throw new StorageError(
1053
+ "tierToObjectStorage() requires objectStorage to be configured (new ZeroBucket({ objectStorage: new ObjectStorage({ bucket }) }))."
1054
+ );
1055
+ }
1056
+ if (!isValidId(id)) return null;
1057
+ const key = id.toLowerCase();
1058
+ try {
1059
+ return await this.run(
1060
+ "tier_to_object_storage",
1061
+ connection,
1062
+ async (q) => {
1063
+ const row = (await q.query(SELECT_FOR_TIERING, [id])).rows[0];
1064
+ if (!row) return null;
1065
+ if (row.storage_backend !== "postgres") return false;
1066
+ await os.upload(key, row.data, { mimeType: row.mime_type });
1067
+ await q.query(UPDATE_AFTER_TIERING, [os.bucket, key, id]);
1068
+ return true;
1069
+ },
1070
+ { tx: true }
1071
+ );
1072
+ } catch (exc) {
1073
+ throw wrap("Failed to tier image to object storage", exc);
1074
+ }
1075
+ }
1076
+ };
1077
+ function blobParams(r, refs) {
1078
+ return [
1079
+ r.checksumSha256,
1080
+ r.data,
1081
+ r.mimeType,
1082
+ r.sizeBytes,
1083
+ r.width,
1084
+ r.height,
1085
+ refs
1086
+ ];
1087
+ }
1088
+ function rowParams(r) {
1089
+ return [
1090
+ r.data,
1091
+ r.mimeType,
1092
+ r.originalFilename,
1093
+ r.sizeBytes,
1094
+ r.width,
1095
+ r.height,
1096
+ r.checksumSha256
1097
+ ];
1098
+ }
1099
+ function isQueryable(c) {
1100
+ return typeof c.query === "function";
1101
+ }
1102
+
1103
+ // src/adapters/sqlite.ts
1104
+ import { randomUUID } from "crypto";
1105
+ import { existsSync, statSync } from "fs";
1106
+ var SCHEMA2 = `
1107
+ CREATE TABLE IF NOT EXISTS zerobucket_images (
1108
+ id TEXT PRIMARY KEY,
1109
+ data BLOB,
1110
+ mime_type TEXT NOT NULL,
1111
+ original_filename TEXT,
1112
+ size_bytes INTEGER NOT NULL,
1113
+ width INTEGER,
1114
+ height INTEGER,
1115
+ checksum_sha256 TEXT NOT NULL,
1116
+ created_at TEXT NOT NULL,
1117
+ updated_at TEXT NOT NULL,
1118
+ storage_backend TEXT NOT NULL DEFAULT 'sqlite',
1119
+ object_storage_bucket TEXT,
1120
+ object_storage_key TEXT,
1121
+ CHECK (
1122
+ (storage_backend = 'sqlite'
1123
+ AND data IS NOT NULL
1124
+ AND object_storage_key IS NULL
1125
+ AND object_storage_bucket IS NULL)
1126
+ OR
1127
+ (storage_backend = 'object_storage'
1128
+ AND data IS NULL
1129
+ AND object_storage_key IS NOT NULL
1130
+ AND object_storage_bucket IS NOT NULL)
1131
+ )
1132
+ );
1133
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_checksum ON zerobucket_images (checksum_sha256);
1134
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_created_at ON zerobucket_images (created_at);
1135
+ `;
1136
+ var DEDUP_SCHEMA2 = `
1137
+ CREATE TABLE IF NOT EXISTS zerobucket_blobs (
1138
+ checksum_sha256 TEXT PRIMARY KEY,
1139
+ data BLOB NOT NULL,
1140
+ mime_type TEXT NOT NULL,
1141
+ size_bytes INTEGER NOT NULL,
1142
+ width INTEGER,
1143
+ height INTEGER,
1144
+ ref_count INTEGER NOT NULL DEFAULT 0,
1145
+ created_at TEXT NOT NULL
1146
+ );
1147
+ CREATE TABLE IF NOT EXISTS zerobucket_image_refs (
1148
+ id TEXT PRIMARY KEY,
1149
+ checksum_sha256 TEXT NOT NULL REFERENCES zerobucket_blobs(checksum_sha256),
1150
+ original_filename TEXT,
1151
+ created_at TEXT NOT NULL,
1152
+ updated_at TEXT NOT NULL
1153
+ );
1154
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_image_refs_checksum ON zerobucket_image_refs (checksum_sha256);
1155
+ CREATE INDEX IF NOT EXISTS idx_zerobucket_image_refs_created_at ON zerobucket_image_refs (created_at);
1156
+ `;
1157
+ var COLS = `id, data, mime_type, original_filename, size_bytes, width, height, checksum_sha256, storage_backend, object_storage_bucket, object_storage_key`;
1158
+ var INSERT2 = `INSERT INTO zerobucket_images (id, data, mime_type, original_filename, size_bytes, width, height, checksum_sha256, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
1159
+ var SELECT_FULL2 = `SELECT ${COLS} FROM zerobucket_images WHERE id = ?`;
1160
+ var selectMany = (n) => `SELECT ${COLS} FROM zerobucket_images WHERE id IN (${placeholders(n)})`;
1161
+ var SELECT_METADATA2 = `SELECT id, mime_type, original_filename, size_bytes, width, height, checksum_sha256 FROM zerobucket_images WHERE id = ?`;
1162
+ var STREAM_INFO = `SELECT size_bytes, storage_backend, object_storage_key FROM zerobucket_images WHERE id = ?`;
1163
+ var CHUNK = `SELECT substr(data, ?, ?) AS chunk FROM zerobucket_images WHERE id = ?`;
1164
+ var EXISTS2 = `SELECT 1 FROM zerobucket_images WHERE id = ?`;
1165
+ var DELETE_ONE = `DELETE FROM zerobucket_images WHERE id = ? RETURNING storage_backend, object_storage_key`;
1166
+ var deleteMany = (n) => `DELETE FROM zerobucket_images WHERE id IN (${placeholders(n)}) RETURNING id, storage_backend, object_storage_key`;
1167
+ var SELECT_FOR_TIERING2 = `SELECT data, mime_type, size_bytes, storage_backend FROM zerobucket_images WHERE id = ?`;
1168
+ var UPDATE_AFTER_TIERING2 = `UPDATE zerobucket_images SET data = NULL, storage_backend = 'object_storage', object_storage_bucket = ?, object_storage_key = ?, updated_at = ? WHERE id = ?`;
1169
+ var D_FROM2 = `FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256`;
1170
+ var D_COLS2 = `r.id AS id, b.data AS data, b.mime_type AS mime_type, r.original_filename AS original_filename, b.size_bytes AS size_bytes, b.width AS width, b.height AS height, r.checksum_sha256 AS checksum_sha256, 'sqlite' AS storage_backend, NULL AS object_storage_bucket, NULL AS object_storage_key`;
1171
+ var D_UPSERT = `INSERT INTO zerobucket_blobs (checksum_sha256, data, mime_type, size_bytes, width, height, ref_count, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (checksum_sha256) DO UPDATE SET ref_count = ref_count + excluded.ref_count`;
1172
+ var D_INSERT_REF2 = `INSERT INTO zerobucket_image_refs (id, checksum_sha256, original_filename, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`;
1173
+ var D_SELECT_FULL = `SELECT ${D_COLS2} ${D_FROM2} WHERE r.id = ?`;
1174
+ var dSelectMany = (n) => `SELECT ${D_COLS2} ${D_FROM2} WHERE r.id IN (${placeholders(n)})`;
1175
+ var D_SELECT_METADATA = `SELECT r.id AS id, b.mime_type AS mime_type, r.original_filename AS original_filename, b.size_bytes AS size_bytes, b.width AS width, b.height AS height, r.checksum_sha256 AS checksum_sha256 ${D_FROM2} WHERE r.id = ?`;
1176
+ var D_STREAM_INFO = `SELECT b.size_bytes AS size_bytes, 'sqlite' AS storage_backend, NULL AS object_storage_key ${D_FROM2} WHERE r.id = ?`;
1177
+ var D_CHUNK = `SELECT substr(b.data, ?, ?) AS chunk ${D_FROM2} WHERE r.id = ?`;
1178
+ var D_EXISTS = `SELECT 1 FROM zerobucket_image_refs WHERE id = ?`;
1179
+ var D_DELETE_REF2 = `DELETE FROM zerobucket_image_refs WHERE id = ? RETURNING checksum_sha256`;
1180
+ var dDeleteRefs = (n) => `DELETE FROM zerobucket_image_refs WHERE id IN (${placeholders(n)}) RETURNING id, checksum_sha256`;
1181
+ var D_DECREMENT2 = `UPDATE zerobucket_blobs SET ref_count = ref_count - ? WHERE checksum_sha256 = ? RETURNING ref_count`;
1182
+ var D_DELETE_EMPTY2 = `DELETE FROM zerobucket_blobs WHERE checksum_sha256 = ? AND ref_count <= 0`;
1183
+ var IN_CHUNK = 500;
1184
+ var ATTEMPT_BUSY_MS = 25;
1185
+ var DEFAULT_BUSY_TIMEOUT_MS = 1e4;
1186
+ function placeholders(n) {
1187
+ return Array.from({ length: n }, () => "?").join(", ");
1188
+ }
1189
+ function isoNow() {
1190
+ return (/* @__PURE__ */ new Date()).toISOString().replace("Z", "000+00:00");
1191
+ }
1192
+ function isBusy(exc) {
1193
+ const code = exc?.code;
1194
+ return typeof code === "string" && (code.startsWith("SQLITE_BUSY") || code.startsWith("SQLITE_LOCKED"));
1195
+ }
1196
+ var Mutex = class {
1197
+ tail = Promise.resolve();
1198
+ run(fn) {
1199
+ const prev = this.tail;
1200
+ let release;
1201
+ this.tail = new Promise((r) => release = r);
1202
+ return prev.then(fn).finally(release);
1203
+ }
1204
+ };
1205
+ var SQLiteBackend = class {
1206
+ constructor(opts) {
1207
+ this.opts = opts;
1208
+ if (!opts.path)
1209
+ throw new TypeError(
1210
+ 'SQLiteBackend requires a `path` (a file path or ":memory:")'
1211
+ );
1212
+ this.dedup = opts.dedup ?? false;
1213
+ this.busyTimeoutMs = opts.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS;
1214
+ if (this.dedup && opts.objectStorage) {
1215
+ throw new TypeError(
1216
+ "objectStorage is not supported together with dedup: true (same restriction as the Python package). Tiering moves one image's bytes, but a deduplicated blob can be shared by many images."
1217
+ );
1218
+ }
1219
+ }
1220
+ opts;
1221
+ db;
1222
+ Database;
1223
+ readyPromise;
1224
+ closed = false;
1225
+ dedup;
1226
+ busyTimeoutMs;
1227
+ writeLock = new Mutex();
1228
+ // ---- lifecycle -------------------------------------------------------
1229
+ ready() {
1230
+ if (this.closed)
1231
+ return Promise.reject(
1232
+ new StorageError("This ZeroBucket instance has been closed")
1233
+ );
1234
+ this.readyPromise ??= this.init().catch((exc) => {
1235
+ this.readyPromise = void 0;
1236
+ throw exc;
1237
+ });
1238
+ return this.readyPromise;
1239
+ }
1240
+ async init() {
1241
+ try {
1242
+ const mod = await import("better-sqlite3");
1243
+ this.Database = mod.default ?? mod;
1244
+ } catch (cause) {
1245
+ throw new StorageError(
1246
+ "SQLiteBackend requires the 'better-sqlite3' package. Install it with: npm install better-sqlite3",
1247
+ { cause }
1248
+ );
1249
+ }
1250
+ const db = new this.Database(this.opts.path, { timeout: ATTEMPT_BUSY_MS });
1251
+ try {
1252
+ await this.retrying(() => {
1253
+ if (this.opts.path !== ":memory:" && db.pragma("journal_mode", { simple: true }) !== "wal") {
1254
+ db.pragma("journal_mode = WAL");
1255
+ }
1256
+ db.pragma("foreign_keys = ON");
1257
+ if (this.opts.autoMigrate ?? true)
1258
+ db.exec(this.dedup ? DEDUP_SCHEMA2 : SCHEMA2);
1259
+ });
1260
+ } catch (exc) {
1261
+ try {
1262
+ db.close();
1263
+ } catch {
1264
+ }
1265
+ throw new StorageError(
1266
+ `Could not open SQLite database ${JSON.stringify(this.opts.path)}: ${msg(exc)}`,
1267
+ { cause: exc }
1268
+ );
1269
+ }
1270
+ this.db = db;
1271
+ }
1272
+ async close() {
1273
+ this.closed = true;
1274
+ const db = this.db;
1275
+ this.db = void 0;
1276
+ this.readyPromise = void 0;
1277
+ await this.writeLock.run(async () => {
1278
+ db?.close();
1279
+ });
1280
+ }
1281
+ // ---- execution core --------------------------------------------------
1282
+ emit(operation, start, success, error, retryCount) {
1283
+ const cb = this.opts.onOperation;
1284
+ if (!cb) return;
1285
+ try {
1286
+ cb({
1287
+ operation,
1288
+ durationMs: performance.now() - start,
1289
+ success,
1290
+ error,
1291
+ retryCount
1292
+ });
1293
+ } catch {
1294
+ }
1295
+ }
1296
+ /** Re-run `fn` while another connection holds a lock, sleeping asynchronously between attempts. `fn` must be atomic. */
1297
+ async retrying(fn, onRetry) {
1298
+ const deadline = performance.now() + this.busyTimeoutMs;
1299
+ let attempt = 0;
1300
+ for (; ; ) {
1301
+ try {
1302
+ return fn();
1303
+ } catch (exc) {
1304
+ if (!isBusy(exc) || performance.now() >= deadline) throw exc;
1305
+ attempt += 1;
1306
+ onRetry?.(attempt);
1307
+ await sleep(
1308
+ Math.min(5 * 2 ** Math.min(attempt, 5), 100) + Math.random() * 5
1309
+ );
1310
+ }
1311
+ }
1312
+ }
1313
+ /** BEGIN IMMEDIATE takes the write lock up front, so a BUSY comes before any work and the whole unit is safely re-runnable. */
1314
+ tx(db, work) {
1315
+ db.exec("BEGIN IMMEDIATE");
1316
+ try {
1317
+ const result = work(db);
1318
+ db.exec("COMMIT");
1319
+ return result;
1320
+ } catch (exc) {
1321
+ try {
1322
+ db.exec("ROLLBACK");
1323
+ } catch {
1324
+ }
1325
+ throw exc;
1326
+ }
1327
+ }
1328
+ /**
1329
+ * All-or-nothing work on a CALLER-supplied handle. SAVEPOINT works whether or not the caller has an open
1330
+ * transaction: inside one it nests (a failure rolls back only our work); outside one it begins and, on
1331
+ * RELEASE, commits.
1332
+ */
1333
+ atomic(db, work) {
1334
+ db.exec("SAVEPOINT zerobucket_atomic");
1335
+ try {
1336
+ const result = work(db);
1337
+ db.exec("RELEASE SAVEPOINT zerobucket_atomic");
1338
+ return result;
1339
+ } catch (exc) {
1340
+ try {
1341
+ db.exec("ROLLBACK TO SAVEPOINT zerobucket_atomic");
1342
+ db.exec("RELEASE SAVEPOINT zerobucket_atomic");
1343
+ } catch {
1344
+ }
1345
+ throw exc;
1346
+ }
1347
+ }
1348
+ async execute(operation, connection, mode, work) {
1349
+ const start = performance.now();
1350
+ let retries = 0;
1351
+ try {
1352
+ let result;
1353
+ if (connection) {
1354
+ if (typeof connection.prepare !== "function") {
1355
+ throw new TypeError(
1356
+ "SQLiteBackend expects a better-sqlite3 Database as `connection` (an object with prepare()), not a pg client."
1357
+ );
1358
+ }
1359
+ const db = connection;
1360
+ result = mode === "write" ? this.atomic(db, work) : work(db);
1361
+ } else {
1362
+ await this.ready();
1363
+ const db = this.db;
1364
+ const onRetry = (n) => retries = n;
1365
+ result = mode === "write" ? await this.writeLock.run(
1366
+ () => this.retrying(() => this.tx(db, work), onRetry)
1367
+ ) : await this.retrying(() => work(db), onRetry);
1368
+ }
1369
+ this.emit(operation, start, true, null, retries);
1370
+ return result;
1371
+ } catch (exc) {
1372
+ this.emit(operation, start, false, msg(exc), retries);
1373
+ throw exc;
1374
+ }
1375
+ }
1376
+ // ---- StorageBackend --------------------------------------------------
1377
+ async put(row, { connection } = {}) {
1378
+ try {
1379
+ return await this.execute(
1380
+ "put",
1381
+ connection,
1382
+ "write",
1383
+ (db) => this.insertOne(db, row)
1384
+ );
1385
+ } catch (exc) {
1386
+ throw wrap("Failed to store image", exc);
1387
+ }
1388
+ }
1389
+ insertOne(db, r) {
1390
+ const id = randomUUID();
1391
+ const now = isoNow();
1392
+ if (this.dedup) {
1393
+ db.prepare(D_UPSERT).run(
1394
+ r.checksumSha256,
1395
+ r.data,
1396
+ r.mimeType,
1397
+ r.sizeBytes,
1398
+ r.width,
1399
+ r.height,
1400
+ 1,
1401
+ now
1402
+ );
1403
+ db.prepare(D_INSERT_REF2).run(
1404
+ id,
1405
+ r.checksumSha256,
1406
+ r.originalFilename,
1407
+ now,
1408
+ now
1409
+ );
1410
+ } else {
1411
+ db.prepare(INSERT2).run(
1412
+ id,
1413
+ r.data,
1414
+ r.mimeType,
1415
+ r.originalFilename,
1416
+ r.sizeBytes,
1417
+ r.width,
1418
+ r.height,
1419
+ r.checksumSha256,
1420
+ now,
1421
+ now
1422
+ );
1423
+ }
1424
+ return id;
1425
+ }
1426
+ async putMany(rows, { connection } = {}) {
1427
+ if (rows.length === 0) return [];
1428
+ try {
1429
+ return await this.execute("put_many", connection, "write", (db) => {
1430
+ if (!this.dedup) return rows.map((r) => this.insertOne(db, r));
1431
+ const now = isoNow();
1432
+ const groups = /* @__PURE__ */ new Map();
1433
+ for (const r of rows) {
1434
+ const g = groups.get(r.checksumSha256);
1435
+ if (g) g.n += 1;
1436
+ else groups.set(r.checksumSha256, { row: r, n: 1 });
1437
+ }
1438
+ for (const [checksum, { row, n }] of groups) {
1439
+ db.prepare(D_UPSERT).run(
1440
+ checksum,
1441
+ row.data,
1442
+ row.mimeType,
1443
+ row.sizeBytes,
1444
+ row.width,
1445
+ row.height,
1446
+ n,
1447
+ now
1448
+ );
1449
+ }
1450
+ return rows.map((r) => {
1451
+ const id = randomUUID();
1452
+ db.prepare(D_INSERT_REF2).run(
1453
+ id,
1454
+ r.checksumSha256,
1455
+ r.originalFilename,
1456
+ now,
1457
+ now
1458
+ );
1459
+ return id;
1460
+ });
1461
+ });
1462
+ } catch (exc) {
1463
+ throw wrap("Failed to store image batch", exc);
1464
+ }
1465
+ }
1466
+ async get(id, { connection } = {}) {
1467
+ if (!isValidId(id)) return null;
1468
+ const norm = id.toLowerCase();
1469
+ let row;
1470
+ try {
1471
+ row = await this.execute(
1472
+ "get",
1473
+ connection,
1474
+ "read",
1475
+ (db) => db.prepare(this.dedup ? D_SELECT_FULL : SELECT_FULL2).get(norm)
1476
+ );
1477
+ } catch (exc) {
1478
+ throw wrap("Failed to retrieve image", exc);
1479
+ }
1480
+ return row ? hydrateRow(row, norm, this.opts.objectStorage) : null;
1481
+ }
1482
+ async getMany(ids, { connection } = {}) {
1483
+ const valid = [
1484
+ ...new Set(ids.filter(isValidId).map((i) => i.toLowerCase()))
1485
+ ];
1486
+ if (valid.length === 0) return [];
1487
+ let rows;
1488
+ try {
1489
+ rows = await this.execute("get_many", connection, "read", (db) => {
1490
+ const out = [];
1491
+ for (let i = 0; i < valid.length; i += IN_CHUNK) {
1492
+ const part = valid.slice(i, i + IN_CHUNK);
1493
+ out.push(
1494
+ ...db.prepare(
1495
+ this.dedup ? dSelectMany(part.length) : selectMany(part.length)
1496
+ ).all(...part)
1497
+ );
1498
+ }
1499
+ return out;
1500
+ });
1501
+ } catch (exc) {
1502
+ throw wrap("Failed to retrieve image batch", exc);
1503
+ }
1504
+ return mapLimit(
1505
+ rows,
1506
+ 4,
1507
+ (r) => hydrateRow(r, String(r.id), this.opts.objectStorage)
1508
+ );
1509
+ }
1510
+ async getMetadata(id, { connection } = {}) {
1511
+ if (!isValidId(id)) return null;
1512
+ let row;
1513
+ try {
1514
+ row = await this.execute(
1515
+ "get_metadata",
1516
+ connection,
1517
+ "read",
1518
+ (db) => db.prepare(this.dedup ? D_SELECT_METADATA : SELECT_METADATA2).get(id.toLowerCase())
1519
+ );
1520
+ } catch (exc) {
1521
+ throw wrap("Failed to retrieve image metadata", exc);
1522
+ }
1523
+ if (!row) return null;
1524
+ return {
1525
+ id: String(row.id),
1526
+ mimeType: row.mime_type,
1527
+ originalFilename: row.original_filename,
1528
+ sizeBytes: row.size_bytes,
1529
+ width: row.width,
1530
+ height: row.height,
1531
+ checksumSha256: row.checksum_sha256
1532
+ };
1533
+ }
1534
+ async getStream(id, opts) {
1535
+ if (!isValidId(id)) return null;
1536
+ const norm = id.toLowerCase();
1537
+ const { connection, chunkSize } = opts;
1538
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0)
1539
+ throw new RangeError("chunkSize must be a positive integer");
1540
+ let info;
1541
+ try {
1542
+ info = await this.execute(
1543
+ "get_metadata",
1544
+ connection,
1545
+ "read",
1546
+ (db) => db.prepare(this.dedup ? D_STREAM_INFO : STREAM_INFO).get(norm)
1547
+ );
1548
+ } catch (exc) {
1549
+ throw wrap("Failed to retrieve image metadata", exc);
1550
+ }
1551
+ if (!info) return null;
1552
+ const totalSize = info.size_bytes;
1553
+ const start = opts.range?.start ?? 0;
1554
+ const end = Math.min(opts.range?.end ?? totalSize - 1, totalSize - 1);
1555
+ if (info.storage_backend === "object_storage") {
1556
+ const os = this.opts.objectStorage;
1557
+ if (!os) throw tieredWithoutStorage(norm, info.object_storage_key);
1558
+ return streamFromObjectStorage(
1559
+ os,
1560
+ norm,
1561
+ info.object_storage_key,
1562
+ start,
1563
+ end,
1564
+ chunkSize
1565
+ );
1566
+ }
1567
+ const self = this;
1568
+ async function* generate() {
1569
+ let offset = start;
1570
+ let delivered = 0;
1571
+ const wanted = Math.max(0, end - start + 1);
1572
+ while (delivered < wanted) {
1573
+ const length = Math.min(chunkSize, wanted - delivered);
1574
+ let row;
1575
+ try {
1576
+ row = await self.execute(
1577
+ "get_stream",
1578
+ connection,
1579
+ "read",
1580
+ (db) => db.prepare(self.dedup ? D_CHUNK : CHUNK).get(offset + 1, length, norm)
1581
+ );
1582
+ } catch (exc) {
1583
+ throw wrap("Failed to stream image", exc);
1584
+ }
1585
+ if (!row) {
1586
+ throw new StorageError(
1587
+ `Image ${JSON.stringify(norm)} was deleted while streaming (delivered ${delivered} of ${wanted} bytes). Pass connection with your own open transaction if you need a consistent read across concurrent writers.`
1588
+ );
1589
+ }
1590
+ const chunk = row.chunk;
1591
+ if (!chunk || chunk.length === 0) {
1592
+ throw new StorageError(
1593
+ `Image ${JSON.stringify(norm)} ended early while streaming (delivered ${delivered} of ${wanted} bytes).`
1594
+ );
1595
+ }
1596
+ yield chunk;
1597
+ offset += chunk.length;
1598
+ delivered += chunk.length;
1599
+ }
1600
+ }
1601
+ return generate();
1602
+ }
1603
+ async delete(id, { connection } = {}) {
1604
+ if (!isValidId(id)) return false;
1605
+ const norm = id.toLowerCase();
1606
+ try {
1607
+ if (this.dedup) {
1608
+ return await this.execute("delete", connection, "write", (db) => {
1609
+ const ref = db.prepare(D_DELETE_REF2).get(norm);
1610
+ if (!ref) return false;
1611
+ const dec = db.prepare(D_DECREMENT2).get(1, ref.checksum_sha256);
1612
+ if (dec && dec.ref_count <= 0)
1613
+ db.prepare(D_DELETE_EMPTY2).run(ref.checksum_sha256);
1614
+ return true;
1615
+ });
1616
+ }
1617
+ const row = await this.execute(
1618
+ "delete",
1619
+ connection,
1620
+ "write",
1621
+ (db) => db.prepare(DELETE_ONE).get(norm)
1622
+ );
1623
+ if (row?.storage_backend === "object_storage")
1624
+ await this.cleanupObjects([row.object_storage_key], connection);
1625
+ return row !== void 0;
1626
+ } catch (exc) {
1627
+ throw wrap("Failed to delete image", exc);
1628
+ }
1629
+ }
1630
+ async deleteMany(ids, { connection } = {}) {
1631
+ const valid = [
1632
+ ...new Set(ids.filter(isValidId).map((i) => i.toLowerCase()))
1633
+ ];
1634
+ if (valid.length === 0) return [];
1635
+ try {
1636
+ if (this.dedup) {
1637
+ return await this.execute("delete_many", connection, "write", (db) => {
1638
+ const deleted = [];
1639
+ for (let i = 0; i < valid.length; i += IN_CHUNK) {
1640
+ const part = valid.slice(i, i + IN_CHUNK);
1641
+ deleted.push(...db.prepare(dDeleteRefs(part.length)).all(...part));
1642
+ }
1643
+ const counts = /* @__PURE__ */ new Map();
1644
+ for (const r of deleted)
1645
+ counts.set(
1646
+ r.checksum_sha256,
1647
+ (counts.get(r.checksum_sha256) ?? 0) + 1
1648
+ );
1649
+ for (const [checksum, n] of counts) {
1650
+ const dec = db.prepare(D_DECREMENT2).get(n, checksum);
1651
+ if (dec && dec.ref_count <= 0)
1652
+ db.prepare(D_DELETE_EMPTY2).run(checksum);
1653
+ }
1654
+ return deleted.map((r) => String(r.id));
1655
+ });
1656
+ }
1657
+ const rows = await this.execute(
1658
+ "delete_many",
1659
+ connection,
1660
+ "write",
1661
+ (db) => {
1662
+ const out = [];
1663
+ for (let i = 0; i < valid.length; i += IN_CHUNK) {
1664
+ const part = valid.slice(i, i + IN_CHUNK);
1665
+ out.push(...db.prepare(deleteMany(part.length)).all(...part));
1666
+ }
1667
+ return out;
1668
+ }
1669
+ );
1670
+ await this.cleanupObjects(
1671
+ rows.filter((r) => r.storage_backend === "object_storage").map((r) => r.object_storage_key),
1672
+ connection
1673
+ );
1674
+ return rows.map((r) => String(r.id));
1675
+ } catch (exc) {
1676
+ throw wrap("Failed to delete image batch", exc);
1677
+ }
1678
+ }
1679
+ async exists(id, { connection } = {}) {
1680
+ if (!isValidId(id)) return false;
1681
+ try {
1682
+ return await this.execute(
1683
+ "exists",
1684
+ connection,
1685
+ "read",
1686
+ (db) => db.prepare(this.dedup ? D_EXISTS : EXISTS2).get(id.toLowerCase()) !== void 0
1687
+ );
1688
+ } catch (exc) {
1689
+ throw wrap("Failed to check image existence", exc);
1690
+ }
1691
+ }
1692
+ // ---- maintenance (CLI) -----------------------------------------------
1693
+ async getInfo() {
1694
+ try {
1695
+ return await this.execute("info", void 0, "read", (db) => {
1696
+ const has = (t) => db.prepare(
1697
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?"
1698
+ ).get(t) !== void 0;
1699
+ if (!has(this.dedup ? "zerobucket_image_refs" : "zerobucket_images") || this.dedup && !has("zerobucket_blobs"))
1700
+ return null;
1701
+ const j = this.dedup ? D_FROM2 : "FROM zerobucket_images";
1702
+ const size = this.dedup ? "b.size_bytes" : "size_bytes";
1703
+ const created = this.dedup ? "r.created_at" : "created_at";
1704
+ const mime = this.dedup ? "b.mime_type" : "mime_type";
1705
+ const tot = db.prepare(
1706
+ `SELECT count(*) AS n, coalesce(sum(${size}), 0) AS bytes, min(${created}) AS oldest, max(${created}) AS newest ${j}`
1707
+ ).get();
1708
+ const fmt = db.prepare(
1709
+ `SELECT ${mime} AS m, count(*) AS n, coalesce(sum(${size}), 0) AS bytes ${j} GROUP BY ${mime} ORDER BY count(*) DESC, ${mime}`
1710
+ ).all();
1711
+ let onDisk = null;
1712
+ if (this.opts.path !== ":memory:") {
1713
+ let total = statSync(this.opts.path).size;
1714
+ for (const suffix of ["-wal", "-shm"])
1715
+ if (existsSync(this.opts.path + suffix))
1716
+ total += statSync(this.opts.path + suffix).size;
1717
+ onDisk = prettySize(total);
1718
+ }
1719
+ const info = {
1720
+ mode: this.dedup ? "dedup" : "classic",
1721
+ count: tot.n,
1722
+ totalBytes: Number(tot.bytes),
1723
+ oldest: tot.oldest,
1724
+ newest: tot.newest,
1725
+ onDisk,
1726
+ byFormat: fmt.map((r) => ({
1727
+ mimeType: r.m,
1728
+ count: r.n,
1729
+ bytes: Number(r.bytes)
1730
+ }))
1731
+ };
1732
+ if (this.dedup) {
1733
+ const b = db.prepare(
1734
+ "SELECT count(*) AS n, coalesce(sum(size_bytes), 0) AS bytes FROM zerobucket_blobs"
1735
+ ).get();
1736
+ info.dedup = { blobs: b.n, storedBytes: Number(b.bytes) };
1737
+ } else {
1738
+ const t = db.prepare(
1739
+ "SELECT count(*) AS n, coalesce(sum(size_bytes), 0) AS bytes FROM zerobucket_images WHERE storage_backend = 'object_storage'"
1740
+ ).get();
1741
+ info.tiered = { count: t.n, bytes: Number(t.bytes) };
1742
+ }
1743
+ return info;
1744
+ });
1745
+ } catch (exc) {
1746
+ throw wrap("Failed to read storage info", exc);
1747
+ }
1748
+ }
1749
+ async listImages(o = {}) {
1750
+ const where = [];
1751
+ const params = [];
1752
+ if (o.minSize !== void 0)
1753
+ where.push(`${this.dedup ? "b.size_bytes" : "size_bytes"} >= ?`), params.push(o.minSize);
1754
+ if (o.olderThanDays !== void 0) {
1755
+ const cutoff = new Date(Date.now() - o.olderThanDays * 864e5).toISOString().replace("Z", "000+00:00");
1756
+ where.push(`${this.dedup ? "r.created_at" : "created_at"} <= ?`);
1757
+ params.push(cutoff);
1758
+ }
1759
+ if (o.onlyUntiered && !this.dedup) where.push("storage_backend = 'sqlite'");
1760
+ const from = this.dedup ? D_FROM2 : "FROM zerobucket_images";
1761
+ const idCol = this.dedup ? "r.id" : "id";
1762
+ const tierCol = this.dedup ? "0 AS tiered" : "(storage_backend = 'object_storage') AS tiered";
1763
+ const order = o.sample !== void 0 ? "ORDER BY random()" : `ORDER BY ${this.dedup ? "r.created_at" : "created_at"}, ${idCol}`;
1764
+ const lim = o.sample ?? o.limit;
1765
+ let sql = `SELECT ${idCol} AS id, ${tierCol} ${from}${where.length ? " WHERE " + where.join(" AND ") : ""} ${order}`;
1766
+ if (lim !== void 0) sql += " LIMIT ?", params.push(lim);
1767
+ try {
1768
+ const rows = await this.execute(
1769
+ "list_images",
1770
+ void 0,
1771
+ "read",
1772
+ (db) => db.prepare(sql).all(...params)
1773
+ );
1774
+ return rows.map((r) => ({
1775
+ id: String(r.id),
1776
+ tiered: Boolean(r.tiered)
1777
+ }));
1778
+ } catch (exc) {
1779
+ throw wrap("Failed to list images", exc);
1780
+ }
1781
+ }
1782
+ /**
1783
+ * Remove tiered objects AFTER their rows are gone (a failed object delete leaves a harmless orphan; the
1784
+ * reverse order could leave a row pointing at nothing). Skipped inside a caller-owned transaction, since the
1785
+ * commit outcome is unknown. Failures never fail the delete; they are reported through onOperation.
1786
+ */
1787
+ async cleanupObjects(keys, connection) {
1788
+ const os = this.opts.objectStorage;
1789
+ if (!os || connection || keys.length === 0) return;
1790
+ await Promise.all(
1791
+ keys.map(async (key) => {
1792
+ const start = performance.now();
1793
+ try {
1794
+ await os.delete(key);
1795
+ this.emit("object_storage_delete", start, true, null, 0);
1796
+ } catch (exc) {
1797
+ this.emit("object_storage_delete", start, false, msg(exc), 0);
1798
+ }
1799
+ })
1800
+ );
1801
+ }
1802
+ /**
1803
+ * Move an image's bytes into object storage. null = no such image, false = already tiered, true = tiered now.
1804
+ *
1805
+ * SAFETY (same guarantee as Postgres): the upload happens INSIDE a BEGIN IMMEDIATE transaction; if it fails the
1806
+ * transaction rolls back and the row is untouched.
1807
+ *
1808
+ * TRADEOFF (coarser than Postgres): SQLite has no row locks, so BEGIN IMMEDIATE locks the WHOLE DATABASE for the
1809
+ * upload. Other processes' writes wait; this process's writes queue behind an async lock; reads are not blocked.
1810
+ */
1811
+ async tierToObjectStorage(id, { connection } = {}) {
1812
+ if (this.dedup)
1813
+ throw new StorageError(
1814
+ "tierToObjectStorage() is not supported in dedup mode (a blob may be shared by many images)."
1815
+ );
1816
+ const os = this.opts.objectStorage;
1817
+ if (!os) {
1818
+ throw new StorageError(
1819
+ "tierToObjectStorage() requires objectStorage to be configured (new ZeroBucket({ sqlite, objectStorage: new ObjectStorage({ bucket }) }))."
1820
+ );
1821
+ }
1822
+ if (connection) {
1823
+ throw new StorageError(
1824
+ "tierToObjectStorage() does not accept `connection` on SQLite: it needs its own dedicated connection for the BEGIN IMMEDIATE transaction."
1825
+ );
1826
+ }
1827
+ if (this.opts.path === ":memory:") {
1828
+ throw new StorageError(
1829
+ "tierToObjectStorage() needs a database file: an in-memory SQLite database cannot be shared with its dedicated tiering connection."
1830
+ );
1831
+ }
1832
+ if (!isValidId(id)) return null;
1833
+ const norm = id.toLowerCase();
1834
+ const start = performance.now();
1835
+ let retries = 0;
1836
+ try {
1837
+ await this.ready();
1838
+ const result = await this.writeLock.run(async () => {
1839
+ const tdb = new this.Database(this.opts.path, {
1840
+ timeout: ATTEMPT_BUSY_MS
1841
+ });
1842
+ try {
1843
+ await this.retrying(
1844
+ () => tdb.exec("BEGIN IMMEDIATE"),
1845
+ (n) => retries = n
1846
+ );
1847
+ try {
1848
+ const row = tdb.prepare(SELECT_FOR_TIERING2).get(norm);
1849
+ if (!row) {
1850
+ tdb.exec("ROLLBACK");
1851
+ return null;
1852
+ }
1853
+ if (row.storage_backend !== "sqlite") {
1854
+ tdb.exec("ROLLBACK");
1855
+ return false;
1856
+ }
1857
+ await os.upload(norm, row.data, {
1858
+ mimeType: row.mime_type
1859
+ });
1860
+ tdb.prepare(UPDATE_AFTER_TIERING2).run(os.bucket, norm, isoNow(), norm);
1861
+ tdb.exec("COMMIT");
1862
+ return true;
1863
+ } catch (exc) {
1864
+ try {
1865
+ tdb.exec("ROLLBACK");
1866
+ } catch {
1867
+ }
1868
+ throw exc;
1869
+ }
1870
+ } finally {
1871
+ tdb.close();
1872
+ }
1873
+ });
1874
+ this.emit("tier_to_object_storage", start, true, null, retries);
1875
+ return result;
1876
+ } catch (exc) {
1877
+ this.emit("tier_to_object_storage", start, false, msg(exc), retries);
1878
+ throw wrap("Failed to tier image to object storage", exc);
1879
+ }
1880
+ }
1881
+ };
1882
+
1883
+ // src/object-storage.ts
1884
+ var ObjectStorage = class {
1885
+ constructor(opts) {
1886
+ this.opts = opts;
1887
+ if (!opts.bucket)
1888
+ throw new TypeError("ObjectStorage requires a bucket name");
1889
+ this.bucket = opts.bucket;
1890
+ }
1891
+ opts;
1892
+ bucket;
1893
+ clientPromise;
1894
+ connection() {
1895
+ this.clientPromise ??= (async () => {
1896
+ let sdk;
1897
+ try {
1898
+ sdk = await import("@aws-sdk/client-s3");
1899
+ } catch (cause) {
1900
+ throw new StorageError(
1901
+ "Object-storage tiering requires the optional dependency '@aws-sdk/client-s3'. Install it with: npm install @aws-sdk/client-s3",
1902
+ { cause }
1903
+ );
1904
+ }
1905
+ const o = this.opts;
1906
+ const client = o.client ?? new sdk.S3Client({
1907
+ endpoint: o.endpoint,
1908
+ region: o.region ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? "us-east-1",
1909
+ credentials: o.credentials,
1910
+ forcePathStyle: o.forcePathStyle ?? o.endpoint !== void 0
1911
+ });
1912
+ return { sdk, client };
1913
+ })().catch((exc) => {
1914
+ this.clientPromise = void 0;
1915
+ throw exc;
1916
+ });
1917
+ return this.clientPromise;
1918
+ }
1919
+ async upload(key, data, { mimeType }) {
1920
+ const { sdk, client } = await this.connection();
1921
+ try {
1922
+ await client.send(
1923
+ new sdk.PutObjectCommand({
1924
+ Bucket: this.bucket,
1925
+ Key: key,
1926
+ Body: data,
1927
+ ContentType: mimeType
1928
+ })
1929
+ );
1930
+ } catch (exc) {
1931
+ throw new StorageError(
1932
+ `Failed to upload ${JSON.stringify(key)} to bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
1933
+ { cause: exc }
1934
+ );
1935
+ }
1936
+ }
1937
+ async download(key) {
1938
+ return this.get(key, void 0);
1939
+ }
1940
+ async downloadRange(key, start, endInclusive) {
1941
+ return this.get(key, `bytes=${start}-${endInclusive}`);
1942
+ }
1943
+ async get(key, range) {
1944
+ const { sdk, client } = await this.connection();
1945
+ try {
1946
+ const res = await client.send(
1947
+ new sdk.GetObjectCommand({
1948
+ Bucket: this.bucket,
1949
+ Key: key,
1950
+ Range: range
1951
+ })
1952
+ );
1953
+ return Buffer.from(await res.Body.transformToByteArray());
1954
+ } catch (exc) {
1955
+ throw new StorageError(
1956
+ `Failed to download ${JSON.stringify(key)} from bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
1957
+ { cause: exc }
1958
+ );
1959
+ }
1960
+ }
1961
+ async delete(key) {
1962
+ const { sdk, client } = await this.connection();
1963
+ try {
1964
+ await client.send(
1965
+ new sdk.DeleteObjectCommand({ Bucket: this.bucket, Key: key })
1966
+ );
1967
+ } catch (exc) {
1968
+ throw new StorageError(
1969
+ `Failed to delete ${JSON.stringify(key)} from bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
1970
+ { cause: exc }
1971
+ );
1972
+ }
1973
+ }
1974
+ async exists(key) {
1975
+ const { sdk, client } = await this.connection();
1976
+ try {
1977
+ await client.send(
1978
+ new sdk.HeadObjectCommand({ Bucket: this.bucket, Key: key })
1979
+ );
1980
+ return true;
1981
+ } catch (exc) {
1982
+ const e = exc;
1983
+ if (e.name === "NotFound" || e.name === "NoSuchKey" || e.$metadata?.httpStatusCode === 404)
1984
+ return false;
1985
+ throw new StorageError(
1986
+ `Failed to check ${JSON.stringify(key)} in bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
1987
+ { cause: exc }
1988
+ );
1989
+ }
1990
+ }
1991
+ };
1992
+ function msg2(exc) {
1993
+ return exc instanceof Error ? exc.message : String(exc);
1994
+ }
1995
+
1996
+ // src/cli.ts
1997
+ var defaultIO = () => ({
1998
+ out: (l) => console.log(l),
1999
+ err: (l) => console.error(l),
2000
+ env: process.env
2001
+ });
2002
+ var CliExit = class extends Error {
2003
+ constructor(code, message) {
2004
+ super(message);
2005
+ this.code = code;
2006
+ }
2007
+ code;
2008
+ };
2009
+ var usageError = (m) => new CliExit(2, m);
2010
+ function cliVersion() {
2011
+ try {
2012
+ return JSON.parse(
2013
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
2014
+ ).version;
2015
+ } catch {
2016
+ return "unknown";
2017
+ }
2018
+ }
2019
+ var HELP = `zerobucket - database-native image storage.
2020
+
2021
+ Usage: zerobucket <command> [options]
2022
+
2023
+ Commands:
2024
+ init Create the schema (tables and indexes) if missing.
2025
+ migrate Apply schema migrations (currently: same as init).
2026
+ --to-dedup copy every classic image into the dedup tables (PostgreSQL only; non-destructive)
2027
+ info Show storage stats: count, size, breakdown by format.
2028
+ verify Re-checksum stored images to detect corruption.
2029
+ --sample N check a random sample of N images instead of every image
2030
+ --bucket ... also verify images tiered to object storage (same options as 'tier')
2031
+ tier Move image(s) from the database into S3-compatible object storage.
2032
+ IMAGE_ID tier a single image, OR bulk:
2033
+ --all | --min-size BYTES | --older-than DAYS (combinable), --limit N, --dry-run
2034
+ --bucket NAME (required) bucket must already exist
2035
+ --endpoint-url URL for non-AWS stores (R2, MinIO, B2, Spaces)
2036
+ --region NAME --aws-access-key-id ID --aws-secret-access-key KEY
2037
+
2038
+ Database (choose one; flags beat environment variables):
2039
+ --database-url URL PostgreSQL connection string (env: ZEROBUCKET_DATABASE_URL)
2040
+ --sqlite PATH SQLite database file (env: ZEROBUCKET_SQLITE_PATH)
2041
+ --dedup operate on the dedup-mode tables instead of the classic table
2042
+
2043
+ Other:
2044
+ --version, -v print the version
2045
+ --help, -h show this help
2046
+
2047
+ Exit codes: 0 success, 1 problems found or an operation failed, 2 usage or connection error.`;
2048
+ var OPTIONS = {
2049
+ "database-url": { type: "string" },
2050
+ sqlite: { type: "string" },
2051
+ dedup: { type: "boolean" },
2052
+ help: { type: "boolean", short: "h" },
2053
+ version: { type: "boolean", short: "v" },
2054
+ "to-dedup": { type: "boolean" },
2055
+ sample: { type: "string" },
2056
+ bucket: { type: "string" },
2057
+ "endpoint-url": { type: "string" },
2058
+ region: { type: "string" },
2059
+ "aws-access-key-id": { type: "string" },
2060
+ "aws-secret-access-key": { type: "string" },
2061
+ "min-size": { type: "string" },
2062
+ "older-than": { type: "string" },
2063
+ all: { type: "boolean" },
2064
+ limit: { type: "string" },
2065
+ "dry-run": { type: "boolean" }
2066
+ };
2067
+ var COMMAND_OPTIONS = {
2068
+ init: [],
2069
+ migrate: ["to-dedup"],
2070
+ info: [],
2071
+ verify: [
2072
+ "sample",
2073
+ "bucket",
2074
+ "endpoint-url",
2075
+ "region",
2076
+ "aws-access-key-id",
2077
+ "aws-secret-access-key"
2078
+ ],
2079
+ tier: [
2080
+ "bucket",
2081
+ "endpoint-url",
2082
+ "region",
2083
+ "aws-access-key-id",
2084
+ "aws-secret-access-key",
2085
+ "min-size",
2086
+ "older-than",
2087
+ "all",
2088
+ "limit",
2089
+ "dry-run"
2090
+ ]
2091
+ };
2092
+ var COMMON = /* @__PURE__ */ new Set(["database-url", "sqlite", "dedup", "help", "version"]);
2093
+ function resolveTarget(v, env) {
2094
+ if (v.sqlite && v["database-url"])
2095
+ throw usageError(
2096
+ "Error: choose one database: --sqlite OR --database-url, not both."
2097
+ );
2098
+ if (v.sqlite) return { kind: "sqlite", path: v.sqlite };
2099
+ if (v["database-url"]) return { kind: "postgres", url: v["database-url"] };
2100
+ const url = env.ZEROBUCKET_DATABASE_URL;
2101
+ const path = env.ZEROBUCKET_SQLITE_PATH;
2102
+ if (url && path) {
2103
+ throw usageError(
2104
+ "Error: both ZEROBUCKET_DATABASE_URL and ZEROBUCKET_SQLITE_PATH are set. Pass --database-url or --sqlite to choose."
2105
+ );
2106
+ }
2107
+ if (url) return { kind: "postgres", url };
2108
+ if (path) return { kind: "sqlite", path };
2109
+ throw usageError(
2110
+ "Error: no database provided. Pass --database-url (PostgreSQL) or --sqlite PATH, or set the ZEROBUCKET_DATABASE_URL / ZEROBUCKET_SQLITE_PATH environment variable."
2111
+ );
2112
+ }
2113
+ function openBackend(t, o) {
2114
+ return t.kind === "sqlite" ? new SQLiteBackend({
2115
+ path: t.path,
2116
+ dedup: o.dedup,
2117
+ autoMigrate: o.autoMigrate,
2118
+ objectStorage: o.objectStorage
2119
+ }) : new PostgresBackend({
2120
+ connectionString: t.url,
2121
+ dedup: o.dedup,
2122
+ autoMigrate: o.autoMigrate,
2123
+ objectStorage: o.objectStorage,
2124
+ maxRetries: 0
2125
+ });
2126
+ }
2127
+ async function connect(backend, what) {
2128
+ try {
2129
+ await backend.ready();
2130
+ } catch (exc) {
2131
+ await backend.close().catch(() => {
2132
+ });
2133
+ throw usageError(`Error: could not ${what}: ${msg(exc)}`);
2134
+ }
2135
+ }
2136
+ function positiveInt(name, raw, min) {
2137
+ if (raw === void 0) return void 0;
2138
+ if (!/^\d+$/.test(raw) || Number(raw) < min)
2139
+ throw usageError(`Error: --${name} must be an integer >= ${min}.`);
2140
+ return Number(raw);
2141
+ }
2142
+ var num = (n) => n.toLocaleString("en-US");
2143
+ function buildObjectStorage(v) {
2144
+ if (!v.bucket) throw usageError("Error: --bucket is required.");
2145
+ const id = v["aws-access-key-id"];
2146
+ const secret = v["aws-secret-access-key"];
2147
+ if (Boolean(id) !== Boolean(secret))
2148
+ throw usageError(
2149
+ "Error: pass both --aws-access-key-id and --aws-secret-access-key, or neither."
2150
+ );
2151
+ return new ObjectStorage({
2152
+ bucket: v.bucket,
2153
+ endpoint: v["endpoint-url"],
2154
+ region: v.region,
2155
+ credentials: id && secret ? { accessKeyId: id, secretAccessKey: secret } : void 0
2156
+ });
2157
+ }
2158
+ function requireSqliteFile(t, hint) {
2159
+ if (t.kind === "sqlite" && t.path !== ":memory:" && !existsSync2(t.path)) {
2160
+ throw new CliExit(
2161
+ 1,
2162
+ `SQLite database file ${JSON.stringify(t.path)} does not exist yet. ${hint}`
2163
+ );
2164
+ }
2165
+ }
2166
+ async function cmdInit(v, env, io) {
2167
+ const backend = openBackend(resolveTarget(v, env), {
2168
+ dedup: Boolean(v.dedup),
2169
+ autoMigrate: true
2170
+ });
2171
+ await connect(backend, "initialize schema");
2172
+ io.out(
2173
+ v.dedup ? "zerobucket_blobs and zerobucket_image_refs tables and indexes are ready." : "zerobucket_images table and indexes are ready."
2174
+ );
2175
+ await backend.close();
2176
+ return 0;
2177
+ }
2178
+ async function cmdMigrate(v, env, io) {
2179
+ if (v["to-dedup"]) {
2180
+ const target = resolveTarget(v, env);
2181
+ if (target.kind !== "postgres")
2182
+ throw usageError("Error: --to-dedup is only supported for PostgreSQL.");
2183
+ const backend = openBackend(target, { dedup: true, autoMigrate: true });
2184
+ await connect(backend, "connect");
2185
+ try {
2186
+ const r = await backend.migrateClassicToDedup();
2187
+ io.out(
2188
+ `Migrated ${num(r.imagesMigrated)} image(s) into ${num(r.distinctBlobsCreated)} distinct blob(s).`
2189
+ );
2190
+ io.out(
2191
+ ` Duplicate references found: ${num(r.duplicateReferencesFound)}`
2192
+ );
2193
+ io.out(` Already migrated (skipped): ${num(r.alreadyMigrated)}`);
2194
+ io.out("The classic table was not modified.");
2195
+ return 0;
2196
+ } catch (exc) {
2197
+ throw new CliExit(1, `Error: ${msg(exc)}`);
2198
+ } finally {
2199
+ await backend.close();
2200
+ }
2201
+ }
2202
+ io.out(
2203
+ "Note: zerobucket does not have versioned migrations yet -- this currently just ensures the base schema exists, same as 'init'."
2204
+ );
2205
+ return cmdInit(v, env, io);
2206
+ }
2207
+ async function cmdInfo(v, env, io) {
2208
+ const target = resolveTarget(v, env);
2209
+ requireSqliteFile(target, "Run 'zerobucket init --sqlite PATH' first.");
2210
+ const backend = openBackend(target, {
2211
+ dedup: Boolean(v.dedup),
2212
+ autoMigrate: false
2213
+ });
2214
+ await connect(backend, "connect");
2215
+ try {
2216
+ const info = await backend.getInfo();
2217
+ if (!info) {
2218
+ io.out(
2219
+ v.dedup ? "zerobucket_blobs / zerobucket_image_refs tables do not exist yet. Run 'zerobucket init --dedup' first." : "zerobucket_images table does not exist yet. Run 'zerobucket init' first."
2220
+ );
2221
+ return 1;
2222
+ }
2223
+ if (info.mode === "dedup") {
2224
+ io.out(
2225
+ `zerobucket_image_refs: ${num(info.count)} image(s) sharing ${num(info.dedup.blobs)} distinct blob(s)`
2226
+ );
2227
+ } else {
2228
+ io.out(`zerobucket_images: ${num(info.count)} image(s)`);
2229
+ }
2230
+ io.out(
2231
+ ` Total stored bytes (application-recorded): ${num(info.totalBytes)} bytes`
2232
+ );
2233
+ if (info.dedup) {
2234
+ const saved = info.totalBytes - info.dedup.storedBytes;
2235
+ const pct = info.totalBytes > 0 ? (saved / info.totalBytes * 100).toFixed(1) : "0.0";
2236
+ io.out(
2237
+ ` Physical bytes after dedup: ${num(info.dedup.storedBytes)} bytes (saved ${num(saved)} bytes, ${pct}%)`
2238
+ );
2239
+ }
2240
+ if (info.onDisk) {
2241
+ io.out(
2242
+ target.kind === "postgres" ? ` On-disk size (table + TOAST + indexes): ${info.onDisk}` : ` On-disk size (database file + WAL): ${info.onDisk}`
2243
+ );
2244
+ }
2245
+ if (info.tiered && info.tiered.count > 0) {
2246
+ io.out(
2247
+ ` Tiered to object storage: ${num(info.tiered.count)} image(s), ${num(info.tiered.bytes)} bytes (not in the database)`
2248
+ );
2249
+ }
2250
+ if (info.oldest !== null) {
2251
+ io.out(` Oldest: ${info.oldest}`);
2252
+ io.out(` Newest: ${info.newest}`);
2253
+ }
2254
+ if (info.byFormat.length > 0) {
2255
+ io.out(" By format:");
2256
+ for (const f of info.byFormat) {
2257
+ io.out(
2258
+ ` ${f.mimeType.padEnd(12)} ${String(f.count).padStart(8)} image(s) ${num(f.bytes).padStart(14)} bytes`
2259
+ );
2260
+ }
2261
+ }
2262
+ return 0;
2263
+ } finally {
2264
+ await backend.close();
2265
+ }
2266
+ }
2267
+ async function cmdVerify(v, env, io) {
2268
+ const sample = positiveInt("sample", v.sample, 1);
2269
+ const os = v.bucket ? buildObjectStorage(v) : void 0;
2270
+ const target = resolveTarget(v, env);
2271
+ requireSqliteFile(target, "Nothing to verify.");
2272
+ const backend = openBackend(target, {
2273
+ dedup: Boolean(v.dedup),
2274
+ autoMigrate: false,
2275
+ objectStorage: os
2276
+ });
2277
+ await connect(backend, "connect");
2278
+ const mismatches = [];
2279
+ const errors = [];
2280
+ let checked = 0;
2281
+ let skippedTiered = 0;
2282
+ try {
2283
+ let entries;
2284
+ try {
2285
+ entries = await backend.listImages({ sample });
2286
+ } catch (exc) {
2287
+ throw new CliExit(
2288
+ 1,
2289
+ `Error: ${msg(exc)} (has 'zerobucket init' been run?)`
2290
+ );
2291
+ }
2292
+ const total = entries.length;
2293
+ if (total === 0) {
2294
+ io.out("No images to verify.");
2295
+ return 0;
2296
+ }
2297
+ io.out(`Verifying ${num(total)} image(s)...`);
2298
+ for (let i = 1; i <= total; i++) {
2299
+ const e = entries[i - 1];
2300
+ if (e.tiered && !os) {
2301
+ skippedTiered += 1;
2302
+ } else {
2303
+ try {
2304
+ const rec = await backend.get(e.id);
2305
+ if (rec) {
2306
+ checked += 1;
2307
+ if (createHash("sha256").update(rec.data).digest("hex") !== rec.checksumSha256.trim())
2308
+ mismatches.push(e.id);
2309
+ }
2310
+ } catch (exc) {
2311
+ errors.push(`${e.id}: ${msg(exc)}`);
2312
+ }
2313
+ }
2314
+ if (i % 100 === 0 || i === total) io.out(` ${i}/${total} checked...`);
2315
+ }
2316
+ } finally {
2317
+ await backend.close();
2318
+ }
2319
+ io.out("");
2320
+ if (mismatches.length > 0) {
2321
+ io.out(
2322
+ `FAILED: ${mismatches.length} of ${checked} image(s) have a checksum mismatch (possible corruption):`
2323
+ );
2324
+ for (const id of mismatches) io.out(` ${id}`);
2325
+ }
2326
+ if (errors.length > 0) {
2327
+ io.out(`ERROR: could not read ${errors.length} image(s):`);
2328
+ for (const e of errors) io.out(` ${e}`);
2329
+ }
2330
+ if (skippedTiered > 0) {
2331
+ io.out(
2332
+ `Note: ${skippedTiered} image(s) tiered to object storage were skipped. Pass --bucket (and credentials) to verify them too.`
2333
+ );
2334
+ }
2335
+ if (mismatches.length > 0 || errors.length > 0) return 1;
2336
+ io.out(`OK: all ${checked} image(s) verified, no checksum mismatches.`);
2337
+ return 0;
2338
+ }
2339
+ async function cmdTier(v, positional, env, io) {
2340
+ const bulk = Boolean(v.all) || v["min-size"] !== void 0 || v["older-than"] !== void 0;
2341
+ if (positional && bulk)
2342
+ throw usageError(
2343
+ "Error: can't combine a single IMAGE_ID with --all/--min-size/--older-than."
2344
+ );
2345
+ if (!positional && !bulk) {
2346
+ throw usageError(
2347
+ "Error: specify either a single IMAGE_ID to tier, or a bulk selection filter (--all, --min-size, and/or --older-than)."
2348
+ );
2349
+ }
2350
+ if (v.dedup)
2351
+ throw usageError(
2352
+ "Error: tier is not supported with --dedup (a deduplicated blob can be shared by many images)."
2353
+ );
2354
+ const minSize = positiveInt("min-size", v["min-size"], 0);
2355
+ const olderThanDays = positiveInt("older-than", v["older-than"], 0);
2356
+ const limit = positiveInt("limit", v.limit, 1);
2357
+ const os = buildObjectStorage(v);
2358
+ const target = resolveTarget(v, env);
2359
+ requireSqliteFile(target, "Nothing to tier.");
2360
+ const backend = openBackend(target, {
2361
+ dedup: false,
2362
+ autoMigrate: false,
2363
+ objectStorage: os
2364
+ });
2365
+ await connect(backend, "connect");
2366
+ try {
2367
+ let candidates;
2368
+ if (positional) {
2369
+ candidates = [positional];
2370
+ } else {
2371
+ candidates = (await backend.listImages({
2372
+ minSize,
2373
+ olderThanDays,
2374
+ limit,
2375
+ onlyUntiered: true
2376
+ })).map((e) => e.id);
2377
+ if (candidates.length === 0) {
2378
+ io.out("No matching images to tier (or all already tiered).");
2379
+ return 0;
2380
+ }
2381
+ }
2382
+ if (v["dry-run"]) {
2383
+ io.out(`Would tier ${candidates.length} image(s):`);
2384
+ for (const id of candidates) io.out(` ${id}`);
2385
+ return 0;
2386
+ }
2387
+ let tiered = 0;
2388
+ let skipped = 0;
2389
+ let failed = 0;
2390
+ let notAttempted = 0;
2391
+ const total = candidates.length;
2392
+ for (let i = 1; i <= total; i++) {
2393
+ const id = candidates[i - 1];
2394
+ try {
2395
+ const r = await backend.tierToObjectStorage(id);
2396
+ if (r === null) {
2397
+ io.err(` NOT FOUND ${id}`);
2398
+ failed += 1;
2399
+ } else if (r === false) skipped += 1;
2400
+ else tiered += 1;
2401
+ } catch (exc) {
2402
+ io.err(` FAILED ${id}: ${msg(exc)}`);
2403
+ failed += 1;
2404
+ if (/optional dependency '@aws-sdk\/client-s3'/.test(msg(exc))) {
2405
+ notAttempted = total - i;
2406
+ if (notAttempted > 0)
2407
+ io.err(
2408
+ ` Stopping: the remaining ${notAttempted} image(s) would fail the same way.`
2409
+ );
2410
+ break;
2411
+ }
2412
+ }
2413
+ if (total > 1 && (i % 50 === 0 || i === total))
2414
+ io.out(` ${i}/${total} processed...`);
2415
+ }
2416
+ io.out("");
2417
+ io.out(
2418
+ `Tiered: ${tiered}, already tiered (skipped): ${skipped}, failed: ${failed}${notAttempted > 0 ? `, not attempted: ${notAttempted}` : ""}`
2419
+ );
2420
+ return failed > 0 ? 1 : 0;
2421
+ } finally {
2422
+ await backend.close();
2423
+ }
2424
+ }
2425
+ async function main(argv, io = defaultIO()) {
2426
+ try {
2427
+ let parsed;
2428
+ try {
2429
+ parsed = parseArgs({
2430
+ args: argv,
2431
+ options: OPTIONS,
2432
+ allowPositionals: true,
2433
+ strict: true
2434
+ });
2435
+ } catch (exc) {
2436
+ throw usageError(
2437
+ `Error: ${msg(exc)}
2438
+ Run 'zerobucket --help' for usage.`
2439
+ );
2440
+ }
2441
+ const { values: v, positionals } = parsed;
2442
+ if (v.version) {
2443
+ io.out(`zerobucket ${cliVersion()}`);
2444
+ return 0;
2445
+ }
2446
+ if (v.help) {
2447
+ io.out(HELP);
2448
+ return 0;
2449
+ }
2450
+ const command = positionals[0];
2451
+ if (!command) {
2452
+ io.err(HELP);
2453
+ return 2;
2454
+ }
2455
+ const allowed = COMMAND_OPTIONS[command];
2456
+ if (!allowed)
2457
+ throw usageError(
2458
+ `Error: unknown command ${JSON.stringify(command)}.
2459
+ Run 'zerobucket --help' for usage.`
2460
+ );
2461
+ for (const name of Object.keys(v)) {
2462
+ if (!COMMON.has(name) && !allowed.includes(name))
2463
+ throw usageError(`Error: --${name} is not valid for '${command}'.`);
2464
+ }
2465
+ if (positionals.length > (command === "tier" ? 2 : 1))
2466
+ throw usageError(
2467
+ `Error: unexpected argument ${JSON.stringify(positionals[command === "tier" ? 2 : 1])}.`
2468
+ );
2469
+ if (command !== "tier" && positionals.length > 1)
2470
+ throw usageError(
2471
+ `Error: unexpected argument ${JSON.stringify(positionals[1])}.`
2472
+ );
2473
+ switch (command) {
2474
+ case "init":
2475
+ return await cmdInit(v, io.env, io);
2476
+ case "migrate":
2477
+ return await cmdMigrate(v, io.env, io);
2478
+ case "info":
2479
+ return await cmdInfo(v, io.env, io);
2480
+ case "verify":
2481
+ return await cmdVerify(v, io.env, io);
2482
+ default:
2483
+ return await cmdTier(v, positionals[1], io.env, io);
2484
+ }
2485
+ } catch (exc) {
2486
+ if (exc instanceof CliExit) {
2487
+ (exc.code === 1 && !exc.message.startsWith("Error") ? io.out : io.err)(
2488
+ exc.message
2489
+ );
2490
+ return exc.code;
2491
+ }
2492
+ io.err(`Error: ${msg(exc)}`);
2493
+ return 1;
2494
+ }
2495
+ }
2496
+
2497
+ // src/bin.ts
2498
+ main(process.argv.slice(2)).then(
2499
+ (code) => {
2500
+ process.exitCode = code;
2501
+ },
2502
+ (exc) => {
2503
+ console.error(`Error: ${exc instanceof Error ? exc.message : String(exc)}`);
2504
+ process.exitCode = 1;
2505
+ }
2506
+ );