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

connections.ts

213 lines7.6 KB

1import type { EnvironmentId as EnvironmentIdType } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Stream from "effect/Stream";
5import * as SubscriptionRef from "effect/SubscriptionRef";
6import { AsyncResult, Atom } from "effect/reactivity";
7​
8import * as EnvironmentRegistry from "../connection/registry.ts";
9import type { ConnectionCatalogEntry } from "../connection/catalog.ts";
10import { AVAILABLE_CONNECTION_STATE } from "../connection/model.ts";
11import * as EnvironmentSupervisor from "../connection/supervisor.ts";
12import {
13 PullRequestRoutingPermissions,
14 type PullRequestRoutingPermission,
15 type StoredPullRequestRoutingPermission,
16} from "../connection/pullRequestRoutingPermissions.ts";
17import {
18 createAtomCommandScheduler,
19 createRuntimeCommand,
20 environmentSessionGenerationAtom,
21 followStreamInEnvironment,
22} from "./runtime.ts";
23​
24export interface EnvironmentCatalogState {
25 readonly isReady: boolean;
26 readonly entries: ReadonlyMap<EnvironmentIdType, ConnectionCatalogEntry>;
28​
29export function* enabledEnvironmentIds(
30 catalog: EnvironmentCatalogState,
31): Generator<EnvironmentIdType> {
32 for (const [environmentId, entry] of catalog.entries) {
33 if (entry.enabled && entry.unsupportedReason === undefined) {
34 yield environmentId;
35 }
36 }
38​
39const EMPTY_ENVIRONMENT_CATALOG_STATE: EnvironmentCatalogState = Object.freeze({
40 isReady: false,
41 entries: new Map(),
42});
43​
44export function createEnvironmentCatalogAtoms<R, E>(
45 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
46) {
47 const commandScheduler = createAtomCommandScheduler();
48 const serial = { mode: "serial" as const, key: () => "environment-catalog" };
49 const catalogAtom = runtime.atom(
50 Stream.unwrap(
51 EnvironmentRegistry.EnvironmentRegistry.pipe(
52 Effect.map((registry) =>
53 SubscriptionRef.changes(registry.entries).pipe(
54 Stream.map((entries) => ({
55 isReady: true,
56 entries,
57 })),
58 ),
59 ),
60 ),
61 ),
62 { initialValue: EMPTY_ENVIRONMENT_CATALOG_STATE },
63 );
64​
65 const catalogValueAtom = Atom.make((get) =>
66 Option.getOrElse(AsyncResult.value(get(catalogAtom)), () => EMPTY_ENVIRONMENT_CATALOG_STATE),
67 ).pipe(Atom.withLabel("environment-catalog-value"));
68​
69 const pullRequestRoutingPermissionsAtom = runtime.atom(
70 Stream.unwrap(
71 PullRequestRoutingPermissions.pipe(Effect.map((permissions) => permissions.changes)),
72 ),
73 { initialValue: [] as ReadonlyArray<StoredPullRequestRoutingPermission> },
74 );
75 const pullRequestRoutingPermissionsValueAtom = Atom.make((get) =>
76 Option.getOrElse(AsyncResult.value(get(pullRequestRoutingPermissionsAtom)), () => []),
77 ).pipe(Atom.withLabel("environment-pull-request-routing-permissions"));
78 const setPullRequestRoutingPermission = createRuntimeCommand(runtime, {
79 label: "environment-catalog:pull-request-routing-permission",
80 scheduler: commandScheduler,
81 concurrency: serial,
82 execute: Effect.fn(function* (input: {
83 readonly environmentId: EnvironmentIdType;
84 readonly permission: PullRequestRoutingPermission;
85 }) {
86 const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
87 const entry = (yield* SubscriptionRef.get(registry.entries)).get(input.environmentId);
88 if (entry === undefined)
89 return yield* new EnvironmentRegistry.EnvironmentNotRegisteredError({
90 environmentId: input.environmentId,
91 });
92 const permissions = yield* PullRequestRoutingPermissions;
93 yield* permissions.set(entry, input.permission);
94 }),
95 });
96​
97 const networkStatusAtom = runtime.atom(
98 Stream.unwrap(
99 EnvironmentRegistry.EnvironmentRegistry.pipe(
100 Effect.map((registry) => SubscriptionRef.changes(registry.networkStatus)),
101 ),
102 ),
103 { initialValue: "unknown" as const },
104 );
105​
106 const networkStatusValueAtom = Atom.make((get) =>
107 Option.getOrElse(AsyncResult.value(get(networkStatusAtom)), () => "unknown" as const),
108 ).pipe(Atom.withLabel("environment-network-status-value"));
109​
110 const stateAtom = Atom.family((environmentId: EnvironmentIdType) =>
111 runtime.atom(
112 followStreamInEnvironment(
113 environmentId,
114 Stream.unwrap(
115 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
116 Effect.map((supervisor) => SubscriptionRef.changes(supervisor.state)),
117 ),
118 ),
119 ),
120 { initialValue: AVAILABLE_CONNECTION_STATE },
121 ),
122 );
123​
124 const sessionGenerationAtom = (environmentId: EnvironmentIdType) =>
125 environmentSessionGenerationAtom(runtime, environmentId);
126​
127 const register = createRuntimeCommand(runtime, {
128 label: "environment-catalog:register",
129 scheduler: commandScheduler,
130 concurrency: serial,
131 execute: (
132 target: Parameters<EnvironmentRegistry.EnvironmentRegistry["Service"]["register"]>[0],
133 ) =>
134 EnvironmentRegistry.EnvironmentRegistry.pipe(
135 Effect.flatMap((registry) => registry.register(target)),
136 ),
137 });
138 const remove = createRuntimeCommand(runtime, {
139 label: "environment-catalog:remove",
140 scheduler: commandScheduler,
141 concurrency: serial,
142 execute: (environmentId: EnvironmentIdType) =>
143 EnvironmentRegistry.EnvironmentRegistry.pipe(
144 Effect.flatMap((registry) => registry.remove(environmentId)),
145 ),
146 });
147 const removeRelayEnvironments = createRuntimeCommand(runtime, {
148 label: "environment-catalog:remove-relay-environments",
149 scheduler: commandScheduler,
150 concurrency: serial,
151 execute: (_input: void) =>
152 EnvironmentRegistry.EnvironmentRegistry.pipe(
153 Effect.flatMap((registry) => registry.removeRelayEnvironments()),
154 ),
155 });
156 const setEnabled = createRuntimeCommand(runtime, {
157 label: "environment-catalog:set-enabled",
158 scheduler: commandScheduler,
159 concurrency: serial,
160 execute: (input: { readonly environmentId: EnvironmentIdType; readonly enabled: boolean }) =>
161 EnvironmentRegistry.EnvironmentRegistry.pipe(
162 Effect.flatMap((registry) => registry.setEnabled(input.environmentId, input.enabled)),
163 ),
164 });
165 const removeRoute = createRuntimeCommand(runtime, {
166 label: "environment-catalog:remove-route",
167 scheduler: commandScheduler,
168 concurrency: serial,
169 execute: (input: { readonly environmentId: EnvironmentIdType; readonly routeId: string }) =>
170 EnvironmentRegistry.EnvironmentRegistry.pipe(
171 Effect.flatMap((registry) => registry.removeRoute(input.environmentId, input.routeId)),
172 ),
173 });
174 const reorderRoutes = createRuntimeCommand(runtime, {
175 label: "environment-catalog:reorder-routes",
176 scheduler: commandScheduler,
177 concurrency: serial,
178 execute: (input: {
179 readonly environmentId: EnvironmentIdType;
180 readonly routeIds: ReadonlyArray<string>;
181 }) =>
182 EnvironmentRegistry.EnvironmentRegistry.pipe(
183 Effect.flatMap((registry) => registry.reorderRoutes(input.environmentId, input.routeIds)),
184 ),
185 });
186 const retryNow = createRuntimeCommand(runtime, {
187 label: "environment-catalog:retry-now",
188 scheduler: commandScheduler,
189 concurrency: serial,
190 execute: (environmentId: EnvironmentIdType) =>
191 EnvironmentRegistry.EnvironmentRegistry.pipe(
192 Effect.flatMap((registry) => registry.retryNow(environmentId)),
193 ),
194 });
195​
196 return {
197 catalogAtom,
198 catalogValueAtom,
199 pullRequestRoutingPermissionsValueAtom,
200 setPullRequestRoutingPermission,
201 networkStatusAtom,
202 networkStatusValueAtom,
203 stateAtom,
204 sessionGenerationAtom,
205 register,
206 remove,
207 removeRoute,
208 reorderRoutes,
209 removeRelayEnvironments,
210 retryNow,
211 setEnabled,
212 };