@emnapi/wasi-threads 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,7 @@ export declare interface CommandPayloadMap {
27
27
  'cleanup-thread': CleanupThreadPayload;
28
28
  'terminate-all-threads': TerminateAllThreadsPayload;
29
29
  'spawn-thread': SpawnThreadPayload;
30
+ 'thread-error': ThreadErrorPayload;
30
31
  }
31
32
 
32
33
  export declare type CommandType = keyof CommandPayloadMap;
@@ -68,6 +69,13 @@ export declare interface ReuseWorkerOptions {
68
69
  strict?: boolean;
69
70
  }
70
71
 
72
+ export declare interface SerializedError {
73
+ name: string;
74
+ message: string;
75
+ stack?: string;
76
+ cause?: unknown;
77
+ }
78
+
71
79
  export declare interface SpawnThreadPayload {
72
80
  startArg: number;
73
81
  errorOrTid: number;
@@ -87,6 +95,14 @@ export declare interface StartResult {
87
95
  export declare interface TerminateAllThreadsPayload {
88
96
  }
89
97
 
98
+ export declare interface ThreadErrorPayload {
99
+ error: SerializedError;
100
+ phase: ThreadFailurePhase;
101
+ tid?: number;
102
+ }
103
+
104
+ export declare type ThreadFailurePhase = 'load' | 'start' | 'async-work' | 'message' | 'messageerror' | 'exit';
105
+
90
106
  export declare class ThreadManager {
91
107
  unusedWorkers: WorkerLike[];
92
108
  pthreads: Record<number, WorkerLike>;
@@ -94,6 +110,10 @@ export declare class ThreadManager {
94
110
  wasmModule: WebAssembly.Module | null;
95
111
  wasmMemory: WebAssembly.Memory | null;
96
112
  private readonly messageEvents;
113
+ private readonly registeredWorkers;
114
+ private readonly expectedTerminations;
115
+ private readonly loadRejects;
116
+ private _fatalError;
97
117
  private readonly _childThread;
98
118
  private readonly _onCreateWorker;
99
119
  private readonly _reuseWorker;
@@ -108,6 +128,8 @@ export declare class ThreadManager {
108
128
  loadWasmModuleToAllWorkers(): Promise<WorkerLike[]>;
109
129
  preloadWorkers(): Promise<WorkerLike[]>;
110
130
  setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void;
131
+ private assertRunning;
132
+ private fail;
111
133
  markId(worker: WorkerLike): number;
112
134
  returnWorkerToPool(worker: WorkerLike): void;
113
135
  loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise<WorkerLike>;
@@ -116,6 +138,7 @@ export declare class ThreadManager {
116
138
  cleanThread(worker: WorkerLike, tid: number, force?: boolean): void;
117
139
  terminateWorker(worker: WorkerLike): void;
118
140
  terminateAllThreads(): void;
141
+ private shutdownAllWorkers;
119
142
  addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void;
120
143
  fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void;
121
144
  }
@@ -151,6 +174,8 @@ export declare class ThreadMessageHandler {
151
174
  private _start;
152
175
  protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void;
153
176
  protected handleAfterLoad<E extends WorkerMessageEvent>(e: E, f: (e: E) => void): void;
177
+ protected beforeReportError(_error: Error, _type: WorkerMessageType | 'async-worker-init', _tid?: number): void;
178
+ protected reportError(value: unknown, type: WorkerMessageType | 'async-worker-init', tid?: number): void;
154
179
  }
155
180
 
156
181
  export declare interface ThreadMessageHandlerOptions {
@@ -14,13 +14,74 @@ function getPostMessage(options) {
14
14
  ? postMessage
15
15
  : undefined;
16
16
  }
17
- function serizeErrorToBuffer(sab, code, error) {
17
+ function normalizeError(value) {
18
+ if (value instanceof Error)
19
+ return value;
20
+ if (typeof value === 'object' && value !== null && 'error' in value) {
21
+ const nested = value.error;
22
+ if (nested !== undefined && nested !== value)
23
+ return normalizeError(nested);
24
+ }
25
+ const record = typeof value === 'object' && value !== null
26
+ ? value
27
+ : undefined;
28
+ const message = record?.message !== undefined
29
+ ? String(record.message)
30
+ : typeof value === 'string'
31
+ ? value
32
+ : 'Worker sent an unknown error';
33
+ const name = record?.name !== undefined ? String(record.name) : 'Error';
34
+ let error;
35
+ try {
36
+ const ErrorConstructor = name === 'RuntimeError'
37
+ ? (_WebAssembly?.RuntimeError ?? Error)
38
+ : Error;
39
+ error = new ErrorConstructor(message);
40
+ }
41
+ catch (_) {
42
+ error = new Error(message);
43
+ }
44
+ error.name = name;
45
+ if (record?.stack !== undefined) {
46
+ Object.defineProperty(error, 'stack', {
47
+ value: String(record.stack),
48
+ writable: true,
49
+ enumerable: false,
50
+ configurable: true
51
+ });
52
+ }
53
+ if (record?.cause !== undefined) {
54
+ Object.defineProperty(error, 'cause', {
55
+ value: record.cause,
56
+ writable: true,
57
+ enumerable: false,
58
+ configurable: true
59
+ });
60
+ }
61
+ return error;
62
+ }
63
+ function serializeError(value) {
64
+ const error = normalizeError(value);
65
+ const serialized = {
66
+ name: error.name,
67
+ message: error.message
68
+ };
69
+ if (error.stack !== undefined)
70
+ serialized.stack = error.stack;
71
+ if ('cause' in error && error.cause !== undefined)
72
+ serialized.cause = error.cause;
73
+ return serialized;
74
+ }
75
+ function deserializeError(value) {
76
+ return normalizeError(value);
77
+ }
78
+ function serializeErrorToBuffer(sab, code, error) {
18
79
  const i32array = new Int32Array(sab);
19
80
  Atomics.store(i32array, 0, code);
20
81
  if (code > 1 && error) {
21
82
  const name = error.name;
22
83
  const message = error.message;
23
- const stack = error.stack;
84
+ const stack = error.stack ?? '';
24
85
  const nameBuffer = new TextEncoder().encode(name);
25
86
  const messageBuffer = new TextEncoder().encode(message);
26
87
  const stackBuffer = new TextEncoder().encode(stack);
@@ -33,7 +94,7 @@ function serizeErrorToBuffer(sab, code, error) {
33
94
  buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length);
34
95
  }
35
96
  }
36
- function deserizeErrorFromBuffer(sab) {
97
+ function deserializeErrorFromBuffer(sab) {
37
98
  const i32array = new Int32Array(sab);
38
99
  const status = Atomics.load(i32array, 0);
39
100
  if (status <= 1) {
@@ -59,16 +120,17 @@ function deserizeErrorFromBuffer(sab) {
59
120
  });
60
121
  return error;
61
122
  }
123
+ const deserizeErrorFromBuffer = deserializeErrorFromBuffer;
62
124
  function isSharedArrayBuffer(value) {
63
125
  return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) ||
64
126
  (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'));
65
127
  }
66
128
  function isTrapError(e) {
67
129
  try {
68
- return e instanceof _WebAssembly.RuntimeError;
130
+ return e instanceof _WebAssembly.RuntimeError || e?.name === 'RuntimeError';
69
131
  }
70
132
  catch (_) {
71
- return false;
133
+ return e?.name === 'RuntimeError';
72
134
  }
73
135
  }
74
136
 
@@ -131,6 +193,9 @@ class ThreadManager {
131
193
  this.wasmModule = null;
132
194
  this.wasmMemory = null;
133
195
  this.messageEvents = new WeakMap();
196
+ this.registeredWorkers = new Set();
197
+ this.expectedTerminations = new WeakSet();
198
+ this.loadRejects = new WeakMap();
134
199
  if (!options) {
135
200
  throw new TypeError('ThreadManager(): options is not provided');
136
201
  }
@@ -209,7 +274,22 @@ class ThreadManager {
209
274
  this.wasmModule = wasmModule;
210
275
  this.wasmMemory = wasmMemory;
211
276
  }
277
+ assertRunning() {
278
+ if (this._fatalError)
279
+ throw this._fatalError;
280
+ }
281
+ fail(value, rethrow) {
282
+ if (this._fatalError)
283
+ return;
284
+ this._fatalError = normalizeError(value);
285
+ this.shutdownAllWorkers(false, this._fatalError);
286
+ if (rethrow) {
287
+ const error = this._fatalError;
288
+ Promise.resolve().then(() => { throw error; });
289
+ }
290
+ }
212
291
  markId(worker) {
292
+ this.assertRunning();
213
293
  if (worker.__emnapi_tid)
214
294
  return worker.__emnapi_tid;
215
295
  const tid = nextWorkerID + 43;
@@ -219,6 +299,10 @@ class ThreadManager {
219
299
  return tid;
220
300
  }
221
301
  returnWorkerToPool(worker) {
302
+ if (this._fatalError) {
303
+ this.terminateWorker(worker);
304
+ return;
305
+ }
222
306
  var tid = worker.__emnapi_tid;
223
307
  if (tid !== undefined) {
224
308
  delete this.pthreads[tid];
@@ -230,31 +314,37 @@ class ThreadManager {
230
314
  }
231
315
  }
232
316
  loadWasmModuleToWorker(worker, sab) {
317
+ this.assertRunning();
233
318
  if (worker.whenLoaded)
234
319
  return worker.whenLoaded;
320
+ this.registeredWorkers.add(worker);
235
321
  const err = this.printErr;
236
322
  const beforeLoad = this._beforeLoad;
237
323
  const _this = this;
238
324
  worker.whenLoaded = new Promise((resolve, reject) => {
239
325
  const handleError = function (e) {
326
+ if (_this.expectedTerminations.has(worker))
327
+ return;
240
328
  let message = 'worker sent an error!';
241
329
  if (worker.__emnapi_tid !== undefined) {
242
330
  message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!';
243
331
  }
244
- if ('message' in e) {
245
- err(message + ' ' + e.message);
246
- if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) {
247
- try {
248
- _this.terminateAllThreads();
249
- }
250
- catch (_) { }
251
- }
332
+ const error = normalizeError(e);
333
+ if (error.message) {
334
+ err(message + ' ' + error.message);
252
335
  }
253
336
  else {
254
337
  err(message);
255
338
  }
256
- reject(e);
257
- throw e;
339
+ if (!worker.loaded) {
340
+ reject(error);
341
+ _this.loadRejects.delete(worker);
342
+ _this.terminateWorker(worker);
343
+ return;
344
+ }
345
+ _this.fail(error, !ENVIRONMENT_IS_NODE);
346
+ if (ENVIRONMENT_IS_NODE)
347
+ throw error;
258
348
  };
259
349
  const handleMessage = (data) => {
260
350
  if (data.__emnapi__) {
@@ -262,6 +352,7 @@ class ThreadManager {
262
352
  const payload = data.__emnapi__.payload;
263
353
  if (type === 'loaded') {
264
354
  worker.loaded = true;
355
+ this.loadRejects.delete(worker);
265
356
  if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) {
266
357
  worker.unref();
267
358
  }
@@ -278,6 +369,18 @@ class ThreadManager {
278
369
  else if (type === 'terminate-all-threads') {
279
370
  this.terminateAllThreads();
280
371
  }
372
+ else if (type === 'thread-error') {
373
+ const threadError = payload;
374
+ const error = deserializeError(threadError.error);
375
+ if (!worker.loaded && threadError.phase === 'load') {
376
+ reject(error);
377
+ this.loadRejects.delete(worker);
378
+ this.terminateWorker(worker);
379
+ }
380
+ else {
381
+ this.fail(error, true);
382
+ }
383
+ }
281
384
  }
282
385
  };
283
386
  worker.onmessage = (e) => {
@@ -285,6 +388,9 @@ class ThreadManager {
285
388
  this.fireMessageEvent(worker, e);
286
389
  };
287
390
  worker.onerror = handleError;
391
+ worker.onmessageerror = (e) => {
392
+ handleError(normalizeError(e));
393
+ };
288
394
  if (ENVIRONMENT_IS_NODE) {
289
395
  worker.on('message', function (data) {
290
396
  worker.onmessage?.({
@@ -294,35 +400,55 @@ class ThreadManager {
294
400
  worker.on('error', function (e) {
295
401
  worker.onerror?.(e);
296
402
  });
403
+ worker.on('messageerror', function (e) {
404
+ handleError(normalizeError(e));
405
+ });
406
+ worker.on('exit', function (code) {
407
+ if (!_this.expectedTerminations.has(worker)) {
408
+ handleError(new Error('Worker stopped with exit code ' + code));
409
+ }
410
+ });
297
411
  worker.on('detachedExit', function () { });
298
412
  }
299
- if (typeof beforeLoad === 'function') {
300
- beforeLoad(worker);
301
- }
413
+ this.loadRejects.set(worker, reject);
302
414
  try {
415
+ if (typeof beforeLoad === 'function') {
416
+ beforeLoad(worker);
417
+ }
303
418
  worker.postMessage(createMessage('load', {
304
419
  wasmModule: this.wasmModule,
305
420
  wasmMemory: this.wasmMemory,
306
421
  sab
307
422
  }));
308
423
  }
309
- catch (err) {
310
- checkSharedWasmMemory(this.wasmMemory);
311
- throw err;
424
+ catch (caughtError) {
425
+ let error = caughtError;
426
+ try {
427
+ checkSharedWasmMemory(this.wasmMemory);
428
+ }
429
+ catch (memoryError) {
430
+ error = memoryError;
431
+ }
432
+ reject(error);
433
+ this.loadRejects.delete(worker);
434
+ this.terminateWorker(worker);
312
435
  }
313
436
  });
314
437
  return worker.whenLoaded;
315
438
  }
316
439
  allocateUnusedWorker() {
440
+ this.assertRunning();
317
441
  const _onCreateWorker = this._onCreateWorker;
318
442
  if (typeof _onCreateWorker !== 'function') {
319
443
  throw new TypeError('`options.onCreateWorker` is not provided');
320
444
  }
321
445
  const worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' });
446
+ this.registeredWorkers.add(worker);
322
447
  this.unusedWorkers.push(worker);
323
448
  return worker;
324
449
  }
325
450
  getNewWorker(sab) {
451
+ this.assertRunning();
326
452
  if (this._reuseWorker) {
327
453
  if (this.unusedWorkers.length === 0) {
328
454
  if (this._reuseWorker.strict) {
@@ -354,6 +480,9 @@ class ThreadManager {
354
480
  }
355
481
  terminateWorker(worker) {
356
482
  const tid = worker.__emnapi_tid;
483
+ this.expectedTerminations.add(worker);
484
+ this.registeredWorkers.delete(worker);
485
+ this.loadRejects.delete(worker);
357
486
  worker.terminate();
358
487
  this.messageEvents.get(worker)?.clear();
359
488
  this.messageEvents.delete(worker);
@@ -365,16 +494,23 @@ class ThreadManager {
365
494
  };
366
495
  }
367
496
  terminateAllThreads() {
368
- const runningWorkers = Object.values(this.pthreads);
369
- for (let i = 0; i < runningWorkers.length; ++i) {
370
- this.terminateWorker(runningWorkers[i]);
371
- }
372
- for (let i = 0; i < this.unusedWorkers.length; ++i) {
373
- this.terminateWorker(this.unusedWorkers[i]);
374
- }
497
+ this.shutdownAllWorkers(true);
498
+ }
499
+ shutdownAllWorkers(recreatePool, reason) {
500
+ const workers = new Set([
501
+ ...this.registeredWorkers,
502
+ ...Object.values(this.pthreads),
503
+ ...this.unusedWorkers
504
+ ]);
505
+ workers.forEach((worker) => {
506
+ if (reason)
507
+ this.loadRejects.get(worker)?.(reason);
508
+ this.terminateWorker(worker);
509
+ });
375
510
  this.unusedWorkers = [];
376
511
  this.pthreads = Object.create(null);
377
- this.preparePool();
512
+ if (recreatePool && !this._fatalError)
513
+ this.preparePool();
378
514
  }
379
515
  addMessageEventListener(worker, onMessage) {
380
516
  let listeners = this.messageEvents.get(worker);
@@ -476,6 +612,36 @@ function createInstanceProxy(instance, memory) {
476
612
 
477
613
  //#region src/wasi-threads.ts
478
614
  const patchedWasiInstances = new WeakMap();
615
+ const THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2;
616
+ const sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function'
617
+ ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get
618
+ : undefined;
619
+ function isConclusivelySharedArrayBuffer(buffer) {
620
+ if (sharedArrayBufferByteLength === undefined)
621
+ return false;
622
+ try {
623
+ sharedArrayBufferByteLength.call(buffer);
624
+ return true;
625
+ }
626
+ catch (_) {
627
+ return false;
628
+ }
629
+ }
630
+ function getThreadSpawnResultView(memory, address, wasm64) {
631
+ const offset = typeof address === 'bigint' ? Number(address) : address >>> 0;
632
+ let buffer = memory.buffer;
633
+ if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength &&
634
+ isConclusivelySharedArrayBuffer(buffer)) {
635
+ if (wasm64) {
636
+ memory.grow(BigInt(0));
637
+ }
638
+ else {
639
+ memory.grow(0);
640
+ }
641
+ buffer = memory.buffer;
642
+ }
643
+ return new Int32Array(buffer, offset, 2);
644
+ }
479
645
  class WASIThreads {
480
646
  constructor(options) {
481
647
  if (!options) {
@@ -528,7 +694,7 @@ class WASIThreads {
528
694
  catch (err) {
529
695
  this.PThread?.printErr(err.stack);
530
696
  if (isNewABI) {
531
- const struct = new Int32Array(this.wasmMemory.buffer, errorOrTid, 2);
697
+ const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64);
532
698
  Atomics.store(struct, 0, 1);
533
699
  Atomics.store(struct, 1, EAGAIN);
534
700
  Atomics.notify(struct, 1);
@@ -547,7 +713,7 @@ class WASIThreads {
547
713
  }
548
714
  const _free = this.wasmInstance.exports.free;
549
715
  const free = wasm64 ? (ptr) => { _free(BigInt(ptr)); } : _free;
550
- const struct = new Int32Array(this.wasmMemory.buffer, errorOrTid, 2);
716
+ const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64);
551
717
  Atomics.store(struct, 0, 0);
552
718
  Atomics.store(struct, 1, 0);
553
719
  if (this.childThread) {
@@ -769,7 +935,7 @@ class ThreadMessageHandler {
769
935
  }
770
936
  this.postMessage = postMsg;
771
937
  this.onLoad = options?.onLoad;
772
- this.onError = typeof options?.onError === 'function' ? options.onError : (_type, err) => { throw err; };
938
+ this.onError = typeof options?.onError === 'function' ? options.onError : (error) => { throw error; };
773
939
  this.instance = undefined;
774
940
  this.messagesBeforeLoad = [];
775
941
  }
@@ -794,7 +960,8 @@ class ThreadMessageHandler {
794
960
  }
795
961
  }
796
962
  catch (err) {
797
- this.onError(err, type);
963
+ const tid = type === 'start' ? payload.tid : undefined;
964
+ this.reportError(err, type, tid);
798
965
  }
799
966
  }
800
967
  }
@@ -811,7 +978,14 @@ class ThreadMessageHandler {
811
978
  }
812
979
  const then = source && 'then' in source ? source.then : undefined;
813
980
  if (typeof then === 'function') {
814
- then.call(source, (source) => { this._loaded(null, source, payload); }, (err) => { this._loaded(err, null, payload); });
981
+ then.call(source, (source) => { this._loaded(null, source, payload); }, (err) => {
982
+ try {
983
+ this._loaded(normalizeError(err), null, payload);
984
+ }
985
+ catch (loadError) {
986
+ this.reportError(loadError, 'load');
987
+ }
988
+ });
815
989
  }
816
990
  else {
817
991
  this._loaded(null, source, payload);
@@ -875,10 +1049,34 @@ class ThreadMessageHandler {
875
1049
  this.messagesBeforeLoad.push(e.data);
876
1050
  }
877
1051
  }
1052
+ beforeReportError(_error, _type, _tid) { }
1053
+ reportError(value, type, tid) {
1054
+ const error = normalizeError(value);
1055
+ this.beforeReportError(error, type, tid);
1056
+ const phase = type === 'async-worker-init' ? 'async-work' : type;
1057
+ const report = () => {
1058
+ try {
1059
+ this.postMessage(createMessage('thread-error', {
1060
+ error: serializeError(error),
1061
+ phase,
1062
+ tid
1063
+ }));
1064
+ }
1065
+ catch (_) { }
1066
+ };
1067
+ if (ENVIRONMENT_IS_NODE) {
1068
+ this.onError(error, type);
1069
+ report();
1070
+ }
1071
+ else {
1072
+ report();
1073
+ this.onError(error, type);
1074
+ }
1075
+ }
878
1076
  }
879
1077
  function notifyPthreadCreateResult(sab, result, error) {
880
1078
  if (sab) {
881
- serizeErrorToBuffer(sab.buffer, result, error);
1079
+ serializeErrorToBuffer(sab.buffer, result, error);
882
1080
  Atomics.notify(sab, 0);
883
1081
  }
884
1082
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emnapi/wasi-threads",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "WASI threads proposal implementation in JavaScript",
5
5
  "type": "module",
6
6
  "main": "./dist/wasi-threads.js",