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