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 // Enabled environments only, like serverConfigsAtom: a disabled connection keeps its cached
156 // config, and its accounts would otherwise count in usage limits. Usage limits ride on provider
157 // statuses, so these surfaces rebuild on every push by design.
158 const presentationsWithProvidersAtom = Atom.make((get) => {
159 const previous = Option.getOrNull(
160 get.self<ReadonlyMap<EnvironmentId, EnvironmentPresentationWithProviders>>(),
161 );
162 const next = new Map<EnvironmentId, EnvironmentPresentationWithProviders>();
163 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
164 const presentation = get(presentationAtom(environmentId));
165 if (presentation === null) continue;
166 const serverConfig = get(input.serverConfigValueAtom(environmentId));
167 const prior = previous?.get(environmentId);
168 next.set(
169 environmentId,
170 prior !== undefined &&
171 prior.entry === presentation.entry &&
172 prior.connection === presentation.connection &&
173 prior.serverConfig === serverConfig
174 ? prior
175 : { ...presentation, serverConfig },
176 );
177 }
178 return previous !== null && mapsEqual(previous, next) ? previous : next;
179 }).pipe(Atom.withLabel("environment-presentations-with-providers"));
180
181 return {
182 presentationAtom,
183 presentationsAtom,
184 serverConfigsAtom,
185 providersByEnvironmentAtom,
186 presentationsWithProvidersAtom,
187 };
188}
189
190export interface EnvironmentConnectionSummary {
191 readonly environmentId: EnvironmentId;
192 readonly environmentLabel: string;
193 readonly displayUrl: string;
194 readonly isRelayManaged: boolean;
195 readonly isEnabled: boolean;
196 readonly connectionState: EnvironmentConnectionPhase;
197 readonly connectionError: string | null;
198 readonly connectionErrorTraceId: string | null;
199}
200
201export function projectEnvironmentConnectionSummary(
202 environmentId: EnvironmentId,
203 environment: EnvironmentPresentation,
204): EnvironmentConnectionSummary {
205 return {
206 environmentId,
207 environmentLabel: environment.entry.target.label,
208 displayUrl: connectionCatalogDisplayUrl(environment.entry) ?? "",
209 isRelayManaged: hasRelayRoute(environment.entry),
210 isEnabled: environment.entry.enabled,
211 connectionState: environment.connection.phase,
212 connectionError: environment.connection.error,
213 connectionErrorTraceId: environment.connection.traceId,
214 };
215}
216
217export function createEnvironmentSummaryAtoms(input: {
218 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
219 readonly presentationAtom: (
220 environmentId: EnvironmentId,
221 ) => Atom.Atom<EnvironmentPresentation | null>;
222}) {
223 const environmentIdsAtom = Atom.make((get) => {
224 const next = [...get(input.catalogValueAtom).entries.keys()];
225 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentId>>());
226 return previous !== null &&
227 previous.length === next.length &&
228 next.every((id, index) => id === previous[index])
229 ? previous
230 : next;
231 });
232 const identitiesAtom = Atom.make((get) => {
233 const next = [...get(input.catalogValueAtom).entries].map(([environmentId, entry]) => ({
234 environmentId,
235 label: entry.target.label,
236 }));
237 const previous = Option.getOrNull(
238 get.self<ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>>(),
239 );
240 return previous !== null &&
241 previous.length === next.length &&
242 next.every(
243 (value, index) =>
244 value.environmentId === previous[index]?.environmentId &&
245 value.label === previous[index]?.label,
246 )
247 ? previous
248 : next;
249 });
250 const environmentAtom = Atom.family((environmentId: EnvironmentId) =>
251 Atom.make((get) => {
252 const presentation = get(input.presentationAtom(environmentId));
253 if (presentation === null) return null;
254 const next = projectEnvironmentConnectionSummary(environmentId, presentation);
255 const previous = Option.getOrNull(get.self<EnvironmentConnectionSummary | null>());
256 if (
257 previous !== null &&
258 previous.environmentId === next.environmentId &&
259 previous.environmentLabel === next.environmentLabel &&
260 previous.displayUrl === next.displayUrl &&
261 previous.isRelayManaged === next.isRelayManaged &&
262 previous.isEnabled === next.isEnabled &&
263 previous.connectionState === next.connectionState &&
264 previous.connectionError === next.connectionError &&
265 previous.connectionErrorTraceId === next.connectionErrorTraceId
266 )
267 return previous;
268 return next;
269 }),
270 );
271 const environmentsAtom = Atom.make((get) => {
272 const next: Array<EnvironmentConnectionSummary> = [];
273 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
274 const environment = get(environmentAtom(environmentId));
275 if (environment !== null) next.push(environment);
276 }
277 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentConnectionSummary>>());
278 return previous !== null &&
279 previous.length === next.length &&
280 next.every((value, index) => value === previous[index])
281 ? previous
282 : next;
283 }).pipe(Atom.withLabel("environment-connection-summaries"));
284 const connectedEnvironmentIdsAtom = Atom.make((get) => {
285 const next = get(environmentIdsAtom).filter(
286 (id) => get(environmentAtom(id))?.connectionState === "connected",
287 );
288 const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentId>>());
289 return previous !== null &&
290 previous.length === next.length &&
291 next.every((id, index) => id === previous[index])
292 ? previous
293 : next;
294 });
295 const machineByIdAtom = Atom.make((get) => {
296 const next = new Map(
297 get(environmentIdsAtom).map(
298 (environmentId) =>
299 [
300 environmentId,
301 resolveEnvironmentMachineKind(
302 get(input.presentationAtom(environmentId))?.serverConfig ?? null,
303 ),
304 ] as const,
305 ),
306 );
307 const previous = Option.getOrNull(
308 get.self<ReadonlyMap<EnvironmentId, EnvironmentMachineKind>>(),
309 );
310 return previous !== null && mapsEqual(previous, next) ? previous : next;
311 });
312 const pullRequestsSupportedAtom = Atom.make((get) =>
313 get(environmentIdsAtom).some(
314 (environmentId) =>
315 get(input.presentationAtom(environmentId))?.serverConfig?.environment.capabilities
316 .pullRequests === true,
317 ),
318 );
319 return {
320 environmentIdsAtom,
321 connectedEnvironmentIdsAtom,
322 identitiesAtom,
323 environmentsAtom,
324 machineByIdAtom,
325 pullRequestsSupportedAtom,
326 };
327}