Open History to see the last commit
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>;
124}
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 loadServerConfig: () => Effect.succeed(Option.none()),
251 saveServerConfig: () => Effect.void,
252 loadVcsRefs: () => Effect.succeed(Option.none()),
253 saveVcsRefs: () => Effect.void,
254 clear: (environmentId) =>
255 Ref.update(shellCache, (current) => {
256 const next = new Map(current);
257 next.delete(environmentId);
258 return next;
259 }).pipe(
260 Effect.andThen(
261 Ref.update(cacheClears, (environmentIds) => [...environmentIds, environmentId]),
262 ),
263 ),
264 });
265 const ownedDataCleanup = Persistence.EnvironmentOwnedDataCleanup.of({
266 clear: (environmentId) =>
267 Ref.update(ownedDataClears, (environmentIds) => [...environmentIds, environmentId]),
268 });
269 const networkStatus = yield* SubscriptionRef.make<"unknown" | "offline" | "online">("online");
270 const connectivity = Connectivity.Connectivity.of({
271 status: SubscriptionRef.get(networkStatus),
272 changes: SubscriptionRef.changes(networkStatus),
273 });
274 const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({
275 get: (connectionId) =>
276 Ref.update(profileReadCount, (count) => count + 1).pipe(
277 Effect.andThen(Ref.get(storedProfiles)),
278 Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))),
279 ),
280 put: (profile) =>
281 Ref.update(storedProfiles, (current) => {
282 const next = new Map(current);
283 next.set(profile.connectionId, profile);
284 return next;
285 }),
286 remove: (connectionId) =>
287 Ref.update(storedProfiles, (current) => {
288 const next = new Map(current);
289 next.delete(connectionId);
290 return next;
291 }),
292 });
293 const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({
294 get: (connectionId) =>
295 Ref.get(storedCredentials).pipe(
296 Effect.map((current) => Option.fromUndefinedOr(current.get(connectionId))),
297 ),
298 put: (connectionId, credential) =>
299 Ref.update(storedCredentials, (current) => {
300 const next = new Map(current);
301 next.set(connectionId, credential);
302 return next;
303 }),
304 remove: (connectionId) =>
305 Ref.update(storedCredentials, (current) => {
306 const next = new Map(current);
307 next.delete(connectionId);
308 return next;
309 }),
310 });
311 const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({
312 get: (environmentId) =>
313 Ref.get(storedRemoteTokens).pipe(
314 Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
315 ),
316 put: (token) =>
317 Ref.update(storedRemoteTokens, (current) => {
318 const next = new Map(current);
319 next.set(token.environmentId, token);
320 return next;
321 }),
322 remove: (environmentId) =>
323 Ref.update(storedRemoteTokens, (current) => {
324 const next = new Map(current);
325 next.delete(environmentId);
326 return next;
327 }),
328 });
329 const sshGateway = ClientCapabilities.SshEnvironmentGateway.of({
330 provision: () => Effect.die(new Error("SSH provisioning is not used.")),
331 prepare: () => Effect.die(new Error("SSH preparation is not used.")),
332 disconnect: (target) => Ref.update(disconnectedSshTargets, (current) => [...current, target]),
333 });
334 const driver = ConnectionDriver.ConnectionDriver.of({
335 connect: (entry, reportProgress) =>
336 Effect.gen(function* () {
337 const target = entry.target;
338 const prepared = {
339 ...PREPARED,
340 environmentId: target.environmentId,
341 label: target.label,
342 target,
343 };
344 yield* reportProgress({ stage: "preparing" });
345 yield* reportProgress({ stage: "opening", prepared });
346 yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void;
347 const closed = yield* Deferred.make<never, ConnectionTransientError>();
348 yield* Ref.update(sessions, (current) => [...current, { closed }]);
349 const session = yield* Effect.acquireRelease(
350 Effect.succeed({
351 client: {} as RpcSession.RpcSession["client"],
352 initialConfig: Effect.die(new Error("Config is not used by registry tests.")),
353 ready: Effect.void,
354 probe: Effect.void,
355 closed: Deferred.await(closed),
356 } satisfies RpcSession.RpcSession),
357 () => Ref.update(releasedSessions, (count) => count + 1),
358 );
359 yield* reportProgress({ stage: "synchronizing", prepared });
360 yield* session.ready;
361 return { prepared, session };
362 }),
363 });
364
365 const cacheLayer = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore);
366 const layer = EnvironmentRegistry.layer.pipe(
367 Layer.provide(
368 Layer.mergeAll(
369 Layer.succeed(Persistence.ConnectionTargetStore, targetStore),
370 Layer.succeed(Persistence.ConnectionRegistrationStore, registrationStore),
371 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
372 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
373 Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
374 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, sshGateway),
375 Layer.succeed(Connectivity.Connectivity, connectivity),
376 Layer.succeed(
377 ConnectionWakeups.ConnectionWakeups,
378 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }),
379 ),
380 Layer.succeed(ConnectionDriver.ConnectionDriver, driver),
381 cacheLayer,
382 Layer.succeed(Persistence.EnvironmentOwnedDataCleanup, ownedDataCleanup),
383 ),
384 ),
385 );
386
387 return {
388 layer,
389 storedTargets,
390 shellCache,
391 cacheClears,
392 ownedDataClears,
393 sessions,
394 releasedSessions,
395 storedProfiles,
396 profileReadCount,
397 storedCredentials,
398 storedRemoteTokens,
399 disconnectedSshTargets,
400 networkStatus,
401 };
402});
403
404function awaitConnectionState(
405 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
406 environmentId: EnvironmentId,
407 predicate: (state: SupervisorConnectionState) => boolean,
408) {
409 return Effect.gen(function* () {
410 const current = yield* registry.state(environmentId);
411 if (predicate(current)) {
412 return current;
413 }
414 return yield* registry
415 .stateChanges(environmentId)
416 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
417 });
418}
419
420describe("EnvironmentRegistry", () => {
421 it.effect("hydrates connection profiles into catalog entries", () =>
422 Effect.gen(function* () {
423 const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
424
425 yield* Effect.gen(function* () {
426 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
427 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
428 SSH_CONNECTION.environmentId,
429 );
430
431 expect(entry?.target).toEqual(SSH_CONNECTION);
432 expect(Option.getOrThrow(entry?.profile ?? Option.none())).toEqual(SSH_PROFILE);
433 }).pipe(Effect.provide(harness.layer), Effect.scoped);
434 }),
435 );
436
437 it.effect("publishes network status changes independently of connection state", () =>
438 Effect.gen(function* () {
439 const harness = yield* makeHarness([]);
440
441 yield* Effect.gen(function* () {
442 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
443 const offline = yield* Effect.forkChild(
444 SubscriptionRef.changes(registry.networkStatus).pipe(
445 Stream.filter((status) => status === "offline"),
446 Stream.runHead,
447 Effect.map(Option.getOrThrow),
448 ),
449 );
450
451 yield* SubscriptionRef.set(harness.networkStatus, "offline");
452
453 expect(yield* Fiber.join(offline)).toBe("offline");
454 expect(yield* SubscriptionRef.get(registry.networkStatus)).toBe("offline");
455 }).pipe(Effect.provide(harness.layer), Effect.scoped);
456 }),
457 );
458
459 it.effect("starts persisted environments independently", () =>
460 Effect.gen(function* () {
461 const bothLoadsStarted = yield* Deferred.make<void>();
462 const releaseLoads = yield* Deferred.make<void>();
463 const loadCount = yield* Ref.make(0);
464 const harness = yield* makeHarness([TARGET, SECOND_TARGET], [], [], {
465 beforeSessionConnect: () =>
466 Ref.updateAndGet(loadCount, (count) => count + 1).pipe(
467 Effect.tap((count) =>
468 count === 2 ? Deferred.succeed(bothLoadsStarted, undefined) : Effect.void,
469 ),
470 Effect.andThen(Deferred.await(releaseLoads)),
471 ),
472 });
473
474 yield* Effect.gen(function* () {
475 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
476 const start = yield* Effect.forkChild(registry.start);
477
478 yield* Deferred.await(bothLoadsStarted).pipe(Effect.timeout("1 second"));
479 yield* Deferred.succeed(releaseLoads, undefined);
480 yield* Fiber.join(start);
481
482 expect(yield* Ref.get(loadCount)).toBe(2);
483 }).pipe(Effect.provide(harness.layer), Effect.scoped);
484 }),
485 );
486
487 it.effect("exposes the current RPC generation to late query subscribers", () =>
488 Effect.gen(function* () {
489 const harness = yield* makeHarness([TARGET]);
490 yield* Effect.gen(function* () {
491 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
492 yield* registry.start;
493 yield* awaitConnectionState(
494 registry,
495 TARGET.environmentId,
496 (state) => state.phase === "connected",
497 );
498
499 const generation = yield* registry
500 .runStream(
501 TARGET.environmentId,
502 Stream.unwrap(
503 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
504 Effect.map((supervisor) =>
505 Stream.concat(
506 Stream.fromEffect(SubscriptionRef.get(supervisor.state)),
507 SubscriptionRef.changes(supervisor.state),
508 ).pipe(
509 Stream.filterMap((state) =>
510 state.phase === "connected"
511 ? Result.succeed(state.generation)
512 : Result.failVoid,
513 ),
514 Stream.changes,
515 ),
516 ),
517 ),
518 ),
519 )
520 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
521
522 expect(generation).toBe(1);
523 }).pipe(Effect.provide(harness.layer), Effect.scoped);
524 }),
525 );
526
527 it.effect("preserves cached data on connection failure and clears it on explicit removal", () =>
528 Effect.gen(function* () {
529 const harness = yield* makeHarness([TARGET]);
530 yield* Effect.gen(function* () {
531 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
532 yield* registry.start;
533 yield* awaitConnectionState(
534 registry,
535 TARGET.environmentId,
536 (state) => state.phase === "connected",
537 );
538 const controls = yield* Ref.get(harness.sessions);
539 expect(controls).toHaveLength(1);
540 const active = controls[0];
541 expect(active).toBeDefined();
542 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
543 CACHED_SNAPSHOT,
544 );
545
546 const retryFiber = yield* Effect.forkChild(
547 awaitConnectionState(
548 registry,
549 TARGET.environmentId,
550 (state) => state.phase === "backoff",
551 ),
552 );
553 yield* Effect.yieldNow;
554 yield* Deferred.fail(
555 active!.closed,
556 new ConnectionTransientError({
557 reason: "transport",
558 detail: "Disconnected.",
559 }),
560 );
561 yield* Fiber.join(retryFiber);
562 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
563 CACHED_SNAPSHOT,
564 );
565
566 yield* registry.remove(TARGET.environmentId);
567 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
568 expect((yield* Ref.get(harness.shellCache)).has(TARGET.environmentId)).toBe(false);
569 expect(yield* Ref.get(harness.cacheClears)).toEqual([TARGET.environmentId]);
570 expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(
571 false,
572 );
573 }).pipe(Effect.provide(harness.layer));
574 }),
575 );
576
577 it.effect("persists and starts a newly registered environment", () =>
578 Effect.gen(function* () {
579 const harness = yield* makeHarness([]);
580
581 yield* Effect.gen(function* () {
582 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
583 yield* registry.register(new RelayConnectionRegistration({ target: RELAY_TARGET }));
584 yield* awaitConnectionState(
585 registry,
586 RELAY_TARGET.environmentId,
587 (state) => state.phase === "connected",
588 );
589
590 expect((yield* Ref.get(harness.storedTargets)).get(RELAY_TARGET.environmentId)).toEqual(
591 RELAY_TARGET,
592 );
593 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
594 }).pipe(Effect.provide(harness.layer));
595 }),
596 );
597
598 it.effect("moves durable streams to a replacement supervisor", () =>
599 Effect.gen(function* () {
600 const replacement = new RelayConnectionTarget({
601 environmentId: RELAY_TARGET.environmentId,
602 label: "Replacement relay environment",
603 });
604 const harness = yield* makeHarness([RELAY_TARGET]);
605
606 yield* Effect.gen(function* () {
607 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
608 const firstObserved = yield* Deferred.make<void>();
609 const secondObserved = yield* Deferred.make<void>();
610 const labels = yield* Ref.make<ReadonlyArray<string>>([]);
611 yield* registry.start;
612 yield* awaitConnectionState(
613 registry,
614 RELAY_TARGET.environmentId,
615 (state) => state.phase === "connected",
616 );
617
618 const subscription = yield* Effect.forkChild(
619 registry
620 .followStream(
621 RELAY_TARGET.environmentId,
622 Stream.unwrap(
623 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
624 Effect.map((supervisor) =>
625 Stream.concat(Stream.succeed(supervisor.target.label), Stream.never),
626 ),
627 ),
628 ),
629 )
630 .pipe(
631 Stream.tap((label) =>
632 Ref.updateAndGet(labels, (current) => [...current, label]).pipe(
633 Effect.flatMap((current) =>
634 current.length === 1
635 ? Deferred.succeed(firstObserved, undefined)
636 : Deferred.succeed(secondObserved, undefined),
637 ),
638 ),
639 ),
640 Stream.runDrain,
641 ),
642 );
643
644 yield* Deferred.await(firstObserved).pipe(Effect.timeout("1 second"));
645 yield* registry.register(new RelayConnectionRegistration({ target: replacement }));
646 yield* Deferred.await(secondObserved).pipe(Effect.timeout("1 second"));
647 yield* Fiber.interrupt(subscription);
648
649 expect(yield* Ref.get(labels)).toEqual([RELAY_TARGET.label, replacement.label]);
650 }).pipe(Effect.provide(harness.layer), Effect.scoped);
651 }),
652 );
653
654 it.effect("ignores retry signals for environments that are no longer registered", () =>
655 Effect.gen(function* () {
656 const harness = yield* makeHarness([]);
657
658 yield* Effect.gen(function* () {
659 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
660 yield* registry.retryNow(EnvironmentId.make("removed-environment"));
661 }).pipe(Effect.provide(harness.layer), Effect.scoped);
662 }),
663 );
664
665 it.effect("removes all relay-owned data without touching non-cloud connections", () =>
666 Effect.gen(function* () {
667 const harness = yield* makeHarness(
668 [RELAY_TARGET, SECOND_RELAY_TARGET, BEARER_TARGET],
669 [BEARER_PROFILE],
670 [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]],
671 );
672
673 yield* Effect.gen(function* () {
674 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
675 yield* registry.removeRelayEnvironments();
676
677 const targets = yield* Ref.get(harness.storedTargets);
678 expect(targets.has(RELAY_TARGET.environmentId)).toBe(false);
679 expect(targets.has(SECOND_RELAY_TARGET.environmentId)).toBe(false);
680 expect(targets.get(BEARER_TARGET.environmentId)).toEqual(BEARER_TARGET);
681 expect(yield* Ref.get(harness.cacheClears)).toEqual(
682 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
683 );
684 expect(yield* Ref.get(harness.ownedDataClears)).toEqual(
685 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
686 );
687 expect(
688 (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId),
689 ).toBe(true);
690 }).pipe(Effect.provide(harness.layer), Effect.scoped);
691 }),
692 );
693
694 it.effect("keeps the runtime registered when durable removal fails", () =>
695 Effect.gen(function* () {
696 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
697 beforeRegistrationRemove: () =>
698 Effect.fail(
699 new Persistence.ConnectionPersistenceError({
700 operation: "remove-connection",
701 message: "Storage is unavailable.",
702 }),
703 ),
704 });
705
706 yield* Effect.gen(function* () {
707 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
708 yield* registry.start;
709 yield* awaitConnectionState(
710 registry,
711 RELAY_TARGET.environmentId,
712 (state) => state.phase === "connected",
713 );
714
715 const error = yield* Effect.flip(registry.removeRelayEnvironments());
716
717 expect(error._tag).toBe("ConnectionPersistenceError");
718 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
719 expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
720 true,
721 );
722 expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
723 expect(yield* Ref.get(harness.cacheClears)).toEqual([]);
724 expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]);
725 }).pipe(Effect.provide(harness.layer), Effect.scoped);
726 }),
727 );
728
729 it.effect("starts a newly paired bearer environment without re-reading its profile", () =>
730 Effect.gen(function* () {
731 const harness = yield* makeHarness([]);
732
733 yield* Effect.gen(function* () {
734 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
735 yield* registry.register(
736 new BearerConnectionRegistration({
737 target: BEARER_TARGET,
738 profile: BEARER_PROFILE,
739 credential: BEARER_CREDENTIAL,
740 }),
741 );
742 yield* awaitConnectionState(
743 registry,
744 BEARER_TARGET.environmentId,
745 (state) => state.phase === "connected",
746 );
747
748 expect(yield* Ref.get(harness.profileReadCount)).toBe(0);
749 expect(
750 Option.getOrThrow(
751 (yield* SubscriptionRef.get(registry.entries)).get(BEARER_TARGET.environmentId)
752 ?.profile ?? Option.none(),
753 ),
754 ).toEqual(BEARER_PROFILE);
755 }).pipe(Effect.provide(harness.layer), Effect.scoped);
756 }),
757 );
758
759 it.effect("starts platform environments without persisting or removing them", () =>
760 Effect.gen(function* () {
761 const harness = yield* makeHarness([]);
762
763 yield* Effect.gen(function* () {
764 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
765 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
766 yield* awaitConnectionState(
767 registry,
768 TARGET.environmentId,
769 (state) => state.phase === "connected",
770 );
771
772 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
773 expect(
774 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
775 ).toEqual(TARGET);
776
777 const error = yield* Effect.flip(registry.remove(TARGET.environmentId));
778 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
779 expect(
780 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
781 ).toEqual(TARGET);
782 }).pipe(Effect.provide(harness.layer));
783 }),
784 );
785
786 it.effect("gives a primary platform registration precedence over persisted registrations", () =>
787 Effect.gen(function* () {
788 const shadowedTarget = new RelayConnectionTarget({
789 environmentId: TARGET.environmentId,
790 label: "Shadowed relay environment",
791 });
792 const harness = yield* makeHarness([shadowedTarget]);
793
794 yield* Effect.gen(function* () {
795 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
796 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
797
798 expect(
799 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
800 ).toEqual(TARGET);
801 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
802
803 yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget }));
804
805 expect(
806 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
807 ).toEqual(TARGET);
808 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
809 }).pipe(Effect.provide(harness.layer), Effect.scoped);
810 }),
811 );
812
813 it.effect("rechecks platform ownership after waiting for the environment lease", () =>
814 Effect.gen(function* () {
815 const registrationStarted = yield* Deferred.make<void>();
816 const continueRegistration = yield* Deferred.make<void>();
817 const shadowedTarget = new RelayConnectionTarget({
818 environmentId: TARGET.environmentId,
819 label: "Shadowed relay environment",
820 });
821 const harness = yield* makeHarness([], [], [], {
822 beforeRegistrationRegister: () =>
823 Deferred.succeed(registrationStarted, undefined).pipe(
824 Effect.andThen(Deferred.await(continueRegistration)),
825 ),
826 });
827
828 yield* Effect.gen(function* () {
829 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
830 const persistedRegistration = yield* registry
831 .register(new RelayConnectionRegistration({ target: shadowedTarget }))
832 .pipe(Effect.forkChild({ startImmediately: true }));
833 yield* Deferred.await(registrationStarted);
834
835 const platformRegistration = yield* registry
836 .registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }))
837 .pipe(Effect.forkChild({ startImmediately: true }));
838 yield* Effect.yieldNow;
839 const removal = yield* Effect.flip(registry.remove(TARGET.environmentId)).pipe(
840 Effect.forkChild({ startImmediately: true }),
841 );
842
843 yield* Deferred.succeed(continueRegistration, undefined);
844 yield* Fiber.join(persistedRegistration);
845 yield* Fiber.join(platformRegistration);
846 const error = yield* Fiber.join(removal);
847
848 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
849 expect(
850 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
851 ).toEqual(TARGET);
852 }).pipe(Effect.provide(harness.layer), Effect.scoped);
853 }),
854 );
855
856 it.effect("does not reacquire a runtime while its registration is being removed", () =>
857 Effect.gen(function* () {
858 const removalStarted = yield* Deferred.make<void>();
859 const continueRemoval = yield* Deferred.make<void>();
860 const harness = yield* makeHarness([TARGET], [], [], {
861 beforeRegistrationRemove: () =>
862 Deferred.succeed(removalStarted, undefined).pipe(
863 Effect.andThen(Deferred.await(continueRemoval)),
864 ),
865 });
866
867 yield* Effect.gen(function* () {
868 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
869 yield* registry.start;
870 yield* awaitConnectionState(
871 registry,
872 TARGET.environmentId,
873 (state) => state.phase === "connected",
874 );
875
876 const removal = yield* Effect.forkChild(registry.remove(TARGET.environmentId));
877 yield* Deferred.await(removalStarted);
878
879 const stateLookup = yield* Effect.forkChild(
880 Effect.flip(registry.state(TARGET.environmentId)),
881 );
882 yield* Effect.yieldNow;
883 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
884
885 yield* Deferred.succeed(continueRemoval, undefined);
886 yield* Fiber.join(removal);
887 const error = yield* Fiber.join(stateLookup);
888 expect(error._tag).toBe("EnvironmentNotRegisteredError");
889 }).pipe(Effect.provide(harness.layer), Effect.scoped);
890 }),
891 );
892
893 it.effect("retains a healthy runtime when the platform repeats an identical registration", () =>
894 Effect.gen(function* () {
895 const harness = yield* makeHarness([]);
896
897 yield* Effect.gen(function* () {
898 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
899 const registration = new PrimaryConnectionRegistration({ target: TARGET });
900 yield* registry.registerPlatform(registration);
901 yield* awaitConnectionState(
902 registry,
903 TARGET.environmentId,
904 (state) => state.phase === "connected",
905 );
906
907 yield* registry.registerPlatform(registration);
908
909 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
910 }).pipe(Effect.provide(harness.layer), Effect.scoped);
911 }),
912 );
913
914 it.effect("removes all owned SSH state only on explicit removal", () =>
915 Effect.gen(function* () {
916 const harness = yield* makeHarness(
917 [SSH_CONNECTION],
918 [SSH_PROFILE],
919 [
920 [
921 SSH_CONNECTION.connectionId,
922 new BearerConnectionCredential({ token: "temporary-token" }),
923 ],
924 ],
925 );
926
927 yield* Effect.gen(function* () {
928 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
929 yield* registry.start;
930 yield* registry.remove(SSH_CONNECTION.environmentId);
931
932 expect((yield* Ref.get(harness.storedProfiles)).has(SSH_CONNECTION.connectionId)).toBe(
933 false,
934 );
935 expect((yield* Ref.get(harness.storedCredentials)).has(SSH_CONNECTION.connectionId)).toBe(
936 false,
937 );
938 expect((yield* Ref.get(harness.storedRemoteTokens)).has(SSH_CONNECTION.environmentId)).toBe(
939 false,
940 );
941 expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
942 }).pipe(Effect.provide(harness.layer));
943 }),
944 );
945});