@reddb-io/browser 0.2.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 +69 -4
- package/package.json +1 -1
- package/src/index.d.ts +15 -1
- package/src/index.js +33 -10
- package/src/protocol.js +2 -0
- package/src/wasm/reddb_wasm.d.ts +4 -0
- package/src/wasm/reddb_wasm.js +44 -0
- package/src/wasm/reddb_wasm_bg.wasm +0 -0
- package/src/wasm/reddb_wasm_bg.wasm.d.ts +2 -0
- package/src/worker.js +78 -13
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.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
|
|
@@ -88,7 +88,7 @@ COALESCE, ABS, JSON_PARSE, JSON_EXTRACT/JSON_EXTRACT_TEXT and CONTAINS. Unknown
|
|
|
88
88
|
fields/functions are rejected even on empty tables. Functions and operators use
|
|
89
89
|
the canonical Rust evaluators; exact values retain `reddb-json-v1` tags.
|
|
90
90
|
|
|
91
|
-
|
|
91
|
+
DISTINCT, grouping/aggregates, windows, joins/subqueries,
|
|
92
92
|
universal/system sources, other collection models, TTL and retention are rejected
|
|
93
93
|
explicitly. Materialization is capped at 100,000 visible source rows, independently
|
|
94
94
|
of LIMIT. Superseded and moderated rows use the shared committed-scan visibility;
|
|
@@ -100,6 +100,31 @@ pending row actions. DML commits use the native WAL batch; catalog changes use
|
|
|
100
100
|
one complete native snapshot publication. BEGIN copies the committed resident
|
|
101
101
|
image, so transaction startup costs memory proportional to the local database.
|
|
102
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
|
+
|
|
103
128
|
The embedding application owns this local file and its origin. This API does not
|
|
104
129
|
establish a server user/tenant session or replay server RLS policies: export only
|
|
105
130
|
the authorized subset into an application-owned file. Import a native `.rdb` into
|
|
@@ -124,9 +149,9 @@ try {
|
|
|
124
149
|
|
|
125
150
|
The versioned Worker/WASM contract reports `abiVersion: 1`,
|
|
126
151
|
`valueEncoding: 'reddb-json-v1'` and capabilities. Currently `queryValidation`
|
|
127
|
-
and `scalarQueries` are true. Version `0.
|
|
152
|
+
and `scalarQueries` are true. Version `0.4.0` also reports `storedQueries: true`
|
|
128
153
|
with `storedQueryMode: 'read-write-tables'`, `sqlWrites: true` and
|
|
129
|
-
`transactions: true`; `sync` remains false.
|
|
154
|
+
`transactions: true`, `queryParameters: true` and `databaseBackups: true`; `sync` remains false.
|
|
130
155
|
Capabilities describe the engine, not the operations exposed by a particular handle. Mismatched SDK/Worker/WASM versions fail with `VERSION_MISMATCH` before
|
|
131
156
|
opening storage. Cache the JS, Worker and WASM as one versioned unit.
|
|
132
157
|
|
|
@@ -250,6 +275,46 @@ OPFS is subject to origin quota, storage eviction and explicit site-data clearin
|
|
|
250
275
|
Applications can request persistent storage through `navigator.storage.persist()`;
|
|
251
276
|
these primitives do not promise that a browser will grant it or sync after closing.
|
|
252
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
|
+
|
|
253
318
|
## Offline asset loading
|
|
254
319
|
|
|
255
320
|
The SDK does not register a service worker or control application updates. A
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -14,6 +14,8 @@ export interface RuntimeInfo {
|
|
|
14
14
|
readonly storedQueryMode: 'read-write-tables'
|
|
15
15
|
readonly sqlWrites: boolean
|
|
16
16
|
readonly transactions: boolean
|
|
17
|
+
readonly queryParameters?: boolean
|
|
18
|
+
readonly databaseBackups?: boolean
|
|
17
19
|
readonly sync: boolean
|
|
18
20
|
}
|
|
19
21
|
}
|
|
@@ -64,9 +66,14 @@ export function openArtifact(options: {
|
|
|
64
66
|
worker?: Worker
|
|
65
67
|
}): Promise<Artifact>
|
|
66
68
|
|
|
69
|
+
/** Scalars bind as AST literals; integer numbers must be safe and bigints fit i64/u64. */
|
|
70
|
+
export type QueryParameter = null | boolean | number | string | bigint
|
|
71
|
+
|
|
67
72
|
export interface Database extends Runtime {
|
|
68
73
|
/** SELECT and table SQL mutations; mutations return an affectedRows column. */
|
|
69
|
-
query(sql: string): Promise<{ columns: string[]; rows: unknown[][] }>
|
|
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>
|
|
70
77
|
/** Release exclusive ownership of the local file and terminate its worker. */
|
|
71
78
|
close(): Promise<void>
|
|
72
79
|
}
|
|
@@ -78,3 +85,10 @@ export function openDatabase(options: {
|
|
|
78
85
|
create?: boolean
|
|
79
86
|
worker?: Worker
|
|
80
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 } 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,11 +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
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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')
|
|
143
145
|
}
|
|
144
|
-
|
|
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 })
|
|
145
150
|
}
|
|
146
151
|
catch (error) { client.shutdown(error); throw error }
|
|
147
152
|
return client
|
|
@@ -164,12 +169,30 @@ export async function openArtifact(options) {
|
|
|
164
169
|
|
|
165
170
|
/** Local table SQL and single-owner transactions over a canonical OPFS .rdb. */
|
|
166
171
|
export async function openDatabase(options) {
|
|
167
|
-
|
|
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) {
|
|
168
185
|
return {
|
|
169
186
|
...runtimeMethods(client),
|
|
170
|
-
query
|
|
171
|
-
|
|
172
|
-
|
|
187
|
+
query(sql, params) {
|
|
188
|
+
if (typeof sql !== 'string') return Promise.reject(new BrowserError('INVALID_ARGUMENT', 'Expected an RQL string'))
|
|
189
|
+
if (params === undefined) return client.call('query', { sql })
|
|
190
|
+
if (!Array.isArray(params) || params.length > MAX_QUERY_PARAMETERS) {
|
|
191
|
+
return Promise.reject(new BrowserError('INVALID_ARGUMENT', 'Expected an array of at most 65536 positional parameters'))
|
|
192
|
+
}
|
|
193
|
+
return client.call('queryWithParams', { sql, params })
|
|
194
|
+
},
|
|
195
|
+
exportBackup: () => client.call('exportBackup'),
|
|
173
196
|
close: client.closeFile,
|
|
174
197
|
}
|
|
175
198
|
}
|
package/src/protocol.js
CHANGED
package/src/wasm/reddb_wasm.d.ts
CHANGED
|
@@ -29,9 +29,11 @@ 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;
|
|
36
|
+
queryWithParams(sql: string, params: Array<any>, now_ms: number): any;
|
|
35
37
|
}
|
|
36
38
|
|
|
37
39
|
/**
|
|
@@ -59,9 +61,11 @@ export interface InitOutput {
|
|
|
59
61
|
readonly browserartifact_open: (a: any, b: number, c: number) => [number, number, number];
|
|
60
62
|
readonly browserartifact_readSnapshot: (a: number) => [number, number, number, number];
|
|
61
63
|
readonly browserartifact_readWal: (a: number) => [number, number, number];
|
|
64
|
+
readonly browserdatabase_checkHealthy: (a: number) => [number, number];
|
|
62
65
|
readonly browserdatabase_create: (a: any, b: number, c: number, d: number) => [number, number, number];
|
|
63
66
|
readonly browserdatabase_open: (a: any, b: number, c: number) => [number, number, number];
|
|
64
67
|
readonly browserdatabase_query: (a: number, b: number, c: number, d: number) => [number, number, number];
|
|
68
|
+
readonly browserdatabase_queryWithParams: (a: number, b: number, c: number, d: any, e: number) => [number, number, number];
|
|
65
69
|
readonly executeScalar: (a: number, b: number) => [number, number, number];
|
|
66
70
|
readonly runtimeInfo: () => [number, number, number];
|
|
67
71
|
readonly validateQuery: (a: number, b: number) => [number, number];
|
package/src/wasm/reddb_wasm.js
CHANGED
|
@@ -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
|
|
@@ -185,6 +191,21 @@ export class BrowserDatabase {
|
|
|
185
191
|
}
|
|
186
192
|
return takeFromExternrefTable0(ret[0]);
|
|
187
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* @param {string} sql
|
|
196
|
+
* @param {Array<any>} params
|
|
197
|
+
* @param {number} now_ms
|
|
198
|
+
* @returns {any}
|
|
199
|
+
*/
|
|
200
|
+
queryWithParams(sql, params, now_ms) {
|
|
201
|
+
const ptr0 = passStringToWasm0(sql, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
202
|
+
const len0 = WASM_VECTOR_LEN;
|
|
203
|
+
const ret = wasm.browserdatabase_queryWithParams(this.__wbg_ptr, ptr0, len0, params, now_ms);
|
|
204
|
+
if (ret[2]) {
|
|
205
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
206
|
+
}
|
|
207
|
+
return takeFromExternrefTable0(ret[0]);
|
|
208
|
+
}
|
|
188
209
|
}
|
|
189
210
|
if (Symbol.dispose) BrowserDatabase.prototype[Symbol.dispose] = BrowserDatabase.prototype.free;
|
|
190
211
|
|
|
@@ -229,6 +250,25 @@ export function validateQuery(sql) {
|
|
|
229
250
|
function __wbg_get_imports() {
|
|
230
251
|
const import0 = {
|
|
231
252
|
__proto__: null,
|
|
253
|
+
__wbg___wbindgen_boolean_get_c3dd5c39f1b5a12b: function(arg0) {
|
|
254
|
+
const v = arg0;
|
|
255
|
+
const ret = typeof(v) === 'boolean' ? v : undefined;
|
|
256
|
+
return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;
|
|
257
|
+
},
|
|
258
|
+
__wbg___wbindgen_is_bigint_d6a8167cac401b95: function(arg0) {
|
|
259
|
+
const ret = typeof(arg0) === 'bigint';
|
|
260
|
+
return ret;
|
|
261
|
+
},
|
|
262
|
+
__wbg___wbindgen_is_null_066086be3abe9bb3: function(arg0) {
|
|
263
|
+
const ret = arg0 === null;
|
|
264
|
+
return ret;
|
|
265
|
+
},
|
|
266
|
+
__wbg___wbindgen_number_get_dd6d69a6079f26f1: function(arg0, arg1) {
|
|
267
|
+
const obj = arg1;
|
|
268
|
+
const ret = typeof(obj) === 'number' ? obj : undefined;
|
|
269
|
+
getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
|
|
270
|
+
getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
|
|
271
|
+
},
|
|
232
272
|
__wbg___wbindgen_string_get_965592073e5d848c: function(arg0, arg1) {
|
|
233
273
|
const obj = arg1;
|
|
234
274
|
const ret = typeof(obj) === 'string' ? obj : undefined;
|
|
@@ -318,6 +358,10 @@ function __wbg_get_imports() {
|
|
|
318
358
|
const ret = Reflect.set(arg0, arg1, arg2);
|
|
319
359
|
return ret;
|
|
320
360
|
}, arguments); },
|
|
361
|
+
__wbg_toString_7fbc0abf5c3327f5: function() { return handleError(function (arg0, arg1) {
|
|
362
|
+
const ret = arg0.toString(arg1);
|
|
363
|
+
return ret;
|
|
364
|
+
}, arguments); },
|
|
321
365
|
__wbg_truncate_d9e55b46e14f9493: function() { return handleError(function (arg0, arg1) {
|
|
322
366
|
arg0.truncate(arg1);
|
|
323
367
|
}, arguments); },
|
|
Binary file
|
|
@@ -10,9 +10,11 @@ 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];
|
|
17
|
+
export const browserdatabase_queryWithParams: (a: number, b: number, c: number, d: any, e: number) => [number, number, number];
|
|
16
18
|
export const executeScalar: (a: number, b: number) => [number, number, number];
|
|
17
19
|
export const runtimeInfo: () => [number, number, number];
|
|
18
20
|
export const validateQuery: (a: number, b: 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 } 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
|
-
|
|
50
|
+
directory = await root.getDirectoryHandle('reddb-browser', { create: !sqlDatabase || create || restoring })
|
|
47
51
|
let file
|
|
48
|
-
|
|
49
|
-
|
|
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,15 +154,34 @@ 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
|
-
|
|
114
|
-
|
|
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) {
|
|
118
|
-
if (method
|
|
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
|
+
}
|
|
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')
|
|
178
|
+
if (method === 'queryWithParams') {
|
|
179
|
+
if (!Array.isArray(params.params) || params.params.length > MAX_QUERY_PARAMETERS) {
|
|
180
|
+
throw error('INVALID_ARGUMENT', 'Expected an array of at most 65536 positional parameters')
|
|
181
|
+
}
|
|
182
|
+
if (typeof database.queryWithParams !== 'function') throw error('VERSION_MISMATCH', 'WASM parameter binding is missing')
|
|
183
|
+
return database.queryWithParams(params.sql, params.params, Date.now())
|
|
184
|
+
}
|
|
120
185
|
return database.query(params.sql, Date.now())
|
|
121
186
|
}
|
|
122
187
|
switch (method) {
|
|
@@ -145,7 +210,7 @@ self.onmessage = ({ data }) => {
|
|
|
145
210
|
queue = queue.then(async () => {
|
|
146
211
|
try {
|
|
147
212
|
const result = await execute(method, params)
|
|
148
|
-
self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, result })
|
|
213
|
+
self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, result }, method === 'exportBackup' ? [result.buffer] : [])
|
|
149
214
|
} catch (failure) {
|
|
150
215
|
self.postMessage({ abiVersion: RUNTIME_ABI_VERSION, id, error: { code: failure.code || 'ARTIFACT_ERROR', message: failure.message || String(failure) } })
|
|
151
216
|
}
|