Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Console from "effect/Console";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Terminal from "effect/Terminal";
6import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
7import { FetchHttpClient } from "effect/http";
8
9import packageJson from "../../package.json" with { type: "json" };
10import * as BootService from "../cloud/bootService.ts";
11import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
12import type * as ServerConfig from "../config.ts";
13import * as ProcessRunner from "../processRunner.ts";
14import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
15
16export const layer = (config: ServerConfig.ServerConfig["Service"]) =>
17 BootService.layer({
18 baseDir: config.baseDir,
19 logsDir: config.logsDir,
20 cliVersion: packageJson.version,
21 }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer));
22
23export type ServiceReconcileResult =
24 | {
25 readonly changed: false;
26 readonly status: BootService.BootServiceStatus;
27 }
28 | {
29 readonly changed: true;
30 readonly previouslyInstalled: boolean;
31 readonly plan: BootService.BootServicePlan;
32 };
33
34const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
35 readonly allowDowngrade?: boolean;
36 readonly start?: boolean;
37}) {
38 const service = yield* BootService.BootService;
39 const status = yield* service.status;
40 if (status.installed && status.current) {
41 return { changed: false, status } satisfies ServiceReconcileResult;
42 }
43 if (
44 status.installedVersion !== undefined &&
45 options?.allowDowngrade !== true &&
46 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
47 ) {
48 return yield* new BootService.BootServiceDowngradeRefusedError({
49 installedVersion: status.installedVersion,
50 targetVersion: packageJson.version,
51 });
52 }
53 const plan = yield* service.install(options);
54 return {
55 changed: true,
56 previouslyInstalled: status.installed,
57 plan,
58 } satisfies ServiceReconcileResult;
59});
60
61function formatServiceChange(
62 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
63): string {
64 if (result.plan.handedOff === true) {
65 return `Handed the T3 Code service switch to t3@${packageJson.version} to a separate systemd unit, since this session runs inside the service and disconnects when it restarts.\nResult: ${result.plan.logPath}`;
66 }
67 return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
68}
69
70function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion: string): string {
71 if (!status.supported) {
72 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
73 }
74 if (!status.installed) {
75 return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
76 }
77 const installedVersion = status.installedVersion ?? cliVersion;
78 const problems = (status.problems ?? []).map(
79 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,
80 );
81 if (
82 !status.current &&
83 status.installedVersion !== undefined &&
84 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
85 ) {
86 return [
87 "T3 Code service",
88 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
89 ` Unit: ${status.unitPath}`,
90 ` Logs: ${status.logPath}`,
91 ...problems,
92 ` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`,
93 ].join("\n");
94 }
95 return [
96 "T3 Code service",
97 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
98 ` Unit: ${status.unitPath}`,
99 ` Logs: ${status.logPath}`,
100 ...problems,
101 ...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]),
102 ].join("\n");
103}
104
105const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(
106 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
107 run: Effect.Effect<A, E, BootService.BootService>,
108) {
109 const logLevel = yield* GlobalFlag.LogLevel;
110 const config = yield* resolveCliAuthConfig(flags, logLevel);
111 return yield* run.pipe(Effect.provide(layer(config)));
112});
113
114const serviceReconcileFlags = {
115 ...projectLocationFlags,
116 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
117 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
118 Flag.withDefault(false),
119 ),
120};
121
122const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
123 Command.withDescription("Install T3 Code as a background service for this user."),
124 Command.withHandler((flags) =>
125 runServiceCommand(
126 flags,
127 Effect.gen(function* () {
128 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
129 if (!result.changed) {
130 yield* Console.log(
131 `T3 Code service is already installed with t3@${packageJson.version}.`,
132 );
133 return;
134 }
135 yield* Console.log(formatServiceChange(result));
136 }),
137 ),
138 ),
139);
140
141const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
142 Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
143 Command.unlisted,
144 Command.withHandler((flags) =>
145 runServiceCommand(
146 flags,
147 Effect.gen(function* () {
148 yield* Console.log(
149 "`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
150 );
151 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
152 if (!result.changed) {
153 yield* Console.log(`T3 Code service is already using t3@${packageJson.version}.`);
154 return;
155 }
156 yield* Console.log(formatServiceChange(result));
157 }),
158 ),
159 ),
160);
161
162const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(
163 Command.withDescription(
164 "Restart the background service. Picks up a version installed by `t3 update` that was not restarted at the time.",
165 ),
166 Command.withHandler((flags) =>
167 runServiceCommand(
168 flags,
169 Effect.gen(function* () {
170 const service = yield* BootService.BootService;
171 const status = yield* service.status;
172 const outcome = yield* service.restart;
173 const onVersion =
174 status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;
175 yield* Console.log(
176 outcome === "restarted"
177 ? `Restarted the T3 Code service${onVersion}.`
178 : outcome === "queued"
179 ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`
180 : "T3 Code service is not installed.",
181 );
182 }),
183 ),
184 ),
185);
186
187const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
188 Command.withDescription("Stop and remove the T3 Code background service."),
189 Command.withHandler((flags) =>
190 runServiceCommand(
191 flags,
192 Effect.gen(function* () {
193 const service = yield* BootService.BootService;
194 const removed = yield* service.uninstall;
195 yield* Console.log(
196 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
197 );
198 }),
199 ),
200 ),
201);
202
203const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
204 Command.withDescription("Show whether the T3 Code background service is installed."),
205 Command.withHandler((flags) =>
206 runServiceCommand(
207 flags,
208 Effect.gen(function* () {
209 const service = yield* BootService.BootService;
210 yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));
211 }),
212 ),
213 ),
214);
215
216export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";
217
218export const offerServiceDuringOnboarding = Effect.gen(function* () {
219 const service = yield* BootService.BootService;
220 const status = yield* service.status;
221 const { supported, installed, current } = status;
222 if (!supported) {
223 return "skipped" as const;
224 }
225 if (installed && current) {
226 yield* Console.log("T3 Code is already set up to run in the background on this machine.");
227 return "ready" as const;
228 }
229 for (const problem of status.problems ?? []) {
230 yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
231 }
232 if (
233 installed &&
234 status.installedVersion !== undefined &&
235 compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
236 ) {
237 yield* Console.log(
238 `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
239 );
240 return "skipped" as const;
241 }
242 const platform = yield* HostProcess.Platform;
243 const wanted = yield* Prompt.run(
244 Prompt.Confirm({
245 message: installed
246 ? "The installed T3 Code service needs an update or repair. Update it now?"
247 : platform === "darwin"
248 ? "Run T3 Code in the background whenever you log in to this Mac? " +
249 "It stays reachable through T3 Connect while you are logged in."
250 : "Run T3 Code in the background whenever this machine boots? " +
251 "It stays reachable through T3 Connect even after you log out.",
252 initial: true,
253 }),
254 );
255 if (!wanted) {
256 return "skipped" as const;
257 }
258 const result = yield* reconcileService();
259 if (result.changed) {
260 yield* Console.log(
261 result.plan.handedOff === true
262 ? formatServiceChange(result)
263 : `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
264 );
265 }
266 return result.changed && result.plan.handedOff === true
267 ? ("pending" as const)
268 : ("ready" as const);
269});
270
271const reportServiceSetupFailure = (error: BootService.BootServiceError) =>
272 Console.warn(`Background setup did not finish: ${error.message}`).pipe(
273 Effect.as("skipped" as const),
274 );
275
276export const recoverServiceOnboardingOffer = <R>(
277 offer: Effect.Effect<
278 ServiceOnboardingOutcome,
279 BootService.BootServiceError | Terminal.QuitError,
280 R
281 >,
282) =>
283 offer.pipe(
284 Effect.catchTags({
285 QuitError: () => Effect.succeed("skipped" as const),
286 BootServiceUnsupportedError: (error) =>
287 Console.log(`Skipping background setup: ${error.message}`).pipe(
288 Effect.as("skipped" as const),
289 ),
290 BootServiceCommandError: reportServiceSetupFailure,
291 BootServiceInstallError: reportServiceSetupFailure,
292 BootServicePrerequisiteError: reportServiceSetupFailure,
293 BootServiceUpdatePendingError: reportServiceSetupFailure,
294 BootServiceDowngradeRefusedError: reportServiceSetupFailure,
295 }),
296 );
297
298export const serviceCommand = Command.make("service").pipe(
299 Command.withDescription("Manage the T3 Code background service."),
300 Command.withSubcommands([
301 serviceInstallCommand,
302 serviceRestartCommand,
303 serviceUninstallCommand,
304 serviceStatusCommand,
305 serviceUpdateCommand,
306 ]),
307);