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

outdatedHostUpdate.test.ts

354 lines13.0 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_PROTOCOL_VERSION,
4 ExecutionEnvironmentDescriptor,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as SubscriptionRef from "effect/SubscriptionRef";
13import * as HttpClient from "effect/http/HttpClient";
14import * as HttpClientResponse from "effect/http/HttpClientResponse";
15import * as Socket from "effect/socket/Socket";
16​
17import type { ConnectionCatalogEntry } from "./catalog.ts";
18import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
19import { PrimaryConnectionTarget } from "./model.ts";
20import { updateOutdatedHost } from "./outdatedHostUpdate.ts";
21import * as EnvironmentRegistry from "./registry.ts";
22import * as ConnectionResolver from "./resolver.ts";
23import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
24​
25const TARGET = new PrimaryConnectionTarget({
26 environmentId: EnvironmentId.make("environment-old"),
27 label: "Build Mac",
28 httpBaseUrl: "https://build.example.test",
29 wsBaseUrl: "wss://build.example.test",
30});
31​
32const descriptor = (protocol: number | undefined, serverVersion: string) =>
33 ({
34 environmentId: TARGET.environmentId,
35 label: TARGET.label,
36 platform: { os: "darwin", arch: "arm64" },
37 serverVersion,
38 ...(protocol === undefined ? {} : { orchestrationProtocolVersion: protocol }),
39 capabilities: { repositoryIdentity: true, serverSelfUpdate: "boot-service" },
40 }) satisfies ExecutionEnvironmentDescriptor;
41​
42const RpcRequest = Schema.TaggedStruct("Request", {
43 id: Schema.Union([Schema.String, Schema.Number]),
44 payload: Schema.Unknown,
45 tag: Schema.String,
46});
47const isRpcRequest = Schema.is(RpcRequest);
48const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
49const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
50const encodeDescriptor = Schema.encodeSync(Schema.fromJsonString(ExecutionEnvironmentDescriptor));
51​
52type Listener = (event: { readonly type: string; readonly data?: unknown }) => void;
53​
54class OutdatedHostSocket {
55 static readonly OPEN = 1;
56 readyState = 0;
57 readonly requests: Array<typeof RpcRequest.Type> = [];
58 private readonly listeners = new Map<string, Set<Listener>>();
59​
60 readonly url: string;
61 private readonly onUpdate: () => void;
62​
63 constructor(url: string, onUpdate: () => void) {
64 this.url = url;
65 this.onUpdate = onUpdate;
66 queueMicrotask(() => {
67 this.readyState = OutdatedHostSocket.OPEN;
68 this.emit({ type: "open" });
69 });
70 }
71​
72 addEventListener(type: string, listener: Listener) {
73 const listeners = this.listeners.get(type) ?? new Set<Listener>();
74 listeners.add(listener);
75 this.listeners.set(type, listeners);
76 }
77​
78 removeEventListener(type: string, listener: Listener) {
79 this.listeners.get(type)?.delete(listener);
80 }
81​
82 send(data: string) {
83 const message = decodeJson(data);
84 if (!isRpcRequest(message)) return;
85 this.requests.push(message);
86 if (message.tag !== WS_METHODS.serverUpdateServer) return;
87 this.onUpdate();
88 queueMicrotask(() =>
89 this.emit({
90 type: "message",
91 data: encodeJson({
92 _tag: "Exit",
93 requestId: message.id,
94 exit: {
95 _tag: "Success",
96 value: { targetVersion: "0.0.46", method: "boot-service", updateId: "update-1" },
97 },
98 }),
99 }),
100 );
101 }
102​
103 close() {
104 this.readyState = 3;
105 this.emit({ type: "close" });
106 }
107​
108 private emit(event: { readonly type: string; readonly data?: unknown }) {
109 for (const listener of this.listeners.get(event.type) ?? []) listener(event);
110 }
112​
113describe("updateOutdatedHost", () => {
114 it.effect("updates a protocol-1 host over a bare socket, then switches it back on", () =>
115 Effect.gen(function* () {
116 const blocked = orchestrationProtocolCompatibilityError(descriptor(undefined, "0.0.45"));
117 expect(blocked).toMatchObject({ serverUpdateRequired: true });
118​
119 const sockets: Array<OutdatedHostSocket> = [];
120 let served: ExecutionEnvironmentDescriptor = descriptor(undefined, "0.0.45");
121 const entries = yield* SubscriptionRef.make<
122 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
123 >(
124 new Map([
125 [
126 TARGET.environmentId,
127 {
128 target: TARGET,
129 profile: Option.none(),
130 enabled: false,
131 unsupportedReason: blocked?.message ?? "",
132 serverUpdateRequired: true,
133 },
134 ],
135 ]),
136 );
137 const calls: Array<string> = [];
138 const registry = EnvironmentRegistry.EnvironmentRegistry.of({
139 entries,
140 setCompatibility: (_environmentId: EnvironmentId, error: unknown) =>
141 Effect.sync(() => calls.push(`compatibility:${error === null ? "clear" : "block"}`)),
142 setEnabled: (_environmentId: EnvironmentId, enabled: boolean) =>
143 Effect.sync(() => calls.push(`enabled:${enabled}`)),
144 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
145 const resolver = ConnectionResolver.ConnectionResolver.of({
146 prepare: () => Effect.die(new Error("The update must bypass the protocol gate.")),
147 prepareForUpdate: () =>
148 Effect.sync(() => served).pipe(
149 Effect.map((current) => ({
150 descriptor: current,
151 prepared: {
152 environmentId: TARGET.environmentId,
153 label: TARGET.label,
154 httpBaseUrl: TARGET.httpBaseUrl,
155 socketUrl: "wss://build.example.test/ws?wsTicket=ticket",
156 httpAuthorization: null,
157 target: TARGET,
158 },
159 })),
160 ),
161 });
162 const httpClient = HttpClient.make((request) =>
163 Effect.sync(() =>
164 HttpClientResponse.fromWeb(request, new Response(encodeDescriptor(served))),
165 ),
166 );
167​
168 const result = yield* updateOutdatedHost(
169 TARGET.environmentId,
170 { targetVersion: "0.0.46" },
171 () => Effect.void,
172 ).pipe(
173 Effect.provide(
174 Layer.mergeAll(
175 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry),
176 Layer.succeed(ConnectionResolver.ConnectionResolver, resolver),
177 Layer.succeed(
178 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
179 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
180 state: yield* SubscriptionRef.make(
181 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
182 ),
183 refresh: Effect.void,
184 }),
185 ),
186 Layer.succeed(HttpClient.HttpClient, httpClient),
187 Layer.succeed(Socket.WebSocketConstructor, (url) => {
188 const socket = new OutdatedHostSocket(url, () => {
189 served = descriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46");
190 });
191 sockets.push(socket);
192 return socket as unknown as globalThis.WebSocket;
193 }),
194 ),
195 ),
196 );
197​
198 expect(sockets[0]?.url).not.toContain("orchestrationProtocol");
199 expect(sockets[0]?.requests.map((request) => request.tag)).toEqual([
200 WS_METHODS.serverUpdateServer,
201 ]);
202 expect(result.targetVersion).toBe("0.0.46");
203 expect(calls).toEqual(["compatibility:clear", "enabled:true"]);
204 }),
205 );
206​
207 it.effect("switches a host that is already compatible back on without opening a socket", () =>
208 Effect.gen(function* () {
209 const calls: Array<string> = [];
210 let opened = false;
211 const prepared = {
212 environmentId: TARGET.environmentId,
213 label: TARGET.label,
214 httpBaseUrl: TARGET.httpBaseUrl,
215 socketUrl: "wss://build.example.test/ws",
216 httpAuthorization: null,
217 target: TARGET,
218 };
219 const result = yield* updateOutdatedHost(
220 TARGET.environmentId,
221 { targetVersion: "0.0.46" },
222 () => Effect.void,
223 ).pipe(
224 Effect.provide(
225 Layer.mergeAll(
226 Layer.succeed(
227 EnvironmentRegistry.EnvironmentRegistry,
228 EnvironmentRegistry.EnvironmentRegistry.of({
229 entries: yield* SubscriptionRef.make<
230 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
231 >(
232 new Map([
233 [
234 TARGET.environmentId,
235 { target: TARGET, profile: Option.none(), enabled: false },
236 ],
237 ]),
238 ),
239 setCompatibility: (_environmentId: EnvironmentId, error: unknown) =>
240 Effect.sync(() =>
241 calls.push(`compatibility:${error === null ? "clear" : "block"}`),
242 ),
243 setEnabled: (_environmentId: EnvironmentId, enabled: boolean) =>
244 Effect.sync(() => calls.push(`enabled:${enabled}`)),
245 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
246 ),
247 Layer.succeed(
248 ConnectionResolver.ConnectionResolver,
249 ConnectionResolver.ConnectionResolver.of({
250 prepare: () => Effect.die(new Error("unused")),
251 prepareForUpdate: () =>
252 Effect.succeed({
253 descriptor: descriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46"),
254 prepared,
255 }),
256 }),
257 ),
258 Layer.succeed(
259 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
260 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
261 state: yield* SubscriptionRef.make(
262 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
263 ),
264 refresh: Effect.void,
265 }),
266 ),
267 Layer.succeed(
268 HttpClient.HttpClient,
269 HttpClient.make(() => Effect.die(new Error("unused"))),
270 ),
271 // A v2 host answers a bare socket with 426, so opening one fails.
272 Layer.succeed(Socket.WebSocketConstructor, () => {
273 opened = true;
274 throw new Error("unused");
275 }),
276 ),
277 ),
278 );
279 expect(opened).toBe(false);
280 expect(result.targetVersion).toBe("0.0.46");
281 expect(calls).toEqual(["compatibility:clear", "enabled:true"]);
282 }),
283 );
284​
285 it.effect("refuses a host that cannot update itself without opening a socket", () =>
286 Effect.gen(function* () {
287 const manual = {
288 ...descriptor(undefined, "0.0.45"),
289 capabilities: { repositoryIdentity: true },
290 };
291 let opened = false;
292 const error = yield* Effect.flip(
293 updateOutdatedHost(TARGET.environmentId, { targetVersion: "0.0.46" }, () => Effect.void),
294 ).pipe(
295 Effect.provide(
296 Layer.mergeAll(
297 Layer.succeed(
298 EnvironmentRegistry.EnvironmentRegistry,
299 EnvironmentRegistry.EnvironmentRegistry.of({
300 entries: yield* SubscriptionRef.make<
301 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
302 >(
303 new Map([
304 [
305 TARGET.environmentId,
306 { target: TARGET, profile: Option.none(), enabled: false },
307 ],
308 ]),
309 ),
310 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
311 ),
312 Layer.succeed(
313 ConnectionResolver.ConnectionResolver,
314 ConnectionResolver.ConnectionResolver.of({
315 prepare: () => Effect.die(new Error("unused")),
316 prepareForUpdate: () =>
317 Effect.succeed({
318 descriptor: manual,
319 prepared: {
320 environmentId: TARGET.environmentId,
321 label: TARGET.label,
322 httpBaseUrl: TARGET.httpBaseUrl,
323 socketUrl: "wss://build.example.test/ws",
324 httpAuthorization: null,
325 target: TARGET,
326 },
327 }),
328 }),
329 ),
330 Layer.succeed(
331 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
332 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
333 state: yield* SubscriptionRef.make(
334 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
335 ),
336 refresh: Effect.void,
337 }),
338 ),
339 Layer.succeed(
340 HttpClient.HttpClient,
341 HttpClient.make(() => Effect.die(new Error("unused"))),
342 ),
343 Layer.succeed(Socket.WebSocketConstructor, () => {
344 opened = true;
345 throw new Error("unused");
346 }),
347 ),
348 ),
349 );
350 expect(error).toMatchObject({ _tag: "OutdatedHostUpdateError" });
351 expect(opened).toBe(false);
352 }),
353 );
354});