Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serviceLauncherClient.ts

248 lines8.2 KB

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 }
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 }
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;
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 // IPC channels are not inherited; without one, launcher context belongs to an ancestor.
117 const rawContext = host.connected ? environment[SERVICE_LAUNCHER_CONTEXT_ENV] : undefined;
118 const context = rawContext === undefined ? undefined : decodeServiceLauncherContext(rawContext);
119​
120 if (rawContext !== undefined && context === undefined) {
121 return yield* new ServiceLauncherClientError({ operation: "decode-context" });
122 }
123 if (context !== undefined && context.childVersion !== currentVersion) {
124 return yield* new ServiceLauncherClientError({ operation: "version-mismatch" });
125 }
126​
127 const managed = context !== undefined;
128​
129 return { host, context, managed };
130 },
131);
132​
133export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_client.resolve_mode")(
134 function* () {
135 const { managed } = yield* resolveStartup();
136 return { managed };
137 },
138);
139​
140export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: {
141 readonly currentVersion?: string;
142}) {
143 const { host, context, managed } = yield* resolveStartup(options);
144​
145 const exchange = (
146 message: ServiceLauncherChildMessage,
147 accept: (reply: ServiceLauncherParentMessage) => boolean,
148 ) =>
149 Effect.callback<ServiceLauncherParentMessage, ServiceLauncherClientError>((resume) => {
150 if (!managed) {
151 resume(Effect.fail(new ServiceLauncherClientError({ operation: "unmanaged" })));
152 return;
153 }
154​
155 let settled = false;
156 const cleanup = () => {
157 host.off("message", onMessage);
158 host.off("disconnect", onDisconnect);
159 };
160 const settle = (
161 effect: Effect.Effect<ServiceLauncherParentMessage, ServiceLauncherClientError>,
162 ) => {
163 if (settled) return;
164 settled = true;
165 cleanup();
166 resume(effect);
167 };
168 const onMessage = (...args: ReadonlyArray<unknown>) => {
169 const reply = decodeServiceLauncherParentMessage(args[0]);
170 if (reply !== undefined && accept(reply)) settle(Effect.succeed(reply));
171 };
172 const onDisconnect = () =>
173 settle(Effect.fail(new ServiceLauncherClientError({ operation: "disconnect" })));
174​
175 host.on("message", onMessage);
176 host.on("disconnect", onDisconnect);
177 try {
178 host.send(message, (error) => {
179 if (error !== null) {
180 settle(
181 Effect.fail(new ServiceLauncherClientError({ operation: "send", cause: error })),
182 );
183 }
184 });
185 } catch (cause) {
186 settle(Effect.fail(new ServiceLauncherClientError({ operation: "send", cause })));
187 }
188​
189 return Effect.sync(cleanup);
190 }).pipe(
191 Effect.timeoutOrElse({
192 duration: "30 seconds",
193 orElse: () => Effect.fail(new ServiceLauncherClientError({ operation: "timeout" })),
194 }),
195 );
196​
197 const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>
198 exchange(
199 { type: "request-update", ...input },
200 (reply) => reply.type === "update-accepted" || reply.type === "update-rejected",
201 ).pipe(
202 Effect.flatMap((reply) =>
203 reply.type === "update-accepted"
204 ? Effect.succeed(reply.updateId)
205 : reply.type === "update-rejected"
206 ? Effect.fail(
207 new ServiceLauncherRejectedError({
208 targetVersion: input.targetVersion,
209 reason: reply.reason,
210 }),
211 )
212 : Effect.die("service launcher returned an impossible update response"),
213 ),
214 );
215​
216 const pending = context?.update?.status === "pending" ? context.update : undefined;
217 const outcome =
218 context?.update === undefined || context.update.status === "pending"
219 ? undefined
220 : context.update;
221 const prepareTrial =
222 pending !== undefined
223 ? exchange(
224 { type: "prepared", updateId: pending.id },
225 (reply) => reply.type === "committed" && reply.updateId === pending.id,
226 ).pipe(
227 Effect.flatMap((reply) => {
228 if (reply.type !== "committed") {
229 return Effect.die("service launcher returned an impossible prepared response");
230 }
231 return Effect.succeed({
232 id: pending.id,
233 fromVersion: pending.fromVersion,
234 targetVersion: pending.targetVersion,
235 status: "committed" as const,
236 });
237 }),
238 )
239 : Effect.succeed(outcome);
240​
241 return ServiceLauncherClient.of({
242 managed,
243 requestUpdate,
244 prepareTrial,
245 });
246});
247​
248export const layer = Layer.effect(ServiceLauncherClient, make());