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

registry.ts

581 lines19.7 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 ConnectionRegistration,
19 type PrimaryConnectionRegistration,
20 SshConnectionProfile,
21 connectionRegistrationCatalogEntry,
22} from "./catalog.ts";
23import * as ConnectionProfileStore from "./profileStore.ts";
24import * as Connectivity from "./connectivity.ts";
25import type {
26 ConnectionAttemptError,
27 ConnectionTarget,
28 NetworkStatus,
29 SupervisorConnectionState,
30} from "./model.ts";
31import * as Persistence from "../platform/persistence.ts";
32import * as EnvironmentSupervisor from "./supervisor.ts";
33import * as ConnectionDriver from "./driver.ts";
34import * as ConnectionWakeups from "./wakeups.ts";
35​
36const isSshConnectionProfile = Schema.is(SshConnectionProfile);
37​
38export class EnvironmentNotRegisteredError extends Schema.TaggedErrorClass<EnvironmentNotRegisteredError>()(
39 "EnvironmentNotRegisteredError",
40 {
41 environmentId: EnvironmentId,
42 },
43) {
44 override get message(): string {
45 return `Environment ${this.environmentId} is not registered.`;
46 }
48​
49export class PlatformEnvironmentRemovalError extends Schema.TaggedErrorClass<PlatformEnvironmentRemovalError>()(
50 "PlatformEnvironmentRemovalError",
51 {
52 environmentId: EnvironmentId,
53 },
54) {
55 override get message(): string {
56 return `Platform-managed environment ${this.environmentId} cannot be removed.`;
57 }
59​
60export class EnvironmentRegistry extends Context.Service<
61 EnvironmentRegistry,
62 {
63 readonly entries: SubscriptionRef.SubscriptionRef<
64 ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
65 >;
66 readonly networkStatus: SubscriptionRef.SubscriptionRef<NetworkStatus>;
67 readonly start: Effect.Effect<void>;
68 readonly register: (
69 registration: ConnectionRegistration,
70 ) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
71 readonly registerPlatform: (registration: PrimaryConnectionRegistration) => Effect.Effect<void>;
72 readonly remove: (
73 environmentId: EnvironmentId,
74 ) => Effect.Effect<
75 void,
76 | Persistence.ConnectionPersistenceError
77 | ConnectionAttemptError
78 | EnvironmentNotRegisteredError
79 | PlatformEnvironmentRemovalError
80 >;
81 readonly removeRelayEnvironments: () => Effect.Effect<
82 void,
83 | Persistence.ConnectionPersistenceError
84 | ConnectionAttemptError
85 | PlatformEnvironmentRemovalError
86 >;
87 readonly retryNow: (environmentId: EnvironmentId) => Effect.Effect<void>;
88 readonly state: (
89 environmentId: EnvironmentId,
90 ) => Effect.Effect<SupervisorConnectionState, EnvironmentNotRegisteredError>;
91 readonly stateChanges: (
92 environmentId: EnvironmentId,
93 ) => Stream.Stream<SupervisorConnectionState, EnvironmentNotRegisteredError>;
94 readonly run: <A, E, R>(
95 environmentId: EnvironmentId,
96 effect: Effect.Effect<A, E, R>,
97 ) => Effect.Effect<
98 A,
99 E | EnvironmentNotRegisteredError,
100 Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
101 >;
102 readonly runStream: <A, E, R>(
103 environmentId: EnvironmentId,
104 stream: Stream.Stream<A, E, R>,
105 ) => Stream.Stream<
106 A,
107 E | EnvironmentNotRegisteredError,
108 Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
109 >;
110 readonly followStream: <A, E, R>(
111 environmentId: EnvironmentId,
112 stream: Stream.Stream<A, E, R>,
113 ) => Stream.Stream<A, E, Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>>;
114 }
115>()("@t3tools/client-runtime/connection/registry/EnvironmentRegistry") {}
116​
117interface EnvironmentServiceScope {
118 readonly entry: ConnectionCatalogEntry;
119 readonly supervisor: EnvironmentSupervisor.EnvironmentSupervisor["Service"];
120 readonly scope: Scope.Closeable;
122​
123export const make = Effect.gen(function* () {
124 const storage = yield* Persistence.ConnectionTargetStore;
125 const registrations = yield* Persistence.ConnectionRegistrationStore;
126 const cache = yield* Persistence.EnvironmentCacheStore;
127 const ownedDataCleanup = yield* Persistence.EnvironmentOwnedDataCleanup;
128 const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;
129 const connectivity = yield* Connectivity.Connectivity;
130 const driver = yield* ConnectionDriver.ConnectionDriver;
131 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
132 const ssh = yield* ClientCapabilities.SshEnvironmentGateway;
133 const persistedTargets = yield* storage.list;
134 const initialEntries = new Map(
135 yield* Effect.forEach(
136 persistedTargets,
137 Effect.fn("EnvironmentRegistry.loadCatalogEntry")(function* (target) {
138 const profile =
139 target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
140 ? yield* profiles.get(target.connectionId)
141 : Option.none();
142 return [
143 target.environmentId,
144 { target, profile } satisfies ConnectionCatalogEntry,
145 ] as const;
146 }),
147 { concurrency: "unbounded" },
148 ),
149 );
150 const entries =
151 yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(initialEntries);
152 const networkStatus = yield* SubscriptionRef.make(yield* connectivity.status);
153 const serviceScopes = yield* SubscriptionRef.make<
154 ReadonlyMap<EnvironmentId, EnvironmentServiceScope>
155 >(new Map());
156 const platformEnvironmentIds = yield* Ref.make<ReadonlySet<EnvironmentId>>(new Set());
157 const persistedTargetsByEnvironment = yield* Ref.make<
158 ReadonlyMap<EnvironmentId, ConnectionTarget>
159 >(new Map(persistedTargets.map((target) => [target.environmentId, target])));
160 interface LeaseLock {
161 readonly semaphore: Semaphore.Semaphore;
162 readonly users: number;
163 }
164​
165 const leaseLocks = yield* Ref.make<ReadonlyMap<EnvironmentId, LeaseLock>>(new Map());
166 const leaseLocksGuard = yield* Semaphore.make(1);
167 const started = yield* Ref.make(false);
168​
169 const withLeaseLock = <A, E, R>(
170 environmentId: EnvironmentId,
171 effect: Effect.Effect<A, E, R>,
172 ): Effect.Effect<A, E, R> =>
173 Effect.acquireUseRelease(
174 leaseLocksGuard.withPermits(1)(
175 Effect.gen(function* () {
176 const current = yield* Ref.get(leaseLocks);
177 const existing = current.get(environmentId);
178 if (existing !== undefined) {
179 yield* Ref.set(
180 leaseLocks,
181 new Map(current).set(environmentId, {
182 semaphore: existing.semaphore,
183 users: existing.users + 1,
184 }),
185 );
186 return existing.semaphore;
187 }
188 const semaphore = yield* Semaphore.make(1);
189 yield* Ref.set(leaseLocks, new Map(current).set(environmentId, { semaphore, users: 1 }));
190 return semaphore;
191 }),
192 ),
193 (semaphore) => semaphore.withPermits(1)(effect),
194 (semaphore) =>
195 leaseLocksGuard.withPermits(1)(
196 Ref.update(leaseLocks, (current) => {
197 const existing = current.get(environmentId);
198 if (existing === undefined || existing.semaphore !== semaphore) {
199 return current;
200 }
201 const next = new Map(current);
202 if (existing.users === 1) {
203 next.delete(environmentId);
204 } else {
205 next.set(environmentId, {
206 semaphore,
207 users: existing.users - 1,
208 });
209 }
210 return next;
211 }),
212 ),
213 ).pipe(Effect.withSpan("EnvironmentRegistry.withLeaseLock"));
214​
215 const getEntry = Effect.fn("EnvironmentRegistry.getEntry")(function* (
216 environmentId: EnvironmentId,
217 ) {
218 const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
219 if (entry === undefined) {
220 return yield* new EnvironmentNotRegisteredError({
221 environmentId,
222 });
223 }
224 return entry;
225 });
226​
227 const closeServiceScope = Effect.fn("EnvironmentRegistry.closeServiceScope")(function* (
228 environmentId: EnvironmentId,
229 ) {
230 const current = yield* SubscriptionRef.get(serviceScopes);
231 const lease = current.get(environmentId);
232 if (lease === undefined) {
233 return;
234 }
235 const next = new Map(current);
236 next.delete(environmentId);
237 yield* SubscriptionRef.set(serviceScopes, next);
238 yield* Scope.close(lease.scope, Exit.void);
239 });
240​
241 const createServiceScope = Effect.fn("EnvironmentRegistry.createServiceScope")(
242 (entry: ConnectionCatalogEntry) =>
243 Effect.uninterruptible(
244 Effect.gen(function* () {
245 const environmentId = entry.target.environmentId;
246 const scope = yield* Scope.make();
247 const supervisor = yield* EnvironmentSupervisor.make(entry, {
248 initiallyDesired: false,
249 }).pipe(
250 Effect.provideService(Connectivity.Connectivity, connectivity),
251 Effect.provideService(ConnectionDriver.ConnectionDriver, driver),
252 Effect.provideService(ConnectionWakeups.ConnectionWakeups, wakeups),
253 Scope.provide(scope),
254 Effect.onError(() => Scope.close(scope, Exit.void)),
255 );
256 yield* supervisor.connect;
257 yield* SubscriptionRef.update(serviceScopes, (current) => {
258 const next = new Map(current);
259 next.set(environmentId, { entry, supervisor, scope });
260 return next;
261 });
262 return supervisor;
263 }),
264 ),
265 );
266​
267 const acquireSupervisor = Effect.fn("EnvironmentRegistry.acquireSupervisor")(function* (
268 environmentId: EnvironmentId,
269 ) {
270 return yield* withLeaseLock(
271 environmentId,
272 Effect.gen(function* () {
273 const entry = yield* getEntry(environmentId);
274 const existing = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
275 if (existing !== undefined) {
276 if (Equal.equals(existing.entry, entry)) {
277 return existing.supervisor;
278 }
279 yield* closeServiceScope(environmentId);
280 }
281 return yield* createServiceScope(entry);
282 }),
283 );
284 });
285​
286 const run: EnvironmentRegistry["Service"]["run"] = Effect.fn("EnvironmentRegistry.run")(
287 function* <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) {
288 const supervisor = yield* acquireSupervisor(environmentId);
289 return yield* Effect.provideService(
290 effect,
291 EnvironmentSupervisor.EnvironmentSupervisor,
292 supervisor,
293 );
294 },
295 );
296​
297 const runStream: EnvironmentRegistry["Service"]["runStream"] = <A, E, R>(
298 environmentId: EnvironmentId,
299 stream: Stream.Stream<A, E, R>,
300 ) =>
301 Stream.unwrap(
302 acquireSupervisor(environmentId).pipe(
303 Effect.map((supervisor) =>
304 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
305 ),
306 ),
307 );
308​
309 const followStream: EnvironmentRegistry["Service"]["followStream"] = <A, E, R>(
310 environmentId: EnvironmentId,
311 stream: Stream.Stream<A, E, R>,
312 ) =>
313 Stream.concat(
314 Stream.fromEffect(SubscriptionRef.get(entries)),
315 SubscriptionRef.changes(entries),
316 ).pipe(
317 Stream.map((current) => Option.fromUndefinedOr(current.get(environmentId))),
318 Stream.changes,
319 Stream.switchMap(
320 Option.match({
321 onNone: () => Stream.empty,
322 onSome: () =>
323 Stream.unwrap(
324 acquireSupervisor(environmentId).pipe(
325 Effect.match({
326 onFailure: () => Stream.empty,
327 onSuccess: (supervisor) =>
328 Stream.provideService(
329 stream,
330 EnvironmentSupervisor.EnvironmentSupervisor,
331 supervisor,
332 ),
333 }),
334 ),
335 ),
336 }),
337 ),
338 );
339​
340 const start = Effect.gen(function* () {
341 if (yield* Ref.getAndSet(started, true)) {
342 return;
343 }
344 yield* Effect.forEach(
345 persistedTargets,
346 (target) =>
347 acquireSupervisor(target.environmentId).pipe(
348 Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
349 ),
350 {
351 concurrency: "unbounded",
352 discard: true,
353 },
354 );
355 }).pipe(Effect.withSpan("EnvironmentRegistry.start"));
356​
357 const installEntryLocked = Effect.fn("EnvironmentRegistry.installEntryLocked")(function* (
358 entry: ConnectionCatalogEntry,
359 options?: { readonly retainEquivalentRuntime?: boolean },
360 ) {
361 const target = entry.target;
362 const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
363 const existingScope = (yield* SubscriptionRef.get(serviceScopes)).get(target.environmentId);
364 if (
365 options?.retainEquivalentRuntime === true &&
366 previous !== undefined &&
367 Equal.equals(previous, entry) &&
368 existingScope !== undefined &&
369 Equal.equals(existingScope.entry, entry)
370 ) {
371 return;
372 }
373​
374 yield* closeServiceScope(target.environmentId);
375 yield* SubscriptionRef.update(entries, (current) => {
376 const next = new Map(current);
377 next.set(target.environmentId, entry);
378 return next;
379 });
380 yield* createServiceScope(entry);
381 });
382​
383 const register = Effect.fn("EnvironmentRegistry.register")(function* (
384 registration: ConnectionRegistration,
385 ) {
386 const entry = connectionRegistrationCatalogEntry(registration);
387 const environmentId = entry.target.environmentId;
388 yield* withLeaseLock(
389 environmentId,
390 Effect.gen(function* () {
391 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
392 return;
393 }
394 yield* registrations.register(registration);
395 yield* Ref.update(persistedTargetsByEnvironment, (current) => {
396 const next = new Map(current);
397 next.set(environmentId, registration.target);
398 return next;
399 });
400 yield* installEntryLocked(entry);
401 }),
402 );
403 });
404​
405 const registerPlatform = Effect.fn("EnvironmentRegistry.registerPlatform")(function* (
406 registration: PrimaryConnectionRegistration,
407 ) {
408 const entry = connectionRegistrationCatalogEntry(registration);
409 const target = entry.target;
410 yield* withLeaseLock(
411 target.environmentId,
412 Effect.gen(function* () {
413 yield* Ref.update(platformEnvironmentIds, (current) => {
414 const next = new Set(current);
415 next.add(target.environmentId);
416 return next;
417 });
418​
419 const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get(
420 target.environmentId,
421 );
422 if (persistedTarget !== undefined) {
423 yield* registrations.remove(persistedTarget).pipe(
424 Effect.tap(() =>
425 Ref.update(persistedTargetsByEnvironment, (current) => {
426 const next = new Map(current);
427 next.delete(target.environmentId);
428 return next;
429 }),
430 ),
431 Effect.catch((error) =>
432 Effect.logWarning(
433 "Could not remove a persisted registration shadowed by the primary environment.",
434 {
435 environmentId: target.environmentId,
436 error,
437 },
438 ),
439 ),
440 );
441 }
442​
443 yield* installEntryLocked(entry, { retainEquivalentRuntime: true });
444 }),
445 );
446 });
447​
448 const remove = Effect.fn("EnvironmentRegistry.remove")(function* (environmentId: EnvironmentId) {
449 return yield* withLeaseLock(
450 environmentId,
451 Effect.gen(function* () {
452 if ((yield* Ref.get(platformEnvironmentIds)).has(environmentId)) {
453 return yield* new PlatformEnvironmentRemovalError({
454 environmentId,
455 });
456 }
457 const target = (yield* getEntry(environmentId)).target;
458 const profile =
459 target._tag === "BearerConnectionTarget" || target._tag === "SshConnectionTarget"
460 ? yield* profiles.get(target.connectionId)
461 : Option.none();
462​
463 yield* registrations.remove(target);
464 yield* Ref.update(persistedTargetsByEnvironment, (current) => {
465 const next = new Map(current);
466 next.delete(environmentId);
467 return next;
468 });
469 yield* closeServiceScope(environmentId);
470 yield* SubscriptionRef.update(entries, (current) => {
471 const next = new Map(current);
472 next.delete(environmentId);
473 return next;
474 });
475 yield* Effect.all(
476 [
477 cache.clear(environmentId).pipe(
478 Effect.catch((error) =>
479 Effect.logWarning("Could not clear cached environment data after removal.", {
480 environmentId,
481 error,
482 }),
483 ),
484 ),
485 ownedDataCleanup.clear(environmentId),
486 ],
487 { concurrency: "unbounded", discard: true },
488 );
489​
490 if (
491 target._tag === "SshConnectionTarget" &&
492 Option.isSome(profile) &&
493 isSshConnectionProfile(profile.value)
494 ) {
495 yield* ssh.disconnect(profile.value.target).pipe(
496 Effect.tapError((error) =>
497 Effect.logWarning("Could not disconnect the managed SSH environment.", {
498 environmentId,
499 error,
500 }),
501 ),
502 Effect.ignore,
503 );
504 }
505 }),
506 );
507 });
508​
509 const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(
510 function* () {
511 const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]
512 .filter((entry) => entry.target._tag === "RelayConnectionTarget")
513 .map((entry) => entry.target.environmentId);
514​
515 yield* Effect.forEach(
516 relayEnvironmentIds,
517 (environmentId) =>
518 remove(environmentId).pipe(
519 Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
520 ),
521 {
522 concurrency: "unbounded",
523 discard: true,
524 },
525 );
526 },
527 );
528​
529 const retryNow = (environmentId: EnvironmentId) =>
530 acquireSupervisor(environmentId).pipe(
531 Effect.flatMap((supervisor) => supervisor.retryNow),
532 Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),
533 Effect.withSpan("EnvironmentRegistry.retryNow"),
534 );
535 const state = Effect.fn("EnvironmentRegistry.state")(function* (environmentId: EnvironmentId) {
536 const supervisor = yield* acquireSupervisor(environmentId);
537 return yield* SubscriptionRef.get(supervisor.state);
538 });
539 const stateChanges = (environmentId: EnvironmentId) =>
540 followStream(
541 environmentId,
542 Stream.unwrap(
543 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
544 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.state)),
545 ),
546 ),
547 );
548​
549 yield* Effect.addFinalizer(() =>
550 SubscriptionRef.get(serviceScopes).pipe(
551 Effect.flatMap((current) =>
552 Effect.forEach(current.values(), (lease) => Scope.close(lease.scope, Exit.void), {
553 concurrency: "unbounded",
554 discard: true,
555 }),
556 ),
557 ),
558 );
559 yield* connectivity.changes.pipe(
560 Stream.runForEach((status) => SubscriptionRef.set(networkStatus, status)),
561 Effect.forkScoped,
562 );
563​
564 return EnvironmentRegistry.of({
565 entries,
566 networkStatus,
567 start,
568 register,
569 registerPlatform,
570 remove,
571 removeRelayEnvironments,
572 retryNow,
573 state,
574 stateChanges,
575 run,
576 runStream,
577 followStream,
578 });
579});
580​
581export const layer = Layer.effect(EnvironmentRegistry, make);