@reddb-io/browser 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -1
- package/package.json +2 -2
- package/src/index.d.ts +12 -1
- package/src/index.js +75 -16
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ 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
|
-
Version `0.
|
|
15
|
+
Version `0.5.0` adds reusable Worker sessions. Native `.rdb` backup export and restore remain available. It exposes local table SELECT, CREATE TABLE, INSERT, UPDATE, DELETE
|
|
16
16
|
and explicit BEGIN/COMMIT/ROLLBACK transactions through `openDatabase`.
|
|
17
17
|
Other models, synchronization, conflict
|
|
18
18
|
resolution and forwarding between tabs remain pending. The browser package
|
|
@@ -43,6 +43,47 @@ try {
|
|
|
43
43
|
Consumers receive built JS/Worker/WASM assets and TypeScript declarations; they
|
|
44
44
|
need no Rust toolchain. The commands below are for engine/package contributors.
|
|
45
45
|
|
|
46
|
+
## Reuse the Worker between file owners
|
|
47
|
+
|
|
48
|
+
Use a session when an application opens and closes a database frequently. The
|
|
49
|
+
session retains the initialized Worker and WASM; each database handle still
|
|
50
|
+
owns an exclusive file lock until it closes. Only one database can be open in
|
|
51
|
+
one session at a time.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { createDatabaseSession } from '@reddb-io/browser'
|
|
55
|
+
import RedDBWorker from '@reddb-io/browser/worker?worker'
|
|
56
|
+
|
|
57
|
+
const session = await createDatabaseSession({ worker: new RedDBWorker() })
|
|
58
|
+
try {
|
|
59
|
+
// Repeat this block for later operations using the same session.
|
|
60
|
+
await navigator.locks.request('my-app-operation', async () => {
|
|
61
|
+
const db = await session.openDatabase({ name: 'my-app', create: true })
|
|
62
|
+
try {
|
|
63
|
+
await db.query('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)')
|
|
64
|
+
console.log(await db.query('SELECT id, body FROM notes'))
|
|
65
|
+
} finally { await db.close() }
|
|
66
|
+
})
|
|
67
|
+
} finally { await session.close() }
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Use the same outer application lock in every tab to queue operations. The SDK's
|
|
71
|
+
file lock still returns `FILE_BUSY` to simultaneous owners; sessions do not add
|
|
72
|
+
cross-tab forwarding or shared transactions. Protect stale application snapshots
|
|
73
|
+
with the application's existing writer/slot locks as well.
|
|
74
|
+
|
|
75
|
+
`db.close()` releases the file and discards an uncommitted transaction. Later
|
|
76
|
+
opens recover the current committed file, including writes by other owners.
|
|
77
|
+
An old handle remains closed even after the session opens another database.
|
|
78
|
+
A failed release fences the session and terminates its Worker. Close/discard a
|
|
79
|
+
session after a Worker failure and create a new one for retry.
|
|
80
|
+
|
|
81
|
+
`session.close()` closes its current file and terminates the Worker. It is
|
|
82
|
+
idempotent; callers must dispose sessions when finished. Keeping WASM initialized
|
|
83
|
+
retains its memory between operations. This amortizes startup, not native file
|
|
84
|
+
recovery or SQL execution. Standalone `openDatabase()` retains its existing
|
|
85
|
+
behavior: its handle closes both file and Worker.
|
|
86
|
+
|
|
46
87
|
## Local table SQL from JS/TS
|
|
47
88
|
|
|
48
89
|
Use `create: true` to create a missing local database. Existing native `.rdb`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reddb-io/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "RedDB local browser table SQL, transactions and offline OPFS persistence through a shared Rust/WASM engine.",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
},
|
|
15
15
|
"scripts": {
|
|
16
16
|
"build": "node scripts/build.mjs",
|
|
17
|
-
"test": "node scripts/build-test.mjs && node --test test/runtime.test.mjs test/browser.test.mjs",
|
|
17
|
+
"test": "node scripts/build-test.mjs && node --test test/runtime.test.mjs test/browser.test.mjs test/session.test.mjs",
|
|
18
18
|
"prepack": "node scripts/verify-dist.mjs",
|
|
19
19
|
"test:distribution": "node --test test/distribution.test.mjs",
|
|
20
20
|
"build:interop": "node scripts/build-interop.mjs",
|
package/src/index.d.ts
CHANGED
|
@@ -74,7 +74,7 @@ export interface Database extends Runtime {
|
|
|
74
74
|
query(sql: string, params?: readonly QueryParameter[]): Promise<{ columns: string[]; rows: unknown[][] }>
|
|
75
75
|
/** Complete native .rdb image of committed state, at most 256 MiB. Pending SQL changes are excluded. */
|
|
76
76
|
exportBackup(): Promise<Uint8Array>
|
|
77
|
-
/** Release
|
|
77
|
+
/** Release file ownership; standalone handles also terminate their Worker. */
|
|
78
78
|
close(): Promise<void>
|
|
79
79
|
}
|
|
80
80
|
|
|
@@ -86,6 +86,17 @@ export function openDatabase(options: {
|
|
|
86
86
|
worker?: Worker
|
|
87
87
|
}): Promise<Database>
|
|
88
88
|
|
|
89
|
+
/** One initialized Worker, with at most one open database at a time. */
|
|
90
|
+
export interface DatabaseSession {
|
|
91
|
+
/** The returned handle releases its file, but retains this session's Worker, on close. */
|
|
92
|
+
openDatabase(options: { name: string; create?: boolean }): Promise<Database>
|
|
93
|
+
/** Close the current file, discard uncommitted changes, and terminate the Worker. */
|
|
94
|
+
close(): Promise<void>
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Retain WASM initialization between file owners; callers must close the session when finished. */
|
|
98
|
+
export function createDatabaseSession(options?: { worker?: Worker }): Promise<DatabaseSession>
|
|
99
|
+
|
|
89
100
|
/** Restore a native .rdb image to a new name. Existing files are never overwritten. */
|
|
90
101
|
export function restoreDatabase(options: {
|
|
91
102
|
name: string
|
package/src/index.js
CHANGED
|
@@ -126,28 +126,38 @@ export function createInteropRuntime({ worker } = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
-
|
|
129
|
+
function requireStorage() {
|
|
130
|
+
if (!globalThis.isSecureContext || !globalThis.Worker || !globalThis.navigator?.storage?.getDirectory || !globalThis.navigator?.locks) {
|
|
131
|
+
throw new BrowserError('STORAGE_UNSUPPORTED', 'RedDB Browser requires HTTPS, module Workers, OPFS and Web Locks')
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function validateFileOptions(name, create) {
|
|
130
136
|
if (typeof create !== 'boolean') throw new BrowserError('INVALID_ARGUMENT', 'Expected a boolean create option')
|
|
131
137
|
if (typeof name !== 'string' || !/^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{0,79}$/.test(name)) {
|
|
132
138
|
throw new BrowserError('INVALID_NAME', 'Artifact names must contain 1–80 letters, digits, dots, underscores or hyphens')
|
|
133
139
|
}
|
|
134
|
-
|
|
135
|
-
|
|
140
|
+
requireStorage()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function openClientFile(client, name, create, backup, method) {
|
|
144
|
+
const info = await client.ready
|
|
145
|
+
const sqlDatabase = method === 'openDatabase' || method === 'restoreDatabase'
|
|
146
|
+
if (sqlDatabase && (info.capabilities.storedQueries !== true
|
|
147
|
+
|| info.capabilities.storedQueryMode !== 'read-write-tables' || !info.capabilities.sqlWrites || !info.capabilities.transactions
|
|
148
|
+
|| info.capabilities.queryParameters !== true)) {
|
|
149
|
+
throw new BrowserError('VERSION_MISMATCH', 'WASM runtime does not expose local table SQL, transactions and parameters')
|
|
136
150
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const info = await client.ready
|
|
140
|
-
const sqlDatabase = method === 'openDatabase' || method === 'restoreDatabase'
|
|
141
|
-
if (sqlDatabase && (info.capabilities.storedQueries !== true
|
|
142
|
-
|| info.capabilities.storedQueryMode !== 'read-write-tables' || !info.capabilities.sqlWrites || !info.capabilities.transactions
|
|
143
|
-
|| info.capabilities.queryParameters !== true)) {
|
|
144
|
-
throw new BrowserError('VERSION_MISMATCH', 'WASM runtime does not expose local table SQL, transactions and parameters')
|
|
145
|
-
}
|
|
146
|
-
if (method === 'restoreDatabase' && info.capabilities.databaseBackups !== true) {
|
|
147
|
-
throw new BrowserError('VERSION_MISMATCH', 'Worker runtime does not expose database backups')
|
|
148
|
-
}
|
|
149
|
-
await client.call(method, sqlDatabase ? { name, create, ...(backup === undefined ? {} : { backup }) } : { name })
|
|
151
|
+
if (method === 'restoreDatabase' && info.capabilities.databaseBackups !== true) {
|
|
152
|
+
throw new BrowserError('VERSION_MISMATCH', 'Worker runtime does not expose database backups')
|
|
150
153
|
}
|
|
154
|
+
await client.call(method, sqlDatabase ? { name, create, ...(backup === undefined ? {} : { backup }) } : { name })
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function openFile({ name, worker, create = false, backup } = {}, method = 'open') {
|
|
158
|
+
validateFileOptions(name, create)
|
|
159
|
+
const client = createClient(worker)
|
|
160
|
+
try { await openClientFile(client, name, create, backup, method) }
|
|
151
161
|
catch (error) { client.shutdown(error); throw error }
|
|
152
162
|
return client
|
|
153
163
|
}
|
|
@@ -172,6 +182,55 @@ export async function openDatabase(options) {
|
|
|
172
182
|
return databaseMethods(await openFile(options, 'openDatabase'))
|
|
173
183
|
}
|
|
174
184
|
|
|
185
|
+
/** Reuse one initialized Worker across sequential, independently owned database handles. */
|
|
186
|
+
export async function createDatabaseSession({ worker } = {}) {
|
|
187
|
+
requireStorage()
|
|
188
|
+
const client = createClient(worker)
|
|
189
|
+
await client.ready
|
|
190
|
+
let active = false
|
|
191
|
+
let closed = false
|
|
192
|
+
let closing
|
|
193
|
+
return {
|
|
194
|
+
async openDatabase({ name, create = false } = {}) {
|
|
195
|
+
if (closed) throw new BrowserError('CLOSED', 'This database session is closed')
|
|
196
|
+
validateFileOptions(name, create)
|
|
197
|
+
if (active) throw new BrowserError('INVALID_ARGUMENT', 'Close the current database before opening another in this session')
|
|
198
|
+
active = true
|
|
199
|
+
try {
|
|
200
|
+
await openClientFile(client, name, create, undefined, 'openDatabase')
|
|
201
|
+
if (closed) throw new BrowserError('CLOSED', 'This database session is closed')
|
|
202
|
+
} catch (error) { active = false; throw error }
|
|
203
|
+
let released = false
|
|
204
|
+
let fileClosing
|
|
205
|
+
return databaseMethods({
|
|
206
|
+
call(method, params) {
|
|
207
|
+
if (released || closed) return Promise.reject(new BrowserError('CLOSED', 'This database handle is closed'))
|
|
208
|
+
return client.call(method, params)
|
|
209
|
+
},
|
|
210
|
+
closeFile() {
|
|
211
|
+
if (!fileClosing) {
|
|
212
|
+
released = true
|
|
213
|
+
fileClosing = closed ? closing : client.call('close').then(() => { active = false }).catch(error => {
|
|
214
|
+
// A failed release cannot lend this Worker to another file owner.
|
|
215
|
+
closed = true
|
|
216
|
+
client.shutdown(error)
|
|
217
|
+
throw error
|
|
218
|
+
})
|
|
219
|
+
}
|
|
220
|
+
return fileClosing
|
|
221
|
+
},
|
|
222
|
+
})
|
|
223
|
+
},
|
|
224
|
+
close() {
|
|
225
|
+
if (!closing) {
|
|
226
|
+
closed = true
|
|
227
|
+
closing = client.closeFile()
|
|
228
|
+
}
|
|
229
|
+
return closing
|
|
230
|
+
},
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
175
234
|
/** Restore a native .rdb backup to a new, exclusively owned OPFS filename. */
|
|
176
235
|
export async function restoreDatabase(options) {
|
|
177
236
|
const backup = options?.backup
|