Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
9 changes: 7 additions & 2 deletions apps/server/src/cli/servicePreflight.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import { Command, Flag } from "effect/cli";
Expand All @@ -10,8 +11,12 @@ export const servicePreflightCommand = Command.make("__service-preflight", {
}).pipe(
Command.unlisted,
Command.withHandler(({ databasePath, launcherProtocol }) =>
Console.log(JSON.stringify(runServicePreflight({ databasePath, launcherProtocol }))).pipe(
Effect.asVoid,
HostProcess.Platform.pipe(
Effect.flatMap((platform) =>
Console.log(
JSON.stringify(runServicePreflight({ databasePath, launcherProtocol, platform })),
),
),
),
),
);
24 changes: 23 additions & 1 deletion apps/server/src/cloud/servicePreflight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ it.each([1])("blocks legacy launcher protocol %i with exact recovery steps", (la
const result = runServicePreflight({
databasePath: "/missing/state.sqlite",
launcherProtocol,
platform: "linux",
version: "9.8.7",
});

Expand All @@ -33,6 +34,22 @@ it.each([1])("blocks legacy launcher protocol %i with exact recovery steps", (la
expect(reason).toContain("which -a t3");
});

// regression: #34435 Windows hosts were told to run `curl | sh` and `~/.local/bin/t3 service install`
it("gives Windows hosts recovery steps that run on Windows", () => {
const result = runServicePreflight({
databasePath: "C:\\missing\\state.sqlite",
launcherProtocol: 3,
platform: "win32",
version: "9.8.7",
});
const reason = result.status === "blocked" ? result.reason : "";
expect(reason).toMatch(new RegExp(`\\b${SERVICE_LAUNCHER_PROTOCOL}\\b`));
expect(reason).toContain("9.8.7");
expect(reason).not.toContain("| sh");
expect(reason).not.toContain("which -a");
expect(reason).not.toContain("~/.local/bin/t3");
});

it.layer(NodeServices.layer)("service preflight database", (it) => {
it.effect("blocks a database that a newer build migrated", () =>
Effect.gen(function* () {
Expand All @@ -47,7 +64,11 @@ it.layer(NodeServices.layer)("service preflight database", (it) => {
const insert = db.prepare("INSERT INTO effect_sql_migrations VALUES (?, ?)");
for (const [id, name] of migrationManifest) insert.run(id, name);
const preflight = () =>
runServicePreflight({ databasePath, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL });
runServicePreflight({
databasePath,
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
platform: "linux",
});

expect(preflight().status).toBe("ready");
expect(databaseMigrationHead(databasePath)).toBe(BUILD_MIGRATION_HEAD);
Expand All @@ -69,6 +90,7 @@ it.layer(NodeServices.layer)("service preflight database", (it) => {
runServicePreflight({
databasePath: unreadable,
launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
platform: "linux",
}).status,
).toBe("blocked");
// A missing database is a fresh install.
Expand Down
16 changes: 13 additions & 3 deletions apps/server/src/cloud/servicePreflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type ServicePreflightResult =
export function runServicePreflight(input: {
readonly databasePath: string;
readonly launcherProtocol: number;
readonly platform: NodeJS.Platform;
readonly version?: string;
}): ServicePreflightResult {
const version = input.version ?? packageJson.version;
Expand All @@ -28,9 +29,18 @@ export function runServicePreflight(input: {
// reinstall itself and report success, so name the exact install and the path check.
reason: [
`The installed service launcher speaks protocol ${input.launcherProtocol}, but t3@${version} requires protocol ${SERVICE_LAUNCHER_PROTOCOL}.`,
`On the server machine, install this exact CLI: \`curl -fsSL https://t3.codes/install.sh | T3CODE_VERSION=${version} sh\`.`,
`Check that \`t3 --version\` prints ${version} and that \`which -a t3\` lists no older t3 (such as an npm or nvm install) first, then run \`~/.local/bin/t3 service install\` (the installer's default path).`,
"Updating the desktop app does not update this CLI, and `t3 service update` only repairs the service with whichever CLI runs it.",
...(input.platform === "win32"
? [
`On the server machine, install this exact CLI in PowerShell: \`$env:T3CODE_VERSION="${version}"; irm https://t3.codes/install.ps1 | iex\`.`,
`Check that \`t3 --version\` prints ${version} and that \`where.exe t3\` lists no older t3 first.`,
`Windows has no \`t3 service install\`, so change whatever runs \`t3 __service-launcher\` to start it from \`%USERPROFILE%\\.local\\bin\\t3.cmd\` (the installer's default path) and restart it. Later remote updates repoint that t3.cmd, so a launcher started through it moves forward on its next restart.`,
"Updating the desktop app does not update this CLI.",
]
: [
`On the server machine, install this exact CLI: \`curl -fsSL https://t3.codes/install.sh | T3CODE_VERSION=${version} sh\`.`,
`Check that \`t3 --version\` prints ${version} and that \`which -a t3\` lists no older t3 (such as an npm or nvm install) first, then run \`~/.local/bin/t3 service install\` (the installer's default path).`,
"Updating the desktop app does not update this CLI, and `t3 service update` only repairs the service with whichever CLI runs it.",
]),
].join(" "),
};
}
Expand Down
26 changes: 23 additions & 3 deletions apps/server/src/serviceLauncher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
render = renderBootServiceUnit,
missingUnit = false,
legacyInstall = false,
windowsShim = false,
) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand All @@ -407,6 +408,16 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
yield* fs.writeFileString(databasePath, "before trial");
const unit = yield* fakeServiceUnit(fs, path, root, "1.0.0", render);
if (missingUnit) yield* fs.remove(unit.path);
const shimPath = path.join(root, "bin", "t3.cmd");
if (windowsShim) {
yield* fs.makeDirectory(path.dirname(shimPath), { recursive: true });
const target = path.join(root, "runtime", "versions", "1.0.0", "t3.exe");
yield* fs.writeFileString(shimPath, `@echo off\r\n"${target}" %*`);
yield* fs.makeDirectory(path.join(root, "runtime"), { recursive: true });
yield* fs.writeFileString(path.join(root, "runtime", "launchers"), `${shimPath}\r\n`);
}
// Windows has no service unit; the launcher runs through the installer's shim.
const launcherOptions = windowsShim ? {} : { serviceUnit: unit };
const childSource = `
import assert from "node:assert/strict";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
Expand Down Expand Up @@ -462,7 +473,7 @@ if (context.update?.status === "pending") {
const launcher = new Launcher(
root,
yield* Effect.promise(() => readServiceState(statePath)),
{ serviceUnit: unit },
launcherOptions,
);
const failure = yield* Effect.promise(() =>
launcher.run().then(
Expand All @@ -480,13 +491,13 @@ if (context.update?.status === "pending") {
const fresh = new Launcher(
root,
yield* Effect.promise(() => readServiceState(statePath)),
{ serviceUnit: unit },
launcherOptions,
);
const running = fresh.run();
yield* Effect.promise(() => fresh.stop("SIGTERM"));
yield* Effect.promise(() => running);
});
return { fs, root, unit, recover };
return { fs, root, unit, shimPath, recover };
});

it.effect.each([
Expand Down Expand Up @@ -516,6 +527,15 @@ if (context.update?.status === "pending") {
}),
);

it.effect("repoints the installer's t3.cmd on commit when there is no service unit", () =>
Effect.gen(function* () {
const { fs, root, shimPath } = yield* commitUpdate(renderBootServiceUnit, false, false, true);
const path = yield* Path.Path;
const target = path.join(root, "runtime", "versions", "1.1.0", "t3.exe");
assert.equal(yield* fs.readFileString(shimPath), `@echo off\r\n"${target}" %*`);
}),
);

it.effect(
"keeps a durable commit through unit failure and retries a failed reload on restart",
() =>
Expand Down
41 changes: 40 additions & 1 deletion apps/server/src/serviceLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,14 @@ function repointServiceUnit(contents: string, version: string): string {
return contents;
}

// A `t3.cmd` exactly as the install script or `t3 update` writes it, running a version in `versionsDir`.
const generatedShimVersion = (contents: string, versionsDir: string) => {
const target = /^@echo off\r?\n"([^"]+)" %\*\s*$/.exec(contents)?.[1];
if (target === undefined) return undefined;
const relative = NodePath.relative(versionsDir, target);
return /^([^\\/]+)[\\/]t3\.exe$/.exec(relative)?.[1];
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
};

const DB_FILE_SUFFIXES = ["", "-wal", "-shm"] as const;
const RESTORE_MARKER = ".restore-pending";

Expand Down Expand Up @@ -972,7 +980,7 @@ export class Launcher {
// Selection is durable before this best-effort unit reconciliation.
async #repointServiceUnit(version: string): Promise<void> {
const unit = this.#serviceUnit;
if (unit === undefined) return;
if (unit === undefined) return this.#repointShims(version);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
try {
const release = await acquireServiceSelectionLock(unit.path);
try {
Expand Down Expand Up @@ -1008,6 +1016,37 @@ export class Launcher {
}
}

/**
* Windows has no unit to repoint, so a launcher started through the installer's `t3.cmd`
* restarts on whatever the shim runs. Move recorded shims forward with the commit.
*/
async #repointShims(version: string): Promise<void> {
const runtimeDir = NodePath.join(this.#baseDir, "runtime");
const versionsDir = NodePath.join(runtimeDir, "versions");
const recorded = await NodeFSP.readFile(NodePath.join(runtimeDir, "launchers"), "utf8").catch(
() => "",
);
for (const shim of recorded.split(/\r?\n/)) {
if (!shim.toLowerCase().endsWith(".cmd")) continue;
try {
const contents = await NodeFSP.readFile(shim, "utf8");
const current = generatedShimVersion(contents, versionsDir);
if (
current === undefined ||
(isExactServiceVersion(current) && compareExactServiceVersions(current, version) >= 0)
) {
continue;
}
const target = NodePath.join(versionsDir, version, "t3.exe");
await replaceFileDurably(shim, `@echo off\r\n"${target}" %*`);
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
} catch (error) {
process.stderr.write(
`[service-launcher] Could not point ${shim} at t3@${version}: ${error instanceof Error ? error.message : String(error)}\n`,
);
}
}
}

async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
const pending = this.#state.update;
if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
Expand Down
Loading