@reddb-io/browser 0.3.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 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.3.0` exposes local table SELECT, CREATE TABLE, INSERT, UPDATE, DELETE
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`
@@ -149,9 +190,9 @@ try {
149
190
 
150
191
  The versioned Worker/WASM contract reports `abiVersion: 1`,
151
192
  `valueEncoding: 'reddb-json-v1'` and capabilities. Currently `queryValidation`
152
- and `scalarQueries` are true. Version `0.3.0` also reports `storedQueries: true`
193
+ and `scalarQueries` are true. Version `0.4.0` also reports `storedQueries: true`
153
194
  with `storedQueryMode: 'read-write-tables'`, `sqlWrites: true` and
154
- `transactions: true` and `queryParameters: true`; `sync` remains false.
195
+ `transactions: true`, `queryParameters: true` and `databaseBackups: true`; `sync` remains false.
155
196
  Capabilities describe the engine, not the operations exposed by a particular handle. Mismatched SDK/Worker/WASM versions fail with `VERSION_MISMATCH` before
156
197
  opening storage. Cache the JS, Worker and WASM as one versioned unit.
157
198
 
@@ -275,6 +316,46 @@ OPFS is subject to origin quota, storage eviction and explicit site-data clearin
275
316
  Applications can request persistent storage through `navigator.storage.persist()`;
276
317
  these primitives do not promise that a browser will grant it or sync after closing.
277
318
 
319
+ ## Database backups
320
+
321
+ `database.exportBackup()` returns a `Uint8Array` containing the complete native
322
+ `.rdb` file, including its committed catalog, snapshot and WAL. The Worker keeps
323
+ exclusive ownership while reading the file and transfers the resulting buffer
324
+ to the caller. No SQL is generated and no storage format is reimplemented in JS.
325
+ An active transaction stays active; its uncommitted changes are excluded.
326
+ The Rust publication fence is checked before copying. A backup read/flush failure
327
+ closes the owner; reopen and recover before issuing more operations. A size-limit
328
+ rejection leaves the handle usable.
329
+
330
+ ```ts
331
+ import { restoreDatabase } from '@reddb-io/browser'
332
+ import RedDBWorker from '@reddb-io/browser/worker?worker'
333
+
334
+ const backup = await database.exportBackup()
335
+ // Save these bytes outside this origin, for example as a downloaded .rdb file.
336
+ const restored = await restoreDatabase({
337
+ name: 'my-app-restored', backup, worker: new RedDBWorker(),
338
+ })
339
+ try { console.log(await restored.query('SELECT * FROM notes')) }
340
+ finally { await restored.close() }
341
+ ```
342
+
343
+ Restore requires a new name. An existing file returns `DATABASE_EXISTS`; an
344
+ actively owned destination returns `FILE_BUSY`. It writes the new file, flushes
345
+ it and opens it through the canonical Rust engine before returning a handle.
346
+ A rejected backup removes only its newly created destination before reporting
347
+ the failure. Worker/browser termination during restore can leave an incomplete
348
+ new destination; it is never silently overwritten on retry.
349
+
350
+ Backups are bounded at 256 MiB of physical file bytes. The embedding application
351
+ owns file selection, download and retention. These are complete physical copies,
352
+ which can contain older/deleted bytes, not compacted or redacted exports. They
353
+ do not provide additional encryption, synchronization or tenant filtering.
354
+ Treat backups as sensitive and export only an authorized database. File codecs,
355
+ format versions and native publication/recovery remain unchanged. Export takes
356
+ O(file size) reads and one full JS buffer; restore also holds the input and the
357
+ recovered resident database in memory. No performance improvement is claimed.
358
+
278
359
  ## Offline asset loading
279
360
 
280
361
  The SDK does not register a service worker or control application updates. A
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/browser",
3
- "version": "0.3.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
@@ -15,6 +15,7 @@ export interface RuntimeInfo {
15
15
  readonly sqlWrites: boolean
16
16
  readonly transactions: boolean
17
17
  readonly queryParameters?: boolean
18
+ readonly databaseBackups?: boolean
18
19
  readonly sync: boolean
19
20
  }
20
21
  }
@@ -71,7 +72,9 @@ export type QueryParameter = null | boolean | number | string | bigint
71
72
  export interface Database extends Runtime {
72
73
  /** SELECT and table SQL mutations; mutations return an affectedRows column. */
73
74
  query(sql: string, params?: readonly QueryParameter[]): Promise<{ columns: string[]; rows: unknown[][] }>
74
- /** Release exclusive ownership of the local file and terminate its worker. */
75
+ /** Complete native .rdb image of committed state, at most 256 MiB. Pending SQL changes are excluded. */
76
+ exportBackup(): Promise<Uint8Array>
77
+ /** Release file ownership; standalone handles also terminate their Worker. */
75
78
  close(): Promise<void>
76
79
  }
77
80
 
@@ -82,3 +85,21 @@ export function openDatabase(options: {
82
85
  create?: boolean
83
86
  worker?: Worker
84
87
  }): Promise<Database>
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
+
100
+ /** Restore a native .rdb image to a new name. Existing files are never overwritten. */
101
+ export function restoreDatabase(options: {
102
+ name: string
103
+ backup: Uint8Array
104
+ worker?: Worker
105
+ }): 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, MAX_QUERY_PARAMETERS } from './protocol.js'
2
+ import { BrowserError, RUNTIME_ABI_VERSION, VALUE_ENCODING, MAX_QUERY_PARAMETERS, MAX_DATABASE_BACKUP_BYTES } from './protocol.js'
3
3
  export { BrowserError } from './protocol.js'
4
4
 
5
5
  function createClient(suppliedWorker) {
@@ -126,24 +126,38 @@ export function createInteropRuntime({ worker } = {}) {
126
126
  }
127
127
  }
128
128
 
129
- async function openFile({ name, worker, create = false } = {}, 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
- 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 })
151
+ if (method === 'restoreDatabase' && info.capabilities.databaseBackups !== true) {
152
+ throw new BrowserError('VERSION_MISMATCH', 'Worker runtime does not expose database backups')
146
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) }
147
161
  catch (error) { client.shutdown(error); throw error }
148
162
  return client
149
163
  }
@@ -165,7 +179,68 @@ export async function openArtifact(options) {
165
179
 
166
180
  /** Local table SQL and single-owner transactions over a canonical OPFS .rdb. */
167
181
  export async function openDatabase(options) {
168
- const client = await openFile(options, 'openDatabase')
182
+ return databaseMethods(await openFile(options, 'openDatabase'))
183
+ }
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
+ /** Restore a native .rdb backup to a new, exclusively owned OPFS filename. */
235
+ export async function restoreDatabase(options) {
236
+ const backup = options?.backup
237
+ if (!(backup instanceof Uint8Array) || !backup.byteLength || backup.byteLength > MAX_DATABASE_BACKUP_BYTES) {
238
+ throw new BrowserError('INVALID_ARGUMENT', 'Expected a nonempty .rdb backup of at most 256 MiB as Uint8Array')
239
+ }
240
+ return databaseMethods(await openFile(options, 'restoreDatabase'))
241
+ }
242
+
243
+ function databaseMethods(client) {
169
244
  return {
170
245
  ...runtimeMethods(client),
171
246
  query(sql, params) {
@@ -176,6 +251,7 @@ export async function openDatabase(options) {
176
251
  }
177
252
  return client.call('queryWithParams', { sql, params })
178
253
  },
254
+ exportBackup: () => client.call('exportBackup'),
179
255
  close: client.closeFile,
180
256
  }
181
257
  }
package/src/protocol.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export const RUNTIME_ABI_VERSION = 1
2
2
  export const VALUE_ENCODING = 'reddb-json-v1'
3
3
  export const MAX_QUERY_PARAMETERS = 65_536
4
+ export const MAX_DATABASE_BACKUP_BYTES = 256 * 1024 * 1024
4
5
 
5
6
  export class BrowserError extends Error {
6
7
  constructor(code, message) {
@@ -29,6 +29,7 @@ export class BrowserDatabase {
29
29
  private constructor();
30
30
  free(): void;
31
31
  [Symbol.dispose](): void;
32
+ checkHealthy(): void;
32
33
  static create(handle: any, name: string, now_ms: number): BrowserDatabase;
33
34
  static open(handle: any, name: string): BrowserDatabase;
34
35
  query(sql: string, now_ms: number): any;
@@ -60,6 +61,7 @@ export interface InitOutput {
60
61
  readonly browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
61
62
  readonly browserartifact_readSnapshot: (a: number) => [number, number, number, number];
62
63
  readonly browserartifact_readWal: (a: number) => [number, number, number];
64
+ readonly browserdatabase_checkHealthy: (a: number) => [number, number];
63
65
  readonly browserdatabase_create: (a: any, b: number, c: number, d: number) => [number, number, number];
64
66
  readonly browserdatabase_open: (a: any, b: number, c: number) => [number, number, number];
65
67
  readonly browserdatabase_query: (a: number, b: number, c: number, d: number) => [number, number, number];
@@ -142,6 +142,12 @@ export class BrowserDatabase {
142
142
  const ptr = this.__destroy_into_raw();
143
143
  wasm.__wbg_browserdatabase_free(ptr, 0);
144
144
  }
145
+ checkHealthy() {
146
+ const ret = wasm.browserdatabase_checkHealthy(this.__wbg_ptr);
147
+ if (ret[1]) {
148
+ throw takeFromExternrefTable0(ret[0]);
149
+ }
150
+ }
145
151
  /**
146
152
  * @param {any} handle
147
153
  * @param {string} name
Binary file
@@ -10,6 +10,7 @@ export const browserartifact_generation: (a: number) => [number, number, number,
10
10
  export const browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
11
11
  export const browserartifact_readSnapshot: (a: number) => [number, number, number, number];
12
12
  export const browserartifact_readWal: (a: number) => [number, number, number];
13
+ export const browserdatabase_checkHealthy: (a: number) => [number, number];
13
14
  export const browserdatabase_create: (a: any, b: number, c: number, d: number) => [number, number, number];
14
15
  export const browserdatabase_open: (a: any, b: number, c: number) => [number, number, number];
15
16
  export const browserdatabase_query: (a: number, b: number, c: number, d: number) => [number, number, number];
package/src/worker.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import init, * as wasm from './wasm/reddb_wasm.js'
2
- import { RUNTIME_ABI_VERSION, VALUE_ENCODING, MAX_QUERY_PARAMETERS } from './protocol.js'
2
+ import { RUNTIME_ABI_VERSION, VALUE_ENCODING, MAX_QUERY_PARAMETERS, MAX_DATABASE_BACKUP_BYTES } from './protocol.js'
3
3
 
4
4
  let artifact
5
5
  let database
@@ -35,20 +35,26 @@ function synchronous(value) {
35
35
  return value
36
36
  }
37
37
 
38
- async function open(name, sqlDatabase = false, create = false) {
38
+ async function open(name, sqlDatabase = false, create = false, backup) {
39
+ const restoring = backup !== undefined
39
40
  await initialize()
40
41
  if (artifact || database) throw error('INVALID_ARGUMENT', 'This worker already owns an open file')
41
42
  await new Promise((resolve, reject) => {
42
43
  ownership = navigator.locks.request(`reddb-browser:${name}`, { ifAvailable: true }, async (lock) => {
43
44
  if (!lock) throw error('FILE_BUSY', 'This artifact is already open in another worker or tab')
45
+ let directory
46
+ let created = false
47
+ let opened = false
44
48
  try {
45
49
  const root = await navigator.storage.getDirectory()
46
- const directory = await root.getDirectoryHandle('reddb-browser', { create: !sqlDatabase || create })
50
+ directory = await root.getDirectoryHandle('reddb-browser', { create: !sqlDatabase || create || restoring })
47
51
  let file
48
- let created = false
49
- try { file = await directory.getFileHandle(`${name}.rdb`, { create: !sqlDatabase }) }
52
+ try {
53
+ file = await directory.getFileHandle(`${name}.rdb`, { create: !sqlDatabase })
54
+ if (restoring) throw error('DATABASE_EXISTS', 'Restore requires a new database name; existing files are never overwritten')
55
+ }
50
56
  catch (failure) {
51
- if (!sqlDatabase || !create || failure.name !== 'NotFoundError') throw failure
57
+ if (!sqlDatabase || (!create && !restoring) || failure.name !== 'NotFoundError') throw failure
52
58
  file = await directory.getFileHandle(`${name}.rdb`, { create: true })
53
59
  created = true
54
60
  }
@@ -56,6 +62,16 @@ async function open(name, sqlDatabase = false, create = false) {
56
62
  throw error('STORAGE_UNSUPPORTED', 'This browser does not support synchronous OPFS access in a dedicated worker')
57
63
  }
58
64
  access = await file.createSyncAccessHandle()
65
+ if (restoring) {
66
+ let offset = 0
67
+ while (offset < backup.byteLength) {
68
+ const written = synchronous(access.write(backup.subarray(offset, offset + 1024 * 1024), { at: offset }))
69
+ if (!written) throw error('ARTIFACT_ERROR', 'Unable to write the complete database backup')
70
+ offset += written
71
+ }
72
+ synchronous(access.flush())
73
+ backup = undefined
74
+ }
59
75
  const fileIo = {
60
76
  readAt: (buffer, offset) => synchronous(access.read(buffer, { at: offset })),
61
77
  writeAt: (buffer, offset) => synchronous(access.write(buffer, { at: offset })),
@@ -63,19 +79,19 @@ async function open(name, sqlDatabase = false, create = false) {
63
79
  truncate: (size) => synchronous(access.truncate(size)),
64
80
  flush: () => synchronous(access.flush()),
65
81
  }
66
- if (sqlDatabase) database = created
82
+ if (sqlDatabase) database = created && !restoring
67
83
  ? wasm.BrowserDatabase.create(fileIo, name, Date.now())
68
84
  : wasm.BrowserDatabase.open(fileIo, name)
69
85
  else artifact = fileIo.getSize() === 0
70
86
  ? wasm.BrowserArtifact.create(fileIo, name, Date.now())
71
87
  : wasm.BrowserArtifact.open(fileIo, name)
88
+ opened = true
72
89
  const lifetime = new Promise((resolveRelease) => { release = resolveRelease })
73
90
  resolve()
74
91
  await lifetime
75
92
  } catch (failure) {
76
93
  const reported = sqlDatabase && failure.name === 'NotFoundError'
77
94
  ? error('DATABASE_NOT_FOUND', 'The local .rdb file does not exist') : failure
78
- reject(reported)
79
95
  throw reported
80
96
  } finally {
81
97
  artifact?.free()
@@ -84,6 +100,10 @@ async function open(name, sqlDatabase = false, create = false) {
84
100
  database = undefined
85
101
  if (access) synchronous(access.close())
86
102
  access = undefined
103
+ // Reject through ownership.catch only after cleanup, before the SDK can
104
+ // terminate this Worker. An interrupted restore may leave a new file;
105
+ // existing destinations are always preserved.
106
+ if (restoring && created && !opened) await directory.removeEntry(`${name}.rdb`)
87
107
  }
88
108
  })
89
109
  // Observe early lock/open failures, including ifAvailable returning null.
@@ -96,9 +116,35 @@ function bytes(value) {
96
116
  return value
97
117
  }
98
118
 
119
+ function backupBytes(value) {
120
+ const backup = bytes(value)
121
+ if (!backup.byteLength || backup.byteLength > MAX_DATABASE_BACKUP_BYTES) {
122
+ throw error('INVALID_ARGUMENT', 'Expected a nonempty .rdb backup of at most 256 MiB')
123
+ }
124
+ return backup
125
+ }
126
+
127
+ function exportBackup() {
128
+ database.checkHealthy()
129
+ const size = synchronous(access.getSize())
130
+ if (!Number.isSafeInteger(size) || size < 1 || size > MAX_DATABASE_BACKUP_BYTES) {
131
+ throw error('BACKUP_SIZE_LIMIT', 'Database backups must fit within 256 MiB')
132
+ }
133
+ synchronous(access.flush())
134
+ const backup = new Uint8Array(size)
135
+ let offset = 0
136
+ while (offset < size) {
137
+ const read = synchronous(access.read(backup.subarray(offset, offset + 1024 * 1024), { at: offset }))
138
+ if (!read) throw error('ARTIFACT_ERROR', 'Unable to read the complete database backup')
139
+ offset += read
140
+ }
141
+ return backup
142
+ }
143
+
99
144
  async function execute(method, params) {
100
145
  if (method === 'initialize' || method === 'info') return initialize()
101
146
  if (method === 'open') return open(params.name)
147
+ if (method === 'restoreDatabase') return open(params.name, true, false, backupBytes(params.backup))
102
148
  if (method === 'openDatabase') {
103
149
  if (typeof params.create !== 'boolean') throw error('INVALID_ARGUMENT', 'Expected a boolean create option')
104
150
  return open(params.name, true, params.create)
@@ -108,13 +154,25 @@ async function execute(method, params) {
108
154
  if (typeof params.sql !== 'string') throw error('INVALID_ARGUMENT', 'Expected an RQL string')
109
155
  return method === 'validateQuery' ? wasm.validateQuery(params.sql) : wasm.executeScalar(params.sql)
110
156
  }
111
- if (!artifact && !database) throw error('CLOSED', 'The file is not open')
112
157
  if (method === 'close') {
113
- release()
114
- await ownership
158
+ if (artifact || database) {
159
+ release()
160
+ await ownership
161
+ }
115
162
  return
116
163
  }
164
+ if (!artifact && !database) throw error('CLOSED', 'The file is not open')
117
165
  if (database) {
166
+ if (method === 'exportBackup') {
167
+ try { return exportBackup() }
168
+ catch (failure) {
169
+ if (failure.code !== 'DATABASE_ERROR' && failure.code !== 'BACKUP_SIZE_LIMIT') {
170
+ release()
171
+ await ownership
172
+ }
173
+ throw failure
174
+ }
175
+ }
118
176
  if (method !== 'query' && method !== 'queryWithParams') throw error('QUERY_UNSUPPORTED', 'This database handle exposes local SQL')
119
177
  if (typeof params.sql !== 'string') throw error('INVALID_ARGUMENT', 'Expected an RQL string')
120
178
  if (method === 'queryWithParams') {
@@ -152,7 +210,7 @@ self.onmessage = ({ data }) => {
152
210
  queue = queue.then(async () => {
153
211
  try {
154
212
  const result = await execute(method, params)
155
- self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, result })
213
+ self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, result }, method === 'exportBackup' ? [result.buffer] : [])
156
214
  } catch (failure) {
157
215
  self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, error: { code: failure.code || 'ARTIFACT_ERROR', message: failure.message || String(failure) } })
158
216
  }