@reddb-io/browser 0.4.0 → 0.6.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 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.4.0` adds native `.rdb` backup export and restore. It exposes local table SELECT, CREATE TABLE, INSERT, UPDATE, DELETE
15
+ Version `0.6.0` adds local database sessions for Dart/Flutter Web and retains 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.4.0",
3
+ "version": "0.6.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 exclusive ownership of the local file and terminate its worker. */
77
+ /** Release file ownership; standalone handles also terminate their Worker. */
78
78
  close(): Promise<void>
79
79
  }
80
80
 
@@ -86,9 +86,28 @@ 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
92
103
  backup: Uint8Array
93
104
  worker?: Worker
94
105
  }): Promise<Database>
106
+
107
+ /** JSON-safe, token-fenced session operations for JS-interop consumers. */
108
+ export interface DatabaseSessionBridge {
109
+ /** ready, openDatabase, info, query, closeDatabase, close. Failures resolve as envelopes. */
110
+ invoke(method: string, params?: Record<string, unknown>): Promise<InteropResult>
111
+ }
112
+
113
+ export function createInteropDatabaseSession(options?: { worker?: Worker }): DatabaseSessionBridge
package/src/index.js CHANGED
@@ -126,28 +126,38 @@ export function createInteropRuntime({ worker } = {}) {
126
126
  }
127
127
  }
128
128
 
129
- async function openFile({ name, worker, create = false, backup } = {}, method = 'open') {
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
- if (!globalThis.isSecureContext || !globalThis.Worker || !globalThis.navigator?.storage?.getDirectory || !globalThis.navigator?.locks) {
135
- throw new BrowserError('STORAGE_UNSUPPORTED', 'RedDB Browser requires HTTPS, module Workers, OPFS and Web Locks')
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
- const client = createClient(worker)
138
- try {
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,116 @@ 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
+
234
+ /** JSON-safe session boundary for Dart and other JS-interop hosts. */
235
+ export function createInteropDatabaseSession(options = {}) {
236
+ let ready
237
+ try { ready = createDatabaseSession(options) }
238
+ catch (error) { ready = Promise.reject(error) }
239
+ ready.catch(() => {})
240
+ let database
241
+ let handle = 0
242
+ let fileClosing
243
+ let closed = false
244
+ return {
245
+ async invoke(method, params = {}) {
246
+ try {
247
+ if (method === 'close' || (method === 'closeDatabase' && closed)) {
248
+ closed = true
249
+ await (await ready).close()
250
+ return { ok: true, result: null }
251
+ }
252
+ if (closed) throw new BrowserError('CLOSED', 'This database session is closed')
253
+ const session = await ready
254
+ if (closed) throw new BrowserError('CLOSED', 'This database session is closed')
255
+ if (!params || typeof params !== 'object' || Array.isArray(params)) {
256
+ throw new BrowserError('INVALID_ARGUMENT', 'Expected an argument object')
257
+ }
258
+ let result
259
+ switch (method) {
260
+ case 'ready': break
261
+ case 'openDatabase':
262
+ database = await session.openDatabase({ name: params.name, create: params.create ?? false })
263
+ fileClosing = undefined
264
+ result = ++handle
265
+ break
266
+ case 'closeDatabase':
267
+ // A repeated close of an old handle cannot release the current owner.
268
+ if (params.handle === handle) {
269
+ if (database) {
270
+ const releasing = database
271
+ database = undefined
272
+ fileClosing = releasing.close()
273
+ }
274
+ await fileClosing
275
+ }
276
+ break
277
+ case 'info':
278
+ case 'query':
279
+ if (!database || params.handle !== handle) throw new BrowserError('CLOSED', 'This database handle is closed')
280
+ result = method === 'info' ? await database.info() : await database.query(params.sql, params.params)
281
+ break
282
+ default: throw new BrowserError('INVALID_ARGUMENT', 'Unknown database operation')
283
+ }
284
+ return { ok: true, result: result ?? null }
285
+ } catch (error) {
286
+ return { ok: false, error: {
287
+ code: typeof error.code === 'string' ? error.code : 'RUNTIME_ERROR',
288
+ message: error.message || String(error),
289
+ } }
290
+ }
291
+ },
292
+ }
293
+ }
294
+
175
295
  /** Restore a native .rdb backup to a new, exclusively owned OPFS filename. */
176
296
  export async function restoreDatabase(options) {
177
297
  const backup = options?.backup