/ proof-of-concept / instrawave-compose
Sign in
proof-of-concept / instrawave-compose
instrawave-compose / src / numbl / client.ts
36 lines · 1.3 KBCodeBlameHistory
2 * worker each time so a hung custom algorithm dies with its worker when
3 * the next classification starts. */
4import type { ClfRequest, ClfResponse } from './algo.worker.ts';
5import type { Detection, TrainingArrays } from './types.ts';
7let current: Worker | null = null;
8let nextId = 1;
10export function classifyInWorker(
11 source: string,
12 x: Float32Array,
13 fs: number,
14 training: TrainingArrays,
15): Promise<{ detections: Detection[]; logs: string[] }> {
16 current?.terminate();
17 const worker = new Worker(new URL('./algo.worker.ts', import.meta.url), { type: 'module' });
18 current = worker;
19 const id = nextId++;
20 const req: ClfRequest = { id, source, x, fs, training };
21 return new Promise((resolve, reject) => {
22 worker.onmessage = (e: MessageEvent<ClfResponse>) => {
23 if (e.data.id !== id) return;
24 worker.terminate();
25 if (current === worker) current = null;
26 if (e.data.ok && e.data.detections) resolve({ detections: e.data.detections, logs: e.data.logs });
27 else reject(new Error(e.data.error ?? 'classifier failed'));
28 };
29 worker.onerror = (e) => {
30 worker.terminate();
31 if (current === worker) current = null;
32 reject(new Error(e.message || 'classifier worker failed'));
33 };
34 worker.postMessage(req);
35 });
↑↓ move↵openescclose