Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Equal from "effect/Equal";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as Semaphore from "effect/Semaphore";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14
15import * as ClientCapabilities from "../platform/capabilities.ts";
16import {
17 type ConnectionCatalogEntry,
18 type ConnectionRegistration,
19 type PlatformConnectionRegistration,
20 type PrimaryConnectionRegistration,
21 SshConnectionProfile,
22 connectionRegistrationCatalogEntry,
23} from "./catalog.ts";
24import * as ConnectionCredentialStore from "./credentialStore.ts";
25import * as ConnectionProfileStore from "./profileStore.ts";
26import * as Connectivity from "./connectivity.ts";
27import type {
28 ConnectionAttemptError,
29 ConnectionTarget,
30 NetworkStatus,
31 SupervisorConnectionState,
32} from "./model.ts";
33import { ConnectionBlockedError } from "./model.ts";
34import * as Persistence from "../platform/persistence.ts";
35import * as EnvironmentSupervisor from "./supervisor.ts";
36import * as ConnectionDriver from "./driver.ts";
37import * as ConnectionWakeups from "./wakeups.ts";
38import {
39 GitHubRoutingPermissions,
40 gitHubRoutingConnectionKey,
41} from "./githubRoutingPermissions.ts";
42
43const isSshConnectionProfile = Schema.is(SshConnectionProfile);
44
45export class EnvironmentNotRegisteredError extends Schema.TaggedError<EnvironmentNotRegisteredError>()(
46 "EnvironmentNotRegisteredError",
47 {
48 environmentId: EnvironmentId,
49 },
50) {
51 override get message(): string {
52 return `Environment ${this.environmentId} is not registered.`;
53 }
54}
55
56export class PlatformEnvironmentRemovalError extends Schema.TaggedError<PlatformEnvironmentRemovalError>()(
57 "PlatformEnvironmentRemovalError",
58 {
59 environmentId: EnvironmentId,
60 },
61) {
62 override get message(): string {
63 return `Platform-managed environment ${this.environmentId} cannot be removed.`;
64 }
65}
66
67export class EnvironmentRegistry extends Context.Service<
68 EnvironmentRegistry,
69 {
70 readonly entries: SubscriptionRef.SubscriptionRef<
71 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
72 >;
73 readonly networkStatus: SubscriptionRef.SubscriptionRef<NetworkStatus>;
74 readonly start: Effect.Effect<void>;
75 readonly register: (
76 registration: ConnectionRegistration,
77 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
78 readonly registerPlatform: (registration: PrimaryConnectionRegistration) => Effect.Effect<void>;
79 readonly reconcilePlatform: (
80 registrations: ReadonlyArray<PlatformConnectionRegistration>,
81 ) => Effect.Effect<void>;
82 readonly remove: (
83 environmentId: EnvironmentId,
84 ) => Effect.Effect<
85 void,
86 | Persistence.ConnectionPersistenceError
87 | ConnectionAttemptError
88 | EnvironmentNotRegisteredError
89 | PlatformEnvironmentRemovalError
90 >;
91 readonly removeRelayEnvironments: () => Effect.Effect<
92 void,
93 | Persistence.ConnectionPersistenceError
94 | ConnectionAttemptError
95 | PlatformEnvironmentRemovalError
96 >;
97 readonly retryNow: (environmentId: EnvironmentId) => Effect.Effect<void>;
98 /**
99 * Switches a saved environment on or off. Off drops the socket, stops the
100 * retry ladder, and persists so the next launch stays off. Registration,
101 * credentials, and cache are untouched.
102 */
103 readonly setEnabled: (
104 environmentId: EnvironmentId,
105 enabled: boolean,
106 ) => Effect.Effect<
107 void,
108 | EnvironmentNotRegisteredError
109 | Persistence.ConnectionPersistenceError
110 | ConnectionBlockedError
111 >;
112 readonly setCompatibility: (
113 environmentId: EnvironmentId,
114 error: ConnectionBlockedError | null,
115 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
116 readonly state: (
117 environmentId: EnvironmentId,
118 ) => Effect.Effect<SupervisorConnectionState, EnvironmentNotRegisteredError>;
119 readonly stateChanges: (
120 environmentId: EnvironmentId,
121 ) => Stream.Stream<SupervisorConnectionState, EnvironmentNotRegisteredError>;
122 readonly run: <A, E, R>(
123 environmentId: EnvironmentId,
124 effect: Effect.Effect<A, E, R>,
125 ) => Effect.Effect<
126 A,
127 E | EnvironmentNotRegisteredError,
128 Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
129 >;
130 readonly runStream: <A, E, R>(
131 environmentId: EnvironmentId,
132 stream: Stream.Stream<A, E, R>,
133 ) => Stream.Stream<
134 A,
135 E | EnvironmentNotRegisteredError,
136 Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
137 >;
138 readonly followStream: <A, E, R>(
139 environmentId: EnvironmentId,
140 stream: Stream.Stream<A, E, R>,
141 ) => Stream.Stream<A, E, Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>>;
142 }
143>()("@t3tools/client-runtime/connection/registry/EnvironmentRegistry") {}
144
145interface EnvironmentServiceScope {
146 readonly entry: ConnectionCatalogEntry;
147 readonly supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"];
148 readonly scope: Scope.Closeable;
149}
150
151/** @public Service construction is part of the canonical Effect module API. */
152export const make = Effect.gen(function* () {
153 const registryScope = yield* Scope.Scope;
154 const storage = yield* Persistence.ConnectionTargetStore;
155 const registrations = yield* Persistence.ConnectionRegistrationStore;
156 const cache = yield* Persistence.EnvironmentCacheStore;
157 const ownedDataCleanup = yield* Persistence.EnvironmentOwnedDataCleanup;
158 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
159 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
160 const githubRoutingPermissions = yield* GitHubRoutingPermissions;
161 const connectivity = yield* Connectivity.Connectivity;
162 const driver = yield* ConnectionDriver.ConnectionDriver;
163 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
164 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
165 const persistedTargets = yield* storage.list;
166 const disabledEnvironmentIds = new Set(yield* storage.listDisabled);
167 const initialEntries = new Map(
168 yield* Effect.forEach(
169 persistedTargets,
170 Effect.fn("EnvironmentRegistry.loadCatalogEntry")(function* (target) {
171 const profile =
172 target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
173 ? yield* profiles.get(target.connectionId)
174 : Option.none();
175 return [
176 target.environmentId,
177 {
178 target,
179 profile,
180 enabled: !disabledEnvironmentIds.has(target.environmentId),
181 } satisfies ConnectionCatalogEntry,
182 ] as const;
183 }),
184 { concurrency: "unbounded" },
185 ),
186 );
187 const entries =
188 yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(initialEntries);
189 const networkStatus = yield* SubscriptionRef.make(yield* connectivity.status);
190 const serviceScopes = yield* SubscriptionRef.make<
191 ReadonlyMap<EnvironmentId, EnvironmentServiceScope>
192 >(new Map());
193 const platformEnvironmentIds = yield* Ref.make<ReadonlySet<EnvironmentId>>(new Set());
194 const persistedTargetsByEnvironment = yield* Ref.make<
195 ReadonlyMap<EnvironmentId, ConnectionTarget>
196 >(new Map(persistedTargets.map((target) => [target.environmentId, target])));
197 interface LeaseLock {
198 readonly semaphore: Semaphore.Semaphore;
199 readonly users: number;
200 }
201
202 const leaseLocks = yield* Ref.make<ReadonlyMap<EnvironmentId, LeaseLock>>(new Map());
203 const leaseLocksGuard = yield* Semaphore.make(1);
204 const started = yield* Ref.make(false);
205
206 const withLeaseLock = <A, E, R>(
207 environmentId: EnvironmentId,
208 effect: Effect.Effect<A, E, R>,
209 ): Effect.Effect<A, E, R> =>
210 Effect.acquireUseRelease(
211 leaseLocksGuard.withPermits(1)(
212 Effect.gen(function* () {
213 const current = yield* Ref.get(leaseLocks);
214 const existing = current.get(environmentId);
215 if (existing !== undefined) {
216 yield* Ref.set(
217 leaseLocks,
218 new Map(current).set(environmentId, {
219 semaphore: existing.semaphore,
220 users: existing.users + 1,
221 }),
222 );
223 return existing.semaphore;
224 }
225 const semaphore = yield* Semaphore.make(1);
226 yield* Ref.set(leaseLocks, new Map(current).set(environmentId, { semaphore, users: 1 }));
227 return semaphore;
228 }),
229 ),
230 (semaphore) => semaphore.withPermits(1)(effect),
231 (semaphore) =>
232 leaseLocksGuard.withPermits(1)(
233 Ref.update(leaseLocks, (current) => {
234 const existing = current.get(environmentId);
235 if (existing === undefined || existing.semaphore !== semaphore) {
236 return current;
237 }
238 const next = new Map(current);
239 if (existing.users === 1) {
240 next.delete(environmentId);
241 } else {
242 next.set(environmentId, {
243 semaphore,
244 users: existing.users - 1,
245 });
246 }
247 return next;
248 }),
249 ),
250 ).pipe(Effect.withSpan("EnvironmentRegistry.withLeaseLock"));
251
252 const getEntry = Effect.fn("EnvironmentRegistry.getEntry")(function* (
253 environmentId: EnvironmentId,
254 ) {
255 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
256 if (entry === undefined) {
257 return yield* new EnvironmentNotRegisteredError({
258 environmentId,
259 });
260 }
261 return entry;
262 });
263
264 const closeServiceScope = Effect.fn("EnvironmentRegistry.closeServiceScope")(function* (
265 environmentId: EnvironmentId,
266 ) {
267 const current = yield* SubscriptionRef.get(serviceScopes);
268 const lease = current.get(environmentId);
269 if (lease === undefined) {
270 return;
271 }
272 const next = new Map(current);
273 next.delete(environmentId);
274 yield* SubscriptionRef.set(serviceScopes, next);
275 yield* Scope.close(lease.scope, Exit.void);
276 });
277
278 const createServiceScope = Effect.fn("EnvironmentRegistry.createServiceScope")(
279 (entry: ConnectionCatalogEntry) =>
280 Effect.uninterruptible(
281 Effect.gen(function* () {
282 const environmentId = entry.target.environmentId;
283 const scope = yield* Scope.fork(registryScope);
284 const supervisor = yield* EnvironmentSupervisor.make(entry, {
285 initiallyDesired: false,
286 }).pipe(
287 Effect.provideService(Connectivity.Connectivity, connectivity),
288 Effect.provideService(ConnectionDriver.ConnectionDriver, driver),
289 Effect.provideService(ConnectionWakeups.ConnectionWakeups, wakeups),
290 Scope.provide(scope),
291 Effect.onError(() => Scope.close(scope, Exit.void)),
292 );
293 if (entry.enabled) {
294 yield* supervisor.connect;
295 }
296 yield* SubscriptionRef.update(serviceScopes, (current) => {
297 const next = new Map(current);
298 next.set(environmentId, { entry, supervisor, scope });
299 return next;
300 });
301 yield* SubscriptionRef.changes(supervisor.state).pipe(
302 Stream.runForEach((state) =>
303 state.phase === "blocked" && state.lastFailure?.reason === "unsupported"
304 ? setCompatibility(environmentId, state.lastFailure).pipe(
305 Effect.catch((error) =>
306 Effect.logWarning("Could not disable an unsupported environment.", {
307 environmentId,
308 error,
309 }),
310 ),
311 )
312 : Effect.void,
313 ),
314 Effect.forkIn(scope),
315 );
316 return supervisor;
317 }),
318 ),
319 );
320
321 const acquireSupervisor = Effect.fn("EnvironmentRegistry.acquireSupervisor")(function* (
322 environmentId: EnvironmentId,
323 ) {
324 return yield* withLeaseLock(
325 environmentId,
326 Effect.gen(function* () {
327 const entry = yield* getEntry(environmentId);
328 const existing = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
329 if (existing !== undefined) {
330 if (Equal.equals(existing.entry, entry)) {
331 return existing.supervisor;
332 }
333 yield* closeServiceScope(environmentId);
334 }
335 return yield* createServiceScope(entry);
336 }),
337 );
338 });
339
340 const run: EnvironmentRegistry["Service"]["run"] = Effect.fn("EnvironmentRegistry.run")(
341 function* <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) {
342 const supervisor = yield* acquireSupervisor(environmentId);
343 return yield* Effect.provideService(
344 effect,
345 EnvironmentSupervisor.EnvironmentSupervisor,
346 supervisor,
347 );
348 },
349 );
350
351 const runStream: EnvironmentRegistry["Service"]["runStream"] = <A, E, R>(
352 environmentId: EnvironmentId,
353 stream: Stream.Stream<A, E, R>,
354 ) =>
355 Stream.unwrap(
356 acquireSupervisor(environmentId).pipe(
357 Effect.map((supervisor) =>
358 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
359 ),
360 ),
361 );
362
363 const followStream: EnvironmentRegistry["Service"]["followStream"] = <A, E, R>(
364 environmentId: EnvironmentId,
365 stream: Stream.Stream<A, E, R>,
366 ) =>
367 Stream.concat(
368 Stream.fromEffect(SubscriptionRef.get(entries)),
369 SubscriptionRef.changes(entries),
370 ).pipe(
371 Stream.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
372 Stream.changes,
373 Stream.switchMap(
374 Option.match({
375 onNone: () => Stream.empty,
376 onSome: () =>
377 Stream.unwrap(
378 acquireSupervisor(environmentId).pipe(
379 Effect.match({
380 onFailure: () => Stream.empty,
381 onSuccess: (supervisor) =>
382 Stream.provideService(
383 stream,
384 EnvironmentSupervisor.EnvironmentSupervisor,
385 supervisor,
386 ),
387 }),
388 ),
389 ),
390 }),
391 ),
392 );
393
394 const start = Effect.gen(function* () {
395 if (yield* Ref.getAndSet(started, true)) {
396 return;
397 }
398 yield* Effect.forEach(
399 persistedTargets,
400 (target) =>
401 acquireSupervisor(target.environmentId).pipe(
402 Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
403 ),
404 {
405 concurrency: "unbounded",
406 discard: true,
407 },
408 );
409 }).pipe(Effect.withSpan("EnvironmentRegistry.start"));
410
411 const installEntryLocked = Effect.fn("EnvironmentRegistry.installEntryLocked")(function* (
412 entry: ConnectionCatalogEntry,
413 options?: { readonly retainEquivalentRuntime?: boolean },
414 ) {
415 const target = entry.target;
416 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
417 const existingScope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
418 if (
419 options?.retainEquivalentRuntime === true &&
420 previous !== undefined &&
421 Equal.equals(previous, entry) &&
422 existingScope !== undefined &&
423 Equal.equals(existingScope.entry, entry)
424 ) {
425 return;
426 }
427
428 yield* closeServiceScope(target.environmentId);
429 yield* SubscriptionRef.update(entries, (current) => {
430 const next = new Map(current);
431 next.set(target.environmentId, entry);
432 return next;
433 });
434 yield* createServiceScope(entry);
435 });
436
437 const register = Effect.fn("EnvironmentRegistry.register")(function* (
438 registration: ConnectionRegistration,
439 ) {
440 const registered = connectionRegistrationCatalogEntry(registration);
441 const environmentId = registered.target.environmentId;
442 yield* withLeaseLock(
443 environmentId,
444 Effect.gen(function* () {
445 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
446 return;
447 }
448 // Editing a saved environment must preserve its disabled state.
449 const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
450 const entry: ConnectionCatalogEntry =
451 previous === undefined
452 ? registered
453 : {
454 ...registered,
455 enabled: previous.enabled,
456 ...(previous.unsupportedReason !== undefined &&
457 gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
458 ? { unsupportedReason: previous.unsupportedReason }
459 : {}),
460 };
461 if (
462 previous !== undefined &&
463 gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry)
464 ) {
465 yield* githubRoutingPermissions.forget(environmentId).pipe(
466 Effect.mapError(
467 (error) =>
468 new Persistence.ConnectionPersistenceError({
469 operation: "register-connection",
470 message: error.message,
471 }),
472 ),
473 );
474 }
475 yield* registrations.register(registration);
476 yield* Ref.update(persistedTargetsByEnvironment, (current) => {
477 const next = new Map(current);
478 next.set(environmentId, registration.target);
479 return next;
480 });
481 yield* installEntryLocked(entry);
482 }),
483 );
484 });
485
486 const installPlatformRegistration = Effect.fn("EnvironmentRegistry.installPlatformRegistration")(
487 function* (registration: PlatformConnectionRegistration) {
488 const registered = connectionRegistrationCatalogEntry(registration);
489 const target = registered.target;
490 yield* withLeaseLock(
491 target.environmentId,
492 Effect.gen(function* () {
493 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
494 const entry: ConnectionCatalogEntry =
495 previous?.unsupportedReason !== undefined &&
496 gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
497 ? { ...registered, enabled: false, unsupportedReason: previous.unsupportedReason }
498 : registered;
499 const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get(
500 target.environmentId,
501 );
502 if (
503 persistedTarget !== undefined ||
504 (previous !== undefined &&
505 gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry))
506 ) {
507 const revoked = yield* githubRoutingPermissions.forget(target.environmentId).pipe(
508 Effect.tapError((error) =>
509 Effect.logWarning(
510 "Could not clear GitHub routing permission for a platform environment.",
511 {
512 environmentId: target.environmentId,
513 error,
514 },
515 ),
516 ),
517 Effect.exit,
518 );
519 if (Exit.isFailure(revoked)) return;
520 }
521 yield* Ref.update(platformEnvironmentIds, (current) => {
522 const next = new Set(current);
523 next.add(target.environmentId);
524 return next;
525 });
526
527 // Secondary desktop-local backends (e.g. a parallel WSL backend) live
528 // on their own loopback origin, so they authenticate with a bearer
529 // token instead of the primary's same-origin cookie. Stash it where
530 // the resolver's bearer broker looks it up.
531 if (registration._tag === "BearerConnectionRegistration") {
532 yield* credentials.put(registration.target.connectionId, registration.credential).pipe(
533 Effect.catch((error) =>
534 Effect.logWarning("Could not store the platform bearer credential.", {
535 environmentId: target.environmentId,
536 error,
537 }),
538 ),
539 );
540 }
541
542 if (persistedTarget !== undefined) {
543 yield* registrations.remove(persistedTarget).pipe(
544 Effect.tap(() =>
545 Ref.update(persistedTargetsByEnvironment, (current) => {
546 const next = new Map(current);
547 next.delete(target.environmentId);
548 return next;
549 }),
550 ),
551 Effect.catch((error) =>
552 Effect.logWarning(
553 "Could not remove a persisted registration shadowed by a platform environment.",
554 {
555 environmentId: target.environmentId,
556 error,
557 },
558 ),
559 ),
560 );
561 }
562
563 yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
564 }),
565 );
566 },
567 );
568
569 // Tear down a platform-managed environment that the host no longer reports
570 // (e.g. the user turned the parallel WSL backend off). Platform environments
571 // bypass the user-facing `remove` guard since they are reconciled from the
572 // bootstrap rather than removed by hand.
573 const removePlatformEnvironment = Effect.fn("EnvironmentRegistry.removePlatformEnvironment")(
574 function* (environmentId: EnvironmentId) {
575 yield* withLeaseLock(
576 environmentId,
577 Effect.gen(function* () {
578 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
579 const revoked = yield* githubRoutingPermissions.forget(environmentId).pipe(
580 Effect.tapError((error) =>
581 Effect.logWarning(
582 "Could not clear GitHub routing permission after platform removal.",
583 {
584 environmentId,
585 error,
586 },
587 ),
588 ),
589 Effect.exit,
590 );
591 if (Exit.isFailure(revoked)) return;
592 yield* Ref.update(platformEnvironmentIds, (current) => {
593 const next = new Set(current);
594 next.delete(environmentId);
595 return next;
596 });
597 yield* closeServiceScope(environmentId);
598 yield* SubscriptionRef.update(entries, (current) => {
599 const next = new Map(current);
600 next.delete(environmentId);
601 return next;
602 });
603 if (entry !== undefined && entry.target._tag === "BearerConnectionTarget") {
604 yield* credentials.remove(entry.target.connectionId).pipe(
605 Effect.catch((error) =>
606 Effect.logWarning("Could not clear the platform bearer credential.", {
607 environmentId,
608 error,
609 }),
610 ),
611 );
612 }
613 yield* Effect.all(
614 [
615 cache.clear(environmentId).pipe(
616 Effect.catch((error) =>
617 Effect.logWarning("Could not clear cached environment data after removal.", {
618 environmentId,
619 error,
620 }),
621 ),
622 ),
623 ownedDataCleanup.clear(environmentId),
624 ],
625 { concurrency: "unbounded", discard: true },
626 );
627 }),
628 );
629 },
630 );
631
632 const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* (
633 registration: PrimaryConnectionRegistration,
634 ) {
635 yield* installPlatformRegistration(registration);
636 });
637
638 // Reconcile the full set of platform-managed environments against what the
639 // host currently reports: add/refresh the desired ones and tear down any
640 // platform environment that disappeared (WSL toggled off, distro switched).
641 const reconcilePlatform = Effect.fn("EnvironmentRegistry.reconcilePlatform")(function* (
642 platformRegistrations: ReadonlyArray<PlatformConnectionRegistration>,
643 ) {
644 const desiredIds = new Set(
645 platformRegistrations.map((registration) => registration.target.environmentId),
646 );
647 const currentPlatformIds = yield* Ref.get(platformEnvironmentIds);
648 yield* Effect.forEach(
649 currentPlatformIds,
650 (environmentId) =>
651 desiredIds.has(environmentId) ? Effect.void : removePlatformEnvironment(environmentId),
652 { discard: true },
653 );
654 yield* Effect.forEach(platformRegistrations, installPlatformRegistration, { discard: true });
655 });
656
657 const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) {
658 return yield* withLeaseLock(
659 environmentId,
660 Effect.gen(function* () {
661 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
662 return yield* new PlatformEnvironmentRemovalError({
663 environmentId,
664 });
665 }
666 const target = (yield* getEntry(environmentId)).target;
667 const profile =
668 target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
669 ? yield* profiles.get(target.connectionId)
670 : Option.none();
671
672 yield* githubRoutingPermissions.forget(environmentId);
673 yield* registrations.remove(target);
674 yield* Ref.update(persistedTargetsByEnvironment, (current) => {
675 const next = new Map(current);
676 next.delete(environmentId);
677 return next;
678 });
679 yield* closeServiceScope(environmentId);
680 yield* SubscriptionRef.update(entries, (current) => {
681 const next = new Map(current);
682 next.delete(environmentId);
683 return next;
684 });
685 yield* Effect.all(
686 [
687 cache.clear(environmentId).pipe(
688 Effect.catch((error) =>
689 Effect.logWarning("Could not clear cached environment data after removal.", {
690 environmentId,
691 error,
692 }),
693 ),
694 ),
695 ownedDataCleanup.clear(environmentId),
696 ],
697 { concurrency: "unbounded", discard: true },
698 );
699
700 if (
701 target._tag === "SshConnectionTarget" &&
702 Option.isSome(profile) &&
703 isSshConnectionProfile(profile.value)
704 ) {
705 yield* ssh.disconnect(profile.value.target).pipe(
706 Effect.tapError((error) =>
707 Effect.logWarning("Could not disconnect the managed SSH environment.", {
708 environmentId,
709 error,
710 }),
711 ),
712 Effect.ignore,
713 );
714 }
715 }),
716 );
717 });
718
719 const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(
720 function* () {
721 const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]
722 .filter((entry) => entry.target._tag === "RelayConnectionTarget")
723 .map((entry) => entry.target.environmentId);
724
725 yield* Effect.forEach(
726 relayEnvironmentIds,
727 (environmentId) =>
728 remove(environmentId).pipe(
729 Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
730 ),
731 {
732 concurrency: "unbounded",
733 discard: true,
734 },
735 );
736 },
737 );
738
739 const retryNow = (environmentId: EnvironmentId) =>
740 acquireSupervisor(environmentId).pipe(
741 Effect.flatMap((supervisor) => supervisor.retryNow),
742 Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
743 Effect.withSpan("EnvironmentRegistry.retryNow"),
744 );
745 const setEnabled = Effect.fn("EnvironmentRegistry.setEnabled")(function* (
746 environmentId: EnvironmentId,
747 enabled: boolean,
748 ) {
749 yield* withLeaseLock(
750 environmentId,
751 Effect.gen(function* () {
752 const entry = yield* getEntry(environmentId);
753 if (enabled && entry.unsupportedReason !== undefined) {
754 return yield* new ConnectionBlockedError({
755 reason: "unsupported",
756 detail: entry.unsupportedReason,
757 });
758 }
759 if (entry.enabled === enabled) {
760 return;
761 }
762 // Platform-managed environments are reconciled from the host and are
763 // never persisted, so only user-saved ones write the flag.
764 if (!(yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
765 yield* registrations.setEnabled(environmentId, enabled);
766 }
767 const next: ConnectionCatalogEntry = { ...entry, enabled };
768 // Update the lease in place so the supervisor keeps its generation and
769 // durable streams; `installEntryLocked` would tear it down instead.
770 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
771 if (lease !== undefined) {
772 yield* SubscriptionRef.update(serviceScopes, (current) => {
773 const nextScopes = new Map(current);
774 nextScopes.set(environmentId, { ...lease, entry: next });
775 return nextScopes;
776 });
777 }
778 yield* SubscriptionRef.update(entries, (current) => {
779 const nextEntries = new Map(current);
780 nextEntries.set(environmentId, next);
781 return nextEntries;
782 });
783 if (lease !== undefined) {
784 yield* enabled ? lease.supervisor.connect : lease.supervisor.disconnect;
785 } else if (enabled) {
786 yield* createServiceScope(next);
787 }
788 // The supervisor only owns the RPC session. A managed SSH backend and
789 // its tunnel outlive it, so switching off tears those down as well.
790 if (
791 !enabled &&
792 entry.target._tag === "SshConnectionTarget" &&
793 Option.isSome(entry.profile) &&
794 isSshConnectionProfile(entry.profile.value)
795 ) {
796 yield* ssh.disconnect(entry.profile.value.target).pipe(
797 Effect.tapError((error) =>
798 Effect.logWarning("Could not disconnect the switched-off SSH environment.", {
799 environmentId,
800 error,
801 }),
802 ),
803 Effect.ignore,
804 );
805 }
806 }),
807 );
808 });
809
810 const state = Effect.fn("EnvironmentRegistry.state")(function* (environmentId: EnvironmentId) {
811 const supervisor = yield* acquireSupervisor(environmentId);
812 return yield* SubscriptionRef.get(supervisor.state);
813 });
814 const stateChanges = (environmentId: EnvironmentId) =>
815 followStream(
816 environmentId,
817 Stream.unwrap(
818 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
819 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.state)),
820 ),
821 ),
822 );
823
824 yield* Effect.addFinalizer(() =>
825 SubscriptionRef.get(serviceScopes).pipe(
826 Effect.flatMap((current) =>
827 Effect.forEach(current.values(), (lease) => Scope.close(lease.scope, Exit.void), {
828 concurrency: "unbounded",
829 discard: true,
830 }),
831 ),
832 ),
833 );
834 yield* connectivity.changes.pipe(
835 Stream.runForEach((status) => SubscriptionRef.set(networkStatus, status)),
836 Effect.forkScoped,
837 );
838
839 const setCompatibility = Effect.fn("EnvironmentRegistry.setCompatibility")(function* (
840 environmentId: EnvironmentId,
841 error: ConnectionBlockedError | null,
842 ) {
843 yield* withLeaseLock(
844 environmentId,
845 Effect.gen(function* () {
846 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
847 if (entry === undefined || entry.unsupportedReason === (error?.message ?? undefined))
848 return;
849 const { unsupportedReason: _previousReason, ...rest } = entry;
850 const next: ConnectionCatalogEntry =
851 error === null ? rest : { ...rest, enabled: false, unsupportedReason: error.message };
852 if (
853 error !== null &&
854 entry.enabled &&
855 !(yield* Ref.get(platformEnvironmentIds)).has(environmentId)
856 ) {
857 yield* registrations.setEnabled(environmentId, false);
858 }
859 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
860 if (lease !== undefined) {
861 yield* SubscriptionRef.update(serviceScopes, (current) =>
862 new Map(current).set(environmentId, { ...lease, entry: next }),
863 );
864 if (error !== null) yield* lease.supervisor.disconnect;
865 }
866 yield* SubscriptionRef.update(entries, (current) =>
867 new Map(current).set(environmentId, next),
868 );
869 }),
870 );
871 });
872
873 return EnvironmentRegistry.of({
874 entries,
875 networkStatus,
876 start,
877 register,
878 registerPlatform,
879 reconcilePlatform,
880 remove,
881 removeRelayEnvironments,
882 retryNow,
883 setEnabled,
884 setCompatibility,
885 state,
886 stateChanges,
887 run,
888 runStream,
889 followStream,
890 });
891});
892
893export const layer = Layer.effect(EnvironmentRegistry, make);