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

bootService.ts

400 lines13.6 KB

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