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