Skip to content
Open
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
60 changes: 60 additions & 0 deletions apps/server/src/cloud/serviceLauncherClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import { assert, expect, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";

import {
SERVICE_LAUNCHER_CONTEXT_ENV,
Expand Down Expand Up @@ -148,6 +150,64 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])(
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

// regression: #42653 an older launcher can commit durably but reply after the 30-second wait
it.effect.each([
{ status: "committed" as const, continues: true },
{ status: "pending" as const, continues: false },
])(
"after an unanswered prepared, a $status service state decides the trial",
({ status, continues }) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-trial-timeout-" });
const baseDir = path.join(root, ".t3");
const pending = {
id: "update-1",
fromVersion: "1.0.0",
targetVersion: "1.1.0",
dbPath: "/tmp/state.sqlite",
status: "pending" as const,
};
const committed = {
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
};
yield* fs.makeDirectory(path.join(baseDir, "runtime"), { recursive: true });
yield* fs.writeFileString(
path.join(baseDir, "runtime", "service-state.json"),
JSON.stringify(
status === "committed"
? { protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.1.0", update: committed }
: { protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.0.0", update: pending },
),
);
const host = new FakeLauncherProcess({
protocol: SERVICE_LAUNCHER_PROTOCOL,
childVersion: "1.1.0",
update: pending,
});
host.env["HOME"] = root;
const client = yield* makeClient(host, "1.1.0").pipe(
Effect.provideService(HostProcess.Platform, "darwin"),
);
const prepared = yield* Effect.forkChild(Effect.exit(client.prepareTrial({ baseDir })), {
startImmediately: true,
});
yield* TestClock.adjust("30 seconds");
const exit = yield* Fiber.join(prepared);
if (continues) {
expect(exit).toEqual(Exit.succeed(committed));
} else {
expect(exit).toEqual(
Exit.fail(new ServiceLauncherClient.ServiceLauncherClientError({ operation: "timeout" })),
);
}
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it.effect("returns the launcher-generated ID only after update acceptance", () =>
Effect.gen(function* () {
const host = new FakeLauncherProcess({
Expand Down
48 changes: 31 additions & 17 deletions apps/server/src/cloud/serviceLauncherClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import {
import {
decodeServiceLauncherContext,
decodeServiceLauncherParentMessage,
parseServiceState,
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_STATE_FILE,
type ServiceLauncherChildMessage,
type ServiceLauncherParentMessage,
type SupportedLauncherProtocol,
Expand Down Expand Up @@ -368,24 +370,36 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o
{ type: "prepared", updateId: pending.id },
(reply) => reply.type === "committed" && reply.updateId === pending.id,
).pipe(
Effect.flatMap((reply) =>
reply.type !== "committed"
? Effect.die("service launcher returned an impossible prepared response")
: repointLaunchers({
baseDir: input.baseDir,
targetVersion: pending.targetVersion,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
Effect.provideService(HostProcess.Environment, environment),
Effect.provideService(HostProcess.Platform, platform),
Effect.as({
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
}),
// An older launcher may finish slow cleanup before it replies; its durable commit is the decision.
Effect.catchIf(
(error) => error.operation === "timeout",
(error) =>
fs.readFileString(path.join(input.baseDir, "runtime", SERVICE_STATE_FILE)).pipe(
Effect.map(parseServiceState),
Effect.orElseSucceed(() => undefined),
Effect.flatMap((state) =>
state?.update?.id === pending.id && state.update.status === "committed"
? Effect.void
: Effect.fail(error),
),
),
),
Effect.andThen(
repointLaunchers({
baseDir: input.baseDir,
targetVersion: pending.targetVersion,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
Effect.provideService(HostProcess.Environment, environment),
Effect.provideService(HostProcess.Platform, platform),
Effect.as({
id: pending.id,
fromVersion: pending.fromVersion,
targetVersion: pending.targetVersion,
status: "committed" as const,
}),
),
),
),
)
Expand Down
51 changes: 49 additions & 2 deletions apps/server/src/serviceLauncher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,18 @@ const spawnHook = vi.hoisted(() => ({
}));

const failRm = vi.hoisted(() => ({ path: undefined as string | undefined }));
const holdRm = vi.hoisted(() => ({
current: undefined as ((path: unknown) => Promise<void>) | undefined,
}));

vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof NodeFSP>();
const rm: typeof actual.rm = (path, options) =>
path === failRm.path
? Promise.reject(Object.assign(new Error("EACCES"), { code: "EACCES" }))
: actual.rm(path, options);
: holdRm.current === undefined
? actual.rm(path, options)
: holdRm.current(path).then(() => actual.rm(path, options));
return { ...actual, rm };
});

Expand Down Expand Up @@ -405,6 +410,9 @@ setInterval(() => {}, 1_000);
}[scenario],
);
assert.equal(yield* fs.readFileString(databasePath), "before trial");
// The child can answer "committed" before the launcher discards the backup; let it finish.
yield* Effect.promise(() => launcher.stop("SIGTERM"));
yield* Effect.promise(() => running);
assert.isFalse(yield* fs.exists(backupPath));
}),
);
Expand Down Expand Up @@ -1210,6 +1218,7 @@ process.exit(0);
const statePath = path.join(root, "runtime", "service-state.json");
const databasePath = path.join(root, "userdata", "state.sqlite");
const activatedPath = path.join(root, "activated");
const backupAtCommitPath = path.join(root, "backup-at-commit");
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
yield* fs.writeFileString(databasePath, "before trial");
const unit = yield* fakeServiceUnit(fs, path, root, "1.0.0", render);
Expand All @@ -1235,6 +1244,10 @@ if (context.update?.status === "pending") {
assert.equal(state.activeVersion, "1.1.0");
assert.equal(state.update.status, "committed");
writeFileSync(${JSON.stringify(activatedPath)}, message.updateId);
writeFileSync(
${JSON.stringify(backupAtCommitPath)},
String(existsSync(${JSON.stringify(path.join(root, "runtime", "db-backup"))} + "/" + message.updateId)),
);
process.exit(0);
}
});
Expand Down Expand Up @@ -1293,9 +1306,43 @@ if (context.update?.status === "pending") {
yield* Effect.promise(() => fresh.stop("SIGTERM"));
yield* Effect.promise(() => running);
});
return { fs, root, unit, recover };
return { fs, root, unit, recover, backupAtCommitPath };
});

// The trial waits only 30 seconds for "committed"; backup cleanup can take minutes on a full disk.
it.effect("tells the trial it is committed before discarding the database backup", () =>
Effect.gen(function* () {
// Once "committed" is sent, hold the backup removal until the trial has read it and exited.
let committedSent = false;
const trialExited = Promise.withResolvers<void>();
yield* Effect.acquireRelease(
Effect.sync(() => {
spawnHook.current = (child) => {
child.send = new Proxy(child.send, {
apply(send, self, args: Parameters<typeof child.send>) {
if ((args[0] as { type?: unknown } | null)?.type === "committed") {
committedSent = true;
child.once("exit", () => trialExited.resolve());
}
return Reflect.apply(send, self, args);
},
});
};
holdRm.current = async (target) => {
if (committedSent && String(target).includes("db-backup")) await trialExited.promise;
};
}),
() =>
Effect.sync(() => {
spawnHook.current = undefined;
holdRm.current = undefined;
}),
);
const { fs, backupAtCommitPath } = yield* commitUpdate();
assert.equal(yield* fs.readFileString(backupAtCommitPath), "true");
}),
);

it.effect.each([
{
name: "systemd after a protocol-3 local upgrade",
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/serviceLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1392,10 +1392,10 @@ export class Launcher {
};
await this.#selectState(next);
child.role = "active";
await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
try {
await sendMessage(child.process, { type: "committed", updateId: committed.id });
} finally {
await discardDatabaseBackup(this.#baseDir, committed.id).catch(() => undefined);
await this.#repointServiceUnit(committed.targetVersion);
}
}
Expand Down
6 changes: 4 additions & 2 deletions docs/internals/07_server-updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ restarts never depend on npm cache eviction or a moving tag.
3. Start the new runtime as a trial. It must finish migrations, acquire fallible dependencies, bind
HTTP, and hold long-running roots at the activation gate before reporting `prepared`.
4. Only after the launcher commits the new version durably and replies `committed` may the child
release activation gates and accept work. A failed or timed-out trial stops and restores the
snapshot before booting the old version.
release activation gates and accept work. The launcher replies before slow cleanup, but a remote
update keeps the old launcher, so a trial whose wait times out also accepts this update's commit
from the state file. A failed or timed-out trial stops and restores the snapshot before booting
the old version.

## Client acknowledgement

Expand Down
Loading