@livestore/wa-sqlite 1.0.1-dev.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +78 -0
  3. package/dist/wa-sqlite-async.mjs +16 -0
  4. package/dist/wa-sqlite-async.wasm +0 -0
  5. package/dist/wa-sqlite-jspi.mjs +16 -0
  6. package/dist/wa-sqlite-jspi.wasm +0 -0
  7. package/dist/wa-sqlite.mjs +16 -0
  8. package/dist/wa-sqlite.wasm +0 -0
  9. package/package.json +45 -0
  10. package/src/FacadeVFS.js +508 -0
  11. package/src/VFS.js +222 -0
  12. package/src/WebLocksMixin.js +412 -0
  13. package/src/examples/AccessHandlePoolVFS.js +458 -0
  14. package/src/examples/IDBBatchAtomicVFS.js +820 -0
  15. package/src/examples/IDBMirrorVFS.js +875 -0
  16. package/src/examples/MemoryAsyncVFS.js +100 -0
  17. package/src/examples/MemoryVFS.js +176 -0
  18. package/src/examples/OPFSAdaptiveVFS.js +437 -0
  19. package/src/examples/OPFSAnyContextVFS.js +300 -0
  20. package/src/examples/OPFSCoopSyncVFS.js +590 -0
  21. package/src/examples/OPFSPermutedVFS.js +1214 -0
  22. package/src/examples/README.md +89 -0
  23. package/src/examples/tag.js +82 -0
  24. package/src/sqlite-api.js +914 -0
  25. package/src/sqlite-constants.js +275 -0
  26. package/src/types/globals.d.ts +60 -0
  27. package/src/types/index.d.ts +1302 -0
  28. package/src/types/tsconfig.json +6 -0
  29. package/test/AccessHandlePoolVFS.test.js +27 -0
  30. package/test/IDBBatchAtomicVFS.test.js +97 -0
  31. package/test/IDBMirrorVFS.test.js +27 -0
  32. package/test/MemoryAsyncVFS.test.js +27 -0
  33. package/test/MemoryVFS.test.js +27 -0
  34. package/test/OPFSAdaptiveVFS.test.js +27 -0
  35. package/test/OPFSAnyContextVFS.test.js +27 -0
  36. package/test/OPFSCoopSyncVFS.test.js +27 -0
  37. package/test/OPFSPermutedVFS.test.js +27 -0
  38. package/test/TestContext.js +96 -0
  39. package/test/WebLocksMixin.test.js +521 -0
  40. package/test/api.test.js +49 -0
  41. package/test/api_exec.js +89 -0
  42. package/test/api_misc.js +63 -0
  43. package/test/api_statements.js +426 -0
  44. package/test/callbacks.test.js +373 -0
  45. package/test/sql.test.js +64 -0
  46. package/test/sql_0001.js +49 -0
  47. package/test/sql_0002.js +52 -0
  48. package/test/sql_0003.js +83 -0
  49. package/test/sql_0004.js +81 -0
  50. package/test/sql_0005.js +76 -0
  51. package/test/test-worker.js +204 -0
  52. package/test/vfs_xAccess.js +2 -0
  53. package/test/vfs_xClose.js +52 -0
  54. package/test/vfs_xOpen.js +91 -0
  55. package/test/vfs_xRead.js +38 -0
  56. package/test/vfs_xWrite.js +36 -0
@@ -0,0 +1,590 @@
1
+ // Copyright 2024 Roy T. Hashimoto. All Rights Reserved.
2
+ import { FacadeVFS } from '../FacadeVFS.js';
3
+ import * as VFS from '../VFS.js';
4
+
5
+ const DEFAULT_TEMPORARY_FILES = 10;
6
+ const LOCK_NOTIFY_INTERVAL = 1000;
7
+
8
+ const DB_RELATED_FILE_SUFFIXES = ['', '-journal', '-wal'];
9
+
10
+ const finalizationRegistry = new FinalizationRegistry(releaser => releaser());
11
+
12
+ class File {
13
+ /** @type {string} */ path
14
+ /** @type {number} */ flags;
15
+ /** @type {FileSystemSyncAccessHandle} */ accessHandle;
16
+
17
+ /** @type {PersistentFile?} */ persistentFile;
18
+
19
+ constructor(path, flags) {
20
+ this.path = path;
21
+ this.flags = flags;
22
+ }
23
+ }
24
+
25
+ class PersistentFile {
26
+ /** @type {FileSystemFileHandle} */ fileHandle
27
+ /** @type {FileSystemSyncAccessHandle} */ accessHandle = null
28
+
29
+ // The following properties are for main database files.
30
+
31
+ /** @type {boolean} */ isLockBusy = false;
32
+ /** @type {boolean} */ isFileLocked = false;
33
+ /** @type {boolean} */ isRequestInProgress = false;
34
+ /** @type {function} */ handleLockReleaser = null;
35
+
36
+ /** @type {BroadcastChannel} */ handleRequestChannel;
37
+ /** @type {boolean} */ isHandleRequested = false;
38
+
39
+ constructor(fileHandle) {
40
+ this.fileHandle = fileHandle;
41
+ }
42
+ }
43
+
44
+ export class OPFSCoopSyncVFS extends FacadeVFS {
45
+ /** @type {Map<number, File>} */ mapIdToFile = new Map();
46
+
47
+ lastError = null;
48
+ log = null; //function(...args) { console.log(`[${contextName}]`, ...args) };
49
+
50
+ /** @type {Map<string, PersistentFile>} */ persistentFiles = new Map();
51
+ /** @type {Map<string, FileSystemSyncAccessHandle>} */ boundAccessHandles = new Map();
52
+ /** @type {Set<FileSystemSyncAccessHandle>} */ unboundAccessHandles = new Set();
53
+ /** @type {Set<string>} */ accessiblePaths = new Set();
54
+ releaser = null;
55
+
56
+ static async create(name, module) {
57
+ const vfs = new OPFSCoopSyncVFS(name, module);
58
+ await Promise.all([
59
+ vfs.isReady(),
60
+ vfs.#initialize(DEFAULT_TEMPORARY_FILES),
61
+ ]);
62
+ return vfs;
63
+ }
64
+
65
+ constructor(name, module) {
66
+ super(name, module);
67
+ }
68
+
69
+ async #initialize(nTemporaryFiles) {
70
+ // Delete temporary directories no longer in use.
71
+ const root = await navigator.storage.getDirectory();
72
+ // @ts-ignore
73
+ for await (const entry of root.values()) {
74
+ if (entry.kind === 'directory' && entry.name.startsWith('.ahp-')) {
75
+ // A lock with the same name as the directory protects it from
76
+ // being deleted.
77
+ await navigator.locks.request(entry.name, { ifAvailable: true }, async lock => {
78
+ if (lock) {
79
+ this.log?.(`Deleting temporary directory ${entry.name}`);
80
+ await root.removeEntry(entry.name, { recursive: true });
81
+ } else {
82
+ this.log?.(`Temporary directory ${entry.name} is in use`);
83
+ }
84
+ });
85
+ }
86
+ }
87
+
88
+ // Create our temporary directory.
89
+ const tmpDirName = `.ahp-${Math.random().toString(36).slice(2)}`;
90
+ this.releaser = await new Promise(resolve => {
91
+ navigator.locks.request(tmpDirName, () => {
92
+ return new Promise(release => {
93
+ resolve(release);
94
+ });
95
+ });
96
+ });
97
+ finalizationRegistry.register(this, this.releaser);
98
+ const tmpDir = await root.getDirectoryHandle(tmpDirName, { create: true });
99
+
100
+ // Populate temporary directory.
101
+ for (let i = 0; i < nTemporaryFiles; i++) {
102
+ const tmpFile = await tmpDir.getFileHandle(`${i}.tmp`, { create: true });
103
+ const tmpAccessHandle = await tmpFile.createSyncAccessHandle();
104
+ this.unboundAccessHandles.add(tmpAccessHandle);
105
+ }
106
+ }
107
+
108
+ /**
109
+ * @param {string?} zName
110
+ * @param {number} fileId
111
+ * @param {number} flags
112
+ * @param {DataView} pOutFlags
113
+ * @returns {number}
114
+ */
115
+ jOpen(zName, fileId, flags, pOutFlags) {
116
+ try {
117
+ const url = new URL(zName || Math.random().toString(36).slice(2), 'file://');
118
+ const path = url.pathname;
119
+
120
+ if (flags & VFS.SQLITE_OPEN_MAIN_DB) {
121
+ const persistentFile = this.persistentFiles.get(path);
122
+ if (persistentFile?.isRequestInProgress) {
123
+ // Should not reach here unless SQLite itself retries an open.
124
+ // Otherwise, asynchronous operations started on a previous
125
+ // open try should have completed.
126
+ return VFS.SQLITE_BUSY;
127
+ } else if (!persistentFile) {
128
+ // This is the usual starting point for opening a database.
129
+ // Register a Promise that resolves when the database and related
130
+ // files are ready to be used.
131
+ this.log?.(`creating persistent file for ${path}`);
132
+ const create = !!(flags & VFS.SQLITE_OPEN_CREATE);
133
+ this._module.retryOps.push((async () => {
134
+ try {
135
+ // Get the path directory handle.
136
+ let dirHandle = await navigator.storage.getDirectory();
137
+ const directories = path.split('/').filter(d => d);
138
+ const filename = directories.pop();
139
+ for (const directory of directories) {
140
+ dirHandle = await dirHandle.getDirectoryHandle(directory, { create });
141
+ }
142
+
143
+ // Get file handles for the database and related files,
144
+ // and create persistent file instances.
145
+ for (const suffix of DB_RELATED_FILE_SUFFIXES) {
146
+ const fileHandle = await dirHandle.getFileHandle(filename + suffix, { create });
147
+ await this.#createPersistentFile(fileHandle);
148
+ }
149
+
150
+ // Get access handles for the files.
151
+ const file = new File(path, flags);
152
+ file.persistentFile = this.persistentFiles.get(path);
153
+ await this.#requestAccessHandle(file);
154
+ } catch (e) {
155
+ // Use an invalid persistent file to signal this error
156
+ // for the retried open.
157
+ const persistentFile = new PersistentFile(null);
158
+ this.persistentFiles.set(path, persistentFile);
159
+ console.error(e);
160
+ }
161
+ })());
162
+ return VFS.SQLITE_BUSY;
163
+ } else if (!persistentFile.fileHandle) {
164
+ // The asynchronous open operation failed.
165
+ this.persistentFiles.delete(path);
166
+ return VFS.SQLITE_CANTOPEN;
167
+ } else if (!persistentFile.accessHandle) {
168
+ // This branch is reached if the database was previously opened
169
+ // and closed.
170
+ this._module.retryOps.push((async () => {
171
+ const file = new File(path, flags);
172
+ file.persistentFile = this.persistentFiles.get(path);
173
+ await this.#requestAccessHandle(file);
174
+ })());
175
+ return VFS.SQLITE_BUSY;
176
+ }
177
+ }
178
+
179
+ if (!this.accessiblePaths.has(path) &&
180
+ !(flags & VFS.SQLITE_OPEN_CREATE)) {
181
+ throw new Error(`File ${path} not found`);
182
+ }
183
+
184
+ const file = new File(path, flags);
185
+ this.mapIdToFile.set(fileId, file);
186
+
187
+ if (this.persistentFiles.has(path)) {
188
+ file.persistentFile = this.persistentFiles.get(path);
189
+ } else if (this.boundAccessHandles.has(path)) {
190
+ // This temporary file was previously created and closed. Reopen
191
+ // the same access handle.
192
+ file.accessHandle = this.boundAccessHandles.get(path);
193
+ } else if (this.unboundAccessHandles.size) {
194
+ // Associate an unbound access handle to this file.
195
+ file.accessHandle = this.unboundAccessHandles.values().next().value;
196
+ file.accessHandle.truncate(0);
197
+ this.unboundAccessHandles.delete(file.accessHandle);
198
+ this.boundAccessHandles.set(path, file.accessHandle);
199
+ }
200
+ this.accessiblePaths.add(path);
201
+
202
+ pOutFlags.setInt32(0, flags, true);
203
+ return VFS.SQLITE_OK;
204
+ } catch (e) {
205
+ this.lastError = e;
206
+ return VFS.SQLITE_CANTOPEN;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * @param {string} zName
212
+ * @param {number} syncDir
213
+ * @returns {number}
214
+ */
215
+ jDelete(zName, syncDir) {
216
+ try {
217
+ const url = new URL(zName, 'file://');
218
+ const path = url.pathname;
219
+ if (this.persistentFiles.has(path)) {
220
+ const persistentFile = this.persistentFiles.get(path);
221
+ persistentFile.accessHandle.truncate(0);
222
+ } else {
223
+ this.boundAccessHandles.get(path)?.truncate(0);
224
+ }
225
+ this.accessiblePaths.delete(path);
226
+ return VFS.SQLITE_OK;
227
+ } catch (e) {
228
+ this.lastError = e;
229
+ return VFS.SQLITE_IOERR_DELETE;
230
+ }
231
+ }
232
+
233
+ /**
234
+ * @param {string} zName
235
+ * @param {number} flags
236
+ * @param {DataView} pResOut
237
+ * @returns {number}
238
+ */
239
+ jAccess(zName, flags, pResOut) {
240
+ try {
241
+ const url = new URL(zName, 'file://');
242
+ const path = url.pathname;
243
+ pResOut.setInt32(0, this.accessiblePaths.has(path) ? 1 : 0, true);
244
+ return VFS.SQLITE_OK;
245
+ } catch (e) {
246
+ this.lastError = e;
247
+ return VFS.SQLITE_IOERR_ACCESS;
248
+ }
249
+ }
250
+
251
+ /**
252
+ * @param {number} fileId
253
+ * @returns {number}
254
+ */
255
+ jClose(fileId) {
256
+ try {
257
+ const file = this.mapIdToFile.get(fileId);
258
+ this.mapIdToFile.delete(fileId);
259
+
260
+ if (file?.flags & VFS.SQLITE_OPEN_MAIN_DB) {
261
+ if (file.persistentFile?.handleLockReleaser) {
262
+ this.#releaseAccessHandle(file);
263
+ }
264
+ } else if (file?.flags & VFS.SQLITE_OPEN_DELETEONCLOSE) {
265
+ file.accessHandle.truncate(0);
266
+ this.accessiblePaths.delete(file.path);
267
+ if (!this.persistentFiles.has(file.path)) {
268
+ this.boundAccessHandles.delete(file.path);
269
+ this.unboundAccessHandles.add(file.accessHandle);
270
+ }
271
+ }
272
+ return VFS.SQLITE_OK;
273
+ } catch (e) {
274
+ this.lastError = e;
275
+ return VFS.SQLITE_IOERR_CLOSE;
276
+ }
277
+ }
278
+
279
+ /**
280
+ * @param {number} fileId
281
+ * @param {Uint8Array} pData
282
+ * @param {number} iOffset
283
+ * @returns {number}
284
+ */
285
+ jRead(fileId, pData, iOffset) {
286
+ try {
287
+ const file = this.mapIdToFile.get(fileId);
288
+
289
+ // On Chrome (at least), passing pData to accessHandle.read() is
290
+ // an error because pData is a Proxy of a Uint8Array. Calling
291
+ // subarray() produces a real Uint8Array and that works.
292
+ const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
293
+ const bytesRead = accessHandle.read(pData.subarray(), { at: iOffset });
294
+
295
+ // Opening a database file performs one read without a xLock call.
296
+ if ((file.flags & VFS.SQLITE_OPEN_MAIN_DB) && !file.persistentFile.isFileLocked) {
297
+ this.#releaseAccessHandle(file);
298
+ }
299
+
300
+ if (bytesRead < pData.byteLength) {
301
+ pData.fill(0, bytesRead);
302
+ return VFS.SQLITE_IOERR_SHORT_READ;
303
+ }
304
+ return VFS.SQLITE_OK;
305
+ } catch (e) {
306
+ this.lastError = e;
307
+ return VFS.SQLITE_IOERR_READ;
308
+ }
309
+ }
310
+
311
+ /**
312
+ * @param {number} fileId
313
+ * @param {Uint8Array} pData
314
+ * @param {number} iOffset
315
+ * @returns {number}
316
+ */
317
+ jWrite(fileId, pData, iOffset) {
318
+ try {
319
+ const file = this.mapIdToFile.get(fileId);
320
+
321
+ // On Chrome (at least), passing pData to accessHandle.write() is
322
+ // an error because pData is a Proxy of a Uint8Array. Calling
323
+ // subarray() produces a real Uint8Array and that works.
324
+ const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
325
+ const nBytes = accessHandle.write(pData.subarray(), { at: iOffset });
326
+ if (nBytes !== pData.byteLength) throw new Error('short write');
327
+ return VFS.SQLITE_OK;
328
+ } catch (e) {
329
+ this.lastError = e;
330
+ return VFS.SQLITE_IOERR_WRITE;
331
+ }
332
+ }
333
+
334
+ /**
335
+ * @param {number} fileId
336
+ * @param {number} iSize
337
+ * @returns {number}
338
+ */
339
+ jTruncate(fileId, iSize) {
340
+ try {
341
+ const file = this.mapIdToFile.get(fileId);
342
+ const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
343
+ accessHandle.truncate(iSize);
344
+ return VFS.SQLITE_OK;
345
+ } catch (e) {
346
+ this.lastError = e;
347
+ return VFS.SQLITE_IOERR_TRUNCATE;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * @param {number} fileId
353
+ * @param {number} flags
354
+ * @returns {number}
355
+ */
356
+ jSync(fileId, flags) {
357
+ try {
358
+ const file = this.mapIdToFile.get(fileId);
359
+ const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
360
+ accessHandle.flush();
361
+ return VFS.SQLITE_OK;
362
+ } catch (e) {
363
+ this.lastError = e;
364
+ return VFS.SQLITE_IOERR_FSYNC;
365
+ }
366
+ }
367
+
368
+ /**
369
+ * @param {number} fileId
370
+ * @param {DataView} pSize64
371
+ * @returns {number}
372
+ */
373
+ jFileSize(fileId, pSize64) {
374
+ try {
375
+ const file = this.mapIdToFile.get(fileId);
376
+ const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
377
+ const size = accessHandle.getSize();
378
+ pSize64.setBigInt64(0, BigInt(size), true);
379
+ return VFS.SQLITE_OK;
380
+ } catch (e) {
381
+ this.lastError = e;
382
+ return VFS.SQLITE_IOERR_FSTAT;
383
+ }
384
+ }
385
+
386
+ /**
387
+ * @param {number} fileId
388
+ * @param {number} lockType
389
+ * @returns {number}
390
+ */
391
+ jLock(fileId, lockType) {
392
+ const file = this.mapIdToFile.get(fileId);
393
+ if (file.persistentFile.isRequestInProgress) {
394
+ file.persistentFile.isLockBusy = true;
395
+ return VFS.SQLITE_BUSY;
396
+ }
397
+
398
+ file.persistentFile.isFileLocked = true;
399
+ if (!file.persistentFile.handleLockReleaser) {
400
+ // Start listening for notifications from other connections.
401
+ // This is before we actually get access handles, but waiting to
402
+ // listen until then allows a race condition where notifications
403
+ // are missed.
404
+ file.persistentFile.handleRequestChannel.onmessage = () => {
405
+ this.log?.(`received notification for ${file.path}`);
406
+ if (file.persistentFile.isFileLocked) {
407
+ // We're still using the access handle, so mark it to be
408
+ // released when we're done.
409
+ file.persistentFile.isHandleRequested = true;
410
+ } else {
411
+ // Release the access handles immediately.
412
+ this.#releaseAccessHandle(file);
413
+ }
414
+ file.persistentFile.handleRequestChannel.onmessage = null;
415
+ };
416
+
417
+ this.#requestAccessHandle(file);
418
+ this.log?.('returning SQLITE_BUSY');
419
+ file.persistentFile.isLockBusy = true;
420
+ return VFS.SQLITE_BUSY;
421
+ }
422
+ file.persistentFile.isLockBusy = false;
423
+ return VFS.SQLITE_OK;
424
+ }
425
+
426
+ /**
427
+ * @param {number} fileId
428
+ * @param {number} lockType
429
+ * @returns {number}
430
+ */
431
+ jUnlock(fileId, lockType) {
432
+ const file = this.mapIdToFile.get(fileId);
433
+ if (lockType === VFS.SQLITE_LOCK_NONE) {
434
+ // Don't change any state if this unlock is because xLock returned
435
+ // SQLITE_BUSY.
436
+ if (!file.persistentFile.isLockBusy) {
437
+ if (file.persistentFile.isHandleRequested) {
438
+ // Another connection wants the access handle.
439
+ this.#releaseAccessHandle(file);
440
+ this.isHandleRequested = false;
441
+ }
442
+ file.persistentFile.isFileLocked = false;
443
+ }
444
+ }
445
+ return VFS.SQLITE_OK;
446
+ }
447
+
448
+ /**
449
+ * @param {number} fileId
450
+ * @param {number} op
451
+ * @param {DataView} pArg
452
+ * @returns {number|Promise<number>}
453
+ */
454
+ jFileControl(fileId, op, pArg) {
455
+ try {
456
+ const file = this.mapIdToFile.get(fileId);
457
+ switch (op) {
458
+ case VFS.SQLITE_FCNTL_PRAGMA:
459
+ const key = extractString(pArg, 4);
460
+ const value = extractString(pArg, 8);
461
+ this.log?.('xFileControl', file.path, 'PRAGMA', key, value);
462
+ switch (key.toLowerCase()) {
463
+ case 'journal_mode':
464
+ if (value &&
465
+ !['off', 'memory', 'delete', 'wal'].includes(value.toLowerCase())) {
466
+ throw new Error('journal_mode must be "off", "memory", "delete", or "wal"');
467
+ }
468
+ break;
469
+ }
470
+ break;
471
+ }
472
+ } catch (e) {
473
+ this.lastError = e;
474
+ return VFS.SQLITE_IOERR;
475
+ }
476
+ return VFS.SQLITE_NOTFOUND;
477
+ }
478
+
479
+ /**
480
+ * @param {Uint8Array} zBuf
481
+ * @returns
482
+ */
483
+ jGetLastError(zBuf) {
484
+ if (this.lastError) {
485
+ console.error(this.lastError);
486
+ const outputArray = zBuf.subarray(0, zBuf.byteLength - 1);
487
+ const { written } = new TextEncoder().encodeInto(this.lastError.message, outputArray);
488
+ zBuf[written] = 0;
489
+ }
490
+ return VFS.SQLITE_OK
491
+ }
492
+
493
+ /**
494
+ * @param {FileSystemFileHandle} fileHandle
495
+ * @returns {Promise<PersistentFile>}
496
+ */
497
+ async #createPersistentFile(fileHandle) {
498
+ const persistentFile = new PersistentFile(fileHandle);
499
+ const root = await navigator.storage.getDirectory();
500
+ const relativePath = await root.resolve(fileHandle);
501
+ const path = `/${relativePath.join('/')}`;
502
+ persistentFile.handleRequestChannel = new BroadcastChannel(`ahp:${path}`);
503
+ this.persistentFiles.set(path, persistentFile);
504
+
505
+ const f = await fileHandle.getFile();
506
+ if (f.size) {
507
+ this.accessiblePaths.add(path);
508
+ }
509
+ return persistentFile;
510
+ }
511
+
512
+ /**
513
+ * @param {File} file
514
+ */
515
+ #requestAccessHandle(file) {
516
+ console.assert(!file.persistentFile.handleLockReleaser);
517
+ if (!file.persistentFile.isRequestInProgress) {
518
+ file.persistentFile.isRequestInProgress = true;
519
+ this._module.retryOps.push((async () => {
520
+ // Acquire the Web Lock.
521
+ file.persistentFile.handleLockReleaser = await this.#acquireLock(file.persistentFile);
522
+
523
+ // Get access handles for the database and releated files in parallel.
524
+ this.log?.(`creating access handles for ${file.path}`)
525
+ await Promise.all(DB_RELATED_FILE_SUFFIXES.map(async suffix => {
526
+ const persistentFile = this.persistentFiles.get(file.path + suffix);
527
+ if (persistentFile) {
528
+ persistentFile.accessHandle =
529
+ await persistentFile.fileHandle.createSyncAccessHandle();
530
+ }
531
+ }));
532
+ file.persistentFile.isRequestInProgress = false;
533
+ })());
534
+ return this._module.retryOps.at(-1);
535
+ }
536
+ return Promise.resolve();
537
+ }
538
+
539
+ /**
540
+ * @param {File} file
541
+ */
542
+ async #releaseAccessHandle(file) {
543
+ DB_RELATED_FILE_SUFFIXES.forEach(async suffix => {
544
+ const persistentFile = this.persistentFiles.get(file.path + suffix);
545
+ if (persistentFile) {
546
+ persistentFile.accessHandle?.close();
547
+ persistentFile.accessHandle = null;
548
+ }
549
+ });
550
+ this.log?.(`access handles closed for ${file.path}`)
551
+
552
+ file.persistentFile.handleLockReleaser?.();
553
+ file.persistentFile.handleLockReleaser = null;
554
+ this.log?.(`lock released for ${file.path}`)
555
+ }
556
+
557
+ /**
558
+ * @param {PersistentFile} persistentFile
559
+ * @returns {Promise<function>} lock releaser
560
+ */
561
+ #acquireLock(persistentFile) {
562
+ return new Promise(resolve => {
563
+ // Tell other connections we want the access handle.
564
+ const lockName = persistentFile.handleRequestChannel.name;
565
+ const notify = () => {
566
+ this.log?.(`notifying for ${lockName}`);
567
+ persistentFile.handleRequestChannel.postMessage(null);
568
+ }
569
+ const notifyId = setInterval(notify, LOCK_NOTIFY_INTERVAL);
570
+ setTimeout(notify);
571
+
572
+ this.log?.(`lock requested: ${lockName}`)
573
+ navigator.locks.request(lockName, lock => {
574
+ // We have the lock. Stop asking other connections for it.
575
+ this.log?.(`lock acquired: ${lockName}`, lock);
576
+ clearInterval(notifyId);
577
+ return new Promise(resolve);
578
+ });
579
+ });
580
+ }
581
+ }
582
+
583
+ function extractString(dataView, offset) {
584
+ const p = dataView.getUint32(offset, true);
585
+ if (p) {
586
+ const chars = new Uint8Array(dataView.buffer, p);
587
+ return new TextDecoder().decode(chars.subarray(0, chars.indexOf(0)));
588
+ }
589
+ return null;
590
+ }