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