@ryuugg/stanza 0.3.1 → 0.3.3

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/src/pool.ts ADDED
@@ -0,0 +1,473 @@
1
+ import { availableParallelism } from "node:os";
2
+ import { statSync } from "node:fs";
3
+ import type { MessagePort } from "node:worker_threads";
4
+ import {
5
+ formatFile,
6
+ mergeOutcomes,
7
+ readText,
8
+ type FileOutcome,
9
+ type FormatRun,
10
+ type Formatted,
11
+ type Input,
12
+ } from "./format.ts";
13
+ import {
14
+ deserializerFiles,
15
+ embedDeserializers,
16
+ type DeserializerFiles,
17
+ } from "./languages/javascript/deserializers.ts";
18
+
19
+ export const THRESHOLD = 256;
20
+ export const DEFAULT_WORKERS = 3;
21
+ export const CHUNK_SIZE = 64;
22
+
23
+ export const LANE = { starting: 0, serving: 1, finished: 2, gone: 3 } as const;
24
+ type LaneState = (typeof LANE)[keyof typeof LANE];
25
+
26
+ export type Deferral = (path: string, text: string) => boolean;
27
+
28
+ export interface FileInput extends Omit<Input, "read"> {
29
+ output: string;
30
+ }
31
+
32
+ export interface PoolData<Input, Job> {
33
+ id: number;
34
+ inputs: Input[];
35
+ job: Job;
36
+ chunkSize: number;
37
+ counter: SharedArrayBuffer;
38
+ signal: SharedArrayBuffer;
39
+ claims: SharedArrayBuffer;
40
+ lanes: SharedArrayBuffer;
41
+ posted: SharedArrayBuffer;
42
+ port: MessagePort;
43
+ addon: string | undefined;
44
+ deserializers: DeserializerFiles;
45
+ }
46
+
47
+ export type ChunkMessage<Result> =
48
+ | (Result & { chunk: number })
49
+ | { chunk: number | undefined; error: string };
50
+
51
+ export interface PoolTask<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job> {
52
+ worker: string | URL;
53
+ job: Job;
54
+ chunkSize?: number;
55
+ chunk(inputs: Input[]): Result;
56
+ merge(result: Result): void;
57
+ item(input: Input): Outcome;
58
+ }
59
+
60
+ interface Board {
61
+ counter: Int32Array;
62
+ signal: Int32Array;
63
+ claims: Int32Array;
64
+ lanes: Int32Array;
65
+ posted: Int32Array;
66
+ }
67
+
68
+ interface Ledger<Outcome> {
69
+ readonly inputCount: number;
70
+ readonly chunkSize: number;
71
+ readonly results: ((Outcome | null)[] | undefined)[];
72
+ readonly errors: string[];
73
+ pending: number;
74
+ unowned: number;
75
+ }
76
+
77
+ interface Lane {
78
+ readonly port: MessagePort;
79
+ drained: number;
80
+ started: boolean;
81
+ fault: string | undefined;
82
+ exitCode: number | undefined;
83
+ recovered: number;
84
+ }
85
+
86
+ export function workerCount(
87
+ fileCount: number,
88
+ env: Readonly<Record<string, string | undefined>>,
89
+ maximum = DEFAULT_WORKERS,
90
+ cores = availableParallelism(),
91
+ ): number {
92
+ const override = env.STANZA_WORKERS;
93
+ if (override !== undefined && /^\d+$/.test(override)) {
94
+ const count = Number(override);
95
+ if (count <= 64) return count;
96
+ }
97
+
98
+ if (fileCount < THRESHOLD) return 0;
99
+
100
+ return Math.max(0, Math.min(maximum, cores - 1));
101
+ }
102
+
103
+ export function hardLinked(input: FileInput, run: FormatRun): boolean {
104
+ if (run.mode !== "fix" || !run.write) return false;
105
+
106
+ try {
107
+ return statSync(input.path).nlink > 1;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ export function formatChunk(inputs: FileInput[], run: FormatRun, defer?: Deferral) {
114
+ const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
115
+ const outcomes = inputs.map((input) => {
116
+ if (hardLinked(input, run)) return null;
117
+
118
+ const text = readText(input.path);
119
+ if (defer !== undefined && typeof text === "string" && defer(input.path, text)) return null;
120
+
121
+ return formatFile({ ...input, read: () => text }, run, input.output, warnings);
122
+ });
123
+
124
+ return { outcomes, unread: [...warnings.unread], unreadWidth: [...warnings.unreadWidth] };
125
+ }
126
+
127
+ function wake(signal: Int32Array): void {
128
+ Atomics.add(signal, 0, 1);
129
+ Atomics.notify(signal, 0);
130
+ }
131
+
132
+ function errorText(error: unknown): string {
133
+ return error instanceof Error ? error.message : String(error);
134
+ }
135
+
136
+ function chunkLength(ledger: Ledger<unknown>, chunk: number): number {
137
+ return Math.min(ledger.chunkSize, ledger.inputCount - chunk * ledger.chunkSize);
138
+ }
139
+
140
+ function settle<Outcome>(
141
+ ledger: Ledger<Outcome>,
142
+ chunk: number,
143
+ outcomes: (Outcome | null)[],
144
+ ): boolean {
145
+ if (ledger.results[chunk] !== undefined) return false;
146
+
147
+ ledger.results[chunk] = outcomes;
148
+ ledger.pending--;
149
+ return true;
150
+ }
151
+
152
+ function settleOnMain(ledger: Ledger<unknown>, chunk: number): boolean {
153
+ return settle(ledger, chunk, Array<null>(chunkLength(ledger, chunk)).fill(null));
154
+ }
155
+
156
+ function accept<Input, Outcome, Result extends { outcomes: (Outcome | null)[] }, Job>(
157
+ ledger: Ledger<Outcome>,
158
+ message: ChunkMessage<Result>,
159
+ task: PoolTask<Input, Outcome, Result, Job>,
160
+ ): void {
161
+ if ("error" in message) {
162
+ if (message.chunk === undefined || settleOnMain(ledger, message.chunk))
163
+ ledger.errors.push(message.error);
164
+
165
+ return;
166
+ }
167
+
168
+ if (settle(ledger, message.chunk, message.outcomes)) task.merge(message);
169
+ }
170
+
171
+ function stopped(states: LaneState[]): boolean {
172
+ return states.every((state) => state >= LANE.finished);
173
+ }
174
+
175
+ function quiet(
176
+ index: number,
177
+ states: LaneState[],
178
+ posted: number[],
179
+ lanes: Map<number, Lane>,
180
+ ): boolean {
181
+ return states[index]! >= LANE.finished && (lanes.get(index)?.drained ?? 0) >= posted[index]!;
182
+ }
183
+
184
+ function recoverStopped(
185
+ ledger: Ledger<unknown>,
186
+ claims: Int32Array,
187
+ states: LaneState[],
188
+ posted: number[],
189
+ lanes: Map<number, Lane>,
190
+ ): void {
191
+ const everyLaneQuiet = states.every((_, index) => quiet(index, states, posted, lanes));
192
+ for (let chunk = 0; chunk < claims.length; chunk++) {
193
+ const owner = Atomics.load(claims, chunk);
194
+ const ownerQuiet = owner !== 0 && quiet(owner - 1, states, posted, lanes);
195
+ if (!ownerQuiet && !everyLaneQuiet) continue;
196
+ if (!settleOnMain(ledger, chunk)) continue;
197
+
198
+ const lane = lanes.get(owner - 1);
199
+ if (lane === undefined) ledger.unowned += chunkLength(ledger, chunk);
200
+ else lane.recovered += chunkLength(ledger, chunk);
201
+ }
202
+ }
203
+
204
+ function fileCount(count: number): string {
205
+ return `${count} ${count === 1 ? "file" : "files"}`;
206
+ }
207
+
208
+ function laneLoss(lane: Lane): string | undefined {
209
+ const exit = `exited with code ${lane.exitCode}`;
210
+ if (!lane.started)
211
+ return `a worker thread failed to start, so main did its share: ${lane.fault ?? exit}`;
212
+
213
+ if (lane.recovered === 0 && lane.fault === undefined && (lane.exitCode ?? 0) !== 0)
214
+ return `a worker thread ${exit}, so main did its share`;
215
+
216
+ if (lane.recovered === 0) return lane.fault;
217
+
218
+ const files = fileCount(lane.recovered);
219
+ if (lane.fault !== undefined)
220
+ return `a worker thread failed before reporting ${files}, so main took them over: ${lane.fault}`;
221
+
222
+ const ending = lane.exitCode === undefined ? "stopped" : exit;
223
+ return `a worker thread ${ending} before reporting ${files}, so main took them over`;
224
+ }
225
+
226
+ function recoveredAny(ledger: Ledger<unknown>, lanes: Map<number, Lane>): boolean {
227
+ return ledger.unowned > 0 || [...lanes.values()].some((lane) => lane.recovered > 0);
228
+ }
229
+
230
+ function losses(ledger: Ledger<unknown>, lanes: Map<number, Lane>): string[] {
231
+ const laneLosses = [...lanes.values()].flatMap((lane) => laneLoss(lane) ?? []);
232
+ const unowned =
233
+ ledger.unowned === 0
234
+ ? []
235
+ : [
236
+ `a worker thread stopped before reporting ${fileCount(ledger.unowned)}, so main took them over`,
237
+ ];
238
+
239
+ return [...ledger.errors, ...laneLosses, ...unowned];
240
+ }
241
+
242
+ export async function runPooled<
243
+ Input,
244
+ Outcome,
245
+ Result extends { outcomes: (Outcome | null)[] },
246
+ Job,
247
+ >(
248
+ inputs: Input[],
249
+ task: PoolTask<Input, Outcome, Result, Job>,
250
+ count: number,
251
+ ): Promise<{ outcomes: Outcome[]; errors: string[] }> {
252
+ const { Worker, MessageChannel, receiveMessageOnPort } =
253
+ require("node:worker_threads") as typeof import("node:worker_threads");
254
+
255
+ const chunkSize = task.chunkSize ?? CHUNK_SIZE;
256
+ const chunkCount = Math.ceil(inputs.length / chunkSize);
257
+ const board: Board = {
258
+ counter: new Int32Array(new SharedArrayBuffer(4)),
259
+ signal: new Int32Array(new SharedArrayBuffer(4)),
260
+ claims: new Int32Array(new SharedArrayBuffer(4 * chunkCount)),
261
+ lanes: new Int32Array(new SharedArrayBuffer(4 * count)),
262
+ posted: new Int32Array(new SharedArrayBuffer(4 * count)),
263
+ };
264
+
265
+ const ledger: Ledger<Outcome> = {
266
+ inputCount: inputs.length,
267
+ chunkSize,
268
+ results: Array.from({ length: chunkCount }, () => undefined),
269
+ errors: [],
270
+ pending: chunkCount,
271
+ unowned: 0,
272
+ };
273
+
274
+ const lanes = new Map<number, Lane>();
275
+ const deserializers = deserializerFiles();
276
+ let open = true;
277
+
278
+ for (let id = 0; id < count; id++) {
279
+ const { port1, port2 } = new MessageChannel();
280
+ try {
281
+ const workerData: PoolData<Input, Job> = {
282
+ id,
283
+ inputs,
284
+ job: task.job,
285
+ chunkSize,
286
+ counter: board.counter.buffer as SharedArrayBuffer,
287
+ signal: board.signal.buffer as SharedArrayBuffer,
288
+ claims: board.claims.buffer as SharedArrayBuffer,
289
+ lanes: board.lanes.buffer as SharedArrayBuffer,
290
+ posted: board.posted.buffer as SharedArrayBuffer,
291
+ port: port2,
292
+ addon: process.env.NAPI_RS_NATIVE_LIBRARY_PATH,
293
+ deserializers,
294
+ };
295
+
296
+ const worker = new Worker(task.worker, { workerData, transferList: [port2] });
297
+ const lane: Lane = {
298
+ port: port1,
299
+ drained: 0,
300
+ started: true,
301
+ fault: undefined,
302
+ exitCode: undefined,
303
+ recovered: 0,
304
+ };
305
+
306
+ worker.on("error", (error: Error) => {
307
+ if (!open) return;
308
+ lane.fault ??= error.message;
309
+ wake(board.signal);
310
+ });
311
+
312
+ worker.on("exit", (code: number) => {
313
+ if (!open) return;
314
+
315
+ lane.started = Atomics.load(board.lanes, id) !== LANE.starting;
316
+ lane.exitCode = code;
317
+ Atomics.store(board.lanes, id, LANE.gone);
318
+ wake(board.signal);
319
+ });
320
+
321
+ worker.unref();
322
+ lanes.set(id, lane);
323
+ } catch (error: unknown) {
324
+ Atomics.store(board.lanes, id, LANE.gone);
325
+ ledger.errors.push(errorText(error));
326
+ port1.close();
327
+ port2.close();
328
+ }
329
+ }
330
+
331
+ try {
332
+ for (;;) {
333
+ const observed = Atomics.load(board.signal, 0);
334
+ const states = Array.from(
335
+ board.lanes,
336
+ (_, index) => Atomics.load(board.lanes, index) as LaneState,
337
+ );
338
+
339
+ const posted = Array.from(board.posted, (_, index) => Atomics.load(board.posted, index));
340
+
341
+ for (const lane of lanes.values()) {
342
+ let received: ReturnType<typeof receiveMessageOnPort>;
343
+ while ((received = receiveMessageOnPort(lane.port)) !== undefined) {
344
+ lane.drained++;
345
+ accept(ledger, received.message as ChunkMessage<Result>, task);
346
+ }
347
+ }
348
+
349
+ const chunk =
350
+ Atomics.load(board.counter, 0) < chunkCount ? Atomics.add(board.counter, 0, 1) : chunkCount;
351
+
352
+ if (chunk < chunkCount) {
353
+ try {
354
+ const result = task.chunk(inputs.slice(chunk * chunkSize, (chunk + 1) * chunkSize));
355
+ accept(ledger, { chunk, ...result }, task);
356
+ } catch (error: unknown) {
357
+ accept(ledger, { chunk, error: errorText(error) }, task);
358
+ }
359
+
360
+ continue;
361
+ }
362
+
363
+ recoverStopped(ledger, board.claims, states, posted, lanes);
364
+
365
+ const undelivered = [...lanes].some(([index, lane]) => lane.drained < posted[index]!);
366
+ const exited = [...lanes.values()].every((lane) => lane.exitCode !== undefined);
367
+ const settled = ledger.pending === 0 && stopped(states) && !undelivered;
368
+ if (settled && (exited || !recoveredAny(ledger, lanes))) break;
369
+
370
+ if (undelivered && stopped(states)) {
371
+ await new Promise((resolve) => setImmediate(resolve));
372
+ continue;
373
+ }
374
+
375
+ // Bun releases a waitAsync's hold on the event loop when another thread notifies, before main resumes.
376
+ const holdLoop = setInterval(() => {}, 2 ** 30);
377
+ try {
378
+ await Atomics.waitAsync(board.signal, 0, observed).value;
379
+ } finally {
380
+ clearInterval(holdLoop);
381
+ }
382
+ }
383
+ } finally {
384
+ open = false;
385
+ for (const lane of lanes.values()) lane.port.close();
386
+ }
387
+
388
+ const outcomes: Outcome[] = [];
389
+ for (const [chunk, results] of ledger.results.entries())
390
+ for (const [offset, outcome] of results!.entries())
391
+ outcomes.push(outcome ?? task.item(inputs[chunk * chunkSize + offset]!));
392
+
393
+ return { outcomes, errors: losses(ledger, lanes) };
394
+ }
395
+
396
+ export function serveChunks<Input, Job, Result>(work: (inputs: Input[], job: Job) => Result): void {
397
+ const { workerData } = require("node:worker_threads") as typeof import("node:worker_threads");
398
+ const data = workerData as PoolData<Input, Job>;
399
+
400
+ const counter = new Int32Array(data.counter);
401
+ const signal = new Int32Array(data.signal);
402
+ const claims = new Int32Array(data.claims);
403
+ const lanes = new Int32Array(data.lanes);
404
+ const posted = new Int32Array(data.posted);
405
+ function post(message: ChunkMessage<Result>): void {
406
+ data.port.postMessage(message);
407
+ Atomics.add(posted, data.id, 1);
408
+ wake(signal);
409
+ }
410
+
411
+ Atomics.store(lanes, data.id, LANE.serving);
412
+ wake(signal);
413
+
414
+ try {
415
+ if (data.addon !== undefined) process.env.NAPI_RS_NATIVE_LIBRARY_PATH = data.addon;
416
+ embedDeserializers(data.deserializers);
417
+
418
+ const chunkCount = Math.ceil(data.inputs.length / data.chunkSize);
419
+ for (
420
+ let chunk = Atomics.add(counter, 0, 1);
421
+ chunk < chunkCount;
422
+ chunk = Atomics.add(counter, 0, 1)
423
+ ) {
424
+ Atomics.store(claims, chunk, data.id + 1);
425
+
426
+ try {
427
+ const result = work(
428
+ data.inputs.slice(chunk * data.chunkSize, (chunk + 1) * data.chunkSize),
429
+ data.job,
430
+ );
431
+
432
+ post({ chunk, ...result });
433
+ } catch (error: unknown) {
434
+ post({ chunk, error: errorText(error) });
435
+ }
436
+ }
437
+ } catch (error: unknown) {
438
+ post({ chunk: undefined, error: errorText(error) });
439
+ } finally {
440
+ Atomics.store(lanes, data.id, LANE.finished);
441
+ wake(signal);
442
+ }
443
+ }
444
+
445
+ export async function formatPooled(
446
+ inputs: FileInput[],
447
+ run: FormatRun,
448
+ count: number,
449
+ ): Promise<{ formatted: Formatted; errors: string[] }> {
450
+ const warnings = { unread: new Set<string>(), unreadWidth: new Set<string>() };
451
+ // A compiled Bun worker resolves a bare specifier inside bunfs, not a file URL.
452
+ const specifier = Bun.main.includes("/$bunfs/")
453
+ ? "./worker.ts"
454
+ : new URL("./worker.ts", import.meta.url);
455
+
456
+ const { outcomes, errors } = await runPooled(
457
+ inputs,
458
+ {
459
+ worker: specifier,
460
+ job: run,
461
+ chunk: (inputs) => formatChunk(inputs, run),
462
+ merge(result) {
463
+ for (const path of result.unread) warnings.unread.add(path);
464
+ for (const path of result.unreadWidth) warnings.unreadWidth.add(path);
465
+ },
466
+ item: (input): FileOutcome =>
467
+ formatFile({ ...input, read: () => readText(input.path) }, run, input.output, warnings),
468
+ },
469
+ count,
470
+ );
471
+
472
+ return { formatted: mergeOutcomes(outcomes, warnings), errors };
473
+ }
package/src/usage.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export const bothBraces = "use one of --braces or --no-braces";
2
2
 
3
3
  export const usage =
4
- "Usage: stanza (--fix | --check) [--changed [--hunks] | --stdin <path> | [--] <paths...>] [--json] [--braces | --no-braces]\n stanza --check --staged [--hunks] [--json] [--braces | --no-braces]\n stanza explain <file>:<line> [--no-braces]\n stanza hook [--braces | --no-braces] [--hunks]";
4
+ "Usage: stanza (--fix | --check) [--changed [--hunks] | --stdin <path> | [--] <paths...>] [--json] [--braces | --no-braces]\n stanza --check --staged [--hunks] [--json] [--braces | --no-braces]\n stanza explain [--no-braces] [--] <file>:<line>\n stanza hook [--braces | --no-braces] [--hunks]";
5
5
 
6
6
  export const flags: (readonly [string, string])[] = [
7
7
  ["--fix", "apply every deterministic rule in place"],
@@ -13,11 +13,14 @@ export const flags: (readonly [string, string])[] = [
13
13
  "--stdin <path>",
14
14
  "source on stdin; --fix: fixed text on stdout, findings on stderr; --check: findings on stdout",
15
15
  ],
16
- ["--json", "findings as a JSON array, for hooks"],
16
+ ["--json", "findings as a JSON array"],
17
17
  ["--braces", "turn on the braces rule even when lint config turns it off or cannot be read"],
18
18
  ["--no-braces", "turn off the braces rule, keep the blank line rules"],
19
19
  ["explain <file>:<line>", "which rule decides the gap or braced body at that line, and why"],
20
- ["hook", "the Stop hook and PreToolUse hook on Write, reads JSON on stdin"],
20
+ [
21
+ "hook",
22
+ "Stop and SubagentStop; PostToolUse on Edit, MultiEdit and Codex `apply_patch`; PreToolUse on Write; reads JSON on stdin",
23
+ ],
21
24
  ["--help", "usage, flags and the rule catalog"],
22
25
  ["--version", "the version, and for a built binary the commit it was built from"],
23
26
  ];
package/src/worker.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { tooDeep } from "./depth.ts";
2
+ import { formatChunk, serveChunks, type FileInput } from "./pool.ts";
3
+ import type { FormatRun } from "./format.ts";
4
+
5
+ serveChunks((inputs: FileInput[], run: FormatRun) => formatChunk(inputs, run, tooDeep));