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