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

service.ts

201 lines7.0 KB

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