Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PiRpc.test.ts

65 lines2.4 KB

1import { assert, it } from "@effect/vitest";
2import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Sink from "effect/Sink";
6import * as Stream from "effect/Stream";
7import * as TestClock from "effect/testing/TestClock";
8import { ChildProcessSpawner } from "effect/unstable/process";
9import { vi } from "vite-plus/test";
10​
11import { makePiRpcConnection } from "./PiRpc.ts";
12​
13/** Deliberately outside the valid pid range so a real group-kill can never land. */
14const FAKE_PID = 999_999_999;
15​
16/** A pi process that exits with code 0 right after spawning. */
17const exitedPiSpawner = ChildProcessSpawner.make(() =>
18 Effect.succeed(
19 ChildProcessSpawner.makeHandle({
20 pid: ChildProcessSpawner.ProcessId(FAKE_PID),
21 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
22 isRunning: Effect.succeed(false),
23 kill: () => Effect.void,
24 unref: Effect.succeed(Effect.void),
25 stdin: Sink.drain,
26 stdout: Stream.empty,
27 stderr: Stream.empty,
28 all: Stream.empty,
29 getInputFd: () => Sink.drain,
30 getOutputFd: () => Stream.empty,
31 }),
32 ),
33);
34​
35it.effect("terminates extension subprocesses that outlive pi in its process group", () =>
36 Effect.gen(function* () {
37 const signals: Array<[number, string | number | undefined]> = [];
38 let groupAlive = true;
39 const kill = vi.spyOn(process, "kill").mockImplementation((pid, signal) => {
40 signals.push([pid, signal]);
41 if (signal === 0 && !groupAlive) throw Object.assign(new Error("ESRCH"), { code: "ESRCH" });
42 if (signal === "SIGTERM") groupAlive = false;
43 return true;
44 });
45 yield* Effect.addFinalizer(() => Effect.sync(() => kill.mockRestore()));
46​
47 const connection = yield* makePiRpcConnection({
48 command: "pi",
49 args: ["--mode", "rpc"],
50 cwd: undefined,
51 env: {},
52 }).pipe(
53 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, exitedPiSpawner),
54 Effect.provideService(HostProcessPlatform, "linux"),
55 );
56 assert.equal(yield* connection.exited, 0);
57​
58 const terminating = yield* Effect.forkChild(connection.terminate);
59 yield* TestClock.adjust("1 second");
60 yield* Fiber.join(terminating);
61​
62 assert.deepInclude(signals, [-FAKE_PID, "SIGTERM"]);
63 assert.notDeepInclude(signals, [-FAKE_PID, "SIGKILL"]);
64 }).pipe(Effect.scoped),
65);