The best way to control Claude Code, Codex and more from any computer or phone

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