@reddb-io/browser 0.1.0 → 0.3.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 +124 -33
- package/package.json +2 -2
- package/src/index.d.ts +22 -1
- package/src/index.js +35 -4
- package/src/protocol.js +1 -0
- package/src/wasm/reddb_wasm.d.ts +19 -0
- package/src/wasm/reddb_wasm.js +112 -0
- package/src/wasm/reddb_wasm_bg.wasm +0 -0
- package/src/wasm/reddb_wasm_bg.wasm.d.ts +5 -0
- package/src/worker.js +47 -14
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.3.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,110 @@ 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
|
+
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
|
+
### Positional parameters
|
|
104
|
+
|
|
105
|
+
Use `query(sql, params)` to bind values separately from the SQL text:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
const body = "O'Reilly's offline note"
|
|
109
|
+
await database.query('INSERT INTO notes (id, body) VALUES ($1, $2)', [1, body])
|
|
110
|
+
const found = await database.query('SELECT id, body FROM notes WHERE id = $1', [1])
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The canonical native Rust binder replaces AST parameter nodes with typed literals.
|
|
114
|
+
Values never become SQL syntax. `$1`, `$2`, … and numbered `?1`, `?2`, … use
|
|
115
|
+
one-based, contiguous indexes; repeated indexes reuse the same value. Missing,
|
|
116
|
+
extra or skipped positions return `INVALID_PARAMS` and abort an active SQL
|
|
117
|
+
transaction until ROLLBACK. Invalid JavaScript argument types are rejected before
|
|
118
|
+
statement execution.
|
|
119
|
+
|
|
120
|
+
Parameters accept `null`, boolean, string, finite fractional numbers, safe integer
|
|
121
|
+
numbers and `bigint` in the signed i64 or unsigned u64 range. Unsafe integer
|
|
122
|
+
numbers must use `bigint`; exact results retain the existing `$int`/`$uint` tags.
|
|
123
|
+
Objects, arrays, dates and binary values are not parameter values in this release.
|
|
124
|
+
At most 65,536 values are admitted. Bind parameters in supported SELECT/INSERT/
|
|
125
|
+
UPDATE/DELETE expressions, including LIMIT (> 0) and OFFSET (>= 0); table/column
|
|
126
|
+
names, operators and DDL are not parameterized.
|
|
127
|
+
|
|
128
|
+
The embedding application owns this local file and its origin. This API does not
|
|
129
|
+
establish a server user/tenant session or replay server RLS policies: export only
|
|
130
|
+
the authorized subset into an application-owned file. Import a native `.rdb` into
|
|
131
|
+
`navigator.storage.getDirectory()/reddb-browser/<name>.rdb` under the same
|
|
132
|
+
`reddb-browser:<name>` Web Lock before opening it. Keep native binary bytes intact;
|
|
133
|
+
no format translation is needed. Newly created browser databases use the same format.
|
|
134
|
+
|
|
43
135
|
## Shared runtime and language interop
|
|
44
136
|
|
|
45
137
|
`createRuntime({ worker? })` opens no file and requires neither OPFS nor Web
|
|
@@ -57,8 +149,10 @@ try {
|
|
|
57
149
|
|
|
58
150
|
The versioned Worker/WASM contract reports `abiVersion: 1`,
|
|
59
151
|
`valueEncoding: 'reddb-json-v1'` and capabilities. Currently `queryValidation`
|
|
60
|
-
and `scalarQueries` are true
|
|
61
|
-
|
|
152
|
+
and `scalarQueries` are true. Version `0.3.0` also reports `storedQueries: true`
|
|
153
|
+
with `storedQueryMode: 'read-write-tables'`, `sqlWrites: true` and
|
|
154
|
+
`transactions: true` and `queryParameters: true`; `sync` remains false.
|
|
155
|
+
Capabilities describe the engine, not the operations exposed by a particular handle. Mismatched SDK/Worker/WASM versions fail with `VERSION_MISMATCH` before
|
|
62
156
|
opening storage. Cache the JS, Worker and WASM as one versioned unit.
|
|
63
157
|
|
|
64
158
|
`createInteropRuntime({ worker? })` returns a synchronous bridge object with
|
|
@@ -124,8 +218,8 @@ adapter supplies file locks, encryption and its WAL writer through a synchronous
|
|
|
124
218
|
barrier; portable pagers without a WAL reject nonzero page LSNs. Shared native/WASM
|
|
125
219
|
fixtures cover failed allocation fences and WAL barriers. The OPFS restart fixture
|
|
126
220
|
uses this complete pager and verifies checkpoint completion through another fresh
|
|
127
|
-
pager.
|
|
128
|
-
|
|
221
|
+
pager. Those page-level fixtures are distinct from the public local SQL API
|
|
222
|
+
described above; encryption and concurrent multi-connection qualification remain pending.
|
|
129
223
|
Native differential tests additionally compare
|
|
130
224
|
the scalar corpus to actual `RedDBRuntime` query results.
|
|
131
225
|
|
|
@@ -193,8 +287,8 @@ HTTPS or a trusted localhost context is required for OPFS and Web Locks.
|
|
|
193
287
|
The browser suite includes a test host's service worker and restarts the entire
|
|
194
288
|
browser with networking disabled. It reloads the JS/worker/WASM assets, recovers
|
|
195
289
|
OPFS data, writes again and executes a scalar query without reaching the HTTP
|
|
196
|
-
host.
|
|
197
|
-
|
|
290
|
+
host. Installed TS/Vite consumers additionally create tables and run CRUD,
|
|
291
|
+
commit and rollback across two offline browser restarts with the HTTP listener stopped.
|
|
198
292
|
|
|
199
293
|
## Shared transaction state
|
|
200
294
|
|
|
@@ -208,10 +302,9 @@ serializable row/vault predicates with tenant separation. On Chromium/Firefox,
|
|
|
208
302
|
the test host also caches this separate conformance artifact and reruns the suite
|
|
209
303
|
after a full offline browser restart with the HTTP listener stopped.
|
|
210
304
|
|
|
211
|
-
These are volatile engine assertions in a test-only WASM artifact.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
recovery still require the runtime integration below.
|
|
305
|
+
These are volatile engine assertions in a test-only WASM artifact. The public
|
|
306
|
+
SDK uses exclusive single-owner transactions as described above; it does not
|
|
307
|
+
expose this full native concurrent-MVCC/savepoint surface.
|
|
215
308
|
|
|
216
309
|
## Shared entities and read visibility
|
|
217
310
|
|
|
@@ -250,9 +343,9 @@ HTTP host stopped, and exports for native verification. It retains opaque
|
|
|
250
343
|
metadata bytes without interpreting native metadata policy. A separate native
|
|
251
344
|
dump test checks the complete entity corpus and actual native metadata. These
|
|
252
345
|
remain test-only records without application collection schemas or transactional
|
|
253
|
-
publication.
|
|
254
|
-
|
|
255
|
-
|
|
346
|
+
publication. The public table SQL API uses these shared codecs with the durable
|
|
347
|
+
query/transaction paths described above. Other collection models remain pending;
|
|
348
|
+
the canonical file format is unchanged.
|
|
256
349
|
|
|
257
350
|
## Shared query records and materialization
|
|
258
351
|
|
|
@@ -279,10 +372,9 @@ materializes full/projected records from its persisted entities after restart
|
|
|
279
372
|
and verifies their fields before native export. Native integration compares
|
|
280
373
|
shared records with actual stored-data query results after dump and paged reopen.
|
|
281
374
|
|
|
282
|
-
These are internal/test-only
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
unfinished. No file format, wire envelope or public browser API changes here.
|
|
375
|
+
These are internal/test-only extraction fixtures. Public local table SQL now
|
|
376
|
+
uses the shared materialization, query and publication paths described above.
|
|
377
|
+
Other collection models remain pending in the public SDK.
|
|
286
378
|
|
|
287
379
|
## Shared resident collection storage
|
|
288
380
|
|
|
@@ -295,10 +387,9 @@ Four shared conformance cases exercise all original record-oracle entity shapes,
|
|
|
295
387
|
key-version lookup and raw mutation, bounded/cancelled scans, metadata and sealing;
|
|
296
388
|
the browser worker repeats them after the existing offline restart.
|
|
297
389
|
|
|
298
|
-
These
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
production artifact/scalar API and all file formats remain unchanged.
|
|
390
|
+
These fixtures exercise canonical resident storage independently of the public
|
|
391
|
+
table SQL and durable transaction API described above. Other collection models
|
|
392
|
+
remain pending; the artifact/scalar API and all file formats remain compatible.
|
|
302
393
|
|
|
303
394
|
## Shared snapshot recovery
|
|
304
395
|
|
|
@@ -315,16 +406,16 @@ invalid counts/tags/UTF-8, nesting at the RQL depth limit, checksum failures,
|
|
|
315
406
|
legacy optional tails and host callback errors. Metadata nesting above the existing
|
|
316
407
|
RQL JSON limit is now rejected; previously the native metadata reader was unbounded.
|
|
317
408
|
The native host retains collection/index restoration, ID allocation and WAL policy.
|
|
318
|
-
|
|
319
|
-
|
|
409
|
+
The public local table SQL API now builds on these recovery primitives; the
|
|
410
|
+
internal fixtures remain separate from application entrypoints.
|
|
320
411
|
|
|
321
412
|
## Remaining work toward the approved Browser design
|
|
322
413
|
|
|
323
414
|
1. Extract the remaining storage-coupled executor/runtime into the shared portable engine and
|
|
324
415
|
preserve native query/transaction semantics for tables, documents, KV, graph
|
|
325
416
|
and vectors. Port clocks, crypto randomness and task scheduling.
|
|
326
|
-
2.
|
|
327
|
-
|
|
417
|
+
2. Add a transactional outbox, change observation, and one-owner request forwarding
|
|
418
|
+
between tabs to the application-facing SDK.
|
|
328
419
|
3. Implement versioned, policy-filtered snapshot and resumable change protocols
|
|
329
420
|
in `reddb-wire` and the server. Revalidate normal authorization/RLS on upload;
|
|
330
421
|
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.3.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,7 +11,10 @@ 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
|
|
17
|
+
readonly queryParameters?: boolean
|
|
15
18
|
readonly sync: boolean
|
|
16
19
|
}
|
|
17
20
|
}
|
|
@@ -61,3 +64,21 @@ export function openArtifact(options: {
|
|
|
61
64
|
/** Fresh module Worker supplied by a bundler (e.g. Vite ?worker). The artifact owns its lifetime. */
|
|
62
65
|
worker?: Worker
|
|
63
66
|
}): Promise<Artifact>
|
|
67
|
+
|
|
68
|
+
/** Scalars bind as AST literals; integer numbers must be safe and bigints fit i64/u64. */
|
|
69
|
+
export type QueryParameter = null | boolean | number | string | bigint
|
|
70
|
+
|
|
71
|
+
export interface Database extends Runtime {
|
|
72
|
+
/** SELECT and table SQL mutations; mutations return an affectedRows column. */
|
|
73
|
+
query(sql: string, params?: readonly QueryParameter[]): Promise<{ columns: string[]; rows: unknown[][] }>
|
|
74
|
+
/** Release exclusive ownership of the local file and terminate its worker. */
|
|
75
|
+
close(): Promise<void>
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Recover an OPFS .rdb. Creation is explicit; corrupt existing files are preserved. */
|
|
79
|
+
export function openDatabase(options: {
|
|
80
|
+
name: string
|
|
81
|
+
/** Create a missing database. Defaults to false. */
|
|
82
|
+
create?: boolean
|
|
83
|
+
worker?: Worker
|
|
84
|
+
}): Promise<Database>
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Shared Rust/WASM runtime and artifact storage. */
|
|
2
|
-
import { BrowserError, RUNTIME_ABI_VERSION, VALUE_ENCODING } from './protocol.js'
|
|
2
|
+
import { BrowserError, RUNTIME_ABI_VERSION, VALUE_ENCODING, MAX_QUERY_PARAMETERS } from './protocol.js'
|
|
3
3
|
export { BrowserError } from './protocol.js'
|
|
4
4
|
|
|
5
5
|
function createClient(suppliedWorker) {
|
|
@@ -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,22 @@ 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
|
+
|| info.capabilities.queryParameters !== true)) {
|
|
143
|
+
throw new BrowserError('VERSION_MISMATCH', 'WASM runtime does not expose local table SQL, transactions and parameters')
|
|
144
|
+
}
|
|
145
|
+
await client.call(method, method === 'openDatabase' ? { name, create } : { name })
|
|
146
|
+
}
|
|
139
147
|
catch (error) { client.shutdown(error); throw error }
|
|
148
|
+
return client
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Open an exclusively owned, canonical .rdb artifact in an OPFS worker. */
|
|
152
|
+
export async function openArtifact(options) {
|
|
153
|
+
const client = await openFile(options)
|
|
140
154
|
const { call } = client
|
|
141
155
|
return {
|
|
142
156
|
...runtimeMethods(client),
|
|
@@ -148,3 +162,20 @@ export async function openArtifact({ name, worker } = {}) {
|
|
|
148
162
|
close: client.closeFile,
|
|
149
163
|
}
|
|
150
164
|
}
|
|
165
|
+
|
|
166
|
+
/** Local table SQL and single-owner transactions over a canonical OPFS .rdb. */
|
|
167
|
+
export async function openDatabase(options) {
|
|
168
|
+
const client = await openFile(options, 'openDatabase')
|
|
169
|
+
return {
|
|
170
|
+
...runtimeMethods(client),
|
|
171
|
+
query(sql, params) {
|
|
172
|
+
if (typeof sql !== 'string') return Promise.reject(new BrowserError('INVALID_ARGUMENT', 'Expected an RQL string'))
|
|
173
|
+
if (params === undefined) return client.call('query', { sql })
|
|
174
|
+
if (!Array.isArray(params) || params.length > MAX_QUERY_PARAMETERS) {
|
|
175
|
+
return Promise.reject(new BrowserError('INVALID_ARGUMENT', 'Expected an array of at most 65536 positional parameters'))
|
|
176
|
+
}
|
|
177
|
+
return client.call('queryWithParams', { sql, params })
|
|
178
|
+
},
|
|
179
|
+
close: client.closeFile,
|
|
180
|
+
}
|
|
181
|
+
}
|
package/src/protocol.js
CHANGED
package/src/wasm/reddb_wasm.d.ts
CHANGED
|
@@ -21,6 +21,20 @@ 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
|
+
queryWithParams(sql: string, params: Array<any>, now_ms: number): any;
|
|
36
|
+
}
|
|
37
|
+
|
|
24
38
|
/**
|
|
25
39
|
* Experimental storage-free execution, using the native scalar evaluator.
|
|
26
40
|
*/
|
|
@@ -38,6 +52,7 @@ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembl
|
|
|
38
52
|
export interface InitOutput {
|
|
39
53
|
readonly memory: WebAssembly.Memory;
|
|
40
54
|
readonly __wbg_browserartifact_free: (a: number, b: number) => void;
|
|
55
|
+
readonly __wbg_browserdatabase_free: (a: number, b: number) => void;
|
|
41
56
|
readonly browserartifact_append: (a: number, b: any) => [number, number];
|
|
42
57
|
readonly browserartifact_checkpoint: (a: number, b: number, c: number, d: number) => [number, number];
|
|
43
58
|
readonly browserartifact_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
@@ -45,6 +60,10 @@ export interface InitOutput {
|
|
|
45
60
|
readonly browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
|
|
46
61
|
readonly browserartifact_readSnapshot: (a: number) => [number, number, number, number];
|
|
47
62
|
readonly browserartifact_readWal: (a: number) => [number, number, number];
|
|
63
|
+
readonly browserdatabase_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
64
|
+
readonly browserdatabase_open: (a: any, b: number, c: number) => [number, number, number];
|
|
65
|
+
readonly browserdatabase_query: (a: number, b: number, c: number, d: number) => [number, number, number];
|
|
66
|
+
readonly browserdatabase_queryWithParams: (a: number, b: number, c: number, d: any, e: number) => [number, number, number];
|
|
48
67
|
readonly executeScalar: (a: number, b: number) => [number, number, number];
|
|
49
68
|
readonly runtimeInfo: () => [number, number, number];
|
|
50
69
|
readonly validateQuery: (a: number, b: number) => [number, number];
|
package/src/wasm/reddb_wasm.js
CHANGED
|
@@ -121,6 +121,88 @@ 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
|
+
* @param {string} sql
|
|
190
|
+
* @param {Array<any>} params
|
|
191
|
+
* @param {number} now_ms
|
|
192
|
+
* @returns {any}
|
|
193
|
+
*/
|
|
194
|
+
queryWithParams(sql, params, now_ms) {
|
|
195
|
+
const ptr0 = passStringToWasm0(sql, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
196
|
+
const len0 = WASM_VECTOR_LEN;
|
|
197
|
+
const ret = wasm.browserdatabase_queryWithParams(this.__wbg_ptr, ptr0, len0, params, now_ms);
|
|
198
|
+
if (ret[2]) {
|
|
199
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
200
|
+
}
|
|
201
|
+
return takeFromExternrefTable0(ret[0]);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (Symbol.dispose) BrowserDatabase.prototype[Symbol.dispose] = BrowserDatabase.prototype.free;
|
|
205
|
+
|
|
124
206
|
/**
|
|
125
207
|
* Experimental storage-free execution, using the native scalar evaluator.
|
|
126
208
|
* @param {string} sql
|
|
@@ -162,6 +244,25 @@ export function validateQuery(sql) {
|
|
|
162
244
|
function __wbg_get_imports() {
|
|
163
245
|
const import0 = {
|
|
164
246
|
__proto__: null,
|
|
247
|
+
__wbg___wbindgen_boolean_get_c3dd5c39f1b5a12b: function(arg0) {
|
|
248
|
+
const v = arg0;
|
|
249
|
+
const ret = typeof(v) === 'boolean' ? v : undefined;
|
|
250
|
+
return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;
|
|
251
|
+
},
|
|
252
|
+
__wbg___wbindgen_is_bigint_d6a8167cac401b95: function(arg0) {
|
|
253
|
+
const ret = typeof(arg0) === 'bigint';
|
|
254
|
+
return ret;
|
|
255
|
+
},
|
|
256
|
+
__wbg___wbindgen_is_null_066086be3abe9bb3: function(arg0) {
|
|
257
|
+
const ret = arg0 === null;
|
|
258
|
+
return ret;
|
|
259
|
+
},
|
|
260
|
+
__wbg___wbindgen_number_get_dd6d69a6079f26f1: function(arg0, arg1) {
|
|
261
|
+
const obj = arg1;
|
|
262
|
+
const ret = typeof(obj) === 'number' ? obj : undefined;
|
|
263
|
+
getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
|
|
264
|
+
getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
|
|
265
|
+
},
|
|
165
266
|
__wbg___wbindgen_string_get_965592073e5d848c: function(arg0, arg1) {
|
|
166
267
|
const obj = arg1;
|
|
167
268
|
const ret = typeof(obj) === 'string' ? obj : undefined;
|
|
@@ -228,6 +329,10 @@ function __wbg_get_imports() {
|
|
|
228
329
|
const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
|
|
229
330
|
return ret;
|
|
230
331
|
},
|
|
332
|
+
__wbg_now_2f4c4ba4ac7f00bf: function() {
|
|
333
|
+
const ret = Date.now();
|
|
334
|
+
return ret;
|
|
335
|
+
},
|
|
231
336
|
__wbg_parse_342d5616e14beccc: function() { return handleError(function (arg0, arg1) {
|
|
232
337
|
const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
|
|
233
338
|
return ret;
|
|
@@ -247,6 +352,10 @@ function __wbg_get_imports() {
|
|
|
247
352
|
const ret = Reflect.set(arg0, arg1, arg2);
|
|
248
353
|
return ret;
|
|
249
354
|
}, arguments); },
|
|
355
|
+
__wbg_toString_7fbc0abf5c3327f5: function() { return handleError(function (arg0, arg1) {
|
|
356
|
+
const ret = arg0.toString(arg1);
|
|
357
|
+
return ret;
|
|
358
|
+
}, arguments); },
|
|
250
359
|
__wbg_truncate_d9e55b46e14f9493: function() { return handleError(function (arg0, arg1) {
|
|
251
360
|
arg0.truncate(arg1);
|
|
252
361
|
}, arguments); },
|
|
@@ -278,6 +387,9 @@ function __wbg_get_imports() {
|
|
|
278
387
|
const BrowserArtifactFinalization = (typeof FinalizationRegistry === 'undefined')
|
|
279
388
|
? { register: () => {}, unregister: () => {} }
|
|
280
389
|
: new FinalizationRegistry(ptr => wasm.__wbg_browserartifact_free(ptr, 1));
|
|
390
|
+
const BrowserDatabaseFinalization = (typeof FinalizationRegistry === 'undefined')
|
|
391
|
+
? { register: () => {}, unregister: () => {} }
|
|
392
|
+
: new FinalizationRegistry(ptr => wasm.__wbg_browserdatabase_free(ptr, 1));
|
|
281
393
|
|
|
282
394
|
function addToExternrefTable0(obj) {
|
|
283
395
|
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,10 @@ 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];
|
|
16
|
+
export const browserdatabase_queryWithParams: (a: number, b: number, c: number, d: any, e: number) => [number, number, number];
|
|
12
17
|
export const executeScalar: (a: number, b: number) => [number, number, number];
|
|
13
18
|
export const runtimeInfo: () => [number, number, number];
|
|
14
19
|
export const validateQuery: (a: number, b: number) => [number, number];
|
package/src/worker.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import init, * as wasm from './wasm/reddb_wasm.js'
|
|
2
|
-
import { RUNTIME_ABI_VERSION, VALUE_ENCODING } from './protocol.js'
|
|
2
|
+
import { RUNTIME_ABI_VERSION, VALUE_ENCODING, MAX_QUERY_PARAMETERS } 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,33 @@ 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' && method !== 'queryWithParams') 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
|
+
if (method === 'queryWithParams') {
|
|
121
|
+
if (!Array.isArray(params.params) || params.params.length > MAX_QUERY_PARAMETERS) {
|
|
122
|
+
throw error('INVALID_ARGUMENT', 'Expected an array of at most 65536 positional parameters')
|
|
123
|
+
}
|
|
124
|
+
if (typeof database.queryWithParams !== 'function') throw error('VERSION_MISMATCH', 'WASM parameter binding is missing')
|
|
125
|
+
return database.queryWithParams(params.sql, params.params, Date.now())
|
|
126
|
+
}
|
|
127
|
+
return database.query(params.sql, Date.now())
|
|
128
|
+
}
|
|
92
129
|
switch (method) {
|
|
93
130
|
case 'generation': return artifact.generation()
|
|
94
131
|
case 'readWal': return artifact.readWal()
|
|
@@ -101,10 +138,6 @@ async function execute(method, params) {
|
|
|
101
138
|
throw error('INVALID_ARGUMENT', 'WAL capacity must be an unsigned 32-bit integer')
|
|
102
139
|
}
|
|
103
140
|
return artifact.checkpoint(bytes(params.snapshot), params.minWalBytes)
|
|
104
|
-
case 'close':
|
|
105
|
-
release()
|
|
106
|
-
await ownership
|
|
107
|
-
return
|
|
108
141
|
default: throw error('INVALID_ARGUMENT', `Unknown artifact operation: ${method}`)
|
|
109
142
|
}
|
|
110
143
|
}
|