Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

registry.ts

1,159 lines42.6 KB

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