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