Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 151 additions & 11 deletions apps/server/src/cloud/bootService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ import { expect, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Clock from "effect/Clock";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
import { CliError } from "effect/cli";
import { HttpClient } from "effect/http";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
Expand Down Expand Up @@ -181,6 +184,48 @@ it.each([
const macInstallerPath =
"/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";

const processOutput = {
stdout: "",
stderr: "",
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};

// launchctl on macOS 15: `bootout --wait` is a usage error (64) that leaves the job loaded,
// bootout of an unloaded job fails with ESRCH (3), and bootstrap over a loaded label is EIO (5).
// A booted-out job stays loaded for `exitPrints` more prints while it drains through ExitTimeOut,
// and bootout then returns EINPROGRESS (36).
interface LaunchdJob {
loaded: boolean;
exitPrints?: number;
exiting?: number | undefined;
}
const launchctl = (job: LaunchdJob, args: ReadonlyArray<string>) => {
if (args.includes("--wait")) return 64;
switch (args[0]) {
case "bootout":
if (!job.loaded) return 3;
job.exiting = job.exitPrints ?? 0;
job.loaded = job.exiting > 0;
return job.loaded ? 36 : 0;
case "print":
if (job.exiting !== undefined && --job.exiting < 0) {
job.loaded = false;
job.exiting = undefined;
}
return job.loaded ? 0 : 113;
case "bootstrap":
if (job.loaded) return 5;
job.loaded = true;
return 0;
default:
return 0;
}
};

const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
platform: NodeJS.Platform = "linux",
installerPath = macInstallerPath,
Expand Down Expand Up @@ -228,6 +273,9 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
launcher?: { readonly close: () => void };
/** Task Scheduler's own copy of the task. */
task?: { xml: string; enabled: boolean };
/** launchd's model of the agent, so a bootout can be seen to unload it before bootstrap. */
launchd: LaunchdJob | undefined;
onCommand?: (command: string) => Effect.Effect<void, ProcessRunner.ProcessRunError>;
} = {
failCommand: undefined,
linger: "yes",
Expand All @@ -237,6 +285,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
enabled: true,
active: true,
startLimitHit: false,
launchd: platform === "darwin" ? { loaded: false } : undefined,
};
const runner = ProcessRunner.ProcessRunner.of({
run: Effect.fn("test.run_boot_service_command")(function* (
Expand All @@ -249,20 +298,21 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
command === "systemctl --user stop t3code.service" ||
command === "systemctl --user disable --now t3code.service" ||
command === "systemctl --user restart --no-block t3code.service" ||
command.startsWith("launchctl bootout --wait ") ||
command.startsWith("launchctl bootout ") ||
(input.command === "schtasks" && input.args[0] === "/End")
) {
markersAtStop.push(yield* fs.exists(marker));
markersAtStop.push(yield* fs.exists(marker).pipe(Effect.orDie));
}
if (
command === "systemctl --user daemon-reload" ||
(input.command === "schtasks" && input.args[0] === "/Create")
) {
markersAtPreparation.push(yield* fs.exists(marker));
markersAtPreparation.push(yield* fs.exists(marker).pipe(Effect.orDie));
}
if (command === control.interruptCommand) return yield* Effect.interrupt;
invocations.push(input);
timeouts.set(command, input.timeout);
if (control.onCommand !== undefined) yield* control.onCommand(command);
if (command === "systemctl --user reset-failed t3code.service") control.startLimitHit = false;
const refusedStart = control.startLimitHit && command.startsWith("systemctl --user restart ");
// `--no-block` only queues the job, so systemd reports success even when it refuses it.
Expand All @@ -278,7 +328,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined;
if (input.command === "schtasks" && !failed) {
if (input.args[0] === "/Create") {
const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? ""));
const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "").pipe(Effect.orDie));
control.task = { xml, enabled: !serviceTaskIsDisabled(xml) };
}
if (control.task !== undefined && input.args[0] === "/Change") {
Expand All @@ -292,15 +342,21 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
// The manager loads units only from its own unit directory.
const unitOutsideManager =
command === "systemctl --user enable t3code.service" &&
!(yield* fs.exists(path.join(managerUnitDir, "t3code.service")));
!(yield* fs.exists(path.join(managerUnitDir, "t3code.service")).pipe(Effect.orDie));
// A timed-out stop may still stop the service.
if (command === "systemctl --user stop t3code.service") control.active = false;
if (
control.stateAfterStop !== undefined &&
(command === "systemctl --user stop t3code.service" ||
command.startsWith("launchctl bootout --wait "))
command.startsWith("launchctl bootout "))
) {
yield* fs.writeFileString(statePath, control.stateAfterStop);
yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
}
if (control.launchd !== undefined && input.command === "launchctl") {
return {
...processOutput,
code: ChildProcessSpawner.ExitCode(failed ? 1 : launchctl(control.launchd, input.args)),
};
}
return {
stdout:
Expand Down Expand Up @@ -352,7 +408,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}, Effect.orDie),
}),
});
const makeService = (
environmentPath: string | undefined = installerPath,
Expand Down Expand Up @@ -924,7 +980,8 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
"systemctl --user restart t3code.service",
]
: [
"launchctl bootout --wait gui/501/com.t3tools.t3code.service",
"launchctl bootout gui/501/com.t3tools.t3code.service",
"launchctl print gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plan.unitPath}`,
],
);
Expand Down Expand Up @@ -1531,7 +1588,7 @@ process.disconnect();
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
// launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it.
expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
expect(timeouts.get("launchctl bootout gui/501/com.t3tools.t3code.service")).toEqual(
Duration.seconds(120),
);
}),
Expand Down Expand Up @@ -1756,13 +1813,96 @@ process.disconnect();
Effect.gen(function* () {
const { service, control } = yield* makeHarness("darwin");
yield* service.install();
control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
control.launchd = { loaded: false };

yield* service.install();
expect((yield* service.status).current).toBe(true);
}),
);

// regression: #11995 macOS 15 launchctl rejects `bootout --wait` without stopping the job
it.effect("uninstall unloads the launch agent when launchctl rejects bootout --wait", () =>
Effect.gen(function* () {
const { service, control } = yield* makeHarness("darwin");
yield* service.install();

expect(yield* service.uninstall).toBe(true);
expect(control.launchd?.loaded).toBe(false);
}),
);

it.effect("waits for a booted-out launch agent to exit before bootstrapping it again", () =>
Effect.gen(function* () {
const { service, control, commands } = yield* makeHarness("darwin");
yield* service.install();
control.launchd = { loaded: true, exitPrints: 2 };
// The first command after bootout is the wait's print, or a premature bootstrap.
const afterBootout = yield* Deferred.make<void>();
control.onCommand = (command) =>
/^launchctl (print|bootstrap) /.test(command)
? Deferred.succeed(afterBootout, undefined)
: Effect.void;
commands.length = 0;

const reinstall = yield* service.install().pipe(Effect.forkChild);
yield* Deferred.await(afterBootout);
yield* TestClock.adjust("1 second");
yield* Fiber.join(reinstall);

expect(control.launchd.loaded).toBe(true);
expect(commands.filter((command) => command.startsWith("launchctl print "))).toHaveLength(3);
}),
);

it.effect("keeps waiting for a draining launch agent when a print times out", () =>
Effect.gen(function* () {
const { service, control } = yield* makeHarness("darwin");
yield* service.install();
control.launchd = { loaded: true, exitPrints: 1 };
const afterBootout = yield* Deferred.make<void>();
// The first print times out; a premature bootstrap also releases the clock.
control.onCommand = (command) =>
Effect.gen(function* () {
if (!/^launchctl (print|bootstrap) /.test(command)) return;
const first = yield* Deferred.succeed(afterBootout, undefined);
if (first && command.startsWith("launchctl print ")) {
return yield* new ProcessRunner.ProcessTimeoutError({
command: "launchctl",
argumentCount: 2,
timeoutMs: 5000,
});
}
});

const reinstall = yield* service.install().pipe(Effect.forkChild);
yield* Deferred.await(afterBootout);
yield* TestClock.adjust("1 second");
yield* Fiber.join(reinstall);

expect(control.launchd.loaded).toBe(true);
}),
);

it.effect("keeps the launch agent installed when it is still loaded at the stop deadline", () =>
Effect.gen(function* () {
const { service, control, fs } = yield* makeHarness("darwin");
const plan = yield* service.install();
control.launchd = { loaded: true, exitPrints: Number.POSITIVE_INFINITY };
const polling = yield* Deferred.make<void>();
control.onCommand = (command) =>
command.startsWith("launchctl print ")
? Deferred.succeed(polling, undefined).pipe(Effect.asVoid)
: Effect.void;

const uninstall = yield* service.uninstall.pipe(Effect.exit, Effect.forkChild);
yield* Deferred.await(polling);
yield* TestClock.adjust("121 seconds");

expect(Exit.isFailure(yield* Fiber.join(uninstall))).toBe(true);
expect(yield* fs.exists(plan.unitPath)).toBe(true);
}),
);

it.effect("keeps failed launch agent installs pending until activation succeeds", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, control } = yield* makeHarness("darwin");
Expand Down
Loading