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 Stream.changes,
456 Stream.switchMap(
457 Option.match({
458 onNone: () => Stream.empty,
459 onSome: () =>
460 Stream.unwrap(
461 acquireSupervisor(environmentId).pipe(
462 Effect.match({
463 onFailure: () => Stream.empty,
464 onSuccess: (supervisor) =>
465 Stream.provideService(
466 stream,
467 EnvironmentSupervisor.EnvironmentSupervisor,
468 supervisor,
469 ),
470 }),
471 ),
472 ),
473 }),
474 ),
475 );
476
477 const start = Effect.gen(function* () {
478 if (yield* Ref.getAndSet(started, true)) {
479 return;
480 }
481 yield* Effect.forEach(
482 persistedRoutesByEnvironment.keys(),
483 (environmentId) =>
484 acquireSupervisor(environmentId).pipe(
485 Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }),
486 ),
487 {
488 concurrency: "unbounded",
489 discard: true,
490 },
491 );
492 }).pipe(Effect.withSpan("EnvironmentRegistry.start"));
493
494 const installEntryLocked = Effect.fn("EnvironmentRegistry.installEntryLocked")(function* (
495 entry: ConnectionCatalogEntry,
496 options?: { readonly retainEquivalentRuntime?: boolean },
497 ) {
498 const target = entry.target;
499 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
500 const existingScope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
501 if (
502 options?.retainEquivalentRuntime === true &&
503 previous !== undefined &&
504 Equal.equals(previous, entry) &&
505 existingScope !== undefined &&
506 Equal.equals(existingScope.entry, entry)
507 ) {
508 return;
509 }
510
511 yield* closeServiceScope(target.environmentId);
512 yield* SubscriptionRef.update(entries, (current) => {
513 const next = new Map(current);
514 next.set(target.environmentId, entry);
515 return next;
516 });
517 yield* createServiceScope(entry);
518 });
519
520 const forgetRoutingTrust = (
521 environmentId: EnvironmentId,
522 operation: "register-connection" | "set-connection-routes",
523 ) =>
524 githubRoutingPermissions.forget(environmentId).pipe(
525 Effect.mapError(
526 (error) =>
527 new Persistence.ConnectionPersistenceError({
528 operation,
529 message: error.message,
530 }),
531 ),
532 );
533
534 const persistedRoutes = (entry: ConnectionCatalogEntry) =>
535 connectionRoutes(entry).map((route) => route.target as PersistedConnectionTarget);
536
537 /**
538 * The entry after its routes change. GitHub trust and an unsupported
539 * verdict both belong to the saved addresses: a changed set may reach a
540 * different server, so both are dropped and the next connection decides.
541 * Reordering keeps the same addresses, so both stay.
542 */
543 const withRoutes = (previous: ConnectionCatalogEntry, routes: ReadonlyArray<ConnectionRoute>) => {
544 const next = entryWithRoutes(previous, routes);
545 if (gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(next)) {
546 return { entry: next, addressesChanged: false };
547 }
548 const { unsupportedReason: _reason, serverUpdateRequired: _update, ...rest } = next;
549 return { entry: rest, addressesChanged: true };
550 };
551
552 const register = Effect.fn("EnvironmentRegistry.register")(function* (
553 registration: ConnectionRegistration,
554 ) {
555 const registered = connectionRegistrationCatalogEntry(registration);
556 const environmentId = registered.target.environmentId;
557 yield* withLeaseLock(
558 environmentId,
559 Effect.gen(function* () {
560 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
561 return;
562 }
563 // A new route joins the environment's saved routes. Registering one it
564 // already has (the same id, or a pairing to the same address) replaces
565 // it in place. Editing keeps the disabled state.
566 const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
567 let entry = registered;
568 if (previous !== undefined) {
569 const route: ConnectionRoute = { target: registered.target, profile: registered.profile };
570 const existing = connectionRoutes(previous);
571 const sameAddress = findRouteToSameAddress(existing, route);
572 const routes = existing.filter(
573 (existing) =>
574 existing !== sameAddress ||
575 connectionRouteId(existing.target) === connectionRouteId(route.target),
576 );
577 const next = withRoutes(previous, upsertRoute(routes, route));
578 if (next.addressesChanged) {
579 yield* forgetRoutingTrust(environmentId, "register-connection");
580 }
581 entry = next.entry;
582 }
583 yield* registrations.register(registration, persistedRoutes(entry));
584 yield* Ref.update(persistedEnvironmentIds, (current) =>
585 new Set(current).add(environmentId),
586 );
587 yield* installEntryLocked(entry);
588 }),
589 );
590 });
591
592 /** Writes a new route list for a user-saved environment and restarts its connection. */
593 const replaceRoutesLocked = Effect.fn("EnvironmentRegistry.replaceRoutesLocked")(function* (
594 previous: ConnectionCatalogEntry,
595 routes: ReadonlyArray<ConnectionRoute>,
596 ) {
597 const environmentId = previous.target.environmentId;
598 const next = withRoutes(previous, routes);
599 if (next.addressesChanged) {
600 yield* forgetRoutingTrust(environmentId, "set-connection-routes");
601 }
602 yield* registrations.setRoutes(environmentId, persistedRoutes(next.entry));
603 yield* installEntryLocked(next.entry);
604 });
605
606 const userEntry = Effect.fn("EnvironmentRegistry.userEntry")(function* (
607 environmentId: EnvironmentId,
608 ) {
609 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
610 return yield* new PlatformEnvironmentRemovalError({ environmentId });
611 }
612 return yield* getEntry(environmentId);
613 });
614
615 const installPlatformRegistration = Effect.fn("EnvironmentRegistry.installPlatformRegistration")(
616 function* (registration: PlatformConnectionRegistration) {
617 const registered = connectionRegistrationCatalogEntry(registration);
618 const target = registered.target;
619 yield* withLeaseLock(
620 target.environmentId,
621 Effect.gen(function* () {
622 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
623 const entry: ConnectionCatalogEntry =
624 previous?.unsupportedReason !== undefined &&
625 gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
626 ? { ...registered, enabled: false, ...unsupportedState(previous) }
627 : registered;
628 const persisted = (yield* Ref.get(persistedEnvironmentIds)).has(target.environmentId);
629 if (
630 persisted ||
631 (previous !== undefined &&
632 gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry))
633 ) {
634 const revoked = yield* githubRoutingPermissions.forget(target.environmentId).pipe(
635 Effect.tapError((error) =>
636 Effect.logWarning(
637 "Could not clear GitHub routing permission for a platform environment.",
638 {
639 environmentId: target.environmentId,
640 error,
641 },
642 ),
643 ),
644 Effect.exit,
645 );
646 if (Exit.isFailure(revoked)) return;
647 }
648 yield* Ref.update(platformEnvironmentIds, (current) => {
649 const next = new Set(current);
650 next.add(target.environmentId);
651 return next;
652 });
653
654 // Secondary desktop-local backends (e.g. a parallel WSL backend) live
655 // on their own loopback origin, so they authenticate with a bearer
656 // token instead of the primary's same-origin cookie. Stash it where
657 // the resolver's bearer broker looks it up.
658 let bearerReplaced = false;
659 if (registration._tag === "BearerConnectionRegistration") {
660 const stored = yield* credentials
661 .get(registration.target.connectionId)
662 .pipe(Effect.orElseSucceed(() => Option.none<ConnectionCredential>()));
663 const changed =
664 Option.isSome(stored) && !Equal.equals(stored.value, registration.credential);
665 // Only a bearer that was actually stored can be retried with; a
666 // failed write leaves the rejected one in place.
667 bearerReplaced = yield* credentials
668 .put(registration.target.connectionId, registration.credential)
669 .pipe(
670 Effect.as(changed),
671 Effect.catch((error) =>
672 Effect.logWarning("Could not store the platform bearer credential.", {
673 environmentId: target.environmentId,
674 error,
675 }).pipe(Effect.as(false)),
676 ),
677 );
678 }
679
680 if (persisted) {
681 yield* registrations.remove(target.environmentId).pipe(
682 Effect.tap(() =>
683 Ref.update(persistedEnvironmentIds, (current) => {
684 const next = new Set(current);
685 next.delete(target.environmentId);
686 return next;
687 }),
688 ),
689 Effect.catch((error) =>
690 Effect.logWarning(
691 "Could not remove a persisted registration shadowed by a platform environment.",
692 {
693 environmentId: target.environmentId,
694 error,
695 },
696 ),
697 ),
698 );
699 }
700
701 yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
702
703 // The catalog entry carries no credential, so a fresh bearer keeps
704 // the equivalent runtime. Anything not yet connected may be using the
705 // old bearer: an attempt in flight would fail with it and then wait
706 // blocked for a manual retry. Retry with the new one instead. A
707 // connected session keeps its socket.
708 if (bearerReplaced) {
709 const scope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
710 if (scope !== undefined) {
711 const state = yield* SubscriptionRef.get(scope.supervisor.state);
712 if (
713 state.phase === "connecting" ||
714 state.phase === "backoff" ||
715 (state.phase === "blocked" &&
716 state.lastFailure?._tag === "ConnectionBlockedError" &&
717 state.lastFailure.reason === "authentication")
718 ) {
719 yield* scope.supervisor.retryNow;
720 }
721 }
722 }
723 }),
724 );
725 },
726 );
727
728 // Tear down a platform-managed environment that the host no longer reports
729 // (e.g. the user turned the parallel WSL backend off). Platform environments
730 // bypass the user-facing `remove` guard since they are reconciled from the
731 // bootstrap rather than removed by hand.
732 const removePlatformEnvironment = Effect.fn("EnvironmentRegistry.removePlatformEnvironment")(
733 function* (environmentId: EnvironmentId) {
734 yield* withLeaseLock(
735 environmentId,
736 Effect.gen(function* () {
737 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
738 const revoked = yield* githubRoutingPermissions.forget(environmentId).pipe(
739 Effect.tapError((error) =>
740 Effect.logWarning(
741 "Could not clear GitHub routing permission after platform removal.",
742 {
743 environmentId,
744 error,
745 },
746 ),
747 ),
748 Effect.exit,
749 );
750 if (Exit.isFailure(revoked)) return;
751 yield* Ref.update(platformEnvironmentIds, (current) => {
752 const next = new Set(current);
753 next.delete(environmentId);
754 return next;
755 });
756 yield* closeServiceScope(environmentId);
757 yield* SubscriptionRef.update(entries, (current) => {
758 const next = new Map(current);
759 next.delete(environmentId);
760 return next;
761 });
762 if (entry !== undefined && entry.target._tag === "BearerConnectionTarget") {
763 yield* credentials.remove(entry.target.connectionId).pipe(
764 Effect.catch((error) =>
765 Effect.logWarning("Could not clear the platform bearer credential.", {
766 environmentId,
767 error,
768 }),
769 ),
770 );
771 }
772 yield* Effect.all(
773 [
774 cache.clear(environmentId).pipe(
775 Effect.catch((error) =>
776 Effect.logWarning("Could not clear cached environment data after removal.", {
777 environmentId,
778 error,
779 }),
780 ),
781 ),
782 ownedDataCleanup.clear(environmentId),
783 ],
784 { concurrency: "unbounded", discard: true },
785 );
786 }),
787 );
788 },
789 );
790
791 const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* (
792 registration: PrimaryConnectionRegistration,
793 ) {
794 yield* installPlatformRegistration(registration);
795 });
796
797 // Reconcile the full set of platform-managed environments against what the
798 // host currently reports: add/refresh the desired ones and tear down any
799 // platform environment that disappeared (WSL toggled off, distro switched).
800 const reconcilePlatform = Effect.fn("EnvironmentRegistry.reconcilePlatform")(function* (
801 platformRegistrations: ReadonlyArray<PlatformConnectionRegistration>,
802 ) {
803 const desiredIds = new Set(
804 platformRegistrations.map((registration) => registration.target.environmentId),
805 );
806 const currentPlatformIds = yield* Ref.get(platformEnvironmentIds);
807 yield* Effect.forEach(
808 currentPlatformIds,
809 (environmentId) =>
810 desiredIds.has(environmentId) ? Effect.void : removePlatformEnvironment(environmentId),
811 { discard: true },
812 );
813 yield* Effect.forEach(platformRegistrations, installPlatformRegistration, { discard: true });
814 });
815
816 /** Forgets a user-saved environment. Callers hold its lease lock. */
817 const removeLocked = Effect.fn("EnvironmentRegistry.removeLocked")(function* (
818 environmentId: EnvironmentId,
819 ) {
820 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
821 return yield* new PlatformEnvironmentRemovalError({
822 environmentId,
823 });
824 }
825 const entry = yield* getEntry(environmentId);
826
827 yield* githubRoutingPermissions.forget(environmentId);
828 yield* registrations.remove(environmentId);
829 yield* Ref.update(persistedEnvironmentIds, (current) => {
830 const next = new Set(current);
831 next.delete(environmentId);
832 return next;
833 });
834 yield* closeServiceScope(environmentId);
835 yield* SubscriptionRef.update(entries, (current) => {
836 const next = new Map(current);
837 next.delete(environmentId);
838 return next;
839 });
840 yield* Effect.all(
841 [
842 cache.clear(environmentId).pipe(
843 Effect.catch((error) =>
844 Effect.logWarning("Could not clear cached environment data after removal.", {
845 environmentId,
846 error,
847 }),
848 ),
849 ),
850 ownedDataCleanup.clear(environmentId),
851 ],
852 { concurrency: "unbounded", discard: true },
853 );
854
855 for (const route of connectionRoutes(entry)) {
856 const profile = Option.getOrNull(route.profile);
857 if (profile !== null && isSshConnectionProfile(profile)) {
858 yield* disconnectSsh(environmentId, profile);
859 }
860 }
861 });
862
863 const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) {
864 return yield* withLeaseLock(environmentId, removeLocked(environmentId));
865 });
866
867 const disconnectSsh = (environmentId: EnvironmentId, profile: SshConnectionProfile) =>
868 ssh.disconnect(profile.target).pipe(
869 Effect.tapError((error) =>
870 Effect.logWarning("Could not disconnect the managed SSH environment.", {
871 environmentId,
872 error,
873 }),
874 ),
875 Effect.ignore,
876 );
877
878 // Plain HTTP routes are unusable from an HTTPS page, which blocks mixed content.
879 const allowInsecureRoutes =
880 typeof globalThis.location === "undefined" || globalThis.location.protocol !== "https:";
881
882 /**
883 * Saves the direct addresses a connected server reports as learned routes,
884 * replacing learned routes it no longer reports. Routes the user saved are
885 * never changed. Learned routes reuse the active route's credential, so they
886 * do not revoke GitHub routing trust the way a newly paired address does.
887 */
888 const learnRoutes = Effect.fn("EnvironmentRegistry.learnRoutes")(function* (input: {
889 readonly environmentId: EnvironmentId;
890 readonly activeRoute: ConnectionRoute;
891 readonly reported: ReadonlyArray<{ readonly httpBaseUrl: string }>;
892 }) {
893 return yield* withLeaseLock(
894 input.environmentId,
895 Effect.gen(function* () {
896 if ((yield* Ref.get(platformEnvironmentIds)).has(input.environmentId)) {
897 return Option.none<ConnectionCatalogEntry>();
898 }
899 const entry = (yield* SubscriptionRef.get(entries)).get(input.environmentId);
900 if (entry === undefined) return Option.none<ConnectionCatalogEntry>();
901 const routes = mergeLearnedRoutes({
902 entry,
903 activeRoute: input.activeRoute,
904 reported: input.reported,
905 allowInsecure: allowInsecureRoutes,
906 });
907 if (routes === null) return Option.none<ConnectionCatalogEntry>();
908 const next = entryWithRoutes(entry, routes);
909 // A learned route owns its profile (address and authorization); the
910 // credential stays with the route it borrows from.
911 const previousIds = new Set(
912 connectionRoutes(entry).map((route) => connectionRouteId(route.target)),
913 );
914 for (const route of routes) {
915 if (!isLearned(route) || previousIds.has(connectionRouteId(route.target))) continue;
916 const profile = Option.getOrNull(route.profile);
917 if (profile !== null) yield* profiles.put(profile);
918 }
919 yield* registrations.setRoutes(input.environmentId, persistedRoutes(next));
920 // Update the lease in place: the live session already works, and
921 // `installEntryLocked` would replace it for a route list change.
922 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(input.environmentId);
923 if (lease !== undefined) {
924 yield* SubscriptionRef.update(serviceScopes, (current) =>
925 new Map(current).set(input.environmentId, { ...lease, entry: next }),
926 );
927 }
928 yield* SubscriptionRef.update(entries, (current) =>
929 new Map(current).set(input.environmentId, next),
930 );
931 return Option.some(next);
932 }),
933 ).pipe(
934 Effect.catch((error) =>
935 Effect.logWarning("Could not save routes learned from the environment.", {
936 environmentId: input.environmentId,
937 error,
938 }).pipe(Effect.as(Option.none<ConnectionCatalogEntry>())),
939 ),
940 );
941 });
942
943 const removeRoute = Effect.fn("EnvironmentRegistry.removeRoute")(function* (
944 environmentId: EnvironmentId,
945 routeId: string,
946 ) {
947 // One lock for the whole decision: a route registered between "this was
948 // the last route" and the removal must not be deleted with it.
949 yield* withLeaseLock(
950 environmentId,
951 Effect.gen(function* () {
952 const entry = yield* userEntry(environmentId);
953 const routes = connectionRoutes(entry);
954 const route = routes.find((candidate) => connectionRouteId(candidate.target) === routeId);
955 if (route === undefined) return;
956 const remaining = routesAfterRemoving(routes, routeId);
957 if (remaining.length === 0) return yield* removeLocked(environmentId);
958 yield* replaceRoutesLocked(entry, remaining);
959 const profile = Option.getOrNull(route.profile);
960 if (profile !== null && isSshConnectionProfile(profile)) {
961 yield* disconnectSsh(environmentId, profile);
962 }
963 }),
964 );
965 });
966
967 const reorderRoutes = Effect.fn("EnvironmentRegistry.reorderRoutes")(function* (
968 environmentId: EnvironmentId,
969 routeIds: ReadonlyArray<string>,
970 ) {
971 yield* withLeaseLock(
972 environmentId,
973 Effect.gen(function* () {
974 const entry = yield* userEntry(environmentId);
975 const routes = connectionRoutes(entry);
976 const byId = new Map(routes.map((route) => [connectionRouteId(route.target), route]));
977 const reordered = routeIds.flatMap((id) => byId.get(id) ?? []);
978 if (reordered.length !== routes.length || new Set(routeIds).size !== routes.length) {
979 return yield* new ConnectionBlockedError({
980 reason: "configuration",
981 detail: "The route order must list every saved route once.",
982 });
983 }
984 if (reordered.every((route, index) => route === routes[index])) return;
985 yield* replaceRoutesLocked(entry, reordered);
986 }),
987 );
988 });
989
990 const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(
991 function* () {
992 const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]
993 .filter((entry) =>
994 connectionRoutes(entry).some((route) => route.target._tag === "RelayConnectionTarget"),
995 )
996 .map((entry) => entry.target.environmentId);
997
998 yield* Effect.forEach(
999 relayEnvironmentIds,
1000 (environmentId) =>
1001 removeRoute(environmentId, RELAY_ROUTE_ID).pipe(
1002 Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }),
1003 ),
1004 {
1005 concurrency: "unbounded",
1006 discard: true,
1007 },
1008 );
1009 },
1010 );
1011
1012 const retryNow = (environmentId: EnvironmentId) =>
1013 acquireSupervisor(environmentId).pipe(
1014 Effect.flatMap((supervisor) => supervisor.retryNow),
1015 Effect.catchTags({ EnvironmentNotRegisteredError: () => Effect.void }),
1016 Effect.withSpan("EnvironmentRegistry.retryNow"),
1017 );
1018 const setEnabled = Effect.fn("EnvironmentRegistry.setEnabled")(function* (
1019 environmentId: EnvironmentId,
1020 enabled: boolean,
1021 ) {
1022 yield* withLeaseLock(
1023 environmentId,
1024 Effect.gen(function* () {
1025 const entry = yield* getEntry(environmentId);
1026 if (enabled && entry.unsupportedReason !== undefined) {
1027 return yield* new ConnectionBlockedError({
1028 reason: "unsupported",
1029 detail: entry.unsupportedReason,
1030 });
1031 }
1032 if (entry.enabled === enabled) {
1033 return;
1034 }
1035 // Platform-managed environments are reconciled from the host and are
1036 // never persisted, so only user-saved ones write the flag.
1037 if (!(yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
1038 yield* registrations.setEnabled(environmentId, enabled);
1039 }
1040 const next: ConnectionCatalogEntry = { ...entry, enabled };
1041 // Update the lease in place so the supervisor keeps its generation and
1042 // durable streams; `installEntryLocked` would tear it down instead.
1043 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
1044 if (lease !== undefined) {
1045 yield* SubscriptionRef.update(serviceScopes, (current) => {
1046 const nextScopes = new Map(current);
1047 nextScopes.set(environmentId, { ...lease, entry: next });
1048 return nextScopes;
1049 });
1050 }
1051 yield* SubscriptionRef.update(entries, (current) => {
1052 const nextEntries = new Map(current);
1053 nextEntries.set(environmentId, next);
1054 return nextEntries;
1055 });
1056 if (lease !== undefined) {
1057 yield* enabled ? lease.supervisor.connect : lease.supervisor.disconnect;
1058 } else if (enabled) {
1059 yield* createServiceScope(next);
1060 }
1061 // The supervisor only owns the RPC session. A managed SSH backend and
1062 // its tunnel outlive it, so switching off tears those down as well.
1063 if (!enabled) {
1064 for (const route of connectionRoutes(entry)) {
1065 const profile = Option.getOrNull(route.profile);
1066 if (profile !== null && isSshConnectionProfile(profile)) {
1067 yield* disconnectSsh(environmentId, profile);
1068 }
1069 }
1070 }
1071 }),
1072 );
1073 });
1074
1075 const state = Effect.fn("EnvironmentRegistry.state")(function* (environmentId: EnvironmentId) {
1076 const supervisor = yield* acquireSupervisor(environmentId);
1077 return yield* SubscriptionRef.get(supervisor.state);
1078 });
1079 const stateChanges = (environmentId: EnvironmentId) =>
1080 followStream(
1081 environmentId,
1082 Stream.unwrap(
1083 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
1084 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.state)),
1085 ),
1086 ),
1087 );
1088
1089 yield* Effect.addFinalizer(() =>
1090 SubscriptionRef.get(serviceScopes).pipe(
1091 Effect.flatMap((current) =>
1092 Effect.forEach(current.values(), (lease) => Scope.close(lease.scope, Exit.void), {
1093 concurrency: "unbounded",
1094 discard: true,
1095 }),
1096 ),
1097 ),
1098 );
1099 yield* connectivity.changes.pipe(
1100 Stream.runForEach((status) => SubscriptionRef.set(networkStatus, status)),
1101 Effect.forkScoped,
1102 );
1103
1104 const setCompatibility = Effect.fn("EnvironmentRegistry.setCompatibility")(function* (
1105 environmentId: EnvironmentId,
1106 error: ConnectionBlockedError | null,
1107 ) {
1108 yield* withLeaseLock(
1109 environmentId,
1110 Effect.gen(function* () {
1111 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
1112 if (
1113 entry === undefined ||
1114 (entry.unsupportedReason === (error?.message ?? undefined) &&
1115 entry.serverUpdateRequired === (error?.serverUpdateRequired ?? undefined))
1116 )
1117 return;
1118 const {
1119 unsupportedReason: _previousReason,
1120 serverUpdateRequired: _previousUpdateRequired,
1121 ...rest
1122 } = entry;
1123 const next: ConnectionCatalogEntry =
1124 error === null
1125 ? rest
1126 : {
1127 ...rest,
1128 enabled: false,
1129 unsupportedReason: error.message,
1130 ...(error.serverUpdateRequired === true ? { serverUpdateRequired: true } : {}),
1131 };
1132 if (
1133 error !== null &&
1134 entry.enabled &&
1135 !(yield* Ref.get(platformEnvironmentIds)).has(environmentId)
1136 ) {
1137 yield* registrations.setEnabled(environmentId, false);
1138 }
1139 const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
1140 if (lease !== undefined) {
1141 yield* SubscriptionRef.update(serviceScopes, (current) =>
1142 new Map(current).set(environmentId, { ...lease, entry: next }),
1143 );
1144 if (error !== null) yield* lease.supervisor.disconnect;
1145 }
1146 yield* SubscriptionRef.update(entries, (current) =>
1147 new Map(current).set(environmentId, next),
1148 );
1149 }),
1150 );
1151 });
1152
1153 return EnvironmentRegistry.of({
1154 entries,
1155 networkStatus,
1156 start,
1157 register,
1158 registerPlatform,
1159 reconcilePlatform,
1160 remove,
1161 removeRoute,
1162 reorderRoutes,
1163 removeRelayEnvironments,
1164 retryNow,
1165 setEnabled,
1166 setCompatibility,
1167 state,
1168 stateChanges,
1169 run,
1170 runStream,
1171 followStream,
1172 });
1173});
1174
1175export const layer = Layer.effect(EnvironmentRegistry, make);