sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / wasm / api / sqlite3-worker1-promiser.c-pp.js
| 1 | //#if not omit-oo1 |
| 2 | /* |
| 3 | 2022-08-24 |
| 4 | |
| 5 | The author disclaims copyright to this source code. In place of a |
| 6 | legal notice, here is a blessing: |
| 7 | |
| 8 | * May you do good and not evil. |
| 9 | * May you find forgiveness for yourself and forgive others. |
| 10 | * May you share freely, never taking more than you give. |
| 11 | |
| 12 | *********************************************************************** |
| 13 | |
| 14 | This file implements a Promise-based proxy for the sqlite3 Worker |
| 15 | API #1. It is intended to be included either from the main thread or |
| 16 | a Worker, but only if (A) the environment supports nested Workers |
| 17 | and (B) it's _not_ a Worker which loads the sqlite3 WASM/JS |
| 18 | module. This file's features will load that module and provide a |
| 19 | slightly simpler client-side interface than the slightly-lower-level |
| 20 | Worker API does. |
| 21 | |
| 22 | In non-ESM builds this file necessarily exposes one global symbol, |
| 23 | but clients may freely `delete` that symbol after calling it (and |
| 24 | are encouraged to do so). |
| 25 | */ |
| 26 | //#if not defined target:es6-module |
| 27 | 'use strict'; |
| 28 | //#/if |
| 29 | /** |
| 30 | Configures an sqlite3 Worker API #1 Worker such that it can be |
| 31 | manipulated via a Promise-based interface and returns a factory |
| 32 | function which returns Promises for communicating with the worker. |
| 33 | This proxy has an _almost_ identical interface to the normal |
| 34 | worker API, with any exceptions documented below. |
| 35 | |
| 36 | It requires a configuration object with the following properties: |
| 37 | |
| 38 | - `worker` (required): a Worker instance which loads |
| 39 | `sqlite3-worker1.js` or a functional equivalent. Note that the |
| 40 | promiser factory replaces the worker.onmessage property. This |
| 41 | config option may alternately be a function, in which case this |
| 42 | function re-assigns this property with the result of calling that |
| 43 | function, enabling delayed instantiation of a Worker. |
| 44 | |
| 45 | - `onready` (optional, but...): this callback is called with no |
| 46 | arguments when the worker fires its initial |
| 47 | 'sqlite3-api'/'worker1-ready' message, which it does when |
| 48 | sqlite3.initWorker1API() completes its initialization. This is the |
| 49 | simplest way to tell the worker to kick off work at the earliest |
| 50 | opportunity, and the only way to know when the worker module has |
| 51 | completed loading. The irony of using a callback for this, instead |
| 52 | of returning a promise from sqlite3Worker1Promiser() is not lost on |
| 53 | the developers: see sqlite3Worker1Promiser.v2() which uses a |
| 54 | Promise instead. |
| 55 | |
| 56 | - `onunhandled` (optional): a callback which gets passed the |
| 57 | message event object for any worker.onmessage() events which |
| 58 | are not handled by this proxy. Ideally that "should" never |
| 59 | happen, as this proxy aims to handle all known message types. |
| 60 | |
| 61 | - `generateMessageId` (optional): a function which, when passed an |
| 62 | about-to-be-posted message object, generates a _unique_ message ID |
| 63 | for the message, which this API then assigns as the messageId |
| 64 | property of the message. It _must_ generate unique IDs on each call |
| 65 | so that dispatching can work. If not defined, a default generator |
| 66 | is used (which should be sufficient for most or all cases). |
| 67 | |
| 68 | - `debug` (optional): a console.debug()-style function for logging |
| 69 | information about messages. |
| 70 | |
| 71 | This function returns a stateful factory function with the |
| 72 | following interfaces: |
| 73 | |
| 74 | - Promise function(messageType, messageArgs) |
| 75 | - Promise function({message object}) |
| 76 | |
| 77 | The first form expects the "type" and "args" values for a Worker |
| 78 | message. The second expects an object in the form {type:..., |
| 79 | args:...} plus any other properties the client cares to set. This |
| 80 | function will always set the `messageId` property on the object, |
| 81 | even if it's already set, and will set the `dbId` property to the |
| 82 | current database ID if it is _not_ set in the message object. |
| 83 | |
| 84 | The function throws on error. |
| 85 | |
| 86 | The function installs a temporary message listener, posts a |
| 87 | message to the configured Worker, and handles the message's |
| 88 | response via the temporary message listener. The then() callback |
| 89 | of the returned Promise is passed the `message.data` property from |
| 90 | the resulting message, i.e. the payload from the worker, stripped |
| 91 | of the lower-level event state which the onmessage() handler |
| 92 | receives. |
| 93 | |
| 94 | Example usage: |
| 95 | |
| 96 | ``` |
| 97 | const config = {...}; |
| 98 | const sq3Promiser = sqlite3Worker1Promiser(config); |
| 99 | sq3Promiser('open', {filename:"/foo.db"}).then(function(msg){ |
| 100 | console.log("open response",msg); // => {type:'open', result: {filename:'/foo.db'}, ...} |
| 101 | }); |
| 102 | sq3Promiser({type:'close'}).then((msg)=>{ |
| 103 | console.log("close response",msg); // => {type:'close', result: {filename:'/foo.db'}, ...} |
| 104 | }); |
| 105 | ``` |
| 106 | |
| 107 | Differences from Worker API #1: |
| 108 | |
| 109 | - exec's {callback: STRING} option does not work via this |
| 110 | interface (it triggers an exception), but {callback: function} |
| 111 | does and works exactly like the STRING form does in the Worker: |
| 112 | the callback is called one time for each row of the result set, |
| 113 | passed the same worker message format as the worker API emits: |
| 114 | |
| 115 | { |
| 116 | type:typeString, |
| 117 | row:VALUE, |
| 118 | rowNumber:1-based-#, |
| 119 | columnNames: array |
| 120 | } |
| 121 | |
| 122 | Where `typeString` is an internally-synthesized message type string |
| 123 | used temporarily for worker message dispatching. It can be ignored |
| 124 | by all client code except that which tests this API. The `row` |
| 125 | property contains the row result in the form implied by the |
| 126 | `rowMode` option (defaulting to `'array'`). The `rowNumber` is a |
| 127 | 1-based integer value incremented by 1 on each call into the |
| 128 | callback. |
| 129 | |
| 130 | At the end of the result set, the same event is fired with |
| 131 | (row=undefined, rowNumber=null) to indicate that the end of the |
| 132 | result set has been reached. The rows arrive via worker-posted |
| 133 | messages, with all the implications of that. |
| 134 | |
| 135 | Notable shortcomings: |
| 136 | |
| 137 | - "v1" of this this API is not suitable for use as an ESM module |
| 138 | because ESM worker modules were not widely supported when it was |
| 139 | developed. For use as an ESM module, see the "v2" interface later |
| 140 | on in this file. |
| 141 | */ |
| 142 | const sqlite3Worker1Promiser = function callee(config = callee.defaultConfig){ |
| 143 | // Inspired by: https://stackoverflow.com/a/52439530 |
| 144 | if(1===arguments.length && 'function'===typeof arguments[0]){ |
| 145 | const f = config; |
| 146 | config = Object.assign(Object.create(null), callee.defaultConfig); |
| 147 | config.onready = f; |
| 148 | }else{ |
| 149 | config = Object.assign(Object.create(null), callee.defaultConfig, config); |
| 150 | } |
| 151 | const handlerMap = Object.create(null); |
| 152 | const noop = function(){}; |
| 153 | const err = config.onerror |
| 154 | || noop /* config.onerror is intentionally undocumented |
| 155 | pending finding a less ambiguous name */; |
| 156 | const debug = config.debug || noop; |
| 157 | const idTypeMap = config.generateMessageId ? undefined : Object.create(null); |
| 158 | const genMsgId = config.generateMessageId || function(msg){ |
| 159 | return msg.type+'#'+(idTypeMap[msg.type] = (idTypeMap[msg.type]||0) + 1); |
| 160 | }; |
| 161 | const toss = (...args)=>{throw new Error(args.join(' '))}; |
| 162 | if(!config.worker) config.worker = callee.defaultConfig.worker; |
| 163 | if('function'===typeof config.worker) config.worker = config.worker(); |
| 164 | let dbId; |
| 165 | let promiserFunc; |
| 166 | config.worker.onmessage = function(ev){ |
| 167 | ev = ev.data; |
| 168 | debug('worker1.onmessage',ev); |
| 169 | let msgHandler = handlerMap[ev.messageId]; |
| 170 | if(!msgHandler){ |
| 171 | if(ev && 'sqlite3-api'===ev.type && 'worker1-ready'===ev.result) { |
| 172 | /*fired one time when the Worker1 API initializes*/ |
| 173 | if(config.onready) config.onready(promiserFunc); |
| 174 | return; |
| 175 | } |
| 176 | msgHandler = handlerMap[ev.type] /* check for exec per-row callback */; |
| 177 | if(msgHandler && msgHandler.onrow){ |
| 178 | msgHandler.onrow(ev); |
| 179 | return; |
| 180 | } |
| 181 | if(config.onunhandled) config.onunhandled(arguments[0]); |
| 182 | else err("sqlite3Worker1Promiser() unhandled worker message:",ev); |
| 183 | return; |
| 184 | } |
| 185 | delete handlerMap[ev.messageId]; |
| 186 | switch(ev.type){ |
| 187 | case 'error': |
| 188 | msgHandler.reject(ev); |
| 189 | return; |
| 190 | case 'open': |
| 191 | if(!dbId) dbId = ev.dbId; |
| 192 | break; |
| 193 | case 'close': |
| 194 | if(ev.dbId===dbId) dbId = undefined; |
| 195 | break; |
| 196 | default: |
| 197 | break; |
| 198 | } |
| 199 | try {msgHandler.resolve(ev)} |
| 200 | catch(e){msgHandler.reject(e)} |
| 201 | }/*worker.onmessage()*/; |
| 202 | return promiserFunc = function(/*(msgType, msgArgs) || (msgEnvelope)*/){ |
| 203 | let msg; |
| 204 | if(1===arguments.length){ |
| 205 | msg = arguments[0]; |
| 206 | }else if(2===arguments.length){ |
| 207 | msg = Object.create(null); |
| 208 | msg.type = arguments[0]; |
| 209 | msg.args = arguments[1]; |
| 210 | msg.dbId = msg.args.dbId; |
| 211 | }else{ |
| 212 | toss("Invalid arguments for sqlite3Worker1Promiser()-created factory."); |
| 213 | } |
| 214 | if(!msg.dbId && msg.type!=='open') msg.dbId = dbId; |
| 215 | msg.messageId = genMsgId(msg); |
| 216 | msg.departureTime = performance.now(); |
| 217 | const proxy = Object.create(null); |
| 218 | proxy.message = msg; |
| 219 | let rowCallbackId /* message handler ID for exec on-row callback proxy */; |
| 220 | if('exec'===msg.type && msg.args){ |
| 221 | if('function'===typeof msg.args.callback){ |
| 222 | rowCallbackId = msg.messageId+':row'; |
| 223 | proxy.onrow = msg.args.callback; |
| 224 | msg.args.callback = rowCallbackId; |
| 225 | handlerMap[rowCallbackId] = proxy; |
| 226 | }else if('string' === typeof msg.args.callback){ |
| 227 | toss("exec callback may not be a string when using the Promise interface."); |
| 228 | /** |
| 229 | Design note: the reason for this limitation is that this |
| 230 | API takes over worker.onmessage() and the client has no way |
| 231 | of adding their own message-type handlers to it. Per-row |
| 232 | callbacks are implemented as short-lived message.type |
| 233 | mappings for worker.onmessage(). |
| 234 | |
| 235 | We "could" work around this by providing a new |
| 236 | config.fallbackMessageHandler (or some such) which contains |
| 237 | a map of event type names to callbacks. Seems like overkill |
| 238 | for now, seeing as the client can pass callback functions |
| 239 | to this interface (whereas the string-form "callback" is |
| 240 | needed for the over-the-Worker interface). |
| 241 | */ |
| 242 | } |
| 243 | } |
| 244 | //debug("requestWork", msg); |
| 245 | let p = new Promise(function(resolve, reject){ |
| 246 | proxy.resolve = resolve; |
| 247 | proxy.reject = reject; |
| 248 | handlerMap[msg.messageId] = proxy; |
| 249 | debug("Posting",msg.type,"message to Worker dbId="+(dbId||'default')+':',msg); |
| 250 | config.worker.postMessage(msg); |
| 251 | }); |
| 252 | if(rowCallbackId) p = p.finally(()=>delete handlerMap[rowCallbackId]); |
| 253 | return p; |
| 254 | }; |
| 255 | }/*sqlite3Worker1Promiser()*/; |
| 256 | |
| 257 | sqlite3Worker1Promiser.defaultConfig = { |
| 258 | worker: function(){ |
| 259 | //#if target:es6-bundler-friendly |
| 260 | return new Worker(new URL("sqlite3-worker1-bundler-friendly.mjs", import.meta.url),{ |
| 261 | type: 'module' |
| 262 | }); |
| 263 | //#elif target:es6-module |
| 264 | return new Worker(new URL("sqlite3-worker1.mjs", import.meta.url),{ |
| 265 | type: 'module' |
| 266 | }); |
| 267 | //#else |
| 268 | let theJs = "sqlite3-worker1.js"; |
| 269 | if(this.currentScript){ |
| 270 | const src = this.currentScript.src.split('/'); |
| 271 | src.pop(); |
| 272 | theJs = src.join('/')+'/' + theJs; |
| 273 | //sqlite3.config.warn("promiser currentScript, theJs =",this.currentScript,theJs); |
| 274 | }else if(globalThis.location){ |
| 275 | //sqlite3.config.warn("promiser globalThis.location =",globalThis.location); |
| 276 | const s = urlParams.get('sqlite3.dir'); |
| 277 | if( s ){ |
| 278 | if( s.indexOf(':')<0 && s.indexOf('//')<0 ){ |
| 279 | theJs = s + '/' + theJs; |
| 280 | }else{ |
| 281 | console.warn("Invalid sqlite3.dir value:",s); |
| 282 | } |
| 283 | } |
| 284 | if(urlParams.has('sqlite3.dir')){ |
| 285 | theJs = urlParams.get('sqlite3.dir') + '/' + theJs; |
| 286 | } |
| 287 | } |
| 288 | return new Worker(theJs + globalThis.location.search); |
| 289 | //#/if |
| 290 | } |
| 291 | //#if not target:es6-module |
| 292 | .bind({ |
| 293 | currentScript: globalThis?.document?.currentScript |
| 294 | }) |
| 295 | //#/if |
| 296 | , |
| 297 | onerror: (...args)=>console.error('sqlite3Worker1Promiser():',...args) |
| 298 | }/*defaultConfig*/; |
| 299 | |
| 300 | /** |
| 301 | sqlite3Worker1Promiser.v2(), added in 3.46, works identically to |
| 302 | sqlite3Worker1Promiser() except that it returns a Promise instead |
| 303 | of relying on an onready callback in the config object. The Promise |
| 304 | resolves to the same factory function which |
| 305 | sqlite3Worker1Promiser() returns. |
| 306 | |
| 307 | If config is-a function or is an object which contains an onready |
| 308 | function, that function is replaced by a proxy which will resolve |
| 309 | after calling the original function and will reject if that |
| 310 | function throws. |
| 311 | */ |
| 312 | sqlite3Worker1Promiser.v2 = function callee(config = callee.defaultConfig){ |
| 313 | let oldFunc; |
| 314 | if( 'function' == typeof config ){ |
| 315 | oldFunc = config; |
| 316 | config = {}; |
| 317 | }else if('function'===typeof config?.onready){ |
| 318 | oldFunc = config.onready; |
| 319 | delete config.onready; |
| 320 | } |
| 321 | const promiseProxy = Object.create(null); |
| 322 | config = Object.assign((config || Object.create(null)),{ |
| 323 | onready: async function(func){ |
| 324 | try { |
| 325 | if( oldFunc ) await oldFunc(func); |
| 326 | promiseProxy.resolve(func); |
| 327 | } |
| 328 | catch(e){promiseProxy.reject(e)} |
| 329 | } |
| 330 | }); |
| 331 | const p = new Promise(function(resolve,reject){ |
| 332 | promiseProxy.resolve = resolve; |
| 333 | promiseProxy.reject = reject; |
| 334 | }); |
| 335 | try{ |
| 336 | sqlite3Worker1Promiser(config); |
| 337 | }catch(e){ |
| 338 | promiseProxy.reject(e); |
| 339 | } |
| 340 | return p; |
| 341 | }; |
| 342 | |
| 343 | sqlite3Worker1Promiser.v2.defaultConfig = |
| 344 | sqlite3Worker1Promiser.defaultConfig; |
| 345 | |
| 346 | //#if target:es6-module |
| 347 | /** |
| 348 | When built as a module, we export sqlite3Worker1Promiser.v2() |
| 349 | instead of sqlite3Worker1Promise() because (A) its interface is more |
| 350 | conventional for ESM usage and (B) the ESM export option for this |
| 351 | API did not exist until v2 was created, so there's no backwards |
| 352 | incompatibility. |
| 353 | */ |
| 354 | export default sqlite3Worker1Promiser.v2; |
| 355 | //#else |
| 356 | globalThis.sqlite3Worker1Promiser = |
| 357 | /* Prior to 3.55, sqlite3Worker1Promiser was defined as a globalThis |
| 358 | property. It turns out, however, that defining it as a const |
| 359 | works too, so we now define it as such. However, documentation |
| 360 | has historically referred to this function as |
| 361 | globalThis.sqlite3Worker1Promiser, so we retain that mapping here |
| 362 | in non-esm builds for backwards compatibility. |
| 363 | */ sqlite3Worker1Promiser; |
| 364 | //#/if /* target:es6-module */ |
| 365 | //#else |
| 366 | /* Built with the omit-oo1 flag. */ |
| 367 | //#/if if not omit-oo1 |