@dolthub/doltlite-wasm 0.11.16

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,1105 @@
1
+ /* @preserve
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) we should change our
50
+ usage of those methods to remove the "await".
51
+ */
52
+
53
+ "use strict";
54
+ const urlParams = new URL(globalThis.location.href).searchParams;
55
+ const vfsName = urlParams.get('vfs');
56
+ if( !vfsName ){
57
+ throw new Error("Expecting vfs=opfs|opfs-wl URL argument for this worker");
58
+ }
59
+ /**
60
+ We use this to allow us to differentiate debug output from
61
+ multiple instances, e.g. multiple Workers to the "opfs"
62
+ VFS or both the "opfs" and "opfs-wl" VFSes.
63
+ */
64
+ const workerId = (Math.random() * 10000000) | 0;
65
+ const isWebLocker = 'opfs-wl'===urlParams.get('vfs');
66
+ const wPost = (type,...args)=>postMessage({type, payload:args});
67
+ const installAsyncProxy = function(){
68
+ const toss = function(...args){throw new Error(args.join(' '))};
69
+ if(globalThis.window === globalThis){
70
+ toss("This code cannot run from the main thread.",
71
+ "Load it as a Worker from a separate Worker.");
72
+ }else if(!navigator?.storage?.getDirectory){
73
+ toss("This API requires navigator.storage.getDirectory.");
74
+ }
75
+
76
+ /**
77
+ Will hold state copied to this object from the synchronous side of
78
+ this API.
79
+ */
80
+ const state = Object.create(null);
81
+
82
+ /* initS11n() is preprocessor-injected so that we have identical
83
+ copies in the synchronous and async halves. This side does not
84
+ load the SQLite library, so does not have access to that copy. */
85
+ const initS11n = function(){
86
+ /**
87
+ This proxy de/serializes cross-thread function arguments and
88
+ output-pointer values via the state.sabIO SharedArrayBuffer,
89
+ using the region defined by (state.sabS11nOffset,
90
+ state.sabS11nOffset + state.sabS11nSize]. Only one dataset is
91
+ recorded at a time.
92
+
93
+ This is not a general-purpose format. It only supports the
94
+ range of operations, and data sizes, needed by the
95
+ sqlite3_vfs and sqlite3_io_methods operations. Serialized
96
+ data are transient and this serialization algorithm may
97
+ change at any time.
98
+
99
+ The data format can be succinctly summarized as:
100
+
101
+ Nt...Td...D
102
+
103
+ Where:
104
+
105
+ - N = number of entries (1 byte)
106
+
107
+ - t = type ID of first argument (1 byte)
108
+
109
+ - ...T = type IDs of the 2nd and subsequent arguments (1 byte
110
+ each).
111
+
112
+ - d = raw bytes of first argument (per-type size).
113
+
114
+ - ...D = raw bytes of the 2nd and subsequent arguments (per-type
115
+ size).
116
+
117
+ All types except strings have fixed sizes. Strings are stored
118
+ using their TextEncoder/TextDecoder representations. It would
119
+ arguably make more sense to store them as Int16Arrays of
120
+ their JS character values, but how best/fastest to get that
121
+ in and out of string form is an open point. Initial
122
+ experimentation with that approach did not gain us any speed.
123
+
124
+ Historical note: this impl was initially about 1% this size by
125
+ using using JSON.stringify/parse(), but using fit-to-purpose
126
+ serialization saves considerable runtime.
127
+ */
128
+ if(state.s11n) return state.s11n;
129
+ const textDecoder = new TextDecoder(),
130
+ textEncoder = new TextEncoder('utf-8'),
131
+ viewU8 = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize),
132
+ viewDV = new DataView(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
133
+ state.s11n = Object.create(null);
134
+ /* Only arguments and return values of these types may be
135
+ serialized. This covers the whole range of types needed by the
136
+ sqlite3_vfs API. */
137
+ const TypeIds = Object.create(null);
138
+ TypeIds.number = { id: 1, size: 8, getter: 'getFloat64', setter: 'setFloat64' };
139
+ TypeIds.bigint = { id: 2, size: 8, getter: 'getBigInt64', setter: 'setBigInt64' };
140
+ TypeIds.boolean = { id: 3, size: 4, getter: 'getInt32', setter: 'setInt32' };
141
+ TypeIds.string = { id: 4 };
142
+
143
+ const getTypeId = (v)=>(
144
+ TypeIds[typeof v]
145
+ || toss("Maintenance required: this value type cannot be serialized.",v)
146
+ );
147
+ const getTypeIdById = (tid)=>{
148
+ switch(tid){
149
+ case TypeIds.number.id: return TypeIds.number;
150
+ case TypeIds.bigint.id: return TypeIds.bigint;
151
+ case TypeIds.boolean.id: return TypeIds.boolean;
152
+ case TypeIds.string.id: return TypeIds.string;
153
+ default: toss("Invalid type ID:",tid);
154
+ }
155
+ };
156
+
157
+ /**
158
+ Returns an array of the deserialized state stored by the most
159
+ recent serialize() operation (from this thread or the
160
+ counterpart thread), or null if the serialization buffer is
161
+ empty. If passed a truthy argument, the serialization buffer
162
+ is cleared after deserialization.
163
+ */
164
+ state.s11n.deserialize = function(clear=false){
165
+ const t = performance.now();
166
+ const argc = viewU8[0];
167
+ const rc = argc ? [] : null;
168
+ if(argc){
169
+ const typeIds = [];
170
+ let offset = 1, i, n, v;
171
+ for(i = 0; i < argc; ++i, ++offset){
172
+ typeIds.push(getTypeIdById(viewU8[offset]));
173
+ }
174
+ for(i = 0; i < argc; ++i){
175
+ const t = typeIds[i];
176
+ if(t.getter){
177
+ v = viewDV[t.getter](offset, state.littleEndian);
178
+ offset += t.size;
179
+ }else{/*String*/
180
+ n = viewDV.getInt32(offset, state.littleEndian);
181
+ offset += 4;
182
+ v = textDecoder.decode(viewU8.slice(offset, offset+n));
183
+ offset += n;
184
+ }
185
+ rc.push(v);
186
+ }
187
+ }
188
+ if(clear) viewU8[0] = 0;
189
+ //log("deserialize:",argc, rc);
190
+ return rc;
191
+ };
192
+
193
+ /**
194
+ Serializes all arguments to the shared buffer for consumption
195
+ by the counterpart thread.
196
+
197
+ This routine is only intended for serializing OPFS VFS
198
+ arguments and (in at least one special case) result values,
199
+ and the buffer is sized to be able to comfortably handle
200
+ those.
201
+
202
+ If passed no arguments then it zeroes out the serialization
203
+ state.
204
+ */
205
+ state.s11n.serialize = function(...args){
206
+ const t = performance.now();
207
+ if(args.length){
208
+ //log("serialize():",args);
209
+ const typeIds = [];
210
+ let i = 0, offset = 1;
211
+ viewU8[0] = args.length & 0xff /* header = # of args */;
212
+ for(; i < args.length; ++i, ++offset){
213
+ /* Write the TypeIds.id value into the next args.length
214
+ bytes. */
215
+ typeIds.push(getTypeId(args[i]));
216
+ viewU8[offset] = typeIds[i].id;
217
+ }
218
+ for(i = 0; i < args.length; ++i) {
219
+ /* Deserialize the following bytes based on their
220
+ corresponding TypeIds.id from the header. */
221
+ const t = typeIds[i];
222
+ if(t.setter){
223
+ viewDV[t.setter](offset, args[i], state.littleEndian);
224
+ offset += t.size;
225
+ }else{/*String*/
226
+ const s = textEncoder.encode(args[i]);
227
+ viewDV.setInt32(offset, s.byteLength, state.littleEndian);
228
+ offset += 4;
229
+ viewU8.set(s, offset);
230
+ offset += s.byteLength;
231
+ }
232
+ }
233
+ //log("serialize() result:",viewU8.slice(0,offset));
234
+ }else{
235
+ viewU8[0] = 0;
236
+ }
237
+ };
238
+
239
+ state.s11n.storeException = state.asyncS11nExceptions
240
+ ? ((priority,e)=>{
241
+ if(priority<=state.asyncS11nExceptions){
242
+ state.s11n.serialize([e.name,': ',e.message].join(""));
243
+ }
244
+ })
245
+ : ()=>{};
246
+
247
+ return state.s11n;
248
+ }/*initS11n()*/;
249
+
250
+ /**
251
+ verbose:
252
+
253
+ 0 = no logging output
254
+ 1 = only errors
255
+ 2 = warnings and errors
256
+ 3 = debug, warnings, and errors
257
+ */
258
+ state.verbose = 1;
259
+
260
+ const loggers = {
261
+ 0:console.error.bind(console),
262
+ 1:console.warn.bind(console),
263
+ 2:console.log.bind(console)
264
+ };
265
+ const logImpl = (level,...args)=>{
266
+ if(state.verbose>level) loggers[level](vfsName+' async-proxy',workerId+":",...args);
267
+ };
268
+ const log = (...args)=>logImpl(2, ...args);
269
+ const warn = (...args)=>logImpl(1, ...args);
270
+ const error = (...args)=>logImpl(0, ...args);
271
+
272
+ /**
273
+ __openFiles is a map of sqlite3_file pointers (integers) to
274
+ metadata related to a given OPFS file handles. The pointers are, in
275
+ this side of the interface, opaque file handle IDs provided by the
276
+ synchronous part of this constellation. Each value is an object
277
+ with a structure demonstrated in the xOpen() impl.
278
+ */
279
+ const __openFiles = Object.create(null);
280
+ /**
281
+ __implicitLocks is a Set of sqlite3_file pointers (integers)
282
+ which were "auto-locked". i.e. those for which we necessarily
283
+ obtain a sync access handle without an explicit xLock() call
284
+ guarding access. Such locks will be released during
285
+ `waitLoop()`'s idle time, whereas a sync access handle obtained
286
+ via xLock(), or subsequently xLock()'d after auto-acquisition,
287
+ will not be released until xUnlock() is called.
288
+
289
+ Maintenance reminder: if we relinquish auto-locks at the end of the
290
+ operation which acquires them, we pay a massive performance
291
+ penalty: speedtest1 benchmarks take up to 4x as long. By delaying
292
+ the lock release until idle time, the hit is negligible.
293
+ */
294
+ const __implicitLocks = new Set();
295
+
296
+ /**
297
+ Expects an OPFS file path. It gets resolved, such that ".."
298
+ components are properly expanded, and returned. If the 2nd arg is
299
+ true, the result is returned as an array of path elements, else an
300
+ absolute path string is returned.
301
+ */
302
+ const getResolvedPath = function(filename,splitIt){
303
+ const p = new URL(
304
+ filename, 'file://irrelevant'
305
+ ).pathname;
306
+ return splitIt ? p.split('/').filter((v)=>!!v) : p;
307
+ };
308
+
309
+ /**
310
+ Takes the absolute path to a filesystem element. Returns an array
311
+ of [handleOfContainingDir, filename]. If the 2nd argument is truthy
312
+ then each directory element leading to the file is created along
313
+ the way. Throws if any creation or resolution fails.
314
+ */
315
+ const getDirForFilename = async function f(absFilename, createDirs = false){
316
+ const path = getResolvedPath(absFilename, true);
317
+ const filename = path.pop();
318
+ let dh = state.rootDir;
319
+ for(const dirName of path){
320
+ if(dirName){
321
+ dh = await dh.getDirectoryHandle(dirName, {create: !!createDirs});
322
+ }
323
+ }
324
+ return [dh, filename];
325
+ };
326
+
327
+ /**
328
+ If the given file-holding object has a sync handle attached to it,
329
+ that handle is removed and asynchronously closed. Though it may
330
+ sound sensible to continue work as soon as the close() returns
331
+ (noting that it's asynchronous), doing so can cause operations
332
+ performed soon afterwards, e.g. a call to getSyncHandle(), to fail
333
+ because they may happen out of order from the close(). OPFS does
334
+ not guaranty that the actual order of operations is retained in
335
+ such cases. i.e. always "await" on the result of this function.
336
+ */
337
+ const closeSyncHandle = async (fh)=>{
338
+ if(fh.syncHandle){
339
+ log("Closing sync handle for",fh.filenameAbs);
340
+ const h = fh.syncHandle;
341
+ delete fh.syncHandle;
342
+ delete fh.xLock;
343
+ __implicitLocks.delete(fh.fid);
344
+ return h.close();
345
+ }
346
+ };
347
+
348
+ /**
349
+ A proxy for closeSyncHandle() which is guaranteed to not throw.
350
+
351
+ This function is part of a lock/unlock step in functions which
352
+ require a sync access handle but may be called without xLock()
353
+ having been called first. Such calls need to release that
354
+ handle to avoid locking the file for all of time. This is an
355
+ _attempt_ at reducing cross-tab contention but it may prove
356
+ to be more of a problem than a solution and may need to be
357
+ removed.
358
+ */
359
+ const closeSyncHandleNoThrow = async (fh)=>{
360
+ try{await closeSyncHandle(fh)}
361
+ catch(e){
362
+ warn("closeSyncHandleNoThrow() ignoring:",e,fh);
363
+ }
364
+ };
365
+
366
+ /* Release all auto-locks. */
367
+ const releaseImplicitLocks = async ()=>{
368
+ if(__implicitLocks.size){
369
+ /* Release all auto-locks. */
370
+ for(const fid of __implicitLocks){
371
+ const fh = __openFiles[fid];
372
+ await closeSyncHandleNoThrow(fh);
373
+ log("Auto-unlocked",fid,fh.filenameAbs);
374
+ }
375
+ }
376
+ };
377
+
378
+ /**
379
+ An experiment in improving concurrency by freeing up implicit locks
380
+ sooner. This is known to impact performance dramatically but it has
381
+ also shown to improve concurrency considerably.
382
+
383
+ If fh.releaseImplicitLocks is truthy and fh is in __implicitLocks,
384
+ this routine returns closeSyncHandleNoThrow(), else it is a no-op.
385
+ */
386
+ const releaseImplicitLock = async (fh)=>{
387
+ if(fh.releaseImplicitLocks && __implicitLocks.has(fh.fid)){
388
+ return closeSyncHandleNoThrow(fh);
389
+ }
390
+ };
391
+
392
+ /**
393
+ An error class specifically for use with getSyncHandle(), the goal
394
+ of which is to eventually be able to distinguish unambiguously
395
+ between locking-related failures and other types, noting that we
396
+ cannot currently do so because createSyncAccessHandle() does not
397
+ define its exceptions in the required level of detail.
398
+
399
+ 2022-11-29: according to:
400
+
401
+ https://github.com/whatwg/fs/pull/21
402
+
403
+ NoModificationAllowedError will be the standard exception thrown
404
+ when acquisition of a sync access handle fails due to a locking
405
+ error. As of this writing, that error type is not visible in the
406
+ dev console in Chrome v109, nor is it documented in MDN, but an
407
+ error with that "name" property is being thrown from the OPFS
408
+ layer.
409
+ */
410
+ class GetSyncHandleError extends Error {
411
+ constructor(errorObject, ...msg){
412
+ super([
413
+ ...msg, ': '+errorObject.name+':',
414
+ errorObject.message
415
+ ].join(' '), {
416
+ cause: errorObject
417
+ });
418
+ this.name = 'GetSyncHandleError';
419
+ }
420
+ };
421
+
422
+ /**
423
+ Attempts to find a suitable SQLITE_xyz result code for Error
424
+ object e. Returns either such a translation or rc if if it does
425
+ not know how to translate the exception.
426
+ */
427
+ GetSyncHandleError.convertRc = (e,rc)=>{
428
+ if( e instanceof GetSyncHandleError ){
429
+ if( e.cause.name==='NoModificationAllowedError'
430
+ /* Inconsistent exception.name from Chrome/ium with the
431
+ same exception.message text: */
432
+ || (e.cause.name==='DOMException'
433
+ && 0===e.cause.message.indexOf('Access Handles cannot')) ){
434
+ return state.sq3Codes.SQLITE_BUSY;
435
+ }else if( 'NotFoundError'===e.cause.name ){
436
+ /**
437
+ Maintenance reminder: SQLITE_NOTFOUND, though it looks like
438
+ a good match, has different semantics than NotFoundError
439
+ and is not suitable here.
440
+ */
441
+ return state.sq3Codes.SQLITE_CANTOPEN;
442
+ }
443
+ }else if( 'NotFoundError'===e?.name ){
444
+ return state.sq3Codes.SQLITE_CANTOPEN;
445
+ }
446
+ return rc;
447
+ };
448
+
449
+ /**
450
+ Returns the sync access handle associated with the given file
451
+ handle object (which must be a valid handle object, as created by
452
+ xOpen()), lazily opening it if needed.
453
+
454
+ In order to help alleviate cross-tab contention for a dabase, if
455
+ an exception is thrown while acquiring the handle, this routine
456
+ will wait briefly and try again, up to `maxTries` of times. If
457
+ acquisition still fails at that point it will give up and
458
+ propagate the exception. Client-level code will see that either
459
+ as an I/O error or SQLITE_BUSY, depending on the exception and
460
+ the context.
461
+
462
+ 2024-06-12: there is a rare race condition here which has been
463
+ reported a single time:
464
+
465
+ https://sqlite.org/forum/forumpost/9ee7f5340802d600
466
+
467
+ What appears to be happening is that file we're waiting for a
468
+ lock on is deleted while we wait. What currently happens here is
469
+ that a locking exception is thrown but the exception type is
470
+ NotFoundError. In such cases, we very probably should attempt to
471
+ re-open/re-create the file an obtain the lock on it (noting that
472
+ there's another race condition there). That's easy to say but
473
+ creating a viable test for that condition has proven challenging
474
+ so far.
475
+
476
+ Interface quirk: if fh.xLock is falsy and the handle is acquired
477
+ then fh.fid is added to __implicitLocks(). If fh.xLock is truthy,
478
+ it is not added as an implicit lock. i.e. xLock() impls must set
479
+ fh.xLock immediately _before_ calling this and must arrange to
480
+ restore it to its previous value if this function throws.
481
+
482
+ 2026-03-06:
483
+
484
+ - baseWaitTime is the number of milliseconds to wait for the
485
+ first retry, increasing by one factor for each retry. It defaults
486
+ to (state.asyncIdleWaitTime*2).
487
+
488
+ - maxTries is the number of attempt to make, each one spaced out
489
+ by one additional factor of the baseWaitTime (e.g. 300, then 600,
490
+ then 900, the 1200...). This MUST be an integer >0.
491
+
492
+ Only the Web Locks impl should use the 3rd and 4th parameters.
493
+ */
494
+ const getSyncHandle = async (fh, opName, baseWaitTime, maxTries = 6)=>{
495
+ if(!fh.syncHandle){
496
+ const t = performance.now();
497
+ log("Acquiring sync handle for",fh.filenameAbs);
498
+ const msBase = baseWaitTime ?? (state.asyncIdleWaitTime * 2);
499
+ maxTries ??= 6;
500
+ let i = 1, ms = msBase;
501
+ for(; true; ms = msBase * ++i){
502
+ try {
503
+ //if(i<3) toss("Just testing getSyncHandle() wait-and-retry.");
504
+ //TODO? A config option which tells it to throw here
505
+ //randomly every now and then, for testing purposes.
506
+ fh.syncHandle = await fh.fileHandle.createSyncAccessHandle();
507
+ break;
508
+ }catch(e){
509
+ if(i === maxTries){
510
+ throw new GetSyncHandleError(
511
+ e, "Error getting sync handle for",opName+"().",maxTries,
512
+ "attempts failed.",fh.filenameAbs
513
+ );
514
+ }
515
+ warn("Error getting sync handle for",opName+"(). Waiting",ms,
516
+ "ms and trying again.",fh.filenameAbs,e);
517
+ Atomics.wait(state.sabOPView, state.opIds.retry, 0, ms);
518
+ }
519
+ }
520
+ log("Got",opName+"() sync handle for",fh.filenameAbs,
521
+ 'in',performance.now() - t,'ms');
522
+ if(!fh.xLock){
523
+ __implicitLocks.add(fh.fid);
524
+ log("Acquired implicit lock for",opName+"()",fh.fid,fh.filenameAbs);
525
+ }
526
+ }
527
+ return fh.syncHandle;
528
+ };
529
+
530
+ /**
531
+ Stores the given value at state.sabOPView[state.opIds.rc] and then
532
+ Atomics.notify()'s it.
533
+
534
+ The opName is only used for logging and debugging - all result
535
+ codes are expected on the same state.sabOPView slot.
536
+ */
537
+ const storeAndNotify = (opName, value)=>{
538
+ log(opName+"() => notify(",value,")");
539
+ Atomics.store(state.sabOPView, state.opIds.rc, value);
540
+ Atomics.notify(state.sabOPView, state.opIds.rc);
541
+ };
542
+
543
+ /**
544
+ Throws if fh is a file-holding object which is flagged as read-only.
545
+ */
546
+ const affirmNotRO = function(opName,fh){
547
+ if(fh.readOnly) toss(opName+"(): File is read-only: "+fh.filenameAbs);
548
+ };
549
+
550
+ /**
551
+ Gets set to true by the 'opfs-async-shutdown' command to quit the
552
+ wait loop. This is only intended for debugging purposes: we cannot
553
+ inspect this file's state while the tight waitLoop() is running and
554
+ need a way to stop that loop for introspection purposes.
555
+ */
556
+ let flagAsyncShutdown = false;
557
+
558
+ /**
559
+ Asynchronous wrappers for sqlite3_vfs and sqlite3_io_methods
560
+ methods, as well as helpers like mkdir().
561
+ */
562
+ const vfsAsyncImpls = {
563
+ 'opfs-async-shutdown': async ()=>{
564
+ flagAsyncShutdown = true;
565
+ storeAndNotify('opfs-async-shutdown', 0);
566
+ },
567
+ mkdir: async (dirname)=>{
568
+ let rc = 0;
569
+ try {
570
+ await getDirForFilename(dirname+"/filepart", true);
571
+ }catch(e){
572
+ state.s11n.storeException(2,e);
573
+ rc = state.sq3Codes.SQLITE_IOERR;
574
+ }
575
+ storeAndNotify('mkdir', rc);
576
+ },
577
+ xAccess: async (filename)=>{
578
+ /* OPFS cannot support the full range of xAccess() queries
579
+ sqlite3 calls for. We can essentially just tell if the file
580
+ is accessible, but if it is then it's automatically writable
581
+ (unless it's locked, which we cannot(?) know without trying
582
+ to open it). OPFS does not have the notion of read-only.
583
+
584
+ The return semantics of this function differ from sqlite3's
585
+ xAccess semantics because we are limited in what we can
586
+ communicate back to our synchronous communication partner: 0 =
587
+ accessible, non-0 means not accessible.
588
+ */
589
+ let rc = 0;
590
+ try{
591
+ const [dh, fn] = await getDirForFilename(filename);
592
+ await dh.getFileHandle(fn);
593
+ }catch(e){
594
+ state.s11n.storeException(2,e);
595
+ rc = state.sq3Codes.SQLITE_IOERR;
596
+ }
597
+ storeAndNotify('xAccess', rc);
598
+ },
599
+ xClose: async function(fid/*sqlite3_file pointer*/){
600
+ const opName = 'xClose';
601
+ __implicitLocks.delete(fid);
602
+ const fh = __openFiles[fid];
603
+ let rc = 0;
604
+ if(fh){
605
+ delete __openFiles[fid];
606
+ await closeSyncHandle(fh);
607
+ if(fh.deleteOnClose){
608
+ try{ await fh.dirHandle.removeEntry(fh.filenamePart) }
609
+ catch(e){ warn("Ignoring dirHandle.removeEntry() failure of",fh,e) }
610
+ }
611
+ }else{
612
+ state.s11n.serialize();
613
+ rc = state.sq3Codes.SQLITE_NOTFOUND;
614
+ }
615
+ storeAndNotify(opName, rc);
616
+ },
617
+ xDelete: async function(...args){
618
+ const rc = await vfsAsyncImpls.xDeleteNoWait(...args);
619
+ storeAndNotify('xDelete', rc);
620
+ },
621
+ xDeleteNoWait: async function(filename, syncDir = 0, recursive = false){
622
+ /* The syncDir flag is, for purposes of the VFS API's semantics,
623
+ ignored here. However, if it has the value 0x1234 then: after
624
+ deleting the given file, recursively try to delete any empty
625
+ directories left behind in its wake (ignoring any errors and
626
+ stopping at the first failure).
627
+
628
+ That said: we don't know for sure that removeEntry() fails if
629
+ the dir is not empty because the API is not documented. It has,
630
+ however, a "recursive" flag which defaults to false, so
631
+ presumably it will fail if the dir is not empty and that flag
632
+ is false.
633
+ */
634
+ let rc = 0;
635
+ try {
636
+ while(filename){
637
+ const [hDir, filenamePart] = await getDirForFilename(filename, false);
638
+ if(!filenamePart) break;
639
+ await hDir.removeEntry(filenamePart, {recursive});
640
+ if(0x1234 !== syncDir) break;
641
+ recursive = false;
642
+ filename = getResolvedPath(filename, true);
643
+ filename.pop();
644
+ filename = filename.join('/');
645
+ }
646
+ }catch(e){
647
+ state.s11n.storeException(2,e);
648
+ rc = state.sq3Codes.SQLITE_IOERR_DELETE;
649
+ }
650
+ return rc;
651
+ },
652
+ xFileSize: async function(fid/*sqlite3_file pointer*/){
653
+ const fh = __openFiles[fid];
654
+ let rc = 0;
655
+ try{
656
+ const sz = await (await getSyncHandle(fh,'xFileSize')).getSize();
657
+ state.s11n.serialize(Number(sz));
658
+ }catch(e){
659
+ state.s11n.storeException(1,e);
660
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR);
661
+ }
662
+ await releaseImplicitLock(fh);
663
+ storeAndNotify('xFileSize', rc);
664
+ },
665
+ /**
666
+ The first argument is semantically invalid here - it's an
667
+ address in the synchronous side's heap. We can do nothing with
668
+ it here except use it as a unique-per-file identifier.
669
+ i.e. a lookup key.
670
+ */
671
+ xOpen: async function(fid/*sqlite3_file pointer*/, filename,
672
+ flags/*SQLITE_OPEN_...*/,
673
+ opfsFlags/*OPFS_...*/){
674
+ const opName = 'xOpen';
675
+ const create = (state.sq3Codes.SQLITE_OPEN_CREATE & flags);
676
+ try{
677
+ let hDir, filenamePart;
678
+ try {
679
+ [hDir, filenamePart] = await getDirForFilename(filename, !!create);
680
+ }catch(e){
681
+ state.s11n.storeException(1,e);
682
+ storeAndNotify(opName, state.sq3Codes.SQLITE_NOTFOUND);
683
+ return;
684
+ }
685
+ if( state.opfsFlags.OPFS_UNLINK_BEFORE_OPEN & opfsFlags ){
686
+ try{
687
+ await hDir.removeEntry(filenamePart);
688
+ }catch(e){
689
+ /* ignoring */
690
+ //warn("Ignoring failed Unlink of",filename,":",e);
691
+ }
692
+ }
693
+ const hFile = await hDir.getFileHandle(filenamePart, {create});
694
+ const fh = Object.assign(Object.create(null),{
695
+ fid: fid,
696
+ filenameAbs: filename,
697
+ filenamePart: filenamePart,
698
+ dirHandle: hDir,
699
+ fileHandle: hFile,
700
+ sabView: state.sabFileBufView,
701
+ readOnly: !create && !!(state.sq3Codes.SQLITE_OPEN_READONLY & flags),
702
+ deleteOnClose: !!(state.sq3Codes.SQLITE_OPEN_DELETEONCLOSE & flags)
703
+ });
704
+ fh.releaseImplicitLocks =
705
+ (opfsFlags & state.opfsFlags.OPFS_UNLOCK_ASAP)
706
+ || state.opfsFlags.defaultUnlockAsap;
707
+ __openFiles[fid] = fh;
708
+ storeAndNotify(opName, 0);
709
+ }catch(e){
710
+ error(opName,e);
711
+ state.s11n.storeException(1,e);
712
+ storeAndNotify(opName, state.sq3Codes.SQLITE_IOERR);
713
+ }
714
+ },
715
+ xRead: async function(fid/*sqlite3_file pointer*/,n,offset64){
716
+ let rc = 0, nRead;
717
+ const fh = __openFiles[fid];
718
+ try{
719
+ nRead = (await getSyncHandle(fh,'xRead')).read(
720
+ fh.sabView.subarray(0, n),
721
+ {at: Number(offset64)}
722
+ );
723
+ if(nRead < n){/* Zero-fill remaining bytes */
724
+ fh.sabView.fill(0, nRead, n);
725
+ rc = state.sq3Codes.SQLITE_IOERR_SHORT_READ;
726
+ }
727
+ }catch(e){
728
+ //error("xRead() failed",e,fh);
729
+ state.s11n.storeException(1,e);
730
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_READ);
731
+ }
732
+ await releaseImplicitLock(fh);
733
+ storeAndNotify('xRead',rc);
734
+ },
735
+ xSync: async function(fid/*sqlite3_file pointer*/,flags/*ignored*/){
736
+ const fh = __openFiles[fid];
737
+ let rc = 0;
738
+ if(!fh.readOnly && fh.syncHandle){
739
+ try {
740
+ await fh.syncHandle.flush();
741
+ }catch(e){
742
+ state.s11n.storeException(2,e);
743
+ rc = state.sq3Codes.SQLITE_IOERR_FSYNC;
744
+ }
745
+ }
746
+ storeAndNotify('xSync',rc);
747
+ },
748
+ xTruncate: async function(fid/*sqlite3_file pointer*/,size){
749
+ let rc = 0;
750
+ const fh = __openFiles[fid];
751
+ try{
752
+ affirmNotRO('xTruncate', fh);
753
+ await (await getSyncHandle(fh,'xTruncate')).truncate(size);
754
+ }catch(e){
755
+ //error("xTruncate():",e,fh);
756
+ state.s11n.storeException(2,e);
757
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_TRUNCATE);
758
+ }
759
+ await releaseImplicitLock(fh);
760
+ storeAndNotify('xTruncate',rc);
761
+ },
762
+ xWrite: async function(fid/*sqlite3_file pointer*/,n,offset64){
763
+ let rc;
764
+ const fh = __openFiles[fid];
765
+ try{
766
+ affirmNotRO('xWrite', fh);
767
+ rc = (
768
+ n === (await getSyncHandle(fh,'xWrite'))
769
+ .write(fh.sabView.subarray(0, n),
770
+ {at: Number(offset64)})
771
+ ) ? 0 : state.sq3Codes.SQLITE_IOERR_WRITE;
772
+ }catch(e){
773
+ //error("xWrite():",e,fh);
774
+ state.s11n.storeException(1,e);
775
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_WRITE);
776
+ }
777
+ await releaseImplicitLock(fh);
778
+ storeAndNotify('xWrite',rc);
779
+ }
780
+ }/*vfsAsyncImpls*/;
781
+
782
+ if( isWebLocker ){
783
+ /* We require separate xLock() and xUnlock() implementations for the
784
+ original and Web Lock implementations. The ones in this block
785
+ are for the WebLock impl.
786
+
787
+ The Golden Rule for this impl is: if we have a web lock, we
788
+ must also hold the SAH. When "upgrading" an implicit lock to a
789
+ requested (explicit) lock, we must remove the SAH from the
790
+ __implicitLocks set. When we unlock, we release both the web
791
+ lock and the SAH. That invariant must be kept intact or race
792
+ conditions on SAHs will ensue.
793
+ */
794
+ /** Registry of active Web Locks: fid -> { mode, resolveRelease } */
795
+ const __activeWebLocks = Object.create(null);
796
+
797
+ vfsAsyncImpls.xLock = async function(fid/*sqlite3_file pointer*/,
798
+ lockType/*SQLITE_LOCK_...*/,
799
+ isFromUnlock/*only if called from this.xUnlock()*/){
800
+ const whichOp = isFromUnlock ? 'xUnlock' : 'xLock';
801
+ const fh = __openFiles[fid];
802
+ //error("xLock()",fid, lockType, isFromUnlock, fh);
803
+ const requestedMode = (lockType >= state.sq3Codes.SQLITE_LOCK_RESERVED)
804
+ ? 'exclusive' : 'shared';
805
+ const existing = __activeWebLocks[fid];
806
+ if( existing ){
807
+ if( existing.mode === requestedMode
808
+ || (existing.mode === 'exclusive'
809
+ && requestedMode === 'shared') ) {
810
+ fh.xLock = lockType;
811
+ storeAndNotify(whichOp, 0);
812
+ /* Don't do this: existing.mode = requestedMode;
813
+
814
+ Paraphrased from advice given by a consulting developer:
815
+
816
+ If you hold an exclusive lock and SQLite requests shared,
817
+ you should keep exiting.mode as exclusive in because the
818
+ underlying Web Lock is still exclusive. Changing it to
819
+ shared would trick xLock into thinking it needs to
820
+ perform a release/re-acquire dance if an exclusive is
821
+ later requested.
822
+ */
823
+ return 0 /* Already held at required or higher level */;
824
+ }
825
+ /*
826
+ Upgrade path: we must release shared and acquire exclusive.
827
+ This transition is NOT atomic in Web Locks API.
828
+
829
+ It _effectively_ is atomic if we don't call
830
+ closeSyncHandle(fh), as no other worker can lock that until
831
+ we let it go. But we can't do that without eventually
832
+ leading to deadly embrace situations, so we don't do that.
833
+ (That's not a hypothetical, it has happened.)
834
+ */
835
+ await closeSyncHandle(fh);
836
+ existing.resolveRelease();
837
+ delete __activeWebLocks[fid];
838
+ }
839
+
840
+ const lockName = "sqlite3-vfs-opfs:" + fh.filenameAbs;
841
+ const oldLockType = fh.xLock;
842
+ return new Promise((resolveWaitLoop) => {
843
+ //log("xLock() initial promise entered...");
844
+ navigator.locks.request(lockName, { mode: requestedMode }, async (lock) => {
845
+ //log("xLock() Web Lock entered.", fh);
846
+ __implicitLocks.delete(fid);
847
+ let rc = 0;
848
+ try{
849
+ fh.xLock = lockType/*must be set before getSyncHandle() is called!*/;
850
+ await getSyncHandle(fh, 'xLock', state.asyncIdleWaitTime, 5);
851
+ }catch(e){
852
+ fh.xLock = oldLockType;
853
+ state.s11n.storeException(1, e);
854
+ rc = GetSyncHandleError.convertRc(e, state.sq3Codes.SQLITE_BUSY);
855
+ }
856
+ const releasePromise = rc
857
+ ? undefined
858
+ : new Promise((resolveRelease) => {
859
+ __activeWebLocks[fid] = { mode: requestedMode, resolveRelease };
860
+ });
861
+ storeAndNotify(whichOp, rc) /* unblock the C side */;
862
+ resolveWaitLoop(0) /* unblock waitLoop() */;
863
+ await releasePromise /* hold the lock until xUnlock */;
864
+ });
865
+ });
866
+ };
867
+
868
+ /** Internal helper for the opfs-wl xUnlock() */
869
+ const wlCloseHandle = async(fh)=>{
870
+ let rc = 0;
871
+ try{
872
+ /* For the record, we've never once seen closeSyncHandle()
873
+ throw, nor should it because destructors do not throw. */
874
+ await closeSyncHandle(fh);
875
+ }catch(e){
876
+ state.s11n.storeException(1,e);
877
+ rc = state.sq3Codes.SQLITE_IOERR_UNLOCK;
878
+ }
879
+ return rc;
880
+ };
881
+
882
+ vfsAsyncImpls.xUnlock = async function(fid/*sqlite3_file pointer*/,
883
+ lockType/*SQLITE_LOCK_...*/){
884
+ const fh = __openFiles[fid];
885
+ const existing = __activeWebLocks[fid];
886
+ if( !existing ){
887
+ const rc = await wlCloseHandle(fh);
888
+ storeAndNotify('xUnlock', rc);
889
+ return rc;
890
+ }
891
+ //log("xUnlock()",fid, lockType, fh);
892
+ let rc = 0;
893
+ if( lockType === state.sq3Codes.SQLITE_LOCK_NONE ){
894
+ /* SQLite usually unlocks all the way to NONE */
895
+ rc = await wlCloseHandle(fh);
896
+ existing.resolveRelease();
897
+ delete __activeWebLocks[fid];
898
+ fh.xLock = lockType;
899
+ }else if( lockType === state.sq3Codes.SQLITE_LOCK_SHARED
900
+ && existing.mode === 'exclusive' ){
901
+ /* downgrade EXCLUSIVE -> SHARED */
902
+ rc = await wlCloseHandle(fh);
903
+ if( 0===rc ){
904
+ fh.xLock = lockType;
905
+ existing.resolveRelease();
906
+ delete __activeWebLocks[fid];
907
+ return vfsAsyncImpls.xLock(fid, lockType, true);
908
+ }
909
+ }else{
910
+ /* ??? */
911
+ error("xUnlock() unhandled condition", fh);
912
+ }
913
+ storeAndNotify('xUnlock', rc);
914
+ return 0;
915
+ }
916
+
917
+ }else{
918
+ /* Original/"legacy" xLock() and xUnlock() */
919
+
920
+ vfsAsyncImpls.xLock = async function(fid/*sqlite3_file pointer*/,
921
+ lockType/*SQLITE_LOCK_...*/){
922
+ const fh = __openFiles[fid];
923
+ let rc = 0;
924
+ const oldLockType = fh.xLock;
925
+ fh.xLock = lockType;
926
+ if( !fh.syncHandle ){
927
+ try {
928
+ await getSyncHandle(fh,'xLock');
929
+ __implicitLocks.delete(fid);
930
+ }catch(e){
931
+ state.s11n.storeException(1,e);
932
+ rc = GetSyncHandleError.convertRc(e,state.sq3Codes.SQLITE_IOERR_LOCK);
933
+ fh.xLock = oldLockType;
934
+ }
935
+ }
936
+ storeAndNotify('xLock',rc);
937
+ };
938
+
939
+ vfsAsyncImpls.xUnlock = async function(fid/*sqlite3_file pointer*/,
940
+ lockType/*SQLITE_LOCK_...*/){
941
+ let rc = 0;
942
+ const fh = __openFiles[fid];
943
+ if( fh.syncHandle
944
+ && state.sq3Codes.SQLITE_LOCK_NONE===lockType
945
+ /* Note that we do not differentiate between lock types in
946
+ this VFS. We're either locked or unlocked. */ ){
947
+ try { await closeSyncHandle(fh) }
948
+ catch(e){
949
+ state.s11n.storeException(1,e);
950
+ rc = state.sq3Codes.SQLITE_IOERR_UNLOCK;
951
+ }
952
+ }
953
+ storeAndNotify('xUnlock',rc);
954
+ }
955
+
956
+ }/*xLock() and xUnlock() impls*/
957
+
958
+ const waitLoop = async function f(){
959
+ if( !f.inited ){
960
+ f.inited = true;
961
+ f.opHandlers = Object.create(null);
962
+ for(let k of Object.keys(state.opIds)){
963
+ const vi = vfsAsyncImpls[k];
964
+ if(!vi) continue;
965
+ const o = Object.create(null);
966
+ f.opHandlers[state.opIds[k]] = o;
967
+ o.key = k;
968
+ o.f = vi;
969
+ }
970
+ }
971
+ const opIds = state.opIds;
972
+ const opView = state.sabOPView;
973
+ const slotWhichOp = opIds.whichOp;
974
+ const idleWaitTime = state.asyncIdleWaitTime;
975
+ const hasWaitAsync = !!Atomics.waitAsync;
976
+ while(!flagAsyncShutdown){
977
+ try {
978
+ let opId;
979
+ if( hasWaitAsync ){
980
+ opId = Atomics.load(opView, slotWhichOp);
981
+ if( 0===opId ){
982
+ const rv = Atomics.waitAsync(opView, slotWhichOp, 0,
983
+ idleWaitTime);
984
+ if( rv.async ) await rv.value;
985
+ await releaseImplicitLocks();
986
+ continue;
987
+ }
988
+ }else{
989
+ /**
990
+ For browsers without Atomics.waitAsync(), we require
991
+ the legacy implementation. Browser versions where
992
+ waitAsync() arrived:
993
+
994
+ Chrome: 90 (2021-04-13)
995
+ Firefox: 145 (2025-11-11)
996
+ Safari: 16.4 (2023-03-27)
997
+
998
+ The "opfs" VFS was not born until Chrome was somewhere in
999
+ the v104-108 range (Summer/Autumn 2022) and did not work
1000
+ with Safari < v17 (2023-09-18) due to a WebKit bug which
1001
+ restricted OPFS access from sub-Workers.
1002
+
1003
+ The waitAsync() counterpart of this block can be used by
1004
+ both "opfs" and "opfs-wl", whereas this block can only be
1005
+ used by "opfs". Performance comparisons between the two
1006
+ in high-contention tests have been indecisive.
1007
+ */
1008
+ if('not-equal'!==Atomics.wait(
1009
+ state.sabOPView, slotWhichOp, 0, state.asyncIdleWaitTime
1010
+ )){
1011
+ /* Maintenance note: we compare against 'not-equal' because
1012
+
1013
+ https://github.com/tomayac/sqlite-wasm/issues/12
1014
+
1015
+ is reporting that this occasionally, under high loads,
1016
+ returns 'ok', which leads to the whichOp being 0 (which
1017
+ isn't a valid operation ID and leads to an exception,
1018
+ along with a corresponding ugly console log
1019
+ message). Unfortunately, the conditions for that cannot
1020
+ be reliably reproduced. The only place in our code which
1021
+ writes a 0 to the state.opIds.whichOp SharedArrayBuffer
1022
+ index is a few lines down from here, and that instance
1023
+ is required in order for clear communication between
1024
+ the sync half of this proxy and this half.
1025
+
1026
+ Much later (2026-03-07): that phenomenon is apparently
1027
+ called a spurious wakeup.
1028
+ */
1029
+ await releaseImplicitLocks();
1030
+ continue;
1031
+ }
1032
+ opId = Atomics.load(state.sabOPView, slotWhichOp);
1033
+ }
1034
+ Atomics.store(opView, slotWhichOp, 0);
1035
+ const hnd = f.opHandlers[opId]?.f ?? toss("No waitLoop handler for whichOp #",opId);
1036
+ const args = state.s11n.deserialize(
1037
+ true /* clear s11n to keep the caller from confusing this with
1038
+ an exception string written by the upcoming
1039
+ operation */
1040
+ ) || [];
1041
+ //error("waitLoop() whichOp =",opId, f.opHandlers[opId].key, args);
1042
+ await hnd(...args);
1043
+ }catch(e){
1044
+ error('in waitLoop():', e);
1045
+ }
1046
+ }
1047
+ };
1048
+
1049
+ navigator.storage.getDirectory().then(function(d){
1050
+ state.rootDir = d;
1051
+ globalThis.onmessage = function({data}){
1052
+ //log(globalThis.location.href,"onmessage()",data);
1053
+ switch(data.type){
1054
+ case 'opfs-async-init':{
1055
+ /* Receive shared state from synchronous partner */
1056
+ const opt = data.args;
1057
+ for(const k in opt) state[k] = opt[k];
1058
+ state.verbose = opt.verbose ?? 1;
1059
+ state.sabOPView = new Int32Array(state.sabOP);
1060
+ state.sabFileBufView = new Uint8Array(state.sabIO, 0, state.fileBufferSize);
1061
+ state.sabS11nView = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize);
1062
+ Object.keys(vfsAsyncImpls).forEach((k)=>{
1063
+ if(!Number.isFinite(state.opIds[k])){
1064
+ toss("Maintenance required: missing state.opIds[",k,"]");
1065
+ }
1066
+ });
1067
+ initS11n();
1068
+ //warn("verbosity =",opt.verbose, state.verbose);
1069
+ log("init state",state);
1070
+ wPost('opfs-async-inited');
1071
+ waitLoop();
1072
+ break;
1073
+ }
1074
+ case 'opfs-async-restart':
1075
+ if(flagAsyncShutdown){
1076
+ warn("Restarting after opfs-async-shutdown. Might or might not work.");
1077
+ flagAsyncShutdown = false;
1078
+ waitLoop();
1079
+ }
1080
+ break;
1081
+ }
1082
+ };
1083
+ wPost('opfs-async-loaded');
1084
+ }).catch((e)=>error("error initializing OPFS asyncer:",e));
1085
+ }/*installAsyncProxy()*/;
1086
+ if(globalThis.window === globalThis){
1087
+ wPost('opfs-unavailable',
1088
+ "This code cannot run from the main thread.",
1089
+ "Load it as a Worker from a separate Worker.");
1090
+ }else if(!globalThis.SharedArrayBuffer){
1091
+ wPost('opfs-unavailable', "Missing SharedArrayBuffer API.",
1092
+ "The server must emit the COOP/COEP response headers to enable that.");
1093
+ }else if(!globalThis.Atomics){
1094
+ wPost('opfs-unavailable', "Missing Atomics API.",
1095
+ "The server must emit the COOP/COEP response headers to enable that.");
1096
+ }else if(isWebLocker && !globalThis.Atomics.waitAsync){
1097
+ wPost('opfs-unavailable',"Missing required Atomics.waitSync() for "+vfsName);
1098
+ }else if(!globalThis.FileSystemHandle ||
1099
+ !globalThis.FileSystemDirectoryHandle ||
1100
+ !globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle ||
1101
+ !navigator?.storage?.getDirectory){
1102
+ wPost('opfs-unavailable',"Missing required OPFS APIs.");
1103
+ }else{
1104
+ installAsyncProxy();
1105
+ }