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

update.ts

752 lines28.7 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 releaseAssetUrl,
9 updateFeedFileName,
10 type CliReleaseChannel,
11} from "@t3tools/shared/cliRelease";
12import * as Console from "effect/Console";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/cli";
21import {
22 FetchHttpClient,
23 HttpClient,
24 HttpClientError,
25 HttpClientRequest,
26 HttpClientResponse,
27} from "effect/http";
28​
29import packageJson from "../../package.json" with { type: "json" };
30import * as BootService from "../cloud/bootService.ts";
31import {
32 ensurePinnedRuntimeInstalled,
33 findPosixLauncher,
34 generatedWindowsShimTarget,
35 launcherOwnsVersionsDir,
36 isUnpublishedRelease,
37 pinnedRuntimePaths,
38 PinnedRuntimeInstallError,
39 PinnedRuntimePreflightBlockedError,
40 pinnedRuntimeVersionsDir,
41 prunePinnedRuntimes,
42 recordPinnedRuntimeLauncher,
43 resolveLauncherPath,
44 windowsShimTarget,
45 writePosixLauncher,
46} from "../cloud/pinnedRuntime.ts";
47import {
48 compareExactServiceVersions,
49 decodeServiceUnit,
50 isExactServiceVersion,
51 SERVICE_LAUNCHER_PROTOCOL,
52} from "../cloud/serviceProtocol.ts";
53import { runStagedServicePreflight } from "../cloud/servicePreflight.ts";
54import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
55import { managedUpdateMirror, managedUpdateRefusal } from "../policy/managedUpdates.ts";
56import * as ProcessRunner from "../processRunner.ts";
57import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
58import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
59import { hostShellWord } from "./invocation.ts";
60import { createUpdateProgress } from "./updateProgress.ts";
61import * as CliService from "./service.ts";
62​
63export class CliUpdateError extends Schema.TaggedError<CliUpdateError>()("CliUpdateError", {
64 reason: Schema.String,
65 cause: Schema.optional(Schema.Defect()),
66}) {
67 override get message(): string {
68 return this.reason;
69 }
71​
72const ReleaseIndex = Schema.Array(
73 Schema.Struct({
74 tag_name: Schema.String,
75 draft: Schema.optional(Schema.Boolean),
76 }),
77);
78const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex));
79​
80const RELEASE_INDEX_TIMEOUT = Duration.seconds(30);
81const RELEASE_INDEX_MAX_PAGES = 10;
82​
83const isPinnedRuntimeInstallError = Schema.is(PinnedRuntimeInstallError);
84​
85const resolveGithubToken = (
86 explicitToken: string | undefined,
87 environment: Readonly<Record<string, string | undefined>>,
88): string | undefined =>
89 explicitToken?.trim() ||
90 environment.GH_TOKEN?.trim() ||
91 environment.GITHUB_TOKEN?.trim() ||
92 undefined;
93​
94const buildAuthenticatedUpdateCommand = (input: {
95 readonly requestedVersion?: string | undefined;
96 readonly channel?: CliReleaseChannel | undefined;
97 readonly allowDowngrade?: boolean;
98 readonly assumeYes?: boolean;
99}): string => {
100 const parts = ["t3", "update"];
101 if (input.requestedVersion !== undefined) {
102 parts.push(input.requestedVersion);
103 } else if (input.channel !== undefined) {
104 parts.push("--channel", input.channel);
105 }
106 if (input.allowDowngrade) parts.push("--allow-downgrade");
107 if (input.assumeYes) parts.push("--yes");
108 parts.push("--github-token", "$(gh auth token)");
109 return parts.join(" ");
110};
111​
112export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(function* (
113 channel: CliReleaseChannel,
114 explicitGithubToken?: string | undefined,
115 retryCommand?: string | undefined,
116) {
117 const httpClient = yield* HttpClient.HttpClient;
118 const environment = yield* HostProcess.Environment;
119 const githubToken = resolveGithubToken(explicitGithubToken, environment);
120 for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) {
121 const request = HttpClientRequest.get(cliReleaseIndexPageUrl(page)).pipe(
122 HttpClientRequest.setHeader("Accept", "application/vnd.github+json"),
123 );
124 const authenticatedRequest =
125 githubToken === undefined
126 ? request
127 : HttpClientRequest.setHeader(request, "Authorization", `Bearer ${githubToken}`);
128 const body = yield* httpClient.execute(authenticatedRequest).pipe(
129 Effect.flatMap(HttpClientResponse.filterStatusOk),
130 Effect.flatMap((response) => response.text),
131 Effect.mapError((error) => {
132 const status =
133 HttpClientError.isHttpClientError(error) && error.reason._tag === "StatusCodeError"
134 ? error.reason.response.status
135 : undefined;
136 if (githubToken !== undefined && (status === 401 || status === 403)) {
137 return new CliUpdateError({
138 reason:
139 "GitHub rejected the provided token while listing t3 releases. Check `--github-token` (or GH_TOKEN / GITHUB_TOKEN).",
140 cause: error,
141 });
142 }
143 return new CliUpdateError({ reason: "Could not list t3 releases.", cause: error });
144 }),
145 Effect.timeoutOrElse({
146 duration: RELEASE_INDEX_TIMEOUT,
147 orElse: () => Effect.fail(new CliUpdateError({ reason: "Timed out listing t3 releases." })),
148 }),
149 );
150 const releases = yield* decodeReleaseIndex(body).pipe(
151 Effect.mapError(
152 () => new CliUpdateError({ reason: "The t3 release index had an unexpected shape." }),
153 ),
154 );
155 const version = newestCliReleaseVersion(releases, channel, {
156 includeDrafts: channel === "preview" && githubToken !== undefined,
157 });
158 if (version !== undefined) return version;
159 if (releases.length === 0) break;
160 }
161 if (channel === "preview") {
162 const command = retryCommand ?? buildAuthenticatedUpdateCommand({ channel: "preview" });
163 return yield* new CliUpdateError({
164 reason:
165 githubToken === undefined
166 ? `No published preview release was found. If it's behind auth, run \`${command}\`.`
167 : "No preview release was found. Make sure your GitHub token has access to pingdotgg/t3code.",
168 });
169 }
170 return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` });
171});
172​
173/** The version an update mirror's feed file for this platform offers on `channel`. */
174export const resolveMirrorVersion = Effect.fn("cli.update.resolve_mirror")(function* (
175 mirror: { readonly organization: string; readonly feedUrl: string },
176 channel: CliReleaseChannel,
177) {
178 if (channel === "preview") {
179 return yield* new CliUpdateError({
180 reason: `${mirror.organization}'s update mirror has no preview builds.`,
181 });
182 }
183 const httpClient = yield* HttpClient.HttpClient;
184 const fileName = updateFeedFileName(
185 channel === "nightly" ? "nightly" : "latest",
186 yield* HostProcess.Platform,
187 yield* HostProcess.Architecture,
188 );
189 const url = releaseAssetUrl(mirror.feedUrl, fileName);
190 // Not the URL, whose query can hold the mirror's access token.
191 const unreadable = new CliUpdateError({
192 reason: `Could not read ${fileName} from ${mirror.organization}'s update mirror.`,
193 });
194 const body = yield* httpClient.get(url).pipe(
195 Effect.flatMap(HttpClientResponse.filterStatusOk),
196 Effect.flatMap((response) => response.text),
197 Effect.mapError(() => unreadable),
198 Effect.timeoutOrElse({
199 duration: RELEASE_INDEX_TIMEOUT,
200 orElse: () => Effect.fail(unreadable),
201 }),
202 );
203 const version = /^version:\s*["']?([^"'\s]+)/m.exec(body)?.[1];
204 if (
205 version === undefined ||
206 !isExactServiceVersion(version) ||
207 cliReleaseChannelOf(version) !== channel
208 ) {
209 return yield* unreadable;
210 }
211 return version;
212});
213​
214/**
215 * Only a launcher that already points into this home's `runtime/versions` tree is touched; a
216 * plain copy of the executable, or a launcher for some other install, is left alone. It is
217 * recorded before it moves, so prune never meets a repointed launcher it does not know about.
218 */
219export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function* (input: {
220 readonly launchedAs: string | undefined;
221 readonly baseDir: string;
222 readonly targetEntryPath: string;
223}) {
224 const fs = yield* FileSystem.FileSystem;
225 const path = yield* Path.Path;
226 const platform = yield* HostProcess.Platform;
227 if (input.launchedAs === undefined) return Option.none<string>();
228 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
229 const ownsTarget = (candidate: string) => launcherOwnsVersionsDir(path, versionsDir, candidate);
230 const remember = (launcher: string) =>
231 recordPinnedRuntimeLauncher({ baseDir: input.baseDir, launcher }).pipe(
232 Effect.mapError(
233 () => new CliUpdateError({ reason: `Could not record the t3 launcher at ${launcher}.` }),
234 ),
235 );
236​
237 if (platform === "win32") {
238 const shimPath = yield* findWindowsShim(input.launchedAs, versionsDir);
239 if (shimPath === undefined) return Option.none<string>();
240 const current = yield* fs.readFileString(shimPath).pipe(Effect.option);
241 const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined;
242 if (quoted === undefined || !ownsTarget(quoted)) return Option.none<string>();
243 yield* remember(shimPath);
244 yield* fs
245 .writeFileString(shimPath, `@echo off\r\n"${input.targetEntryPath}" %*`)
246 .pipe(
247 Effect.mapError(
248 () => new CliUpdateError({ reason: `Could not rewrite the t3 launcher at ${shimPath}.` }),
249 ),
250 );
251 return Option.some(shimPath);
252 }
253​
254 const launcher = yield* findPosixLauncher({ launchedAs: input.launchedAs, versionsDir });
255 if (launcher === undefined) return Option.none<string>();
256 yield* remember(launcher);
257 yield* writePosixLauncher({
258 launcher,
259 executable: input.targetEntryPath,
260 exclusive: false,
261 }).pipe(
262 Effect.mapError(
263 (cause) =>
264 new CliUpdateError({ reason: `Could not repoint the t3 launcher at ${launcher}.`, cause }),
265 ),
266 );
267 return Option.some(launcher);
268});
269​
270/** Windows executables see their own path, so locate the installer shim by matching its target. */
271export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* (
272 executablePath: string,
273 versionsDir?: string,
274) {
275 const fs = yield* FileSystem.FileSystem;
276 const path = yield* Path.Path;
277 const environment = yield* HostProcess.Environment;
278 const candidates = [
279 ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []),
280 ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"),
281 ]
282 .filter((entry) => entry.trim().length > 0)
283 .map((directory) => ({
284 shimPath: path.join(directory, "t3.cmd"),
285 parseTarget: windowsShimTarget,
286 }));
287 if (versionsDir !== undefined) {
288 const recorded = yield* fs
289 .readFileString(path.join(path.dirname(versionsDir), "launchers"))
290 .pipe(Effect.orElseSucceed(() => ""));
291 for (const shimPath of recorded.split(/\r?\n/)) {
292 if (path.isAbsolute(shimPath) && path.basename(shimPath).toLowerCase() === "t3.cmd") {
293 candidates.push({ shimPath, parseTarget: generatedWindowsShimTarget });
294 }
295 }
296 }
297 for (const { shimPath, parseTarget } of candidates) {
298 const contents = yield* fs.readFileString(shimPath).pipe(Effect.option);
299 if (Option.isNone(contents)) continue;
300 const target = parseTarget(contents.value);
301 if (
302 target !== undefined &&
303 path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase()
304 ) {
305 return shimPath;
306 }
307 }
308 return undefined;
309});
310​
311const updateFlags = {
312 ...projectLocationFlags,
313 channel: Flag.Literals("channel", CLI_RELEASE_CHANNELS).pipe(
314 Flag.withDescription(
315 "Release channel to follow. Defaults to the channel this t3 was published on.",
316 ),
317 Flag.optional,
318 ),
319 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
320 Flag.withDescription("Allow moving to an older version than the one running."),
321 Flag.withDefault(false),
322 ),
323 yes: Flag.Boolean("yes").pipe(
324 Flag.withAlias("y"),
325 Flag.withDescription(
326 "Restart the background service without asking. Required to restart it from a script, where there is no prompt.",
327 ),
328 Flag.withDefault(false),
329 ),
330 githubToken: Flag.String("github-token").pipe(
331 Flag.withDescription(
332 "GitHub token for listing and downloading unlisted preview releases. Defaults to GH_TOKEN or GITHUB_TOKEN.",
333 ),
334 Flag.optional,
335 ),
336};
337​
338const versionArgument = Argument.String("version").pipe(
339 Argument.withDescription(
340 "Exact version to install. Defaults to the newest release on the channel.",
341 ),
342 Argument.optional,
343);
344​
345export const updateCommand = Command.make("update", {
346 ...updateFlags,
347 version: versionArgument,
348}).pipe(
349 Command.withDescription(
350 "Download a newer t3 and switch this machine to it, including the background service when one is installed.",
351 ),
352 Command.withHandler((flags) =>
353 Effect.gen(function* () {
354 const logLevel = yield* GlobalFlag.LogLevel;
355 const config = yield* resolveCliAuthConfig(flags, logLevel);
356 return yield* runUpdate({
357 baseDir: config.baseDir,
358 logsDir: config.logsDir,
359 databasePath: config.dbPath,
360 serverRuntimeStatePath: config.serverRuntimeStatePath,
361 channel: Option.getOrUndefined(flags.channel),
362 requestedVersion: Option.getOrUndefined(flags.version),
363 allowDowngrade: flags.allowDowngrade,
364 assumeYes: flags.yes,
365 githubToken: Option.getOrUndefined(flags.githubToken),
366 }).pipe(
367 Effect.provide(
368 Layer.mergeAll(
369 CliService.layer(config),
370 ProcessRunner.layer,
371 FetchHttpClient.layer,
372 ManagedPolicy.layer,
373 ),
374 ),
375 );
376 }),
377 ),
378);
379​
380const findForegroundServer = Effect.fn("cli.update.find_foreground_server")(function* (input: {
381 readonly serverRuntimeStatePath: string;
382 readonly serviceInstalled: boolean;
383}) {
384 const state = yield* readPersistedServerRuntimeState(input.serverRuntimeStatePath);
385 if (Option.isNone(state) || state.value.serviceManaged || !isProcessAlive(state.value.pid)) {
386 return undefined;
387 }
388 if (input.serviceInstalled && (yield* belongsToBootService(state.value.pid))) return undefined;
389 return state.value;
390});
391​
392const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(function* (
393 pid: number,
394) {
395 const platform = yield* HostProcess.Platform;
396 const fs = yield* FileSystem.FileSystem;
397 const runner = yield* ProcessRunner.ProcessRunner;
398 if (platform === "linux") {
399 const cgroup = yield* fs.readFileString(`/proc/${pid}/cgroup`).pipe(Effect.option);
400 return Option.isSome(cgroup) && cgroup.value.includes("/t3code.service");
401 }
402 if (platform === "darwin") {
403 const parent = yield* runner
404 .run({
405 command: "ps",
406 args: ["-o", "ppid=", "-p", String(pid)],
407 timeout: Duration.seconds(5),
408 })
409 .pipe(Effect.option);
410 const ppid = Option.isSome(parent) && parent.value.code === 0 ? parent.value.stdout.trim() : "";
411 if (!/^\d+$/.test(ppid)) return false;
412 const command = yield* runner
413 .run({ command: "ps", args: ["-o", "command=", "-p", ppid], timeout: Duration.seconds(5) })
414 .pipe(
415 Effect.map((result) => (result.code === 0 ? result.stdout : "")),
416 Effect.orElseSucceed(() => ""),
417 );
418 return /__service-launcher/.test(command);
419 }
420 return false;
421});
422​
423export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
424 readonly baseDir: string;
425 readonly logsDir: string;
426 readonly databasePath: string;
427 readonly serverRuntimeStatePath: string;
428 readonly channel: CliReleaseChannel | undefined;
429 readonly requestedVersion: string | undefined;
430 readonly allowDowngrade: boolean;
431 readonly assumeYes: boolean;
432 readonly githubToken?: string | undefined;
433}) {
434 const fs = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const runner = yield* ProcessRunner.ProcessRunner;
437 const platform = yield* HostProcess.Platform;
438 const arch = yield* HostProcess.Architecture;
439 const environment = yield* HostProcess.Environment;
440 const httpClient = yield* HttpClient.HttpClient;
441 const service = yield* BootService.BootService;
442 const policy = yield* ManagedPolicy.ManagedPolicy;
443 const mirror = managedUpdateMirror(policy.document);
444 const githubToken = resolveGithubToken(input.githubToken, environment);
445​
446 const currentVersion = packageJson.version;
447 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
448 const refusal = managedUpdateRefusal(
449 policy.document,
450 input.requestedVersion === undefined ? channel : cliReleaseChannelOf(input.requestedVersion),
451 );
452 if (refusal !== undefined) {
453 return yield* new CliUpdateError({ reason: refusal });
454 }
455 if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
456 return yield* new CliUpdateError({
457 reason: `'${input.requestedVersion}' is not an exact t3 version.`,
458 });
459 }
460 const retryCommand = buildAuthenticatedUpdateCommand({
461 requestedVersion: input.requestedVersion,
462 channel: input.channel,
463 allowDowngrade: input.allowDowngrade,
464 assumeYes: input.assumeYes,
465 });
466 const progress = createUpdateProgress();
467 progress.status("Checking for updates...");
468 const targetVersion = yield* (
469 input.requestedVersion !== undefined
470 ? Effect.succeed(input.requestedVersion)
471 : mirror === undefined
472 ? resolveNewestVersion(channel, githubToken, retryCommand)
473 : resolveMirrorVersion(mirror, channel)
474 ).pipe(Effect.ensuring(Effect.sync(progress.finish)));
475 const targetChannel = cliReleaseChannelOf(targetVersion);
476​
477 const currentChannel = cliReleaseChannelOf(currentVersion);
478 if (targetChannel === "preview" && currentChannel !== "preview") {
479 yield* Console.log(
480 [
481 `t3@${targetVersion} is a preview build.`,
482 " Preview builds are cut by maintainers from unreleased branches to exercise the release",
483 " pipeline. They can be broken, receive no fixes, and are never offered as updates; you",
484 ` will have to switch back to ${currentChannel} yourself with \`t3 update --channel ${currentChannel} --allow-downgrade\`.`,
485 ].join("\n"),
486 );
487 if (!(process.stdin.isTTY && process.stdout.isTTY)) {
488 return yield* new CliUpdateError({
489 reason:
490 "Refusing to install a preview build without confirmation. Run this from a terminal to confirm, or pass --channel preview from an interactive shell.",
491 });
492 }
493 const confirmed = yield* Prompt.run(
494 Prompt.Confirm({ message: "Install the preview build anyway?", initial: false }),
495 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
496 if (!confirmed) {
497 yield* Console.log("Left as is.");
498 return;
499 }
500 }
501​
502 const status = yield* service.status;
503 // Service names are per user, so another home's unit belongs to a different install.
504 const servesThisHome = status.installedBaseDir !== undefined && status.otherBaseDir === undefined;
505 const serviceInstalled = status.supported && status.installed && servesThisHome;
506 const foreground = yield* findForegroundServer({
507 serverRuntimeStatePath: input.serverRuntimeStatePath,
508 serviceInstalled,
509 });
510 const serviceVersion = serviceInstalled ? status.installedVersion : undefined;
511 const executableCurrent = targetVersion === currentVersion;
512 const restartPending = status.problems?.includes("restart-pending") === true;
513 const serviceCurrent =
514 !serviceInstalled ||
515 (serviceVersion === targetVersion &&
516 (executableCurrent ? status.current : (status.problems ?? []).length === 0));
517 const newestInstalled =
518 serviceVersion !== undefined && compareExactServiceVersions(serviceVersion, currentVersion) > 0
519 ? serviceVersion
520 : currentVersion;
521​
522 if (executableCurrent && serviceCurrent) {
523 yield* Console.log(
524 serviceVersion !== undefined
525 ? `t3 and its background service are already on ${targetVersion} (${targetChannel}).`
526 : `t3 is already on ${targetVersion} (${targetChannel}).`,
527 );
528 return;
529 }
530 if (!input.allowDowngrade && compareExactServiceVersions(targetVersion, newestInstalled) < 0) {
531 return yield* new CliUpdateError({
532 reason: `t3@${targetVersion} is older than the installed ${newestInstalled}. Pass --allow-downgrade to install it anyway.`,
533 });
534 }
535​
536 const alreadyOnDisk = yield* fs
537 .readFileString(pinnedRuntimePaths(path, input.baseDir, targetVersion, platform).sentinelPath)
538 .pipe(
539 Effect.map((sentinel) => sentinel.trim() === targetVersion),
540 Effect.orElseSucceed(() => false),
541 );
542​
543 progress.heading(
544 executableCurrent && restartPending
545 ? `The background service is still running the version before ${targetVersion} (${targetChannel}).`
546 : executableCurrent
547 ? `Updating the background service ${serviceVersion ?? "(unknown version)"} -> ${targetVersion} (${targetChannel}).`
548 : alreadyOnDisk
549 ? "Switching T3 Code"
550 : "Updating T3 Code",
551 executableCurrent
552 ? ""
553 : `${currentVersion} → ${targetVersion}${targetChannel === "stable" ? "" : ` (${targetChannel})`}`,
554 );
555 let restartService = false;
556 if (serviceInstalled && !serviceCurrent) {
557 yield* Console.log(
558 " A background service is installed for this T3 home. Restarting it interrupts anything running in it: agent turns, terminals, remote clients.",
559 );
560 if (input.assumeYes) {
561 restartService = true;
562 } else if (process.stdin.isTTY && process.stdout.isTTY) {
563 restartService = yield* Prompt.run(
564 Prompt.Confirm({
565 message: "Restart the background service once the download is verified?",
566 initial: true,
567 }),
568 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
569 } else {
570 yield* Console.log(
571 " Not a terminal, so the service keeps running its current version. Rerun with --yes to restart it now, or run `t3 service restart` later.",
572 );
573 }
574 }
575​
576 const releaseBaseUrl =
577 mirror?.feedUrl ?? (environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined);
578 const runtime = yield* ensurePinnedRuntimeInstalled({
579 onProgress: progress.report,
580 baseDir: input.baseDir,
581 version: targetVersion,
582 fs,
583 path,
584 runner,
585 httpClient,
586 platform,
587 arch,
588 releaseBaseUrl,
589 githubToken: releaseBaseUrl === undefined ? githubToken : undefined,
590 requirePublishedRelease: mirror !== undefined,
591 validate: (runtime) =>
592 runStagedServicePreflight({
593 runner,
594 runtime,
595 targetVersion,
596 databasePath: input.databasePath,
597 // The target then runs under its own launcher, so only its database check matters. Older
598 // builds may predate protocol 4; every stable release since 0.0.43 accepts 3.
599 launcherProtocol:
600 compareExactServiceVersions(targetVersion, currentVersion) < 0
601 ? 3
602 : SERVICE_LAUNCHER_PROTOCOL,
603 }).pipe(
604 Effect.catchTags({
605 PinnedRuntimeInstallError: (error) =>
606 Effect.fail(
607 error.exitCode === undefined
608 ? error
609 : new PinnedRuntimePreflightBlockedError({
610 version: targetVersion,
611 reason: `t3@${targetVersion} could not confirm it supports this database (its check exited with code ${error.exitCode}), so t3 did not switch to it.`,
612 }),
613 ),
614 }),
615 ),
616 }).pipe(
617 Effect.ensuring(Effect.sync(progress.finish)),
618 Effect.catchTags({
619 PinnedRuntimePreflightBlockedError: (error) =>
620 Effect.fail(new CliUpdateError({ reason: error.reason })),
621 }),
622 Effect.catchIf(
623 (error): error is PinnedRuntimeInstallError =>
624 isPinnedRuntimeInstallError(error) &&
625 releaseBaseUrl === undefined &&
626 githubToken !== undefined &&
627 error.downloadHost === "api.github.com" &&
628 (error.httpStatus === 401 || error.httpStatus === 403),
629 (error) =>
630 Effect.fail(
631 new CliUpdateError({
632 reason:
633 "GitHub rejected the provided token while downloading t3. Check `--github-token` (or GH_TOKEN / GITHUB_TOKEN).",
634 cause: error,
635 }),
636 ),
637 ),
638 Effect.catchIf(isUnpublishedRelease, () => {
639 if (mirror !== undefined) {
640 return Effect.fail(
641 new CliUpdateError({
642 reason: `${mirror.organization}'s update mirror has no t3@${targetVersion} for this machine.`,
643 }),
644 );
645 }
646 if (githubToken === undefined) {
647 return Effect.fail(
648 new CliUpdateError({
649 reason: `No release archive was found for t3@${targetVersion}. If it's behind auth, run \`${retryCommand}\`.`,
650 }),
651 );
652 }
653 return Effect.fail(
654 new CliUpdateError({
655 reason: `No release archive was found for t3@${targetVersion}. Make sure the release exists and your GitHub token has access to pingdotgg/t3code.`,
656 }),
657 );
658 }),
659 );
660​
661 const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined;
662 const repointed = yield* repointLauncher({
663 launchedAs,
664 baseDir: input.baseDir,
665 targetEntryPath: runtime.entryPath,
666 });
667​
668 // Use today's service manager for the target version. Inside the service it hands off to
669 // the target CLI, so stopping this process cannot interrupt the switch.
670 let servicePlan: BootService.BootServicePlan | undefined;
671 if (serviceInstalled && !serviceCurrent) {
672 yield* Console.log(
673 restartService
674 ? "Restarting the background service..."
675 : "Updating the background service...",
676 );
677 servicePlan = yield* BootService.BootService.pipe(
678 Effect.flatMap((target) =>
679 target.install({ allowDowngrade: input.allowDowngrade, start: restartService }),
680 ),
681 Effect.provide(
682 BootService.layer({
683 baseDir: input.baseDir,
684 logsDir: input.logsDir,
685 cliVersion: targetVersion,
686 }),
687 ),
688 Effect.mapError(
689 (error) =>
690 new CliUpdateError({
691 reason: `t3@${targetVersion} is installed but the background service could not be ${restartService ? "updated" : "pointed at it"}: ${error.message}`,
692 }),
693 ),
694 );
695 }
696​
697 // A handed-off service install rewrites the unit later, while the old launcher may be stopped.
698 if (servicePlan?.handedOff !== true) {
699 // A stopped service's unit still names the launcher runtime it will start.
700 const unit = yield* fs
701 .readFile(status.unitPath)
702 .pipe(Effect.map(decodeServiceUnit), Effect.option);
703 yield* prunePinnedRuntimes({
704 baseDir: input.baseDir,
705 keep: [currentVersion, targetVersion],
706 references: Option.toArray(Option.flatMapNullishOr(unit, BootService.bootServiceProgramOf)),
707 });
708 }
709​
710 progress.success(`Installed T3 Code ${targetVersion}`);
711 if (Option.isSome(repointed)) {
712 yield* Console.log(" Run t3 to get started.\n");
713 } else {
714 // Command Prompt and PowerShell share no quoted form, so Windows keeps the bare path.
715 const entry =
716 platform === "win32" ? runtime.entryPath : hostShellWord(platform, runtime.entryPath);
717 yield* Console.log(` Run ${entry}\n`);
718 }
719 if (servicePlan?.handedOff === true) {
720 yield* Console.log(
721 ` Background service switching to ${targetVersion} outside this session, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
722 );
723 } else if (servicePlan !== undefined && restartService) {
724 yield* Console.log(` Background service restarted on ${targetVersion}`);
725 } else if (serviceInstalled && serviceCurrent) {
726 yield* Console.log(` Background service already on ${targetVersion}`);
727 } else if (serviceInstalled) {
728 // A pending restart means the service already points at serviceVersion but runs an older one.
729 const running =
730 serviceVersion === undefined
731 ? "an unknown version"
732 : restartPending
733 ? `the version before ${serviceVersion}`
734 : serviceVersion;
735 yield* Console.log(
736 ` Background service still running ${running}. Run \`t3 service restart\` when you are ready to switch it to ${targetVersion}.`,
737 );
738 } else if (status.installed && status.installedBaseDir === undefined) {
739 yield* Console.log(
740 ` A background service definition was found, but its T3 home could not be determined, so it was left unchanged. Check ${status.unitPath}.`,
741 );
742 } else if (status.installed && !servesThisHome) {
743 yield* Console.log(
744 ` The background service serves ${status.installedBaseDir} and was left unchanged.`,
745 );
746 }
747 if (foreground !== undefined) {
748 yield* Console.log(
749 ` A server started by hand is still running at ${foreground.origin} (pid ${foreground.pid}). Stop it and start it again to pick up ${targetVersion}.`,
750 );
751 }
752});