Skip to content

Commit 7b1b4ce

Browse files
committed
fix(service): give a Windows cold start room to bind, without loosening zero budget
Reimplements #3039 (author @ntdatt812), whose diagnosis and production logic are both right. confirmServiceServing had a fixed 20s deadline and returned as soon as the clock passed it. A Windows cold start does NTFS ACL hardening and previous- session journal recovery before the listener exists, so #3009 recorded a service that bound a few seconds late and then stayed healthy -- reported as a terminal failure with exit 1. The caller's fallback is to start a second proxy against a port that is about to be taken, which is worse than waiting. Windows now gets 45s, every other platform keeps 20s, and the loop knocks once more after a short grace before calling it dead. Two changes to #3039 as submitted: - It relaxed `expect(probes).toBe(1)` to `toBeGreaterThanOrEqual(1)` in the zero-budget test. That assertion is what stops a future change from sleeping when the caller asked not to wait, and "at least one" passes against exactly the version it is meant to forbid. The `waited` guard already preserves the contract, so the original assertion is restored and the comment says why. - Its Windows-budget test asserted only `toBeGreaterThan(linux)`, which accepts 21s. The reported service bound past 20s, so the number is the contract: the test now pins 45_000 absolutely. Mutation-checked, both restored afterwards: remove the `waited` guard -> 181 pass / 1 fail, the zero-budget test remove the grace probe -> 181 pass / 1 fail, the #3009 test Closes #3009.
1 parent 9d122dd commit 7b1b4ce

2 files changed

Lines changed: 79 additions & 3 deletions

File tree

‎src/service.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -660,6 +660,23 @@ export function installedServiceListenPort(): number {
660660

661661
export const SERVICE_INSTALL_HEALTH_MS = 20_000;
662662

663+
/**
664+
* Windows gets a longer budget because its cold start does more before the
665+
* listener exists: NTFS ACL hardening and previous-session journal recovery
666+
* both run first, and #3009 recorded a service that bound a few seconds past
667+
* the 20s deadline and then stayed healthy. Reporting that as a terminal
668+
* repair failure is worse than waiting — the caller's fallback is to start a
669+
* second proxy against a port that is about to be taken.
670+
*/
671+
export const SERVICE_INSTALL_HEALTH_WINDOWS_MS = 45_000;
672+
673+
/** The health budget for the platform this is running on. */
674+
export function serviceInstallHealthMs(
675+
platform: NodeJS.Platform = process.platform,
676+
): number {
677+
return platform === "win32" ? SERVICE_INSTALL_HEALTH_WINDOWS_MS : SERVICE_INSTALL_HEALTH_MS;
678+
}
679+
663680
/**
664681
* Whether a proxy actually answers on the port this install/start just produced.
665682
*
@@ -690,12 +707,23 @@ export async function confirmServiceServing(
690707
const now = deps.now ?? Date.now;
691708
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(r => setTimeout(r, ms)));
692709
const probe = deps.probe ?? (async (p, h) => !!(await proxyIdentityAt(p, { hostname: h })));
693-
const deadline = now() + (deps.timeoutMs ?? SERVICE_INSTALL_HEALTH_MS);
710+
const deadline = now() + (deps.timeoutMs ?? serviceInstallHealthMs());
711+
let waited = false;
694712
for (;;) {
695713
if (await probe(port, hostname)) return { ok: true, port };
696-
if (now() >= deadline) return { ok: false, port };
714+
if (now() >= deadline) break;
715+
await sleep(500);
716+
waited = true;
717+
}
718+
// The probe that ran last started before the deadline, so a service that binds
719+
// during it is reported as dead (#3009). Knock once more after a short grace
720+
// before calling it a failure. A zero budget means the caller asked not to
721+
// wait, so it gets exactly the single probe it asked for and nothing more.
722+
if (waited) {
697723
await sleep(500);
724+
if (await probe(port, hostname)) return { ok: true, port };
698725
}
726+
return { ok: false, port };
699727
}
700728

701729
/**

‎tests/service.test.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { pathToFileURL } from "node:url";
77
import * as serviceModule from "../src/service";
88
import { saveConfig } from "../src/config";
99
import { windowsEnvIndirectBatchValue } from "../src/lib/win-paths";
10-
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, stableLauncherEntry, systemdNeedsDaemonReload, systemdServiceInstallCleanupOps, uninstallSystemd, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy } from "../src/service";
10+
import { assertServiceAuthEnvironment, assertServiceEnvironmentMatchesInstall, bakedServicePathsDiagnostic, confirmServiceServing, launchdListenPort, systemdListenPort, buildPlist, buildUnit, buildWindowsLauncherVbs, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsServiceScript, buildWindowsTaskXml, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, installFreshWindowsSchedulerSafely, installServiceSafely, launchctlLoadFailed, launchdJobMatchesPlist, normalizeServiceSubcommand, parseServiceArgs, parseServiceInstallState, planServiceCommand, prepareServiceInstall, probeServiceInstallation, readWindowsSchedulerXmlState, registerFreshWindowsSchedulerTask, removeNativeWindowsServiceForScheduler, repairService, resolveServiceListenPort, runLaunchctl, selectServiceSubcommand, SERVICE_INSTALL_HEALTH_MS, SERVICE_INSTALL_HEALTH_WINDOWS_MS, serviceInstallHealthMs, serviceLogPath, serviceStartableFromTray, serviceStatusReport, serviceRetryCommand, serviceStatusSummary, stableLauncherEntry, systemdNeedsDaemonReload, systemdServiceInstallCleanupOps, uninstallSystemd, windowsListenPort, winswListenPort, startLaunchd, windowsTaskRegistrationHealthy } from "../src/service";
1111
import type { ServiceDiagnostic } from "../src/service";
1212
import { definitionCarriesCredential, resolvedProxyEnv, writeServiceDefinitionFile } from "../src/service";
1313
import { buildWinswXml } from "../src/lib/winsw";
@@ -3142,9 +3142,57 @@ describe("service serving confirmation", () => {
31423142
now: () => 0,
31433143
timeoutMs: 0,
31443144
});
3145+
// Exactly one. "At least one" would also pass against a version that
3146+
// sleeps and knocks again, which is the opposite of what a zero budget
3147+
// asks for — #3039 relaxed this to toBeGreaterThanOrEqual and that is
3148+
// precisely the assertion the grace probe must not be allowed to satisfy.
31453149
expect(probes).toBe(1);
31463150
});
31473151

3152+
// #3009: a Windows cold start does NTFS ACL hardening and previous-session
3153+
// journal recovery before the listener exists, so the service can bind
3154+
// seconds after the deadline and then stay healthy. `ocx service repair`
3155+
// reported that as a terminal failure with exit 1, and the caller's fallback
3156+
// is to start a second proxy against a port that is about to be taken.
3157+
test("accepts a service that binds during the grace after the deadline", async () => {
3158+
let now = 0;
3159+
let probes = 0;
3160+
const out = await confirmServiceServing({
3161+
port: 10100,
3162+
// Answers only once the clock is past the deadline, which is the shape
3163+
// the report describes: healthy, just not within the budget.
3164+
probe: async () => { probes += 1; return now > 2_000; },
3165+
sleep: async ms => { now += ms; },
3166+
now: () => now,
3167+
timeoutMs: 2_000,
3168+
});
3169+
expect(out).toEqual({ ok: true, port: 10100 });
3170+
expect(probes).toBeGreaterThan(1);
3171+
});
3172+
3173+
test("still fails a service that never binds", async () => {
3174+
let now = 0;
3175+
const out = await confirmServiceServing({
3176+
port: 10100,
3177+
probe: async () => false,
3178+
sleep: async ms => { now += ms; },
3179+
now: () => now,
3180+
timeoutMs: 2_000,
3181+
});
3182+
expect(out).toEqual({ ok: false, port: 10100 });
3183+
});
3184+
3185+
// Windows is the platform the extra budget exists for; everything else keeps
3186+
// the original 20s so this cannot slow a healthy Linux install down. Pinned
3187+
// absolutely, not relatively: a relational assertion accepts 21s, and the
3188+
// reported service bound past 20s, so the number is the contract.
3189+
test("gives Windows a longer cold-start budget than the other platforms", () => {
3190+
expect(serviceInstallHealthMs("win32")).toBe(SERVICE_INSTALL_HEALTH_WINDOWS_MS);
3191+
expect(SERVICE_INSTALL_HEALTH_WINDOWS_MS).toBe(45_000);
3192+
expect(serviceInstallHealthMs("linux")).toBe(SERVICE_INSTALL_HEALTH_MS);
3193+
expect(serviceInstallHealthMs("darwin")).toBe(SERVICE_INSTALL_HEALTH_MS);
3194+
});
3195+
31483196
// A service reinstall invalidates the pidfile, so resolving the target through
31493197
// it (findLiveProxy) would report a serving service as dead. Ask the baked port.
31503198
test("probes the port it was given rather than resolving one", async () => {

0 commit comments

Comments
 (0)