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

service.ts

501 lines20.2 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, resolveHostCliHint } 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 source = contents.split("\n");
51 const lines: string[] = [];
52 for (let index = 0, offset = 0; index < source.length;) {
53 const line = source[index]!;
54 const match = SERVICE_ENV_KEY.exec(line);
55 let end = index + 1;
56 if (match !== null) {
57 // util.parseEnv lets a quoted value run to its closing quote across lines,
58 // skipping only spaces, tabs and CRs before the opening quote.
59 const rest = line.slice(match[0].length).replace(/^[ \t\r]+/u, "");
60 const quote = rest[0];
61 if ((quote === '"' || quote === "'" || quote === "`") && !rest.includes(quote, 1)) {
62 const closing = contents.indexOf(quote, offset + line.length);
63 if (closing !== -1) {
64 end += contents.slice(offset + line.length, closing).split("\n").length - 1;
65 }
66 }
67 }
68 const span = source.slice(index, end);
69 offset += span.reduce((length, part) => length + part.length + 1, 0);
70 index = end;
71 const key = match?.[1];
72 if (key === undefined || !Object.hasOwn(entries, key)) {
73 lines.push(span.join("\n"));
74 continue;
75 }
76 const value = entries[key];
77 if (value === undefined || written.has(key)) continue;
78 written.add(key);
79 lines.push(`${key}=${value}`);
80 }
81 while (lines.at(-1) === "") lines.pop();
82 for (const [key, value] of Object.entries(entries)) {
83 if (value !== undefined && !written.has(key)) lines.push(`${key}=${value}`);
84 }
85 return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
86};
87​
88/** `service.env` under `baseDir`, parsed as the service launcher parses it. */
89export const readServiceEnv = Effect.fn("cli.service.read_env")(function* (baseDir: string) {
90 const fs = yield* FileSystem.FileSystem;
91 const path = (yield* Path.Path).join(baseDir, SERVICE_ENV_FILE);
92 const contents = (yield* fs.exists(path)) ? yield* fs.readFileString(path) : "";
93 const entries = Object.entries(NodeUtil.parseEnv(contents)).flatMap(([key, value]) =>
94 value === undefined ? [] : [[key, value] as const],
95 );
96 return { path, contents, entries: Object.fromEntries(entries) };
97});
98​
99export const writeServiceEnv = Effect.fn("cli.service.write_env")(function* (
100 baseDir: string,
101 entries: Readonly<Record<string, string | undefined>>,
102) {
103 const fs = yield* FileSystem.FileSystem;
104 const current = yield* readServiceEnv(baseDir);
105 const next = upsertServiceEnv(current.contents, entries);
106 if (next === current.contents) return;
107 yield* fs.makeDirectory(baseDir, { recursive: true });
108 yield* fs.writeFileString(current.path, next);
109});
110​
111export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
112 readonly allowDowngrade?: boolean;
113 readonly start?: boolean;
114}) {
115 const { baseDir } = yield* ServerConfig.ServerConfig;
116 const service = yield* BootService.BootService;
117 const status = yield* service.status;
118 // Before the downgrade check, which reads this home's state, not the service's.
119 if (status.otherBaseDir !== undefined) {
120 return yield* new BootService.BootServiceOtherBaseDirError({
121 installedBaseDir: status.otherBaseDir,
122 baseDir,
123 });
124 }
125 if (status.installed && status.current) {
126 return { changed: false, status } satisfies ServiceReconcileResult;
127 }
128 if (status.supported && !status.installed) {
129 // A new service listens on this machine only, until `t3 up` opens the local network.
130 const { entries } = yield* readServiceEnv(baseDir);
131 if (entries.T3CODE_LAN === undefined && entries.T3CODE_HOST === undefined) {
132 yield* writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
133 }
134 }
135 if (
136 status.installedVersion !== undefined &&
137 options?.allowDowngrade !== true &&
138 compareExactServiceVersions(packageJson.version, status.installedVersion) < 0
139 ) {
140 return yield* new BootService.BootServiceDowngradeRefusedError({
141 installedVersion: status.installedVersion,
142 targetVersion: packageJson.version,
143 });
144 }
145 const plan = yield* service.install(options);
146 return {
147 changed: true,
148 previouslyInstalled: status.installed,
149 plan,
150 } satisfies ServiceReconcileResult;
151});
152​
153export function formatServiceChange(
154 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
155): string {
156 if (result.plan.handedOff === true) {
157 return `Service update to t3@${packageJson.version} queued. This session will disconnect.\nLog: ${result.plan.logPath}`;
158 }
159 return `Service ${result.previouslyInstalled ? "updated" : "installed"} · t3@${packageJson.version}\nLog: ${result.plan.logPath}`;
161​
162const MEMORY_CONTROLLER_DISABLED =
163 "the kernel's memory cgroup controller is disabled. Add `cgroup_enable=memory` to the kernel command line and reboot.";
164​
165function formatProtection(
166 protection: ServiceProtection.ServiceProtectionState | undefined,
167): ReadonlyArray<string> {
168 if (protection === undefined) return [];
169 return [
170 !protection.memoryControllerAvailable
171 ? ` Memory protection: unavailable, ${MEMORY_CONTROLLER_DISABLED}`
172 : protection.unprotected === undefined
173 ? ` Memory protection: on${protection.setByProtect ? " (t3 service protect)" : ""}`
174 : ` Memory protection: off, ${protection.unprotected} grants none. Run \`t3 service protect\`.`,
175 ...(protection.oomScoreAdj === undefined ? [] : [` OOM score: ${protection.oomScoreAdj}`]),
176 ];
178​
179function formatServiceStatus(
180 status: BootService.BootServiceStatus,
181 cliVersion: string,
182 commands: { readonly install: string; readonly restart: string; readonly update: string },
183 protection?: ServiceProtection.ServiceProtectionState,
184): string {
185 if (!status.supported) {
186 return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd, Windows with Task Scheduler";
187 }
188 if (!status.installed) {
189 return `T3 Code service\n Status: not installed\n Next: Run \`${commands.install}\`.`;
190 }
191 if (status.otherBaseDir !== undefined) {
192 return [
193 "T3 Code service",
194 " Status: installed for another T3 home",
195 ` Base dir: ${status.otherBaseDir}`,
196 ` Next: Pass \`${BootService.formatBootServiceBaseDirOption(status.otherBaseDir)}\` to manage it.`,
197 ].join("\n");
198 }
199 const installedVersion = status.installedVersion ?? cliVersion;
200 const problems = (status.problems ?? []).map(
201 (problem) => ` [${problem}] ${BootService.formatBootServiceProblem(problem, commands)}`,
202 );
203 if (
204 !status.current &&
205 status.installedVersion !== undefined &&
206 compareExactServiceVersions(status.installedVersion, cliVersion) > 0
207 ) {
208 return [
209 "T3 Code service",
210 ` Status: installed · t3@${installedVersion} (newer than this t3@${cliVersion} CLI)`,
211 ` Unit: ${status.unitPath}`,
212 ` Logs: ${status.logPath}`,
213 ...formatProtection(protection),
214 ...problems,
215 ` Next: Run \`${commands.update}\` to match it, or pass \`--allow-downgrade\` to \`${commands.install}\` explicitly.`,
216 ].join("\n");
217 }
218 return [
219 "T3 Code service",
220 ` Status: ${status.current ? `installed · t3@${installedVersion}` : "needs an update or repair"}`,
221 ` Unit: ${status.unitPath}`,
222 ` Logs: ${status.logPath}`,
223 ...formatProtection(protection),
224 ...problems,
225 ...(status.current ? [] : [` Next: Run \`${commands.install}\` to repair it.`]),
226 ].join("\n");
228​
229const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
230 flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0]["baseDir"] },
231 run: Effect.Effect<A, E, R>,
232) {
233 const logLevel = yield* GlobalFlag.LogLevel;
234 const config = yield* resolveCliAuthConfig(flags, logLevel);
235 return yield* run.pipe(Effect.provide(Layer.merge(layer(config), ServerConfig.layer(config))));
236});
237​
238const serviceReconcileFlags = {
239 ...projectLocationFlags,
240 allowDowngrade: Flag.Boolean("allow-downgrade").pipe(
241 Flag.withDescription("Allow replacing a newer installed service with this older CLI version."),
242 Flag.withDefault(false),
243 ),
244};
245​
246const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
247 Command.withDescription(
248 "Install T3 Code as a background service for this user. `t3 up` also chooses how your other devices reach it.",
249 ),
250 Command.withHandler((flags) =>
251 runServiceCommand(
252 flags,
253 Effect.gen(function* () {
254 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
255 if (!result.changed) {
256 yield* Console.log(
257 `T3 Code service is already installed with t3@${packageJson.version} (${yield* resolveEntryPath}).`,
258 );
259 return;
260 }
261 yield* Console.log(formatServiceChange(result));
262 if (!result.previouslyInstalled) {
263 const upCommand = yield* resolveHostCliHint("up", flags.baseDir);
264 yield* Console.log(`Run \`${upCommand}\` to choose how your other devices reach it.`);
265 }
266 }),
267 ),
268 ),
269);
270​
271const serviceUpdateCommand = Command.make("update", serviceReconcileFlags).pipe(
272 Command.withDescription("Deprecated. Run `t3 update` to move to a newer release."),
273 Command.unlisted,
274 Command.withHandler((flags) =>
275 runServiceCommand(
276 flags,
277 Effect.gen(function* () {
278 yield* Console.log(
279 "`t3 service update` is deprecated: run `t3 update` to move to a newer release, or `t3 service install` to repair the service. Repairing now.",
280 );
281 const result = yield* reconcileService({ allowDowngrade: flags.allowDowngrade });
282 if (!result.changed) {
283 yield* Console.log(
284 `T3 Code service is already using t3@${packageJson.version} (${yield* resolveEntryPath}).`,
285 );
286 return;
287 }
288 yield* Console.log(formatServiceChange(result));
289 }),
290 ),
291 ),
292);
293​
294const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(
295 Command.withDescription(
296 "Restart the background service. Picks up a version installed by `t3 update` that was not restarted at the time.",
297 ),
298 Command.withHandler((flags) =>
299 runServiceCommand(
300 flags,
301 Effect.gen(function* () {
302 const service = yield* BootService.BootService;
303 const status = yield* service.status;
304 const outcome = yield* service.restart;
305 const onVersion =
306 status.installedVersion === undefined ? "" : ` on t3@${status.installedVersion}`;
307 yield* Console.log(
308 outcome === "restarted"
309 ? `Restarted the T3 Code service${onVersion}.`
310 : outcome === "queued"
311 ? `Queued a restart of the T3 Code service${onVersion}. This session runs inside the service and disconnects when it goes down.\nLogs: ${status.logPath}`
312 : status.otherBaseDir !== undefined
313 ? `The T3 Code service serves ${status.otherBaseDir}, so it was not restarted. Pass \`${BootService.formatBootServiceBaseDirOption(status.otherBaseDir)}\` to restart it.`
314 : "T3 Code service is not installed.",
315 );
316 }),
317 ),
318 ),
319);
320​
321const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(
322 Command.withDescription("Stop and remove the T3 Code background service."),
323 Command.withHandler((flags) =>
324 runServiceCommand(
325 flags,
326 Effect.gen(function* () {
327 const service = yield* BootService.BootService;
328 // An unreadable unit stays removable; only a unit known to serve another home is kept.
329 const otherBaseDir = yield* service.status.pipe(
330 Effect.map((status) => status.otherBaseDir),
331 Effect.orElseSucceed(() => undefined),
332 );
333 if (otherBaseDir !== undefined) {
334 yield* Console.log(
335 `The T3 Code service serves ${otherBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(otherBaseDir)}\` to remove it.`,
336 );
337 return;
338 }
339 const removed = yield* service.uninstall;
340 yield* Console.log(
341 removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",
342 );
343 }),
344 ),
345 ),
346);
347​
348const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(
349 Command.withDescription("Show whether the T3 Code background service is installed."),
350 Command.withHandler((flags) =>
351 runServiceCommand(
352 flags,
353 Effect.gen(function* () {
354 const service = yield* BootService.BootService;
355 const path = yield* Path.Path;
356 const status = yield* service.status;
357 const protection =
358 status.installed && (yield* HostProcess.Platform) === "linux"
359 ? yield* ServiceProtection.readProtection(path.dirname(status.unitPath)).pipe(
360 Effect.provide(ProcessRunner.layer),
361 )
362 : undefined;
363 const commands = {
364 install: yield* resolveHostCliHint("service install", flags.baseDir),
365 restart: yield* resolveHostCliHint("service restart", flags.baseDir),
366 update: yield* resolveHostCliHint("update", flags.baseDir, [
367 status.installedVersion ?? packageJson.version,
368 ]),
369 };
370 yield* Console.log(formatServiceStatus(status, packageJson.version, commands, protection));
371 }),
372 ),
373 ),
374);
375​
376const formatDropIns = (dropIns: ReadonlyArray<ServiceProtection.DropIn>) =>
377 dropIns.map(
378 ({ path, contents }) => ` ${path}: ${contents.trimEnd().split("\n").slice(1).join(" ")}`,
379 );
380​
381const confirm = (yes: boolean, message: string) =>
382 yes ? Effect.succeed(true) : Prompt.run(Prompt.Confirm({ message, initial: false }));
383​
384const serviceProtectCommand = Command.make("protect", {
385 ...projectLocationFlags,
386 undo: Flag.Boolean("undo").pipe(
387 Flag.withDescription("Remove the protection this command set up."),
388 Flag.withDefault(false),
389 ),
390 yes: Flag.Boolean("yes").pipe(
391 Flag.withDescription("Answer yes to every question, including SSH and Tailscale."),
392 Flag.withDefault(false),
393 ),
394}).pipe(
395 Command.withDescription(
396 "Protect the T3 Code server from agents under memory pressure (Linux with systemd). Asks for sudo.",
397 ),
398 Command.withHandler((flags) =>
399 Effect.gen(function* () {
400 const unsupported = "Service protection needs Linux with systemd.";
401 if ((yield* HostProcess.Platform) !== "linux") return yield* Console.log(unsupported);
402 // Before resolving config, which creates T3 directories that root would then own.
403 if ((yield* HostProcess.UserId) === 0) {
404 return yield* Console.log(
405 "Run `t3 service protect` as the user that runs T3 Code, without sudo. It asks for sudo when it needs root.",
406 );
407 }
408 return yield* runServiceCommand(
409 flags,
410 Effect.gen(function* () {
411 const uid = yield* HostProcess.UserId;
412 const remote = yield* ServiceProtection.detectRemoteAccessUnits;
413 const { unitPath } = yield* (yield* BootService.BootService).status;
414 if (uid === undefined || remote === undefined || unitPath === "") {
415 return yield* Console.log(unsupported);
416 }
417 const userUnitDir = (yield* Path.Path).dirname(unitPath);
418​
419 if (flags.undo) {
420 const installed = yield* ServiceProtection.installedProtection(
421 ServiceProtection.protectionPlan({
422 uid,
423 userUnitDir,
424 remoteAccessUnits: ServiceProtection.REMOTE_ACCESS_UNITS,
425 }),
426 );
427 if (installed === undefined) {
428 return yield* Console.log("T3 Code service protection is not set up.");
429 }
430 yield* Console.log(
431 [
432 "Removes:",
433 ...[...installed.system, ...installed.user, installed.managerDefaults].map(
434 ({ path, shared }) =>
435 ` ${path}${shared === true ? " (kept while another user is protected)" : ""}`,
436 ),
437 ].join("\n"),
438 );
439 if (!(yield* confirm(flags.yes, "Remove T3 Code service protection?"))) return;
440 yield* ServiceProtection.removeProtection(installed);
441 return yield* Console.log(
442 "Removed T3 Code service protection. The server's OOM score returns to normal after `t3 service restart`.",
443 );
444 }
445​
446 yield* Console.log(
447 [
448 "Keeps T3 Code running when agents fill this machine's memory:",
449 " - reserves memory for the T3 Code server, so the kernel takes memory from agents first",
450 " - makes the out-of-memory killer pick agents before the server",
451 "It adds systemd drop-in files and changes nothing else. Undo with `t3 service protect --undo`.",
452 ].join("\n"),
453 );
454 const names = remote.map((unit) => unit.replace(/\.service$/, "")).join(" and ");
455 const protectRemote =
456 remote.length > 0 &&
457 (yield* confirm(
458 flags.yes,
459 `Also protect ${names} so you can still reach this machine under memory pressure?`,
460 ));
461 const plan = ServiceProtection.protectionPlan({
462 uid,
463 userUnitDir,
464 remoteAccessUnits: protectRemote ? remote : [],
465 });
466 yield* Console.log(
467 [
468 "Drop-ins it writes, as root through sudo:",
469 ...formatDropIns(plan.system),
470 "As you:",
471 ...formatDropIns([plan.managerDefaults, ...plan.user]),
472 ].join("\n"),
473 );
474 const memoryController = yield* ServiceProtection.memoryControllerAvailable;
475 if (!memoryController) {
476 yield* Console.log(`Only the OOM scores can apply: ${MEMORY_CONTROLLER_DISABLED}`);
477 }
478 if (!(yield* confirm(flags.yes, "Apply these settings?"))) return;
479 yield* ServiceProtection.applyProtection(plan);
480 yield* Console.log(
481 memoryController
482 ? "Protected T3 Code. Memory protection applies now; the server takes its OOM score after `t3 service restart`. Undo with `t3 service protect --undo`."
483 : "Protected T3 Code's OOM score; the server takes it after `t3 service restart`. Memory protection applies once the kernel's memory controller is enabled. Undo with `t3 service protect --undo`.",
484 );
485 }).pipe(Effect.provide(ProcessRunner.layer)),
486 );
487 }),
488 ),
489);
490​
491export const serviceCommand = Command.make("service").pipe(
492 Command.withDescription("Manage the T3 Code background service."),
493 Command.withSubcommands([
494 serviceInstallCommand,
495 serviceRestartCommand,
496 serviceUninstallCommand,
497 serviceStatusCommand,
498 serviceProtectCommand,
499 serviceUpdateCommand,
500 ]),
501);