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

outdatedHostUpdate.test.ts

317 lines11.6 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.serverUpdateServer) return;
128 this.onUpdate();
129 queueMicrotask(() =>
130 this.emit({
131 type: "message",
132 data: encodeJson({
133 _tag: "Exit",
134 requestId: message.id,
135 exit: {
136 _tag: "Success",
137 value: { targetVersion: "0.0.46", method: "boot-service", updateId: "update-1" },
138 },
139 }),
140 }),
141 );
142 }
143​
144 close() {
145 this.readyState = 3;
146 this.emit({ type: "close" });
147 }
148​
149 private emit(event: { readonly type: string; readonly data?: unknown }) {
150 for (const listener of this.listeners.get(event.type) ?? []) listener(event);
151 }
153​
154describe("updateOutdatedHost", () => {
155 it.effect("updates a protocol-1 host over a bare socket, then switches it back on", () =>
156 Effect.gen(function* () {
157 const blocked = orchestrationProtocolCompatibilityError(descriptor(undefined, "0.0.45"));
158 expect(blocked).toMatchObject({ serverUpdateRequired: true });
159​
160 const sockets: Array<OutdatedHostSocket> = [];
161 let served: ExecutionEnvironmentDescriptor = descriptor(undefined, "0.0.45");
162 const entries = yield* SubscriptionRef.make<
163 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
164 >(
165 new Map([
166 [
167 TARGET.environmentId,
168 {
169 target: TARGET,
170 profile: Option.none(),
171 enabled: false,
172 unsupportedReason: blocked?.message ?? "",
173 serverUpdateRequired: true,
174 },
175 ],
176 ]),
177 );
178 const calls: Array<string> = [];
179 const registry = EnvironmentRegistry.EnvironmentRegistry.of({
180 entries,
181 setCompatibility: (_environmentId: EnvironmentId, error: unknown) =>
182 Effect.sync(() => calls.push(`compatibility:${error === null ? "clear" : "block"}`)),
183 setEnabled: (_environmentId: EnvironmentId, enabled: boolean) =>
184 Effect.sync(() => calls.push(`enabled:${enabled}`)),
185 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
186 const resolver = ConnectionResolver.ConnectionResolver.of({
187 prepare: () => Effect.die(new Error("The update must bypass the protocol gate.")),
188 prepareForUpdate: () =>
189 Effect.sync(() => served).pipe(
190 Effect.map((current) => ({
191 descriptor: current,
192 prepared: {
193 environmentId: TARGET.environmentId,
194 label: TARGET.label,
195 httpBaseUrl: TARGET.httpBaseUrl,
196 socketUrl: "wss://build.example.test/ws?wsTicket=ticket",
197 httpAuthorization: null,
198 target: TARGET,
199 },
200 })),
201 ),
202 });
203 const httpClient = HttpClient.make((request) =>
204 Effect.sync(() =>
205 HttpClientResponse.fromWeb(request, new Response(encodeDescriptor(served))),
206 ),
207 );
208​
209 const result = yield* updateOutdatedHost(
210 TARGET.environmentId,
211 { targetVersion: "0.0.46" },
212 () => Effect.void,
213 ).pipe(
214 Effect.provide(
215 Layer.mergeAll(
216 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, registry),
217 Layer.succeed(ConnectionResolver.ConnectionResolver, resolver),
218 Layer.succeed(
219 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
220 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
221 state: yield* SubscriptionRef.make(
222 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
223 ),
224 refresh: Effect.void,
225 }),
226 ),
227 Layer.succeed(HttpClient.HttpClient, httpClient),
228 Layer.succeed(Socket.WebSocketConstructor, (url) => {
229 const socket = new OutdatedHostSocket(url, () => {
230 served = descriptor(ORCHESTRATION_PROTOCOL_VERSION, "0.0.46");
231 });
232 sockets.push(socket);
233 return socket as unknown as globalThis.WebSocket;
234 }),
235 ),
236 ),
237 );
238​
239 expect(sockets[0]?.url).not.toContain("orchestrationProtocol");
240 expect(sockets[0]?.requests.map((request) => request.tag)).toEqual([
241 WS_METHODS.serverUpdateServer,
242 ]);
243 expect(result.targetVersion).toBe("0.0.46");
244 expect(calls).toEqual(["compatibility:clear", "enabled:true"]);
245 }),
246 );
247​
248 it.effect("refuses a host that cannot update itself without opening a socket", () =>
249 Effect.gen(function* () {
250 const manual = {
251 ...descriptor(undefined, "0.0.45"),
252 capabilities: { repositoryIdentity: true },
253 };
254 let opened = false;
255 const error = yield* Effect.flip(
256 updateOutdatedHost(TARGET.environmentId, { targetVersion: "0.0.46" }, () => Effect.void),
257 ).pipe(
258 Effect.provide(
259 Layer.mergeAll(
260 Layer.succeed(
261 EnvironmentRegistry.EnvironmentRegistry,
262 EnvironmentRegistry.EnvironmentRegistry.of({
263 entries: yield* SubscriptionRef.make<
264 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
265 >(
266 new Map([
267 [
268 TARGET.environmentId,
269 { target: TARGET, profile: Option.none(), enabled: false },
270 ],
271 ]),
272 ),
273 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
274 ),
275 Layer.succeed(
276 ConnectionResolver.ConnectionResolver,
277 ConnectionResolver.ConnectionResolver.of({
278 prepare: () => Effect.die(new Error("unused")),
279 prepareForUpdate: () =>
280 Effect.succeed({
281 descriptor: manual,
282 prepared: {
283 environmentId: TARGET.environmentId,
284 label: TARGET.label,
285 httpBaseUrl: TARGET.httpBaseUrl,
286 socketUrl: "wss://build.example.test/ws",
287 httpAuthorization: null,
288 target: TARGET,
289 },
290 }),
291 }),
292 ),
293 Layer.succeed(
294 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
295 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
296 state: yield* SubscriptionRef.make(
297 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
298 ),
299 refresh: Effect.void,
300 }),
301 ),
302 Layer.succeed(
303 HttpClient.HttpClient,
304 HttpClient.make(() => Effect.die(new Error("unused"))),
305 ),
306 Layer.succeed(Socket.WebSocketConstructor, () => {
307 opened = true;
308 throw new Error("unused");
309 }),
310 ),
311 ),
312 );
313 expect(error).toMatchObject({ _tag: "OutdatedHostUpdateError" });
314 expect(opened).toBe(false);
315 }),
316 );
317});