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

usePullRequestList.ts

383 lines13.7 KB

1import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
2import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import * as Effect from "effect/Effect";
6import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
7import { use, useMemo, useState } from "react";
8import { environmentCatalog } from "../../connection/catalog";
9import {
10 composerPullRequests,
11 pullRequestListPagesFamily,
12 pullRequestListPagesKey,
13 pullRequestListStatsFamily,
14} from "../../state/pull-requests";
15import {
16 appendPullRequestListPage,
17 mergeEnvironmentPullRequestPages,
18 nextPullRequestListInput,
19 patchPullRequestListEntry,
20 pullRequestListHead,
21 shownPullRequestListPages,
22 pullRequestStatKey as statKey,
23 scopedPullRequestListKey,
24 withShownPullRequestStats,
25 type EnvironmentPullRequestListEntry,
26 type PullRequestListPages,
27} from "./pullRequestList";
28​
29type ListTarget = { readonly environmentId: EnvironmentId; readonly input: PullRequestListInput };
30type Read = <A>(atom: Atom.Atom<A>) => A;
31​
32/** The head the list query holds now, cached or answered. */
33function currentHead(read: Read, target: ListTarget) {
34 return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null);
36​
37function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
38 return shownPullRequestListPages(
39 read(pullRequestListPagesFamily(pullRequestListPagesKey(target))),
40 currentHead(read, target),
41 );
43​
44const sourcesFamily = Atom.family((key: string) => {
45 const targets: readonly ListTarget[] = JSON.parse(key);
46 return Atom.make((get) =>
47 targets.map((target) => ({
48 target,
49 result: get(composerPullRequests.list(target)),
50 pages: currentPages(get, target),
51 stats: get(pullRequestListStatsFamily(target.environmentId)),
52 })),
53 );
54});
55​
56function continuations(registry: AtomRegistry.AtomRegistry, targets: readonly ListTarget[]) {
57 return targets.flatMap((target) => {
58 const pages = currentPages((atom) => registry.get(atom), target);
59 const input = pages && nextPullRequestListInput(pages, target.input);
60 return pages && input ? [{ target, pages, input }] : [];
61 });
63​
64async function loadNextPages(
65 registry: AtomRegistry.AtomRegistry,
66 targets: readonly ListTarget[],
67 retry: boolean,
68 signal: AbortSignal,
69) {
70 const responses = await Promise.allSettled(
71 continuations(registry, targets).map(async ({ target, pages, input }) => {
72 const response = await executeAtomQuery(
73 registry,
74 composerPullRequests.list({ ...target, input }),
75 {
76 signal,
77 refresh: retry,
78 reportFailure: false,
79 },
80 );
81 if (signal.aborted) return;
82 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
83 if (response.value.errors.length)
84 throw new Error(response.value.errors.map((error) => error.message).join("\n"));
85 const pagesAtom = pullRequestListPagesFamily(pullRequestListPagesKey(target));
86 const next = appendPullRequestListPage(
87 currentPages((atom) => registry.get(atom), target) ?? pages,
88 response.value,
89 input,
90 );
91 registry.set(pagesAtom, next);
92 if (
93 input.cursors &&
94 Object.keys(next.nextCursors).length &&
95 JSON.stringify(Object.entries(input.cursors).sort()) ===
96 JSON.stringify(Object.entries(next.nextCursors).sort())
97 )
98 throw new Error("Couldn't advance the list. Try again.");
99 }),
100 );
101 return requestErrors(responses);
103​
104async function refreshHeads(
105 registry: AtomRegistry.AtomRegistry,
106 targets: readonly ListTarget[],
107 signal: AbortSignal,
108) {
109 const responses = await Promise.allSettled(
110 targets.map(async (target) => {
111 await composerPullRequests.invalidate.run(registry, {
112 environmentId: target.environmentId,
113 input: {},
114 });
115 if (signal.aborted) return;
116 const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
117 refresh: true,
118 signal,
119 reportFailure: false,
120 });
121 if (signal.aborted) return;
122 if (response._tag === "Failure") throw squashAtomCommandFailure(response);
123 registry.set(
124 pullRequestListPagesFamily(pullRequestListPagesKey(target)),
125 pullRequestListHead(null, response.value),
126 );
127 }),
128 );
129 return requestErrors(responses);
131​
132// One load of each kind per list scope. The atoms are not kept alive, so leaving a scope (a
133// filter change, unmount) interrupts its load and aborts the requests.
134const pageLoadFamily = Atom.family((scopeKey: string) =>
135 Atom.fn((retry: boolean, get) =>
136 Effect.promise((signal) => loadNextPages(get.registry, JSON.parse(scopeKey), retry, signal)),
137 ),
138);
139const refreshLoadFamily = Atom.family((scopeKey: string) =>
140 Atom.fn((_: void, get) =>
141 Effect.promise((signal) => refreshHeads(get.registry, JSON.parse(scopeKey), signal)),
142 ),
143);
144​
145// Changes when any of the scope's environments brings up a new session.
146const sessionsFamily = Atom.family((scopeKey: string) =>
147 Atom.make((get) =>
148 (JSON.parse(scopeKey) as readonly ListTarget[])
149 .map(({ environmentId }) => get(environmentCatalog.sessionGenerationAtom(environmentId)))
150 .join(),
151 ),
152);
153​
154const settledError = (result: AsyncResult.AsyncResult<string | null, never>) =>
155 AsyncResult.isSuccess(result) && !result.waiting ? result.value : null;
156​
157export function usePullRequestList(targets: readonly ListTarget[]) {
158 const registry = use(RegistryContext);
159 const scopeKey = JSON.stringify(targets);
160 const sources = useAtomValue(sourcesFamily(scopeKey));
161 const pageAtom = pageLoadFamily(scopeKey);
162 const refreshAtom = refreshLoadFamily(scopeKey);
163 const page = useAtomValue(pageAtom);
164 const refresh = useAtomValue(refreshAtom);
165 const loadError = settledError(page);
166​
167 // A page or refresh asked for while an environment was unreachable fails at once, and its
168 // error stops loading on scroll. Once it is back, ask for the page again; a refresh's error is
169 // stale by then because the list queries re-run on reconnect.
170 // A listener alone does not compute the atom, so nothing would follow the connections.
171 useAtomMount(sessionsFamily(scopeKey));
172 useAtomSubscribe(sessionsFamily(scopeKey), () => {
173 const pageResult = registry.get(pageAtom);
174 const refreshResult = registry.get(refreshAtom);
175 if (settledError(refreshResult) !== null) registry.set(refreshAtom, Atom.Reset);
176 else if (settledError(pageResult) !== null && !refreshResult.waiting)
177 registry.set(pageAtom, true);
178 });
179​
180 // Read from the registry, not the render: a second onEndReached before React re-renders must
181 // see the load the first one started.
182 const loadMore = (retry = false) => {
183 const pageResult = registry.get(pageAtom);
184 const refreshResult = registry.get(refreshAtom);
185 if (pageResult.waiting || refreshResult.waiting) return;
186 if (!retry && settledError(pageResult)) return;
187 if (!continuations(registry, targets).length) return;
188 registry.set(refreshAtom, Atom.Reset);
189 registry.set(pageAtom, retry);
190 };
191​
192 const onRefresh = () => {
193 if (!targets.length || registry.get(refreshAtom).waiting) return;
194 registry.set(pageAtom, Atom.Reset);
195 registry.set(refreshAtom, undefined);
196 };
197​
198 const data = useMemo(
199 () =>
200 mergeEnvironmentPullRequestPages(
201 sources.flatMap(({ target, pages, stats }) =>
202 pages
203 ? [
204 {
205 environmentId: target.environmentId,
206 pages: {
207 ...pages,
208 entries: pages.entries.map((entry) => {
209 const stat = stats.stats.get(statKey(entry));
210 return stat
211 ? { ...entry, additions: stat.additions, deletions: stat.deletions }
212 : entry;
213 }),
214 },
215 },
216 ]
217 : [],
218 ),
219 ),
220 [sources],
221 );
222 const [visible, setVisible] = useState<{
223 key: string;
224 rows: readonly EnvironmentPullRequestListEntry[];
225 }>({ key: scopeKey, rows: [] });
226 const onViewableItemsChanged = ({
227 viewableItems,
228 }: {
229 viewableItems: readonly { item: EnvironmentPullRequestListEntry; isViewable: boolean }[];
230 }) => {
231 const rows = viewableItems.filter((token) => token.isViewable).map((token) => token.item);
232 setVisible((previous) =>
233 previous.key === scopeKey &&
234 previous.rows.map(scopedPullRequestListKey).join() ===
235 rows.map(scopedPullRequestListKey).join()
236 ? previous
237 : { key: scopeKey, rows },
238 );
239 };
240 const visibleRows =
241 visible.key === scopeKey && visible.rows.length ? visible.rows : data.entries.slice(0, 8);
242 // Visible rows carry the cached-answer overlay below. Decide which still need stats on the rows
243 // without it, so a cached answer shown offline does not unmount the query that holds it.
244 const withoutCachedOverlay = new Map(
245 data.entries.map((row) => [scopedPullRequestListKey(row), row]),
246 );
247 const statsKey = JSON.stringify(
248 targets.flatMap(({ environmentId }) => {
249 const refs = visibleRows
250 .filter((row) => {
251 const base = withoutCachedOverlay.get(scopedPullRequestListKey(row)) ?? row;
252 return row.environmentId === environmentId && base.additions + base.deletions === 0;
253 })
254 .map(({ projectId, host, repository, number }) => ({
255 projectId,
256 host,
257 repository,
258 number,
259 }));
260 return refs.length ? [{ environmentId, input: { refs } }] : [];
261 }),
262 );
263 const statsAtom = useMemo(() => {
264 const queries: readonly Parameters<typeof composerPullRequests.listStats>[0][] =
265 JSON.parse(statsKey);
266 return Atom.make((get) =>
267 queries.map((target) => ({
268 environmentId: target.environmentId,
269 result: get(composerPullRequests.listStats(target)),
270 })),
271 );
272 }, [statsKey]);
273 const counts = useAtomValue(statsAtom);
274 // Server answers land in pullRequestListStatsFamily; these cover a cached answer, which is
275 // all an offline environment has. Scrolling makes a new stats query, which has no answer until
276 // its cached rows load, so each environment keeps the answer it showed until the new one lands.
277 const [shown, setShown] = useState({ counts, answers: answeredStats(counts, []) });
278 if (shown.counts !== counts) setShown({ counts, answers: answeredStats(counts, shown.answers) });
279 const entries = useMemo(
280 () => withShownPullRequestStats(data.entries, shown.answers),
281 [data.entries, shown.answers],
282 );
283​
284 const updateEntry = (
285 entry: EnvironmentPullRequestListEntry,
286 patch: Partial<EnvironmentPullRequestListEntry>,
287 ) => {
288 const target = targets.find((target) => target.environmentId === entry.environmentId);
289 if (!target) return;
290 const pagesAtom = pullRequestListPagesFamily(pullRequestListPagesKey(target));
291 const read = <A>(atom: Atom.Atom<A>) => registry.get(atom);
292 const patched = patchPullRequestListEntry(
293 read(pagesAtom),
294 currentHead(read, target),
295 entry,
296 patch,
297 Date.now(),
298 );
299 if (patched) registry.set(pagesAtom, patched);
300 registry.refresh(composerPullRequests.list(target));
301 };
302 const errors = useMemo(
303 () =>
304 sources.flatMap(({ target, result }) => {
305 if (result._tag !== "Failure") return [];
306 const cause = Cause.squash(result.cause);
307 return [
308 {
309 environmentId: target.environmentId,
310 projectTitle: "",
311 message: cause instanceof Error ? cause.message : "Couldn't load pull requests.",
312 },
313 ];
314 }),
315 [sources],
316 );
317 const listing = useMemo(
318 () => ({ ...data, entries, errors: [...data.errors, ...errors] }),
319 [data, entries, errors],
320 );
321 return {
322 data: listing,
323 entries,
324 error: errors.map((error) => error.message).join("\n") || null,
325 isPending: sources.some(({ result }) => result.waiting) && !data.entries.length,
326 continued: data.continued,
327 loadMore,
328 onRefresh,
329 onViewableItemsChanged,
330 updateEntry,
331 refreshing: refresh.waiting,
332 loadingMore: page.waiting,
333 loadMoreError: loadError,
334 hasMore: sources.some(
335 ({ pages, target }) => pages && nextPullRequestListInput(pages, target.input),
336 ),
337 };
339​
340function requestErrors(results: readonly PromiseSettledResult<unknown>[]) {
341 return (
342 results
343 .flatMap((result) =>
344 result.status === "rejected"
345 ? [
346 result.reason instanceof Error
347 ? result.reason.message
348 : "Couldn't load pull requests.",
349 ]
350 : [],
351 )
352 .join("\n") || null
353 );
355​
356type StatsAnswer = {
357 readonly environmentId: EnvironmentId;
358 readonly stats: readonly PullRequestDiffStat[];
359};
360​
361/** Each environment's newest stats answer, or the one it had while its query has none. */
362function answeredStats(
363 counts: readonly {
364 readonly environmentId: EnvironmentId;
365 readonly result: AsyncResult.AsyncResult<
366 { readonly stats: readonly PullRequestDiffStat[] },
367 unknown
368 >;
369 }[],
370 previous: readonly StatsAnswer[],
371): readonly StatsAnswer[] {
372 const next = counts.flatMap(({ environmentId, result }) => {
373 const kept = previous.find((answer) => answer.environmentId === environmentId);
374 if (!AsyncResult.isSuccess(result)) return kept ? [kept] : [];
375 return kept?.stats === result.value.stats
376 ? [kept]
377 : [{ environmentId, stats: result.value.stats }];
378 });
379 return next.length === previous.length &&
380 next.every((answer, index) => answer === previous[index])
381 ? previous
382 : next;