@x-otto/host-tasks 0.0.0-stage → 0.4.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build-revision.json +4 -0
- package/dist/index.d.ts +95 -0
- package/dist/index.js +547 -0
- package/package.json +20 -4
- package/README.md +0 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
type TaskEffect = 'none' | 'write';
|
|
3
|
+
type TaskFailureKind = 'timeout' | 'cancelled' | 'crash' | 'error' | 'rejected';
|
|
4
|
+
type TaskOutcome<Output> = {
|
|
5
|
+
ok: true;
|
|
6
|
+
output: Output;
|
|
7
|
+
durationMs: number;
|
|
8
|
+
} | {
|
|
9
|
+
ok: false;
|
|
10
|
+
kind: TaskFailureKind;
|
|
11
|
+
detail?: string;
|
|
12
|
+
durationMs: number;
|
|
13
|
+
};
|
|
14
|
+
interface TaskSpec<Input> {
|
|
15
|
+
name: string;
|
|
16
|
+
effect?: TaskEffect;
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
workerSource: string;
|
|
19
|
+
input?: Input;
|
|
20
|
+
}
|
|
21
|
+
interface TaskRunOptions {
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}
|
|
25
|
+
interface TaskPoolStats {
|
|
26
|
+
running: number;
|
|
27
|
+
queued: number;
|
|
28
|
+
queuedBytes?: number;
|
|
29
|
+
completed: number;
|
|
30
|
+
failed: number;
|
|
31
|
+
timedOut: number;
|
|
32
|
+
cancelled: number;
|
|
33
|
+
crashed: number;
|
|
34
|
+
}
|
|
35
|
+
interface TaskPoolOptions {
|
|
36
|
+
size?: number;
|
|
37
|
+
idleMs?: number;
|
|
38
|
+
onFailure?: (failure: {
|
|
39
|
+
name: string;
|
|
40
|
+
kind: TaskFailureKind;
|
|
41
|
+
detail?: string;
|
|
42
|
+
}) => void;
|
|
43
|
+
}
|
|
44
|
+
interface TaskPool {
|
|
45
|
+
run<Input, Output>(spec: TaskSpec<Input>, options?: TaskRunOptions): Promise<TaskOutcome<Output>>;
|
|
46
|
+
stats(): TaskPoolStats;
|
|
47
|
+
pendingWrites(): number;
|
|
48
|
+
whenIdle(): Promise<void>;
|
|
49
|
+
close(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
interface StallSentinelOptions {
|
|
52
|
+
thresholdMs?: number;
|
|
53
|
+
intervalMs?: number;
|
|
54
|
+
onStall: (stallMs: number) => void;
|
|
55
|
+
}
|
|
56
|
+
interface StallSentinel {
|
|
57
|
+
stop(): void;
|
|
58
|
+
maxStallMs(): number;
|
|
59
|
+
}
|
|
60
|
+
declare const HOST_MAIN_THREAD_STALL = "HOST_MAIN_THREAD_STALL";
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/pool.d.ts
|
|
63
|
+
declare function createTaskPool(options?: TaskPoolOptions): TaskPool;
|
|
64
|
+
declare function startStallSentinel(options: {
|
|
65
|
+
thresholdMs?: number;
|
|
66
|
+
intervalMs?: number;
|
|
67
|
+
onStall: (stallMs: number) => void;
|
|
68
|
+
}): {
|
|
69
|
+
stop(): void;
|
|
70
|
+
maxStallMs(): number;
|
|
71
|
+
};
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/process-pool.d.ts
|
|
74
|
+
interface ProcessPoolOptions {
|
|
75
|
+
size?: number;
|
|
76
|
+
drainTimeoutMs?: number;
|
|
77
|
+
onFailure?: (failure: {
|
|
78
|
+
name: string;
|
|
79
|
+
kind: string;
|
|
80
|
+
detail?: string;
|
|
81
|
+
}) => void;
|
|
82
|
+
}
|
|
83
|
+
interface ProcessPool {
|
|
84
|
+
run<Input, Output>(spec: TaskSpec<Input>, options?: TaskRunOptions): Promise<TaskOutcome<Output>>;
|
|
85
|
+
stats(): TaskPoolStats;
|
|
86
|
+
drain(timeoutMs?: number): Promise<boolean>;
|
|
87
|
+
close(): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
declare function createProcessPool(options?: ProcessPoolOptions): ProcessPool;
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/shared-pool.d.ts
|
|
92
|
+
declare function sharedTaskPool(): TaskPool;
|
|
93
|
+
declare function closeSharedTaskPool(): Promise<void>;
|
|
94
|
+
//#endregion
|
|
95
|
+
export { HOST_MAIN_THREAD_STALL, type ProcessPool, type ProcessPoolOptions, type StallSentinel, type StallSentinelOptions, type TaskEffect, type TaskFailureKind, type TaskOutcome, type TaskPool, type TaskPoolOptions, type TaskPoolStats, type TaskRunOptions, type TaskSpec, closeSharedTaskPool, createProcessPool, createTaskPool, sharedTaskPool, startStallSentinel };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
|
|
4
|
+
//#region src/queue-bytes.ts
|
|
5
|
+
function taskBytesOf(body, input) {
|
|
6
|
+
if (input === void 0) return body.length;
|
|
7
|
+
try {
|
|
8
|
+
return body.length + JSON.stringify(input).length;
|
|
9
|
+
} catch {
|
|
10
|
+
return body.length;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/pool.ts
|
|
16
|
+
const DEFAULT_POOL_SIZE = 4;
|
|
17
|
+
const DEFAULT_TIMEOUT_MS$1 = 3e4;
|
|
18
|
+
const DEFAULT_IDLE_MS = 5e3;
|
|
19
|
+
function createTaskPool(options = {}) {
|
|
20
|
+
const size = Math.max(1, options.size ?? DEFAULT_POOL_SIZE);
|
|
21
|
+
const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
|
|
22
|
+
const queue = [];
|
|
23
|
+
let slots = [];
|
|
24
|
+
const stats = {
|
|
25
|
+
running: 0,
|
|
26
|
+
queued: 0,
|
|
27
|
+
completed: 0,
|
|
28
|
+
failed: 0,
|
|
29
|
+
timedOut: 0,
|
|
30
|
+
cancelled: 0,
|
|
31
|
+
crashed: 0
|
|
32
|
+
};
|
|
33
|
+
const idleWaiters = [];
|
|
34
|
+
const writeDrainWaiters = [];
|
|
35
|
+
let nextId = 0;
|
|
36
|
+
let isClosed = false;
|
|
37
|
+
let pendingWrites = 0;
|
|
38
|
+
let idleTimer;
|
|
39
|
+
const runningCount = () => slots.filter((slot) => slot.job !== void 0).length;
|
|
40
|
+
const drainWrites = (budgetMs) => {
|
|
41
|
+
if (pendingWrites === 0) return Promise.resolve();
|
|
42
|
+
return new Promise((resolve) => {
|
|
43
|
+
const timer = setTimeout(() => {
|
|
44
|
+
resolve();
|
|
45
|
+
}, budgetMs);
|
|
46
|
+
const done = () => {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
resolve();
|
|
49
|
+
};
|
|
50
|
+
writeDrainWaiters.push(done);
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
const refreshIdleTimer = () => {
|
|
54
|
+
if (idleTimer !== void 0) clearTimeout(idleTimer);
|
|
55
|
+
idleTimer = setTimeout(() => {
|
|
56
|
+
idleTimer = void 0;
|
|
57
|
+
if (runningCount() > 0 || queue.length > 0 || isClosed) return;
|
|
58
|
+
for (const slot of slots.slice()) slot.retire();
|
|
59
|
+
}, idleMs);
|
|
60
|
+
idleTimer.unref?.();
|
|
61
|
+
};
|
|
62
|
+
const checkIdle = () => {
|
|
63
|
+
if (runningCount() > 0 || queue.length > 0) return;
|
|
64
|
+
for (const waiter of idleWaiters.splice(0)) waiter();
|
|
65
|
+
refreshIdleTimer();
|
|
66
|
+
};
|
|
67
|
+
const settle = (job, outcome) => {
|
|
68
|
+
if (job.settled) return;
|
|
69
|
+
job.settled = true;
|
|
70
|
+
if (job.timer !== void 0) {
|
|
71
|
+
clearTimeout(job.timer);
|
|
72
|
+
job.timer = void 0;
|
|
73
|
+
}
|
|
74
|
+
job.detachAbort?.();
|
|
75
|
+
job.detachAbort = void 0;
|
|
76
|
+
if (job.slot !== void 0) {
|
|
77
|
+
const slot = job.slot;
|
|
78
|
+
if (slot.job === job) slot.job = void 0;
|
|
79
|
+
if (outcome.ok) stats.completed += 1;
|
|
80
|
+
else {
|
|
81
|
+
stats.failed += 1;
|
|
82
|
+
if (outcome.kind === "timeout") stats.timedOut += 1;
|
|
83
|
+
if (outcome.kind === "cancelled") stats.cancelled += 1;
|
|
84
|
+
if (outcome.kind === "crash") stats.crashed += 1;
|
|
85
|
+
if (outcome.kind === "crash" || outcome.kind === "timeout" || outcome.kind === "cancelled") slot.retire();
|
|
86
|
+
options.onFailure?.({
|
|
87
|
+
name: job.name,
|
|
88
|
+
kind: outcome.kind,
|
|
89
|
+
...outcome.detail === void 0 ? {} : { detail: outcome.detail }
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
if (job.effect === "write") {
|
|
93
|
+
pendingWrites = Math.max(0, pendingWrites - 1);
|
|
94
|
+
if (pendingWrites === 0) for (const waiter of writeDrainWaiters.splice(0)) waiter();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
job.resolve(outcome);
|
|
98
|
+
drain();
|
|
99
|
+
checkIdle();
|
|
100
|
+
};
|
|
101
|
+
const drain = () => {
|
|
102
|
+
if (isClosed) return;
|
|
103
|
+
while (queue.length > 0) {
|
|
104
|
+
const slot = freeSlot();
|
|
105
|
+
if (slot === void 0) break;
|
|
106
|
+
start(slot, queue.shift());
|
|
107
|
+
}
|
|
108
|
+
stats.queued = queue.length;
|
|
109
|
+
stats.running = runningCount();
|
|
110
|
+
};
|
|
111
|
+
const freeSlot = () => {
|
|
112
|
+
const existing = slots.find((slot) => slot.job === void 0);
|
|
113
|
+
if (existing !== void 0) return existing;
|
|
114
|
+
return slots.length < size ? createSlot() : void 0;
|
|
115
|
+
};
|
|
116
|
+
const start = (slot, job) => {
|
|
117
|
+
job.slot = slot;
|
|
118
|
+
job.startedAt = performance.now();
|
|
119
|
+
slot.job = job;
|
|
120
|
+
if (job.effect === "write") pendingWrites += 1;
|
|
121
|
+
if (job.signal?.aborted === true) {
|
|
122
|
+
settle(job, {
|
|
123
|
+
ok: false,
|
|
124
|
+
kind: "cancelled",
|
|
125
|
+
durationMs: 0
|
|
126
|
+
});
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (job.signal !== void 0) {
|
|
130
|
+
const signal = job.signal;
|
|
131
|
+
const onAbort = () => {
|
|
132
|
+
settle(job, {
|
|
133
|
+
ok: false,
|
|
134
|
+
kind: "cancelled",
|
|
135
|
+
durationMs: performance.now() - job.startedAt
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
139
|
+
job.detachAbort = () => signal.removeEventListener("abort", onAbort);
|
|
140
|
+
}
|
|
141
|
+
if (job.timeoutMs > 0) {
|
|
142
|
+
job.timer = setTimeout(() => {
|
|
143
|
+
settle(job, {
|
|
144
|
+
ok: false,
|
|
145
|
+
kind: "timeout",
|
|
146
|
+
detail: `timed out after ${String(job.timeoutMs)}ms`,
|
|
147
|
+
durationMs: performance.now() - job.startedAt
|
|
148
|
+
});
|
|
149
|
+
}, job.timeoutMs);
|
|
150
|
+
job.timer.unref?.();
|
|
151
|
+
}
|
|
152
|
+
slot.worker.postMessage({
|
|
153
|
+
id: job.id,
|
|
154
|
+
body: job.body,
|
|
155
|
+
input: job.input
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
const createSlot = () => {
|
|
159
|
+
const worker = new Worker(WORKER_SOURCE, { eval: true });
|
|
160
|
+
worker.unref();
|
|
161
|
+
const slot = {
|
|
162
|
+
worker,
|
|
163
|
+
job: void 0,
|
|
164
|
+
retire() {
|
|
165
|
+
worker.removeAllListeners();
|
|
166
|
+
worker.terminate();
|
|
167
|
+
slots = slots.filter((entry) => entry !== slot);
|
|
168
|
+
slot.job = void 0;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
worker.on("message", (message) => {
|
|
172
|
+
const job = slot.job;
|
|
173
|
+
if (job === void 0 || message.id !== job.id) return;
|
|
174
|
+
settle(job, message.ok === true ? {
|
|
175
|
+
ok: true,
|
|
176
|
+
output: message.output,
|
|
177
|
+
durationMs: performance.now() - job.startedAt
|
|
178
|
+
} : {
|
|
179
|
+
ok: false,
|
|
180
|
+
kind: "error",
|
|
181
|
+
detail: message.error ?? "task failed",
|
|
182
|
+
durationMs: performance.now() - job.startedAt
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
worker.on("error", (error) => {
|
|
186
|
+
const job = slot.job;
|
|
187
|
+
if (job !== void 0) settle(job, {
|
|
188
|
+
ok: false,
|
|
189
|
+
kind: "crash",
|
|
190
|
+
detail: String(error),
|
|
191
|
+
durationMs: performance.now() - job.startedAt
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
worker.on("exit", (code) => {
|
|
195
|
+
const job = slot.job;
|
|
196
|
+
slots = slots.filter((entry) => entry !== slot);
|
|
197
|
+
if (job !== void 0) settle(job, {
|
|
198
|
+
ok: false,
|
|
199
|
+
kind: "crash",
|
|
200
|
+
detail: `worker exited with code ${String(code)}`,
|
|
201
|
+
durationMs: performance.now() - job.startedAt
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
slots.push(slot);
|
|
205
|
+
return slot;
|
|
206
|
+
};
|
|
207
|
+
refreshIdleTimer();
|
|
208
|
+
return {
|
|
209
|
+
run(spec, runOptions = {}) {
|
|
210
|
+
if (isClosed) return Promise.resolve({
|
|
211
|
+
ok: false,
|
|
212
|
+
kind: "rejected",
|
|
213
|
+
detail: "pool closed",
|
|
214
|
+
durationMs: 0
|
|
215
|
+
});
|
|
216
|
+
const job = {
|
|
217
|
+
id: nextId += 1,
|
|
218
|
+
name: spec.name,
|
|
219
|
+
effect: spec.effect ?? "none",
|
|
220
|
+
body: spec.workerSource,
|
|
221
|
+
bytes: taskBytesOf(spec.workerSource, spec.input),
|
|
222
|
+
timeoutMs: runOptions.timeoutMs ?? spec.timeoutMs ?? DEFAULT_TIMEOUT_MS$1,
|
|
223
|
+
input: spec.input,
|
|
224
|
+
signal: runOptions.signal,
|
|
225
|
+
startedAt: 0,
|
|
226
|
+
timer: void 0,
|
|
227
|
+
slot: void 0,
|
|
228
|
+
settled: false,
|
|
229
|
+
detachAbort: void 0,
|
|
230
|
+
resolve: () => void 0
|
|
231
|
+
};
|
|
232
|
+
return new Promise((resolve) => {
|
|
233
|
+
job.resolve = (outcome) => resolve(outcome);
|
|
234
|
+
queue.push(job);
|
|
235
|
+
stats.queued = queue.length;
|
|
236
|
+
drain();
|
|
237
|
+
});
|
|
238
|
+
},
|
|
239
|
+
stats() {
|
|
240
|
+
return {
|
|
241
|
+
...stats,
|
|
242
|
+
queued: queue.length,
|
|
243
|
+
queuedBytes: queue.reduce((total, job) => total + job.bytes, 0),
|
|
244
|
+
running: runningCount()
|
|
245
|
+
};
|
|
246
|
+
},
|
|
247
|
+
pendingWrites() {
|
|
248
|
+
return pendingWrites;
|
|
249
|
+
},
|
|
250
|
+
whenIdle() {
|
|
251
|
+
if (runningCount() === 0 && queue.length === 0) return Promise.resolve();
|
|
252
|
+
return new Promise((resolve) => {
|
|
253
|
+
idleWaiters.push(resolve);
|
|
254
|
+
});
|
|
255
|
+
},
|
|
256
|
+
async close() {
|
|
257
|
+
if (isClosed) {
|
|
258
|
+
await drainWrites(WRITE_DRAIN_BUDGET_MS);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
isClosed = true;
|
|
262
|
+
if (idleTimer !== void 0) {
|
|
263
|
+
clearTimeout(idleTimer);
|
|
264
|
+
idleTimer = void 0;
|
|
265
|
+
}
|
|
266
|
+
for (const job of queue.splice(0)) job.resolve({
|
|
267
|
+
ok: false,
|
|
268
|
+
kind: "cancelled",
|
|
269
|
+
detail: "pool closed",
|
|
270
|
+
durationMs: 0
|
|
271
|
+
});
|
|
272
|
+
await drainWrites(WRITE_DRAIN_BUDGET_MS);
|
|
273
|
+
for (const slot of slots.slice()) {
|
|
274
|
+
const job = slot.job;
|
|
275
|
+
if (job !== void 0) settle(job, {
|
|
276
|
+
ok: false,
|
|
277
|
+
kind: "cancelled",
|
|
278
|
+
detail: "pool closed",
|
|
279
|
+
durationMs: 0
|
|
280
|
+
});
|
|
281
|
+
slot.retire();
|
|
282
|
+
}
|
|
283
|
+
pendingWrites = 0;
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
const WRITE_DRAIN_BUDGET_MS = 2e3;
|
|
288
|
+
const WORKER_SOURCE = [
|
|
289
|
+
"const { parentPort } = require('node:worker_threads')",
|
|
290
|
+
"parentPort.on(\"message\", (message) => {",
|
|
291
|
+
" const fn = new Function(\"input\", \"return (async () => {\" + message.body + \"\\n})()\")",
|
|
292
|
+
" Promise.resolve()",
|
|
293
|
+
" .then(() => fn(message.input))",
|
|
294
|
+
" .then((output) => parentPort.postMessage({ id: message.id, ok: true, output }))",
|
|
295
|
+
" .catch((error) => parentPort.postMessage({ id: message.id, ok: false, error: String(error && error.message ? error.message : error) }))",
|
|
296
|
+
"})"
|
|
297
|
+
].join("\n");
|
|
298
|
+
function startStallSentinel(options) {
|
|
299
|
+
const thresholdMs = options.thresholdMs ?? 200;
|
|
300
|
+
const intervalMs = options.intervalMs ?? 50;
|
|
301
|
+
let last = performance.now();
|
|
302
|
+
let maxStall = 0;
|
|
303
|
+
const timer = setInterval(() => {
|
|
304
|
+
const now = performance.now();
|
|
305
|
+
const stall = now - last - intervalMs;
|
|
306
|
+
last = now;
|
|
307
|
+
if (stall > thresholdMs) {
|
|
308
|
+
maxStall = Math.max(maxStall, stall);
|
|
309
|
+
options.onStall(stall);
|
|
310
|
+
}
|
|
311
|
+
}, intervalMs);
|
|
312
|
+
timer.unref?.();
|
|
313
|
+
return {
|
|
314
|
+
stop() {
|
|
315
|
+
clearInterval(timer);
|
|
316
|
+
},
|
|
317
|
+
maxStallMs() {
|
|
318
|
+
return maxStall;
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
//#endregion
|
|
324
|
+
//#region src/process-pool.ts
|
|
325
|
+
const DEFAULT_SIZE = 2;
|
|
326
|
+
const DEFAULT_TIMEOUT_MS = 6e4;
|
|
327
|
+
const DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
|
|
328
|
+
const CHILD_SOURCE = [
|
|
329
|
+
"const body = process.argv[1]",
|
|
330
|
+
"process.on(\"message\", (message) => {",
|
|
331
|
+
" const fn = new Function(\"input\", \"return (async () => {\" + message.body + \"\\n})()\")",
|
|
332
|
+
" Promise.resolve()",
|
|
333
|
+
" .then(() => fn(message.input))",
|
|
334
|
+
" .then((output) => process.send({ id: message.id, ok: true, output }))",
|
|
335
|
+
" .catch((error) => process.send({ id: message.id, ok: false, error: String(error && error.message ? error.message : error) }))",
|
|
336
|
+
"})",
|
|
337
|
+
"void body"
|
|
338
|
+
].join("\n");
|
|
339
|
+
function createProcessPool(options = {}) {
|
|
340
|
+
const size = Math.max(1, options.size ?? DEFAULT_SIZE);
|
|
341
|
+
const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;
|
|
342
|
+
const children = [];
|
|
343
|
+
const queue = [];
|
|
344
|
+
const stats = {
|
|
345
|
+
running: 0,
|
|
346
|
+
queued: 0,
|
|
347
|
+
completed: 0,
|
|
348
|
+
failed: 0,
|
|
349
|
+
timedOut: 0,
|
|
350
|
+
cancelled: 0,
|
|
351
|
+
crashed: 0
|
|
352
|
+
};
|
|
353
|
+
const inFlight = /* @__PURE__ */ new Map();
|
|
354
|
+
const idleWaiters = [];
|
|
355
|
+
let nextId = 0;
|
|
356
|
+
let isClosed = false;
|
|
357
|
+
const runningCount = () => inFlight.size;
|
|
358
|
+
const spawnChild = () => {
|
|
359
|
+
const child = spawn(process.execPath, ["-e", CHILD_SOURCE], { stdio: [
|
|
360
|
+
"ignore",
|
|
361
|
+
"ignore",
|
|
362
|
+
"ignore",
|
|
363
|
+
"ipc"
|
|
364
|
+
] });
|
|
365
|
+
child.unref();
|
|
366
|
+
child.channel?.unref?.();
|
|
367
|
+
child.on("message", (message) => {
|
|
368
|
+
const job = inFlight.get(child);
|
|
369
|
+
if (job === void 0 || message.id !== job.id) return;
|
|
370
|
+
settle(child, job, message.ok === true ? {
|
|
371
|
+
ok: true,
|
|
372
|
+
output: message.output,
|
|
373
|
+
durationMs: performance.now() - job.startedAt
|
|
374
|
+
} : {
|
|
375
|
+
ok: false,
|
|
376
|
+
kind: "error",
|
|
377
|
+
detail: message.error ?? "task failed",
|
|
378
|
+
durationMs: performance.now() - job.startedAt
|
|
379
|
+
});
|
|
380
|
+
});
|
|
381
|
+
child.on("exit", (code, signal) => {
|
|
382
|
+
const job = inFlight.get(child);
|
|
383
|
+
if (job !== void 0) settle(child, job, {
|
|
384
|
+
ok: false,
|
|
385
|
+
kind: "crash",
|
|
386
|
+
detail: signal === null ? `child exited with code ${String(code)}` : `child killed by ${signal}`,
|
|
387
|
+
durationMs: performance.now() - job.startedAt
|
|
388
|
+
});
|
|
389
|
+
const index = children.indexOf(child);
|
|
390
|
+
if (index >= 0) children.splice(index, 1);
|
|
391
|
+
drain();
|
|
392
|
+
});
|
|
393
|
+
children.push(child);
|
|
394
|
+
return child;
|
|
395
|
+
};
|
|
396
|
+
const settle = (child, job, outcome) => {
|
|
397
|
+
if (job.settled) return;
|
|
398
|
+
job.settled = true;
|
|
399
|
+
if (job.timer !== void 0) {
|
|
400
|
+
clearTimeout(job.timer);
|
|
401
|
+
job.timer = void 0;
|
|
402
|
+
}
|
|
403
|
+
if (inFlight.get(child) === job) inFlight.delete(child);
|
|
404
|
+
stats.running = runningCount();
|
|
405
|
+
if (inFlight.size === 0) for (const waiter of idleWaiters.splice(0)) waiter();
|
|
406
|
+
if (outcome.ok) stats.completed += 1;
|
|
407
|
+
else {
|
|
408
|
+
stats.failed += 1;
|
|
409
|
+
if (outcome.kind === "timeout") stats.timedOut += 1;
|
|
410
|
+
if (outcome.kind === "cancelled") stats.cancelled += 1;
|
|
411
|
+
if (outcome.kind === "crash") stats.crashed += 1;
|
|
412
|
+
options.onFailure?.({
|
|
413
|
+
name: job.name,
|
|
414
|
+
kind: outcome.kind,
|
|
415
|
+
...outcome.detail === void 0 ? {} : { detail: outcome.detail }
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
job.resolve(outcome);
|
|
419
|
+
if (!outcome.ok && (outcome.kind === "timeout" || outcome.kind === "cancelled" || outcome.kind === "crash")) try {
|
|
420
|
+
child.kill("SIGKILL");
|
|
421
|
+
} catch {}
|
|
422
|
+
drain();
|
|
423
|
+
};
|
|
424
|
+
const drain = () => {
|
|
425
|
+
if (isClosed) return;
|
|
426
|
+
while (queue.length > 0) {
|
|
427
|
+
const free = children.filter((child) => !inFlight.has(child));
|
|
428
|
+
if (free.length === 0 && children.length >= size) break;
|
|
429
|
+
start(free[0] ?? spawnChild(), queue.shift());
|
|
430
|
+
}
|
|
431
|
+
stats.queued = queue.length;
|
|
432
|
+
};
|
|
433
|
+
const start = (child, job) => {
|
|
434
|
+
job.startedAt = performance.now();
|
|
435
|
+
inFlight.set(child, job);
|
|
436
|
+
stats.running = runningCount();
|
|
437
|
+
job.timer = setTimeout(() => {
|
|
438
|
+
settle(child, job, {
|
|
439
|
+
ok: false,
|
|
440
|
+
kind: "timeout",
|
|
441
|
+
detail: `timed out after ${String(job.timeoutMs)}ms`,
|
|
442
|
+
durationMs: performance.now() - job.startedAt
|
|
443
|
+
});
|
|
444
|
+
}, job.timeoutMs);
|
|
445
|
+
job.timer.unref?.();
|
|
446
|
+
child.send({
|
|
447
|
+
id: job.id,
|
|
448
|
+
body: job.body,
|
|
449
|
+
input: job.input
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
return {
|
|
453
|
+
run(spec, runOptions = {}) {
|
|
454
|
+
if (isClosed) return Promise.resolve({
|
|
455
|
+
ok: false,
|
|
456
|
+
kind: "rejected",
|
|
457
|
+
detail: "process pool closed",
|
|
458
|
+
durationMs: 0
|
|
459
|
+
});
|
|
460
|
+
const job = {
|
|
461
|
+
id: nextId += 1,
|
|
462
|
+
name: spec.name,
|
|
463
|
+
body: spec.workerSource,
|
|
464
|
+
bytes: taskBytesOf(spec.workerSource, spec.input),
|
|
465
|
+
input: spec.input,
|
|
466
|
+
timeoutMs: runOptions.timeoutMs ?? spec.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
467
|
+
startedAt: 0,
|
|
468
|
+
settled: false,
|
|
469
|
+
timer: void 0,
|
|
470
|
+
resolve: () => void 0
|
|
471
|
+
};
|
|
472
|
+
return new Promise((resolve) => {
|
|
473
|
+
job.resolve = (outcome) => resolve(outcome);
|
|
474
|
+
if (runOptions.signal?.aborted === true) {
|
|
475
|
+
resolve({
|
|
476
|
+
ok: false,
|
|
477
|
+
kind: "cancelled",
|
|
478
|
+
durationMs: 0
|
|
479
|
+
});
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
queue.push(job);
|
|
483
|
+
stats.queued = queue.length;
|
|
484
|
+
drain();
|
|
485
|
+
});
|
|
486
|
+
},
|
|
487
|
+
stats() {
|
|
488
|
+
return {
|
|
489
|
+
...stats,
|
|
490
|
+
queued: queue.length,
|
|
491
|
+
queuedBytes: queue.reduce((total, job) => total + job.bytes, 0),
|
|
492
|
+
running: runningCount()
|
|
493
|
+
};
|
|
494
|
+
},
|
|
495
|
+
async drain(timeout) {
|
|
496
|
+
if (inFlight.size === 0) return true;
|
|
497
|
+
await Promise.race([new Promise((resolve) => idleWaiters.push(resolve)), new Promise((resolve) => setTimeout(resolve, timeout ?? drainTimeoutMs))]);
|
|
498
|
+
return inFlight.size === 0;
|
|
499
|
+
},
|
|
500
|
+
async close() {
|
|
501
|
+
isClosed = true;
|
|
502
|
+
for (const job of queue.splice(0)) job.resolve({
|
|
503
|
+
ok: false,
|
|
504
|
+
kind: "cancelled",
|
|
505
|
+
detail: "process pool closed",
|
|
506
|
+
durationMs: 0
|
|
507
|
+
});
|
|
508
|
+
for (const job of inFlight.values()) job.resolve({
|
|
509
|
+
ok: false,
|
|
510
|
+
kind: "cancelled",
|
|
511
|
+
detail: "process pool closed",
|
|
512
|
+
durationMs: 0
|
|
513
|
+
});
|
|
514
|
+
for (const child of children) try {
|
|
515
|
+
child.kill("SIGKILL");
|
|
516
|
+
} catch {}
|
|
517
|
+
inFlight.clear();
|
|
518
|
+
children.length = 0;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
//#endregion
|
|
524
|
+
//#region src/shared-pool.ts
|
|
525
|
+
const SHARED_POOL_KEY = Symbol.for("@x-otto/host-tasks/shared");
|
|
526
|
+
const SHARED_POOL_OPTIONS = {
|
|
527
|
+
size: 2,
|
|
528
|
+
idleMs: 1e4
|
|
529
|
+
};
|
|
530
|
+
function sharedTaskPool() {
|
|
531
|
+
const holder = globalThis;
|
|
532
|
+
holder[SHARED_POOL_KEY] ??= createTaskPool(SHARED_POOL_OPTIONS);
|
|
533
|
+
return holder[SHARED_POOL_KEY];
|
|
534
|
+
}
|
|
535
|
+
async function closeSharedTaskPool() {
|
|
536
|
+
const holder = globalThis;
|
|
537
|
+
const pool = holder[SHARED_POOL_KEY];
|
|
538
|
+
holder[SHARED_POOL_KEY] = void 0;
|
|
539
|
+
await pool?.close();
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
//#endregion
|
|
543
|
+
//#region src/types.ts
|
|
544
|
+
const HOST_MAIN_THREAD_STALL = "HOST_MAIN_THREAD_STALL";
|
|
545
|
+
|
|
546
|
+
//#endregion
|
|
547
|
+
export { HOST_MAIN_THREAD_STALL, closeSharedTaskPool, createProcessPool, createTaskPool, sharedTaskPool, startStallSentinel };
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x-otto/host-tasks",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0-beta.0",
|
|
4
|
+
"description": "单进程内的统一后台执行端口:pool lane(线程池,按任务限并发)+ 超时/取消/崩溃分类 + effect 语义(是否计入排空)+ 主线程卡顿哨兵",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public",
|
|
20
|
+
"tag": "beta"
|
|
21
|
+
}
|
|
22
|
+
}
|
package/README.md
DELETED