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

service.ts

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