Open History to see the last commit
1import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12
13import * as ProcessRunner from "../processRunner.ts";
14import {
15 ensurePinnedRuntimeInstalled,
16 pinnedRuntimePaths,
17 PinnedRuntimeInstallError,
18} from "./pinnedRuntime.ts";
19import {
20 SERVICE_LAUNCHER_FILE,
21 SERVICE_LAUNCHER_PROTOCOL,
22 SERVICE_STATE_FILE,
23 parseServiceState,
24 serviceStateHasPendingUpdate,
25 type ServiceState,
26} from "./serviceProtocol.ts";
27
28const BOOT_SERVICE_NAME = "t3code";
29export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
30export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
31
32/** systemd expands `%` specifiers, including in unquoted append-log paths. */
33export function escapeSystemdSpecifiers(value: string): string {
34 return value.replaceAll("%", "%%");
35}
36
37export function quoteSystemdValue(value: string): string {
38 const escaped = escapeSystemdSpecifiers(value);
39 return /[\s"'\\]/.test(escaped)
40 ? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`
41 : escaped;
42}
43
44export interface BootServicePlan {
45 readonly nodePath: string;
46 readonly launcherPath: string;
47 readonly baseDir: string;
48 readonly logPath: string;
49 readonly unitPath: string;
50}
51
52/** Pure renderer: service units cannot rely on the user's shell or PATH. */
53export function renderBootServiceUnit(plan: BootServicePlan): string {
54 // The user manager has no reliable network-online target; server networking retries itself.
55 return [
56 "[Unit]",
57 "Description=T3 Code server",
58 "StartLimitIntervalSec=300",
59 "StartLimitBurst=5",
60 "",
61 "[Service]",
62 "Type=simple",
63 "WorkingDirectory=%h",
64 `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
65 `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
66 `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
67 // Let the launcher mark an explicit stop before it signals the server.
68 // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
69 "KillMode=mixed",
70 // Agent tool calls run as children of the server, so they share this cgroup.
71 // With the systemd default of OOMPolicy=stop, the kernel killing one greedy
72 // child stops the whole unit: the server, every live agent, and the user's
73 // connection. Keep running and let Restart=always cover the main process.
74 "OOMPolicy=continue",
75 "Restart=always",
76 "RestartSec=5",
77 `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
78 `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,
79 "",
80 "[Install]",
81 "WantedBy=default.target",
82 "",
83 ].join("\n");
84}
85
86export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
87 "BootServiceUnsupportedError",
88 { platform: Schema.String },
89) {
90 override get message(): string {
91 return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
92 }
93}
94
95export class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(
96 "BootServiceCommandError",
97 {
98 step: Schema.String,
99 exitCode: Schema.optional(Schema.Number),
100 stdoutLength: Schema.optional(Schema.Number),
101 stderrLength: Schema.optional(Schema.Number),
102 cause: Schema.optional(Schema.Defect()),
103 },
104) {
105 override get message(): string {
106 return this.exitCode === undefined
107 ? `Background setup failed while ${this.step}.`
108 : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
109 }
110}
111
112export class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(
113 "BootServiceInstallError",
114 { cause: Schema.Defect() },
115) {
116 override get message(): string {
117 return "Could not set up the T3 Code background service.";
118 }
119}
120
121export class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(
122 "BootServiceUpdatePendingError",
123 {},
124) {
125 override get message(): string {
126 return "A remote server update is still pending. Wait for it to finish, then retry.";
127 }
128}
129
130export type BootServiceError =
131 | BootServiceUnsupportedError
132 | BootServiceCommandError
133 | BootServiceInstallError
134 | BootServiceUpdatePendingError;
135
136export interface BootServiceStatus {
137 readonly supported: boolean;
138 readonly installed: boolean;
139 readonly current: boolean;
140 readonly unitPath: string;
141 readonly logPath: string;
142}
143
144export class BootService extends Context.Service<
145 BootService,
146 {
147 readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
148 readonly uninstall: Effect.Effect<boolean, BootServiceError>;
149 readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;
150 }
151>()("t3/cloud/bootService") {}
152
153export interface BootServiceHost {
154 readonly execPath: string;
155 readonly launcherSourcePath?: string;
156}
157
158export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
159 readonly baseDir: string;
160 readonly logsDir: string;
161 readonly cliVersion: string;
162 readonly host?: BootServiceHost;
163}) {
164 const hostExecPath = yield* HostProcessExecutablePath;
165 const platform = yield* HostProcessPlatform;
166 const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
167 const fs = yield* FileSystem.FileSystem;
168 const path = yield* Path.Path;
169 const runner = yield* ProcessRunner.ProcessRunner;
170 const host = input.host ?? { execPath: hostExecPath };
171
172 const unitDir = path.join(homeDir, ".config", "systemd", "user");
173 const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
174 const logPath = path.join(input.logsDir, "boot-service.log");
175 const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
176 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
177 const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
178 const launcherSourcePath =
179 host.launcherSourcePath ??
180 path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);
181 const writeDurably = (filePath: string, contents: string) =>
182 Effect.scoped(
183 Effect.gen(function* () {
184 const directory = path.dirname(filePath);
185 yield* fs.makeDirectory(directory, { recursive: true });
186 const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
187 yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
188 yield* (yield* fs.open(tempPath, { flag: "r" })).sync;
189 yield* fs.rename(tempPath, filePath);
190 yield* (yield* fs.open(directory, { flag: "r" })).sync;
191 }),
192 ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
193 const plan: BootServicePlan = {
194 nodePath: host.execPath,
195 launcherPath,
196 baseDir: input.baseDir,
197 logPath,
198 unitPath,
199 };
200
201 const requireSystemdLinux = Effect.gen(function* () {
202 if (platform !== "linux" || homeDir === "") {
203 return yield* new BootServiceUnsupportedError({ platform });
204 }
205 });
206
207 const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
208 step: string,
209 command: string,
210 args: ReadonlyArray<string>,
211 options?: { readonly timeout?: Duration.Input },
212 ) {
213 return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
214 Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
215 Effect.filterOrFail(
216 (result) => result.code === 0,
217 (result) =>
218 new BootServiceCommandError({
219 step,
220 exitCode: Number(result.code),
221 stdoutLength: result.stdout.length,
222 stderrLength: result.stderr.length,
223 }),
224 ),
225 Effect.tapError((error) =>
226 DateTime.now.pipe(
227 Effect.flatMap((now) =>
228 fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, {
229 flag: "a",
230 }),
231 ),
232 Effect.ignore,
233 ),
234 ),
235 );
236 });
237
238 const install: BootService["Service"]["install"] = Effect.gen(function* () {
239 yield* requireSystemdLinux;
240 yield* fs
241 .makeDirectory(input.logsDir, { recursive: true })
242 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
243
244 // Prepare every immutable artifact before stopping the installed unit.
245 yield* ensurePinnedRuntimeInstalled({
246 baseDir: input.baseDir,
247 version: input.cliVersion,
248 fs,
249 path,
250 runner,
251 validate: (runtime) =>
252 runner
253 .run({
254 command: host.execPath,
255 args: [runtime.entryPath, "--version"],
256 timeout: Duration.seconds(30),
257 })
258 .pipe(
259 Effect.mapError(
260 (cause) =>
261 new PinnedRuntimeInstallError({
262 step: "verifying the pinned t3 runtime",
263 cause,
264 }),
265 ),
266 Effect.flatMap((result) => {
267 const reportedVersion = /\bv(\S+)\s*$/.exec(result.stdout)?.[1];
268 return result.code === 0 && reportedVersion === input.cliVersion
269 ? Effect.void
270 : Effect.fail(
271 new PinnedRuntimeInstallError({
272 step: "verifying the pinned t3 runtime",
273 exitCode: Number(result.code),
274 stdoutLength: result.stdout.length,
275 stderrLength: result.stderr.length,
276 }),
277 );
278 }),
279 ),
280 }).pipe(
281 Effect.mapError((error) =>
282 error._tag === "PinnedRuntimeInstallError"
283 ? new BootServiceCommandError({
284 step: error.step,
285 exitCode: error.exitCode,
286 stdoutLength: error.stdoutLength,
287 stderrLength: error.stderrLength,
288 cause: error,
289 })
290 : new BootServiceInstallError({ cause: error }),
291 ),
292 );
293 const launcherSource = yield* fs
294 .readFileString(launcherSourcePath)
295 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
296
297 const installed = yield* fs
298 .exists(unitPath)
299 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
300 if (installed) {
301 yield* runStep("stopping the installed service", "systemctl", [
302 "--user",
303 "stop",
304 BOOT_SERVICE_UNIT_FILE,
305 ]);
306 }
307
308 yield* Effect.gen(function* () {
309 if (installed) {
310 const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);
311 if (
312 Option.isSome(previousStateText) &&
313 serviceStateHasPendingUpdate(previousStateText.value)
314 ) {
315 return yield* new BootServiceUpdatePendingError();
316 }
317 }
318 yield* fs
319 .makeDirectory(unitDir, { recursive: true })
320 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
321 yield* writeDurably(launcherPath, launcherSource);
322 yield* writeDurably(
323 statePath,
324 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.
325 `${JSON.stringify(
326 {
327 protocol: SERVICE_LAUNCHER_PROTOCOL,
328 activeVersion: input.cliVersion,
329 } satisfies ServiceState,
330 null,
331 2,
332 )}\n`,
333 );
334 yield* writeDurably(unitPath, renderBootServiceUnit(plan));
335
336 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
337 yield* runStep("enabling the service", "systemctl", [
338 "--user",
339 "enable",
340 BOOT_SERVICE_UNIT_FILE,
341 ]);
342 yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
343 // Start last. No administrative state write occurs after this succeeds.
344 yield* runStep("starting the service", "systemctl", [
345 "--user",
346 "restart",
347 BOOT_SERVICE_UNIT_FILE,
348 ]);
349 }).pipe(
350 Effect.tapError(() =>
351 installed
352 ? runStep("restarting the service after a failed update", "systemctl", [
353 "--user",
354 "restart",
355 BOOT_SERVICE_UNIT_FILE,
356 ]).pipe(Effect.ignore)
357 : Effect.void,
358 ),
359 );
360 return plan;
361 }).pipe(Effect.withSpan("cloud.boot_service.install"));
362
363 const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
364 yield* requireSystemdLinux;
365 if (
366 !(yield* fs
367 .exists(unitPath)
368 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
369 )
370 return false;
371 yield* runStep("stopping the service", "systemctl", [
372 "--user",
373 "disable",
374 "--now",
375 BOOT_SERVICE_UNIT_FILE,
376 ]);
377 yield* fs
378 .remove(unitPath)
379 .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
380 yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
381 return true;
382 }).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
383
384 const status: BootService["Service"]["status"] = Effect.gen(function* () {
385 if (platform !== "linux" || homeDir === "") {
386 return { supported: false, installed: false, current: false, unitPath, logPath };
387 }
388 if (!(yield* fs.exists(unitPath))) {
389 return { supported: true, installed: false, current: false, unitPath, logPath };
390 }
391 const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =
392 yield* Effect.all([
393 fs.readFileString(unitPath),
394 fs.exists(launcherPath),
395 fs.exists(runtimePaths.entryPath),
396 fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
397 fs.readFileString(statePath).pipe(Effect.option),
398 ]);
399 const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;
400 return {
401 supported: true,
402 installed: true,
403 current:
404 unit === renderBootServiceUnit(plan) &&
405 launcherExists &&
406 runtimeEntryExists &&
407 Option.isSome(runtimeSentinel) &&
408 runtimeSentinel.value.trim() === input.cliVersion &&
409 state?.activeVersion === input.cliVersion &&
410 state?.update?.status !== "pending",
411 unitPath,
412 logPath,
413 };
414 }).pipe(
415 Effect.mapError((cause) => new BootServiceInstallError({ cause })),
416 Effect.withSpan("cloud.boot_service.status"),
417 );
418
419 return BootService.of({ install, uninstall, status });
420});
421
422export const layer = (input: {
423 readonly baseDir: string;
424 readonly logsDir: string;
425 readonly cliVersion: string;
426 readonly host?: BootServiceHost;
427}) => Layer.effect(BootService, make(input));