Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2// @effect-diagnostics globalDate:off
3// @effect-diagnostics globalTimers:off
4// This file is shipped as a standalone bundle and copied to a stable path by
5// `t3 service update`. Keep runtime imports limited to Node built-ins.
6import * as NodeChildProcess from "node:child_process";
7import * as NodeCrypto from "node:crypto";
8import * as NodeFSP from "node:fs/promises";
9import * as NodePath from "node:path";
10
11import type {
12 PendingServiceUpdate,
13 ServiceLauncherChildMessage,
14 ServiceLauncherContext,
15 ServiceLauncherParentMessage,
16 ServiceState,
17 ServiceUpdateRecord,
18} from "./cloud/serviceProtocol.ts";
19import {
20 compareExactServiceVersions,
21 decodeServiceLauncherChildMessage,
22 isExactServiceVersion,
23 parseServiceState,
24 SERVICE_LAUNCHER_CONTEXT_ENV,
25 SERVICE_LAUNCHER_PROTOCOL,
26 SERVICE_STATE_FILE,
27} from "./cloud/serviceProtocol.ts";
28
29const HANDOFF_DELAY_MS = 2_000;
30const PREPARED_TIMEOUT_MS = 120_000;
31const TERMINATE_GRACE_MS = 5_000;
32
33type TerminalStatus = "committed" | "rolled-back" | "failed";
34type ChildRole = "active" | "trial";
35
36interface ManagedChild {
37 readonly version: string;
38 role: ChildRole;
39 readonly process: NodeChildProcess.ChildProcess;
40}
41
42const runtimePaths = (baseDir: string, version: string) => {
43 const versionDir = NodePath.join(baseDir, "runtime", "versions", version);
44 return {
45 versionDir,
46 entryPath: NodePath.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"),
47 sentinelPath: NodePath.join(versionDir, ".install-complete"),
48 };
49};
50
51export async function readServiceState(filePath: string): Promise<ServiceState> {
52 const contents = await NodeFSP.readFile(filePath, "utf8");
53 const state = parseServiceState(contents);
54 if (state === undefined) throw new Error("Service state is invalid or unsupported.");
55 return state;
56}
57
58/** Durable same-directory replacement used for every runtime state transition. */
59export async function writeServiceState(filePath: string, state: ServiceState): Promise<void> {
60 const directory = NodePath.dirname(filePath);
61 await NodeFSP.mkdir(directory, { recursive: true, mode: 0o700 });
62 const tempPath = NodePath.join(
63 directory,
64 `.${NodePath.basename(filePath)}.${process.pid}.${NodeCrypto.randomUUID()}`,
65 );
66 let handle: NodeFSP.FileHandle | undefined;
67 try {
68 handle = await NodeFSP.open(tempPath, "wx", 0o600);
69 await handle.writeFile(`${JSON.stringify(state, null, 2)}\n`, "utf8");
70 await handle.sync();
71 await handle.close();
72 handle = undefined;
73 await NodeFSP.rename(tempPath, filePath);
74 const directoryHandle = await NodeFSP.open(directory, "r");
75 try {
76 await directoryHandle.sync();
77 } finally {
78 await directoryHandle.close();
79 }
80 } finally {
81 await handle?.close().catch(() => undefined);
82 await NodeFSP.rm(tempPath, { force: true }).catch(() => undefined);
83 }
84}
85
86async function runtimeExists(baseDir: string, version: string): Promise<boolean> {
87 const paths = runtimePaths(baseDir, version);
88 try {
89 const [entry, sentinel] = await Promise.all([
90 NodeFSP.stat(paths.entryPath),
91 NodeFSP.readFile(paths.sentinelPath, "utf8"),
92 ]);
93 return entry.isFile() && sentinel.trim() === version;
94 } catch {
95 return false;
96 }
97}
98
99function terminalUpdate<S extends TerminalStatus>(input: {
100 readonly pending: PendingServiceUpdate;
101 readonly status: S;
102 readonly reason?: string;
103}): Exclude<ServiceUpdateRecord, PendingServiceUpdate> & { readonly status: S } {
104 return {
105 id: input.pending.id,
106 fromVersion: input.pending.fromVersion,
107 targetVersion: input.pending.targetVersion,
108 status: input.status,
109 ...(input.reason === undefined ? {} : { reason: input.reason }),
110 };
111}
112
113function sendMessage(
114 child: NodeChildProcess.ChildProcess,
115 message: ServiceLauncherParentMessage,
116): Promise<void> {
117 return new Promise((resolve, reject) => {
118 if (!child.connected || child.send === undefined) {
119 reject(new Error("service child IPC is disconnected."));
120 return;
121 }
122 child.send(message, (error) => (error === null ? resolve() : reject(error)));
123 });
124}
125
126function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
127 if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
128 return new Promise((resolve) => child.once("exit", () => resolve()));
129}
130
131async function terminateChild(
132 child: NodeChildProcess.ChildProcess,
133 signal: NodeJS.Signals = "SIGTERM",
134): Promise<void> {
135 if (child.exitCode !== null || child.signalCode !== null) return;
136 child.kill(signal);
137 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
138 try {
139 await waitForExit(child);
140 } finally {
141 clearTimeout(force);
142 }
143}
144
145export class Launcher {
146 readonly #baseDir: string;
147 readonly #statePath: string;
148 #state: ServiceState;
149 #child: ManagedChild | null = null;
150 #timer: NodeJS.Timeout | undefined;
151 #transitions: Promise<void> = Promise.resolve();
152 #stopping = false;
153 #done = false;
154 readonly #completion = Promise.withResolvers<void>();
155
156 constructor(baseDir: string, state: ServiceState) {
157 this.#baseDir = baseDir;
158 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
159 this.#state = state;
160 }
161
162 async run(): Promise<void> {
163 const onSigterm = () => void this.stop("SIGTERM");
164 const onSigint = () => void this.stop("SIGINT");
165 process.once("SIGTERM", onSigterm);
166 process.once("SIGINT", onSigint);
167 try {
168 this.#enqueue(() => this.#recover());
169 await this.#completion.promise;
170 } finally {
171 process.off("SIGTERM", onSigterm);
172 process.off("SIGINT", onSigint);
173 }
174 }
175
176 #enqueue(transition: () => Promise<void>): void {
177 this.#transitions = this.#transitions
178 .then(transition, transition)
179 .catch((cause: unknown) =>
180 this.#fatal(cause instanceof Error ? cause : new Error(String(cause))),
181 );
182 }
183
184 async #fatal(error: Error): Promise<void> {
185 if (this.#done) return;
186 this.#done = true;
187 this.#stopping = true;
188 this.#clearTimer();
189 const child = this.#child?.process;
190 this.#child = null;
191 if (child !== undefined) await terminateChild(child);
192 this.#completion.reject(error);
193 }
194
195 async stop(signal: NodeJS.Signals): Promise<void> {
196 if (this.#stopping) {
197 await this.#completion.promise.catch(() => undefined);
198 return;
199 }
200 this.#stopping = true;
201 this.#clearTimer();
202 this.#enqueue(async () => {
203 const child = this.#child?.process;
204 this.#child = null;
205 if (child !== undefined) await terminateChild(child, signal);
206 this.#done = true;
207 this.#completion.resolve();
208 });
209 await this.#completion.promise.catch(() => undefined);
210 }
211
212 #clearTimer(): void {
213 clearTimeout(this.#timer);
214 this.#timer = undefined;
215 }
216
217 async #recover(): Promise<void> {
218 const update = this.#state.update;
219 if (update?.status !== "pending") {
220 await this.#startChild(this.#state.activeVersion, "active", update);
221 return;
222 }
223 if (!(await runtimeExists(this.#baseDir, update.targetVersion))) {
224 await this.#returnToPrevious(update, "failed", "target-runtime-missing");
225 return;
226 }
227 await this.#startTrial(update);
228 }
229
230 async #startTrial(pending: PendingServiceUpdate): Promise<void> {
231 try {
232 await this.#startChild(pending.targetVersion, "trial", pending);
233 } catch {
234 await this.#returnToPrevious(pending, "failed", "candidate-start-failed");
235 }
236 }
237
238 async #startChild(version: string, role: ChildRole, update?: ServiceUpdateRecord): Promise<void> {
239 if (this.#stopping) return;
240 if (!(await runtimeExists(this.#baseDir, version))) {
241 throw new Error(`Selected t3@${version} runtime is missing or incomplete.`);
242 }
243 if (this.#stopping) return;
244 const paths = runtimePaths(this.#baseDir, version);
245 const context: ServiceLauncherContext = {
246 protocol: SERVICE_LAUNCHER_PROTOCOL,
247 childVersion: version,
248 ...(update === undefined ? {} : { update }),
249 };
250 const child = NodeChildProcess.spawn(process.execPath, [paths.entryPath, "serve"], {
251 env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
252 stdio: ["inherit", "inherit", "inherit", "ipc"],
253 });
254 await new Promise<void>((resolve, reject) => {
255 const onError = (error: Error) => reject(error);
256 child.once("error", onError);
257 child.once("spawn", () => {
258 child.removeListener("error", onError);
259 child.on("error", (error) => this.#enqueue(() => Promise.reject(error)));
260 resolve();
261 });
262 });
263 if (this.#stopping) {
264 await terminateChild(child);
265 return;
266 }
267
268 const managed: ManagedChild = {
269 version,
270 role,
271 process: child,
272 };
273 this.#child = managed;
274 child.on("message", (value) => {
275 const message = decodeServiceLauncherChildMessage(value);
276 if (message !== undefined) this.#enqueue(() => this.#handleMessage(managed, message));
277 });
278 child.once("exit", (code, signal) =>
279 this.#enqueue(() => this.#handleExit(managed, code, signal)),
280 );
281
282 if (role === "trial") {
283 this.#timer = setTimeout(
284 () => this.#enqueue(() => this.#handlePreparedTimeout(managed)),
285 PREPARED_TIMEOUT_MS,
286 );
287 }
288 }
289
290 async #handleMessage(child: ManagedChild, message: ServiceLauncherChildMessage): Promise<void> {
291 if (this.#child !== child || this.#stopping) return;
292 if (message.type === "request-update") {
293 await this.#handleUpdateRequest(child, message);
294 return;
295 }
296 await this.#handlePrepared(child, message.updateId);
297 }
298
299 async #handleUpdateRequest(
300 child: ManagedChild,
301 message: Extract<ServiceLauncherChildMessage, { readonly type: "request-update" }>,
302 ): Promise<void> {
303 const reject = (reason: string) =>
304 sendMessage(child.process, { type: "update-rejected", reason });
305 if (child.role !== "active") {
306 await reject("Only the active server can request an update.");
307 return;
308 }
309 if (child.version !== this.#state.activeVersion) {
310 await reject("The requesting server is not the selected active version.");
311 return;
312 }
313 if (this.#state.update?.status === "pending") {
314 await reject("Another server update is already pending.");
315 return;
316 }
317 if (!isExactServiceVersion(message.targetVersion)) {
318 await reject("The requested target is not an exact version.");
319 return;
320 }
321 if (compareExactServiceVersions(message.targetVersion, child.version) <= 0) {
322 await reject("Remote updates must select a newer server version.");
323 return;
324 }
325 if (!(await runtimeExists(this.#baseDir, message.targetVersion))) {
326 await reject("The requested target runtime is missing or incomplete.");
327 return;
328 }
329
330 const pending: PendingServiceUpdate = {
331 id: NodeCrypto.randomUUID(),
332 fromVersion: child.version,
333 targetVersion: message.targetVersion,
334 status: "pending",
335 };
336 const next: ServiceState = { ...this.#state, update: pending };
337 await writeServiceState(this.#statePath, next);
338 this.#state = next;
339 await sendMessage(child.process, { type: "update-accepted", updateId: pending.id });
340 this.#timer = setTimeout(() => this.#enqueue(() => this.#beginTrial(child)), HANDOFF_DELAY_MS);
341 }
342
343 async #beginTrial(child: ManagedChild): Promise<void> {
344 const pending = this.#state.update;
345 if (this.#child !== child || child.role !== "active" || pending?.status !== "pending") {
346 return;
347 }
348 this.#timer = undefined;
349 this.#child = null;
350 await terminateChild(child.process);
351 await this.#startTrial(pending);
352 }
353
354 async #handlePrepared(child: ManagedChild, updateId: string): Promise<void> {
355 const pending = this.#state.update;
356 if (
357 child.role !== "trial" ||
358 pending?.status !== "pending" ||
359 pending.id !== updateId ||
360 pending.targetVersion !== child.version
361 ) {
362 if (child.role === "trial" && pending?.status === "pending") {
363 await this.#returnToPrevious(pending, "rolled-back", "invalid-prepared", child);
364 return;
365 }
366 throw new Error("Trial child reported prepared for an unexpected update.");
367 }
368 this.#clearTimer();
369 const committed = terminalUpdate({ pending, status: "committed" });
370 const next: ServiceState = {
371 ...this.#state,
372 activeVersion: pending.targetVersion,
373 update: committed,
374 };
375 await writeServiceState(this.#statePath, next);
376 this.#state = next;
377 child.role = "active";
378 await sendMessage(child.process, { type: "committed", updateId: committed.id });
379 }
380
381 async #handlePreparedTimeout(child: ManagedChild): Promise<void> {
382 const pending = this.#state.update;
383 if (this.#child !== child || child.role !== "trial" || pending?.status !== "pending") {
384 return;
385 }
386 this.#timer = undefined;
387 await this.#returnToPrevious(pending, "rolled-back", "prepared-timeout", child);
388 }
389
390 async #handleExit(
391 child: ManagedChild,
392 code: number | null,
393 signal: NodeJS.Signals | null,
394 ): Promise<void> {
395 if (this.#child !== child || this.#stopping) return;
396 this.#child = null;
397 if (child.role === "trial") {
398 this.#clearTimer();
399 const pending = this.#state.update;
400 if (pending?.status !== "pending") {
401 throw new Error("Trial child exited without matching pending state.");
402 }
403 await this.#returnToPrevious(
404 pending,
405 "rolled-back",
406 `candidate-exited:${String(code ?? signal ?? "unknown")}`,
407 );
408 return;
409 }
410
411 this.#clearTimer();
412 const pending = this.#state.update;
413 if (pending?.status === "pending") {
414 await this.#startTrial(pending);
415 return;
416 }
417 throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`);
418 }
419
420 async #returnToPrevious(
421 pending: PendingServiceUpdate,
422 status: "rolled-back" | "failed",
423 reason: string,
424 child?: ManagedChild,
425 ): Promise<void> {
426 const outcome = terminalUpdate({ pending, status, reason });
427 const next: ServiceState = {
428 ...this.#state,
429 activeVersion: pending.fromVersion,
430 update: outcome,
431 };
432 await writeServiceState(this.#statePath, next);
433 this.#state = next;
434 if (child !== undefined) {
435 this.#child = null;
436 await terminateChild(child.process);
437 }
438 await this.#startChild(next.activeVersion, "active", outcome);
439 }
440}
441
442async function main(): Promise<void> {
443 const baseDir = process.env.T3CODE_HOME?.trim();
444 if (baseDir === undefined || baseDir === "") {
445 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
446 }
447 const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
448 const state = await readServiceState(statePath);
449 await new Launcher(baseDir, state).run();
450}
451
452if (import.meta.main) {
453 main().catch((cause: unknown) => {
454 const error = cause instanceof Error ? cause : new Error(String(cause));
455 process.stderr.write(`[service-launcher] ${error.message}\n`);
456 process.exitCode = 1;
457 });
458}