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

connections.ts

244 lines8.7 KB

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