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