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