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