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

service.ts

299 lines11.1 KB

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