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