defuss-dbsonl 0.0.0-stage → 0.4.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 +63 -0
- package/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +127 -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 +875 -0
- package/dist/index.d.cts +140 -0
- package/dist/index.d.mts +140 -0
- package/dist/index.mjs +872 -0
- package/dist/server.cjs +276 -0
- package/dist/server.d.cts +12 -0
- package/dist/server.d.mts +12 -0
- package/dist/server.mjs +273 -0
- package/dist/types-B_SuDjVq.d.cts +128 -0
- package/dist/types-B_SuDjVq.d.mts +128 -0
- package/docs/API.md +83 -0
- package/docs/FORMAT.md +64 -0
- package/docs/PERFORMANCE.md +115 -0
- package/examples/ARCH.md +5 -0
- package/examples/basic.ts +13 -0
- package/examples/transaction.ts +14 -0
- package/package.json +80 -4
package/ARCH.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
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. A bounded LRU cache stores decoded pages, never application values. 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. Portable reads acquire short I/O locks because Storage 0.3.0 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
|
+
## Native read and write performance
|
|
36
|
+
|
|
37
|
+
VERIFIED: Every database handle owns a connection with at most two idle read descriptors and one idle commit-lock descriptor. 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. Commit-lock attempts use the nonblocking call of the shipped N-API binding of pinned `@lickle/lock` 0.0.1; pin and I/O locks use its nonblocking `tryLock` wrapper. No blocking lock acquisition or timeout-based ownership is introduced.
|
|
38
|
+
|
|
39
|
+
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. A per-handle 8 KiB parse cache avoids repeated DSON decoding, not fresh I/O. Aligned comparisons use 32-bit words; measured manual unrolling was not retained because it regressed Node.
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
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 for each removed generation. 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.
|
|
44
|
+
|
|
45
|
+
## Reclamation and crashes
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
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.
|
|
52
|
+
|
|
53
|
+
## Transactions, memory and lifecycle
|
|
54
|
+
|
|
55
|
+
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.
|
|
56
|
+
|
|
57
|
+
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.
|
|
58
|
+
|
|
59
|
+
## Operations, security and privacy
|
|
60
|
+
|
|
61
|
+
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.
|
|
62
|
+
|
|
63
|
+
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,26 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
Breaking changes:
|
|
6
|
+
|
|
7
|
+
- The native entry `defuss-dbsonl/node` is renamed to `defuss-dbsonl/server`. Replace the import path; `createFileBackend` and its options are unchanged.
|
|
8
|
+
- 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.
|
|
9
|
+
|
|
10
|
+
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.
|
|
11
|
+
|
|
12
|
+
## 0.3.0
|
|
13
|
+
|
|
14
|
+
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.
|
|
15
|
+
|
|
16
|
+
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.
|
|
17
|
+
|
|
18
|
+
## 0.2.0
|
|
19
|
+
|
|
20
|
+
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.
|
|
21
|
+
|
|
22
|
+
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.
|
|
23
|
+
|
|
24
|
+
## 0.1.0
|
|
25
|
+
|
|
26
|
+
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,128 @@
|
|
|
1
|
-
#
|
|
1
|
+
# defuss-dbsonl 0.4.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` 1.3.0 and `defuss-storage` 0.3.0 and ships TypeScript declarations with ESM and CommonJS builds.
|
|
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.4.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 makes it fail with `CONFLICT` instead of retrying, because a retry would repeat any side effects in your callback. Retry explicitly where that is safe. `batch()` accepts concurrent writers and serializes their publication. `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 LRU 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 | Independent processes and workers can share one database | Commits still serialize to keep one revision order |
|
|
87
|
+
| Transactions | Per-key conflict detection | Whole-database revision check | Rules out write skew and range phantoms without read-set tracking | Writers touching disjoint keys can still conflict |
|
|
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, and native factories also sync directory metadata. 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, Firefox or WebKit, so their behavior is unknown. 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 via mise, dependencies, Chromium, VAE runtime
|
|
113
|
+
make verify # lint, tests, coverage, packed-package e2e
|
|
114
|
+
make bench # matched v0.2 versus current benchmarks
|
|
115
|
+
make vae # verification, review and documentation gate
|
|
116
|
+
make release # tarball, source ZIP and checksums; never publishes or commits
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
VERIFIED: `make verify` runs strict type checks, lint, real-storage tests, coverage thresholds and a packed-package suite on Node, Bun and Chromium. 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.
|
|
120
|
+
|
|
121
|
+
| Page | Answers |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| [ARCH.md](ARCH.md) | Why the protocol is built this way: lock order, crashes, reclamation, security |
|
|
124
|
+
| [docs/API.md](docs/API.md) | Every operation, option default, budget and error code |
|
|
125
|
+
| [docs/FORMAT.md](docs/FORMAT.md) | Files on disk, slot layout and publication order |
|
|
126
|
+
| [docs/PERFORMANCE.md](docs/PERFORMANCE.md) | Benchmark protocol, results and the reasons behind the read path |
|
|
127
|
+
|
|
128
|
+
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 };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
class DbsonlError extends Error {
|
|
4
|
+
constructor(code, message, options2) {
|
|
5
|
+
super(message, options2);
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.name = "DbsonlError";
|
|
8
|
+
}
|
|
9
|
+
code;
|
|
10
|
+
}
|
|
11
|
+
function abort(signal) {
|
|
12
|
+
if (signal?.aborted) throw new DbsonlError("ABORTED", "Operation cancelled.", { cause: signal.reason });
|
|
13
|
+
}
|
|
14
|
+
function natural(value, name2, min = 0) {
|
|
15
|
+
if (!Number.isSafeInteger(value) || value < min) throw new RangeError(`${name2} must be a safe integer >= ${min}.`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function key(value) {
|
|
19
|
+
if (typeof value !== "string" || value.length > 4096) throw new TypeError("A key must be a string of at most 4096 UTF-16 code units.");
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
function name(value) {
|
|
23
|
+
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.");
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
function corrupt(message) {
|
|
27
|
+
throw new DbsonlError("CORRUPT", message);
|
|
28
|
+
}
|
|
29
|
+
function reference(value, end) {
|
|
30
|
+
const r = value;
|
|
31
|
+
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.");
|
|
32
|
+
}
|
|
33
|
+
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 });
|
|
34
|
+
function options(input) {
|
|
35
|
+
const out = { ...DEFAULT_OPTIONS };
|
|
36
|
+
for (const field of Object.keys(out)) out[field] = natural(input[field] ?? out[field], field, field.startsWith("maxCache") ? 0 : 1);
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
|
|
41
|
+
exports.DbsonlError = DbsonlError;
|
|
42
|
+
exports.abort = abort;
|
|
43
|
+
exports.corrupt = corrupt;
|
|
44
|
+
exports.key = key;
|
|
45
|
+
exports.name = name;
|
|
46
|
+
exports.natural = natural;
|
|
47
|
+
exports.options = options;
|
|
48
|
+
exports.reference = reference;
|