Open History to see the last commit
1import {
2 HostProcessArchitecture,
3 HostProcessEnvironment,
4 HostProcessInvokedAs,
5 HostProcessIsExecutable,
6 HostProcessPlatform,
7 HostProcessWorkingDirectory,
8} from "@t3tools/shared/hostProcess";
9import {
10 CLI_RELEASE_BASE_URL_ENV,
11 CLI_RELEASE_CHANNELS,
12 cliReleaseIndexPageUrl,
13 cliReleaseChannelOf,
14 newestCliReleaseVersion,
15 type CliReleaseChannel,
16} from "@t3tools/shared/cliRelease";
17import * as Console from "effect/Console";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as Schema from "effect/Schema";
25import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
26import {
27 FetchHttpClient,
28 HttpClient,
29 HttpClientRequest,
30 HttpClientResponse,
31} from "effect/unstable/http";
32
33import packageJson from "../../package.json" with { type: "json" };
34import * as BootService from "../cloud/bootService.ts";
35import {
36 ensurePinnedRuntimeInstalled,
37 pinnedRuntimeCommand,
38 PinnedRuntimeInstallError,
39 pinnedRuntimePaths,
40} from "../cloud/pinnedRuntime.ts";
41import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
42import * as ProcessRunner from "../processRunner.ts";
43import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
44import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
45import { bootServiceLayer } from "./service.ts";
46
47export class CliUpdateError extends Schema.TaggedError<CliUpdateError>()("CliUpdateError", {
48 reason: Schema.String,
49}) {
50 override get message(): string {
51 return this.reason;
52 }
53}
54
55const ReleaseIndex = Schema.Array(
56 Schema.Struct({
57 tag_name: Schema.String,
58 draft: Schema.optional(Schema.Boolean),
59 }),
60);
61const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex));
62
63const RELEASE_INDEX_TIMEOUT = Duration.seconds(30);
64// Enough to walk past a long run of nightlies without hammering the API when
65// a channel genuinely has nothing published.
66const RELEASE_INDEX_MAX_PAGES = 10;
67
68/** Asks GitHub for the newest published version on a channel, page by page. */
69const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(function* (
70 channel: CliReleaseChannel,
71) {
72 const httpClient = yield* HttpClient.HttpClient;
73 for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) {
74 const body = yield* httpClient
75 .execute(
76 HttpClientRequest.get(cliReleaseIndexPageUrl(page)).pipe(
77 HttpClientRequest.setHeader("Accept", "application/vnd.github+json"),
78 ),
79 )
80 .pipe(
81 Effect.flatMap(HttpClientResponse.filterStatusOk),
82 Effect.flatMap((response) => response.text),
83 Effect.mapError(() => new CliUpdateError({ reason: "Could not list t3 releases." })),
84 Effect.timeoutOrElse({
85 duration: RELEASE_INDEX_TIMEOUT,
86 orElse: () =>
87 Effect.fail(new CliUpdateError({ reason: "Timed out listing t3 releases." })),
88 }),
89 );
90 const releases = yield* decodeReleaseIndex(body).pipe(
91 Effect.mapError(
92 () => new CliUpdateError({ reason: "The t3 release index had an unexpected shape." }),
93 ),
94 );
95 const version = newestCliReleaseVersion(releases, channel);
96 if (version !== undefined) return version;
97 if (releases.length === 0) break;
98 }
99 return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
100});
101
102/**
103 * The launcher the install scripts leave behind: a symlink at `<bin>/t3` on
104 * POSIX, a `t3.cmd` shim on Windows. `t3 update` repoints it so the next `t3`
105 * invocation is the new version. Only a launcher that already points into
106 * this home's `runtime/versions` tree is touched; a plain copy of the
107 * executable, or a launcher for some other install, is left alone.
108 */
109export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function* (input: {
110 /** Path the current process was started through, if known. */
111 readonly launchedAs: string | undefined;
112 /** `<baseDir>/runtime/versions` of the home being updated. */
113 readonly versionsDir: string;
114 readonly targetEntryPath: string;
115}) {
116 const fs = yield* FileSystem.FileSystem;
117 const path = yield* Path.Path;
118 const platform = yield* HostProcessPlatform;
119 if (input.launchedAs === undefined) return Option.none<string>();
120 const ownsTarget = (candidate: string) => {
121 const relative = path.relative(input.versionsDir, path.resolve(candidate));
122 return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
123 };
124
125 if (platform === "win32") {
126 // The shim runs the executable by absolute path, so the executable sees
127 // itself as argv0; the shim is the `t3.cmd` next to it only when launched
128 // from an install script's bin directory. Find it by searching the
129 // directories that would resolve `t3` on this shell's PATH.
130 const shimPath = yield* findWindowsShim(input.launchedAs);
131 if (shimPath === undefined) return Option.none<string>();
132 const current = yield* fs.readFileString(shimPath).pipe(Effect.option);
133 const quoted = Option.isSome(current) ? /^"([^"]+)"/m.exec(current.value)?.[1] : undefined;
134 if (quoted === undefined || !ownsTarget(quoted)) return Option.none<string>();
135 yield* fs
136 .writeFileString(shimPath, `@echo off\r\n"${input.targetEntryPath}" %*`)
137 .pipe(
138 Effect.mapError(
139 () => new CliUpdateError({ reason: `Could not rewrite the t3 launcher at ${shimPath}.` }),
140 ),
141 );
142 return Option.some(shimPath);
143 }
144
145 const linkTarget = yield* fs.readLink(input.launchedAs).pipe(Effect.option);
146 if (Option.isNone(linkTarget)) return Option.none<string>();
147 const resolvedTarget = path.resolve(path.dirname(input.launchedAs), linkTarget.value);
148 if (!ownsTarget(resolvedTarget)) return Option.none<string>();
149 const tempLink = `${input.launchedAs}.${process.pid}.tmp`;
150 yield* fs.symlink(input.targetEntryPath, tempLink).pipe(
151 Effect.andThen(fs.rename(tempLink, input.launchedAs)),
152 Effect.mapError(
153 () =>
154 new CliUpdateError({ reason: `Could not repoint the t3 launcher at ${input.launchedAs}.` }),
155 ),
156 );
157 return Option.some(input.launchedAs);
158});
159
160/**
161 * The path the executable was started through. Node keeps the shell's
162 * spelling in argv0: a launcher symlink or `./t3` resolves against the
163 * working directory, while a bare `t3` was found on PATH and has to be
164 * looked up there again, or the launcher symlink is never seen.
165 */
166export const resolveLauncherPath = Effect.gen(function* () {
167 const path = yield* Path.Path;
168 const fs = yield* FileSystem.FileSystem;
169 const invokedAs = yield* HostProcessInvokedAs;
170 const cwd = yield* HostProcessWorkingDirectory;
171 const environment = yield* HostProcessEnvironment;
172 const platform = yield* HostProcessPlatform;
173 if (invokedAs.includes("/") || invokedAs.includes("\\")) {
174 return path.resolve(cwd, invokedAs);
175 }
176 const delimiter = platform === "win32" ? ";" : ":";
177 for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
178 if (directory.length === 0) continue;
179 const candidate = path.join(directory, invokedAs);
180 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
181 return candidate;
182 }
183 }
184 return undefined;
185});
186
187/**
188 * On Windows a `.cmd` shim is what PATH resolves, but the executable it runs
189 * only ever sees its own path. Walk PATH for a `t3.cmd` whose target is the
190 * running executable; that is the launcher the install script wrote.
191 */
192const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* (
193 executablePath: string,
194) {
195 const fs = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const environment = yield* HostProcessEnvironment;
198 const candidates = [
199 ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []),
200 ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"),
201 ].filter((entry) => entry.trim().length > 0);
202 for (const directory of candidates) {
203 const shimPath = path.join(directory, "t3.cmd");
204 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
205 if (Option.isNone(contents)) continue;
206 const target = /^"([^"]+)"/m.exec(contents.value)?.[1];
207 if (
208 target !== undefined &&
209 path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase()
210 ) {
211 return shimPath;
212 }
213 }
214 return undefined;
215});
216
217const updateFlags = {
218 ...projectLocationFlags,
219 channel: Flag.choice("channel", CLI_RELEASE_CHANNELS).pipe(
220 Flag.withDescription(
221 "Release channel to follow. Defaults to the channel this t3 was published on.",
222 ),
223 Flag.optional,
224 ),
225 allowDowngrade: Flag.boolean("allow-downgrade").pipe(
226 Flag.withDescription("Allow moving to an older version than the one running."),
227 Flag.withDefault(false),
228 ),
229 yes: Flag.boolean("yes").pipe(
230 Flag.withAlias("y"),
231 Flag.withDescription(
232 "Restart the background service without asking. Required to restart it from a script, where there is no prompt.",
233 ),
234 Flag.withDefault(false),
235 ),
236};
237
238const versionArgument = Argument.string("version").pipe(
239 Argument.withDescription(
240 "Exact version to install. Defaults to the newest release on the channel.",
241 ),
242 Argument.optional,
243);
244
245export const updateCommand = Command.make("update", {
246 ...updateFlags,
247 version: versionArgument,
248}).pipe(
249 Command.withDescription(
250 "Download a newer t3 and switch this machine to it, including the background service when one is installed.",
251 ),
252 Command.withHandler((flags) =>
253 Effect.gen(function* () {
254 const logLevel = yield* GlobalFlag.LogLevel;
255 const config = yield* resolveCliAuthConfig(flags, logLevel);
256 return yield* runUpdate({
257 baseDir: config.baseDir,
258 serverRuntimeStatePath: config.serverRuntimeStatePath,
259 channel: Option.getOrUndefined(flags.channel),
260 requestedVersion: Option.getOrUndefined(flags.version),
261 allowDowngrade: flags.allowDowngrade,
262 assumeYes: flags.yes,
263 }).pipe(
264 Effect.provide(
265 Layer.mergeAll(bootServiceLayer(config), ProcessRunner.layer, FetchHttpClient.layer),
266 ),
267 );
268 }),
269 ),
270);
271
272/**
273 * A `t3 serve` or `t3` someone started by hand, as opposed to the one the
274 * background service supervises. The server records its pid on startup; a
275 * stale file from a crashed server is ignored by checking the pid is alive.
276 *
277 * Servers from before `serviceManaged` was recorded cannot be told apart by
278 * the file alone, so the launcher-supervised case is also recognised by
279 * lineage: a service server's parent is the launcher, and on Linux that
280 * launcher runs inside the unit's cgroup.
281 */
282const findForegroundServer = Effect.fn("cli.update.find_foreground_server")(function* (input: {
283 readonly serverRuntimeStatePath: string;
284 readonly serviceInstalled: boolean;
285}) {
286 const state = yield* readPersistedServerRuntimeState(input.serverRuntimeStatePath);
287 if (Option.isNone(state) || state.value.serviceManaged || !isProcessAlive(state.value.pid)) {
288 return undefined;
289 }
290 if (input.serviceInstalled && (yield* belongsToBootService(state.value.pid))) return undefined;
291 return state.value;
292});
293
294const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(function* (
295 pid: number,
296) {
297 const platform = yield* HostProcessPlatform;
298 const fs = yield* FileSystem.FileSystem;
299 const runner = yield* ProcessRunner.ProcessRunner;
300 if (platform === "linux") {
301 const cgroup = yield* fs.readFileString(`/proc/${pid}/cgroup`).pipe(Effect.option);
302 return Option.isSome(cgroup) && cgroup.value.includes("/t3code.service");
303 }
304 if (platform === "darwin") {
305 // The service server's parent is the launcher process.
306 const parent = yield* runner
307 .run({
308 command: "ps",
309 args: ["-o", "ppid=", "-p", String(pid)],
310 timeout: Duration.seconds(5),
311 })
312 .pipe(Effect.option);
313 const ppid = Option.isSome(parent) && parent.value.code === 0 ? parent.value.stdout.trim() : "";
314 if (!/^\d+$/.test(ppid)) return false;
315 const command = yield* runner
316 .run({ command: "ps", args: ["-o", "command=", "-p", ppid], timeout: Duration.seconds(5) })
317 .pipe(
318 Effect.map((result) => (result.code === 0 ? result.stdout : "")),
319 Effect.orElseSucceed(() => ""),
320 );
321 return /__service-launcher/.test(command);
322 }
323 return false;
324});
325
326const runUpdate = Effect.fn("cli.update.run")(function* (input: {
327 readonly baseDir: string;
328 readonly serverRuntimeStatePath: string;
329 readonly channel: CliReleaseChannel | undefined;
330 readonly requestedVersion: string | undefined;
331 readonly allowDowngrade: boolean;
332 readonly assumeYes: boolean;
333}) {
334 const fs = yield* FileSystem.FileSystem;
335 const path = yield* Path.Path;
336 const runner = yield* ProcessRunner.ProcessRunner;
337 const platform = yield* HostProcessPlatform;
338 const arch = yield* HostProcessArchitecture;
339 const environment = yield* HostProcessEnvironment;
340 const httpClient = yield* HttpClient.HttpClient;
341 const service = yield* BootService.BootService;
342
343 const currentVersion = packageJson.version;
344 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
345 if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
346 return yield* new CliUpdateError({
347 reason: `'${input.requestedVersion}' is not an exact t3 version.`,
348 });
349 }
350 const targetVersion = input.requestedVersion ?? (yield* resolveNewestVersion(channel));
351 const targetChannel = cliReleaseChannelOf(targetVersion);
352
353 // Preview is a maintainers' dogfooding train: it is cut by hand from
354 // unmerged branches, receives no fixes, and is never offered to anyone.
355 // Reaching it from stable or nightly takes an explicit ask and an explicit
356 // acknowledgement; the flag alone is not enough from a script.
357 const currentChannel = cliReleaseChannelOf(currentVersion);
358 if (targetChannel === "preview" && currentChannel !== "preview") {
359 yield* Console.log(
360 [
361 `t3@${targetVersion} is a preview build.`,
362 " Preview builds are cut by maintainers from unreleased branches to exercise the release",
363 " pipeline. They can be broken, receive no fixes, and are never offered as updates; you",
364 ` will have to switch back to ${currentChannel} yourself with \`t3 update --channel ${currentChannel} --allow-downgrade\`.`,
365 ].join("\n"),
366 );
367 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
368 return yield* new CliUpdateError({
369 reason:
370 "Refusing to install a preview build without confirmation. Run this from a terminal to confirm, or pass --channel preview from an interactive shell.",
371 });
372 }
373 const confirmed = yield* Prompt.run(
374 Prompt.confirm({ message: "Install the preview build anyway?", initial: false }),
375 ).pipe(Effect.catchTag("QuitError", () => Effect.succeed(false)));
376 if (!confirmed) {
377 yield* Console.log("Left as is.");
378 return;
379 }
380 }
381
382 // Work out everything that will be touched before touching anything, so the
383 // user sees one plan and one question rather than a surprise restart.
384 const status = yield* service.status;
385 // The unit name is per user, not per T3 home. Only touch the service when it
386 // serves the home this update targets; otherwise it belongs to another
387 // install on this machine and restarting it would take that server down.
388 const servesThisHome =
389 status.installedBaseDir !== undefined &&
390 path.resolve(status.installedBaseDir) === path.resolve(input.baseDir);
391 const serviceInstalled = status.supported && status.installed && servesThisHome;
392 const foreground = yield* findForegroundServer({
393 serverRuntimeStatePath: input.serverRuntimeStatePath,
394 serviceInstalled,
395 });
396 // What this machine runs is the executable behind the launcher and, when a
397 // service is installed for this home, the version that service runs. Either
398 // being stale is an update to do, and the newest of the two is what the
399 // downgrade check protects.
400 const serviceVersion = serviceInstalled ? status.installedVersion : undefined;
401 const executableCurrent = targetVersion === currentVersion;
402 // A service whose recorded version is missing or unreadable is not known
403 // to be current, so it gets the update rather than being skipped.
404 const serviceCurrent = !serviceInstalled || serviceVersion === targetVersion;
405 const newestInstalled =
406 serviceVersion !== undefined && compareExactServiceVersions(serviceVersion, currentVersion) > 0
407 ? serviceVersion
408 : currentVersion;
409
410 if (executableCurrent && serviceCurrent) {
411 yield* Console.log(
412 serviceVersion !== undefined
413 ? `t3 and its background service are already on ${targetVersion} (${targetChannel}).`
414 : `t3 is already on ${targetVersion} (${targetChannel}).`,
415 );
416 return;
417 }
418 if (!input.allowDowngrade && compareExactServiceVersions(targetVersion, newestInstalled) < 0) {
419 return yield* new CliUpdateError({
420 reason: `t3@${targetVersion} is older than the installed ${newestInstalled}. Pass --allow-downgrade to install it anyway.`,
421 });
422 }
423
424 const alreadyOnDisk = yield* fs
425 .readFileString(pinnedRuntimePaths(path, input.baseDir, targetVersion, platform).sentinelPath)
426 .pipe(
427 Effect.map((sentinel) => sentinel.trim() === targetVersion),
428 Effect.orElseSucceed(() => false),
429 );
430
431 yield* Console.log(
432 executableCurrent
433 ? `Updating the background service ${serviceVersion ?? "(unknown version)"} -> ${targetVersion} (${targetChannel}).`
434 : alreadyOnDisk
435 ? `Switching t3 ${currentVersion} -> ${targetVersion} (${targetChannel}, already downloaded).`
436 : `Updating t3 ${currentVersion} -> ${targetVersion} (${targetChannel}).`,
437 );
438 let restartService = false;
439 if (serviceInstalled && !serviceCurrent) {
440 yield* Console.log(
441 " A background service is installed for this T3 home. Restarting it interrupts anything running in it: agent turns, terminals, remote clients.",
442 );
443 if (input.assumeYes) {
444 restartService = true;
445 } else if (process.stdin.isTTY && process.stdout.isTTY) {
446 restartService = yield* Prompt.run(
447 Prompt.confirm({
448 message: "Restart the background service once the download is verified?",
449 initial: true,
450 }),
451 ).pipe(Effect.catchTag("QuitError", () => Effect.succeed(false)));
452 } else {
453 yield* Console.log(
454 " Not a terminal, so the service is left on its current version. Rerun with --yes to restart it, or run `t3 service update` later.",
455 );
456 }
457 }
458
459 const runtime = yield* ensurePinnedRuntimeInstalled({
460 baseDir: input.baseDir,
461 version: targetVersion,
462 fs,
463 path,
464 runner,
465 httpClient,
466 platform,
467 arch,
468 releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined,
469 validate: (paths) =>
470 runner
471 .run({
472 command: pinnedRuntimeCommand(paths).command,
473 args: [...pinnedRuntimeCommand(paths).args, "--version"],
474 timeout: Duration.seconds(30),
475 })
476 .pipe(
477 Effect.mapError(
478 (cause) =>
479 new PinnedRuntimeInstallError({ step: "verifying the downloaded t3", cause }),
480 ),
481 Effect.flatMap((result) =>
482 result.code === 0 && /\bv(\S+)\s*$/.exec(result.stdout)?.[1] === targetVersion
483 ? Effect.void
484 : Effect.fail(
485 new PinnedRuntimeInstallError({
486 step: "verifying the downloaded t3",
487 exitCode: Number(result.code),
488 }),
489 ),
490 ),
491 ),
492 }).pipe(
493 Effect.catchIf(
494 (error): error is PinnedRuntimeInstallError =>
495 error._tag === "PinnedRuntimeInstallError" &&
496 error.step.startsWith("downloading the t3 release checksums") &&
497 String(error.cause).includes("404"),
498 () =>
499 Effect.fail(
500 new CliUpdateError({
501 reason: `No release archive was published for t3@${targetVersion}.`,
502 }),
503 ),
504 ),
505 );
506
507 const launchedAs = (yield* HostProcessIsExecutable) ? yield* resolveLauncherPath : undefined;
508 const repointed = yield* repointLauncher({
509 launchedAs,
510 versionsDir: path.dirname(runtime.versionDir),
511 targetEntryPath: runtime.entryPath,
512 });
513
514 // The new executable owns the service switch: it verifies itself, writes its
515 // own version into the unit, and restarts the service on it.
516 let serviceUpdated = false;
517 if (restartService) {
518 const result = yield* runner.run({
519 command: runtime.entryPath,
520 args: [
521 "service",
522 "update",
523 "--base-dir",
524 input.baseDir,
525 ...(input.allowDowngrade ? ["--allow-downgrade"] : []),
526 ],
527 timeout: Duration.minutes(5),
528 });
529 if (result.code !== 0) {
530 return yield* new CliUpdateError({
531 reason: `t3@${targetVersion} is installed but the background service could not be updated (exit ${String(result.code)}).\n${result.stderr.trim() || result.stdout.trim()}`,
532 });
533 }
534 serviceUpdated = true;
535 }
536
537 yield* Console.log("");
538 yield* Console.log(`t3 ${targetVersion} is installed at ${runtime.entryPath}`);
539 if (Option.isSome(repointed)) {
540 yield* Console.log(` ${repointed.value} now runs ${targetVersion}`);
541 } else {
542 yield* Console.log(` Run it as ${runtime.entryPath}, or point your \`t3\` launcher at it.`);
543 }
544 if (serviceUpdated) {
545 yield* Console.log(` Background service restarted on ${targetVersion}`);
546 } else if (serviceInstalled && serviceCurrent) {
547 yield* Console.log(` Background service already on ${targetVersion}`);
548 } else if (serviceInstalled) {
549 yield* Console.log(
550 ` Background service still running ${serviceVersion ?? "an unknown version"}. Run \`t3 service update\` when you are ready to restart it.`,
551 );
552 } else if (status.installed && !servesThisHome) {
553 yield* Console.log(
554 ` The background service serves ${status.installedBaseDir ?? "another T3 home"} and was left unchanged.`,
555 );
556 }
557 if (foreground !== undefined) {
558 yield* Console.log(
559 ` A server started by hand is still running at ${foreground.origin} (pid ${foreground.pid}). Stop it and start it again to pick up ${targetVersion}.`,
560 );
561 }
562});