Open History to see the last commit
1import {
2 resolveEnvironmentMachineKind,
3 type EnvironmentMachineKind,
4 type EnvironmentId,
5 type ServerConfig,
6 type ServerProvider,
7} from "@t3tools/contracts";
8import * as Option from "effect/Option";
9import { AsyncResult, Atom } from "effect/reactivity";
10
11import { AVAILABLE_CONNECTION_STATE, type SupervisorConnectionState } from "../connection/model.ts";
12import {
13 connectionCatalogDisplayUrl,
14 presentEnvironmentConnection,
15 type EnvironmentConnectionPhase,
16 type EnvironmentConnectionPresentation,
17 type EnvironmentPresentation,
18 type EnvironmentServerConfig,
19} from "../connection/presentation.ts";
20import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
21import { hasRelayRoute } from "../connection/routes.ts";
22
23function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
24 if (left.size !== right.size) {
25 return false;
26 }
27 for (const [key, value] of left) {
28 if (right.get(key) !== value) {
29 return false;
30 }
31 }
32 return true;
33}
34
35function sameConnection(
36 left: EnvironmentConnectionPresentation,
37 right: EnvironmentConnectionPresentation,
38): boolean {
39 return left.phase === right.phase && left.error === right.error && left.traceId === right.traceId;
40}
41
42function withoutProviders(
43 config: ServerConfig | null,
44 previous: EnvironmentServerConfig | null,
45): EnvironmentServerConfig | null {
46 if (config === null) {
47 return null;
48 }
49 const { providers: _providers, ...next } = config;
50 if (previous === null) {
51 return next;
52 }
53 const keys = Object.keys(next) as Array<keyof EnvironmentServerConfig>;
54 return keys.length === Object.keys(previous).length &&
55 keys.every((key) => key in previous && previous[key] === next[key])
56 ? previous
57 : next;
58}
59
60export interface EnvironmentPresentationWithProviders extends Omit<
61 EnvironmentPresentation,
62 "serverConfig"
63> {
64 readonly serverConfig: ServerConfig | null;
65}
66
67export function createEnvironmentPresentationAtoms<E>(input: {
68 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
69 readonly stateAtom: (
70 environmentId: EnvironmentId,
71 ) => Atom.Atom<AsyncResult.AsyncResult<SupervisorConnectionState, E>>;
72 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
73}) {
74 const presentationAtom = Atom.family((environmentId: EnvironmentId) =>
75 Atom.make((get) => {
76 const entry = get(input.catalogValueAtom).entries.get(environmentId);
77 if (entry === undefined) {
78 return null;
79 }
80 const state = Option.getOrElse(
81 AsyncResult.value(get(input.stateAtom(environmentId))),
82 () => AVAILABLE_CONNECTION_STATE,
83 );
84 const previous = Option.getOrNull(get.self<EnvironmentPresentation | null>());
85 const connection: EnvironmentConnectionPresentation =
86 entry.unsupportedReason === undefined
87 ? presentEnvironmentConnection(state)
88 : { phase: "unsupported", error: entry.unsupportedReason, traceId: null };
89 const next = {
90 entry,
91 connection:
92 previous !== null && sameConnection(previous.connection, connection)
93 ? previous.connection
94 : connection,
95 serverConfig: withoutProviders(
96 get(input.serverConfigValueAtom(environmentId)),
97 previous?.serverConfig ?? null,
98 ),
99 } satisfies EnvironmentPresentation;
100 return previous !== null &&
101 previous.entry === next.entry &&
102 previous.connection === next.connection &&
103 previous.serverConfig === next.serverConfig
104 ? previous
105 : next;
106 }).pipe(Atom.withLabel(`environment-presentation:${environmentId}`)),
107 );
108
109 let previous: ReadonlyMap<EnvironmentId, EnvironmentPresentation> = new Map();
110 const presentationsAtom = Atom.make((get) => {
111 const next = new Map<EnvironmentId, EnvironmentPresentation>();
112 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
113 const presentation = get(presentationAtom(environmentId));
114 if (presentation !== null) {
115 next.set(environmentId, presentation);
116 }
117 }
118 if (mapsEqual(previous, next)) {
119 return previous;
120 }
121 previous = next;
122 return previous;
123 }).pipe(Atom.withLabel("environment-presentations"));
124
125 // Enabled environments only, like the full server-configs map, but without providers, so
126 // capability checks on every sidebar row and markdown link skip provider status pushes.
127 const serverConfigsAtom = Atom.make((get) => {
128 const next = new Map<EnvironmentId, EnvironmentServerConfig>();
129 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
130 const serverConfig = get(presentationAtom(environmentId))?.serverConfig;
131 if (serverConfig != null) {
132 next.set(environmentId, serverConfig);
133 }
134 }
135 const previous = Option.getOrNull(
136 get.self<ReadonlyMap<EnvironmentId, EnvironmentServerConfig>>(),
137 );
138 return previous !== null && mapsEqual(previous, next) ? previous : next;
139 }).pipe(Atom.withLabel("environment-server-configs-without-providers"));
140
141 const providersByEnvironmentAtom = Atom.make((get) => {
142 const next = new Map<EnvironmentId, ReadonlyArray<ServerProvider>>();
143 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
144 const providers = get(input.serverConfigValueAtom(environmentId))?.providers;
145 if (providers !== undefined) {
146 next.set(environmentId, providers);
147 }
148 }
149 const previous = Option.getOrNull(
150 get.self<ReadonlyMap<EnvironmentId, ReadonlyArray<ServerProvider>>>(),
151 );
152 return previous !== null && mapsEqual(previous, next) ? previous : next;
153 }).pipe(Atom.withLabel("environment-providers"));
154
155 // Usage limits ride on provider statuses, so these surfaces rebuild on every push by design.
156 const presentationsWithProvidersAtom = Atom.make((get) => {
157 const previous = Option.getOrNull(
158 get.self<ReadonlyMap<EnvironmentId, EnvironmentPresentationWithProviders>>(),
159 );
160 const next = new Map<EnvironmentId, EnvironmentPresentationWithProviders>();
161 for (const [environmentId, presentation] of get(presentationsAtom)) {
162 const serverConfig = get(input.serverConfigValueAtom(environmentId));
163 const prior = previous?.get(environmentId);
164 next.set(
165 environmentId,
166 prior !== undefined &&
167 prior.entry === presentation.entry &&
168 prior.connection === presentation.connection &&
169 prior.serverConfig === serverConfig
170 ? prior
171 : { ...presentation, serverConfig },
172 );
173 }
174 return previous !== null && mapsEqual(previous, next) ? previous : next;
175 }).pipe(Atom.withLabel("environment-presentations-with-providers"));
176
177 return {
178 presentationAtom,
179 presentationsAtom,
180 serverConfigsAtom,
181 providersByEnvironmentAtom,
182 presentationsWithProvidersAtom,
183 };
184}
185
186export interface EnvironmentConnectionSummary {
187 readonly environmentId: EnvironmentId;
188 readonly environmentLabel: string;
189 readonly displayUrl: string;
190 readonly isRelayManaged: boolean;
191 readonly isEnabled: boolean;
192 readonly connectionState: EnvironmentConnectionPhase;
193 readonly connectionError: string | null;
194 readonly connectionErrorTraceId: string | null;
195}
196
197export function projectEnvironmentConnectionSummary(
198 environmentId: EnvironmentId,
199 environment: EnvironmentPresentation,
200): EnvironmentConnectionSummary {
201 return {
202 environmentId,
203 environmentLabel: environment.entry.target.label,
204 displayUrl: connectionCatalogDisplayUrl(environment.entry) ?? "",
205 isRelayManaged: hasRelayRoute(environment.entry),
206 isEnabled: environment.entry.enabled,
207 connectionState: environment.connection.phase,
208 connectionError: environment.connection.error,
209 connectionErrorTraceId: environment.connection.traceId,
210 };
211}
212
213export function createEnvironmentSummaryAtoms(input: {
214 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
215 readonly presentationAtom: (
216 environmentId: EnvironmentId,
217 ) => Atom.Atom<EnvironmentPresentation | null>;
218}) {
219 const environmentIdsAtom = Atom.make((get) => {
220 const next = [...get(input.catalogValueAtom).entries.keys()];
221 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentId>>());
222 return previous !== null &&
223 previous.length === next.length &&
224 next.every((id, index) => id === previous[index])
225 ? previous
226 : next;
227 });
228 const identitiesAtom = Atom.make((get) => {
229 const next = [...get(input.catalogValueAtom).entries].map(([environmentId, entry]) => ({
230 environmentId,
231 label: entry.target.label,
232 }));
233 const previous = Option.getOrNull(
234 get.self<ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>>(),
235 );
236 return previous !== null &&
237 previous.length === next.length &&
238 next.every(
239 (value, index) =>
240 value.environmentId === previous[index]?.environmentId &&
241 value.label === previous[index]?.label,
242 )
243 ? previous
244 : next;
245 });
246 const environmentAtom = Atom.family((environmentId: EnvironmentId) =>
247 Atom.make((get) => {
248 const presentation = get(input.presentationAtom(environmentId));
249 if (presentation === null) return null;
250 const next = projectEnvironmentConnectionSummary(environmentId, presentation);
251 const previous = Option.getOrNull(get.self<EnvironmentConnectionSummary | null>());
252 if (
253 previous !== null &&
254 previous.environmentId === next.environmentId &&
255 previous.environmentLabel === next.environmentLabel &&
256 previous.displayUrl === next.displayUrl &&
257 previous.isRelayManaged === next.isRelayManaged &&
258 previous.isEnabled === next.isEnabled &&
259 previous.connectionState === next.connectionState &&
260 previous.connectionError === next.connectionError &&
261 previous.connectionErrorTraceId === next.connectionErrorTraceId
262 )
263 return previous;
264 return next;
265 }),
266 );
267 const environmentsAtom = Atom.make((get) => {
268 const next: Array<EnvironmentConnectionSummary> = [];
269 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
270 const environment = get(environmentAtom(environmentId));
271 if (environment !== null) next.push(environment);
272 }
273 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentConnectionSummary>>());
274 return previous !== null &&
275 previous.length === next.length &&
276 next.every((value, index) => value === previous[index])
277 ? previous
278 : next;
279 }).pipe(Atom.withLabel("environment-connection-summaries"));
280 const connectedEnvironmentIdsAtom = Atom.make((get) => {
281 const next = get(environmentIdsAtom).filter(
282 (id) => get(environmentAtom(id))?.connectionState === "connected",
283 );
284 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentId>>());
285 return previous !== null &&
286 previous.length === next.length &&
287 next.every((id, index) => id === previous[index])
288 ? previous
289 : next;
290 });
291 const machineByIdAtom = Atom.make((get) => {
292 const next = new Map(
293 get(environmentIdsAtom).map(
294 (environmentId) =>
295 [
296 environmentId,
297 resolveEnvironmentMachineKind(
298 get(input.presentationAtom(environmentId))?.serverConfig ?? null,
299 ),
300 ] as const,
301 ),
302 );
303 const previous = Option.getOrNull(
304 get.self<ReadonlyMap<EnvironmentId, EnvironmentMachineKind>>(),
305 );
306 return previous !== null && mapsEqual(previous, next) ? previous : next;
307 });
308 const pullRequestsSupportedAtom = Atom.make((get) =>
309 get(environmentIdsAtom).some(
310 (environmentId) =>
311 get(input.presentationAtom(environmentId))?.serverConfig?.environment.capabilities
312 .pullRequests === true,
313 ),
314 );
315 return {
316 environmentIdsAtom,
317 connectedEnvironmentIdsAtom,
318 identitiesAtom,
319 environmentsAtom,
320 machineByIdAtom,
321 pullRequestsSupportedAtom,
322 };
323}