wuica-cli 0.0.0-stage → 0.1.7
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/LICENSE +661 -0
- package/README.md +436 -2
- package/bin/wuica-mcp.js +16 -0
- package/bin/wuica.js +25 -0
- package/dist/data/arch/ADL-P.json.br +0 -0
- package/dist/data/arch/BDW.json.br +0 -0
- package/dist/data/arch/CFL.json.br +0 -0
- package/dist/data/arch/CLX.json.br +0 -0
- package/dist/data/arch/HSW.json.br +0 -0
- package/dist/data/arch/ICL.json.br +0 -0
- package/dist/data/arch/ICX.json.br +0 -0
- package/dist/data/arch/IVB.json.br +0 -0
- package/dist/data/arch/KBL.json.br +0 -0
- package/dist/data/arch/RKL.json.br +0 -0
- package/dist/data/arch/SKL.json.br +0 -0
- package/dist/data/arch/SKX.json.br +0 -0
- package/dist/data/arch/SNB.json.br +0 -0
- package/dist/data/arch/TGL.json.br +0 -0
- package/dist/data/arch/ZEN3.json.br +0 -0
- package/dist/data/uarch.json.br +0 -0
- package/dist/manifest.json +81 -0
- package/dist/wuica_asm.wasm.br +0 -0
- package/dist/wuica_wasm.wasm.br +0 -0
- package/index.d.ts +372 -0
- package/lib/archs.js +44 -0
- package/lib/cli.js +430 -0
- package/lib/core.js +36 -0
- package/lib/details.js +60 -0
- package/lib/files.js +18 -0
- package/lib/index.js +474 -0
- package/lib/insights.js +100 -0
- package/lib/mcp.js +366 -0
- package/lib/thread-worker.js +46 -0
- package/lib/threads.js +224 -0
- package/lib/wasm.js +221 -0
- package/lib/web/accum.js +202 -0
- package/lib/web/asm-regions.js +415 -0
- package/lib/web/assembler.js +188 -0
- package/lib/web/caveats.js +206 -0
- package/lib/web/loop-find.js +492 -0
- package/lib/whatif.js +136 -0
- package/licenses/LICENSE-LLVM.txt +279 -0
- package/licenses/LICENSE-XED.txt +178 -0
- package/package.json +58 -4
package/lib/mcp.js
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// The MCP tools of wuica as plain data (one definition for the stdio server here and the HTTP server in server/): name,
|
|
2
|
+
// title, description, input JSON Schema, annotations and the handler; a small JSON Schema validator for exactly the
|
|
3
|
+
// keywords these schemas use; and the stdio server (`wuica mcp`, `wuica-mcp`): newline-delimited JSON-RPC 2.0 on
|
|
4
|
+
// stdin/stdout, no dependencies. stdout carries protocol messages only.
|
|
5
|
+
//
|
|
6
|
+
// Protocol: the initialize handshake of the MCP revisions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05 (the
|
|
7
|
+
// client's version if it is one of these, else the latest); ping; tools/list; tools/call. JSON-RPC batches (arrays) only
|
|
8
|
+
// under 2025-03-26, the one revision that has them. Notifications get no reply. The process ends at the end of stdin.
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import readline from 'node:readline';
|
|
12
|
+
import { createWuica } from './index.js';
|
|
13
|
+
import { whatIf, VARIANTS } from './whatif.js';
|
|
14
|
+
|
|
15
|
+
const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
16
|
+
|
|
17
|
+
export const PROTOCOL_VERSIONS = Object.freeze(['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']);
|
|
18
|
+
export const SERVER_INFO = Object.freeze({ name: 'wuica', version: pkg.version });
|
|
19
|
+
export const CAPABILITIES = Object.freeze({ tools: { listChanged: true } });
|
|
20
|
+
|
|
21
|
+
const ASSUMPTIONS =
|
|
22
|
+
'The number is the predicted steady-state throughput in core clock cycles per iteration of the block: a block that ends ' +
|
|
23
|
+
'with a (conditional) branch is simulated as a loop body; any other block as if it were unrolled, i.e. repeated back to ' +
|
|
24
|
+
'back. Lower is faster. Assumptions: all memory accesses hit the L1 data cache, no branch mispredictions, no ' +
|
|
25
|
+
'interference from other code or hyperthreads; the result does not depend on register or memory values except through ' +
|
|
26
|
+
'dependencies. ZEN3, ADL-P and ICX are prototype models (experimental, from the fork jtl06/uiCA), less validated than ' +
|
|
27
|
+
"uiCA's Intel models (SNB through RKL).";
|
|
28
|
+
|
|
29
|
+
const INPUT_NOTE =
|
|
30
|
+
'Give the block either as `source` (x86-64 assembly in Intel (noprefix) or AT&T syntax: detected unless `syntax` says; one instruction per ' +
|
|
31
|
+
'line; labels and directives are allowed, e.g. "loop: add rax, [rsi]\\n dec rcx\\n jnz loop") or as `hex` (machine ' +
|
|
32
|
+
'code bytes, e.g. "4801d8"). A whole function (gcc -S or clang -S output, objdump -d lines with addresses, with or ' +
|
|
33
|
+
'without the bytes) is fine: by default (`loop: "auto"`) its innermost loop is analyzed (the first one in the code), ' +
|
|
34
|
+
'or the body without prologue and epilogue if it is a compiler\'s function without a loop; the deepest loop is ' +
|
|
35
|
+
'preferred (clang\'s "Inner Loop Header" notes count), among equals the first; branches out of the loop count as not taken (so an exit ' +
|
|
36
|
+
'to a label that is not in the text assembles); with addresses, the alignment offset is the loop\'s address mod 64 ' +
|
|
37
|
+
'unless options.alignmentOffset is given. The response\'s `loop` says what was analyzed (index, count, name, lines, ' +
|
|
38
|
+
'address, function, depth). `loop: "whole"` analyzes the whole text; `loop: N` the N-th loop (0-based: deepest first, ' +
|
|
39
|
+
'then in code order); `loop: ".LBB0_12"` a loop by its label; `func: "name"` only the loops of that function.';
|
|
40
|
+
|
|
41
|
+
const ERRORS_NOTE =
|
|
42
|
+
'Failures are tool errors whose JSON is {code, error, stderr}: code 1 = bad request (e.g. unknown arch, bad hex), ' +
|
|
43
|
+
'2 = assembler error (stderr lines as llvm-mc prints them; positioned ones carry tag {line, column, severity, text}), ' +
|
|
44
|
+
'3 = the analysis failed for this input.';
|
|
45
|
+
|
|
46
|
+
// ---- the input schemas (JSON Schema, draft-07 as before) ----------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
const SCHEMA = 'http://json-schema.org/draft-07/schema#';
|
|
49
|
+
const obj = (properties, required = []) => ({ type: 'object', properties, ...(required.length ? { required } : {}), $schema: SCHEMA, additionalProperties: false });
|
|
50
|
+
const str = (description, extra = {}) => ({ description, type: 'string', ...extra });
|
|
51
|
+
|
|
52
|
+
const codeShape = {
|
|
53
|
+
source: str('x86-64 assembly text of the basic block (give source or hex)'),
|
|
54
|
+
hex: str('machine code as hex bytes, e.g. "4801d84801c349ffcf75f5" (spaces allowed)'),
|
|
55
|
+
syntax: str('syntax of `source`: "auto" (default: detected from the text), "intel" (noprefix) or "att"', { enum: ['auto', 'intel', 'att'] }),
|
|
56
|
+
loop: {
|
|
57
|
+
description: 'what of `source` is analyzed: "auto" (default: the deepest loop of a whole function, else the text), "whole", the index of a loop (0-based), or its label',
|
|
58
|
+
anyOf: [{ type: 'string', enum: ['auto', 'whole'] }, { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, { type: 'string', minLength: 1 }],
|
|
59
|
+
},
|
|
60
|
+
func: str('only the loops of this function (a label of `source`)', { minLength: 1 }),
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const int = (description, minimum, maximum) => ({ description, type: 'integer', minimum, maximum });
|
|
64
|
+
const bool = (description) => ({ description, type: 'boolean' });
|
|
65
|
+
const optionsShape = {
|
|
66
|
+
description: 'simulation options of uiCA; all optional',
|
|
67
|
+
type: 'object',
|
|
68
|
+
properties: {
|
|
69
|
+
alignmentOffset: int('offset of the block from a 64-byte boundary (default 0); affects the front end', 0, 63),
|
|
70
|
+
initPolicy: str('initial register values: "diff" (default: all registers differ), "same", "stack"', { enum: ['diff', 'same', 'stack'] }),
|
|
71
|
+
simpleFrontEnd: bool('model a front end limited only by the issue width (default false)'),
|
|
72
|
+
noMicroFusion: bool('disable micro-fusion (default false)'),
|
|
73
|
+
noMacroFusion: bool('disable macro-fusion (default false)'),
|
|
74
|
+
minIterations: int('simulate at least this many iterations (default 10)', 1, 100000),
|
|
75
|
+
minCycles: int('simulate at least this many cycles (default 500)', 1, 1000000),
|
|
76
|
+
},
|
|
77
|
+
additionalProperties: false,
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const json = (value) => ({ type: 'text', text: JSON.stringify(value, null, 1) });
|
|
81
|
+
const omitBytes = ({ bytes, ...rest }) => rest;
|
|
82
|
+
|
|
83
|
+
function result(r) {
|
|
84
|
+
return r.code ? { isError: true, content: [json(r)] } : { content: [json(r)] };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const INSTRUCTIONS =
|
|
88
|
+
'wuica predicts the throughput of x86-64 basic blocks (loop bodies) with uiCA\'s cycle-level pipeline model, ' +
|
|
89
|
+
'locally. Use `analyze` for one block on one microarchitecture (bottlenecks, per-port usage, full report), ' +
|
|
90
|
+
'`what_if` for the effect of unrolling, an ideal front end, fusion, or removing the dependency chain, ' +
|
|
91
|
+
'`compare_archs` to see a block on several microarchitectures, `list_archs` for the ids, `assemble` to check ' +
|
|
92
|
+
'that assembly text is accepted and see its encoding. ' + ASSUMPTIONS;
|
|
93
|
+
|
|
94
|
+
const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
|
|
95
|
+
const execution = { taskSupport: 'forbidden' };
|
|
96
|
+
|
|
97
|
+
// The tools: [{name, title, description, inputSchema, annotations, execution, handler(args) -> CallToolResult}]. w: a
|
|
98
|
+
// wuica instance (createWuica) or anything with its analyze, compare, assemble, archs and summarize.
|
|
99
|
+
export function mcpTools(w) {
|
|
100
|
+
return [
|
|
101
|
+
{
|
|
102
|
+
name: 'list_archs',
|
|
103
|
+
title: 'List microarchitectures',
|
|
104
|
+
description:
|
|
105
|
+
'Lists the microarchitecture models in order of release: id (to pass as `arch`), name, release year, and ' +
|
|
106
|
+
'`prototype` (true for the experimental models ZEN3, ADL-P and ICX of the fork jtl06/uiCA, which are less ' +
|
|
107
|
+
'validated than uiCA\'s Intel models). `fields` selects fields (also available: table, xedChip).',
|
|
108
|
+
inputSchema: obj({
|
|
109
|
+
fields: { description: 'fields to return (default: id, name, year, prototype)', type: 'array', items: { type: 'string', enum: ['id', 'name', 'year', 'prototype', 'table', 'xedChip'] } },
|
|
110
|
+
}),
|
|
111
|
+
annotations: readOnly, execution,
|
|
112
|
+
handler: async ({ fields }) => ({ content: [json(w.archs(fields ?? ['id', 'name', 'year', 'prototype']))] }),
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
name: 'analyze',
|
|
116
|
+
title: 'Predict basic-block throughput (uiCA)',
|
|
117
|
+
description:
|
|
118
|
+
'Simulates an x86-64 basic block on one microarchitecture with uiCA\'s pipeline model and returns the predicted ' +
|
|
119
|
+
'throughput, the bottleneck(s), the per-component limits and a per-instruction table. ' + INPUT_NOTE + ' ' +
|
|
120
|
+
ASSUMPTIONS + '\n\nResult (JSON, format "json" or "both"): `tp` = cycles per iteration; `mode` = "loop" or ' +
|
|
121
|
+
'"unroll"; `bottlenecks` = the components that limit the throughput (e.g. Dependencies = a loop-carried ' +
|
|
122
|
+
'dependency chain, Ports = execution-port pressure, Issue/Decoder/Predecoder/DSB/LSD = front end); `limits` = ' +
|
|
123
|
+
'the throughput that would be achieved if that component were the only bottleneck (the largest is the binding ' +
|
|
124
|
+
'one); `instructions[]` = per instruction: average uops per iteration issued/executed, `ports` = uops per ' +
|
|
125
|
+
'iteration on each execution port, `uopSource` = where the uops came from (MITE legacy decoders, DSB uop cache, ' +
|
|
126
|
+
'LSD loop buffer, MS microcode sequencer), `notes` M = macro-fused with the previous instruction, J = not ' +
|
|
127
|
+
'cacheable in the DSB because of the JCC erratum, X = instruction not supported by the model (no data: the ' +
|
|
128
|
+
'result is unreliable); `stderr` = assembler warnings and decode warnings (`decodeErrors` > 0: some bytes could ' +
|
|
129
|
+
'not be decoded); `insights` = a derived diagnosis: `utilization` (each limit and execution port as a fraction ' +
|
|
130
|
+
'of tp; 1 = saturated), `binding` (the limiting component: the same as `bottlenecks`; [] when uiCA names none, then ' +
|
|
131
|
+
'`largest` is the largest limit, the nearest bound, which alone does not reach tp), `next` (the next limit and `maxSpeedup`, an upper ' +
|
|
132
|
+
'bound of the speedup if the binding component were removed), `unexplained` (cycles no single limit explains), ' +
|
|
133
|
+
'`chain` (the loop-carried critical dependency chain: `index` into `instructions`, operand, latency, carried ' +
|
|
134
|
+
'into the next iteration), `hot` (the instructions with the largest share of the binding resource: fix these ' +
|
|
135
|
+
'first), `caveats` (known blind spots of the model the block meets, not simulated: rmw-index = a read-modify-write ' +
|
|
136
|
+
'to an indexed address, whose store forwarding between iterations depends on the data; exit = an exit before the ' +
|
|
137
|
+
'loop\'s branch, whose mispredict is not modelled; split = loads at an offset that is not a multiple of their width, ' +
|
|
138
|
+
'which may cross a cache line (on ZEN3, ADL-P and ICX, whose models charge crossings, only loads whose address register ' +
|
|
139
|
+
'is written other than by adding an immediate); `instructions` = indexes into `instructions`). With `details: true`, each instruction also has `allowedPorts` (uops.info notation, e.g. 1*p0156+1*p23), ' +
|
|
140
|
+
'`uops`, `fusedUops`, `latencies` ("input->output:cycles"), `frontEnd` (length, offset = alignment offset + position in the block, crosses ' +
|
|
141
|
+
'16/32/64-byte boundaries, lcp = length-changing prefix, microcoded, macro-fusion), and `insights` has `portSet` (the ' +
|
|
142
|
+
'ports behind the Ports limit and the instructions whose uops can only use them) and `issueSlots` (issue slots per ' +
|
|
143
|
+
'iteration: issued, or lost to the front end, a full reorder buffer (rob) or scheduler (rs), other). ' +
|
|
144
|
+
'Format "text" (or the second item of "both") is uiCA\'s complete text report. ' + ERRORS_NOTE,
|
|
145
|
+
inputSchema: obj({
|
|
146
|
+
arch: str('microarchitecture id (default "SKL"); see list_archs, e.g. SKL, ICL, TGL, RKL, ADL-P, ZEN3'),
|
|
147
|
+
...codeShape,
|
|
148
|
+
options: optionsShape,
|
|
149
|
+
format: str('"json" (summary), "text" (uiCA\'s report) or "both" (default)', { enum: ['json', 'text', 'both'] }),
|
|
150
|
+
details: bool('true: per instruction also its allowed ports, latencies and front-end facts, and in insights the port set behind the Ports limit and the issue slots per cause (a slower analysis; default false)'),
|
|
151
|
+
}),
|
|
152
|
+
annotations: readOnly, execution,
|
|
153
|
+
handler: async ({ arch, format, details, ...request }) => {
|
|
154
|
+
const r = await w.analyze(arch ?? 'SKL', details ? { ...request, options: { ...(request.options ?? {}), details: true } } : request);
|
|
155
|
+
if (r.code) return result(r);
|
|
156
|
+
const content = [];
|
|
157
|
+
if (format !== 'text') content.push(json(w.summarize(r)));
|
|
158
|
+
if (format !== 'json') content.push({ type: 'text', text: r.text });
|
|
159
|
+
return { content };
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
name: 'what_if',
|
|
164
|
+
title: 'What-if experiments on a basic block',
|
|
165
|
+
description:
|
|
166
|
+
'Re-analyzes an x86-64 basic block with one change each and reports the predicted throughput per ORIGINAL ' +
|
|
167
|
+
'iteration, the change `delta` (cycles; negative = faster) and `speedup` (base tp / variant tp) against the base: ' +
|
|
168
|
+
'unroll2/unroll4/unroll8 (n copies of the loop body and its branch once; registers are not renamed, so the ' +
|
|
169
|
+
'dependencies stay and only the loop overhead goes; loops only), acc2/acc3/acc4/acc8 (N accumulators: unrolled ×N ' +
|
|
170
|
+
'with the register of the loop-carried chain renamed into a free register in each copy, so the copies form N ' +
|
|
171
|
+
'independent chains, as N accumulators or N CRC streams written by hand; `renamed` says which registers; the ' +
|
|
172
|
+
'result\'s `accumulators.best` is the smallest N within 1% of the fastest, 1 = as it is: call it per arch for the ' +
|
|
173
|
+
'best N per CPU; not possible when the chain goes through memory or flags or an implicit operand), simpleFrontEnd (a front end limited only by the ' +
|
|
174
|
+
'issue width), noMacroFusion / noMicroFusion (switched; if the base already has the option set, the variant ' +
|
|
175
|
+
'switches it back), nochain (no analysis: the largest limit other than Dependencies, an estimate of the ' +
|
|
176
|
+
'throughput without the loop-carried chain; `estimate: true`). A variant that cannot be made or analyzed has ' +
|
|
177
|
+
'`error`. Use it to decide whether unrolling, breaking the chain or front-end work is worth it. ' + INPUT_NOTE + ' ' +
|
|
178
|
+
ASSUMPTIONS + ' ' + ERRORS_NOTE,
|
|
179
|
+
inputSchema: obj({
|
|
180
|
+
arch: str('microarchitecture id (default "SKL"); see list_archs'),
|
|
181
|
+
...codeShape,
|
|
182
|
+
options: optionsShape,
|
|
183
|
+
variants: { description: `the experiments (default: all of ${VARIANTS.join(', ')})`, type: 'array', items: { type: 'string', enum: [...VARIANTS] } },
|
|
184
|
+
}),
|
|
185
|
+
annotations: readOnly, execution,
|
|
186
|
+
handler: async ({ arch, variants, ...request }) => result(await whatIf((a, req) => w.analyze(a, req), arch ?? 'SKL', request, variants ?? VARIANTS, { assemble: (text) => w.assemble(text, 'intel') })),
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
name: 'compare_archs',
|
|
190
|
+
title: 'Compare a block across microarchitectures',
|
|
191
|
+
description:
|
|
192
|
+
'Predicts the throughput of one x86-64 basic block on several microarchitectures (default: all) and returns, per ' +
|
|
193
|
+
'microarchitecture, `tp` in cycles per iteration and the bottleneck(s) (a row with code != 0 failed on that ' +
|
|
194
|
+
'microarchitecture). Use it to see how a loop behaves on older vs. newer Intel cores or on AMD Zen 3. ' +
|
|
195
|
+
INPUT_NOTE + ' ' + ASSUMPTIONS + ' ' + ERRORS_NOTE,
|
|
196
|
+
inputSchema: obj({
|
|
197
|
+
...codeShape,
|
|
198
|
+
archs: { description: 'microarchitecture ids to compare (default: all of list_archs)', type: 'array', items: { type: 'string' } },
|
|
199
|
+
options: optionsShape,
|
|
200
|
+
}),
|
|
201
|
+
annotations: readOnly, execution,
|
|
202
|
+
handler: async (request) => result(await w.compare(request)),
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
name: 'assemble',
|
|
206
|
+
title: 'Assemble x86-64 code',
|
|
207
|
+
description:
|
|
208
|
+
'Assembles x86-64 assembly text with LLVM\'s assembler (LLVM 22, the same bytes as llvm-mc) and returns ' +
|
|
209
|
+
'{code: 0, hex, length, stderr} (stderr: warnings), or the assembler\'s errors as {code: 2, error, stderr} with ' +
|
|
210
|
+
'line/column tags. The syntax is detected unless given (Intel noprefix or AT&T); the text may switch with .intel_syntax noprefix / ' +
|
|
211
|
+
'.att_syntax. Only .text is returned.',
|
|
212
|
+
inputSchema: obj({
|
|
213
|
+
source: { description: 'the assembly text', type: 'string' },
|
|
214
|
+
syntax: codeShape.syntax,
|
|
215
|
+
}, ['source']),
|
|
216
|
+
annotations: readOnly, execution,
|
|
217
|
+
handler: async ({ source, syntax }) => result(omitBytes(await w.assemble(source, syntax ?? 'auto'))),
|
|
218
|
+
},
|
|
219
|
+
];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The tool as tools/list shows it (without the handler).
|
|
223
|
+
export const toolListing = ({ handler, ...t }) => t;
|
|
224
|
+
|
|
225
|
+
// ---- a validator for the keywords these schemas use ------------------------------------------------------------------------
|
|
226
|
+
// type (object, array, string, integer, number, boolean), properties, required, additionalProperties: false, enum, items,
|
|
227
|
+
// minimum, maximum, minLength, anyOf. Returns the first problem as text ("options.minIterations: expected an integer,
|
|
228
|
+
// got \"many\""), or null.
|
|
229
|
+
const kind = (v) => (v === null ? 'null' : Array.isArray(v) ? 'an array' : typeof v === 'object' ? 'an object' : typeof v === 'string' ? 'a string' : typeof v === 'boolean' ? 'a boolean' : typeof v === 'number' ? (Number.isInteger(v) ? 'an integer' : 'a number') : typeof v);
|
|
230
|
+
const show = (v) => JSON.stringify(v)?.slice(0, 60) ?? String(v);
|
|
231
|
+
export function validate(schema, value, at = '') {
|
|
232
|
+
const where = at || 'arguments';
|
|
233
|
+
if (schema.anyOf) {
|
|
234
|
+
const errs = schema.anyOf.map((s) => validate(s, value, at));
|
|
235
|
+
if (errs.some((e) => e === null)) return null;
|
|
236
|
+
const allowed = schema.anyOf.map((s) => (s.enum ? s.enum.map((x) => JSON.stringify(x)).join(' or ') : s.type === 'integer' ? `an integer${s.minimum !== undefined ? ` >= ${s.minimum}` : ''}` : s.minLength ? 'a non-empty string' : `a ${s.type}`));
|
|
237
|
+
return `${where}: expected ${allowed.join(', or ')}, got ${show(value)}`;
|
|
238
|
+
}
|
|
239
|
+
switch (schema.type) {
|
|
240
|
+
case 'object': {
|
|
241
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return `${where}: expected an object, got ${kind(value)}`;
|
|
242
|
+
for (const k of schema.required ?? []) if (!(k in value) || value[k] === undefined) return `${at ? `${at}.` : ''}${k}: required`;
|
|
243
|
+
const props = schema.properties ?? {};
|
|
244
|
+
if (schema.additionalProperties === false) {
|
|
245
|
+
const extra = Object.keys(value).filter((k) => !Object.hasOwn(props, k));
|
|
246
|
+
if (extra.length) return `${where}: unknown key${extra.length > 1 ? 's' : ''} ${extra.map((k) => JSON.stringify(k)).join(', ')} (known: ${Object.keys(props).join(', ')})`;
|
|
247
|
+
}
|
|
248
|
+
for (const [k, s] of Object.entries(props)) {
|
|
249
|
+
if (value[k] === undefined) continue;
|
|
250
|
+
const e = validate(s, value[k], at ? `${at}.${k}` : k);
|
|
251
|
+
if (e) return e;
|
|
252
|
+
}
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
case 'array': {
|
|
256
|
+
if (!Array.isArray(value)) return `${where}: expected an array, got ${kind(value)}`;
|
|
257
|
+
for (let i = 0; i < value.length; i++) { const e = schema.items ? validate(schema.items, value[i], `${where}[${i}]`) : null; if (e) return e; }
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
case 'string':
|
|
261
|
+
if (typeof value !== 'string') return `${where}: expected a string, got ${kind(value)}`;
|
|
262
|
+
if (schema.minLength !== undefined && value.length < schema.minLength) return `${where}: expected at least ${schema.minLength} character${schema.minLength === 1 ? '' : 's'}`;
|
|
263
|
+
break;
|
|
264
|
+
case 'integer':
|
|
265
|
+
if (!Number.isInteger(value)) return `${where}: expected an integer, got ${show(value)}`;
|
|
266
|
+
break;
|
|
267
|
+
case 'number':
|
|
268
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) return `${where}: expected a number, got ${show(value)}`;
|
|
269
|
+
break;
|
|
270
|
+
case 'boolean':
|
|
271
|
+
if (typeof value !== 'boolean') return `${where}: expected true or false, got ${show(value)}`;
|
|
272
|
+
break;
|
|
273
|
+
default:
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
if (schema.enum && !schema.enum.includes(value)) return `${where}: expected one of ${schema.enum.map((x) => JSON.stringify(x)).join(', ')}, got ${show(value)}`;
|
|
277
|
+
if (schema.minimum !== undefined && value < schema.minimum) return `${where}: expected at least ${schema.minimum}, got ${value}`;
|
|
278
|
+
if (schema.maximum !== undefined && value > schema.maximum) return `${where}: expected at most ${schema.maximum}, got ${value}`;
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// tools/call on a table of tools: a CallToolResult, or {error: {code, message}} for a protocol error (an unknown tool).
|
|
283
|
+
// Arguments that do not fit the schema are a tool error (isError), as the MCP specification asks, so a model can retry.
|
|
284
|
+
export async function callTool(tools, name, args) {
|
|
285
|
+
const tool = tools.find((t) => t.name === name);
|
|
286
|
+
if (!tool) return { error: { code: -32602, message: `Unknown tool: ${name}` } };
|
|
287
|
+
const problem = validate(tool.inputSchema, args ?? {});
|
|
288
|
+
if (problem) return { isError: true, content: [{ type: 'text', text: `Invalid arguments for tool ${name}: ${problem}` }] };
|
|
289
|
+
try {
|
|
290
|
+
return await tool.handler(args ?? {});
|
|
291
|
+
} catch (e) {
|
|
292
|
+
return { isError: true, content: [{ type: 'text', text: `${name} failed: ${e?.message ?? e}` }] };
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ---- the stdio server ----------------------------------------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
const RPC = { parse: -32700, invalidRequest: -32600, method: -32601, params: -32602, internal: -32603 };
|
|
299
|
+
const err = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
|
|
300
|
+
const ok = (id, result) => ({ jsonrpc: '2.0', id, result });
|
|
301
|
+
|
|
302
|
+
// One JSON-RPC message (an object) -> the reply object, or null (a notification, or a response from the client).
|
|
303
|
+
export async function handleMessage(state, tools, m) {
|
|
304
|
+
if (m === null || typeof m !== 'object' || Array.isArray(m) || m.jsonrpc !== '2.0') return err(m?.id, RPC.invalidRequest, 'Invalid Request: not a JSON-RPC 2.0 message');
|
|
305
|
+
const isRequest = 'id' in m && m.id !== null && (typeof m.id === 'string' || typeof m.id === 'number');
|
|
306
|
+
if (typeof m.method !== 'string') {
|
|
307
|
+
if ('result' in m || 'error' in m) return null; // a response (this server sends no requests)
|
|
308
|
+
return err(m.id, RPC.invalidRequest, 'Invalid Request: no method');
|
|
309
|
+
}
|
|
310
|
+
if (!isRequest) {
|
|
311
|
+
if ('id' in m) return err(null, RPC.invalidRequest, 'Invalid Request: the id must be a string or a number');
|
|
312
|
+
return null; // notifications/initialized, notifications/cancelled, ...: nothing to answer
|
|
313
|
+
}
|
|
314
|
+
const params = m.params ?? {};
|
|
315
|
+
if (params === null || typeof params !== 'object') return err(m.id, RPC.params, 'Invalid params: expected an object');
|
|
316
|
+
switch (m.method) {
|
|
317
|
+
case 'initialize': {
|
|
318
|
+
if (typeof params.protocolVersion !== 'string') return err(m.id, RPC.params, 'Invalid params: protocolVersion (a string) is required');
|
|
319
|
+
state.version = PROTOCOL_VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0];
|
|
320
|
+
return ok(m.id, { protocolVersion: state.version, capabilities: CAPABILITIES, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
|
|
321
|
+
}
|
|
322
|
+
case 'ping':
|
|
323
|
+
return ok(m.id, {});
|
|
324
|
+
case 'tools/list':
|
|
325
|
+
return ok(m.id, { tools: tools.map(toolListing) });
|
|
326
|
+
case 'tools/call': {
|
|
327
|
+
if (typeof params.name !== 'string') return err(m.id, RPC.params, 'Invalid params: name (a string) is required');
|
|
328
|
+
if (params.arguments !== undefined && (params.arguments === null || typeof params.arguments !== 'object' || Array.isArray(params.arguments))) return err(m.id, RPC.params, 'Invalid params: arguments must be an object');
|
|
329
|
+
const r = await callTool(tools, params.name, params.arguments);
|
|
330
|
+
return r.error ? err(m.id, r.error.code, r.error.message) : ok(m.id, r);
|
|
331
|
+
}
|
|
332
|
+
default:
|
|
333
|
+
return err(m.id, RPC.method, `Method not found: ${m.method}`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// One line of input -> the line to write, or null.
|
|
338
|
+
export async function handleLine(state, tools, line) {
|
|
339
|
+
if (!line.trim()) return null;
|
|
340
|
+
let m;
|
|
341
|
+
try { m = JSON.parse(line); } catch { return JSON.stringify(err(null, RPC.parse, 'Parse error')); }
|
|
342
|
+
if (Array.isArray(m)) {
|
|
343
|
+
// batches: only the 2025-03-26 revision has them
|
|
344
|
+
if (state.version !== '2025-03-26') return JSON.stringify(err(null, RPC.invalidRequest, 'Invalid Request: batches are not supported in this protocol version'));
|
|
345
|
+
if (!m.length) return JSON.stringify(err(null, RPC.invalidRequest, 'Invalid Request: an empty batch'));
|
|
346
|
+
const replies = (await Promise.all(m.map((x) => handleMessage(state, tools, x)))).filter(Boolean);
|
|
347
|
+
return replies.length ? JSON.stringify(replies) : null;
|
|
348
|
+
}
|
|
349
|
+
const r = await handleMessage(state, tools, m);
|
|
350
|
+
return r ? JSON.stringify(r) : null;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// The stdio server: requests are answered in the order they arrive; the end of stdin ends it.
|
|
354
|
+
export async function runServer(options = {}, io = { stdin: process.stdin, stdout: process.stdout }) {
|
|
355
|
+
const w = await createWuica(options);
|
|
356
|
+
const tools = mcpTools(w);
|
|
357
|
+
const state = { version: null };
|
|
358
|
+
// a client that closes its end early: the writes that follow are dropped, the end of stdin still ends the server
|
|
359
|
+
io.stdout.on?.('error', (e) => { if (e?.code !== 'EPIPE') throw e; });
|
|
360
|
+
const rl = readline.createInterface({ input: io.stdin, crlfDelay: Infinity });
|
|
361
|
+
for await (const line of rl) {
|
|
362
|
+
const out = await handleLine(state, tools, line);
|
|
363
|
+
if (out !== null) io.stdout.write(out + '\n');
|
|
364
|
+
}
|
|
365
|
+
await w.close?.();
|
|
366
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// A worker thread of the library's thread pool (threads.js): an analyzer instance of the shared compiled module (whose
|
|
2
|
+
// memory has a smaller limit than the main thread's), with the tables of the microarchitectures it is given. It answers
|
|
3
|
+
// one job at a time with the fields of a compare() row. Nothing in here writes to stdout (the MCP server speaks JSON-RPC
|
|
4
|
+
// on stdout).
|
|
5
|
+
//
|
|
6
|
+
// workerData: {module (WebAssembly.Module), uarch (bytes of uarch.json), dataDir, recycleBytes}
|
|
7
|
+
// Messages in: {id, table, request}
|
|
8
|
+
// Messages out: {type: 'ready'} | {type: 'init-error', message} | {id, fields, recycle}
|
|
9
|
+
// fields null: the table could not be loaded, or the analysis trapped (it may only have hit this thread's memory
|
|
10
|
+
// limit): the main thread does it again, so that the row is the one it would have made itself.
|
|
11
|
+
// recycle: this thread should be stopped (its memory, which never shrinks, has grown beyond recycleBytes, or it trapped).
|
|
12
|
+
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
15
|
+
import { Analyzer } from './wasm.js';
|
|
16
|
+
import { readMaybeCompressed } from './files.js';
|
|
17
|
+
import { analysisResult, compareFields } from './core.js';
|
|
18
|
+
|
|
19
|
+
const { module, uarch, dataDir, recycleBytes } = workerData;
|
|
20
|
+
let analyzer = null;
|
|
21
|
+
try {
|
|
22
|
+
analyzer = new Analyzer(module);
|
|
23
|
+
analyzer.loadUarch(uarch);
|
|
24
|
+
} catch (e) {
|
|
25
|
+
parentPort.postMessage({ type: 'init-error', message: String(e?.message ?? e) });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (analyzer) {
|
|
29
|
+
parentPort.on('message', async ({ id, table, request }) => {
|
|
30
|
+
if (!analyzer.hasArch(table)) {
|
|
31
|
+
try {
|
|
32
|
+
analyzer.loadArch(table, await readMaybeCompressed(path.join(dataDir, 'arch', `${table}.json`)));
|
|
33
|
+
} catch {
|
|
34
|
+
parentPort.postMessage({ id, fields: null, recycle: analyzer.memoryBytes === 0 }); // 0: the module trapped
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const response = analyzer.analyze(request);
|
|
39
|
+
if (response.trapped || analyzer.memoryBytes === 0) { // trapped, or could not be restarted after an earlier trap
|
|
40
|
+
parentPort.postMessage({ id, fields: null, recycle: true });
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
parentPort.postMessage({ id, fields: compareFields(analysisResult(response)), recycle: analyzer.memoryBytes > recycleBytes });
|
|
44
|
+
});
|
|
45
|
+
parentPort.postMessage({ type: 'ready' });
|
|
46
|
+
}
|
package/lib/threads.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// Worker threads for compare(): the analyses of one block on several microarchitectures run in parallel, one per thread
|
|
2
|
+
// at a time (thread-worker.js). The module is compiled once for all threads, and each thread loads only the tables of
|
|
3
|
+
// the microarchitectures it is given.
|
|
4
|
+
//
|
|
5
|
+
// - Memory: the threads' module has a smaller memory limit than the main thread's (maxMemoryBytes: a quarter of the
|
|
6
|
+
// RAM shared by the threads, from 256 MiB to 1 GiB each), so that an input that needs a lot of memory cannot take it
|
|
7
|
+
// on every thread at once. An analysis that traps in a thread (it may only have hit that limit) is given back to the
|
|
8
|
+
// caller, which runs it on its own thread, so the result is the same as without threads. A thread whose memory has
|
|
9
|
+
// grown beyond half its limit (it never shrinks) is stopped after its job.
|
|
10
|
+
// - The pool is started by the first compare() that uses threads and kept for the next ones; its threads are started
|
|
11
|
+
// as jobs need them, up to the number run() is given (and `limit`). While no job runs they do not keep the process alive, and
|
|
12
|
+
// after IDLE_MS without a job they are stopped (close() stops them at once).
|
|
13
|
+
// - A table is pinned to the thread that loaded it: a job goes to a thread that has its table, else a table no thread
|
|
14
|
+
// has goes to the first free thread (or a new one). So every table is loaded once, whatever the number of compares.
|
|
15
|
+
// A new thread gets its first job at once (it waits in the thread's queue while the thread starts).
|
|
16
|
+
// - Warm-up: V8 compiles the module's functions when they are first called (and optimizes the hot ones later, in the
|
|
17
|
+
// background), and the compiled code belongs to the module, which the threads share. While new threads start
|
|
18
|
+
// (~80 ms), this thread analyzes a block once on an instance of their module, so that they find most of the code
|
|
19
|
+
// compiled (on aethia the first analysis of the SHA-256 showcase in 8 new threads at once takes ~100 instead of
|
|
20
|
+
// ~230 ms).
|
|
21
|
+
// - A thread that cannot start or stops unexpectedly does not fail anything: its jobs resolve to null and the caller
|
|
22
|
+
// runs them on its own thread. After a start failure the pool is `broken` and the caller stops using it.
|
|
23
|
+
|
|
24
|
+
import os from 'node:os';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { Worker, isMainThread } from 'node:worker_threads';
|
|
27
|
+
import { Analyzer, capMemory } from './wasm.js';
|
|
28
|
+
import { readMaybeCompressed } from './files.js';
|
|
29
|
+
import { WARM_HEX } from './core.js';
|
|
30
|
+
|
|
31
|
+
const WORKER = new URL('./thread-worker.js', import.meta.url);
|
|
32
|
+
export const IDLE_MS = 30_000;
|
|
33
|
+
const WARM_MIN_HEX = 2 * 1024; // the smallest block (hex digits: 1 KB of code, ~250 instructions) that gets a warm-up
|
|
34
|
+
const MIB = 2 ** 20;
|
|
35
|
+
|
|
36
|
+
// The memory limit of a thread's analyzer, for `threads` threads.
|
|
37
|
+
export function maxMemoryBytes(threads, total = os.totalmem()) {
|
|
38
|
+
return Math.min(1024 * MIB, Math.max(256 * MIB, Math.floor(total / 4 / Math.max(1, threads) / (64 * 1024)) * 64 * 1024));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The most threads compare() uses: `option` (createWuica's `threads`), else the environment variable WUICA_THREADS,
|
|
42
|
+
// else "auto": os.availableParallelism() (on the main thread; 1 inside a worker thread). 1 means no threads.
|
|
43
|
+
export function threadLimit(option, env = process.env) {
|
|
44
|
+
const raw = threadOption(option, env);
|
|
45
|
+
if (raw === 'auto') return isMainThread ? Math.max(1, os.availableParallelism()) : 1;
|
|
46
|
+
const n = Number(raw);
|
|
47
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
48
|
+
throw new TypeError(`${option !== undefined && option !== null ? 'threads' : 'WUICA_THREADS'}: expected a non-negative integer or "auto", got ${JSON.stringify(raw)}`);
|
|
49
|
+
}
|
|
50
|
+
return n;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// The option as given (option, else WUICA_THREADS), "auto" if there is none (also for 0).
|
|
54
|
+
export function threadOption(option, env = process.env) {
|
|
55
|
+
const raw = option ?? (env.WUICA_THREADS === undefined || env.WUICA_THREADS === '' ? 'auto' : env.WUICA_THREADS);
|
|
56
|
+
return raw === 0 || raw === '0' ? 'auto' : raw;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// The threads for a compare of jobs with `tables` different tables: one per table, at most `limit`; with "auto", at
|
|
60
|
+
// most one per two tables. A thread's start costs about as much as an analysis (it starts, loads its table, and its first
|
|
61
|
+
// analysis runs on code that is not optimized yet, which on aethia makes the SHA-256 showcase take ~100-230 instead of
|
|
62
|
+
// ~45 ms), so a thread pays off from its second analysis on: on aethia (8 cores, 16 threads) -arch all takes 0.60 s
|
|
63
|
+
// with 4 or 8 threads, 0.67 s with 12 and 0.71 s with 15 (1.05 s without threads), and for a small block 8 threads are
|
|
64
|
+
// as fast as none and 15 are 12% slower.
|
|
65
|
+
export function threadsFor(tables, limit, auto) {
|
|
66
|
+
return Math.min(limit, auto ? Math.ceil(tables / 2) : tables);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class ThreadPool {
|
|
70
|
+
#workerData = null;
|
|
71
|
+
#wasm; #uarch; #dataDir;
|
|
72
|
+
#compiled = null; // promise of the module with the threads' memory limit
|
|
73
|
+
#limit;
|
|
74
|
+
#slots = []; // {worker, ready, job, tables: Set}
|
|
75
|
+
#warmed = false;
|
|
76
|
+
#want; // the threads the latest run() may start
|
|
77
|
+
#queue = []; // {id, table, request, resolve}
|
|
78
|
+
#nextId = 1;
|
|
79
|
+
#idleTimer = null;
|
|
80
|
+
broken = false;
|
|
81
|
+
|
|
82
|
+
// wasm: the bytes of the analyzer module; uarch: the bytes of uarch.json; limit: the most threads.
|
|
83
|
+
constructor({ wasm, uarch, dataDir, limit }) {
|
|
84
|
+
this.#wasm = wasm; this.#uarch = uarch; this.#dataDir = dataDir;
|
|
85
|
+
this.#limit = limit;
|
|
86
|
+
this.#want = limit;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get threads() { return this.#slots.length; }
|
|
90
|
+
|
|
91
|
+
// jobs: [{table, request}] -> a promise of [fields | null] in the same order (null: not done, run it elsewhere).
|
|
92
|
+
// A thread is started for each table no thread has, while there are fewer than `threads` (and `limit`).
|
|
93
|
+
async run(jobs, threads = this.#limit) {
|
|
94
|
+
this.#want = Math.min(this.#limit, threads);
|
|
95
|
+
clearTimeout(this.#idleTimer);
|
|
96
|
+
this.#idleTimer = null;
|
|
97
|
+
if (!this.#workerData) {
|
|
98
|
+
const maxBytes = maxMemoryBytes(this.#limit);
|
|
99
|
+
this.#compiled ??= WebAssembly.compile(capMemory(this.#wasm, maxBytes / (64 * 1024)));
|
|
100
|
+
try {
|
|
101
|
+
const module = await this.#compiled;
|
|
102
|
+
this.#workerData ??= { module, uarch: this.#uarch, dataDir: this.#dataDir, recycleBytes: maxBytes / 2 };
|
|
103
|
+
} catch {
|
|
104
|
+
this.broken = true;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const out = Promise.all(jobs.map(({ table, request }) => new Promise((resolve) => {
|
|
108
|
+
if (this.broken) { resolve(null); return; }
|
|
109
|
+
this.#queue.push({ id: this.#nextId++, table, request, resolve });
|
|
110
|
+
})));
|
|
111
|
+
// (not for a small block: its analyses are short, and the warm-up would compete with them for the CPU)
|
|
112
|
+
if (this.#pump() && !this.#warmed && jobs[0]?.request.hex.length >= WARM_MIN_HEX) {
|
|
113
|
+
this.#warmed = true;
|
|
114
|
+
this.#warmUp(jobs[0]).catch(() => {});
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// One analysis of WARM_HEX on an instance of the threads' module (see the top); the instance is dropped afterwards.
|
|
120
|
+
async #warmUp({ table, request }) {
|
|
121
|
+
const bytes = await readMaybeCompressed(path.join(this.#dataDir, 'arch', `${table}.json`));
|
|
122
|
+
const a = new Analyzer(this.#workerData.module);
|
|
123
|
+
a.loadUarch(this.#uarch);
|
|
124
|
+
a.loadArch(table, bytes);
|
|
125
|
+
a.analyze({ hex: WARM_HEX, arch: request.arch });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
#owner(table) { return this.#slots.find((s) => s.tables.has(table)); }
|
|
129
|
+
|
|
130
|
+
// The job for a free thread: one of its tables, else one of a table no thread has.
|
|
131
|
+
#pick(slot) {
|
|
132
|
+
let i = this.#queue.findIndex((j) => slot.tables.has(j.table));
|
|
133
|
+
if (i < 0) i = this.#queue.findIndex((j) => !this.#owner(j.table));
|
|
134
|
+
return i < 0 ? null : this.#queue.splice(i, 1)[0];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Gives the waiting jobs to free threads, and starts a thread for each job of a table no thread has (up to the
|
|
138
|
+
// limit). Returns the number of threads started.
|
|
139
|
+
#pump() {
|
|
140
|
+
for (const s of this.#slots) {
|
|
141
|
+
if (s.job || !this.#queue.length) continue;
|
|
142
|
+
const j = this.#pick(s);
|
|
143
|
+
if (j) this.#start(s, j);
|
|
144
|
+
}
|
|
145
|
+
let started = 0;
|
|
146
|
+
while (this.#slots.length < this.#want) {
|
|
147
|
+
const i = this.#queue.findIndex((j) => !this.#owner(j.table));
|
|
148
|
+
if (i < 0) break;
|
|
149
|
+
this.#spawn(this.#queue.splice(i, 1)[0]);
|
|
150
|
+
started++;
|
|
151
|
+
}
|
|
152
|
+
this.#idle();
|
|
153
|
+
return started;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
#start(slot, job) {
|
|
157
|
+
slot.job = job;
|
|
158
|
+
slot.tables.add(job.table);
|
|
159
|
+
slot.worker.ref();
|
|
160
|
+
slot.worker.postMessage({ id: job.id, table: job.table, request: job.request });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
#spawn(job) {
|
|
164
|
+
const worker = new Worker(WORKER, { workerData: this.#workerData, stdout: true, stderr: true });
|
|
165
|
+
const slot = { worker, ready: false, job: null, tables: new Set() };
|
|
166
|
+
this.#slots.push(slot);
|
|
167
|
+
this.#start(slot, job);
|
|
168
|
+
worker.on('message', (m) => {
|
|
169
|
+
if (m.type === 'ready') {
|
|
170
|
+
slot.ready = true;
|
|
171
|
+
} else if (m.type === 'init-error') {
|
|
172
|
+
this.#fail(slot, true);
|
|
173
|
+
} else if (slot.job && m.id === slot.job.id) {
|
|
174
|
+
const job = slot.job;
|
|
175
|
+
slot.job = null;
|
|
176
|
+
worker.unref();
|
|
177
|
+
job.resolve(m.fields);
|
|
178
|
+
if (m.recycle) this.#remove(slot);
|
|
179
|
+
this.#pump();
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
worker.on('error', () => this.#fail(slot, !slot.ready));
|
|
183
|
+
worker.on('exit', () => this.#fail(slot, !slot.ready));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Stops a thread and forgets it (its tables are no longer pinned to it). False if it was gone already.
|
|
187
|
+
#remove(slot) {
|
|
188
|
+
const i = this.#slots.indexOf(slot);
|
|
189
|
+
if (i < 0) return false;
|
|
190
|
+
this.#slots.splice(i, 1);
|
|
191
|
+
slot.worker.terminate().catch(() => {});
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// A thread that failed: its job (and, if it never started, every waiting job) is given back to the caller.
|
|
196
|
+
#fail(slot, atStart) {
|
|
197
|
+
if (!this.#remove(slot)) return;
|
|
198
|
+
slot.job?.resolve(null);
|
|
199
|
+
slot.job = null;
|
|
200
|
+
if (atStart) this.broken = true;
|
|
201
|
+
if (this.broken) for (const j of this.#queue.splice(0)) j.resolve(null);
|
|
202
|
+
this.#pump();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// No job left: the threads are stopped after IDLE_MS (a timer that does not keep the process alive).
|
|
206
|
+
#idle() {
|
|
207
|
+
if (this.#queue.length || this.#slots.some((s) => s.job) || this.#idleTimer || !this.#slots.length) return;
|
|
208
|
+
this.#idleTimer = setTimeout(() => { this.#idleTimer = null; this.close(); }, IDLE_MS);
|
|
209
|
+
this.#idleTimer.unref();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Stops the threads; waiting and running jobs resolve to null. The next run() starts new ones.
|
|
213
|
+
async close() {
|
|
214
|
+
clearTimeout(this.#idleTimer);
|
|
215
|
+
this.#idleTimer = null;
|
|
216
|
+
const slots = this.#slots.splice(0);
|
|
217
|
+
for (const j of this.#queue.splice(0)) j.resolve(null);
|
|
218
|
+
await Promise.all(slots.map((s) => {
|
|
219
|
+
s.job?.resolve(null);
|
|
220
|
+
s.job = null;
|
|
221
|
+
return s.worker.terminate().catch(() => {});
|
|
222
|
+
}));
|
|
223
|
+
}
|
|
224
|
+
}
|