stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 1 | /* |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 2 | 2022-09-18 |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 3 | |
| 4 | The author disclaims copyright to this source code. In place of a |
| 5 | legal notice, here is a blessing: |
| 6 | |
| 7 | * May you do good and not evil. |
| 8 | * May you find forgiveness for yourself and forgive others. |
| 9 | * May you share freely, never taking more than you give. |
| 10 | |
| 11 | *********************************************************************** |
| 12 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 13 | This file holds the synchronous half of an sqlite3_vfs |
| 14 | implementation which proxies, in a synchronous fashion, the |
| 15 | asynchronous Origin-Private FileSystem (OPFS) APIs using a second |
| 16 | Worker, implemented in sqlite3-opfs-async-proxy.js. This file is |
| 17 | intended to be appended to the main sqlite3 JS deliverable somewhere |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 18 | after sqlite3-api-oo1.js and before sqlite3-api-cleanup.js. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 19 | */ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 20 | 'use strict'; |
| 21 | self.sqlite3ApiBootstrap.initializers.push(function(sqlite3){ |
| 22 | /** |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 23 | installOpfsVfs() returns a Promise which, on success, installs an |
| 24 | sqlite3_vfs named "opfs", suitable for use with all sqlite3 APIs |
| 25 | which accept a VFS. It is intended to be called via |
| 26 | sqlite3ApiBootstrap.initializersAsync or an equivalent mechanism. |
| 27 | |
| 28 | The installed VFS uses the Origin-Private FileSystem API for |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 29 | all file storage. On error it is rejected with an exception |
| 30 | explaining the problem. Reasons for rejection include, but are |
| 31 | not limited to: |
| 32 | |
| 33 | - The counterpart Worker (see below) could not be loaded. |
| 34 | |
| 35 | - The environment does not support OPFS. That includes when |
| 36 | this function is called from the main window thread. |
| 37 | |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 38 | Significant notes and limitations: |
| 39 | |
| 40 | - As of this writing, OPFS is still very much in flux and only |
| 41 | available in bleeding-edge versions of Chrome (v102+, noting that |
| 42 | that number will increase as the OPFS API matures). |
| 43 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 44 | - The OPFS features used here are only available in dedicated Worker |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 45 | threads. This file tries to detect that case, resulting in a |
| 46 | rejected Promise if those features do not seem to be available. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 47 | |
| 48 | - It requires the SharedArrayBuffer and Atomics classes, and the |
| 49 | former is only available if the HTTP server emits the so-called |
| 50 | COOP and COEP response headers. These features are required for |
| 51 | proxying OPFS's synchronous API via the synchronous interface |
| 52 | required by the sqlite3_vfs API. |
| 53 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 54 | - This function may only be called a single time. When called, this |
| 55 | function removes itself from the sqlite3 object. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 56 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 57 | All arguments to this function are for internal/development purposes |
| 58 | only. They do not constitute a public API and may change at any |
| 59 | time. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 60 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 61 | The argument may optionally be a plain object with the following |
| 62 | configuration options: |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 63 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 64 | - proxyUri: as described above |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 65 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 66 | - verbose (=2): an integer 0-3. 0 disables all logging, 1 enables |
| 67 | logging of errors. 2 enables logging of warnings and errors. 3 |
| 68 | additionally enables debugging info. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 69 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 70 | - sanityChecks (=false): if true, some basic sanity tests are |
| 71 | run on the OPFS VFS API after it's initialized, before the |
| 72 | returned Promise resolves. |
| 73 | |
| 74 | On success, the Promise resolves to the top-most sqlite3 namespace |
| 75 | object and that object gets a new object installed in its |
| 76 | `opfs` property, containing several OPFS-specific utilities. |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 77 | */ |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 78 | const installOpfsVfs = function callee(options){ |
stephan | 4cffb64 | 2022-09-20 16:20:35 +0000 | [diff] [blame] | 79 | if(!self.SharedArrayBuffer || |
stephan | f6c686c | 2022-09-30 11:01:44 +0000 | [diff] [blame] | 80 | !self.Atomics || |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 81 | !self.FileSystemHandle || |
| 82 | !self.FileSystemDirectoryHandle || |
| 83 | !self.FileSystemFileHandle || |
| 84 | !self.FileSystemFileHandle.prototype.createSyncAccessHandle || |
| 85 | !navigator.storage.getDirectory){ |
| 86 | return Promise.reject( |
| 87 | new Error("This environment does not have OPFS support.") |
| 88 | ); |
| 89 | } |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 90 | if(!options || 'object'!==typeof options){ |
| 91 | options = Object.create(null); |
| 92 | } |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 93 | const urlParams = new URL(self.location.href).searchParams; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 94 | if(undefined===options.verbose){ |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 95 | options.verbose = urlParams.has('opfs-verbose') ? 3 : 2; |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 96 | } |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 97 | if(undefined===options.sanityChecks){ |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 98 | options.sanityChecks = urlParams.has('opfs-sanity-check'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 99 | } |
| 100 | if(undefined===options.proxyUri){ |
| 101 | options.proxyUri = callee.defaultProxyUri; |
| 102 | } |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 103 | |
stephan | cd0df83 | 2022-10-19 04:44:58 +0000 | [diff] [blame] | 104 | if('function' === typeof options.proxyUri){ |
| 105 | options.proxyUri = options.proxyUri(); |
| 106 | } |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 107 | const thePromise = new Promise(function(promiseResolve, promiseReject_){ |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 108 | const loggers = { |
| 109 | 0:console.error.bind(console), |
| 110 | 1:console.warn.bind(console), |
| 111 | 2:console.log.bind(console) |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 112 | }; |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 113 | const logImpl = (level,...args)=>{ |
| 114 | if(options.verbose>level) loggers[level]("OPFS syncer:",...args); |
| 115 | }; |
| 116 | const log = (...args)=>logImpl(2, ...args); |
| 117 | const warn = (...args)=>logImpl(1, ...args); |
| 118 | const error = (...args)=>logImpl(0, ...args); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 119 | const toss = function(...args){throw new Error(args.join(' '))}; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 120 | const capi = sqlite3.capi; |
stephan | 8948fbe | 2022-10-29 07:54:10 +0000 | [diff] [blame] | 121 | const wasm = sqlite3.wasm; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 122 | const sqlite3_vfs = capi.sqlite3_vfs; |
| 123 | const sqlite3_file = capi.sqlite3_file; |
| 124 | const sqlite3_io_methods = capi.sqlite3_io_methods; |
stephan | 509f405 | 2022-09-19 09:58:01 +0000 | [diff] [blame] | 125 | /** |
| 126 | Generic utilities for working with OPFS. This will get filled out |
| 127 | by the Promise setup and, on success, installed as sqlite3.opfs. |
| 128 | */ |
| 129 | const opfsUtil = Object.create(null); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 130 | /** |
| 131 | Not part of the public API. Solely for internal/development |
| 132 | use. |
| 133 | */ |
| 134 | opfsUtil.metrics = { |
| 135 | dump: function(){ |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 136 | let k, n = 0, t = 0, w = 0; |
| 137 | for(k in state.opIds){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 138 | const m = metrics[k]; |
| 139 | n += m.count; |
| 140 | t += m.time; |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 141 | w += m.wait; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 142 | m.avgTime = (m.count && m.time) ? (m.time / m.count) : 0; |
| 143 | m.avgWait = (m.count && m.wait) ? (m.wait / m.count) : 0; |
| 144 | } |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 145 | console.log(self.location.href, |
| 146 | "metrics for",self.location.href,":",metrics, |
| 147 | "\nTotal of",n,"op(s) for",t, |
| 148 | "ms (incl. "+w+" ms of waiting on the async side)"); |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 149 | console.log("Serialization metrics:",metrics.s11n); |
stephan | 3c272ba | 2022-10-04 00:54:00 +0000 | [diff] [blame] | 150 | W.postMessage({type:'opfs-async-metrics'}); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 151 | }, |
| 152 | reset: function(){ |
| 153 | let k; |
| 154 | const r = (m)=>(m.count = m.time = m.wait = 0); |
| 155 | for(k in state.opIds){ |
| 156 | r(metrics[k] = Object.create(null)); |
| 157 | } |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 158 | let s = metrics.s11n = Object.create(null); |
| 159 | s = s.serialize = Object.create(null); |
| 160 | s.count = s.time = 0; |
| 161 | s = metrics.s11n.deserialize = Object.create(null); |
| 162 | s.count = s.time = 0; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 163 | } |
| 164 | }/*metrics*/; |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 165 | const promiseReject = function(err){ |
| 166 | opfsVfs.dispose(); |
| 167 | return promiseReject_(err); |
| 168 | }; |
stephan | b0ab21d | 2022-11-03 22:14:47 +0000 | [diff] [blame] | 169 | const W = |
stephan | ee026c5 | 2022-11-18 02:29:59 +0000 | [diff] [blame^] | 170 | //#if SQLITE_JS_ESM |
stephan | b0ab21d | 2022-11-03 22:14:47 +0000 | [diff] [blame] | 171 | new Worker(new URL(options.proxyUri, import.meta.url)); |
stephan | ee026c5 | 2022-11-18 02:29:59 +0000 | [diff] [blame^] | 172 | //#else |
stephan | b0ab21d | 2022-11-03 22:14:47 +0000 | [diff] [blame] | 173 | new Worker(options.proxyUri); |
stephan | ee026c5 | 2022-11-18 02:29:59 +0000 | [diff] [blame^] | 174 | //#endif |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 175 | W._originalOnError = W.onerror /* will be restored later */; |
| 176 | W.onerror = function(err){ |
| 177 | // The error object doesn't contain any useful info when the |
| 178 | // failure is, e.g., that the remote script is 404. |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 179 | error("Error initializing OPFS asyncer:",err); |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 180 | promiseReject(new Error("Loading OPFS async Worker failed for unknown reasons.")); |
| 181 | }; |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 182 | const pDVfs = capi.sqlite3_vfs_find(null)/*pointer to default VFS*/; |
| 183 | const dVfs = pDVfs |
| 184 | ? new sqlite3_vfs(pDVfs) |
| 185 | : null /* dVfs will be null when sqlite3 is built with |
| 186 | SQLITE_OS_OTHER. Though we cannot currently handle |
| 187 | that case, the hope is to eventually be able to. */; |
| 188 | const opfsVfs = new sqlite3_vfs(); |
| 189 | const opfsIoMethods = new sqlite3_io_methods(); |
| 190 | opfsVfs.$iVersion = 2/*yes, two*/; |
| 191 | opfsVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof; |
| 192 | opfsVfs.$mxPathname = 1024/*sure, why not?*/; |
| 193 | opfsVfs.$zName = wasm.allocCString("opfs"); |
| 194 | // All C-side memory of opfsVfs is zeroed out, but just to be explicit: |
| 195 | opfsVfs.$xDlOpen = opfsVfs.$xDlError = opfsVfs.$xDlSym = opfsVfs.$xDlClose = null; |
| 196 | opfsVfs.ondispose = [ |
| 197 | '$zName', opfsVfs.$zName, |
| 198 | 'cleanup default VFS wrapper', ()=>(dVfs ? dVfs.dispose() : null), |
| 199 | 'cleanup opfsIoMethods', ()=>opfsIoMethods.dispose() |
| 200 | ]; |
| 201 | /** |
| 202 | Pedantic sidebar about opfsVfs.ondispose: the entries in that array |
| 203 | are items to clean up when opfsVfs.dispose() is called, but in this |
| 204 | environment it will never be called. The VFS instance simply |
| 205 | hangs around until the WASM module instance is cleaned up. We |
| 206 | "could" _hypothetically_ clean it up by "importing" an |
| 207 | sqlite3_os_end() impl into the wasm build, but the shutdown order |
| 208 | of the wasm engine and the JS one are undefined so there is no |
| 209 | guaranty that the opfsVfs instance would be available in one |
| 210 | environment or the other when sqlite3_os_end() is called (_if_ it |
| 211 | gets called at all in a wasm build, which is undefined). |
| 212 | */ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 213 | /** |
| 214 | State which we send to the async-api Worker or share with it. |
| 215 | This object must initially contain only cloneable or sharable |
| 216 | objects. After the worker's "inited" message arrives, other types |
| 217 | of data may be added to it. |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 218 | |
| 219 | For purposes of Atomics.wait() and Atomics.notify(), we use a |
| 220 | SharedArrayBuffer with one slot reserved for each of the API |
| 221 | proxy's methods. The sync side of the API uses Atomics.wait() |
| 222 | on the corresponding slot and the async side uses |
| 223 | Atomics.notify() on that slot. |
| 224 | |
| 225 | The approach of using a single SAB to serialize comms for all |
| 226 | instances might(?) lead to deadlock situations in multi-db |
| 227 | cases. We should probably have one SAB here with a single slot |
| 228 | for locking a per-file initialization step and then allocate a |
| 229 | separate SAB like the above one for each file. That will |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 230 | require a bit of acrobatics but should be feasible. The most |
| 231 | problematic part is that xOpen() would have to use |
| 232 | postMessage() to communicate its SharedArrayBuffer, and mixing |
| 233 | that approach with Atomics.wait/notify() gets a bit messy. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 234 | */ |
| 235 | const state = Object.create(null); |
| 236 | state.verbose = options.verbose; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 237 | state.littleEndian = (()=>{ |
| 238 | const buffer = new ArrayBuffer(2); |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 239 | new DataView(buffer).setInt16(0, 256, true /* ==>littleEndian */); |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 240 | // Int16Array uses the platform's endianness. |
| 241 | return new Int16Array(buffer)[0] === 256; |
| 242 | })(); |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 243 | /** |
| 244 | Whether the async counterpart should log exceptions to |
| 245 | the serialization channel. That produces a great deal of |
| 246 | noise for seemingly innocuous things like xAccess() checks |
| 247 | for missing files, so this option may have one of 3 values: |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 248 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 249 | 0 = no exception logging |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 250 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 251 | 1 = only log exceptions for "significant" ops like xOpen(), |
| 252 | xRead(), and xWrite(). |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 253 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 254 | 2 = log all exceptions. |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 255 | */ |
| 256 | state.asyncS11nExceptions = 1; |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 257 | /* Size of file I/O buffer block. 64k = max sqlite3 page size, and |
| 258 | xRead/xWrite() will never deal in blocks larger than that. */ |
| 259 | state.fileBufferSize = 1024 * 64; |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 260 | state.sabS11nOffset = state.fileBufferSize; |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 261 | /** |
| 262 | The size of the block in our SAB for serializing arguments and |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 263 | result values. Needs to be large enough to hold serialized |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 264 | values of any of the proxied APIs. Filenames are the largest |
| 265 | part but are limited to opfsVfs.$mxPathname bytes. |
| 266 | */ |
| 267 | state.sabS11nSize = opfsVfs.$mxPathname * 2; |
| 268 | /** |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 269 | The SAB used for all data I/O between the synchronous and |
| 270 | async halves (file i/o and arg/result s11n). |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 271 | */ |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 272 | state.sabIO = new SharedArrayBuffer( |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 273 | state.fileBufferSize/* file i/o block */ |
| 274 | + state.sabS11nSize/* argument/result serialization block */ |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 275 | ); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 276 | state.opIds = Object.create(null); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 277 | const metrics = Object.create(null); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 278 | { |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 279 | /* Indexes for use in our SharedArrayBuffer... */ |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 280 | let i = 0; |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 281 | /* SAB slot used to communicate which operation is desired |
| 282 | between both workers. This worker writes to it and the other |
| 283 | listens for changes. */ |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 284 | state.opIds.whichOp = i++; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 285 | /* Slot for storing return values. This worker listens to that |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 286 | slot and the other worker writes to it. */ |
| 287 | state.opIds.rc = i++; |
| 288 | /* Each function gets an ID which this worker writes to |
| 289 | the whichOp slot. The async-api worker uses Atomic.wait() |
| 290 | on the whichOp slot to figure out which operation to run |
| 291 | next. */ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 292 | state.opIds.xAccess = i++; |
| 293 | state.opIds.xClose = i++; |
| 294 | state.opIds.xDelete = i++; |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 295 | state.opIds.xDeleteNoWait = i++; |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 296 | state.opIds.xFileControl = i++; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 297 | state.opIds.xFileSize = i++; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 298 | state.opIds.xLock = i++; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 299 | state.opIds.xOpen = i++; |
| 300 | state.opIds.xRead = i++; |
| 301 | state.opIds.xSleep = i++; |
| 302 | state.opIds.xSync = i++; |
| 303 | state.opIds.xTruncate = i++; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 304 | state.opIds.xUnlock = i++; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 305 | state.opIds.xWrite = i++; |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 306 | state.opIds.mkdir = i++; |
stephan | 3c272ba | 2022-10-04 00:54:00 +0000 | [diff] [blame] | 307 | state.opIds['opfs-async-metrics'] = i++; |
| 308 | state.opIds['opfs-async-shutdown'] = i++; |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 309 | /* The retry slot is used by the async part for wait-and-retry |
| 310 | semantics. Though we could hypothetically use the xSleep slot |
| 311 | for that, doing so might lead to undesired side effects. */ |
| 312 | state.opIds.retry = i++; |
| 313 | state.sabOP = new SharedArrayBuffer( |
| 314 | i * 4/* ==sizeof int32, noting that Atomics.wait() and friends |
| 315 | can only function on Int32Array views of an SAB. */); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 316 | opfsUtil.metrics.reset(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 317 | } |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 318 | /** |
| 319 | SQLITE_xxx constants to export to the async worker |
| 320 | counterpart... |
| 321 | */ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 322 | state.sq3Codes = Object.create(null); |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 323 | [ |
stephan | f45c337 | 2022-11-02 11:53:31 +0000 | [diff] [blame] | 324 | 'SQLITE_ACCESS_EXISTS', |
| 325 | 'SQLITE_ACCESS_READWRITE', |
stephan | 43b442a | 2022-10-31 11:53:34 +0000 | [diff] [blame] | 326 | 'SQLITE_ERROR', |
| 327 | 'SQLITE_IOERR', |
| 328 | 'SQLITE_IOERR_ACCESS', |
| 329 | 'SQLITE_IOERR_CLOSE', |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 330 | 'SQLITE_IOERR_DELETE', |
stephan | 43b442a | 2022-10-31 11:53:34 +0000 | [diff] [blame] | 331 | 'SQLITE_IOERR_FSYNC', |
| 332 | 'SQLITE_IOERR_LOCK', |
| 333 | 'SQLITE_IOERR_READ', |
| 334 | 'SQLITE_IOERR_SHORT_READ', |
| 335 | 'SQLITE_IOERR_TRUNCATE', |
| 336 | 'SQLITE_IOERR_UNLOCK', |
| 337 | 'SQLITE_IOERR_WRITE', |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 338 | 'SQLITE_LOCK_EXCLUSIVE', |
stephan | 43b442a | 2022-10-31 11:53:34 +0000 | [diff] [blame] | 339 | 'SQLITE_LOCK_NONE', |
| 340 | 'SQLITE_LOCK_PENDING', |
| 341 | 'SQLITE_LOCK_RESERVED', |
| 342 | 'SQLITE_LOCK_SHARED', |
| 343 | 'SQLITE_MISUSE', |
| 344 | 'SQLITE_NOTFOUND', |
| 345 | 'SQLITE_OPEN_CREATE', |
| 346 | 'SQLITE_OPEN_DELETEONCLOSE', |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 347 | 'SQLITE_OPEN_READONLY' |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 348 | ].forEach((k)=>{ |
| 349 | if(undefined === (state.sq3Codes[k] = capi[k])){ |
| 350 | toss("Maintenance required: not found:",k); |
| 351 | } |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 352 | }); |
stephan | 3961b26 | 2022-08-10 11:26:08 +0000 | [diff] [blame] | 353 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 354 | /** |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 355 | Runs the given operation (by name) in the async worker |
| 356 | counterpart, waits for its response, and returns the result |
| 357 | which the async worker writes to SAB[state.opIds.rc]. The |
| 358 | 2nd and subsequent arguments must be the aruguments for the |
| 359 | async op. |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 360 | */ |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 361 | const opRun = (op,...args)=>{ |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 362 | const opNdx = state.opIds[op] || toss("Invalid op ID:",op); |
| 363 | state.s11n.serialize(...args); |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 364 | Atomics.store(state.sabOPView, state.opIds.rc, -1); |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 365 | Atomics.store(state.sabOPView, state.opIds.whichOp, opNdx); |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 366 | Atomics.notify(state.sabOPView, state.opIds.whichOp) |
| 367 | /* async thread will take over here */; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 368 | const t = performance.now(); |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 369 | Atomics.wait(state.sabOPView, state.opIds.rc, -1) |
| 370 | /* When this wait() call returns, the async half will have |
| 371 | completed the operation and reported its results. */; |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 372 | const rc = Atomics.load(state.sabOPView, state.opIds.rc); |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 373 | metrics[op].wait += performance.now() - t; |
| 374 | if(rc && state.asyncS11nExceptions){ |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 375 | const err = state.s11n.deserialize(); |
| 376 | if(err) error(op+"() async error:",...err); |
| 377 | } |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 378 | return rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 379 | }; |
| 380 | |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 381 | /** |
| 382 | Not part of the public API. Only for test/development use. |
| 383 | */ |
| 384 | opfsUtil.debug = { |
| 385 | asyncShutdown: ()=>{ |
| 386 | warn("Shutting down OPFS async listener. The OPFS VFS will no longer work."); |
| 387 | opRun('opfs-async-shutdown'); |
| 388 | }, |
| 389 | asyncRestart: ()=>{ |
| 390 | warn("Attempting to restart OPFS VFS async listener. Might work, might not."); |
| 391 | W.postMessage({type: 'opfs-async-restart'}); |
| 392 | } |
| 393 | }; |
| 394 | |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 395 | const initS11n = ()=>{ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 396 | /** |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 397 | !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |
| 398 | ACHTUNG: this code is 100% duplicated in the other half of |
| 399 | this proxy! The documentation is maintained in the |
| 400 | "synchronous half". |
| 401 | !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 402 | |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 403 | This proxy de/serializes cross-thread function arguments and |
| 404 | output-pointer values via the state.sabIO SharedArrayBuffer, |
| 405 | using the region defined by (state.sabS11nOffset, |
| 406 | state.sabS11nOffset]. Only one dataset is recorded at a time. |
| 407 | |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 408 | This is not a general-purpose format. It only supports the |
| 409 | range of operations, and data sizes, needed by the |
| 410 | sqlite3_vfs and sqlite3_io_methods operations. Serialized |
| 411 | data are transient and this serialization algorithm may |
| 412 | change at any time. |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 413 | |
| 414 | The data format can be succinctly summarized as: |
| 415 | |
| 416 | Nt...Td...D |
| 417 | |
| 418 | Where: |
| 419 | |
| 420 | - N = number of entries (1 byte) |
| 421 | |
| 422 | - t = type ID of first argument (1 byte) |
| 423 | |
| 424 | - ...T = type IDs of the 2nd and subsequent arguments (1 byte |
| 425 | each). |
| 426 | |
| 427 | - d = raw bytes of first argument (per-type size). |
| 428 | |
| 429 | - ...D = raw bytes of the 2nd and subsequent arguments (per-type |
| 430 | size). |
| 431 | |
| 432 | All types except strings have fixed sizes. Strings are stored |
| 433 | using their TextEncoder/TextDecoder representations. It would |
| 434 | arguably make more sense to store them as Int16Arrays of |
| 435 | their JS character values, but how best/fastest to get that |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 436 | in and out of string form is an open point. Initial |
| 437 | experimentation with that approach did not gain us any speed. |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 438 | |
| 439 | Historical note: this impl was initially about 1% this size by |
| 440 | using using JSON.stringify/parse(), but using fit-to-purpose |
| 441 | serialization saves considerable runtime. |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 442 | */ |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 443 | if(state.s11n) return state.s11n; |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 444 | const textDecoder = new TextDecoder(), |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 445 | textEncoder = new TextEncoder('utf-8'), |
| 446 | viewU8 = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize), |
| 447 | viewDV = new DataView(state.sabIO, state.sabS11nOffset, state.sabS11nSize); |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 448 | state.s11n = Object.create(null); |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 449 | /* Only arguments and return values of these types may be |
| 450 | serialized. This covers the whole range of types needed by the |
| 451 | sqlite3_vfs API. */ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 452 | const TypeIds = Object.create(null); |
| 453 | TypeIds.number = { id: 1, size: 8, getter: 'getFloat64', setter: 'setFloat64' }; |
| 454 | TypeIds.bigint = { id: 2, size: 8, getter: 'getBigInt64', setter: 'setBigInt64' }; |
| 455 | TypeIds.boolean = { id: 3, size: 4, getter: 'getInt32', setter: 'setInt32' }; |
| 456 | TypeIds.string = { id: 4 }; |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 457 | |
| 458 | const getTypeId = (v)=>( |
| 459 | TypeIds[typeof v] |
| 460 | || toss("Maintenance required: this value type cannot be serialized.",v) |
| 461 | ); |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 462 | const getTypeIdById = (tid)=>{ |
| 463 | switch(tid){ |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 464 | case TypeIds.number.id: return TypeIds.number; |
| 465 | case TypeIds.bigint.id: return TypeIds.bigint; |
| 466 | case TypeIds.boolean.id: return TypeIds.boolean; |
| 467 | case TypeIds.string.id: return TypeIds.string; |
| 468 | default: toss("Invalid type ID:",tid); |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 469 | } |
| 470 | }; |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 471 | |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 472 | /** |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 473 | Returns an array of the deserialized state stored by the most |
| 474 | recent serialize() operation (from from this thread or the |
stephan | da26415 | 2022-11-10 13:14:30 +0000 | [diff] [blame] | 475 | counterpart thread), or null if the serialization buffer is |
| 476 | empty. If passed a truthy argument, the serialization buffer |
| 477 | is cleared after deserialization. |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 478 | */ |
stephan | da26415 | 2022-11-10 13:14:30 +0000 | [diff] [blame] | 479 | state.s11n.deserialize = function(clear=false){ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 480 | ++metrics.s11n.deserialize.count; |
| 481 | const t = performance.now(); |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 482 | const argc = viewU8[0]; |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 483 | const rc = argc ? [] : null; |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 484 | if(argc){ |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 485 | const typeIds = []; |
| 486 | let offset = 1, i, n, v; |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 487 | for(i = 0; i < argc; ++i, ++offset){ |
| 488 | typeIds.push(getTypeIdById(viewU8[offset])); |
| 489 | } |
| 490 | for(i = 0; i < argc; ++i){ |
| 491 | const t = typeIds[i]; |
| 492 | if(t.getter){ |
| 493 | v = viewDV[t.getter](offset, state.littleEndian); |
| 494 | offset += t.size; |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 495 | }else{/*String*/ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 496 | n = viewDV.getInt32(offset, state.littleEndian); |
| 497 | offset += 4; |
| 498 | v = textDecoder.decode(viewU8.slice(offset, offset+n)); |
| 499 | offset += n; |
| 500 | } |
| 501 | rc.push(v); |
| 502 | } |
| 503 | } |
stephan | da26415 | 2022-11-10 13:14:30 +0000 | [diff] [blame] | 504 | if(clear) viewU8[0] = 0; |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 505 | //log("deserialize:",argc, rc); |
| 506 | metrics.s11n.deserialize.time += performance.now() - t; |
| 507 | return rc; |
| 508 | }; |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 509 | |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 510 | /** |
| 511 | Serializes all arguments to the shared buffer for consumption |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 512 | by the counterpart thread. |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 513 | |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 514 | This routine is only intended for serializing OPFS VFS |
| 515 | arguments and (in at least one special case) result values, |
| 516 | and the buffer is sized to be able to comfortably handle |
| 517 | those. |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 518 | |
| 519 | If passed no arguments then it zeroes out the serialization |
| 520 | state. |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 521 | */ |
| 522 | state.s11n.serialize = function(...args){ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 523 | const t = performance.now(); |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 524 | ++metrics.s11n.serialize.count; |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 525 | if(args.length){ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 526 | //log("serialize():",args); |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 527 | const typeIds = []; |
| 528 | let i = 0, offset = 1; |
| 529 | viewU8[0] = args.length & 0xff /* header = # of args */; |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 530 | for(; i < args.length; ++i, ++offset){ |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 531 | /* Write the TypeIds.id value into the next args.length |
| 532 | bytes. */ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 533 | typeIds.push(getTypeId(args[i])); |
| 534 | viewU8[offset] = typeIds[i].id; |
| 535 | } |
| 536 | for(i = 0; i < args.length; ++i) { |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 537 | /* Deserialize the following bytes based on their |
| 538 | corresponding TypeIds.id from the header. */ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 539 | const t = typeIds[i]; |
| 540 | if(t.setter){ |
| 541 | viewDV[t.setter](offset, args[i], state.littleEndian); |
| 542 | offset += t.size; |
stephan | 72ab400 | 2022-09-21 12:27:35 +0000 | [diff] [blame] | 543 | }else{/*String*/ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 544 | const s = textEncoder.encode(args[i]); |
| 545 | viewDV.setInt32(offset, s.byteLength, state.littleEndian); |
| 546 | offset += 4; |
| 547 | viewU8.set(s, offset); |
| 548 | offset += s.byteLength; |
| 549 | } |
| 550 | } |
| 551 | //log("serialize() result:",viewU8.slice(0,offset)); |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 552 | }else{ |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 553 | viewU8[0] = 0; |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 554 | } |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 555 | metrics.s11n.serialize.time += performance.now() - t; |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 556 | }; |
| 557 | return state.s11n; |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 558 | }/*initS11n()*/; |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 559 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 560 | /** |
| 561 | Generates a random ASCII string len characters long, intended for |
| 562 | use as a temporary file name. |
| 563 | */ |
| 564 | const randomFilename = function f(len=16){ |
| 565 | if(!f._chars){ |
| 566 | f._chars = "abcdefghijklmnopqrstuvwxyz"+ |
| 567 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ |
| 568 | "012346789"; |
| 569 | f._n = f._chars.length; |
| 570 | } |
| 571 | const a = []; |
| 572 | let i = 0; |
| 573 | for( ; i < len; ++i){ |
| 574 | const ndx = Math.random() * (f._n * 64) % f._n | 0; |
| 575 | a[i] = f._chars[ndx]; |
| 576 | } |
stephan | b0ab21d | 2022-11-03 22:14:47 +0000 | [diff] [blame] | 577 | return a.join(""); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 578 | }; |
| 579 | |
| 580 | /** |
| 581 | Map of sqlite3_file pointers to objects constructed by xOpen(). |
| 582 | */ |
| 583 | const __openFiles = Object.create(null); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 584 | |
| 585 | /** |
| 586 | Installs a StructBinder-bound function pointer member of the |
| 587 | given name and function in the given StructType target object. |
| 588 | It creates a WASM proxy for the given function and arranges for |
| 589 | that proxy to be cleaned up when tgt.dispose() is called. Throws |
| 590 | on the slightest hint of error (e.g. tgt is-not-a StructType, |
| 591 | name does not map to a struct-bound member, etc.). |
| 592 | |
| 593 | Returns a proxy for this function which is bound to tgt and takes |
| 594 | 2 args (name,func). That function returns the same thing, |
| 595 | permitting calls to be chained. |
| 596 | |
| 597 | If called with only 1 arg, it has no side effects but returns a |
| 598 | func with the same signature as described above. |
| 599 | */ |
| 600 | const installMethod = function callee(tgt, name, func){ |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 601 | if(!(tgt instanceof sqlite3.StructBinder.StructType)){ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 602 | toss("Usage error: target object is-not-a StructType."); |
| 603 | } |
| 604 | if(1===arguments.length){ |
| 605 | return (n,f)=>callee(tgt,n,f); |
| 606 | } |
| 607 | if(!callee.argcProxy){ |
| 608 | callee.argcProxy = function(func,sig){ |
| 609 | return function(...args){ |
| 610 | if(func.length!==arguments.length){ |
| 611 | toss("Argument mismatch. Native signature is:",sig); |
| 612 | } |
| 613 | return func.apply(this, args); |
| 614 | } |
| 615 | }; |
| 616 | callee.removeFuncList = function(){ |
| 617 | if(this.ondispose.__removeFuncList){ |
| 618 | this.ondispose.__removeFuncList.forEach( |
| 619 | (v,ndx)=>{ |
| 620 | if('number'===typeof v){ |
| 621 | try{wasm.uninstallFunction(v)} |
| 622 | catch(e){/*ignore*/} |
| 623 | } |
| 624 | /* else it's a descriptive label for the next number in |
| 625 | the list. */ |
| 626 | } |
| 627 | ); |
| 628 | delete this.ondispose.__removeFuncList; |
| 629 | } |
| 630 | }; |
| 631 | }/*static init*/ |
| 632 | const sigN = tgt.memberSignature(name); |
| 633 | if(sigN.length<2){ |
| 634 | toss("Member",name," is not a function pointer. Signature =",sigN); |
| 635 | } |
| 636 | const memKey = tgt.memberKey(name); |
stephan | c2ccd67 | 2022-09-20 10:47:36 +0000 | [diff] [blame] | 637 | const fProxy = 0 |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 638 | /** This middle-man proxy is only for use during development, to |
| 639 | confirm that we always pass the proper number of |
| 640 | arguments. We know that the C-level code will always use the |
| 641 | correct argument count. */ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 642 | ? callee.argcProxy(func, sigN) |
| 643 | : func; |
| 644 | const pFunc = wasm.installFunction(fProxy, tgt.memberSignature(name, true)); |
| 645 | tgt[memKey] = pFunc; |
| 646 | if(!tgt.ondispose) tgt.ondispose = []; |
| 647 | if(!tgt.ondispose.__removeFuncList){ |
| 648 | tgt.ondispose.push('ondispose.__removeFuncList handler', |
| 649 | callee.removeFuncList); |
| 650 | tgt.ondispose.__removeFuncList = []; |
| 651 | } |
| 652 | tgt.ondispose.__removeFuncList.push(memKey, pFunc); |
| 653 | return (n,f)=>callee(tgt, n, f); |
| 654 | }/*installMethod*/; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 655 | |
| 656 | const opTimer = Object.create(null); |
| 657 | opTimer.op = undefined; |
| 658 | opTimer.start = undefined; |
| 659 | const mTimeStart = (op)=>{ |
| 660 | opTimer.start = performance.now(); |
| 661 | opTimer.op = op; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 662 | ++metrics[op].count; |
| 663 | }; |
| 664 | const mTimeEnd = ()=>( |
| 665 | metrics[opTimer.op].time += performance.now() - opTimer.start |
| 666 | ); |
| 667 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 668 | /** |
| 669 | Impls for the sqlite3_io_methods methods. Maintenance reminder: |
| 670 | members are in alphabetical order to simplify finding them. |
| 671 | */ |
| 672 | const ioSyncWrappers = { |
| 673 | xCheckReservedLock: function(pFile,pOut){ |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 674 | /** |
| 675 | As of late 2022, only a single lock can be held on an OPFS |
| 676 | file. We have no way of checking whether any _other_ db |
| 677 | connection has a lock except by trying to obtain and (on |
| 678 | success) release a sync-handle for it, but doing so would |
| 679 | involve an inherent race condition. For the time being, |
| 680 | pending a better solution, we simply report whether the |
| 681 | given pFile instance has a lock. |
| 682 | */ |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 683 | const f = __openFiles[pFile]; |
| 684 | wasm.setMemValue(pOut, f.lockMode ? 1 : 0, 'i32'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 685 | return 0; |
| 686 | }, |
| 687 | xClose: function(pFile){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 688 | mTimeStart('xClose'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 689 | let rc = 0; |
| 690 | const f = __openFiles[pFile]; |
| 691 | if(f){ |
| 692 | delete __openFiles[pFile]; |
| 693 | rc = opRun('xClose', pFile); |
| 694 | if(f.sq3File) f.sq3File.dispose(); |
| 695 | } |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 696 | mTimeEnd(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 697 | return rc; |
| 698 | }, |
| 699 | xDeviceCharacteristics: function(pFile){ |
| 700 | //debug("xDeviceCharacteristics(",pFile,")"); |
| 701 | return capi.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN; |
| 702 | }, |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 703 | xFileControl: function(pFile, opId, pArg){ |
| 704 | mTimeStart('xFileControl'); |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 705 | const rc = (capi.SQLITE_FCNTL_SYNC===opId) |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 706 | ? opRun('xSync', pFile, 0) |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 707 | : capi.SQLITE_NOTFOUND; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 708 | mTimeEnd(); |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 709 | return rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 710 | }, |
| 711 | xFileSize: function(pFile,pSz64){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 712 | mTimeStart('xFileSize'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 713 | const rc = opRun('xFileSize', pFile); |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 714 | if(0==rc){ |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 715 | const sz = state.s11n.deserialize()[0]; |
stephan | 278d3fa | 2022-09-26 13:55:10 +0000 | [diff] [blame] | 716 | wasm.setMemValue(pSz64, sz, 'i64'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 717 | } |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 718 | mTimeEnd(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 719 | return rc; |
| 720 | }, |
| 721 | xLock: function(pFile,lockType){ |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 722 | mTimeStart('xLock'); |
| 723 | const f = __openFiles[pFile]; |
| 724 | let rc = 0; |
| 725 | if( capi.SQLITE_LOCK_NONE === f.lockType ) { |
| 726 | rc = opRun('xLock', pFile, lockType); |
| 727 | if( 0===rc ) f.lockType = lockType; |
| 728 | }else{ |
| 729 | f.lockType = lockType; |
| 730 | } |
| 731 | mTimeEnd(); |
| 732 | return rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 733 | }, |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 734 | xRead: function(pFile,pDest,n,offset64){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 735 | mTimeStart('xRead'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 736 | const f = __openFiles[pFile]; |
| 737 | let rc; |
| 738 | try { |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 739 | rc = opRun('xRead',pFile, n, Number(offset64)); |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 740 | if(0===rc || capi.SQLITE_IOERR_SHORT_READ===rc){ |
| 741 | /** |
| 742 | Results get written to the SharedArrayBuffer f.sabView. |
| 743 | Because the heap is _not_ a SharedArrayBuffer, we have |
| 744 | to copy the results. TypedArray.set() seems to be the |
| 745 | fastest way to copy this. */ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 746 | wasm.heap8u().set(f.sabView.subarray(0, n), pDest); |
stephan | 862281f | 2022-09-19 09:25:25 +0000 | [diff] [blame] | 747 | } |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 748 | }catch(e){ |
| 749 | error("xRead(",arguments,") failed:",e,f); |
| 750 | rc = capi.SQLITE_IOERR_READ; |
| 751 | } |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 752 | mTimeEnd(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 753 | return rc; |
| 754 | }, |
| 755 | xSync: function(pFile,flags){ |
stephan | aec046a | 2022-09-19 18:22:29 +0000 | [diff] [blame] | 756 | ++metrics.xSync.count; |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 757 | return 0; // impl'd in xFileControl() |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 758 | }, |
| 759 | xTruncate: function(pFile,sz64){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 760 | mTimeStart('xTruncate'); |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 761 | const rc = opRun('xTruncate', pFile, Number(sz64)); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 762 | mTimeEnd(); |
| 763 | return rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 764 | }, |
| 765 | xUnlock: function(pFile,lockType){ |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 766 | mTimeStart('xUnlock'); |
| 767 | const f = __openFiles[pFile]; |
| 768 | let rc = 0; |
| 769 | if( capi.SQLITE_LOCK_NONE === lockType |
| 770 | && f.lockType ){ |
| 771 | rc = opRun('xUnlock', pFile, lockType); |
| 772 | } |
| 773 | if( 0===rc ) f.lockType = lockType; |
| 774 | mTimeEnd(); |
| 775 | return rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 776 | }, |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 777 | xWrite: function(pFile,pSrc,n,offset64){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 778 | mTimeStart('xWrite'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 779 | const f = __openFiles[pFile]; |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 780 | let rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 781 | try { |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 782 | f.sabView.set(wasm.heap8u().subarray(pSrc, pSrc+n)); |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 783 | rc = opRun('xWrite', pFile, n, Number(offset64)); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 784 | }catch(e){ |
| 785 | error("xWrite(",arguments,") failed:",e,f); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 786 | rc = capi.SQLITE_IOERR_WRITE; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 787 | } |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 788 | mTimeEnd(); |
| 789 | return rc; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 790 | } |
| 791 | }/*ioSyncWrappers*/; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 792 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 793 | /** |
| 794 | Impls for the sqlite3_vfs methods. Maintenance reminder: members |
| 795 | are in alphabetical order to simplify finding them. |
| 796 | */ |
| 797 | const vfsSyncWrappers = { |
| 798 | xAccess: function(pVfs,zName,flags,pOut){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 799 | mTimeStart('xAccess'); |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 800 | const rc = opRun('xAccess', wasm.cstringToJs(zName)); |
| 801 | wasm.setMemValue( pOut, (rc ? 0 : 1), 'i32' ); |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 802 | mTimeEnd(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 803 | return 0; |
| 804 | }, |
| 805 | xCurrentTime: function(pVfs,pOut){ |
| 806 | /* If it turns out that we need to adjust for timezone, see: |
| 807 | https://stackoverflow.com/a/11760121/1458521 */ |
| 808 | wasm.setMemValue(pOut, 2440587.5 + (new Date().getTime()/86400000), |
| 809 | 'double'); |
| 810 | return 0; |
| 811 | }, |
| 812 | xCurrentTimeInt64: function(pVfs,pOut){ |
| 813 | // TODO: confirm that this calculation is correct |
| 814 | wasm.setMemValue(pOut, (2440587.5 * 86400000) + new Date().getTime(), |
| 815 | 'i64'); |
| 816 | return 0; |
| 817 | }, |
| 818 | xDelete: function(pVfs, zName, doSyncDir){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 819 | mTimeStart('xDelete'); |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 820 | opRun('xDelete', wasm.cstringToJs(zName), doSyncDir, false); |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 821 | /* We're ignoring errors because we cannot yet differentiate |
| 822 | between harmless and non-harmless failures. */ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 823 | mTimeEnd(); |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 824 | return 0; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 825 | }, |
| 826 | xFullPathname: function(pVfs,zName,nOut,pOut){ |
| 827 | /* Until/unless we have some notion of "current dir" |
| 828 | in OPFS, simply copy zName to pOut... */ |
| 829 | const i = wasm.cstrncpy(pOut, zName, nOut); |
| 830 | return i<nOut ? 0 : capi.SQLITE_CANTOPEN |
| 831 | /*CANTOPEN is required by the docs but SQLITE_RANGE would be a closer match*/; |
| 832 | }, |
| 833 | xGetLastError: function(pVfs,nOut,pOut){ |
| 834 | /* TODO: store exception.message values from the async |
| 835 | partner in a dedicated SharedArrayBuffer, noting that we'd have |
| 836 | to encode them... TextEncoder can do that for us. */ |
| 837 | warn("OPFS xGetLastError() has nothing sensible to return."); |
| 838 | return 0; |
| 839 | }, |
stephan | 8766fd2 | 2022-09-19 05:19:04 +0000 | [diff] [blame] | 840 | //xSleep is optionally defined below |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 841 | xOpen: function f(pVfs, zName, pFile, flags, pOutFlags){ |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 842 | mTimeStart('xOpen'); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 843 | if(0===zName){ |
| 844 | zName = randomFilename(); |
| 845 | }else if('number'===typeof zName){ |
| 846 | zName = wasm.cstringToJs(zName); |
| 847 | } |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 848 | const fh = Object.create(null); |
| 849 | fh.fid = pFile; |
| 850 | fh.filename = zName; |
| 851 | fh.sab = new SharedArrayBuffer(state.fileBufferSize); |
| 852 | fh.flags = flags; |
| 853 | const rc = opRun('xOpen', pFile, zName, flags); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 854 | if(!rc){ |
| 855 | /* Recall that sqlite3_vfs::xClose() will be called, even on |
| 856 | error, unless pFile->pMethods is NULL. */ |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 857 | if(fh.readOnly){ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 858 | wasm.setMemValue(pOutFlags, capi.SQLITE_OPEN_READONLY, 'i32'); |
| 859 | } |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 860 | __openFiles[pFile] = fh; |
| 861 | fh.sabView = state.sabFileBufView; |
| 862 | fh.sq3File = new sqlite3_file(pFile); |
| 863 | fh.sq3File.$pMethods = opfsIoMethods.pointer; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 864 | fh.lockType = capi.SQLITE_LOCK_NONE; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 865 | } |
stephan | f815011 | 2022-09-19 17:09:09 +0000 | [diff] [blame] | 866 | mTimeEnd(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 867 | return rc; |
| 868 | }/*xOpen()*/ |
| 869 | }/*vfsSyncWrappers*/; |
| 870 | |
stephan | 8766fd2 | 2022-09-19 05:19:04 +0000 | [diff] [blame] | 871 | if(dVfs){ |
| 872 | opfsVfs.$xRandomness = dVfs.$xRandomness; |
| 873 | opfsVfs.$xSleep = dVfs.$xSleep; |
| 874 | } |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 875 | if(!opfsVfs.$xRandomness){ |
| 876 | /* If the default VFS has no xRandomness(), add a basic JS impl... */ |
| 877 | vfsSyncWrappers.xRandomness = function(pVfs, nOut, pOut){ |
| 878 | const heap = wasm.heap8u(); |
| 879 | let i = 0; |
| 880 | for(; i < nOut; ++i) heap[pOut + i] = (Math.random()*255000) & 0xFF; |
| 881 | return i; |
| 882 | }; |
| 883 | } |
| 884 | if(!opfsVfs.$xSleep){ |
| 885 | /* If we can inherit an xSleep() impl from the default VFS then |
stephan | 8766fd2 | 2022-09-19 05:19:04 +0000 | [diff] [blame] | 886 | assume it's sane and use it, otherwise install a JS-based |
| 887 | one. */ |
| 888 | vfsSyncWrappers.xSleep = function(pVfs,ms){ |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 889 | Atomics.wait(state.sabOPView, state.opIds.xSleep, 0, ms); |
stephan | 8766fd2 | 2022-09-19 05:19:04 +0000 | [diff] [blame] | 890 | return 0; |
| 891 | }; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 892 | } |
| 893 | |
| 894 | /* Install the vfs/io_methods into their C-level shared instances... */ |
stephan | 278d3fa | 2022-09-26 13:55:10 +0000 | [diff] [blame] | 895 | for(let k of Object.keys(ioSyncWrappers)){ |
| 896 | installMethod(opfsIoMethods, k, ioSyncWrappers[k]); |
| 897 | } |
| 898 | for(let k of Object.keys(vfsSyncWrappers)){ |
| 899 | installMethod(opfsVfs, k, vfsSyncWrappers[k]); |
| 900 | } |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 901 | |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 902 | /** |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 903 | Expects an OPFS file path. It gets resolved, such that ".." |
| 904 | components are properly expanded, and returned. If the 2nd arg |
| 905 | is true, the result is returned as an array of path elements, |
| 906 | else an absolute path string is returned. |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 907 | */ |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 908 | opfsUtil.getResolvedPath = function(filename,splitIt){ |
| 909 | const p = new URL(filename, "file://irrelevant").pathname; |
| 910 | return splitIt ? p.split('/').filter((v)=>!!v) : p; |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 911 | }; |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 912 | |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 913 | /** |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 914 | Takes the absolute path to a filesystem element. Returns an |
| 915 | array of [handleOfContainingDir, filename]. If the 2nd argument |
| 916 | is truthy then each directory element leading to the file is |
| 917 | created along the way. Throws if any creation or resolution |
| 918 | fails. |
| 919 | */ |
| 920 | opfsUtil.getDirForFilename = async function f(absFilename, createDirs = false){ |
| 921 | const path = opfsUtil.getResolvedPath(absFilename, true); |
| 922 | const filename = path.pop(); |
| 923 | let dh = opfsUtil.rootDirectory; |
| 924 | for(const dirName of path){ |
| 925 | if(dirName){ |
| 926 | dh = await dh.getDirectoryHandle(dirName, {create: !!createDirs}); |
| 927 | } |
| 928 | } |
| 929 | return [dh, filename]; |
| 930 | }; |
| 931 | |
| 932 | /** |
| 933 | Creates the given directory name, recursively, in |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 934 | the OPFS filesystem. Returns true if it succeeds or the |
| 935 | directory already exists, else false. |
| 936 | */ |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 937 | opfsUtil.mkdir = async function(absDirName){ |
| 938 | try { |
| 939 | await opfsUtil.getDirForFilename(absDirName+"/filepart", true); |
| 940 | return true; |
| 941 | }catch(e){ |
| 942 | //console.warn("mkdir(",absDirName,") failed:",e); |
| 943 | return false; |
| 944 | } |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 945 | }; |
| 946 | /** |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 947 | Checks whether the given OPFS filesystem entry exists, |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 948 | returning true if it does, false if it doesn't. |
| 949 | */ |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 950 | opfsUtil.entryExists = async function(fsEntryName){ |
| 951 | try { |
stephan | f45c337 | 2022-11-02 11:53:31 +0000 | [diff] [blame] | 952 | const [dh, fn] = await opfsUtil.getDirForFilename(fsEntryName); |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 953 | await dh.getFileHandle(fn); |
| 954 | return true; |
| 955 | }catch(e){ |
| 956 | return false; |
| 957 | } |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 958 | }; |
| 959 | |
| 960 | /** |
| 961 | Generates a random ASCII string, intended for use as a |
| 962 | temporary file name. Its argument is the length of the string, |
| 963 | defaulting to 16. |
| 964 | */ |
| 965 | opfsUtil.randomFilename = randomFilename; |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 966 | |
| 967 | /** |
| 968 | Re-registers the OPFS VFS. This is intended only for odd use |
| 969 | cases which have to call sqlite3_shutdown() as part of their |
| 970 | initialization process, which will unregister the VFS |
| 971 | registered by installOpfsVfs(). If passed a truthy value, the |
| 972 | OPFS VFS is registered as the default VFS, else it is not made |
| 973 | the default. Returns the result of the the |
| 974 | sqlite3_vfs_register() call. |
| 975 | |
| 976 | Design note: the problem of having to re-register things after |
| 977 | a shutdown/initialize pair is more general. How to best plug |
| 978 | that in to the library is unclear. In particular, we cannot |
| 979 | hook in to any C-side calls to sqlite3_initialize(), so we |
| 980 | cannot add an after-initialize callback mechanism. |
| 981 | */ |
stephan | 3d64548 | 2022-09-27 09:17:37 +0000 | [diff] [blame] | 982 | opfsUtil.registerVfs = (asDefault=false)=>{ |
stephan | 8948fbe | 2022-10-29 07:54:10 +0000 | [diff] [blame] | 983 | return wasm.exports.sqlite3_vfs_register( |
stephan | 56fae74 | 2022-09-24 10:12:19 +0000 | [diff] [blame] | 984 | opfsVfs.pointer, asDefault ? 1 : 0 |
| 985 | ); |
| 986 | }; |
stephan | 3d64548 | 2022-09-27 09:17:37 +0000 | [diff] [blame] | 987 | |
stephan | 3c272ba | 2022-10-04 00:54:00 +0000 | [diff] [blame] | 988 | /** |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 989 | Returns a promise which resolves to an object which represents |
| 990 | all files and directories in the OPFS tree. The top-most object |
| 991 | has two properties: `dirs` is an array of directory entries |
| 992 | (described below) and `files` is a list of file names for all |
| 993 | files in that directory. |
| 994 | |
| 995 | Traversal starts at sqlite3.opfs.rootDirectory. |
| 996 | |
| 997 | Each `dirs` entry is an object in this form: |
| 998 | |
| 999 | ``` |
| 1000 | { name: directoryName, |
| 1001 | dirs: [...subdirs], |
| 1002 | files: [...file names] |
| 1003 | } |
| 1004 | ``` |
| 1005 | |
| 1006 | The `files` and `subdirs` entries are always set but may be |
| 1007 | empty arrays. |
| 1008 | |
| 1009 | The returned object has the same structure but its `name` is |
| 1010 | an empty string. All returned objects are created with |
| 1011 | Object.create(null), so have no prototype. |
| 1012 | |
| 1013 | Design note: the entries do not contain more information, |
| 1014 | e.g. file sizes, because getting such info is not only |
| 1015 | expensive but is subject to locking-related errors. |
stephan | 3c272ba | 2022-10-04 00:54:00 +0000 | [diff] [blame] | 1016 | */ |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 1017 | opfsUtil.treeList = async function(){ |
| 1018 | const doDir = async function callee(dirHandle,tgt){ |
| 1019 | tgt.name = dirHandle.name; |
| 1020 | tgt.dirs = []; |
| 1021 | tgt.files = []; |
| 1022 | for await (const handle of dirHandle.values()){ |
| 1023 | if('directory' === handle.kind){ |
| 1024 | const subDir = Object.create(null); |
| 1025 | tgt.dirs.push(subDir); |
| 1026 | await callee(handle, subDir); |
| 1027 | }else{ |
| 1028 | tgt.files.push(handle.name); |
| 1029 | } |
| 1030 | } |
| 1031 | }; |
| 1032 | const root = Object.create(null); |
| 1033 | await doDir(opfsUtil.rootDirectory, root); |
| 1034 | return root; |
| 1035 | }; |
| 1036 | |
| 1037 | /** |
| 1038 | Irrevocably deletes _all_ files in the current origin's OPFS. |
| 1039 | Obviously, this must be used with great caution. It may throw |
| 1040 | an exception if removal of anything fails (e.g. a file is |
| 1041 | locked), but the precise conditions under which it will throw |
| 1042 | are not documented (so we cannot tell you what they are). |
| 1043 | */ |
| 1044 | opfsUtil.rmfr = async function(){ |
| 1045 | const dir = opfsUtil.rootDirectory, opt = {recurse: true}; |
| 1046 | for await (const handle of dir.values()){ |
| 1047 | dir.removeEntry(handle.name, opt); |
stephan | 3c272ba | 2022-10-04 00:54:00 +0000 | [diff] [blame] | 1048 | } |
| 1049 | }; |
| 1050 | |
stephan | 49048b1 | 2022-11-01 07:49:49 +0000 | [diff] [blame] | 1051 | /** |
| 1052 | Deletes the given OPFS filesystem entry. As this environment |
| 1053 | has no notion of "current directory", the given name must be an |
| 1054 | absolute path. If the 2nd argument is truthy, deletion is |
| 1055 | recursive (use with caution!). |
| 1056 | |
| 1057 | The returned Promise resolves to true if the deletion was |
| 1058 | successful, else false (but...). The OPFS API reports the |
| 1059 | reason for the failure only in human-readable form, not |
| 1060 | exceptions which can be type-checked to determine the |
| 1061 | failure. Because of that... |
| 1062 | |
| 1063 | If the final argument is truthy then this function will |
| 1064 | propagate any exception on error, rather than returning false. |
| 1065 | */ |
| 1066 | opfsUtil.unlink = async function(fsEntryName, recursive = false, |
| 1067 | throwOnError = false){ |
| 1068 | try { |
| 1069 | const [hDir, filenamePart] = |
| 1070 | await opfsUtil.getDirForFilename(fsEntryName, false); |
| 1071 | await hDir.removeEntry(filenamePart, {recursive}); |
| 1072 | return true; |
| 1073 | }catch(e){ |
| 1074 | if(throwOnError){ |
| 1075 | throw new Error("unlink(",arguments[0],") failed: "+e.message,{ |
| 1076 | cause: e |
| 1077 | }); |
| 1078 | } |
| 1079 | return false; |
| 1080 | } |
| 1081 | }; |
| 1082 | |
| 1083 | /** |
| 1084 | Traverses the OPFS filesystem, calling a callback for each one. |
| 1085 | The argument may be either a callback function or an options object |
| 1086 | with any of the following properties: |
| 1087 | |
| 1088 | - `callback`: function which gets called for each filesystem |
| 1089 | entry. It gets passed 3 arguments: 1) the |
| 1090 | FileSystemFileHandle or FileSystemDirectoryHandle of each |
| 1091 | entry (noting that both are instanceof FileSystemHandle). 2) |
| 1092 | the FileSystemDirectoryHandle of the parent directory. 3) the |
| 1093 | current depth level, with 0 being at the top of the tree |
| 1094 | relative to the starting directory. If the callback returns a |
| 1095 | literal false, as opposed to any other falsy value, traversal |
| 1096 | stops without an error. Any exceptions it throws are |
| 1097 | propagated. Results are undefined if the callback manipulate |
| 1098 | the filesystem (e.g. removing or adding entries) because the |
| 1099 | how OPFS iterators behave in the face of such changes is |
| 1100 | undocumented. |
| 1101 | |
| 1102 | - `recursive` [bool=true]: specifies whether to recurse into |
| 1103 | subdirectories or not. Whether recursion is depth-first or |
| 1104 | breadth-first is unspecified! |
| 1105 | |
| 1106 | - `directory` [FileSystemDirectoryEntry=sqlite3.opfs.rootDirectory] |
| 1107 | specifies the starting directory. |
| 1108 | |
| 1109 | If this function is passed a function, it is assumed to be the |
| 1110 | callback. |
| 1111 | |
| 1112 | Returns a promise because it has to (by virtue of being async) |
| 1113 | but that promise has no specific meaning: the traversal it |
| 1114 | performs is synchronous. The promise must be used to catch any |
| 1115 | exceptions propagated by the callback, however. |
| 1116 | |
| 1117 | TODO: add an option which specifies whether to traverse |
| 1118 | depth-first or breadth-first. We currently do depth-first but |
| 1119 | an incremental file browsing widget would benefit more from |
| 1120 | breadth-first. |
| 1121 | */ |
| 1122 | opfsUtil.traverse = async function(opt){ |
| 1123 | const defaultOpt = { |
| 1124 | recursive: true, |
| 1125 | directory: opfsUtil.rootDirectory |
| 1126 | }; |
| 1127 | if('function'===typeof opt){ |
| 1128 | opt = {callback:opt}; |
| 1129 | } |
| 1130 | opt = Object.assign(defaultOpt, opt||{}); |
| 1131 | const doDir = async function callee(dirHandle, depth){ |
| 1132 | for await (const handle of dirHandle.values()){ |
| 1133 | if(false === opt.callback(handle, dirHandle, depth)) return false; |
| 1134 | else if(opt.recursive && 'directory' === handle.kind){ |
| 1135 | if(false === await callee(handle, depth + 1)) break; |
| 1136 | } |
| 1137 | } |
| 1138 | }; |
| 1139 | doDir(opt.directory, 0); |
| 1140 | }; |
| 1141 | |
| 1142 | //TODO to support fiddle and worker1 db upload: |
stephan | 3d64548 | 2022-09-27 09:17:37 +0000 | [diff] [blame] | 1143 | //opfsUtil.createFile = function(absName, content=undefined){...} |
| 1144 | |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 1145 | if(sqlite3.oo1){ |
| 1146 | opfsUtil.OpfsDb = function(...args){ |
stephan | e681b65 | 2022-10-28 10:36:18 +0000 | [diff] [blame] | 1147 | const opt = sqlite3.oo1.DB.dbCtorHelper.normalizeArgs(...args); |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 1148 | opt.vfs = opfsVfs.$zName; |
stephan | e681b65 | 2022-10-28 10:36:18 +0000 | [diff] [blame] | 1149 | sqlite3.oo1.DB.dbCtorHelper.call(this, opt); |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 1150 | }; |
| 1151 | opfsUtil.OpfsDb.prototype = Object.create(sqlite3.oo1.DB.prototype); |
stephan | e681b65 | 2022-10-28 10:36:18 +0000 | [diff] [blame] | 1152 | sqlite3.oo1.DB.dbCtorHelper.setVfsPostOpenSql( |
stephan | 4f5bbed | 2022-10-03 13:03:41 +0000 | [diff] [blame] | 1153 | opfsVfs.pointer, |
stephan | c7fb48d | 2022-10-04 09:12:05 +0000 | [diff] [blame] | 1154 | [ |
| 1155 | /* Truncate journal mode is faster than delete or wal for |
| 1156 | this vfs, per speedtest1. */ |
stephan | ed3182f | 2022-10-04 11:14:23 +0000 | [diff] [blame] | 1157 | "pragma journal_mode=truncate;" |
stephan | c7fb48d | 2022-10-04 09:12:05 +0000 | [diff] [blame] | 1158 | /* |
| 1159 | This vfs benefits hugely from cache on moderate/large |
| 1160 | speedtest1 --size 50 and --size 100 workloads. We currently |
| 1161 | rely on setting a non-default cache size when building |
| 1162 | sqlite3.wasm. If that policy changes, the cache can |
| 1163 | be set here. |
| 1164 | */ |
| 1165 | //"pragma cache_size=-8388608;" |
stephan | b0ab21d | 2022-11-03 22:14:47 +0000 | [diff] [blame] | 1166 | ].join("") |
stephan | 4f5bbed | 2022-10-03 13:03:41 +0000 | [diff] [blame] | 1167 | ); |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 1168 | } |
stephan | 4f5bbed | 2022-10-03 13:03:41 +0000 | [diff] [blame] | 1169 | |
stephan | f386012 | 2022-09-18 17:32:35 +0000 | [diff] [blame] | 1170 | /** |
| 1171 | Potential TODOs: |
| 1172 | |
| 1173 | - Expose one or both of the Worker objects via opfsUtil and |
| 1174 | publish an interface for proxying the higher-level OPFS |
| 1175 | features like getting a directory listing. |
| 1176 | */ |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 1177 | const sanityCheck = function(){ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1178 | const scope = wasm.scopedAllocPush(); |
| 1179 | const sq3File = new sqlite3_file(); |
| 1180 | try{ |
| 1181 | const fid = sq3File.pointer; |
| 1182 | const openFlags = capi.SQLITE_OPEN_CREATE |
| 1183 | | capi.SQLITE_OPEN_READWRITE |
| 1184 | //| capi.SQLITE_OPEN_DELETEONCLOSE |
| 1185 | | capi.SQLITE_OPEN_MAIN_DB; |
| 1186 | const pOut = wasm.scopedAlloc(8); |
stephan | b8c8d4e | 2022-09-20 13:25:39 +0000 | [diff] [blame] | 1187 | const dbFile = "/sanity/check/file"+randomFilename(8); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1188 | const zDbFile = wasm.scopedAllocCString(dbFile); |
| 1189 | let rc; |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 1190 | state.s11n.serialize("This is ä string."); |
| 1191 | rc = state.s11n.deserialize(); |
| 1192 | log("deserialize() says:",rc); |
| 1193 | if("This is ä string."!==rc[0]) toss("String d13n error."); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1194 | vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut); |
| 1195 | rc = wasm.getMemValue(pOut,'i32'); |
| 1196 | log("xAccess(",dbFile,") exists ?=",rc); |
| 1197 | rc = vfsSyncWrappers.xOpen(opfsVfs.pointer, zDbFile, |
| 1198 | fid, openFlags, pOut); |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 1199 | log("open rc =",rc,"state.sabOPView[xOpen] =", |
| 1200 | state.sabOPView[state.opIds.xOpen]); |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 1201 | if(0!==rc){ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1202 | error("open failed with code",rc); |
| 1203 | return; |
| 1204 | } |
| 1205 | vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut); |
| 1206 | rc = wasm.getMemValue(pOut,'i32'); |
| 1207 | if(!rc) toss("xAccess() failed to detect file."); |
| 1208 | rc = ioSyncWrappers.xSync(sq3File.pointer, 0); |
| 1209 | if(rc) toss('sync failed w/ rc',rc); |
| 1210 | rc = ioSyncWrappers.xTruncate(sq3File.pointer, 1024); |
| 1211 | if(rc) toss('truncate failed w/ rc',rc); |
| 1212 | wasm.setMemValue(pOut,0,'i64'); |
| 1213 | rc = ioSyncWrappers.xFileSize(sq3File.pointer, pOut); |
| 1214 | if(rc) toss('xFileSize failed w/ rc',rc); |
| 1215 | log("xFileSize says:",wasm.getMemValue(pOut, 'i64')); |
| 1216 | rc = ioSyncWrappers.xWrite(sq3File.pointer, zDbFile, 10, 1); |
| 1217 | if(rc) toss("xWrite() failed!"); |
| 1218 | const readBuf = wasm.scopedAlloc(16); |
| 1219 | rc = ioSyncWrappers.xRead(sq3File.pointer, readBuf, 6, 2); |
| 1220 | wasm.setMemValue(readBuf+6,0); |
| 1221 | let jRead = wasm.cstringToJs(readBuf); |
| 1222 | log("xRead() got:",jRead); |
| 1223 | if("sanity"!==jRead) toss("Unexpected xRead() value."); |
stephan | 8766fd2 | 2022-09-19 05:19:04 +0000 | [diff] [blame] | 1224 | if(vfsSyncWrappers.xSleep){ |
| 1225 | log("xSleep()ing before close()ing..."); |
| 1226 | vfsSyncWrappers.xSleep(opfsVfs.pointer,2000); |
| 1227 | log("waking up from xSleep()"); |
| 1228 | } |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1229 | rc = ioSyncWrappers.xClose(fid); |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 1230 | log("xClose rc =",rc,"sabOPView =",state.sabOPView); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1231 | log("Deleting file:",dbFile); |
| 1232 | vfsSyncWrappers.xDelete(opfsVfs.pointer, zDbFile, 0x1234); |
| 1233 | vfsSyncWrappers.xAccess(opfsVfs.pointer, zDbFile, 0, pOut); |
| 1234 | rc = wasm.getMemValue(pOut,'i32'); |
| 1235 | if(rc) toss("Expecting 0 from xAccess(",dbFile,") after xDelete()."); |
stephan | c9e2602 | 2022-09-20 10:11:52 +0000 | [diff] [blame] | 1236 | warn("End of OPFS sanity checks."); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1237 | }finally{ |
| 1238 | sq3File.dispose(); |
| 1239 | wasm.scopedAllocPop(scope); |
| 1240 | } |
| 1241 | }/*sanityCheck()*/; |
stephan | 6559e0a | 2022-09-27 14:31:34 +0000 | [diff] [blame] | 1242 | |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1243 | W.onmessage = function({data}){ |
| 1244 | //log("Worker.onmessage:",data); |
| 1245 | switch(data.type){ |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 1246 | case 'opfs-async-loaded': |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 1247 | /*Arrives as soon as the asyc proxy finishes loading. |
| 1248 | Pass our config and shared state on to the async worker.*/ |
stephan | 5e8bb0a | 2022-09-20 08:27:57 +0000 | [diff] [blame] | 1249 | W.postMessage({type: 'opfs-async-init',args: state}); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1250 | break; |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 1251 | case 'opfs-async-inited':{ |
stephan | e8afca3 | 2022-09-21 14:02:47 +0000 | [diff] [blame] | 1252 | /*Indicates that the async partner has received the 'init' |
| 1253 | and has finished initializing, so the real work can |
| 1254 | begin...*/ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1255 | try { |
stephan | 0e0687c | 2022-09-19 13:44:23 +0000 | [diff] [blame] | 1256 | const rc = capi.sqlite3_vfs_register(opfsVfs.pointer, 0); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1257 | if(rc){ |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1258 | toss("sqlite3_vfs_register(OPFS) failed with rc",rc); |
| 1259 | } |
| 1260 | if(opfsVfs.pointer !== capi.sqlite3_vfs_find("opfs")){ |
| 1261 | toss("BUG: sqlite3_vfs_find() failed for just-installed OPFS VFS"); |
| 1262 | } |
| 1263 | capi.sqlite3_vfs_register.addReference(opfsVfs, opfsIoMethods); |
stephan | c4b87be | 2022-09-20 01:28:47 +0000 | [diff] [blame] | 1264 | state.sabOPView = new Int32Array(state.sabOP); |
stephan | 138647a | 2022-09-20 03:31:02 +0000 | [diff] [blame] | 1265 | state.sabFileBufView = new Uint8Array(state.sabIO, 0, state.fileBufferSize); |
| 1266 | state.sabS11nView = new Uint8Array(state.sabIO, state.sabS11nOffset, state.sabS11nSize); |
| 1267 | initS11n(); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1268 | if(options.sanityChecks){ |
| 1269 | warn("Running sanity checks because of opfs-sanity-check URL arg..."); |
| 1270 | sanityCheck(); |
| 1271 | } |
stephan | 1f095d4 | 2022-09-26 11:38:58 +0000 | [diff] [blame] | 1272 | navigator.storage.getDirectory().then((d)=>{ |
| 1273 | W.onerror = W._originalOnError; |
| 1274 | delete W._originalOnError; |
| 1275 | sqlite3.opfs = opfsUtil; |
| 1276 | opfsUtil.rootDirectory = d; |
| 1277 | log("End of OPFS sqlite3_vfs setup.", opfsVfs); |
| 1278 | promiseResolve(sqlite3); |
| 1279 | }); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1280 | }catch(e){ |
| 1281 | error(e); |
| 1282 | promiseReject(e); |
| 1283 | } |
| 1284 | break; |
| 1285 | } |
| 1286 | default: |
| 1287 | promiseReject(e); |
| 1288 | error("Unexpected message from the async worker:",data); |
| 1289 | break; |
stephan | f861b36 | 2022-10-25 08:06:17 +0000 | [diff] [blame] | 1290 | }/*switch(data.type)*/ |
| 1291 | }/*W.onmessage()*/; |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1292 | })/*thePromise*/; |
| 1293 | return thePromise; |
| 1294 | }/*installOpfsVfs()*/; |
stephan | 5b9973d | 2022-09-27 13:40:12 +0000 | [diff] [blame] | 1295 | installOpfsVfs.defaultProxyUri = |
stephan | 5b9973d | 2022-09-27 13:40:12 +0000 | [diff] [blame] | 1296 | "sqlite3-opfs-async-proxy.js"; |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 1297 | self.sqlite3ApiBootstrap.initializersAsync.push(async (sqlite3)=>{ |
stephan | cd0df83 | 2022-10-19 04:44:58 +0000 | [diff] [blame] | 1298 | if(sqlite3.scriptInfo && !sqlite3.scriptInfo.isWorker){ |
| 1299 | return; |
| 1300 | } |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 1301 | try{ |
stephan | cd0df83 | 2022-10-19 04:44:58 +0000 | [diff] [blame] | 1302 | let proxyJs = installOpfsVfs.defaultProxyUri; |
| 1303 | if(sqlite3.scriptInfo.sqlite3Dir){ |
| 1304 | installOpfsVfs.defaultProxyUri = |
| 1305 | sqlite3.scriptInfo.sqlite3Dir + proxyJs; |
| 1306 | //console.warn("installOpfsVfs.defaultProxyUri =",installOpfsVfs.defaultProxyUri); |
| 1307 | } |
stephan | ff891b4 | 2022-10-09 15:12:37 +0000 | [diff] [blame] | 1308 | return installOpfsVfs().catch((e)=>{ |
stephan | cd0df83 | 2022-10-19 04:44:58 +0000 | [diff] [blame] | 1309 | console.warn("Ignoring inability to install OPFS sqlite3_vfs:",e.message); |
stephan | ff891b4 | 2022-10-09 15:12:37 +0000 | [diff] [blame] | 1310 | }); |
stephan | 9a55773 | 2022-10-04 17:06:51 +0000 | [diff] [blame] | 1311 | }catch(e){ |
| 1312 | console.error("installOpfsVfs() exception:",e); |
| 1313 | throw e; |
| 1314 | } |
| 1315 | }); |
stephan | c5313af | 2022-09-18 02:35:30 +0000 | [diff] [blame] | 1316 | }/*sqlite3ApiBootstrap.initializers.push()*/); |