Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

update.ts

552 lines21.5 KB

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