zerobucket 0.6.1 → 0.8.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
@@ -1880,6 +1880,977 @@ var SQLiteBackend = class {
1880
1880
  }
1881
1881
  };
1882
1882
 
1883
+ // src/adapters/mysql.ts
1884
+ import { randomUUID as randomUUID2 } from "crypto";
1885
+ var SCHEMA3 = `
1886
+ CREATE TABLE IF NOT EXISTS zerobucket_images (
1887
+ id CHAR(36) PRIMARY KEY,
1888
+ data LONGBLOB NOT NULL,
1889
+ mime_type VARCHAR(255) NOT NULL,
1890
+ original_filename TEXT,
1891
+ size_bytes INT NOT NULL,
1892
+ width INT,
1893
+ height INT,
1894
+ checksum_sha256 CHAR(64) NOT NULL,
1895
+ created_at DATETIME(6) NOT NULL,
1896
+ updated_at DATETIME(6) NOT NULL,
1897
+ INDEX idx_zerobucket_checksum (checksum_sha256),
1898
+ INDEX idx_zerobucket_created_at (created_at)
1899
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
1900
+ var TIERING_CHECK = "chk_zerobucket_storage";
1901
+ var MIGRATE_LOCK = "zerobucket_migrate";
1902
+ var COLS2 = `id, data, mime_type, original_filename, size_bytes, width, height, checksum_sha256, storage_backend, object_storage_bucket, object_storage_key`;
1903
+ var INSERT3 = `INSERT INTO zerobucket_images (id, data, mime_type, original_filename, size_bytes, width, height, checksum_sha256, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
1904
+ var SELECT_FULL3 = `SELECT ${COLS2} FROM zerobucket_images WHERE id = ?`;
1905
+ var SELECT_MANY2 = `SELECT ${COLS2} FROM zerobucket_images WHERE id IN (?)`;
1906
+ var SELECT_METADATA3 = `SELECT id, mime_type, original_filename, size_bytes, width, height, checksum_sha256 FROM zerobucket_images WHERE id = ?`;
1907
+ var STREAM_INFO2 = `SELECT size_bytes, storage_backend, object_storage_key FROM zerobucket_images WHERE id = ?`;
1908
+ var CHUNK2 = `SELECT SUBSTRING(data FROM ? FOR ?) AS chunk FROM zerobucket_images WHERE id = ?`;
1909
+ var EXISTS3 = `SELECT 1 FROM zerobucket_images WHERE id = ?`;
1910
+ var LOCK_ONE = `SELECT storage_backend, object_storage_key FROM zerobucket_images WHERE id = ? FOR UPDATE`;
1911
+ var DELETE_ONE2 = `DELETE FROM zerobucket_images WHERE id = ?`;
1912
+ var LOCK_MANY = `SELECT id, storage_backend, object_storage_key FROM zerobucket_images FORCE INDEX (PRIMARY) WHERE id IN (?) ORDER BY id FOR UPDATE`;
1913
+ var SELECT_FOR_TIERING3 = `SELECT data, mime_type, size_bytes, storage_backend FROM zerobucket_images WHERE id = ? FOR UPDATE`;
1914
+ var UPDATE_AFTER_TIERING3 = `UPDATE zerobucket_images SET data = NULL, storage_backend = 'object_storage', object_storage_bucket = ?, object_storage_key = ?, updated_at = ? WHERE id = ?`;
1915
+ var LOCAL = "mysql";
1916
+ var DEDUP_BLOBS_SCHEMA = `
1917
+ CREATE TABLE IF NOT EXISTS zerobucket_blobs (
1918
+ checksum_sha256 CHAR(64) PRIMARY KEY,
1919
+ data LONGBLOB NOT NULL,
1920
+ mime_type VARCHAR(255) NOT NULL,
1921
+ size_bytes INT NOT NULL,
1922
+ width INT,
1923
+ height INT,
1924
+ ref_count INT NOT NULL DEFAULT 0,
1925
+ created_at DATETIME(6) NOT NULL
1926
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
1927
+ var DEDUP_REFS_SCHEMA = `
1928
+ CREATE TABLE IF NOT EXISTS zerobucket_image_refs (
1929
+ id CHAR(36) PRIMARY KEY,
1930
+ checksum_sha256 CHAR(64) NOT NULL,
1931
+ original_filename TEXT,
1932
+ created_at DATETIME(6) NOT NULL,
1933
+ updated_at DATETIME(6) NOT NULL,
1934
+ INDEX idx_zerobucket_image_refs_checksum (checksum_sha256),
1935
+ INDEX idx_zerobucket_image_refs_created_at (created_at),
1936
+ FOREIGN KEY (checksum_sha256) REFERENCES zerobucket_blobs(checksum_sha256)
1937
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`;
1938
+ function upsertBlobSql(n) {
1939
+ if (!Number.isInteger(n) || n < 1) throw new RangeError("invalid ref count");
1940
+ return `INSERT INTO zerobucket_blobs (checksum_sha256, data, mime_type, size_bytes, width, height, ref_count, created_at) VALUES (?, ?, ?, ?, ?, ?, ${n}, ?) ON DUPLICATE KEY UPDATE ref_count = ref_count + ${n}`;
1941
+ }
1942
+ var D_INSERT_REF3 = `INSERT INTO zerobucket_image_refs (id, checksum_sha256, original_filename, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`;
1943
+ var D_COLS3 = `r.id, b.data, b.mime_type, r.original_filename, b.size_bytes, b.width, b.height, r.checksum_sha256, '${LOCAL}' AS storage_backend, NULL AS object_storage_bucket, NULL AS object_storage_key`;
1944
+ var D_FROM3 = `FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256`;
1945
+ var D_LOCK_REF = `SELECT checksum_sha256 FROM zerobucket_image_refs WHERE id = ? FOR UPDATE`;
1946
+ var D_DELETE_REF3 = `DELETE FROM zerobucket_image_refs WHERE id = ?`;
1947
+ var D_LOCK_REFS = `SELECT id, checksum_sha256 FROM zerobucket_image_refs FORCE INDEX (PRIMARY) WHERE id IN (?) ORDER BY id FOR UPDATE`;
1948
+ var D_DECREMENT3 = `UPDATE zerobucket_blobs SET ref_count = ref_count - ? WHERE checksum_sha256 = ?`;
1949
+ var D_DELETE_EMPTY3 = `DELETE FROM zerobucket_blobs WHERE checksum_sha256 = ? AND ref_count <= 0`;
1950
+ var CLASSIC_SQL2 = {
1951
+ selectFull: SELECT_FULL3,
1952
+ selectMany: SELECT_MANY2,
1953
+ selectMetadata: SELECT_METADATA3,
1954
+ streamInfo: STREAM_INFO2,
1955
+ chunk: CHUNK2,
1956
+ exists: EXISTS3
1957
+ };
1958
+ var DEDUP_SQL2 = {
1959
+ selectFull: `SELECT ${D_COLS3} ${D_FROM3} WHERE r.id = ?`,
1960
+ selectMany: `SELECT ${D_COLS3} ${D_FROM3} WHERE r.id IN (?)`,
1961
+ selectMetadata: `SELECT r.id, b.mime_type, r.original_filename, b.size_bytes, b.width, b.height, r.checksum_sha256 ${D_FROM3} WHERE r.id = ?`,
1962
+ streamInfo: `SELECT b.size_bytes, '${LOCAL}' AS storage_backend, NULL AS object_storage_key ${D_FROM3} WHERE r.id = ?`,
1963
+ chunk: `SELECT SUBSTRING(b.data FROM ? FOR ?) AS chunk ${D_FROM3} WHERE r.id = ?`,
1964
+ exists: `SELECT 1 FROM zerobucket_image_refs WHERE id = ?`
1965
+ };
1966
+ var RETRYABLE_ERRNOS = /* @__PURE__ */ new Set([
1967
+ 1205,
1968
+ // ER_LOCK_WAIT_TIMEOUT
1969
+ 1213,
1970
+ // ER_LOCK_DEADLOCK
1971
+ 1040,
1972
+ // ER_CON_COUNT_ERROR (too many connections)
1973
+ 1053,
1974
+ // ER_SERVER_SHUTDOWN
1975
+ 1927,
1976
+ // ER_CONNECTION_KILLED (MariaDB)
1977
+ 2002,
1978
+ // CR_CONNECTION_ERROR
1979
+ 2003,
1980
+ // CR_CONN_HOST_ERROR
1981
+ 2006,
1982
+ // CR_SERVER_GONE_ERROR
1983
+ 2013
1984
+ // CR_SERVER_LOST
1985
+ ]);
1986
+ var CONNECTION_CODES = /* @__PURE__ */ new Set([
1987
+ "PROTOCOL_CONNECTION_LOST",
1988
+ "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR",
1989
+ "PROTOCOL_ENQUEUE_AFTER_QUIT",
1990
+ "ECONNRESET",
1991
+ "ECONNREFUSED",
1992
+ "ETIMEDOUT",
1993
+ "EPIPE",
1994
+ "ECONNABORTED"
1995
+ ]);
1996
+ function errnoOf(exc) {
1997
+ const n = exc?.errno;
1998
+ return typeof n === "number" ? n : void 0;
1999
+ }
2000
+ var PoolTimeoutError = class extends StorageError {
2001
+ };
2002
+ function isRetryable2(exc) {
2003
+ if (!(exc instanceof Error) || exc instanceof PoolTimeoutError) return false;
2004
+ const e = exc;
2005
+ const n = errnoOf(exc);
2006
+ if (n !== void 0 && RETRYABLE_ERRNOS.has(n)) return true;
2007
+ if (typeof e.code === "string") {
2008
+ if (CONNECTION_CODES.has(e.code)) return true;
2009
+ if (e.code === "ER_LOCK_WAIT_TIMEOUT" || e.code === "ER_LOCK_DEADLOCK" || e.code === "ER_CON_COUNT_ERROR" || e.code === "ER_SERVER_SHUTDOWN" || e.code === "ER_CONNECTION_KILLED")
2010
+ return true;
2011
+ }
2012
+ return false;
2013
+ }
2014
+ function isConnectionLevel2(exc) {
2015
+ if (!(exc instanceof Error)) return false;
2016
+ const e = exc;
2017
+ if (e.fatal === true) return true;
2018
+ if (typeof e.code === "string" && CONNECTION_CODES.has(e.code)) return true;
2019
+ const n = errnoOf(exc);
2020
+ return n === 2006 || n === 2013 || n === 1927 || n === 1053;
2021
+ }
2022
+ var MAX_BACKOFF_MS2 = 2e3;
2023
+ function backoffDelayMs2(attempt, baseDelayMs) {
2024
+ const exponential = baseDelayMs * 2 ** (attempt - 1);
2025
+ const jitter = Math.random() * baseDelayMs;
2026
+ return Math.min(exponential + jitter, MAX_BACKOFF_MS2);
2027
+ }
2028
+ function friendly(prefix, exc) {
2029
+ if (errnoOf(exc) === 1153) {
2030
+ return new StorageError(
2031
+ `${prefix}: the image is larger than the server's max_allowed_packet. Raise it (for example \`SET GLOBAL max_allowed_packet = 67108864\`, and set it in my.cnf to make it permanent), or lower \`maxBytes\`.`,
2032
+ { cause: exc }
2033
+ );
2034
+ }
2035
+ return wrap(prefix, exc);
2036
+ }
2037
+ function mysqlNow() {
2038
+ return `${(/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", "")}000`;
2039
+ }
2040
+ function normalizeUrl(url) {
2041
+ return url.replace(/^mariadb:\/\//i, "mysql://");
2042
+ }
2043
+ function isMysqlConnection(c) {
2044
+ const m = c;
2045
+ return typeof m.query === "function" && typeof m.execute === "function";
2046
+ }
2047
+ var MySQLBackend = class {
2048
+ constructor(opts) {
2049
+ this.opts = opts;
2050
+ if (!opts.connectionString && !opts.pool) {
2051
+ throw new TypeError(
2052
+ "MySQLBackend requires either `connectionString` or `pool`"
2053
+ );
2054
+ }
2055
+ this.dedup = opts.dedup ?? false;
2056
+ if (this.dedup && opts.objectStorage) {
2057
+ throw new TypeError(
2058
+ "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."
2059
+ );
2060
+ }
2061
+ this.sql = this.dedup ? DEDUP_SQL2 : CLASSIC_SQL2;
2062
+ this.ownsPool = !opts.pool;
2063
+ this.pool = opts.pool;
2064
+ this.maxRetries = opts.maxRetries ?? 3;
2065
+ this.retryBaseDelayMs = opts.retryBaseDelayMs ?? 100;
2066
+ this.poolTimeoutMs = opts.poolTimeoutMs ?? 1e4;
2067
+ this.autoMigrate = opts.autoMigrate ?? true;
2068
+ }
2069
+ opts;
2070
+ pool;
2071
+ ownsPool;
2072
+ readyPromise;
2073
+ closed = false;
2074
+ maxRetries;
2075
+ retryBaseDelayMs;
2076
+ poolTimeoutMs;
2077
+ autoMigrate;
2078
+ dedup;
2079
+ sql;
2080
+ // ---- lifecycle -------------------------------------------------------
2081
+ ready() {
2082
+ if (this.closed)
2083
+ return Promise.reject(
2084
+ new StorageError("This ZeroBucket instance has been closed")
2085
+ );
2086
+ this.readyPromise ??= this.init().catch((exc) => {
2087
+ this.readyPromise = void 0;
2088
+ throw exc;
2089
+ });
2090
+ return this.readyPromise;
2091
+ }
2092
+ async init() {
2093
+ if (!this.pool) {
2094
+ let mod;
2095
+ try {
2096
+ mod = await import("mysql2/promise");
2097
+ } catch (cause) {
2098
+ throw new StorageError(
2099
+ "MySQLBackend requires the 'mysql2' package. Install it with: npm install mysql2",
2100
+ { cause }
2101
+ );
2102
+ }
2103
+ const createPool = (mod.default ?? mod).createPool;
2104
+ this.pool = createPool({
2105
+ uri: normalizeUrl(this.opts.connectionString),
2106
+ connectionLimit: this.opts.poolMaxSize ?? 5,
2107
+ waitForConnections: true,
2108
+ queueLimit: 0,
2109
+ connectTimeout: this.poolTimeoutMs,
2110
+ charset: "utf8mb4",
2111
+ timezone: "Z",
2112
+ enableKeepAlive: true
2113
+ });
2114
+ }
2115
+ try {
2116
+ if (this.autoMigrate) {
2117
+ await this.runPooled("migrate", (q) => this.migrate(q), false);
2118
+ } else {
2119
+ await this.runPooled("ping", (q) => q.query("SELECT 1"), false);
2120
+ }
2121
+ } catch (exc) {
2122
+ if (this.ownsPool) {
2123
+ await this.pool.end().catch(() => {
2124
+ });
2125
+ this.pool = void 0;
2126
+ }
2127
+ throw exc instanceof StorageError ? exc : new StorageError(`Could not connect to MySQL/MariaDB: ${msg(exc)}`, {
2128
+ cause: exc
2129
+ });
2130
+ }
2131
+ }
2132
+ /**
2133
+ * Create the schema if missing, under a server-side named lock so concurrent first callers (in this
2134
+ * or any other process) run the DDL one at a time. Every step checks before it changes anything, so
2135
+ * re-running is a no-op.
2136
+ */
2137
+ async migrate(q) {
2138
+ const locked = (await q.query("SELECT GET_LOCK(?, 30) AS got", [MIGRATE_LOCK]))[0][0]?.got;
2139
+ if (locked !== 1) {
2140
+ throw new StorageError(
2141
+ "Timed out waiting for another process to finish migrating the ZeroBucket schema."
2142
+ );
2143
+ }
2144
+ try {
2145
+ if (this.dedup) {
2146
+ await this.migrateDedup(q);
2147
+ return;
2148
+ }
2149
+ const tableExists = (await q.query(
2150
+ "SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'zerobucket_images'"
2151
+ ))[0].length > 0;
2152
+ if (!tableExists) await q.query(SCHEMA3);
2153
+ const cols = new Map(
2154
+ (await q.query(
2155
+ "SELECT COLUMN_NAME AS c, IS_NULLABLE AS nullable FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'zerobucket_images'"
2156
+ ))[0].map((r) => [r.c, r.nullable])
2157
+ );
2158
+ if (!cols.has("storage_backend"))
2159
+ await q.query(
2160
+ `ALTER TABLE zerobucket_images ADD COLUMN storage_backend VARCHAR(20) NOT NULL DEFAULT '${LOCAL}'`
2161
+ );
2162
+ if (!cols.has("object_storage_bucket"))
2163
+ await q.query(
2164
+ "ALTER TABLE zerobucket_images ADD COLUMN object_storage_bucket VARCHAR(255)"
2165
+ );
2166
+ if (!cols.has("object_storage_key"))
2167
+ await q.query(
2168
+ "ALTER TABLE zerobucket_images ADD COLUMN object_storage_key VARCHAR(512)"
2169
+ );
2170
+ if (cols.get("data") === "NO")
2171
+ await q.query(
2172
+ "ALTER TABLE zerobucket_images MODIFY data LONGBLOB NULL"
2173
+ );
2174
+ const hasCheck = (await q.query(
2175
+ "SELECT 1 FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'zerobucket_images' AND CONSTRAINT_NAME = ?",
2176
+ [TIERING_CHECK]
2177
+ ))[0].length > 0;
2178
+ if (!hasCheck) {
2179
+ await q.query(
2180
+ `ALTER TABLE zerobucket_images ADD CONSTRAINT ${TIERING_CHECK} CHECK ((storage_backend = '${LOCAL}' AND data IS NOT NULL AND object_storage_bucket IS NULL AND object_storage_key IS NULL) OR (storage_backend = 'object_storage' AND data IS NULL AND object_storage_bucket IS NOT NULL AND object_storage_key IS NOT NULL))`
2181
+ );
2182
+ }
2183
+ } catch (exc) {
2184
+ throw new StorageError(`Migration failed: ${msg(exc)}`, { cause: exc });
2185
+ } finally {
2186
+ await q.query("SELECT RELEASE_LOCK(?)", [MIGRATE_LOCK]).catch(() => {
2187
+ });
2188
+ }
2189
+ }
2190
+ /** Dedup tables, created only if missing (same no-needless-DDL rule as the classic table). */
2191
+ async migrateDedup(q) {
2192
+ const have = new Set(
2193
+ (await q.query(
2194
+ "SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN ('zerobucket_blobs', 'zerobucket_image_refs')"
2195
+ ))[0].map((r) => r.t)
2196
+ );
2197
+ if (!have.has("zerobucket_blobs")) await q.query(DEDUP_BLOBS_SCHEMA);
2198
+ if (!have.has("zerobucket_image_refs")) await q.query(DEDUP_REFS_SCHEMA);
2199
+ }
2200
+ async close() {
2201
+ this.closed = true;
2202
+ const pool = this.pool;
2203
+ this.pool = void 0;
2204
+ this.readyPromise = void 0;
2205
+ if (pool && this.ownsPool) await pool.end();
2206
+ }
2207
+ // ---- execution core --------------------------------------------------
2208
+ emit(operation, start, success, error, retryCount) {
2209
+ const cb = this.opts.onOperation;
2210
+ if (!cb) return;
2211
+ try {
2212
+ cb({
2213
+ operation,
2214
+ durationMs: performance.now() - start,
2215
+ success,
2216
+ error,
2217
+ retryCount
2218
+ });
2219
+ } catch {
2220
+ }
2221
+ }
2222
+ /** Wait for a pool slot, but never longer than poolTimeoutMs. */
2223
+ acquire() {
2224
+ const pool = this.pool;
2225
+ if (this.closed || !pool)
2226
+ return Promise.reject(
2227
+ new StorageError("This ZeroBucket instance has been closed")
2228
+ );
2229
+ return new Promise((resolve, reject) => {
2230
+ let settled = false;
2231
+ const timer = setTimeout(() => {
2232
+ settled = true;
2233
+ reject(
2234
+ new PoolTimeoutError(
2235
+ `Timed out after ${this.poolTimeoutMs}ms waiting for a MySQL/MariaDB connection (poolMaxSize=${this.opts.poolMaxSize ?? 5}; all connections are in use).`
2236
+ )
2237
+ );
2238
+ }, this.poolTimeoutMs);
2239
+ pool.getConnection().then(
2240
+ (conn) => {
2241
+ if (settled) {
2242
+ conn.release();
2243
+ return;
2244
+ }
2245
+ settled = true;
2246
+ clearTimeout(timer);
2247
+ resolve(conn);
2248
+ },
2249
+ (exc) => {
2250
+ if (settled) return;
2251
+ settled = true;
2252
+ clearTimeout(timer);
2253
+ reject(exc);
2254
+ }
2255
+ );
2256
+ });
2257
+ }
2258
+ /**
2259
+ * Run `work` on a pooled connection. `tx` wraps it in a transaction. Transient failures retry the
2260
+ * WHOLE closure on a fresh connection after a full rollback.
2261
+ */
2262
+ async runPooled(operation, work, tx) {
2263
+ const start = performance.now();
2264
+ let attempt = 0;
2265
+ for (; ; ) {
2266
+ let conn;
2267
+ let destroy = false;
2268
+ try {
2269
+ conn = await this.acquire();
2270
+ if (tx) await conn.beginTransaction();
2271
+ const result = await work(conn);
2272
+ if (tx) await conn.commit();
2273
+ this.emit(operation, start, true, null, attempt);
2274
+ return result;
2275
+ } catch (exc) {
2276
+ if (conn && tx) {
2277
+ try {
2278
+ await conn.rollback();
2279
+ } catch {
2280
+ destroy = true;
2281
+ }
2282
+ }
2283
+ if (isConnectionLevel2(exc)) destroy = true;
2284
+ attempt += 1;
2285
+ if (attempt > this.maxRetries || !isRetryable2(exc)) {
2286
+ this.emit(operation, start, false, msg(exc), attempt - 1);
2287
+ throw exc;
2288
+ }
2289
+ } finally {
2290
+ if (conn) {
2291
+ if (destroy) conn.destroy();
2292
+ else conn.release();
2293
+ }
2294
+ }
2295
+ await sleep(backoffDelayMs2(attempt, this.retryBaseDelayMs));
2296
+ }
2297
+ }
2298
+ /**
2299
+ * Run `work` and return its result, emitting exactly one OperationEvent.
2300
+ *
2301
+ * connection given -> run once on it; no retry, and no commit/rollback of the caller's transaction.
2302
+ * connection absent -> pooled, retried (see runPooled).
2303
+ */
2304
+ async run(operation, connection, work, { tx = false } = {}) {
2305
+ if (connection) {
2306
+ if (!isMysqlConnection(connection)) {
2307
+ throw new TypeError(
2308
+ "MySQLBackend expects a mysql2/promise connection as `connection` (an object with query() and execute())."
2309
+ );
2310
+ }
2311
+ const start = performance.now();
2312
+ try {
2313
+ const result = tx ? await this.atomic(connection, work) : await work(connection);
2314
+ this.emit(operation, start, true, null, 0);
2315
+ return result;
2316
+ } catch (exc) {
2317
+ this.emit(operation, start, false, msg(exc), 0);
2318
+ throw exc;
2319
+ }
2320
+ }
2321
+ await this.ready();
2322
+ return this.runPooled(operation, work, tx);
2323
+ }
2324
+ /**
2325
+ * Make multi-statement work all-or-nothing on a CALLER-supplied connection.
2326
+ *
2327
+ * Is a transaction open? SAVEPOINT followed by ROLLBACK TO SAVEPOINT succeeds only inside one (in
2328
+ * autocommit mode the savepoint is gone before the next statement and the rollback fails with 1305).
2329
+ * - Open -> reuse that SAVEPOINT: a failure undoes only our work; success joins the caller's transaction.
2330
+ * - None -> START TRANSACTION and COMMIT our own, so a failure can never leave half-applied state.
2331
+ */
2332
+ async atomic(conn, work) {
2333
+ let inTransaction;
2334
+ await conn.query("SAVEPOINT zerobucket_atomic");
2335
+ try {
2336
+ await conn.query("ROLLBACK TO SAVEPOINT zerobucket_atomic");
2337
+ inTransaction = true;
2338
+ } catch (exc) {
2339
+ if (errnoOf(exc) !== 1305) throw exc;
2340
+ inTransaction = false;
2341
+ await conn.query("START TRANSACTION");
2342
+ }
2343
+ try {
2344
+ const result = await work(conn);
2345
+ await conn.query(
2346
+ inTransaction ? "RELEASE SAVEPOINT zerobucket_atomic" : "COMMIT"
2347
+ );
2348
+ return result;
2349
+ } catch (exc) {
2350
+ try {
2351
+ await conn.query(
2352
+ inTransaction ? "ROLLBACK TO SAVEPOINT zerobucket_atomic" : "ROLLBACK"
2353
+ );
2354
+ if (inTransaction)
2355
+ await conn.query("RELEASE SAVEPOINT zerobucket_atomic");
2356
+ } catch {
2357
+ }
2358
+ throw exc;
2359
+ }
2360
+ }
2361
+ // ---- StorageBackend --------------------------------------------------
2362
+ async put(row, { connection } = {}) {
2363
+ try {
2364
+ const id = randomUUID2();
2365
+ if (this.dedup) {
2366
+ await this.run(
2367
+ "put",
2368
+ connection,
2369
+ async (q) => {
2370
+ const now = mysqlNow();
2371
+ await q.execute(upsertBlobSql(1), blobParams2(row, now));
2372
+ await q.execute(D_INSERT_REF3, refParams(id, row, now));
2373
+ },
2374
+ { tx: true }
2375
+ );
2376
+ return id;
2377
+ }
2378
+ await this.run("put", connection, async (q) => {
2379
+ await q.execute(INSERT3, rowParams2(id, row, mysqlNow()));
2380
+ });
2381
+ return id;
2382
+ } catch (exc) {
2383
+ throw friendly("Failed to store image", exc);
2384
+ }
2385
+ }
2386
+ async putMany(rows, { connection } = {}) {
2387
+ if (rows.length === 0) return [];
2388
+ try {
2389
+ const ids = rows.map(() => randomUUID2());
2390
+ await this.run(
2391
+ "put_many",
2392
+ connection,
2393
+ async (q) => {
2394
+ const now = mysqlNow();
2395
+ if (this.dedup) {
2396
+ const groups = /* @__PURE__ */ new Map();
2397
+ for (const r of rows) {
2398
+ const g = groups.get(r.checksumSha256);
2399
+ if (g) g.n += 1;
2400
+ else groups.set(r.checksumSha256, { row: r, n: 1 });
2401
+ }
2402
+ for (const checksum of [...groups.keys()].sort()) {
2403
+ const g = groups.get(checksum);
2404
+ await q.execute(upsertBlobSql(g.n), blobParams2(g.row, now));
2405
+ }
2406
+ for (let i = 0; i < rows.length; i++)
2407
+ await q.execute(D_INSERT_REF3, refParams(ids[i], rows[i], now));
2408
+ return;
2409
+ }
2410
+ for (let i = 0; i < rows.length; i++)
2411
+ await q.execute(INSERT3, rowParams2(ids[i], rows[i], now));
2412
+ },
2413
+ { tx: true }
2414
+ );
2415
+ return ids;
2416
+ } catch (exc) {
2417
+ throw friendly("Failed to store image batch", exc);
2418
+ }
2419
+ }
2420
+ async get(id, { connection } = {}) {
2421
+ if (!isValidId(id)) return null;
2422
+ let row;
2423
+ try {
2424
+ row = await this.run(
2425
+ "get",
2426
+ connection,
2427
+ async (q) => (await q.query(this.sql.selectFull, [id]))[0][0]
2428
+ );
2429
+ } catch (exc) {
2430
+ throw wrap("Failed to retrieve image", exc);
2431
+ }
2432
+ return row ? this.hydrate(row, id) : null;
2433
+ }
2434
+ async getMany(ids, { connection } = {}) {
2435
+ const valid = ids.filter(isValidId);
2436
+ if (valid.length === 0) return [];
2437
+ let rows;
2438
+ try {
2439
+ rows = await this.run(
2440
+ "get_many",
2441
+ connection,
2442
+ async (q) => (await q.query(this.sql.selectMany, [valid]))[0]
2443
+ );
2444
+ } catch (exc) {
2445
+ throw wrap("Failed to retrieve image batch", exc);
2446
+ }
2447
+ return mapLimit(rows, 4, (r) => this.hydrate(r, String(r.id)));
2448
+ }
2449
+ async getMetadata(id, { connection } = {}) {
2450
+ if (!isValidId(id)) return null;
2451
+ let row;
2452
+ try {
2453
+ row = await this.run(
2454
+ "get_metadata",
2455
+ connection,
2456
+ async (q) => (await q.query(this.sql.selectMetadata, [id]))[0][0]
2457
+ );
2458
+ } catch (exc) {
2459
+ throw wrap("Failed to retrieve image metadata", exc);
2460
+ }
2461
+ if (!row) return null;
2462
+ return {
2463
+ id: String(row.id),
2464
+ mimeType: row.mime_type,
2465
+ originalFilename: row.original_filename,
2466
+ sizeBytes: row.size_bytes,
2467
+ width: row.width,
2468
+ height: row.height,
2469
+ checksumSha256: row.checksum_sha256
2470
+ };
2471
+ }
2472
+ async getStream(id, opts) {
2473
+ if (!isValidId(id)) return null;
2474
+ const { connection, chunkSize } = opts;
2475
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0)
2476
+ throw new RangeError("chunkSize must be a positive integer");
2477
+ let info;
2478
+ try {
2479
+ info = await this.run(
2480
+ "get_metadata",
2481
+ connection,
2482
+ async (q) => (await q.query(this.sql.streamInfo, [id]))[0][0]
2483
+ );
2484
+ } catch (exc) {
2485
+ throw wrap("Failed to retrieve image metadata", exc);
2486
+ }
2487
+ if (!info) return null;
2488
+ const totalSize = info.size_bytes;
2489
+ const start = opts.range?.start ?? 0;
2490
+ const end = Math.min(opts.range?.end ?? totalSize - 1, totalSize - 1);
2491
+ if (info.storage_backend === "object_storage") {
2492
+ const os = this.opts.objectStorage;
2493
+ if (!os) throw tieredWithoutStorage(id, info.object_storage_key);
2494
+ return streamFromObjectStorage(
2495
+ os,
2496
+ id,
2497
+ info.object_storage_key,
2498
+ start,
2499
+ end,
2500
+ chunkSize
2501
+ );
2502
+ }
2503
+ const self = this;
2504
+ async function* generate() {
2505
+ let offset = start;
2506
+ let delivered = 0;
2507
+ const wanted = Math.max(0, end - start + 1);
2508
+ while (delivered < wanted) {
2509
+ const length = Math.min(chunkSize, wanted - delivered);
2510
+ let row;
2511
+ try {
2512
+ row = await self.run(
2513
+ "get_stream",
2514
+ connection,
2515
+ async (q) => (await q.query(self.sql.chunk, [offset + 1, length, id]))[0][0]
2516
+ );
2517
+ } catch (exc) {
2518
+ throw wrap("Failed to stream image", exc);
2519
+ }
2520
+ if (!row) {
2521
+ throw new StorageError(
2522
+ `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.`
2523
+ );
2524
+ }
2525
+ const chunk = row.chunk;
2526
+ if (!chunk || chunk.length === 0) {
2527
+ throw new StorageError(
2528
+ `Image ${JSON.stringify(id)} ended early while streaming (delivered ${delivered} of ${wanted} bytes).`
2529
+ );
2530
+ }
2531
+ yield chunk;
2532
+ offset += chunk.length;
2533
+ delivered += chunk.length;
2534
+ }
2535
+ }
2536
+ return generate();
2537
+ }
2538
+ async delete(id, { connection } = {}) {
2539
+ if (!isValidId(id)) return false;
2540
+ if (this.dedup) return this.deleteDedup(id, connection);
2541
+ try {
2542
+ const row = await this.run(
2543
+ "delete",
2544
+ connection,
2545
+ async (q) => {
2546
+ const found = (await q.query(LOCK_ONE, [id]))[0][0];
2547
+ if (!found) return void 0;
2548
+ await q.query(DELETE_ONE2, [id]);
2549
+ return found;
2550
+ },
2551
+ { tx: true }
2552
+ );
2553
+ if (row?.storage_backend === "object_storage")
2554
+ await this.cleanupObject([row.object_storage_key], connection);
2555
+ return row !== void 0;
2556
+ } catch (exc) {
2557
+ throw wrap("Failed to delete image", exc);
2558
+ }
2559
+ }
2560
+ async deleteMany(ids, { connection } = {}) {
2561
+ const valid = [...new Set(ids.filter(isValidId))];
2562
+ if (valid.length === 0) return [];
2563
+ if (this.dedup) return this.deleteManyDedup(valid, connection);
2564
+ try {
2565
+ const rows = await this.run(
2566
+ "delete_many",
2567
+ connection,
2568
+ async (q) => {
2569
+ const found = (await q.query(LOCK_MANY, [valid]))[0];
2570
+ for (const r of found) await q.query(DELETE_ONE2, [r.id]);
2571
+ return found;
2572
+ },
2573
+ { tx: true }
2574
+ );
2575
+ await this.cleanupObject(
2576
+ rows.filter((r) => r.storage_backend === "object_storage").map((r) => r.object_storage_key),
2577
+ connection
2578
+ );
2579
+ return rows.map((r) => String(r.id));
2580
+ } catch (exc) {
2581
+ throw wrap("Failed to delete image batch", exc);
2582
+ }
2583
+ }
2584
+ async exists(id, { connection } = {}) {
2585
+ if (!isValidId(id)) return false;
2586
+ try {
2587
+ return await this.run(
2588
+ "exists",
2589
+ connection,
2590
+ async (q) => (await q.query(this.sql.exists, [id]))[0].length > 0
2591
+ );
2592
+ } catch (exc) {
2593
+ throw wrap("Failed to check image existence", exc);
2594
+ }
2595
+ }
2596
+ // ---- maintenance (CLI) -----------------------------------------------
2597
+ /** Storage statistics, or null if the tables do not exist yet (nothing is created). */
2598
+ async getInfo() {
2599
+ try {
2600
+ return await this.run("info", void 0, async (q) => {
2601
+ const need = this.dedup ? ["zerobucket_image_refs", "zerobucket_blobs"] : ["zerobucket_images"];
2602
+ const present = new Set(
2603
+ (await q.query(
2604
+ "SELECT TABLE_NAME AS t FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (?)",
2605
+ [need]
2606
+ ))[0].map((r) => r.t)
2607
+ );
2608
+ if (!need.every((t) => present.has(t))) return null;
2609
+ const j = this.dedup ? "FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256" : "FROM zerobucket_images";
2610
+ const size = this.dedup ? "b.size_bytes" : "size_bytes";
2611
+ const created = this.dedup ? "r.created_at" : "created_at";
2612
+ const mime = this.dedup ? "b.mime_type" : "mime_type";
2613
+ const tot = (await q.query(
2614
+ `SELECT COUNT(*) AS n, COALESCE(SUM(${size}), 0) AS bytes, CAST(MIN(${created}) AS CHAR) AS oldest, CAST(MAX(${created}) AS CHAR) AS newest ${j}`
2615
+ ))[0][0];
2616
+ const disk = (await q.query(
2617
+ "SELECT COALESCE(SUM(DATA_LENGTH + INDEX_LENGTH), 0) AS s FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (?)",
2618
+ [need]
2619
+ ))[0][0];
2620
+ const fmt = (await q.query(
2621
+ `SELECT ${mime} AS m, COUNT(*) AS n, COALESCE(SUM(${size}), 0) AS bytes ${j} GROUP BY ${mime} ORDER BY COUNT(*) DESC, ${mime}`
2622
+ ))[0];
2623
+ const utc = (v) => v ? `${v}+00:00` : null;
2624
+ const info = {
2625
+ mode: this.dedup ? "dedup" : "classic",
2626
+ count: Number(tot.n),
2627
+ totalBytes: Number(tot.bytes),
2628
+ oldest: utc(tot.oldest),
2629
+ newest: utc(tot.newest),
2630
+ onDisk: prettySize(Number(disk.s)),
2631
+ byFormat: fmt.map((r) => ({
2632
+ mimeType: r.m,
2633
+ count: Number(r.n),
2634
+ bytes: Number(r.bytes)
2635
+ }))
2636
+ };
2637
+ if (this.dedup) {
2638
+ const b = (await q.query(
2639
+ "SELECT COUNT(*) AS n, COALESCE(SUM(size_bytes), 0) AS bytes FROM zerobucket_blobs"
2640
+ ))[0][0];
2641
+ info.dedup = { blobs: Number(b.n), storedBytes: Number(b.bytes) };
2642
+ } else {
2643
+ const t = (await q.query(
2644
+ "SELECT COUNT(*) AS n, COALESCE(SUM(size_bytes), 0) AS bytes FROM zerobucket_images WHERE storage_backend = 'object_storage'"
2645
+ ))[0][0];
2646
+ info.tiered = { count: Number(t.n), bytes: Number(t.bytes) };
2647
+ }
2648
+ return info;
2649
+ });
2650
+ } catch (exc) {
2651
+ throw wrap("Failed to read storage info", exc);
2652
+ }
2653
+ }
2654
+ /** Ids matching the filters: oldest first, or a random sample. Used by the CLI's verify and tier. */
2655
+ async listImages(o = {}) {
2656
+ const where = [];
2657
+ const params = [];
2658
+ const created = this.dedup ? "r.created_at" : "created_at";
2659
+ if (o.minSize !== void 0) {
2660
+ where.push(`${this.dedup ? "b.size_bytes" : "size_bytes"} >= ?`);
2661
+ params.push(o.minSize);
2662
+ }
2663
+ if (o.olderThanDays !== void 0) {
2664
+ where.push(`${created} <= UTC_TIMESTAMP(6) - INTERVAL ? DAY`);
2665
+ params.push(o.olderThanDays);
2666
+ }
2667
+ if (o.onlyUntiered && !this.dedup)
2668
+ where.push(`storage_backend = '${LOCAL}'`);
2669
+ const from = this.dedup ? "FROM zerobucket_image_refs r JOIN zerobucket_blobs b ON r.checksum_sha256 = b.checksum_sha256" : "FROM zerobucket_images";
2670
+ const idCol = this.dedup ? "r.id" : "id";
2671
+ const tierCol = this.dedup ? "0 AS tiered" : "(storage_backend = 'object_storage') AS tiered";
2672
+ const order = o.sample !== void 0 ? "ORDER BY RAND()" : `ORDER BY ${created}, ${idCol}`;
2673
+ const lim = o.sample ?? o.limit;
2674
+ let sql = `SELECT ${idCol} AS id, ${tierCol} ${from}${where.length ? " WHERE " + where.join(" AND ") : ""} ${order}`;
2675
+ if (lim !== void 0) {
2676
+ if (!Number.isInteger(lim) || lim < 0)
2677
+ throw new RangeError("limit/sample must be a non-negative integer");
2678
+ sql += ` LIMIT ${lim}`;
2679
+ }
2680
+ try {
2681
+ const rows = await this.run(
2682
+ "list_images",
2683
+ void 0,
2684
+ async (q) => (await q.query(sql, params))[0]
2685
+ );
2686
+ return rows.map((r) => ({
2687
+ id: String(r.id),
2688
+ tiered: Boolean(Number(r.tiered))
2689
+ }));
2690
+ } catch (exc) {
2691
+ throw wrap("Failed to list images", exc);
2692
+ }
2693
+ }
2694
+ // ---- dedup deletes ---------------------------------------------------
2695
+ /**
2696
+ * Lock the ref row, delete it, then decrement its blob (the UPDATE takes the blob row lock, so two
2697
+ * deletes of different refs to one blob serialize instead of racing) and remove the blob once nothing
2698
+ * references it. All in one transaction: a failure can never leave a ref without its count or the reverse.
2699
+ */
2700
+ async deleteDedup(id, connection) {
2701
+ try {
2702
+ return await this.run(
2703
+ "delete",
2704
+ connection,
2705
+ async (q) => {
2706
+ const ref = (await q.query(D_LOCK_REF, [id]))[0][0];
2707
+ if (!ref) return false;
2708
+ const checksum = ref.checksum_sha256;
2709
+ await q.query(D_DELETE_REF3, [id]);
2710
+ await q.query(D_DECREMENT3, [1, checksum]);
2711
+ await q.query(D_DELETE_EMPTY3, [checksum]);
2712
+ return true;
2713
+ },
2714
+ { tx: true }
2715
+ );
2716
+ } catch (exc) {
2717
+ throw wrap("Failed to delete image", exc);
2718
+ }
2719
+ }
2720
+ async deleteManyDedup(ids, connection) {
2721
+ try {
2722
+ return await this.run(
2723
+ "delete_many",
2724
+ connection,
2725
+ async (q) => {
2726
+ const found = (await q.query(D_LOCK_REFS, [ids]))[0];
2727
+ if (found.length === 0) return [];
2728
+ for (const r of found) await q.query(D_DELETE_REF3, [r.id]);
2729
+ const counts = /* @__PURE__ */ new Map();
2730
+ for (const r of found)
2731
+ counts.set(
2732
+ r.checksum_sha256,
2733
+ (counts.get(r.checksum_sha256) ?? 0) + 1
2734
+ );
2735
+ for (const checksum of [...counts.keys()].sort()) {
2736
+ await q.query(D_DECREMENT3, [counts.get(checksum), checksum]);
2737
+ await q.query(D_DELETE_EMPTY3, [checksum]);
2738
+ }
2739
+ return found.map((r) => String(r.id));
2740
+ },
2741
+ { tx: true }
2742
+ );
2743
+ } catch (exc) {
2744
+ throw wrap("Failed to delete image batch", exc);
2745
+ }
2746
+ }
2747
+ // ---- helpers ---------------------------------------------------------
2748
+ hydrate(row, id) {
2749
+ return hydrateRow(row, id, this.opts.objectStorage);
2750
+ }
2751
+ /**
2752
+ * Remove tiered objects AFTER their rows are gone: once the row is deleted the image is correctly
2753
+ * "not found" to everyone, so a failed object delete only leaves a harmless orphan, whereas deleting
2754
+ * the object first and then failing the row delete would leave a row pointing at nothing.
2755
+ *
2756
+ * Never runs inside a caller-owned transaction (`connection`): we cannot know whether it will
2757
+ * commit. In that case the object stays until you remove it yourself after committing. Failures are
2758
+ * reported through onOperation and never fail the delete itself.
2759
+ */
2760
+ async cleanupObject(keys, connection) {
2761
+ const os = this.opts.objectStorage;
2762
+ if (!os || connection || keys.length === 0) return;
2763
+ await Promise.all(
2764
+ keys.map(async (key) => {
2765
+ const start = performance.now();
2766
+ try {
2767
+ await os.delete(key);
2768
+ this.emit("object_storage_delete", start, true, null, 0);
2769
+ } catch (exc) {
2770
+ this.emit("object_storage_delete", start, false, msg(exc), 0);
2771
+ }
2772
+ })
2773
+ );
2774
+ }
2775
+ /**
2776
+ * Move an image's bytes out of the database into object storage, replacing the row's `data` with a
2777
+ * pointer. Returns null (no such image), false (already tiered: a safe no-op, so backfills can be
2778
+ * re-run) or true (tiered just now).
2779
+ *
2780
+ * SAFETY: the upload happens INSIDE the same transaction as the row lock (SELECT ... FOR UPDATE)
2781
+ * and the UPDATE that flips the row. If the upload fails the transaction rolls back and the row is
2782
+ * untouched: there is no moment when the bytes exist nowhere, or when a row claims to be tiered
2783
+ * without a completed upload.
2784
+ *
2785
+ * TRADEOFF: InnoDB row-locks only THIS row for the duration of the upload. Concurrent writes to this
2786
+ * image wait (up to innodb_lock_wait_timeout, 50s by default); every other row is unaffected and
2787
+ * plain reads are never blocked. Meant for explicit maintenance, not hot paths.
2788
+ *
2789
+ * Retry is safe: a transient error replays the whole closure, and the deterministic key (the image
2790
+ * id) makes the re-upload an idempotent overwrite.
2791
+ */
2792
+ async tierToObjectStorage(id, { connection } = {}) {
2793
+ if (this.dedup) {
2794
+ throw new StorageError(
2795
+ "tierToObjectStorage() is not supported in dedup mode (a blob may be shared by many images)."
2796
+ );
2797
+ }
2798
+ const os = this.opts.objectStorage;
2799
+ if (!os) {
2800
+ throw new StorageError(
2801
+ "tierToObjectStorage() requires objectStorage to be configured (new ZeroBucket({ objectStorage: new ObjectStorage({ bucket }) }))."
2802
+ );
2803
+ }
2804
+ if (!isValidId(id)) return null;
2805
+ const key = id.toLowerCase();
2806
+ try {
2807
+ return await this.run(
2808
+ "tier_to_object_storage",
2809
+ connection,
2810
+ async (q) => {
2811
+ const row = (await q.query(SELECT_FOR_TIERING3, [id]))[0][0];
2812
+ if (!row) return null;
2813
+ if (row.storage_backend !== LOCAL) return false;
2814
+ await os.upload(key, row.data, { mimeType: row.mime_type });
2815
+ await q.query(UPDATE_AFTER_TIERING3, [os.bucket, key, mysqlNow(), id]);
2816
+ return true;
2817
+ },
2818
+ { tx: true }
2819
+ );
2820
+ } catch (exc) {
2821
+ throw wrap("Failed to tier image to object storage", exc);
2822
+ }
2823
+ }
2824
+ };
2825
+ function blobParams2(r, now) {
2826
+ return [
2827
+ r.checksumSha256,
2828
+ r.data,
2829
+ r.mimeType,
2830
+ r.sizeBytes,
2831
+ r.width,
2832
+ r.height,
2833
+ now
2834
+ ];
2835
+ }
2836
+ function refParams(id, r, now) {
2837
+ return [id, r.checksumSha256, r.originalFilename, now, now];
2838
+ }
2839
+ function rowParams2(id, r, now) {
2840
+ return [
2841
+ id,
2842
+ r.data,
2843
+ r.mimeType,
2844
+ r.originalFilename,
2845
+ r.sizeBytes,
2846
+ r.width,
2847
+ r.height,
2848
+ r.checksumSha256,
2849
+ now,
2850
+ now
2851
+ ];
2852
+ }
2853
+
1883
2854
  // src/heic.ts
1884
2855
  import { createRequire } from "module";
1885
2856
  import { join } from "path";
@@ -2268,9 +3239,14 @@ var ZeroBucket = class _ZeroBucket {
2268
3239
  beforeGet;
2269
3240
  beforePut;
2270
3241
  constructor(options = {}) {
2271
- if (options.sqlite !== void 0 && (options.connectionString || options.pool)) {
3242
+ const chosen = [
3243
+ options.sqlite !== void 0 && "`sqlite`",
3244
+ (options.mysql !== void 0 || options.mysqlPool) && "`mysql`/`mysqlPool`",
3245
+ (options.connectionString || options.pool) && "`connectionString`/`pool`"
3246
+ ].filter(Boolean);
3247
+ if (chosen.length > 1) {
2272
3248
  throw new TypeError(
2273
- "Choose one database: `sqlite` OR `connectionString`/`pool`, not both."
3249
+ `Choose one database: ${chosen.join(" OR ")}, not several.`
2274
3250
  );
2275
3251
  }
2276
3252
  this.backend = options.backend ?? (options.sqlite !== void 0 ? new SQLiteBackend({
@@ -2279,6 +3255,18 @@ var ZeroBucket = class _ZeroBucket {
2279
3255
  dedup: options.dedup,
2280
3256
  objectStorage: options.objectStorage,
2281
3257
  onOperation: options.onOperation
3258
+ }) : options.mysql !== void 0 || options.mysqlPool ? new MySQLBackend({
3259
+ connectionString: options.mysql,
3260
+ pool: options.mysqlPool,
3261
+ autoMigrate: options.autoMigrate,
3262
+ maxRetries: options.maxRetries,
3263
+ retryBaseDelayMs: options.retryBaseDelayMs,
3264
+ poolMinSize: options.poolMinSize,
3265
+ poolMaxSize: options.poolMaxSize,
3266
+ poolTimeoutMs: options.poolTimeoutMs,
3267
+ onOperation: options.onOperation,
3268
+ objectStorage: options.objectStorage,
3269
+ dedup: options.dedup
2282
3270
  }) : new PostgresBackend({
2283
3271
  connectionString: options.connectionString,
2284
3272
  pool: options.pool,
@@ -2879,6 +3867,7 @@ export {
2879
3867
  ImageNotFoundError,
2880
3868
  ImageTooLargeError,
2881
3869
  ImageValidationError,
3870
+ MySQLBackend,
2882
3871
  ObjectStorage,
2883
3872
  PDFValidator,
2884
3873
  PostgresBackend,