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

update.ts

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