mirror of
https://github.com/morluto/rea.git
synced 2026-12-03 21:46:01 +00:00
* fix(cli): deliver complete TOON beyond the string limit * fix(cli): own cancellation through TOON delivery * test(cli): await TOON stage acknowledgements * fix(cli): build TOON cancellations through domain factory --------- Co-authored-by: ShuaixinHuang <197200901+ShuaixinHuang@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
67 lines
2.1 KiB
TypeScript
67 lines
2.1 KiB
TypeScript
import { CallerAbort } from "../domain/analysisErrorCore.js";
|
|
|
|
/** Process signal boundary injectable without emitting signals into a test runner. */
|
|
export interface CommandCancellationHost {
|
|
on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
|
off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown;
|
|
exitCode?: number | string | null | undefined;
|
|
}
|
|
|
|
/** Own process signals until both the operation and its resources settle. */
|
|
export class CommandCancellationScope {
|
|
readonly #controller = new AbortController();
|
|
#exitStatus: 130 | 143 | undefined;
|
|
#finished = false;
|
|
#closed = false;
|
|
|
|
constructor(private readonly host: CommandCancellationHost = process) {
|
|
host.on("SIGINT", this.#interrupt);
|
|
host.on("SIGTERM", this.#terminate);
|
|
}
|
|
|
|
get signal(): AbortSignal {
|
|
return this.#controller.signal;
|
|
}
|
|
|
|
get exitStatus(): 130 | 143 | undefined {
|
|
return this.#exitStatus;
|
|
}
|
|
|
|
readonly #interrupt = () => this.#abort("SIGINT", 130);
|
|
readonly #terminate = () => this.#abort("SIGTERM", 143);
|
|
|
|
#abort(signal: "SIGINT" | "SIGTERM", status: 130 | 143): void {
|
|
this.#exitStatus ??= status;
|
|
this.#controller.abort(CallerAbort.forProcessSignal(signal));
|
|
if (this.#finished) this.finish();
|
|
}
|
|
|
|
/** Publish the disposition while a failed resource close still owns signals. */
|
|
finish(): void {
|
|
this.#finished = true;
|
|
if (this.#exitStatus !== undefined) this.host.exitCode = this.#exitStatus;
|
|
}
|
|
|
|
/** Release signal ownership only after the resource owner confirms cleanup. */
|
|
close(): void {
|
|
if (this.#closed) return;
|
|
this.#closed = true;
|
|
this.host.off("SIGINT", this.#interrupt);
|
|
this.host.off("SIGTERM", this.#terminate);
|
|
this.finish();
|
|
}
|
|
}
|
|
|
|
/** Translate one-shot CLI interrupts into awaited cleanup and conventional exit codes. */
|
|
export const withCommandCancellation = async <Value>(
|
|
operation: (signal: AbortSignal) => Promise<Value>,
|
|
host: CommandCancellationHost = process,
|
|
): Promise<Value> => {
|
|
const scope = new CommandCancellationScope(host);
|
|
try {
|
|
return await operation(scope.signal);
|
|
} finally {
|
|
scope.close();
|
|
}
|
|
};
|