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

ProviderUpdateEnvironmentRows.tsx

366 lines12.1 KB

1import { CheckIcon } from "lucide-react";
2import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
3import {
4 AuthProvidersManageScope,
5 type EnvironmentId,
6 type ServerProvider,
7} from "@t3tools/contracts";
8import {
9 isAtomCommandInterrupted,
10 squashAtomCommandFailure,
11 type AtomCommandResult,
12} from "@t3tools/client-runtime/state/runtime";
13​
14import { cn } from "~/lib/utils";
15import { serverEnvironment } from "~/state/server";
16import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
17import { useAtomCommand } from "~/state/use-atom-command";
18import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
19import {
20 collectProviderUpdateOutcomeSnapshots,
21 firstRejectedProviderUpdateMessage,
22 getProviderUpdateProgressToastView,
23 getProviderUpdateSidebarPillView,
24 isTerminalProviderUpdatePhase,
25 resolveEnvironmentUpdateRowStatus,
26 type LocalEnvironmentUpdateGroup,
27 type LocalProviderUpdateOutcome,
28 type ProviderUpdateRowStatus,
29 type ProviderUpdateRowStatusKind,
30 type ProviderUpdateToastView,
31} from "./ProviderUpdateLaunchNotification.logic";
32import { Button } from "./ui/button";
33import { Spinner } from "./ui/spinner";
34​
35type ProviderUpdateCommandResult = AtomCommandResult<
36 { readonly providers: ReadonlyArray<ServerProvider> },
37 unknown
38>;
39​
40function toProviderUpdateOutcome(input: {
41 readonly environmentId: EnvironmentId;
42 readonly isPrimary: boolean;
43 readonly target: {
44 readonly driver: ServerProvider["driver"];
45 readonly instanceId: ServerProvider["instanceId"];
46 };
47 readonly result: ProviderUpdateCommandResult;
48}): PromiseSettledResult<LocalProviderUpdateOutcome> {
49 if (input.result._tag === "Failure") {
50 if (isAtomCommandInterrupted(input.result)) {
51 return {
52 status: "fulfilled",
53 value: {
54 environmentId: input.environmentId,
55 isPrimary: input.isPrimary,
56 driver: input.target.driver,
57 instanceId: input.target.instanceId,
58 provider: null,
59 },
60 };
61 }
62 const error = squashAtomCommandFailure(input.result);
63 return {
64 status: "rejected",
65 reason: error instanceof Error ? error : new Error("Provider update failed."),
66 };
67 }
68​
69 const provider =
70 input.result.value.providers.find(
71 (candidate) => candidate.instanceId === input.target.instanceId,
72 ) ?? null;
73 return {
74 status: "fulfilled",
75 value: {
76 environmentId: input.environmentId,
77 isPrimary: input.isPrimary,
78 driver: input.target.driver,
79 instanceId: input.target.instanceId,
80 provider,
81 },
82 };
84​
85// Keep it well beyond the server's own update timeout (5 min) so a legitimately
86// slow update (npm installs routinely run tens of seconds) is never cut off and
87// left showing a dead, unresponsive Update button.
88const PENDING_EXPIRY_MS = 6 * 60_000;
89​
90function rowToneClass(kind: ProviderUpdateRowStatusKind): string {
91 switch (kind) {
92 case "failed":
93 return "text-destructive";
94 case "unchanged":
95 return "text-warning";
96 case "success":
97 return "text-success";
98 default:
99 return "text-muted-foreground";
100 }
102​
103function EnvironmentUpdateRow({
104 group,
105 status,
106 onUpdate,
107}: {
108 readonly group: LocalEnvironmentUpdateGroup;
109 readonly status: ProviderUpdateRowStatus;
110 readonly onUpdate: () => void;
111}) {
112 const canManageProviders = useEnvironmentScope(group.environmentId, AuthProvidersManageScope);
113 let trailing: ReactNode;
114 switch (status.kind) {
115 case "loading":
116 trailing = <Spinner size="md" tone="muted" />;
117 break;
118 case "success":
119 trailing = <CheckIcon aria-hidden="true" className="size-4 text-success" />;
120 break;
121 case "failed":
122 case "unchanged":
123 trailing = (
124 <Button size="xs" variant="outline" disabled={!canManageProviders} onClick={onUpdate}>
125 Retry
126 </Button>
127 );
128 break;
129 default:
130 trailing = (
131 <Button size="xs" variant="outline" disabled={!canManageProviders} onClick={onUpdate}>
132 Update
133 </Button>
134 );
135 break;
136 }
137​
138 return (
139 <div className="flex items-center justify-between gap-3 py-0.5">
140 <div className="flex min-w-0 flex-col">
141 <span className="truncate font-medium text-foreground">{group.label}</span>
142 <span className={cn("truncate text-xs", rowToneClass(status.kind))}>{status.text}</span>
143 {!canManageProviders ? (
144 <span className="text-xs text-muted-foreground">
145 This connection cannot manage provider accounts.
146 </span>
147 ) : null}
148 </div>
149 <div className="shrink-0">{trailing}</div>
150 </div>
151 );
153​
154export function ProviderUpdateEnvironmentRows({
155 onInteract,
156}: {
157 readonly onInteract?: () => void;
158}) {
159 const { groups } = useLocalEnvironmentUpdateGroups();
160 const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {
161 reportFailure: false,
162 });
163 const groupByEnvironment = useMemo(
164 () => new Map(groups.map((group) => [group.environmentId, group] as const)),
165 [groups],
166 );
167​
168 const visibleAfterIsoRef = useRef<string>(new Date().toISOString());
169​
170 // setPendingEnvironments is an async state update, and PENDING_EXPIRY_MS can
171 // clear the spinner while a request is still in flight, so a rapid
172 // double-click (or a click after the expiry fires mid- request) would
173 // otherwise dispatch a second full round of updates. A ref updates
174 // synchronously, so we can bail before doing any work.
175 const inFlightEnvironmentsRef = useRef<Set<EnvironmentId>>(new Set());
176​
177 // Bumped on each dispatch and captured locally, so an attempt that was
178 // superseded -- e.g. one that already tripped the expiry safety net and was
179 // retried -- detects it is no longer current and skips every state write when
180 // it finally resolves, instead of clobbering the newer attempt's
181 // spinner/result/error or its in-flight guard.
182 const requestVersionRef = useRef<Map<EnvironmentId, number>>(new Map());
183​
184 const [pendingEnvironments, setPendingEnvironments] = useState<ReadonlySet<EnvironmentId>>(
185 () => new Set(),
186 );
187 const [errorByEnvironment, setErrorByEnvironment] = useState<ReadonlyMap<EnvironmentId, string>>(
188 () => new Map(),
189 );
190 const [resultByEnvironment, setResultByEnvironment] = useState<
191 ReadonlyMap<EnvironmentId, ProviderUpdateToastView>
192 >(() => new Map());
193​
194 const clearPending = useCallback((environmentId: EnvironmentId) => {
195 setPendingEnvironments((previous) => {
196 if (!previous.has(environmentId)) {
197 return previous;
198 }
199 const next = new Set(previous);
200 next.delete(environmentId);
201 return next;
202 });
203 }, []);
204​
205 const handleUpdate = useCallback(
206 async (environmentId: EnvironmentId) => {
207 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
208 const group = groupByEnvironment.get(environmentId);
209 if (!group || group.candidates.length === 0) {
210 return;
211 }
212 if (inFlightEnvironmentsRef.current.has(environmentId)) {
213 return;
214 }
215 inFlightEnvironmentsRef.current.add(environmentId);
216 const requestVersion = (requestVersionRef.current.get(environmentId) ?? 0) + 1;
217 requestVersionRef.current.set(environmentId, requestVersion);
218 const isCurrentRequest = () =>
219 requestVersionRef.current.get(environmentId) === requestVersion;
220 onInteract?.();
221 const providerCount = group.candidates.length;
222 const targets = group.candidates.map((candidate) => ({
223 driver: candidate.driver,
224 instanceId: candidate.instanceId,
225 }));
226​
227 setPendingEnvironments((previous) => new Set(previous).add(environmentId));
228 setErrorByEnvironment((previous) => {
229 if (!previous.has(environmentId)) {
230 return previous;
231 }
232 const next = new Map(previous);
233 next.delete(environmentId);
234 return next;
235 });
236 setResultByEnvironment((previous) => {
237 if (!previous.has(environmentId)) {
238 return previous;
239 }
240 const next = new Map(previous);
241 next.delete(environmentId);
242 return next;
243 });
244​
245 const expiry = setTimeout(() => {
246 if (!isCurrentRequest()) {
247 return;
248 }
249 inFlightEnvironmentsRef.current.delete(environmentId);
250 clearPending(environmentId);
251 setErrorByEnvironment((previous) =>
252 new Map(previous).set(environmentId, "Update timed out — try again."),
253 );
254 }, PENDING_EXPIRY_MS);
255 try {
256 const results = await Promise.all(
257 targets.map(async (target): Promise<PromiseSettledResult<LocalProviderUpdateOutcome>> => {
258 try {
259 const result = await updateProvider({
260 environmentId,
261 input: { provider: target.driver, instanceId: target.instanceId },
262 });
263 return toProviderUpdateOutcome({
264 environmentId,
265 isPrimary: group.isPrimary,
266 target,
267 result,
268 });
269 } catch (error) {
270 return {
271 status: "rejected",
272 reason: error instanceof Error ? error : new Error("Provider update failed."),
273 };
274 }
275 }),
276 );
277 if (!isCurrentRequest()) {
278 return;
279 }
280 setErrorByEnvironment((previous) => {
281 if (!previous.has(environmentId)) {
282 return previous;
283 }
284 const next = new Map(previous);
285 next.delete(environmentId);
286 return next;
287 });
288 if (results.length === 0) {
289 setErrorByEnvironment((previous) =>
290 new Map(previous).set(
291 environmentId,
292 "This environment isn’t connected — try again once it reconnects.",
293 ),
294 );
295 return;
296 }
297 const rejectedMessage = firstRejectedProviderUpdateMessage(results);
298 if (rejectedMessage) {
299 setErrorByEnvironment((previous) =>
300 new Map(previous).set(environmentId, rejectedMessage),
301 );
302 return;
303 }
304 const view = getProviderUpdateProgressToastView({
305 providers: collectProviderUpdateOutcomeSnapshots(results),
306 providerCount,
307 });
308 // A stored view never re-polls, so persisting it would pin the row's
309 // spinner forever once the pending flag expires. Drop it and let the
310 // live per-environment provider state (pill) plus the pending expiry
311 // drive the row, so it self-heals to whatever the backend actually did.
312 if (isTerminalProviderUpdatePhase(view.phase)) {
313 setResultByEnvironment((previous) => new Map(previous).set(environmentId, view));
314 }
315 } catch (error) {
316 if (isCurrentRequest()) {
317 setErrorByEnvironment((previous) =>
318 new Map(previous).set(
319 environmentId,
320 error instanceof Error ? error.message : "Provider update failed.",
321 ),
322 );
323 }
324 } finally {
325 clearTimeout(expiry);
326 if (isCurrentRequest()) {
327 clearPending(environmentId);
328 inFlightEnvironmentsRef.current.delete(environmentId);
329 }
330 }
331 },
332 [clearPending, groupByEnvironment, onInteract, updateProvider],
333 );
334​
335 const rows = groups
336 .map((group) => ({
337 group,
338 status: resolveEnvironmentUpdateRowStatus({
339 group,
340 error: errorByEnvironment.get(group.environmentId),
341 result: resultByEnvironment.get(group.environmentId),
342 pill: getProviderUpdateSidebarPillView(group.candidates, {
343 visibleAfterIso: visibleAfterIsoRef.current,
344 }),
345 isPending: pendingEnvironments.has(group.environmentId),
346 }),
347 }))
348 .filter(({ group, status }) => group.candidates.length > 0 || status.kind !== "idle");
349​
350 if (rows.length === 0) {
351 return null;
352 }
353​
354 return (
355 <div className="mt-0.5 flex flex-col gap-1">
356 {rows.map(({ group, status }) => (
357 <EnvironmentUpdateRow
358 key={group.environmentId}
359 group={group}
360 status={status}
361 onUpdate={() => handleUpdate(group.environmentId)}
362 />
363 ))}
364 </div>
365 );