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