interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / wasm / api / sqlite3-vfs-opfs-sahpool.c-pp.js

1678 lines · 62861 bytes Raw Blame History
1//#if not target:node and not omit-opfs-sahpool
2/*
3 2023-07-14
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 a sqlite3_vfs backed by OPFS storage which uses a
15 different implementation strategy than the "opfs" VFS. This one is a
16 port of Roy Hashimoto's OPFS SyncAccessHandle pool:
17
18 https://github.com/rhashimoto/wa-sqlite/blob/master/src/examples/AccessHandlePoolVFS.js
19
20 As described at:
21
22 https://github.com/rhashimoto/wa-sqlite/discussions/67
23
24 with Roy's explicit permission to permit us to port his to our
25 infrastructure rather than having to clean-room reverse-engineer it:
26
27 https://sqlite.org/forum/forumpost/e140d84e71
28
29 Primary differences from the "opfs" VFS include:
30
31 - This one avoids the need for a sub-worker to synchronize
32 communication between the synchronous C API and the
33 only-partly-synchronous OPFS API.
34
35 - It does so by opening a fixed number of OPFS files at
36 library-level initialization time, obtaining SyncAccessHandles to
37 each, and manipulating those handles via the synchronous sqlite3_vfs
38 interface. If it cannot open them (e.g. they are already opened by
39 another tab) then the VFS will not be installed.
40
41 - Because of that, this one lacks all library-level concurrency
42 support.
43
44 - Also because of that, it does not require the SharedArrayBuffer,
45 so can function without the COOP/COEP HTTP response headers.
46
47 - Also because of that, this one is much faster and the performance
48 gap increases as the job sizes increase.
49
50 - It can hypothetically support Safari 16.4+, whereas the "opfs" VFS
51 requires v17 due to a subworker/storage bug in 16.x which makes it
52 incompatible with that VFS.
53
54 - This VFS requires the "semi-fully-sync" FileSystemSyncAccessHandle
55 (hereafter "SAH") APIs released with Chrome v108 (and all other
56 major browsers released since March 2023). If that API is not
57 detected, the VFS is not registered.
58*/
59sqlite3ApiBootstrap.initializers.push(function(sqlite3){
60 'use strict';
61 if( sqlite3.config.disable?.vfs?.['opfs-sahpool'] ){
62 return;
63 }
64
65 const toss = sqlite3.util.toss;
66 const toss3 = sqlite3.util.toss3;
67 const initPromises = Object.create(null) /* cache of (name:result) of VFS init results */;
68 const capi = sqlite3.capi;
69 const util = sqlite3.util;
70 const wasm = sqlite3.wasm;
71 // Config opts for the VFS...
72 const SECTOR_SIZE = 4096;
73 const HEADER_MAX_PATH_SIZE = 512;
74 const HEADER_FLAGS_SIZE = 4;
75 const HEADER_DIGEST_SIZE = 8;
76 const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
77 const HEADER_OFFSET_FLAGS = HEADER_MAX_PATH_SIZE;
78 const HEADER_OFFSET_DIGEST = HEADER_CORPUS_SIZE;
79 const HEADER_OFFSET_DATA = SECTOR_SIZE;
80 /* Bitmask of file types which may persist across sessions.
81 SQLITE_OPEN_xyz types not listed here may be inadvertently
82 left in OPFS but are treated as transient by this VFS and
83 they will be cleaned up during VFS init. */
84 const PERSISTENT_FILE_TYPES =
85 capi.SQLITE_OPEN_MAIN_DB |
86 capi.SQLITE_OPEN_MAIN_JOURNAL |
87 capi.SQLITE_OPEN_SUPER_JOURNAL |
88 capi.SQLITE_OPEN_WAL;
89 const FLAG_COMPUTE_DIGEST_V2 = capi.SQLITE_OPEN_MEMORY
90 /* Part of the fix for
91 https://github.com/sqlite/sqlite-wasm/issues/97
92
93 Summary: prior to version 3.50.0 computeDigest() always computes
94 a value of [0,0] due to overflows, so it does not do anything
95 useful. Fixing it invalidates old persistent files, so we
96 instead only fix it for files created or updated since the bug
97 was discovered and fixed.
98
99 This flag determines whether we use the broken legacy
100 computeDigest() or the v2 variant. We only use this flag for
101 newly-created/overwritten files. Pre-existing files have the
102 broken digest stored in them so need to continue to use that.
103
104 What this means, in terms of db file compatibility between
105 versions:
106
107 - DBs created with versions older than this fix (<3.50.0)
108 can be read by post-fix versions. Such DBs which are written
109 to in-place (not replaced) by newer versions can still be read
110 by older versions, as the affected digest is only modified
111 when the SAH slot is assigned to a given filename.
112
113 - DBs created with post-fix versions will, when read by a pre-fix
114 version, be seen as having a "bad digest" and will be
115 unceremoniously replaced by that pre-fix version. When swapping
116 back to a post-fix version, that version will see that the file
117 entry is missing the FLAG_COMPUTE_DIGEST_V2 bit so will treat it
118 as a legacy file.
119
120 This flag is stored in the same memory as the various
121 SQLITE_OPEN_... flags and we must be careful here to not use a
122 flag bit which is otherwise relevant for the VFS.
123 SQLITE_OPEN_MEMORY is handled by sqlite3_open_v2() and friends,
124 not the VFS, so we'll repurpose that one. If we take a
125 currently-unused bit and it ends up, at some later point, being
126 used, we would have to invalidate existing VFS files in order to
127 move to another bit. Similarly, if the SQLITE_OPEN_MEMORY bit
128 were ever reassigned (which it won't be!), we'd invalidate all
129 VFS-side files.
130 */;
131
132 /** Subdirectory of the VFS's space where "opaque" (randomly-named)
133 files are stored. Changing this effectively invalidates the data
134 stored under older names (orphaning it), so don't do that. */
135 const OPAQUE_DIR_NAME = ".opaque";
136
137 /**
138 Returns short a string of random alphanumeric characters
139 suitable for use as a random filename.
140 */
141 const getRandomName = ()=>Math.random().toString(36).slice(2);
142
143 const textDecoder = new TextDecoder();
144 const textEncoder = new TextEncoder();
145
146 const optionDefaults = Object.assign(Object.create(null),{
147 name: 'opfs-sahpool',
148 directory: undefined /* derived from .name */,
149 initialCapacity: 6,
150 clearOnInit: false,
151 /* Logging verbosity 3+ == everything, 2 == warnings+errors, 1 ==
152 errors only. */
153 verbosity: 2,
154 forceReinitIfPreviouslyFailed: false,
155 preserveOnInitFailure: false
156 });
157
158 /** Logging routines, from most to least serious. */
159 const loggers = [
160 sqlite3.config.error,
161 sqlite3.config.warn,
162 sqlite3.config.log
163 ];
164 const log = sqlite3.config.log;
165 const warn = sqlite3.config.warn;
166 const error = sqlite3.config.error;
167
168 /* Maps (sqlite3_vfs*) to OpfsSAHPool instances */
169 const __mapVfsToPool = new Map();
170 const getPoolForVfs = (pVfs)=>__mapVfsToPool.get(pVfs);
171 const setPoolForVfs = (pVfs,pool)=>{
172 if(pool) __mapVfsToPool.set(pVfs, pool);
173 else __mapVfsToPool.delete(pVfs);
174 };
175 /* Maps (sqlite3_file*) to OpfsSAHPool instances */
176 const __mapSqlite3File = new Map();
177 const getPoolForPFile = (pFile)=>__mapSqlite3File.get(pFile);
178 const setPoolForPFile = (pFile,pool)=>{
179 if(pool) __mapSqlite3File.set(pFile, pool);
180 else __mapSqlite3File.delete(pFile);
181 };
182
183 /**
184 Impls for the sqlite3_io_methods methods. Maintenance reminder:
185 members are in alphabetical order to simplify finding them.
186 */
187 const ioMethods = {
188 xCheckReservedLock: function(pFile,pOut){
189 const pool = getPoolForPFile(pFile);
190 pool.log('xCheckReservedLock');
191 pool.storeErr();
192 const file = pool.getOFileForS3File(pFile);
193 wasm.poke32(
194 pOut,
195 pool.hasReservedLock(file.path) ? 1 : 0
196 /* As forum:b2fbb61642 elaborates on why we cannot simply
197 check file.lockType>=capi.SQLITE_LOCK_RESERVED
198 here. Summary: xOpen() has long allowed multiple handles to
199 the same filename and we need to check if any of them have
200 a lock to avoid a specific corruption case which that forum
201 thread demonstrates. */
202 );
203 return 0;
204 },
205 xClose: function(pFile){
206 const pool = getPoolForPFile(pFile);
207 pool.storeErr();
208 const file = pool.getOFileForS3File(pFile);
209 if(file) {
210 try{
211 pool.log(`xClose ${file.path}`);
212 pool.unlockFile(file, capi.SQLITE_LOCK_NONE);
213 pool.mapS3FileToOFile(pFile, false);
214 file.sah.flush();
215 if(file.flags & capi.SQLITE_OPEN_DELETEONCLOSE){
216 pool.deletePath(file.path);
217 }
218 }catch(e){
219 return pool.storeErr(e, capi.SQLITE_IOERR);
220 }
221 }
222 return 0;
223 },
224 xDeviceCharacteristics: function(pFile){
225 return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
226 },
227 xFileControl: function(pFile, opId, pArg){
228 return capi.SQLITE_NOTFOUND;
229 },
230 xFileSize: function(pFile,pSz64){
231 const pool = getPoolForPFile(pFile);
232 pool.log(`xFileSize`);
233 const file = pool.getOFileForS3File(pFile);
234 const size = file.sah.getSize() - HEADER_OFFSET_DATA;
235 //log(`xFileSize ${file.path} ${size}`);
236 wasm.poke64(pSz64, BigInt(size));
237 return 0;
238 },
239 xLock: function(pFile,lockType){
240 const pool = getPoolForPFile(pFile);
241 pool.log(`xLock ${lockType}`);
242 pool.storeErr();
243 const file = pool.getOFileForS3File(pFile);
244 return pool.lockFile(file, lockType);
245 },
246 xRead: function(pFile,pDest,n,offset64){
247 const pool = getPoolForPFile(pFile);
248 pool.storeErr();
249 const file = pool.getOFileForS3File(pFile);
250 pool.log(`xRead ${file.path} ${n} @ ${offset64}`);
251 try {
252 const nRead = file.sah.read(
253 wasm.heap8u().subarray(Number(pDest), Number(pDest)+n),
254 {at: HEADER_OFFSET_DATA + Number(offset64)}
255 );
256 if(nRead < n){
257 wasm.heap8u().fill(0, Number(pDest) + nRead, Number(pDest) + n);
258 return capi.SQLITE_IOERR_SHORT_READ;
259 }
260 return 0;
261 }catch(e){
262 return pool.storeErr(e, capi.SQLITE_IOERR);
263 }
264 },
265 xSectorSize: function(pFile){
266 return SECTOR_SIZE;
267 },
268 xSync: function(pFile,flags){
269 const pool = getPoolForPFile(pFile);
270 pool.log(`xSync ${flags}`);
271 pool.storeErr();
272 const file = pool.getOFileForS3File(pFile);
273 //log(`xSync ${file.path} ${flags}`);
274 try{
275 file.sah.flush();
276 return 0;
277 }catch(e){
278 return pool.storeErr(e, capi.SQLITE_IOERR);
279 }
280 },
281 xTruncate: function(pFile,sz64){
282 const pool = getPoolForPFile(pFile);
283 pool.log(`xTruncate ${sz64}`);
284 pool.storeErr();
285 const file = pool.getOFileForS3File(pFile);
286 //log(`xTruncate ${file.path} ${iSize}`);
287 try{
288 file.sah.truncate(HEADER_OFFSET_DATA + Number(sz64));
289 return 0;
290 }catch(e){
291 return pool.storeErr(e, capi.SQLITE_IOERR);
292 }
293 },
294 xUnlock: function(pFile,lockType){
295 const pool = getPoolForPFile(pFile);
296 pool.log('xUnlock');
297 const file = pool.getOFileForS3File(pFile);
298 pool.unlockFile(file, lockType);
299 return 0;
300 },
301 xWrite: function(pFile,pSrc,n,offset64){
302 const pool = getPoolForPFile(pFile);
303 pool.storeErr();
304 const file = pool.getOFileForS3File(pFile);
305 pool.log(`xWrite ${file.path} ${n} ${offset64}`);
306 try{
307 const nBytes = file.sah.write(
308 wasm.heap8u().subarray(Number(pSrc), Number(pSrc)+n),
309 { at: HEADER_OFFSET_DATA + Number(offset64) }
310 );
311 return n===nBytes ? 0 : toss("Unknown write() failure.");
312 }catch(e){
313 return pool.storeErr(e, capi.SQLITE_IOERR);
314 }
315 }
316 }/*ioMethods*/;
317
318 const opfsIoMethods = new capi.sqlite3_io_methods();
319 opfsIoMethods.$iVersion = 1;
320 sqlite3.vfs.installVfs({
321 io: {struct: opfsIoMethods, methods: ioMethods}
322 });
323
324 /**
325 Impls for the sqlite3_vfs methods. Maintenance reminder: members
326 are in alphabetical order to simplify finding them.
327 */
328 const vfsMethods = {
329 xAccess: function(pVfs,zName,flags,pOut){
330 //log(`xAccess ${wasm.cstrToJs(zName)}`);
331 const pool = getPoolForVfs(pVfs);
332 pool.storeErr();
333 try{
334 const name = pool.getPath(zName);
335 wasm.poke32(pOut, pool.hasFilename(name) ? 1 : 0);
336 }catch(e){
337 /*ignored*/
338 wasm.poke32(pOut, 0);
339 }
340 return 0;
341 },
342 xCurrentTime: function(pVfs,pOut){
343 wasm.poke(pOut, 2440587.5 + (new Date().getTime()/86400000),
344 'double');
345 return 0;
346 },
347 xCurrentTimeInt64: function(pVfs,pOut){
348 wasm.poke(pOut, (2440587.5 * 86400000) + new Date().getTime(),
349 'i64');
350 return 0;
351 },
352 xDelete: function(pVfs, zName, doSyncDir){
353 const pool = getPoolForVfs(pVfs);
354 pool.log(`xDelete ${wasm.cstrToJs(zName)}`);
355 pool.storeErr();
356 try{
357 pool.deletePath(pool.getPath(zName));
358 return 0;
359 }catch(e){
360 pool.storeErr(e);
361 return capi.SQLITE_IOERR_DELETE;
362 }
363 },
364 xFullPathname: function(pVfs,zName,nOut,pOut){
365 //const pool = getPoolForVfs(pVfs);
366 //pool.log(`xFullPathname ${wasm.cstrToJs(zName)}`);
367 const i = wasm.cstrncpy(pOut, zName, nOut);
368 return i<nOut ? 0 : capi.SQLITE_CANTOPEN;
369 },
370 xGetLastError: function(pVfs,nOut,pOut){
371 const pool = getPoolForVfs(pVfs);
372 const e = pool.popErr();
373 pool.log(`xGetLastError ${nOut} e =`,e);
374 if(e){
375 const scope = wasm.scopedAllocPush();
376 try{
377 const [cMsg, n] = wasm.scopedAllocCString(e.message, true);
378 wasm.cstrncpy(pOut, cMsg, nOut);
379 if(n > nOut) wasm.poke8(wasm.ptr.add(pOut,nOut,-1), 0);
380 }catch(e){
381 return capi.SQLITE_NOMEM;
382 }finally{
383 wasm.scopedAllocPop(scope);
384 }
385 }
386 return e ? (e.sqlite3Rc || capi.SQLITE_IOERR) : 0;
387 },
388 //xSleep is optionally defined below
389 xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){
390 const pool = getPoolForVfs(pVfs);
391 try{
392 flags &= ~FLAG_COMPUTE_DIGEST_V2;
393 pool.log(`xOpen ${wasm.cstrToJs(zName)} ${flags}`);
394 // First try to open a path that already exists in the file system.
395 const path = (zName && wasm.peek8(zName))
396 ? pool.getPath(zName)
397 : getRandomName();
398 let sah = pool.getSAHForPath(path);
399 if(sah && (flags & capi.SQLITE_OPEN_CREATE)
400 && (flags & capi.SQLITE_OPEN_EXCLUSIVE)){
401 toss('file already exists:', path);
402 }
403 if(!sah && (flags & capi.SQLITE_OPEN_CREATE)) {
404 // File not found so try to create it.
405 if(pool.getFileCount() < pool.getCapacity()) {
406 // Choose an unassociated OPFS file from the pool.
407 sah = pool.nextAvailableSAH();
408 pool.setClientPath(sah, path, flags);
409 }else{
410 // File pool is full.
411 toss('SAH pool is full. Cannot create file',path);
412 }
413 }
414 if(!sah){
415 toss('file not found:',path);
416 }
417 // Subsequent I/O methods are only passed the sqlite3_file
418 // pointer, so map the relevant info we need to that pointer.
419 const file = {path, flags, sah};
420 pool.mapS3FileToOFile(pFile, file);
421 file.lockType = capi.SQLITE_LOCK_NONE;
422 const sq3File = new capi.sqlite3_file(pFile);
423 sq3File.$pMethods = opfsIoMethods.pointer;
424 sq3File.dispose();
425 wasm.poke32(pOutFlags, flags);
426 return 0;
427 }catch(e){
428 pool.storeErr(e);
429 return capi.SQLITE_CANTOPEN;
430 }
431 }/*xOpen()*/
432 }/*vfsMethods*/;
433
434 /**
435 Creates, initializes, and returns an sqlite3_vfs instance for an
436 OpfsSAHPool. The argument is the VFS's name (JS string).
437
438 Throws if the VFS name is already registered or if something
439 goes terribly wrong via sqlite3.vfs.installVfs().
440
441 Maintenance reminder: the only detail about the returned object
442 which is specific to any given OpfsSAHPool instance is the $zName
443 member. All other state is identical.
444 */
445 const createOpfsVfs = function(vfsName){
446 if( sqlite3.capi.sqlite3_vfs_find(vfsName)){
447 toss3("VFS name is already registered:", vfsName);
448 }
449 const opfsVfs = new capi.sqlite3_vfs();
450 /* We fetch the default VFS so that we can inherit some
451 methods from it. */
452 const pDVfs = capi.sqlite3_vfs_find(null);
453 const dVfs = pDVfs
454 ? new capi.sqlite3_vfs(pDVfs)
455 : null /* dVfs will be null when sqlite3 is built with
456 SQLITE_OS_OTHER. */;
457 opfsVfs.$iVersion = 2/*yes, two*/;
458 opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
459 opfsVfs.$mxPathname = HEADER_MAX_PATH_SIZE;
460 opfsVfs.addOnDispose(
461 opfsVfs.$zName = wasm.allocCString(vfsName),
462 ()=>setPoolForVfs(opfsVfs.pointer, 0)
463 );
464
465 if(dVfs){
466 /* Inherit certain VFS members from the default VFS,
467 if available. */
468 opfsVfs.$xRandomness = dVfs.$xRandomness;
469 dVfs.dispose();
470 }
471 if(!opfsVfs.$xRandomness && !vfsMethods.xRandomness){
472 /* If the default VFS has no xRandomness(), add a basic JS impl... */
473 vfsMethods.xRandomness = function(pVfs, nOut, pOut){
474 const heap = wasm.heap8u();
475 let i = 0;
476 const npOut = Number(pOut);
477 for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF;
478 return i;
479 };
480 }
481 /**
482 This VFS's xSleep() must be a no-op. In this environment,
483 only db handles within the same thread can ever come into
484 contention, and that contention cannot be resolved if
485 one of the handles sleeps in that same thread.
486 See also: forum:3f0794c5d8
487 */
488 vfsMethods.xSleep = (pVfs,ms)=>0;
489 sqlite3.vfs.installVfs({
490 vfs: {struct: opfsVfs, methods: vfsMethods}
491 });
492 return opfsVfs;
493 };
494
495 /**
496 Class for managing OPFS-related state for the OPFS
497 SharedAccessHandle Pool sqlite3_vfs. This class is
498 internal-use-only, never exposed to the client. OpfsSAHPoolUtil
499 is the public-facing part.
500 */
501 class OpfsSAHPool {
502 /* OPFS dir in which VFS metadata is stored. */
503 vfsDir;
504 /* Directory handle to this.vfsDir. */
505 #dhVfsRoot;
506 /* Directory handle to the subdir of this.#dhVfsRoot which holds
507 the randomly-named "opaque" files. This subdir exists in the
508 hope that we can eventually support client-created files in
509 this.#dhVfsRoot. */
510 #dhOpaque;
511 /* Directory handle to this.dhVfsRoot's parent dir. Needed
512 for a VFS-wipe op. */
513 #dhVfsParent;
514 /* Maps SAHs to their opaque file names. */
515 #mapSAHToName = new Map();
516 /* Maps client-side file names to SAHs. */
517 #mapFilenameToSAH = new Map();
518 /* Set of currently-unused SAHs. */
519 #availableSAH = new Set();
520 /* Maps (sqlite3_file*) to xOpen's file objects. */
521 #mapS3FileToOFile = new Map();
522 /* Maps client-side file names to the lock state of the files
523 opened via this pool: {nShared, lockType}, modelled after
524 os_unix.c:unixInodeInfo. */
525 #mapPathToLock = new Map();
526
527 /* Maps SAH to an abstract File Object which contains
528 various metadata about that handle. */
529
530 /** Buffer used by [sg]etClientPath(). */
531 #apBody = new Uint8Array(HEADER_CORPUS_SIZE);
532 // DataView for this.#apBody
533 #dvBody;
534
535 // associated sqlite3_vfs instance
536 #cVfs;
537
538 // Logging verbosity. See optionDefaults.verbosity.
539 #verbosity;
540
541 /**
542 Options are documented in installOpfsSAHPoolVfs().
543 */
544 constructor(options = Object.create(null)){
545 this.#verbosity = options.verbosity ?? optionDefaults.verbosity;
546 this.vfsName = options.name || optionDefaults.name;
547 this.#cVfs = createOpfsVfs(this.vfsName);
548 setPoolForVfs(this.#cVfs.pointer, this);
549 this.vfsDir = options.directory || ("."+this.vfsName);
550 this.#dvBody =
551 new DataView(this.#apBody.buffer, this.#apBody.byteOffset);
552 this.isReady = this
553 .reset(!!(options.clearOnInit ?? optionDefaults.clearOnInit))
554 .then(()=>{
555 if(this.$error) throw this.$error;
556 return this.getCapacity()
557 ? Promise.resolve(undefined)
558 : this.addCapacity(options.initialCapacity
559 || optionDefaults.initialCapacity);
560 });
561 }
562
563 #logImpl(level,...args){
564 if(this.#verbosity>level) loggers[level](this.vfsName+":",...args);
565 };
566 log(...args){this.#logImpl(2, ...args)};
567 warn(...args){this.#logImpl(1, ...args)};
568 error(...args){this.#logImpl(0, ...args)};
569
570 /* Design note: at the time this method was added, the developer
571 was unaware that getter syntax was an option: get vfs(){...} */
572 getVfs(){return this.#cVfs}
573
574 /* Current pool capacity. */
575 getCapacity(){return this.#mapSAHToName.size}
576
577 /* Current number of in-use files from pool. */
578 getFileCount(){return this.#mapFilenameToSAH.size}
579
580 /* Returns an array of the names of all
581 currently-opened client-specified filenames. */
582 getFileNames(){
583 const rc = [];
584 for(const n of this.#mapFilenameToSAH.keys()) rc.push(n);
585 return rc;
586 }
587
588 /**
589 Adds n files to the pool's capacity. This change is
590 persistent across settings. Returns a Promise which resolves
591 to the new capacity.
592 */
593 async addCapacity(n){
594 for(let i = 0; i < n; ++i){
595 const name = getRandomName();
596 const h = await this.#dhOpaque.getFileHandle(name, {create:true});
597 const ah = await h.createSyncAccessHandle();
598 this.#mapSAHToName.set(ah,name);
599 this.setClientPath(ah, '', 0);
600 //this.#createFileObject(ah,undefined,name);
601 }
602 return this.getCapacity();
603 }
604
605 /**
606 Reduce capacity by n, but can only reduce up to the limit of
607 currently-available SAHs. Returns a Promise which resolves to
608 the number of slots really removed. Throws if removal of an
609 OPFS filesystem entry fails for any reason, in which case the
610 VFS itself is left in a well-defined state, possibly partially
611 reduced in capacity compared to before this call, but the file
612 which was unable to be removed is in an undefined state. It may
613 be orphaned and/or later recycled.
614
615 As of 3.54, throws if n is an invalid value. Prior to that
616 an invalid value could cause it to remove all entries.
617 */
618 async reduceCapacity(n){
619 if(!Number.isSafeInteger(n) || n < 0){
620 toss('Invalid capacity reduction:', n);
621 }
622 let nRm = 0;
623 for(const ah of Array.from(this.#availableSAH)){
624 if(nRm === n || this.getFileCount() === this.getCapacity()){
625 break;
626 }
627 const name = this.#mapSAHToName.get(ah);
628 ah.close();
629 this.#mapSAHToName.delete(ah);
630 this.#availableSAH.delete(ah);
631 await this.#dhOpaque.removeEntry(name);
632 //#if 0
633 /* removeEntry() may throw, in which case the storage is in an
634 undefined state and that particular file name might or
635 might not work ever again. One suggestion contributed
636 off-list is that when removeEntry() throws, we re-animate
637 the entry:
638
639 ah.close();
640 try {
641 await this.#dhOpaque.removeEntry(name);
642 } catch (e) {
643 this.#mapSAHToName.delete(ah);
644 this.#availableSAH.delete(ah);
645 const h = await this.#dhOpaque.getFileHandle(name);
646 const restored = await h.createSyncAccessHandle();
647 this.#mapSAHToName.set(restored, name);
648 this.#availableSAH.add(restored);
649 throw e;
650 }
651 this.#mapSAHToName.delete(ah);
652 this.#availableSAH.delete(ah);
653
654 But that feels like a bigger minefield than the current
655 approach, in particular given the very, very niche use
656 cases for this function.
657 */
658 //#/if
659 ++nRm;
660 }
661 return nRm;
662 }
663
664 /**
665 Releases all currently-opened SAHs. The only legal operation
666 after this is acquireAccessHandles() or (if this is called from
667 pauseVfs()) either of isPaused() or unpauseVfs().
668 */
669 releaseAccessHandles(){
670 for(const ah of this.#mapSAHToName.keys()) ah.close();
671 this.#mapSAHToName.clear();
672 this.#mapFilenameToSAH.clear();
673 this.#availableSAH.clear();
674 this.#mapS3FileToOFile.clear();
675 this.#mapPathToLock.clear();
676 }
677
678 /**
679 Opens all files under this.vfsDir/this.#dhOpaque and acquires a
680 SAH for each. Returns a Promise which resolves to no value but
681 completes once all SAHs are acquired. If acquiring an SAH
682 throws, this.$error will contain the corresponding Error
683 object.
684
685 If it throws, it waits for every pending acquisition to settle,
686 then releases all SAHs it acquired, leaving the VFS in a
687 well-defined but unusable state.
688
689 If clearFiles is true, the client-stored state of each file is
690 cleared when its handle is acquired, including its name, flags,
691 and any data stored after the metadata block.
692 */
693 async acquireAccessHandles(clearFiles=false){
694 const files = [];
695 for await (const [name,h] of this.#dhOpaque){
696 if('file'===h.kind){
697 files.push([name,h]);
698 }
699 }
700 const results = await Promise.allSettled(files.map(async([name,h])=>{
701 const ah = await h.createSyncAccessHandle()
702 this.#mapSAHToName.set(ah, name);
703 if(clearFiles){
704 ah.truncate(HEADER_OFFSET_DATA);
705 this.setClientPath(ah, '', 0);
706 }else{
707 const path = this.getClientPath(ah);
708 if(path){
709 this.#mapFilenameToSAH.set(path, ah);
710 }else{
711 this.#availableSAH.add(ah);
712 }
713 }
714 }));
715 const failure = results.find((r)=>'rejected'===r.status)
716 /* If any failures are found then clean up and re-throw the
717 first one. We "could" record them all but we can only throw
718 one of them (or an exception wrapping all of them, which
719 seems unnecessary). */;
720 if( failure ){
721 this.storeErr(failure.reason);
722 this.releaseAccessHandles();
723 throw failure.reason;
724 }
725 }
726
727 /**
728 Given an SAH, returns the client-specified name of
729 that file by extracting it from the SAH's header.
730
731 On error it disassociates SAH from the pool and returns an
732 empty string. Propagates any exceptions from the SAH API and
733 throws for short header reads.
734 */
735 getClientPath(sah){
736 const nRead = sah.read(this.#apBody, {at: 0});
737 const nSah = sah.getSize();
738 const minSz = Math.min(this.#apBody.byteLength, nSah);
739 if( nRead<minSz ){
740 toss("OPFSSAHPool[",this.vfsName,"]: Short header read:",
741 nRead,"of", minSz," bytes");
742 }
743 // Delete any unexpected files left over by previous
744 // untimely errors, recovering when we can...
745 const flags = this.#dvBody.getUint32(HEADER_OFFSET_FLAGS);
746 const nPath = this.#apBody.indexOf(0);
747 if( nPath>0
748 && nSah>HEADER_OFFSET_DATA
749 && 0===(flags & capi.SQLITE_OPEN_DELETEONCLOSE) ){
750 /* This entry's header has presumably been "torn" by untimely
751 death during a write, but we can recover from that.
752 Discussion: bugs:7418667df7 */
753 return textDecoder.decode(this.#apBody.subarray(0, nPath));
754 }
755 if(this.#apBody[0] &&
756 ((flags & capi.SQLITE_OPEN_DELETEONCLOSE) ||
757 (flags & PERSISTENT_FILE_TYPES)===0)){
758 warn(`Removing file with unexpected flags ${flags.toString(16)}`,
759 this.#apBody);
760 this.setClientPath(sah, '', 0);
761 return '';
762 }
763 const fileDigest = new Uint32Array(HEADER_DIGEST_SIZE / 4);
764 sah.read(fileDigest, {at: HEADER_OFFSET_DIGEST});
765 const compDigest = this.computeDigest(this.#apBody, flags);
766 //warn("getClientPath() flags",'0x'+flags.toString(16), "compDigest", compDigest);
767 if(fileDigest.every((v,i) => v===compDigest[i])){
768 // Valid digest
769 if(0===nPath){
770 // This file is unassociated, so truncate it to avoid
771 // leaving stale db data laying around.
772 sah.truncate(HEADER_OFFSET_DATA);
773 }
774 //warn("getClientPath() flags",'0x'+flags.toString(16), "compDigest", compDigest,"nPath",nPath);
775 return nPath
776 ? textDecoder.decode(this.#apBody.subarray(0, nPath))
777 : '';
778 }else{
779 // Invalid digest
780 warn('Disassociating file with bad digest.');
781 this.setClientPath(sah, '', 0);
782 return '';
783 }
784 }
785
786 /**
787 Stores the given client-defined path and SQLITE_OPEN_xyz flags
788 into the given SAH. If path is an empty string then the file is
789 disassociated from the pool but its previous name is preserved
790 in the metadata.
791
792 If nameToRemove is truthy then it must be the "old" name when path
793 is falsy. This function removes the mapping of that name to an
794 SAH.
795 */
796 setClientPath(sah, path, flags, nameToRemove){
797 const enc = textEncoder.encodeInto(path, this.#apBody);
798 if(HEADER_MAX_PATH_SIZE <= enc.written + 1/*NUL byte*/){
799 toss("Path too long:",path);
800 }
801 if(path && flags){
802 /* When creating or re-writing files, update their digest, if
803 needed, to v2. We continue to use v1 for the (!path) case
804 (empty files) because there's little reason not to use a
805 digest of 0 for empty entries. */
806 flags |= FLAG_COMPUTE_DIGEST_V2;
807 }
808 this.#apBody.fill(0, enc.written, HEADER_MAX_PATH_SIZE);
809 this.#dvBody.setUint32(HEADER_OFFSET_FLAGS, flags);
810 const digest = this.computeDigest(this.#apBody, flags);
811 //console.warn("setClientPath(",path,") digest",digest);
812 sah.write(this.#apBody, {at: 0});
813 if(nameToRemove){
814 /* The placement of this is very specific: between the above
815 write and the digest. If the above write fails,
816 nameToRemove remains in the mapping pool. If it succeeds,
817 nameToRemove is no longer available and needs to be removed
818 from the SAH mapping. If the write() _below_ fails, that
819 leaves us with a consistent world view.
820
821 Discussion: bugs:432f260aa787a53 */
822 this.#mapFilenameToSAH.delete(nameToRemove);
823 }
824 sah.write(digest, {at: HEADER_OFFSET_DIGEST});
825 sah.flush();
826
827 if(path){
828 this.#mapFilenameToSAH.set(path, sah);
829 this.#availableSAH.delete(sah);
830 }else{
831 // This is not a persistent file, so eliminate the contents.
832 sah.truncate(HEADER_OFFSET_DATA);
833 this.#availableSAH.add(sah);
834 }
835 }
836
837 /**
838 Computes a digest for the given byte array and returns it as a
839 two-element Uint32Array. This digest gets stored in the
840 metadata for each file as a validation check. Changing this
841 algorithm invalidates all existing databases for this VFS, so
842 don't do that.
843
844 See the docs for FLAG_COMPUTE_DIGEST_V2 for more details.
845 */
846 computeDigest(byteArray, fileFlags){
847 if( fileFlags & FLAG_COMPUTE_DIGEST_V2 ){
848 let h1 = 0xdeadbeef;
849 let h2 = 0x41c6ce57;
850 for(const v of byteArray){
851 h1 = Math.imul(h1 ^ v, 2654435761);
852 h2 = Math.imul(h2 ^ v, 104729);
853 }
854 return new Uint32Array([h1>>>0, h2>>>0]);
855 }else{
856 /* this is what the buggy legacy computation worked out to */
857 return new Uint32Array([0,0]);
858 }
859 }
860
861 /**
862 Re-initializes the state of the SAH pool, releasing and
863 re-acquiring all handles.
864
865 See acquireAccessHandles() for the specifics of the clearFiles
866 argument.
867 */
868 async reset(clearFiles){
869 await this.isReady;
870 let h = await navigator.storage.getDirectory();
871 let prev, prevName;
872 for(const d of this.vfsDir.split('/')){
873 if(d){
874 prev = h;
875 h = await h.getDirectoryHandle(d,{create:true});
876 }
877 }
878 this.#dhVfsRoot = h;
879 this.#dhVfsParent = prev;
880 this.#dhOpaque = await this.#dhVfsRoot.getDirectoryHandle(
881 OPAQUE_DIR_NAME,{create:true}
882 );
883 this.releaseAccessHandles();
884 return this.acquireAccessHandles(clearFiles);
885 }
886
887 /**
888 Returns the pathname part of the given argument,
889 which may be any of:
890
891 - a URL object
892 - A JS string representing a file name
893 - Wasm C-string representing a file name
894
895 All "../" parts and duplicate slashes are resolve/removed from
896 the returned result.
897 */
898 getPath(arg) {
899 if(wasm.isPtr(arg)) arg = wasm.cstrToJs(arg);
900 return ((arg instanceof URL)
901 ? arg
902 : new URL(arg, 'file://localhost/')).pathname;
903 }
904
905 /**
906 Removes the association of the given client-specified file
907 name (JS string) from the pool. Returns true if a mapping
908 is found, else false.
909 */
910 deletePath(path) {
911 const sah = this.#mapFilenameToSAH.get(path);
912 if(sah) {
913 this.setClientPath(sah, '', 0, path);
914 }
915 return !!sah;
916 }
917
918 /**
919 Sets e (an Error object) as this object's current error. Pass a
920 falsy (or no) value to clear it. If code is truthy it is
921 assumed to be an SQLITE_xxx result code, defaulting to
922 SQLITE_IOERR if code is falsy.
923
924 Returns the 2nd argument.
925 */
926 storeErr(e,code){
927 if(e){
928 e.sqlite3Rc = code || capi.SQLITE_IOERR;
929 this.error(e);
930 }
931 this.$error = e;
932 return code;
933 }
934 /**
935 Pops this object's Error object and returns
936 it (a falsy value if no error is set).
937 */
938 popErr(){
939 const rc = this.$error;
940 this.$error = undefined;
941 return rc;
942 }
943
944 /**
945 Returns the next available SAH without removing
946 it from the set.
947 */
948 nextAvailableSAH(){
949 const [rc] = this.#availableSAH.keys();
950 return rc;
951 }
952
953 /**
954 Given an (sqlite3_file*), returns the mapped
955 xOpen file object.
956 */
957 getOFileForS3File(pFile){
958 return this.#mapS3FileToOFile.get(pFile);
959 }
960 /**
961 Maps or unmaps (if file is falsy) the given (sqlite3_file*)
962 to an xOpen file object and to this pool object.
963 */
964 mapS3FileToOFile(pFile,file){
965 if(file){
966 this.#mapS3FileToOFile.set(pFile, file);
967 setPoolForPFile(pFile, this);
968 }else{
969 this.#mapS3FileToOFile.delete(pFile);
970 setPoolForPFile(pFile, false);
971 }
972 }
973
974 /**
975 Returns true if the given client-defined file name is in this
976 object's name-to-SAH map.
977 */
978 hasFilename(name){
979 return this.#mapFilenameToSAH.has(name)
980 }
981
982 /**
983 Returns the SAH associated with the given
984 client-defined file name.
985 */
986 getSAHForPath(path){
987 return this.#mapFilenameToSAH.get(path);
988 }
989
990 /**
991 Removes this object's sqlite3_vfs registration and shuts down
992 this object, releasing all handles, mappings, and whatnot,
993 including deleting its data directory. There is currently no
994 way to "revive" the object and reaquire its
995 resources. Similarly, there is no recovery strategy if removal
996 of any given SAH fails, so such errors are ignored by this
997 function.
998
999 This function is intended primarily for testing.
1000
1001 Resolves to true if it did its job, false if the
1002 VFS has already been shut down.
1003
1004 @see pauseVfs()
1005 @see unpauseVfs()
1006 */
1007 async removeVfs(){
1008 if(!this.#cVfs.pointer || !this.#dhOpaque) return false;
1009 capi.sqlite3_vfs_unregister(this.#cVfs.pointer);
1010 this.#cVfs.dispose();
1011 delete initPromises[this.vfsName];
1012 try{
1013 this.releaseAccessHandles();
1014 await this.#dhVfsRoot.removeEntry(OPAQUE_DIR_NAME, {recursive: true});
1015 this.#dhOpaque = undefined;
1016 await this.#dhVfsParent.removeEntry(
1017 this.#dhVfsRoot.name, {recursive: true}
1018 );
1019 this.#dhVfsRoot = this.#dhVfsParent = undefined;
1020 }catch(e){
1021 sqlite3.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",e);
1022 /*otherwise ignored - there is no recovery strategy*/
1023 }
1024 return true;
1025 }
1026
1027 /**
1028 "Pauses" this VFS by unregistering it from SQLite and
1029 relinquishing all open SAHs, leaving the associated files
1030 intact. If this object is already paused, this is a
1031 no-op. Returns this object.
1032
1033 This function throws if SQLite has any opened file handles
1034 hosted by this VFS, as the alternative would be to invoke
1035 Undefined Behavior by closing file handles out from under the
1036 library. Similarly, automatically closing any database handles
1037 opened by this VFS would invoke Undefined Behavior in
1038 downstream code which is holding those pointers.
1039
1040 If this function throws due to open file handles then it has
1041 no side effects. If the OPFS API throws while closing handles
1042 then the VFS is left in an undefined state.
1043
1044 @see isPaused()
1045 @see unpauseVfs()
1046 */
1047 pauseVfs(){
1048 if(this.#mapS3FileToOFile.size>0){
1049 sqlite3.SQLite3Error.toss(
1050 capi.SQLITE_MISUSE, "Cannot pause VFS",
1051 this.vfsName,"because it has opened files."
1052 );
1053 }
1054 if(this.#mapSAHToName.size>0){
1055 capi.sqlite3_vfs_unregister(this.vfsName);
1056 this.releaseAccessHandles();
1057 }
1058 return this;
1059 }
1060
1061 /**
1062 Returns true if this pool is currently paused else false.
1063
1064 @see pauseVfs()
1065 @see unpauseVfs()
1066 */
1067 isPaused(){
1068 return 0===this.#mapSAHToName.size;
1069 }
1070
1071 /**
1072 "Unpauses" this VFS, reacquiring all SAH's and (if successful)
1073 re-registering it with SQLite. This is a no-op if the VFS is
1074 not currently paused.
1075
1076 The returned Promise resolves to this object. See
1077 acquireAccessHandles() for how it behaves if it throws due to
1078 SAH acquisition failure.
1079
1080 @see isPaused()
1081 @see pauseVfs()
1082 */
1083 async unpauseVfs(){
1084 if(0===this.#mapSAHToName.size){
1085 return this.acquireAccessHandles(false).
1086 then(()=>capi.sqlite3_vfs_register(this.#cVfs, 0),this);
1087 }
1088 return this;
1089 }
1090
1091 //! Documented elsewhere in this file.
1092 exportFile(name){
1093 const sah = this.#mapFilenameToSAH.get(name) || toss("File not found:",name);
1094 const n = sah.getSize() - HEADER_OFFSET_DATA;
1095 const b = new Uint8Array(n>0 ? n : 0);
1096 if(n>0){
1097 const nRead = sah.read(b, {at: HEADER_OFFSET_DATA});
1098 if(nRead != n){
1099 toss("Expected to read "+n+" bytes but read "+nRead+".");
1100 }
1101 }
1102 return b;
1103 }
1104
1105 //! Impl for importDb() when its 2nd arg is a function.
1106 async importDbChunked(name, callback){
1107 const sah = this.#mapFilenameToSAH.get(name)
1108 || this.nextAvailableSAH()
1109 || toss("No available handles to import to.");
1110 sah.truncate(0);
1111 let nWrote = 0, chunk, checkedHeader = false, err = false;
1112 try{
1113 while( undefined !== (chunk = await callback()) ){
1114 if(chunk instanceof ArrayBuffer) chunk = new Uint8Array(chunk);
1115 if( !checkedHeader && 0===nWrote && chunk.byteLength>=15 ){
1116 util.affirmDbHeader(chunk);
1117 checkedHeader = true;
1118 }
1119 const n = sah.write(chunk, {at: HEADER_OFFSET_DATA + nWrote});
1120 if( n!==chunk.byteLength ){
1121 toss("Expected to write "+chunk.byteLength+
1122 "bytes but wrote"+n+".");
1123 }
1124 nWrote += chunk.byteLength;
1125 }
1126 if( nWrote < 512 || 0!==nWrote % 512 ){
1127 toss("Input size",nWrote,"is not correct for an SQLite database.");
1128 }
1129 if( !checkedHeader ){
1130 const header = new Uint8Array(20);
1131 sah.read( header, {at: HEADER_OFFSET_DATA} );
1132 util.affirmDbHeader( header );
1133 }
1134 sah.write(new Uint8Array([1,1]), {
1135 at: HEADER_OFFSET_DATA + 18
1136 }/*force db out of WAL mode*/);
1137 }catch(e){
1138 this.setClientPath(sah, '', 0);
1139 throw e;
1140 }
1141 this.setClientPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
1142 return nWrote;
1143 }
1144
1145 //! Documented elsewhere in this file.
1146 importDb(name, bytes){
1147 if( bytes instanceof ArrayBuffer ) bytes = new Uint8Array(bytes);
1148 else if( bytes instanceof Function ) return this.importDbChunked(name, bytes);
1149 util.affirmIsDb(bytes);
1150 const sah = this.#mapFilenameToSAH.get(name)
1151 || this.nextAvailableSAH()
1152 || toss("No available handles to import to.");
1153 const n = bytes.byteLength;
1154 const nWrote = sah.write(bytes, {at: HEADER_OFFSET_DATA});
1155 if(nWrote != n){
1156 this.setClientPath(sah, '', 0);
1157 toss("Expected to write "+n+" bytes but wrote "+nWrote+".");
1158 }else{
1159 sah.truncate(HEADER_OFFSET_DATA + n
1160 /* Ensure no trailing junk when overwriting an
1161 existing file with a shorter one. */);
1162 sah.write(new Uint8Array([1,1]), {at: HEADER_OFFSET_DATA+18}
1163 /* force db out of WAL mode */);
1164 this.setClientPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
1165 }
1166 return nWrote;
1167 }
1168
1169 /**
1170 Returns true if any (sqlite3_file*) currently opened by this
1171 pool using the given client-provided file name (as distinct from
1172 its opaque name) holds a RESERVED or greater lock, else false.
1173 */
1174 hasReservedLock(filename){
1175 const lk = this.#mapPathToLock.get(filename);
1176 return !!lk && lk.lockType>capi.SQLITE_LOCK_SHARED;
1177 }
1178
1179 /**
1180 Implements xLock() for the given xOpen-generated file object.
1181 This pool holds its SAHs exclusively, so its xOpen() represent
1182 the only connections to a given file. The locks are held
1183 separately from their file object in the same thread the same
1184 way in which os_unix.c:unixLock() distinguishes multiple
1185 connections of a single process which share an inode: a lock
1186 which conflicts with another connection's lock fails with
1187 SQLITE_BUSY, and a failed attempt to get from RESERVED to
1188 EXCLUSIVE leaves a PENDING lock, which admits no new SHARED
1189 locks.
1190 */
1191 lockFile(file, lockType){
1192 if(file.lockType>=lockType) return 0;
1193 let lk = this.#mapPathToLock.get(file.path);
1194 if(!lk){
1195 lk = Object.assign(Object.create(null),{
1196 nShared: 0, lockType: capi.SQLITE_LOCK_NONE
1197 });
1198 this.#mapPathToLock.set(file.path, lk);
1199 }
1200 if(file.lockType!==lk.lockType
1201 && (lk.lockType>=capi.SQLITE_LOCK_PENDING
1202 || lockType>capi.SQLITE_LOCK_SHARED)){
1203 return capi.SQLITE_BUSY;
1204 }
1205 if(lockType===capi.SQLITE_LOCK_SHARED){
1206 ++lk.nShared;
1207 if(lk.lockType===capi.SQLITE_LOCK_NONE) lk.lockType = lockType;
1208 }else if(lockType===capi.SQLITE_LOCK_EXCLUSIVE && lk.nShared>1){
1209 if(file.lockType===capi.SQLITE_LOCK_RESERVED){
1210 file.lockType = lk.lockType = capi.SQLITE_LOCK_PENDING;
1211 }
1212 return capi.SQLITE_BUSY;
1213 }else{
1214 lk.lockType = lockType;
1215 }
1216 file.lockType = lockType;
1217 return 0;
1218 }
1219
1220 /** Implements xUnlock() for the given xOpen file object. */
1221 unlockFile(file, lockType){
1222 if(file.lockType<=lockType) return;
1223 const lk = this.#mapPathToLock.get(file.path);
1224 if(file.lockType>capi.SQLITE_LOCK_SHARED){
1225 lk.lockType = capi.SQLITE_LOCK_SHARED;
1226 }
1227 if(lockType===capi.SQLITE_LOCK_NONE && 0===--lk.nShared
1228 /* Maintenance reminder: the && ordering is significant */){
1229 this.#mapPathToLock.delete(file.path);
1230 }
1231 file.lockType = lockType;
1232 }
1233
1234 }/*class OpfsSAHPool*/;
1235
1236 /**
1237 A OpfsSAHPoolUtil instance is exposed to clients in order to
1238 manipulate an OpfsSAHPool object without directly exposing that
1239 object and allowing for some semantic changes compared to that
1240 class.
1241
1242 Class docs are in the client-level docs for
1243 installOpfsSAHPoolVfs().
1244 */
1245 class OpfsSAHPoolUtil {
1246 /* This object's associated OpfsSAHPool. */
1247 #p;
1248
1249 constructor(sahPool){
1250 this.#p = sahPool;
1251 this.vfsName = sahPool.vfsName;
1252 }
1253
1254 async addCapacity(n){ return this.#p.addCapacity(n) }
1255
1256 async reduceCapacity(n){ return this.#p.reduceCapacity(n) }
1257
1258 getCapacity(){ return this.#p.getCapacity(this.#p) }
1259
1260 getFileCount(){ return this.#p.getFileCount() }
1261 getFileNames(){ return this.#p.getFileNames() }
1262
1263 async reserveMinimumCapacity(min){
1264 const c = this.#p.getCapacity();
1265 return (c < min) ? this.#p.addCapacity(min - c) : c;
1266 }
1267
1268 exportFile(name){ return this.#p.exportFile(name) }
1269
1270 importDb(name, bytes){ return this.#p.importDb(name,bytes) }
1271
1272 async wipeFiles(){ return this.#p.reset(true) }
1273
1274 unlink(filename){ return this.#p.deletePath(filename) }
1275
1276 async removeVfs(){ return this.#p.removeVfs() }
1277
1278 pauseVfs(){ this.#p.pauseVfs(); return this; }
1279 async unpauseVfs(){ return this.#p.unpauseVfs().then(()=>this); }
1280 isPaused(){ return this.#p.isPaused() }
1281
1282 }/* class OpfsSAHPoolUtil */;
1283
1284 /**
1285 Returns a resolved Promise if the current environment
1286 has a "fully-sync" SAH impl, else a rejected Promise.
1287 */
1288 const apiVersionCheck = async ()=>{
1289 const dh = await navigator.storage.getDirectory();
1290 const fn = '.opfs-sahpool-sync-check-'+getRandomName();
1291 const fh = await dh.getFileHandle(fn, { create: true });
1292 const ah = await fh.createSyncAccessHandle();
1293 const close = ah.close();
1294 await close;
1295 await dh.removeEntry(fn);
1296 if(close?.then){
1297 toss("The local OPFS API is too old for opfs-sahpool:",
1298 "it has an async FileSystemSyncAccessHandle.close() method.");
1299 }
1300 return true;
1301 };
1302
1303 /**
1304 installOpfsSAHPoolVfs() asynchronously initializes the OPFS
1305 SyncAccessHandle (a.k.a. SAH) Pool VFS. It returns a Promise which
1306 either resolves to a utility object described below or rejects with
1307 an Error value.
1308
1309 Initialization of this VFS is not automatic because its
1310 registration requires that it lock all resources it
1311 will potentially use, even if client code does not want
1312 to use them. That, in turn, can lead to locking errors
1313 when, for example, one page in a given origin has loaded
1314 this VFS but does not use it, then another page in that
1315 origin tries to use the VFS. If the VFS were automatically
1316 registered, the second page would fail to load the VFS
1317 due to OPFS locking errors.
1318
1319 If this function is called more than once with a given "name"
1320 option (see below), it will return the same Promise. Calls for
1321 different names will return different Promises which resolve to
1322 independent objects and refer to different VFS registrations.
1323
1324 On success, the resulting Promise resolves to a utility object
1325 which can be used to query and manipulate the pool. Its API is
1326 described at the end of these docs.
1327
1328 This function accepts an options object to configure certain
1329 parts but it is only acknowledged for the very first call for
1330 each distinct name and ignored for all subsequent calls with that
1331 same name.
1332
1333 The options, in alphabetical order:
1334
1335 - `clearOnInit`: (default=false) if truthy, contents and filename
1336 mapping are removed from each SAH it is acquired during
1337 initialization of the VFS, leaving the VFS's storage in a pristine
1338 state. Use this only for databases which need not survive a page
1339 reload.
1340
1341 - `initialCapacity`: (default=6) Specifies the default capacity of
1342 the VFS. This should not be set unduly high because the VFS has
1343 to open (and keep open) a file for each entry in the pool. This
1344 setting only has an effect when the pool is initially empty. It
1345 does not have any effect if a pool already exists.
1346
1347 - `directory`: (default="."+`name`) Specifies the OPFS directory
1348 name in which to store metadata for the `"opfs-sahpool"`
1349 sqlite3_vfs. Only one instance of this VFS can be installed per
1350 JavaScript engine, and any two engines with the same storage
1351 directory name will collide with each other, leading to locking
1352 errors and the inability to register the VFS in the second and
1353 subsequent engine. Using a different directory name for each
1354 application enables different engines in the same HTTP origin to
1355 co-exist, but their data are invisible to each other. Changing
1356 this name will effectively orphan any databases stored under
1357 previous names. The default is unspecified but descriptive. This
1358 option may contain multiple path elements, e.g. "foo/bar/baz",
1359 and they are created automatically. In practice there should be
1360 no driving need to change this. ACHTUNG: all files in this
1361 directory are assumed to be managed by the VFS. Do not place
1362 other files in that directory, as they may be deleted or
1363 otherwise modified by the VFS.
1364
1365 - `name`: (default="opfs-sahpool") sets the name to register this
1366 VFS under. Normally this should not be changed, but it is
1367 possible to register this VFS under multiple names so long as
1368 each has its own separate directory to work from. The storage for
1369 each is invisible to all others. The name must be a string
1370 compatible with `sqlite3_vfs_register()` and friends and suitable
1371 for use in URI-style database file names.
1372
1373 Achtung: if a custom `name` is provided, a custom `directory`
1374 must also be provided if any other instance is registered with
1375 the default directory. If no directory is explicitly provided
1376 then a directory name is synthesized from the `name` option.
1377
1378
1379 - `forceReinitIfPreviouslyFailed`: (default=`false`) Is a fallback option
1380 to assist in working around certain flaky environments which may
1381 mysteriously fail to permit access to OPFS sync access handles on
1382 an initial attempt but permit it on a second attemp. This option
1383 should never be used but is provided for those who choose to
1384 throw caution to the wind and trust such environments. If this
1385 option is truthy _and_ the previous attempt to initialize this
1386 VFS with the same `name` failed, the VFS will attempt to
1387 initialize a second time instead of returning the cached
1388 failure. See discussion at
1389 <https://github.com/sqlite/sqlite-wasm/issues/79>
1390
1391 - `preserveOnInitFailure`: (default=`false`) If truthy,
1392 initialization failure unregisters and disposes of the VFS and
1393 releases acquired handles without also deleting its storage. This
1394 does not undo changes already made during initialization,
1395 including `clearOnInit`. Otherwise, initialization failure
1396 invokes this.removeVfs(), which attempts to delete the
1397 pool. Retrying a cached initialization failure requires
1398 `forceReinitIfPreviouslyFailed`. See discussion at
1399 <https://sqlite.org/forum/forumpost/5664cd4baee50236>.
1400
1401
1402 Peculiarities of this VFS vis a vis other SQLite VFSes:
1403
1404 - Paths given to it _must_ be absolute. Relative paths will not
1405 be properly recognized. This is arguably a bug but correcting it
1406 requires some hoop-jumping in routines which have no business
1407 doing such tricks. (2026-01-19 (2.5 years later): the specifics
1408 are lost to history, but this was a side effect of xOpen()
1409 receiving an immutable C-string filename, to which no implicit
1410 "/" can be prefixed without causing a discrepancy between what
1411 the user provided and what the VFS stores. Its conceivable that
1412 that quirk could be glossed over in xFullPathname(), but
1413 regressions when doing so cannot be ruled out, so there are no
1414 current plans to change this behavior.)
1415
1416 - It is possible to install multiple instances under different
1417 names, each sandboxed from one another inside their own private
1418 directory. This feature exists primarily as a way for disparate
1419 applications within a given HTTP origin to use this VFS without
1420 introducing locking issues between them.
1421
1422
1423 The API for the utility object passed on by this function's
1424 Promise, in alphabetical order...
1425
1426 - [async] number addCapacity(n)
1427
1428 Adds `n` entries to the current pool. This change is persistent
1429 across sessions so should not be called automatically at each app
1430 startup (but see `reserveMinimumCapacity()`). Its returned Promise
1431 resolves to the new capacity. Because this operation is necessarily
1432 asynchronous, the C-level VFS API cannot call this on its own as
1433 needed.
1434
1435 - byteArray exportFile(name)
1436
1437 Synchronously reads the contents of the given file into a
1438 Uint8Array and returns it. This will throw if the given name is
1439 not currently in active use or on I/O error. Because of how this
1440 VFS maps names to storage, the given name is _not_ visible
1441 directly in OPFS (or, if it is, it's not from this VFS).
1442
1443 - number getCapacity()
1444
1445 Returns the number of files currently contained in the SAH
1446 pool. The default capacity is only large enough for one or two
1447 databases and their associated temp files.
1448
1449 - number getFileCount()
1450
1451 Returns the number of files from the pool currently allocated to
1452 slots. This is not the same as the files being "opened".
1453
1454 - array getFileNames()
1455
1456 Returns an array of the names of the files currently allocated to
1457 slots. This list is the same length as getFileCount().
1458
1459 - void importDb(name, bytes)
1460
1461 Imports the contents of an SQLite database, provided as a byte
1462 array or ArrayBuffer, under the given name, overwriting any
1463 existing content. Throws if the pool has no available file slots,
1464 on I/O error, or if the input does not appear to be a database.
1465 In the latter case, only a cursory examination is made to
1466 determine whether the input is a db (and only in non-SEE builds,
1467 as we cannot distinguish encrypted DBs from garbage input).
1468
1469 Results are undefined if the given db name refers to an opened
1470 db. This routine is _only_ for importing database files, not
1471 arbitrary files, the reason being that this VFS will
1472 automatically clean up any non-database files so importing them
1473 is pointless.
1474
1475 If passed a function for its second argument, its behavior
1476 changes to asynchronous and it imports its data in chunks fed to
1477 it by the given callback function. It calls the callback (which
1478 may be async) repeatedly, expecting either a Uint8Array or
1479 ArrayBuffer (to denote new input) or undefined (to denote
1480 EOF). For so long as the callback continues to return
1481 non-undefined, it will append incoming data to the given
1482 VFS-hosted database file. The result of the resolved Promise when
1483 called this way is the size of the resulting database.
1484
1485 On success this routine rewrites the database header bytes in the
1486 output file (not the input array) to force disabling of WAL mode,
1487 (A) for historical reasons and (B) getting WAL to work in this
1488 build requires doing a (pragma locking_mode=exclusive) on the db
1489 before using it.
1490
1491 On a write error, the handle is removed from the pool and made
1492 available for re-use.
1493
1494 - [async] number reduceCapacity(n)
1495
1496 Removes up to `n` entries from the pool, with the caveat that it can
1497 only remove currently-unused entries. It returns a Promise which
1498 resolves to the number of entries actually removed.
1499
1500 - [async] boolean removeVfs()
1501
1502 Unregisters the opfs-sahpool VFS and removes its directory from OPFS
1503 (which means that _all client content_ is removed). After calling
1504 this, the VFS may no longer be used and there is no way to re-add it
1505 aside from reloading the current JavaScript context.
1506
1507 Results are undefined if a database is currently in use with this
1508 VFS.
1509
1510 The returned Promise resolves to true if it performed the removal
1511 and false if the VFS was not installed.
1512
1513 If the VFS has a multi-level directory, e.g. "/foo/bar/baz", _only_
1514 the bottom-most directory is removed because this VFS cannot know for
1515 certain whether the higher-level directories contain data which
1516 should be removed.
1517
1518 - [async] number reserveMinimumCapacity(min)
1519
1520 If the current capacity is less than `min`, the capacity is
1521 increased to `min`, else this returns with no side effects. The
1522 resulting Promise resolves to the new capacity.
1523
1524 - boolean unlink(filename)
1525
1526 If a virtual file exists with the given name, disassociates it from
1527 the pool and returns true, else returns false without side
1528 effects. Results are undefined if the file is currently in active
1529 use.
1530
1531 - string vfsName
1532
1533 The SQLite VFS name under which this pool's VFS is registered.
1534
1535 - [async] void wipeFiles()
1536
1537 Clears all client-defined state of all SAHs and makes all of them
1538 available for re-use by the pool. Results are undefined if any such
1539 handles are currently in use, e.g. by an sqlite3 db.
1540
1541 APIs specific to the "pause" capability (added in version 3.49):
1542
1543 Summary: "pausing" the VFS disassociates it from SQLite and
1544 relinquishes its SAHs so that they may be opened by another
1545 instance of this VFS (running in a separate tab/page or Worker).
1546 "Unpausing" it takes back control, if able.
1547
1548 - pauseVfs()
1549
1550 "Pauses" this VFS by unregistering it from SQLite and
1551 relinquishing all open SAHs, leaving the associated files intact.
1552 This enables pages/tabs to coordinate semi-concurrent usage of
1553 this VFS. If this object is already paused, this is a
1554 no-op. Returns this object. Throws if SQLite has any opened file
1555 handles hosted by this VFS. If this function throws due to open
1556 file handles then it has no side effects. If the OPFS API throws
1557 while closing handles then the VFS is left in an undefined state.
1558
1559 - isPaused()
1560
1561 Returns true if this VFS is paused, else false.
1562
1563 - [async] unpauseVfs()
1564
1565 Restores the VFS to an active state after having called
1566 pauseVfs() on it. This is a no-op if the VFS is not paused. The
1567 returned Promise resolves to this object on success. A rejected
1568 Promise means there was a problem reacquiring the SAH handles
1569 (possibly because they're in use by another instance or have
1570 since been removed). Generically speaking, there is no recovery
1571 strategy for that type of error, but if the problem is simply
1572 that the OPFS files are locked, then a later attempt to unpause
1573 it, made after the concurrent instance releases the SAHs, may
1574 recover from the situation.
1575 */
1576 sqlite3.installOpfsSAHPoolVfs = async function(options=Object.create(null)){
1577 options = Object.assign(Object.create(null), optionDefaults, (options||{}));
1578 const vfsName = options.name;
1579 if(options.$testThrowPhase1){
1580 throw options.$testThrowPhase1;
1581 }
1582 if(initPromises[vfsName]){
1583 try {
1584 const p = await initPromises[vfsName];
1585 //log("installOpfsSAHPoolVfs() returning cached result",options,vfsName,p);
1586 return p;
1587 }catch(e){
1588 //log("installOpfsSAHPoolVfs() got cached failure",options,vfsName,e);
1589 if( options.forceReinitIfPreviouslyFailed ){
1590 delete initPromises[vfsName];
1591 /* Fall through and try again. */
1592 }else{
1593 throw e;
1594 }
1595 }
1596 }
1597 if(!globalThis.FileSystemHandle ||
1598 !globalThis.FileSystemDirectoryHandle ||
1599 !globalThis.FileSystemFileHandle ||
1600 !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle ||
1601 !navigator?.storage?.getDirectory){
1602 return (initPromises[vfsName] = Promise.reject(new Error("Missing required OPFS APIs.")));
1603 }
1604
1605 /**
1606 An interal detail of OpfsSAHPool, called only by initPromises().
1607
1608 Unregisters and disposes of OpfsSAHPool thePool, releasing all
1609 of its SAHs without deleting its files. Used when
1610 initialization fails and the preserveOnInitFailure option is
1611 set. This is a no-op if thePool.getVfs().pointer is falsy. Returns the
1612 undefined value.
1613 */
1614 const unregisterVfs = (thePool)=>{
1615 const cVfs = thePool.getVfs();
1616 if( cVfs?.pointer ){
1617 capi.sqlite3_vfs_unregister(cVfs.pointer);
1618 cVfs.dispose();
1619 thePool.releaseAccessHandles();
1620 }
1621 };
1622
1623 /**
1624 Maintenance reminder: the order of ASYNC ops in this function
1625 is significant. We need to have them all chained at the very
1626 end in order to be able to catch a race condition where
1627 installOpfsSAHPoolVfs() is called twice in rapid succession,
1628 e.g.:
1629
1630 installOpfsSAHPoolVfs().then(console.warn.bind(console));
1631 installOpfsSAHPoolVfs().then(console.warn.bind(console));
1632
1633 If the timing of the async calls is not "just right" then that
1634 second call can end up triggering the init a second time and chaos
1635 ensues.
1636 */
1637 return initPromises[vfsName] = apiVersionCheck().then(async function(){
1638 if(options.$testThrowPhase2){
1639 throw options.$testThrowPhase2;
1640 }
1641 const thePool = new OpfsSAHPool(options);
1642 return thePool.isReady.then(async()=>{
1643 /** The poolUtil object will be the result of the
1644 resolved Promise. */
1645 const poolUtil = new OpfsSAHPoolUtil(thePool);
1646 if(sqlite3.oo1){
1647 const oo1 = sqlite3.oo1;
1648 const theVfs = thePool.getVfs();
1649 const OpfsSAHPoolDb = function(...args){
1650 const opt = oo1.DB.dbCtorHelper.normalizeArgs(...args);
1651 opt.vfs = theVfs.$zName;
1652 oo1.DB.dbCtorHelper.call(this, opt);
1653 };
1654 OpfsSAHPoolDb.prototype = Object.create(oo1.DB.prototype);
1655 poolUtil.OpfsSAHPoolDb = OpfsSAHPoolDb;
1656 }/*extend sqlite3.oo1*/
1657 thePool.log("VFS initialized.");
1658 return poolUtil;
1659 }).catch(async (e)=>{
1660 if( options.preserveOnInitFailure ){
1661 unregisterVfs(thePool);
1662 }else{
1663 await thePool.removeVfs().catch(()=>{});
1664 }
1665 throw e;
1666 });
1667 }).catch((err)=>{
1668 //error("rejecting promise:",err);
1669 return initPromises[vfsName] = Promise.reject(err);
1670 });
1671 }/*installOpfsSAHPoolVfs()*/;
1672}/*sqlite3ApiBootstrap.initializers*/);
1673//#else
1674/*
1675 The OPFS SAH Pool VFS parts are elided from builds targeting
1676 node.js.
1677*/
1678//#/if global snip