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/README.md +167 -20
- package/dist/bin.js +2506 -0
- package/dist/{client-C_W0t8My.d.cts → client-C7xs1dlr.d.cts} +159 -5
- package/dist/{client-C_W0t8My.d.ts → client-C7xs1dlr.d.ts} +159 -5
- package/dist/http.d.cts +1 -1
- package/dist/http.d.ts +1 -1
- package/dist/index.cjs +1639 -134
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +203 -56
- package/dist/index.d.ts +203 -56
- package/dist/index.js +1635 -132
- package/dist/index.js.map +1 -1
- package/package.json +26 -4
package/README.md
CHANGED
|
@@ -10,18 +10,21 @@ This is the Node.js/TypeScript sibling of the [Python package](https://pypi.org/
|
|
|
10
10
|
**It uses the exact same table**, so a Node service and a Python service can share one database
|
|
11
11
|
and read each other's images.
|
|
12
12
|
|
|
13
|
-
> **Status: 0.
|
|
14
|
-
>
|
|
13
|
+
> **Status: early (0.5.x).** PostgreSQL **and SQLite**, each in classic and dedup modes, with S3-compatible
|
|
14
|
+
> object-storage tiering and a `zerobucket` command line tool. MySQL and HEIC are on the roadmap
|
|
15
|
+
> (see [What's not here yet](#whats-not-here-yet)).
|
|
15
16
|
|
|
16
17
|
## Install
|
|
17
18
|
|
|
18
19
|
```bash
|
|
19
|
-
npm install zerobucket pg sharp
|
|
20
|
+
npm install zerobucket pg sharp # PostgreSQL
|
|
21
|
+
npm install zerobucket better-sqlite3 sharp # or SQLite (see below): no database server at all
|
|
20
22
|
```
|
|
21
23
|
|
|
22
|
-
`pg` (the Postgres driver) and `sharp` (image decoding/optimizing) are peer dependencies, so you
|
|
24
|
+
`pg` (the Postgres driver), `better-sqlite3` (SQLite) and `sharp` (image decoding/optimizing) are peer dependencies, so you
|
|
23
25
|
control their versions. If you only store PDFs through a custom validator, `sharp` is not needed.
|
|
24
|
-
|
|
26
|
+
For [object-storage tiering](#object-storage-tiering) also install `@aws-sdk/client-s3` (optional; loaded only when used).
|
|
27
|
+
Requires Node 20+ (SQLite needs Node 22+, see below). Ships ESM and CommonJS with full types.
|
|
25
28
|
|
|
26
29
|
## Quick start
|
|
27
30
|
|
|
@@ -151,6 +154,10 @@ try {
|
|
|
151
154
|
}
|
|
152
155
|
```
|
|
153
156
|
|
|
157
|
+
Multi-statement operations (`putMany`, dedup `put`/`delete`, tiering) are **atomic even on a bare `pg.Client`
|
|
158
|
+
with no open transaction**: ZeroBucket opens its own, or uses a `SAVEPOINT` inside yours so a failure rolls back only
|
|
159
|
+
its own work and leaves your transaction usable.
|
|
160
|
+
|
|
154
161
|
## Batches
|
|
155
162
|
|
|
156
163
|
`putMany` / `getMany` / `deleteMany` are best-effort per item (one bad file doesn't abort the rest):
|
|
@@ -170,6 +177,37 @@ await images.put(pdfBuf, { validator: new PDFValidator() }); // any ContentValid
|
|
|
170
177
|
Optimize strips metadata, applies EXIF orientation first, never upscales, and re-validates its own
|
|
171
178
|
output. Implement `ContentValidator` (`validate(data, { maxBytes })`) to store other content types.
|
|
172
179
|
|
|
180
|
+
## Command line
|
|
181
|
+
|
|
182
|
+
The package installs a `zerobucket` command (`npx zerobucket ...`, or install globally with `npm i -g zerobucket`).
|
|
183
|
+
It has the same commands, flags, messages and exit codes as the Python package's CLI, and additionally works with
|
|
184
|
+
**SQLite** and **dedup mode**, and understands images that were tiered to object storage.
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
export ZEROBUCKET_DATABASE_URL=postgresql://user:pass@localhost/mydb # or: --database-url URL
|
|
188
|
+
# SQLite instead: export ZEROBUCKET_SQLITE_PATH=./images.db # or: --sqlite PATH
|
|
189
|
+
|
|
190
|
+
zerobucket init # create the schema (add --dedup for the dedup tables)
|
|
191
|
+
zerobucket info # image count, sizes, on-disk size, breakdown by format (+ dedup savings / tiered count)
|
|
192
|
+
zerobucket verify # re-checksum every image; exit 1 and list the ids if anything is corrupted
|
|
193
|
+
zerobucket verify --sample 200 # ...or just a random sample (good for a nightly cron job)
|
|
194
|
+
zerobucket tier IMAGE_ID --bucket my-images # move one image to S3
|
|
195
|
+
zerobucket tier --older-than 90 --min-size 500000 --bucket my-images --dry-run # preview a bulk move
|
|
196
|
+
zerobucket tier --all --limit 1000 --bucket my-images --endpoint-url https://<acct>.r2.cloudflarestorage.com
|
|
197
|
+
zerobucket migrate --to-dedup # PostgreSQL: copy classic images into the dedup tables (non-destructive, re-runnable)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
- **Exit codes:** `0` success, `1` problems found or an operation failed, `2` usage or connection error. That makes
|
|
201
|
+
`zerobucket verify && deploy` and cron/CI checks work as you would hope.
|
|
202
|
+
- `info` and `verify` never create anything: looking at a database that does not exist (or has no schema yet) reports it
|
|
203
|
+
and exits 1 instead of silently creating an empty one.
|
|
204
|
+
- `verify` checksums one image at a time (memory stays flat on big tables). Images tiered to object storage are
|
|
205
|
+
skipped with a note unless you also pass `--bucket` (and credentials), in which case they are downloaded and verified too.
|
|
206
|
+
- `tier` processes images one at a time and reports each failure; a failed upload leaves that image untouched in the database.
|
|
207
|
+
Credentials come from the AWS SDK's standard chain, or `--aws-access-key-id` / `--aws-secret-access-key`.
|
|
208
|
+
- `tier` is not available with `--dedup`. `tier`, and `verify --bucket`, need `@aws-sdk/client-s3`; every other command works without it.
|
|
209
|
+
- The same operations are available from code: `new ZeroBucket({...}).tierToObjectStorage(id)`, `migrateClassicToDedup()`, etc.
|
|
210
|
+
|
|
173
211
|
## Reliability and observability
|
|
174
212
|
|
|
175
213
|
- Pooling: `poolMinSize` (1), `poolMaxSize` (5), `poolTimeoutMs` (10000), or pass your own `pool`
|
|
@@ -183,6 +221,109 @@ output. Implement `ContentValidator` (`validate(data, { maxBytes })`) to store o
|
|
|
183
221
|
operation (and once per chunk when streaming). Exceptions in your callback are swallowed.
|
|
184
222
|
- The schema migration is serialized with an advisory lock, so many processes starting at once is safe.
|
|
185
223
|
|
|
224
|
+
## SQLite
|
|
225
|
+
|
|
226
|
+
No database server at all: one file. Ideal for small apps, single-server deployments, desktop/Electron apps, tests and prototypes.
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
const images = new ZeroBucket({ sqlite: "./images.db" }); // npm install better-sqlite3
|
|
230
|
+
// ZeroBucket({ sqlite: ":memory:" }) for a throwaway in-process database
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Everything in this README works on SQLite, **including dedup (`dedup: true`), object-storage tiering, streaming and
|
|
234
|
+
byte ranges, hooks, the HTTP handler, optimize and validators**. The file format is identical to the Python
|
|
235
|
+
package's `SQLiteBackend`, so a Node app and a Python app can share one `.db` file (verified in both directions, including
|
|
236
|
+
tiering and dedup reference counts, by the conformance harness).
|
|
237
|
+
|
|
238
|
+
How it behaves in Node, and why:
|
|
239
|
+
|
|
240
|
+
- **Synchronous driver, event loop kept free.** `better-sqlite3` is synchronous (a local file read is microseconds). Lock
|
|
241
|
+
contention is the exception, and ZeroBucket never lets the driver sleep on a lock, which would freeze your whole server.
|
|
242
|
+
Each attempt waits ~25 ms; a `SQLITE_BUSY` is retried with async sleeps up to `busyTimeoutMs` (default 10 s, set via
|
|
243
|
+
`new ZeroBucket({ backend: new SQLiteBackend({ path, busyTimeoutMs }) })`), then fails with a clear `StorageError`.
|
|
244
|
+
A test holds the write lock from a second process and asserts the event loop keeps ticking while ZeroBucket waits.
|
|
245
|
+
- **One connection, no interleaving.** Each operation is a single synchronous `BEGIN IMMEDIATE ... COMMIT`, so concurrent
|
|
246
|
+
requests can never run inside each other's transaction. WAL mode is set once, and only if the file is not already WAL.
|
|
247
|
+
- **Many processes, one new file** is safe (tested with 8 processes opening a fresh database simultaneously).
|
|
248
|
+
- **Tiering locks the whole database** for the duration of the upload (SQLite has no row locks): other processes' writes
|
|
249
|
+
wait, this process's writes queue, reads are never blocked. It uses its own connection, so `tierToObjectStorage` does not
|
|
250
|
+
accept `connection`, and it needs a real file (not `:memory:`). The safety guarantee is unchanged: a failed upload
|
|
251
|
+
rolls back and leaves the row untouched.
|
|
252
|
+
- **`connection`** takes your own `better-sqlite3` `Database`. Multi-statement operations use a `SAVEPOINT`, so they
|
|
253
|
+
are atomic whether or not you have an open transaction.
|
|
254
|
+
- **Streaming** uses ranged `substr()` reads, so a delete mid-stream raises `StorageError` (like Postgres). SQLite still
|
|
255
|
+
reads the whole blob per chunk, in native memory: this bounds Node-side memory only.
|
|
256
|
+
- **Node 22+ for SQLite.** `better-sqlite3` 13 requires Node 22 or newer and crashes on older versions. It ships its Windows,
|
|
257
|
+
macOS and Linux binaries inside the npm package, so no compiler or Visual Studio is needed. Postgres users can stay on Node 20.
|
|
258
|
+
(`better-sqlite3` 12 declares Node 20 support, but it is untested here.)
|
|
259
|
+
- Not available on SQLite: `migrateClassicToDedup()` (Python has it for Postgres only, too).
|
|
260
|
+
|
|
261
|
+
## Deduplication
|
|
262
|
+
|
|
263
|
+
Store identical bytes once. In dedup mode every `put()` still returns its own id and keeps its own filename,
|
|
264
|
+
but images with the same content share a single stored blob with a reference count (think: the same logo or default
|
|
265
|
+
avatar uploaded a thousand times).
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
const images = new ZeroBucket({ connectionString, dedup: true });
|
|
269
|
+
const a = await images.put(logo, { filename: "a.png" });
|
|
270
|
+
const b = await images.put(logo, { filename: "b.png" }); // different id, same blob: ref_count = 2
|
|
271
|
+
await images.delete(a); // blob stays: ref_count = 1
|
|
272
|
+
await images.delete(b); // last reference gone: blob removed
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
- Uses separate tables (`zerobucket_blobs` + `zerobucket_image_refs`, identical to the Python package), so dedup and
|
|
276
|
+
classic data can never be confused. A Node and a Python dedup app share one database and one set of blobs.
|
|
277
|
+
- Reference counts are exact under concurrency: 20 simultaneous `put()`s of the same bytes give `ref_count == 20`, and a
|
|
278
|
+
`put()` racing the delete of the last reference never loses or leaks the blob (both are tested).
|
|
279
|
+
- Batches (`putMany`, `deleteMany`) take their blob locks in sorted checksum order, so overlapping batches in
|
|
280
|
+
opposite orders cannot deadlock each other.
|
|
281
|
+
- Everything else works unchanged: hooks, streaming, ranges, the HTTP handler, optimize, validators, metrics, retry.
|
|
282
|
+
- Dedup **cannot be combined with `objectStorage`** (a shared blob has many owners), same rule as Python.
|
|
283
|
+
|
|
284
|
+
**Moving existing data in:** `await images.migrateClassicToDedup()` copies every classic image into the dedup tables,
|
|
285
|
+
keeping each id, and never modifies the classic table. It runs in small batches (bounded memory), is safe to re-run
|
|
286
|
+
(already-migrated ids are skipped and counted), and refuses up front if any classic image is tiered to object storage.
|
|
287
|
+
|
|
288
|
+
## Object-storage tiering
|
|
289
|
+
|
|
290
|
+
For the minority of apps whose image volume outgrows what is economical to keep in a database
|
|
291
|
+
(backups, replication lag, per-GB price), move individual images to any S3-compatible store (AWS S3, MinIO,
|
|
292
|
+
Cloudflare R2, Backblaze B2, DigitalOcean Spaces). It is **explicit and opt-in**: `put()` never tiers
|
|
293
|
+
anything by itself, and nothing changes for you until you configure it.
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
import { ZeroBucket, ObjectStorage } from "zerobucket";
|
|
297
|
+
|
|
298
|
+
const images = new ZeroBucket({
|
|
299
|
+
connectionString: process.env.DATABASE_URL,
|
|
300
|
+
objectStorage: new ObjectStorage({ bucket: "my-images" }), // bucket must already exist
|
|
301
|
+
// endpoint: "https://<account>.r2.cloudflarestorage.com", region: "auto" // for non-AWS stores
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
await images.tierToObjectStorage(id); // true = moved now, false = already tiered (safe to re-run a backfill)
|
|
305
|
+
await images.get(id); // unchanged: get / getMany / getStream / HTTP handler all read transparently
|
|
306
|
+
await images.delete(id); // removes the row, then the object
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
- **Safe by construction.** The upload runs _inside_ the database transaction that locks the row. If it fails,
|
|
310
|
+
the transaction rolls back and the row is left byte-for-byte untouched: there is never a moment when the bytes
|
|
311
|
+
exist nowhere, or when a row claims to be tiered without a finished upload.
|
|
312
|
+
- **Real range requests.** Tiered images stream with genuine S3 `Range` GETs, so a `bytes=1000-1999` request fetches
|
|
313
|
+
exactly those bytes (strictly better than the Postgres `substring()` approach).
|
|
314
|
+
- **Locking tradeoff.** The row lock is held for the whole upload, so concurrent _writes to that one image_ wait. Other
|
|
315
|
+
rows and plain reads are never blocked. Treat tiering as a maintenance operation, not a request-path call.
|
|
316
|
+
- **Integrity checks.** A tiered object whose size no longer matches the database, or a missing/short object, raises
|
|
317
|
+
`StorageError`. It never returns wrong data and never silently truncates a stream.
|
|
318
|
+
- **Same keys as Python.** Objects are named by the image's UUID with no prefix, so the Node and Python packages
|
|
319
|
+
can read, tier and delete each other's objects in one bucket (verified by the conformance harness).
|
|
320
|
+
- **Deleting inside your own transaction** (`delete(id, { connection })`) deliberately does **not** remove the
|
|
321
|
+
object: we cannot know whether your transaction will commit, and deleting early would turn a rollback into data
|
|
322
|
+
loss. After you commit, remove it yourself with `objectStorage.delete(id)`.
|
|
323
|
+
- Failures to remove an object after a normal delete never fail the delete (the row is already gone); they are
|
|
324
|
+
reported through `onOperation` as `object_storage_delete` events.
|
|
325
|
+
- Credentials come from the AWS SDK's standard chain (env vars, shared config, IAM role) or `credentials: {...}`.
|
|
326
|
+
|
|
186
327
|
## Shared database with the Python package
|
|
187
328
|
|
|
188
329
|
Same table (`zerobucket_images`), same checksum (SHA-256 hex of the stored bytes), same tiering
|
|
@@ -192,27 +333,33 @@ same corpus of valid and corrupt files identically.
|
|
|
192
333
|
|
|
193
334
|
## Differences from the Python package
|
|
194
335
|
|
|
195
|
-
|
|
|
196
|
-
|
|
|
197
|
-
| API
|
|
198
|
-
| Malformed id (`"abc"`)
|
|
199
|
-
| `optimize`
|
|
200
|
-
| `putMany` inserts
|
|
201
|
-
| Formats
|
|
202
|
-
| Event duration
|
|
203
|
-
|
|
|
336
|
+
| | Python | npm |
|
|
337
|
+
| ---------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
338
|
+
| API | sync + async clients | one async client |
|
|
339
|
+
| Malformed id (`"abc"`) | `StorageError` from Postgres | treated as not found (`ImageNotFoundError`, no DB round trip), friendlier for `/images/:id` routes |
|
|
340
|
+
| `optimize` | Pillow; EXIF stripped, not applied | sharp; EXIF **applied then stripped**; transparency → **white** for JPEG |
|
|
341
|
+
| `putMany` inserts | pipelined | one transaction, statements run sequentially |
|
|
342
|
+
| Formats | JPEG, PNG, WebP, HEIC (extra) | JPEG, PNG, WebP (HEIC not yet) |
|
|
343
|
+
| Event duration | `duration_seconds` | `durationMs` |
|
|
344
|
+
| `migrateClassicToDedup` | loads the whole table into memory; fails if re-run or if any row is tiered | batched, safe to re-run, refuses tiered rows with a clear message |
|
|
345
|
+
| Dedup `putMany` / `deleteMany` locking | arbitrary order (overlapping batches can deadlock) | sorted checksum order (cannot deadlock) |
|
|
346
|
+
| SQLite API | synchronous `SQLiteBackend` + separate async backend | one async client; the sync driver runs on the event loop, lock waits are async (never block it) |
|
|
347
|
+
| SQLite `onOperation` / busy retry | none | `onOperation` events and async `SQLITE_BUSY` retry (`busyTimeoutMs`) |
|
|
348
|
+
| SQLite stream deleted mid-read | sync adapter keeps reading a WAL snapshot (async adapter raises) | raises `StorageError`, like Postgres; use `connection` in a transaction for a snapshot |
|
|
349
|
+
| CLI | PostgreSQL, classic mode only; `verify` crashes on tiered rows | PostgreSQL **and** SQLite, classic **and** dedup; `info`/`verify` understand tiered rows; `migrate --to-dedup` |
|
|
350
|
+
| `connection=` without an open transaction | multi-statement ops rely on the driver's implicit transaction | always atomic (own transaction or savepoint) |
|
|
351
|
+
| `delete(id, connection=...)` on a tiered image | deletes the S3 object immediately | leaves the object until you delete it after commit (a rolled-back transaction can never lose data) |
|
|
352
|
+
| S3 delete failure after `delete()` | raises after the row is gone | never fails the delete; reported via `onOperation` |
|
|
353
|
+
| Options | snake_case kwargs | camelCase options object |
|
|
204
354
|
|
|
205
355
|
## What's not here yet
|
|
206
356
|
|
|
207
|
-
Planned, in order:
|
|
208
|
-
|
|
209
|
-
(never wrong data), and **deleting** such a row from Node removes the database row but leaves the S3
|
|
210
|
-
object behind (the same documented orphan behaviour as Python without `object_storage`).
|
|
211
|
-
Delete tiered images from Python if you use tiering.
|
|
357
|
+
Planned, in order: **MySQL/MariaDB** and **HEIC**.
|
|
358
|
+
Tiering and dedup cannot be combined (same rule as the Python package).
|
|
212
359
|
|
|
213
360
|
## Runtime notes
|
|
214
361
|
|
|
215
|
-
Node 20
|
|
362
|
+
Node 20+ for Postgres, Node 22+ for SQLite. Bun/Deno: expected to work, not yet tested. Edge runtimes (Cloudflare Workers, Vercel Edge) cannot open raw
|
|
216
363
|
Postgres TCP connections through `pg` without a proxy such as Hyperdrive; use the Node runtime for these routes.
|
|
217
364
|
In serverless, keep `poolMaxSize` small (1-2) or inject a pool shared across invocations.
|
|
218
365
|
|