defuss-dbsonl 0.0.0-stage → 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/ARCH.md +69 -0
- package/CHANGELOG.md +56 -0
- package/LICENSE +21 -0
- package/README.md +130 -2
- package/dist/backend-CU4f3EUz.cjs +82 -0
- package/dist/backend-c-pjfpXZ.mjs +76 -0
- package/dist/browser.cjs +42 -0
- package/dist/browser.d.cts +20 -0
- package/dist/browser.d.mts +20 -0
- package/dist/browser.mjs +40 -0
- package/dist/common-0JC30Xiv.mjs +38 -0
- package/dist/common-2ybGl1zj.cjs +48 -0
- package/dist/index.cjs +1309 -0
- package/dist/index.d.cts +182 -0
- package/dist/index.d.mts +182 -0
- package/dist/index.mjs +1306 -0
- package/dist/server.cjs +288 -0
- package/dist/server.d.cts +12 -0
- package/dist/server.d.mts +12 -0
- package/dist/server.mjs +285 -0
- package/dist/types-B_SuDjVq.d.cts +128 -0
- package/dist/types-B_SuDjVq.d.mts +128 -0
- package/docs/API.md +85 -0
- package/docs/FORMAT.md +66 -0
- package/docs/PERFORMANCE.md +170 -0
- package/examples/ARCH.md +5 -0
- package/examples/basic.ts +13 -0
- package/examples/transaction.ts +14 -0
- package/package.json +81 -4
package/ARCH.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
VERIFIED: DBSONL separates a portable transactional engine from byte storage and coordination. DSON owns serialization and frame CRC32C checks. Storage owns bounded writes and portable byte I/O; the native connection adds bounded positional reads of immutable committed data. DBSONL owns immutable indexing, commit ordering, snapshot lifetime and reclamation.
|
|
4
|
+
|
|
5
|
+
```mermaid
|
|
6
|
+
flowchart TD
|
|
7
|
+
A[Batch or transaction] --> B[Commit lock]
|
|
8
|
+
B --> C[Append values and index paths]
|
|
9
|
+
C --> D[Flush generation]
|
|
10
|
+
D --> E[Publish head slot]
|
|
11
|
+
E --> F[Committed root]
|
|
12
|
+
F --> G[Snapshot generation pin]
|
|
13
|
+
G --> H[Immutable page reads]
|
|
14
|
+
F --> I[Copy live values]
|
|
15
|
+
I --> J[Publish packed generation]
|
|
16
|
+
J --> K[Collect unpinned generations]
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Why this design
|
|
20
|
+
|
|
21
|
+
VERIFIED: A persistent B+tree avoids a database-sized RAM map without requiring a second database dependency. Fanout 32 trades modest page sizes for logarithmic tree navigation. Values are separate DSON frames; pages contain only keys, references and revisions. Rewriting a path rather than mutating it gives readers stable roots with no undo log. A batch coalesces edits in private dirty nodes and persists each final dirty page once, avoiding unobservable intermediate roots. An edit whose path is already dirty or cached runs synchronously; only a page read awaits. A bounded cache stores decoded pages, never application values. It evicts by second chance: a hit only marks its page, and eviction moves a marked page to the back once. Exact LRU reordered the Map on every hit, about 5% of a memory commit. Index pages are written by `encodePage`, which produces the same frames as `encodeFrame` in trusted mode about 30% faster because it knows the few property names pages use. A commit edits cached copies of the pages on its paths instead of rereading them, and adds the pages it wrote once their root is published; a page address within a generation never changes meaning, because only an unpublished tail is ever rewritten. Open reads constant-size metadata and generation length, not every value.
|
|
22
|
+
|
|
23
|
+
VERIFIED: A two-slot manifest avoids relying on atomic rename, which Storage and OPFS do not expose uniformly. Each slot is a checksummed DSON frame in a 4096-byte region. The newest valid publication wins. Writers append after the published end, flush, then replace the older slot. A partial slot is ignored. An empty head whose generations are all empty is an interrupted create: only `create: true` initializes it, because no slot was published; invalid fields in a checksummed slot, a missing referenced generation or committed truncation fail closed. A failed publication reports `COMMIT_UNCERTAIN`; reread the revision before retrying. Successful publication increments the logical revision once per nonempty batch.
|
|
24
|
+
|
|
25
|
+
VERIFIED: These choices spend extra write bandwidth on index paths and two small metadata writes during compaction. They remove full replay and read-held writer exclusion. Benchmark evidence separates batch and per-record flush workloads rather than treating them as equivalent. A universal Pareto-optimality claim would require a defined workload distribution and objective function.
|
|
26
|
+
|
|
27
|
+
## Ownership and lock order
|
|
28
|
+
|
|
29
|
+
VERIFIED: The commit lock serializes head inspection and publication. A snapshot takes a shared generation pin while holding that lock, then releases the commit lock. While a handle's own commit group holds the lock, that handle pins the group's last flushed head instead: nobody else can publish or collect then, and the group releases the lock only after those pins are granted. Readers therefore never see a head before its flush. Portable reads acquire short I/O locks because Storage 0.3 and OPFS grant exclusive handle ownership. Native reads use independent read-only descriptors: committed prefixes are immutable, writers truncate only unpublished tails, and the pin prevents removal. A native snapshot therefore reads concurrently with appends. The lifetime of a read session does not reserve the commit lock.
|
|
30
|
+
|
|
31
|
+
VERIFIED: Native locks are separate whole-file locks scoped to open descriptions/handles; they do not expire with a clock or heartbeat. A paused process cannot lose ownership to a second writer. The kernel releases ownership on process death. Web Locks release when their worker/context dies. Memory coordination is instance-local. Raw Storage writes and unrelated processes ignoring the protocol are outside the ownership contract.
|
|
32
|
+
|
|
33
|
+
VERIFIED: Acquisition order is commit lock, generation pin, I/O lock. Snapshot readers use their pin and, for portable adapters, short I/O locks without reacquiring the commit lock. A direct `get()` holds the commit lock until its bounded lookup finishes, which also excludes collection without a separate snapshot pin. Compaction pins both its source and candidate generation before releasing the commit lock. It writes only the candidate and reads the source in short operations. Publication compares the original publication number, so even another compaction causes a conflict. Exclusive compaction keeps the commit lock through the copy for guaranteed progress.
|
|
34
|
+
|
|
35
|
+
VERIFIED: Commits queued on one handle form a group: the next lock holder checks every member in queue order, appends all of their values and pages with one writer, flushes the generation once and publishes one head. Each member keeps its own revision, so the group equals sequential commits that no reader observed in between. A group is capped by one batch's operation and byte budgets; any failure before publication retries its members one at a time, so one member cannot fail another. The alternative, one publication per commit, paid two flushes per commit: with four writers on Node under macOS, about 8 ms per commit. Grouping cuts the flushes per commit; the cost is that a member waits for the slowest check in its group.
|
|
36
|
+
|
|
37
|
+
VERIFIED: A forming group first sets the head that new snapshots pin, then waits while transactions on its handle hold a snapshot but have not queued their commit, waking on every arrival, for at most half the previous group's publication time. Without the wait, four transaction writers on one handle alternated between groups of one and three members, because the writer released first committed again while the other three were still in the next group; on Node under macOS that cost 4.4 ms per commit, and the wait brought it to 2.1 ms in full groups of four. A transaction that outlasts one wait is not waited for again, and a writer with no transaction in flight never waits. An earlier variant waited before setting the pinned head, so snapshots that started during its wait queued behind the lock it held; it measured slower and was dropped.
|
|
38
|
+
|
|
39
|
+
VERIFIED: A transaction checks the revisions of the keys it read, not the database revision. The commit lock makes the check and publication atomic, so every read is still current at the commit point and the transactions serialize in commit order. Absence is recorded as revision 0, so a key that appears is a conflict. Scans fall back to the database revision, because a range cannot be rechecked without listing what was absent. The whole-database check it replaced rejected disjoint writers: four writers on separate keys retried 1.5 to 2.1 times per commit.
|
|
40
|
+
|
|
41
|
+
## Native read and write performance
|
|
42
|
+
|
|
43
|
+
VERIFIED: Every database handle owns a connection with at most two idle read descriptors and at most eight idle lock descriptors, one per lock name: normally the commit lock, the I/O locks of the head and the current generation, and its pin. Reopening a lock file cost about 60 µs on macOS, three times per transaction. Only an unlocked descriptor is reused, so simultaneous owners still hold distinct open file descriptions and flock keeps them apart. In-flight reads retain their descriptors until completion. Local FIFO admission avoids polling for same-connection commit-lock contention; separate processes still acquire the same kernel lock. Every lock attempt uses the nonblocking call of the shipped N-API binding of pinned `@lickle/lock` 0.0.1. No blocking lock acquisition or timeout-based ownership is introduced.
|
|
44
|
+
|
|
45
|
+
VERIFIED: `get()` reads the current head under the commit lock on every call. It can overlap this with a lookup through the previously parsed root. That candidate is accepted only if every head byte is unchanged; otherwise it is discarded and the current root is read. Both branches are drained before releasing the lock, including on errors. Native connections read that 8 KiB manifest with a blocking call even when values use asynchronous I/O: every operation reads it, it stays in the page cache, and a blocking read of it took 0.4 to 0.6 µs against 9 to 18 µs for a thread-pool round trip. A cold manifest blocks the event loop for one 8 KiB read. A per-handle 8 KiB parse cache avoids repeated DSON decoding, not fresh I/O; publication patches in the slot it wrote, so the writer's next read of its own head needs no decode. Aligned comparisons use 32-bit words; measured manual unrolling was not retained because it regressed Node.
|
|
46
|
+
|
|
47
|
+
VERIFIED: Known-length record references are checked against both committed end and the record budget before allocation. Native reads then fetch and checksum the complete frame. Values are decoded anew for every point lookup. Each native scan or compaction keeps one read-ahead window of at most 64 KiB within its pinned prefix. Large values bypass that window. The writer buffers at most 64 KiB, drains it before the file flush, and only then publishes the head, so buffering never reorders data ahead of publication.
|
|
48
|
+
|
|
49
|
+
VERIFIED: Native read descriptors do not participate in Storage's exclusive handle registry. This is limited to regular, read-only files and the DBSONL immutability protocol; mutations still use Storage and its I/O lock. `collect()` unlinks unpinned files and closes its connection's idle reader and idle pin and I/O lock descriptors for each removed generation, so no descriptor of an unlinked lock file is reused. Another idle process may still hold an unlinked descriptor until eviction or database close; OS disk-space release can therefore lag namespace removal. Closing all idle database handles releases those resources. Replacing live head or generation inodes outside this protocol is unsupported.
|
|
50
|
+
|
|
51
|
+
## Reclamation and crashes
|
|
52
|
+
|
|
53
|
+
VERIFIED: Compaction copies live values with a streaming bulk builder that retains at most 32 references per level. It writes both head slots to the new generation before returning. Collection refreshes the alternate slot to the selected head, then tries exclusive pins on obsolete generations. Busy generations remain. Candidate pins protect a concurrent compactor from collection. Abandoned candidates from killed processes become collectible.
|
|
54
|
+
|
|
55
|
+
VERIFIED: Native lock files for reclaimed generations are removed while the commit lock excludes new pin creation. The current generation and fixed database locks remain. This prevents an inode replacement race between old and new lock owners. Cleanup requires exclusive ownership; there are no age-based stale-lock guesses.
|
|
56
|
+
|
|
57
|
+
VERIFIED: Data written after the published end is private. A later writer truncates only that unpublished tail. A committed frame with a bad checksum fails when read; `verify()` walks all reachable values and index pages, validates ordering, counts and revisions. Neither compaction nor open repairs published corruption. Old snapshots delay reclamation intentionally, preserving their data.
|
|
58
|
+
|
|
59
|
+
## Transactions, memory and lifecycle
|
|
60
|
+
|
|
61
|
+
VERIFIED: Batch values are encoded before admission returns, preventing caller mutation during queued work. Both per-transaction and aggregate pending-byte budgets are enforced. A transaction callback reads from one snapshot plus a bounded staged overlay. The final database revision must still equal its snapshot revision, including read-only transactions and range scans. This conservative validation provides serializability but can reject transactions touching disjoint keys. Automatic retries are omitted because callbacks may have external effects.
|
|
62
|
+
|
|
63
|
+
VERIFIED: Closing a snapshot rejects new reads, drains admitted reads and releases its pin. Paused iterators do not prevent closure. Closing a database stops admission, drains operations, closes its snapshots and discards its cache. Cancellation is cooperative during waiting and copying. After publication starts, completion is success or an uncertain commit error rather than an ordinary cancellation.
|
|
64
|
+
|
|
65
|
+
## Operations, security and privacy
|
|
66
|
+
|
|
67
|
+
VERIFIED: The trusted storage root is application-owned. Native byte and lock files reject symlink traversal where supported; database names are lowercase identifiers. Bounds and backward-only child references reject malformed addresses and disk cycles. CRC32C detects damage, not forgery. DSON values may be cyclic and contain binary data. Applications needing encryption or authentication must provide those policies separately.
|
|
68
|
+
|
|
69
|
+
VERIFIED: There is no network service or background maintenance. Applications schedule `compact()` and `collect()` and close snapshots promptly. Maintenance needs enough disk space for the live copy. No telemetry or application-value logging occurs. Tests use temporary databases and real processes. Source, tests, examples and tooling each document their own responsibilities in ARCH.md.
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
VERIFIED: The website fits phones: code and tables scroll sideways instead of wrapping, tables tint every other row, cards put their icon beside the heading, and the install tabs stack. `make e2e` now also drives the website in WebKit at iPhone size, including the OPFS counter and the menu sheet, and fails if the page scrolls sideways.
|
|
6
|
+
|
|
7
|
+
VERIFIED: The OPFS demo replaces a worker that leaves a request unanswered for 5 s, retries a failed open on the next click and shows the browser error behind a failure. The demo was reported to stop on an iPhone after a delete; desktop WebKit and Chromium did not reproduce it, so the cause is still open.
|
|
8
|
+
|
|
9
|
+
VERIFIED: Commits got cheaper without changing the format or the lock protocol. A commit edits cached copies of the index pages on its paths instead of rereading and decoding them, and caches the pages it publishes. Publication patches the manifest parse cache, skips the directory sync (a commit creates no file), and truncates only when a failed commit left a tail. Native connections reuse one idle descriptor per lock name instead of reopening a lock file for every I/O lock and pin. In single-process probes on macOS arm64, a memory transaction fell from 0.31–0.38 ms to 0.14–0.15 ms and a durable Bun transaction from 1.16 ms to 0.50 ms; durable Node commits stay bound by their two flushes, which took about 3 ms each under Node on that host.
|
|
10
|
+
|
|
11
|
+
VERIFIED: Behavior change: a transaction now conflicts only when a key it read changed, appeared or disappeared after its snapshot, instead of on any concurrent commit. Writers on disjoint keys no longer retry; write skew and point-read phantoms are still rejected, and a transaction that scanned falls back to the whole-database check. With four contending writers, retries fell from 1.5 to 2.1 per commit to none.
|
|
12
|
+
|
|
13
|
+
VERIFIED: Commits queued on one handle publish as a group: one append, one generation flush and one head flush, with a revision and receipt per commit. A cancelled, conflicting or failing member is rejected alone. A transaction started while its handle's group holds the commit lock pins the last flushed head instead of waiting behind the group's flushes.
|
|
14
|
+
|
|
15
|
+
VERIFIED: A forming commit group waits, at most half the previous group's publication time, for transactions on its handle that already hold a snapshot. Four transaction writers on one handle had alternated between groups of one and three members; in full groups a contended durable Node commit fell from 4.4 to 2.1 ms on macOS arm64, and a contended memory commit from 65 to 59 µs under Node and from 72 to 63 µs under Bun. A transaction that outlasts one wait is not waited for again.
|
|
16
|
+
|
|
17
|
+
VERIFIED: defuss-dson is now 1.4.0, which writes the same frames as 1.3.0. In microbenchmarks of dbsonl's values, pages and manifests on macOS arm64 it encoded three to five times faster and decoded 2.5 to 6 times faster. Index pages and manifests use its `trusted` mode, which skips the per-property checks for plain data the engine built itself. On macOS arm64 a 24-entry leaf page encoded in 9 to 12 µs instead of 49 to 53 µs and decoded in 12 to 15 µs instead of 42 to 65 µs.
|
|
18
|
+
|
|
19
|
+
VERIFIED: Index pages are written by a page-specific DSON writer with the same bytes as `encodeFrame` in trusted mode (checked on 2000 generated pages per test run), about 30% faster per page, and the page cache evicts by second chance instead of reordering on every hit. Together they took a contended memory commit from 59 to 49 µs under Node and from 63 to 56 µs under Bun in single-process probes.
|
|
20
|
+
|
|
21
|
+
VERIFIED: Index edits and buffered appends run synchronously unless they need I/O, and native connections read the 8 KiB manifest with a blocking call; a cold manifest blocks the event loop for one 8 KiB read. A durable point read fell from 45 to 27 µs under Node and to about 33 µs under Bun in single-process probes.
|
|
22
|
+
|
|
23
|
+
VERIFIED: In `make bench-redis` on macOS arm64, defuss-dbsonl now takes less time than Redis in 12 of 16 pairings, against 4 for 0.4.0. The single durable Node writes still lose, because each commit flushes twice and a flush took about 3 ms under Node there, and so do the 1000-write batches in memory, where encoding each value as its own DSON frame costs more than Redis's `JSON.stringify`. `docs/PERFORMANCE.md` has the table.
|
|
24
|
+
|
|
25
|
+
VERIFIED: defuss-storage is now 0.3.1.
|
|
26
|
+
|
|
27
|
+
VERIFIED: `make bench-redis` compares the current build with a throwaway loopback Redis pinned in `mise.toml`: point reads, 1000-write batches, `WATCH`/`MULTI`/`EXEC` transactions against `transaction()`, and four contending writers. Each engine's turn starts after a full garbage collection, because otherwise one engine's garbage was collected inside the other's timed work. `docs/PERFORMANCE.md` has the results.
|
|
28
|
+
|
|
29
|
+
## 0.4.0
|
|
30
|
+
|
|
31
|
+
Breaking changes:
|
|
32
|
+
|
|
33
|
+
- The native entry `defuss-dbsonl/node` is renamed to `defuss-dbsonl/server`. Replace the import path; `createFileBackend` and its options are unchanged.
|
|
34
|
+
- The `defuss-dbsonl/legacy` subpath (the v0.1 log store) and the `defuss-dbsonl/records` frame API are removed, together with `examples/migrate.ts`. Migrate v0.1 data with defuss-dbsonl 0.3.x, then upgrade.
|
|
35
|
+
|
|
36
|
+
VERIFIED: Format 2 and the lock protocol are unchanged; the packed-package suite runs 0.2.0 and 0.4.0 writers concurrently against one database. `openDbsonl(..., { create: true })` completes an interrupted create: an empty head file whose generation files are all empty. Any persisted byte still fails closed with `CORRUPT`. Writer index-page loads use one known-length read. Browser tests cover directory-handle Storage through the format-2 API.
|
|
37
|
+
|
|
38
|
+
VERIFIED: Added a project website in `docs/index.html` whose demos run the library in the visitor's tab: a snapshot during transfers, a transaction conflict, a DSON round trip and an OPFS counter that survives reloads. `make e2e` drives every demo against the installed tarball. The npm package ships only the Markdown pages from `docs/`.
|
|
39
|
+
|
|
40
|
+
VERIFIED: `make bench` measures the vendored v0.2.0 and v0.3.0 builds beside the current build in one session. In three macOS arm64 runs, Bun ran some 0.4.0 read workloads slower than 0.3.0: snapshot reads and scans on memory storage by 20% to 26%, and scans on native storage by 12% to 34%. Node showed no consistent difference. `docs/PERFORMANCE.md` has the tables.
|
|
41
|
+
|
|
42
|
+
## 0.3.0
|
|
43
|
+
|
|
44
|
+
VERIFIED: Preserved format 2, all public operations, portable backends and legacy exports. Added per-database native descriptor ownership, local FIFO commit admission, nonblocking native lock attempts, concurrent positional reads and pipelined fresh-head/value reads. Metadata parsing is cached only while freshly read bytes match. Point values remain uncached and detached.
|
|
45
|
+
|
|
46
|
+
VERIFIED: Added bounded 64 KiB scan/compaction read-ahead and writer buffering before the existing durability barrier. Added repeated matched benchmarks against the shipped v0.2 tarball, Node/Bun equality-kernel measurements, mixed-version process tests and native resource/corruption regressions. Manual loop unrolling was measured and rejected for the shared implementation.
|
|
47
|
+
|
|
48
|
+
## 0.2.0
|
|
49
|
+
|
|
50
|
+
VERIFIED: Added persistent copy-on-write B+tree indexing, immutable snapshot roots, queued multi-client writers, atomic batches, optimistic serializable transactions, compare-and-swap revisions, streaming compaction, generation reclamation and full logical integrity verification. Native clients coordinate through whole-file OS locks; browser workers coordinate through Web Locks. Manifest publication uses two checksummed slots and a committed byte boundary.
|
|
51
|
+
|
|
52
|
+
VERIFIED: Added bounded page caching, aggregate pending-write admission, mixed Node/Bun process tests, SIGKILL coverage, browser-worker contention and a migration example. Retained the v0.1 implementation under `/legacy` and the unchanged frame API under `/records`. Root API and format are intentionally versioned changes; no automatic data rewrite occurs.
|
|
53
|
+
|
|
54
|
+
## 0.1.0
|
|
55
|
+
|
|
56
|
+
VERIFIED: Initial DSON framed record layer, append-only keyed log, bounded scans, explicit recovery inspection/repair and memory/native/browser adapter verification.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aron Homberg
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,131 @@
|
|
|
1
|
-
#
|
|
1
|
+
# defuss-dbsonl 0.5.0
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Transactional key-value storage for Node.js, Bun and browser workers. Values are DSON, so dates, binary views, bigint, `undefined` and cyclic references survive storage. It is built on [defuss-dson](https://dson.defuss.org) 1.4.0 and [defuss-storage](https://storage.defuss.org) 0.3.1 and ships TypeScript declarations with ESM and CommonJS builds. It is designed as the backing store and API of [defuss-dataview](https://dataview.defuss.org), which adds filters, sorting and paging for table and tree grids. Project website: [docs/index.html](docs/index.html).
|
|
4
|
+
|
|
5
|
+
VERIFIED: A database is a persistent copy-on-write B+tree with immutable snapshots, atomic batches, optimistic serializable transactions, compaction and process-safe coordination. Opening reads two small manifest slots instead of replaying a log, and readers never block writers.
|
|
6
|
+
|
|
7
|
+
## Install and use
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
make release
|
|
11
|
+
bun add ./validation/defuss-dbsonl-0.5.0.tgz
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`make release` builds the tarball locally; registry publication is a separate step.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { openDbsonl } from 'defuss-dbsonl';
|
|
18
|
+
import { createFileBackend } from 'defuss-dbsonl/server';
|
|
19
|
+
|
|
20
|
+
const backend = await createFileBackend('./data');
|
|
21
|
+
const db = await openDbsonl<number>(backend, 'accounts', { create: true });
|
|
22
|
+
await db.batch([
|
|
23
|
+
{ operation: 'put', key: 'alice', value: 100 },
|
|
24
|
+
{ operation: 'put', key: 'bob', value: 50 },
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
const before = await db.beginRead();
|
|
28
|
+
try {
|
|
29
|
+
await db.transaction(async tx => {
|
|
30
|
+
const alice = (await tx.get('alice')).value!;
|
|
31
|
+
const bob = (await tx.get('bob')).value!;
|
|
32
|
+
tx.put('alice', alice - 20);
|
|
33
|
+
tx.put('bob', bob + 20);
|
|
34
|
+
});
|
|
35
|
+
console.log((await before.get('alice')).value); // 100: the snapshot keeps its root.
|
|
36
|
+
await db.compact();
|
|
37
|
+
} finally {
|
|
38
|
+
await before.close();
|
|
39
|
+
await db.collect();
|
|
40
|
+
await db.close();
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The transaction callback runs once. A concurrent commit that changed a key the callback read makes it fail with `CONFLICT` instead of retrying, because a retry would repeat any side effects in your callback; after a scan, any concurrent commit does. Retry explicitly where that is safe. Concurrent batches and transactions on one handle publish together: one write and one pair of flushes for the queued group, while each keeps its own revision and receipt. `ifRevision` gives compare-and-swap for changes prepared outside a transaction.
|
|
45
|
+
|
|
46
|
+
Memory storage needs no platform entry:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { createMemoryBackend, openDbsonl } from 'defuss-dbsonl';
|
|
50
|
+
const db = await openDbsonl(createMemoryBackend(), 'example', { create: true });
|
|
51
|
+
await db.put('binary', new Uint8Array([1, 2, 3]));
|
|
52
|
+
await db.close();
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
In a dedicated browser worker:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { createOPFSStorage } from 'defuss-storage/opfs';
|
|
59
|
+
import { createBrowserBackend } from 'defuss-dbsonl/browser';
|
|
60
|
+
import { openDbsonl } from 'defuss-dbsonl';
|
|
61
|
+
const namespace = 'my-app';
|
|
62
|
+
const storage = await createOPFSStorage({ name: namespace });
|
|
63
|
+
const backend = createBrowserBackend(storage, namespace, navigator.locks);
|
|
64
|
+
const db = await openDbsonl(backend, 'documents', { create: true });
|
|
65
|
+
await db.put('hello', { bytes: new Uint8Array([42]), time: new Date() });
|
|
66
|
+
await db.close();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Every adapter that reaches the same files must use the same Web Locks namespace, because the namespace is the only thing that tells two workers they share a database. `createDirectoryStorage` works the same way. With Storage admission limits below 64 KiB, pass the accepted write chunk size as the fourth `createBrowserBackend` argument.
|
|
70
|
+
|
|
71
|
+
| Entry | Contents | Why it is separate |
|
|
72
|
+
| --- | --- | --- |
|
|
73
|
+
| `defuss-dbsonl` | `openDbsonl`, `createMemoryBackend`, errors, types | Runs anywhere; declarations need neither Node nor DOM types |
|
|
74
|
+
| `defuss-dbsonl/server` | `createFileBackend` for Node.js and Bun | Loads the native lock addon and `node:fs`, which browser bundles must not see |
|
|
75
|
+
| `defuss-dbsonl/browser` | `createBrowserBackend` over Web Locks | Keeps the Web Locks adapter out of server bundles |
|
|
76
|
+
|
|
77
|
+
## Design choices
|
|
78
|
+
|
|
79
|
+
Each row names the obvious alternative, the reason it was not taken and the cost of the choice.
|
|
80
|
+
|
|
81
|
+
| Concern | Plausible alternative | Chosen | Why | Cost |
|
|
82
|
+
| --- | --- | --- | --- | --- |
|
|
83
|
+
| Finding keys | In-memory key map rebuilt by replaying a log | Persistent B+tree, fanout 32, bounded page cache | Memory does not grow with key count and open needs no replay | Uncached point reads perform disk I/O |
|
|
84
|
+
| Readers versus writers | Read locks that block commits | Immutable roots and shared generation pins | A slow reader cannot stall writers | Old generations stay on disk until readers close |
|
|
85
|
+
| Atomic publication | Write a new file, then rename it | Two checksummed head slots, written alternately | OPFS and Storage expose no uniform atomic rename | Every commit writes one 4 KiB slot |
|
|
86
|
+
| Multiple writers | One owning process | OS whole-file locks or Web Locks, held per commit group | Independent processes and workers can share one database | Commits still serialize to keep one revision order |
|
|
87
|
+
| Transactions | One revision check for the whole database | Each point read rechecked at commit; the whole-database check after a scan | Writers on disjoint keys commit without retrying, and write skew and phantoms are still ruled out | A transaction keeps the revision of every key it read, up to `maxTransactionOperations` keys, then falls back to the whole-database check |
|
|
88
|
+
| Space reuse | In-place updates or a background vacuum | Explicit `compact()` and `collect()` | No hidden I/O; the application chooses when to pay | Compaction needs disk space for one live copy |
|
|
89
|
+
| Stale locks | Lock files that expire after a timeout | Kernel locks released on process death | A paused process never loses ownership to a second writer | Requires the native addon on servers |
|
|
90
|
+
|
|
91
|
+
VERIFIED: `compact()` lets writers continue while it copies and returns `CONFLICT` if one of them published meanwhile. `compact({ mode: 'exclusive' })` queues writers instead, which guarantees progress under sustained write traffic. Existing snapshots stay readable either way. Compaction does not delete anything; `collect()` reclaims unpinned obsolete and abandoned generations.
|
|
92
|
+
|
|
93
|
+
## Guarantees and boundaries
|
|
94
|
+
|
|
95
|
+
VERIFIED: A published root makes a whole batch visible at once. Values and index pages are flushed before a head slot is written. Native factories also sync the directory after creating or removing a file, before any head refers to it; a commit only appends to and overwrites existing files. Two checksummed slots survive an interrupted write of either one. A writer reuses any unpublished tail left by a failed commit. Published corruption fails validation; nothing repairs data automatically, because a guessed repair can turn damage into silent data loss.
|
|
96
|
+
|
|
97
|
+
VERIFIED: Native locking uses `@lickle/lock` 0.0.1, which takes whole-file `flock`/`LockFileEx` locks through a Node-API addon. Version 0.3.0 was tested on Linux x64; on 2026-11-14 the full suite, including process termination and the packed-package run, also passed on macOS arm64. Both used Node 24.22.1 and Bun 1.4.3. Chromium workers were tested with real OPFS, directory handles and Web Locks. Memory backends coordinate only clients that share one backend object.
|
|
98
|
+
|
|
99
|
+
VERIFIED: No test run has exercised power cuts, network filesystems, Windows or Firefox, so their behavior is unknown. WebKit has run only the website demos, including the OPFS counter, in Playwright's WebKit build at iPhone size; the browser test suite runs in Chromium. The addon ships binaries for Linux x64 glibc, macOS x64/arm64 and Windows x64. The native factory refuses to start where directory sync is unsupported, rather than silently promising less durability. OPFS has no directory-sync API and reports `durability: 'file'`; memory reports `'memory'`. There is no distributed consensus, encryption or protection against hostile writers.
|
|
100
|
+
|
|
101
|
+
Resource budgets cap retained engine work. The page cache is bounded by encoded bytes and page count, independent of key count. Decoded values, active traversal paths, caller-held values, snapshots and the memory adapter's stored bytes are outside that budget. [API](docs/API.md) lists the defaults and error codes.
|
|
102
|
+
|
|
103
|
+
## Compatibility
|
|
104
|
+
|
|
105
|
+
VERIFIED: Versions 0.2 through 0.4 share the on-disk format and the lock protocol. The packed-package suite runs 0.2.0 and the current build concurrently on Node and Bun against one database, so upgrading needs no migration.
|
|
106
|
+
|
|
107
|
+
Version 0.4.0 renamed the native entry from `defuss-dbsonl/node` to `defuss-dbsonl/server` and removed the `/legacy` and `/records` subpaths. Data in the v0.1 log format must be migrated with defuss-dbsonl 0.3.x first; that release ships `defuss-dbsonl/legacy` and `examples/migrate.ts`. See [CHANGELOG.md](CHANGELOG.md).
|
|
108
|
+
|
|
109
|
+
## Develop and verify
|
|
110
|
+
|
|
111
|
+
```sh
|
|
112
|
+
make setup # pinned Node/Bun/Redis via mise, dependencies, Chromium, WebKit, VAE runtime
|
|
113
|
+
make verify # lint, tests, coverage, packed-package e2e
|
|
114
|
+
make bench # matched v0.2 versus current benchmarks
|
|
115
|
+
make bench-redis # current build versus a throwaway loopback Redis, run as mise exec -- make bench-redis
|
|
116
|
+
make dev # rebuild the website demos and serve docs/ on 127.0.0.1:3000
|
|
117
|
+
make vae # verification, review and documentation gate
|
|
118
|
+
make release # tarball, source ZIP and checksums; never publishes or commits
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
VERIFIED: `make verify` runs strict type checks, lint, real-storage tests, coverage thresholds and a packed-package suite on Node, Bun and Chromium, plus the website in WebKit at iPhone size. That suite runs mixed Node/Bun processes on both 0.2.0 and the current build, kills writers mid-batch and runs concurrent browser workers. `make release` packages only after the pinned defuss-vae 0.9.0 gate passes for the current source fingerprint. `make` lists every target; `.env.example` documents the browser executable overrides.
|
|
122
|
+
|
|
123
|
+
| Page | Answers |
|
|
124
|
+
| --- | --- |
|
|
125
|
+
| [docs/index.html](docs/index.html) | The project website, with demos that run the library in the visitor's tab; `make site` rebuilds its bundles |
|
|
126
|
+
| [ARCH.md](ARCH.md) | Why the protocol is built this way: lock order, crashes, reclamation, security |
|
|
127
|
+
| [docs/API.md](docs/API.md) | Every operation, option default, budget and error code |
|
|
128
|
+
| [docs/FORMAT.md](docs/FORMAT.md) | Files on disk, slot layout and publication order |
|
|
129
|
+
| [docs/PERFORMANCE.md](docs/PERFORMANCE.md) | Benchmark protocol, results and the reasons behind the read path |
|
|
130
|
+
|
|
131
|
+
Every authored source folder has its own ARCH.md.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var defussStorage = require('defuss-storage');
|
|
4
|
+
var common = require('./common-2ybGl1zj.cjs');
|
|
5
|
+
|
|
6
|
+
function createMemoryCoordinator() {
|
|
7
|
+
const states = /* @__PURE__ */ new Map();
|
|
8
|
+
const coordinator = {
|
|
9
|
+
async acquire(name, shared = false, signal, tryOnly = false) {
|
|
10
|
+
common.abort(signal);
|
|
11
|
+
let state = states.get(name);
|
|
12
|
+
if (!state) {
|
|
13
|
+
state = { readers: 0, writer: false, queue: [] };
|
|
14
|
+
states.set(name, state);
|
|
15
|
+
}
|
|
16
|
+
const current = state;
|
|
17
|
+
const grant = (read) => {
|
|
18
|
+
if (read) current.readers++;
|
|
19
|
+
else current.writer = true;
|
|
20
|
+
let released = false;
|
|
21
|
+
return async () => {
|
|
22
|
+
if (released) return;
|
|
23
|
+
released = true;
|
|
24
|
+
if (read) current.readers--;
|
|
25
|
+
else current.writer = false;
|
|
26
|
+
while (!current.writer && current.queue.length && (!current.readers || current.queue[0].shared)) {
|
|
27
|
+
const next = current.queue.shift();
|
|
28
|
+
next.resolve(grant(next.shared));
|
|
29
|
+
}
|
|
30
|
+
if (!current.writer && !current.readers && !current.queue.length) states.delete(name);
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
if (!current.writer && !current.queue.length && (shared || !current.readers)) return grant(shared);
|
|
34
|
+
if (tryOnly) return void 0;
|
|
35
|
+
const release = await new Promise((resolve) => current.queue.push({ shared, resolve }));
|
|
36
|
+
try {
|
|
37
|
+
common.abort(signal);
|
|
38
|
+
return release;
|
|
39
|
+
} catch (error) {
|
|
40
|
+
await release();
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
async syncDirectory() {
|
|
45
|
+
},
|
|
46
|
+
async retire() {
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
return coordinator;
|
|
50
|
+
}
|
|
51
|
+
function createMemoryBackend(options) {
|
|
52
|
+
return { storage: defussStorage.createMemoryStorage(options), coordinator: createMemoryCoordinator(), durability: "memory", writeChunkBytes: Math.min(65536, options?.maxWriteBytes ?? 65536, options?.maxPendingWriteBytes ?? 65536) };
|
|
53
|
+
}
|
|
54
|
+
async function withFile(backend, name, open, work) {
|
|
55
|
+
return locked(backend, `io-${name}`, async () => {
|
|
56
|
+
const file = await backend.storage.open(name, open);
|
|
57
|
+
try {
|
|
58
|
+
return await work(file);
|
|
59
|
+
} finally {
|
|
60
|
+
await file.close();
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
async function locked(backend, name, work, signal) {
|
|
65
|
+
const release = await backend.coordinator.acquire(name, false, signal);
|
|
66
|
+
if (!release) throw new Error("Coordinator did not grant a blocking lock.");
|
|
67
|
+
try {
|
|
68
|
+
common.abort(signal);
|
|
69
|
+
return await work();
|
|
70
|
+
} finally {
|
|
71
|
+
await release();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function writeBytes(file, offset, bytes, chunkSize) {
|
|
75
|
+
for (let used = 0; used < bytes.length; used += chunkSize) await file.write(offset + used, bytes.subarray(used, used + chunkSize));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
exports.createMemoryBackend = createMemoryBackend;
|
|
79
|
+
exports.createMemoryCoordinator = createMemoryCoordinator;
|
|
80
|
+
exports.locked = locked;
|
|
81
|
+
exports.withFile = withFile;
|
|
82
|
+
exports.writeBytes = writeBytes;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createMemoryStorage } from 'defuss-storage';
|
|
2
|
+
import { a as abort } from './common-0JC30Xiv.mjs';
|
|
3
|
+
|
|
4
|
+
function createMemoryCoordinator() {
|
|
5
|
+
const states = /* @__PURE__ */ new Map();
|
|
6
|
+
const coordinator = {
|
|
7
|
+
async acquire(name, shared = false, signal, tryOnly = false) {
|
|
8
|
+
abort(signal);
|
|
9
|
+
let state = states.get(name);
|
|
10
|
+
if (!state) {
|
|
11
|
+
state = { readers: 0, writer: false, queue: [] };
|
|
12
|
+
states.set(name, state);
|
|
13
|
+
}
|
|
14
|
+
const current = state;
|
|
15
|
+
const grant = (read) => {
|
|
16
|
+
if (read) current.readers++;
|
|
17
|
+
else current.writer = true;
|
|
18
|
+
let released = false;
|
|
19
|
+
return async () => {
|
|
20
|
+
if (released) return;
|
|
21
|
+
released = true;
|
|
22
|
+
if (read) current.readers--;
|
|
23
|
+
else current.writer = false;
|
|
24
|
+
while (!current.writer && current.queue.length && (!current.readers || current.queue[0].shared)) {
|
|
25
|
+
const next = current.queue.shift();
|
|
26
|
+
next.resolve(grant(next.shared));
|
|
27
|
+
}
|
|
28
|
+
if (!current.writer && !current.readers && !current.queue.length) states.delete(name);
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
if (!current.writer && !current.queue.length && (shared || !current.readers)) return grant(shared);
|
|
32
|
+
if (tryOnly) return void 0;
|
|
33
|
+
const release = await new Promise((resolve) => current.queue.push({ shared, resolve }));
|
|
34
|
+
try {
|
|
35
|
+
abort(signal);
|
|
36
|
+
return release;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
await release();
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
async syncDirectory() {
|
|
43
|
+
},
|
|
44
|
+
async retire() {
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
return coordinator;
|
|
48
|
+
}
|
|
49
|
+
function createMemoryBackend(options) {
|
|
50
|
+
return { storage: createMemoryStorage(options), coordinator: createMemoryCoordinator(), durability: "memory", writeChunkBytes: Math.min(65536, options?.maxWriteBytes ?? 65536, options?.maxPendingWriteBytes ?? 65536) };
|
|
51
|
+
}
|
|
52
|
+
async function withFile(backend, name, open, work) {
|
|
53
|
+
return locked(backend, `io-${name}`, async () => {
|
|
54
|
+
const file = await backend.storage.open(name, open);
|
|
55
|
+
try {
|
|
56
|
+
return await work(file);
|
|
57
|
+
} finally {
|
|
58
|
+
await file.close();
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
async function locked(backend, name, work, signal) {
|
|
63
|
+
const release = await backend.coordinator.acquire(name, false, signal);
|
|
64
|
+
if (!release) throw new Error("Coordinator did not grant a blocking lock.");
|
|
65
|
+
try {
|
|
66
|
+
abort(signal);
|
|
67
|
+
return await work();
|
|
68
|
+
} finally {
|
|
69
|
+
await release();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function writeBytes(file, offset, bytes, chunkSize) {
|
|
73
|
+
for (let used = 0; used < bytes.length; used += chunkSize) await file.write(offset + used, bytes.subarray(used, used + chunkSize));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { writeBytes as a, createMemoryCoordinator as b, createMemoryBackend as c, locked as l, withFile as w };
|
package/dist/browser.cjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var common = require('./common-2ybGl1zj.cjs');
|
|
4
|
+
|
|
5
|
+
function createBrowserBackend(storage, namespace, locks, writeChunkBytes = 65536) {
|
|
6
|
+
if (!namespace || !locks?.request) throw new TypeError("A namespace and Web Lock manager are required.");
|
|
7
|
+
common.natural(writeChunkBytes, "writeChunkBytes", 1);
|
|
8
|
+
return { storage, writeChunkBytes, durability: storage.capabilities.persistent ? "file" : "memory", coordinator: {
|
|
9
|
+
acquire(name, shared = false, signal, tryOnly = false) {
|
|
10
|
+
common.abort(signal);
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const request = locks.request(`defuss-dbsonl:${namespace}:${name}`, { mode: shared ? "shared" : "exclusive", ifAvailable: tryOnly }, async (lock) => {
|
|
13
|
+
if (!lock) {
|
|
14
|
+
resolve(void 0);
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
common.abort(signal);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
reject(error);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
let finish;
|
|
24
|
+
const held = new Promise((done) => {
|
|
25
|
+
finish = done;
|
|
26
|
+
});
|
|
27
|
+
resolve(async () => {
|
|
28
|
+
finish();
|
|
29
|
+
await request;
|
|
30
|
+
});
|
|
31
|
+
await held;
|
|
32
|
+
}).catch(reject);
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
async syncDirectory() {
|
|
36
|
+
},
|
|
37
|
+
async retire() {
|
|
38
|
+
}
|
|
39
|
+
} };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
exports.createBrowserBackend = createBrowserBackend;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { StorageAdapter } from 'defuss-storage';
|
|
2
|
+
import { Backend } from './index.cjs';
|
|
3
|
+
|
|
4
|
+
/** VERIFIED: Web Locks coordinate independent workers; a generation pin is a held shared lock. */
|
|
5
|
+
|
|
6
|
+
/** Minimal structural surface keeps core declarations independent of DOM ambient types. */
|
|
7
|
+
interface WebLockManager {
|
|
8
|
+
request(name: string, options: {
|
|
9
|
+
mode: 'shared' | 'exclusive';
|
|
10
|
+
ifAvailable: boolean;
|
|
11
|
+
}, callback: (lock: unknown | null) => Promise<void>): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Supply navigator.locks and the same namespace for every adapter addressing the same files.
|
|
15
|
+
* OPFS flush persists file contents; Web APIs offer no directory-fsync primitive.
|
|
16
|
+
*/
|
|
17
|
+
declare function createBrowserBackend(storage: StorageAdapter, namespace: string, locks: WebLockManager, writeChunkBytes?: number): Backend;
|
|
18
|
+
|
|
19
|
+
export { createBrowserBackend };
|
|
20
|
+
export type { WebLockManager };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { StorageAdapter } from 'defuss-storage';
|
|
2
|
+
import { Backend } from './index.mjs';
|
|
3
|
+
|
|
4
|
+
/** VERIFIED: Web Locks coordinate independent workers; a generation pin is a held shared lock. */
|
|
5
|
+
|
|
6
|
+
/** Minimal structural surface keeps core declarations independent of DOM ambient types. */
|
|
7
|
+
interface WebLockManager {
|
|
8
|
+
request(name: string, options: {
|
|
9
|
+
mode: 'shared' | 'exclusive';
|
|
10
|
+
ifAvailable: boolean;
|
|
11
|
+
}, callback: (lock: unknown | null) => Promise<void>): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Supply navigator.locks and the same namespace for every adapter addressing the same files.
|
|
15
|
+
* OPFS flush persists file contents; Web APIs offer no directory-fsync primitive.
|
|
16
|
+
*/
|
|
17
|
+
declare function createBrowserBackend(storage: StorageAdapter, namespace: string, locks: WebLockManager, writeChunkBytes?: number): Backend;
|
|
18
|
+
|
|
19
|
+
export { createBrowserBackend };
|
|
20
|
+
export type { WebLockManager };
|
package/dist/browser.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { n as natural, a as abort } from './common-0JC30Xiv.mjs';
|
|
2
|
+
|
|
3
|
+
function createBrowserBackend(storage, namespace, locks, writeChunkBytes = 65536) {
|
|
4
|
+
if (!namespace || !locks?.request) throw new TypeError("A namespace and Web Lock manager are required.");
|
|
5
|
+
natural(writeChunkBytes, "writeChunkBytes", 1);
|
|
6
|
+
return { storage, writeChunkBytes, durability: storage.capabilities.persistent ? "file" : "memory", coordinator: {
|
|
7
|
+
acquire(name, shared = false, signal, tryOnly = false) {
|
|
8
|
+
abort(signal);
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const request = locks.request(`defuss-dbsonl:${namespace}:${name}`, { mode: shared ? "shared" : "exclusive", ifAvailable: tryOnly }, async (lock) => {
|
|
11
|
+
if (!lock) {
|
|
12
|
+
resolve(void 0);
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
abort(signal);
|
|
17
|
+
} catch (error) {
|
|
18
|
+
reject(error);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
let finish;
|
|
22
|
+
const held = new Promise((done) => {
|
|
23
|
+
finish = done;
|
|
24
|
+
});
|
|
25
|
+
resolve(async () => {
|
|
26
|
+
finish();
|
|
27
|
+
await request;
|
|
28
|
+
});
|
|
29
|
+
await held;
|
|
30
|
+
}).catch(reject);
|
|
31
|
+
});
|
|
32
|
+
},
|
|
33
|
+
async syncDirectory() {
|
|
34
|
+
},
|
|
35
|
+
async retire() {
|
|
36
|
+
}
|
|
37
|
+
} };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export { createBrowserBackend };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
class DbsonlError extends Error {
|
|
2
|
+
constructor(code, message, options2) {
|
|
3
|
+
super(message, options2);
|
|
4
|
+
this.code = code;
|
|
5
|
+
this.name = "DbsonlError";
|
|
6
|
+
}
|
|
7
|
+
code;
|
|
8
|
+
}
|
|
9
|
+
function abort(signal) {
|
|
10
|
+
if (signal?.aborted) throw new DbsonlError("ABORTED", "Operation cancelled.", { cause: signal.reason });
|
|
11
|
+
}
|
|
12
|
+
function natural(value, name2, min = 0) {
|
|
13
|
+
if (!Number.isSafeInteger(value) || value < min) throw new RangeError(`${name2} must be a safe integer >= ${min}.`);
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function key(value) {
|
|
17
|
+
if (typeof value !== "string" || value.length > 4096) throw new TypeError("A key must be a string of at most 4096 UTF-16 code units.");
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function name(value) {
|
|
21
|
+
if (typeof value !== "string" || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(value)) throw new TypeError("Use a lowercase database name of 1..64 letters, digits, underscores or hyphens.");
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function corrupt(message) {
|
|
25
|
+
throw new DbsonlError("CORRUPT", message);
|
|
26
|
+
}
|
|
27
|
+
function reference(value, end) {
|
|
28
|
+
const r = value;
|
|
29
|
+
if (!r || !Number.isSafeInteger(r.offset) || !Number.isSafeInteger(r.byteLength) || r.offset < 0 || r.byteLength < 16 || !Number.isSafeInteger(r.offset + r.byteLength) || r.offset + r.byteLength > end) corrupt("Reference escapes its committed boundary.");
|
|
30
|
+
}
|
|
31
|
+
const DEFAULT_OPTIONS = Object.freeze({ maxRecordBytes: 16 * 1024 * 1024, maxTransactionBytes: 64 * 1024 * 1024, maxTransactionOperations: 1e4, maxPendingOperations: 256, maxPendingBytes: 128 * 1024 * 1024, maxCacheBytes: 8 * 1024 * 1024, maxCachePages: 1024 });
|
|
32
|
+
function options(input) {
|
|
33
|
+
const out = { ...DEFAULT_OPTIONS };
|
|
34
|
+
for (const field of Object.keys(out)) out[field] = natural(input[field] ?? out[field], field, field.startsWith("maxCache") ? 0 : 1);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export { DbsonlError as D, abort as a, name as b, corrupt as c, DEFAULT_OPTIONS as d, key as k, natural as n, options as o, reference as r };
|