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

pullRequests.ts

337 lines12.6 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 createLinkedPullRequestSummaryAtomFamily,
4 createPullRequestEnvironmentAtoms,
5 createPullRequestStackAtomFamily,
6} from "@t3tools/client-runtime/state/pull-requests";
7import type {
8 EnvironmentId,
9 PullRequestListInput,
10 PullRequestListStatsInput,
11 PullRequestListEntry,
12 PullRequestRef,
13 PullRequestSummary,
14} from "@t3tools/contracts";
15import * as Option from "effect/Option";
16import { AsyncResult, Atom } from "effect/reactivity";
17import { useCallback, useLayoutEffect, useMemo } from "react";
18​
19import { connectionAtomRuntime } from "../connection/runtime";
20import { appAtomRegistry } from "../rpc/atomRegistry";
21import {
22 mergePullRequestLists,
23 type EnvironmentPullRequestStat,
24 type MergedPullRequestList,
25} from "../components/pullRequest/pullRequestList.logic";
26import { formatEnvironmentQueryError } from "./query";
27​
28export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime);
29export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(
30 connectionAtomRuntime,
31 pullRequestEnvironment.refreshes,
32);
33​
34export interface ObservedPullRequestSummary {
35 readonly summary: PullRequestSummary;
36 /** Client arrival time, the only ordering older servers leave us for same-dated snapshots. */
37 readonly observedAt: number;
39​
40const observedPullRequestSummaryAtom = Atom.family((key: string) =>
41 Atom.make<ObservedPullRequestSummary | null>(null).pipe(
42 Atom.setIdleTTL(5 * 60_000),
43 Atom.withLabel(`web-pull-requests:observed-summary:${key}`),
44 ),
45);
46​
47/**
48 * Positive when `incoming` is the newer snapshot. Merged is final. Then the host's own update
49 * time, then the server's read-start time, which survives its caches; a snapshot without one
50 * never beats a stamped read. Zero when neither side carries a read time.
51 */
52function compareSummaries(current: PullRequestSummary, incoming: PullRequestSummary): number {
53 const merged = Number(incoming.state === "merged") - Number(current.state === "merged");
54 if (merged !== 0) return merged;
55 const updated = Date.parse(incoming.updatedAt) - Date.parse(current.updatedAt);
56 if (updated !== 0) return updated;
57 if (current.observedAt === undefined && incoming.observedAt === undefined) return 0;
58 return (incoming.observedAt ?? -Infinity) - (current.observedAt ?? -Infinity);
60​
61export function newestPullRequestSummary(
62 current: PullRequestSummary | null,
63 observed: PullRequestSummary | null,
64): PullRequestSummary | null {
65 if (current === null) return observed;
66 if (observed === null) return current;
67 return compareSummaries(current, observed) >= 0 ? observed : current;
69​
70/** Reuse list status without treating its deferred line-count placeholders as real stats. */
71export function pullRequestListEntryToSummary(entry: PullRequestListEntry): PullRequestSummary {
72 return {
73 provider: entry.provider,
74 projectId: entry.projectId,
75 repository: entry.repository,
76 number: entry.number,
77 title: entry.title,
78 url: entry.url,
79 state: entry.state,
80 isDraft: entry.isDraft,
81 headBranch: entry.headBranch,
82 baseBranch: entry.baseBranch,
83 updatedAt: entry.updatedAt,
84 ...(entry.observedAt === undefined ? {} : { observedAt: entry.observedAt }),
85 author: entry.author,
86 ...(entry.reviewDecision === undefined ? {} : { reviewDecision: entry.reviewDecision }),
87 ...(entry.checksState === undefined ? {} : { checksState: entry.checksState }),
88 mergeability: entry.mergeability,
89 };
91​
92// A project has one remote, so its id already pins the host. Leaving the host out lets a list
93// row, a hostless legacy reference and a URL-derived thread reference share one entry.
94function pullRequestSummaryKey(environmentId: EnvironmentId, reference: PullRequestRef): string {
95 return JSON.stringify([
96 environmentId,
97 reference.projectId,
98 reference.repository.toLowerCase(),
99 reference.number,
100 ]);
102​
103/** The observation to hold after `incoming` arrives. Returns `current` itself on a tie. */
104export function newestPullRequestObservation(
105 current: ObservedPullRequestSummary | null,
106 incoming: ObservedPullRequestSummary | null,
107): ObservedPullRequestSummary | null {
108 if (current === null) return incoming;
109 if (incoming === null) return current;
110 let order = compareSummaries(current.summary, incoming.summary);
111 // Client clocks only break ties between snapshots that both lack a server read time.
112 if (
113 order === 0 &&
114 current.summary.observedAt === undefined &&
115 incoming.summary.observedAt === undefined
116 ) {
117 order = incoming.observedAt - current.observedAt;
118 }
119 if (!(order > 0)) return current;
120 // A sparse summary must not erase known status, or carry old detail stats into a new list read.
121 return {
122 ...incoming,
123 summary: {
124 ...incoming.summary,
125 isDraft: incoming.summary.isDraft ?? current.summary.isDraft,
126 mergeability: incoming.summary.mergeability ?? current.summary.mergeability,
127 reviewDecision:
128 incoming.summary.reviewDecision === undefined
129 ? current.summary.reviewDecision
130 : incoming.summary.reviewDecision,
131 checksState:
132 incoming.summary.checksState === undefined
133 ? current.summary.checksState
134 : incoming.summary.checksState,
135 },
136 };
138​
139function observePullRequestSummary(
140 environmentId: EnvironmentId,
141 reference: PullRequestRef,
142 summary: PullRequestSummary,
143 observedAt: number,
144): void {
145 const atom = observedPullRequestSummaryAtom(pullRequestSummaryKey(environmentId, reference));
146 appAtomRegistry.modify(atom, (previous) => {
147 const next = newestPullRequestObservation(previous, { summary, observedAt });
148 return next === previous ? [false, previous] : [true, next];
149 });
151​
152export function useSharedPullRequestSummary(
153 environmentId: EnvironmentId | null,
154 reference: PullRequestRef | null,
155 current: PullRequestSummary | null,
156 observedAt: number | null = null,
157): PullRequestSummary | null {
158 const key =
159 environmentId === null || reference === null
160 ? "none"
161 : pullRequestSummaryKey(environmentId, reference);
162 const atom = observedPullRequestSummaryAtom(key);
163 const observed = useAtomValue(atom);
164 useLayoutEffect(() => {
165 if (environmentId === null || reference === null || current === null || observedAt === null)
166 return;
167 observePullRequestSummary(environmentId, reference, current, observedAt);
168 }, [current, environmentId, reference, observedAt]);
169 return (
170 newestPullRequestObservation(
171 observed,
172 current === null || observedAt === null ? null : { summary: current, observedAt },
173 )?.summary ?? current
174 );
176export const pullRequestStackAtom = createPullRequestStackAtomFamily(
177 connectionAtomRuntime,
178 pullRequestEnvironment.refreshes,
179);
180​
181export interface EnvironmentQueryTarget<Input> {
182 readonly environmentId: EnvironmentId;
183 readonly input: Input;
185​
186interface MergedEnvironmentQueryView<A> {
187 /** One entry per query target that has answered, in the order the targets were given. */
188 readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
189 /** The first environment that failed. Others may still have answered — this is not fatal. */
190 readonly error: string | null;
191 readonly isPending: boolean;
192 readonly observations: ReadonlyArray<readonly [EnvironmentId, A, number]>;
194​
195/**
196 * The same per-environment query read across several environments at once. React cannot subscribe
197 * to a list of atoms whose length changes, so the fan-out happens inside one derived atom keyed by
198 * the targets — the same shape the cross-environment thread search uses.
199 *
200 * An environment that fails contributes nothing rather than blanking the page: the pull request
201 * list is a union, and one unreachable machine should not hide the others' rows.
202 */
203function createMergedEnvironmentQuery<Input, A>(
204 label: string,
205 atomFor: (
206 target: EnvironmentQueryTarget<Input>,
207 ) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
208) {
209 const family = Atom.family((key: string) =>
210 Atom.make((get): MergedEnvironmentQueryView<A> => {
211 const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
212 const values: Array<readonly [EnvironmentId, A]> = [];
213 const observations: Array<readonly [EnvironmentId, A, number]> = [];
214 let error: string | null = null;
215 let isPending = false;
216 for (const target of targets) {
217 const result = get(atomFor(target));
218 isPending ||= result.waiting;
219 if (result._tag === "Failure" && error === null) {
220 error = formatEnvironmentQueryError(result.cause);
221 }
222 const value = Option.getOrNull(AsyncResult.value(result));
223 if (value !== null) values.push([target.environmentId, value]);
224 if (result._tag === "Success") {
225 observations.push([target.environmentId, result.value, result.timestamp]);
226 }
227 }
228 return { values, error, isPending, observations };
229 }).pipe(Atom.withLabel(`${label}:${key}`)),
230 );
231 const empty = Atom.make<MergedEnvironmentQueryView<A>>({
232 values: [],
233 observations: [],
234 error: null,
235 isPending: false,
236 }).pipe(Atom.withLabel(`${label}:empty`));
237 return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
238 const key = JSON.stringify(targets);
239 const view = useAtomValue(targets.length === 0 ? empty : family(key));
240 const refresh = useCallback(
241 (override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {
242 const refreshTargets =
243 override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);
244 for (const atom of new Set(refreshTargets.map(atomFor))) {
245 appAtomRegistry.refresh(atom);
246 }
247 },
248 [key],
249 );
250 return { ...view, refresh };
251 };
253​
254const usePullRequestListsQuery = createMergedEnvironmentQuery(
255 "web-pull-requests:list",
256 pullRequestEnvironment.list,
257);
258​
259const usePullRequestStatsQuery = createMergedEnvironmentQuery(
260 "web-pull-requests:list-stats",
261 pullRequestEnvironment.listStats,
262);
263​
264const usePullRequestTurnRefreshQuery = createMergedEnvironmentQuery(
265 "web-pull-requests:turn-refreshes",
266 ({ environmentId }: EnvironmentQueryTarget<Readonly<Record<string, never>>>) =>
267 pullRequestEnvironment.refreshes({ environmentId, input: {} }),
268);
269​
270export function usePullRequestTurnRefreshes(
271 environmentIds: ReadonlyArray<EnvironmentId>,
272): ReadonlyArray<readonly [EnvironmentId, number]> {
273 return usePullRequestTurnRefreshQuery(
274 environmentIds.map((environmentId) => ({ environmentId, input: {} })),
275 ).values;
277​
278export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number | null {
279 const result = useAtomValue(pullRequestEnvironment.refreshes({ environmentId, input: {} }));
280 return Option.getOrNull(AsyncResult.value(result));
282​
283export interface MergedPullRequestListView {
284 readonly data: MergedPullRequestList | null;
285 readonly error: string | null;
286 readonly isPending: boolean;
287 readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;
289​
290/** One listing per environment, merged into the single list the page renders. */
291export function usePullRequestList(
292 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
293): MergedPullRequestListView {
294 const query = usePullRequestListsQuery(targets);
295 useLayoutEffect(() => {
296 for (const [environmentId, answer, observedAt] of query.observations) {
297 for (const entry of answer.entries) {
298 observePullRequestSummary(
299 environmentId,
300 {
301 projectId: entry.projectId,
302 host: entry.host,
303 repository: entry.repository,
304 number: entry.number,
305 },
306 pullRequestListEntryToSummary(entry),
307 observedAt,
308 );
309 }
310 }
311 }, [query.observations]);
312 const data = useMemo(() => mergePullRequestLists(query.values), [query.values]);
313 return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };
315​
316/** The line counts for the rows on screen, asked of each environment for its own rows. */
317export function usePullRequestListStats(
318 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
319): {
320 readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
321 readonly isPending: boolean;
322 readonly refresh: (
323 targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
324 ) => void;
325} {
326 const query = usePullRequestStatsQuery(targets);
327 const stats = useMemo(
328 () =>
329 query.values.length === 0
330 ? null
331 : query.values.flatMap(([environmentId, result]) =>
332 result.stats.map((stat) => ({ ...stat, environmentId })),
333 ),
334 [query.values],
335 );
336 return { stats, isPending: query.isPending, refresh: query.refresh };