@reddb-io/browser 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -33
- package/package.json +2 -2
- package/src/index.d.ts +18 -1
- package/src/index.js +28 -3
- package/src/wasm/reddb_wasm.d.ts +17 -0
- package/src/wasm/reddb_wasm.js +74 -0
- package/src/wasm/reddb_wasm_bg.wasm +0 -0
- package/src/wasm/reddb_wasm_bg.wasm.d.ts +4 -0
- package/src/worker.js +39 -13
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# RedDB Browser — persistence and query engine
|
|
2
2
|
|
|
3
3
|
The `@reddb-io/browser` package runs the canonical Rust `.rdb` artifact publication/recovery code, RQL parser and shared
|
|
4
|
-
|
|
4
|
+
query evaluator in a dedicated WebAssembly worker, persisting through a real
|
|
5
5
|
OPFS sync access handle.
|
|
6
6
|
Artifact storage requires a secure context, module workers, OPFS and Web Locks.
|
|
7
7
|
The storage-independent runtime only needs module workers and WebAssembly.
|
|
@@ -12,9 +12,11 @@ RedDB server, account, CDN or external API. Applications bundle the JS, worker
|
|
|
12
12
|
and WASM assets and make them available locally or through their own offline
|
|
13
13
|
application cache. Sync is optional and must never gate local reads or writes.
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
Version `0.2.0` exposes local table SELECT, CREATE TABLE, INSERT, UPDATE, DELETE
|
|
16
|
+
and explicit BEGIN/COMMIT/ROLLBACK transactions through `openDatabase`.
|
|
17
|
+
Other models, synchronization, conflict
|
|
18
|
+
resolution and forwarding between tabs remain pending. The browser package
|
|
19
|
+
does not replace the remote `@reddb-io/client`.
|
|
18
20
|
|
|
19
21
|
## Use from JS/TS
|
|
20
22
|
|
|
@@ -26,20 +28,85 @@ npm add @reddb-io/browser
|
|
|
26
28
|
```
|
|
27
29
|
|
|
28
30
|
```ts
|
|
29
|
-
import {
|
|
31
|
+
import { openDatabase } from '@reddb-io/browser'
|
|
30
32
|
import RedDBWorker from '@reddb-io/browser/worker?worker'
|
|
31
33
|
|
|
32
|
-
const
|
|
34
|
+
const database = await openDatabase({ name: 'my-app', create: true, worker: new RedDBWorker() })
|
|
33
35
|
try {
|
|
34
|
-
|
|
36
|
+
await database.query('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)')
|
|
37
|
+
console.log(await database.query('SELECT id, body FROM notes'))
|
|
35
38
|
} finally {
|
|
36
|
-
await
|
|
39
|
+
await database.close()
|
|
37
40
|
}
|
|
38
41
|
```
|
|
39
42
|
|
|
40
43
|
Consumers receive built JS/Worker/WASM assets and TypeScript declarations; they
|
|
41
44
|
need no Rust toolchain. The commands below are for engine/package contributors.
|
|
42
45
|
|
|
46
|
+
## Local table SQL from JS/TS
|
|
47
|
+
|
|
48
|
+
Use `create: true` to create a missing local database. Existing native `.rdb`
|
|
49
|
+
artifacts recover their persisted collection contracts, snapshot and committed WAL.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { openDatabase } from '@reddb-io/browser'
|
|
53
|
+
import RedDBWorker from '@reddb-io/browser/worker?worker'
|
|
54
|
+
|
|
55
|
+
const database = await openDatabase({
|
|
56
|
+
name: 'my-app', create: true, worker: new RedDBWorker(),
|
|
57
|
+
})
|
|
58
|
+
try {
|
|
59
|
+
await database.query('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)')
|
|
60
|
+
await database.query('BEGIN')
|
|
61
|
+
await database.query("INSERT INTO notes VALUES (1, 'Offline'), (2, 'Temporary')")
|
|
62
|
+
await database.query("UPDATE notes SET body = 'Saved offline' WHERE id = 1")
|
|
63
|
+
await database.query('DELETE FROM notes WHERE id = 2')
|
|
64
|
+
await database.query('COMMIT')
|
|
65
|
+
console.log(await database.query('SELECT id, body FROM notes ORDER BY id'))
|
|
66
|
+
} finally { await database.close() }
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The example inserts fixed primary keys; subsequent runs should supply new IDs
|
|
70
|
+
or update the existing records. The handle uses the same exclusive Web Lock/OPFS
|
|
71
|
+
ownership as `openArtifact`; a second owner receives `FILE_BUSY`. Without
|
|
72
|
+
`create: true`, missing files return `DATABASE_NOT_FOUND`. Corrupt existing files
|
|
73
|
+
and missing/corrupt catalogs are errors, never recreated or inferred from rows.
|
|
74
|
+
|
|
75
|
+
Mutations return `{ columns: ['affectedRows'], rows: [[count]] }`. A statement
|
|
76
|
+
publishes only after all rows pass the shared schema, defaults, generated-field,
|
|
77
|
+
CHECK and uniqueness rules. Inside BEGIN, reads see the handle's staged writes;
|
|
78
|
+
COMMIT publishes them together. ROLLBACK, close or worker termination discard
|
|
79
|
+
uncommitted changes. Statement errors abort an explicit transaction until
|
|
80
|
+
ROLLBACK. Ambiguous storage failures fence the handle until reopen. Savepoints
|
|
81
|
+
and explicit isolation options are not exposed by this single-owner API.
|
|
82
|
+
|
|
83
|
+
Supported: one named table, aliases, `*`, literals, columns and JSON paths,
|
|
84
|
+
arithmetic/casts/CASE, nullable predicates, source-expression ORDER BY with native
|
|
85
|
+
NULL ordering, and literal LIMIT/OFFSET. Admitted scalar calls are UPPER, LOWER,
|
|
86
|
+
LENGTH/CHAR_LENGTH/CHARACTER_LENGTH/OCTET_LENGTH, TRIM/LTRIM/RTRIM, CONCAT,
|
|
87
|
+
COALESCE, ABS, JSON_PARSE, JSON_EXTRACT/JSON_EXTRACT_TEXT and CONTAINS. Unknown
|
|
88
|
+
fields/functions are rejected even on empty tables. Functions and operators use
|
|
89
|
+
the canonical Rust evaluators; exact values retain `reddb-json-v1` tags.
|
|
90
|
+
|
|
91
|
+
Parameters, DISTINCT, grouping/aggregates, windows, joins/subqueries,
|
|
92
|
+
universal/system sources, other collection models, TTL and retention are rejected
|
|
93
|
+
explicitly. Materialization is capped at 100,000 visible source rows, independently
|
|
94
|
+
of LIMIT. Superseded and moderated rows use the shared committed-scan visibility;
|
|
95
|
+
secret values in `SELECT *` keep the canonical redacted JSON representation.
|
|
96
|
+
Writes currently require ordinary table contracts without AI/event policies,
|
|
97
|
+
context indexes or encrypted columns. RETURNING, ON CONFLICT, UPDATE LIMIT and
|
|
98
|
+
compound assignment syntax are rejected. Transactions admit at most 100,000
|
|
99
|
+
pending row actions. DML commits use the native WAL batch; catalog changes use
|
|
100
|
+
one complete native snapshot publication. BEGIN copies the committed resident
|
|
101
|
+
image, so transaction startup costs memory proportional to the local database.
|
|
102
|
+
|
|
103
|
+
The embedding application owns this local file and its origin. This API does not
|
|
104
|
+
establish a server user/tenant session or replay server RLS policies: export only
|
|
105
|
+
the authorized subset into an application-owned file. Import a native `.rdb` into
|
|
106
|
+
`navigator.storage.getDirectory()/reddb-browser/<name>.rdb` under the same
|
|
107
|
+
`reddb-browser:<name>` Web Lock before opening it. Keep native binary bytes intact;
|
|
108
|
+
no format translation is needed. Newly created browser databases use the same format.
|
|
109
|
+
|
|
43
110
|
## Shared runtime and language interop
|
|
44
111
|
|
|
45
112
|
`createRuntime({ worker? })` opens no file and requires neither OPFS nor Web
|
|
@@ -57,8 +124,10 @@ try {
|
|
|
57
124
|
|
|
58
125
|
The versioned Worker/WASM contract reports `abiVersion: 1`,
|
|
59
126
|
`valueEncoding: 'reddb-json-v1'` and capabilities. Currently `queryValidation`
|
|
60
|
-
and `scalarQueries` are true
|
|
61
|
-
|
|
127
|
+
and `scalarQueries` are true. Version `0.2.0` also reports `storedQueries: true`
|
|
128
|
+
with `storedQueryMode: 'read-write-tables'`, `sqlWrites: true` and
|
|
129
|
+
`transactions: true`; `sync` remains false.
|
|
130
|
+
Capabilities describe the engine, not the operations exposed by a particular handle. Mismatched SDK/Worker/WASM versions fail with `VERSION_MISMATCH` before
|
|
62
131
|
opening storage. Cache the JS, Worker and WASM as one versioned unit.
|
|
63
132
|
|
|
64
133
|
`createInteropRuntime({ worker? })` returns a synchronous bridge object with
|
|
@@ -124,8 +193,8 @@ adapter supplies file locks, encryption and its WAL writer through a synchronous
|
|
|
124
193
|
barrier; portable pagers without a WAL reject nonzero page LSNs. Shared native/WASM
|
|
125
194
|
fixtures cover failed allocation fences and WAL barriers. The OPFS restart fixture
|
|
126
195
|
uses this complete pager and verifies checkpoint completion through another fresh
|
|
127
|
-
pager.
|
|
128
|
-
|
|
196
|
+
pager. Those page-level fixtures are distinct from the public local SQL API
|
|
197
|
+
described above; encryption and concurrent multi-connection qualification remain pending.
|
|
129
198
|
Native differential tests additionally compare
|
|
130
199
|
the scalar corpus to actual `RedDBRuntime` query results.
|
|
131
200
|
|
|
@@ -193,8 +262,8 @@ HTTPS or a trusted localhost context is required for OPFS and Web Locks.
|
|
|
193
262
|
The browser suite includes a test host's service worker and restarts the entire
|
|
194
263
|
browser with networking disabled. It reloads the JS/worker/WASM assets, recovers
|
|
195
264
|
OPFS data, writes again and executes a scalar query without reaching the HTTP
|
|
196
|
-
host.
|
|
197
|
-
|
|
265
|
+
host. Installed TS/Vite consumers additionally create tables and run CRUD,
|
|
266
|
+
commit and rollback across two offline browser restarts with the HTTP listener stopped.
|
|
198
267
|
|
|
199
268
|
## Shared transaction state
|
|
200
269
|
|
|
@@ -208,10 +277,9 @@ serializable row/vault predicates with tenant separation. On Chromium/Firefox,
|
|
|
208
277
|
the test host also caches this separate conformance artifact and reruns the suite
|
|
209
278
|
after a full offline browser restart with the HTTP listener stopped.
|
|
210
279
|
|
|
211
|
-
These are volatile engine assertions in a test-only WASM artifact.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
recovery still require the runtime integration below.
|
|
280
|
+
These are volatile engine assertions in a test-only WASM artifact. The public
|
|
281
|
+
SDK uses exclusive single-owner transactions as described above; it does not
|
|
282
|
+
expose this full native concurrent-MVCC/savepoint surface.
|
|
215
283
|
|
|
216
284
|
## Shared entities and read visibility
|
|
217
285
|
|
|
@@ -250,9 +318,9 @@ HTTP host stopped, and exports for native verification. It retains opaque
|
|
|
250
318
|
metadata bytes without interpreting native metadata policy. A separate native
|
|
251
319
|
dump test checks the complete entity corpus and actual native metadata. These
|
|
252
320
|
remain test-only records without application collection schemas or transactional
|
|
253
|
-
publication.
|
|
254
|
-
|
|
255
|
-
|
|
321
|
+
publication. The public table SQL API uses these shared codecs with the durable
|
|
322
|
+
query/transaction paths described above. Other collection models remain pending;
|
|
323
|
+
the canonical file format is unchanged.
|
|
256
324
|
|
|
257
325
|
## Shared query records and materialization
|
|
258
326
|
|
|
@@ -279,10 +347,9 @@ materializes full/projected records from its persisted entities after restart
|
|
|
279
347
|
and verifies their fields before native export. Native integration compares
|
|
280
348
|
shared records with actual stored-data query results after dump and paged reopen.
|
|
281
349
|
|
|
282
|
-
These are internal/test-only
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
unfinished. No file format, wire envelope or public browser API changes here.
|
|
350
|
+
These are internal/test-only extraction fixtures. Public local table SQL now
|
|
351
|
+
uses the shared materialization, query and publication paths described above.
|
|
352
|
+
Other collection models remain pending in the public SDK.
|
|
286
353
|
|
|
287
354
|
## Shared resident collection storage
|
|
288
355
|
|
|
@@ -295,10 +362,9 @@ Four shared conformance cases exercise all original record-oracle entity shapes,
|
|
|
295
362
|
key-version lookup and raw mutation, bounded/cancelled scans, metadata and sealing;
|
|
296
363
|
the browser worker repeats them after the existing offline restart.
|
|
297
364
|
|
|
298
|
-
These
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
production artifact/scalar API and all file formats remain unchanged.
|
|
365
|
+
These fixtures exercise canonical resident storage independently of the public
|
|
366
|
+
table SQL and durable transaction API described above. Other collection models
|
|
367
|
+
remain pending; the artifact/scalar API and all file formats remain compatible.
|
|
302
368
|
|
|
303
369
|
## Shared snapshot recovery
|
|
304
370
|
|
|
@@ -315,16 +381,16 @@ invalid counts/tags/UTF-8, nesting at the RQL depth limit, checksum failures,
|
|
|
315
381
|
legacy optional tails and host callback errors. Metadata nesting above the existing
|
|
316
382
|
RQL JSON limit is now rejected; previously the native metadata reader was unbounded.
|
|
317
383
|
The native host retains collection/index restoration, ID allocation and WAL policy.
|
|
318
|
-
|
|
319
|
-
|
|
384
|
+
The public local table SQL API now builds on these recovery primitives; the
|
|
385
|
+
internal fixtures remain separate from application entrypoints.
|
|
320
386
|
|
|
321
387
|
## Remaining work toward the approved Browser design
|
|
322
388
|
|
|
323
389
|
1. Extract the remaining storage-coupled executor/runtime into the shared portable engine and
|
|
324
390
|
preserve native query/transaction semantics for tables, documents, KV, graph
|
|
325
391
|
and vectors. Port clocks, crypto randomness and task scheduling.
|
|
326
|
-
2.
|
|
327
|
-
|
|
392
|
+
2. Add a transactional outbox, change observation, and one-owner request forwarding
|
|
393
|
+
between tabs to the application-facing SDK.
|
|
328
394
|
3. Implement versioned, policy-filtered snapshot and resumable change protocols
|
|
329
395
|
in `reddb-wire` and the server. Revalidate normal authorization/RLS on upload;
|
|
330
396
|
preserve transaction grouping, idempotency, stable graph references and deletes.
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reddb-io/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
|
-
"description": "RedDB browser
|
|
6
|
+
"description": "RedDB local browser table SQL, transactions and offline OPFS persistence through a shared Rust/WASM engine.",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": {
|
|
9
9
|
"types": "./src/index.d.ts",
|
package/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Local table SQL, transactions and persistence in browser-owned OPFS artifacts. */
|
|
2
2
|
export class BrowserError extends Error {
|
|
3
3
|
readonly code: string
|
|
4
4
|
constructor(code: string, message: string)
|
|
@@ -11,6 +11,8 @@ export interface RuntimeInfo {
|
|
|
11
11
|
readonly queryValidation: boolean
|
|
12
12
|
readonly scalarQueries: boolean
|
|
13
13
|
readonly storedQueries: boolean
|
|
14
|
+
readonly storedQueryMode: 'read-write-tables'
|
|
15
|
+
readonly sqlWrites: boolean
|
|
14
16
|
readonly transactions: boolean
|
|
15
17
|
readonly sync: boolean
|
|
16
18
|
}
|
|
@@ -61,3 +63,18 @@ export function openArtifact(options: {
|
|
|
61
63
|
/** Fresh module Worker supplied by a bundler (e.g. Vite ?worker). The artifact owns its lifetime. */
|
|
62
64
|
worker?: Worker
|
|
63
65
|
}): Promise<Artifact>
|
|
66
|
+
|
|
67
|
+
export interface Database extends Runtime {
|
|
68
|
+
/** SELECT and table SQL mutations; mutations return an affectedRows column. */
|
|
69
|
+
query(sql: string): Promise<{ columns: string[]; rows: unknown[][] }>
|
|
70
|
+
/** Release exclusive ownership of the local file and terminate its worker. */
|
|
71
|
+
close(): Promise<void>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Recover an OPFS .rdb. Creation is explicit; corrupt existing files are preserved. */
|
|
75
|
+
export function openDatabase(options: {
|
|
76
|
+
name: string
|
|
77
|
+
/** Create a missing database. Defaults to false. */
|
|
78
|
+
create?: boolean
|
|
79
|
+
worker?: Worker
|
|
80
|
+
}): Promise<Database>
|
package/src/index.js
CHANGED
|
@@ -126,8 +126,8 @@ export function createInteropRuntime({ worker } = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
-
|
|
130
|
-
|
|
129
|
+
async function openFile({ name, worker, create = false } = {}, method = 'open') {
|
|
130
|
+
if (typeof create !== 'boolean') throw new BrowserError('INVALID_ARGUMENT', 'Expected a boolean create option')
|
|
131
131
|
if (typeof name !== 'string' || !/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{0,79}$/.test(name)) {
|
|
132
132
|
throw new BrowserError('INVALID_NAME', 'Artifact names must contain 1–80 letters, digits, dots, underscores or hyphens')
|
|
133
133
|
}
|
|
@@ -135,8 +135,21 @@ export async function openArtifact({ name, worker } = {}) {
|
|
|
135
135
|
throw new BrowserError('STORAGE_UNSUPPORTED', 'RedDB Browser requires HTTPS, module Workers, OPFS and Web Locks')
|
|
136
136
|
}
|
|
137
137
|
const client = createClient(worker)
|
|
138
|
-
try {
|
|
138
|
+
try {
|
|
139
|
+
const info = await client.ready
|
|
140
|
+
if (method === 'openDatabase' && (info.capabilities.storedQueries !== true
|
|
141
|
+
|| info.capabilities.storedQueryMode !== 'read-write-tables' || !info.capabilities.sqlWrites || !info.capabilities.transactions)) {
|
|
142
|
+
throw new BrowserError('VERSION_MISMATCH', 'WASM runtime does not expose local table SQL and transactions')
|
|
143
|
+
}
|
|
144
|
+
await client.call(method, method === 'openDatabase' ? { name, create } : { name })
|
|
145
|
+
}
|
|
139
146
|
catch (error) { client.shutdown(error); throw error }
|
|
147
|
+
return client
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Open an exclusively owned, canonical .rdb artifact in an OPFS worker. */
|
|
151
|
+
export async function openArtifact(options) {
|
|
152
|
+
const client = await openFile(options)
|
|
140
153
|
const { call } = client
|
|
141
154
|
return {
|
|
142
155
|
...runtimeMethods(client),
|
|
@@ -148,3 +161,15 @@ export async function openArtifact({ name, worker } = {}) {
|
|
|
148
161
|
close: client.closeFile,
|
|
149
162
|
}
|
|
150
163
|
}
|
|
164
|
+
|
|
165
|
+
/** Local table SQL and single-owner transactions over a canonical OPFS .rdb. */
|
|
166
|
+
export async function openDatabase(options) {
|
|
167
|
+
const client = await openFile(options, 'openDatabase')
|
|
168
|
+
return {
|
|
169
|
+
...runtimeMethods(client),
|
|
170
|
+
query: sql => typeof sql === 'string'
|
|
171
|
+
? client.call('query', { sql })
|
|
172
|
+
: Promise.reject(new BrowserError('INVALID_ARGUMENT', 'Expected an RQL string')),
|
|
173
|
+
close: client.closeFile,
|
|
174
|
+
}
|
|
175
|
+
}
|
package/src/wasm/reddb_wasm.d.ts
CHANGED
|
@@ -21,6 +21,19 @@ export class BrowserArtifact {
|
|
|
21
21
|
readWal(): Array<any>;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Local SQL over the same canonical snapshot/WAL publication and recovery path.
|
|
26
|
+
* The worker retains the exclusive OPFS handle until this wrapper is freed.
|
|
27
|
+
*/
|
|
28
|
+
export class BrowserDatabase {
|
|
29
|
+
private constructor();
|
|
30
|
+
free(): void;
|
|
31
|
+
[Symbol.dispose](): void;
|
|
32
|
+
static create(handle: any, name: string, now_ms: number): BrowserDatabase;
|
|
33
|
+
static open(handle: any, name: string): BrowserDatabase;
|
|
34
|
+
query(sql: string, now_ms: number): any;
|
|
35
|
+
}
|
|
36
|
+
|
|
24
37
|
/**
|
|
25
38
|
* Experimental storage-free execution, using the native scalar evaluator.
|
|
26
39
|
*/
|
|
@@ -38,6 +51,7 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
|
|
|
38
51
|
export interface InitOutput {
|
|
39
52
|
readonly memory: WebAssembly.Memory;
|
|
40
53
|
readonly __wbg_browserartifact_free: (a: number, b: number) => void;
|
|
54
|
+
readonly __wbg_browserdatabase_free: (a: number, b: number) => void;
|
|
41
55
|
readonly browserartifact_append: (a: number, b: any) => [number, number];
|
|
42
56
|
readonly browserartifact_checkpoint: (a: number, b: number, c: number, d: number) => [number, number];
|
|
43
57
|
readonly browserartifact_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
@@ -45,6 +59,9 @@ export interface InitOutput {
|
|
|
45
59
|
readonly browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
|
|
46
60
|
readonly browserartifact_readSnapshot: (a: number) => [number, number, number, number];
|
|
47
61
|
readonly browserartifact_readWal: (a: number) => [number, number, number];
|
|
62
|
+
readonly browserdatabase_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
63
|
+
readonly browserdatabase_open: (a: any, b: number, c: number) => [number, number, number];
|
|
64
|
+
readonly browserdatabase_query: (a: number, b: number, c: number, d: number) => [number, number, number];
|
|
48
65
|
readonly executeScalar: (a: number, b: number) => [number, number, number];
|
|
49
66
|
readonly runtimeInfo: () => [number, number, number];
|
|
50
67
|
readonly validateQuery: (a: number, b: number) => [number, number];
|
package/src/wasm/reddb_wasm.js
CHANGED
|
@@ -121,6 +121,73 @@ export class BrowserArtifact {
|
|
|
121
121
|
}
|
|
122
122
|
if (Symbol.dispose) BrowserArtifact.prototype[Symbol.dispose] = BrowserArtifact.prototype.free;
|
|
123
123
|
|
|
124
|
+
/**
|
|
125
|
+
* Local SQL over the same canonical snapshot/WAL publication and recovery path.
|
|
126
|
+
* The worker retains the exclusive OPFS handle until this wrapper is freed.
|
|
127
|
+
*/
|
|
128
|
+
export class BrowserDatabase {
|
|
129
|
+
static __wrap(ptr) {
|
|
130
|
+
const obj = Object.create(BrowserDatabase.prototype);
|
|
131
|
+
obj.__wbg_ptr = ptr;
|
|
132
|
+
BrowserDatabaseFinalization.register(obj, obj.__wbg_ptr, obj);
|
|
133
|
+
return obj;
|
|
134
|
+
}
|
|
135
|
+
__destroy_into_raw() {
|
|
136
|
+
const ptr = this.__wbg_ptr;
|
|
137
|
+
this.__wbg_ptr = 0;
|
|
138
|
+
BrowserDatabaseFinalization.unregister(this);
|
|
139
|
+
return ptr;
|
|
140
|
+
}
|
|
141
|
+
free() {
|
|
142
|
+
const ptr = this.__destroy_into_raw();
|
|
143
|
+
wasm.__wbg_browserdatabase_free(ptr, 0);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* @param {any} handle
|
|
147
|
+
* @param {string} name
|
|
148
|
+
* @param {number} now_ms
|
|
149
|
+
* @returns {BrowserDatabase}
|
|
150
|
+
*/
|
|
151
|
+
static create(handle, name, now_ms) {
|
|
152
|
+
const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
153
|
+
const len0 = WASM_VECTOR_LEN;
|
|
154
|
+
const ret = wasm.browserdatabase_create(handle, ptr0, len0, now_ms);
|
|
155
|
+
if (ret[2]) {
|
|
156
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
157
|
+
}
|
|
158
|
+
return BrowserDatabase.__wrap(ret[0]);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* @param {any} handle
|
|
162
|
+
* @param {string} name
|
|
163
|
+
* @returns {BrowserDatabase}
|
|
164
|
+
*/
|
|
165
|
+
static open(handle, name) {
|
|
166
|
+
const ptr0 = passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
167
|
+
const len0 = WASM_VECTOR_LEN;
|
|
168
|
+
const ret = wasm.browserdatabase_open(handle, ptr0, len0);
|
|
169
|
+
if (ret[2]) {
|
|
170
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
171
|
+
}
|
|
172
|
+
return BrowserDatabase.__wrap(ret[0]);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* @param {string} sql
|
|
176
|
+
* @param {number} now_ms
|
|
177
|
+
* @returns {any}
|
|
178
|
+
*/
|
|
179
|
+
query(sql, now_ms) {
|
|
180
|
+
const ptr0 = passStringToWasm0(sql, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
181
|
+
const len0 = WASM_VECTOR_LEN;
|
|
182
|
+
const ret = wasm.browserdatabase_query(this.__wbg_ptr, ptr0, len0, now_ms);
|
|
183
|
+
if (ret[2]) {
|
|
184
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
185
|
+
}
|
|
186
|
+
return takeFromExternrefTable0(ret[0]);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (Symbol.dispose) BrowserDatabase.prototype[Symbol.dispose] = BrowserDatabase.prototype.free;
|
|
190
|
+
|
|
124
191
|
/**
|
|
125
192
|
* Experimental storage-free execution, using the native scalar evaluator.
|
|
126
193
|
* @param {string} sql
|
|
@@ -228,6 +295,10 @@ function __wbg_get_imports() {
|
|
|
228
295
|
const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
|
|
229
296
|
return ret;
|
|
230
297
|
},
|
|
298
|
+
__wbg_now_2f4c4ba4ac7f00bf: function() {
|
|
299
|
+
const ret = Date.now();
|
|
300
|
+
return ret;
|
|
301
|
+
},
|
|
231
302
|
__wbg_parse_342d5616e14beccc: function() { return handleError(function (arg0, arg1) {
|
|
232
303
|
const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
|
|
233
304
|
return ret;
|
|
@@ -278,6 +349,9 @@ function __wbg_get_imports() {
|
|
|
278
349
|
const BrowserArtifactFinalization = (typeof FinalizationRegistry === 'undefined')
|
|
279
350
|
? { register: () => {}, unregister: () => {} }
|
|
280
351
|
: new FinalizationRegistry(ptr => wasm.__wbg_browserartifact_free(ptr, 1));
|
|
352
|
+
const BrowserDatabaseFinalization = (typeof FinalizationRegistry === 'undefined')
|
|
353
|
+
? { register: () => {}, unregister: () => {} }
|
|
354
|
+
: new FinalizationRegistry(ptr => wasm.__wbg_browserdatabase_free(ptr, 1));
|
|
281
355
|
|
|
282
356
|
function addToExternrefTable0(obj) {
|
|
283
357
|
const idx = wasm.__externref_table_alloc();
|
|
Binary file
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
/* eslint-disable */
|
|
3
3
|
export const memory: WebAssembly.Memory;
|
|
4
4
|
export const __wbg_browserartifact_free: (a: number, b: number) => void;
|
|
5
|
+
export const __wbg_browserdatabase_free: (a: number, b: number) => void;
|
|
5
6
|
export const browserartifact_append: (a: number, b: any) => [number, number];
|
|
6
7
|
export const browserartifact_checkpoint: (a: number, b: number, c: number, d: number) => [number, number];
|
|
7
8
|
export const browserartifact_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
@@ -9,6 +10,9 @@ export const browserartifact_generation: (a: number) => [number, number, number,
|
|
|
9
10
|
export const browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
|
|
10
11
|
export const browserartifact_readSnapshot: (a: number) => [number, number, number, number];
|
|
11
12
|
export const browserartifact_readWal: (a: number) => [number, number, number];
|
|
13
|
+
export const browserdatabase_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
14
|
+
export const browserdatabase_open: (a: any, b: number, c: number) => [number, number, number];
|
|
15
|
+
export const browserdatabase_query: (a: number, b: number, c: number, d: number) => [number, number, number];
|
|
12
16
|
export const executeScalar: (a: number, b: number) => [number, number, number];
|
|
13
17
|
export const runtimeInfo: () => [number, number, number];
|
|
14
18
|
export const validateQuery: (a: number, b: number) => [number, number];
|
package/src/worker.js
CHANGED
|
@@ -2,6 +2,7 @@ import init, * as wasm from './wasm/reddb_wasm.js'
|
|
|
2
2
|
import { RUNTIME_ABI_VERSION, VALUE_ENCODING } from './protocol.js'
|
|
3
3
|
|
|
4
4
|
let artifact
|
|
5
|
+
let database
|
|
5
6
|
let access
|
|
6
7
|
let release
|
|
7
8
|
let ownership
|
|
@@ -34,15 +35,23 @@ function synchronous(value) {
|
|
|
34
35
|
return value
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
async function open(name) {
|
|
38
|
+
async function open(name, sqlDatabase = false, create = false) {
|
|
38
39
|
await initialize()
|
|
40
|
+
if (artifact || database) throw error('INVALID_ARGUMENT', 'This worker already owns an open file')
|
|
39
41
|
await new Promise((resolve, reject) => {
|
|
40
42
|
ownership = navigator.locks.request(`reddb-browser:${name}`, { ifAvailable: true }, async (lock) => {
|
|
41
43
|
if (!lock) throw error('FILE_BUSY', 'This artifact is already open in another worker or tab')
|
|
42
44
|
try {
|
|
43
45
|
const root = await navigator.storage.getDirectory()
|
|
44
|
-
const directory = await root.getDirectoryHandle('reddb-browser', { create:
|
|
45
|
-
|
|
46
|
+
const directory = await root.getDirectoryHandle('reddb-browser', { create: !sqlDatabase || create })
|
|
47
|
+
let file
|
|
48
|
+
let created = false
|
|
49
|
+
try { file = await directory.getFileHandle(`${name}.rdb`, { create: !sqlDatabase }) }
|
|
50
|
+
catch (failure) {
|
|
51
|
+
if (!sqlDatabase || !create || failure.name !== 'NotFoundError') throw failure
|
|
52
|
+
file = await directory.getFileHandle(`${name}.rdb`, { create: true })
|
|
53
|
+
created = true
|
|
54
|
+
}
|
|
46
55
|
if (typeof file.createSyncAccessHandle !== 'function') {
|
|
47
56
|
throw error('STORAGE_UNSUPPORTED', 'This browser does not support synchronous OPFS access in a dedicated worker')
|
|
48
57
|
}
|
|
@@ -54,18 +63,25 @@ async function open(name) {
|
|
|
54
63
|
truncate: (size) => synchronous(access.truncate(size)),
|
|
55
64
|
flush: () => synchronous(access.flush()),
|
|
56
65
|
}
|
|
57
|
-
|
|
58
|
-
? wasm.
|
|
59
|
-
: wasm.
|
|
66
|
+
if (sqlDatabase) database = created
|
|
67
|
+
? wasm.BrowserDatabase.create(fileIo, name, Date.now())
|
|
68
|
+
: wasm.BrowserDatabase.open(fileIo, name)
|
|
69
|
+
else artifact = fileIo.getSize() === 0
|
|
70
|
+
? wasm.BrowserArtifact.create(fileIo, name, Date.now())
|
|
71
|
+
: wasm.BrowserArtifact.open(fileIo, name)
|
|
60
72
|
const lifetime = new Promise((resolveRelease) => { release = resolveRelease })
|
|
61
73
|
resolve()
|
|
62
74
|
await lifetime
|
|
63
75
|
} catch (failure) {
|
|
64
|
-
|
|
65
|
-
|
|
76
|
+
const reported = sqlDatabase && failure.name === 'NotFoundError'
|
|
77
|
+
? error('DATABASE_NOT_FOUND', 'The local .rdb file does not exist') : failure
|
|
78
|
+
reject(reported)
|
|
79
|
+
throw reported
|
|
66
80
|
} finally {
|
|
67
81
|
artifact?.free()
|
|
68
82
|
artifact = undefined
|
|
83
|
+
database?.free()
|
|
84
|
+
database = undefined
|
|
69
85
|
if (access) synchronous(access.close())
|
|
70
86
|
access = undefined
|
|
71
87
|
}
|
|
@@ -83,12 +99,26 @@ function bytes(value) {
|
|
|
83
99
|
async function execute(method, params) {
|
|
84
100
|
if (method === 'initialize' || method === 'info') return initialize()
|
|
85
101
|
if (method === 'open') return open(params.name)
|
|
102
|
+
if (method === 'openDatabase') {
|
|
103
|
+
if (typeof params.create !== 'boolean') throw error('INVALID_ARGUMENT', 'Expected a boolean create option')
|
|
104
|
+
return open(params.name, true, params.create)
|
|
105
|
+
}
|
|
86
106
|
if (method === 'validateQuery' || method === 'executeScalar') {
|
|
87
107
|
await initialize()
|
|
88
108
|
if (typeof params.sql !== 'string') throw error('INVALID_ARGUMENT', 'Expected an RQL string')
|
|
89
109
|
return method === 'validateQuery' ? wasm.validateQuery(params.sql) : wasm.executeScalar(params.sql)
|
|
90
110
|
}
|
|
91
|
-
if (!artifact) throw error('CLOSED', 'The
|
|
111
|
+
if (!artifact && !database) throw error('CLOSED', 'The file is not open')
|
|
112
|
+
if (method === 'close') {
|
|
113
|
+
release()
|
|
114
|
+
await ownership
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
if (database) {
|
|
118
|
+
if (method !== 'query') throw error('QUERY_UNSUPPORTED', 'This database handle exposes local SQL')
|
|
119
|
+
if (typeof params.sql !== 'string') throw error('INVALID_ARGUMENT', 'Expected an RQL string')
|
|
120
|
+
return database.query(params.sql, Date.now())
|
|
121
|
+
}
|
|
92
122
|
switch (method) {
|
|
93
123
|
case 'generation': return artifact.generation()
|
|
94
124
|
case 'readWal': return artifact.readWal()
|
|
@@ -101,10 +131,6 @@ async function execute(method, params) {
|
|
|
101
131
|
throw error('INVALID_ARGUMENT', 'WAL capacity must be an unsigned 32-bit integer')
|
|
102
132
|
}
|
|
103
133
|
return artifact.checkpoint(bytes(params.snapshot), params.minWalBytes)
|
|
104
|
-
case 'close':
|
|
105
|
-
release()
|
|
106
|
-
await ownership
|
|
107
|
-
return
|
|
108
134
|
default: throw error('INVALID_ARGUMENT', `Unknown artifact operation: ${method}`)
|
|
109
135
|
}
|
|
110
136
|
}
|