Open History to see the last commit
1import {
2 type DesktopSshEnvironmentTarget,
3 EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
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";
54import { v2ShellSnapshot } from "../state/orchestrationV2TestFixtures.ts";
55
56const TARGET = new PrimaryConnectionTarget({
57 environmentId: EnvironmentId.make("environment-1"),
58 label: "Test environment",
59 httpBaseUrl: "https://environment.example.test",
60 wsBaseUrl: "wss://environment.example.test",
61});
62const SECOND_TARGET = new PrimaryConnectionTarget({
63 environmentId: EnvironmentId.make("environment-2"),
64 label: "Second environment",
65 httpBaseUrl: "https://environment-2.example.test",
66 wsBaseUrl: "wss://environment-2.example.test",
67});
68
69const PREPARED: PreparedConnection = {
70 environmentId: TARGET.environmentId,
71 label: TARGET.label,
72 httpBaseUrl: TARGET.httpBaseUrl,
73 socketUrl: "wss://environment.example.test/ws",
74 httpAuthorization: null,
75 target: TARGET,
76};
77
78const RELAY_TARGET = new RelayConnectionTarget({
79 environmentId: EnvironmentId.make("environment-relay"),
80 label: "Relay environment",
81});
82const SECOND_RELAY_TARGET = new RelayConnectionTarget({
83 environmentId: EnvironmentId.make("environment-relay-2"),
84 label: "Second relay environment",
85});
86
87const BEARER_TARGET = new BearerConnectionTarget({
88 environmentId: EnvironmentId.make("environment-bearer"),
89 label: "Bearer environment",
90 connectionId: "bearer-connection",
91});
92const BEARER_PROFILE = new BearerConnectionProfile({
93 connectionId: BEARER_TARGET.connectionId,
94 environmentId: BEARER_TARGET.environmentId,
95 label: BEARER_TARGET.label,
96 httpBaseUrl: "https://bearer.example.test",
97 wsBaseUrl: "wss://bearer.example.test",
98});
99const BEARER_CREDENTIAL = new BearerConnectionCredential({
100 token: "bearer-token",
101});
102
103const SSH_TARGET: DesktopSshEnvironmentTarget = {
104 alias: "test",
105 hostname: "test.example.test",
106 username: "developer",
107 port: 22,
108};
109const SSH_CONNECTION = new SshConnectionTarget({
110 environmentId: EnvironmentId.make("environment-ssh"),
111 label: "SSH environment",
112 connectionId: "ssh-connection",
113});
114const SSH_PROFILE = new SshConnectionProfile({
115 connectionId: SSH_CONNECTION.connectionId,
116 environmentId: SSH_CONNECTION.environmentId,
117 label: SSH_CONNECTION.label,
118 target: SSH_TARGET,
119});
120
121const CACHED_SNAPSHOT: OrchestrationV2ShellSnapshot = {
122 ...v2ShellSnapshot,
123 snapshotSequence: 1,
124};
125
126interface SessionControl {
127 readonly closed: Deferred.Deferred<never, ConnectionTransientError>;
128}
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 subscribeServerConfig: () =>
360 Stream.die(new Error("Config is not used by registry tests.")),
361 ready: Effect.void,
362 probe: Effect.void,
363 closed: Deferred.await(closed),
364 } satisfies RpcSession.RpcSession),
365 () => Ref.update(releasedSessions, (count) => count + 1),
366 );
367 yield* reportProgress({ stage: "synchronizing", prepared });
368 yield* session.ready;
369 return { prepared, session };
370 }),
371 });
372
373 const cacheLayer = Layer.succeed(Persistence.EnvironmentCacheStore, cacheStore);
374 const layer = EnvironmentRegistry.layer.pipe(
375 Layer.provide(
376 Layer.mergeAll(
377 Layer.succeed(Persistence.ConnectionTargetStore, targetStore),
378 Layer.succeed(Persistence.ConnectionRegistrationStore, registrationStore),
379 Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),
380 Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),
381 Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),
382 Layer.succeed(ClientCapabilities.SshEnvironmentGateway, sshGateway),
383 Layer.succeed(Connectivity.Connectivity, connectivity),
384 Layer.succeed(
385 ConnectionWakeups.ConnectionWakeups,
386 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }),
387 ),
388 Layer.succeed(ConnectionDriver.ConnectionDriver, driver),
389 cacheLayer,
390 Layer.succeed(Persistence.EnvironmentOwnedDataCleanup, ownedDataCleanup),
391 ),
392 ),
393 );
394
395 return {
396 layer,
397 storedTargets,
398 shellCache,
399 cacheClears,
400 ownedDataClears,
401 sessions,
402 releasedSessions,
403 storedProfiles,
404 profileReadCount,
405 storedCredentials,
406 storedRemoteTokens,
407 disconnectedSshTargets,
408 networkStatus,
409 };
410});
411
412function awaitConnectionState(
413 registry: EnvironmentRegistry.EnvironmentRegistry["Service"],
414 environmentId: EnvironmentId,
415 predicate: (state: SupervisorConnectionState) => boolean,
416) {
417 return Effect.gen(function* () {
418 const current = yield* registry.state(environmentId);
419 if (predicate(current)) {
420 return current;
421 }
422 return yield* registry
423 .stateChanges(environmentId)
424 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
425 });
426}
427
428describe("EnvironmentRegistry", () => {
429 it.effect("replays connected state when arming a desktop commit observer", () =>
430 Effect.gen(function* () {
431 const harness = yield* makeHarness([TARGET]);
432
433 yield* Effect.gen(function* () {
434 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
435 yield* registry.start;
436 yield* awaitConnectionState(
437 registry,
438 TARGET.environmentId,
439 (state) => state.phase === "connected",
440 );
441
442 const commits = yield* Ref.make(0);
443 const result = yield* runDesktopCommitWithReconnectObserver(
444 registry.stateChanges(TARGET.environmentId),
445 Ref.update(commits, (count) => count + 1).pipe(
446 Effect.andThen(Effect.fail("commit refused")),
447 ),
448 ).pipe(Effect.flip, Effect.timeout("1 second"));
449
450 expect(result).toBe("commit refused");
451 expect(yield* Ref.get(commits)).toBe(1);
452 }).pipe(Effect.provide(harness.layer), Effect.scoped);
453 }),
454 );
455
456 it.effect("does not acquire a session after the registry scope has already closed", () =>
457 Effect.gen(function* () {
458 const harness = yield* makeHarness([TARGET]);
459 const registryScope = yield* Scope.make();
460 const context = yield* Layer.build(harness.layer).pipe(Scope.provide(registryScope));
461 const registry = Context.get(context, EnvironmentRegistry.EnvironmentRegistry);
462 const dispatcher = new Scheduler.MixedScheduler("sync", () => () => {}).makeDispatcher();
463 const scheduler: Scheduler.Scheduler = {
464 executionMode: "sync",
465 shouldYield: () => false,
466 makeDispatcher: () => dispatcher,
467 };
468
469 yield* Scope.close(registryScope, Exit.void);
470 yield* registry.start.pipe(Effect.provideService(Scheduler.Scheduler, scheduler));
471 dispatcher.flush();
472
473 expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
474 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
475 }),
476 );
477
478 it.effect("hydrates connection profiles into catalog entries", () =>
479 Effect.gen(function* () {
480 const harness = yield* makeHarness([SSH_CONNECTION], [SSH_PROFILE]);
481
482 yield* Effect.gen(function* () {
483 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
484 const entry = (yield* SubscriptionRef.get(registry.entries)).get(
485 SSH_CONNECTION.environmentId,
486 );
487
488 expect(entry?.target).toEqual(SSH_CONNECTION);
489 expect(Option.getOrThrow(entry?.profile ?? Option.none())).toEqual(SSH_PROFILE);
490 }).pipe(Effect.provide(harness.layer), Effect.scoped);
491 }),
492 );
493
494 it.effect("publishes network status changes independently of connection state", () =>
495 Effect.gen(function* () {
496 const harness = yield* makeHarness([]);
497
498 yield* Effect.gen(function* () {
499 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
500 const offline = yield* Effect.forkChild(
501 SubscriptionRef.changes(registry.networkStatus).pipe(
502 Stream.filter((status) => status === "offline"),
503 Stream.runHead,
504 Effect.map(Option.getOrThrow),
505 ),
506 );
507
508 yield* SubscriptionRef.set(harness.networkStatus, "offline");
509
510 expect(yield* Fiber.join(offline)).toBe("offline");
511 expect(yield* SubscriptionRef.get(registry.networkStatus)).toBe("offline");
512 }).pipe(Effect.provide(harness.layer), Effect.scoped);
513 }),
514 );
515
516 it.effect("starts persisted environments independently", () =>
517 Effect.gen(function* () {
518 const bothLoadsStarted = yield* Deferred.make<void>();
519 const releaseLoads = yield* Deferred.make<void>();
520 const loadCount = yield* Ref.make(0);
521 const harness = yield* makeHarness([TARGET, SECOND_TARGET], [], [], {
522 beforeSessionConnect: () =>
523 Ref.updateAndGet(loadCount, (count) => count + 1).pipe(
524 Effect.tap((count) =>
525 count === 2 ? Deferred.succeed(bothLoadsStarted, undefined) : Effect.void,
526 ),
527 Effect.andThen(Deferred.await(releaseLoads)),
528 ),
529 });
530
531 yield* Effect.gen(function* () {
532 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
533 const start = yield* Effect.forkChild(registry.start);
534
535 yield* Deferred.await(bothLoadsStarted).pipe(Effect.timeout("1 second"));
536 yield* Deferred.succeed(releaseLoads, undefined);
537 yield* Fiber.join(start);
538
539 expect(yield* Ref.get(loadCount)).toBe(2);
540 }).pipe(Effect.provide(harness.layer), Effect.scoped);
541 }),
542 );
543
544 it.effect("exposes the current RPC generation to late query subscribers", () =>
545 Effect.gen(function* () {
546 const harness = yield* makeHarness([TARGET]);
547 yield* Effect.gen(function* () {
548 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
549 yield* registry.start;
550 yield* awaitConnectionState(
551 registry,
552 TARGET.environmentId,
553 (state) => state.phase === "connected",
554 );
555
556 const generation = yield* registry
557 .runStream(
558 TARGET.environmentId,
559 Stream.unwrap(
560 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
561 Effect.map((supervisor) =>
562 Stream.concat(
563 Stream.fromEffect(SubscriptionRef.get(supervisor.state)),
564 SubscriptionRef.changes(supervisor.state),
565 ).pipe(
566 Stream.filterMap((state) =>
567 state.phase === "connected"
568 ? Result.succeed(state.generation)
569 : Result.failVoid,
570 ),
571 Stream.changes,
572 ),
573 ),
574 ),
575 ),
576 )
577 .pipe(Stream.runHead, Effect.map(Option.getOrThrow));
578
579 expect(generation).toBe(1);
580 }).pipe(Effect.provide(harness.layer), Effect.scoped);
581 }),
582 );
583
584 it.effect("preserves cached data on connection failure and clears it on explicit removal", () =>
585 Effect.gen(function* () {
586 const harness = yield* makeHarness([TARGET]);
587 yield* Effect.gen(function* () {
588 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
589 yield* registry.start;
590 yield* awaitConnectionState(
591 registry,
592 TARGET.environmentId,
593 (state) => state.phase === "connected",
594 );
595 const controls = yield* Ref.get(harness.sessions);
596 expect(controls).toHaveLength(1);
597 const active = controls[0];
598 expect(active).toBeDefined();
599 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
600 CACHED_SNAPSHOT,
601 );
602
603 const retryFiber = yield* Effect.forkChild(
604 awaitConnectionState(
605 registry,
606 TARGET.environmentId,
607 (state) => state.phase === "backoff",
608 ),
609 );
610 yield* Effect.yieldNow;
611 yield* Deferred.fail(
612 active!.closed,
613 new ConnectionTransientError({
614 reason: "transport",
615 detail: "Disconnected.",
616 }),
617 );
618 yield* Fiber.join(retryFiber);
619 expect((yield* Ref.get(harness.shellCache)).get(TARGET.environmentId)).toEqual(
620 CACHED_SNAPSHOT,
621 );
622
623 yield* registry.remove(TARGET.environmentId);
624 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
625 expect((yield* Ref.get(harness.shellCache)).has(TARGET.environmentId)).toBe(false);
626 expect(yield* Ref.get(harness.cacheClears)).toEqual([TARGET.environmentId]);
627 expect((yield* SubscriptionRef.get(registry.entries)).has(TARGET.environmentId)).toBe(
628 false,
629 );
630 }).pipe(Effect.provide(harness.layer));
631 }),
632 );
633
634 it.effect("persists and starts a newly registered environment", () =>
635 Effect.gen(function* () {
636 const harness = yield* makeHarness([]);
637
638 yield* Effect.gen(function* () {
639 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
640 yield* registry.register(new RelayConnectionRegistration({ target: RELAY_TARGET }));
641 yield* awaitConnectionState(
642 registry,
643 RELAY_TARGET.environmentId,
644 (state) => state.phase === "connected",
645 );
646
647 expect((yield* Ref.get(harness.storedTargets)).get(RELAY_TARGET.environmentId)).toEqual(
648 RELAY_TARGET,
649 );
650 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
651 }).pipe(Effect.provide(harness.layer));
652 }),
653 );
654
655 it.effect("moves durable streams to a replacement supervisor", () =>
656 Effect.gen(function* () {
657 const replacement = new RelayConnectionTarget({
658 environmentId: RELAY_TARGET.environmentId,
659 label: "Replacement relay environment",
660 });
661 const harness = yield* makeHarness([RELAY_TARGET]);
662
663 yield* Effect.gen(function* () {
664 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
665 const firstObserved = yield* Deferred.make<void>();
666 const secondObserved = yield* Deferred.make<void>();
667 const labels = yield* Ref.make<ReadonlyArray<string>>([]);
668 yield* registry.start;
669 yield* awaitConnectionState(
670 registry,
671 RELAY_TARGET.environmentId,
672 (state) => state.phase === "connected",
673 );
674
675 const subscription = yield* Effect.forkChild(
676 registry
677 .followStream(
678 RELAY_TARGET.environmentId,
679 Stream.unwrap(
680 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
681 Effect.map((supervisor) =>
682 Stream.concat(Stream.succeed(supervisor.target.label), Stream.never),
683 ),
684 ),
685 ),
686 )
687 .pipe(
688 Stream.tap((label) =>
689 Ref.updateAndGet(labels, (current) => [...current, label]).pipe(
690 Effect.flatMap((current) =>
691 current.length === 1
692 ? Deferred.succeed(firstObserved, undefined)
693 : Deferred.succeed(secondObserved, undefined),
694 ),
695 ),
696 ),
697 Stream.runDrain,
698 ),
699 );
700
701 yield* Deferred.await(firstObserved).pipe(Effect.timeout("1 second"));
702 yield* registry.register(new RelayConnectionRegistration({ target: replacement }));
703 yield* Deferred.await(secondObserved).pipe(Effect.timeout("1 second"));
704 yield* Fiber.interrupt(subscription);
705
706 expect(yield* Ref.get(labels)).toEqual([RELAY_TARGET.label, replacement.label]);
707 }).pipe(Effect.provide(harness.layer), Effect.scoped);
708 }),
709 );
710
711 it.effect("ignores retry signals for environments that are no longer registered", () =>
712 Effect.gen(function* () {
713 const harness = yield* makeHarness([]);
714
715 yield* Effect.gen(function* () {
716 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
717 yield* registry.retryNow(EnvironmentId.make("removed-environment"));
718 }).pipe(Effect.provide(harness.layer), Effect.scoped);
719 }),
720 );
721
722 it.effect("removes all relay-owned data without touching non-cloud connections", () =>
723 Effect.gen(function* () {
724 const harness = yield* makeHarness(
725 [RELAY_TARGET, SECOND_RELAY_TARGET, BEARER_TARGET],
726 [BEARER_PROFILE],
727 [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]],
728 );
729
730 yield* Effect.gen(function* () {
731 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
732 yield* registry.removeRelayEnvironments();
733
734 const targets = yield* Ref.get(harness.storedTargets);
735 expect(targets.has(RELAY_TARGET.environmentId)).toBe(false);
736 expect(targets.has(SECOND_RELAY_TARGET.environmentId)).toBe(false);
737 expect(targets.get(BEARER_TARGET.environmentId)).toEqual(BEARER_TARGET);
738 expect(yield* Ref.get(harness.cacheClears)).toEqual(
739 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
740 );
741 expect(yield* Ref.get(harness.ownedDataClears)).toEqual(
742 expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),
743 );
744 expect(
745 (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId),
746 ).toBe(true);
747 }).pipe(Effect.provide(harness.layer), Effect.scoped);
748 }),
749 );
750
751 it.effect("keeps the runtime registered when durable removal fails", () =>
752 Effect.gen(function* () {
753 const harness = yield* makeHarness([RELAY_TARGET], [], [], {
754 beforeRegistrationRemove: () =>
755 Effect.fail(
756 new Persistence.ConnectionPersistenceError({
757 operation: "remove-connection",
758 message: "Storage is unavailable.",
759 }),
760 ),
761 });
762
763 yield* Effect.gen(function* () {
764 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
765 yield* registry.start;
766 yield* awaitConnectionState(
767 registry,
768 RELAY_TARGET.environmentId,
769 (state) => state.phase === "connected",
770 );
771
772 const error = yield* Effect.flip(registry.removeRelayEnvironments());
773
774 expect(error._tag).toBe("ConnectionPersistenceError");
775 expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
776 expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
777 true,
778 );
779 expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);
780 expect(yield* Ref.get(harness.cacheClears)).toEqual([]);
781 expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]);
782 }).pipe(Effect.provide(harness.layer), Effect.scoped);
783 }),
784 );
785
786 it.effect("starts a newly paired bearer environment without re-reading its profile", () =>
787 Effect.gen(function* () {
788 const harness = yield* makeHarness([]);
789
790 yield* Effect.gen(function* () {
791 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
792 yield* registry.register(
793 new BearerConnectionRegistration({
794 target: BEARER_TARGET,
795 profile: BEARER_PROFILE,
796 credential: BEARER_CREDENTIAL,
797 }),
798 );
799 yield* awaitConnectionState(
800 registry,
801 BEARER_TARGET.environmentId,
802 (state) => state.phase === "connected",
803 );
804
805 expect(yield* Ref.get(harness.profileReadCount)).toBe(0);
806 expect(
807 Option.getOrThrow(
808 (yield* SubscriptionRef.get(registry.entries)).get(BEARER_TARGET.environmentId)
809 ?.profile ?? Option.none(),
810 ),
811 ).toEqual(BEARER_PROFILE);
812 }).pipe(Effect.provide(harness.layer), Effect.scoped);
813 }),
814 );
815
816 it.effect("starts platform environments without persisting or removing them", () =>
817 Effect.gen(function* () {
818 const harness = yield* makeHarness([]);
819
820 yield* Effect.gen(function* () {
821 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
822 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
823 yield* awaitConnectionState(
824 registry,
825 TARGET.environmentId,
826 (state) => state.phase === "connected",
827 );
828
829 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
830 expect(
831 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
832 ).toEqual(TARGET);
833
834 const error = yield* Effect.flip(registry.remove(TARGET.environmentId));
835 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
836 expect(
837 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
838 ).toEqual(TARGET);
839 }).pipe(Effect.provide(harness.layer));
840 }),
841 );
842
843 it.effect("gives a primary platform registration precedence over persisted registrations", () =>
844 Effect.gen(function* () {
845 const shadowedTarget = new RelayConnectionTarget({
846 environmentId: TARGET.environmentId,
847 label: "Shadowed relay environment",
848 });
849 const harness = yield* makeHarness([shadowedTarget]);
850
851 yield* Effect.gen(function* () {
852 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
853 yield* registry.registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }));
854
855 expect(
856 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
857 ).toEqual(TARGET);
858 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
859
860 yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget }));
861
862 expect(
863 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
864 ).toEqual(TARGET);
865 expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);
866 }).pipe(Effect.provide(harness.layer), Effect.scoped);
867 }),
868 );
869
870 it.effect("rechecks platform ownership after waiting for the environment lease", () =>
871 Effect.gen(function* () {
872 const registrationStarted = yield* Deferred.make<void>();
873 const continueRegistration = yield* Deferred.make<void>();
874 const shadowedTarget = new RelayConnectionTarget({
875 environmentId: TARGET.environmentId,
876 label: "Shadowed relay environment",
877 });
878 const harness = yield* makeHarness([], [], [], {
879 beforeRegistrationRegister: () =>
880 Deferred.succeed(registrationStarted, undefined).pipe(
881 Effect.andThen(Deferred.await(continueRegistration)),
882 ),
883 });
884
885 yield* Effect.gen(function* () {
886 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
887 const persistedRegistration = yield* registry
888 .register(new RelayConnectionRegistration({ target: shadowedTarget }))
889 .pipe(Effect.forkChild({ startImmediately: true }));
890 yield* Deferred.await(registrationStarted);
891
892 const platformRegistration = yield* registry
893 .registerPlatform(new PrimaryConnectionRegistration({ target: TARGET }))
894 .pipe(Effect.forkChild({ startImmediately: true }));
895 yield* Effect.yieldNow;
896 const removal = yield* Effect.flip(registry.remove(TARGET.environmentId)).pipe(
897 Effect.forkChild({ startImmediately: true }),
898 );
899
900 yield* Deferred.succeed(continueRegistration, undefined);
901 yield* Fiber.join(persistedRegistration);
902 yield* Fiber.join(platformRegistration);
903 const error = yield* Fiber.join(removal);
904
905 expect(error._tag).toBe("PlatformEnvironmentRemovalError");
906 expect(
907 (yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,
908 ).toEqual(TARGET);
909 }).pipe(Effect.provide(harness.layer), Effect.scoped);
910 }),
911 );
912
913 it.effect("does not reacquire a runtime while its registration is being removed", () =>
914 Effect.gen(function* () {
915 const removalStarted = yield* Deferred.make<void>();
916 const continueRemoval = yield* Deferred.make<void>();
917 const harness = yield* makeHarness([TARGET], [], [], {
918 beforeRegistrationRemove: () =>
919 Deferred.succeed(removalStarted, undefined).pipe(
920 Effect.andThen(Deferred.await(continueRemoval)),
921 ),
922 });
923
924 yield* Effect.gen(function* () {
925 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
926 yield* registry.start;
927 yield* awaitConnectionState(
928 registry,
929 TARGET.environmentId,
930 (state) => state.phase === "connected",
931 );
932
933 const removal = yield* Effect.forkChild(registry.remove(TARGET.environmentId));
934 yield* Deferred.await(removalStarted);
935
936 const stateLookup = yield* Effect.forkChild(
937 Effect.flip(registry.state(TARGET.environmentId)),
938 );
939 yield* Effect.yieldNow;
940 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
941
942 yield* Deferred.succeed(continueRemoval, undefined);
943 yield* Fiber.join(removal);
944 const error = yield* Fiber.join(stateLookup);
945 expect(error._tag).toBe("EnvironmentNotRegisteredError");
946 }).pipe(Effect.provide(harness.layer), Effect.scoped);
947 }),
948 );
949
950 it.effect("retains a healthy runtime when the platform repeats an identical registration", () =>
951 Effect.gen(function* () {
952 const harness = yield* makeHarness([]);
953
954 yield* Effect.gen(function* () {
955 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
956 const registration = new PrimaryConnectionRegistration({ target: TARGET });
957 yield* registry.registerPlatform(registration);
958 yield* awaitConnectionState(
959 registry,
960 TARGET.environmentId,
961 (state) => state.phase === "connected",
962 );
963
964 yield* registry.registerPlatform(registration);
965
966 expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
967 }).pipe(Effect.provide(harness.layer), Effect.scoped);
968 }),
969 );
970
971 it.effect("removes all owned SSH state only on explicit removal", () =>
972 Effect.gen(function* () {
973 const harness = yield* makeHarness(
974 [SSH_CONNECTION],
975 [SSH_PROFILE],
976 [
977 [
978 SSH_CONNECTION.connectionId,
979 new BearerConnectionCredential({ token: "temporary-token" }),
980 ],
981 ],
982 );
983
984 yield* Effect.gen(function* () {
985 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
986 yield* registry.start;
987 yield* registry.remove(SSH_CONNECTION.environmentId);
988
989 expect((yield* Ref.get(harness.storedProfiles)).has(SSH_CONNECTION.connectionId)).toBe(
990 false,
991 );
992 expect((yield* Ref.get(harness.storedCredentials)).has(SSH_CONNECTION.connectionId)).toBe(
993 false,
994 );
995 expect((yield* Ref.get(harness.storedRemoteTokens)).has(SSH_CONNECTION.environmentId)).toBe(
996 false,
997 );
998 expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);
999 }).pipe(Effect.provide(harness.layer));
1000 }),
1001 );
1002});