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

registry.test.ts

973 lines36.5 KB

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