File size: 7,087 Bytes
5cb63c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | // Active process cancellation must keep one canonical terminal reason.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createDeferred } from "../../../test/helpers/promise.js";
import { createProcessSupervisor } from "./supervisor.js";
import type {
ProcessSupervisor,
SpawnInput,
SpawnProcessAdapter,
TerminationReason,
} from "./types.js";
const { createChildAdapterMock, createPtyAdapterMock } = vi.hoisted(() => ({
createChildAdapterMock: vi.fn(),
createPtyAdapterMock: vi.fn(),
}));
vi.mock("./adapters/child.js", () => ({
createChildAdapter: async (
...args: Parameters<typeof import("./adapters/child.js").createChildAdapter>
) => ({
adapter: await createChildAdapterMock(...args),
ready: Promise.resolve(),
}),
}));
vi.mock("./adapters/pty.js", () => ({
createPtyAdapter: createPtyAdapterMock,
}));
type CancellationTestAdapter = SpawnProcessAdapter<NodeJS.Signals | null> & {
killMock: ReturnType<typeof vi.fn>;
disposeMock: ReturnType<typeof vi.fn>;
settle: (signal: NodeJS.Signals) => void;
};
function createCancellationTestAdapter(): CancellationTestAdapter {
const completion = createDeferred<{ code: number | null; signal: NodeJS.Signals | null }>();
const killMock = vi.fn();
const disposeMock = vi.fn();
return {
pid: 4321,
supportsRawOutput: false,
onStdout: () => undefined,
onStderr: () => undefined,
wait: async () => completion.promise,
kill: (signal) => killMock(signal),
dispose: disposeMock,
killMock,
disposeMock,
settle: (signal) => completion.resolve({ code: null, signal }),
};
}
type CancellationPath = "run-id" | "scope";
function cancelThrough(
supervisor: ProcessSupervisor,
path: CancellationPath,
runId: string,
scopeKey: string,
reason: TerminationReason,
): void {
if (path === "scope") {
supervisor.cancelScope(scopeKey, reason);
return;
}
supervisor.cancel(runId, reason);
}
const cancellationPaths = [
{ label: "run ID", first: "run-id", later: "run-id" },
{ label: "scope", first: "scope", later: "scope" },
{ label: "run ID followed by scope", first: "run-id", later: "scope" },
{ label: "scope followed by run ID", first: "scope", later: "run-id" },
] as const satisfies ReadonlyArray<{
label: string;
first: CancellationPath;
later: CancellationPath;
}>;
const cancellationReasons = [
{
firstReason: "manual-cancel",
laterReasons: ["overall-timeout", "no-output-timeout", "manual-cancel"],
},
{
firstReason: "overall-timeout",
laterReasons: ["manual-cancel", "no-output-timeout", "overall-timeout"],
},
{
firstReason: "no-output-timeout",
laterReasons: ["manual-cancel", "overall-timeout", "no-output-timeout"],
},
] as const satisfies ReadonlyArray<{
firstReason: TerminationReason;
laterReasons: ReadonlyArray<TerminationReason>;
}>;
describe("process supervisor first cancellation reason", () => {
beforeEach(() => {
createChildAdapterMock.mockReset();
createPtyAdapterMock.mockReset();
vi.useFakeTimers();
});
it("keeps the first manual-cancel when a later construction deadline fires", async () => {
const startup = createDeferred<CancellationTestAdapter>();
createChildAdapterMock.mockReturnValueOnce(startup.promise);
const supervisor = createProcessSupervisor();
const runId = "manual-cancel-then-timeout";
const pendingRun = supervisor.spawn({
runId,
mode: "child",
argv: [process.execPath, "-e", "setInterval(() => {}, 1_000)"],
timeoutMs: 25,
stdinMode: "pipe-closed",
});
expect(createChildAdapterMock).toHaveBeenCalledOnce();
supervisor.cancel(runId, "manual-cancel");
await vi.advanceTimersByTimeAsync(25);
const constructionState = await Promise.race([
pendingRun.then(
() => "settled" as const,
() => "rejected" as const,
),
Promise.resolve().then(() => "pending" as const),
]);
expect(constructionState).toBe("settled");
const run = await pendingRun;
await expect(run.wait()).resolves.toMatchObject({
reason: "manual-cancel",
timedOut: false,
noOutputTimedOut: false,
});
expect(run.activity.resultSettled).toBe(true);
const lateAdapter = createCancellationTestAdapter();
const killed = createDeferred();
lateAdapter.killMock.mockImplementation(() => killed.resolve());
startup.resolve(lateAdapter);
await killed.promise;
expect(lateAdapter.killMock).toHaveBeenCalledWith("SIGKILL");
expect(lateAdapter.disposeMock).not.toHaveBeenCalled();
lateAdapter.settle("SIGKILL");
await run.waitForExtinction?.();
expect(lateAdapter.disposeMock).toHaveBeenCalled();
});
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
});
for (const mode of ["child", "pty"] as const) {
describe(`${mode} processes`, () => {
for (const path of cancellationPaths) {
describe(path.label, () => {
it.each(cancellationReasons)(
"keeps $firstReason after repeated overlapping cancellation",
async ({ firstReason, laterReasons }) => {
const adapter = createCancellationTestAdapter();
const adapterMock = mode === "child" ? createChildAdapterMock : createPtyAdapterMock;
adapterMock.mockResolvedValueOnce(adapter);
const supervisor = createProcessSupervisor();
const runId = `first-cancellation-${mode}`;
const scopeKey = `scope:first-cancellation-${mode}`;
const input: SpawnInput = {
runId,
scopeKey,
mode,
argv: [process.execPath, "-e", ""],
};
const run = await supervisor.spawn(input);
const exitPromise = run.wait();
cancelThrough(supervisor, path.first, runId, scopeKey, firstReason);
for (const laterReason of laterReasons) {
cancelThrough(supervisor, path.later, runId, scopeKey, laterReason);
expect(run.activity.resultSettled, `after ${laterReason}`).toBe(false);
}
expect(adapter.killMock).toHaveBeenCalledTimes(1);
const signal =
process.platform === "win32" && firstReason !== "manual-cancel"
? "SIGKILL"
: "SIGTERM";
expect(adapter.killMock).toHaveBeenCalledWith(signal);
adapter.settle(signal);
await expect(exitPromise).resolves.toMatchObject({
reason: firstReason,
exitSignal: signal,
timedOut: firstReason !== "manual-cancel",
noOutputTimedOut: firstReason === "no-output-timeout",
});
expect(run.activity.resultSettled).toBe(true);
expect(adapter.disposeMock).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
},
);
});
}
});
}
});
|