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

service.ts

310 lines11.3 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";
15import { resolveEntryPath } from "./invocation.ts";
16​
17export const layer = (config: ServerConfig.ServerConfig["Service"]) =>
18 BootService.layer({
19 baseDir: config.baseDir,
20 logsDir: config.logsDir,
21 cliVersion: packageJson.version,
22 }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer));
23​
24export type ServiceReconcileResult =
25 | {
26 readonly changed: false;
27 readonly status: BootService.BootServiceStatus;
28 }
29 | {
30 readonly changed: true;
31 readonly previouslyInstalled: boolean;
32 readonly plan: BootService.BootServicePlan;
33 };
34​
35const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
36 readonly allowDowngrade?: boolean;
37 readonly start?: boolean;
38}) {
39 const service = yield* BootService.BootService;
40 const status = yield* service.status;
41 if (status.installed && status.current) {
42 return { changed: false, status } satisfies ServiceReconcileResult;
43 }
44 if (
45 status.installedVersion !== undefined &&
46 options?.allowDowngrade !== true &&
47 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
48 ) {
49 return yield* new BootService.BootServiceDowngradeRefusedError({
50 installedVersion: status.installedVersion,
51 targetVersion: packageJson.version,
52 });
53 }
54 const plan = yield* service.install(options);
55 return {
56 changed: true,
57 previouslyInstalled: status.installed,
58 plan,
59 } satisfies ServiceReconcileResult;
60});
61​
62function formatServiceChange(
63 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
64): string {
65 if (result.plan.handedOff === true) {
66 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}`;
67 }
68 return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
70​
71function formatServiceStatus(status: BootService.BootServiceStatus, cliVersion: string): string {
72 if (!status.supported) {
73 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
74 }
75 if (!status.installed) {
76 return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
77 }
78 const installedVersion = status.installedVersion ?? cliVersion;
79 const problems = (status.problems ?? []).map(
80 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,
81 );
82 if (
83 !status.current &&
84 status.installedVersion !== undefined &&
85 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
86 ) {
87 return [
88 "T3 Code service",
89 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
90 ` Unit: ${status.unitPath}`,
91 ` Logs: ${status.logPath}`,
92 ...problems,
93 ` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`,
94 ].join("\n");
95 }
96 return [
97 "T3 Code service",
98 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
99 ` Unit: ${status.unitPath}`,
100 ` Logs: ${status.logPath}`,
101 ...problems,
102 ...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]),
103 ].join("\n");
105​
106const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
107 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
108 run: Effect.Effect<A, E, R>,
109) {
110 const logLevel = yield* GlobalFlag.LogLevel;
111 const config = yield* resolveCliAuthConfig(flags, logLevel);
112 return yield* run.pipe(Effect.provide(layer(config)));
113});
114​
115const serviceReconcileFlags = {
116 ...projectLocationFlags,
117 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
118 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
119 Flag.withDefault(false),
120 ),
121};
122​
123const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
124 Command.withDescription("Install T3 Code as a background service for this user."),
125 Command.withHandler((flags) =>
126 runServiceCommand(
127 flags,
128 Effect.gen(function* () {
129 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
130 if (!result.changed) {
131 yield* Console.log(
132 `T3 Code service is already installed with t3@${packageJson.version} (${yield* resolveEntryPath}).`,
133 );
134 return;
135 }
136 yield* Console.log(formatServiceChange(result));
137 }),
138 ),
139 ),
140);
141​
142const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
143 Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
144 Command.unlisted,
145 Command.withHandler((flags) =>
146 runServiceCommand(
147 flags,
148 Effect.gen(function* () {
149 yield* Console.log(
150 "`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
151 );
152 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
153 if (!result.changed) {
154 yield* Console.log(
155 `T3 Code service is already using t3@${packageJson.version} (${yield* resolveEntryPath}).`,
156 );
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);