fix(server): validate update rollback boundaries

This commit is contained in:
Theo Browne committed 2026-08-01 00:07:09 -07:00
1 parent c072888cff
commit cd25a3de9a
14 files changed
+499 -48

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@ import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import { applySystemdSelfUpdatePlan } from "../cloud/systemdSelfUpdate.ts";
import type * as ServerConfig from "../config.ts";
import { validateMigrationIdentities } from "../persistence/Migrations.ts";
import { validateAutomaticUpdateMigrationFrontier } from "../persistence/Migrations.ts";
import * as ProcessRunner from "../processRunner.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -169,7 +169,7 @@ const serviceValidateUpdateCommand = Command.make("_validate-update", {
const NodeSqliteClient = yield* Effect.promise(
() => import("../persistence/NodeSqliteClient.ts"),
);
yield* validateMigrationIdentities().pipe(
yield* validateAutomaticUpdateMigrationFrontier().pipe(
Effect.scoped,
Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
);
+1
View File
@@ -535,6 +535,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(SystemdSelfUpdatePlan))),
);
assert.equal(plan.previousUnit, previousUnit);
assert.equal(plan.serviceUnit, BOOT_SERVICE_UNIT_FILE);
assert.include(plan.nextUnit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
assert.equal(
plan.runtimeStatePath,
+1
View File
@@ -394,6 +394,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
fromVersion: packageJson.version,
targetVersion,
currentPid: process.pid,
serviceUnit: BOOT_SERVICE_UNIT_FILE,
unitPath,
previousUnit,
nextUnit,
@@ -0,0 +1,237 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Opt-in acceptance coverage for the real systemd handoff and rollback path.
* Every unit and file is uniquely named; this must never target t3code.service.
*
* Run on Linux with a user manager:
* T3_SYSTEMD_SELF_UPDATE_ACCEPTANCE=1 vp test run \
* apps/server/src/cloud/systemdSelfUpdate.acceptance.test.ts
*/
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { FetchHttpClient } from "effect/unstable/http";
import { describe } from "vite-plus/test";
import * as ProcessRunner from "../processRunner.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { quoteSystemdValue } from "./bootService.ts";
import {
SystemdSelfUpdatePlan,
SystemdSelfUpdateReceipt,
waitForSystemdSelfUpdateReadiness,
writeSystemdSelfUpdatePlan,
} from "./systemdSelfUpdate.ts";
const OLD_VERSION = "0.0.28";
const TARGET_VERSION = "0.0.29";
const decodeLaunch = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Struct({
pid: Schema.Int,
version: Schema.String,
}),
),
);
const fixtureServerSource = `
import * as fs from "node:fs";
import * as http from "node:http";
const [runtimeStatePath, launchesPath, version, readiness] = process.argv.slice(2);
const descriptor = {
environmentId: "systemd-self-update-acceptance",
label: "Systemd self-update acceptance",
platform: { os: "linux", arch: "x64" },
serverVersion: version,
capabilities: { repositoryIdentity: true },
};
const server = http.createServer((request, response) => {
if (request.url === "/.well-known/t3/ready" && readiness === "ready") {
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify(descriptor));
return;
}
response.writeHead(503);
response.end();
});
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") process.exit(1);
fs.appendFileSync(launchesPath, JSON.stringify({ pid: process.pid, version }) + "\\n");
fs.writeFileSync(runtimeStatePath, JSON.stringify({
version: 1,
pid: process.pid,
port: address.port,
origin: "http://127.0.0.1:" + address.port,
startedAt: new Date().toISOString(),
}) + "\\n");
});
`;
const runAcceptanceScenario = Effect.fn("test.runSystemdSelfUpdateAcceptance")(function* (
scenario: "healthy" | "rollback",
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const home = process.env.HOME;
if (!home) {
return yield* Effect.die(new Error("HOME is required for a systemd user-manager test."));
}
const directory = yield* fs.makeTempDirectoryScoped({ prefix: `t3-systemd-${scenario}-` });
const runtimeStatePath = path.join(directory, "server-runtime.json");
const launchesPath = path.join(directory, "launches.jsonl");
const receiptPath = path.join(directory, "receipt.json");
const planPath = path.join(directory, "plan.json");
const fixtureServerPath = path.join(directory, "fixture-server.mjs");
yield* fs.writeFileString(fixtureServerPath, fixtureServerSource);
const suffix = `${String(process.pid)}-${String(yield* Clock.currentTimeMillis)}-${scenario}`;
const serviceUnit = `t3code-self-update-acceptance-${suffix}.service`;
const helperUnit = `t3code-self-update-acceptance-helper-${suffix}.service`;
const userUnitDirectory = path.join(home, ".config", "systemd", "user");
const unitPath = path.join(userUnitDirectory, serviceUnit);
yield* fs.makeDirectory(userUnitDirectory, { recursive: true });
const renderUnit = (version: string, readiness: "ready" | "blocked") =>
[
"[Unit]",
"Description=T3 self-update acceptance fixture",
"",
"[Service]",
"Type=simple",
`ExecStart=${quoteSystemdValue(process.execPath)} ${quoteSystemdValue(fixtureServerPath)} ${quoteSystemdValue(runtimeStatePath)} ${quoteSystemdValue(launchesPath)} ${version} ${readiness}`,
"Restart=no",
"TimeoutStopSec=5",
"",
].join("\n");
const previousUnit = renderUnit(OLD_VERSION, "ready");
const nextUnit = renderUnit(TARGET_VERSION, scenario === "healthy" ? "ready" : "blocked");
const systemctl = (args: ReadonlyArray<string>) =>
runner.run({ command: "systemctl", args: ["--user", ...args] });
const cleanup = Effect.gen(function* () {
yield* systemctl(["stop", helperUnit, serviceUnit]).pipe(Effect.ignore);
yield* systemctl(["reset-failed", helperUnit, serviceUnit]).pipe(Effect.ignore);
yield* fs.remove(unitPath, { force: true }).pipe(Effect.ignore);
yield* systemctl(["daemon-reload"]).pipe(Effect.ignore);
});
yield* Effect.addFinalizer(() => cleanup);
yield* fs.writeFileString(unitPath, previousUnit);
const reload = yield* systemctl(["daemon-reload"]);
assert.equal(Number(reload.code), 0);
const start = yield* systemctl(["start", serviceUnit]);
assert.equal(Number(start.code), 0);
yield* waitForSystemdSelfUpdateReadiness(
{
expectedVersion: OLD_VERSION,
previousPid: 0,
runtimeStatePath,
},
{ timeout: Duration.seconds(10), interval: Duration.millis(100) },
);
const initialState = yield* readPersistedServerRuntimeState(runtimeStatePath);
if (Option.isNone(initialState)) {
return yield* Effect.die(
new Error("The disposable systemd service did not publish runtime state."),
);
}
const plan = new SystemdSelfUpdatePlan({
version: 1,
fromVersion: OLD_VERSION,
targetVersion: TARGET_VERSION,
currentPid: initialState.value.pid,
serviceUnit,
unitPath,
previousUnit,
nextUnit,
runtimeStatePath,
receiptPath,
});
yield* writeSystemdSelfUpdatePlan(planPath, plan);
const repositoryRoot = path.resolve(import.meta.dirname, "../../../..");
const cliEntryPath = path.join(repositoryRoot, "apps", "server", "src", "bin.ts");
const handoff = yield* runner.run({
command: "systemd-run",
args: [
"--user",
"--wait",
"--collect",
"--service-type=exec",
`--unit=${helperUnit}`,
process.execPath,
"--experimental-strip-types",
cliEntryPath,
"service",
"_apply-update",
"--plan",
planPath,
],
timeout: Duration.seconds(90),
});
assert.equal(Number(handoff.code), 0, handoff.stderr);
const receipt = yield* fs
.readFileString(receiptPath)
.pipe(
Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(SystemdSelfUpdateReceipt))),
);
assert.equal(receipt.phase, scenario === "healthy" ? "healthy" : "rolled-back");
assert.equal(
yield* fs.readFileString(unitPath),
scenario === "healthy" ? nextUnit : previousUnit,
);
yield* waitForSystemdSelfUpdateReadiness(
{
expectedVersion: scenario === "healthy" ? TARGET_VERSION : OLD_VERSION,
previousPid: initialState.value.pid,
runtimeStatePath,
},
{ timeout: Duration.seconds(10), interval: Duration.millis(100) },
);
const launches = (yield* fs.readFileString(launchesPath))
.trim()
.split("\n")
.map((line) => decodeLaunch(line));
assert.deepEqual(
launches.map(({ version }) => version),
scenario === "healthy"
? [OLD_VERSION, TARGET_VERSION]
: [OLD_VERSION, TARGET_VERSION, OLD_VERSION],
);
});
describe.runIf(process.env.T3_SYSTEMD_SELF_UPDATE_ACCEPTANCE === "1")(
"systemd self-update acceptance",
() => {
const layer = ProcessRunner.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.merge(FetchHttpClient.layer),
);
it.live(
"keeps the helper alive while replacing the host service",
() => runAcceptanceScenario("healthy").pipe(Effect.provide(layer)),
30_000,
);
it.live(
"rolls back a server that binds HTTP without becoming runtime-ready",
() => runAcceptanceScenario("rollback").pipe(Effect.provide(layer)),
120_000,
);
},
);
@@ -6,14 +6,17 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ProcessRunner from "../processRunner.ts";
import { PersistedServerRuntimeState } from "../serverRuntimeState.ts";
import {
SystemdSelfUpdateActivationError,
SystemdSelfUpdatePlan,
SystemdSelfUpdateReceipt,
activateSystemdSelfUpdatePlan,
waitForSystemdSelfUpdateReadiness,
} from "./systemdSelfUpdate.ts";
interface RecordedCommand {
@@ -59,6 +62,7 @@ it.layer(NodeServices.layer)("systemd self-update activation", (it) => {
fromVersion: "0.0.28",
targetVersion: "0.0.29",
currentPid: 123,
serviceUnit: "t3code-self-update-test.service",
unitPath,
previousUnit,
nextUnit: "new unit\n",
@@ -95,7 +99,7 @@ it.layer(NodeServices.layer)("systemd self-update activation", (it) => {
commands.map(({ args }) => args),
[
["--user", "daemon-reload"],
["--user", "restart", "t3code.service"],
["--user", "restart", "t3code-self-update-test.service"],
],
);
assert.equal((yield* readReceipt(fixture.receiptPath)).phase, "healthy");
@@ -132,10 +136,10 @@ it.layer(NodeServices.layer)("systemd self-update activation", (it) => {
commands.map(({ args }) => args),
[
["--user", "daemon-reload"],
["--user", "restart", "t3code.service"],
["--user", "restart", "t3code-self-update-test.service"],
["--user", "daemon-reload"],
["--user", "reset-failed", "t3code.service"],
["--user", "restart", "t3code.service"],
["--user", "reset-failed", "t3code-self-update-test.service"],
["--user", "restart", "t3code-self-update-test.service"],
],
);
const receipt = yield* readReceipt(fixture.receiptPath);
@@ -164,4 +168,52 @@ it.layer(NodeServices.layer)("systemd self-update activation", (it) => {
assert.equal((yield* readReceipt(fixture.receiptPath)).phase, "recovery-failed");
}),
);
it.effect("probes the runtime-readiness endpoint on the replacement process", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-systemd-ready-test-" });
const runtimeStatePath = path.join(directory, "server-runtime.json");
const encodeRuntimeState = Schema.encodeEffect(
Schema.fromJsonString(PersistedServerRuntimeState),
);
const encodedRuntimeState = yield* encodeRuntimeState({
version: 1,
pid: 456,
port: 3210,
origin: "http://127.0.0.1:3210",
startedAt: "2026-01-01T00:00:00.000Z",
});
yield* fs.writeFileString(runtimeStatePath, `${encodedRuntimeState}\n`);
const requests: Array<string> = [];
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => {
requests.push(request.url);
return Effect.succeed(
HttpClientResponse.fromWeb(
request,
Response.json({
environmentId: "environment-test",
label: "Test environment",
platform: { os: "linux", arch: "x64" },
serverVersion: "0.0.29",
capabilities: { repositoryIdentity: true },
}),
),
);
}),
);
yield* waitForSystemdSelfUpdateReadiness({
expectedVersion: "0.0.29",
previousPid: 123,
runtimeStatePath,
}).pipe(Effect.provide(httpClientLayer));
assert.deepEqual(requests, ["http://127.0.0.1:3210/.well-known/t3/ready"]);
}),
);
});
+8 -7
View File
@@ -12,7 +12,6 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts";
export const SYSTEMD_SELF_UPDATE_UNIT = "t3code-self-update.service";
export const SYSTEMD_SELF_UPDATE_DIRECTORY = "self-update";
@@ -23,7 +22,7 @@ const DEFAULT_RESTART_DELAY = Duration.seconds(2);
const DEFAULT_READINESS_TIMEOUT = Duration.seconds(60);
const DEFAULT_READINESS_INTERVAL = Duration.millis(500);
const READINESS_REQUEST_TIMEOUT = Duration.seconds(2);
const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment";
const WELL_KNOWN_READY_PATH = "/.well-known/t3/ready";
export class SystemdSelfUpdatePlan extends Schema.Class<SystemdSelfUpdatePlan>(
"SystemdSelfUpdatePlan",
@@ -32,6 +31,7 @@ export class SystemdSelfUpdatePlan extends Schema.Class<SystemdSelfUpdatePlan>(
fromVersion: Schema.String,
targetVersion: Schema.String,
currentPid: Schema.Int,
serviceUnit: Schema.String,
unitPath: Schema.String,
previousUnit: Schema.String,
nextUnit: Schema.String,
@@ -185,7 +185,8 @@ const installUnit = Effect.fn("systemdSelfUpdate.installUnit")(function* (
yield* runSystemctl(["--user", "daemon-reload"], "daemon-reload");
});
const restartBootService = runSystemctl(["--user", "restart", BOOT_SERVICE_UNIT_FILE], "restart");
const restartBootService = (serviceUnit: string) =>
runSystemctl(["--user", "restart", serviceUnit], "restart");
export interface SystemdSelfUpdateReadinessInput {
readonly expectedVersion: string;
@@ -227,7 +228,7 @@ export const waitForSystemdSelfUpdateReadiness = Effect.fn("systemdSelfUpdate.wa
}
const request = HttpClientRequest.get(
new URL(WELL_KNOWN_ENVIRONMENT_PATH, state.value.origin).toString(),
new URL(WELL_KNOWN_READY_PATH, state.value.origin).toString(),
);
const descriptor = yield* client.execute(request).pipe(
Effect.timeout(READINESS_REQUEST_TIMEOUT),
@@ -277,7 +278,7 @@ export const activateSystemdSelfUpdatePlan = Effect.fn("systemdSelfUpdate.activa
yield* writeReceipt(plan, "activating").pipe(Effect.ignore);
yield* Effect.sleep(options.restartDelay ?? DEFAULT_RESTART_DELAY);
yield* installUnit(plan, plan.nextUnit);
yield* restartBootService;
yield* restartBootService(plan.serviceUnit);
yield* waitForReadiness({
expectedVersion: plan.targetVersion,
previousPid: plan.currentPid,
@@ -298,8 +299,8 @@ export const activateSystemdSelfUpdatePlan = Effect.fn("systemdSelfUpdate.activa
);
const recovery = Effect.gen(function* () {
yield* installUnit(plan, plan.previousUnit);
yield* runSystemctl(["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], "reset-failed");
yield* restartBootService;
yield* runSystemctl(["--user", "reset-failed", plan.serviceUnit], "reset-failed");
yield* restartBootService(plan.serviceUnit);
yield* waitForReadiness({
expectedVersion: plan.fromVersion,
previousPid: plan.currentPid,
+18 -7
View File
@@ -40,6 +40,7 @@ import {
} from "./auth/http.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
@@ -177,13 +178,23 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
"metadata",
Effect.fnUntraced(function* (handlers) {
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
return handlers.handle(
"descriptor",
Effect.fn("environment.metadata.descriptor")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
return yield* serverEnvironment.getDescriptor;
}, traceRelayRequest),
);
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
return handlers
.handle(
"descriptor",
Effect.fn("environment.metadata.descriptor")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
return yield* serverEnvironment.getDescriptor;
}, traceRelayRequest),
)
.handle(
"ready",
Effect.fn("environment.metadata.ready")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* startup.awaitReady.pipe(Effect.orDie);
return yield* serverEnvironment.getDescriptor;
}, traceRelayRequest),
);
}),
);
+51 -1
View File
@@ -3,7 +3,12 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { MigrationIdentityMismatchError, validateMigrationIdentities } from "./Migrations.ts";
import {
AutomaticUpdateMigrationFrontierError,
MigrationIdentityMismatchError,
validateAutomaticUpdateMigrationFrontier,
validateMigrationIdentities,
} from "./Migrations.ts";
import * as NodeSqliteClient from "./NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
@@ -50,4 +55,49 @@ layer("migration identity validation", (it) => {
yield* validateMigrationIdentities();
}),
);
it.effect("rejects automatic downgrade when the database has a newer migration", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* createTrackingTable();
yield* sql`
INSERT INTO effect_sql_migrations (migration_id, name)
VALUES (999, 'FutureMigration')
`;
const error = yield* validateAutomaticUpdateMigrationFrontier().pipe(Effect.flip);
assert.instanceOf(error, AutomaticUpdateMigrationFrontierError);
assert.equal(error.databaseMigrationId, 999);
assert.equal(error.targetMigrationId, 35);
}),
);
it.effect("rejects automatic updates that would run migrations", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* createTrackingTable();
yield* sql`
INSERT INTO effect_sql_migrations (migration_id, name)
VALUES (34, 'ProjectionThreadsSnoozed')
`;
const error = yield* validateAutomaticUpdateMigrationFrontier().pipe(Effect.flip);
assert.instanceOf(error, AutomaticUpdateMigrationFrontierError);
assert.equal(error.databaseMigrationId, 34);
assert.equal(error.targetMigrationId, 35);
}),
);
it.effect("allows automatic updates on the same migration frontier", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* createTrackingTable();
yield* sql`
INSERT INTO effect_sql_migrations (migration_id, name)
VALUES (35, 'ProjectionThreadTitleRegeneration')
`;
yield* validateAutomaticUpdateMigrationFrontier();
}),
);
});
+58 -18
View File
@@ -127,33 +127,53 @@ export class MigrationIdentityMismatchError extends Schema.TaggedErrorClass<Migr
}
}
export class AutomaticUpdateMigrationFrontierError extends Schema.TaggedErrorClass<AutomaticUpdateMigrationFrontierError>()(
"AutomaticUpdateMigrationFrontierError",
{
databaseMigrationId: Schema.Int,
targetMigrationId: Schema.Int,
},
) {
override get message(): string {
return this.databaseMigrationId > this.targetMigrationId
? `This database is newer than the requested t3 build (migration ${String(this.databaseMigrationId)} vs ${String(this.targetMigrationId)}).`
: `The requested t3 build would migrate this database (migration ${String(this.databaseMigrationId)} to ${String(this.targetMigrationId)}), which is not safe during an automatic update.`;
}
}
const readPersistedMigrationIdentities = Effect.fn("readPersistedMigrationIdentities")(
function* () {
const sql = yield* SqlClient.SqlClient;
const tables = yield* sql<{ readonly name: string }>`
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name = 'effect_sql_migrations'
`;
if (tables.length === 0) {
return [];
}
return yield* sql<{
readonly migration_id: number;
readonly name: string;
}>`
SELECT migration_id, name
FROM effect_sql_migrations
ORDER BY migration_id
`;
},
);
/**
* Refuse to run a build whose migration history disagrees with the database.
* Unknown newer IDs are intentionally allowed so a compatible older build can
* inspect a database created by a newer release without rewriting its history.
*/
export const validateMigrationIdentities = Effect.fn("validateMigrationIdentities")(function* () {
const sql = yield* SqlClient.SqlClient;
const tables = yield* sql<{ readonly name: string }>`
SELECT name
FROM sqlite_master
WHERE type = 'table' AND name = 'effect_sql_migrations'
`;
if (tables.length === 0) {
return;
}
const expectedNames = new Map<number, string>(
migrationEntries.map(([migrationId, name]) => [migrationId, name]),
);
const persisted = yield* sql<{
readonly migration_id: number;
readonly name: string;
}>`
SELECT migration_id, name
FROM effect_sql_migrations
ORDER BY migration_id
`;
const persisted = yield* readPersistedMigrationIdentities();
for (const migration of persisted) {
const expectedName = expectedNames.get(migration.migration_id);
@@ -167,6 +187,26 @@ export const validateMigrationIdentities = Effect.fn("validateMigrationIdentitie
}
});
/**
* Automatic activation is safe only when the target and database are already
* on the same schema. A binary rollback cannot undo a migration, and an older
* target cannot safely interpret migration IDs that it does not know about.
*/
export const validateAutomaticUpdateMigrationFrontier = Effect.fn(
"validateAutomaticUpdateMigrationFrontier",
)(function* () {
yield* validateMigrationIdentities();
const persisted = yield* readPersistedMigrationIdentities();
const databaseMigrationId = persisted.at(-1)?.migration_id ?? 0;
const targetMigrationId = migrationEntries.at(-1)?.[0] ?? 0;
if (databaseMigrationId !== targetMigrationId) {
return yield* new AutomaticUpdateMigrationFrontierError({
databaseMigrationId,
targetMigrationId,
});
}
});
export interface RunMigrationsOptions {
readonly toMigrationInclusive?: number | undefined;
}
+25
View File
@@ -782,6 +782,7 @@ const buildAppUnderTest = (options?: {
Layer.provide(
Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({
awaitCommandReady: Effect.void,
awaitReady: Effect.void,
markHttpListening: Effect.void,
enqueueCommand: (effect) => effect,
...options?.layers?.serverRuntimeStartup,
@@ -1361,6 +1362,30 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("does not report update readiness before the runtime publishes ready", () =>
Effect.gen(function* () {
const runtimeReady = yield* Deferred.make<void>();
yield* buildAppUnderTest({
layers: {
serverRuntimeStartup: {
awaitReady: Deferred.await(runtimeReady),
},
},
});
const url = yield* getHttpServerUrl("/.well-known/t3/ready");
const responseFiber = yield* fetchEffect(url).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
assert.isUndefined(responseFiber.pollUnsafe());
yield* Deferred.succeed(runtimeReady, undefined);
const response = yield* Fiber.join(responseFiber);
const body = yield* responseJsonEffect<typeof testEnvironmentDescriptor>(response);
assert.equal(response.status, 200);
assert.deepEqual(body, testEnvironmentDescriptor);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("compresses large JSON responses through the composed routes", () =>
Effect.gen(function* () {
const descriptor = {
+5
View File
@@ -59,6 +59,7 @@ export class ServerRuntimeStartup extends Context.Service<
ServerRuntimeStartup,
{
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
readonly awaitReady: Effect.Effect<void, ServerRuntimeStartupError>;
readonly markHttpListening: Effect.Effect<void>;
readonly enqueueCommand: <A, E>(
effect: Effect.Effect<A, E>,
@@ -300,6 +301,7 @@ export const make = Effect.gen(function* () {
const commandGate = yield* makeCommandGate;
const httpListening = yield* Deferred.make<void>();
const runtimeReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
const reactorScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
@@ -425,6 +427,7 @@ export const make = Effect.gen(function* () {
});
yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause });
yield* commandGate.failCommandReady(error);
yield* Deferred.fail(runtimeReady, error).pipe(Effect.orDie);
return;
}
@@ -444,6 +447,7 @@ export const make = Effect.gen(function* () {
},
}),
);
yield* Deferred.succeed(runtimeReady, undefined).pipe(Effect.orDie);
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* launchStartupHeartbeat;
@@ -470,6 +474,7 @@ export const make = Effect.gen(function* () {
return {
awaitCommandReady: commandGate.awaitCommandReady,
awaitReady: Deferred.await(runtimeReady),
markHttpListening: Deferred.succeed(httpListening, undefined),
enqueueCommand: commandGate.enqueueCommand,
} satisfies ServerRuntimeStartup["Service"];
+9 -4
View File
@@ -90,9 +90,12 @@ successfully. Boot-service setup and self-update share the same process-wide ins
they cannot mutate a pinned runtime concurrently.
Before any restart, the current Node executable runs the replacement with `--version`, then asks
the target artifact to validate its migration identities against the live database in read-only
mode. A failed install, version preflight, or compatibility check leaves the current server running.
Targets old enough to lack the compatibility command are not eligible for remote activation.
the target artifact to validate the live database in read-only mode. Automatic activation requires
the target and database to be on the exact same migration frontier. This rejects both downgrades and
updates that would migrate the database because a binary rollback cannot undo a schema change. Use
the manual host service update path for those releases. A failed install, version preflight, or
compatibility check leaves the current server running. Targets old enough to lack the compatibility
command are not eligible for remote activation.
Candidate cleanup is narrower than "any failed preflight". The candidate runtime is removed only when
the preflight process actually completes and reports a bad exit code or the wrong version: that is
@@ -118,7 +121,9 @@ For `boot-service`, the request process writes a typed plan but leaves its live
starts a fixed-name `t3code-self-update.service` transient unit with `systemd-run --user`; the
transient unit has a separate cgroup and acts as the cross-process update lock. After a short grace
period it atomically installs the candidate unit, reloads systemd, performs a blocking restart, and
probes the public environment descriptor for the exact target version. If activation or readiness
probes the public runtime-readiness endpoint for the exact target version. The endpoint does not
respond until the server's command runtime is usable and its lifecycle `ready` event has been
published, so an HTTP listener alone cannot make an activation healthy. If activation or readiness
fails, the helper restores the previous unit, clears systemd's failed state, restarts it, and proves
the previous version is ready. The plan and latest receipt live under the environment state
directory's `self-update` folder for diagnosis.
+17
View File
@@ -190,6 +190,23 @@ connect the new client to a server on the previous version and verify that the u
reconnects to the matching server. Test one automatic path and the manual or desktop-managed
guidance when those environments are available.
The automatic boot-service path also requires a real systemd user-manager acceptance run. Use a
disposable T3 home and uniquely named host and helper units, never the developer's daily
`t3code.service`. Exercise both outcomes:
1. A same-migration-frontier candidate becomes runtime-ready, the helper survives the host-unit
restart, and the receipt reaches `healthy` with a new runtime PID and the exact target version.
2. A candidate that binds HTTP but never becomes runtime-ready times out, the previous unit is
restored, and the receipt reaches `rolled-back` with the old version command-ready again.
Treat the systemd run as a release blocker when the update lifecycle changes. CI jobs without a
user manager may skip it, but a Linux release host must record the run before publishing.
```bash
T3_SYSTEMD_SELF_UPDATE_ACCEPTANCE=1 vp test run \
apps/server/src/cloud/systemdSelfUpdate.acceptance.test.ts
```
## Desktop auto-update notes
- Updater runtime: `apps/desktop/src/updates/DesktopUpdates.ts`.
+11 -5
View File
@@ -371,11 +371,17 @@ export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
});
export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
success: ExecutionEnvironmentDescriptor,
}),
) {}
export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata")
.add(
HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
success: ExecutionEnvironmentDescriptor,
}),
)
.add(
HttpApiEndpoint.get("ready", "/.well-known/t3/ready", {
success: ExecutionEnvironmentDescriptor,
}),
) {}
export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
.add(