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

service.ts

430 lines16.7 KB

1import * as NodeUtil from "node:util";
2​
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Console from "effect/Console";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
10import { FetchHttpClient } from "effect/http";
11​
12import packageJson from "../../package.json" with { type: "json" };
13import * as BootService from "../cloud/bootService.ts";
14import * as ServiceProtection from "../cloud/serviceProtection.ts";
15import { compareExactServiceVersions, SERVICE_ENV_FILE } from "../cloud/serviceProtocol.ts";
16import * as ServerConfig from "../config.ts";
17import * as ProcessRunner from "../processRunner.ts";
18import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
19import { resolveEntryPath } from "./invocation.ts";
20​
21export const layer = (config: ServerConfig.ServerConfig["Service"]) =>
22 BootService.layer({
23 baseDir: config.baseDir,
24 logsDir: config.logsDir,
25 cliVersion: packageJson.version,
26 }).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(FetchHttpClient.layer));
27​
28export type ServiceReconcileResult =
29 | {
30 readonly changed: false;
31 readonly status: BootService.BootServiceStatus;
32 }
33 | {
34 readonly changed: true;
35 readonly previouslyInstalled: boolean;
36 readonly plan: BootService.BootServicePlan;
37 };
38​
39const SERVICE_ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/u;
40​
41/**
42 * Sets or removes (`undefined`) entries in `service.env` text and keeps every
43 * other line, including comments, as the user wrote it.
44 */
45export const upsertServiceEnv = (
46 contents: string,
47 entries: Readonly<Record<string, string | undefined>>,
48): string => {
49 const written = new Set<string>();
50 const lines = contents.split("\n").flatMap((line) => {
51 const key = SERVICE_ENV_KEY.exec(line)?.[1];
52 if (key === undefined || !Object.hasOwn(entries, key)) return [line];
53 const value = entries[key];
54 if (value === undefined || written.has(key)) return [];
55 written.add(key);
56 return [`${key}=${value}`];
57 });
58 while (lines.at(-1) === "") lines.pop();
59 for (const [key, value] of Object.entries(entries)) {
60 if (value !== undefined && !written.has(key)) lines.push(`${key}=${value}`);
61 }
62 return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
63};
64​
65/** `service.env` under `baseDir`, parsed as the service launcher parses it. */
66export const readServiceEnv = Effect.fn("cli.service.read_env")(function* (baseDir: string) {
67 const fs = yield* FileSystem.FileSystem;
68 const path = (yield* Path.Path).join(baseDir, SERVICE_ENV_FILE);
69 const contents = (yield* fs.exists(path)) ? yield* fs.readFileString(path) : "";
70 const entries = Object.entries(NodeUtil.parseEnv(contents)).flatMap(([key, value]) =>
71 value === undefined ? [] : [[key, value] as const],
72 );
73 return { path, contents, entries: Object.fromEntries(entries) };
74});
75​
76export const writeServiceEnv = Effect.fn("cli.service.write_env")(function* (
77 baseDir: string,
78 entries: Readonly<Record<string, string | undefined>>,
79) {
80 const fs = yield* FileSystem.FileSystem;
81 const current = yield* readServiceEnv(baseDir);
82 const next = upsertServiceEnv(current.contents, entries);
83 if (next === current.contents) return;
84 yield* fs.makeDirectory(baseDir, { recursive: true });
85 yield* fs.writeFileString(current.path, next);
86});
87​
88export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
89 readonly allowDowngrade?: boolean;
90 readonly start?: boolean;
91}) {
92 const { baseDir } = yield* ServerConfig.ServerConfig;
93 const service = yield* BootService.BootService;
94 const status = yield* service.status;
95 if (status.installed && status.current) {
96 return { changed: false, status } satisfies ServiceReconcileResult;
97 }
98 if (status.supported && !status.installed) {
99 // A new service listens on this machine only, until `t3 up` opens the local network.
100 const { entries } = yield* readServiceEnv(baseDir);
101 if (entries.T3CODE_LAN === undefined && entries.T3CODE_HOST === undefined) {
102 yield* writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
103 }
104 }
105 if (
106 status.installedVersion !== undefined &&
107 options?.allowDowngrade !== true &&
108 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
109 ) {
110 return yield* new BootService.BootServiceDowngradeRefusedError({
111 installedVersion: status.installedVersion,
112 targetVersion: packageJson.version,
113 });
114 }
115 const plan = yield* service.install(options);
116 return {
117 changed: true,
118 previouslyInstalled: status.installed,
119 plan,
120 } satisfies ServiceReconcileResult;
121});
122​
123export function formatServiceChange(
124 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
125): string {
126 if (result.plan.handedOff === true) {
127 return `Service update to t3@${packageJson.version} queued. This session will disconnect.\nLog: ${result.plan.logPath}`;
128 }
129 return `Service ${result.previouslyInstalled ? "updated" : "installed"} · t3@${packageJson.version}\nLog: ${result.plan.logPath}`;
131​
132function formatProtection(
133 protection: ServiceProtection.ServiceProtectionState | undefined,
134): ReadonlyArray<string> {
135 if (protection === undefined) return [];
136 return [
137 protection.unprotected === undefined
138 ? ` Memory protection: on${protection.setByProtect ? " (t3 service protect)" : ""}`
139 : ` Memory protection: off, ${protection.unprotected} grants none. Run \`t3 service protect\`.`,
140 ...(protection.oomScoreAdj === undefined ? [] : [` OOM score: ${protection.oomScoreAdj}`]),
141 ];
143​
144function formatServiceStatus(
145 status: BootService.BootServiceStatus,
146 cliVersion: string,
147 protection?: ServiceProtection.ServiceProtectionState,
148): string {
149 if (!status.supported) {
150 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
151 }
152 if (!status.installed) {
153 return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
154 }
155 const installedVersion = status.installedVersion ?? cliVersion;
156 const problems = (status.problems ?? []).map(
157 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem)}`,
158 );
159 if (
160 !status.current &&
161 status.installedVersion !== undefined &&
162 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
163 ) {
164 return [
165 "T3 Code service",
166 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
167 ` Unit: ${status.unitPath}`,
168 ` Logs: ${status.logPath}`,
169 ...formatProtection(protection),
170 ...problems,
171 ` Next: Run \`t3 update ${installedVersion}\` to match it, or pass \`--allow-downgrade\` to \`t3 service install\` explicitly.`,
172 ].join("\n");
173 }
174 return [
175 "T3 Code service",
176 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
177 ` Unit: ${status.unitPath}`,
178 ` Logs: ${status.logPath}`,
179 ...formatProtection(protection),
180 ...problems,
181 ...(status.current ? [] : [" Next: Run `t3 service install` to repair it."]),
182 ].join("\n");
184​
185const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
186 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
187 run: Effect.Effect<A, E, R>,
188) {
189 const logLevel = yield* GlobalFlag.LogLevel;
190 const config = yield* resolveCliAuthConfig(flags, logLevel);
191 return yield* run.pipe(Effect.provide(Layer.merge(layer(config), ServerConfig.layer(config))));
192});
193​
194const serviceReconcileFlags = {
195 ...projectLocationFlags,
196 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
197 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
198 Flag.withDefault(false),
199 ),
200};
201​
202const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
203 Command.withDescription(
204 "Install T3 Code as a background service for this user. `t3 up` also chooses how your other devices reach it.",
205 ),
206 Command.withHandler((flags) =>
207 runServiceCommand(
208 flags,
209 Effect.gen(function* () {
210 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
211 if (!result.changed) {
212 yield* Console.log(
213 `T3 Code service is already installed with t3@${packageJson.version} (${yield* resolveEntryPath}).`,
214 );
215 return;
216 }
217 yield* Console.log(formatServiceChange(result));
218 if (!result.previouslyInstalled) {
219 yield* Console.log("Run `t3 up` to choose how your other devices reach it.");
220 }
221 }),
222 ),
223 ),
224);
225​
226const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
227 Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
228 Command.unlisted,
229 Command.withHandler((flags) =>
230 runServiceCommand(
231 flags,
232 Effect.gen(function* () {
233 yield* Console.log(
234 "`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
235 );
236 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
237 if (!result.changed) {
238 yield* Console.log(
239 `T3 Code service is already using t3@${packageJson.version} (${yield* resolveEntryPath}).`,
240 );
241 return;
242 }
243 yield* Console.log(formatServiceChange(result));
244 }),
245 ),
246 ),
247);
248​
249const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(
250 Command.withDescription(
251 "Restart the background service. Picks up a version installed by `t3 update` that was not restarted at the time.",
252 ),
253 Command.withHandler((flags) =>
254 runServiceCommand(
255 flags,
256 Effect.gen(function* () {
257 const service = yield* BootService.BootService;
258 const status = yield* service.status;
259 const outcome = yield* service.restart;
260 const onVersion =
261 status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;
262 yield* Console.log(
263 outcome === "restarted"
264 ? `Restarted the T3 Code service${onVersion}.`
265 : outcome === "queued"
266 ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`
267 : "T3 Code service is not installed.",
268 );
269 }),
270 ),
271 ),
272);
273​
274const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
275 Command.withDescription("Stop and remove the T3 Code background service."),
276 Command.withHandler((flags) =>
277 runServiceCommand(
278 flags,
279 Effect.gen(function* () {
280 const service = yield* BootService.BootService;
281 const removed = yield* service.uninstall;
282 yield* Console.log(
283 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
284 );
285 }),
286 ),
287 ),
288);
289​
290const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
291 Command.withDescription("Show whether the T3 Code background service is installed."),
292 Command.withHandler((flags) =>
293 runServiceCommand(
294 flags,
295 Effect.gen(function* () {
296 const service = yield* BootService.BootService;
297 const path = yield* Path.Path;
298 const status = yield* service.status;
299 const protection =
300 status.installed && (yield* HostProcess.Platform) === "linux"
301 ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe(
302 Effect.provide(ProcessRunner.layer),
303 )
304 : undefined;
305 yield* Console.log(formatServiceStatus(status, packageJson.version, protection));
306 }),
307 ),
308 ),
309);
310​
311const formatDropIns = (dropIns: ReadonlyArray<ServiceProtection.DropIn>) =>
312 dropIns.map(
313 ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`,
314 );
315​
316const confirm = (yes: boolean, message: string) =>
317 yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false }));
318​
319const serviceProtectCommand = Command.make("protect", {
320 ...projectLocationFlags,
321 undo: Flag.Boolean("undo").pipe(
322 Flag.withDescription("Remove the protection this command set up."),
323 Flag.withDefault(false),
324 ),
325 yes: Flag.Boolean("yes").pipe(
326 Flag.withDescription("Answer yes to every question, including SSH and Tailscale."),
327 Flag.withDefault(false),
328 ),
329}).pipe(
330 Command.withDescription(
331 "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.",
332 ),
333 Command.withHandler((flags) =>
334 Effect.gen(function* () {
335 const unsupported = "Service protection needs Linux with systemd.";
336 if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported);
337 // Before resolving config, which creates T3 directories that root would then own.
338 if ((yield* HostProcess.UserId) === 0) {
339 return yield* Console.log(
340 "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.",
341 );
342 }
343 return yield* runServiceCommand(
344 flags,
345 Effect.gen(function* () {
346 const uid = yield* HostProcess.UserId;
347 const remote = yield* ServiceProtection.detectRemoteAccessUnits;
348 const { unitPath } = yield* (yield* BootService.BootService).status;
349 if (uid === undefined || remote === undefined || unitPath === "") {
350 return yield* Console.log(unsupported);
351 }
352 const userUnitDir = (yield* Path.Path).dirname(unitPath);
353​
354 if (flags.undo) {
355 const installed = yield* ServiceProtection.installedProtection(
356 ServiceProtection.protectionPlan({
357 uid,
358 userUnitDir,
359 remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS,
360 }),
361 );
362 if (installed === undefined) {
363 return yield* Console.log("T3 Code service protection is not set up.");
364 }
365 yield* Console.log(
366 [
367 "Removes:",
368 ...[...installed.system, ...installed.user, installed.managerDefaults].map(
369 ({ path, shared }) =>
370 ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`,
371 ),
372 ].join("\n"),
373 );
374 if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return;
375 yield* ServiceProtection.removeProtection(installed);
376 return yield* Console.log(
377 "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.",
378 );
379 }
380​
381 yield* Console.log(
382 [
383 "Keeps T3 Code running when agents fill this machine's memory:",
384 " - reserves memory for the T3 Code server, so the kernel takes memory from agents first",
385 " - makes the out-of-memory killer pick agents before the server",
386 "It adds systemd drop-in files and changes nothing else. Undo with `t3 service protect --undo`.",
387 ].join("\n"),
388 );
389 const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and ");
390 const protectRemote =
391 remote.length > 0 &&
392 (yield* confirm(
393 flags.yes,
394 `Also protect ${names} so you can still reach this machine under memory pressure?`,
395 ));
396 const plan = ServiceProtection.protectionPlan({
397 uid,
398 userUnitDir,
399 remoteAccessUnits: protectRemote ? remote : [],
400 });
401 yield* Console.log(
402 [
403 "Drop-ins it writes, as root through sudo:",
404 ...formatDropIns(plan.system),
405 "As you:",
406 ...formatDropIns([plan.managerDefaults, ...plan.user]),
407 ].join("\n"),
408 );
409 if (!(yield* confirm(flags.yes, "Apply these settings?"))) return;
410 yield* ServiceProtection.applyProtection(plan);
411 yield* Console.log(
412 "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`.",
413 );
414 }).pipe(Effect.provide(ProcessRunner.layer)),
415 );
416 }),
417 ),
418);
419​
420export const serviceCommand = Command.make("service").pipe(
421 Command.withDescription("Manage the T3 Code background service."),
422 Command.withSubcommands([
423 serviceInstallCommand,
424 serviceRestartCommand,
425 serviceUninstallCommand,
426 serviceStatusCommand,
427 serviceProtectCommand,
428 serviceUpdateCommand,
429 ]),
430);