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

service.ts

446 lines17.4 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 path = yield* Path.Path;
282 const { baseDir } = yield* ServerConfig.ServerConfig;
283 // An unreadable unit stays removable; only a unit known to serve another home is kept.
284 const installedBaseDir = yield* service.status.pipe(
285 Effect.map((status) => status.installedBaseDir),
286 Effect.orElseSucceed(() => undefined),
287 );
288 if (
289 installedBaseDir !== undefined &&
290 path.resolve(installedBaseDir) !== path.resolve(baseDir)
291 ) {
292 yield* Console.log(
293 "The installed service runs another T3 home, so it was not removed. Pass its --base-dir.",
294 );
295 return;
296 }
297 const removed = yield* service.uninstall;
298 yield* Console.log(
299 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
300 );
301 }),
302 ),
303 ),
304);
305​
306const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
307 Command.withDescription("Show whether the T3 Code background service is installed."),
308 Command.withHandler((flags) =>
309 runServiceCommand(
310 flags,
311 Effect.gen(function* () {
312 const service = yield* BootService.BootService;
313 const path = yield* Path.Path;
314 const status = yield* service.status;
315 const protection =
316 status.installed && (yield* HostProcess.Platform) === "linux"
317 ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe(
318 Effect.provide(ProcessRunner.layer),
319 )
320 : undefined;
321 yield* Console.log(formatServiceStatus(status, packageJson.version, protection));
322 }),
323 ),
324 ),
325);
326​
327const formatDropIns = (dropIns: ReadonlyArray<ServiceProtection.DropIn>) =>
328 dropIns.map(
329 ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`,
330 );
331​
332const confirm = (yes: boolean, message: string) =>
333 yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false }));
334​
335const serviceProtectCommand = Command.make("protect", {
336 ...projectLocationFlags,
337 undo: Flag.Boolean("undo").pipe(
338 Flag.withDescription("Remove the protection this command set up."),
339 Flag.withDefault(false),
340 ),
341 yes: Flag.Boolean("yes").pipe(
342 Flag.withDescription("Answer yes to every question, including SSH and Tailscale."),
343 Flag.withDefault(false),
344 ),
345}).pipe(
346 Command.withDescription(
347 "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.",
348 ),
349 Command.withHandler((flags) =>
350 Effect.gen(function* () {
351 const unsupported = "Service protection needs Linux with systemd.";
352 if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported);
353 // Before resolving config, which creates T3 directories that root would then own.
354 if ((yield* HostProcess.UserId) === 0) {
355 return yield* Console.log(
356 "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.",
357 );
358 }
359 return yield* runServiceCommand(
360 flags,
361 Effect.gen(function* () {
362 const uid = yield* HostProcess.UserId;
363 const remote = yield* ServiceProtection.detectRemoteAccessUnits;
364 const { unitPath } = yield* (yield* BootService.BootService).status;
365 if (uid === undefined || remote === undefined || unitPath === "") {
366 return yield* Console.log(unsupported);
367 }
368 const userUnitDir = (yield* Path.Path).dirname(unitPath);
369​
370 if (flags.undo) {
371 const installed = yield* ServiceProtection.installedProtection(
372 ServiceProtection.protectionPlan({
373 uid,
374 userUnitDir,
375 remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS,
376 }),
377 );
378 if (installed === undefined) {
379 return yield* Console.log("T3 Code service protection is not set up.");
380 }
381 yield* Console.log(
382 [
383 "Removes:",
384 ...[...installed.system, ...installed.user, installed.managerDefaults].map(
385 ({ path, shared }) =>
386 ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`,
387 ),
388 ].join("\n"),
389 );
390 if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return;
391 yield* ServiceProtection.removeProtection(installed);
392 return yield* Console.log(
393 "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.",
394 );
395 }
396​
397 yield* Console.log(
398 [
399 "Keeps T3 Code running when agents fill this machine's memory:",
400 " - reserves memory for the T3 Code server, so the kernel takes memory from agents first",
401 " - makes the out-of-memory killer pick agents before the server",
402 "It adds systemd drop-in files and changes nothing else. Undo with `t3 service protect --undo`.",
403 ].join("\n"),
404 );
405 const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and ");
406 const protectRemote =
407 remote.length > 0 &&
408 (yield* confirm(
409 flags.yes,
410 `Also protect ${names} so you can still reach this machine under memory pressure?`,
411 ));
412 const plan = ServiceProtection.protectionPlan({
413 uid,
414 userUnitDir,
415 remoteAccessUnits: protectRemote ? remote : [],
416 });
417 yield* Console.log(
418 [
419 "Drop-ins it writes, as root through sudo:",
420 ...formatDropIns(plan.system),
421 "As you:",
422 ...formatDropIns([plan.managerDefaults, ...plan.user]),
423 ].join("\n"),
424 );
425 if (!(yield* confirm(flags.yes, "Apply these settings?"))) return;
426 yield* ServiceProtection.applyProtection(plan);
427 yield* Console.log(
428 "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`.",
429 );
430 }).pipe(Effect.provide(ProcessRunner.layer)),
431 );
432 }),
433 ),
434);
435​
436export const serviceCommand = Command.make("service").pipe(
437 Command.withDescription("Manage the T3 Code background service."),
438 Command.withSubcommands([
439 serviceInstallCommand,
440 serviceRestartCommand,
441 serviceUninstallCommand,
442 serviceStatusCommand,
443 serviceProtectCommand,
444 serviceUpdateCommand,
445 ]),
446);