Skip to content

Commit dd3bebe

Browse files
committed
fix(server): close the Windows service review findings
Six review findings, all about the same class of failure: something looks successful while a second server ends up on one SQLite database, or while nothing runs at all. - The pid file is claimed exclusively with `wx`, and released only by the process that owns it. A Startup shortcut that fires twice now leaves the second launcher exiting instead of starting a rival server. - Failing to publish the pid file no longer continues silently. A live launcher without one is invisible to the CLI, which reads absence as proof that nothing is running. - A failed stop-request write fails the operation once a live launcher is confirmed, rather than reading as "nothing to stop". - install and uninstall decide whether to stop from the pid file, not from the shortcut. A launcher outlives a shortcut someone deleted by hand. - `status` reads the shortcut back through the Probe action and compares its target and arguments. Comparing the script that wrote the shortcut said nothing about a shortcut edited or replaced since. - Connect onboarding no longer promises Windows users the service survives sign-out, which contradicted the prompt they had just accepted.
1 parent 6493ba3 commit dd3bebe

5 files changed

Lines changed: 223 additions & 51 deletions

File tree

‎apps/server/src/cli/connect.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
type RelayClientInstallProgressStage,
66
} from "@t3tools/contracts";
77
import { RelayOkResponse } from "@t3tools/contracts/relay";
8+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
89
import * as RelayClient from "@t3tools/shared/relayClient";
910
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
1011
import * as Cause from "effect/Cause";
@@ -694,9 +695,13 @@ export const connectCommand = Command.make("connect", {
694695
// fail the command, just tell the user what happened and move on.
695696
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
696697
if (background) {
697-
yield* Console.log(
698-
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
699-
);
698+
// Windows starts the service at sign-in and stops it at sign-out, so
699+
// the Linux promise would contradict the prompt the user just agreed to.
700+
const reach =
701+
(yield* HostProcessPlatform) === "win32"
702+
? "T3 Code will start again every time you sign in to Windows."
703+
: "T3 Code will stay reachable after you log out.";
704+
yield* Console.log(`\n✓ Background service ready\n\n${reach}`);
700705
return;
701706
}
702707
const serveCommand = yield* resolveCliCommand("serve");

‎apps/server/src/cloud/bootServiceWindows.test.ts‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,20 @@ const makeHarness = Effect.fn("test.make_windows_boot_service_harness")(function
133133
const pidPath = path.join(runtimeDir, SERVICE_PID_FILE);
134134
const stopRequestPath = path.join(runtimeDir, ".service-stop-request");
135135
const commands: string[] = [];
136+
const powershell = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
137+
const expectedArguments = BootServiceWindows.expectedShortcutArguments({
138+
...plan,
139+
startupScriptPath,
140+
});
136141
const control = {
137142
shell: "True",
138143
disabled: "False",
139144
failCommand: undefined as string | undefined,
140145
/** Set to false to model a launcher that never answers the stop request. */
141146
launcherStopsOnRequest: true,
147+
/** What the fake shortcut currently points at, so drift can be modelled. */
148+
shortcutTarget: powershell,
149+
shortcutArguments: expectedArguments,
142150
};
143151
// The fake stands in for PowerShell: creating and removing the shortcut is a
144152
// plain file write here, which is all the module observes.
@@ -166,7 +174,10 @@ const makeHarness = Effect.fn("test.make_windows_boot_service_harness")(function
166174
return {
167175
stdout:
168176
action === "Probe"
169-
? `shell=${control.shell}\ndisabled=${control.disabled}\n`
177+
? `shell=${control.shell}\ndisabled=${control.disabled}\n` +
178+
((yield* fs.exists(shortcutPath).pipe(Effect.orElseSucceed(() => false)))
179+
? `target=${control.shortcutTarget}\narguments=${control.shortcutArguments}\n`
180+
: "")
170181
: input.args[1] === "--version"
171182
? "t3 v1.2.3\n"
172183
: "",
@@ -192,7 +203,9 @@ const makeHarness = Effect.fn("test.make_windows_boot_service_harness")(function
192203
Layer.succeed(HostProcessPlatform, platform),
193204
Layer.succeed(HostProcessExecutablePath, "C:\\node.exe"),
194205
Layer.succeed(HostProcessArguments, ["C:\\node.exe", path.join(home, "bin.mjs")]),
195-
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { APPDATA: appData } })),
206+
ConfigProvider.layer(
207+
ConfigProvider.fromEnv({ env: { APPDATA: appData, SystemRoot: "C:\\Windows" } }),
208+
),
196209
),
197210
),
198211
);
@@ -316,6 +329,32 @@ it.layer(NodeServices.layer)("windows boot service", (it) => {
316329
}).pipe(TestClock.withLive),
317330
);
318331

332+
it.effect("goes stale when the shortcut itself is edited, not just the script", () =>
333+
Effect.gen(function* () {
334+
const { service, control } = yield* makeHarness();
335+
yield* service.install;
336+
expect((yield* service.status).current).toBe(true);
337+
338+
// The generated scripts still match. Only the .lnk was tampered with, and
339+
// that is the thing sign-in actually runs.
340+
control.shortcutArguments = "-File C:\\somewhere\\else.ps1";
341+
expect((yield* service.status).current).toBe(false);
342+
}).pipe(TestClock.withLive),
343+
);
344+
345+
it.effect("stops a running launcher even when the shortcut was deleted by hand", () =>
346+
Effect.gen(function* () {
347+
const { service, fs, shortcutPath, pidPath } = yield* makeHarness();
348+
yield* service.install;
349+
// A launcher outlives its shortcut, so keying the stop on the shortcut
350+
// would leave a server running with nothing left to manage it.
351+
yield* fs.remove(shortcutPath, { force: true });
352+
353+
expect(yield* service.uninstall).toBe(true);
354+
expect(yield* fs.exists(pidPath)).toBe(false);
355+
}).pipe(TestClock.withLive),
356+
);
357+
319358
it.effect("fails closed off Windows", () =>
320359
Effect.gen(function* () {
321360
const { service } = yield* makeHarness("linux");

‎apps/server/src/cloud/bootServiceWindows.ts‎

Lines changed: 61 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,14 @@ export interface WindowsBootServicePlan extends BootServicePlan {
125125
export interface WindowsPreflight {
126126
readonly shellRunning: boolean;
127127
readonly entryDisabled: boolean;
128+
/** Absent when no shortcut exists yet. */
129+
readonly shortcutTarget?: string;
130+
readonly shortcutArguments?: string;
131+
}
132+
133+
/** Windows only. What the shortcut must point at for the service to work. */
134+
export function expectedShortcutArguments(plan: WindowsBootServicePlan): string {
135+
return `-NoLogo -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${plan.startupScriptPath}"`;
128136
}
129137

130138
/**
@@ -197,9 +205,7 @@ export function renderShortcutScript(plan: WindowsBootServicePlan): string {
197205
"$shell = New-Object -ComObject WScript.Shell",
198206
"$shortcut = $shell.CreateShortcut($shortcutPath)",
199207
"$shortcut.TargetPath = Join-Path $env:SystemRoot 'System32\\WindowsPowerShell\\v1.0\\powershell.exe'",
200-
`$shortcut.Arguments = ${quotePowerShellLiteral(
201-
`-NoLogo -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${plan.startupScriptPath}"`,
202-
)}`,
208+
`$shortcut.Arguments = ${quotePowerShellLiteral(expectedShortcutArguments(plan))}`,
203209
"$shortcut.WorkingDirectory = $env:USERPROFILE",
204210
`$shortcut.Description = ${quotePowerShellLiteral(`${SHORTCUT_NAME}, started at sign-in`)}`,
205211
"# Minimized, because PowerShell paints a console before it hides itself.",
@@ -222,11 +228,18 @@ export function parseProbeOutput(stdout: string): WindowsPreflight | undefined {
222228
const match = new RegExp(`^${key}=(True|False)\\s*$`, "im").exec(stdout)?.[1];
223229
return match === undefined ? undefined : match === "True";
224230
};
231+
const readText = (key: string) => new RegExp(`^${key}=(.*)$`, "im").exec(stdout)?.[1]?.trim();
225232
const shellRunning = read("shell");
226233
const entryDisabled = read("disabled");
227-
return shellRunning === undefined || entryDisabled === undefined
228-
? undefined
229-
: { shellRunning, entryDisabled };
234+
if (shellRunning === undefined || entryDisabled === undefined) return undefined;
235+
const shortcutTarget = readText("target");
236+
const shortcutArguments = readText("arguments");
237+
return {
238+
shellRunning,
239+
entryDisabled,
240+
...(shortcutTarget === undefined ? {} : { shortcutTarget }),
241+
...(shortcutArguments === undefined ? {} : { shortcutArguments }),
242+
};
230243
}
231244

232245
export interface WindowsBootServiceInput {
@@ -409,29 +422,28 @@ export const make = Effect.fn("cloud.boot_service_windows.make")(function* (
409422
*/
410423
const requestStop = Effect.gen(function* () {
411424
const recordedPid = yield* fs.readFileString(pidPath).pipe(Effect.option);
412-
if (Option.isNone(recordedPid)) return;
425+
if (Option.isNone(recordedPid)) return false;
413426
const pid = Number.parseInt(recordedPid.value.trim(), 10);
414427
if (!Number.isInteger(pid) || pid <= 0 || !(yield* processIsAlive(pid))) {
415428
// The launcher died without cleaning up. Nothing to wait for.
416429
yield* fs.remove(pidPath, { force: true }).pipe(Effect.ignore);
417-
return;
430+
return false;
418431
}
419432

420-
// A missing runtime directory must not block an uninstall: the shortcut is
421-
// the thing the user asked to remove, and it lives elsewhere.
422-
const requested = yield* fs.writeFileString(stopRequestPath, "").pipe(
423-
Effect.as(true),
424-
Effect.orElseSucceed(() => false),
425-
);
426-
if (!requested) return;
433+
// A launcher is confirmed alive, so a failed write must fail the whole
434+
// operation. Swallowing it would let the caller carry on and start a second
435+
// server against the same database.
436+
yield* fs
437+
.writeFileString(stopRequestPath, "")
438+
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
427439

428440
const timeoutMs = Duration.toMillis(input.stopRequestTimeout ?? STOP_REQUEST_TIMEOUT);
429441
const pollMs = Math.min(timeoutMs, Duration.toMillis(STOP_REQUEST_ACK_POLL));
430442
const attempts = Math.max(1, Math.ceil(timeoutMs / pollMs));
431443
for (let attempt = 0; attempt < attempts; attempt += 1) {
432444
yield* Effect.sleep(Duration.millis(pollMs));
433445
const stillRunning = yield* fs.exists(pidPath).pipe(Effect.orElseSucceed(() => true));
434-
if (!stillRunning) return;
446+
if (!stillRunning) return true;
435447
}
436448
// Refusing here is the whole point. Carrying on would write over a launcher
437449
// we could not confirm dead.
@@ -543,19 +555,18 @@ export const make = Effect.fn("cloud.boot_service_windows.make")(function* (
543555
const installed = yield* fs
544556
.exists(unitPath)
545557
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
546-
if (installed) {
547-
yield* requestStop;
548-
}
558+
// Keyed on the pid file, never on the shortcut. A launcher outlives a
559+
// manually deleted shortcut, and starting a second one alongside it would
560+
// put two servers on the same database.
561+
const stopped = yield* requestStop;
549562

550563
yield* Effect.gen(function* () {
551-
if (installed) {
552-
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
553-
if (
554-
Option.isSome(previousStateText) &&
555-
serviceStateHasPendingUpdate(previousStateText.value)
556-
) {
557-
return yield* new BootServiceUpdatePendingError();
558-
}
564+
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
565+
if (
566+
Option.isSome(previousStateText) &&
567+
serviceStateHasPendingUpdate(previousStateText.value)
568+
) {
569+
return yield* new BootServiceUpdatePendingError();
559570
}
560571
yield* writeDurably(launcherPath, launcherSource);
561572
yield* writeDurably(
@@ -577,7 +588,7 @@ export const make = Effect.fn("cloud.boot_service_windows.make")(function* (
577588
yield* runPowerShellScript("starting the service", startupScriptPath);
578589
}).pipe(
579590
Effect.tapError(() =>
580-
installed
591+
installed || stopped
581592
? runPowerShellScript(
582593
"restarting the service after a failed update",
583594
startupScriptPath,
@@ -590,14 +601,16 @@ export const make = Effect.fn("cloud.boot_service_windows.make")(function* (
590601

591602
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
592603
yield* requireWindows;
593-
if (
594-
!(yield* fs
595-
.exists(unitPath)
596-
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
597-
)
598-
return false;
604+
const installed = yield* fs
605+
.exists(unitPath)
606+
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
607+
608+
// Stop first, and decide that on the pid file rather than the shortcut. A
609+
// launcher survives someone deleting the shortcut by hand, and leaving it
610+
// running is exactly what the user asked us not to do.
611+
const stopped = yield* requestStop;
612+
if (!installed && !stopped) return false;
599613

600-
yield* requestStop;
601614
// A shortcut is an ordinary file, so removing it needs no PowerShell. That
602615
// also means a missing or broken generated script cannot strand the entry.
603616
yield* fs
@@ -632,13 +645,26 @@ export const make = Effect.fn("cloud.boot_service_windows.make")(function* (
632645
fs.readFileString(statePath).pipe(Effect.option),
633646
]);
634647
const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
648+
// Read the shortcut itself back, because the script that wrote it matching
649+
// proves nothing about the .lnk someone may have edited or replaced since.
650+
const shortcut = yield* runShortcutScript(
651+
"checking the Windows Startup shortcut",
652+
"Probe",
653+
).pipe(
654+
Effect.map((probe) => parseProbeOutput(probe.stdout)),
655+
Effect.orElseSucceed(() => undefined),
656+
);
657+
const shortcutMatches =
658+
shortcut?.shortcutTarget === powershell &&
659+
shortcut.shortcutArguments === expectedShortcutArguments(plan);
635660
// Duplicated from the Linux status. The runtime and state checks are the
636661
// same, but the Linux copy also compares the systemd unit, so it cannot be
637662
// shared without changing the Linux path.
638663
return {
639664
supported: true,
640665
installed: true,
641666
current:
667+
shortcutMatches &&
642668
Option.isSome(startupScript) &&
643669
startupScript.value === renderStartupScript(plan) &&
644670
// The shortcut script embeds the shortcut path, the interpreter and the

‎apps/server/src/serviceLauncher.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
decodeServiceState,
1212
isExactServiceVersion,
1313
SERVICE_LAUNCHER_PROTOCOL,
14+
SERVICE_PID_FILE,
1415
SERVICE_STOP_MARKER_FILE,
1516
SERVICE_STOP_REQUEST_FILE,
1617
} from "./cloud/serviceProtocol.ts";
@@ -427,3 +428,43 @@ process.exit(1);
427428
}).pipe(TestClock.withLive),
428429
);
429430
});
431+
432+
it.layer(NodeServices.layer)("self-supervising pid ownership", (it) => {
433+
it.effect("a second launcher exits rather than running a second server", () =>
434+
Effect.gen(function* () {
435+
const fs = yield* FileSystem.FileSystem;
436+
const path = yield* Path.Path;
437+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-pid-" });
438+
const statePath = path.join(root, "runtime", "service-state.json");
439+
const versionDir = path.join(root, "runtime", "versions", "1.0.0");
440+
const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs");
441+
yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
442+
yield* fs.writeFileString(entryPath, "setInterval(() => {}, 1_000);\n");
443+
yield* fs.writeFileString(path.join(versionDir, ".install-complete"), "1.0.0\n");
444+
yield* Effect.promise(() =>
445+
writeServiceState(statePath, {
446+
protocol: SERVICE_LAUNCHER_PROTOCOL,
447+
activeVersion: "1.0.0",
448+
}),
449+
);
450+
const state = yield* Effect.promise(() => readServiceState(statePath));
451+
452+
const first = new Launcher(root, state, { selfSupervise: true, restartDelayMs: 5 });
453+
const firstRunning = first.run();
454+
yield* Effect.sleep("100 millis");
455+
const pidPath = path.join(root, "runtime", SERVICE_PID_FILE);
456+
assert.isTrue(yield* fs.exists(pidPath));
457+
458+
// The Startup shortcut firing twice must not put two servers on one
459+
// database. The second launcher sees a live owner and gives up.
460+
const second = new Launcher(root, state, { selfSupervise: true, restartDelayMs: 5 });
461+
yield* Effect.promise(() => second.run());
462+
// It also must not take the first launcher's pid file with it on the way out.
463+
assert.isTrue(yield* fs.exists(pidPath));
464+
465+
yield* Effect.promise(() => first.stop("SIGTERM"));
466+
yield* Effect.promise(() => firstRunning);
467+
assert.isFalse(yield* fs.exists(pidPath));
468+
}).pipe(TestClock.withLive),
469+
);
470+
});

0 commit comments

Comments
 (0)