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