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

registry.ts

816 lines29.1 KB

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