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