sqlite3-vfs-opfs-sahpool.c-pp.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. //#ifnot target=node
  2. /*
  3. 2023-07-14
  4. The author disclaims copyright to this source code. In place of a
  5. legal notice, here is a blessing:
  6. * May you do good and not evil.
  7. * May you find forgiveness for yourself and forgive others.
  8. * May you share freely, never taking more than you give.
  9. ***********************************************************************
  10. This file holds a sqlite3_vfs backed by OPFS storage which uses a
  11. different implementation strategy than the "opfs" VFS. This one is a
  12. port of Roy Hashimoto's OPFS SyncAccessHandle pool:
  13. https://github.com/rhashimoto/wa-sqlite/blob/master/src/examples/AccessHandlePoolVFS.js
  14. As described at:
  15. https://github.com/rhashimoto/wa-sqlite/discussions/67
  16. with Roy's explicit permission to permit us to port his to our
  17. infrastructure rather than having to clean-room reverse-engineer it:
  18. https://sqlite.org/forum/forumpost/e140d84e71
  19. Primary differences from the "opfs" VFS include:
  20. - This one avoids the need for a sub-worker to synchronize
  21. communication between the synchronous C API and the
  22. only-partly-synchronous OPFS API.
  23. - It does so by opening a fixed number of OPFS files at
  24. library-level initialization time, obtaining SyncAccessHandles to
  25. each, and manipulating those handles via the synchronous sqlite3_vfs
  26. interface. If it cannot open them (e.g. they are already opened by
  27. another tab) then the VFS will not be installed.
  28. - Because of that, this one lacks all library-level concurrency
  29. support.
  30. - Also because of that, it does not require the SharedArrayBuffer,
  31. so can function without the COOP/COEP HTTP response headers.
  32. - It can hypothetically support Safari 16.4+, whereas the "opfs" VFS
  33. requires v17 due to a subworker/storage bug in 16.x which makes it
  34. incompatible with that VFS.
  35. - This VFS requires the "semi-fully-sync" FileSystemSyncAccessHandle
  36. (hereafter "SAH") APIs released with Chrome v108 (and all other
  37. major browsers released since March 2023). If that API is not
  38. detected, the VFS is not registered.
  39. */
  40. globalThis.sqlite3ApiBootstrap.initializers.push(function(sqlite3){
  41. 'use strict';
  42. const toss = sqlite3.util.toss;
  43. const toss3 = sqlite3.util.toss3;
  44. const initPromises = Object.create(null) /* cache of (name:result) of VFS init results */;
  45. const capi = sqlite3.capi;
  46. const util = sqlite3.util;
  47. const wasm = sqlite3.wasm;
  48. // Config opts for the VFS...
  49. const SECTOR_SIZE = 4096;
  50. const HEADER_MAX_PATH_SIZE = 512;
  51. const HEADER_FLAGS_SIZE = 4;
  52. const HEADER_DIGEST_SIZE = 8;
  53. const HEADER_CORPUS_SIZE = HEADER_MAX_PATH_SIZE + HEADER_FLAGS_SIZE;
  54. const HEADER_OFFSET_FLAGS = HEADER_MAX_PATH_SIZE;
  55. const HEADER_OFFSET_DIGEST = HEADER_CORPUS_SIZE;
  56. const HEADER_OFFSET_DATA = SECTOR_SIZE;
  57. /* Bitmask of file types which may persist across sessions.
  58. SQLITE_OPEN_xyz types not listed here may be inadvertently
  59. left in OPFS but are treated as transient by this VFS and
  60. they will be cleaned up during VFS init. */
  61. const PERSISTENT_FILE_TYPES =
  62. capi.SQLITE_OPEN_MAIN_DB |
  63. capi.SQLITE_OPEN_MAIN_JOURNAL |
  64. capi.SQLITE_OPEN_SUPER_JOURNAL |
  65. capi.SQLITE_OPEN_WAL;
  66. /** Subdirectory of the VFS's space where "opaque" (randomly-named)
  67. files are stored. Changing this effectively invalidates the data
  68. stored under older names (orphaning it), so don't do that. */
  69. const OPAQUE_DIR_NAME = ".opaque";
  70. /**
  71. Returns short a string of random alphanumeric characters
  72. suitable for use as a random filename.
  73. */
  74. const getRandomName = ()=>Math.random().toString(36).slice(2);
  75. const textDecoder = new TextDecoder();
  76. const textEncoder = new TextEncoder();
  77. const optionDefaults = Object.assign(Object.create(null),{
  78. name: 'opfs-sahpool',
  79. directory: undefined /* derived from .name */,
  80. initialCapacity: 6,
  81. clearOnInit: false,
  82. /* Logging verbosity 3+ == everything, 2 == warnings+errors, 1 ==
  83. errors only. */
  84. verbosity: 2,
  85. forceReinitIfPreviouslyFailed: false
  86. });
  87. /** Logging routines, from most to least serious. */
  88. const loggers = [
  89. sqlite3.config.error,
  90. sqlite3.config.warn,
  91. sqlite3.config.log
  92. ];
  93. const log = sqlite3.config.log;
  94. const warn = sqlite3.config.warn;
  95. const error = sqlite3.config.error;
  96. /* Maps (sqlite3_vfs*) to OpfsSAHPool instances */
  97. const __mapVfsToPool = new Map();
  98. const getPoolForVfs = (pVfs)=>__mapVfsToPool.get(pVfs);
  99. const setPoolForVfs = (pVfs,pool)=>{
  100. if(pool) __mapVfsToPool.set(pVfs, pool);
  101. else __mapVfsToPool.delete(pVfs);
  102. };
  103. /* Maps (sqlite3_file*) to OpfsSAHPool instances */
  104. const __mapSqlite3File = new Map();
  105. const getPoolForPFile = (pFile)=>__mapSqlite3File.get(pFile);
  106. const setPoolForPFile = (pFile,pool)=>{
  107. if(pool) __mapSqlite3File.set(pFile, pool);
  108. else __mapSqlite3File.delete(pFile);
  109. };
  110. /**
  111. Impls for the sqlite3_io_methods methods. Maintenance reminder:
  112. members are in alphabetical order to simplify finding them.
  113. */
  114. const ioMethods = {
  115. xCheckReservedLock: function(pFile,pOut){
  116. const pool = getPoolForPFile(pFile);
  117. pool.log('xCheckReservedLock');
  118. pool.storeErr();
  119. wasm.poke32(pOut, 1);
  120. return 0;
  121. },
  122. xClose: function(pFile){
  123. const pool = getPoolForPFile(pFile);
  124. pool.storeErr();
  125. const file = pool.getOFileForS3File(pFile);
  126. if(file) {
  127. try{
  128. pool.log(`xClose ${file.path}`);
  129. pool.mapS3FileToOFile(pFile, false);
  130. file.sah.flush();
  131. if(file.flags & capi.SQLITE_OPEN_DELETEONCLOSE){
  132. pool.deletePath(file.path);
  133. }
  134. }catch(e){
  135. return pool.storeErr(e, capi.SQLITE_IOERR);
  136. }
  137. }
  138. return 0;
  139. },
  140. xDeviceCharacteristics: function(pFile){
  141. return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
  142. },
  143. xFileControl: function(pFile, opId, pArg){
  144. return capi.SQLITE_NOTFOUND;
  145. },
  146. xFileSize: function(pFile,pSz64){
  147. const pool = getPoolForPFile(pFile);
  148. pool.log(`xFileSize`);
  149. const file = pool.getOFileForS3File(pFile);
  150. const size = file.sah.getSize() - HEADER_OFFSET_DATA;
  151. //log(`xFileSize ${file.path} ${size}`);
  152. wasm.poke64(pSz64, BigInt(size));
  153. return 0;
  154. },
  155. xLock: function(pFile,lockType){
  156. const pool = getPoolForPFile(pFile);
  157. pool.log(`xLock ${lockType}`);
  158. pool.storeErr();
  159. const file = pool.getOFileForS3File(pFile);
  160. file.lockType = lockType;
  161. return 0;
  162. },
  163. xRead: function(pFile,pDest,n,offset64){
  164. const pool = getPoolForPFile(pFile);
  165. pool.storeErr();
  166. const file = pool.getOFileForS3File(pFile);
  167. pool.log(`xRead ${file.path} ${n} @ ${offset64}`);
  168. try {
  169. const nRead = file.sah.read(
  170. wasm.heap8u().subarray(pDest, pDest+n),
  171. {at: HEADER_OFFSET_DATA + Number(offset64)}
  172. );
  173. if(nRead < n){
  174. wasm.heap8u().fill(0, pDest + nRead, pDest + n);
  175. return capi.SQLITE_IOERR_SHORT_READ;
  176. }
  177. return 0;
  178. }catch(e){
  179. return pool.storeErr(e, capi.SQLITE_IOERR);
  180. }
  181. },
  182. xSectorSize: function(pFile){
  183. return SECTOR_SIZE;
  184. },
  185. xSync: function(pFile,flags){
  186. const pool = getPoolForPFile(pFile);
  187. pool.log(`xSync ${flags}`);
  188. pool.storeErr();
  189. const file = pool.getOFileForS3File(pFile);
  190. //log(`xSync ${file.path} ${flags}`);
  191. try{
  192. file.sah.flush();
  193. return 0;
  194. }catch(e){
  195. return pool.storeErr(e, capi.SQLITE_IOERR);
  196. }
  197. },
  198. xTruncate: function(pFile,sz64){
  199. const pool = getPoolForPFile(pFile);
  200. pool.log(`xTruncate ${sz64}`);
  201. pool.storeErr();
  202. const file = pool.getOFileForS3File(pFile);
  203. //log(`xTruncate ${file.path} ${iSize}`);
  204. try{
  205. file.sah.truncate(HEADER_OFFSET_DATA + Number(sz64));
  206. return 0;
  207. }catch(e){
  208. return pool.storeErr(e, capi.SQLITE_IOERR);
  209. }
  210. },
  211. xUnlock: function(pFile,lockType){
  212. const pool = getPoolForPFile(pFile);
  213. pool.log('xUnlock');
  214. const file = pool.getOFileForS3File(pFile);
  215. file.lockType = lockType;
  216. return 0;
  217. },
  218. xWrite: function(pFile,pSrc,n,offset64){
  219. const pool = getPoolForPFile(pFile);
  220. pool.storeErr();
  221. const file = pool.getOFileForS3File(pFile);
  222. pool.log(`xWrite ${file.path} ${n} ${offset64}`);
  223. try{
  224. const nBytes = file.sah.write(
  225. wasm.heap8u().subarray(pSrc, pSrc+n),
  226. { at: HEADER_OFFSET_DATA + Number(offset64) }
  227. );
  228. return n===nBytes ? 0 : toss("Unknown write() failure.");
  229. }catch(e){
  230. return pool.storeErr(e, capi.SQLITE_IOERR);
  231. }
  232. }
  233. }/*ioMethods*/;
  234. const opfsIoMethods = new capi.sqlite3_io_methods();
  235. opfsIoMethods.$iVersion = 1;
  236. sqlite3.vfs.installVfs({
  237. io: {struct: opfsIoMethods, methods: ioMethods}
  238. });
  239. /**
  240. Impls for the sqlite3_vfs methods. Maintenance reminder: members
  241. are in alphabetical order to simplify finding them.
  242. */
  243. const vfsMethods = {
  244. xAccess: function(pVfs,zName,flags,pOut){
  245. //log(`xAccess ${wasm.cstrToJs(zName)}`);
  246. const pool = getPoolForVfs(pVfs);
  247. pool.storeErr();
  248. try{
  249. const name = pool.getPath(zName);
  250. wasm.poke32(pOut, pool.hasFilename(name) ? 1 : 0);
  251. }catch(e){
  252. /*ignored*/
  253. wasm.poke32(pOut, 0);
  254. }
  255. return 0;
  256. },
  257. xCurrentTime: function(pVfs,pOut){
  258. wasm.poke(pOut, 2440587.5 + (new Date().getTime()/86400000),
  259. 'double');
  260. return 0;
  261. },
  262. xCurrentTimeInt64: function(pVfs,pOut){
  263. wasm.poke(pOut, (2440587.5 * 86400000) + new Date().getTime(),
  264. 'i64');
  265. return 0;
  266. },
  267. xDelete: function(pVfs, zName, doSyncDir){
  268. const pool = getPoolForVfs(pVfs);
  269. pool.log(`xDelete ${wasm.cstrToJs(zName)}`);
  270. pool.storeErr();
  271. try{
  272. pool.deletePath(pool.getPath(zName));
  273. return 0;
  274. }catch(e){
  275. pool.storeErr(e);
  276. return capi.SQLITE_IOERR_DELETE;
  277. }
  278. },
  279. xFullPathname: function(pVfs,zName,nOut,pOut){
  280. //const pool = getPoolForVfs(pVfs);
  281. //pool.log(`xFullPathname ${wasm.cstrToJs(zName)}`);
  282. const i = wasm.cstrncpy(pOut, zName, nOut);
  283. return i<nOut ? 0 : capi.SQLITE_CANTOPEN;
  284. },
  285. xGetLastError: function(pVfs,nOut,pOut){
  286. const pool = getPoolForVfs(pVfs);
  287. const e = pool.popErr();
  288. pool.log(`xGetLastError ${nOut} e =`,e);
  289. if(e){
  290. const scope = wasm.scopedAllocPush();
  291. try{
  292. const [cMsg, n] = wasm.scopedAllocCString(e.message, true);
  293. wasm.cstrncpy(pOut, cMsg, nOut);
  294. if(n > nOut) wasm.poke8(pOut + nOut - 1, 0);
  295. }catch(e){
  296. return capi.SQLITE_NOMEM;
  297. }finally{
  298. wasm.scopedAllocPop(scope);
  299. }
  300. }
  301. return e ? (e.sqlite3Rc || capi.SQLITE_IOERR) : 0;
  302. },
  303. //xSleep is optionally defined below
  304. xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){
  305. const pool = getPoolForVfs(pVfs);
  306. try{
  307. pool.log(`xOpen ${wasm.cstrToJs(zName)} ${flags}`);
  308. // First try to open a path that already exists in the file system.
  309. const path = (zName && wasm.peek8(zName))
  310. ? pool.getPath(zName)
  311. : getRandomName();
  312. let sah = pool.getSAHForPath(path);
  313. if(!sah && (flags & capi.SQLITE_OPEN_CREATE)) {
  314. // File not found so try to create it.
  315. if(pool.getFileCount() < pool.getCapacity()) {
  316. // Choose an unassociated OPFS file from the pool.
  317. sah = pool.nextAvailableSAH();
  318. pool.setAssociatedPath(sah, path, flags);
  319. }else{
  320. // File pool is full.
  321. toss('SAH pool is full. Cannot create file',path);
  322. }
  323. }
  324. if(!sah){
  325. toss('file not found:',path);
  326. }
  327. // Subsequent I/O methods are only passed the sqlite3_file
  328. // pointer, so map the relevant info we need to that pointer.
  329. const file = {path, flags, sah};
  330. pool.mapS3FileToOFile(pFile, file);
  331. file.lockType = capi.SQLITE_LOCK_NONE;
  332. const sq3File = new capi.sqlite3_file(pFile);
  333. sq3File.$pMethods = opfsIoMethods.pointer;
  334. sq3File.dispose();
  335. wasm.poke32(pOutFlags, flags);
  336. return 0;
  337. }catch(e){
  338. pool.storeErr(e);
  339. return capi.SQLITE_CANTOPEN;
  340. }
  341. }/*xOpen()*/
  342. }/*vfsMethods*/;
  343. /**
  344. Creates and initializes an sqlite3_vfs instance for an
  345. OpfsSAHPool. The argument is the VFS's name (JS string).
  346. Throws if the VFS name is already registered or if something
  347. goes terribly wrong via sqlite3.vfs.installVfs().
  348. Maintenance reminder: the only detail about the returned object
  349. which is specific to any given OpfsSAHPool instance is the $zName
  350. member. All other state is identical.
  351. */
  352. const createOpfsVfs = function(vfsName){
  353. if( sqlite3.capi.sqlite3_vfs_find(vfsName)){
  354. toss3("VFS name is already registered:", vfsName);
  355. }
  356. const opfsVfs = new capi.sqlite3_vfs();
  357. /* We fetch the default VFS so that we can inherit some
  358. methods from it. */
  359. const pDVfs = capi.sqlite3_vfs_find(null);
  360. const dVfs = pDVfs
  361. ? new capi.sqlite3_vfs(pDVfs)
  362. : null /* dVfs will be null when sqlite3 is built with
  363. SQLITE_OS_OTHER. */;
  364. opfsVfs.$iVersion = 2/*yes, two*/;
  365. opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
  366. opfsVfs.$mxPathname = HEADER_MAX_PATH_SIZE;
  367. opfsVfs.addOnDispose(
  368. opfsVfs.$zName = wasm.allocCString(vfsName),
  369. ()=>setPoolForVfs(opfsVfs.pointer, 0)
  370. );
  371. if(dVfs){
  372. /* Inherit certain VFS members from the default VFS,
  373. if available. */
  374. opfsVfs.$xRandomness = dVfs.$xRandomness;
  375. opfsVfs.$xSleep = dVfs.$xSleep;
  376. dVfs.dispose();
  377. }
  378. if(!opfsVfs.$xRandomness && !vfsMethods.xRandomness){
  379. /* If the default VFS has no xRandomness(), add a basic JS impl... */
  380. vfsMethods.xRandomness = function(pVfs, nOut, pOut){
  381. const heap = wasm.heap8u();
  382. let i = 0;
  383. for(; i < nOut; ++i) heap[pOut + i] = (Math.random()*255000) & 0xFF;
  384. return i;
  385. };
  386. }
  387. if(!opfsVfs.$xSleep && !vfsMethods.xSleep){
  388. vfsMethods.xSleep = (pVfs,ms)=>0;
  389. }
  390. sqlite3.vfs.installVfs({
  391. vfs: {struct: opfsVfs, methods: vfsMethods}
  392. });
  393. return opfsVfs;
  394. };
  395. /**
  396. Class for managing OPFS-related state for the
  397. OPFS SharedAccessHandle Pool sqlite3_vfs.
  398. */
  399. class OpfsSAHPool {
  400. /* OPFS dir in which VFS metadata is stored. */
  401. vfsDir;
  402. /* Directory handle to this.vfsDir. */
  403. #dhVfsRoot;
  404. /* Directory handle to the subdir of this.#dhVfsRoot which holds
  405. the randomly-named "opaque" files. This subdir exists in the
  406. hope that we can eventually support client-created files in
  407. this.#dhVfsRoot. */
  408. #dhOpaque;
  409. /* Directory handle to this.dhVfsRoot's parent dir. Needed
  410. for a VFS-wipe op. */
  411. #dhVfsParent;
  412. /* Maps SAHs to their opaque file names. */
  413. #mapSAHToName = new Map();
  414. /* Maps client-side file names to SAHs. */
  415. #mapFilenameToSAH = new Map();
  416. /* Set of currently-unused SAHs. */
  417. #availableSAH = new Set();
  418. /* Maps (sqlite3_file*) to xOpen's file objects. */
  419. #mapS3FileToOFile_ = new Map();
  420. /* Maps SAH to an abstract File Object which contains
  421. various metadata about that handle. */
  422. //#mapSAHToMeta = new Map();
  423. /** Buffer used by [sg]etAssociatedPath(). */
  424. #apBody = new Uint8Array(HEADER_CORPUS_SIZE);
  425. // DataView for this.#apBody
  426. #dvBody;
  427. // associated sqlite3_vfs instance
  428. #cVfs;
  429. // Logging verbosity. See optionDefaults.verbosity.
  430. #verbosity;
  431. constructor(options = Object.create(null)){
  432. this.#verbosity = options.verbosity ?? optionDefaults.verbosity;
  433. this.vfsName = options.name || optionDefaults.name;
  434. this.#cVfs = createOpfsVfs(this.vfsName);
  435. setPoolForVfs(this.#cVfs.pointer, this);
  436. this.vfsDir = options.directory || ("."+this.vfsName);
  437. this.#dvBody =
  438. new DataView(this.#apBody.buffer, this.#apBody.byteOffset);
  439. this.isReady = this
  440. .reset(!!(options.clearOnInit ?? optionDefaults.clearOnInit))
  441. .then(()=>{
  442. if(this.$error) throw this.$error;
  443. return this.getCapacity()
  444. ? Promise.resolve(undefined)
  445. : this.addCapacity(options.initialCapacity
  446. || optionDefaults.initialCapacity);
  447. });
  448. }
  449. #logImpl(level,...args){
  450. if(this.#verbosity>level) loggers[level](this.vfsName+":",...args);
  451. };
  452. log(...args){this.#logImpl(2, ...args)};
  453. warn(...args){this.#logImpl(1, ...args)};
  454. error(...args){this.#logImpl(0, ...args)};
  455. getVfs(){return this.#cVfs}
  456. /* Current pool capacity. */
  457. getCapacity(){return this.#mapSAHToName.size}
  458. /* Current number of in-use files from pool. */
  459. getFileCount(){return this.#mapFilenameToSAH.size}
  460. /* Returns an array of the names of all
  461. currently-opened client-specified filenames. */
  462. getFileNames(){
  463. const rc = [];
  464. const iter = this.#mapFilenameToSAH.keys();
  465. for(const n of iter) rc.push(n);
  466. return rc;
  467. }
  468. // #createFileObject(sah,clientName,opaqueName){
  469. // const f = Object.assign(Object.create(null),{
  470. // clientName, opaqueName
  471. // });
  472. // this.#mapSAHToMeta.set(sah, f);
  473. // return f;
  474. // }
  475. // #unmapFileObject(sah){
  476. // this.#mapSAHToMeta.delete(sah);
  477. // }
  478. /**
  479. Adds n files to the pool's capacity. This change is
  480. persistent across settings. Returns a Promise which resolves
  481. to the new capacity.
  482. */
  483. async addCapacity(n){
  484. for(let i = 0; i < n; ++i){
  485. const name = getRandomName();
  486. const h = await this.#dhOpaque.getFileHandle(name, {create:true});
  487. const ah = await h.createSyncAccessHandle();
  488. this.#mapSAHToName.set(ah,name);
  489. this.setAssociatedPath(ah, '', 0);
  490. //this.#createFileObject(ah,undefined,name);
  491. }
  492. return this.getCapacity();
  493. }
  494. /**
  495. Reduce capacity by n, but can only reduce up to the limit
  496. of currently-available SAHs. Returns a Promise which resolves
  497. to the number of slots really removed.
  498. */
  499. async reduceCapacity(n){
  500. let nRm = 0;
  501. for(const ah of Array.from(this.#availableSAH)){
  502. if(nRm === n || this.getFileCount() === this.getCapacity()){
  503. break;
  504. }
  505. const name = this.#mapSAHToName.get(ah);
  506. //this.#unmapFileObject(ah);
  507. ah.close();
  508. await this.#dhOpaque.removeEntry(name);
  509. this.#mapSAHToName.delete(ah);
  510. this.#availableSAH.delete(ah);
  511. ++nRm;
  512. }
  513. return nRm;
  514. }
  515. /**
  516. Releases all currently-opened SAHs. The only legal
  517. operation after this is acquireAccessHandles().
  518. */
  519. releaseAccessHandles(){
  520. for(const ah of this.#mapSAHToName.keys()) ah.close();
  521. this.#mapSAHToName.clear();
  522. this.#mapFilenameToSAH.clear();
  523. this.#availableSAH.clear();
  524. }
  525. /**
  526. Opens all files under this.vfsDir/this.#dhOpaque and acquires
  527. a SAH for each. returns a Promise which resolves to no value
  528. but completes once all SAHs are acquired. If acquiring an SAH
  529. throws, SAHPool.$error will contain the corresponding
  530. exception.
  531. If clearFiles is true, the client-stored state of each file is
  532. cleared when its handle is acquired, including its name, flags,
  533. and any data stored after the metadata block.
  534. */
  535. async acquireAccessHandles(clearFiles){
  536. const files = [];
  537. for await (const [name,h] of this.#dhOpaque){
  538. if('file'===h.kind){
  539. files.push([name,h]);
  540. }
  541. }
  542. return Promise.all(files.map(async([name,h])=>{
  543. try{
  544. const ah = await h.createSyncAccessHandle()
  545. this.#mapSAHToName.set(ah, name);
  546. if(clearFiles){
  547. ah.truncate(HEADER_OFFSET_DATA);
  548. this.setAssociatedPath(ah, '', 0);
  549. }else{
  550. const path = this.getAssociatedPath(ah);
  551. if(path){
  552. this.#mapFilenameToSAH.set(path, ah);
  553. }else{
  554. this.#availableSAH.add(ah);
  555. }
  556. }
  557. }catch(e){
  558. this.storeErr(e);
  559. this.releaseAccessHandles();
  560. throw e;
  561. }
  562. }));
  563. }
  564. /**
  565. Given an SAH, returns the client-specified name of
  566. that file by extracting it from the SAH's header.
  567. On error, it disassociates SAH from the pool and
  568. returns an empty string.
  569. */
  570. getAssociatedPath(sah){
  571. sah.read(this.#apBody, {at: 0});
  572. // Delete any unexpected files left over by previous
  573. // untimely errors...
  574. const flags = this.#dvBody.getUint32(HEADER_OFFSET_FLAGS);
  575. if(this.#apBody[0] &&
  576. ((flags & capi.SQLITE_OPEN_DELETEONCLOSE) ||
  577. (flags & PERSISTENT_FILE_TYPES)===0)){
  578. warn(`Removing file with unexpected flags ${flags.toString(16)}`,
  579. this.#apBody);
  580. this.setAssociatedPath(sah, '', 0);
  581. return '';
  582. }
  583. const fileDigest = new Uint32Array(HEADER_DIGEST_SIZE / 4);
  584. sah.read(fileDigest, {at: HEADER_OFFSET_DIGEST});
  585. const compDigest = this.computeDigest(this.#apBody);
  586. if(fileDigest.every((v,i) => v===compDigest[i])){
  587. // Valid digest
  588. const pathBytes = this.#apBody.findIndex((v)=>0===v);
  589. if(0===pathBytes){
  590. // This file is unassociated, so truncate it to avoid
  591. // leaving stale db data laying around.
  592. sah.truncate(HEADER_OFFSET_DATA);
  593. }
  594. return pathBytes
  595. ? textDecoder.decode(this.#apBody.subarray(0,pathBytes))
  596. : '';
  597. }else{
  598. // Invalid digest
  599. warn('Disassociating file with bad digest.');
  600. this.setAssociatedPath(sah, '', 0);
  601. return '';
  602. }
  603. }
  604. /**
  605. Stores the given client-defined path and SQLITE_OPEN_xyz flags
  606. into the given SAH. If path is an empty string then the file is
  607. disassociated from the pool but its previous name is preserved
  608. in the metadata.
  609. */
  610. setAssociatedPath(sah, path, flags){
  611. const enc = textEncoder.encodeInto(path, this.#apBody);
  612. if(HEADER_MAX_PATH_SIZE <= enc.written + 1/*NUL byte*/){
  613. toss("Path too long:",path);
  614. }
  615. this.#apBody.fill(0, enc.written, HEADER_MAX_PATH_SIZE);
  616. this.#dvBody.setUint32(HEADER_OFFSET_FLAGS, flags);
  617. const digest = this.computeDigest(this.#apBody);
  618. sah.write(this.#apBody, {at: 0});
  619. sah.write(digest, {at: HEADER_OFFSET_DIGEST});
  620. sah.flush();
  621. if(path){
  622. this.#mapFilenameToSAH.set(path, sah);
  623. this.#availableSAH.delete(sah);
  624. }else{
  625. // This is not a persistent file, so eliminate the contents.
  626. sah.truncate(HEADER_OFFSET_DATA);
  627. this.#availableSAH.add(sah);
  628. }
  629. }
  630. /**
  631. Computes a digest for the given byte array and returns it as a
  632. two-element Uint32Array. This digest gets stored in the
  633. metadata for each file as a validation check. Changing this
  634. algorithm invalidates all existing databases for this VFS, so
  635. don't do that.
  636. */
  637. computeDigest(byteArray){
  638. let h1 = 0xdeadbeef;
  639. let h2 = 0x41c6ce57;
  640. for(const v of byteArray){
  641. h1 = 31 * h1 + (v * 307);
  642. h2 = 31 * h2 + (v * 307);
  643. }
  644. return new Uint32Array([h1>>>0, h2>>>0]);
  645. }
  646. /**
  647. Re-initializes the state of the SAH pool, releasing and
  648. re-acquiring all handles.
  649. See acquireAccessHandles() for the specifics of the clearFiles
  650. argument.
  651. */
  652. async reset(clearFiles){
  653. await this.isReady;
  654. let h = await navigator.storage.getDirectory();
  655. let prev, prevName;
  656. for(const d of this.vfsDir.split('/')){
  657. if(d){
  658. prev = h;
  659. h = await h.getDirectoryHandle(d,{create:true});
  660. }
  661. }
  662. this.#dhVfsRoot = h;
  663. this.#dhVfsParent = prev;
  664. this.#dhOpaque = await this.#dhVfsRoot.getDirectoryHandle(
  665. OPAQUE_DIR_NAME,{create:true}
  666. );
  667. this.releaseAccessHandles();
  668. return this.acquireAccessHandles(clearFiles);
  669. }
  670. /**
  671. Returns the pathname part of the given argument,
  672. which may be any of:
  673. - a URL object
  674. - A JS string representing a file name
  675. - Wasm C-string representing a file name
  676. All "../" parts and duplicate slashes are resolve/removed from
  677. the returned result.
  678. */
  679. getPath(arg) {
  680. if(wasm.isPtr(arg)) arg = wasm.cstrToJs(arg);
  681. return ((arg instanceof URL)
  682. ? arg
  683. : new URL(arg, 'file://localhost/')).pathname;
  684. }
  685. /**
  686. Removes the association of the given client-specified file
  687. name (JS string) from the pool. Returns true if a mapping
  688. is found, else false.
  689. */
  690. deletePath(path) {
  691. const sah = this.#mapFilenameToSAH.get(path);
  692. if(sah) {
  693. // Un-associate the name from the SAH.
  694. this.#mapFilenameToSAH.delete(path);
  695. this.setAssociatedPath(sah, '', 0);
  696. }
  697. return !!sah;
  698. }
  699. /**
  700. Sets e (an Error object) as this object's current error. Pass a
  701. falsy (or no) value to clear it. If code is truthy it is
  702. assumed to be an SQLITE_xxx result code, defaulting to
  703. SQLITE_IOERR if code is falsy.
  704. Returns the 2nd argument.
  705. */
  706. storeErr(e,code){
  707. if(e){
  708. e.sqlite3Rc = code || capi.SQLITE_IOERR;
  709. this.error(e);
  710. }
  711. this.$error = e;
  712. return code;
  713. }
  714. /**
  715. Pops this object's Error object and returns
  716. it (a falsy value if no error is set).
  717. */
  718. popErr(){
  719. const rc = this.$error;
  720. this.$error = undefined;
  721. return rc;
  722. }
  723. /**
  724. Returns the next available SAH without removing
  725. it from the set.
  726. */
  727. nextAvailableSAH(){
  728. const [rc] = this.#availableSAH.keys();
  729. return rc;
  730. }
  731. /**
  732. Given an (sqlite3_file*), returns the mapped
  733. xOpen file object.
  734. */
  735. getOFileForS3File(pFile){
  736. return this.#mapS3FileToOFile_.get(pFile);
  737. }
  738. /**
  739. Maps or unmaps (if file is falsy) the given (sqlite3_file*)
  740. to an xOpen file object and to this pool object.
  741. */
  742. mapS3FileToOFile(pFile,file){
  743. if(file){
  744. this.#mapS3FileToOFile_.set(pFile, file);
  745. setPoolForPFile(pFile, this);
  746. }else{
  747. this.#mapS3FileToOFile_.delete(pFile);
  748. setPoolForPFile(pFile, false);
  749. }
  750. }
  751. /**
  752. Returns true if the given client-defined file name is in this
  753. object's name-to-SAH map.
  754. */
  755. hasFilename(name){
  756. return this.#mapFilenameToSAH.has(name)
  757. }
  758. /**
  759. Returns the SAH associated with the given
  760. client-defined file name.
  761. */
  762. getSAHForPath(path){
  763. return this.#mapFilenameToSAH.get(path);
  764. }
  765. /**
  766. Removes this object's sqlite3_vfs registration and shuts down
  767. this object, releasing all handles, mappings, and whatnot,
  768. including deleting its data directory. There is currently no
  769. way to "revive" the object and reaquire its resources.
  770. This function is intended primarily for testing.
  771. Resolves to true if it did its job, false if the
  772. VFS has already been shut down.
  773. */
  774. async removeVfs(){
  775. if(!this.#cVfs.pointer || !this.#dhOpaque) return false;
  776. capi.sqlite3_vfs_unregister(this.#cVfs.pointer);
  777. this.#cVfs.dispose();
  778. delete initPromises[this.vfsName];
  779. try{
  780. this.releaseAccessHandles();
  781. await this.#dhVfsRoot.removeEntry(OPAQUE_DIR_NAME, {recursive: true});
  782. this.#dhOpaque = undefined;
  783. await this.#dhVfsParent.removeEntry(
  784. this.#dhVfsRoot.name, {recursive: true}
  785. );
  786. this.#dhVfsRoot = this.#dhVfsParent = undefined;
  787. }catch(e){
  788. sqlite3.config.error(this.vfsName,"removeVfs() failed:",e);
  789. /*otherwise ignored - there is no recovery strategy*/
  790. }
  791. return true;
  792. }
  793. //! Documented elsewhere in this file.
  794. exportFile(name){
  795. const sah = this.#mapFilenameToSAH.get(name) || toss("File not found:",name);
  796. const n = sah.getSize() - HEADER_OFFSET_DATA;
  797. const b = new Uint8Array(n>0 ? n : 0);
  798. if(n>0){
  799. const nRead = sah.read(b, {at: HEADER_OFFSET_DATA});
  800. if(nRead != n){
  801. toss("Expected to read "+n+" bytes but read "+nRead+".");
  802. }
  803. }
  804. return b;
  805. }
  806. //! Impl for importDb() when its 2nd arg is a function.
  807. async importDbChunked(name, callback){
  808. const sah = this.#mapFilenameToSAH.get(name)
  809. || this.nextAvailableSAH()
  810. || toss("No available handles to import to.");
  811. sah.truncate(0);
  812. let nWrote = 0, chunk, checkedHeader = false, err = false;
  813. try{
  814. while( undefined !== (chunk = await callback()) ){
  815. if(chunk instanceof ArrayBuffer) chunk = new Uint8Array(chunk);
  816. if( 0===nWrote && chunk.byteLength>=15 ){
  817. util.affirmDbHeader(chunk);
  818. checkedHeader = true;
  819. }
  820. sah.write(chunk, {at: HEADER_OFFSET_DATA + nWrote});
  821. nWrote += chunk.byteLength;
  822. }
  823. if( nWrote < 512 || 0!==nWrote % 512 ){
  824. toss("Input size",nWrote,"is not correct for an SQLite database.");
  825. }
  826. if( !checkedHeader ){
  827. const header = new Uint8Array(20);
  828. sah.read( header, {at: 0} );
  829. util.affirmDbHeader( header );
  830. }
  831. sah.write(new Uint8Array([1,1]), {
  832. at: HEADER_OFFSET_DATA + 18
  833. }/*force db out of WAL mode*/);
  834. }catch(e){
  835. this.setAssociatedPath(sah, '', 0);
  836. throw e;
  837. }
  838. this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
  839. return nWrote;
  840. }
  841. //! Documented elsewhere in this file.
  842. importDb(name, bytes){
  843. if( bytes instanceof ArrayBuffer ) bytes = new Uint8Array(bytes);
  844. else if( bytes instanceof Function ) return this.importDbChunked(name, bytes);
  845. const sah = this.#mapFilenameToSAH.get(name)
  846. || this.nextAvailableSAH()
  847. || toss("No available handles to import to.");
  848. const n = bytes.byteLength;
  849. if(n<512 || n%512!=0){
  850. toss("Byte array size is invalid for an SQLite db.");
  851. }
  852. const header = "SQLite format 3";
  853. for(let i = 0; i < header.length; ++i){
  854. if( header.charCodeAt(i) !== bytes[i] ){
  855. toss("Input does not contain an SQLite database header.");
  856. }
  857. }
  858. const nWrote = sah.write(bytes, {at: HEADER_OFFSET_DATA});
  859. if(nWrote != n){
  860. this.setAssociatedPath(sah, '', 0);
  861. toss("Expected to write "+n+" bytes but wrote "+nWrote+".");
  862. }else{
  863. sah.write(new Uint8Array([1,1]), {at: HEADER_OFFSET_DATA+18}
  864. /* force db out of WAL mode */);
  865. this.setAssociatedPath(sah, name, capi.SQLITE_OPEN_MAIN_DB);
  866. }
  867. return nWrote;
  868. }
  869. }/*class OpfsSAHPool*/;
  870. /**
  871. A OpfsSAHPoolUtil instance is exposed to clients in order to
  872. manipulate an OpfsSAHPool object without directly exposing that
  873. object and allowing for some semantic changes compared to that
  874. class.
  875. Class docs are in the client-level docs for
  876. installOpfsSAHPoolVfs().
  877. */
  878. class OpfsSAHPoolUtil {
  879. /* This object's associated OpfsSAHPool. */
  880. #p;
  881. constructor(sahPool){
  882. this.#p = sahPool;
  883. this.vfsName = sahPool.vfsName;
  884. }
  885. async addCapacity(n){ return this.#p.addCapacity(n) }
  886. async reduceCapacity(n){ return this.#p.reduceCapacity(n) }
  887. getCapacity(){ return this.#p.getCapacity(this.#p) }
  888. getFileCount(){ return this.#p.getFileCount() }
  889. getFileNames(){ return this.#p.getFileNames() }
  890. async reserveMinimumCapacity(min){
  891. const c = this.#p.getCapacity();
  892. return (c < min) ? this.#p.addCapacity(min - c) : c;
  893. }
  894. exportFile(name){ return this.#p.exportFile(name) }
  895. importDb(name, bytes){ return this.#p.importDb(name,bytes) }
  896. async wipeFiles(){ return this.#p.reset(true) }
  897. unlink(filename){ return this.#p.deletePath(filename) }
  898. async removeVfs(){ return this.#p.removeVfs() }
  899. }/* class OpfsSAHPoolUtil */;
  900. /**
  901. Returns a resolved Promise if the current environment
  902. has a "fully-sync" SAH impl, else a rejected Promise.
  903. */
  904. const apiVersionCheck = async ()=>{
  905. const dh = await navigator.storage.getDirectory();
  906. const fn = '.opfs-sahpool-sync-check-'+getRandomName();
  907. const fh = await dh.getFileHandle(fn, { create: true });
  908. const ah = await fh.createSyncAccessHandle();
  909. const close = ah.close();
  910. await close;
  911. await dh.removeEntry(fn);
  912. if(close?.then){
  913. toss("The local OPFS API is too old for opfs-sahpool:",
  914. "it has an async FileSystemSyncAccessHandle.close() method.");
  915. }
  916. return true;
  917. };
  918. /**
  919. installOpfsSAHPoolVfs() asynchronously initializes the OPFS
  920. SyncAccessHandle (a.k.a. SAH) Pool VFS. It returns a Promise which
  921. either resolves to a utility object described below or rejects with
  922. an Error value.
  923. Initialization of this VFS is not automatic because its
  924. registration requires that it lock all resources it
  925. will potentially use, even if client code does not want
  926. to use them. That, in turn, can lead to locking errors
  927. when, for example, one page in a given origin has loaded
  928. this VFS but does not use it, then another page in that
  929. origin tries to use the VFS. If the VFS were automatically
  930. registered, the second page would fail to load the VFS
  931. due to OPFS locking errors.
  932. If this function is called more than once with a given "name"
  933. option (see below), it will return the same Promise. Calls for
  934. different names will return different Promises which resolve to
  935. independent objects and refer to different VFS registrations.
  936. On success, the resulting Promise resolves to a utility object
  937. which can be used to query and manipulate the pool. Its API is
  938. described at the end of these docs.
  939. This function accepts an options object to configure certain
  940. parts but it is only acknowledged for the very first call and
  941. ignored for all subsequent calls.
  942. The options, in alphabetical order:
  943. - `clearOnInit`: (default=false) if truthy, contents and filename
  944. mapping are removed from each SAH it is acquired during
  945. initalization of the VFS, leaving the VFS's storage in a pristine
  946. state. Use this only for databases which need not survive a page
  947. reload.
  948. - `initialCapacity`: (default=6) Specifies the default capacity of
  949. the VFS. This should not be set unduly high because the VFS has
  950. to open (and keep open) a file for each entry in the pool. This
  951. setting only has an effect when the pool is initially empty. It
  952. does not have any effect if a pool already exists.
  953. - `directory`: (default="."+`name`) Specifies the OPFS directory
  954. name in which to store metadata for the `"opfs-sahpool"`
  955. sqlite3_vfs. Only one instance of this VFS can be installed per
  956. JavaScript engine, and any two engines with the same storage
  957. directory name will collide with each other, leading to locking
  958. errors and the inability to register the VFS in the second and
  959. subsequent engine. Using a different directory name for each
  960. application enables different engines in the same HTTP origin to
  961. co-exist, but their data are invisible to each other. Changing
  962. this name will effectively orphan any databases stored under
  963. previous names. The default is unspecified but descriptive. This
  964. option may contain multiple path elements, e.g. "foo/bar/baz",
  965. and they are created automatically. In practice there should be
  966. no driving need to change this. ACHTUNG: all files in this
  967. directory are assumed to be managed by the VFS. Do not place
  968. other files in that directory, as they may be deleted or
  969. otherwise modified by the VFS.
  970. - `name`: (default="opfs-sahpool") sets the name to register this
  971. VFS under. Normally this should not be changed, but it is
  972. possible to register this VFS under multiple names so long as
  973. each has its own separate directory to work from. The storage for
  974. each is invisible to all others. The name must be a string
  975. compatible with `sqlite3_vfs_register()` and friends and suitable
  976. for use in URI-style database file names.
  977. Achtung: if a custom `name` is provided, a custom `directory`
  978. must also be provided if any other instance is registered with
  979. the default directory. If no directory is explicitly provided
  980. then a directory name is synthesized from the `name` option.
  981. - `forceReinitIfPreviouslyFailed`: (default=`false`) Is a fallback option
  982. to assist in working around certain flaky environments which may
  983. mysteriously fail to permit access to OPFS sync access handles on
  984. an initial attempt but permit it on a second attemp. This option
  985. should never be used but is provided for those who choose to
  986. throw caution to the wind and trust such environments. If this
  987. option is truthy _and_ the previous attempt to initialize this
  988. VFS with the same `name` failed, the VFS will attempt to
  989. initialize a second time instead of returning the cached
  990. failure. See discussion at:
  991. <https://github.com/sqlite/sqlite-wasm/issues/79>
  992. Peculiarities of this VFS vis a vis other SQLite VFSes:
  993. - Paths given to it _must_ be absolute. Relative paths will not
  994. be properly recognized. This is arguably a bug but correcting it
  995. requires some hoop-jumping in routines which have no business
  996. doing such tricks.
  997. - It is possible to install multiple instances under different
  998. names, each sandboxed from one another inside their own private
  999. directory. This feature exists primarily as a way for disparate
  1000. applications within a given HTTP origin to use this VFS without
  1001. introducing locking issues between them.
  1002. The API for the utility object passed on by this function's
  1003. Promise, in alphabetical order...
  1004. - [async] number addCapacity(n)
  1005. Adds `n` entries to the current pool. This change is persistent
  1006. across sessions so should not be called automatically at each app
  1007. startup (but see `reserveMinimumCapacity()`). Its returned Promise
  1008. resolves to the new capacity. Because this operation is necessarily
  1009. asynchronous, the C-level VFS API cannot call this on its own as
  1010. needed.
  1011. - byteArray exportFile(name)
  1012. Synchronously reads the contents of the given file into a Uint8Array
  1013. and returns it. This will throw if the given name is not currently
  1014. in active use or on I/O error. Note that the given name is _not_
  1015. visible directly in OPFS (or, if it is, it's not from this VFS).
  1016. - number getCapacity()
  1017. Returns the number of files currently contained
  1018. in the SAH pool. The default capacity is only large enough for one
  1019. or two databases and their associated temp files.
  1020. - number getFileCount()
  1021. Returns the number of files from the pool currently allocated to
  1022. slots. This is not the same as the files being "opened".
  1023. - array getFileNames()
  1024. Returns an array of the names of the files currently allocated to
  1025. slots. This list is the same length as getFileCount().
  1026. - void importDb(name, bytes)
  1027. Imports the contents of an SQLite database, provided as a byte
  1028. array or ArrayBuffer, under the given name, overwriting any
  1029. existing content. Throws if the pool has no available file slots,
  1030. on I/O error, or if the input does not appear to be a
  1031. database. In the latter case, only a cursory examination is made.
  1032. Results are undefined if the given db name refers to an opened
  1033. db. Note that this routine is _only_ for importing database
  1034. files, not arbitrary files, the reason being that this VFS will
  1035. automatically clean up any non-database files so importing them
  1036. is pointless.
  1037. If passed a function for its second argument, its behavior
  1038. changes to asynchronous and it imports its data in chunks fed to
  1039. it by the given callback function. It calls the callback (which
  1040. may be async) repeatedly, expecting either a Uint8Array or
  1041. ArrayBuffer (to denote new input) or undefined (to denote
  1042. EOF). For so long as the callback continues to return
  1043. non-undefined, it will append incoming data to the given
  1044. VFS-hosted database file. The result of the resolved Promise when
  1045. called this way is the size of the resulting database.
  1046. On succes this routine rewrites the database header bytes in the
  1047. output file (not the input array) to force disabling of WAL mode.
  1048. On a write error, the handle is removed from the pool and made
  1049. available for re-use.
  1050. - [async] number reduceCapacity(n)
  1051. Removes up to `n` entries from the pool, with the caveat that it can
  1052. only remove currently-unused entries. It returns a Promise which
  1053. resolves to the number of entries actually removed.
  1054. - [async] boolean removeVfs()
  1055. Unregisters the opfs-sahpool VFS and removes its directory from OPFS
  1056. (which means that _all client content_ is removed). After calling
  1057. this, the VFS may no longer be used and there is no way to re-add it
  1058. aside from reloading the current JavaScript context.
  1059. Results are undefined if a database is currently in use with this
  1060. VFS.
  1061. The returned Promise resolves to true if it performed the removal
  1062. and false if the VFS was not installed.
  1063. If the VFS has a multi-level directory, e.g. "/foo/bar/baz", _only_
  1064. the bottom-most directory is removed because this VFS cannot know for
  1065. certain whether the higher-level directories contain data which
  1066. should be removed.
  1067. - [async] number reserveMinimumCapacity(min)
  1068. If the current capacity is less than `min`, the capacity is
  1069. increased to `min`, else this returns with no side effects. The
  1070. resulting Promise resolves to the new capacity.
  1071. - boolean unlink(filename)
  1072. If a virtual file exists with the given name, disassociates it from
  1073. the pool and returns true, else returns false without side
  1074. effects. Results are undefined if the file is currently in active
  1075. use.
  1076. - string vfsName
  1077. The SQLite VFS name under which this pool's VFS is registered.
  1078. - [async] void wipeFiles()
  1079. Clears all client-defined state of all SAHs and makes all of them
  1080. available for re-use by the pool. Results are undefined if any such
  1081. handles are currently in use, e.g. by an sqlite3 db.
  1082. */
  1083. sqlite3.installOpfsSAHPoolVfs = async function(options=Object.create(null)){
  1084. options = Object.assign(Object.create(null), optionDefaults, (options||{}));
  1085. const vfsName = options.name;
  1086. if(options.$testThrowPhase1){
  1087. throw options.$testThrowPhase1;
  1088. }
  1089. if(initPromises[vfsName]){
  1090. try {
  1091. const p = await initPromises[vfsName];
  1092. //log("installOpfsSAHPoolVfs() returning cached result",options,vfsName,p);
  1093. return p;
  1094. }catch(e){
  1095. //log("installOpfsSAHPoolVfs() got cached failure",options,vfsName,e);
  1096. if( options.forceReinitIfPreviouslyFailed ){
  1097. delete initPromises[vfsName];
  1098. /* Fall through and try again. */
  1099. }else{
  1100. throw e;
  1101. }
  1102. }
  1103. }
  1104. if(!globalThis.FileSystemHandle ||
  1105. !globalThis.FileSystemDirectoryHandle ||
  1106. !globalThis.FileSystemFileHandle ||
  1107. !globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle ||
  1108. !navigator?.storage?.getDirectory){
  1109. return (initPromises[vfsName] = Promise.reject(new Error("Missing required OPFS APIs.")));
  1110. }
  1111. /**
  1112. Maintenance reminder: the order of ASYNC ops in this function
  1113. is significant. We need to have them all chained at the very
  1114. end in order to be able to catch a race condition where
  1115. installOpfsSAHPoolVfs() is called twice in rapid succession,
  1116. e.g.:
  1117. installOpfsSAHPoolVfs().then(console.warn.bind(console));
  1118. installOpfsSAHPoolVfs().then(console.warn.bind(console));
  1119. If the timing of the async calls is not "just right" then that
  1120. second call can end up triggering the init a second time and chaos
  1121. ensues.
  1122. */
  1123. return initPromises[vfsName] = apiVersionCheck().then(async function(){
  1124. if(options.$testThrowPhase2){
  1125. throw options.$testThrowPhase2;
  1126. }
  1127. const thePool = new OpfsSAHPool(options);
  1128. return thePool.isReady.then(async()=>{
  1129. /** The poolUtil object will be the result of the
  1130. resolved Promise. */
  1131. const poolUtil = new OpfsSAHPoolUtil(thePool);
  1132. if(sqlite3.oo1){
  1133. const oo1 = sqlite3.oo1;
  1134. const theVfs = thePool.getVfs();
  1135. const OpfsSAHPoolDb = function(...args){
  1136. const opt = oo1.DB.dbCtorHelper.normalizeArgs(...args);
  1137. opt.vfs = theVfs.$zName;
  1138. oo1.DB.dbCtorHelper.call(this, opt);
  1139. };
  1140. OpfsSAHPoolDb.prototype = Object.create(oo1.DB.prototype);
  1141. poolUtil.OpfsSAHPoolDb = OpfsSAHPoolDb;
  1142. }/*extend sqlite3.oo1*/
  1143. thePool.log("VFS initialized.");
  1144. return poolUtil;
  1145. }).catch(async (e)=>{
  1146. await thePool.removeVfs().catch(()=>{});
  1147. throw e;
  1148. });
  1149. }).catch((err)=>{
  1150. //error("rejecting promise:",err);
  1151. return initPromises[vfsName] = Promise.reject(err);
  1152. });
  1153. }/*installOpfsSAHPoolVfs()*/;
  1154. }/*sqlite3ApiBootstrap.initializers*/);
  1155. //#else
  1156. /*
  1157. The OPFS SAH Pool VFS parts are elided from builds targeting
  1158. node.js.
  1159. */
  1160. //#endif target=node