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 ConnectionCredential,
19 type ConnectionProfile,
20 type ConnectionRegistration,
21 type ConnectionRoute,
22 type PlatformConnectionRegistration,
23 type PrimaryConnectionRegistration,
24 SshConnectionProfile,
25 connectionRegistrationCatalogEntry,
26} from "./catalog.ts";
27import * as ConnectionCredentialStore from "./credentialStore.ts";
28import * as ConnectionProfileStore from "./profileStore.ts";
29import * as Connectivity from "./connectivity.ts";
30import type {
31 ConnectionAttemptError,
32 ConnectionTarget,
33 NetworkStatus,
34 PersistedConnectionTarget,
35 SupervisorConnectionState,
36} from "./model.ts";
37import { ConnectionBlockedError } from "./model.ts";
38import * as Persistence from "../platform/persistence.ts";
39import * as EnvironmentSupervisor from "./supervisor.ts";
40import * as ConnectionDriver from "./driver.ts";
41import * as ConnectionWakeups from "./wakeups.ts";
42import {
43 GitHubRoutingPermissions,
44 gitHubRoutingConnectionKey,
45} from "./githubRoutingPermissions.ts";
46import {
47 RELAY_ROUTE_ID,
48 connectionRouteId,
49 connectionRoutes,
50 entryWithRoutes,
51 findRouteToSameAddress,
52 isLearned,
53 mergeLearnedRoutes,
54 routesAfterRemoving,
55 upsertRoute,
56} from "./routes.ts";
57
58const isSshConnectionProfile = Schema.is(SshConnectionProfile);
59
60function unsupportedState(
61 entry: ConnectionCatalogEntry,
62): Pick<ConnectionCatalogEntry, "unsupportedReason" | "serverUpdateRequired"> {
63 return {
64 ...(entry.unsupportedReason === undefined
65 ? {}
66 : { unsupportedReason: entry.unsupportedReason }),
67 ...(entry.serverUpdateRequired === true ? { serverUpdateRequired: true } : {}),
68 };
69}
70
71export class EnvironmentNotRegisteredError extends Schema.TaggedError<EnvironmentNotRegisteredError>()(
72 "EnvironmentNotRegisteredError",
73 {
74 environmentId: EnvironmentId,
75 },
76) {
77 override get message(): string {
78 return `Environment ${this.environmentId} is not registered.`;
79 }
80}
81
82export class PlatformEnvironmentRemovalError extends Schema.TaggedError<PlatformEnvironmentRemovalError>()(
83 "PlatformEnvironmentRemovalError",
84 {
85 environmentId: EnvironmentId,
86 },
87) {
88 override get message(): string {
89 return `Platform-managed environment ${this.environmentId} cannot be removed.`;
90 }
91}
92
93export class EnvironmentRegistry extends Context.Service<
94 EnvironmentRegistry,
95 {
96 readonly entries: SubscriptionRef.SubscriptionRef<
97 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
98 >;
99 readonly networkStatus: SubscriptionRef.SubscriptionRef<NetworkStatus>;
100 readonly start: Effect.Effect<void>;
101 readonly register: (
102 registration: ConnectionRegistration,
103 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
104 readonly registerPlatform: (registration: PrimaryConnectionRegistration) => Effect.Effect<void>;
105 readonly reconcilePlatform: (
106 registrations: ReadonlyArray<PlatformConnectionRegistration>,
107 ) => Effect.Effect<void>;
108 readonly remove: (
109 environmentId: EnvironmentId,
110 ) => Effect.Effect<
111 void,
112 | Persistence.ConnectionPersistenceError
113 | ConnectionAttemptError
114 | EnvironmentNotRegisteredError
115 | PlatformEnvironmentRemovalError
116 >;
117 /**
118 * Drops one route. Removing an environment's last route removes the
119 * environment, the same as `remove`.
120 */
121 readonly removeRoute: (
122 environmentId: EnvironmentId,
123 routeId: string,
124 ) => Effect.Effect<
125 void,
126 | Persistence.ConnectionPersistenceError
127 | ConnectionAttemptError
128 | EnvironmentNotRegisteredError
129 | PlatformEnvironmentRemovalError
130 >;
131 /** Reorders an environment's routes; `routeIds` lists every route, preferred first. */
132 readonly reorderRoutes: (
133 environmentId: EnvironmentId,
134 routeIds: ReadonlyArray<string>,
135 ) => Effect.Effect<
136 void,
137 | Persistence.ConnectionPersistenceError
138 | EnvironmentNotRegisteredError
139 | PlatformEnvironmentRemovalError
140 | ConnectionBlockedError
141 >;
142 /**
143 * Drops the T3 Connect route of every environment, after a cloud sign-out
144 * or account change. Environments with no other route are removed.
145 */
146 readonly removeRelayEnvironments: () => Effect.Effect<
147 void,
148 | Persistence.ConnectionPersistenceError
149 | ConnectionAttemptError
150 | PlatformEnvironmentRemovalError
151 >;
152 readonly retryNow: (environmentId: EnvironmentId) => Effect.Effect<void>;
153 /**
154 * Switches a saved environment on or off. Off drops the socket, stops the
155 * retry ladder, and persists so the next launch stays off. Registration,
156 * credentials, and cache are untouched.
157 */
158 readonly setEnabled: (
159 environmentId: EnvironmentId,
160 enabled: boolean,
161 ) => Effect.Effect<
162 void,
163 | EnvironmentNotRegisteredError
164 | Persistence.ConnectionPersistenceError
165 | ConnectionBlockedError
166 >;
167 readonly setCompatibility: (
168 environmentId: EnvironmentId,
169 error: ConnectionBlockedError | null,
170 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
171 readonly state: (
172 environmentId: EnvironmentId,
173 ) => Effect.Effect<SupervisorConnectionState, EnvironmentNotRegisteredError>;
174 readonly stateChanges: (
175 environmentId: EnvironmentId,
176 ) => Stream.Stream<SupervisorConnectionState, EnvironmentNotRegisteredError>;
177 readonly run: <A, E, R>(
178 environmentId: EnvironmentId,
179 effect: Effect.Effect<A, E, R>,
180 ) => Effect.Effect<
181 A,
182 E | EnvironmentNotRegisteredError,
183 Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
184 >;
185 readonly runStream: <A, E, R>(
186 environmentId: EnvironmentId,
187 stream: Stream.Stream<A, E, R>,
188 ) => Stream.Stream<
189 A,
190 E | EnvironmentNotRegisteredError,
191 Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
192 >;
193 readonly followStream: <A, E, R>(
194 environmentId: EnvironmentId,
195 stream: Stream.Stream<A, E, R>,
196 ) => Stream.Stream<A, E, Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>>;
197 }
198>()("@t3tools/client-runtime/connection/registry/EnvironmentRegistry") {}
199
200interface EnvironmentServiceScope {
201 readonly entry: ConnectionCatalogEntry;
202 readonly supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"];
203 readonly scope: Scope.Closeable;
204}
205
206/** @public Service construction is part of the canonical Effect module API. */
207export const make = Effect.gen(function* () {
208 const registryScope = yield* Scope.Scope;
209 const storage = yield* Persistence.ConnectionTargetStore;
210 const registrations = yield* Persistence.ConnectionRegistrationStore;
211 const cache = yield* Persistence.EnvironmentCacheStore;
212 const ownedDataCleanup = yield* Persistence.EnvironmentOwnedDataCleanup;
213 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
214 const credentials = yield* ConnectionCredentialStore.ConnectionCredentialStore;
215 const githubRoutingPermissions = yield* GitHubRoutingPermissions;
216 const connectivity = yield* Connectivity.Connectivity;
217 const driver = yield* ConnectionDriver.ConnectionDriver;
218 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
219 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
220 const persistedTargets = yield* storage.list;
221 const disabledEnvironmentIds = new Set(yield* storage.listDisabled);
222 const loadRoute = Effect.fn("EnvironmentRegistry.loadRoute")(function* (
223 target: ConnectionTarget,
224 ) {
225 const profile: Option.Option<ConnectionProfile> =
226 target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
227 ? yield* profiles.get(target.connectionId)
228 : Option.none();
229 return { target, profile } satisfies ConnectionRoute;
230 });
231 const persistedRoutesByEnvironment = new Map<EnvironmentId, Array<ConnectionTarget>>();
232 for (const target of persistedTargets) {
233 const routes = persistedRoutesByEnvironment.get(target.environmentId) ?? [];
234 routes.push(target);
235 persistedRoutesByEnvironment.set(target.environmentId, routes);
236 }
237 const initialEntries = new Map(
238 yield* Effect.forEach(
239 persistedRoutesByEnvironment,
240 Effect.fn("EnvironmentRegistry.loadCatalogEntry")(function* ([environmentId, targets]) {
241 const loaded = yield* Effect.forEach(targets, loadRoute, { concurrency: "unbounded" });
242 // A learned route without its profile has no address to reach; it is
243 // learned again on the next connection. A paired route keeps its slot
244 // so its missing profile still surfaces as a connection error.
245 const seen = new Set<string>();
246 const usable = loaded.filter((route) => {
247 const id = connectionRouteId(route.target);
248 if (seen.has(id)) return false;
249 seen.add(id);
250 return !(id.startsWith("learned:") && Option.isNone(route.profile));
251 });
252 const routes = usable.length > 0 ? usable : loaded.slice(0, 1);
253 const first = routes[0]!;
254 return [
255 environmentId,
256 entryWithRoutes(
257 {
258 target: first.target,
259 profile: first.profile,
260 enabled: !disabledEnvironmentIds.has(environmentId),
261 },
262 routes,
263 ),
264 ] as const;
265 }),
266 { concurrency: "unbounded" },
267 ),
268 );
269 const entries =
270 yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(initialEntries);
271 const networkStatus = yield* SubscriptionRef.make(yield* connectivity.status);
272 const serviceScopes = yield* SubscriptionRef.make<
273 ReadonlyMap<EnvironmentId, EnvironmentServiceScope>
274 >(new Map());
275 const platformEnvironmentIds = yield* Ref.make<ReadonlySet<EnvironmentId>>(new Set());
276 const persistedEnvironmentIds = yield* Ref.make<ReadonlySet<EnvironmentId>>(
277 new Set(persistedRoutesByEnvironment.keys()),
278 );
279 interface LeaseLock {
280 readonly semaphore: Semaphore.Semaphore;
281 readonly users: number;
282 }
283
284 const leaseLocks = yield* Ref.make<ReadonlyMap<EnvironmentId, LeaseLock>>(new Map());
285 const leaseLocksGuard = yield* Semaphore.make(1);
286 const started = yield* Ref.make(false);
287
288 const withLeaseLock = <A, E, R>(
289 environmentId: EnvironmentId,
290 effect: Effect.Effect<A, E, R>,
291 ): Effect.Effect<A, E, R> =>
292 Effect.acquireUseRelease(
293 leaseLocksGuard.withPermits(1)(
294 Effect.gen(function* () {
295 const current = yield* Ref.get(leaseLocks);
296 const existing = current.get(environmentId);
297 if (existing !== undefined) {
298 yield* Ref.set(
299 leaseLocks,
300 new Map(current).set(environmentId, {
301 semaphore: existing.semaphore,
302 users: existing.users + 1,
303 }),
304 );
305 return existing.semaphore;
306 }
307 const semaphore = yield* Semaphore.make(1);
308 yield* Ref.set(leaseLocks, new Map(current).set(environmentId, { semaphore, users: 1 }));
309 return semaphore;
310 }),
311 ),
312 (semaphore) => semaphore.withPermits(1)(effect),
313 (semaphore) =>
314 leaseLocksGuard.withPermits(1)(
315 Ref.update(leaseLocks, (current) => {
316 const existing = current.get(environmentId);
317 if (existing === undefined || existing.semaphore !== semaphore) {
318 return current;
319 }
320 const next = new Map(current);
321 if (existing.users === 1) {
322 next.delete(environmentId);
323 } else {
324 next.set(environmentId, {
325 semaphore,
326 users: existing.users - 1,
327 });
328 }
329 return next;
330 }),
331 ),
332 ).pipe(Effect.withSpan("EnvironmentRegistry.withLeaseLock"));
333
334 const getEntry = Effect.fn("EnvironmentRegistry.getEntry")(function* (
335 environmentId: EnvironmentId,
336 ) {
337 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
338 if (entry === undefined) {
339 return yield* new EnvironmentNotRegisteredError({
340 environmentId,
341 });
342 }
343 return entry;
344 });
345
346 const closeServiceScope = Effect.fn("EnvironmentRegistry.closeServiceScope")(function* (
347 environmentId: EnvironmentId,
348 ) {
349 const current = yield* SubscriptionRef.get(serviceScopes);
350 const lease = current.get(environmentId);
351 if (lease === undefined) {
352 return;
353 }
354 const next = new Map(current);
355 next.delete(environmentId);
356 yield* SubscriptionRef.set(serviceScopes, next);
357 yield* Scope.close(lease.scope, Exit.void);
358 });
359
360 const createServiceScope = Effect.fn("EnvironmentRegistry.createServiceScope")(
361 (entry: ConnectionCatalogEntry) =>
362 Effect.uninterruptible(
363 Effect.gen(function* () {
364 const environmentId = entry.target.environmentId;
365 const scope = yield* Scope.fork(registryScope);
366 const supervisor = yield* EnvironmentSupervisor.make(entry, {
367 initiallyDesired: false,
368 learnRoutes: (input) => learnRoutes({ environmentId, ...input }),
369 }).pipe(
370 Effect.provideService(Connectivity.Connectivity, connectivity),
371 Effect.provideService(ConnectionDriver.ConnectionDriver, driver),
372 Effect.provideService(ConnectionWakeups.ConnectionWakeups, wakeups),
373 Scope.provide(scope),
374 Effect.onError(() => Scope.close(scope, Exit.void)),
375 );
376 if (entry.enabled) {
377 yield* supervisor.connect;
378 }
379 yield* SubscriptionRef.update(serviceScopes, (current) => {
380 const next = new Map(current);
381 next.set(environmentId, { entry, supervisor, scope });
382 return next;
383 });
384 yield* SubscriptionRef.changes(supervisor.state).pipe(
385 Stream.runForEach((state) =>
386 state.phase === "blocked" && state.lastFailure?.reason === "unsupported"
387 ? setCompatibility(environmentId, state.lastFailure).pipe(
388 Effect.catch((error) =>
389 Effect.logWarning("Could not disable an unsupported environment.", {
390 environmentId,
391 error,
392 }),
393 ),
394 )
395 : Effect.void,
396 ),
397 Effect.forkIn(scope),
398 );
399 return supervisor;
400 }),
401 ),
402 );
403
404 const acquireSupervisor = Effect.fn("EnvironmentRegistry.acquireSupervisor")(function* (
405 environmentId: EnvironmentId,
406 ) {
407 return yield* withLeaseLock(
408 environmentId,
409 Effect.gen(function* () {
410 const entry = yield* getEntry(environmentId);
411 const existing = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
412 if (existing !== undefined) {
413 if (Equal.equals(existing.entry, entry)) {
414 return existing.supervisor;
415 }
416 yield* closeServiceScope(environmentId);
417 }
418 return yield* createServiceScope(entry);
419 }),
420 );
421 });
422
423 const run: EnvironmentRegistry["Service"]["run"] = Effect.fn("EnvironmentRegistry.run")(
424 function* <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) {
425 const supervisor = yield* acquireSupervisor(environmentId);
426 return yield* Effect.provideService(
427 effect,
428 EnvironmentSupervisor.EnvironmentSupervisor,
429 supervisor,
430 );
431 },
432 );
433
434 const runStream: EnvironmentRegistry["Service"]["runStream"] = <A, E, R>(
435 environmentId: EnvironmentId,
436 stream: Stream.Stream<A, E, R>,
437 ) =>
438 Stream.unwrap(
439 acquireSupervisor(environmentId).pipe(
440 Effect.map((supervisor) =>
441 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
442 ),
443 ),
444 );
445
446 const followStream: EnvironmentRegistry["Service"]["followStream"] = <A, E, R>(
447 environmentId: EnvironmentId,
448 stream: Stream.Stream<A, E, R>,
449 ) =>
450 Stream.concat(
451 Stream.fromEffect(SubscriptionRef.get(entries)),
452 SubscriptionRef.changes(entries),
453 ).pipe(
454 Stream.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
455 // Re-pairing can replace the supervisor while its catalog details stay unchanged.
456 Stream.changesWith(
457 (previous, current) => Option.getOrNull(previous) === Option.getOrNull(current),
458 ),
459 Stream.switchMap(
460 Option.match({
461 onNone: () => Stream.empty,
462 onSome: () =>
463 Stream.unwrap(
464 acquireSupervisor(environmentId).pipe(
465 Effect.match({
466 onFailure: () => Stream.empty,
467 onSuccess: (supervisor) =>
468 Stream.provideService(
469 stream,
470 EnvironmentSupervisor.EnvironmentSupervisor,
471 supervisor,
472 ),
473 }),
474 ),
475 ),
476 }),
477 ),
478 );
479
480 const start = Effect.gen(function* () {
481 if (yield* Ref.getAndSet(started, true)) {
482 return;
483 }
484 yield* Effect.forEach(
485 persistedRoutesByEnvironment.keys(),
486 (environmentId) =>
487 acquireSupervisor(environmentId).pipe(
488 Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }),
489 ),
490 {
491 concurrency: "unbounded",
492 discard: true,
493 },
494 );
495 }).pipe(Effect.withSpan("EnvironmentRegistry.start"));
496
497 const installEntryLocked = Effect.fn("EnvironmentRegistry.installEntryLocked")(function* (
498 entry: ConnectionCatalogEntry,
499 options?: { readonly retainEquivalentRuntime?: boolean },
500 ) {
501 const target = entry.target;
502 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
503 const existingScope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
504 if (
505 options?.retainEquivalentRuntime === true &&
506 previous !== undefined &&
507 Equal.equals(previous, entry) &&
508 existingScope !== undefined &&
509 Equal.equals(existingScope.entry, entry)
510 ) {
511 return;
512 }
513
514 yield* closeServiceScope(target.environmentId);
515 yield* SubscriptionRef.update(entries, (current) => {
516 const next = new Map(current);
517 next.set(target.environmentId, entry);
518 return next;
519 });
520 yield* createServiceScope(entry);
521 });
522
523 const forgetRoutingTrust = (
524 environmentId: EnvironmentId,
525 operation: "register-connection" | "set-connection-routes",
526 ) =>
527 githubRoutingPermissions.forget(environmentId).pipe(
528 Effect.mapError(
529 (error) =>
530 new Persistence.ConnectionPersistenceError({
531 operation,
532 message: error.message,
533 }),
534 ),
535 );
536
537 const persistedRoutes = (entry: ConnectionCatalogEntry) =>
538 connectionRoutes(entry).map((route) => route.target as PersistedConnectionTarget);
539
540 /**
541 * The entry after its routes change. GitHub trust and an unsupported
542 * verdict both belong to the saved addresses: a changed set may reach a
543 * different server, so both are dropped and the next connection decides.
544 * Reordering keeps the same addresses, so both stay.
545 */
546 const withRoutes = (previous: ConnectionCatalogEntry, routes: ReadonlyArray<ConnectionRoute>) => {
547 const next = entryWithRoutes(previous, routes);
548 if (gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(next)) {
549 return { entry: next, addressesChanged: false };
550 }
551 const { unsupportedReason: _reason, serverUpdateRequired: _update, ...rest } = next;
552 return { entry: rest, addressesChanged: true };
553 };
554
555 const register = Effect.fn("EnvironmentRegistry.register")(function* (
556 registration: ConnectionRegistration,
557 ) {
558 const registered = connectionRegistrationCatalogEntry(registration);
559 const environmentId = registered.target.environmentId;
560 yield* withLeaseLock(
561 environmentId,
562 Effect.gen(function* () {
563 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
564 return;
565 }
566 // A new route joins the environment's saved routes. Registering one it
567 // already has (the same id, or a pairing to the same address) replaces
568 // it in place. Editing keeps the disabled state.
569 const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
570 let entry = registered;
571 if (previous !== undefined) {
572 const route: ConnectionRoute = { target: registered.target, profile: registered.profile };
573 const existing = connectionRoutes(previous);
574 const sameAddress = findRouteToSameAddress(existing, route);
575 const routes = existing.filter(
576 (existing) =>
577 existing !== sameAddress ||
578 connectionRouteId(existing.target) === connectionRouteId(route.target),
579 );
580 const next = withRoutes(previous, upsertRoute(routes, route));
581 if (next.addressesChanged) {
582 yield* forgetRoutingTrust(environmentId, "register-connection");
583 }
584 entry = next.entry;
585 }
586 yield* registrations.register(registration, persistedRoutes(entry));
587 yield* Ref.update(persistedEnvironmentIds, (current) =>
588 new Set(current).add(environmentId),
589 );
590 yield* installEntryLocked(entry);
591 }),
592 );
593 });
594
595 /** Writes a new route list for a user-saved environment and restarts its connection. */
596 const replaceRoutesLocked = Effect.fn("EnvironmentRegistry.replaceRoutesLocked")(function* (
597 previous: ConnectionCatalogEntry,
598 routes: ReadonlyArray<ConnectionRoute>,
599 ) {
600 const environmentId = previous.target.environmentId;
601 const next = withRoutes(previous, routes);
602 if (next.addressesChanged) {
603 yield* forgetRoutingTrust(environmentId, "set-connection-routes");
604 }
605 yield* registrations.setRoutes(environmentId, persistedRoutes(next.entry));
606 yield* installEntryLocked(next.entry);
607 });
608
609 const userEntry = Effect.fn("EnvironmentRegistry.userEntry")(function* (
610 environmentId: EnvironmentId,
611 ) {
612 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
613 return yield* new PlatformEnvironmentRemovalError({ environmentId });
614 }
615 return yield* getEntry(environmentId);
616 });
617
618 const installPlatformRegistration = Effect.fn("EnvironmentRegistry.installPlatformRegistration")(
619 function* (registration: PlatformConnectionRegistration) {
620 const registered = connectionRegistrationCatalogEntry(registration);
621 const target = registered.target;
622 yield* withLeaseLock(
623 target.environmentId,
624 Effect.gen(function* () {
625 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
626 const entry: ConnectionCatalogEntry =
627 previous?.unsupportedReason !== undefined &&
628 gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
629 ? { ...registered, enabled: false, ...unsupportedState(previous) }
630 : registered;
631 const persisted = (yield* Ref.get(persistedEnvironmentIds)).has(target.environmentId);
632 if (
633 persisted ||
634 (previous !== undefined &&
635 gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry))
636 ) {
637 const revoked = yield* githubRoutingPermissions.forget(target.environmentId).pipe(
638 Effect.tapError((error) =>
639 Effect.logWarning(
640 "Could not clear GitHub routing permission for a platform environment.",
641 {
642 environmentId: target.environmentId,
643 error,
644 },
645 ),
646 ),
647 Effect.exit,
648 );
649 if (Exit.isFailure(revoked)) return;
650 }
651 yield* Ref.update(platformEnvironmentIds, (current) => {
652 const next = new Set(current);
653 next.add(target.environmentId);
654 return next;
655 });
656
657 // Secondary desktop-local backends (e.g. a parallel WSL backend) live
658 // on their own loopback origin, so they authenticate with a bearer
659 // token instead of the primary's same-origin cookie. Stash it where
660 // the resolver's bearer broker looks it up.
661 let bearerReplaced = false;
662 if (registration._tag === "BearerConnectionRegistration") {
663 const stored = yield* credentials
664 .get(registration.target.connectionId)
665 .pipe(Effect.orElseSucceed(() => Option.none<ConnectionCredential>()));
666 const changed =
667 Option.isSome(stored) && !Equal.equals(stored.value, registration.credential);
668 // Only a bearer that was actually stored can be retried with; a
669 // failed write leaves the rejected one in place.
670 bearerReplaced = yield* credentials
671 .put(registration.target.connectionId, registration.credential)
672 .pipe(
673 Effect.as(changed),
674 Effect.catch((error) =>
675 Effect.logWarning("Could not store the platform bearer credential.", {
676 environmentId: target.environmentId,
677 error,
678 }).pipe(Effect.as(false)),
679 ),
680 );
681 }
682
683 if (persisted) {
684 yield* registrations.remove(target.environmentId).pipe(
685 Effect.tap(() =>
686 Ref.update(persistedEnvironmentIds, (current) => {
687 const next = new Set(current);
688 next.delete(target.environmentId);
689 return next;
690 }),
691 ),
692 Effect.catch((error) =>
693 Effect.logWarning(
694 "Could not remove a persisted registration shadowed by a platform environment.",
695 {
696 environmentId: target.environmentId,
697 error,
698 },
699 ),
700 ),
701 );
702 }
703
704 yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
705
706 // The catalog entry carries no credential, so a fresh bearer keeps
707 // the equivalent runtime. Anything not yet connected may be using the
708 // old bearer: an attempt in flight would fail with it and then wait
709 // blocked for a manual retry. Retry with the new one instead. A
710 // connected session keeps its socket.
711 if (bearerReplaced) {
712 const scope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
713 if (scope !== undefined) {
714 const state = yield* SubscriptionRef.get(scope.supervisor.state);
715 if (
716 state.phase === "connecting" ||
717 state.phase === "backoff" ||
718 (state.phase === "blocked" &&
719 state.lastFailure?._tag === "ConnectionBlockedError" &&
720 state.lastFailure.reason === "authentication")
721 ) {
722 yield* scope.supervisor.retryNow;
723 }
724 }
725 }
726 }),
727 );
728 },
729 );
730
731 // Tear down a platform-managed environment that the host no longer reports
732 // (e.g. the user turned the parallel WSL backend off). Platform environments
733 // bypass the user-facing `remove` guard since they are reconciled from the
734 // bootstrap rather than removed by hand.
735 const removePlatformEnvironment = Effect.fn("EnvironmentRegistry.removePlatformEnvironment")(
736 function* (environmentId: EnvironmentId) {
737 yield* withLeaseLock(
738 environmentId,
739 Effect.gen(function* () {
740 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
741 const revoked = yield* githubRoutingPermissions.forget(environmentId).pipe(
742 Effect.tapError((error) =>
743 Effect.logWarning(
744 "Could not clear GitHub routing permission after platform removal.",
745 {
746 environmentId,
747 error,
748 },
749 ),
750 ),
751 Effect.exit,
752 );
753 if (Exit.isFailure(revoked)) return;
754 yield* Ref.update(platformEnvironmentIds, (current) => {
755 const next = new Set(current);
756 next.delete(environmentId);
757 return next;
758 });
759 yield* closeServiceScope(environmentId);
760 yield* SubscriptionRef.update(entries, (current) => {
761 const next = new Map(current);
762 next.delete(environmentId);
763 return next;
764 });
765 if (entry !== undefined && entry.target._tag === "BearerConnectionTarget") {
766 yield* credentials.remove(entry.target.connectionId).pipe(
767 Effect.catch((error) =>
768 Effect.logWarning("Could not clear the platform bearer credential.", {
769 environmentId,
770 error,
771 }),
772 ),
773 );
774 }
775 yield* Effect.all(
776 [
777 cache.clear(environmentId).pipe(
778 Effect.catch((error) =>
779 Effect.logWarning("Could not clear cached environment data after removal.", {
780 environmentId,
781 error,
782 }),
783 ),
784 ),
785 ownedDataCleanup.clear(environmentId),
786 ],
787 { concurrency: "unbounded", discard: true },
788 );
789 }),
790 );
791 },
792 );
793
794 const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* (
795 registration: PrimaryConnectionRegistration,
796 ) {
797 yield* installPlatformRegistration(registration);
798 });
799
800 // Reconcile the full set of platform-managed environments against what the
801 // host currently reports: add/refresh the desired ones and tear down any
802 // platform environment that disappeared (WSL toggled off, distro switched).
803 const reconcilePlatform = Effect.fn("EnvironmentRegistry.reconcilePlatform")(function* (
804 platformRegistrations: ReadonlyArray<PlatformConnectionRegistration>,
805 ) {
806 const desiredIds = new Set(
807 platformRegistrations.map((registration) => registration.target.environmentId),
808 );
809 const currentPlatformIds = yield* Ref.get(platformEnvironmentIds);
810 yield* Effect.forEach(
811 currentPlatformIds,
812 (environmentId) =>
813 desiredIds.has(environmentId) ? Effect.void : removePlatformEnvironment(environmentId),
814 { discard: true },
815 );
816 yield* Effect.forEach(platformRegistrations, installPlatformRegistration, { discard: true });
817 });
818
819 /** Forgets a user-saved environment. Callers hold its lease lock. */
820 const removeLocked = Effect.fn("EnvironmentRegistry.removeLocked")(function* (
821 environmentId: EnvironmentId,
822 ) {
823 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
824 return yield* new PlatformEnvironmentRemovalError({
825 environmentId,
826 });
827 }
828 const entry = yield* getEntry(environmentId);
829
830 yield* githubRoutingPermissions.forget(environmentId);
831 yield* registrations.remove(environmentId);
832 yield* Ref.update(persistedEnvironmentIds, (current) => {
833 const next = new Set(current);
834 next.delete(environmentId);
835 return next;
836 });
837 yield* closeServiceScope(environmentId);
838 yield* SubscriptionRef.update(entries, (current) => {
839 const next = new Map(current);
840 next.delete(environmentId);
841 return next;
842 });
843 yield* Effect.all(
844 [
845 cache.clear(environmentId).pipe(
846 Effect.catch((error) =>
847 Effect.logWarning("Could not clear cached environment data after removal.", {
848 environmentId,
849 error,
850 }),
851 ),
852 ),
853 ownedDataCleanup.clear(environmentId),
854 ],
855 { concurrency: "unbounded", discard: true },
856 );
857
858 for (const route of connectionRoutes(entry)) {
859 const profile = Option.getOrNull(route.profile);
860 if (profile !== null && isSshConnectionProfile(profile)) {
861 yield* disconnectSsh(environmentId, profile);
862 }
863 }
864 });
865
866 const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) {
867 return yield* withLeaseLock(environmentId, removeLocked(environmentId));
868 });
869
870 const disconnectSsh = (environmentId: EnvironmentId, profile: SshConnectionProfile) =>
871 ssh.disconnect(profile.target).pipe(
872 Effect.tapError((error) =>
873 Effect.logWarning("Could not disconnect the managed SSH environment.", {
874 environmentId,
875 error,
876 }),
877 ),
878 Effect.ignore,
879 );
880
881 // Plain HTTP routes are unusable from an HTTPS page, which blocks mixed content.
882 const allowInsecureRoutes =
883 typeof globalThis.location === "undefined" || globalThis.location.protocol !== "https:";
884
885 /**
886 * Saves the direct addresses a connected server reports as learned routes,
887 * replacing learned routes it no longer reports. Routes the user saved are
888 * never changed. Learned routes reuse the active route's credential, so they
889 * do not revoke GitHub routing trust the way a newly paired address does.
890 */
891 const learnRoutes = Effect.fn("EnvironmentRegistry.learnRoutes")(function* (input: {
892 readonly environmentId: EnvironmentId;
893 readonly activeRoute: ConnectionRoute;
894 readonly reported: ReadonlyArray<{ readonly httpBaseUrl: string }>;
895 }) {
896 return yield* withLeaseLock(
897 input.environmentId,
898 Effect.gen(function* () {
899 if ((yield* Ref.get(platformEnvironmentIds)).has(input.environmentId)) {
900 return Option.none<ConnectionCatalogEntry>();
901 }
902 const entry = (yield* SubscriptionRef.get(entries)).get(input.environmentId);
903 if (entry === undefined) return Option.none<ConnectionCatalogEntry>();
904 const routes = mergeLearnedRoutes({
905 entry,
906 activeRoute: input.activeRoute,
907 reported: input.reported,
908 allowInsecure: allowInsecureRoutes,
909 });
910 if (routes === null) return Option.none<ConnectionCatalogEntry>();
911 const next = entryWithRoutes(entry, routes);
912 // A learned route owns its profile (address and authorization); the
913 // credential stays with the route it borrows from.
914 const previousIds = new Set(
915 connectionRoutes(entry).map((route) => connectionRouteId(route.target)),
916 );
917 for (const route of routes) {
918 if (!isLearned(route) || previousIds.has(connectionRouteId(route.target))) continue;
919 const profile = Option.getOrNull(route.profile);
920 if (profile !== null) yield* profiles.put(profile);
921 }
922 yield* registrations.setRoutes(input.environmentId, persistedRoutes(next));
923 // Update the lease in place: the live session already works, and
924 // `installEntryLocked` would replace it for a route list change.
925 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(input.environmentId);
926 if (lease !== undefined) {
927 yield* SubscriptionRef.update(serviceScopes, (current) =>
928 new Map(current).set(input.environmentId, { ...lease, entry: next }),
929 );
930 }
931 yield* SubscriptionRef.update(entries, (current) =>
932 new Map(current).set(input.environmentId, next),
933 );
934 return Option.some(next);
935 }),
936 ).pipe(
937 Effect.catch((error) =>
938 Effect.logWarning("Could not save routes learned from the environment.", {
939 environmentId: input.environmentId,
940 error,
941 }).pipe(Effect.as(Option.none<ConnectionCatalogEntry>())),
942 ),
943 );
944 });
945
946 const removeRoute = Effect.fn("EnvironmentRegistry.removeRoute")(function* (
947 environmentId: EnvironmentId,
948 routeId: string,
949 ) {
950 // One lock for the whole decision: a route registered between "this was
951 // the last route" and the removal must not be deleted with it.
952 yield* withLeaseLock(
953 environmentId,
954 Effect.gen(function* () {
955 const entry = yield* userEntry(environmentId);
956 const routes = connectionRoutes(entry);
957 const route = routes.find((candidate) => connectionRouteId(candidate.target) === routeId);
958 if (route === undefined) return;
959 const remaining = routesAfterRemoving(routes, routeId);
960 if (remaining.length === 0) return yield* removeLocked(environmentId);
961 yield* replaceRoutesLocked(entry, remaining);
962 const profile = Option.getOrNull(route.profile);
963 if (profile !== null && isSshConnectionProfile(profile)) {
964 yield* disconnectSsh(environmentId, profile);
965 }
966 }),
967 );
968 });
969
970 const reorderRoutes = Effect.fn("EnvironmentRegistry.reorderRoutes")(function* (
971 environmentId: EnvironmentId,
972 routeIds: ReadonlyArray<string>,
973 ) {
974 yield* withLeaseLock(
975 environmentId,
976 Effect.gen(function* () {
977 const entry = yield* userEntry(environmentId);
978 const routes = connectionRoutes(entry);
979 const byId = new Map(routes.map((route) => [connectionRouteId(route.target), route]));
980 const reordered = routeIds.flatMap((id) => byId.get(id) ?? []);
981 if (reordered.length !== routes.length || new Set(routeIds).size !== routes.length) {
982 return yield* new ConnectionBlockedError({
983 reason: "configuration",
984 detail: "The route order must list every saved route once.",
985 });
986 }
987 if (reordered.every((route, index) => route === routes[index])) return;
988 yield* replaceRoutesLocked(entry, reordered);
989 }),
990 );
991 });
992
993 const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(
994 function* () {
995 const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]
996 .filter((entry) =>
997 connectionRoutes(entry).some((route) => route.target._tag === "RelayConnectionTarget"),
998 )
999 .map((entry) => entry.target.environmentId);
1000
1001 yield* Effect.forEach(
1002 relayEnvironmentIds,
1003 (environmentId) =>
1004 removeRoute(environmentId, RELAY_ROUTE_ID).pipe(
1005 Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }),
1006 ),
1007 {
1008 concurrency: "unbounded",
1009 discard: true,
1010 },
1011 );
1012 },
1013 );
1014
1015 const retryNow = (environmentId: EnvironmentId) =>
1016 acquireSupervisor(environmentId).pipe(
1017 Effect.flatMap((supervisor) => supervisor.retryNow),
1018 Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }),
1019 Effect.withSpan("EnvironmentRegistry.retryNow"),
1020 );
1021 const setEnabled = Effect.fn("EnvironmentRegistry.setEnabled")(function* (
1022 environmentId: EnvironmentId,
1023 enabled: boolean,
1024 ) {
1025 yield* withLeaseLock(
1026 environmentId,
1027 Effect.gen(function* () {
1028 const entry = yield* getEntry(environmentId);
1029 if (enabled && entry.unsupportedReason !== undefined) {
1030 return yield* new ConnectionBlockedError({
1031 reason: "unsupported",
1032 detail: entry.unsupportedReason,
1033 });
1034 }
1035 if (entry.enabled === enabled) {
1036 return;
1037 }
1038 // Platform-managed environments are reconciled from the host and are
1039 // never persisted, so only user-saved ones write the flag.
1040 if (!(yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
1041 yield* registrations.setEnabled(environmentId, enabled);
1042 }
1043 const next: ConnectionCatalogEntry = { ...entry, enabled };
1044 // Update the lease in place so the supervisor keeps its generation and
1045 // durable streams; `installEntryLocked` would tear it down instead.
1046 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
1047 if (lease !== undefined) {
1048 yield* SubscriptionRef.update(serviceScopes, (current) => {
1049 const nextScopes = new Map(current);
1050 nextScopes.set(environmentId, { ...lease, entry: next });
1051 return nextScopes;
1052 });
1053 }
1054 yield* SubscriptionRef.update(entries, (current) => {
1055 const nextEntries = new Map(current);
1056 nextEntries.set(environmentId, next);
1057 return nextEntries;
1058 });
1059 if (lease !== undefined) {
1060 yield* enabled ? lease.supervisor.connect : lease.supervisor.disconnect;
1061 } else if (enabled) {
1062 yield* createServiceScope(next);
1063 }
1064 // The supervisor only owns the RPC session. A managed SSH backend and
1065 // its tunnel outlive it, so switching off tears those down as well.
1066 if (!enabled) {
1067 for (const route of connectionRoutes(entry)) {
1068 const profile = Option.getOrNull(route.profile);
1069 if (profile !== null && isSshConnectionProfile(profile)) {
1070 yield* disconnectSsh(environmentId, profile);
1071 }
1072 }
1073 }
1074 }),
1075 );
1076 });
1077
1078 const state = Effect.fn("EnvironmentRegistry.state")(function* (environmentId: EnvironmentId) {
1079 const supervisor = yield* acquireSupervisor(environmentId);
1080 return yield* SubscriptionRef.get(supervisor.state);
1081 });
1082 const stateChanges = (environmentId: EnvironmentId) =>
1083 followStream(
1084 environmentId,
1085 Stream.unwrap(
1086 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
1087 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.state)),
1088 ),
1089 ),
1090 );
1091
1092 yield* Effect.addFinalizer(() =>
1093 SubscriptionRef.get(serviceScopes).pipe(
1094 Effect.flatMap((current) =>
1095 Effect.forEach(current.values(), (lease) => Scope.close(lease.scope, Exit.void), {
1096 concurrency: "unbounded",
1097 discard: true,
1098 }),
1099 ),
1100 ),
1101 );
1102 yield* connectivity.changes.pipe(
1103 Stream.runForEach((status) => SubscriptionRef.set(networkStatus, status)),
1104 Effect.forkScoped,
1105 );
1106
1107 const setCompatibility = Effect.fn("EnvironmentRegistry.setCompatibility")(function* (
1108 environmentId: EnvironmentId,
1109 error: ConnectionBlockedError | null,
1110 ) {
1111 yield* withLeaseLock(
1112 environmentId,
1113 Effect.gen(function* () {
1114 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
1115 if (
1116 entry === undefined ||
1117 (entry.unsupportedReason === (error?.message ?? undefined) &&
1118 entry.serverUpdateRequired === (error?.serverUpdateRequired ?? undefined))
1119 )
1120 return;
1121 const {
1122 unsupportedReason: _previousReason,
1123 serverUpdateRequired: _previousUpdateRequired,
1124 ...rest
1125 } = entry;
1126 const next: ConnectionCatalogEntry =
1127 error === null
1128 ? rest
1129 : {
1130 ...rest,
1131 enabled: false,
1132 unsupportedReason: error.message,
1133 ...(error.serverUpdateRequired === true ? { serverUpdateRequired: true } : {}),
1134 };
1135 if (
1136 error !== null &&
1137 entry.enabled &&
1138 !(yield* Ref.get(platformEnvironmentIds)).has(environmentId)
1139 ) {
1140 yield* registrations.setEnabled(environmentId, false);
1141 }
1142 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
1143 if (lease !== undefined) {
1144 yield* SubscriptionRef.update(serviceScopes, (current) =>
1145 new Map(current).set(environmentId, { ...lease, entry: next }),
1146 );
1147 if (error !== null) yield* lease.supervisor.disconnect;
1148 }
1149 yield* SubscriptionRef.update(entries, (current) =>
1150 new Map(current).set(environmentId, next),
1151 );
1152 }),
1153 );
1154 });
1155
1156 return EnvironmentRegistry.of({
1157 entries,
1158 networkStatus,
1159 start,
1160 register,
1161 registerPlatform,
1162 reconcilePlatform,
1163 remove,
1164 removeRoute,
1165 reorderRoutes,
1166 removeRelayEnvironments,
1167 retryNow,
1168 setEnabled,
1169 setCompatibility,
1170 state,
1171 stateChanges,
1172 run,
1173 runStream,
1174 followStream,
1175 });
1176});
1177
1178export const layer = Layer.effect(EnvironmentRegistry, make);