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

registry.test.ts

1,195 lines44.8 KB

1import {
2 type DesktopSshEnvironmentTarget,
3 EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5} from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as Context from "effect/Context";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Ref from "effect/Ref";
15import * as Result from "effect/Result";
16import * as Scheduler from "effect/Scheduler";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20​
21import * as ClientCapabilities from "../platform/capabilities.ts";
22import * as TokenStore from "../authorization/tokenStore.ts";
23import {
24 BearerConnectionCredential,
25 BearerConnectionProfile,
26 BearerConnectionRegistration,
27 type ConnectionRegistration,
28 PrimaryConnectionRegistration,
29 RelayConnectionRegistration,
30 SshConnectionProfile,
31 type ConnectionCredential,
32 type ConnectionProfile,
33} from "./catalog.ts";
34import * as Connectivity from "./connectivity.ts";
35import * as ConnectionCredentialStore from "./credentialStore.ts";
36import * as ConnectionDriver from "./driver.ts";
37import {
38 ConnectionTransientError,
39 BearerConnectionTarget,
40 PrimaryConnectionTarget,
41 RelayConnectionTarget,
42 SshConnectionTarget,
43 type ConnectionTarget,
44 type PreparedConnection,
45 type SupervisorConnectionState,
46} from "./model.ts";
47import * as Persistence from "../platform/persistence.ts";
48import * as ConnectionProfileStore from "./profileStore.ts";
49import * as EnvironmentRegistry from "./registry.ts";
50import {
51 GitHubRoutingPermissions,
52 makeGitHubRoutingPermissions,
53} from "./githubRoutingPermissions.ts";
54import * as RpcSession from "../rpc/session.ts";
55import * as EnvironmentSupervisor from "./supervisor.ts";
56import * as ConnectionWakeups from "./wakeups.ts";
57import { runDesktopCommitWithReconnectObserver } from "../state/server.ts";
58import { v2ShellSnapshot } from "../state/orchestrationV2TestFixtures.ts";
59​
60const TARGET = new PrimaryConnectionTarget({
61 environmentId: EnvironmentId.make("environment-1"),
62 label: "Test environment",
63 httpBaseUrl: "https://environment.example.test",
64 wsBaseUrl: "wss://environment.example.test",
65});
66const SECOND_TARGET = new PrimaryConnectionTarget({
67 environmentId: EnvironmentId.make("environment-2"),
68 label: "Second environment",
69 httpBaseUrl: "https://environment-2.example.test",
70 wsBaseUrl: "wss://environment-2.example.test",
71});
72​
73const PREPARED: PreparedConnection = {
74 environmentId: TARGET.environmentId,
75 label: TARGET.label,
76 httpBaseUrl: TARGET.httpBaseUrl,
77 socketUrl: "wss://environment.example.test/ws",
78 httpAuthorization: null,
79 target: TARGET,
80};
81​
82const RELAY_TARGET = new RelayConnectionTarget({
83 environmentId: EnvironmentId.make("environment-relay"),
84 label: "Relay environment",
85});
86const SECOND_RELAY_TARGET = new RelayConnectionTarget({
87 environmentId: EnvironmentId.make("environment-relay-2"),
88 label: "Second relay environment",
89});
90​
91const BEARER_TARGET = new BearerConnectionTarget({
92 environmentId: EnvironmentId.make("environment-bearer"),
93 label: "Bearer environment",
94 connectionId: "bearer-connection",
95});
96const BEARER_PROFILE = new BearerConnectionProfile({
97 connectionId: BEARER_TARGET.connectionId,
98 environmentId: BEARER_TARGET.environmentId,
99 label: BEARER_TARGET.label,
100 httpBaseUrl: "https://bearer.example.test",
101 wsBaseUrl: "wss://bearer.example.test",
102});
103const BEARER_CREDENTIAL = new BearerConnectionCredential({
104 token: "bearer-token",
105});
106​
107const SSH_TARGET: DesktopSshEnvironmentTarget = {
108 alias: "test",
109 hostname: "test.example.test",
110 username: "developer",
111 port: 22,
112};
113const SSH_CONNECTION = new SshConnectionTarget({
114 environmentId: EnvironmentId.make("environment-ssh"),
115 label: "SSH environment",
116 connectionId: "ssh-connection",
117});
118const SSH_PROFILE = new SshConnectionProfile({
119 connectionId: SSH_CONNECTION.connectionId,
120 environmentId: SSH_CONNECTION.environmentId,
121 label: SSH_CONNECTION.label,
122 target: SSH_TARGET,
123});
124​
125const CACHED_SNAPSHOT: OrchestrationV2ShellSnapshot = {
126 ...v2ShellSnapshot,
127 snapshotSequence: 1,
128};
129​
130interface SessionControl {
131 readonly closed: Deferred.Deferred<never, ConnectionTransientError>;
133​
134const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
135 initialTargets: ReadonlyArray<ConnectionTarget>,
136 initialProfiles: ReadonlyArray<ConnectionProfile> = [],
137 initialCredentials: ReadonlyArray<readonly [string, ConnectionCredential]> = [],
138 options?: {
139 readonly beforeSessionConnect?: (environmentId: EnvironmentId) => Effect.Effect<void>;
140 readonly beforeRegistrationRegister?: (
141 registration: ConnectionRegistration,
142 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
143 readonly beforeRegistrationRemove?: (
144 target: ConnectionTarget,
145 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
146 readonly initialDisabled?: ReadonlyArray<EnvironmentId>;
147 },
148) {
149 const storedTargets = yield* Ref.make(
150 new Map(initialTargets.map((target) => [target.environmentId, target])),
151 );
152 const shellCache = yield* Ref.make(new Map([[TARGET.environmentId, CACHED_SNAPSHOT]]));
153 const cacheClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]);
154 const ownedDataClears = yield* Ref.make<ReadonlyArray<EnvironmentId>>([]);
155 const sessions = yield* Ref.make<ReadonlyArray<SessionControl>>([]);
156 const releasedSessions = yield* Ref.make(0);
157 const storedProfiles = yield* Ref.make(
158 new Map(initialProfiles.map((profile) => [profile.connectionId, profile])),
159 );
160 const profileReadCount = yield* Ref.make(0);
161 const storedCredentials = yield* Ref.make(new Map(initialCredentials));
162 const storedRemoteTokens = yield* Ref.make(
163 new Map([
164 [
165 SSH_CONNECTION.environmentId,
166 new TokenStore.RemoteDpopAccessToken({
167 environmentId: SSH_CONNECTION.environmentId,
168 label: SSH_CONNECTION.label,
169 endpoint: {
170 httpBaseUrl: "https://ssh.example.test",
171 wsBaseUrl: "wss://ssh.example.test",
172 providerKind: "cloudflare_tunnel",
173 },
174 accessToken: "cached-token",
175 expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
176 dpopThumbprint: "thumbprint",
177 }),
178 ],
179 ]),
180 );
181 const disconnectedSshTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);
182​
183 const storedDisabled = yield* Ref.make<ReadonlySet<EnvironmentId>>(
184 new Set(options?.initialDisabled ?? []),
185 );
186 const targetStore = Persistence.ConnectionTargetStore.of({
187 list: Ref.get(storedTargets).pipe(Effect.map((targets) => [...targets.values()])),
188 listDisabled: Ref.get(storedDisabled).pipe(Effect.map((ids) => [...ids])),
189 });
190 const registrationStore = Persistence.ConnectionRegistrationStore.of({
191 register: (registration) =>
192 Effect.gen(function* () {
193 yield* options?.beforeRegistrationRegister?.(registration) ?? Effect.void;
194 yield* Ref.update(storedTargets, (current) => {
195 const next = new Map(current);
196 next.set(registration.target.environmentId, registration.target);
197 return next;
198 });
199 switch (registration._tag) {
200 case "RelayConnectionRegistration":
201 return;
202 case "BearerConnectionRegistration":
203 yield* Ref.update(storedProfiles, (current) => {
204 const next = new Map(current);
205 next.set(registration.profile.connectionId, registration.profile);
206 return next;
207 });
208 yield* Ref.update(storedCredentials, (current) => {
209 const next = new Map(current);
210 next.set(registration.target.connectionId, registration.credential);
211 return next;
212 });
213 return;
214 case "SshConnectionRegistration":
215 yield* Ref.update(storedProfiles, (current) => {
216 const next = new Map(current);
217 next.set(registration.profile.connectionId, registration.profile);
218 return next;
219 });
220 }
221 }),
222 remove: (target) =>
223 Effect.gen(function* () {
224 yield* options?.beforeRegistrationRemove?.(target) ?? Effect.void;
225 yield* Ref.update(storedTargets, (current) => {
226 const next = new Map(current);
227 next.delete(target.environmentId);
228 return next;
229 });
230 if (target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget") {
231 yield* Ref.update(storedProfiles, (current) => {
232 const next = new Map(current);
233 next.delete(target.connectionId);
234 return next;
235 });
236 yield* Ref.update(storedCredentials, (current) => {
237 const next = new Map(current);
238 next.delete(target.connectionId);
239 return next;
240 });
241 }
242 yield* Ref.update(storedRemoteTokens, (current) => {
243 const next = new Map(current);
244 next.delete(target.environmentId);
245 return next;
246 });
247 }),
248 setEnabled: (environmentId, enabled) =>
249 Ref.update(storedDisabled, (current) => {
250 const next = new Set(current);
251 if (enabled) {
252 next.delete(environmentId);
253 } else {
254 next.add(environmentId);
255 }
256 return next;
257 }),
258 });
259 const cacheStore = Persistence.EnvironmentCacheStore.of({
260 loadShell: (environmentId) =>
261 Ref.get(shellCache).pipe(
262 Effect.map((cache) => Option.fromUndefinedOr(cache.get(environmentId))),
263 ),
264 saveShell: (environmentId, snapshot) =>
265 Ref.update(shellCache, (current) => {
266 const next = new Map(current);
267 next.set(environmentId, snapshot);
268 return next;
269 }),
270 loadThread: (_environmentId, _threadId) => Effect.succeed(Option.none()),
271 saveThread: (_environmentId, _thread) => Effect.void,
272 removeThread: (_environmentId, _threadId) => Effect.void,
273 loadServerConfig: () => Effect.succeed(Option.none()),
274 saveServerConfig: () => Effect.void,
275 loadVcsRefs: () => Effect.succeed(Option.none()),
276 saveVcsRefs: () => Effect.void,
277 removeVcsRefs: () => Effect.void,
278 clearVcsRefs: () => Effect.void,
279 clear: (environmentId) =>
280 Ref.update(shellCache, (current) => {
281 const next = new Map(current);
282 next.delete(environmentId);
283 return next;
284 }).pipe(
285 Effect.andThen(
286 Ref.update(cacheClears, (environmentIds) => [...environmentIds, environmentId]),
287 ),
288 ),
289 });
290 const ownedDataCleanup = Persistence.EnvironmentOwnedDataCleanup.of({
291 clear: (environmentId) =>
292 Ref.update(ownedDataClears, (environmentIds) => [...environmentIds, environmentId]),
293 });
294 const networkStatus = yield* SubscriptionRef.make<"unknown" | "offline" | "online">("online");
295 const connectivity = Connectivity.Connectivity.of({
296 status: SubscriptionRef.get(networkStatus),
297 changes: SubscriptionRef.changes(networkStatus),
298 });
299 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
300 get: (connectionId) =>
301 Ref.update(profileReadCount, (count) => count + 1).pipe(
302 Effect.andThen(Ref.get(storedProfiles)),
303 Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))),
304 ),
305 put: (profile) =>
306 Ref.update(storedProfiles, (current) => {
307 const next = new Map(current);
308 next.set(profile.connectionId, profile);
309 return next;
310 }),
311 remove: (connectionId) =>
312 Ref.update(storedProfiles, (current) => {
313 const next = new Map(current);
314 next.delete(connectionId);
315 return next;
316 }),
317 });
318 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
319 get: (connectionId) =>
320 Ref.get(storedCredentials).pipe(
321 Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))),
322 ),
323 put: (connectionId, credential) =>
324 Ref.update(storedCredentials, (current) => {
325 const next = new Map(current);
326 next.set(connectionId, credential);
327 return next;
328 }),
329 remove: (connectionId) =>
330 Ref.update(storedCredentials, (current) => {
331 const next = new Map(current);
332 next.delete(connectionId);
333 return next;
334 }),
335 });
336 const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({
337 get: (environmentId) =>
338 Ref.get(storedRemoteTokens).pipe(
339 Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
340 ),
341 put: (token) =>
342 Ref.update(storedRemoteTokens, (current) => {
343 const next = new Map(current);
344 next.set(token.environmentId, token);
345 return next;
346 }),
347 remove: (environmentId) =>
348 Ref.update(storedRemoteTokens, (current) => {
349 const next = new Map(current);
350 next.delete(environmentId);
351 return next;
352 }),
353 });
354 const sshGateway = ClientCapabilities.SshEnvironmentGateway.of({
355 provision: () => Effect.die(new Error("SSH provisioning is not used.")),
356 prepare: () => Effect.die(new Error("SSH preparation is not used.")),
357 disconnect: (target) => Ref.update(disconnectedSshTargets, (current) => [...current, target]),
358 });
359 const driver = ConnectionDriver.ConnectionDriver.of({
360 connect: (entry, reportProgress) =>
361 Effect.gen(function* () {
362 const target = entry.target;
363 const prepared = {
364 ...PREPARED,
365 environmentId: target.environmentId,
366 label: target.label,
367 target,
368 };
369 yield* reportProgress({ stage: "preparing" });
370 yield* reportProgress({ stage: "opening", prepared });
371 yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void;
372 const closed = yield* Deferred.make<never, ConnectionTransientError>();
373 yield* Ref.update(sessions, (current) => [...current, { closed }]);
374 const session = yield* Effect.acquireRelease(
375 Effect.succeed({
376 client: {} as RpcSession.RpcSession["client"],
377 initialConfig: Effect.die(new Error("Config is not used by registry tests.")),
378 subscribeServerConfig: () =>
379 Stream.die(new Error("Config is not used by registry tests.")),
380 ready: Effect.void,
381 probe: Effect.void,
382 closed: Deferred.await(closed),
383 } satisfies RpcSession.RpcSession),
384 () => Ref.update(releasedSessions, (count) => count + 1),
385 );
386 yield* reportProgress({ stage: "synchronizing", prepared });
387 yield* session.ready;
388 return { prepared, session };
389 }),
390 });
391​
392 const cacheLayer = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore);
393 const layer = EnvironmentRegistry.layer.pipe(
394 Layer.provide(
395 Layer.mergeAll(
396 Layer.succeed(Persistence.ConnectionTargetStore, targetStore),
397 Layer.succeed(Persistence.ConnectionRegistrationStore, registrationStore),
398 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
399 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
400 Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
401 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, sshGateway),
402 Layer.succeed(Connectivity.Connectivity, connectivity),
403 Layer.succeed(
404 ConnectionWakeups.ConnectionWakeups,
405 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }),
406 ),
407 Layer.succeed(ConnectionDriver.ConnectionDriver, driver),
408 cacheLayer,
409 Layer.succeed(Persistence.EnvironmentOwnedDataCleanup, ownedDataCleanup),
410 ),
411 ),
412 );
413​
414 return {
415 layer,
416 storedTargets,
417 shellCache,
418 cacheClears,
419 ownedDataClears,
420 sessions,
421 releasedSessions,
422 storedProfiles,
423 profileReadCount,
424 storedCredentials,
425 storedRemoteTokens,
426 storedDisabled,
427 disconnectedSshTargets,
428 networkStatus,
429 };
430});
431​
432function awaitConnectionState(
433 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
434 environmentId: EnvironmentId,
435 predicate: (state: SupervisorConnectionState) => boolean,
436) {
437 return Effect.gen(function* () {
438 const current = yield* registry.state(environmentId);
439 if (predicate(current)) {
440 return current;
441 }
442 return yield* registry
443 .stateChanges(environmentId)
444 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
445 });
447​
448describe("EnvironmentRegistry", () => {
449 it.effect("replays connected state when arming a desktop commit observer", () =>
450 Effect.gen(function* () {
451 const harness = yield* makeHarness([TARGET]);
452​
453 yield* Effect.gen(function* () {
454 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
455 yield* registry.start;
456 yield* awaitConnectionState(
457 registry,
458 TARGET.environmentId,
459 (state) => state.phase === "connected",
460 );
461​
462 const commits = yield* Ref.make(0);
463 const result = yield* runDesktopCommitWithReconnectObserver(
464 registry.stateChanges(TARGET.environmentId),
465 Ref.update(commits, (count) => count + 1).pipe(
466 Effect.andThen(Effect.fail("commit refused")),
467 ),
468 ).pipe(Effect.flip, Effect.timeout("1 second"));
469​
470 expect(result).toBe("commit refused");
471 expect(yield* Ref.get(commits)).toBe(1);
472 }).pipe(Effect.provide(harness.layer), Effect.scoped);
473 }),
474 );
475​
476 it.effect("does not acquire a session after the registry scope has already closed", () =>
477 Effect.gen(function* () {
478 const harness = yield* makeHarness([TARGET]);
479 const registryScope = yield* Scope.make();
480 const context = yield* Layer.build(harness.layer).pipe(Scope.provide(registryScope));
481 const registry = Context.get(context, EnvironmentRegistry.EnvironmentRegistry);
482 const dispatcher = new Scheduler.MixedScheduler("sync", () => () => {}).makeDispatcher();
483 const scheduler: Scheduler.Scheduler = {
484 executionMode: "sync",
485 shouldYield: () => false,
486 makeDispatcher: () => dispatcher,
487 };
488​
489 yield* Scope.close(registryScope, Exit.void);
490 yield* registry.start.pipe(Effect.provideService(Scheduler.Scheduler, scheduler));
491 dispatcher.flush();
492​
493 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
494 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
495 }),
496 );
497​
498 it.effect("hydrates connection profiles into catalog entries", () =>
499 Effect.gen(function* () {
500 const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
501​
502 yield* Effect.gen(function* () {
503 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
504 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
505 SSH_CONNECTION.environmentId,
506 );
507​
508 expect(entry?.target).toEqual(SSH_CONNECTION);
509 expect(Option.getOrThrow(entry?.profile ?? Option.none())).toEqual(SSH_PROFILE);
510 }).pipe(Effect.provide(harness.layer), Effect.scoped);
511 }),
512 );
513​
514 it.effect("publishes network status changes independently of connection state", () =>
515 Effect.gen(function* () {
516 const harness = yield* makeHarness([]);
517​
518 yield* Effect.gen(function* () {
519 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
520 const offline = yield* Effect.forkChild(
521 SubscriptionRef.changes(registry.networkStatus).pipe(
522 Stream.filter((status) => status === "offline"),
523 Stream.runHead,
524 Effect.map(Option.getOrThrow),
525 ),
526 );
527​
528 yield* SubscriptionRef.set(harness.networkStatus, "offline");
529​
530 expect(yield* Fiber.join(offline)).toBe("offline");
531 expect(yield* SubscriptionRef.get(registry.networkStatus)).toBe("offline");
532 }).pipe(Effect.provide(harness.layer), Effect.scoped);
533 }),
534 );
535​
536 it.effect("starts persisted environments independently", () =>
537 Effect.gen(function* () {
538 const bothLoadsStarted = yield* Deferred.make<void>();
539 const releaseLoads = yield* Deferred.make<void>();
540 const loadCount = yield* Ref.make(0);
541 const harness = yield* makeHarness([TARGET, SECOND_TARGET], [], [], {
542 beforeSessionConnect: () =>
543 Ref.updateAndGet(loadCount, (count) => count + 1).pipe(
544 Effect.tap((count) =>
545 count === 2 ? Deferred.succeed(bothLoadsStarted, undefined) : Effect.void,
546 ),
547 Effect.andThen(Deferred.await(releaseLoads)),
548 ),
549 });
550​
551 yield* Effect.gen(function* () {
552 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
553 const start = yield* Effect.forkChild(registry.start);
554​
555 yield* Deferred.await(bothLoadsStarted).pipe(Effect.timeout("1 second"));
556 yield* Deferred.succeed(releaseLoads, undefined);
557 yield* Fiber.join(start);
558​
559 expect(yield* Ref.get(loadCount)).toBe(2);
560 }).pipe(Effect.provide(harness.layer), Effect.scoped);
561 }),
562 );
563​
564 it.effect("exposes the current RPC generation to late query subscribers", () =>
565 Effect.gen(function* () {
566 const harness = yield* makeHarness([TARGET]);
567 yield* Effect.gen(function* () {
568 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
569 yield* registry.start;
570 yield* awaitConnectionState(
571 registry,
572 TARGET.environmentId,
573 (state) => state.phase === "connected",
574 );
575​
576 const generation = yield* registry
577 .runStream(
578 TARGET.environmentId,
579 Stream.unwrap(
580 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
581 Effect.map((supervisor) =>
582 Stream.concat(
583 Stream.fromEffect(SubscriptionRef.get(supervisor.state)),
584 SubscriptionRef.changes(supervisor.state),
585 ).pipe(
586 Stream.filterMap((state) =>
587 state.phase === "connected"
588 ? Result.succeed(state.generation)
589 : Result.failVoid,
590 ),
591 Stream.changes,
592 ),
593 ),
594 ),
595 ),
596 )
597 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
598​
599 expect(generation).toBe(1);
600 }).pipe(Effect.provide(harness.layer), Effect.scoped);
601 }),
602 );
603​
604 it.effect("preserves cached data on connection failure and clears it on explicit removal", () =>
605 Effect.gen(function* () {
606 const harness = yield* makeHarness([TARGET]);
607 yield* Effect.gen(function* () {
608 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
609 yield* registry.start;
610 yield* awaitConnectionState(
611 registry,
612 TARGET.environmentId,
613 (state) => state.phase === "connected",
614 );
615 const controls = yield* Ref.get(harness.sessions);
616 expect(controls).toHaveLength(1);
617 const active = controls[0];
618 expect(active).toBeDefined();
619 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
620 CACHED_SNAPSHOT,
621 );
622​
623 const retryFiber = yield* Effect.forkChild(
624 awaitConnectionState(
625 registry,
626 TARGET.environmentId,
627 (state) => state.phase === "backoff",
628 ),
629 );
630 yield* Effect.yieldNow;
631 yield* Deferred.fail(
632 active!.closed,
633 new ConnectionTransientError({
634 reason: "transport",
635 detail: "Disconnected.",
636 }),
637 );
638 yield* Fiber.join(retryFiber);
639 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
640 CACHED_SNAPSHOT,
641 );
642​
643 yield* registry.remove(TARGET.environmentId);
644 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
645 expect((yield* Ref.get(harness.shellCache)).has(TARGET.environmentId)).toBe(false);
646 expect(yield* Ref.get(harness.cacheClears)).toEqual([TARGET.environmentId]);
647 expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(
648 false,
649 );
650 }).pipe(Effect.provide(harness.layer));
651 }),
652 );
653​
654 it.effect("persists and starts a newly registered environment", () =>
655 Effect.gen(function* () {
656 const harness = yield* makeHarness([]);
657​
658 yield* Effect.gen(function* () {
659 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
660 yield* registry.register(new RelayConnectionRegistration({ target: RELAY_TARGET }));
661 yield* awaitConnectionState(
662 registry,
663 RELAY_TARGET.environmentId,
664 (state) => state.phase === "connected",
665 );
666​
667 expect((yield* Ref.get(harness.storedTargets)).get(RELAY_TARGET.environmentId)).toEqual(
668 RELAY_TARGET,
669 );
670 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
671 }).pipe(Effect.provide(harness.layer));
672 }),
673 );
674​
675 it.effect("switching an environment off disconnects it and persists the flag", () =>
676 Effect.gen(function* () {
677 const harness = yield* makeHarness([RELAY_TARGET]);
678​
679 yield* Effect.gen(function* () {
680 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
681 yield* registry.start;
682 yield* awaitConnectionState(
683 registry,
684 RELAY_TARGET.environmentId,
685 (state) => state.phase === "connected",
686 );
687​
688 yield* registry.setEnabled(RELAY_TARGET.environmentId, false);
689 yield* awaitConnectionState(
690 registry,
691 RELAY_TARGET.environmentId,
692 (state) => state.phase === "available",
693 );
694​
695 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
696 RELAY_TARGET.environmentId,
697 );
698 expect(entry?.enabled).toBe(false);
699 expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(true);
700 expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
701 expect(yield* Ref.get(harness.releasedSessions)).toBe(1);
702​
703 yield* registry.setEnabled(RELAY_TARGET.environmentId, true);
704 yield* awaitConnectionState(
705 registry,
706 RELAY_TARGET.environmentId,
707 (state) => state.phase === "connected",
708 );
709 expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(
710 false,
711 );
712 }).pipe(Effect.provide(harness.layer));
713 }),
714 );
715​
716 it.effect("re-registering a switched-off environment keeps it off", () =>
717 Effect.gen(function* () {
718 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
719 initialDisabled: [RELAY_TARGET.environmentId],
720 });
721​
722 yield* Effect.gen(function* () {
723 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
724 yield* registry.start;
725 yield* registry.register(
726 new RelayConnectionRegistration({
727 target: new RelayConnectionTarget({ ...RELAY_TARGET, label: "Renamed" }),
728 }),
729 );
730 yield* Effect.yieldNow;
731​
732 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
733 RELAY_TARGET.environmentId,
734 );
735 expect(entry?.target.label).toBe("Renamed");
736 expect(entry?.enabled).toBe(false);
737 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
738 }).pipe(Effect.provide(harness.layer));
739 }),
740 );
741​
742 it.effect("switching an SSH environment off tears down its managed backend", () =>
743 Effect.gen(function* () {
744 const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
745​
746 yield* Effect.gen(function* () {
747 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
748 yield* registry.start;
749 yield* awaitConnectionState(
750 registry,
751 SSH_CONNECTION.environmentId,
752 (state) => state.phase === "connected",
753 );
754​
755 yield* registry.setEnabled(SSH_CONNECTION.environmentId, false);
756 yield* awaitConnectionState(
757 registry,
758 SSH_CONNECTION.environmentId,
759 (state) => state.phase === "available",
760 );
761​
762 expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
763 expect((yield* Ref.get(harness.storedTargets)).has(SSH_CONNECTION.environmentId)).toBe(
764 true,
765 );
766 }).pipe(Effect.provide(harness.layer));
767 }),
768 );
769​
770 it.effect("does not connect a persisted environment that was switched off", () =>
771 Effect.gen(function* () {
772 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
773 initialDisabled: [RELAY_TARGET.environmentId],
774 });
775​
776 yield* Effect.gen(function* () {
777 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
778 yield* registry.start;
779 yield* Effect.yieldNow;
780​
781 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
782 RELAY_TARGET.environmentId,
783 );
784 expect(entry?.enabled).toBe(false);
785 expect((yield* registry.state(RELAY_TARGET.environmentId)).phase).toBe("available");
786 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
787 }).pipe(Effect.provide(harness.layer));
788 }),
789 );
790​
791 it.effect("moves durable streams to a replacement supervisor", () =>
792 Effect.gen(function* () {
793 const replacement = new RelayConnectionTarget({
794 environmentId: RELAY_TARGET.environmentId,
795 label: "Replacement relay environment",
796 });
797 const harness = yield* makeHarness([RELAY_TARGET]);
798​
799 yield* Effect.gen(function* () {
800 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
801 const firstObserved = yield* Deferred.make<void>();
802 const secondObserved = yield* Deferred.make<void>();
803 const labels = yield* Ref.make<ReadonlyArray<string>>([]);
804 yield* registry.start;
805 yield* awaitConnectionState(
806 registry,
807 RELAY_TARGET.environmentId,
808 (state) => state.phase === "connected",
809 );
810​
811 const subscription = yield* Effect.forkChild(
812 registry
813 .followStream(
814 RELAY_TARGET.environmentId,
815 Stream.unwrap(
816 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
817 Effect.map((supervisor) =>
818 Stream.concat(Stream.succeed(supervisor.target.label), Stream.never),
819 ),
820 ),
821 ),
822 )
823 .pipe(
824 Stream.tap((label) =>
825 Ref.updateAndGet(labels, (current) => [...current, label]).pipe(
826 Effect.flatMap((current) =>
827 current.length === 1
828 ? Deferred.succeed(firstObserved, undefined)
829 : Deferred.succeed(secondObserved, undefined),
830 ),
831 ),
832 ),
833 Stream.runDrain,
834 ),
835 );
836​
837 yield* Deferred.await(firstObserved).pipe(Effect.timeout("1 second"));
838 yield* registry.register(new RelayConnectionRegistration({ target: replacement }));
839 yield* Deferred.await(secondObserved).pipe(Effect.timeout("1 second"));
840 yield* Fiber.interrupt(subscription);
841​
842 expect(yield* Ref.get(labels)).toEqual([RELAY_TARGET.label, replacement.label]);
843 }).pipe(Effect.provide(harness.layer), Effect.scoped);
844 }),
845 );
846​
847 it.effect("ignores retry signals for environments that are no longer registered", () =>
848 Effect.gen(function* () {
849 const harness = yield* makeHarness([]);
850​
851 yield* Effect.gen(function* () {
852 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
853 yield* registry.retryNow(EnvironmentId.make("removed-environment"));
854 }).pipe(Effect.provide(harness.layer), Effect.scoped);
855 }),
856 );
857​
858 it.effect("removes all relay-owned data without touching non-cloud connections", () =>
859 Effect.gen(function* () {
860 const harness = yield* makeHarness(
861 [RELAY_TARGET, SECOND_RELAY_TARGET, BEARER_TARGET],
862 [BEARER_PROFILE],
863 [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]],
864 );
865​
866 yield* Effect.gen(function* () {
867 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
868 yield* registry.removeRelayEnvironments();
869​
870 const targets = yield* Ref.get(harness.storedTargets);
871 expect(targets.has(RELAY_TARGET.environmentId)).toBe(false);
872 expect(targets.has(SECOND_RELAY_TARGET.environmentId)).toBe(false);
873 expect(targets.get(BEARER_TARGET.environmentId)).toEqual(BEARER_TARGET);
874 expect(yield* Ref.get(harness.cacheClears)).toEqual(
875 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
876 );
877 expect(yield* Ref.get(harness.ownedDataClears)).toEqual(
878 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
879 );
880 expect(
881 (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId),
882 ).toBe(true);
883 }).pipe(Effect.provide(harness.layer), Effect.scoped);
884 }),
885 );
886​
887 it.effect("keeps the runtime registered when durable removal fails", () =>
888 Effect.gen(function* () {
889 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
890 beforeRegistrationRemove: () =>
891 Effect.fail(
892 new Persistence.ConnectionPersistenceError({
893 operation: "remove-connection",
894 message: "Storage is unavailable.",
895 }),
896 ),
897 });
898​
899 yield* Effect.gen(function* () {
900 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
901 yield* registry.start;
902 yield* awaitConnectionState(
903 registry,
904 RELAY_TARGET.environmentId,
905 (state) => state.phase === "connected",
906 );
907​
908 const error = yield* Effect.flip(registry.removeRelayEnvironments());
909​
910 expect(error._tag).toBe("ConnectionPersistenceError");
911 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
912 expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
913 true,
914 );
915 expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
916 expect(yield* Ref.get(harness.cacheClears)).toEqual([]);
917 expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]);
918 }).pipe(Effect.provide(harness.layer), Effect.scoped);
919 }),
920 );
921​
922 it.effect("starts a newly paired bearer environment without re-reading its profile", () =>
923 Effect.gen(function* () {
924 const harness = yield* makeHarness([]);
925​
926 yield* Effect.gen(function* () {
927 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
928 yield* registry.register(
929 new BearerConnectionRegistration({
930 target: BEARER_TARGET,
931 profile: BEARER_PROFILE,
932 credential: BEARER_CREDENTIAL,
933 }),
934 );
935 yield* awaitConnectionState(
936 registry,
937 BEARER_TARGET.environmentId,
938 (state) => state.phase === "connected",
939 );
940​
941 expect(yield* Ref.get(harness.profileReadCount)).toBe(0);
942 expect(
943 Option.getOrThrow(
944 (yield* SubscriptionRef.get(registry.entries)).get(BEARER_TARGET.environmentId)
945 ?.profile ?? Option.none(),
946 ),
947 ).toEqual(BEARER_PROFILE);
948 }).pipe(Effect.provide(harness.layer), Effect.scoped);
949 }),
950 );
951​
952 it.effect("starts platform environments without persisting or removing them", () =>
953 Effect.gen(function* () {
954 const harness = yield* makeHarness([]);
955​
956 yield* Effect.gen(function* () {
957 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
958 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
959 yield* awaitConnectionState(
960 registry,
961 TARGET.environmentId,
962 (state) => state.phase === "connected",
963 );
964​
965 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
966 expect(
967 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
968 ).toEqual(TARGET);
969​
970 const error = yield* Effect.flip(registry.remove(TARGET.environmentId));
971 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
972 expect(
973 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
974 ).toEqual(TARGET);
975 }).pipe(Effect.provide(harness.layer));
976 }),
977 );
978​
979 it.effect("gives a primary platform registration precedence over persisted registrations", () =>
980 Effect.gen(function* () {
981 const shadowedTarget = new RelayConnectionTarget({
982 environmentId: TARGET.environmentId,
983 label: "Shadowed relay environment",
984 });
985 const harness = yield* makeHarness([shadowedTarget]);
986 const permissions = yield* makeGitHubRoutingPermissions({
987 read: Effect.succeed([]),
988 write: () => Effect.void,
989 });
990 const shadowedEntry = { target: shadowedTarget, profile: Option.none(), enabled: true };
991 yield* permissions.set(shadowedEntry, "read-write");
992​
993 yield* Effect.gen(function* () {
994 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
995 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
996 expect(yield* permissions.get(shadowedEntry)).toBe("off");
997​
998 expect(
999 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1000 ).toEqual(TARGET);
1001 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
1002​
1003 yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget }));
1004​
1005 expect(
1006 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1007 ).toEqual(TARGET);
1008 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
1009 }).pipe(
1010 Effect.provide(harness.layer),
1011 Effect.provideService(GitHubRoutingPermissions, permissions),
1012 Effect.scoped,
1013 );
1014 }),
1015 );
1016​
1017 it.effect("rechecks platform ownership after waiting for the environment lease", () =>
1018 Effect.gen(function* () {
1019 const registrationStarted = yield* Deferred.make<void>();
1020 const continueRegistration = yield* Deferred.make<void>();
1021 const shadowedTarget = new RelayConnectionTarget({
1022 environmentId: TARGET.environmentId,
1023 label: "Shadowed relay environment",
1024 });
1025 const harness = yield* makeHarness([], [], [], {
1026 beforeRegistrationRegister: () =>
1027 Deferred.succeed(registrationStarted, undefined).pipe(
1028 Effect.andThen(Deferred.await(continueRegistration)),
1029 ),
1030 });
1031​
1032 yield* Effect.gen(function* () {
1033 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1034 const persistedRegistration = yield* registry
1035 .register(new RelayConnectionRegistration({ target: shadowedTarget }))
1036 .pipe(Effect.forkChild({ startImmediately: true }));
1037 yield* Deferred.await(registrationStarted);
1038​
1039 const platformRegistration = yield* registry
1040 .registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }))
1041 .pipe(Effect.forkChild({ startImmediately: true }));
1042 yield* Effect.yieldNow;
1043 const removal = yield* Effect.flip(registry.remove(TARGET.environmentId)).pipe(
1044 Effect.forkChild({ startImmediately: true }),
1045 );
1046​
1047 yield* Deferred.succeed(continueRegistration, undefined);
1048 yield* Fiber.join(persistedRegistration);
1049 yield* Fiber.join(platformRegistration);
1050 const error = yield* Fiber.join(removal);
1051​
1052 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
1053 expect(
1054 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1055 ).toEqual(TARGET);
1056 }).pipe(Effect.provide(harness.layer), Effect.scoped);
1057 }),
1058 );
1059​
1060 it.effect("does not reacquire a runtime while its registration is being removed", () =>
1061 Effect.gen(function* () {
1062 const removalStarted = yield* Deferred.make<void>();
1063 const continueRemoval = yield* Deferred.make<void>();
1064 const harness = yield* makeHarness([TARGET], [], [], {
1065 beforeRegistrationRemove: () =>
1066 Deferred.succeed(removalStarted, undefined).pipe(
1067 Effect.andThen(Deferred.await(continueRemoval)),
1068 ),
1069 });
1070​
1071 yield* Effect.gen(function* () {
1072 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1073 yield* registry.start;
1074 yield* awaitConnectionState(
1075 registry,
1076 TARGET.environmentId,
1077 (state) => state.phase === "connected",
1078 );
1079​
1080 const removal = yield* Effect.forkChild(registry.remove(TARGET.environmentId));
1081 yield* Deferred.await(removalStarted);
1082​
1083 const stateLookup = yield* Effect.forkChild(
1084 Effect.flip(registry.state(TARGET.environmentId)),
1085 );
1086 yield* Effect.yieldNow;
1087 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
1088​
1089 yield* Deferred.succeed(continueRemoval, undefined);
1090 yield* Fiber.join(removal);
1091 const error = yield* Fiber.join(stateLookup);
1092 expect(error._tag).toBe("EnvironmentNotRegisteredError");
1093 }).pipe(Effect.provide(harness.layer), Effect.scoped);
1094 }),
1095 );
1096​
1097 it.effect("retains a healthy runtime when the platform repeats an identical registration", () =>
1098 Effect.gen(function* () {
1099 const harness = yield* makeHarness([]);
1100 let failWrites = false;
1101 const permissions = yield* makeGitHubRoutingPermissions({
1102 read: Effect.succeed([]),
1103 write: () =>
1104 failWrites
1105 ? Effect.fail(
1106 new ConnectionTransientError({
1107 reason: "remote-unavailable",
1108 detail: "Storage unavailable",
1109 }),
1111 : Effect.void,
1112 });
1113 const entry = { target: TARGET, profile: Option.none(), enabled: true };
1114​
1115 yield* Effect.gen(function* () {
1116 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1117 const registration = new PrimaryConnectionRegistration({ target: TARGET });
1118 yield* registry.registerPlatform(registration);
1119 yield* awaitConnectionState(
1120 registry,
1121 TARGET.environmentId,
1122 (state) => state.phase === "connected",
1123 );
1124 yield* permissions.set(entry, "read-write");
1125​
1126 yield* registry.registerPlatform(registration);
1127​
1128 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
1129 expect(yield* permissions.get(entry)).toBe("read-write");
1130​
1131 const changedTarget = new PrimaryConnectionTarget({
1132 ...TARGET,
1133 httpBaseUrl: "https://changed.example.test",
1134 });
1135 failWrites = true;
1136 yield* registry.registerPlatform(
1137 new PrimaryConnectionRegistration({ target: changedTarget }),
1138 );
1139 expect(
1140 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
1141 ).toEqual(TARGET);
1142 yield* registry.reconcilePlatform([]);
1143 expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(true);
1144​
1145 failWrites = false;
1146 yield* registry.registerPlatform(
1147 new PrimaryConnectionRegistration({ target: changedTarget }),
1148 );
1149 expect(yield* permissions.get(entry)).toBe("off");
1150 yield* registry.registerPlatform(registration);
1151 expect(yield* permissions.get(entry)).toBe("off");
1152 yield* permissions.set(entry, "read-write");
1153 yield* registry.reconcilePlatform([]);
1154 yield* registry.registerPlatform(registration);
1155 expect(yield* permissions.get(entry)).toBe("off");
1156 }).pipe(
1157 Effect.provide(harness.layer),
1158 Effect.provideService(GitHubRoutingPermissions, permissions),
1159 Effect.scoped,
1160 );
1161 }),
1162 );
1163​
1164 it.effect("removes all owned SSH state only on explicit removal", () =>
1165 Effect.gen(function* () {
1166 const harness = yield* makeHarness(
1167 [SSH_CONNECTION],
1168 [SSH_PROFILE],
1171 SSH_CONNECTION.connectionId,
1172 new BearerConnectionCredential({ token: "temporary-token" }),
1173 ],
1174 ],
1175 );
1176​
1177 yield* Effect.gen(function* () {
1178 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
1179 yield* registry.start;
1180 yield* registry.remove(SSH_CONNECTION.environmentId);
1181​
1182 expect((yield* Ref.get(harness.storedProfiles)).has(SSH_CONNECTION.connectionId)).toBe(
1183 false,
1184 );
1185 expect((yield* Ref.get(harness.storedCredentials)).has(SSH_CONNECTION.connectionId)).toBe(
1186 false,
1187 );
1188 expect((yield* Ref.get(harness.storedRemoteTokens)).has(SSH_CONNECTION.environmentId)).toBe(
1189 false,
1190 );
1191 expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
1192 }).pipe(Effect.provide(harness.layer));
1193 }),
1194 );
1195});