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