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 Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7
8import packageJson from "../../package.json" with { type: "json" };
9import {
10 decodeServiceLauncherContext,
11 decodeServiceLauncherParentMessage,
12 SERVICE_LAUNCHER_CONTEXT_ENV,
13 type ServiceLauncherChildMessage,
14 type ServiceLauncherParentMessage,
15} from "./serviceProtocol.ts";
16
17export class ServiceLauncherClientError extends Schema.TaggedError<ServiceLauncherClientError>()(
18 "ServiceLauncherClientError",
19 {
20 operation: Schema.Literals([
21 "decode-context",
22 "version-mismatch",
23 "unmanaged",
24 "send",
25 "disconnect",
26 "timeout",
27 ]),
28 cause: Schema.optional(Schema.Defect()),
29 },
30) {
31 override get message(): string {
32 switch (this.operation) {
33 case "decode-context":
34 return "The service launcher supplied invalid startup context.";
35 case "version-mismatch":
36 return "The service launcher started a different t3 version.";
37 case "unmanaged":
38 return "This server is not managed by the launcher.";
39 case "send":
40 return "Could not send a request to the service launcher.";
41 case "disconnect":
42 return "The service launcher disconnected before acknowledging the request.";
43 case "timeout":
44 return "The service launcher did not respond within 30 seconds.";
45 }
46 }
47}
48
49export class ServiceLauncherRejectedError extends Schema.TaggedError<ServiceLauncherRejectedError>()(
50 "ServiceLauncherRejectedError",
51 {
52 targetVersion: Schema.String,
53 reason: Schema.String,
54 },
55) {
56 override get message(): string {
57 return this.reason;
58 }
59}
60
61interface ServiceLauncherProcess {
62 readonly connected: boolean;
63 readonly send: (
64 message: ServiceLauncherChildMessage,
65 callback?: (error: Error | null) => void,
66 ) => boolean;
67 readonly on: (
68 event: "message" | "disconnect",
69 listener: (...args: ReadonlyArray<unknown>) => void,
70 ) => void;
71 readonly off: (
72 event: "message" | "disconnect",
73 listener: (...args: ReadonlyArray<unknown>) => void,
74 ) => void;
75}
76
77export const ServiceLauncherHostProcess = Context.Reference<ServiceLauncherProcess>(
78 "t3/cloud/serviceLauncherHostProcess",
79 {
80 defaultValue: () => ({
81 connected: process.connected && process.send !== undefined,
82 send: (message, callback) => {
83 if (process.send === undefined) return false;
84 return callback === undefined ? process.send(message) : process.send(message, callback);
85 },
86 on: (event, listener) => {
87 process.on(event, listener);
88 },
89 off: (event, listener) => {
90 process.off(event, listener);
91 },
92 }),
93 },
94);
95
96export class ServiceLauncherClient extends Context.Service<
97 ServiceLauncherClient,
98 {
99 readonly managed: boolean;
100 readonly requestUpdate: (input: {
101 readonly targetVersion: string;
102 readonly dbPath: string;
103 }) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;
104 readonly prepareTrial: Effect.Effect<
105 ServerSelfUpdateOutcome | undefined,
106 ServiceLauncherClientError
107 >;
108 }
109>()("t3/cloud/serviceLauncherClient") {}
110
111const resolveStartup = Effect.fn("cloud.service_launcher_client.resolve_startup")(
112 function* (options?: { readonly currentVersion?: string }) {
113 const host = yield* ServiceLauncherHostProcess;
114 const environment = yield* HostProcess.Environment;
115 const currentVersion = options?.currentVersion ?? packageJson.version;
116 // The launcher always spawns its child with an IPC channel, and Node does
117 // not pass that channel on. Without one, the context was inherited from an
118 // ancestor (e.g. `t3 serve` run in a T3 terminal), so it describes someone else.
119 const rawContext = host.connected ? environment[SERVICE_LAUNCHER_CONTEXT_ENV] : undefined;
120 const context = rawContext === undefined ? undefined : decodeServiceLauncherContext(rawContext);
121
122 if (rawContext !== undefined && context === undefined) {
123 return yield* new ServiceLauncherClientError({ operation: "decode-context" });
124 }
125 if (context !== undefined && context.childVersion !== currentVersion) {
126 return yield* new ServiceLauncherClientError({ operation: "version-mismatch" });
127 }
128
129 const managed = context !== undefined;
130
131 return { host, context, managed };
132 },
133);
134
135export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
136 function* () {
137 const { managed } = yield* resolveStartup();
138 return { managed };
139 },
140);
141
142export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: {
143 readonly currentVersion?: string;
144}) {
145 const { host, context, managed } = yield* resolveStartup(options);
146
147 const exchange = (
148 message: ServiceLauncherChildMessage,
149 accept: (reply: ServiceLauncherParentMessage) => boolean,
150 ) =>
151 Effect.callback<ServiceLauncherParentMessage, ServiceLauncherClientError>((resume) => {
152 if (!managed) {
153 resume(Effect.fail(new ServiceLauncherClientError({ operation: "unmanaged" })));
154 return;
155 }
156
157 let settled = false;
158 const cleanup = () => {
159 host.off("message", onMessage);
160 host.off("disconnect", onDisconnect);
161 };
162 const settle = (
163 effect: Effect.Effect<ServiceLauncherParentMessage, ServiceLauncherClientError>,
164 ) => {
165 if (settled) return;
166 settled = true;
167 cleanup();
168 resume(effect);
169 };
170 const onMessage = (...args: ReadonlyArray<unknown>) => {
171 const reply = decodeServiceLauncherParentMessage(args[0]);
172 if (reply !== undefined && accept(reply)) settle(Effect.succeed(reply));
173 };
174 const onDisconnect = () =>
175 settle(Effect.fail(new ServiceLauncherClientError({ operation: "disconnect" })));
176
177 host.on("message", onMessage);
178 host.on("disconnect", onDisconnect);
179 try {
180 host.send(message, (error) => {
181 if (error !== null) {
182 settle(
183 Effect.fail(new ServiceLauncherClientError({ operation: "send", cause: error })),
184 );
185 }
186 });
187 } catch (cause) {
188 settle(Effect.fail(new ServiceLauncherClientError({ operation: "send", cause })));
189 }
190
191 return Effect.sync(cleanup);
192 }).pipe(
193 Effect.timeoutOrElse({
194 duration: "30 seconds",
195 orElse: () => Effect.fail(new ServiceLauncherClientError({ operation: "timeout" })),
196 }),
197 );
198
199 const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
200 exchange(
201 { type: "request-update", ...input },
202 (reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
203 ).pipe(
204 Effect.flatMap((reply) =>
205 reply.type === "update-accepted"
206 ? Effect.succeed(reply.updateId)
207 : reply.type === "update-rejected"
208 ? Effect.fail(
209 new ServiceLauncherRejectedError({
210 targetVersion: input.targetVersion,
211 reason: reply.reason,
212 }),
213 )
214 : Effect.die("service launcher returned an impossible update response"),
215 ),
216 );
217
218 const pending = context?.update?.status === "pending" ? context.update : undefined;
219 const outcome =
220 context?.update === undefined || context.update.status === "pending"
221 ? undefined
222 : context.update;
223 const prepareTrial =
224 pending !== undefined
225 ? exchange(
226 { type: "prepared", updateId: pending.id },
227 (reply) => reply.type === "committed" && reply.updateId === pending.id,
228 ).pipe(
229 Effect.flatMap((reply) => {
230 if (reply.type !== "committed") {
231 return Effect.die("service launcher returned an impossible prepared response");
232 }
233 return Effect.succeed({
234 id: pending.id,
235 fromVersion: pending.fromVersion,
236 targetVersion: pending.targetVersion,
237 status: "committed" as const,
238 });
239 }),
240 )
241 : Effect.succeed(outcome);
242
243 return ServiceLauncherClient.of({
244 managed,
245 requestUpdate,
246 prepareTrial,
247 });
248});
249
250export const layer = Layer.effect(ServiceLauncherClient, make());