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

registry.test.ts

940 lines35.2 KB

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