sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / wasm / api / opfs-common-shared.c-pp.js
| 1 | //#if not target:node and (not omit-opfs or not omit-opfs-wl) |
| 2 | /* |
| 3 | 2026-03-04 |
| 4 | |
| 5 | The author disclaims copyright to this source code. In place of a |
| 6 | legal notice, here is a blessing: |
| 7 | |
| 8 | * May you do good and not evil. |
| 9 | * May you find forgiveness for yourself and forgive others. |
| 10 | * May you share freely, never taking more than you give. |
| 11 | |
| 12 | *********************************************************************** |
| 13 | |
| 14 | This file holds code shared by sqlite3-vfs-opfs{,-wl}.c-pp.js. It |
| 15 | creates a private/internal sqlite3.opfs namespace common to the two |
| 16 | and used (only) by them and the test framework. It is not part of |
| 17 | the public API. The library deletes sqlite3.opfs in its final |
| 18 | bootstrapping steps unless it's specifically told to keep them (for |
| 19 | testing purposes only) using an undocumented and unsupported |
| 20 | mechanism. |
| 21 | */ |
| 22 | sqlite3ApiBootstrap.initializers.push(function(sqlite3){ |
| 23 | 'use strict'; |
| 24 | if( sqlite3.config.disable?.vfs?.opfs && |
| 25 | sqlite3.config.disable.vfs['opfs-vfs'] ){ |
| 26 | return; |
| 27 | } |
| 28 | const toss = sqlite3.util.toss, |
| 29 | capi = sqlite3.capi, |
| 30 | util = sqlite3.util, |
| 31 | wasm = sqlite3.wasm; |
| 32 | |
| 33 | /** |
| 34 | Generic utilities for working with OPFS. This will get filled out |
| 35 | by the Promise setup and, on success, installed as sqlite3.opfs. |
| 36 | |
| 37 | This is an internal/private namespace intended for use solely by |
| 38 | the OPFS VFSes and test code for them. The library bootstrapping |
| 39 | process removes this object in non-testing contexts. |
| 40 | */ |
| 41 | const opfsUtil = sqlite3.opfs = Object.create(null); |
| 42 | |
| 43 | /** |
| 44 | Returns true if _this_ thread has access to the OPFS APIs. |
| 45 | */ |
| 46 | opfsUtil.thisThreadHasOPFS = ()=>{ |
| 47 | return globalThis.FileSystemHandle && |
| 48 | globalThis.FileSystemDirectoryHandle && |
| 49 | globalThis.FileSystemFileHandle && |
| 50 | globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle && |
| 51 | navigator?.storage?.getDirectory; |
| 52 | }; |
| 53 | |
| 54 | /** |
| 55 | Must be called by the OPFS VFSes immediately after they determine |
| 56 | whether OPFS is available by calling |
| 57 | thisThreadHasOPFS(). Resolves to the OPFS storage root directory |
| 58 | and sets opfsUtil.rootDirectory to that value. |
| 59 | */ |
| 60 | opfsUtil.getRootDir = async function f(){ |
| 61 | return f.promise ??= navigator.storage.getDirectory().then(d=>{ |
| 62 | opfsUtil.rootDirectory = d; |
| 63 | return d; |
| 64 | }).catch(e=>{ |
| 65 | delete f.promise; |
| 66 | throw e; |
| 67 | }); |
| 68 | }; |
| 69 | |
| 70 | /** |
| 71 | Expects an OPFS file path. It gets resolved, such that ".." |
| 72 | components are properly expanded, and returned. If the 2nd arg |
| 73 | is true, the result is returned as an array of path elements, |
| 74 | else an absolute path string is returned. |
| 75 | */ |
| 76 | opfsUtil.getResolvedPath = function(filename,splitIt){ |
| 77 | const p = new URL(filename, "file://irrelevant").pathname; |
| 78 | return splitIt ? p.split('/').filter((v)=>!!v) : p; |
| 79 | }; |
| 80 | |
| 81 | /** |
| 82 | Takes the absolute path to a filesystem element. Returns an |
| 83 | array of [handleOfContainingDir, filename]. If the 2nd argument |
| 84 | is truthy then each directory element leading to the file is |
| 85 | created along the way. Throws if any creation or resolution |
| 86 | fails. |
| 87 | */ |
| 88 | opfsUtil.getDirForFilename = async function f(absFilename, createDirs = false){ |
| 89 | const path = opfsUtil.getResolvedPath(absFilename, true); |
| 90 | const filename = path.pop(); |
| 91 | let dh = await opfsUtil.getRootDir(); |
| 92 | for(const dirName of path){ |
| 93 | if(dirName){ |
| 94 | dh = await dh.getDirectoryHandle(dirName, {create: !!createDirs}); |
| 95 | } |
| 96 | } |
| 97 | return [dh, filename]; |
| 98 | }; |
| 99 | |
| 100 | /** |
| 101 | Creates the given directory name, recursively, in |
| 102 | the OPFS filesystem. Returns true if it succeeds or the |
| 103 | directory already exists, else false. |
| 104 | */ |
| 105 | opfsUtil.mkdir = async function(absDirName){ |
| 106 | try { |
| 107 | await opfsUtil.getDirForFilename(absDirName+"/filepart", true); |
| 108 | return true; |
| 109 | }catch(e){ |
| 110 | //sqlite3.config.warn("mkdir(",absDirName,") failed:",e); |
| 111 | return false; |
| 112 | } |
| 113 | }; |
| 114 | |
| 115 | /** |
| 116 | Checks whether the given OPFS filesystem entry exists, |
| 117 | returning true if it does, false if it doesn't or if an |
| 118 | exception is intercepted while trying to make the |
| 119 | determination. |
| 120 | */ |
| 121 | opfsUtil.entryExists = async function(fsEntryName){ |
| 122 | try { |
| 123 | const [dh, fn] = await opfsUtil.getDirForFilename(fsEntryName); |
| 124 | await dh.getFileHandle(fn); |
| 125 | return true; |
| 126 | }catch(e){ |
| 127 | return false; |
| 128 | } |
| 129 | }; |
| 130 | |
| 131 | /** |
| 132 | Generates a random ASCII string len characters long, intended for |
| 133 | use as a temporary file name. |
| 134 | */ |
| 135 | opfsUtil.randomFilename = function f(len=16){ |
| 136 | if(!f._chars){ |
| 137 | f._chars = "abcdefghijklmnopqrstuvwxyz"+ |
| 138 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ |
| 139 | "012346789"; |
| 140 | f._n = f._chars.length; |
| 141 | } |
| 142 | const a = []; |
| 143 | let i = 0; |
| 144 | for( ; i < len; ++i){ |
| 145 | const ndx = Math.random() * (f._n * 64) % f._n | 0; |
| 146 | a[i] = f._chars[ndx]; |
| 147 | } |
| 148 | return a.join(""); |
| 149 | /* |
| 150 | An alternative impl. with an unpredictable length |
| 151 | but much simpler: |
| 152 | |
| 153 | Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36) |
| 154 | */ |
| 155 | }; |
| 156 | |
| 157 | /** |
| 158 | Returns a promise which resolves to an object which represents |
| 159 | all files and directories in the OPFS tree. The top-most object |
| 160 | has two properties: `dirs` is an array of directory entries |
| 161 | (described below) and `files` is a list of file names for all |
| 162 | files in that directory. |
| 163 | |
| 164 | Traversal starts at sqlite3.opfs.rootDirectory. |
| 165 | |
| 166 | Each `dirs` entry is an object in this form: |
| 167 | |
| 168 | ``` |
| 169 | { name: directoryName, |
| 170 | dirs: [...subdirs], |
| 171 | files: [...file names] |
| 172 | } |
| 173 | ``` |
| 174 | |
| 175 | The `files` and `subdirs` entries are always set but may be |
| 176 | empty arrays. |
| 177 | |
| 178 | The returned object has the same structure but its `name` is |
| 179 | an empty string. All returned objects are created with |
| 180 | Object.create(null), so have no prototype. |
| 181 | |
| 182 | Design note: the entries do not contain more information, |
| 183 | e.g. file sizes, because getting such info is not only |
| 184 | expensive but is subject to locking-related errors. |
| 185 | */ |
| 186 | opfsUtil.treeList = async function(){ |
| 187 | const doDir = async function callee(dirHandle,tgt){ |
| 188 | tgt.name = dirHandle.name; |
| 189 | tgt.dirs = []; |
| 190 | tgt.files = []; |
| 191 | for await (const handle of dirHandle.values()){ |
| 192 | if('directory' === handle.kind){ |
| 193 | const subDir = Object.create(null); |
| 194 | tgt.dirs.push(subDir); |
| 195 | await callee(handle, subDir); |
| 196 | }else{ |
| 197 | tgt.files.push(handle.name); |
| 198 | } |
| 199 | } |
| 200 | }; |
| 201 | const root = Object.create(null); |
| 202 | const dir = await opfsUtil.getRootDir(); |
| 203 | await doDir(dir, root); |
| 204 | return root; |
| 205 | }; |
| 206 | |
| 207 | /** |
| 208 | Irrevocably deletes _all_ files in the current origin's OPFS. |
| 209 | Obviously, this must be used with great caution. It may throw |
| 210 | an exception if removal of anything fails (e.g. a file is |
| 211 | locked), but the precise conditions under which the underlying |
| 212 | APIs will throw are not documented (so we cannot tell you what |
| 213 | they are). |
| 214 | */ |
| 215 | opfsUtil.rmfr = async function(){ |
| 216 | const rd = await opfsUtil.getRootDir(); |
| 217 | const dir = rd, opt = {recurse: true}; |
| 218 | for await (const handle of dir.values()){ |
| 219 | dir.removeEntry(handle.name, opt); |
| 220 | } |
| 221 | }; |
| 222 | |
| 223 | /** |
| 224 | Deletes the given OPFS filesystem entry. As this environment |
| 225 | has no notion of "current directory", the given name must be an |
| 226 | absolute path. If the 2nd argument is truthy, deletion is |
| 227 | recursive (use with caution!). |
| 228 | |
| 229 | The returned Promise resolves to true if the deletion was |
| 230 | successful, else false (but...). The OPFS API reports the |
| 231 | reason for the failure only in human-readable form, not |
| 232 | exceptions which can be type-checked to determine the |
| 233 | failure. Because of that... |
| 234 | |
| 235 | If the final argument is truthy then this function will |
| 236 | propagate any exception on error, rather than returning false. |
| 237 | */ |
| 238 | opfsUtil.unlink = async function(fsEntryName, recursive = false, |
| 239 | throwOnError = false){ |
| 240 | try { |
| 241 | const [hDir, filenamePart] = |
| 242 | await opfsUtil.getDirForFilename(fsEntryName, false); |
| 243 | await hDir.removeEntry(filenamePart, {recursive}); |
| 244 | return true; |
| 245 | }catch(e){ |
| 246 | if(throwOnError){ |
| 247 | throw new Error("unlink(",arguments[0],") failed: "+e.message,{ |
| 248 | cause: e |
| 249 | }); |
| 250 | } |
| 251 | return false; |
| 252 | } |
| 253 | }; |
| 254 | |
| 255 | /** |
| 256 | Traverses the OPFS filesystem, calling a callback for each |
| 257 | entry. The argument may be either a callback function or an |
| 258 | options object with any of the following properties: |
| 259 | |
| 260 | - `callback`: function which gets called for each filesystem |
| 261 | entry. It gets passed 3 arguments: 1) the |
| 262 | FileSystemFileHandle or FileSystemDirectoryHandle of each |
| 263 | entry (noting that both are instanceof FileSystemHandle). 2) |
| 264 | the FileSystemDirectoryHandle of the parent directory. 3) the |
| 265 | current depth level, with 0 being at the top of the tree |
| 266 | relative to the starting directory. If the callback returns a |
| 267 | literal false, as opposed to any other falsy value, traversal |
| 268 | stops without an error. Any exceptions it throws are |
| 269 | propagated. Results are undefined if the callback manipulate |
| 270 | the filesystem (e.g. removing or adding entries) because the |
| 271 | how OPFS iterators behave in the face of such changes is |
| 272 | undocumented. |
| 273 | |
| 274 | - `recursive` [bool=true]: specifies whether to recurse into |
| 275 | subdirectories or not. Whether recursion is depth-first or |
| 276 | breadth-first is unspecified! |
| 277 | |
| 278 | - `directory` [FileSystemDirectoryEntry=sqlite3.opfs.rootDirectory] |
| 279 | specifies the starting directory. |
| 280 | |
| 281 | If this function is passed a function, it is assumed to be the |
| 282 | callback. |
| 283 | |
| 284 | Returns a promise because it has to (by virtue of being async) |
| 285 | but that promise has no specific meaning: the traversal it |
| 286 | performs is synchronous. The promise must be used to catch any |
| 287 | exceptions propagated by the callback, however. |
| 288 | */ |
| 289 | opfsUtil.traverse = async function(opt){ |
| 290 | const defaultOpt = { |
| 291 | recursive: true, |
| 292 | directory: await opfsUtil.getRootDir() |
| 293 | }; |
| 294 | if('function'===typeof opt){ |
| 295 | opt = {callback:opt}; |
| 296 | } |
| 297 | opt = Object.assign(defaultOpt, opt||{}); |
| 298 | const doDir = async function callee(dirHandle, depth){ |
| 299 | for await (const handle of dirHandle.values()){ |
| 300 | if(false === opt.callback(handle, dirHandle, depth)) return false; |
| 301 | else if(opt.recursive && 'directory' === handle.kind){ |
| 302 | if(false === await callee(handle, depth + 1)) break; |
| 303 | } |
| 304 | } |
| 305 | }; |
| 306 | doDir(opt.directory, 0); |
| 307 | }; |
| 308 | |
| 309 | /** |
| 310 | Impl of opfsUtil.importDb() when it's given a function as its |
| 311 | second argument. |
| 312 | */ |
| 313 | const importDbChunked = async function(filename, callback){ |
| 314 | const [hDir, fnamePart] = await opfsUtil.getDirForFilename(filename, true); |
| 315 | const hFile = await hDir.getFileHandle(fnamePart, {create:true}); |
| 316 | let sah = await hFile.createSyncAccessHandle(); |
| 317 | let nWrote = 0, chunk, checkedHeader = false, err = false; |
| 318 | try{ |
| 319 | sah.truncate(0); |
| 320 | while( undefined !== (chunk = await callback()) ){ |
| 321 | if(chunk instanceof ArrayBuffer) chunk = new Uint8Array(chunk); |
| 322 | if( !checkedHeader && 0===nWrote && chunk.byteLength>=15 ){ |
| 323 | util.affirmDbHeader(chunk); |
| 324 | checkedHeader = true; |
| 325 | } |
| 326 | sah.write(chunk, {at: nWrote}); |
| 327 | nWrote += chunk.byteLength; |
| 328 | } |
| 329 | if( nWrote < 512 || 0!==nWrote % 512 ){ |
| 330 | toss("Input size",nWrote,"is not correct for an SQLite database."); |
| 331 | } |
| 332 | if( !checkedHeader ){ |
| 333 | const header = new Uint8Array(20); |
| 334 | sah.read( header, {at: 0} ); |
| 335 | util.affirmDbHeader( header ); |
| 336 | } |
| 337 | sah.write(new Uint8Array([1,1]), {at: 18}/*force db out of WAL mode*/); |
| 338 | return nWrote; |
| 339 | }catch(e){ |
| 340 | await sah.close(); |
| 341 | sah = undefined; |
| 342 | await hDir.removeEntry( fnamePart ).catch(()=>{}); |
| 343 | throw e; |
| 344 | }finally { |
| 345 | if( sah ) await sah.close(); |
| 346 | } |
| 347 | }; |
| 348 | |
| 349 | /** |
| 350 | Asynchronously imports the given bytes (a byte array or |
| 351 | ArrayBuffer) into the given database file. |
| 352 | |
| 353 | Results are undefined if the given db name refers to an opened |
| 354 | db. |
| 355 | |
| 356 | If passed a function for its second argument, its behaviour |
| 357 | changes: imports its data in chunks fed to it by the given |
| 358 | callback function. It calls the callback (which may be async) |
| 359 | repeatedly, expecting either a Uint8Array or ArrayBuffer (to |
| 360 | denote new input) or undefined (to denote EOF). For so long as |
| 361 | the callback continues to return non-undefined, it will append |
| 362 | incoming data to the given VFS-hosted database file. When |
| 363 | called this way, the resolved value of the returned Promise is |
| 364 | the number of bytes written to the target file. |
| 365 | |
| 366 | It very specifically requires the input to be an SQLite3 database |
| 367 | and throws if that's not the case. It does so in order to |
| 368 | prevent this function from taking on a larger scope than it is |
| 369 | specifically intended to. i.e. we do not want it to become a |
| 370 | convenience for importing arbitrary files into OPFS. Caveat: as |
| 371 | of 3.54 in SEE builds, the "is this a db?" check is necessarily |
| 372 | lax to account for SEE-encrypted databases not having a legible |
| 373 | header. In such builds, only the db size is relevant for the |
| 374 | check. |
| 375 | |
| 376 | This routine rewrites the database header bytes in the output |
| 377 | file (not the input array) to force disabling of WAL mode. |
| 378 | |
| 379 | On error this throws and the state of the input file is |
| 380 | undefined (it depends on where the exception was triggered). |
| 381 | |
| 382 | On success, resolves to the number of bytes written. |
| 383 | */ |
| 384 | opfsUtil.importDb = async function(filename, bytes){ |
| 385 | if( bytes instanceof Function ){ |
| 386 | return importDbChunked(filename, bytes); |
| 387 | } |
| 388 | if(bytes instanceof ArrayBuffer) bytes = new Uint8Array(bytes); |
| 389 | util.affirmIsDb(bytes); |
| 390 | const n = bytes.byteLength; |
| 391 | const [hDir, fnamePart] = await opfsUtil.getDirForFilename(filename, true); |
| 392 | let sah, err, nWrote = 0; |
| 393 | try { |
| 394 | const hFile = await hDir.getFileHandle(fnamePart, {create:true}); |
| 395 | sah = await hFile.createSyncAccessHandle(); |
| 396 | sah.truncate(0); |
| 397 | nWrote = sah.write(bytes, {at: 0}); |
| 398 | if(nWrote != n){ |
| 399 | toss("Expected to write "+n+" bytes but wrote "+nWrote+"."); |
| 400 | } |
| 401 | sah.write(new Uint8Array([1,1]), {at: 18}) /* force db out of WAL mode */; |
| 402 | return nWrote; |
| 403 | }catch(e){ |
| 404 | if( sah ){ await sah.close(); sah = undefined; } |
| 405 | await hDir.removeEntry( fnamePart ).catch(()=>{}); |
| 406 | throw e; |
| 407 | }finally{ |
| 408 | if( sah ) await sah.close(); |
| 409 | } |
| 410 | }; |
| 411 | |
| 412 | /** |
| 413 | Checks for features required for OPFS VFSes and throws with a |
| 414 | descriptive error message if they're not found. This is intended |
| 415 | to be run as part of async VFS installation steps. |
| 416 | */ |
| 417 | opfsUtil.vfsInstallationFeatureCheck = function(vfsName){ |
| 418 | if( !globalThis.SharedArrayBuffer || !globalThis.Atomics ){ |
| 419 | toss("Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics.", |
| 420 | "The server must emit the COOP/COEP response headers to enable those.", |
| 421 | "See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep"); |
| 422 | }else if( 'undefined'===typeof WorkerGlobalScope ){ |
| 423 | toss("The OPFS sqlite3_vfs cannot run in the main thread", |
| 424 | "because it requires Atomics.wait()."); |
| 425 | }else if( !globalThis.FileSystemHandle || |
| 426 | !globalThis.FileSystemDirectoryHandle || |
| 427 | !globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle || |
| 428 | !navigator?.storage?.getDirectory ){ |
| 429 | toss("Missing required OPFS APIs."); |
| 430 | }else if( 'opfs-wl'===vfsName && !globalThis.Atomics.waitAsync ){ |
| 431 | toss('The',vfsName,'VFS requires Atomics.waitAsync(), which is not available.'); |
| 432 | } |
| 433 | }; |
| 434 | |
| 435 | /** |
| 436 | Must be called by the VFS's main installation routine and passed |
| 437 | the options object that function receives and a reference to that |
| 438 | function itself (we don't need this anymore). |
| 439 | |
| 440 | It throws if OPFS is not available. |
| 441 | |
| 442 | If it returns falsy, it detected that OPFS should be disabled, in |
| 443 | which case the callee should immediately return/resolve to the |
| 444 | sqlite3 object. |
| 445 | |
| 446 | Else it returns a new copy of the options object, fleshed out |
| 447 | with any missing defaults. The caller must: |
| 448 | |
| 449 | - Set up any local state they need. |
| 450 | |
| 451 | - Call opfsUtil.createVfsState(vfsName,opt), where opt is the |
| 452 | object returned by this function. |
| 453 | |
| 454 | - Set up any references they may need to state returned |
| 455 | by the previous step. |
| 456 | |
| 457 | - Call opfvs.bindVfs() |
| 458 | */ |
| 459 | opfsUtil.initOptions = function callee(vfsName, options){ |
| 460 | const urlParams = new URL(globalThis.location.href).searchParams; |
| 461 | if( urlParams.has(vfsName+'-disable') ){ |
| 462 | //sqlite3.config.warn('Explicitly not installing "opfs" VFS due to opfs-disable flag.'); |
| 463 | return; |
| 464 | } |
| 465 | try{ |
| 466 | opfsUtil.vfsInstallationFeatureCheck(vfsName); |
| 467 | }catch(e){ |
| 468 | return; |
| 469 | } |
| 470 | options = util.nu(options); |
| 471 | options.vfsName = vfsName; |
| 472 | options.verbose ??= urlParams.has('opfs-verbose') |
| 473 | ? +urlParams.get('opfs-verbose') : 1; |
| 474 | options.sanityChecks ??= urlParams.has('opfs-sanity-check'); |
| 475 | |
| 476 | if( !opfsUtil.proxyUri ){ |
| 477 | opfsUtil.proxyUri = "sqlite3-opfs-async-proxy.js"; |
| 478 | if( sqlite3.scriptInfo?.sqlite3Dir ){ |
| 479 | /* Doing this from one scope up, outside of this function, does |
| 480 | not work. */ |
| 481 | opfsUtil.proxyUri = ( |
| 482 | sqlite3.scriptInfo.sqlite3Dir + opfsUtil.proxyUri |
| 483 | ); |
| 484 | } |
| 485 | } |
| 486 | options.proxyUri ??= opfsUtil.proxyUri; |
| 487 | if('function' === typeof options.proxyUri){ |
| 488 | options.proxyUri = options.proxyUri(); |
| 489 | } |
| 490 | //sqlite3.config.warn("opfsUtil options =",JSON.stringify(options), 'urlParams =', urlParams); |
| 491 | return opfsUtil.options = options; |
| 492 | }; |
| 493 | |
| 494 | /** |
| 495 | Creates, populates, and returns the main state object used by the |
| 496 | "opfs" and "opfs-wl" VFSes, and transfered from those to their |
| 497 | async counterparts. |
| 498 | |
| 499 | The returned object's vfs property holds the fully-populated |
| 500 | capi.sqlite3_vfs instance, tagged with lots of extra state which |
| 501 | the current VFSes need to have exposed to them. |
| 502 | |
| 503 | After setting up any local state needed, the caller must call |
| 504 | theVfs.bindVfs(X,Y), where X is an object containing the |
| 505 | sqlite3_io_methods to override and Y is a callback which gets |
| 506 | triggered if init succeeds, before the final Promise decides |
| 507 | whether or not to reject. |
| 508 | |
| 509 | This object must, when it's passed to the async part, contain |
| 510 | only cloneable or sharable objects. After the worker's "inited" |
| 511 | message arrives, other types of data may be added to it. |
| 512 | */ |
| 513 | opfsUtil.createVfsState = function(){ |
| 514 | const state = util.nu(); |
| 515 | const options = opfsUtil.options; |
| 516 | state.verbose = options.verbose; |
| 517 | |
| 518 | const loggers = [ |
| 519 | sqlite3.config.error, |
| 520 | sqlite3.config.warn, |
| 521 | sqlite3.config.log |
| 522 | ]; |
| 523 | const vfsName = options.vfsName |
| 524 | || toss("Maintenance required: missing VFS name"); |
| 525 | const logImpl = (level,...args)=>{ |
| 526 | if(state.verbose>level) loggers[level](vfsName+":",...args); |
| 527 | }; |
| 528 | const log = (...args)=>logImpl(2, ...args), |
| 529 | warn = (...args)=>logImpl(1, ...args), |
| 530 | error = (...args)=>logImpl(0, ...args), |
| 531 | capi = sqlite3.capi, |
| 532 | wasm = sqlite3.wasm; |
| 533 | |
| 534 | const opfsVfs = state.vfs = new capi.sqlite3_vfs(); |
| 535 | const opfsIoMethods = opfsVfs.ioMethods = new capi.sqlite3_io_methods(); |
| 536 | |
| 537 | opfsIoMethods.$iVersion = 1; |
| 538 | opfsVfs.$iVersion = 2/*yes, two*/; |
| 539 | opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof; |
| 540 | opfsVfs.$mxPathname = 1024/* sure, why not? The OPFS name length limit |
| 541 | is undocumented/unspecified. */; |
| 542 | opfsVfs.$zName = wasm.allocCString(vfsName); |
| 543 | opfsVfs.addOnDispose( |
| 544 | '$zName', opfsVfs.$zName, opfsIoMethods |
| 545 | /** |
| 546 | Pedantic sidebar: the entries in this array are items to |
| 547 | clean up when opfsVfs.dispose() is called, but in this |
| 548 | environment it will never be called. The VFS instance simply |
| 549 | hangs around until the WASM module instance is cleaned up. We |
| 550 | "could" _hypothetically_ clean it up by "importing" an |
| 551 | sqlite3_os_end() impl into the wasm build, but the shutdown |
| 552 | order of the wasm engine and the JS one are undefined so |
| 553 | there is no guaranty that the opfsVfs instance would be |
| 554 | available in one environment or the other when |
| 555 | sqlite3_os_end() is called (_if_ it gets called at all in a |
| 556 | wasm build, which is undefined). i.e. addOnDispose() here is |
| 557 | a matter of "correctness", not necessity. It just wouldn't do |
| 558 | to leave the impression that we're blindly leaking memory. |
| 559 | */ |
| 560 | ); |
| 561 | |
| 562 | opfsVfs.metrics = util.nu({ |
| 563 | counters: util.nu(), |
| 564 | dump: function(){ |
| 565 | let k, n = 0, t = 0, w = 0; |
| 566 | for(k in state.opIds){ |
| 567 | const m = metrics[k]; |
| 568 | n += m.count; |
| 569 | t += m.time; |
| 570 | w += m.wait; |
| 571 | m.avgTime = (m.count && m.time) ? (m.time / m.count) : 0; |
| 572 | m.avgWait = (m.count && m.wait) ? (m.wait / m.count) : 0; |
| 573 | } |
| 574 | sqlite3.config.log(globalThis.location.href, |
| 575 | "metrics for",globalThis.location.href,":",metrics, |
| 576 | "\nTotal of",n,"op(s) for",t, |
| 577 | "ms (incl. "+w+" ms of waiting on the async side)"); |
| 578 | sqlite3.config.log("Serialization metrics:",opfsVfs.metrics.counters.s11n); |
| 579 | opfsVfs.worker?.postMessage?.({type:'opfs-async-metrics'}); |
| 580 | }, |
| 581 | reset: function(){ |
| 582 | let k; |
| 583 | const r = (m)=>(m.count = m.time = m.wait = 0); |
| 584 | const m = opfsVfs.metrics.counters; |
| 585 | for(k in state.opIds){ |
| 586 | r(m[k] = Object.create(null)); |
| 587 | } |
| 588 | let s = m.s11n = Object.create(null); |
| 589 | s = s.serialize = Object.create(null); |
| 590 | s.count = s.time = 0; |
| 591 | s = m.s11n.deserialize = Object.create(null); |
| 592 | s.count = s.time = 0; |
| 593 | } |
| 594 | })/*opfsVfs.metrics*/; |
| 595 | |
| 596 | /** |
| 597 | asyncIdleWaitTime is how long (ms) to wait, in the async proxy, |
| 598 | for each Atomics.wait() when waiting on inbound VFS API calls. |
| 599 | We need to wake up periodically to give the thread a chance to |
| 600 | do other things. If this is too high (e.g. 500ms) then even two |
| 601 | workers/tabs can easily run into locking errors. Some multiple |
| 602 | of this value is also used for determining how long to wait on |
| 603 | lock contention to free up. |
| 604 | */ |
| 605 | state.asyncIdleWaitTime = 150; |
| 606 | |
| 607 | /** |
| 608 | Whether the async counterpart should log exceptions to |
| 609 | the serialization channel. That produces a great deal of |
| 610 | noise for seemingly innocuous things like xAccess() checks |
| 611 | for missing files, so this option may have one of 3 values: |
| 612 | |
| 613 | 0 = no exception logging. |
| 614 | |
| 615 | 1 = only log exceptions for "significant" ops like xOpen(), |
| 616 | xRead(), and xWrite(). Exceptions related to, e.g., wait/retry |
| 617 | loops in acquiring SyncAccessHandles are not logged. |
| 618 | |
| 619 | 2 = log all exceptions. |
| 620 | */ |
| 621 | state.asyncS11nExceptions = 1; |
| 622 | /* Size of file I/O buffer block. 64k = max sqlite3 page size, and |
| 623 | xRead/xWrite() will never deal in blocks larger than that. */ |
| 624 | state.fileBufferSize = 1024 * 64; |
| 625 | state.sabS11nOffset = state.fileBufferSize; |
| 626 | /** |
| 627 | The size of the block in our SAB for serializing arguments and |
| 628 | result values. Needs to be large enough to hold serialized |
| 629 | values of any of the proxied APIs. Filenames are the largest |
| 630 | part but are limited to opfsVfs.$mxPathname bytes. We also |
| 631 | store exceptions there, so it needs to be long enough to hold |
| 632 | a reasonably long exception string. |
| 633 | */ |
| 634 | state.sabS11nSize = opfsVfs.$mxPathname * 2; |
| 635 | /** |
| 636 | The SAB used for all data I/O between the synchronous and |
| 637 | async halves (file i/o and arg/result s11n). |
| 638 | */ |
| 639 | state.sabIO = new SharedArrayBuffer( |
| 640 | state.fileBufferSize/* file i/o block */ |
| 641 | + state.sabS11nSize/* argument/result serialization block */ |
| 642 | ); |
| 643 | |
| 644 | /** |
| 645 | For purposes of Atomics.wait() and Atomics.notify(), we use a |
| 646 | SharedArrayBuffer with one slot reserved for each of the API |
| 647 | proxy's methods. The sync side of the API uses Atomics.wait() |
| 648 | on the corresponding slot and the async side uses |
| 649 | Atomics.notify() on that slot. state.opIds holds the SAB slot |
| 650 | IDs of each of those. |
| 651 | */ |
| 652 | state.opIds = Object.create(null); |
| 653 | { |
| 654 | /* Indexes for use in our SharedArrayBuffer... */ |
| 655 | let i = 0; |
| 656 | /* SAB slot used to communicate which operation is desired |
| 657 | between both workers. This worker writes to it and the other |
| 658 | listens for changes and clears it. The values written to it |
| 659 | are state.opIds.x[A-Z][a-z]+, defined below.*/ |
| 660 | state.opIds.whichOp = i++; |
| 661 | /* Slot for storing return values. This side listens to that |
| 662 | slot and the async proxy writes to it. */ |
| 663 | state.opIds.rc = i++; |
| 664 | /* Each function gets an ID which this worker writes to the |
| 665 | state.opIds.whichOp slot. The async-api worker uses |
| 666 | Atomic.wait() on the whichOp slot to figure out which |
| 667 | operation to run next. */ |
| 668 | state.opIds.xAccess = i++; |
| 669 | state.opIds.xClose = i++; |
| 670 | state.opIds.xDelete = i++; |
| 671 | state.opIds.xDeleteNoWait = i++; |
| 672 | state.opIds.xFileSize = i++; |
| 673 | state.opIds.xLock = i++; |
| 674 | state.opIds.xOpen = i++; |
| 675 | state.opIds.xRead = i++; |
| 676 | state.opIds.xSleep = i++; |
| 677 | state.opIds.xSync = i++; |
| 678 | state.opIds.xTruncate = i++; |
| 679 | state.opIds.xUnlock = i++; |
| 680 | state.opIds.xWrite = i++; |
| 681 | state.opIds.mkdir = i++ /*currently unused*/; |
| 682 | /** Internal signals which are used only during development and |
| 683 | testing via the dev console. */ |
| 684 | state.opIds['opfs-async-metrics'] = i++; |
| 685 | state.opIds['opfs-async-shutdown'] = i++; |
| 686 | /* The retry slot is used by the async part for wait-and-retry |
| 687 | semantics. It is never written to, only used as a convenient |
| 688 | place to wait-with-timeout for a value which will never be |
| 689 | written, i.e. sleep()ing, before retrying a failed attempt to |
| 690 | acquire a SharedAccessHandle. */ |
| 691 | state.opIds.retry = i++; |
| 692 | state.sabOP = new SharedArrayBuffer( |
| 693 | i * 4/* 4==sizeof int32, noting that Atomics.wait() and |
| 694 | friends can only function on Int32Array views of an |
| 695 | SAB. */); |
| 696 | } |
| 697 | /** |
| 698 | SQLITE_xxx constants to export to the async worker |
| 699 | counterpart... |
| 700 | */ |
| 701 | state.sq3Codes = Object.create(null); |
| 702 | for(const k of [ |
| 703 | 'SQLITE_ACCESS_EXISTS', |
| 704 | 'SQLITE_ACCESS_READWRITE', |
| 705 | 'SQLITE_BUSY', |
| 706 | 'SQLITE_CANTOPEN', |
| 707 | 'SQLITE_ERROR', |
| 708 | 'SQLITE_IOERR', |
| 709 | 'SQLITE_IOERR_ACCESS', |
| 710 | 'SQLITE_IOERR_CLOSE', |
| 711 | 'SQLITE_IOERR_DELETE', |
| 712 | 'SQLITE_IOERR_FSYNC', |
| 713 | 'SQLITE_IOERR_LOCK', |
| 714 | 'SQLITE_IOERR_READ', |
| 715 | 'SQLITE_IOERR_SHORT_READ', |
| 716 | 'SQLITE_IOERR_TRUNCATE', |
| 717 | 'SQLITE_IOERR_UNLOCK', |
| 718 | 'SQLITE_IOERR_WRITE', |
| 719 | 'SQLITE_LOCK_EXCLUSIVE', |
| 720 | 'SQLITE_LOCK_NONE', |
| 721 | 'SQLITE_LOCK_PENDING', |
| 722 | 'SQLITE_LOCK_RESERVED', |
| 723 | 'SQLITE_LOCK_SHARED', |
| 724 | 'SQLITE_LOCKED', |
| 725 | 'SQLITE_MISUSE', |
| 726 | 'SQLITE_NOTFOUND', |
| 727 | 'SQLITE_OPEN_CREATE', |
| 728 | 'SQLITE_OPEN_DELETEONCLOSE', |
| 729 | 'SQLITE_OPEN_MAIN_DB', |
| 730 | 'SQLITE_OPEN_READONLY', |
| 731 | 'SQLITE_LOCK_NONE', |
| 732 | 'SQLITE_LOCK_SHARED', |
| 733 | 'SQLITE_LOCK_RESERVED', |
| 734 | 'SQLITE_LOCK_PENDING', |
| 735 | 'SQLITE_LOCK_EXCLUSIVE' |
| 736 | ]){ |
| 737 | state.sq3Codes[k] = |
| 738 | capi[k] ?? toss("Maintenance required: not found:",k); |
| 739 | } |
| 740 | |
| 741 | state.opfsFlags = Object.assign(Object.create(null),{ |
| 742 | /** |
| 743 | Flag for use with xOpen(). URI flag "opfs-unlock-asap=1" |
| 744 | enables this. See defaultUnlockAsap, below. |
| 745 | */ |
| 746 | OPFS_UNLOCK_ASAP: 0x01, |
| 747 | /** |
| 748 | Flag for use with xOpen(). URI flag "delete-before-open=1" |
| 749 | tells the VFS to delete the db file before attempting to open |
| 750 | it. This can be used, e.g., to replace a db which has been |
| 751 | corrupted (without forcing us to expose a delete/unlink() |
| 752 | function in the public API). |
| 753 | |
| 754 | Failure to unlink the file is ignored but may lead to |
| 755 | downstream errors. An unlink can fail if, e.g., another tab |
| 756 | has the handle open. |
| 757 | |
| 758 | It goes without saying that deleting a file out from under |
| 759 | another instance results in Undefined Behavior. |
| 760 | */ |
| 761 | OPFS_UNLINK_BEFORE_OPEN: 0x02, |
| 762 | /** |
| 763 | If true, any async routine which must implicitly acquire a |
| 764 | sync access handle (i.e. an OPFS lock), without an active |
| 765 | xLock(), will release that lock at the end of the call which |
| 766 | acquires it. If false, such implicit locks are not released |
| 767 | until the VFS is idle for some brief amount of time, as |
| 768 | defined by state.asyncIdleWaitTime. |
| 769 | |
| 770 | The benefit of enabling this is higher concurrency. The |
| 771 | down-side is much-reduced performance (as much as a 4x |
| 772 | decrease in speedtest1). |
| 773 | */ |
| 774 | defaultUnlockAsap: false |
| 775 | }); |
| 776 | |
| 777 | opfsVfs.metrics.reset()/*must not be called until state.opIds is set up*/; |
| 778 | const metrics = opfsVfs.metrics.counters; |
| 779 | |
| 780 | /** |
| 781 | Runs the given operation (by name) in the async worker |
| 782 | counterpart, waits for its response, and returns the result |
| 783 | which the async worker writes to SAB[state.opIds.rc]. The 2nd |
| 784 | and subsequent arguments must be the arguments for the async op |
| 785 | (see sqlite3-opfs-async-proxy.c-pp.js). |
| 786 | */ |
| 787 | const opRun = opfsVfs.opRun = (op,...args)=>{ |
| 788 | const opNdx = state.opIds[op] || toss(opfsVfs.vfsName+": Invalid op ID:",op); |
| 789 | state.s11n.serialize(...args); |
| 790 | Atomics.store(state.sabOPView, state.opIds.rc, -1); |
| 791 | Atomics.store(state.sabOPView, state.opIds.whichOp, opNdx); |
| 792 | Atomics.notify(state.sabOPView, state.opIds.whichOp) |
| 793 | /* async thread will take over here */; |
| 794 | const t = performance.now(); |
| 795 | while('not-equal'!==Atomics.wait(state.sabOPView, state.opIds.rc, -1)){ |
| 796 | /* |
| 797 | The reason for this loop is buried in the details of a long |
| 798 | discussion at: |
| 799 | |
| 800 | https://github.com/sqlite/sqlite-wasm/issues/12 |
| 801 | |
| 802 | Summary: in at least one browser flavor, under high loads, |
| 803 | the wait()/notify() pairings can get out of sync and/or |
| 804 | spuriously wake up. Calling wait() here until it returns |
| 805 | 'not-equal' gets them back in sync. |
| 806 | */ |
| 807 | } |
| 808 | /* When the above wait() call returns 'not-equal', the async |
| 809 | half will have completed the operation and reported its |
| 810 | results in the state.opIds.rc slot of the SAB. It may have |
| 811 | also serialized an exception for us. */ |
| 812 | const rc = Atomics.load(state.sabOPView, state.opIds.rc); |
| 813 | metrics[op].wait += performance.now() - t; |
| 814 | if(rc && state.asyncS11nExceptions){ |
| 815 | const err = state.s11n.deserialize(); |
| 816 | if(err) error(op+"() async error:",...err); |
| 817 | } |
| 818 | return rc; |
| 819 | }; |
| 820 | |
| 821 | const opTimer = Object.create(null); |
| 822 | opTimer.op = undefined; |
| 823 | opTimer.start = undefined; |
| 824 | const mTimeStart = opfsVfs.mTimeStart = (op)=>{ |
| 825 | opTimer.start = performance.now(); |
| 826 | opTimer.op = op; |
| 827 | ++metrics[op].count; |
| 828 | }; |
| 829 | const mTimeEnd = opfsVfs.mTimeEnd = ()=>( |
| 830 | metrics[opTimer.op].time += performance.now() - opTimer.start |
| 831 | ); |
| 832 | |
| 833 | /** |
| 834 | Map of sqlite3_file pointers to objects constructed by xOpen(). |
| 835 | */ |
| 836 | const __openFiles = opfsVfs.__openFiles = Object.create(null); |
| 837 | |
| 838 | /** |
| 839 | Impls for the sqlite3_io_methods methods. Maintenance reminder: |
| 840 | members are in alphabetical order to simplify finding them. |
| 841 | */ |
| 842 | const ioSyncWrappers = opfsVfs.ioSyncWrappers = util.nu({ |
| 843 | xCheckReservedLock: function(pFile,pOut){ |
| 844 | /** |
| 845 | After consultation with a topic expert: "opfs-wl" will |
| 846 | continue to use the same no-op impl which "opfs" does |
| 847 | because: |
| 848 | |
| 849 | - xCheckReservedLock() is just a hint. If SQLite needs to |
| 850 | lock, it's still going to try to lock. |
| 851 | |
| 852 | - We cannot do this check synchronously in "opfs-wl", |
| 853 | so would need to pass it to the async proxy. That would |
| 854 | make it inordinately expensive considering that it's |
| 855 | just a hint. |
| 856 | |
| 857 | See: forum:a2f573b00cda1372 |
| 858 | */ |
| 859 | wasm.poke(pOut, 0, 'i32'); |
| 860 | return 0; |
| 861 | }, |
| 862 | xClose: function(pFile){ |
| 863 | mTimeStart('xClose'); |
| 864 | let rc = 0; |
| 865 | const f = __openFiles[pFile]; |
| 866 | if(f){ |
| 867 | delete __openFiles[pFile]; |
| 868 | rc = opRun('xClose', pFile); |
| 869 | if(f.sq3File) f.sq3File.dispose(); |
| 870 | } |
| 871 | mTimeEnd(); |
| 872 | return rc; |
| 873 | }, |
| 874 | xDeviceCharacteristics: function(pFile){ |
| 875 | return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN; |
| 876 | }, |
| 877 | xFileControl: function(pFile, opId, pArg){ |
| 878 | /*mTimeStart('xFileControl'); |
| 879 | mTimeEnd();*/ |
| 880 | return capi.SQLITE_NOTFOUND; |
| 881 | }, |
| 882 | xFileSize: function(pFile,pSz64){ |
| 883 | mTimeStart('xFileSize'); |
| 884 | let rc = opRun('xFileSize', pFile); |
| 885 | if(0==rc){ |
| 886 | try { |
| 887 | const sz = state.s11n.deserialize()[0]; |
| 888 | wasm.poke(pSz64, sz, 'i64'); |
| 889 | }catch(e){ |
| 890 | error("Unexpected error reading xFileSize() result:",e); |
| 891 | rc = state.sq3Codes.SQLITE_IOERR; |
| 892 | } |
| 893 | } |
| 894 | mTimeEnd(); |
| 895 | return rc; |
| 896 | }, |
| 897 | xRead: function(pFile,pDest,n,offset64){ |
| 898 | mTimeStart('xRead'); |
| 899 | const f = __openFiles[pFile]; |
| 900 | let rc; |
| 901 | try { |
| 902 | rc = opRun('xRead',pFile, n, Number(offset64)); |
| 903 | if(0===rc || capi.SQLITE_IOERR_SHORT_READ===rc){ |
| 904 | /** |
| 905 | Results get written to the SharedArrayBuffer f.sabView. |
| 906 | Because the heap is _not_ a SharedArrayBuffer, we have |
| 907 | to copy the results. TypedArray.set() seems to be the |
| 908 | fastest way to copy this. */ |
| 909 | wasm.heap8u().set(f.sabView.subarray(0, n), Number(pDest)); |
| 910 | } |
| 911 | }catch(e){ |
| 912 | error("xRead(",arguments,") failed:",e,f); |
| 913 | rc = capi.SQLITE_IOERR_READ; |
| 914 | } |
| 915 | mTimeEnd(); |
| 916 | return rc; |
| 917 | }, |
| 918 | xSync: function(pFile,flags){ |
| 919 | mTimeStart('xSync'); |
| 920 | const rc = opRun('xSync', pFile, flags); |
| 921 | mTimeEnd(); |
| 922 | return rc; |
| 923 | }, |
| 924 | xTruncate: function(pFile,sz64){ |
| 925 | mTimeStart('xTruncate'); |
| 926 | const rc = opRun('xTruncate', pFile, Number(sz64)); |
| 927 | mTimeEnd(); |
| 928 | return rc; |
| 929 | }, |
| 930 | xWrite: function(pFile,pSrc,n,offset64){ |
| 931 | mTimeStart('xWrite'); |
| 932 | const f = __openFiles[pFile]; |
| 933 | let rc; |
| 934 | try { |
| 935 | f.sabView.set(wasm.heap8u().subarray( |
| 936 | Number(pSrc), Number(pSrc) + n |
| 937 | )); |
| 938 | rc = opRun('xWrite', pFile, n, Number(offset64)); |
| 939 | }catch(e){ |
| 940 | error("xWrite(",arguments,") failed:",e,f); |
| 941 | rc = capi.SQLITE_IOERR_WRITE; |
| 942 | } |
| 943 | mTimeEnd(); |
| 944 | return rc; |
| 945 | } |
| 946 | })/*ioSyncWrappers*/; |
| 947 | |
| 948 | /** |
| 949 | Impls for the sqlite3_vfs methods. Maintenance reminder: members |
| 950 | are in alphabetical order to simplify finding them. |
| 951 | */ |
| 952 | const vfsSyncWrappers = opfsVfs.vfsSyncWrappers = { |
| 953 | xAccess: function(pVfs,zName,flags,pOut){ |
| 954 | mTimeStart('xAccess'); |
| 955 | const rc = opRun('xAccess', wasm.cstrToJs(zName)); |
| 956 | wasm.poke( pOut, (rc ? 0 : 1), 'i32' ); |
| 957 | mTimeEnd(); |
| 958 | return 0; |
| 959 | }, |
| 960 | xCurrentTime: function(pVfs,pOut){ |
| 961 | wasm.poke(pOut, 2440587.5 + (new Date().getTime()/86400000), |
| 962 | 'double'); |
| 963 | return 0; |
| 964 | }, |
| 965 | xCurrentTimeInt64: function(pVfs,pOut){ |
| 966 | wasm.poke(pOut, (2440587.5 * 86400000) + new Date().getTime(), |
| 967 | 'i64'); |
| 968 | return 0; |
| 969 | }, |
| 970 | xDelete: function(pVfs, zName, doSyncDir){ |
| 971 | mTimeStart('xDelete'); |
| 972 | const rc = opRun('xDelete', wasm.cstrToJs(zName), doSyncDir, false); |
| 973 | mTimeEnd(); |
| 974 | return rc; |
| 975 | }, |
| 976 | xFullPathname: function(pVfs,zName,nOut,pOut){ |
| 977 | /* Until/unless we have some notion of "current dir" |
| 978 | in OPFS, simply copy zName to pOut... */ |
| 979 | const i = wasm.cstrncpy(pOut, zName, nOut); |
| 980 | return i<nOut ? 0 : capi.SQLITE_CANTOPEN |
| 981 | /*CANTOPEN is required by the docs but SQLITE_RANGE would be a closer match*/; |
| 982 | }, |
| 983 | xGetLastError: function(pVfs,nOut,pOut){ |
| 984 | /* Mutex use in the overlying APIs cause xGetLastError() to |
| 985 | not be terribly useful for us. e.g. it can't be used to |
| 986 | convey error messages from xOpen() because there would be a |
| 987 | race condition between sqlite3_open()'s call to xOpen() and |
| 988 | this function. */ |
| 989 | sqlite3.config.warn("OPFS xGetLastError() has nothing sensible to return."); |
| 990 | return 0; |
| 991 | }, |
| 992 | //xSleep is optionally defined below |
| 993 | xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){ |
| 994 | mTimeStart('xOpen'); |
| 995 | let opfsFlags = 0; |
| 996 | let jzName, zToFree; |
| 997 | if( !zName ){ |
| 998 | jzName = opfsUtil.randomFilename(); |
| 999 | zName = zToFree = wasm.allocCString(jzName); |
| 1000 | }else if(wasm.isPtr(zName)){ |
| 1001 | if(capi.sqlite3_uri_boolean(zName, "opfs-unlock-asap", 0)){ |
| 1002 | /* -----------------------^^^^^ MUST pass the untranslated |
| 1003 | C-string here. */ |
| 1004 | opfsFlags |= state.opfsFlags.OPFS_UNLOCK_ASAP; |
| 1005 | } |
| 1006 | if(capi.sqlite3_uri_boolean(zName, "delete-before-open", 0)){ |
| 1007 | opfsFlags |= state.opfsFlags.OPFS_UNLINK_BEFORE_OPEN; |
| 1008 | } |
| 1009 | jzName = wasm.cstrToJs(zName); |
| 1010 | //sqlite3.config.warn("xOpen zName =",zName, "opfsFlags =",opfsFlags); |
| 1011 | }else{ |
| 1012 | sqlite3.config.error("Impossible zName value in xOpen?", zName); |
| 1013 | return capi.SQLITE_CANTOPEN; |
| 1014 | } |
| 1015 | const fh = util.nu({ |
| 1016 | fid: pFile, |
| 1017 | filename: jzName, |
| 1018 | sab: new SharedArrayBuffer(state.fileBufferSize), |
| 1019 | flags: flags, |
| 1020 | readOnly: !(capi.SQLITE_OPEN_CREATE & flags) |
| 1021 | && !!(flags & capi.SQLITE_OPEN_READONLY) |
| 1022 | }); |
| 1023 | const rc = opRun('xOpen', pFile, jzName, flags, opfsFlags); |
| 1024 | if(rc){ |
| 1025 | if( zToFree ) wasm.dealloc(zToFree); |
| 1026 | }else{ |
| 1027 | /* Recall that sqlite3_vfs::xClose() will be called, even on |
| 1028 | error, unless pFile->pMethods is NULL. */ |
| 1029 | if(fh.readOnly){ |
| 1030 | wasm.poke(pOutFlags, capi.SQLITE_OPEN_READONLY, 'i32'); |
| 1031 | } |
| 1032 | __openFiles[pFile] = fh; |
| 1033 | fh.sabView = state.sabFileBufView; |
| 1034 | fh.sq3File = new capi.sqlite3_file(pFile); |
| 1035 | if( zToFree ) fh.sq3File.addOnDispose(zToFree); |
| 1036 | fh.sq3File.$pMethods = opfsIoMethods.pointer; |
| 1037 | fh.lockType = capi.SQLITE_LOCK_NONE; |
| 1038 | } |
| 1039 | mTimeEnd(); |
| 1040 | return rc; |
| 1041 | }/*xOpen()*/ |
| 1042 | }/*vfsSyncWrappers*/; |
| 1043 | |
| 1044 | const pDVfs = capi.sqlite3_vfs_find(null)/*pointer to default VFS*/; |
| 1045 | if(pDVfs){ |
| 1046 | const dVfs = new capi.sqlite3_vfs(pDVfs); |
| 1047 | opfsVfs.$xRandomness = dVfs.$xRandomness; |
| 1048 | opfsVfs.$xSleep = dVfs.$xSleep; |
| 1049 | dVfs.dispose(); |
| 1050 | } |
| 1051 | if(!opfsVfs.$xRandomness){ |
| 1052 | /* If the default VFS has no xRandomness(), add a basic JS impl... */ |
| 1053 | opfsVfs.vfsSyncWrappers.xRandomness = function(pVfs, nOut, pOut){ |
| 1054 | const heap = wasm.heap8u(); |
| 1055 | let i = 0; |
| 1056 | const npOut = Number(pOut); |
| 1057 | for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF; |
| 1058 | return i; |
| 1059 | }; |
| 1060 | } |
| 1061 | if(!opfsVfs.$xSleep){ |
| 1062 | /* If we can inherit an xSleep() impl from the default VFS then |
| 1063 | assume it's sane and use it, otherwise install a JS-based |
| 1064 | one. */ |
| 1065 | opfsVfs.vfsSyncWrappers.xSleep = function(pVfs,ms){ |
| 1066 | mTimeStart('xSleep'); |
| 1067 | Atomics.wait(state.sabOPView, state.opIds.xSleep, 0, ms); |
| 1068 | mTimeEnd(); |
| 1069 | return 0; |
| 1070 | }; |
| 1071 | } |
| 1072 | |
| 1073 | //#define vfs.metrics.enable |
| 1074 | //#include "api/opfs-common-inline.c-pp.js" |
| 1075 | //#undef vfs.metrics.enable |
| 1076 | opfsVfs.initS11n = initS11n; |
| 1077 | |
| 1078 | /** |
| 1079 | To be called by the VFS's main installation routine after it has |
| 1080 | wired up enough state to provide its overridden io-method impls |
| 1081 | (which must be properties of the ioMethods argument). Returns a |
| 1082 | Promise which the installation routine must return. callback must |
| 1083 | be a function which performs any post-bootstrap touchups, namely |
| 1084 | plugging in a sqlite3.oo1 wrapper. It is passed (sqlite3, opfsVfs), |
| 1085 | where opfsVfs is the sqlite3_vfs object which was set up by |
| 1086 | opfsUtil.createVfsState(). |
| 1087 | */ |
| 1088 | opfsVfs.bindVfs = function(ioMethods, callback){ |
| 1089 | Object.assign(opfsVfs.ioSyncWrappers, ioMethods); |
| 1090 | const thePromise = new Promise(function(promiseResolve_, promiseReject_){ |
| 1091 | let promiseWasRejected = undefined; |
| 1092 | const promiseReject = (err)=>{ |
| 1093 | promiseWasRejected = true; |
| 1094 | opfsVfs.dispose(); |
| 1095 | return promiseReject_(err); |
| 1096 | }; |
| 1097 | const promiseResolve = ()=>{ |
| 1098 | try{ |
| 1099 | callback(sqlite3, opfsVfs); |
| 1100 | }catch(e){ |
| 1101 | return promiseReject(e); |
| 1102 | } |
| 1103 | promiseWasRejected = false; |
| 1104 | return promiseResolve_(sqlite3); |
| 1105 | }; |
| 1106 | const options = opfsUtil.options; |
| 1107 | //#if not target:es6-bundler-friendly |
| 1108 | const proxyUri = options.proxyUri +( |
| 1109 | (options.proxyUri.indexOf('?')<0) ? '?' : '&' |
| 1110 | )+'vfs='+vfsName; |
| 1111 | //sqlite3.config.error("proxyUri",options.proxyUri, (new Error())); |
| 1112 | //#/if |
| 1113 | const W = opfsVfs.worker = |
| 1114 | //#if target:es6-bundler-friendly |
| 1115 | (()=>{ |
| 1116 | /* Discussion explaining this formulation: |
| 1117 | https://github.com/sqlite/sqlite-wasm/pull/159 */ |
| 1118 | const url = new URL('sqlite3-opfs-async-proxy.js', import.meta.url); |
| 1119 | url.searchParams.set('vfs', vfsName); |
| 1120 | return new Worker(url.toString()); |
| 1121 | })(); |
| 1122 | //#elif target:es6-module |
| 1123 | new Worker(new URL(proxyUri, import.meta.url)); |
| 1124 | //#else |
| 1125 | new Worker(proxyUri); |
| 1126 | //#/if |
| 1127 | let zombieTimer = setTimeout(()=>{ |
| 1128 | /* At attempt to work around a browser-specific quirk in which |
| 1129 | the Worker load is failing in such a way that we neither |
| 1130 | resolve nor reject it. This workaround gives that resolve/reject |
| 1131 | a time limit and rejects if that timer expires. Discussion: |
| 1132 | https://sqlite.org/forum/forumpost/a708c98dcb3ef */ |
| 1133 | if(undefined===promiseWasRejected){ |
| 1134 | promiseReject( |
| 1135 | new Error("Timeout while waiting for OPFS async proxy worker.") |
| 1136 | ); |
| 1137 | } |
| 1138 | }, 4000); |
| 1139 | W._originalOnError = W.onerror /* will be restored later */; |
| 1140 | W.onerror = function(err){ |
| 1141 | // The error object doesn't contain any useful info when the |
| 1142 | // failure is, e.g., that the remote script is 404. |
| 1143 | error("Error initializing OPFS asyncer:",err); |
| 1144 | promiseReject(new Error("Loading OPFS async Worker failed for unknown reasons.")); |
| 1145 | }; |
| 1146 | |
| 1147 | const opRun = opfsVfs.opRun; |
| 1148 | //#if 0 |
| 1149 | /** |
| 1150 | Not part of the public API. Only for test/development use. |
| 1151 | */ |
| 1152 | opfsVfs.debug = { |
| 1153 | asyncShutdown: ()=>{ |
| 1154 | warn("Shutting down OPFS async listener. The OPFS VFS will no longer work."); |
| 1155 | opRun('opfs-async-shutdown'); |
| 1156 | }, |
| 1157 | asyncRestart: ()=>{ |
| 1158 | warn("Attempting to restart OPFS VFS async listener. Might work, might not."); |
| 1159 | W.postMessage({type: 'opfs-async-restart'}); |
| 1160 | } |
| 1161 | }; |
| 1162 | //#/if |
| 1163 | |
| 1164 | const sanityCheck = function(){ |
| 1165 | const scope = wasm.scopedAllocPush(); |
| 1166 | const sq3File = new capi.sqlite3_file(); |
| 1167 | try{ |
| 1168 | const fid = sq3File.pointer; |
| 1169 | const openFlags = capi.SQLITE_OPEN_CREATE |
| 1170 | | capi.SQLITE_OPEN_READWRITE |
| 1171 | //| capi.SQLITE_OPEN_DELETEONCLOSE |
| 1172 | | capi.SQLITE_OPEN_MAIN_DB; |
| 1173 | const pOut = wasm.scopedAlloc(8); |
| 1174 | const dbFile = "/sanity/check/file"+opfsUtil.randomFilename(8); |
| 1175 | const zDbFile = wasm.scopedAllocCString(dbFile); |
| 1176 | let rc; |
| 1177 | state.s11n.serialize("This is ä string."); |
| 1178 | rc = state.s11n.deserialize(); |
| 1179 | log("deserialize() says:",rc); |
| 1180 | if("This is ä string."!==rc[0]) toss("String d13n error."); |
| 1181 | opfsVfs.vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut); |
| 1182 | rc = wasm.peek(pOut,'i32'); |
| 1183 | log("xAccess(",dbFile,") exists ?=",rc); |
| 1184 | rc = opfsVfs.vfsSyncWrappers.xOpen(opfsVfs.pointer, zDbFile, |
| 1185 | fid, openFlags, pOut); |
| 1186 | log("open rc =",rc,"state.sabOPView[xOpen] =", |
| 1187 | state.sabOPView[state.opIds.xOpen]); |
| 1188 | if(0!==rc){ |
| 1189 | error("open failed with code",rc); |
| 1190 | return; |
| 1191 | } |
| 1192 | opfsVfs.vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut); |
| 1193 | rc = wasm.peek(pOut,'i32'); |
| 1194 | if(!rc) toss("xAccess() failed to detect file."); |
| 1195 | rc = opfsVfs.ioSyncWrappers.xSync(sq3File.pointer, 0); |
| 1196 | if(rc) toss('sync failed w/ rc',rc); |
| 1197 | rc = opfsVfs.ioSyncWrappers.xTruncate(sq3File.pointer, 1024); |
| 1198 | if(rc) toss('truncate failed w/ rc',rc); |
| 1199 | wasm.poke(pOut,0,'i64'); |
| 1200 | rc = opfsVfs.ioSyncWrappers.xFileSize(sq3File.pointer, pOut); |
| 1201 | if(rc) toss('xFileSize failed w/ rc',rc); |
| 1202 | log("xFileSize says:",wasm.peek(pOut, 'i64')); |
| 1203 | rc = opfsVfs.ioSyncWrappers.xWrite(sq3File.pointer, zDbFile, 10, 1); |
| 1204 | if(rc) toss("xWrite() failed!"); |
| 1205 | const readBuf = wasm.scopedAlloc(16); |
| 1206 | rc = opfsVfs.ioSyncWrappers.xRead(sq3File.pointer, readBuf, 6, 2); |
| 1207 | wasm.poke(readBuf+6,0); |
| 1208 | let jRead = wasm.cstrToJs(readBuf); |
| 1209 | log("xRead() got:",jRead); |
| 1210 | if("sanity"!==jRead) toss("Unexpected xRead() value."); |
| 1211 | if(opfsVfs.vfsSyncWrappers.xSleep){ |
| 1212 | log("xSleep()ing before close()ing..."); |
| 1213 | opfsVfs.vfsSyncWrappers.xSleep(opfsVfs.pointer,2000); |
| 1214 | log("waking up from xSleep()"); |
| 1215 | } |
| 1216 | rc = opfsVfs.ioSyncWrappers.xClose(fid); |
| 1217 | log("xClose rc =",rc,"sabOPView =",state.sabOPView); |
| 1218 | log("Deleting file:",dbFile); |
| 1219 | opfsVfs.vfsSyncWrappers.xDelete(opfsVfs.pointer, zDbFile, 0x1234); |
| 1220 | opfsVfs.vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut); |
| 1221 | rc = wasm.peek(pOut,'i32'); |
| 1222 | if(rc) toss("Expecting 0 from xAccess(",dbFile,") after xDelete()."); |
| 1223 | warn("End of OPFS sanity checks."); |
| 1224 | }finally{ |
| 1225 | sq3File.dispose(); |
| 1226 | wasm.scopedAllocPop(scope); |
| 1227 | } |
| 1228 | }/*sanityCheck()*/; |
| 1229 | |
| 1230 | W.onmessage = function({data}){ |
| 1231 | //sqlite3.config.warn(vfsName,"Worker.onmessage:",data); |
| 1232 | switch(data.type){ |
| 1233 | case 'opfs-unavailable': |
| 1234 | /* Async proxy has determined that OPFS is unavailable. There's |
| 1235 | nothing more for us to do here. */ |
| 1236 | promiseReject(new Error(data.payload.join(' '))); |
| 1237 | break; |
| 1238 | case 'opfs-async-loaded': |
| 1239 | /* Arrives as soon as the asyc proxy finishes loading. |
| 1240 | Pass our config and shared state on to the async |
| 1241 | worker. */ |
| 1242 | delete state.vfs; |
| 1243 | W.postMessage({type: 'opfs-async-init', args: util.nu(state)}); |
| 1244 | break; |
| 1245 | case 'opfs-async-inited': { |
| 1246 | /* Indicates that the async partner has received the 'init' |
| 1247 | and has finished initializing, so the real work can |
| 1248 | begin... */ |
| 1249 | if(true===promiseWasRejected){ |
| 1250 | break /* promise was already rejected via timer */; |
| 1251 | } |
| 1252 | clearTimeout(zombieTimer); |
| 1253 | zombieTimer = null; |
| 1254 | try { |
| 1255 | sqlite3.vfs.installVfs({ |
| 1256 | io: {struct: opfsVfs.ioMethods, methods: opfsVfs.ioSyncWrappers}, |
| 1257 | vfs: {struct: opfsVfs, methods: opfsVfs.vfsSyncWrappers} |
| 1258 | }); |
| 1259 | state.sabOPView = new Int32Array(state.sabOP); |
| 1260 | state.sabFileBufView = new Uint8Array(state.sabIO, 0, state.fileBufferSize); |
| 1261 | state.sabS11nView = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize); |
| 1262 | opfsVfs.initS11n(); |
| 1263 | opfsVfs.initS11n = null; |
| 1264 | if(options.sanityChecks){ |
| 1265 | warn("Running sanity checks because of opfs-sanity-check URL arg..."); |
| 1266 | sanityCheck(); |
| 1267 | } |
| 1268 | if(opfsUtil.thisThreadHasOPFS()){ |
| 1269 | opfsUtil.getRootDir().then((d)=>{ |
| 1270 | W.onerror = W._originalOnError; |
| 1271 | delete W._originalOnError; |
| 1272 | log("End of OPFS sqlite3_vfs setup.", opfsVfs); |
| 1273 | promiseResolve(); |
| 1274 | }).catch(promiseReject); |
| 1275 | }else{ |
| 1276 | promiseResolve(); |
| 1277 | } |
| 1278 | }catch(e){ |
| 1279 | error(e); |
| 1280 | promiseReject(e); |
| 1281 | } |
| 1282 | break; |
| 1283 | } |
| 1284 | case 'debug': |
| 1285 | warn("debug message from worker:",data); |
| 1286 | break; |
| 1287 | default: { |
| 1288 | const errMsg = ( |
| 1289 | "Unexpected message from the OPFS async worker: " + |
| 1290 | JSON.stringify(data) |
| 1291 | ); |
| 1292 | error(errMsg); |
| 1293 | promiseReject(new Error(errMsg)); |
| 1294 | break; |
| 1295 | } |
| 1296 | }/*switch(data.type)*/ |
| 1297 | }/*W.onmessage()*/; |
| 1298 | })/*thePromise*/; |
| 1299 | return thePromise; |
| 1300 | }/*bindVfs()*/; |
| 1301 | |
| 1302 | return state; |
| 1303 | }/*createVfsState()*/; |
| 1304 | |
| 1305 | }/*sqlite3ApiBootstrap.initializers*/); |
| 1306 | //#/if /* global snip */ |