zerobucket 0.1.0 → 0.5.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/index.js CHANGED
@@ -15,8 +15,91 @@ import { createHash } from "crypto";
15
15
  import { readFile, stat } from "fs/promises";
16
16
  import { basename } from "path";
17
17
 
18
- // src/adapters/postgres.ts
18
+ // src/adapters/shared.ts
19
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
20
103
  var SCHEMA = `
21
104
  CREATE TABLE IF NOT EXISTS zerobucket_images (
22
105
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -82,10 +165,59 @@ var SELECT_STREAM_INFO = `SELECT size_bytes, storage_backend, object_storage_key
82
165
  var DELETE_RETURNING = `DELETE FROM zerobucket_images WHERE id = $1 RETURNING storage_backend, object_storage_key;`;
83
166
  var DELETE_MANY = `DELETE FROM zerobucket_images WHERE id = ANY($1::uuid[]) RETURNING id, storage_backend, object_storage_key;`;
84
167
  var EXISTS = `SELECT 1 FROM zerobucket_images WHERE id = $1;`;
85
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
86
- function isValidId(id) {
87
- return typeof id === "string" && UUID_RE.test(id);
88
- }
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
+ };
89
221
  var RETRYABLE_SQLSTATES = /* @__PURE__ */ new Set([
90
222
  "40001",
91
223
  // serialization_failure
@@ -156,6 +288,13 @@ var PostgresBackend = class {
156
288
  this.maxRetries = opts.maxRetries ?? 3;
157
289
  this.retryBaseDelayMs = opts.retryBaseDelayMs ?? 100;
158
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;
159
298
  }
160
299
  opts;
161
300
  pool;
@@ -165,6 +304,8 @@ var PostgresBackend = class {
165
304
  maxRetries;
166
305
  retryBaseDelayMs;
167
306
  autoMigrate;
307
+ dedup;
308
+ sql;
168
309
  // ---- lifecycle -------------------------------------------------------
169
310
  ready() {
170
311
  if (this.closed)
@@ -229,7 +370,7 @@ var PostgresBackend = class {
229
370
  await client.query(
230
371
  "SELECT pg_advisory_xact_lock(hashtext('zerobucket_migrate'))"
231
372
  );
232
- await client.query(SCHEMA);
373
+ await client.query(this.sql.schema);
233
374
  await client.query("COMMIT");
234
375
  client.release();
235
376
  } catch (exc) {
@@ -262,123 +403,1119 @@ var PostgresBackend = class {
262
403
  }
263
404
  }
264
405
  /**
265
- * Run `work` and return its result, emitting exactly one OperationEvent.
266
- *
267
- * connection given -> run once on it, no BEGIN/COMMIT, no retry.
268
- * connection absent -> pooled; `tx` wraps the work in BEGIN/COMMIT; transient
269
- * failures retry the WHOLE closure on a fresh connection.
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.
270
1332
  */
271
- async run(operation, connection, work, { tx = false } = {}) {
272
- if (connection) {
273
- const start2 = performance.now();
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) {
274
1340
  try {
275
- const result = await work(connection);
276
- this.emit(operation, start2, true, null, 0);
277
- return result;
278
- } catch (exc) {
279
- this.emit(operation, start2, false, msg(exc), 0);
280
- throw exc;
1341
+ db.exec("ROLLBACK TO SAVEPOINT zerobucket_atomic");
1342
+ db.exec("RELEASE SAVEPOINT zerobucket_atomic");
1343
+ } catch {
281
1344
  }
1345
+ throw exc;
282
1346
  }
283
- await this.ready();
1347
+ }
1348
+ async execute(operation, connection, mode, work) {
284
1349
  const start = performance.now();
285
- let attempt = 0;
286
- for (; ; ) {
287
- let client;
288
- let destroy = false;
289
- try {
290
- client = await this.pool.connect();
291
- if (tx) await client.query("BEGIN");
292
- const result = await work(client);
293
- if (tx) await client.query("COMMIT");
294
- this.emit(operation, start, true, null, attempt);
295
- return result;
296
- } catch (exc) {
297
- if (client && tx) {
298
- try {
299
- await client.query("ROLLBACK");
300
- } catch {
301
- destroy = true;
302
- }
303
- }
304
- if (isConnectionLevel(exc)) destroy = true;
305
- attempt += 1;
306
- if (attempt > this.maxRetries || !isRetryable(exc)) {
307
- this.emit(operation, start, false, msg(exc), attempt - 1);
308
- throw exc;
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
+ );
309
1358
  }
310
- } finally {
311
- client?.release(destroy);
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);
312
1368
  }
313
- await sleep(backoffDelayMs(attempt, this.retryBaseDelayMs));
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;
314
1374
  }
315
1375
  }
316
1376
  // ---- StorageBackend --------------------------------------------------
317
1377
  async put(row, { connection } = {}) {
318
1378
  try {
319
- return await this.run("put", connection, async (q) => {
320
- const res = await q.query(INSERT, rowParams(row));
321
- return String(res.rows[0].id);
322
- });
1379
+ return await this.execute(
1380
+ "put",
1381
+ connection,
1382
+ "write",
1383
+ (db) => this.insertOne(db, row)
1384
+ );
323
1385
  } catch (exc) {
324
1386
  throw wrap("Failed to store image", exc);
325
1387
  }
326
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
+ }
327
1426
  async putMany(rows, { connection } = {}) {
328
1427
  if (rows.length === 0) return [];
329
1428
  try {
330
- return await this.run(
331
- "put_many",
332
- connection,
333
- async (q) => {
334
- const ids = [];
335
- for (const r of rows)
336
- ids.push(String((await q.query(INSERT, rowParams(r))).rows[0].id));
337
- return ids;
338
- },
339
- { tx: true }
340
- );
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
+ });
341
1462
  } catch (exc) {
342
1463
  throw wrap("Failed to store image batch", exc);
343
1464
  }
344
1465
  }
345
1466
  async get(id, { connection } = {}) {
346
1467
  if (!isValidId(id)) return null;
1468
+ const norm = id.toLowerCase();
347
1469
  let row;
348
1470
  try {
349
- row = await this.run(
1471
+ row = await this.execute(
350
1472
  "get",
351
1473
  connection,
352
- async (q) => (await q.query(SELECT_FULL, [id])).rows[0]
1474
+ "read",
1475
+ (db) => db.prepare(this.dedup ? D_SELECT_FULL : SELECT_FULL2).get(norm)
353
1476
  );
354
1477
  } catch (exc) {
355
1478
  throw wrap("Failed to retrieve image", exc);
356
1479
  }
357
- return row ? this.toRecord(row, id) : null;
1480
+ return row ? hydrateRow(row, norm, this.opts.objectStorage) : null;
358
1481
  }
359
1482
  async getMany(ids, { connection } = {}) {
360
- const valid = ids.filter(isValidId);
1483
+ const valid = [
1484
+ ...new Set(ids.filter(isValidId).map((i) => i.toLowerCase()))
1485
+ ];
361
1486
  if (valid.length === 0) return [];
362
1487
  let rows;
363
1488
  try {
364
- rows = await this.run(
365
- "get_many",
366
- connection,
367
- async (q) => (await q.query(SELECT_MANY, [valid])).rows
368
- );
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
+ });
369
1501
  } catch (exc) {
370
1502
  throw wrap("Failed to retrieve image batch", exc);
371
1503
  }
372
- return rows.map((r) => this.toRecord(r, String(r.id)));
1504
+ return mapLimit(
1505
+ rows,
1506
+ 4,
1507
+ (r) => hydrateRow(r, String(r.id), this.opts.objectStorage)
1508
+ );
373
1509
  }
374
1510
  async getMetadata(id, { connection } = {}) {
375
1511
  if (!isValidId(id)) return null;
376
1512
  let row;
377
1513
  try {
378
- row = await this.run(
1514
+ row = await this.execute(
379
1515
  "get_metadata",
380
1516
  connection,
381
- async (q) => (await q.query(SELECT_METADATA, [id])).rows[0]
1517
+ "read",
1518
+ (db) => db.prepare(this.dedup ? D_SELECT_METADATA : SELECT_METADATA2).get(id.toLowerCase())
382
1519
  );
383
1520
  } catch (exc) {
384
1521
  throw wrap("Failed to retrieve image metadata", exc);
@@ -396,25 +1533,37 @@ var PostgresBackend = class {
396
1533
  }
397
1534
  async getStream(id, opts) {
398
1535
  if (!isValidId(id)) return null;
1536
+ const norm = id.toLowerCase();
399
1537
  const { connection, chunkSize } = opts;
400
1538
  if (!Number.isInteger(chunkSize) || chunkSize <= 0)
401
1539
  throw new RangeError("chunkSize must be a positive integer");
402
1540
  let info;
403
1541
  try {
404
- info = await this.run(
1542
+ info = await this.execute(
405
1543
  "get_metadata",
406
1544
  connection,
407
- async (q) => (await q.query(SELECT_STREAM_INFO, [id])).rows[0]
1545
+ "read",
1546
+ (db) => db.prepare(this.dedup ? D_STREAM_INFO : STREAM_INFO).get(norm)
408
1547
  );
409
1548
  } catch (exc) {
410
1549
  throw wrap("Failed to retrieve image metadata", exc);
411
1550
  }
412
1551
  if (!info) return null;
413
- if (info.storage_backend === "object_storage")
414
- throw this.tieredWithoutStorage(id, info.object_storage_key);
415
1552
  const totalSize = info.size_bytes;
416
1553
  const start = opts.range?.start ?? 0;
417
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
+ }
418
1567
  const self = this;
419
1568
  async function* generate() {
420
1569
  let offset = start;
@@ -424,23 +1573,24 @@ var PostgresBackend = class {
424
1573
  const length = Math.min(chunkSize, wanted - delivered);
425
1574
  let row;
426
1575
  try {
427
- row = await self.run(
1576
+ row = await self.execute(
428
1577
  "get_stream",
429
1578
  connection,
430
- async (q) => (await q.query(SELECT_CHUNK, [offset + 1, length, id])).rows[0]
1579
+ "read",
1580
+ (db) => db.prepare(self.dedup ? D_CHUNK : CHUNK).get(offset + 1, length, norm)
431
1581
  );
432
1582
  } catch (exc) {
433
1583
  throw wrap("Failed to stream image", exc);
434
1584
  }
435
1585
  if (!row) {
436
1586
  throw new StorageError(
437
- `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.`
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.`
438
1588
  );
439
1589
  }
440
1590
  const chunk = row.chunk;
441
1591
  if (!chunk || chunk.length === 0) {
442
1592
  throw new StorageError(
443
- `Image ${JSON.stringify(id)} ended early while streaming (delivered ${delivered} of ${wanted} bytes).`
1593
+ `Image ${JSON.stringify(norm)} ended early while streaming (delivered ${delivered} of ${wanted} bytes).`
444
1594
  );
445
1595
  }
446
1596
  yield chunk;
@@ -452,25 +1602,74 @@ var PostgresBackend = class {
452
1602
  }
453
1603
  async delete(id, { connection } = {}) {
454
1604
  if (!isValidId(id)) return false;
1605
+ const norm = id.toLowerCase();
455
1606
  try {
456
- const row = await this.run(
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(
457
1618
  "delete",
458
1619
  connection,
459
- async (q) => (await q.query(DELETE_RETURNING, [id])).rows[0]
1620
+ "write",
1621
+ (db) => db.prepare(DELETE_ONE).get(norm)
460
1622
  );
1623
+ if (row?.storage_backend === "object_storage")
1624
+ await this.cleanupObjects([row.object_storage_key], connection);
461
1625
  return row !== void 0;
462
1626
  } catch (exc) {
463
1627
  throw wrap("Failed to delete image", exc);
464
1628
  }
465
1629
  }
466
1630
  async deleteMany(ids, { connection } = {}) {
467
- const valid = ids.filter(isValidId);
1631
+ const valid = [
1632
+ ...new Set(ids.filter(isValidId).map((i) => i.toLowerCase()))
1633
+ ];
468
1634
  if (valid.length === 0) return [];
469
1635
  try {
470
- const rows = await this.run(
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(
471
1658
  "delete_many",
472
1659
  connection,
473
- async (q) => (await q.query(DELETE_MANY, [valid])).rows
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
474
1673
  );
475
1674
  return rows.map((r) => String(r.id));
476
1675
  } catch (exc) {
@@ -480,56 +1679,206 @@ var PostgresBackend = class {
480
1679
  async exists(id, { connection } = {}) {
481
1680
  if (!isValidId(id)) return false;
482
1681
  try {
483
- return await this.run(
1682
+ return await this.execute(
484
1683
  "exists",
485
1684
  connection,
486
- async (q) => ((await q.query(EXISTS, [id])).rowCount ?? 0) > 0
1685
+ "read",
1686
+ (db) => db.prepare(this.dedup ? D_EXISTS : EXISTS2).get(id.toLowerCase()) !== void 0
487
1687
  );
488
1688
  } catch (exc) {
489
1689
  throw wrap("Failed to check image existence", exc);
490
1690
  }
491
1691
  }
492
- // ---- helpers ---------------------------------------------------------
493
- toRecord(row, id) {
494
- if (row.storage_backend === "object_storage")
495
- throw this.tieredWithoutStorage(id, row.object_storage_key);
496
- return {
497
- id: String(row.id),
498
- data: row.data,
499
- mimeType: row.mime_type,
500
- originalFilename: row.original_filename,
501
- sizeBytes: row.size_bytes,
502
- width: row.width,
503
- height: row.height,
504
- checksumSha256: row.checksum_sha256
505
- };
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
+ }
506
1748
  }
507
- tieredWithoutStorage(id, key) {
508
- return new StorageError(
509
- `Image ${JSON.stringify(id)} is stored in object storage (key=${JSON.stringify(key)}) but object-storage tiering is not available in this version of the npm package yet. Read it from the Python package (configured with the same bucket), or wait for npm tiering support.`
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
+ })
510
1800
  );
511
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
+ }
512
1881
  };
513
- function rowParams(r) {
514
- return [
515
- r.data,
516
- r.mimeType,
517
- r.originalFilename,
518
- r.sizeBytes,
519
- r.width,
520
- r.height,
521
- r.checksumSha256
522
- ];
523
- }
524
- function wrap(prefix, exc) {
525
- return exc instanceof StorageError ? exc : new StorageError(`${prefix}: ${msg(exc)}`, { cause: exc });
526
- }
527
- function msg(exc) {
528
- return exc instanceof Error ? exc.message : String(exc);
529
- }
530
- function sleep(ms) {
531
- return new Promise((resolve) => setTimeout(resolve, ms));
532
- }
533
1882
 
534
1883
  // src/validation.ts
535
1884
  var FORMAT_TO_MIME = {
@@ -673,7 +2022,18 @@ var ZeroBucket = class _ZeroBucket {
673
2022
  beforeGet;
674
2023
  beforePut;
675
2024
  constructor(options = {}) {
676
- this.backend = options.backend ?? new PostgresBackend({
2025
+ if (options.sqlite !== void 0 && (options.connectionString || options.pool)) {
2026
+ throw new TypeError(
2027
+ "Choose one database: `sqlite` OR `connectionString`/`pool`, not both."
2028
+ );
2029
+ }
2030
+ this.backend = options.backend ?? (options.sqlite !== void 0 ? new SQLiteBackend({
2031
+ path: options.sqlite,
2032
+ autoMigrate: options.autoMigrate,
2033
+ dedup: options.dedup,
2034
+ objectStorage: options.objectStorage,
2035
+ onOperation: options.onOperation
2036
+ }) : new PostgresBackend({
677
2037
  connectionString: options.connectionString,
678
2038
  pool: options.pool,
679
2039
  autoMigrate: options.autoMigrate,
@@ -682,8 +2042,10 @@ var ZeroBucket = class _ZeroBucket {
682
2042
  poolMinSize: options.poolMinSize,
683
2043
  poolMaxSize: options.poolMaxSize,
684
2044
  poolTimeoutMs: options.poolTimeoutMs,
685
- onOperation: options.onOperation
686
- });
2045
+ onOperation: options.onOperation,
2046
+ objectStorage: options.objectStorage,
2047
+ dedup: options.dedup
2048
+ }));
687
2049
  this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
688
2050
  this.maxPixels = options.maxPixels ?? DEFAULT_MAX_PIXELS;
689
2051
  this.allowedFormats = options.allowedFormats ?? SUPPORTED_FORMATS;
@@ -804,7 +2166,7 @@ var ZeroBucket = class _ZeroBucket {
804
2166
  }
805
2167
  const results = new Array(images.length);
806
2168
  const prepared = [];
807
- await mapLimit(images, PREPARE_CONCURRENCY, async (image, i) => {
2169
+ await mapLimit2(images, PREPARE_CONCURRENCY, async (image, i) => {
808
2170
  try {
809
2171
  const row = await this.prepareRow(image, {
810
2172
  ...options,
@@ -1020,6 +2382,32 @@ var ZeroBucket = class _ZeroBucket {
1020
2382
  success: true
1021
2383
  }));
1022
2384
  }
2385
+ /**
2386
+ * Move an image's bytes from Postgres into object storage; reads, streams and
2387
+ * deletes keep working transparently. Returns true if tiered now, false if it was
2388
+ * already tiered (safe to re-run in a backfill). Throws ImageNotFoundError if missing.
2389
+ *
2390
+ * The upload runs inside the database transaction: if it fails, the row is left
2391
+ * completely untouched. Explicit and opt-in: put() never tiers automatically.
2392
+ * Not gated by beforeGet/beforePut (it is a maintenance operation, as in the Python package).
2393
+ */
2394
+ async tierToObjectStorage(imageId, options = {}) {
2395
+ const result = await this.backend.tierToObjectStorage(imageId, options);
2396
+ if (result === null) throw new ImageNotFoundError(imageId);
2397
+ return result;
2398
+ }
2399
+ /**
2400
+ * One-time, non-destructive copy of classic-mode images into a dedup instance's tables, keeping every
2401
+ * id. Call it on an instance created with `dedup: true`. Safe to re-run. See PostgresBackend for details.
2402
+ */
2403
+ async migrateClassicToDedup() {
2404
+ if (!this.backend.migrateClassicToDedup) {
2405
+ throw new StorageError(
2406
+ "This backend does not support migrateClassicToDedup()."
2407
+ );
2408
+ }
2409
+ return this.backend.migrateClassicToDedup();
2410
+ }
1023
2411
  /** Release the pool (if ZeroBucket created it). */
1024
2412
  close() {
1025
2413
  return this.backend.close();
@@ -1073,7 +2461,7 @@ async function readInput(image, filename, maxBytes) {
1073
2461
  "Unsupported image input. Pass a Buffer, Uint8Array, file path string, Blob/File, or a readable stream."
1074
2462
  );
1075
2463
  }
1076
- async function mapLimit(items, limit, fn) {
2464
+ async function mapLimit2(items, limit, fn) {
1077
2465
  let next = 0;
1078
2466
  const workers = Array.from(
1079
2467
  { length: Math.min(limit, items.length) },
@@ -1090,6 +2478,119 @@ function errText(exc) {
1090
2478
  return exc instanceof Error ? exc.message : String(exc);
1091
2479
  }
1092
2480
 
2481
+ // src/object-storage.ts
2482
+ var ObjectStorage = class {
2483
+ constructor(opts) {
2484
+ this.opts = opts;
2485
+ if (!opts.bucket)
2486
+ throw new TypeError("ObjectStorage requires a bucket name");
2487
+ this.bucket = opts.bucket;
2488
+ }
2489
+ opts;
2490
+ bucket;
2491
+ clientPromise;
2492
+ connection() {
2493
+ this.clientPromise ??= (async () => {
2494
+ let sdk;
2495
+ try {
2496
+ sdk = await import("@aws-sdk/client-s3");
2497
+ } catch (cause) {
2498
+ throw new StorageError(
2499
+ "Object-storage tiering requires the optional dependency '@aws-sdk/client-s3'. Install it with: npm install @aws-sdk/client-s3",
2500
+ { cause }
2501
+ );
2502
+ }
2503
+ const o = this.opts;
2504
+ const client = o.client ?? new sdk.S3Client({
2505
+ endpoint: o.endpoint,
2506
+ region: o.region ?? process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? "us-east-1",
2507
+ credentials: o.credentials,
2508
+ forcePathStyle: o.forcePathStyle ?? o.endpoint !== void 0
2509
+ });
2510
+ return { sdk, client };
2511
+ })().catch((exc) => {
2512
+ this.clientPromise = void 0;
2513
+ throw exc;
2514
+ });
2515
+ return this.clientPromise;
2516
+ }
2517
+ async upload(key, data, { mimeType }) {
2518
+ const { sdk, client } = await this.connection();
2519
+ try {
2520
+ await client.send(
2521
+ new sdk.PutObjectCommand({
2522
+ Bucket: this.bucket,
2523
+ Key: key,
2524
+ Body: data,
2525
+ ContentType: mimeType
2526
+ })
2527
+ );
2528
+ } catch (exc) {
2529
+ throw new StorageError(
2530
+ `Failed to upload ${JSON.stringify(key)} to bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
2531
+ { cause: exc }
2532
+ );
2533
+ }
2534
+ }
2535
+ async download(key) {
2536
+ return this.get(key, void 0);
2537
+ }
2538
+ async downloadRange(key, start, endInclusive) {
2539
+ return this.get(key, `bytes=${start}-${endInclusive}`);
2540
+ }
2541
+ async get(key, range) {
2542
+ const { sdk, client } = await this.connection();
2543
+ try {
2544
+ const res = await client.send(
2545
+ new sdk.GetObjectCommand({
2546
+ Bucket: this.bucket,
2547
+ Key: key,
2548
+ Range: range
2549
+ })
2550
+ );
2551
+ return Buffer.from(await res.Body.transformToByteArray());
2552
+ } catch (exc) {
2553
+ throw new StorageError(
2554
+ `Failed to download ${JSON.stringify(key)} from bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
2555
+ { cause: exc }
2556
+ );
2557
+ }
2558
+ }
2559
+ async delete(key) {
2560
+ const { sdk, client } = await this.connection();
2561
+ try {
2562
+ await client.send(
2563
+ new sdk.DeleteObjectCommand({ Bucket: this.bucket, Key: key })
2564
+ );
2565
+ } catch (exc) {
2566
+ throw new StorageError(
2567
+ `Failed to delete ${JSON.stringify(key)} from bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
2568
+ { cause: exc }
2569
+ );
2570
+ }
2571
+ }
2572
+ async exists(key) {
2573
+ const { sdk, client } = await this.connection();
2574
+ try {
2575
+ await client.send(
2576
+ new sdk.HeadObjectCommand({ Bucket: this.bucket, Key: key })
2577
+ );
2578
+ return true;
2579
+ } catch (exc) {
2580
+ const e = exc;
2581
+ if (e.name === "NotFound" || e.name === "NoSuchKey" || e.$metadata?.httpStatusCode === 404)
2582
+ return false;
2583
+ throw new StorageError(
2584
+ `Failed to check ${JSON.stringify(key)} in bucket ${JSON.stringify(this.bucket)}: ${msg2(exc)}`,
2585
+ { cause: exc }
2586
+ );
2587
+ }
2588
+ }
2589
+ };
2590
+ function msg2(exc) {
2591
+ return exc instanceof Error ? exc.message : String(exc);
2592
+ }
2593
+
1093
2594
  // src/validators/pdf.ts
1094
2595
  var DEFAULT_MAX_PDF_BYTES = 20 * 1024 * 1024;
1095
2596
  var PDFValidator = class {
@@ -1132,8 +2633,10 @@ export {
1132
2633
  ImageNotFoundError,
1133
2634
  ImageTooLargeError,
1134
2635
  ImageValidationError,
2636
+ ObjectStorage,
1135
2637
  PDFValidator,
1136
2638
  PostgresBackend,
2639
+ SQLiteBackend,
1137
2640
  SUPPORTED_FORMATS,
1138
2641
  StorageError,
1139
2642
  UnsupportedFormatError,