sqlite3-worker1-promiser.c-pp.js 13 KB

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