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