Open History to see the last commit
1import type { ServerSelfUpdateOutcome } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Context from "effect/Context";
4import * as Cause from "effect/Cause";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14import packageJson from "../../package.json" with { type: "json" };
15import {
16 generatedWindowsShimTarget,
17 isVersionExecutable,
18 pinnedRuntimePaths,
19 pinnedRuntimeVersionsDir,
20 readPosixLauncherTarget,
21 writePosixLauncher,
22} from "./pinnedRuntime.ts";
23import {
24 decodeServiceLauncherContext,
25 decodeServiceLauncherParentMessage,
26 SERVICE_LAUNCHER_CONTEXT_ENV,
27 type ServiceLauncherChildMessage,
28 type ServiceLauncherParentMessage,
29 type SupportedLauncherProtocol,
30} from "./serviceProtocol.ts";
31import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts";
32
33export class ServiceLauncherClientError extends Schema.TaggedError<ServiceLauncherClientError>()(
34 "ServiceLauncherClientError",
35 {
36 operation: Schema.Literals([
37 "decode-context",
38 "version-mismatch",
39 "unmanaged",
40 "send",
41 "disconnect",
42 "timeout",
43 ]),
44 cause: Schema.optional(Schema.Defect()),
45 },
46) {
47 override get message(): string {
48 switch (this.operation) {
49 case "decode-context":
50 return "The service launcher supplied invalid startup context.";
51 case "version-mismatch":
52 return "The service launcher started a different t3 version.";
53 case "unmanaged":
54 return "This server is not managed by the launcher.";
55 case "send":
56 return "Could not send a request to the service launcher.";
57 case "disconnect":
58 return "The service launcher disconnected before acknowledging the request.";
59 case "timeout":
60 return "The service launcher did not respond within 30 seconds.";
61 }
62 }
63}
64
65export class ServiceLauncherRejectedError extends Schema.TaggedError<ServiceLauncherRejectedError>()(
66 "ServiceLauncherRejectedError",
67 {
68 targetVersion: Schema.String,
69 reason: Schema.String,
70 },
71) {
72 override get message(): string {
73 return this.reason;
74 }
75}
76
77interface ServiceLauncherProcess {
78 readonly connected: boolean;
79 readonly send: (
80 message: ServiceLauncherChildMessage,
81 callback?: (error: Error | null) => void,
82 ) => boolean;
83 readonly on: (
84 event: "message" | "disconnect",
85 listener: (...args: ReadonlyArray<unknown>) => void,
86 ) => void;
87 readonly off: (
88 event: "message" | "disconnect",
89 listener: (...args: ReadonlyArray<unknown>) => void,
90 ) => void;
91}
92
93export const ServiceLauncherHostProcess = Context.Reference<ServiceLauncherProcess>(
94 "t3/cloud/serviceLauncherHostProcess",
95 {
96 defaultValue: () => ({
97 connected: process.connected && process.send !== undefined,
98 send: (message, callback) => {
99 if (process.send === undefined) return false;
100 return callback === undefined ? process.send(message) : process.send(message, callback);
101 },
102 on: (event, listener) => {
103 process.on(event, listener);
104 },
105 off: (event, listener) => {
106 process.off(event, listener);
107 },
108 }),
109 },
110);
111
112export class ServiceLauncherClient extends Context.Service<
113 ServiceLauncherClient,
114 {
115 readonly managed: boolean;
116 /** The supervising launcher's protocol. A remote update never replaces the launcher,
117 so it can be older than this runtime's own. */
118 readonly protocol: SupportedLauncherProtocol | undefined;
119 readonly requestUpdate: (input: {
120 readonly targetVersion: string;
121 readonly dbPath: string;
122 }) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
123 /** Owned `t3` launchers move to the new runtime only when this start commits the trial. */
124 readonly prepareTrial: (input: {
125 readonly baseDir: string;
126 }) => Effect.Effect<ServerSelfUpdateOutcome | undefined, ServiceLauncherClientError>;
127 }
128>()("t3/cloud/serviceLauncherClient") {}
129
130const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup")(
131 function* (options?: { readonly currentVersion?: string }) {
132 const host = yield* ServiceLauncherHostProcess;
133 const environment = yield* HostProcess.Environment;
134 const currentVersion = options?.currentVersion ?? packageJson.version;
135 // IPC channels are not inherited; without one, launcher context belongs to an ancestor.
136 const rawContext = host.connected ? environment[SERVICE_LAUNCHER_CONTEXT_ENV] : undefined;
137 const context = rawContext === undefined ? undefined : decodeServiceLauncherContext(rawContext);
138
139 if (rawContext !== undefined && context === undefined) {
140 return yield* new ServiceLauncherClientError({ operation: "decode-context" });
141 }
142 if (context !== undefined && context.childVersion !== currentVersion) {
143 return yield* new ServiceLauncherClientError({ operation: "version-mismatch" });
144 }
145
146 const managed = context !== undefined;
147
148 return { host, context, managed };
149 },
150);
151
152export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
153 function* () {
154 const { managed } = yield* resolveStartup();
155 return { managed };
156 },
157);
158
159const repointWindowsShims = Effect.fn("cloud.service_launcher_client.repoint_windows_shims")(
160 function* (input: { readonly baseDir: string; readonly targetVersion: string }) {
161 const fs = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const environment = yield* HostProcess.Environment;
164 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
165 const target = pinnedRuntimePaths(path, input.baseDir, input.targetVersion, "win32");
166 const installBinDir =
167 environment["T3CODE_INSTALL_BIN_DIR"] ||
168 (environment["USERPROFILE"]
169 ? path.join(environment["USERPROFILE"], ".local", "bin")
170 : undefined);
171 // The service does not see the installer's bin dir or PATH; the installer records its shim.
172 const recorded = yield* fs
173 .readFileString(path.join(path.dirname(versionsDir), "launchers"))
174 .pipe(Effect.orElseSucceed(() => ""));
175 const candidates = new Set(
176 [
177 ...(installBinDir === undefined ? [] : [path.join(installBinDir, "t3.cmd")]),
178 ...(environment["PATH"] ?? environment["Path"] ?? "")
179 .split(";")
180 .filter((directory) => directory.trim().length > 0)
181 .map((directory) => path.join(directory, "t3.cmd")),
182 ...recorded.split(/\r?\n/).filter((shim) => path.basename(shim).toLowerCase() === "t3.cmd"),
183 ]
184 .filter((shim) => path.isAbsolute(shim))
185 .map((shim) => path.resolve(shim)),
186 );
187 for (const shim of candidates) {
188 yield* Effect.gen(function* () {
189 const contents = yield* fs.readFileString(shim).pipe(Effect.option);
190 if (Option.isNone(contents)) return;
191 const current = generatedWindowsShimTarget(contents.value);
192 if (current === undefined || !isVersionExecutable(path, versionsDir, current)) return;
193 yield* fs.writeFileString(shim, `@echo off\r\n"${target.entryPath}" %*`);
194 }).pipe(
195 Effect.catchCause((cause) =>
196 Cause.hasInterrupts(cause)
197 ? Effect.interrupt
198 : Effect.logWarning("Could not move the t3 command to the updated version", {
199 launchedAs: shim,
200 cause,
201 }),
202 ),
203 );
204 }
205 },
206);
207
208export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint_launchers")(
209 function* (input: { readonly baseDir: string; readonly targetVersion: string }) {
210 const fs = yield* FileSystem.FileSystem;
211 const path = yield* Path.Path;
212 const environment = yield* HostProcess.Environment;
213 const platform = yield* HostProcess.Platform;
214 if (platform === "win32") return yield* repointWindowsShims(input);
215 if (platform !== "linux" && platform !== "darwin") return;
216 const installBinDir =
217 environment["T3CODE_INSTALL_BIN_DIR"] ||
218 (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined);
219 const candidates = new Set<string>();
220 if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3"));
221 const searchPath = environment["PATH"] ?? "";
222 const cwd = yield* HostProcess.WorkingDirectory;
223 for (const directory of searchPath.split(":")) {
224 // Like the shell, an empty entry of a nonempty PATH is the working directory.
225 if (directory.length === 0 && searchPath.length === 0) continue;
226 const candidate = path.join(directory || cwd, "t3");
227 if (directory.length === 0) {
228 // The shell passes over a working-directory entry it cannot run and keeps searching.
229 const info = yield* fs.stat(candidate).pipe(Effect.option);
230 if (Option.isNone(info) || info.value.type !== "File" || (info.value.mode & 0o111) === 0) {
231 continue;
232 }
233 candidates.add(candidate);
234 break;
235 }
236 if (
237 yield* fs.exists(candidate).pipe(
238 Effect.catch((cause) =>
239 Effect.logWarning("Could not check the t3 command on PATH", {
240 launchedAs: candidate,
241 cause,
242 }).pipe(Effect.as(false)),
243 ),
244 )
245 ) {
246 candidates.add(candidate);
247 break;
248 }
249 }
250 const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
251 const target = pinnedRuntimePaths(path, input.baseDir, input.targetVersion, platform);
252 for (const launchedAs of candidates) {
253 yield* Effect.scoped(
254 Effect.gen(function* () {
255 const linkTarget = yield* fs.readLink(launchedAs).pipe(
256 Effect.asSome,
257 Effect.catchIf(
258 (error) =>
259 error.reason._tag === "NotFound" ||
260 (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EINVAL",
261 () => Effect.succeedNone,
262 ),
263 );
264 // A legacy symlink, or the script install.sh and `t3 update` write.
265 const current = Option.isSome(linkTarget)
266 ? path.resolve(path.dirname(launchedAs), linkTarget.value)
267 : yield* readPosixLauncherTarget(launchedAs);
268 if (current === undefined) return;
269 const relative = path.relative(versionsDir, current);
270 if (
271 relative.length === 0 ||
272 relative === ".." ||
273 relative.startsWith(`..${path.sep}`) ||
274 path.isAbsolute(relative)
275 )
276 return;
277 yield* writePosixLauncher({
278 launcher: launchedAs,
279 executable: target.entryPath,
280 exclusive: false,
281 });
282 }),
283 ).pipe(
284 Effect.catchCause((cause) =>
285 Cause.hasInterrupts(cause)
286 ? Effect.interrupt
287 : Effect.logWarning("Could not move the t3 command to the updated version", {
288 launchedAs,
289 cause,
290 }),
291 ),
292 );
293 }
294 },
295);
296
297/** Completes when the launcher asks this server to stop, which Windows cannot signal. */
298export const awaitServiceLauncherStop = Effect.fn("cloud.service_launcher_client.await_stop")(
299 function* (options?: { readonly currentVersion?: string }) {
300 const startup = yield* resolveStartup(options).pipe(Effect.option);
301 if (Option.isNone(startup) || !startup.value.managed) return yield* Effect.never;
302 const { host } = startup.value;
303 return yield* Effect.callback<void>((resume) => {
304 const onMessage = (...args: ReadonlyArray<unknown>) => {
305 if (decodeServiceLauncherParentMessage(args[0])?.type === "stop") resume(Effect.void);
306 };
307 host.on("message", onMessage);
308 return Effect.sync(() => host.off("message", onMessage));
309 });
310 },
311);
312
313export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: {
314 readonly currentVersion?: string;
315}) {
316 const { host, context, managed } = yield* resolveStartup(options);
317 // prepareTrial runs later, outside whatever context built the client.
318 const fs = yield* FileSystem.FileSystem;
319 const path = yield* Path.Path;
320 const environment = yield* HostProcess.Environment;
321 const platform = yield* HostProcess.Platform;
322 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
323 // The launcher that commits a remote update is the old one; its reload after commit
324 // keeps oomd's watch only if the policy is mirrored before it.
325 const keepOomdWatch =
326 platform === "linux"
327 ? spawner
328 .exitCode(
329 ChildProcess.make("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], {
330 env: environment,
331 stdin: "ignore",
332 stdout: "ignore",
333 stderr: "ignore",
334 }),
335 )
336 .pipe(Effect.timeout("30 seconds"), Effect.ignore)
337 : Effect.void;
338
339 const exchange = (
340 message: ServiceLauncherChildMessage,
341 accept: (reply: ServiceLauncherParentMessage) => boolean,
342 ) =>
343 Effect.callback<ServiceLauncherParentMessage, ServiceLauncherClientError>((resume) => {
344 if (!managed) {
345 resume(Effect.fail(new ServiceLauncherClientError({ operation: "unmanaged" })));
346 return;
347 }
348
349 let settled = false;
350 const cleanup = () => {
351 host.off("message", onMessage);
352 host.off("disconnect", onDisconnect);
353 };
354 const settle = (
355 effect: Effect.Effect<ServiceLauncherParentMessage, ServiceLauncherClientError>,
356 ) => {
357 if (settled) return;
358 settled = true;
359 cleanup();
360 resume(effect);
361 };
362 const onMessage = (...args: ReadonlyArray<unknown>) => {
363 const reply = decodeServiceLauncherParentMessage(args[0]);
364 if (reply !== undefined && accept(reply)) settle(Effect.succeed(reply));
365 };
366 const onDisconnect = () =>
367 settle(Effect.fail(new ServiceLauncherClientError({ operation: "disconnect" })));
368
369 host.on("message", onMessage);
370 host.on("disconnect", onDisconnect);
371 try {
372 host.send(message, (error) => {
373 if (error !== null) {
374 settle(
375 Effect.fail(new ServiceLauncherClientError({ operation: "send", cause: error })),
376 );
377 }
378 });
379 } catch (cause) {
380 settle(Effect.fail(new ServiceLauncherClientError({ operation: "send", cause })));
381 }
382
383 return Effect.sync(cleanup);
384 }).pipe(
385 Effect.timeoutOrElse({
386 duration: "30 seconds",
387 orElse: () => Effect.fail(new ServiceLauncherClientError({ operation: "timeout" })),
388 }),
389 );
390
391 const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
392 exchange(
393 { type: "request-update", ...input },
394 (reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
395 ).pipe(
396 Effect.flatMap((reply) =>
397 reply.type === "update-accepted"
398 ? Effect.succeed(reply.updateId)
399 : reply.type === "update-rejected"
400 ? Effect.fail(
401 new ServiceLauncherRejectedError({
402 targetVersion: input.targetVersion,
403 reason: reply.reason,
404 }),
405 )
406 : Effect.die("service launcher returned an impossible update response"),
407 ),
408 );
409
410 const pending = context?.update?.status === "pending" ? context.update : undefined;
411 const outcome =
412 context?.update === undefined || context.update.status === "pending"
413 ? undefined
414 : context.update;
415 const prepareTrial = (input: { readonly baseDir: string }) =>
416 pending !== undefined
417 ? Effect.andThen(
418 keepOomdWatch,
419 exchange(
420 { type: "prepared", updateId: pending.id },
421 (reply) => reply.type === "committed" && reply.updateId === pending.id,
422 ).pipe(
423 Effect.flatMap((reply) =>
424 reply.type !== "committed"
425 ? Effect.die("service launcher returned an impossible prepared response")
426 : repointLaunchers({
427 baseDir: input.baseDir,
428 targetVersion: pending.targetVersion,
429 }).pipe(
430 Effect.provideService(FileSystem.FileSystem, fs),
431 Effect.provideService(Path.Path, path),
432 Effect.provideService(HostProcess.Environment, environment),
433 Effect.provideService(HostProcess.Platform, platform),
434 Effect.as({
435 id: pending.id,
436 fromVersion: pending.fromVersion,
437 targetVersion: pending.targetVersion,
438 status: "committed" as const,
439 }),
440 ),
441 ),
442 ),
443 )
444 : Effect.succeed(outcome);
445
446 return ServiceLauncherClient.of({
447 managed,
448 protocol: context?.protocol,
449 requestUpdate,
450 prepareTrial,
451 });
452});
453
454export const layer = Layer.effect(ServiceLauncherClient, make());