Open History to see the last commit
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 }
111}
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("refuses a host that cannot update itself without opening a socket", () =>
208 Effect.gen(function* () {
209 const manual = {
210 ...descriptor(undefined, "0.0.45"),
211 capabilities: { repositoryIdentity: true },
212 };
213 let opened = false;
214 const error = yield* Effect.flip(
215 updateOutdatedHost(TARGET.environmentId, { targetVersion: "0.0.46" }, () => Effect.void),
216 ).pipe(
217 Effect.provide(
218 Layer.mergeAll(
219 Layer.succeed(
220 EnvironmentRegistry.EnvironmentRegistry,
221 EnvironmentRegistry.EnvironmentRegistry.of({
222 entries: yield* SubscriptionRef.make<
223 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
224 >(
225 new Map([
226 [
227 TARGET.environmentId,
228 { target: TARGET, profile: Option.none(), enabled: false },
229 ],
230 ]),
231 ),
232 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
233 ),
234 Layer.succeed(
235 ConnectionResolver.ConnectionResolver,
236 ConnectionResolver.ConnectionResolver.of({
237 prepare: () => Effect.die(new Error("unused")),
238 prepareForUpdate: () =>
239 Effect.succeed({
240 descriptor: manual,
241 prepared: {
242 environmentId: TARGET.environmentId,
243 label: TARGET.label,
244 httpBaseUrl: TARGET.httpBaseUrl,
245 socketUrl: "wss://build.example.test/ws",
246 httpAuthorization: null,
247 target: TARGET,
248 },
249 }),
250 }),
251 ),
252 Layer.succeed(
253 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
254 RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
255 state: yield* SubscriptionRef.make(
256 RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
257 ),
258 refresh: Effect.void,
259 }),
260 ),
261 Layer.succeed(
262 HttpClient.HttpClient,
263 HttpClient.make(() => Effect.die(new Error("unused"))),
264 ),
265 Layer.succeed(Socket.WebSocketConstructor, () => {
266 opened = true;
267 throw new Error("unused");
268 }),
269 ),
270 ),
271 );
272 expect(error).toMatchObject({ _tag: "OutdatedHostUpdateError" });
273 expect(opened).toBe(false);
274 }),
275 );
276});