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

outdatedHostUpdate.test.ts

438 lines16.2 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 { describeOutdatedHost, 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​
52describe("describeOutdatedHost", () => {
53 it.effect("discovers a disabled outdated host without opening a normal session", () =>
54 Effect.gen(function* () {
55 const expected = descriptor(undefined, "0.0.45");
56 const result = yield* describeOutdatedHost(TARGET.environmentId).pipe(
57 Effect.provideService(
58 EnvironmentRegistry.EnvironmentRegistry,
59 EnvironmentRegistry.EnvironmentRegistry.of({
60 entries: yield* SubscriptionRef.make<
61 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
62 >(
63 new Map([
64 [TARGET.environmentId, { target: TARGET, profile: Option.none(), enabled: false }],
65 ]),
66 ),
67 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
68 ),
69 Effect.provideService(
70 ConnectionResolver.ConnectionResolver,
71 ConnectionResolver.ConnectionResolver.of({
72 prepare: () => Effect.die(new Error("normal sessions reject this protocol")),
73 prepareForUpdate: (entry) =>
74 Effect.succeed({
75 descriptor: expected,
76 prepared: {
77 environmentId: entry.target.environmentId,
78 label: entry.target.label,
79 httpBaseUrl: TARGET.httpBaseUrl,
80 socketUrl: "wss://build.example.test/ws",
81 httpAuthorization: null,
82 target: TARGET,
83 },
84 }),
85 }),
86 ),
87 );
88 expect(result).toEqual(expected);
89 }),
90 );
91});
92​
93type Listener = (event: { readonly type: string; readonly data?: unknown }) => void;
94​
95class OutdatedHostSocket {
96 static readonly OPEN = 1;
97 readyState = 0;
98 readonly requests: Array<typeof RpcRequest.Type> = [];
99 private readonly listeners = new Map<string, Set<Listener>>();
100​
101 readonly url: string;
102 private readonly onUpdate: () => void;
103​
104 constructor(url: string, onUpdate: () => void) {
105 this.url = url;
106 this.onUpdate = onUpdate;
107 queueMicrotask(() => {
108 this.readyState = OutdatedHostSocket.OPEN;
109 this.emit({ type: "open" });
110 });
111 }
112​
113 addEventListener(type: string, listener: Listener) {
114 const listeners = this.listeners.get(type) ?? new Set<Listener>();
115 listeners.add(listener);
116 this.listeners.set(type, listeners);
117 }
118​
119 removeEventListener(type: string, listener: Listener) {
120 this.listeners.get(type)?.delete(listener);
121 }
122​
123 send(data: string) {
124 const message = decodeJson(data);
125 if (!isRpcRequest(message)) return;
126 this.requests.push(message);
127 if (message.tag === WS_METHODS.serverUpdateServerWithProgress) {
128 this.onUpdate();
129 queueMicrotask(() =>
130 this.emit({
131 type: "message",
132 data: encodeJson({
133 _tag: "Chunk",
134 requestId: message.id,
135 values: [{ type: "progress", stage: "downloading" }],
136 }),
137 }),
138 );
139 return;
140 }
141 if (message.tag !== WS_METHODS.serverUpdateServer) return;
142 this.onUpdate();
143 queueMicrotask(() =>
144 this.emit({
145 type: "message",
146 data: encodeJson({
147 _tag: "Exit",
148 requestId: message.id,
149 exit: {
150 _tag: "Success",
151 value: { targetVersion: "0.0.46", method: "boot-service", updateId: "update-1" },
152 },
153 }),
154 }),
155 );
156 }
157​
158 close() {
159 this.readyState = 3;
160 this.emit({ type: "close", code: 1006 });
161 }
162​
163 private emit(event: { readonly type: string; readonly data?: unknown; readonly code?: number }) {
164 for (const listener of this.listeners.get(event.type) ?? []) listener(event);
165 }
167​
168describe("updateOutdatedHost", () => {
169 it.effect("updates a protocol-1 host over a bare socket, then switches it back on", () =>
170 Effect.gen(function* () {
171 const blocked = orchestrationProtocolCompatibilityError(descriptor(undefined, "0.0.45"));
172 expect(blocked).toMatchObject({ serverUpdateRequired: true });
173​
174 const sockets: Array<OutdatedHostSocket> = [];
175 let served: ExecutionEnvironmentDescriptor = descriptor(undefined, "0.0.45");
176 const entries = yield* SubscriptionRef.make<
177 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
178 >(
179 new Map([
180 [
181 TARGET.environmentId,
182 {
183 target: TARGET,
184 profile: Option.none(),
185 enabled: false,
186 unsupportedReason: blocked?.message ?? "",
187 serverUpdateRequired: true,
188 },
189 ],
190 ]),
191 );
192 const calls: Array<string> = [];
193 const registry = EnvironmentRegistry.EnvironmentRegistry.of({
194 entries,
195 setCompatibility: (_environmentId: EnvironmentId, error: unknown) =>
196 Effect.sync(() => calls.push(`compatibility:${error === null ? "clear" : "block"}`)),
197 setEnabled: (_environmentId: EnvironmentId, enabled: boolean) =>
198 Effect.sync(() => calls.push(`enabled:${enabled}`)),
199 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
200 const resolver = ConnectionResolver.ConnectionResolver.of({
201 prepare: () => Effect.die(new Error("The update must bypass the protocol gate.")),
202 prepareForUpdate: () =>
203 Effect.sync(() => served).pipe(
204 Effect.map((current) => ({
205 descriptor: current,
206 prepared: {
207 environmentId: TARGET.environmentId,
208 label: TARGET.label,
209 httpBaseUrl: TARGET.httpBaseUrl,
210 socketUrl: "wss://build.example.test/ws?wsTicket=ticket",
211 httpAuthorization: null,
212 target: TARGET,
213 },
214 })),
215 ),
216 });
217 const httpClient = HttpClient.make((request) =>
218 Effect.sync(() =>
219 HttpClientResponse.fromWeb(request, new Response(encodeDescriptor(served))),
220 ),
221 );
222​
223 const result = yield* updateOutdatedHost(
224 TARGET.environmentId,
225 { targetVersion: "0.0.46" },
226 () => Effect.void,
227 ).pipe(
228 Effect.provide(
229 Layer.mergeAll(
230 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry),
231 Layer.succeed(ConnectionResolver.ConnectionResolver, resolver),
232 Layer.succeed(
233 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
234 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
235 state: yield* SubscriptionRef.make(
236 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
237 ),
238 refresh: Effect.void,
239 }),
240 ),
241 Layer.succeed(HttpClient.HttpClient, httpClient),
242 Layer.succeed(Socket.WebSocketConstructor, (url) => {
243 const socket = new OutdatedHostSocket(url, () => {
244 served = descriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46");
245 });
246 sockets.push(socket);
247 return socket as unknown as globalThis.WebSocket;
248 }),
249 ),
250 ),
251 );
252​
253 expect(sockets[0]?.url).not.toContain("orchestrationProtocol");
254 expect(sockets[0]?.requests.map((request) => request.tag)).toEqual([
255 WS_METHODS.serverUpdateServer,
256 ]);
257 expect(result.targetVersion).toBe("0.0.46");
258 expect(calls).toEqual(["compatibility:clear", "enabled:true"]);
259 }),
260 );
261​
262 it.effect("refuses a host that cannot update itself without opening a socket", () =>
263 Effect.gen(function* () {
264 const manual = {
265 ...descriptor(undefined, "0.0.45"),
266 capabilities: { repositoryIdentity: true },
267 };
268 let opened = false;
269 const error = yield* Effect.flip(
270 updateOutdatedHost(TARGET.environmentId, { targetVersion: "0.0.46" }, () => Effect.void),
271 ).pipe(
272 Effect.provide(
273 Layer.mergeAll(
274 Layer.succeed(
275 EnvironmentRegistry.EnvironmentRegistry,
276 EnvironmentRegistry.EnvironmentRegistry.of({
277 entries: yield* SubscriptionRef.make<
278 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
279 >(
280 new Map([
281 [
282 TARGET.environmentId,
283 { target: TARGET, profile: Option.none(), enabled: false },
284 ],
285 ]),
286 ),
287 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
288 ),
289 Layer.succeed(
290 ConnectionResolver.ConnectionResolver,
291 ConnectionResolver.ConnectionResolver.of({
292 prepare: () => Effect.die(new Error("unused")),
293 prepareForUpdate: () =>
294 Effect.succeed({
295 descriptor: manual,
296 prepared: {
297 environmentId: TARGET.environmentId,
298 label: TARGET.label,
299 httpBaseUrl: TARGET.httpBaseUrl,
300 socketUrl: "wss://build.example.test/ws",
301 httpAuthorization: null,
302 target: TARGET,
303 },
304 }),
305 }),
306 ),
307 Layer.succeed(
308 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
309 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
310 state: yield* SubscriptionRef.make(
311 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
312 ),
313 refresh: Effect.void,
314 }),
315 ),
316 Layer.succeed(
317 HttpClient.HttpClient,
318 HttpClient.make(() => Effect.die(new Error("unused"))),
319 ),
320 Layer.succeed(Socket.WebSocketConstructor, () => {
321 opened = true;
322 throw new Error("unused");
323 }),
324 ),
325 ),
326 );
327 expect(error).toMatchObject({ _tag: "OutdatedHostUpdateError" });
328 expect(opened).toBe(false);
329 }),
330 );
331​
332 it.effect("resumes an outdated host update after progress transport loss", () =>
333 Effect.gen(function* () {
334 const blocked = orchestrationProtocolCompatibilityError(descriptor(undefined, "0.0.45"));
335 expect(blocked).toMatchObject({ serverUpdateRequired: true });
336​
337 const sockets: Array<OutdatedHostSocket> = [];
338 let served: ExecutionEnvironmentDescriptor = {
339 ...descriptor(undefined, "0.0.45"),
340 capabilities: {
341 repositoryIdentity: true,
342 serverSelfUpdate: "boot-service",
343 serverSelfUpdateProgress: true,
344 },
345 };
346 const entries = yield* SubscriptionRef.make<
347 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
348 >(
349 new Map([
350 [
351 TARGET.environmentId,
352 {
353 target: TARGET,
354 profile: Option.none(),
355 enabled: false,
356 unsupportedReason: blocked?.message ?? "",
357 serverUpdateRequired: true,
358 },
359 ],
360 ]),
361 );
362 const calls: Array<string> = [];
363 const registry = EnvironmentRegistry.EnvironmentRegistry.of({
364 entries,
365 setCompatibility: (_environmentId: EnvironmentId, error: unknown) =>
366 Effect.sync(() => calls.push(`compatibility:${error === null ? "clear" : "block"}`)),
367 setEnabled: (_environmentId: EnvironmentId, enabled: boolean) =>
368 Effect.sync(() => calls.push(`enabled:${enabled}`)),
369 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
370 const resolver = ConnectionResolver.ConnectionResolver.of({
371 prepare: () => Effect.die(new Error("The update must bypass the protocol gate.")),
372 prepareForUpdate: () =>
373 Effect.sync(() => served).pipe(
374 Effect.map((current) => ({
375 descriptor: current,
376 prepared: {
377 environmentId: TARGET.environmentId,
378 label: TARGET.label,
379 httpBaseUrl: TARGET.httpBaseUrl,
380 socketUrl: "wss://build.example.test/ws?wsTicket=ticket",
381 httpAuthorization: null,
382 target: TARGET,
383 },
384 })),
385 ),
386 });
387 const httpClient = HttpClient.make((request) =>
388 Effect.sync(() =>
389 HttpClientResponse.fromWeb(request, new Response(encodeDescriptor(served))),
390 ),
391 );
392​
393 const stages: Array<string> = [];
394 const result = yield* updateOutdatedHost(
395 TARGET.environmentId,
396 { targetVersion: "0.0.46" },
397 (stage) =>
398 Effect.sync(() => {
399 stages.push(stage);
400 // Lose the transport only after the consumer has observed progress.
401 if (stage === "downloading") sockets[0]?.close();
402 }),
403 ).pipe(
404 Effect.provide(
405 Layer.mergeAll(
406 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry),
407 Layer.succeed(ConnectionResolver.ConnectionResolver, resolver),
408 Layer.succeed(
409 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
410 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
411 state: yield* SubscriptionRef.make(
412 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
413 ),
414 refresh: Effect.void,
415 }),
416 ),
417 Layer.succeed(HttpClient.HttpClient, httpClient),
418 Layer.succeed(Socket.WebSocketConstructor, (url) => {
419 const socket = new OutdatedHostSocket(url, () => {
420 served = descriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46");
421 });
422 sockets.push(socket);
423 return socket as unknown as globalThis.WebSocket;
424 }),
425 ),
426 ),
427 );
428​
429 expect(sockets[0]?.url).not.toContain("orchestrationProtocol");
430 expect(sockets[0]?.requests.map((request) => request.tag)).toEqual([
431 WS_METHODS.serverUpdateServerWithProgress,
432 ]);
433 expect(stages).toEqual(["downloading", "resuming"]);
434 expect(result.targetVersion).toBe("0.0.46");
435 expect(calls).toEqual(["compatibility:clear", "enabled:true"]);
436 }),
437 );
438});