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