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

registry.test.ts

941 lines35.2 KB

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