@hybrid-compute/worker 0.38.0 → 0.38.1
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/CHANGELOG.md +6 -0
- package/dist/errors.d.ts +38 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +37 -0
- package/dist/errors.js.map +1 -0
- package/dist/expose.d.ts +39 -0
- package/dist/expose.d.ts.map +1 -0
- package/dist/expose.js +111 -0
- package/dist/expose.js.map +1 -0
- package/dist/index.d.ts +115 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +276 -0
- package/dist/index.js.map +1 -0
- package/{src/types.ts → dist/types.d.ts} +17 -26
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils.d.ts +6 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +26 -0
- package/dist/utils.js.map +1 -0
- package/package.json +5 -1
- package/.release-it.json +0 -83
- package/eslint.config.mjs +0 -3
- package/src/__tests__/expose.spec.ts +0 -175
- package/src/__tests__/fixtures/exposed.ts +0 -30
- package/src/__tests__/fixtures/raw.ts +0 -21
- package/src/__tests__/thread-worker.ts +0 -69
- package/src/__tests__/worker.spec.ts +0 -449
- package/src/errors.ts +0 -49
- package/src/expose.ts +0 -130
- package/src/index.ts +0 -389
- package/src/utils.ts +0 -30
- package/tsconfig.build.json +0 -13
- package/tsconfig.json +0 -13
|
@@ -1,449 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert/strict';
|
|
2
|
-
import test, { describe } from 'node:test';
|
|
3
|
-
|
|
4
|
-
import { NoBackendError } from '@hybrid-compute/core';
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
createThreadedCompute,
|
|
8
|
-
ThreadedCompute,
|
|
9
|
-
ThreadedComputeOptionsInterface,
|
|
10
|
-
WorkerTaskError
|
|
11
|
-
} from '..';
|
|
12
|
-
|
|
13
|
-
import { ThreadWorker, withoutWorker, withWorker } from './thread-worker';
|
|
14
|
-
|
|
15
|
-
const fixture = (name: string) =>
|
|
16
|
-
new URL(`./fixtures/${name}.ts`, import.meta.url);
|
|
17
|
-
const exposed = (extra: Partial<ThreadedComputeOptionsInterface> = {}) =>
|
|
18
|
-
createThreadedCompute({
|
|
19
|
-
url: fixture('exposed'),
|
|
20
|
-
canRunTasks: [
|
|
21
|
-
'echo',
|
|
22
|
-
'double',
|
|
23
|
-
'fail',
|
|
24
|
-
'unclonable',
|
|
25
|
-
'waitForAbort',
|
|
26
|
-
'abortedCount',
|
|
27
|
-
'missing'
|
|
28
|
-
],
|
|
29
|
-
...extra
|
|
30
|
-
});
|
|
31
|
-
const raw = (extra: Partial<ThreadedComputeOptionsInterface> = {}) =>
|
|
32
|
-
createThreadedCompute({
|
|
33
|
-
url: fixture('raw'),
|
|
34
|
-
canRunTasks: [
|
|
35
|
-
'echo',
|
|
36
|
-
'errorString',
|
|
37
|
-
'errorObject',
|
|
38
|
-
'errorEmpty',
|
|
39
|
-
'errorOther',
|
|
40
|
-
'errorBigInt',
|
|
41
|
-
'noResult',
|
|
42
|
-
'null',
|
|
43
|
-
'stranger',
|
|
44
|
-
'throw',
|
|
45
|
-
'hang'
|
|
46
|
-
],
|
|
47
|
-
...extra
|
|
48
|
-
});
|
|
49
|
-
const isWorkerError =
|
|
50
|
-
(message: RegExp, check: (error: WorkerTaskError) => boolean = () => true) =>
|
|
51
|
-
(error: unknown) =>
|
|
52
|
-
error instanceof WorkerTaskError &&
|
|
53
|
-
message.test(error.message) &&
|
|
54
|
-
check(error);
|
|
55
|
-
const options = (value: unknown) =>
|
|
56
|
-
value as unknown as ThreadedComputeOptionsInterface;
|
|
57
|
-
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
58
|
-
|
|
59
|
-
describe('options', () => {
|
|
60
|
-
test('throws a TypeError for something that is not an options object', () => {
|
|
61
|
-
for (const value of [undefined, null, './worker.js', []]) {
|
|
62
|
-
assert.throws(() => createThreadedCompute(options(value)), TypeError);
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
test('requires a url: a URL or a non-empty string', () => {
|
|
67
|
-
for (const url of [undefined, '', 42, {}]) {
|
|
68
|
-
assert.throws(
|
|
69
|
-
() => createThreadedCompute(options({ url, canRunTasks: ['echo'] })),
|
|
70
|
-
{
|
|
71
|
-
name: 'TypeError',
|
|
72
|
-
message: /^url must be a URL or a non-empty string/
|
|
73
|
-
}
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
assert.ok(createThreadedCompute({ url: './worker.js', canRunTasks: [] }));
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
test('requires canRunTasks: a list of task names', () => {
|
|
81
|
-
for (const canRunTasks of [undefined, 'echo', ['echo', ''], [42]]) {
|
|
82
|
-
assert.throws(
|
|
83
|
-
() =>
|
|
84
|
-
createThreadedCompute(options({ url: './worker.js', canRunTasks })),
|
|
85
|
-
TypeError
|
|
86
|
-
);
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
test('checks the timeout', () => {
|
|
91
|
-
assert.throws(() => exposed({ timeout: -1 }), RangeError);
|
|
92
|
-
assert.throws(() => exposed({ timeout: Number.NaN }), TypeError);
|
|
93
|
-
assert.throws(() => exposed(options({ timeout: '100' })), TypeError);
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
test('starts no worker when it is created', async () => {
|
|
97
|
-
await withWorker(() => {
|
|
98
|
-
const before = ThreadWorker.started;
|
|
99
|
-
|
|
100
|
-
exposed();
|
|
101
|
-
assert.equal(ThreadWorker.started, before);
|
|
102
|
-
});
|
|
103
|
-
});
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
describe('canRun', () => {
|
|
107
|
-
test('is true for the tasks in canRunTasks only', async () => {
|
|
108
|
-
await withWorker(() => {
|
|
109
|
-
const threaded = exposed();
|
|
110
|
-
|
|
111
|
-
assert.equal(threaded.canRun('echo'), true);
|
|
112
|
-
assert.equal(threaded.canRun('e'), false);
|
|
113
|
-
});
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
test('is false where there are no Web Workers, so auto falls back', async () => {
|
|
117
|
-
await withoutWorker(() => assert.equal(exposed().canRun('echo'), false));
|
|
118
|
-
});
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
describe('runTask with exposeTasks', () => {
|
|
122
|
-
test('resolves the result, for a URL or a string url', async () => {
|
|
123
|
-
await withWorker(async () => {
|
|
124
|
-
const threaded = exposed();
|
|
125
|
-
|
|
126
|
-
assert.equal(await threaded.runTask('double', 21), 42);
|
|
127
|
-
threaded.close();
|
|
128
|
-
|
|
129
|
-
const fromString = exposed({ url: fixture('exposed').href });
|
|
130
|
-
|
|
131
|
-
assert.deepEqual(await fromString.runTask('echo', { a: [1] }), {
|
|
132
|
-
a: [1]
|
|
133
|
-
});
|
|
134
|
-
fromString.close();
|
|
135
|
-
});
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
test('matches concurrent replies by id, in one worker', async () => {
|
|
139
|
-
await withWorker(async () => {
|
|
140
|
-
const before = ThreadWorker.started;
|
|
141
|
-
const threaded = exposed();
|
|
142
|
-
|
|
143
|
-
assert.deepEqual(
|
|
144
|
-
await Promise.all([
|
|
145
|
-
threaded.runTask('echo', 'a'),
|
|
146
|
-
threaded.runTask('double', 2),
|
|
147
|
-
threaded.runTask('echo', 'c')
|
|
148
|
-
]),
|
|
149
|
-
['a', 4, 'c']
|
|
150
|
-
);
|
|
151
|
-
assert.equal(ThreadWorker.started - before, 1);
|
|
152
|
-
threaded.close();
|
|
153
|
-
});
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
test('rejects a thrown error with WorkerTaskError, keeping the detail', async () => {
|
|
157
|
-
await withWorker(async () => {
|
|
158
|
-
const threaded = exposed();
|
|
159
|
-
|
|
160
|
-
await assert.rejects(
|
|
161
|
-
threaded.runTask('fail', 1),
|
|
162
|
-
isWorkerError(/^Worker task 'fail' failed: boom$/, (error) => {
|
|
163
|
-
const detail = error.detail as { name: string; message: string };
|
|
164
|
-
|
|
165
|
-
return (
|
|
166
|
-
error.taskName === 'fail' &&
|
|
167
|
-
detail.name === 'Error' &&
|
|
168
|
-
detail.message === 'boom'
|
|
169
|
-
);
|
|
170
|
-
})
|
|
171
|
-
);
|
|
172
|
-
await assert.rejects(
|
|
173
|
-
threaded.runTask('missing', 1),
|
|
174
|
-
isWorkerError(/failed: No task 'missing' in this worker/)
|
|
175
|
-
);
|
|
176
|
-
await assert.rejects(
|
|
177
|
-
threaded.runTask('unclonable', 1),
|
|
178
|
-
isWorkerError(/failed: the result couldn't be sent/)
|
|
179
|
-
);
|
|
180
|
-
threaded.close();
|
|
181
|
-
});
|
|
182
|
-
});
|
|
183
|
-
|
|
184
|
-
test('rejects an unlisted task with NoBackendError, without starting a worker', async () => {
|
|
185
|
-
await withWorker(async () => {
|
|
186
|
-
const before = ThreadWorker.started;
|
|
187
|
-
|
|
188
|
-
await assert.rejects(
|
|
189
|
-
exposed().runTask('unlisted', 1),
|
|
190
|
-
(error) =>
|
|
191
|
-
error instanceof NoBackendError &&
|
|
192
|
-
error.strategy === 'worker' &&
|
|
193
|
-
/it isn't in canRunTasks/.test(error.message)
|
|
194
|
-
);
|
|
195
|
-
assert.equal(ThreadWorker.started, before);
|
|
196
|
-
});
|
|
197
|
-
});
|
|
198
|
-
|
|
199
|
-
test('rejects with a TypeError where there are no Web Workers', async () => {
|
|
200
|
-
await withoutWorker(() =>
|
|
201
|
-
assert.rejects(exposed().runTask('echo', 1), {
|
|
202
|
-
name: 'TypeError',
|
|
203
|
-
message: /Web Workers are not available/
|
|
204
|
-
})
|
|
205
|
-
);
|
|
206
|
-
});
|
|
207
|
-
|
|
208
|
-
test('rejects input that cannot be cloned, and keeps working', async () => {
|
|
209
|
-
await withWorker(async () => {
|
|
210
|
-
const threaded = exposed();
|
|
211
|
-
|
|
212
|
-
await assert.rejects(
|
|
213
|
-
threaded.runTask('echo', () => 1),
|
|
214
|
-
isWorkerError(
|
|
215
|
-
/couldn't send its input/,
|
|
216
|
-
(error) => error.cause !== undefined
|
|
217
|
-
)
|
|
218
|
-
);
|
|
219
|
-
assert.equal(
|
|
220
|
-
await threaded.runTask('echo', 'still works'),
|
|
221
|
-
'still works'
|
|
222
|
-
);
|
|
223
|
-
threaded.close();
|
|
224
|
-
});
|
|
225
|
-
});
|
|
226
|
-
});
|
|
227
|
-
|
|
228
|
-
describe('runTask with a hand written worker script', () => {
|
|
229
|
-
test('rejects error replies, including falsy ones', async () => {
|
|
230
|
-
await withWorker(async () => {
|
|
231
|
-
const threaded = raw();
|
|
232
|
-
|
|
233
|
-
await assert.rejects(
|
|
234
|
-
threaded.runTask('errorString', 1),
|
|
235
|
-
isWorkerError(
|
|
236
|
-
/failed: task failed$/,
|
|
237
|
-
(error) => error.detail === 'task failed'
|
|
238
|
-
)
|
|
239
|
-
);
|
|
240
|
-
await assert.rejects(
|
|
241
|
-
threaded.runTask('errorObject', 1),
|
|
242
|
-
isWorkerError(
|
|
243
|
-
/failed: bad input$/,
|
|
244
|
-
(error) => (error.detail as { code: string }).code === 'E_TASK'
|
|
245
|
-
)
|
|
246
|
-
);
|
|
247
|
-
await assert.rejects(
|
|
248
|
-
threaded.runTask('errorEmpty', 1),
|
|
249
|
-
isWorkerError(/'errorEmpty' failed$/, (error) => error.detail === '')
|
|
250
|
-
);
|
|
251
|
-
await assert.rejects(
|
|
252
|
-
threaded.runTask('errorOther', 1),
|
|
253
|
-
isWorkerError(/failed: 42$/)
|
|
254
|
-
);
|
|
255
|
-
await assert.rejects(
|
|
256
|
-
threaded.runTask('errorBigInt', 1),
|
|
257
|
-
isWorkerError(/failed: 10$/)
|
|
258
|
-
);
|
|
259
|
-
await assert.rejects(
|
|
260
|
-
threaded.runTask('noResult', 1),
|
|
261
|
-
isWorkerError(/neither a result nor an error/)
|
|
262
|
-
);
|
|
263
|
-
threaded.close();
|
|
264
|
-
});
|
|
265
|
-
});
|
|
266
|
-
|
|
267
|
-
test('ignores messages it cannot match, without throwing', async () => {
|
|
268
|
-
await withWorker(async () => {
|
|
269
|
-
const uncaught: unknown[] = [];
|
|
270
|
-
const listener = (error: unknown) => uncaught.push(error);
|
|
271
|
-
|
|
272
|
-
process.on('uncaughtException', listener);
|
|
273
|
-
|
|
274
|
-
try {
|
|
275
|
-
const threaded = raw({ timeout: 150 });
|
|
276
|
-
|
|
277
|
-
for (const task of ['null', 'stranger']) {
|
|
278
|
-
await assert.rejects(
|
|
279
|
-
threaded.runTask(task, 1),
|
|
280
|
-
isWorkerError(new RegExp(`'${task}' timed out after 150 ms`))
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
threaded.close();
|
|
285
|
-
} finally {
|
|
286
|
-
process.off('uncaughtException', listener);
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
assert.deepEqual(uncaught, []);
|
|
290
|
-
});
|
|
291
|
-
});
|
|
292
|
-
|
|
293
|
-
test('rejects every waiting task when the worker throws, and starts a new worker for the next one', async () => {
|
|
294
|
-
await withWorker(async () => {
|
|
295
|
-
const threaded = raw();
|
|
296
|
-
const before = ThreadWorker.started;
|
|
297
|
-
const waiting = threaded.runTask('hang', 1);
|
|
298
|
-
|
|
299
|
-
await assert.rejects(
|
|
300
|
-
threaded.runTask('throw', 1),
|
|
301
|
-
isWorkerError(
|
|
302
|
-
/'throw' got no reply: the worker threw: thrown inside the worker/,
|
|
303
|
-
(error) => error.cause !== undefined
|
|
304
|
-
)
|
|
305
|
-
);
|
|
306
|
-
await assert.rejects(
|
|
307
|
-
waiting,
|
|
308
|
-
isWorkerError(/'hang' got no reply: the worker threw/)
|
|
309
|
-
);
|
|
310
|
-
assert.equal(await threaded.runTask('echo', 'again'), 'again');
|
|
311
|
-
assert.equal(ThreadWorker.started - before, 2);
|
|
312
|
-
threaded.close();
|
|
313
|
-
});
|
|
314
|
-
});
|
|
315
|
-
|
|
316
|
-
test('rejects when the worker script does not load', async () => {
|
|
317
|
-
await withWorker(async () => {
|
|
318
|
-
const threaded = createThreadedCompute({
|
|
319
|
-
url: fixture('missing'),
|
|
320
|
-
canRunTasks: ['echo']
|
|
321
|
-
});
|
|
322
|
-
|
|
323
|
-
await assert.rejects(
|
|
324
|
-
threaded.runTask('echo', 1),
|
|
325
|
-
isWorkerError(
|
|
326
|
-
/got no reply: the worker failed: its script did not load/
|
|
327
|
-
)
|
|
328
|
-
);
|
|
329
|
-
});
|
|
330
|
-
});
|
|
331
|
-
|
|
332
|
-
test('rejects with WorkerTaskError when the worker cannot be constructed', async () => {
|
|
333
|
-
await withWorker(async () => {
|
|
334
|
-
const threaded = createThreadedCompute({
|
|
335
|
-
url: './constructor-throws.js',
|
|
336
|
-
canRunTasks: ['echo']
|
|
337
|
-
});
|
|
338
|
-
|
|
339
|
-
await assert.rejects(
|
|
340
|
-
threaded.runTask('echo', 1),
|
|
341
|
-
isWorkerError(
|
|
342
|
-
/couldn't start the worker \.\/constructor-throws\.js/,
|
|
343
|
-
(error) => error.cause instanceof TypeError
|
|
344
|
-
)
|
|
345
|
-
);
|
|
346
|
-
});
|
|
347
|
-
});
|
|
348
|
-
|
|
349
|
-
test('rejects every waiting task on a messageerror, and keeps the worker', async () => {
|
|
350
|
-
await withWorker(async () => {
|
|
351
|
-
const threaded = raw();
|
|
352
|
-
const waiting = threaded.runTask('hang', 1);
|
|
353
|
-
|
|
354
|
-
await wait(20);
|
|
355
|
-
ThreadWorker.last?.dispatchEvent(new Event('messageerror'));
|
|
356
|
-
await assert.rejects(
|
|
357
|
-
waiting,
|
|
358
|
-
isWorkerError(/got no reply: a reply from the worker could not be read/)
|
|
359
|
-
);
|
|
360
|
-
assert.equal(await threaded.runTask('echo', 'kept'), 'kept');
|
|
361
|
-
threaded.close();
|
|
362
|
-
});
|
|
363
|
-
});
|
|
364
|
-
});
|
|
365
|
-
|
|
366
|
-
describe('timeout and cancelling', () => {
|
|
367
|
-
test('rejects when the timeout passes, and tells the worker to cancel', async () => {
|
|
368
|
-
await withWorker(async () => {
|
|
369
|
-
const threaded = exposed({ timeout: 100 });
|
|
370
|
-
|
|
371
|
-
await assert.rejects(
|
|
372
|
-
threaded.runTask('waitForAbort', 1),
|
|
373
|
-
isWorkerError(/^Worker task 'waitForAbort' timed out after 100 ms$/)
|
|
374
|
-
);
|
|
375
|
-
assert.equal(await threaded.runTask('abortedCount', null), 1);
|
|
376
|
-
threaded.close();
|
|
377
|
-
});
|
|
378
|
-
});
|
|
379
|
-
|
|
380
|
-
test('rejects with the reason when the signal aborts, and tells the worker to cancel', async () => {
|
|
381
|
-
await withWorker(async () => {
|
|
382
|
-
const threaded = exposed();
|
|
383
|
-
const controller = new AbortController();
|
|
384
|
-
const pending = threaded.runTask('waitForAbort', 1, {
|
|
385
|
-
signal: controller.signal
|
|
386
|
-
});
|
|
387
|
-
|
|
388
|
-
await wait(20);
|
|
389
|
-
controller.abort(new Error('cancelled'));
|
|
390
|
-
await assert.rejects(pending, /cancelled/);
|
|
391
|
-
assert.equal(await threaded.runTask('abortedCount', null), 1);
|
|
392
|
-
threaded.close();
|
|
393
|
-
});
|
|
394
|
-
});
|
|
395
|
-
|
|
396
|
-
test('rejects at once for a signal that has already aborted, without starting a worker', async () => {
|
|
397
|
-
await withWorker(async () => {
|
|
398
|
-
const before = ThreadWorker.started;
|
|
399
|
-
|
|
400
|
-
await assert.rejects(
|
|
401
|
-
exposed().runTask('echo', 1, {
|
|
402
|
-
signal: AbortSignal.abort(new Error('too late'))
|
|
403
|
-
}),
|
|
404
|
-
/too late/
|
|
405
|
-
);
|
|
406
|
-
assert.equal(ThreadWorker.started, before);
|
|
407
|
-
});
|
|
408
|
-
});
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
describe('close', () => {
|
|
412
|
-
test('rejects waiting tasks, and the next task starts a new worker', async () => {
|
|
413
|
-
await withWorker(async () => {
|
|
414
|
-
const threaded = raw();
|
|
415
|
-
const before = ThreadWorker.started;
|
|
416
|
-
const pending = threaded.runTask('hang', 1);
|
|
417
|
-
|
|
418
|
-
await wait(20);
|
|
419
|
-
|
|
420
|
-
const closed = ThreadWorker.last;
|
|
421
|
-
|
|
422
|
-
threaded.close();
|
|
423
|
-
await assert.rejects(
|
|
424
|
-
pending,
|
|
425
|
-
isWorkerError(/'hang' got no reply: the worker was closed/)
|
|
426
|
-
);
|
|
427
|
-
|
|
428
|
-
// Events from the closed worker no longer reach the backend
|
|
429
|
-
const next = threaded.runTask('hang', 2);
|
|
430
|
-
|
|
431
|
-
closed?.dispatchEvent(new Event('error'));
|
|
432
|
-
closed?.dispatchEvent(new Event('messageerror'));
|
|
433
|
-
assert.equal(await threaded.runTask('echo', 'new'), 'new');
|
|
434
|
-
assert.equal(ThreadWorker.started - before, 2);
|
|
435
|
-
threaded.close();
|
|
436
|
-
await assert.rejects(next, isWorkerError(/the worker was closed/));
|
|
437
|
-
});
|
|
438
|
-
});
|
|
439
|
-
|
|
440
|
-
test('does nothing before the first task', () => {
|
|
441
|
-
assert.doesNotThrow(() => exposed().close());
|
|
442
|
-
});
|
|
443
|
-
});
|
|
444
|
-
|
|
445
|
-
describe('createThreadedCompute', () => {
|
|
446
|
-
test('returns an instance of ThreadedCompute', () => {
|
|
447
|
-
assert.ok(exposed() instanceof ThreadedCompute);
|
|
448
|
-
});
|
|
449
|
-
});
|
package/src/errors.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Why a worker task failed: the worker script replied with an `error`, the
|
|
3
|
-
* reply was unusable, the worker crashed or couldn't start, the input couldn't
|
|
4
|
-
* be sent, the timeout passed, or the backend was closed.
|
|
5
|
-
*
|
|
6
|
-
* A task cancelled with an `AbortSignal` rejects with the signal's reason
|
|
7
|
-
* instead, so a `WorkerTaskError` always means something went wrong.
|
|
8
|
-
*
|
|
9
|
-
* @example
|
|
10
|
-
* ```ts
|
|
11
|
-
* try {
|
|
12
|
-
* await threaded.runTask('resizeImage', blob);
|
|
13
|
-
* } catch (error) {
|
|
14
|
-
* if (error instanceof WorkerTaskError) {
|
|
15
|
-
* console.warn(`${error.taskName} failed`, error.detail);
|
|
16
|
-
* }
|
|
17
|
-
* }
|
|
18
|
-
* ```
|
|
19
|
-
*/
|
|
20
|
-
export class WorkerTaskError extends Error {
|
|
21
|
-
/** The name of the task that failed. */
|
|
22
|
-
readonly taskName: string;
|
|
23
|
-
|
|
24
|
-
/** The worker script's `error` value as it was sent, if it sent one. */
|
|
25
|
-
readonly detail?: unknown;
|
|
26
|
-
|
|
27
|
-
/** The underlying error or event, such as a worker crash, if there is one. */
|
|
28
|
-
readonly cause?: unknown;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* @param taskName - The name of the task that failed.
|
|
32
|
-
* @param message - What went wrong.
|
|
33
|
-
* @param details - The worker script's error value and the underlying
|
|
34
|
-
* error, where there is one.
|
|
35
|
-
*/
|
|
36
|
-
constructor(
|
|
37
|
-
taskName: string,
|
|
38
|
-
message: string,
|
|
39
|
-
details: { detail?: unknown; cause?: unknown } = {}
|
|
40
|
-
) {
|
|
41
|
-
super(message);
|
|
42
|
-
this.name = 'WorkerTaskError';
|
|
43
|
-
this.taskName = taskName;
|
|
44
|
-
|
|
45
|
-
if (details.cause !== undefined) this.cause = details.cause;
|
|
46
|
-
|
|
47
|
-
if ('detail' in details) this.detail = details.detail;
|
|
48
|
-
}
|
|
49
|
-
}
|
package/src/expose.ts
DELETED
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
import type { WorkerScopeInterface, WorkerTaskType } from './types.js';
|
|
2
|
-
import { describeValue, isPlainObject } from './utils.js';
|
|
3
|
-
|
|
4
|
-
/** An error as a value the structured clone algorithm can copy. */
|
|
5
|
-
const toErrorValue = (error: unknown) => {
|
|
6
|
-
if (error instanceof Error)
|
|
7
|
-
return { name: error.name, message: error.message };
|
|
8
|
-
|
|
9
|
-
if (typeof error === 'string') return error;
|
|
10
|
-
|
|
11
|
-
return { message: String(error) };
|
|
12
|
-
};
|
|
13
|
-
/** The worker's global scope, or a TypeError outside a worker. */
|
|
14
|
-
const workerScope = (): WorkerScopeInterface => {
|
|
15
|
-
const scope = globalThis as unknown as Partial<WorkerScopeInterface>;
|
|
16
|
-
|
|
17
|
-
if (
|
|
18
|
-
!('WorkerGlobalScope' in globalThis) ||
|
|
19
|
-
typeof scope.addEventListener !== 'function' ||
|
|
20
|
-
typeof scope.postMessage !== 'function'
|
|
21
|
-
) {
|
|
22
|
-
throw new TypeError(
|
|
23
|
-
'exposeTasks must be called in a worker script, or be given a scope to listen on'
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
return scope as WorkerScopeInterface;
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Answers tasks from {@link ThreadedCompute} in a worker script: it listens
|
|
32
|
-
* for task messages, runs the task with that name, and replies with its
|
|
33
|
-
* result, or with an error if the task throws, rejects or doesn't exist.
|
|
34
|
-
*
|
|
35
|
-
* Each task gets the input and a context with a `signal`, which aborts when
|
|
36
|
-
* the caller cancels the task or its timeout passes. A task that checks the
|
|
37
|
-
* signal can stop early; its reply is then not sent.
|
|
38
|
-
*
|
|
39
|
-
* @param tasks - The tasks, by name. List the same names in `canRunTasks`.
|
|
40
|
-
* @param scope - Where to listen and reply. Defaults to the worker's global
|
|
41
|
-
* scope.
|
|
42
|
-
*
|
|
43
|
-
* @throws {TypeError} If `tasks` isn't an object of functions, or if it's
|
|
44
|
-
* called outside a worker without a `scope`.
|
|
45
|
-
*
|
|
46
|
-
* @example
|
|
47
|
-
* ```ts
|
|
48
|
-
* // worker.js
|
|
49
|
-
* import { exposeTasks } from '@hybrid-compute/worker';
|
|
50
|
-
*
|
|
51
|
-
* exposeTasks({
|
|
52
|
-
* double: (n: number) => n * 2,
|
|
53
|
-
* slowSum: async (numbers: number[], { signal }) => {
|
|
54
|
-
* let sum = 0;
|
|
55
|
-
*
|
|
56
|
-
* for (const n of numbers) {
|
|
57
|
-
* signal.throwIfAborted();
|
|
58
|
-
* sum += n;
|
|
59
|
-
* }
|
|
60
|
-
*
|
|
61
|
-
* return sum;
|
|
62
|
-
* }
|
|
63
|
-
* });
|
|
64
|
-
* ```
|
|
65
|
-
*/
|
|
66
|
-
export function exposeTasks(
|
|
67
|
-
tasks: Readonly<Record<string, WorkerTaskType>>,
|
|
68
|
-
scope?: WorkerScopeInterface
|
|
69
|
-
): void {
|
|
70
|
-
if (
|
|
71
|
-
!isPlainObject(tasks) ||
|
|
72
|
-
!Object.values(tasks).every((task) => typeof task === 'function')
|
|
73
|
-
) {
|
|
74
|
-
throw new TypeError(
|
|
75
|
-
`exposeTasks expects an object of task functions, got ${describeValue(tasks)}`
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const target = scope ?? workerScope();
|
|
80
|
-
const running = new Map<number, AbortController>();
|
|
81
|
-
const reply = (message: Record<string, unknown>) => {
|
|
82
|
-
try {
|
|
83
|
-
target.postMessage(message);
|
|
84
|
-
} catch (error) {
|
|
85
|
-
// A result the structured clone algorithm can't copy
|
|
86
|
-
target.postMessage({
|
|
87
|
-
id: message.id,
|
|
88
|
-
error: {
|
|
89
|
-
name: 'DataCloneError',
|
|
90
|
-
message: `the result couldn't be sent: ${error instanceof Error ? error.message : String(error)}`
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
};
|
|
95
|
-
const run = async (id: number, name: string, input: unknown) => {
|
|
96
|
-
const controller = new AbortController();
|
|
97
|
-
|
|
98
|
-
running.set(id, controller);
|
|
99
|
-
|
|
100
|
-
try {
|
|
101
|
-
if (!Object.prototype.hasOwnProperty.call(tasks, name)) {
|
|
102
|
-
throw new Error(`No task '${name}' in this worker`);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const result = await tasks[name](input as never, {
|
|
106
|
-
signal: controller.signal
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
if (!controller.signal.aborted) reply({ id, result });
|
|
110
|
-
} catch (error) {
|
|
111
|
-
if (!controller.signal.aborted) reply({ id, error: toErrorValue(error) });
|
|
112
|
-
} finally {
|
|
113
|
-
running.delete(id);
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
|
|
117
|
-
target.addEventListener('message', ({ data }) => {
|
|
118
|
-
if (!isPlainObject(data) || typeof data.id !== 'number') return;
|
|
119
|
-
|
|
120
|
-
if (data.cancel === true) {
|
|
121
|
-
running.get(data.id)?.abort();
|
|
122
|
-
|
|
123
|
-
return;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
if (typeof data.task !== 'string') return;
|
|
127
|
-
|
|
128
|
-
void run(data.id, data.task, data.input);
|
|
129
|
-
});
|
|
130
|
-
}
|