Skip to content

Commit 040b68a

Browse files
committed
fix(server): refuse deferred installs during legacy service migration
1 parent 34982e5 commit 040b68a

5 files changed

Lines changed: 115 additions & 21 deletions

File tree

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

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
44
import * as ConfigProvider from "effect/ConfigProvider";
55
import * as Duration from "effect/Duration";
66
import * as Effect from "effect/Effect";
7+
import * as Exit from "effect/Exit";
78
import * as FileSystem from "effect/FileSystem";
89
import * as Layer from "effect/Layer";
910
import * as Path from "effect/Path";
@@ -180,7 +181,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
180181
input.args[0] === "--version"
181182
? // The runtime under test reports the version of the directory it
182183
// was launched from, like the real executable.
183-
`t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n`
184+
`t3 v${/[\\/]versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n`
184185
: input.command === "loginctl" && input.args[0] === "show-user"
185186
? `${control.linger}\n`
186187
: input.args[1] === "is-enabled"
@@ -516,6 +517,39 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
516517
}),
517518
);
518519

520+
it.effect("install with start=false refuses a legacy state before writing anything", () =>
521+
Effect.gen(function* () {
522+
const { service, fs, statePath, commands, makeService } = yield* makeHarness();
523+
const path = yield* Path.Path;
524+
const plan = yield* service.install();
525+
const unitBefore = yield* fs.readFileString(plan.unitPath);
526+
const legacyState = '{"protocol":2,"activeVersion":"1.2.3"}';
527+
yield* fs.writeFileString(statePath, legacyState);
528+
commands.length = 0;
529+
530+
const newer = yield* makeService(undefined, "1.2.4");
531+
const result = yield* Effect.exit(newer.install({ start: false }));
532+
533+
expect(yield* fs.readFileString(statePath)).toBe(legacyState);
534+
expect(yield* fs.readFileString(plan.unitPath)).toBe(unitBefore);
535+
expect(
536+
yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
537+
).toBe(false);
538+
expect(commands).toEqual([]);
539+
expect(Exit.isFailure(result)).toBe(true);
540+
if (Exit.isSuccess(result)) return;
541+
const reason = result.cause.reasons[0];
542+
if (reason?._tag !== "Fail") {
543+
expect.fail(`Expected a typed Fail cause, got: ${reason?._tag ?? "no reason"}`);
544+
}
545+
expect(reason.error).toMatchObject({
546+
_tag: "BootServiceMigrationRequiredError",
547+
message:
548+
"Cannot defer this install while the service state migration is pending. Start or restart the service first.",
549+
});
550+
}),
551+
);
552+
519553
it.effect("install with start=false keeps the marker when a later write fails", () =>
520554
Effect.gen(function* () {
521555
const { service, fs, statePath, makeService } = yield* makeHarness();

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
SERVICE_RESTART_PENDING_FILE,
2626
SERVICE_STATE_FILE,
2727
compareExactServiceVersions,
28+
parseLegacyServiceState,
2829
parseServiceState,
2930
serviceStateActiveVersion,
3031
serviceStateHasPendingUpdate,
@@ -491,6 +492,15 @@ export class BootServiceUpdatePendingError extends Schema.TaggedError<BootServic
491492
}
492493
}
493494

495+
export class BootServiceMigrationRequiredError extends Schema.TaggedError<BootServiceMigrationRequiredError>()(
496+
"BootServiceMigrationRequiredError",
497+
{},
498+
) {
499+
override get message(): string {
500+
return "Cannot defer this install while the service state migration is pending. Start or restart the service first.";
501+
}
502+
}
503+
494504
export class BootServiceDowngradeRefusedError extends Schema.TaggedError<BootServiceDowngradeRefusedError>()(
495505
"BootServiceDowngradeRefusedError",
496506
{
@@ -509,6 +519,7 @@ export type BootServiceError =
509519
| BootServiceInstallError
510520
| BootServicePrerequisiteError
511521
| BootServiceUpdatePendingError
522+
| BootServiceMigrationRequiredError
512523
| BootServiceDowngradeRefusedError;
513524

514525
export interface BootServiceStatus {
@@ -755,6 +766,22 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
755766
readonly start?: boolean;
756767
}) {
757768
const manager = yield* requireManager;
769+
const start = options?.start !== false;
770+
let deferredInstallUnitExists = false;
771+
if (!start) {
772+
deferredInstallUnitExists = yield* fs
773+
.exists(unitPath)
774+
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
775+
}
776+
// A deferred install leaves the launcher running, so it must not replace a
777+
// protocol-2 state while startup is validating and migrating that state.
778+
if (deferredInstallUnitExists) {
779+
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
780+
if (Option.isSome(previousStateText) && parseLegacyServiceState(previousStateText.value)) {
781+
return yield* new BootServiceMigrationRequiredError();
782+
}
783+
}
784+
758785
yield* fs
759786
.makeDirectory(input.logsDir, { recursive: true })
760787
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -827,7 +854,6 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
827854
// state file itself. That case is refused below, before anything is
828855
// written, from the same read the downgrade check uses; the stop that
829856
// normally serialises against the launcher is skipped on purpose.
830-
const start = options?.start !== false;
831857
if (installed && start) {
832858
yield* runSteps(manager.stop);
833859
}
@@ -836,6 +862,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
836862
if (installed) {
837863
const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
838864
if (Option.isSome(previousStateText)) {
865+
if (!start && parseLegacyServiceState(previousStateText.value)) {
866+
return yield* new BootServiceMigrationRequiredError();
867+
}
839868
if (serviceStateHasPendingUpdate(previousStateText.value)) {
840869
return yield* new BootServiceUpdatePendingError();
841870
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { expect, it } from "@effect/vitest";
2+
3+
import { parseLegacyServiceState } from "./serviceProtocol.ts";
4+
5+
it("parses only the exact protocol-2 install state", () => {
6+
expect(parseLegacyServiceState('{"protocol":2,"activeVersion":"1.2.3"}')).toEqual({
7+
protocol: 2,
8+
activeVersion: "1.2.3",
9+
});
10+
});
11+
12+
it.each([
13+
'{"protocol":2,"activeVersion":"1.2.3","update":{}}',
14+
'{"protocol":2,"activeVersion":"1.2.3","extra":true}',
15+
'{"protocol":3,"activeVersion":"1.2.3"}',
16+
'{"protocol":4,"activeVersion":"1.2.3"}',
17+
'{"protocol":2,"activeVersion":"latest"}',
18+
"null",
19+
"[]",
20+
"{ malformed",
21+
])("rejects non-migratable service state %s", (contents) => {
22+
expect(parseLegacyServiceState(contents)).toBeUndefined();
23+
});

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ export interface ServiceState {
3131
readonly update?: ServiceUpdateRecord;
3232
}
3333

34+
export interface LegacyServiceState {
35+
readonly protocol: 2;
36+
readonly activeVersion: string;
37+
}
38+
3439
/** Context is copied from launcher-owned state when a child is spawned. */
3540
export interface ServiceLauncherContext {
3641
readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;
@@ -179,6 +184,25 @@ export function parseServiceState(value: string): ServiceState | undefined {
179184
}
180185
}
181186

187+
/** Accepts only the two-field state written by the protocol-2 installer. */
188+
export function parseLegacyServiceState(value: string): LegacyServiceState | undefined {
189+
try {
190+
const parsed: unknown = JSON.parse(value);
191+
if (!isRecord(parsed)) return undefined;
192+
const keys = Object.keys(parsed);
193+
return keys.length === 2 &&
194+
keys.includes("protocol") &&
195+
keys.includes("activeVersion") &&
196+
parsed.protocol === 2 &&
197+
typeof parsed.activeVersion === "string" &&
198+
isExactServiceVersion(parsed.activeVersion)
199+
? { protocol: 2, activeVersion: parsed.activeVersion }
200+
: undefined;
201+
} catch {
202+
return undefined;
203+
}
204+
}
205+
182206
/** Detects an in-flight update across launcher protocol versions before replacing its state. */
183207
export function serviceStateHasPendingUpdate(value: string): boolean {
184208
try {

‎apps/server/src/serviceLauncher.ts‎

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
compareExactServiceVersions,
2323
decodeServiceLauncherChildMessage,
2424
isExactServiceVersion,
25+
parseLegacyServiceState,
2526
parseServiceState,
2627
SERVICE_LAUNCHER_CONTEXT_ENV,
2728
SERVICE_LAUNCHER_PROTOCOL,
@@ -421,25 +422,8 @@ export async function readServiceStateForLauncher(
421422
const state = parseServiceState(contents);
422423
if (state !== undefined) return state;
423424

424-
let parsed: unknown;
425-
try {
426-
parsed = JSON.parse(contents) as unknown;
427-
} catch {
428-
throw new Error("Service state is invalid or unsupported.");
429-
}
430-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
431-
throw new Error("Service state is invalid or unsupported.");
432-
}
433-
const legacy = parsed as Record<string, unknown>;
434-
const keys = Object.keys(legacy);
435-
if (
436-
keys.length !== 2 ||
437-
!keys.includes("protocol") ||
438-
!keys.includes("activeVersion") ||
439-
legacy.protocol !== 2 ||
440-
typeof legacy.activeVersion !== "string" ||
441-
!isExactServiceVersion(legacy.activeVersion)
442-
) {
425+
const legacy = parseLegacyServiceState(contents);
426+
if (legacy === undefined) {
443427
throw new Error("Service state is invalid or unsupported.");
444428
}
445429
if (!(await runtimeExists(baseDir, legacy.activeVersion))) {

0 commit comments

Comments
 (0)