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