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

service.ts

310 lines11.2 KB

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