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

service.ts

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