@sdeverywhere/runtime-async 0.2.0 → 0.2.3

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/README.md CHANGED
@@ -1,28 +1,43 @@
1
1
  # @sdeverywhere/runtime-async
2
2
 
3
- This package provides an implementation of the `ModelRunner` interface from
4
- the `@sdeverywhere/runtime` package that uses a Web Worker (in the browser)
5
- or a worker thread (in a Node.js app) to run the model asynchronously off
6
- the main JavaScript thread.
3
+ This package provides an implementation of the `ModelRunner` interface (from the `@sdeverywhere/runtime` package) that uses a Web Worker (in the browser) or a worker thread (in a Node.js app) to run the model asynchronously off the main JavaScript thread.
4
+
5
+ ## Quick Start
6
+
7
+ The best way to get started with SDEverywhere is to follow the [Quick Start](https://github.com/climateinteractive/SDEverywhere#quick-start) instructions.
8
+ If you follow those instructions, the `@sdeverywhere/runtime-async` package will be added to your project automatically, in which case you can skip the next section and jump straight to the ["Usage"](#usage) section below.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ # npm
14
+ npm install @sdeverywhere/runtime-async
15
+
16
+ # pnpm
17
+ pnpm add @sdeverywhere/runtime-async
18
+
19
+ # yarn
20
+ yarn add @sdeverywhere/runtime-async
21
+ ```
7
22
 
8
23
  ## Usage
9
24
 
10
- ### 1. Initialize the `WasmModel` in a Web Worker
25
+ _NOTE:_ If you followed the "Quick Start" instructions and/or used the
26
+ `@sdeverywhere/create` package to generate your project, the initialization
27
+ steps listed below are already implemented for you in the generated `core` package,
28
+ and you can work directly with a `ModelRunner` and/or `ModelScheduler` instance.
29
+
30
+ ### 1. Initialize your generated model in a Web Worker
11
31
 
12
32
  In your app project, define a separate JavaScript file, called
13
- `worker.js` for example, that initializes the model worker in the
33
+ `worker.js` for example, that initializes the generated model in the
14
34
  context of the Web Worker:
15
35
 
16
36
  ```js
17
- import { initWasmModelAndBuffers } from '@sdeverywhere/runtime'
18
37
  import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'
38
+ import loadGeneratedModel from './sde-prep/generated-model.js'
19
39
 
20
- async function initWasmModel() {
21
- const wasmModules = loadWasm()
22
- return initWasmModelAndBuffers(...)
23
- }
24
-
25
- exposeModelWorker(initWasmModel)
40
+ exposeModelWorker(loadGeneratedModel)
26
41
  ```
27
42
 
28
43
  ### 2. Spawn the worker
package/dist/index.cjs CHANGED
@@ -37,15 +37,15 @@ async function spawnAsyncModelRunner(workerSpec) {
37
37
  async function spawnAsyncModelRunnerWithWorker(worker) {
38
38
  const modelWorker2 = await (0, import_threads.spawn)(worker);
39
39
  const initResult = await modelWorker2.initModel();
40
- let ioBuffer = initResult.ioBuffer;
41
- const rowLength = initResult.rowLength;
40
+ const modelListing = initResult.modelListing ? new import_runtime.ModelListing(initResult.modelListing) : void 0;
41
+ const params2 = new import_runtime.BufferedRunModelParams(modelListing);
42
42
  let running = false;
43
43
  let terminated = false;
44
44
  return {
45
45
  createOutputs: () => {
46
46
  return new import_runtime.Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq);
47
47
  },
48
- runModel: async (inputs, outputs) => {
48
+ runModel: async (inputs, outputs, options) => {
49
49
  if (terminated) {
50
50
  throw new Error("Async model runner has already been terminated");
51
51
  } else if (running) {
@@ -53,24 +53,15 @@ async function spawnAsyncModelRunnerWithWorker(worker) {
53
53
  } else {
54
54
  running = true;
55
55
  }
56
- const runTimeLengthInElements = 1;
57
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
58
- const inputsLengthInElements = inputs.length;
59
- const inputsLengthInBytes = inputsLengthInElements * 8;
60
- const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
61
- for (let i = 0; i < inputs.length; i++) {
62
- inputsArray[i] = inputs[i].get();
63
- }
56
+ params2.updateFromParams(inputs, outputs, options);
57
+ let ioBuffer;
64
58
  try {
65
- ioBuffer = await modelWorker2.runModel((0, import_threads.Transfer)(ioBuffer));
59
+ ioBuffer = await modelWorker2.runModel((0, import_threads.Transfer)(params2.getEncodedBuffer()));
66
60
  } finally {
67
61
  running = false;
68
62
  }
69
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
70
- outputs.runTimeInMillis = runTimeBufferArray[0];
71
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
72
- const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
73
- outputs.updateFromBuffer(outputsArray, rowLength);
63
+ params2.updateFromEncodedBuffer(ioBuffer);
64
+ params2.finalizeOutputs(outputs);
74
65
  return outputs;
75
66
  },
76
67
  terminate: () => {
@@ -87,58 +78,36 @@ async function spawnAsyncModelRunnerWithWorker(worker) {
87
78
  // src/worker.ts
88
79
  var import_worker = require("threads/worker");
89
80
  var import_runtime2 = require("@sdeverywhere/runtime");
90
- var initWasmModel;
91
- var wasmModel;
92
- var inputsWasmBuffer;
93
- var outputsWasmBuffer;
81
+ var initGeneratedModel;
82
+ var runnableModel;
83
+ var params = new import_runtime2.BufferedRunModelParams();
94
84
  var modelWorker = {
95
85
  async initModel() {
96
- if (wasmModel) {
97
- throw new Error("WasmModel was already initialized");
86
+ if (runnableModel) {
87
+ throw new Error("RunnableModel was already initialized");
98
88
  }
99
- const wasmResult = await initWasmModel();
100
- wasmModel = wasmResult.model;
101
- inputsWasmBuffer = wasmResult.inputsBuffer;
102
- outputsWasmBuffer = wasmResult.outputsBuffer;
103
- const runTimeLength = 8;
104
- const inputsLength = inputsWasmBuffer.getArrayView().length;
105
- const outputsLength = outputsWasmBuffer.getArrayView().length;
106
- const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength);
107
- const ioBuffer = ioArray.buffer;
108
- const initResult = {
109
- outputVarIds: wasmResult.outputVarIds,
110
- startTime: wasmModel.startTime,
111
- endTime: wasmModel.endTime,
112
- saveFreq: wasmModel.saveFreq,
113
- rowLength: wasmModel.numSavePoints,
114
- ioBuffer
89
+ const generatedModel = await initGeneratedModel();
90
+ runnableModel = (0, import_runtime2.createRunnableModel)(generatedModel);
91
+ return {
92
+ outputVarIds: runnableModel.outputVarIds,
93
+ modelListing: runnableModel.modelListing,
94
+ startTime: runnableModel.startTime,
95
+ endTime: runnableModel.endTime,
96
+ saveFreq: runnableModel.saveFreq,
97
+ outputRowLength: runnableModel.numSavePoints
115
98
  };
116
- return (0, import_worker.Transfer)(initResult, [ioBuffer]);
117
99
  },
118
100
  runModel(ioBuffer) {
119
- if (!wasmModel) {
120
- throw new Error("WasmModel must be initialized before running the model in worker");
101
+ if (!runnableModel) {
102
+ throw new Error("RunnableModel must be initialized before running the model in worker");
121
103
  }
122
- const runTimeLengthInElements = 1;
123
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
124
- const inputsWasmArray = inputsWasmBuffer.getArrayView();
125
- const inputsLengthInElements = inputsWasmArray.length;
126
- const inputsLengthInBytes = inputsLengthInElements * 8;
127
- const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
128
- inputsWasmArray.set(inputsBufferArray);
129
- const t0 = (0, import_runtime2.perfNow)();
130
- wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer);
131
- const elapsed = (0, import_runtime2.perfElapsed)(t0);
132
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
133
- runTimeBufferArray[0] = elapsed;
134
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
135
- const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
136
- outputsBufferArray.set(outputsWasmBuffer.getArrayView());
104
+ params.updateFromEncodedBuffer(ioBuffer);
105
+ runnableModel.runModel(params);
137
106
  return (0, import_worker.Transfer)(ioBuffer);
138
107
  }
139
108
  };
140
109
  function exposeModelWorker(init) {
141
- initWasmModel = init;
110
+ initGeneratedModel = init;
142
111
  (0, import_worker.expose)(modelWorker);
143
112
  }
144
113
  // Annotate the CommonJS export names for ESM import in node:
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/runner.ts","../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nexport { spawnAsyncModelRunner } from './runner'\n\nexport { exposeModelWorker } from './worker'\n","// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker thread.\n *\n * In your app project, define a JavaScript file, called `worker.js` for example, that\n * initializes the model worker in the context of the Web Worker:\n *\n * ```js\n * import { initWasmModelAndBuffers } from '@sdeverywhere/runtime'\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n *\n * async function initWasmModel() {\n * const wasmModules = loadWasm()\n * return initWasmModelAndBuffers(...)\n * }\n *\n * exposeModelWorker(initWasmModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the Web Worker and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n let ioBuffer: ArrayBuffer = initResult.ioBuffer\n\n // The row length is the number of elements in each row of the outputs buffer\n const rowLength = initResult.rowLength\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Capture the current set of input values into the reusable buffer\n const inputsLengthInElements = inputs.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n for (let i = 0; i < inputs.length; i++) {\n inputsArray[i] = inputs[i].get()\n }\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n try {\n ioBuffer = await modelWorker.runModel(Transfer(ioBuffer))\n } finally {\n running = false\n }\n\n // Save the model run time\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n outputs.runTimeInMillis = runTimeBufferArray[0]\n\n // Capture the outputs array by copying the data into the given `Outputs`\n // data structure\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputs.updateFromBuffer(outputsArray, rowLength)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n","// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { WasmBuffer, WasmModel, WasmModelInitResult } from '@sdeverywhere/runtime'\nimport { perfElapsed, perfNow } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initWasmModel: () => Promise<WasmModelInitResult>\n/** @hidden */\nlet wasmModel: WasmModel\n/** @hidden */\nlet inputsWasmBuffer: WasmBuffer\n/** @hidden */\nlet outputsWasmBuffer: WasmBuffer\n\ninterface InitResult {\n outputVarIds: string[]\n startTime: number\n endTime: number\n saveFreq: number\n rowLength: number\n ioBuffer: ArrayBuffer\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<TransferDescriptor<InitResult>> {\n if (wasmModel) {\n throw new Error('WasmModel was already initialized')\n }\n\n // Initialize the wasm model and associated buffers\n const wasmResult = await initWasmModel()\n\n // Capture the `WasmModel` instance and `WasmBuffer` instances\n wasmModel = wasmResult.model\n inputsWasmBuffer = wasmResult.inputsBuffer\n outputsWasmBuffer = wasmResult.outputsBuffer\n\n // Create a combined array that will hold a copy of the inputs and outputs\n // wasm buffers; this buffer is no-copy transferable, whereas the wasm ones\n // are not allowed to be transferred\n const runTimeLength = 8\n const inputsLength = inputsWasmBuffer.getArrayView().length\n const outputsLength = outputsWasmBuffer.getArrayView().length\n const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength)\n\n // Transfer the underlying buffer to the runner\n const ioBuffer = ioArray.buffer\n const initResult: InitResult = {\n outputVarIds: wasmResult.outputVarIds,\n startTime: wasmModel.startTime,\n endTime: wasmModel.endTime,\n saveFreq: wasmModel.saveFreq,\n rowLength: wasmModel.numSavePoints,\n ioBuffer\n }\n return Transfer(initResult, [ioBuffer])\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!wasmModel) {\n throw new Error('WasmModel must be initialized before running the model in worker')\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Copy the inputs into the wasm inputs buffer\n const inputsWasmArray = inputsWasmBuffer.getArrayView()\n const inputsLengthInElements = inputsWasmArray.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n inputsWasmArray.set(inputsBufferArray)\n\n // Run the model using the wasm buffers\n const t0 = perfNow()\n wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer)\n const elapsed = perfElapsed(t0)\n\n // Write the model run time to the buffer\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n runTimeBufferArray[0] = elapsed\n\n // Copy the outputs from the wasm outputs buffer\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputsBufferArray.set(outputsWasmBuffer.getArrayView())\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the `WasmModel` on the worker thread\n * and sending the outputs back to the main process.\n *\n * @param init The function that initializes the `WasmModel` instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<WasmModelInitResult>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initWasmModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,qBAA4D;AAG5D,qBAAwB;AAqCxB,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,SAAS;AACtB,WAAO,gCAAgC,IAAI,sBAAO,WAAW,OAAO,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,0BAAW,SAAS,WAAW,SAAS,CAAC;AAAA,EAClF;AACF;AAKA,eAAe,gCAAgC,QAAsC;AAEnF,QAAMA,eAAc,UAAM,sBAAM,MAAM;AAGtC,QAAM,aAAa,MAAMA,aAAY,UAAU;AAC/C,MAAI,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A,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAAgD;AAGhF,kBAAgB;AAGhB,4BAAO,WAAW;AACpB;","names":["modelWorker","import_runtime"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/runner.ts","../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nexport { spawnAsyncModelRunner } from './runner'\n\nexport { exposeModelWorker } from './worker'\n","// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, ModelListing, Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker\n * (a Web Worker when running in a browser environment, or a worker thread\n * when running in a Node.js environment).\n *\n * In your app project, define a JavaScript file, called `worker.js` for example,\n * that initializes the generated model in the context of a worker thread:\n *\n * ```js\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n * import loadGeneratedModel from './sde-prep/generated-model.js'\n *\n * exposeModelWorker(loadGeneratedModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the worker thread and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n\n // Create a `ModelListing` instance if the listing was defined in the generated model\n const modelListing = initResult.modelListing ? new ModelListing(initResult.modelListing) : undefined\n\n // Maintain a `BufferedRunModelParams` instance that holds the I/O parameters\n const params = new BufferedRunModelParams(modelListing)\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs, options) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // Update the I/O parameters\n params.updateFromParams(inputs, outputs, options)\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n let ioBuffer: ArrayBuffer\n try {\n ioBuffer = await modelWorker.runModel(Transfer(params.getEncodedBuffer()))\n } finally {\n running = false\n }\n\n // Once the buffer is transferred to the worker, the buffer in the\n // `BufferedRunModelParams` becomes \"detached\" and is no longer usable.\n // After the buffer is transferred back from the worker, we need to\n // restore the state of the object to use the new buffer.\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Copy the output values and elapsed time from the buffer to the\n // `Outputs` instance\n params.finalizeOutputs(outputs)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n","// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { GeneratedModel, RunnableModel } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, createRunnableModel } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initGeneratedModel: () => Promise<GeneratedModel>\n\n/** @hidden */\nlet runnableModel: RunnableModel\n\n/**\n * Maintain a `BufferedRunModelParams` instance that wraps the transferable buffer\n * containing the I/O parameters.\n * @hidden\n */\nconst params = new BufferedRunModelParams()\n\ninterface InitResult {\n outputVarIds: string[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelListing?: /*ModelListingSpecs*/ any\n startTime: number\n endTime: number\n saveFreq: number\n outputRowLength: number\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<InitResult> {\n if (runnableModel) {\n throw new Error('RunnableModel was already initialized')\n }\n\n // Initialize the runnable model\n const generatedModel = await initGeneratedModel()\n runnableModel = createRunnableModel(generatedModel)\n\n // Transfer the model metadata to the runner\n return {\n outputVarIds: runnableModel.outputVarIds,\n modelListing: runnableModel.modelListing,\n startTime: runnableModel.startTime,\n endTime: runnableModel.endTime,\n saveFreq: runnableModel.saveFreq,\n outputRowLength: runnableModel.numSavePoints\n }\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!runnableModel) {\n throw new Error('RunnableModel must be initialized before running the model in worker')\n }\n\n // Update the `BufferedRunModelParams` to use the values in the buffer that was transferred\n // from the runner to the worker\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Run the model synchronously on the worker thread using those I/O parameters\n runnableModel.runModel(params)\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the model on the worker thread and\n * sending the outputs back to the main thread.\n *\n * @param init The function that initializes the generated model instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<GeneratedModel>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initGeneratedModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)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B,OAAO;AACL,qBAAa;AACb,eAAO,sBAAO,UAAUD,YAAW;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF;;;ACpHA,oBAAiC;AAGjC,IAAAE,kBAA4D;AAG5D,IAAI;AAGJ,IAAI;AAOJ,IAAM,SAAS,IAAI,uCAAuB;AAa1C,IAAM,cAAc;AAAA,EAClB,MAAM,YAAiC;AACrC,QAAI,eAAe;AACjB,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAGA,UAAM,iBAAiB,MAAM,mBAAmB;AAChD,wBAAgB,qCAAoB,cAAc;AAGlD,WAAO;AAAA,MACL,cAAc,cAAc;AAAA,MAC5B,cAAc,cAAc;AAAA,MAC5B,WAAW,cAAc;AAAA,MACzB,SAAS,cAAc;AAAA,MACvB,UAAU,cAAc;AAAA,MACxB,iBAAiB,cAAc;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI,MAAM,sEAAsE;AAAA,IACxF;AAIA,WAAO,wBAAwB,QAAQ;AAGvC,kBAAc,SAAS,MAAM;AAG7B,eAAO,wBAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAA2C;AAG3E,uBAAqB;AAGrB,4BAAO,WAAW;AACpB;","names":["modelWorker","params","import_runtime"]}
@@ -0,0 +1,3 @@
1
+ export { spawnAsyncModelRunner } from './runner.cjs';
2
+ export { exposeModelWorker } from './worker.cjs';
3
+ import '@sdeverywhere/runtime';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/runner.ts
2
2
  import { BlobWorker, spawn, Thread, Transfer, Worker } from "threads";
3
- import { Outputs } from "@sdeverywhere/runtime";
3
+ import { BufferedRunModelParams, ModelListing, Outputs } from "@sdeverywhere/runtime";
4
4
  async function spawnAsyncModelRunner(workerSpec) {
5
5
  if (workerSpec["path"]) {
6
6
  return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec["path"]));
@@ -11,15 +11,15 @@ async function spawnAsyncModelRunner(workerSpec) {
11
11
  async function spawnAsyncModelRunnerWithWorker(worker) {
12
12
  const modelWorker2 = await spawn(worker);
13
13
  const initResult = await modelWorker2.initModel();
14
- let ioBuffer = initResult.ioBuffer;
15
- const rowLength = initResult.rowLength;
14
+ const modelListing = initResult.modelListing ? new ModelListing(initResult.modelListing) : void 0;
15
+ const params2 = new BufferedRunModelParams(modelListing);
16
16
  let running = false;
17
17
  let terminated = false;
18
18
  return {
19
19
  createOutputs: () => {
20
20
  return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq);
21
21
  },
22
- runModel: async (inputs, outputs) => {
22
+ runModel: async (inputs, outputs, options) => {
23
23
  if (terminated) {
24
24
  throw new Error("Async model runner has already been terminated");
25
25
  } else if (running) {
@@ -27,24 +27,15 @@ async function spawnAsyncModelRunnerWithWorker(worker) {
27
27
  } else {
28
28
  running = true;
29
29
  }
30
- const runTimeLengthInElements = 1;
31
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
32
- const inputsLengthInElements = inputs.length;
33
- const inputsLengthInBytes = inputsLengthInElements * 8;
34
- const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
35
- for (let i = 0; i < inputs.length; i++) {
36
- inputsArray[i] = inputs[i].get();
37
- }
30
+ params2.updateFromParams(inputs, outputs, options);
31
+ let ioBuffer;
38
32
  try {
39
- ioBuffer = await modelWorker2.runModel(Transfer(ioBuffer));
33
+ ioBuffer = await modelWorker2.runModel(Transfer(params2.getEncodedBuffer()));
40
34
  } finally {
41
35
  running = false;
42
36
  }
43
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
44
- outputs.runTimeInMillis = runTimeBufferArray[0];
45
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
46
- const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
47
- outputs.updateFromBuffer(outputsArray, rowLength);
37
+ params2.updateFromEncodedBuffer(ioBuffer);
38
+ params2.finalizeOutputs(outputs);
48
39
  return outputs;
49
40
  },
50
41
  terminate: () => {
@@ -60,59 +51,37 @@ async function spawnAsyncModelRunnerWithWorker(worker) {
60
51
 
61
52
  // src/worker.ts
62
53
  import { expose, Transfer as Transfer2 } from "threads/worker";
63
- import { perfElapsed, perfNow } from "@sdeverywhere/runtime";
64
- var initWasmModel;
65
- var wasmModel;
66
- var inputsWasmBuffer;
67
- var outputsWasmBuffer;
54
+ import { BufferedRunModelParams as BufferedRunModelParams2, createRunnableModel } from "@sdeverywhere/runtime";
55
+ var initGeneratedModel;
56
+ var runnableModel;
57
+ var params = new BufferedRunModelParams2();
68
58
  var modelWorker = {
69
59
  async initModel() {
70
- if (wasmModel) {
71
- throw new Error("WasmModel was already initialized");
60
+ if (runnableModel) {
61
+ throw new Error("RunnableModel was already initialized");
72
62
  }
73
- const wasmResult = await initWasmModel();
74
- wasmModel = wasmResult.model;
75
- inputsWasmBuffer = wasmResult.inputsBuffer;
76
- outputsWasmBuffer = wasmResult.outputsBuffer;
77
- const runTimeLength = 8;
78
- const inputsLength = inputsWasmBuffer.getArrayView().length;
79
- const outputsLength = outputsWasmBuffer.getArrayView().length;
80
- const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength);
81
- const ioBuffer = ioArray.buffer;
82
- const initResult = {
83
- outputVarIds: wasmResult.outputVarIds,
84
- startTime: wasmModel.startTime,
85
- endTime: wasmModel.endTime,
86
- saveFreq: wasmModel.saveFreq,
87
- rowLength: wasmModel.numSavePoints,
88
- ioBuffer
63
+ const generatedModel = await initGeneratedModel();
64
+ runnableModel = createRunnableModel(generatedModel);
65
+ return {
66
+ outputVarIds: runnableModel.outputVarIds,
67
+ modelListing: runnableModel.modelListing,
68
+ startTime: runnableModel.startTime,
69
+ endTime: runnableModel.endTime,
70
+ saveFreq: runnableModel.saveFreq,
71
+ outputRowLength: runnableModel.numSavePoints
89
72
  };
90
- return Transfer2(initResult, [ioBuffer]);
91
73
  },
92
74
  runModel(ioBuffer) {
93
- if (!wasmModel) {
94
- throw new Error("WasmModel must be initialized before running the model in worker");
75
+ if (!runnableModel) {
76
+ throw new Error("RunnableModel must be initialized before running the model in worker");
95
77
  }
96
- const runTimeLengthInElements = 1;
97
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
98
- const inputsWasmArray = inputsWasmBuffer.getArrayView();
99
- const inputsLengthInElements = inputsWasmArray.length;
100
- const inputsLengthInBytes = inputsLengthInElements * 8;
101
- const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
102
- inputsWasmArray.set(inputsBufferArray);
103
- const t0 = perfNow();
104
- wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer);
105
- const elapsed = perfElapsed(t0);
106
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
107
- runTimeBufferArray[0] = elapsed;
108
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
109
- const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
110
- outputsBufferArray.set(outputsWasmBuffer.getArrayView());
78
+ params.updateFromEncodedBuffer(ioBuffer);
79
+ runnableModel.runModel(params);
111
80
  return Transfer2(ioBuffer);
112
81
  }
113
82
  };
114
83
  function exposeModelWorker(init) {
115
- initWasmModel = init;
84
+ initGeneratedModel = init;
116
85
  expose(modelWorker);
117
86
  }
118
87
  export {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runner.ts","../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker thread.\n *\n * In your app project, define a JavaScript file, called `worker.js` for example, that\n * initializes the model worker in the context of the Web Worker:\n *\n * ```js\n * import { initWasmModelAndBuffers } from '@sdeverywhere/runtime'\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n *\n * async function initWasmModel() {\n * const wasmModules = loadWasm()\n * return initWasmModelAndBuffers(...)\n * }\n *\n * exposeModelWorker(initWasmModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the Web Worker and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n let ioBuffer: ArrayBuffer = initResult.ioBuffer\n\n // The row length is the number of elements in each row of the outputs buffer\n const rowLength = initResult.rowLength\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Capture the current set of input values into the reusable buffer\n const inputsLengthInElements = inputs.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n for (let i = 0; i < inputs.length; i++) {\n inputsArray[i] = inputs[i].get()\n }\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n try {\n ioBuffer = await modelWorker.runModel(Transfer(ioBuffer))\n } finally {\n running = false\n }\n\n // Save the model run time\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n outputs.runTimeInMillis = runTimeBufferArray[0]\n\n // Capture the outputs array by copying the data into the given `Outputs`\n // data structure\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputs.updateFromBuffer(outputsArray, rowLength)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n","// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { WasmBuffer, WasmModel, WasmModelInitResult } from '@sdeverywhere/runtime'\nimport { perfElapsed, perfNow } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initWasmModel: () => Promise<WasmModelInitResult>\n/** @hidden */\nlet wasmModel: WasmModel\n/** @hidden */\nlet inputsWasmBuffer: WasmBuffer\n/** @hidden */\nlet outputsWasmBuffer: WasmBuffer\n\ninterface InitResult {\n outputVarIds: string[]\n startTime: number\n endTime: number\n saveFreq: number\n rowLength: number\n ioBuffer: ArrayBuffer\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<TransferDescriptor<InitResult>> {\n if (wasmModel) {\n throw new Error('WasmModel was already initialized')\n }\n\n // Initialize the wasm model and associated buffers\n const wasmResult = await initWasmModel()\n\n // Capture the `WasmModel` instance and `WasmBuffer` instances\n wasmModel = wasmResult.model\n inputsWasmBuffer = wasmResult.inputsBuffer\n outputsWasmBuffer = wasmResult.outputsBuffer\n\n // Create a combined array that will hold a copy of the inputs and outputs\n // wasm buffers; this buffer is no-copy transferable, whereas the wasm ones\n // are not allowed to be transferred\n const runTimeLength = 8\n const inputsLength = inputsWasmBuffer.getArrayView().length\n const outputsLength = outputsWasmBuffer.getArrayView().length\n const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength)\n\n // Transfer the underlying buffer to the runner\n const ioBuffer = ioArray.buffer\n const initResult: InitResult = {\n outputVarIds: wasmResult.outputVarIds,\n startTime: wasmModel.startTime,\n endTime: wasmModel.endTime,\n saveFreq: wasmModel.saveFreq,\n rowLength: wasmModel.numSavePoints,\n ioBuffer\n }\n return Transfer(initResult, [ioBuffer])\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!wasmModel) {\n throw new Error('WasmModel must be initialized before running the model in worker')\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Copy the inputs into the wasm inputs buffer\n const inputsWasmArray = inputsWasmBuffer.getArrayView()\n const inputsLengthInElements = inputsWasmArray.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n inputsWasmArray.set(inputsBufferArray)\n\n // Run the model using the wasm buffers\n const t0 = perfNow()\n wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer)\n const elapsed = perfElapsed(t0)\n\n // Write the model run time to the buffer\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n runTimeBufferArray[0] = elapsed\n\n // Copy the outputs from the wasm outputs buffer\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputsBufferArray.set(outputsWasmBuffer.getArrayView())\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the `WasmModel` on the worker thread\n * and sending the outputs back to the main process.\n *\n * @param init The function that initializes the `WasmModel` instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<WasmModelInitResult>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initWasmModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";AAEA,SAAS,YAAY,OAAO,QAAQ,UAAU,cAAc;AAG5D,SAAS,eAAe;AAqCxB,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,SAAS;AACtB,WAAO,gCAAgC,IAAI,OAAO,WAAW,OAAO,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,WAAW,SAAS,WAAW,SAAS,CAAC;AAAA,EAClF;AACF;AAKA,eAAe,gCAAgC,QAAsC;AAEnF,QAAMA,eAAc,MAAM,MAAM,MAAM;AAGtC,QAAM,aAAa,MAAMA,aAAY,UAAU;AAC/C,MAAI,WAAwB,WAAW;AAGvC,QAAM,YAAY,WAAW;AAG7B,MAAI,UAAU;AAGd,MAAI,aAAa;AAEjB,SAAO;AAAA,IACL,eAAe,MAAM;AACnB,aAAO,IAAI,QAAQ,WAAW,cAAc,WAAW,WAAW,WAAW,SAAS,WAAW,QAAQ;AAAA,IAC3G;AAAA,IAEA,UAAU,OAAO,QAAQ,YAAY;AACnC,UAAI,YAAY;AACd,cAAM,IAAI,MAAM,gDAAgD;AAAA,MAClE,WAAW,SAAS;AAClB,cAAM,IAAI,MAAM,gEAAgE;AAAA,MAClF,OAAO;AACL,kBAAU;AAAA,MACZ;AAGA,YAAM,0BAA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,aAAyB;AAAA,MAC7B,cAAc,WAAW;AAAA,MACzB,WAAW,UAAU;AAAA,MACrB,SAAS,UAAU;AAAA,MACnB,UAAU,UAAU;AAAA,MACpB,WAAW,UAAU;AAAA,MACrB;AAAA,IACF;AACA,WAAOA,UAAS,YAAY,CAAC,QAAQ,CAAC;AAAA,EACxC;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AAGA,UAAM,0BAA0B;AAChC,UAAM,uBAAuB,0BAA0B;AAGvD,UAAM,kBAAkB,iBAAiB,aAAa;AACtD,UAAM,yBAAyB,gBAAgB;AAC/C,UAAM,sBAAsB,yBAAyB;AACrD,UAAM,oBAAoB,IAAI,aAAa,UAAU,sBAAsB,sBAAsB;AACjG,oBAAgB,IAAI,iBAAiB;AAGrC,UAAM,KAAK,QAAQ;AACnB,cAAU,SAAS,kBAAkB,iBAAiB;AACtD,UAAM,UAAU,YAAY,EAAE;AAG9B,UAAM,qBAAqB,IAAI,aAAa,UAAU,GAAG,uBAAuB;AAChF,uBAAmB,KAAK;AAGxB,UAAM,uBAAuB,uBAAuB;AACpD,UAAM,qBAAqB,IAAI,aAAa,UAAU,oBAAoB;AAC1E,uBAAmB,IAAI,kBAAkB,aAAa,CAAC;AAGvD,WAAOA,UAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAAgD;AAGhF,kBAAgB;AAGhB,SAAO,WAAW;AACpB;","names":["modelWorker","Transfer"]}
1
+ {"version":3,"sources":["../src/runner.ts","../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, ModelListing, Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker\n * (a Web Worker when running in a browser environment, or a worker thread\n * when running in a Node.js environment).\n *\n * In your app project, define a JavaScript file, called `worker.js` for example,\n * that initializes the generated model in the context of a worker thread:\n *\n * ```js\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n * import loadGeneratedModel from './sde-prep/generated-model.js'\n *\n * exposeModelWorker(loadGeneratedModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the worker thread and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n\n // Create a `ModelListing` instance if the listing was defined in the generated model\n const modelListing = initResult.modelListing ? new ModelListing(initResult.modelListing) : undefined\n\n // Maintain a `BufferedRunModelParams` instance that holds the I/O parameters\n const params = new BufferedRunModelParams(modelListing)\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs, options) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // Update the I/O parameters\n params.updateFromParams(inputs, outputs, options)\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n let ioBuffer: ArrayBuffer\n try {\n ioBuffer = await modelWorker.runModel(Transfer(params.getEncodedBuffer()))\n } finally {\n running = false\n }\n\n // Once the buffer is transferred to the worker, the buffer in the\n // `BufferedRunModelParams` becomes \"detached\" and is no longer usable.\n // After the buffer is transferred back from the worker, we need to\n // restore the state of the object to use the new buffer.\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Copy the output values and elapsed time from the buffer to the\n // `Outputs` instance\n params.finalizeOutputs(outputs)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n","// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { GeneratedModel, RunnableModel } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, createRunnableModel } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initGeneratedModel: () => Promise<GeneratedModel>\n\n/** @hidden */\nlet runnableModel: RunnableModel\n\n/**\n * Maintain a `BufferedRunModelParams` instance that wraps the transferable buffer\n * containing the I/O parameters.\n * @hidden\n */\nconst params = new BufferedRunModelParams()\n\ninterface InitResult {\n outputVarIds: string[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelListing?: /*ModelListingSpecs*/ any\n startTime: number\n endTime: number\n saveFreq: number\n outputRowLength: number\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<InitResult> {\n if (runnableModel) {\n throw new Error('RunnableModel was already initialized')\n }\n\n // Initialize the runnable model\n const generatedModel = await initGeneratedModel()\n runnableModel = createRunnableModel(generatedModel)\n\n // Transfer the model metadata to the runner\n return {\n outputVarIds: runnableModel.outputVarIds,\n modelListing: runnableModel.modelListing,\n startTime: runnableModel.startTime,\n endTime: runnableModel.endTime,\n saveFreq: runnableModel.saveFreq,\n outputRowLength: runnableModel.numSavePoints\n }\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!runnableModel) {\n throw new Error('RunnableModel must be initialized before running the model in worker')\n }\n\n // Update the `BufferedRunModelParams` to use the values in the buffer that was transferred\n // from the runner to the worker\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Run the model synchronously on the worker thread using those I/O parameters\n runnableModel.runModel(params)\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the model on the worker thread and\n * sending the outputs back to the main thread.\n *\n * @param init The function that initializes the generated model instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<GeneratedModel>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initGeneratedModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";AAEA,SAAS,YAAY,OAAO,QAAQ,UAAU,cAAc;AAG5D,SAAS,wBAAwB,cAAc,eAAe;AAkC9D,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,MAAM,GAAG;AACtB,WAAO,gCAAgC,IAAI,OAAO,WAAW,MAAM,CAAC,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,WAAW,SAAS,WAAW,QAAQ,CAAC,CAAC;AAAA,EAClF;AACF;AAKA,eAAe,gCAAgC,QAAsC;AAEnF,QAAMA,eAAc,MAAM,MAAM,MAAM;AAGtC,QAAM,aAAa,MAAMA,aAAY,UAAU;AAG/C,QAAM,eAAe,WAAW,eAAe,IAAI,aAAa,WAAW,YAAY,IAAI;AAG3F,QAAMC,UAAS,IAA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A,MACvB,UAAU,cAAc;AAAA,MACxB,iBAAiB,cAAc;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI,MAAM,sEAAsE;AAAA,IACxF;AAIA,WAAO,wBAAwB,QAAQ;AAGvC,kBAAc,SAAS,MAAM;AAG7B,WAAOD,UAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAA2C;AAG3E,uBAAqB;AAGrB,SAAO,WAAW;AACpB;","names":["modelWorker","params","Transfer","BufferedRunModelParams"]}
package/dist/runner.cjs CHANGED
@@ -34,15 +34,15 @@ async function spawnAsyncModelRunner(workerSpec) {
34
34
  async function spawnAsyncModelRunnerWithWorker(worker) {
35
35
  const modelWorker = await (0, import_threads.spawn)(worker);
36
36
  const initResult = await modelWorker.initModel();
37
- let ioBuffer = initResult.ioBuffer;
38
- const rowLength = initResult.rowLength;
37
+ const modelListing = initResult.modelListing ? new import_runtime.ModelListing(initResult.modelListing) : void 0;
38
+ const params = new import_runtime.BufferedRunModelParams(modelListing);
39
39
  let running = false;
40
40
  let terminated = false;
41
41
  return {
42
42
  createOutputs: () => {
43
43
  return new import_runtime.Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq);
44
44
  },
45
- runModel: async (inputs, outputs) => {
45
+ runModel: async (inputs, outputs, options) => {
46
46
  if (terminated) {
47
47
  throw new Error("Async model runner has already been terminated");
48
48
  } else if (running) {
@@ -50,24 +50,15 @@ async function spawnAsyncModelRunnerWithWorker(worker) {
50
50
  } else {
51
51
  running = true;
52
52
  }
53
- const runTimeLengthInElements = 1;
54
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
55
- const inputsLengthInElements = inputs.length;
56
- const inputsLengthInBytes = inputsLengthInElements * 8;
57
- const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
58
- for (let i = 0; i < inputs.length; i++) {
59
- inputsArray[i] = inputs[i].get();
60
- }
53
+ params.updateFromParams(inputs, outputs, options);
54
+ let ioBuffer;
61
55
  try {
62
- ioBuffer = await modelWorker.runModel((0, import_threads.Transfer)(ioBuffer));
56
+ ioBuffer = await modelWorker.runModel((0, import_threads.Transfer)(params.getEncodedBuffer()));
63
57
  } finally {
64
58
  running = false;
65
59
  }
66
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
67
- outputs.runTimeInMillis = runTimeBufferArray[0];
68
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
69
- const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
70
- outputs.updateFromBuffer(outputsArray, rowLength);
60
+ params.updateFromEncodedBuffer(ioBuffer);
61
+ params.finalizeOutputs(outputs);
71
62
  return outputs;
72
63
  },
73
64
  terminate: () => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runner.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker thread.\n *\n * In your app project, define a JavaScript file, called `worker.js` for example, that\n * initializes the model worker in the context of the Web Worker:\n *\n * ```js\n * import { initWasmModelAndBuffers } from '@sdeverywhere/runtime'\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n *\n * async function initWasmModel() {\n * const wasmModules = loadWasm()\n * return initWasmModelAndBuffers(...)\n * }\n *\n * exposeModelWorker(initWasmModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the Web Worker and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n let ioBuffer: ArrayBuffer = initResult.ioBuffer\n\n // The row length is the number of elements in each row of the outputs buffer\n const rowLength = initResult.rowLength\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Capture the current set of input values into the reusable buffer\n const inputsLengthInElements = inputs.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n for (let i = 0; i < inputs.length; i++) {\n inputsArray[i] = inputs[i].get()\n }\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n try {\n ioBuffer = await modelWorker.runModel(Transfer(ioBuffer))\n } finally {\n running = false\n }\n\n // Save the model run time\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n outputs.runTimeInMillis = runTimeBufferArray[0]\n\n // Capture the outputs array by copying the data into the given `Outputs`\n // data structure\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputs.updateFromBuffer(outputsArray, rowLength)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAA4D;AAG5D,qBAAwB;AAqCxB,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,SAAS;AACtB,WAAO,gCAAgC,IAAI,sBAAO,WAAW,OAAO,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,0BAAW,SAAS,WAAW,SAAS,CAAC;AAAA,EAClF;AACF;AAKA,eAAe,gCAAgC,QAAsC;AAEnF,QAAM,cAAc,UAAM,sBAAM,MAAM;AAGtC,QAAM,aAAa,MAAM,YAAY,UAAU;AAC/C,MAAI,WAAwB,WAAW;AAGvC,QAAM,YAAY,WAAW;AAG7B,MAAI,UAAU;AAGd,MAAI,aAAa;AAEjB,SAAO;AAAA,IACL,eAAe,MAAM;AACnB,aAAO,IAAI,uBAAQ,WAAW,cAAc,WAAW,WAAW,WAAW,SAAS,WAAW,QAAQ;AAAA,IAC3G;AAAA,IAEA,UAAU,OAAO,QAAQ,YAAY;AACnC,UAAI,YAAY;AACd,cAAM,IAAI,MAAM,gDAAgD;AAAA,MAClE,WAAW,SAAS;AAClB,cAAM,IAAI,MAAM,gEAAgE;AAAA,MAClF,OAAO;AACL,kBAAU;AAAA,MACZ;AAGA,YAAM,0BAA0B;AAChC,YAAM,uBAAuB,0BAA0B;AAGvD,YAAM,yBAAyB,OAAO;AACtC,YAAM,sBAAsB,yBAAyB;AACrD,YAAM,cAAc,IAAI,aAAa,UAAU,sBAAsB,sBAAsB;AAC3F,eAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,oBAAY,KAAK,OAAO,GAAG,IAAI;AAAA,MACjC;AAMA,UAAI;AACF,mBAAW,MAAM,YAAY,aAAS,yBAAS,QAAQ,CAAC;AAAA,MAC1D,UAAE;AACA,kBAAU;AAAA,MACZ;AAGA,YAAM,qBAAqB,IAAI,aAAa,UAAU,GAAG,uBAAuB;AAChF,cAAQ,kBAAkB,mBAAmB;AAI7C,YAAM,uBAAuB,uBAAuB;AACpD,YAAM,eAAe,IAAI,aAAa,UAAU,oBAAoB;AACpE,cAAQ,iBAAiB,cAAc,SAAS;AAEhD,aAAO;AAAA,IACT;AAAA,IAEA,WAAW,MAAM;AACf,UAAI,YAAY;AACd,eAAO,QAAQ,QAAQ;AAAA,MACzB,OAAO;AACL,qBAAa;AACb,eAAO,sBAAO,UAAU,WAAW;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/runner.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, ModelListing, Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker\n * (a Web Worker when running in a browser environment, or a worker thread\n * when running in a Node.js environment).\n *\n * In your app project, define a JavaScript file, called `worker.js` for example,\n * that initializes the generated model in the context of a worker thread:\n *\n * ```js\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n * import loadGeneratedModel from './sde-prep/generated-model.js'\n *\n * exposeModelWorker(loadGeneratedModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the worker thread and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n\n // Create a `ModelListing` instance if the listing was defined in the generated model\n const modelListing = initResult.modelListing ? new ModelListing(initResult.modelListing) : undefined\n\n // Maintain a `BufferedRunModelParams` instance that holds the I/O parameters\n const params = new BufferedRunModelParams(modelListing)\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs, options) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // Update the I/O parameters\n params.updateFromParams(inputs, outputs, options)\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n let ioBuffer: ArrayBuffer\n try {\n ioBuffer = await modelWorker.runModel(Transfer(params.getEncodedBuffer()))\n } finally {\n running = false\n }\n\n // Once the buffer is transferred to the worker, the buffer in the\n // `BufferedRunModelParams` becomes \"detached\" and is no longer usable.\n // After the buffer is transferred back from the worker, we need to\n // restore the state of the object to use the new buffer.\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Copy the output values and elapsed time from the buffer to the\n // `Outputs` instance\n params.finalizeOutputs(outputs)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,qBAA4D;AAG5D,qBAA8D;AAkC9D,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,MAAM,GAAG;AACtB,WAAO,gCAAgC,IAAI,sBAAO,WAAW,MAAM,CAAC,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,0BAAW,SAAS,WAAW,QAAQ,CAAC,CAAC;AAAA,EAClF;AACF;AAKA,eAAe,gCAAgC,QAAsC;AAEnF,QAAM,cAAc,UAAM,sBAAM,MAAM;AAGtC,QAAM,aAAa,MAAM,YAAY,UAAU;AAG/C,QAAM,eAAe,WAAW,eAAe,IAAI,4BAAa,WAAW,YAAY,IAAI;AAG3F,QAAM,SAAS,IAAI,sCAAuB,YAAY;AAGtD,MAAI,UAAU;AAGd,MAAI,aAAa;AAEjB,SAAO;AAAA,IACL,eAAe,MAAM;AACnB,aAAO,IAAI,uBAAQ,WAAW,cAAc,WAAW,WAAW,WAAW,SAAS,WAAW,QAAQ;AAAA,IAC3G;AAAA,IAEA,UAAU,OAAO,QAAQ,SAAS,YAAY;AAC5C,UAAI,YAAY;AACd,cAAM,IAAI,MAAM,gDAAgD;AAAA,MAClE,WAAW,SAAS;AAClB,cAAM,IAAI,MAAM,gEAAgE;AAAA,MAClF,OAAO;AACL,kBAAU;AAAA,MACZ;AAGA,aAAO,iBAAiB,QAAQ,SAAS,OAAO;AAMhD,UAAI;AACJ,UAAI;AACF,mBAAW,MAAM,YAAY,aAAS,yBAAS,OAAO,iBAAiB,CAAC,CAAC;AAAA,MAC3E,UAAE;AACA,kBAAU;AAAA,MACZ;AAMA,aAAO,wBAAwB,QAAQ;AAIvC,aAAO,gBAAgB,OAAO;AAE9B,aAAO;AAAA,IACT;AAAA,IAEA,WAAW,MAAM;AACf,UAAI,YAAY;AACd,eAAO,QAAQ,QAAQ;AAAA,MACzB,OAAO;AACL,qBAAa;AACb,eAAO,sBAAO,UAAU,WAAW;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,41 @@
1
+ import { ModelRunner } from '@sdeverywhere/runtime';
2
+
3
+ /**
4
+ * Initialize a `ModelRunner` that runs the model asynchronously in a worker
5
+ * (a Web Worker when running in a browser environment, or a worker thread
6
+ * when running in a Node.js environment).
7
+ *
8
+ * In your app project, define a JavaScript file, called `worker.js` for example,
9
+ * that initializes the generated model in the context of a worker thread:
10
+ *
11
+ * ```js
12
+ * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'
13
+ * import loadGeneratedModel from './sde-prep/generated-model.js'
14
+ *
15
+ * exposeModelWorker(loadGeneratedModel)
16
+ * ```
17
+ *
18
+ * Then, in your web app, call the `spawnAsyncModelRunner` function, which
19
+ * will spawn the worker thread and initialize the `ModelRunner` that communicates
20
+ * with the worker:
21
+ *
22
+ * ```js
23
+ * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'
24
+ *
25
+ * async function initApp() {
26
+ * // ...
27
+ * const runner = await spawnAsyncModelRunner({ path: './worker.js' })
28
+ * // ...
29
+ * }
30
+ * ```
31
+ *
32
+ * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`
33
+ * containing the full JavaScript source of the worker.
34
+ */
35
+ declare function spawnAsyncModelRunner(workerSpec: {
36
+ path: string;
37
+ } | {
38
+ source: string;
39
+ }): Promise<ModelRunner>;
40
+
41
+ export { spawnAsyncModelRunner };
package/dist/runner.d.ts CHANGED
@@ -1,25 +1,22 @@
1
1
  import { ModelRunner } from '@sdeverywhere/runtime';
2
2
 
3
3
  /**
4
- * Initialize a `ModelRunner` that runs the model asynchronously in a worker thread.
4
+ * Initialize a `ModelRunner` that runs the model asynchronously in a worker
5
+ * (a Web Worker when running in a browser environment, or a worker thread
6
+ * when running in a Node.js environment).
5
7
  *
6
- * In your app project, define a JavaScript file, called `worker.js` for example, that
7
- * initializes the model worker in the context of the Web Worker:
8
+ * In your app project, define a JavaScript file, called `worker.js` for example,
9
+ * that initializes the generated model in the context of a worker thread:
8
10
  *
9
11
  * ```js
10
- * import { initWasmModelAndBuffers } from '@sdeverywhere/runtime'
11
12
  * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'
13
+ * import loadGeneratedModel from './sde-prep/generated-model.js'
12
14
  *
13
- * async function initWasmModel() {
14
- * const wasmModules = loadWasm()
15
- * return initWasmModelAndBuffers(...)
16
- * }
17
- *
18
- * exposeModelWorker(initWasmModel)
15
+ * exposeModelWorker(loadGeneratedModel)
19
16
  * ```
20
17
  *
21
18
  * Then, in your web app, call the `spawnAsyncModelRunner` function, which
22
- * will spawn the Web Worker and initialize the `ModelRunner` that communicates
19
+ * will spawn the worker thread and initialize the `ModelRunner` that communicates
23
20
  * with the worker:
24
21
  *
25
22
  * ```js
package/dist/runner.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/runner.ts
2
2
  import { BlobWorker, spawn, Thread, Transfer, Worker } from "threads";
3
- import { Outputs } from "@sdeverywhere/runtime";
3
+ import { BufferedRunModelParams, ModelListing, Outputs } from "@sdeverywhere/runtime";
4
4
  async function spawnAsyncModelRunner(workerSpec) {
5
5
  if (workerSpec["path"]) {
6
6
  return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec["path"]));
@@ -11,15 +11,15 @@ async function spawnAsyncModelRunner(workerSpec) {
11
11
  async function spawnAsyncModelRunnerWithWorker(worker) {
12
12
  const modelWorker = await spawn(worker);
13
13
  const initResult = await modelWorker.initModel();
14
- let ioBuffer = initResult.ioBuffer;
15
- const rowLength = initResult.rowLength;
14
+ const modelListing = initResult.modelListing ? new ModelListing(initResult.modelListing) : void 0;
15
+ const params = new BufferedRunModelParams(modelListing);
16
16
  let running = false;
17
17
  let terminated = false;
18
18
  return {
19
19
  createOutputs: () => {
20
20
  return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq);
21
21
  },
22
- runModel: async (inputs, outputs) => {
22
+ runModel: async (inputs, outputs, options) => {
23
23
  if (terminated) {
24
24
  throw new Error("Async model runner has already been terminated");
25
25
  } else if (running) {
@@ -27,24 +27,15 @@ async function spawnAsyncModelRunnerWithWorker(worker) {
27
27
  } else {
28
28
  running = true;
29
29
  }
30
- const runTimeLengthInElements = 1;
31
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
32
- const inputsLengthInElements = inputs.length;
33
- const inputsLengthInBytes = inputsLengthInElements * 8;
34
- const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
35
- for (let i = 0; i < inputs.length; i++) {
36
- inputsArray[i] = inputs[i].get();
37
- }
30
+ params.updateFromParams(inputs, outputs, options);
31
+ let ioBuffer;
38
32
  try {
39
- ioBuffer = await modelWorker.runModel(Transfer(ioBuffer));
33
+ ioBuffer = await modelWorker.runModel(Transfer(params.getEncodedBuffer()));
40
34
  } finally {
41
35
  running = false;
42
36
  }
43
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
44
- outputs.runTimeInMillis = runTimeBufferArray[0];
45
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
46
- const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
47
- outputs.updateFromBuffer(outputsArray, rowLength);
37
+ params.updateFromEncodedBuffer(ioBuffer);
38
+ params.finalizeOutputs(outputs);
48
39
  return outputs;
49
40
  },
50
41
  terminate: () => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runner.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker thread.\n *\n * In your app project, define a JavaScript file, called `worker.js` for example, that\n * initializes the model worker in the context of the Web Worker:\n *\n * ```js\n * import { initWasmModelAndBuffers } from '@sdeverywhere/runtime'\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n *\n * async function initWasmModel() {\n * const wasmModules = loadWasm()\n * return initWasmModelAndBuffers(...)\n * }\n *\n * exposeModelWorker(initWasmModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the Web Worker and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n let ioBuffer: ArrayBuffer = initResult.ioBuffer\n\n // The row length is the number of elements in each row of the outputs buffer\n const rowLength = initResult.rowLength\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Capture the current set of input values into the reusable buffer\n const inputsLengthInElements = inputs.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n for (let i = 0; i < inputs.length; i++) {\n inputsArray[i] = inputs[i].get()\n }\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n try {\n ioBuffer = await modelWorker.runModel(Transfer(ioBuffer))\n } finally {\n running = false\n }\n\n // Save the model run time\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n outputs.runTimeInMillis = runTimeBufferArray[0]\n\n // Capture the outputs array by copying the data into the given `Outputs`\n // data structure\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputs.updateFromBuffer(outputsArray, rowLength)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n"],"mappings":";AAEA,SAAS,YAAY,OAAO,QAAQ,UAAU,cAAc;AAG5D,SAAS,eAAe;AAqCxB,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,SAAS;AACtB,WAAO,gCAAgC,IAAI,OAAO,WAAW,OAAO,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,WAAW,SAAS,WAAW,SAAS,CAAC;AAAA,EAClF;AACF;AAKA,eAAe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","names":[]}
1
+ {"version":3,"sources":["../src/runner.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport { BlobWorker, spawn, Thread, Transfer, Worker } from 'threads'\n\nimport type { ModelRunner } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, ModelListing, Outputs } from '@sdeverywhere/runtime'\n\n/**\n * Initialize a `ModelRunner` that runs the model asynchronously in a worker\n * (a Web Worker when running in a browser environment, or a worker thread\n * when running in a Node.js environment).\n *\n * In your app project, define a JavaScript file, called `worker.js` for example,\n * that initializes the generated model in the context of a worker thread:\n *\n * ```js\n * import { exposeModelWorker } from '@sdeverywhere/runtime-async/worker'\n * import loadGeneratedModel from './sde-prep/generated-model.js'\n *\n * exposeModelWorker(loadGeneratedModel)\n * ```\n *\n * Then, in your web app, call the `spawnAsyncModelRunner` function, which\n * will spawn the worker thread and initialize the `ModelRunner` that communicates\n * with the worker:\n *\n * ```js\n * import { spawnAsyncModelRunner } from '@sdeverywhere/runtime-async/runner'\n *\n * async function initApp() {\n * // ...\n * const runner = await spawnAsyncModelRunner({ path: './worker.js' })\n * // ...\n * }\n * ```\n *\n * @param workerSpec Either a `path` to the worker JavaScript file, or the `source`\n * containing the full JavaScript source of the worker.\n */\nexport async function spawnAsyncModelRunner(workerSpec: { path: string } | { source: string }): Promise<ModelRunner> {\n if (workerSpec['path']) {\n return spawnAsyncModelRunnerWithWorker(new Worker(workerSpec['path']))\n } else {\n return spawnAsyncModelRunnerWithWorker(BlobWorker.fromText(workerSpec['source']))\n }\n}\n\n/**\n * @hidden For internal use only\n */\nasync function spawnAsyncModelRunnerWithWorker(worker: Worker): Promise<ModelRunner> {\n // Spawn the given Worker that contains the `ModelWorker`\n const modelWorker = await spawn(worker)\n\n // Wait for the worker to initialize the wasm model (in the worker thread)\n const initResult = await modelWorker.initModel()\n\n // Create a `ModelListing` instance if the listing was defined in the generated model\n const modelListing = initResult.modelListing ? new ModelListing(initResult.modelListing) : undefined\n\n // Maintain a `BufferedRunModelParams` instance that holds the I/O parameters\n const params = new BufferedRunModelParams(modelListing)\n\n // Use a flag to ensure that only one request is made at a time\n let running = false\n\n // Disallow `runModel` after the runner has been terminated\n let terminated = false\n\n return {\n createOutputs: () => {\n return new Outputs(initResult.outputVarIds, initResult.startTime, initResult.endTime, initResult.saveFreq)\n },\n\n runModel: async (inputs, outputs, options) => {\n if (terminated) {\n throw new Error('Async model runner has already been terminated')\n } else if (running) {\n throw new Error('Async model runner only supports one `runModel` call at a time')\n } else {\n running = true\n }\n\n // Update the I/O parameters\n params.updateFromParams(inputs, outputs, options)\n\n // Run the model in the worker. We pass the underlying `ArrayBuffer`\n // instance back to the worker wrapped in a `Transfer` to make it\n // no-copy transferable, and then the worker will return it back\n // to us.\n let ioBuffer: ArrayBuffer\n try {\n ioBuffer = await modelWorker.runModel(Transfer(params.getEncodedBuffer()))\n } finally {\n running = false\n }\n\n // Once the buffer is transferred to the worker, the buffer in the\n // `BufferedRunModelParams` becomes \"detached\" and is no longer usable.\n // After the buffer is transferred back from the worker, we need to\n // restore the state of the object to use the new buffer.\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Copy the output values and elapsed time from the buffer to the\n // `Outputs` instance\n params.finalizeOutputs(outputs)\n\n return outputs\n },\n\n terminate: () => {\n if (terminated) {\n return Promise.resolve()\n } else {\n terminated = true\n return Thread.terminate(modelWorker)\n }\n }\n }\n}\n"],"mappings":";AAEA,SAAS,YAAY,OAAO,QAAQ,UAAU,cAAc;AAG5D,SAAS,wBAAwB,cAAc,eAAe;AAkC9D,eAAsB,sBAAsB,YAAyE;AACnH,MAAI,WAAW,MAAM,GAAG;AACtB,WAAO,gCAAgC,IAAI,OAAO,WAAW,MAAM,CAAC,CAAC;AAAA,EACvE,OAAO;AACL,WAAO,gCAAgC,WAAW,SAAS,WAAW,QAAQ,CAAC,CAAC;AAAA,EAClF;AACF;AAKA,eAAe,gCAAgC,QAAsC;AAEnF,QAAM,cAAc,MAAM,MAAM,MAAM;AAGtC,QAAM,aAAa,MAAM,YAAY,UAAU;AAG/C,QAAM,eAAe,WAAW,eAAe,IAAI,aAAa,WAAW,YAAY,IAAI;AAG3F,QAAM,SAAS,IAAI,uBAAuB,YAAY;AAGtD,MAAI,UAAU;AAGd,MAAI,aAAa;AAEjB,SAAO;AAAA,IACL,eAAe,MAAM;AACnB,aAAO,IAAI,QAAQ,WAAW,cAAc,WAAW,WAAW,WAAW,SAAS,WAAW,QAAQ;AAAA,IAC3G;AAAA,IAEA,UAAU,OAAO,QAAQ,SAAS,YAAY;AAC5C,UAAI,YAAY;AACd,cAAM,IAAI,MAAM,gDAAgD;AAAA,MAClE,WAAW,SAAS;AAClB,cAAM,IAAI,MAAM,gEAAgE;AAAA,MAClF,OAAO;AACL,kBAAU;AAAA,MACZ;AAGA,aAAO,iBAAiB,QAAQ,SAAS,OAAO;AAMhD,UAAI;AACJ,UAAI;AACF,mBAAW,MAAM,YAAY,SAAS,SAAS,OAAO,iBAAiB,CAAC,CAAC;AAAA,MAC3E,UAAE;AACA,kBAAU;AAAA,MACZ;AAMA,aAAO,wBAAwB,QAAQ;AAIvC,aAAO,gBAAgB,OAAO;AAE9B,aAAO;AAAA,IACT;AAAA,IAEA,WAAW,MAAM;AACf,UAAI,YAAY;AACd,eAAO,QAAQ,QAAQ;AAAA,MACzB,OAAO;AACL,qBAAa;AACb,eAAO,OAAO,UAAU,WAAW;AAAA,MACrC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/dist/worker.cjs CHANGED
@@ -24,58 +24,36 @@ __export(worker_exports, {
24
24
  module.exports = __toCommonJS(worker_exports);
25
25
  var import_worker = require("threads/worker");
26
26
  var import_runtime = require("@sdeverywhere/runtime");
27
- var initWasmModel;
28
- var wasmModel;
29
- var inputsWasmBuffer;
30
- var outputsWasmBuffer;
27
+ var initGeneratedModel;
28
+ var runnableModel;
29
+ var params = new import_runtime.BufferedRunModelParams();
31
30
  var modelWorker = {
32
31
  async initModel() {
33
- if (wasmModel) {
34
- throw new Error("WasmModel was already initialized");
32
+ if (runnableModel) {
33
+ throw new Error("RunnableModel was already initialized");
35
34
  }
36
- const wasmResult = await initWasmModel();
37
- wasmModel = wasmResult.model;
38
- inputsWasmBuffer = wasmResult.inputsBuffer;
39
- outputsWasmBuffer = wasmResult.outputsBuffer;
40
- const runTimeLength = 8;
41
- const inputsLength = inputsWasmBuffer.getArrayView().length;
42
- const outputsLength = outputsWasmBuffer.getArrayView().length;
43
- const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength);
44
- const ioBuffer = ioArray.buffer;
45
- const initResult = {
46
- outputVarIds: wasmResult.outputVarIds,
47
- startTime: wasmModel.startTime,
48
- endTime: wasmModel.endTime,
49
- saveFreq: wasmModel.saveFreq,
50
- rowLength: wasmModel.numSavePoints,
51
- ioBuffer
35
+ const generatedModel = await initGeneratedModel();
36
+ runnableModel = (0, import_runtime.createRunnableModel)(generatedModel);
37
+ return {
38
+ outputVarIds: runnableModel.outputVarIds,
39
+ modelListing: runnableModel.modelListing,
40
+ startTime: runnableModel.startTime,
41
+ endTime: runnableModel.endTime,
42
+ saveFreq: runnableModel.saveFreq,
43
+ outputRowLength: runnableModel.numSavePoints
52
44
  };
53
- return (0, import_worker.Transfer)(initResult, [ioBuffer]);
54
45
  },
55
46
  runModel(ioBuffer) {
56
- if (!wasmModel) {
57
- throw new Error("WasmModel must be initialized before running the model in worker");
47
+ if (!runnableModel) {
48
+ throw new Error("RunnableModel must be initialized before running the model in worker");
58
49
  }
59
- const runTimeLengthInElements = 1;
60
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
61
- const inputsWasmArray = inputsWasmBuffer.getArrayView();
62
- const inputsLengthInElements = inputsWasmArray.length;
63
- const inputsLengthInBytes = inputsLengthInElements * 8;
64
- const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
65
- inputsWasmArray.set(inputsBufferArray);
66
- const t0 = (0, import_runtime.perfNow)();
67
- wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer);
68
- const elapsed = (0, import_runtime.perfElapsed)(t0);
69
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
70
- runTimeBufferArray[0] = elapsed;
71
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
72
- const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
73
- outputsBufferArray.set(outputsWasmBuffer.getArrayView());
50
+ params.updateFromEncodedBuffer(ioBuffer);
51
+ runnableModel.runModel(params);
74
52
  return (0, import_worker.Transfer)(ioBuffer);
75
53
  }
76
54
  };
77
55
  function exposeModelWorker(init) {
78
- initWasmModel = init;
56
+ initGeneratedModel = init;
79
57
  (0, import_worker.expose)(modelWorker);
80
58
  }
81
59
  // Annotate the CommonJS export names for ESM import in node:
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { WasmBuffer, WasmModel, WasmModelInitResult } from '@sdeverywhere/runtime'\nimport { perfElapsed, perfNow } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initWasmModel: () => Promise<WasmModelInitResult>\n/** @hidden */\nlet wasmModel: WasmModel\n/** @hidden */\nlet inputsWasmBuffer: WasmBuffer\n/** @hidden */\nlet outputsWasmBuffer: WasmBuffer\n\ninterface InitResult {\n outputVarIds: string[]\n startTime: number\n endTime: number\n saveFreq: number\n rowLength: number\n ioBuffer: ArrayBuffer\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<TransferDescriptor<InitResult>> {\n if (wasmModel) {\n throw new Error('WasmModel was already initialized')\n }\n\n // Initialize the wasm model and associated buffers\n const wasmResult = await initWasmModel()\n\n // Capture the `WasmModel` instance and `WasmBuffer` instances\n wasmModel = wasmResult.model\n inputsWasmBuffer = wasmResult.inputsBuffer\n outputsWasmBuffer = wasmResult.outputsBuffer\n\n // Create a combined array that will hold a copy of the inputs and outputs\n // wasm buffers; this buffer is no-copy transferable, whereas the wasm ones\n // are not allowed to be transferred\n const runTimeLength = 8\n const inputsLength = inputsWasmBuffer.getArrayView().length\n const outputsLength = outputsWasmBuffer.getArrayView().length\n const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength)\n\n // Transfer the underlying buffer to the runner\n const ioBuffer = ioArray.buffer\n const initResult: InitResult = {\n outputVarIds: wasmResult.outputVarIds,\n startTime: wasmModel.startTime,\n endTime: wasmModel.endTime,\n saveFreq: wasmModel.saveFreq,\n rowLength: wasmModel.numSavePoints,\n ioBuffer\n }\n return Transfer(initResult, [ioBuffer])\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!wasmModel) {\n throw new Error('WasmModel must be initialized before running the model in worker')\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Copy the inputs into the wasm inputs buffer\n const inputsWasmArray = inputsWasmBuffer.getArrayView()\n const inputsLengthInElements = inputsWasmArray.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n inputsWasmArray.set(inputsBufferArray)\n\n // Run the model using the wasm buffers\n const t0 = perfNow()\n wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer)\n const elapsed = perfElapsed(t0)\n\n // Write the model run time to the buffer\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n runTimeBufferArray[0] = elapsed\n\n // Copy the outputs from the wasm outputs buffer\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputsBufferArray.set(outputsWasmBuffer.getArrayView())\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the `WasmModel` on the worker thread\n * and sending the outputs back to the main process.\n *\n * @param init The function that initializes the `WasmModel` instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<WasmModelInitResult>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initWasmModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAiC;AAGjC,qBAAqC;AAGrC,IAAI;AAEJ,IAAI;AAEJ,IAAI;AAEJ,IAAI;AAYJ,IAAM,cAAc;AAAA,EAClB,MAAM,YAAqD;AACzD,QAAI,WAAW;AACb,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAGA,UAAM,aAAa,MAAM,cAAc;AAGvC,gBAAY,WAAW;AACvB,uBAAmB,WAAW;AAC9B,wBAAoB,WAAW;AAK/B,UAAM,gBAAgB;AACtB,UAAM,eAAe,iBAAiB,aAAa,EAAE;AACrD,UAAM,gBAAgB,kBAAkB,aAAa,EAAE;AACvD,UAAM,UAAU,IAAI,aAAa,gBAAgB,eAAe,aAAa;AAG7E,UAAM,WAAW,QAAQ;AACzB,UAAM,aAAyB;AAAA,MAC7B,cAAc,WAAW;AAAA,MACzB,WAAW,UAAU;AAAA,MACrB,SAAS,UAAU;AAAA,MACnB,UAAU,UAAU;AAAA,MACpB,WAAW,UAAU;AAAA,MACrB;AAAA,IACF;AACA,eAAO,wBAAS,YAAY,CAAC,QAAQ,CAAC;AAAA,EACxC;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AAGA,UAAM,0BAA0B;AAChC,UAAM,uBAAuB,0BAA0B;AAGvD,UAAM,kBAAkB,iBAAiB,aAAa;AACtD,UAAM,yBAAyB,gBAAgB;AAC/C,UAAM,sBAAsB,yBAAyB;AACrD,UAAM,oBAAoB,IAAI,aAAa,UAAU,sBAAsB,sBAAsB;AACjG,oBAAgB,IAAI,iBAAiB;AAGrC,UAAM,SAAK,wBAAQ;AACnB,cAAU,SAAS,kBAAkB,iBAAiB;AACtD,UAAM,cAAU,4BAAY,EAAE;AAG9B,UAAM,qBAAqB,IAAI,aAAa,UAAU,GAAG,uBAAuB;AAChF,uBAAmB,KAAK;AAGxB,UAAM,uBAAuB,uBAAuB;AACpD,UAAM,qBAAqB,IAAI,aAAa,UAAU,oBAAoB;AAC1E,uBAAmB,IAAI,kBAAkB,aAAa,CAAC;AAGvD,eAAO,wBAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAAgD;AAGhF,kBAAgB;AAGhB,4BAAO,WAAW;AACpB;","names":[]}
1
+ {"version":3,"sources":["../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { GeneratedModel, RunnableModel } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, createRunnableModel } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initGeneratedModel: () => Promise<GeneratedModel>\n\n/** @hidden */\nlet runnableModel: RunnableModel\n\n/**\n * Maintain a `BufferedRunModelParams` instance that wraps the transferable buffer\n * containing the I/O parameters.\n * @hidden\n */\nconst params = new BufferedRunModelParams()\n\ninterface InitResult {\n outputVarIds: string[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelListing?: /*ModelListingSpecs*/ any\n startTime: number\n endTime: number\n saveFreq: number\n outputRowLength: number\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<InitResult> {\n if (runnableModel) {\n throw new Error('RunnableModel was already initialized')\n }\n\n // Initialize the runnable model\n const generatedModel = await initGeneratedModel()\n runnableModel = createRunnableModel(generatedModel)\n\n // Transfer the model metadata to the runner\n return {\n outputVarIds: runnableModel.outputVarIds,\n modelListing: runnableModel.modelListing,\n startTime: runnableModel.startTime,\n endTime: runnableModel.endTime,\n saveFreq: runnableModel.saveFreq,\n outputRowLength: runnableModel.numSavePoints\n }\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!runnableModel) {\n throw new Error('RunnableModel must be initialized before running the model in worker')\n }\n\n // Update the `BufferedRunModelParams` to use the values in the buffer that was transferred\n // from the runner to the worker\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Run the model synchronously on the worker thread using those I/O parameters\n runnableModel.runModel(params)\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the model on the worker thread and\n * sending the outputs back to the main thread.\n *\n * @param init The function that initializes the generated model instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<GeneratedModel>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initGeneratedModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAAiC;AAGjC,qBAA4D;AAG5D,IAAI;AAGJ,IAAI;AAOJ,IAAM,SAAS,IAAI,sCAAuB;AAa1C,IAAM,cAAc;AAAA,EAClB,MAAM,YAAiC;AACrC,QAAI,eAAe;AACjB,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAGA,UAAM,iBAAiB,MAAM,mBAAmB;AAChD,wBAAgB,oCAAoB,cAAc;AAGlD,WAAO;AAAA,MACL,cAAc,cAAc;AAAA,MAC5B,cAAc,cAAc;AAAA,MAC5B,WAAW,cAAc;AAAA,MACzB,SAAS,cAAc;AAAA,MACvB,UAAU,cAAc;AAAA,MACxB,iBAAiB,cAAc;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI,MAAM,sEAAsE;AAAA,IACxF;AAIA,WAAO,wBAAwB,QAAQ;AAGvC,kBAAc,SAAS,MAAM;AAG7B,eAAO,wBAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAA2C;AAG3E,uBAAqB;AAGrB,4BAAO,WAAW;AACpB;","names":[]}
@@ -0,0 +1,14 @@
1
+ import { GeneratedModel } from '@sdeverywhere/runtime';
2
+
3
+ /**
4
+ * Expose an object in the current worker thread that communicates with the
5
+ * `ModelRunner` instance running in the main thread. The exposed worker
6
+ * object will take care of running the model on the worker thread and
7
+ * sending the outputs back to the main thread.
8
+ *
9
+ * @param init The function that initializes the generated model instance that
10
+ * is used in the worker thread.
11
+ */
12
+ declare function exposeModelWorker(init: () => Promise<GeneratedModel>): void;
13
+
14
+ export { exposeModelWorker };
package/dist/worker.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { WasmModelInitResult } from '@sdeverywhere/runtime';
1
+ import { GeneratedModel } from '@sdeverywhere/runtime';
2
2
 
3
3
  /**
4
4
  * Expose an object in the current worker thread that communicates with the
5
5
  * `ModelRunner` instance running in the main thread. The exposed worker
6
- * object will take care of running the `WasmModel` on the worker thread
7
- * and sending the outputs back to the main process.
6
+ * object will take care of running the model on the worker thread and
7
+ * sending the outputs back to the main thread.
8
8
  *
9
- * @param init The function that initializes the `WasmModel` instance that
9
+ * @param init The function that initializes the generated model instance that
10
10
  * is used in the worker thread.
11
11
  */
12
- declare function exposeModelWorker(init: () => Promise<WasmModelInitResult>): void;
12
+ declare function exposeModelWorker(init: () => Promise<GeneratedModel>): void;
13
13
 
14
14
  export { exposeModelWorker };
package/dist/worker.js CHANGED
@@ -1,58 +1,36 @@
1
1
  // src/worker.ts
2
2
  import { expose, Transfer } from "threads/worker";
3
- import { perfElapsed, perfNow } from "@sdeverywhere/runtime";
4
- var initWasmModel;
5
- var wasmModel;
6
- var inputsWasmBuffer;
7
- var outputsWasmBuffer;
3
+ import { BufferedRunModelParams, createRunnableModel } from "@sdeverywhere/runtime";
4
+ var initGeneratedModel;
5
+ var runnableModel;
6
+ var params = new BufferedRunModelParams();
8
7
  var modelWorker = {
9
8
  async initModel() {
10
- if (wasmModel) {
11
- throw new Error("WasmModel was already initialized");
9
+ if (runnableModel) {
10
+ throw new Error("RunnableModel was already initialized");
12
11
  }
13
- const wasmResult = await initWasmModel();
14
- wasmModel = wasmResult.model;
15
- inputsWasmBuffer = wasmResult.inputsBuffer;
16
- outputsWasmBuffer = wasmResult.outputsBuffer;
17
- const runTimeLength = 8;
18
- const inputsLength = inputsWasmBuffer.getArrayView().length;
19
- const outputsLength = outputsWasmBuffer.getArrayView().length;
20
- const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength);
21
- const ioBuffer = ioArray.buffer;
22
- const initResult = {
23
- outputVarIds: wasmResult.outputVarIds,
24
- startTime: wasmModel.startTime,
25
- endTime: wasmModel.endTime,
26
- saveFreq: wasmModel.saveFreq,
27
- rowLength: wasmModel.numSavePoints,
28
- ioBuffer
12
+ const generatedModel = await initGeneratedModel();
13
+ runnableModel = createRunnableModel(generatedModel);
14
+ return {
15
+ outputVarIds: runnableModel.outputVarIds,
16
+ modelListing: runnableModel.modelListing,
17
+ startTime: runnableModel.startTime,
18
+ endTime: runnableModel.endTime,
19
+ saveFreq: runnableModel.saveFreq,
20
+ outputRowLength: runnableModel.numSavePoints
29
21
  };
30
- return Transfer(initResult, [ioBuffer]);
31
22
  },
32
23
  runModel(ioBuffer) {
33
- if (!wasmModel) {
34
- throw new Error("WasmModel must be initialized before running the model in worker");
24
+ if (!runnableModel) {
25
+ throw new Error("RunnableModel must be initialized before running the model in worker");
35
26
  }
36
- const runTimeLengthInElements = 1;
37
- const runTimeLengthInBytes = runTimeLengthInElements * 8;
38
- const inputsWasmArray = inputsWasmBuffer.getArrayView();
39
- const inputsLengthInElements = inputsWasmArray.length;
40
- const inputsLengthInBytes = inputsLengthInElements * 8;
41
- const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements);
42
- inputsWasmArray.set(inputsBufferArray);
43
- const t0 = perfNow();
44
- wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer);
45
- const elapsed = perfElapsed(t0);
46
- const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements);
47
- runTimeBufferArray[0] = elapsed;
48
- const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes;
49
- const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes);
50
- outputsBufferArray.set(outputsWasmBuffer.getArrayView());
27
+ params.updateFromEncodedBuffer(ioBuffer);
28
+ runnableModel.runModel(params);
51
29
  return Transfer(ioBuffer);
52
30
  }
53
31
  };
54
32
  function exposeModelWorker(init) {
55
- initWasmModel = init;
33
+ initGeneratedModel = init;
56
34
  expose(modelWorker);
57
35
  }
58
36
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { WasmBuffer, WasmModel, WasmModelInitResult } from '@sdeverywhere/runtime'\nimport { perfElapsed, perfNow } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initWasmModel: () => Promise<WasmModelInitResult>\n/** @hidden */\nlet wasmModel: WasmModel\n/** @hidden */\nlet inputsWasmBuffer: WasmBuffer\n/** @hidden */\nlet outputsWasmBuffer: WasmBuffer\n\ninterface InitResult {\n outputVarIds: string[]\n startTime: number\n endTime: number\n saveFreq: number\n rowLength: number\n ioBuffer: ArrayBuffer\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<TransferDescriptor<InitResult>> {\n if (wasmModel) {\n throw new Error('WasmModel was already initialized')\n }\n\n // Initialize the wasm model and associated buffers\n const wasmResult = await initWasmModel()\n\n // Capture the `WasmModel` instance and `WasmBuffer` instances\n wasmModel = wasmResult.model\n inputsWasmBuffer = wasmResult.inputsBuffer\n outputsWasmBuffer = wasmResult.outputsBuffer\n\n // Create a combined array that will hold a copy of the inputs and outputs\n // wasm buffers; this buffer is no-copy transferable, whereas the wasm ones\n // are not allowed to be transferred\n const runTimeLength = 8\n const inputsLength = inputsWasmBuffer.getArrayView().length\n const outputsLength = outputsWasmBuffer.getArrayView().length\n const ioArray = new Float64Array(runTimeLength + inputsLength + outputsLength)\n\n // Transfer the underlying buffer to the runner\n const ioBuffer = ioArray.buffer\n const initResult: InitResult = {\n outputVarIds: wasmResult.outputVarIds,\n startTime: wasmModel.startTime,\n endTime: wasmModel.endTime,\n saveFreq: wasmModel.saveFreq,\n rowLength: wasmModel.numSavePoints,\n ioBuffer\n }\n return Transfer(initResult, [ioBuffer])\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!wasmModel) {\n throw new Error('WasmModel must be initialized before running the model in worker')\n }\n\n // The run time is stored in the first 8 bytes\n const runTimeLengthInElements = 1\n const runTimeLengthInBytes = runTimeLengthInElements * 8\n\n // Copy the inputs into the wasm inputs buffer\n const inputsWasmArray = inputsWasmBuffer.getArrayView()\n const inputsLengthInElements = inputsWasmArray.length\n const inputsLengthInBytes = inputsLengthInElements * 8\n const inputsBufferArray = new Float64Array(ioBuffer, runTimeLengthInBytes, inputsLengthInElements)\n inputsWasmArray.set(inputsBufferArray)\n\n // Run the model using the wasm buffers\n const t0 = perfNow()\n wasmModel.runModel(inputsWasmBuffer, outputsWasmBuffer)\n const elapsed = perfElapsed(t0)\n\n // Write the model run time to the buffer\n const runTimeBufferArray = new Float64Array(ioBuffer, 0, runTimeLengthInElements)\n runTimeBufferArray[0] = elapsed\n\n // Copy the outputs from the wasm outputs buffer\n const outputsOffsetInBytes = runTimeLengthInBytes + inputsLengthInBytes\n const outputsBufferArray = new Float64Array(ioBuffer, outputsOffsetInBytes)\n outputsBufferArray.set(outputsWasmBuffer.getArrayView())\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the `WasmModel` on the worker thread\n * and sending the outputs back to the main process.\n *\n * @param init The function that initializes the `WasmModel` instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<WasmModelInitResult>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initWasmModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";AAGA,SAAS,QAAQ,gBAAgB;AAGjC,SAAS,aAAa,eAAe;AAGrC,IAAI;AAEJ,IAAI;AAEJ,IAAI;AAEJ,IAAI;AAYJ,IAAM,cAAc;AAAA,EAClB,MAAM,YAAqD;AACzD,QAAI,WAAW;AACb,YAAM,IAAI,MAAM,mCAAmC;AAAA,IACrD;AAGA,UAAM,aAAa,MAAM,cAAc;AAGvC,gBAAY,WAAW;AACvB,uBAAmB,WAAW;AAC9B,wBAAoB,WAAW;AAK/B,UAAM,gBAAgB;AACtB,UAAM,eAAe,iBAAiB,aAAa,EAAE;AACrD,UAAM,gBAAgB,kBAAkB,aAAa,EAAE;AACvD,UAAM,UAAU,IAAI,aAAa,gBAAgB,eAAe,aAAa;AAG7E,UAAM,WAAW,QAAQ;AACzB,UAAM,aAAyB;AAAA,MAC7B,cAAc,WAAW;AAAA,MACzB,WAAW,UAAU;AAAA,MACrB,SAAS,UAAU;AAAA,MACnB,UAAU,UAAU;AAAA,MACpB,WAAW,UAAU;AAAA,MACrB;AAAA,IACF;AACA,WAAO,SAAS,YAAY,CAAC,QAAQ,CAAC;AAAA,EACxC;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,kEAAkE;AAAA,IACpF;AAGA,UAAM,0BAA0B;AAChC,UAAM,uBAAuB,0BAA0B;AAGvD,UAAM,kBAAkB,iBAAiB,aAAa;AACtD,UAAM,yBAAyB,gBAAgB;AAC/C,UAAM,sBAAsB,yBAAyB;AACrD,UAAM,oBAAoB,IAAI,aAAa,UAAU,sBAAsB,sBAAsB;AACjG,oBAAgB,IAAI,iBAAiB;AAGrC,UAAM,KAAK,QAAQ;AACnB,cAAU,SAAS,kBAAkB,iBAAiB;AACtD,UAAM,UAAU,YAAY,EAAE;AAG9B,UAAM,qBAAqB,IAAI,aAAa,UAAU,GAAG,uBAAuB;AAChF,uBAAmB,KAAK;AAGxB,UAAM,uBAAuB,uBAAuB;AACpD,UAAM,qBAAqB,IAAI,aAAa,UAAU,oBAAoB;AAC1E,uBAAmB,IAAI,kBAAkB,aAAa,CAAC;AAGvD,WAAO,SAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAAgD;AAGhF,kBAAgB;AAGhB,SAAO,WAAW;AACpB;","names":[]}
1
+ {"version":3,"sources":["../src/worker.ts"],"sourcesContent":["// Copyright (c) 2020-2022 Climate Interactive / New Venture Fund\n\nimport type { TransferDescriptor } from 'threads'\nimport { expose, Transfer } from 'threads/worker'\n\nimport type { GeneratedModel, RunnableModel } from '@sdeverywhere/runtime'\nimport { BufferedRunModelParams, createRunnableModel } from '@sdeverywhere/runtime'\n\n/** @hidden */\nlet initGeneratedModel: () => Promise<GeneratedModel>\n\n/** @hidden */\nlet runnableModel: RunnableModel\n\n/**\n * Maintain a `BufferedRunModelParams` instance that wraps the transferable buffer\n * containing the I/O parameters.\n * @hidden\n */\nconst params = new BufferedRunModelParams()\n\ninterface InitResult {\n outputVarIds: string[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n modelListing?: /*ModelListingSpecs*/ any\n startTime: number\n endTime: number\n saveFreq: number\n outputRowLength: number\n}\n\n/** @hidden */\nconst modelWorker = {\n async initModel(): Promise<InitResult> {\n if (runnableModel) {\n throw new Error('RunnableModel was already initialized')\n }\n\n // Initialize the runnable model\n const generatedModel = await initGeneratedModel()\n runnableModel = createRunnableModel(generatedModel)\n\n // Transfer the model metadata to the runner\n return {\n outputVarIds: runnableModel.outputVarIds,\n modelListing: runnableModel.modelListing,\n startTime: runnableModel.startTime,\n endTime: runnableModel.endTime,\n saveFreq: runnableModel.saveFreq,\n outputRowLength: runnableModel.numSavePoints\n }\n },\n\n runModel(ioBuffer: ArrayBuffer): TransferDescriptor<ArrayBuffer> {\n if (!runnableModel) {\n throw new Error('RunnableModel must be initialized before running the model in worker')\n }\n\n // Update the `BufferedRunModelParams` to use the values in the buffer that was transferred\n // from the runner to the worker\n params.updateFromEncodedBuffer(ioBuffer)\n\n // Run the model synchronously on the worker thread using those I/O parameters\n runnableModel.runModel(params)\n\n // Transfer the buffer back to the runner\n return Transfer(ioBuffer)\n }\n}\n\n/**\n * Expose an object in the current worker thread that communicates with the\n * `ModelRunner` instance running in the main thread. The exposed worker\n * object will take care of running the model on the worker thread and\n * sending the outputs back to the main thread.\n *\n * @param init The function that initializes the generated model instance that\n * is used in the worker thread.\n */\nexport function exposeModelWorker(init: () => Promise<GeneratedModel>): void {\n // Save the initializer, which will be used when the runner calls `initModel`\n // on the worker\n initGeneratedModel = init\n\n // Expose the worker implementation to `threads.js`\n expose(modelWorker)\n}\n"],"mappings":";AAGA,SAAS,QAAQ,gBAAgB;AAGjC,SAAS,wBAAwB,2BAA2B;AAG5D,IAAI;AAGJ,IAAI;AAOJ,IAAM,SAAS,IAAI,uBAAuB;AAa1C,IAAM,cAAc;AAAA,EAClB,MAAM,YAAiC;AACrC,QAAI,eAAe;AACjB,YAAM,IAAI,MAAM,uCAAuC;AAAA,IACzD;AAGA,UAAM,iBAAiB,MAAM,mBAAmB;AAChD,oBAAgB,oBAAoB,cAAc;AAGlD,WAAO;AAAA,MACL,cAAc,cAAc;AAAA,MAC5B,cAAc,cAAc;AAAA,MAC5B,WAAW,cAAc;AAAA,MACzB,SAAS,cAAc;AAAA,MACvB,UAAU,cAAc;AAAA,MACxB,iBAAiB,cAAc;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,SAAS,UAAwD;AAC/D,QAAI,CAAC,eAAe;AAClB,YAAM,IAAI,MAAM,sEAAsE;AAAA,IACxF;AAIA,WAAO,wBAAwB,QAAQ;AAGvC,kBAAc,SAAS,MAAM;AAG7B,WAAO,SAAS,QAAQ;AAAA,EAC1B;AACF;AAWO,SAAS,kBAAkB,MAA2C;AAG3E,uBAAqB;AAGrB,SAAO,WAAW;AACpB;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdeverywhere/runtime-async",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "files": [
5
5
  "dist/**"
6
6
  ],
@@ -26,7 +26,7 @@
26
26
  }
27
27
  },
28
28
  "dependencies": {
29
- "@sdeverywhere/runtime": "^0.2.0",
29
+ "@sdeverywhere/runtime": "^0.2.3",
30
30
  "threads": "1.7.0"
31
31
  },
32
32
  "author": "Climate Interactive",
@@ -49,7 +49,7 @@
49
49
  "test": "vitest run",
50
50
  "test:watch": "vitest",
51
51
  "test:ci": "vitest run",
52
- "type-check": "tsc --noEmit -p tsconfig-build.json",
52
+ "type-check": "tsc --noEmit -p tsconfig-test.json",
53
53
  "build": "tsup",
54
54
  "docs": "../../scripts/gen-docs.js",
55
55
  "ci:build": "run-s clean lint prettier:check type-check build test:ci docs"