@livestore/sqlite-wasm 3.46.0-build0

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.
@@ -0,0 +1,1029 @@
1
+ /*
2
+ 2022-09-16
3
+
4
+ The author disclaims copyright to this source code. In place of a
5
+ legal notice, here is a blessing:
6
+
7
+ * May you do good and not evil.
8
+ * May you find forgiveness for yourself and forgive others.
9
+ * May you share freely, never taking more than you give.
10
+
11
+ ***********************************************************************
12
+
13
+ A Worker which manages asynchronous OPFS handles on behalf of a
14
+ synchronous API which controls it via a combination of Worker
15
+ messages, SharedArrayBuffer, and Atomics. It is the asynchronous
16
+ counterpart of the API defined in sqlite3-vfs-opfs.js.
17
+
18
+ Highly indebted to:
19
+
20
+ https://github.com/rhashimoto/wa-sqlite/blob/master/src/examples/OriginPrivateFileSystemVFS.js
21
+
22
+ for demonstrating how to use the OPFS APIs.
23
+
24
+ This file is to be loaded as a Worker. It does not have any direct
25
+ access to the sqlite3 JS/WASM bits, so any bits which it needs (most
26
+ notably SQLITE_xxx integer codes) have to be imported into it via an
27
+ initialization process.
28
+
29
+ This file represents an implementation detail of a larger piece of
30
+ code, and not a public interface. Its details may change at any time
31
+ and are not intended to be used by any client-level code.
32
+
33
+ 2022-11-27: Chrome v108 changes some async methods to synchronous, as
34
+ documented at:
35
+
36
+ https://developer.chrome.com/blog/sync-methods-for-accesshandles/
37
+
38
+ Firefox v111 and Safari 16.4, both released in March 2023, also
39
+ include this.
40
+
41
+ We cannot change to the sync forms at this point without breaking
42
+ clients who use Chrome v104-ish or higher. truncate(), getSize(),
43
+ flush(), and close() are now (as of v108) synchronous. Calling them
44
+ with an "await", as we have to for the async forms, is still legal
45
+ with the sync forms but is superfluous. Calling the async forms with
46
+ theFunc().then(...) is not compatible with the change to
47
+ synchronous, but we do do not use those APIs that way. i.e. we don't
48
+ _need_ to change anything for this, but at some point (after Chrome
49
+ versions (approximately) 104-107 are extinct) should change our
50
+ usage of those methods to remove the "await".
51
+ */
52
+ 'use strict';
53
+ const wPost = (type, ...args) => postMessage({ type, payload: args });
54
+ const installAsyncProxy = function (self) {
55
+ const toss = function (...args) {
56
+ throw new Error(args.join(' '));
57
+ };
58
+ if (globalThis.window === globalThis) {
59
+ toss(
60
+ 'This code cannot run from the main thread.',
61
+ 'Load it as a Worker from a separate Worker.',
62
+ );
63
+ } else if (!navigator?.storage?.getDirectory) {
64
+ toss('This API requires navigator.storage.getDirectory.');
65
+ }
66
+
67
+ /** Will hold state copied to this object from the syncronous side of this API. */
68
+ const state = Object.create(null);
69
+
70
+ /**
71
+ * Verbose:
72
+ *
73
+ * 0 = no logging output
74
+ * 1 = only errors
75
+ * 2 = warnings and errors
76
+ * 3 = debug, warnings, and errors
77
+ */
78
+ state.verbose = 1;
79
+
80
+ const loggers = {
81
+ 0: console.error.bind(console),
82
+ 1: console.warn.bind(console),
83
+ 2: console.log.bind(console),
84
+ };
85
+ const logImpl = (level, ...args) => {
86
+ if (state.verbose > level) loggers[level]('OPFS asyncer:', ...args);
87
+ };
88
+ const log = (...args) => logImpl(2, ...args);
89
+ const warn = (...args) => logImpl(1, ...args);
90
+ const error = (...args) => logImpl(0, ...args);
91
+ const metrics = Object.create(null);
92
+ metrics.reset = () => {
93
+ let k;
94
+ const r = (m) => (m.count = m.time = m.wait = 0);
95
+ for (k in state.opIds) {
96
+ r((metrics[k] = Object.create(null)));
97
+ }
98
+ let s = (metrics.s11n = Object.create(null));
99
+ s = s.serialize = Object.create(null);
100
+ s.count = s.time = 0;
101
+ s = metrics.s11n.deserialize = Object.create(null);
102
+ s.count = s.time = 0;
103
+ };
104
+ metrics.dump = () => {
105
+ let k,
106
+ n = 0,
107
+ t = 0,
108
+ w = 0;
109
+ for (k in state.opIds) {
110
+ const m = metrics[k];
111
+ n += m.count;
112
+ t += m.time;
113
+ w += m.wait;
114
+ m.avgTime = m.count && m.time ? m.time / m.count : 0;
115
+ }
116
+ console.log(
117
+ globalThis?.location?.href,
118
+ 'metrics for',
119
+ globalThis?.location?.href,
120
+ ':\n',
121
+ metrics,
122
+ '\nTotal of',
123
+ n,
124
+ 'op(s) for',
125
+ t,
126
+ 'ms',
127
+ 'approx',
128
+ w,
129
+ 'ms spent waiting on OPFS APIs.',
130
+ );
131
+ console.log('Serialization metrics:', metrics.s11n);
132
+ };
133
+
134
+ /**
135
+ * __openFiles is a map of sqlite3_file pointers (integers) to metadata
136
+ * related to a given OPFS file handles. The pointers are, in this side of the
137
+ * interface, opaque file handle IDs provided by the synchronous part of this
138
+ * constellation. Each value is an object with a structure demonstrated in the
139
+ * xOpen() impl.
140
+ */
141
+ const __openFiles = Object.create(null);
142
+ /**
143
+ * __implicitLocks is a Set of sqlite3_file pointers (integers) which were
144
+ * "auto-locked". i.e. those for which we obtained a sync access handle
145
+ * without an explicit xLock() call. Such locks will be released during db
146
+ * connection idle time, whereas a sync access handle obtained via xLock(), or
147
+ * subsequently xLock()'d after auto-acquisition, will not be released until
148
+ * xUnlock() is called.
149
+ *
150
+ * Maintenance reminder: if we relinquish auto-locks at the end of the
151
+ * operation which acquires them, we pay a massive performance
152
+ * penalty: speedtest1 benchmarks take up to 4x as long. By delaying
153
+ * the lock release until idle time, the hit is negligible.
154
+ */
155
+ const __implicitLocks = new Set();
156
+
157
+ /**
158
+ * Expects an OPFS file path. It gets resolved, such that ".." components are
159
+ * properly expanded, and returned. If the 2nd arg is true, the result is
160
+ * returned as an array of path elements, else an absolute path string is
161
+ * returned.
162
+ */
163
+ const getResolvedPath = function (filename, splitIt) {
164
+ const p = new URL(filename, 'file://irrelevant').pathname;
165
+ return splitIt ? p.split('/').filter((v) => !!v) : p;
166
+ };
167
+
168
+ /**
169
+ * Takes the absolute path to a filesystem element. Returns an array of
170
+ * [handleOfContainingDir, filename]. If the 2nd argument is truthy then each
171
+ * directory element leading to the file is created along the way. Throws if
172
+ * any creation or resolution fails.
173
+ */
174
+ const getDirForFilename = async function f(absFilename, createDirs = false) {
175
+ const path = getResolvedPath(absFilename, true);
176
+ const filename = path.pop();
177
+ let dh = state.rootDir;
178
+ for (const dirName of path) {
179
+ if (dirName) {
180
+ dh = await dh.getDirectoryHandle(dirName, { create: !!createDirs });
181
+ }
182
+ }
183
+ return [dh, filename];
184
+ };
185
+
186
+ /**
187
+ * If the given file-holding object has a sync handle attached to it, that
188
+ * handle is remove and asynchronously closed. Though it may sound sensible to
189
+ * continue work as soon as the close() returns (noting that it's
190
+ * asynchronous), doing so can cause operations performed soon afterwards,
191
+ * e.g. a call to getSyncHandle() to fail because they may happen out of order
192
+ * from the close(). OPFS does not guaranty that the actual order of
193
+ * operations is retained in such cases. i.e. always "await" on the result of
194
+ * this function.
195
+ */
196
+ const closeSyncHandle = async (fh) => {
197
+ if (fh.syncHandle) {
198
+ log('Closing sync handle for', fh.filenameAbs);
199
+ const h = fh.syncHandle;
200
+ delete fh.syncHandle;
201
+ delete fh.xLock;
202
+ __implicitLocks.delete(fh.fid);
203
+ return h.close();
204
+ }
205
+ };
206
+
207
+ /**
208
+ * A proxy for closeSyncHandle() which is guaranteed to not throw.
209
+ *
210
+ * This function is part of a lock/unlock step in functions which
211
+ * require a sync access handle but may be called without xLock()
212
+ * having been called first. Such calls need to release that
213
+ * handle to avoid locking the file for all of time. This is an
214
+ * _attempt_ at reducing cross-tab contention but it may prove
215
+ * to be more of a problem than a solution and may need to be
216
+ * removed.
217
+ */
218
+ const closeSyncHandleNoThrow = async (fh) => {
219
+ try {
220
+ await closeSyncHandle(fh);
221
+ } catch (e) {
222
+ warn('closeSyncHandleNoThrow() ignoring:', e, fh);
223
+ }
224
+ };
225
+
226
+ /* Release all auto-locks. */
227
+ const releaseImplicitLocks = async () => {
228
+ if (__implicitLocks.size) {
229
+ /* Release all auto-locks. */
230
+ for (const fid of __implicitLocks) {
231
+ const fh = __openFiles[fid];
232
+ await closeSyncHandleNoThrow(fh);
233
+ log('Auto-unlocked', fid, fh.filenameAbs);
234
+ }
235
+ }
236
+ };
237
+
238
+ /**
239
+ * An experiment in improving concurrency by freeing up implicit locks sooner.
240
+ * This is known to impact performance dramatically but it has also shown to
241
+ * improve concurrency considerably.
242
+ *
243
+ * If fh.releaseImplicitLocks is truthy and fh is in __implicitLocks,
244
+ * this routine returns closeSyncHandleNoThrow(), else it is a no-op.
245
+ */
246
+ const releaseImplicitLock = async (fh) => {
247
+ if (fh.releaseImplicitLocks && __implicitLocks.has(fh.fid)) {
248
+ return closeSyncHandleNoThrow(fh);
249
+ }
250
+ };
251
+
252
+ /**
253
+ * An error class specifically for use with getSyncHandle(), the goal of which
254
+ * is to eventually be able to distinguish unambiguously between
255
+ * locking-related failures and other types, noting that we cannot currently
256
+ * do so because createSyncAccessHandle() does not define its exceptions in
257
+ * the required level of detail.
258
+ *
259
+ * 2022-11-29: according to:
260
+ *
261
+ * https://github.com/whatwg/fs/pull/21
262
+ *
263
+ * NoModificationAllowedError will be the standard exception thrown
264
+ * when acquisition of a sync access handle fails due to a locking
265
+ * error. As of this writing, that error type is not visible in the
266
+ * dev console in Chrome v109, nor is it documented in MDN, but an
267
+ * error with that "name" property is being thrown from the OPFS
268
+ * layer.
269
+ */
270
+ class GetSyncHandleError extends Error {
271
+ constructor(errorObject, ...msg) {
272
+ super(
273
+ [...msg, ': ' + errorObject.name + ':', errorObject.message].join(' '),
274
+ {
275
+ cause: errorObject,
276
+ },
277
+ );
278
+ this.name = 'GetSyncHandleError';
279
+ }
280
+ }
281
+ GetSyncHandleError.convertRc = (e, rc) => {
282
+ if (1) {
283
+ return e instanceof GetSyncHandleError &&
284
+ (e.cause.name === 'NoModificationAllowedError' ||
285
+ /* Inconsistent exception.name from Chrome/ium with the
286
+ same exception.message text: */
287
+ (e.cause.name === 'DOMException' &&
288
+ 0 === e.cause.message.indexOf('Access Handles cannot')))
289
+ ? /*console.warn("SQLITE_BUSY",e),*/
290
+ state.sq3Codes.SQLITE_BUSY
291
+ : rc;
292
+ } else {
293
+ return rc;
294
+ }
295
+ };
296
+ /**
297
+ * Returns the sync access handle associated with the given file handle object
298
+ * (which must be a valid handle object, as created by xOpen()), lazily
299
+ * opening it if needed.
300
+ *
301
+ * In order to help alleviate cross-tab contention for a dabase, if
302
+ * an exception is thrown while acquiring the handle, this routine
303
+ * will wait briefly and try again, up to some fixed number of
304
+ * times. If acquisition still fails at that point it will give up
305
+ * and propagate the exception. Client-level code will see that as
306
+ * an I/O error.
307
+ */
308
+ const getSyncHandle = async (fh, opName) => {
309
+ if (!fh.syncHandle) {
310
+ const t = performance.now();
311
+ log('Acquiring sync handle for', fh.filenameAbs);
312
+ const maxTries = 6,
313
+ msBase = state.asyncIdleWaitTime * 2;
314
+ let i = 1,
315
+ ms = msBase;
316
+ for (; true; ms = msBase * ++i) {
317
+ try {
318
+ //if(i<3) toss("Just testing getSyncHandle() wait-and-retry.");
319
+ //TODO? A config option which tells it to throw here
320
+ //randomly every now and then, for testing purposes.
321
+ fh.syncHandle = await fh.fileHandle.createSyncAccessHandle();
322
+ break;
323
+ } catch (e) {
324
+ if (i === maxTries) {
325
+ throw new GetSyncHandleError(
326
+ e,
327
+ 'Error getting sync handle for',
328
+ opName + '().',
329
+ maxTries,
330
+ 'attempts failed.',
331
+ fh.filenameAbs,
332
+ );
333
+ }
334
+ warn(
335
+ 'Error getting sync handle for',
336
+ opName + '(). Waiting',
337
+ ms,
338
+ 'ms and trying again.',
339
+ fh.filenameAbs,
340
+ e,
341
+ );
342
+ Atomics.wait(state.sabOPView, state.opIds.retry, 0, ms);
343
+ }
344
+ }
345
+ log(
346
+ 'Got',
347
+ opName + '() sync handle for',
348
+ fh.filenameAbs,
349
+ 'in',
350
+ performance.now() - t,
351
+ 'ms',
352
+ );
353
+ if (!fh.xLock) {
354
+ __implicitLocks.add(fh.fid);
355
+ log(
356
+ 'Acquired implicit lock for',
357
+ opName + '()',
358
+ fh.fid,
359
+ fh.filenameAbs,
360
+ );
361
+ }
362
+ }
363
+ return fh.syncHandle;
364
+ };
365
+
366
+ /**
367
+ * Stores the given value at state.sabOPView[state.opIds.rc] and then
368
+ * Atomics.notify()'s it.
369
+ */
370
+ const storeAndNotify = (opName, value) => {
371
+ log(opName + '() => notify(', value, ')');
372
+ Atomics.store(state.sabOPView, state.opIds.rc, value);
373
+ Atomics.notify(state.sabOPView, state.opIds.rc);
374
+ };
375
+
376
+ /** Throws if fh is a file-holding object which is flagged as read-only. */
377
+ const affirmNotRO = function (opName, fh) {
378
+ if (fh.readOnly) toss(opName + '(): File is read-only: ' + fh.filenameAbs);
379
+ };
380
+
381
+ /**
382
+ * We track 2 different timers: the "metrics" timer records how much time we
383
+ * spend performing work. The "wait" timer records how much time we spend
384
+ * waiting on the underlying OPFS timer. See the calls to mTimeStart(),
385
+ * mTimeEnd(), wTimeStart(), and wTimeEnd() throughout this file to see how
386
+ * they're used.
387
+ */
388
+ const __mTimer = Object.create(null);
389
+ __mTimer.op = undefined;
390
+ __mTimer.start = undefined;
391
+ const mTimeStart = (op) => {
392
+ __mTimer.start = performance.now();
393
+ __mTimer.op = op;
394
+ //metrics[op] || toss("Maintenance required: missing metrics for",op);
395
+ ++metrics[op].count;
396
+ };
397
+ const mTimeEnd = () =>
398
+ (metrics[__mTimer.op].time += performance.now() - __mTimer.start);
399
+ const __wTimer = Object.create(null);
400
+ __wTimer.op = undefined;
401
+ __wTimer.start = undefined;
402
+ const wTimeStart = (op) => {
403
+ __wTimer.start = performance.now();
404
+ __wTimer.op = op;
405
+ //metrics[op] || toss("Maintenance required: missing metrics for",op);
406
+ };
407
+ const wTimeEnd = () =>
408
+ (metrics[__wTimer.op].wait += performance.now() - __wTimer.start);
409
+
410
+ /**
411
+ * Gets set to true by the 'opfs-async-shutdown' command to quit the wait
412
+ * loop. This is only intended for debugging purposes: we cannot inspect this
413
+ * file's state while the tight waitLoop() is running and need a way to stop
414
+ * that loop for introspection purposes.
415
+ */
416
+ let flagAsyncShutdown = false;
417
+
418
+ /**
419
+ * Asynchronous wrappers for sqlite3_vfs and sqlite3_io_methods methods, as
420
+ * well as helpers like mkdir(). Maintenance reminder: members are in
421
+ * alphabetical order to simplify finding them.
422
+ */
423
+ const vfsAsyncImpls = {
424
+ 'opfs-async-metrics': async () => {
425
+ mTimeStart('opfs-async-metrics');
426
+ metrics.dump();
427
+ storeAndNotify('opfs-async-metrics', 0);
428
+ mTimeEnd();
429
+ },
430
+ 'opfs-async-shutdown': async () => {
431
+ flagAsyncShutdown = true;
432
+ storeAndNotify('opfs-async-shutdown', 0);
433
+ },
434
+ mkdir: async (dirname) => {
435
+ mTimeStart('mkdir');
436
+ let rc = 0;
437
+ wTimeStart('mkdir');
438
+ try {
439
+ await getDirForFilename(dirname + '/filepart', true);
440
+ } catch (e) {
441
+ state.s11n.storeException(2, e);
442
+ rc = state.sq3Codes.SQLITE_IOERR;
443
+ } finally {
444
+ wTimeEnd();
445
+ }
446
+ storeAndNotify('mkdir', rc);
447
+ mTimeEnd();
448
+ },
449
+ xAccess: async (filename) => {
450
+ mTimeStart('xAccess');
451
+ /* OPFS cannot support the full range of xAccess() queries
452
+ sqlite3 calls for. We can essentially just tell if the file
453
+ is accessible, but if it is then it's automatically writable
454
+ (unless it's locked, which we cannot(?) know without trying
455
+ to open it). OPFS does not have the notion of read-only.
456
+
457
+ The return semantics of this function differ from sqlite3's
458
+ xAccess semantics because we are limited in what we can
459
+ communicate back to our synchronous communication partner: 0 =
460
+ accessible, non-0 means not accessible.
461
+ */
462
+ let rc = 0;
463
+ wTimeStart('xAccess');
464
+ try {
465
+ const [dh, fn] = await getDirForFilename(filename);
466
+ await dh.getFileHandle(fn);
467
+ } catch (e) {
468
+ state.s11n.storeException(2, e);
469
+ rc = state.sq3Codes.SQLITE_IOERR;
470
+ } finally {
471
+ wTimeEnd();
472
+ }
473
+ storeAndNotify('xAccess', rc);
474
+ mTimeEnd();
475
+ },
476
+ xClose: async function (fid /*sqlite3_file pointer*/) {
477
+ const opName = 'xClose';
478
+ mTimeStart(opName);
479
+ __implicitLocks.delete(fid);
480
+ const fh = __openFiles[fid];
481
+ let rc = 0;
482
+ wTimeStart(opName);
483
+ if (fh) {
484
+ delete __openFiles[fid];
485
+ await closeSyncHandle(fh);
486
+ if (fh.deleteOnClose) {
487
+ try {
488
+ await fh.dirHandle.removeEntry(fh.filenamePart);
489
+ } catch (e) {
490
+ warn('Ignoring dirHandle.removeEntry() failure of', fh, e);
491
+ }
492
+ }
493
+ } else {
494
+ state.s11n.serialize();
495
+ rc = state.sq3Codes.SQLITE_NOTFOUND;
496
+ }
497
+ wTimeEnd();
498
+ storeAndNotify(opName, rc);
499
+ mTimeEnd();
500
+ },
501
+ xDelete: async function (...args) {
502
+ mTimeStart('xDelete');
503
+ const rc = await vfsAsyncImpls.xDeleteNoWait(...args);
504
+ storeAndNotify('xDelete', rc);
505
+ mTimeEnd();
506
+ },
507
+ xDeleteNoWait: async function (filename, syncDir = 0, recursive = false) {
508
+ /* The syncDir flag is, for purposes of the VFS API's semantics,
509
+ ignored here. However, if it has the value 0x1234 then: after
510
+ deleting the given file, recursively try to delete any empty
511
+ directories left behind in its wake (ignoring any errors and
512
+ stopping at the first failure).
513
+
514
+ That said: we don't know for sure that removeEntry() fails if
515
+ the dir is not empty because the API is not documented. It has,
516
+ however, a "recursive" flag which defaults to false, so
517
+ presumably it will fail if the dir is not empty and that flag
518
+ is false.
519
+ */
520
+ let rc = 0;
521
+ wTimeStart('xDelete');
522
+ try {
523
+ while (filename) {
524
+ const [hDir, filenamePart] = await getDirForFilename(filename, false);
525
+ if (!filenamePart) break;
526
+ await hDir.removeEntry(filenamePart, { recursive });
527
+ if (0x1234 !== syncDir) break;
528
+ recursive = false;
529
+ filename = getResolvedPath(filename, true);
530
+ filename.pop();
531
+ filename = filename.join('/');
532
+ }
533
+ } catch (e) {
534
+ state.s11n.storeException(2, e);
535
+ rc = state.sq3Codes.SQLITE_IOERR_DELETE;
536
+ }
537
+ wTimeEnd();
538
+ return rc;
539
+ },
540
+ xFileSize: async function (fid /*sqlite3_file pointer*/) {
541
+ mTimeStart('xFileSize');
542
+ const fh = __openFiles[fid];
543
+ let rc = 0;
544
+ wTimeStart('xFileSize');
545
+ try {
546
+ const sz = await (await getSyncHandle(fh, 'xFileSize')).getSize();
547
+ state.s11n.serialize(Number(sz));
548
+ } catch (e) {
549
+ state.s11n.storeException(1, e);
550
+ rc = GetSyncHandleError.convertRc(e, state.sq3Codes.SQLITE_IOERR);
551
+ }
552
+ await releaseImplicitLock(fh);
553
+ wTimeEnd();
554
+ storeAndNotify('xFileSize', rc);
555
+ mTimeEnd();
556
+ },
557
+ xLock: async function (
558
+ fid /*sqlite3_file pointer*/,
559
+ lockType /*SQLITE_LOCK_...*/,
560
+ ) {
561
+ mTimeStart('xLock');
562
+ const fh = __openFiles[fid];
563
+ let rc = 0;
564
+ const oldLockType = fh.xLock;
565
+ fh.xLock = lockType;
566
+ if (!fh.syncHandle) {
567
+ wTimeStart('xLock');
568
+ try {
569
+ await getSyncHandle(fh, 'xLock');
570
+ __implicitLocks.delete(fid);
571
+ } catch (e) {
572
+ state.s11n.storeException(1, e);
573
+ rc = GetSyncHandleError.convertRc(
574
+ e,
575
+ state.sq3Codes.SQLITE_IOERR_LOCK,
576
+ );
577
+ fh.xLock = oldLockType;
578
+ }
579
+ wTimeEnd();
580
+ }
581
+ storeAndNotify('xLock', rc);
582
+ mTimeEnd();
583
+ },
584
+ xOpen: async function (
585
+ fid /*sqlite3_file pointer*/,
586
+ filename,
587
+ flags /*SQLITE_OPEN_...*/,
588
+ opfsFlags /*OPFS_...*/,
589
+ ) {
590
+ const opName = 'xOpen';
591
+ mTimeStart(opName);
592
+ const create = state.sq3Codes.SQLITE_OPEN_CREATE & flags;
593
+ wTimeStart('xOpen');
594
+ try {
595
+ let hDir, filenamePart;
596
+ try {
597
+ [hDir, filenamePart] = await getDirForFilename(filename, !!create);
598
+ } catch (e) {
599
+ state.s11n.storeException(1, e);
600
+ storeAndNotify(opName, state.sq3Codes.SQLITE_NOTFOUND);
601
+ mTimeEnd();
602
+ wTimeEnd();
603
+ return;
604
+ }
605
+ const hFile = await hDir.getFileHandle(filenamePart, { create });
606
+ wTimeEnd();
607
+ const fh = Object.assign(Object.create(null), {
608
+ fid: fid,
609
+ filenameAbs: filename,
610
+ filenamePart: filenamePart,
611
+ dirHandle: hDir,
612
+ fileHandle: hFile,
613
+ sabView: state.sabFileBufView,
614
+ readOnly: create
615
+ ? false
616
+ : state.sq3Codes.SQLITE_OPEN_READONLY & flags,
617
+ deleteOnClose: !!(state.sq3Codes.SQLITE_OPEN_DELETEONCLOSE & flags),
618
+ });
619
+ fh.releaseImplicitLocks =
620
+ opfsFlags & state.opfsFlags.OPFS_UNLOCK_ASAP ||
621
+ state.opfsFlags.defaultUnlockAsap;
622
+ if (
623
+ 0 /* this block is modelled after something wa-sqlite
624
+ does but it leads to immediate contention on journal files.
625
+ Update: this approach reportedly only works for DELETE journal
626
+ mode. */ &&
627
+ 0 === (flags & state.sq3Codes.SQLITE_OPEN_MAIN_DB)
628
+ ) {
629
+ /* sqlite does not lock these files, so go ahead and grab an OPFS
630
+ lock. */
631
+ fh.xLock = 'xOpen' /* Truthy value to keep entry from getting
632
+ flagged as auto-locked. String value so
633
+ that we can easily distinguish is later
634
+ if needed. */;
635
+ await getSyncHandle(fh, 'xOpen');
636
+ }
637
+ __openFiles[fid] = fh;
638
+ storeAndNotify(opName, 0);
639
+ } catch (e) {
640
+ wTimeEnd();
641
+ error(opName, e);
642
+ state.s11n.storeException(1, e);
643
+ storeAndNotify(opName, state.sq3Codes.SQLITE_IOERR);
644
+ }
645
+ mTimeEnd();
646
+ },
647
+ xRead: async function (fid /*sqlite3_file pointer*/, n, offset64) {
648
+ mTimeStart('xRead');
649
+ let rc = 0,
650
+ nRead;
651
+ const fh = __openFiles[fid];
652
+ try {
653
+ wTimeStart('xRead');
654
+ nRead = (await getSyncHandle(fh, 'xRead')).read(
655
+ fh.sabView.subarray(0, n),
656
+ { at: Number(offset64) },
657
+ );
658
+ wTimeEnd();
659
+ if (nRead < n) {
660
+ /* Zero-fill remaining bytes */
661
+ fh.sabView.fill(0, nRead, n);
662
+ rc = state.sq3Codes.SQLITE_IOERR_SHORT_READ;
663
+ }
664
+ } catch (e) {
665
+ if (undefined === nRead) wTimeEnd();
666
+ error('xRead() failed', e, fh);
667
+ state.s11n.storeException(1, e);
668
+ rc = GetSyncHandleError.convertRc(e, state.sq3Codes.SQLITE_IOERR_READ);
669
+ }
670
+ await releaseImplicitLock(fh);
671
+ storeAndNotify('xRead', rc);
672
+ mTimeEnd();
673
+ },
674
+ xSync: async function (fid /*sqlite3_file pointer*/, flags /*ignored*/) {
675
+ mTimeStart('xSync');
676
+ const fh = __openFiles[fid];
677
+ let rc = 0;
678
+ if (!fh.readOnly && fh.syncHandle) {
679
+ try {
680
+ wTimeStart('xSync');
681
+ await fh.syncHandle.flush();
682
+ } catch (e) {
683
+ state.s11n.storeException(2, e);
684
+ rc = state.sq3Codes.SQLITE_IOERR_FSYNC;
685
+ }
686
+ wTimeEnd();
687
+ }
688
+ storeAndNotify('xSync', rc);
689
+ mTimeEnd();
690
+ },
691
+ xTruncate: async function (fid /*sqlite3_file pointer*/, size) {
692
+ mTimeStart('xTruncate');
693
+ let rc = 0;
694
+ const fh = __openFiles[fid];
695
+ wTimeStart('xTruncate');
696
+ try {
697
+ affirmNotRO('xTruncate', fh);
698
+ await (await getSyncHandle(fh, 'xTruncate')).truncate(size);
699
+ } catch (e) {
700
+ error('xTruncate():', e, fh);
701
+ state.s11n.storeException(2, e);
702
+ rc = GetSyncHandleError.convertRc(
703
+ e,
704
+ state.sq3Codes.SQLITE_IOERR_TRUNCATE,
705
+ );
706
+ }
707
+ await releaseImplicitLock(fh);
708
+ wTimeEnd();
709
+ storeAndNotify('xTruncate', rc);
710
+ mTimeEnd();
711
+ },
712
+ xUnlock: async function (
713
+ fid /*sqlite3_file pointer*/,
714
+ lockType /*SQLITE_LOCK_...*/,
715
+ ) {
716
+ mTimeStart('xUnlock');
717
+ let rc = 0;
718
+ const fh = __openFiles[fid];
719
+ if (state.sq3Codes.SQLITE_LOCK_NONE === lockType && fh.syncHandle) {
720
+ wTimeStart('xUnlock');
721
+ try {
722
+ await closeSyncHandle(fh);
723
+ } catch (e) {
724
+ state.s11n.storeException(1, e);
725
+ rc = state.sq3Codes.SQLITE_IOERR_UNLOCK;
726
+ }
727
+ wTimeEnd();
728
+ }
729
+ storeAndNotify('xUnlock', rc);
730
+ mTimeEnd();
731
+ },
732
+ xWrite: async function (fid /*sqlite3_file pointer*/, n, offset64) {
733
+ mTimeStart('xWrite');
734
+ let rc;
735
+ const fh = __openFiles[fid];
736
+ wTimeStart('xWrite');
737
+ try {
738
+ affirmNotRO('xWrite', fh);
739
+ rc =
740
+ n ===
741
+ (await getSyncHandle(fh, 'xWrite')).write(fh.sabView.subarray(0, n), {
742
+ at: Number(offset64),
743
+ })
744
+ ? 0
745
+ : state.sq3Codes.SQLITE_IOERR_WRITE;
746
+ } catch (e) {
747
+ error('xWrite():', e, fh);
748
+ state.s11n.storeException(1, e);
749
+ rc = GetSyncHandleError.convertRc(e, state.sq3Codes.SQLITE_IOERR_WRITE);
750
+ }
751
+ await releaseImplicitLock(fh);
752
+ wTimeEnd();
753
+ storeAndNotify('xWrite', rc);
754
+ mTimeEnd();
755
+ },
756
+ }; /*vfsAsyncImpls*/
757
+
758
+ const initS11n = () => {
759
+ /**
760
+ * ACHTUNG: this code is 100% duplicated in the other half of this proxy!
761
+ * The documentation is maintained in the "synchronous half".
762
+ */
763
+ if (state.s11n) return state.s11n;
764
+ const textDecoder = new TextDecoder(),
765
+ textEncoder = new TextEncoder('utf-8'),
766
+ viewU8 = new Uint8Array(
767
+ state.sabIO,
768
+ state.sabS11nOffset,
769
+ state.sabS11nSize,
770
+ ),
771
+ viewDV = new DataView(
772
+ state.sabIO,
773
+ state.sabS11nOffset,
774
+ state.sabS11nSize,
775
+ );
776
+ state.s11n = Object.create(null);
777
+ const TypeIds = Object.create(null);
778
+ TypeIds.number = {
779
+ id: 1,
780
+ size: 8,
781
+ getter: 'getFloat64',
782
+ setter: 'setFloat64',
783
+ };
784
+ TypeIds.bigint = {
785
+ id: 2,
786
+ size: 8,
787
+ getter: 'getBigInt64',
788
+ setter: 'setBigInt64',
789
+ };
790
+ TypeIds.boolean = {
791
+ id: 3,
792
+ size: 4,
793
+ getter: 'getInt32',
794
+ setter: 'setInt32',
795
+ };
796
+ TypeIds.string = { id: 4 };
797
+ const getTypeId = (v) =>
798
+ TypeIds[typeof v] ||
799
+ toss('Maintenance required: this value type cannot be serialized.', v);
800
+ const getTypeIdById = (tid) => {
801
+ switch (tid) {
802
+ case TypeIds.number.id:
803
+ return TypeIds.number;
804
+ case TypeIds.bigint.id:
805
+ return TypeIds.bigint;
806
+ case TypeIds.boolean.id:
807
+ return TypeIds.boolean;
808
+ case TypeIds.string.id:
809
+ return TypeIds.string;
810
+ default:
811
+ toss('Invalid type ID:', tid);
812
+ }
813
+ };
814
+ state.s11n.deserialize = function (clear = false) {
815
+ ++metrics.s11n.deserialize.count;
816
+ const t = performance.now();
817
+ const argc = viewU8[0];
818
+ const rc = argc ? [] : null;
819
+ if (argc) {
820
+ const typeIds = [];
821
+ let offset = 1,
822
+ i,
823
+ n,
824
+ v;
825
+ for (i = 0; i < argc; ++i, ++offset) {
826
+ typeIds.push(getTypeIdById(viewU8[offset]));
827
+ }
828
+ for (i = 0; i < argc; ++i) {
829
+ const t = typeIds[i];
830
+ if (t.getter) {
831
+ v = viewDV[t.getter](offset, state.littleEndian);
832
+ offset += t.size;
833
+ } else {
834
+ /*String*/
835
+ n = viewDV.getInt32(offset, state.littleEndian);
836
+ offset += 4;
837
+ v = textDecoder.decode(viewU8.slice(offset, offset + n));
838
+ offset += n;
839
+ }
840
+ rc.push(v);
841
+ }
842
+ }
843
+ if (clear) viewU8[0] = 0;
844
+ //log("deserialize:",argc, rc);
845
+ metrics.s11n.deserialize.time += performance.now() - t;
846
+ return rc;
847
+ };
848
+ state.s11n.serialize = function (...args) {
849
+ const t = performance.now();
850
+ ++metrics.s11n.serialize.count;
851
+ if (args.length) {
852
+ //log("serialize():",args);
853
+ const typeIds = [];
854
+ let i = 0,
855
+ offset = 1;
856
+ viewU8[0] = args.length & 0xff /* header = # of args */;
857
+ for (; i < args.length; ++i, ++offset) {
858
+ /* Write the TypeIds.id value into the next args.length
859
+ bytes. */
860
+ typeIds.push(getTypeId(args[i]));
861
+ viewU8[offset] = typeIds[i].id;
862
+ }
863
+ for (i = 0; i < args.length; ++i) {
864
+ /* Deserialize the following bytes based on their
865
+ corresponding TypeIds.id from the header. */
866
+ const t = typeIds[i];
867
+ if (t.setter) {
868
+ viewDV[t.setter](offset, args[i], state.littleEndian);
869
+ offset += t.size;
870
+ } else {
871
+ /*String*/
872
+ const s = textEncoder.encode(args[i]);
873
+ viewDV.setInt32(offset, s.byteLength, state.littleEndian);
874
+ offset += 4;
875
+ viewU8.set(s, offset);
876
+ offset += s.byteLength;
877
+ }
878
+ }
879
+ //log("serialize() result:",viewU8.slice(0,offset));
880
+ } else {
881
+ viewU8[0] = 0;
882
+ }
883
+ metrics.s11n.serialize.time += performance.now() - t;
884
+ };
885
+
886
+ state.s11n.storeException = state.asyncS11nExceptions
887
+ ? (priority, e) => {
888
+ if (priority <= state.asyncS11nExceptions) {
889
+ state.s11n.serialize([e.name, ': ', e.message].join(''));
890
+ }
891
+ }
892
+ : () => {};
893
+
894
+ return state.s11n;
895
+ }; /*initS11n()*/
896
+
897
+ const waitLoop = async function f() {
898
+ const opHandlers = Object.create(null);
899
+ for (let k of Object.keys(state.opIds)) {
900
+ const vi = vfsAsyncImpls[k];
901
+ if (!vi) continue;
902
+ const o = Object.create(null);
903
+ opHandlers[state.opIds[k]] = o;
904
+ o.key = k;
905
+ o.f = vi;
906
+ }
907
+ while (!flagAsyncShutdown) {
908
+ try {
909
+ if (
910
+ 'not-equal' !==
911
+ Atomics.wait(
912
+ state.sabOPView,
913
+ state.opIds.whichOp,
914
+ 0,
915
+ state.asyncIdleWaitTime,
916
+ )
917
+ ) {
918
+ /* Maintenance note: we compare against 'not-equal' because
919
+
920
+ https://github.com/tomayac/sqlite-wasm/issues/12
921
+
922
+ is reporting that this occassionally, under high loads,
923
+ returns 'ok', which leads to the whichOp being 0 (which
924
+ isn't a valid operation ID and leads to an exception,
925
+ along with a corresponding ugly console log
926
+ message). Unfortunately, the conditions for that cannot
927
+ be reliably reproduced. The only place in our code which
928
+ writes a 0 to the state.opIds.whichOp SharedArrayBuffer
929
+ index is a few lines down from here, and that instance
930
+ is required in order for clear communication between
931
+ the sync half of this proxy and this half.
932
+ */
933
+ await releaseImplicitLocks();
934
+ continue;
935
+ }
936
+ const opId = Atomics.load(state.sabOPView, state.opIds.whichOp);
937
+ Atomics.store(state.sabOPView, state.opIds.whichOp, 0);
938
+ const hnd =
939
+ opHandlers[opId] ?? toss('No waitLoop handler for whichOp #', opId);
940
+ const args =
941
+ state.s11n.deserialize(
942
+ true /* clear s11n to keep the caller from confusing this with
943
+ an exception string written by the upcoming
944
+ operation */,
945
+ ) || [];
946
+ //warn("waitLoop() whichOp =",opId, hnd, args);
947
+ if (hnd.f) await hnd.f(...args);
948
+ else error('Missing callback for opId', opId);
949
+ } catch (e) {
950
+ error('in waitLoop():', e);
951
+ }
952
+ }
953
+ };
954
+
955
+ navigator.storage
956
+ .getDirectory()
957
+ .then(function (d) {
958
+ state.rootDir = d;
959
+ globalThis.onmessage = function ({ data }) {
960
+ switch (data.type) {
961
+ case 'opfs-async-init': {
962
+ /* Receive shared state from synchronous partner */
963
+ const opt = data.args;
964
+ for (const k in opt) state[k] = opt[k];
965
+ state.verbose = opt.verbose ?? 1;
966
+ state.sabOPView = new Int32Array(state.sabOP);
967
+ state.sabFileBufView = new Uint8Array(
968
+ state.sabIO,
969
+ 0,
970
+ state.fileBufferSize,
971
+ );
972
+ state.sabS11nView = new Uint8Array(
973
+ state.sabIO,
974
+ state.sabS11nOffset,
975
+ state.sabS11nSize,
976
+ );
977
+ Object.keys(vfsAsyncImpls).forEach((k) => {
978
+ if (!Number.isFinite(state.opIds[k])) {
979
+ toss('Maintenance required: missing state.opIds[', k, ']');
980
+ }
981
+ });
982
+ initS11n();
983
+ metrics.reset();
984
+ log('init state', state);
985
+ wPost('opfs-async-inited');
986
+ waitLoop();
987
+ break;
988
+ }
989
+ case 'opfs-async-restart':
990
+ if (flagAsyncShutdown) {
991
+ warn(
992
+ 'Restarting after opfs-async-shutdown. Might or might not work.',
993
+ );
994
+ flagAsyncShutdown = false;
995
+ waitLoop();
996
+ }
997
+ break;
998
+ case 'opfs-async-metrics':
999
+ metrics.dump();
1000
+ break;
1001
+ }
1002
+ };
1003
+ wPost('opfs-async-loaded');
1004
+ })
1005
+ .catch((e) => error('error initializing OPFS asyncer:', e));
1006
+ }; /*installAsyncProxy()*/
1007
+ if (!globalThis.SharedArrayBuffer) {
1008
+ wPost(
1009
+ 'opfs-unavailable',
1010
+ 'Missing SharedArrayBuffer API.',
1011
+ 'The server must emit the COOP/COEP response headers to enable that.',
1012
+ );
1013
+ } else if (!globalThis.Atomics) {
1014
+ wPost(
1015
+ 'opfs-unavailable',
1016
+ 'Missing Atomics API.',
1017
+ 'The server must emit the COOP/COEP response headers to enable that.',
1018
+ );
1019
+ } else if (
1020
+ !globalThis.FileSystemHandle ||
1021
+ !globalThis.FileSystemDirectoryHandle ||
1022
+ !globalThis.FileSystemFileHandle ||
1023
+ !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle ||
1024
+ !navigator?.storage?.getDirectory
1025
+ ) {
1026
+ wPost('opfs-unavailable', 'Missing required OPFS APIs.');
1027
+ } else {
1028
+ installAsyncProxy(self);
1029
+ }