@reddb-io/browser 0.3.0 → 0.4.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.4.0` adds native `.rdb` backup export and restore. 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
@@ -149,9 +149,9 @@ try {
149
149
 
150
150
  The versioned Worker/WASM contract reports `abiVersion: 1`,
151
151
  `valueEncoding: 'reddb-json-v1'` and capabilities. Currently `queryValidation`
152
- and `scalarQueries` are true. Version `0.3.0` also reports `storedQueries: true`
152
+ and `scalarQueries` are true. Version `0.4.0` also reports `storedQueries: true`
153
153
  with `storedQueryMode: 'read-write-tables'`, `sqlWrites: true` and
154
- `transactions: true` and `queryParameters: true`; `sync` remains false.
154
+ `transactions: true`, `queryParameters: true` and `databaseBackups: true`; `sync` remains false.
155
155
  Capabilities describe the engine, not the operations exposed by a particular handle. Mismatched SDK/Worker/WASM versions fail with `VERSION_MISMATCH` before
156
156
  opening storage. Cache the JS, Worker and WASM as one versioned unit.
157
157
 
@@ -275,6 +275,46 @@ OPFS is subject to origin quota, storage eviction and explicit site-data clearin
275
275
  Applications can request persistent storage through `navigator.storage.persist()`;
276
276
  these primitives do not promise that a browser will grant it or sync after closing.
277
277
 
278
+ ## Database backups
279
+
280
+ `database.exportBackup()` returns a `Uint8Array` containing the complete native
281
+ `.rdb` file, including its committed catalog, snapshot and WAL. The Worker keeps
282
+ exclusive ownership while reading the file and transfers the resulting buffer
283
+ to the caller. No SQL is generated and no storage format is reimplemented in JS.
284
+ An active transaction stays active; its uncommitted changes are excluded.
285
+ The Rust publication fence is checked before copying. A backup read/flush failure
286
+ closes the owner; reopen and recover before issuing more operations. A size-limit
287
+ rejection leaves the handle usable.
288
+
289
+ ```ts
290
+ import { restoreDatabase } from '@reddb-io/browser'
291
+ import RedDBWorker from '@reddb-io/browser/worker?worker'
292
+
293
+ const backup = await database.exportBackup()
294
+ // Save these bytes outside this origin, for example as a downloaded .rdb file.
295
+ const restored = await restoreDatabase({
296
+ name: 'my-app-restored', backup, worker: new RedDBWorker(),
297
+ })
298
+ try { console.log(await restored.query('SELECT * FROM notes')) }
299
+ finally { await restored.close() }
300
+ ```
301
+
302
+ Restore requires a new name. An existing file returns `DATABASE_EXISTS`; an
303
+ actively owned destination returns `FILE_BUSY`. It writes the new file, flushes
304
+ it and opens it through the canonical Rust engine before returning a handle.
305
+ A rejected backup removes only its newly created destination before reporting
306
+ the failure. Worker/browser termination during restore can leave an incomplete
307
+ new destination; it is never silently overwritten on retry.
308
+
309
+ Backups are bounded at 256 MiB of physical file bytes. The embedding application
310
+ owns file selection, download and retention. These are complete physical copies,
311
+ which can contain older/deleted bytes, not compacted or redacted exports. They
312
+ do not provide additional encryption, synchronization or tenant filtering.
313
+ Treat backups as sensitive and export only an authorized database. File codecs,
314
+ format versions and native publication/recovery remain unchanged. Export takes
315
+ O(file size) reads and one full JS buffer; restore also holds the input and the
316
+ recovered resident database in memory. No performance improvement is claimed.
317
+
278
318
  ## Offline asset loading
279
319
 
280
320
  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.4.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.",
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,6 +72,8 @@ 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[][] }>
75
+ /** Complete native .rdb image of committed state, at most 256 MiB. Pending SQL changes are excluded. */
76
+ exportBackup(): Promise<Uint8Array>
74
77
  /** Release exclusive ownership of the local file and terminate its worker. */
75
78
  close(): Promise<void>
76
79
  }
@@ -82,3 +85,10 @@ export function openDatabase(options: {
82
85
  create?: boolean
83
86
  worker?: Worker
84
87
  }): Promise<Database>
88
+
89
+ /** Restore a native .rdb image to a new name. Existing files are never overwritten. */
90
+ export function restoreDatabase(options: {
91
+ name: string
92
+ backup: Uint8Array
93
+ worker?: Worker
94
+ }): 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,7 +126,7 @@ export function createInteropRuntime({ worker } = {}) {
126
126
  }
127
127
  }
128
128
 
129
- async function openFile({ name, worker, create = false } = {}, method = 'open') {
129
+ async function openFile({ name, worker, create = false, backup } = {}, method = 'open') {
130
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')
@@ -137,12 +137,16 @@ async function openFile({ name, worker, create = false } = {}, method = 'open')
137
137
  const client = createClient(worker)
138
138
  try {
139
139
  const info = await client.ready
140
- if (method === 'openDatabase' && (info.capabilities.storedQueries !== true
140
+ const sqlDatabase = method === 'openDatabase' || method === 'restoreDatabase'
141
+ if (sqlDatabase && (info.capabilities.storedQueries !== true
141
142
  || info.capabilities.storedQueryMode !== 'read-write-tables' || !info.capabilities.sqlWrites || !info.capabilities.transactions
142
143
  || info.capabilities.queryParameters !== true)) {
143
144
  throw new BrowserError('VERSION_MISMATCH', 'WASM runtime does not expose local table SQL, transactions and parameters')
144
145
  }
145
- await client.call(method, method === 'openDatabase' ? { name, create } : { name })
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 })
146
150
  }
147
151
  catch (error) { client.shutdown(error); throw error }
148
152
  return client
@@ -165,7 +169,19 @@ export async function openArtifact(options) {
165
169
 
166
170
  /** Local table SQL and single-owner transactions over a canonical OPFS .rdb. */
167
171
  export async function openDatabase(options) {
168
- const client = await openFile(options, 'openDatabase')
172
+ return databaseMethods(await openFile(options, 'openDatabase'))
173
+ }
174
+
175
+ /** Restore a native .rdb backup to a new, exclusively owned OPFS filename. */
176
+ export async function restoreDatabase(options) {
177
+ const backup = options?.backup
178
+ if (!(backup instanceof Uint8Array) || !backup.byteLength || backup.byteLength > MAX_DATABASE_BACKUP_BYTES) {
179
+ throw new BrowserError('INVALID_ARGUMENT', 'Expected a nonempty .rdb backup of at most 256 MiB as Uint8Array')
180
+ }
181
+ return databaseMethods(await openFile(options, 'restoreDatabase'))
182
+ }
183
+
184
+ function databaseMethods(client) {
169
185
  return {
170
186
  ...runtimeMethods(client),
171
187
  query(sql, params) {
@@ -176,6 +192,7 @@ export async function openDatabase(options) {
176
192
  }
177
193
  return client.call('queryWithParams', { sql, params })
178
194
  },
195
+ exportBackup: () => client.call('exportBackup'),
179
196
  close: client.closeFile,
180
197
  }
181
198
  }
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
  }