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