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