sbmlsim-core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/loader.mjs CHANGED
@@ -101,6 +101,14 @@ export class EngineError extends Error {
101
101
  }
102
102
  }
103
103
 
104
+ /** An older runtime without the optional prepared-request capability. */
105
+ export class UnsupportedError extends EngineError {
106
+ constructor(message) {
107
+ super("unsupported", message);
108
+ this.name = "UnsupportedError";
109
+ }
110
+ }
111
+
104
112
  /** The exit of the engine through `proc_exit`. */
105
113
  export class WasiExit extends Error {
106
114
  constructor(code) {
@@ -245,6 +253,71 @@ function checkRuntime(engineModule, mathlibModule) {
245
253
  }
246
254
  }
247
255
 
256
+ /** Validate model state sections before compilation. Modules supplied already compiled are trusted. */
257
+ export function validateModelBytes(source) {
258
+ const bytes = source instanceof ArrayBuffer ? new Uint8Array(source)
259
+ : ArrayBuffer.isView(source) ? new Uint8Array(source.buffer, source.byteOffset, source.byteLength) : null;
260
+ if (!bytes || bytes.length < 8) throw new Error("model.wasm is not a WASM binary");
261
+ let pos = 8;
262
+ const leb = (end) => {
263
+ let value = 0;
264
+ for (let shift = 0; shift < 35 && pos < end; shift += 7) {
265
+ const byte = bytes[pos++];
266
+ value += (byte & 127) * 2 ** shift;
267
+ if (!(byte & 128)) return value;
268
+ }
269
+ throw new Error("invalid model.wasm section encoding");
270
+ };
271
+ while (pos < bytes.length) {
272
+ const id = bytes[pos++];
273
+ const length = leb(bytes.length);
274
+ const end = pos + length;
275
+ if (end > bytes.length) throw new Error("invalid model.wasm section length");
276
+ if (id === 1) {
277
+ const count = leb(end);
278
+ for (let i = 0; i < count; i++) {
279
+ // Generated models need ordinary numeric function signatures, not GC heaps,
280
+ // recursive types or host references outside the shared-memory policy.
281
+ if (bytes[pos++] !== 0x60) throw new Error("model.wasm has an unsupported type");
282
+ for (let vector = 0; vector < 2; vector++) {
283
+ const n = leb(end);
284
+ for (let j = 0; j < n; j++) {
285
+ if (pos >= end || ![0x7f, 0x7e, 0x7d, 0x7c, 0x7b].includes(bytes[pos++])) {
286
+ throw new Error("model.wasm has an unsupported reference type");
287
+ }
288
+ }
289
+ }
290
+ }
291
+ }
292
+ if (id === 13) throw new Error("model.wasm must not define exception tags");
293
+ if ([4, 5, 8, 9, 11, 12].includes(id)) {
294
+ // Empty declarations are harmless, but start/data-count are scalar sections.
295
+ if (id === 8 || id === 12 || leb(end) !== 0) {
296
+ throw new Error("model.wasm must not define tables, memories, a start function, elements or data");
297
+ }
298
+ }
299
+ if (id === 6) {
300
+ const count = leb(end);
301
+ for (let i = 0; i < count; i++) {
302
+ const type = bytes[pos++];
303
+ if (![0x7f, 0x7e, 0x7d, 0x7c].includes(type)) throw new Error("model.wasm has an unsupported global type");
304
+ if (bytes[pos++] !== 0) throw new Error("model.wasm must not define mutable globals");
305
+ // The compiler emits no globals. Accept ordinary immutable scalar constants;
306
+ // reject extended constant expressions rather than guessing instruction lengths.
307
+ const op = bytes[pos++];
308
+ if (op === 0x41 || op === 0x42) {
309
+ let n = 0;
310
+ while (pos < end && n++ < 10 && (bytes[pos++] & 128)) {}
311
+ } else if (op === 0x43) pos += 4;
312
+ else if (op === 0x44) pos += 8;
313
+ else throw new Error("model.wasm has an unsupported global initializer");
314
+ if (pos >= end || bytes[pos++] !== 0x0b) throw new Error("model.wasm has an invalid global initializer");
315
+ }
316
+ }
317
+ pos = end;
318
+ }
319
+ }
320
+
248
321
  /** Checks that a model imports `env.memory` and otherwise only functions of mathlib. */
249
322
  function checkModel(modelModule, mathlibModule) {
250
323
  const math = new Set(
@@ -286,6 +359,9 @@ export async function createRuntime({
286
359
  const mathlibModule = await toModule(mathlib, "mathlib.wasm");
287
360
  checkRuntime(engineModule, mathlibModule);
288
361
  const minimum = memoryMinimum(engineModule);
362
+ if (!Number.isSafeInteger(maxMemoryPages) || maxMemoryPages < minimum || maxMemoryPages > MAX_MEMORY_PAGES) {
363
+ throw new Error(`maxMemoryPages must be between ${minimum} and ${MAX_MEMORY_PAGES}`);
364
+ }
289
365
  return {
290
366
  /** The compiled modules, which a worker gets to create a runtime of its own. */
291
367
  modules: { engine: engineModule, mathlib: mathlibModule },
@@ -302,6 +378,7 @@ export async function createRuntime({
302
378
  if (desc.contract !== MODEL_CONTRACT) {
303
379
  throw new Error(`the description is of the contract ${desc.contract}, not ${MODEL_CONTRACT}`);
304
380
  }
381
+ if (!(modelWasm instanceof WebAssembly.Module)) validateModelBytes(modelWasm);
305
382
  const modelModule = await toModule(modelWasm, "model.wasm");
306
383
  checkModel(modelModule, mathlibModule);
307
384
  const memory = new WebAssembly.Memory({ initial: minimum, maximum: maxMemoryPages });
@@ -337,6 +414,24 @@ export async function createRuntime({
337
414
  }
338
415
 
339
416
  /** A model loaded into an engine; one per model and thread. */
417
+ const preparedStates = new WeakMap();
418
+
419
+ /** An opaque reusable request bound to the instance that prepared it. */
420
+ export class PreparedSimulation {
421
+ constructor(token, state) {
422
+ if (token !== preparedStates) throw new TypeError("use instance.prepare()");
423
+ preparedStates.set(this, state);
424
+ }
425
+ get nValues() { return preparedStates.get(this).nValues; }
426
+ close() {
427
+ const state = preparedStates.get(this);
428
+ if (state.closed) return;
429
+ state.closed = true;
430
+ state.instance.plans.delete(this);
431
+ if (!state.instance.trapped) state.instance.guard(() => state.instance.exports.engine_release_prepared(state.handle));
432
+ }
433
+ }
434
+
340
435
  class Instance {
341
436
  constructor(exports, memory, calls) {
342
437
  this.exports = exports;
@@ -345,6 +440,9 @@ class Instance {
345
440
  this.trapped = false;
346
441
  this.encoder = new TextEncoder();
347
442
  this.decoder = new TextDecoder();
443
+ this.inputPtr = 0;
444
+ this.inputCapacity = 0;
445
+ this.plans = new Set();
348
446
  }
349
447
 
350
448
  /** The number of calls of the engine into WASI since the instance was created. */
@@ -388,6 +486,52 @@ class Instance {
388
486
  throw new EngineError("internal", `engine_simulate returned ${code} with the output ${JSON.stringify(output.header)}`);
389
487
  }
390
488
 
489
+ /** Prepares fixed request structure once; varying IDs define the raw value order. */
490
+ prepare(request, { varying = [] } = {}) {
491
+ if (!["engine_prepare", "engine_simulate_prepared", "engine_release_prepared"].every((name) => typeof this.exports[name] === "function")) {
492
+ throw new UnsupportedError("this engine does not support prepared requests");
493
+ }
494
+ if (this.trapped) throw new EngineError("internal", "the instance trapped before and is not used again");
495
+ if (this.plans.size >= 32) throw new EngineError("request", "prepared request limit reached (32)");
496
+ const code = this.call(this.exports.engine_prepare, jsonText({ request: typeof request === "string" ? JSON.parse(request) : request, varying }));
497
+ const output = this.output();
498
+ if (code !== 0) throw output.error ?? new EngineError("internal", "engine_prepare failed without an error");
499
+ const { prepared: handle, n_values: nValues } = output.header;
500
+ if (!Number.isInteger(handle) || !Number.isSafeInteger(nValues) || nValues < 0) throw new EngineError("internal", "invalid prepared request output");
501
+ const plan = new PreparedSimulation(preparedStates, { instance: this, handle, nValues, closed: false });
502
+ this.plans.add(plan);
503
+ return plan;
504
+ }
505
+
506
+ simulatePrepared(plan, values = []) {
507
+ const state = preparedStates.get(plan);
508
+ if (!state || state.instance !== this || state.closed) throw new EngineError("request", "foreign or closed prepared request");
509
+ if (this.trapped) throw new EngineError("internal", "the instance trapped before and is not used again");
510
+ if ((!Array.isArray(values) && !(values instanceof Float64Array)) || values.length !== state.nValues || values.findIndex((value) => !Number.isFinite(value)) >= 0) {
511
+ throw new EngineError("request", `prepared request requires ${state.nValues} finite values`);
512
+ }
513
+ const ptr = this.inputBuffer(values.length * 8);
514
+ const view = new DataView(this.memory.buffer, ptr, values.length * 8);
515
+ for (let i = 0; i < values.length; i++) view.setFloat64(i * 8, values[i], true);
516
+ const code = this.guard(() => this.exports.engine_simulate_prepared(state.handle, ptr, values.length));
517
+ const output = this.output();
518
+ if (code === 0 && output.table) return output.table;
519
+ if (output.error) throw output.error;
520
+ throw new EngineError("internal", "engine_simulate_prepared returned invalid output");
521
+ }
522
+
523
+ inputBuffer(length) {
524
+ if (length > this.inputCapacity) {
525
+ const capacity = Math.max(length, this.inputCapacity * 2, 256);
526
+ const ptr = this.guard(() => this.exports.engine_alloc(capacity)) >>> 0;
527
+ if (!ptr) throw new EngineError("internal", "engine_alloc found no memory for the input");
528
+ if (this.inputCapacity) this.guard(() => this.exports.engine_free(this.inputPtr, this.inputCapacity));
529
+ this.inputPtr = ptr;
530
+ this.inputCapacity = capacity;
531
+ }
532
+ return this.inputPtr;
533
+ }
534
+
391
535
  /** Loads the description (`engine_load`). */
392
536
  load(descText, id) {
393
537
  const before = this.calls();
@@ -406,13 +550,9 @@ class Instance {
406
550
  throw new EngineError("internal", "the instance trapped before and is not used again");
407
551
  }
408
552
  const bytes = this.encoder.encode(text);
409
- const ptr = this.guard(() => this.exports.engine_alloc(bytes.length)) >>> 0;
410
- if (ptr === 0 && bytes.length > 0) {
411
- throw new EngineError("internal", "engine_alloc found no memory for the input");
412
- }
553
+ const ptr = this.inputBuffer(bytes.length);
413
554
  new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);
414
555
  const code = this.guard(() => fn(ptr, bytes.length));
415
- this.guard(() => this.exports.engine_free(ptr, bytes.length));
416
556
  return code;
417
557
  }
418
558
 
@@ -461,6 +601,7 @@ class Instance {
461
601
  error.engineKind = kind;
462
602
  return { header, error };
463
603
  }
604
+ if (header.prepared !== undefined) return { header };
464
605
  const { columns, n_rows: nRows } = header;
465
606
  const start = (4 + headerLength + 7) & ~7;
466
607
  const n = nRows * columns.length;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbmlsim-core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Simulate SBML models compiled to WebAssembly in browsers and Node: the JavaScript host of sbmlsim-core with its engine (CVODE, KLU), a pool of workers and the panel endpoint of sbmlsim",
5
5
  "keywords": [
6
6
  "sbml",
package/panels.mjs CHANGED
@@ -58,7 +58,7 @@ import { EngineError } from "./loader.mjs";
58
58
  import { createPool, defaultWorkers } from "./pool.mjs";
59
59
 
60
60
  /** The version of sbmlsim-core (`js/package.json`), which the provenance of a run names. */
61
- export const CORE_VERSION = "0.4.0";
61
+ export const CORE_VERSION = "0.5.0";
62
62
 
63
63
  /** The engine a provenance names. */
64
64
  export const ENGINE = `sbmlsim-core ${CORE_VERSION}`;
@@ -369,7 +369,9 @@ function product(axes) {
369
369
 
370
370
  /** The runs of the points of a model, shared by the requests of one state (see the module comment). */
371
371
  class Runs {
372
- constructor(maxBytes) {
372
+ constructor(maxBytes, maxEntries, maxInflight) {
373
+ this.maxEntries = maxEntries;
374
+ this.maxInflight = maxInflight;
373
375
  this.maxBytes = maxBytes;
374
376
  this.bytes = 0;
375
377
  this.inflight = new Map();
@@ -391,6 +393,7 @@ class Runs {
391
393
  }
392
394
  let entry = this.inflight.get(key);
393
395
  if (!entry) {
396
+ if (this.inflight.size >= this.maxInflight) return Promise.reject(new Error("panel run limit reached"));
394
397
  const controller = new AbortController();
395
398
  entry = { controller, waiters: 0 };
396
399
  entry.promise = start(controller.signal).then(
@@ -439,12 +442,18 @@ class Runs {
439
442
 
440
443
  /** Keeps the results of a run, evicting the least recently used ones beyond the bound. */
441
444
  store(key, results) {
442
- const bytes = results.reduce((sum, result) => sum + (result ? result.values.byteLength : 0), 0);
445
+ if (results.some((result) => result === null)) return;
446
+ const bytes = 256 + key.length * 2 + results.reduce((sum, result) => sum + 128 + result.values.byteLength + JSON.stringify(result.columns).length * 2, 0);
443
447
  if (bytes > this.maxBytes) return;
448
+ const previous = this.done.get(key);
449
+ if (previous) {
450
+ this.bytes -= previous.bytes;
451
+ this.done.delete(key);
452
+ }
444
453
  this.done.set(key, { results, bytes });
445
454
  this.bytes += bytes;
446
455
  for (const [old, entry] of this.done) {
447
- if (this.bytes <= this.maxBytes) break;
456
+ if (this.bytes <= this.maxBytes && this.done.size <= this.maxEntries) break;
448
457
  this.done.delete(old);
449
458
  this.bytes -= entry.bytes;
450
459
  }
@@ -463,7 +472,9 @@ class Runs {
463
472
  * - `pool`: a pool of `createPool` to run on instead of one of its own (e.g. shared by the
464
473
  * endpoints of several bundles), which `close()` leaves open.
465
474
  * - `fetch`: loads the files of the bundle and the runtime (`globalThis.fetch` without).
466
- * - `maxRunBytes`: the bound of the cache of the runs (`MAX_RUN_BYTES` without).
475
+ * - `maxRunBytes`: numeric buffers plus estimated metadata (`MAX_RUN_BYTES` without).
476
+ * - `maxRunEntries`: maximum cached successful runs (128); failed runs are not stored.
477
+ * - `maxInflightRuns`: maximum distinct runs in flight (32).
467
478
  *
468
479
  * The function has `close()`, which terminates the workers of its own pool.
469
480
  */
@@ -479,10 +490,15 @@ export function createPanelEndpoint(options) {
479
490
  pool: givenPool = null,
480
491
  fetch: load = (url) => globalThis.fetch(url),
481
492
  maxRunBytes = MAX_RUN_BYTES,
493
+ maxRunEntries = 128,
494
+ maxInflightRuns = 32,
482
495
  } = options;
483
496
  if (bundle === undefined || bundle === null) throw new Error("createPanelEndpoint needs the URL of a bundle");
484
497
  const bundleUrl = new URL(String(bundle), globalThis.location?.href);
485
- const runs = new Runs(maxRunBytes);
498
+ for (const [name, value] of Object.entries({ maxRunBytes, maxRunEntries, maxInflightRuns })) {
499
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);
500
+ }
501
+ const runs = new Runs(maxRunBytes, maxRunEntries, maxInflightRuns);
486
502
  const models = new Map();
487
503
  let loading = null;
488
504
  let ownPool = null;
package/pool.mjs CHANGED
@@ -15,12 +15,12 @@
15
15
  // the pool, and posted to the workers as `WebAssembly.Module`s, which a structured clone shares
16
16
  // instead of copying (`js/test/workers.test.mjs`). The workers are created when the queue needs
17
17
  // them, up to `workers`; a model is posted to a worker before the first request of it the worker
18
- // runs, once per worker.
18
+ // runs, until its retained instance is evicted by maxWorkerModels.
19
19
  //
20
20
  // The requests run in the order they were made (a FIFO queue), one at a time per worker. A
21
21
  // request whose `signal` aborts is rejected with the reason of the signal: a queued one is
22
- // dropped from the queue and never runs, a running one finishes in its worker (a simulation is
23
- // one synchronous call of the engine) and its result is discarded. An error of the engine
22
+ // dropped from the queue and never runs. A running one discards its result, or is terminated
23
+ // when hardAbort is enabled. Dispatched work has a 30-second deadline by default (0 disables). An error of the engine
24
24
  // (`EngineError` of `loader.mjs`, e.g. an integration which fails) rejects only its request; a
25
25
  // worker which crashes rejects the request it ran and is replaced by a new one. The values of a
26
26
  // result are a `Float64Array` whose buffer the worker transfers, so nothing is copied twice.
@@ -31,7 +31,20 @@
31
31
  // `addEventListener` (the events `message` and `error` of a Web Worker) or `on` (the events
32
32
  // `message` and `error` of a worker thread, whose `message` gives the data itself).
33
33
 
34
- import { EngineError, createRuntime } from "./loader.mjs";
34
+ import { EngineError, createRuntime, validateModelBytes, MAX_MEMORY_PAGES, ENGINE_SECTION } from "./loader.mjs";
35
+
36
+ const poolPlanStates = new WeakMap();
37
+ const preparedJob = Symbol("prepared job");
38
+
39
+ /** Opaque pool request, invalidated by close or model removal. */
40
+ export class PreparedPoolSimulation {
41
+ constructor(token, state) {
42
+ if (token !== poolPlanStates) throw new TypeError("use pool.prepare()");
43
+ poolPlanStates.set(this, state);
44
+ }
45
+ get nValues() { return poolPlanStates.get(this).nValues; }
46
+ close() { poolPlanStates.get(this).close(); }
47
+ }
35
48
 
36
49
  /** The URL of the script of a worker, next to this module. */
37
50
  export const WORKER_URL = new URL("./worker.mjs", import.meta.url);
@@ -81,6 +94,7 @@ function listen(worker, onMessage, onError) {
81
94
  worker.on("message", onMessage);
82
95
  worker.on("error", onError);
83
96
  worker.on("messageerror", onError);
97
+ worker.on("exit", (code) => onError(new Error(`the worker exited (${code})`)));
84
98
  } else {
85
99
  worker.addEventListener("message", (event) => onMessage(event.data));
86
100
  worker.addEventListener("error", (event) => {
@@ -93,9 +107,10 @@ function listen(worker, onMessage, onError) {
93
107
 
94
108
  /** The error of a request which the worker answered with an error (see `worker.mjs`). */
95
109
  function remoteError(fields) {
96
- if (fields.kind !== undefined && fields.name === "EngineError") {
110
+ if (fields.kind !== undefined && ["EngineError", "UnsupportedError"].includes(fields.name)) {
97
111
  const error = new EngineError(fields.kind, fields.detail ?? fields.message, { flag: fields.flag, time: fields.time });
98
112
  if (fields.message) error.message = fields.message;
113
+ error.name = fields.name;
99
114
  return error;
100
115
  }
101
116
  const error = new Error(fields.message);
@@ -115,80 +130,191 @@ export async function createPool({
115
130
  workers = defaultWorkers(),
116
131
  createWorker = browserWorker,
117
132
  workerUrl = WORKER_URL,
133
+ maxWorkers = 32,
134
+ maxQueuedJobs = 1024,
135
+ maxQueuedBytes = 64 * 2 ** 20,
136
+ maxModelBytes = 128 * 2 ** 20,
137
+ maxModels = 128,
138
+ maxWorkerModels = 8,
139
+ maxMemoryPages,
140
+ maxTotalMemoryBytes = 2 ** 31,
141
+ maxModuleBytes = 32 * 2 ** 20,
142
+ maxDescriptionBytes = 16 * 2 ** 20,
143
+ maxRequestBytes = 16 * 2 ** 20,
144
+ deadlineMs = 30000,
145
+ hardAbort = false,
118
146
  }) {
119
147
  if (!Number.isInteger(workers) || workers < 1) {
120
148
  throw new Error(`a pool needs at least one worker, not ${workers}`);
121
149
  }
122
- const runtime = await createRuntime({ engine, mathlib });
150
+ for (const [name, value] of Object.entries({ maxWorkers, maxQueuedJobs, maxQueuedBytes, maxModelBytes, maxModels, maxWorkerModels, maxTotalMemoryBytes, maxModuleBytes, maxDescriptionBytes, maxRequestBytes })) {
151
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);
152
+ }
153
+ if (workers > maxWorkers) throw new Error(`workers exceeds maxWorkers (${maxWorkers})`);
154
+ const checkDeadline = (value) => {
155
+ if (!Number.isFinite(value) || value < 0 || value > 2147483647) throw new Error("deadlineMs must be between 0 and 2147483647");
156
+ };
157
+ checkDeadline(deadlineMs);
158
+ const checkModuleSize = (module) => {
159
+ if (!(module instanceof WebAssembly.Module) && module?.byteLength > maxModuleBytes) {
160
+ throw new Error(`module exceeds maxModuleBytes (${maxModuleBytes})`);
161
+ }
162
+ };
163
+ checkModuleSize(engine);
164
+ checkModuleSize(mathlib);
165
+ const runtime = await createRuntime({ engine, mathlib, maxMemoryPages });
166
+ const retained = workers * Math.min(maxWorkerModels, maxModels);
167
+ const aggregatePages = Math.floor(maxTotalMemoryBytes / 65536 / retained);
168
+ const sections = WebAssembly.Module.customSections(runtime.modules.engine, ENGINE_SECTION);
169
+ const minimum = JSON.parse(new TextDecoder().decode(sections[0])).memory_minimum_pages;
170
+ if (aggregatePages < minimum) {
171
+ throw new Error(`maxTotalMemoryBytes (${maxTotalMemoryBytes}) cannot fit ${retained} retained instances at the engine minimum (${minimum} pages)`);
172
+ }
173
+ if (maxMemoryPages !== undefined && maxMemoryPages > aggregatePages) {
174
+ throw new Error(`maxMemoryPages (${maxMemoryPages}) exceeds maxTotalMemoryBytes (${maxTotalMemoryBytes}) for ${retained} retained instances; lower workers/maxWorkerModels or raise the total budget`);
175
+ }
176
+ maxMemoryPages ??= Math.min(MAX_MEMORY_PAGES, aggregatePages);
177
+
178
+ // Count UTF-8 bytes without allocating another encoded copy of large JSON strings.
179
+ const checkTextSize = (text, maximum, name) => {
180
+ if (typeof text !== "string") throw new Error(`${name} must serialize to JSON text`);
181
+ let bytes = 0;
182
+ for (let i = 0; i < text.length; i++) {
183
+ const code = text.charCodeAt(i);
184
+ if (code < 128) bytes += 1;
185
+ else if (code < 2048) bytes += 2;
186
+ else if (code >= 0xd800 && code <= 0xdbff && text.charCodeAt(i + 1) >= 0xdc00 && text.charCodeAt(i + 1) <= 0xdfff) {
187
+ bytes += 4;
188
+ i++;
189
+ } else bytes += 3;
190
+ if (bytes > maximum) throw new Error(`${name} exceeds its byte limit (${maximum})`);
191
+ }
192
+ return bytes;
193
+ };
123
194
  const models = new Map();
195
+ const plans = new Map();
196
+ let nextPlanId = 1;
197
+ const loadingModels = new Set();
124
198
  const slots = [];
125
- const queue = [];
199
+ const queue = new Map();
200
+ let queuedBytes = 0;
201
+ let modelBytes = 0;
202
+ const dequeue = (job) => {
203
+ if (queue.delete(job.id)) queuedBytes -= job.bytes;
204
+ };
205
+ let pumping = false;
126
206
  let nextId = 1;
127
207
  let closed = false;
128
208
 
129
209
  /** Settles a job once; later answers of it are ignored. */
130
- const settle = (job, error, result) => {
210
+ const settle = (job, error, result, failed = true) => {
131
211
  if (job.settled) return;
132
212
  job.settled = true;
133
213
  job.signal?.removeEventListener("abort", job.onAbort);
134
- if (error) job.reject(error);
214
+ if (failed) job.reject(error);
135
215
  else job.resolve(result);
136
216
  };
137
217
 
218
+ const stop = (worker) => {
219
+ try { Promise.resolve(worker.terminate()).catch(() => {}); } catch { /* already stopped */ }
220
+ };
221
+
138
222
  const spawn = () => {
139
- const slot = { worker: createWorker(workerUrl), models: new Set(), job: null, dead: false };
140
- listen(
141
- slot.worker,
142
- (message) => {
143
- const job = slot.job;
144
- if (!job || message?.id !== job.id) return;
145
- slot.job = null;
146
- if (message.type === "result") {
147
- settle(job, null, { columns: message.columns, nRows: message.nRows, values: message.values });
148
- } else {
149
- settle(job, remoteError(message.error ?? {}));
150
- }
151
- pump();
152
- },
153
- (error) => {
154
- // a worker which crashed: its request fails, the slot is replaced
155
- if (slot.dead) return;
156
- slot.dead = true;
157
- const index = slots.indexOf(slot);
158
- if (index >= 0) slots.splice(index, 1);
159
- slot.worker.terminate();
160
- if (slot.job) settle(slot.job, error instanceof Error ? error : new Error(String(error)));
161
- slot.job = null;
162
- pump();
163
- },
164
- );
165
- slot.worker.postMessage({ type: "init", ...runtime.modules });
223
+ const slot = { worker: createWorker(workerUrl), models: new Set(), plans: new Set(), job: null, dead: false };
224
+ try {
225
+ listen(
226
+ slot.worker,
227
+ (message) => {
228
+ const job = slot.job;
229
+ if (slot.dead || !job || message?.id !== job.id) return;
230
+ clearTimeout(job.timer);
231
+ slot.job = null;
232
+ if (message.type === "prepared") {
233
+ settle(job, null, message.nValues, false);
234
+ } else if (message.type === "result") {
235
+ settle(job, null, { columns: message.columns, nRows: message.nRows, values: message.values }, false);
236
+ } else {
237
+ settle(job, remoteError(message.error ?? {}));
238
+ }
239
+ pump();
240
+ },
241
+ (error) => retire(slot, error),
242
+ );
243
+ slot.worker.postMessage({ type: "init", ...runtime.modules, maxMemoryPages });
244
+ } catch (error) {
245
+ slot.dead = true;
246
+ stop(slot.worker);
247
+ throw error;
248
+ }
166
249
  slots.push(slot);
167
250
  return slot;
168
251
  };
169
252
 
170
- /** Starts the queued jobs on the idle workers, creating workers up to the most. */
253
+ const retire = (slot, error) => {
254
+ if (slot.dead) return;
255
+ slot.dead = true;
256
+ const index = slots.indexOf(slot);
257
+ if (index >= 0) slots.splice(index, 1);
258
+ stop(slot.worker);
259
+ if (slot.job) { clearTimeout(slot.job.timer); settle(slot.job, error); }
260
+ slot.job = null;
261
+ pump();
262
+ };
263
+
264
+ /** Dispatch failures retire the worker, since preceding messages may have been delivered. */
171
265
  const pump = () => {
172
- while (!closed && queue.length > 0) {
173
- const key = queue[0].key;
174
- const idle = slots.filter((slot) => !slot.job);
175
- const slot = idle.find((s) => s.models.has(key)) ?? idle[0] ?? (slots.length < workers ? spawn() : null);
176
- if (!slot) return;
177
- const job = queue.shift();
178
- if (!slot.models.has(job.key)) {
179
- const { module, description } = models.get(job.key);
180
- slot.worker.postMessage({ type: "model", key: job.key, module, description });
181
- slot.models.add(job.key);
266
+ if (pumping) return;
267
+ pumping = true;
268
+ try {
269
+ while (!closed && queue.size > 0) {
270
+ const job = queue.values().next().value;
271
+ const key = job.key;
272
+ const idle = slots.filter((slot) => !slot.job);
273
+ let slot = idle.find((s) => s.models.has(key)) ?? idle[0];
274
+ if (!slot && slots.length >= workers) return;
275
+ dequeue(job);
276
+ try {
277
+ slot ??= spawn();
278
+ slot.job = job;
279
+ if (job.deadlineMs > 0) job.timer = setTimeout(() => {
280
+ const error = new Error(`worker deadline exceeded (${job.deadlineMs} ms)`);
281
+ error.name = "TimeoutError";
282
+ retire(slot, error);
283
+ }, job.deadlineMs);
284
+ if (!slot.models.has(job.key)) {
285
+ if (slot.models.size >= maxWorkerModels) {
286
+ const oldest = slot.models.values().next().value;
287
+ slot.worker.postMessage({ type: "removeModel", key: oldest });
288
+ slot.models.delete(oldest);
289
+ for (const id of slot.plans) if (plans.get(id)?.key === oldest) slot.plans.delete(id);
290
+ }
291
+ const { module, description } = models.get(job.key);
292
+ slot.worker.postMessage({ type: "model", key: job.key, module, description });
293
+ }
294
+ slot.models.delete(job.key);
295
+ slot.models.add(job.key);
296
+ if (job.prepared) {
297
+ const state = job.prepared;
298
+ const definition = slot.plans.has(state.id) ? {} : { request: state.request, varying: state.varying };
299
+ slot.worker.postMessage({ type: job.type, id: job.id, key: job.key, planId: state.id, values: job.values, ...definition }, job.values ? [job.values.buffer] : []);
300
+ slot.plans.add(state.id);
301
+ } else slot.worker.postMessage({ type: "simulate", id: job.id, key: job.key, request: job.request });
302
+ } catch (error) {
303
+ settle(job, error);
304
+ if (slot) retire(slot, error);
305
+ }
182
306
  }
183
- slot.job = job;
184
- slot.worker.postMessage({ type: "simulate", id: job.id, key: job.key, request: job.request });
185
- }
307
+ } finally { pumping = false; }
186
308
  };
187
309
 
188
- return {
310
+ const api = {
189
311
  /** The most workers of the pool. */
190
312
  size: workers,
191
313
 
314
+ /** Effective per-instance and aggregate linear-memory policies. */
315
+ maxMemoryPages,
316
+ maxTotalMemoryBytes,
317
+
192
318
  /** The compiled modules of the runtime. */
193
319
  modules: runtime.modules,
194
320
 
@@ -199,11 +325,45 @@ export async function createPool({
199
325
  */
200
326
  async addModel(key, model, description) {
201
327
  if (closed) throw new Error("the pool is closed");
202
- if (models.has(key)) throw new Error(`the pool has a model ${key} already`);
328
+ if (models.has(key) || loadingModels.has(key)) throw new Error(`the pool has a model ${key} already`);
329
+ if (models.size + loadingModels.size >= maxModels) throw new Error(`model limit reached (${maxModels})`);
330
+ checkModuleSize(model);
331
+ if (!(model instanceof WebAssembly.Module)) validateModelBytes(model);
203
332
  const text = typeof description === "string" ? description : JSON.stringify(description);
204
- const module = model instanceof WebAssembly.Module ? model : await WebAssembly.compile(model);
205
- if (models.has(key)) throw new Error(`the pool has a model ${key} already`);
206
- models.set(key, { module, description: text });
333
+ const bytes = checkTextSize(text, maxDescriptionBytes, "description")
334
+ + (model instanceof WebAssembly.Module ? 0 : model.byteLength);
335
+ if (modelBytes + bytes > maxModelBytes) throw new Error(`registered models exceed maxModelBytes (${maxModelBytes})`);
336
+ // Reserve before asynchronous compilation so concurrent calls cannot multiply
337
+ // live module inputs beyond the aggregate policy.
338
+ loadingModels.add(key);
339
+ modelBytes += bytes;
340
+ let registered = false;
341
+ try {
342
+ const module = model instanceof WebAssembly.Module ? model : await WebAssembly.compile(model);
343
+ if (closed) throw new Error("the pool is closed");
344
+ models.set(key, { module, description: text, bytes });
345
+ registered = true;
346
+ } finally {
347
+ if (loadingModels.delete(key) && !registered) modelBytes -= bytes;
348
+ }
349
+ },
350
+
351
+ /** Removes an idle model; queued/running users must complete or abort first. */
352
+ removeModel(key) {
353
+ if (loadingModels.has(key) || [...queue.values()].some((job) => job.key === key) || slots.some((slot) => slot.job?.key === key)) {
354
+ throw new Error(`model ${key} is in use`);
355
+ }
356
+ const model = models.get(key);
357
+ if (!model) return false;
358
+ for (const state of [...plans.values()]) if (state.key === key) state.close();
359
+ models.delete(key);
360
+ modelBytes -= model.bytes;
361
+ for (const slot of [...slots]) {
362
+ if (!slot.models.delete(key)) continue;
363
+ try { slot.worker.postMessage({ type: "removeModel", key }); }
364
+ catch (error) { retire(slot, error); }
365
+ }
366
+ return true;
207
367
  },
208
368
 
209
369
  /** Whether the pool has a model under a key. */
@@ -211,25 +371,80 @@ export async function createPool({
211
371
  return models.has(key);
212
372
  },
213
373
 
374
+ async prepare(key, request, { varying = [] } = {}) {
375
+ if (closed) throw new Error("the pool is closed");
376
+ if (!models.has(key)) throw new Error(`the pool has no model ${key}`);
377
+ if (plans.size >= 32) throw new Error("prepared request limit reached (32)");
378
+ const text = typeof request === "string" ? request : JSON.stringify(request);
379
+ const bytes = checkTextSize(text, maxRequestBytes, "request");
380
+ const varyingText = JSON.stringify(varying);
381
+ const varyingBytes = checkTextSize(varyingText, maxRequestBytes, "varying");
382
+ if (modelBytes + bytes + varyingBytes > maxModelBytes) throw new Error(`prepared requests exceed maxModelBytes (${maxModelBytes})`);
383
+ const state = { owner: api, id: nextPlanId++, key, request: text, varying: JSON.parse(varyingText), bytes: bytes + varyingBytes, nValues: 0, closed: false };
384
+ const plan = new PreparedPoolSimulation(poolPlanStates, state);
385
+ state.close = () => {
386
+ if (state.closed) return;
387
+ state.closed = true;
388
+ plans.delete(state.id);
389
+ modelBytes -= state.bytes;
390
+ const error = new Error("the prepared request is closed");
391
+ for (const job of [...queue.values()]) if (job.prepared === state) { dequeue(job); settle(job, error); }
392
+ for (const slot of [...slots]) if (slot.plans.delete(state.id)) {
393
+ try { slot.worker.postMessage({ type: "releasePrepared", key, planId: state.id }); }
394
+ catch (error) { retire(slot, error); }
395
+ }
396
+ };
397
+ plans.set(state.id, state);
398
+ modelBytes += state.bytes;
399
+ try {
400
+ state.nValues = await api.simulate(key, { [preparedJob]: { type: "prepare", prepared: state } });
401
+ if (state.closed || closed) throw new Error("the prepared request is closed");
402
+ return plan;
403
+ } catch (error) { state.close(); throw error; }
404
+ },
405
+
406
+ simulatePrepared(plan, values = [], options = {}) {
407
+ const state = poolPlanStates.get(plan);
408
+ if (!state || state.owner !== api || state.closed) return Promise.reject(new Error("foreign or closed prepared request"));
409
+ if ((!Array.isArray(values) && !(values instanceof Float64Array)) || values.length !== state.nValues || values.findIndex((value) => !Number.isFinite(value)) >= 0) {
410
+ return Promise.reject(new Error(`prepared request requires ${state.nValues} finite values`));
411
+ }
412
+ return api.simulate(state.key, { [preparedJob]: { type: "simulatePrepared", prepared: state, values: Float64Array.from(values) } }, options);
413
+ },
414
+
214
415
  /**
215
416
  * Simulates a request of `simulation/1` (an object or its JSON text) on the model `key` in
216
417
  * a worker; resolves to `{ columns, nRows, values }` as `instance.simulate` of the loader,
217
418
  * the values a `Float64Array`. `signal` (an `AbortSignal`) drops the request, see the module
218
419
  * comment.
219
420
  */
220
- simulate(key, request, { signal } = {}) {
421
+ simulate(key, request, { signal, deadlineMs: jobDeadline = deadlineMs, hardAbort: jobHardAbort = hardAbort } = {}) {
221
422
  return new Promise((resolve, reject) => {
222
423
  if (closed) throw new Error("the pool is closed");
223
424
  if (!models.has(key)) throw new Error(`the pool has no model ${key}`);
425
+ checkDeadline(jobDeadline);
426
+ if (queue.size >= maxQueuedJobs) throw new Error(`pool queue limit reached (${maxQueuedJobs})`);
224
427
  signal?.throwIfAborted();
225
- const job = { id: nextId++, key, request, signal, resolve, reject, settled: false };
428
+ const prepared = request?.[preparedJob];
429
+ const text = prepared ? "" : typeof request === "string" ? request : JSON.stringify(request, (_key, value) => {
430
+ if (typeof value === "function" || typeof value === "symbol") {
431
+ throw new DOMException("request values could not be cloned", "DataCloneError");
432
+ }
433
+ return value;
434
+ });
435
+ const bytes = prepared ? (prepared.values?.byteLength ?? prepared.prepared.bytes) : checkTextSize(text, maxRequestBytes, "request");
436
+ if (bytes > maxRequestBytes) throw new Error(`request exceeds its byte limit (${maxRequestBytes})`);
437
+ if (queuedBytes + bytes > maxQueuedBytes) throw new Error(`pool queue exceeds maxQueuedBytes (${maxQueuedBytes})`);
438
+ const job = { ...prepared, bytes, id: nextId++, key, request: text, signal, resolve, reject, settled: false, deadlineMs: jobDeadline };
226
439
  job.onAbort = () => {
227
- const index = queue.indexOf(job);
228
- if (index >= 0) queue.splice(index, 1);
440
+ dequeue(job);
229
441
  settle(job, signal.reason);
442
+ const slot = slots.find((slot) => slot.job === job);
443
+ if (slot && jobHardAbort) retire(slot, signal.reason);
230
444
  };
231
445
  signal?.addEventListener("abort", job.onAbort, { once: true });
232
- queue.push(job);
446
+ queue.set(job.id, job);
447
+ queuedBytes += bytes;
233
448
  pump();
234
449
  });
235
450
  },
@@ -241,13 +456,20 @@ export async function createPool({
241
456
  close() {
242
457
  if (closed) return;
243
458
  closed = true;
459
+ for (const state of [...plans.values()]) state.close();
244
460
  const error = new Error("the pool is closed");
245
- for (const job of queue.splice(0)) settle(job, error);
461
+ for (const job of queue.values()) settle(job, error);
462
+ queue.clear();
463
+ queuedBytes = 0;
464
+ models.clear();
465
+ loadingModels.clear();
466
+ modelBytes = 0;
246
467
  for (const slot of slots.splice(0)) {
247
468
  slot.dead = true;
248
- slot.worker.terminate();
249
- if (slot.job) settle(slot.job, error);
469
+ stop(slot.worker);
470
+ if (slot.job) { clearTimeout(slot.job.timer); settle(slot.job, error); }
250
471
  }
251
472
  },
252
473
  };
474
+ return api;
253
475
  }
Binary file
Binary file
package/worker.mjs CHANGED
@@ -14,6 +14,7 @@
14
14
  // { type: "model", key, module, description } a model: its `WebAssembly.Module` and the text
15
15
  // of its `model.json`, instantiated at its first
16
16
  // request
17
+ // { type: "removeModel", key } drops a retained model and its instance
17
18
  // { type: "simulate", id, key, request } a request of `simulation/1` on the model `key`
18
19
  //
19
20
  // and its answers, one per request:
@@ -59,20 +60,53 @@ async function instanceOf(key) {
59
60
  async function handle(message) {
60
61
  switch (message.type) {
61
62
  case "init":
62
- runtime = createRuntime({ engine: message.engine, mathlib: message.mathlib });
63
+ runtime = createRuntime({ engine: message.engine, mathlib: message.mathlib, maxMemoryPages: message.maxMemoryPages });
63
64
  runtime.catch(() => {}); // the error is the one of every request
64
65
  return;
65
66
  case "model":
66
- models.set(message.key, { module: message.module, description: message.description, instance: null });
67
+ models.set(message.key, { module: message.module, description: message.description, instance: null, plans: new Map(), definitions: new Map() });
67
68
  return;
69
+ case "releasePrepared": {
70
+ const model = models.get(message.key);
71
+ model?.plans.get(message.planId)?.close();
72
+ model?.plans.delete(message.planId);
73
+ model?.definitions.delete(message.planId);
74
+ return;
75
+ }
76
+ case "removeModel":
77
+ for (const plan of models.get(message.key)?.plans.values() ?? []) plan.close();
78
+ models.delete(message.key);
79
+ return;
80
+ case "prepare":
81
+ case "simulatePrepared":
68
82
  case "simulate": {
69
83
  let instance = null;
70
84
  try {
71
85
  instance = await instanceOf(message.key);
72
- const { columns, nRows, values } = instance.simulate(message.request);
86
+ const model = models.get(message.key);
87
+ let plan;
88
+ if (message.type !== "simulate") {
89
+ if (message.request !== undefined) model.definitions.set(message.planId, { request: message.request, varying: message.varying });
90
+ plan = model.plans.get(message.planId);
91
+ if (!plan) {
92
+ const definition = model.definitions.get(message.planId);
93
+ if (!definition) throw new Error("missing prepared request definition");
94
+ plan = instance.prepare(definition.request, { varying: definition.varying });
95
+ model.plans.set(message.planId, plan);
96
+ }
97
+ }
98
+ if (message.type === "prepare") {
99
+ post({ type: "prepared", id: message.id, nValues: plan.nValues });
100
+ return;
101
+ }
102
+ const { columns, nRows, values } = plan ? instance.simulatePrepared(plan, message.values) : instance.simulate(message.request);
73
103
  post({ type: "result", id: message.id, columns, nRows, values }, [values.buffer]);
74
104
  } catch (error) {
75
- if (instance?.trapped) models.get(message.key).instance = null;
105
+ if (instance?.trapped) {
106
+ const model = models.get(message.key);
107
+ model.instance = null;
108
+ model.plans.clear();
109
+ }
76
110
  post({ type: "error", id: message.id, error: errorFields(error) });
77
111
  }
78
112
  return;