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

service.ts

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