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

pullRequests.ts

754 lines27.6 KB

1import { useAtomValue } from "@effect/atom-react";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import {
4 createLinkedPullRequestSummaryAtomFamily,
5 createPullRequestEnvironmentAtoms,
6 createPullRequestStackAtomFamily,
7} from "@t3tools/client-runtime/state/pull-requests";
8import {
9 PullRequestListResult,
10 PullRequestOperationError,
11 PullRequestUnavailableError,
12 type EnvironmentId,
13 type ProjectId,
14 type PullRequestChecksState,
15 type PullRequestFilesViewedResult,
16 type PullRequestListInput,
17 type PullRequestFilterOptionsInput,
18 type PullRequestListStatsInput,
19 type PullRequestListEntry,
20 type PullRequestRef,
21 type PullRequestSummary,
22 type ThreadPullRequestLink,
23} from "@t3tools/contracts";
24import {
25 threadPullRequestKeyOf,
26 visibleThreadPullRequests,
27} from "@t3tools/client-runtime/thread-pull-requests";
28import * as Cause from "effect/Cause";
29import * as Clock from "effect/Clock";
30import * as Effect from "effect/Effect";
31import * as Option from "effect/Option";
32import * as Schema from "effect/Schema";
33import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
34​
35import { connectionAtomRuntime } from "../connection/runtime";
36import { appAtomRegistry } from "../rpc/atomRegistry";
37import {
38 mergePullRequestLists,
39 type EnvironmentPullRequestStat,
40 type MergedPullRequestList,
41} from "../components/pullRequest/pullRequestList.logic";
42import { writePullRequestDetailSnapshot } from "../components/pullRequest/pullRequestDetail.logic";
43import { pullRequestChecksState } from "../components/pullRequest/pullRequestPresentation";
44import { useGuideRunStore } from "../components/pullRequest/guide/guideRunStore";
45import { formatEnvironmentQueryError } from "./query";
46import { environmentThreadShells } from "./threads";
47​
48export interface ObservedPullRequestSummary {
49 readonly summary: PullRequestSummary;
50 /** Client arrival time, the only ordering older servers leave us for same-dated snapshots. */
51 readonly observedAt: number;
53​
54function compareSummaries(current: PullRequestSummary, incoming: PullRequestSummary): number {
55 const merged = Number(incoming.state === "merged") - Number(current.state === "merged");
56 if (merged !== 0) return merged;
57 const updated = Date.parse(incoming.updatedAt) - Date.parse(current.updatedAt);
58 if (updated !== 0) return updated;
59 if (current.observedAt === undefined && incoming.observedAt === undefined) return 0;
60 return (incoming.observedAt ?? -Infinity) - (current.observedAt ?? -Infinity);
62​
63export function newestPullRequestSummary(
64 current: PullRequestSummary | null,
65 observed: PullRequestSummary | null,
66): PullRequestSummary | null {
67 if (current === null) return observed;
68 if (observed === null) return current;
69 return compareSummaries(current, observed) >= 0 ? observed : current;
71​
72export function pullRequestListEntryToSummary(entry: PullRequestListEntry): PullRequestSummary {
73 return {
74 provider: entry.provider,
75 projectId: entry.projectId,
76 repository: entry.repository,
77 number: entry.number,
78 title: entry.title,
79 url: entry.url,
80 state: entry.state,
81 isDraft: entry.isDraft,
82 headBranch: entry.headBranch,
83 baseBranch: entry.baseBranch,
84 updatedAt: entry.updatedAt,
85 ...(entry.observedAt === undefined ? {} : { observedAt: entry.observedAt }),
86 author: entry.author,
87 ...(entry.reviewDecision === undefined ? {} : { reviewDecision: entry.reviewDecision }),
88 ...(entry.checksState === undefined ? {} : { checksState: entry.checksState }),
89 mergeability: entry.mergeability,
90 };
92​
93// Project ids pin the remote host; omit host so legacy, URL, and list references share entries.
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​
103export function newestPullRequestObservation(
104 current: ObservedPullRequestSummary | null,
105 incoming: ObservedPullRequestSummary | null,
106): ObservedPullRequestSummary | null {
107 if (current === null) return incoming;
108 if (incoming === null) return current;
109 let order = compareSummaries(current.summary, incoming.summary);
110 if (
111 order === 0 &&
112 current.summary.observedAt === undefined &&
113 incoming.summary.observedAt === undefined
114 ) {
115 order = incoming.observedAt - current.observedAt;
116 }
117 if (!(order > 0)) return current;
118 // A sparse summary must not erase known status, or carry old detail stats into a new list read.
119 return {
120 ...incoming,
121 summary: {
122 ...incoming.summary,
123 isDraft: incoming.summary.isDraft ?? current.summary.isDraft,
124 mergeability: incoming.summary.mergeability ?? current.summary.mergeability,
125 reviewDecision:
126 incoming.summary.reviewDecision === undefined
127 ? current.summary.reviewDecision
128 : incoming.summary.reviewDecision,
129 checksState:
130 incoming.summary.checksState === undefined
131 ? current.summary.checksState
132 : incoming.summary.checksState,
133 },
134 };
136​
137export interface ObservedPullRequestChecks {
138 readonly checksState: PullRequestChecksState | null;
139 /** Server read time, when the server reports one. */
140 readonly readAt: number | undefined;
141 /** Client arrival time. */
142 readonly observedAt: number;
144​
145/**
146 * Checks are reread far more often than the rest of a pull request, so they keep their own
147 * freshness: a checks read must not carry old metadata forward, and a list read must not take
148 * back newer checks.
149 */
150export interface PullRequestObservations {
151 readonly metadata: ObservedPullRequestSummary | null;
152 readonly checks: ObservedPullRequestChecks | null;
154​
155const noObservations: PullRequestObservations = { metadata: null, checks: null };
156​
157const pullRequestObservationsAtom = Atom.family((key: string) =>
158 Atom.make<PullRequestObservations>(noObservations).pipe(
159 Atom.setIdleTTL(5 * 60_000),
160 Atom.withLabel(`web-pull-requests:observations:${key}`),
161 ),
162);
163​
164export function observePullRequestChecks(
165 current: PullRequestObservations,
166 incoming: ObservedPullRequestChecks,
167): PullRequestObservations {
168 const previous = current.checks;
169 const newer =
170 previous === null ||
171 (previous.readAt !== undefined && incoming.readAt !== undefined
172 ? incoming.readAt >= previous.readAt
173 : incoming.observedAt >= previous.observedAt);
174 return newer ? { ...current, checks: incoming } : current;
176​
177export function observePullRequestMetadata(
178 current: PullRequestObservations,
179 incoming: ObservedPullRequestSummary,
180): PullRequestObservations {
181 const metadata = newestPullRequestObservation(current.metadata, incoming);
182 const next = metadata === current.metadata ? current : { ...current, metadata };
183 const { checksState } = incoming.summary;
184 return checksState === undefined
185 ? next
186 : observePullRequestChecks(next, {
187 checksState,
188 readAt: incoming.summary.observedAt,
189 observedAt: incoming.observedAt,
190 });
192​
193export function observedPullRequestSummary(
194 observations: PullRequestObservations,
195): PullRequestSummary | null {
196 const { metadata, checks } = observations;
197 if (metadata === null) return null;
198 return checks === null
199 ? metadata.summary
200 : { ...metadata.summary, checksState: checks.checksState };
202​
203function recordObservation(
204 registry: AtomRegistry.AtomRegistry,
205 key: string,
206 observe: (current: PullRequestObservations) => PullRequestObservations,
207): void {
208 registry.modify(pullRequestObservationsAtom(key), (previous) => {
209 const next = observe(previous);
210 return next === previous ? [false, previous] : [true, next];
211 });
213​
214function observePullRequestSummary(
215 registry: AtomRegistry.AtomRegistry,
216 key: string,
217 summary: PullRequestSummary,
218 observedAt: number,
219): void {
220 recordObservation(registry, key, (current) =>
221 observePullRequestMetadata(current, { summary, observedAt }),
222 );
224​
225// Reading localStorage throws where the browser blocks storage; that must not break the page.
226function snapshotStorage(): Storage | undefined {
227 if (typeof window === "undefined") return undefined;
228 try {
229 return window.localStorage;
230 } catch {
231 return undefined;
232 }
234​
235type ListAnswerStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
236​
237const LIST_SCOPE_INDEX_KEY = "t3.pullRequests.listScopes";
238const LIST_SCOPE_KEY_PREFIX = "t3.pullRequests.listScope:";
239const LEGACY_SNAPSHOT_KEY_PREFIX = "t3.pullRequests.list:";
240const LIST_ANSWER_MAX_ENTRIES = 99;
241/**
242 * A scope holds a page of rows per environment, so only the scopes visited most recently are
243 * kept. Eviction drops a whole scope, never one environment's answer, so a restored list is never
244 * missing environments that did answer.
245 */
246const LIST_SCOPE_MAX_KEPT = 8;
247const listScopeCodec = Schema.fromJsonString(
248 Schema.Record(Schema.String, Schema.toCodecJson(PullRequestListResult)),
249);
250const decodeListScope = Schema.decodeUnknownOption(listScopeCodec);
251const encodeListScope = Schema.encodeOption(listScopeCodec);
252const decodeListScopeIndex = Schema.decodeUnknownOption(
253 Schema.fromJsonString(Schema.Array(Schema.String)),
254);
255const sweptStorages = new WeakSet<ListAnswerStorage>();
256​
257/**
258 * The project assignment is left out: a cold start asks before the project shells load, when
259 * every environment is asked for all of its projects, while the answers were remembered after
260 * overlapping projects were split between environments. Each environment's answer covers only
261 * its assigned projects, so the scope's answers together still cover the whole scope.
262 */
263const listScopeKey = ({ projectIds: _projectIds, ...scope }: PullRequestListInput) =>
264 `${LIST_SCOPE_KEY_PREFIX}${JSON.stringify(scope)}`;
265​
266function readListScope(storage: ListAnswerStorage | undefined, key: string) {
267 let raw: string | null = null;
268 try {
269 raw = storage?.getItem(key) ?? null;
270 } catch {}
271 return Option.getOrElse(decodeListScope(raw), (): Record<string, PullRequestListResult> => ({}));
273​
274/** The single composite snapshot this replaced is never read again. */
275function sweepLegacySnapshots(storage: ListAnswerStorage): void {
276 if (sweptStorages.has(storage)) return;
277 sweptStorages.add(storage);
278 const legacy: string[] = [];
279 for (let index = 0; index < storage.length; index++) {
280 const key = storage.key(index);
281 if (key?.startsWith(LEGACY_SNAPSHOT_KEY_PREFIX)) legacy.push(key);
282 }
283 for (const key of legacy) storage.removeItem(key);
285​
286/**
287 * Keeps what a cold start can show before the host answers again. Searches, continuation pages
288 * and grown pages are never shown that way, so only first-page reads are kept. Failures and
289 * cursors are dropped: they describe the moment of the read, and a restored list must not
290 * continue from it.
291 */
292export function rememberPullRequestListAnswer(
293 storage: ListAnswerStorage | undefined,
294 target: EnvironmentQueryTarget<PullRequestListInput>,
295 answer: PullRequestListResult,
296): void {
297 const { input } = target;
298 if (storage === undefined || input.query !== undefined || input.cursors !== undefined) return;
299 if (input.limit !== undefined && input.limit > LIST_ANSWER_MAX_ENTRIES) return;
300 const key = listScopeKey(input);
301 try {
302 sweepLegacySnapshots(storage);
303 const scope = readListScope(storage, key);
304 // An answer for some projects replaces only their rows. A repository this environment no
305 // longer owns stays covered until the environment that took it over answers; the next answer
306 // for all of the environment's projects, which every cold start asks for, drops them.
307 const assigned = input.projectIds === undefined ? undefined : new Set(input.projectIds);
308 const retained =
309 assigned === undefined
310 ? []
311 : (scope[target.environmentId]?.entries ?? []).filter(
312 (entry) => !assigned.has(entry.projectId),
313 );
314 const encoded = encodeListScope({
315 ...scope,
316 [target.environmentId]: {
317 ...answer,
318 // The fresh rows come first, so retained rows only fill what is left of the page.
319 entries: [...answer.entries, ...retained].slice(0, LIST_ANSWER_MAX_ENTRIES),
320 errors: [],
321 nextCursors: {},
322 },
323 });
324 if (Option.isNone(encoded)) return;
325 const index = Option.getOrElse(
326 decodeListScopeIndex(storage.getItem(LIST_SCOPE_INDEX_KEY)),
327 () => [],
328 );
329 const kept = [key, ...index.filter((held) => held !== key)];
330 for (const evicted of kept.slice(LIST_SCOPE_MAX_KEPT)) storage.removeItem(evicted);
331 storage.setItem(key, encoded.value);
332 storage.setItem(LIST_SCOPE_INDEX_KEY, JSON.stringify(kept.slice(0, LIST_SCOPE_MAX_KEPT)));
333 } catch {}
335​
336/**
337 * The kept answers for these reads, merged the way live answers are. An environment without a
338 * kept answer is left out rather than failing the restore: one whose projects were all assigned
339 * to another environment was never asked, and its pull requests are in that environment's answer.
340 */
341export function restorePullRequestList(
342 storage: ListAnswerStorage | undefined,
343 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
344): MergedPullRequestList | null {
345 const scopes = new Map<string, Record<string, PullRequestListResult>>();
346 const answers: Array<readonly [EnvironmentId, PullRequestListResult]> = [];
347 for (const target of targets) {
348 const key = listScopeKey(target.input);
349 const scope = scopes.get(key) ?? readListScope(storage, key);
350 scopes.set(key, scope);
351 const answer = scope[target.environmentId];
352 if (answer !== undefined) answers.push([target.environmentId, answer]);
353 }
354 const merged = mergePullRequestLists(answers);
355 if (merged === null) return null;
356 // Answers kept before the projects were reassigned between environments can overlap.
357 const seen = new Set<string>();
358 const entries = merged.entries.filter((entry) => {
359 const key = `${entry.host}:${entry.repository}#${entry.number}`;
360 if (seen.has(key)) return false;
361 seen.add(key);
362 return true;
363 });
364 return { ...merged, entries };
366​
367export function restoredPullRequestList(
368 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
369): MergedPullRequestList | null {
370 return restorePullRequestList(snapshotStorage(), targets);
372​
373const filesViewedAnswerListeners = new Map<
374 string,
375 Set<(answer: PullRequestFilesViewedResult) => void>
376>();
377​
378function filesViewedAnswerKey({ environmentId, input }: EnvironmentQueryTarget<PullRequestRef>) {
379 return JSON.stringify([
380 environmentId,
381 input.projectId,
382 input.host,
383 input.expectedAccountId,
384 input.allowStale,
385 input.repository,
386 input.number,
387 ]);
389​
390export function subscribePullRequestFilesViewedAnswers(
391 target: EnvironmentQueryTarget<PullRequestRef>,
392 onAnswer: (answer: PullRequestFilesViewedResult) => void,
393) {
394 const key = filesViewedAnswerKey(target);
395 let listeners = filesViewedAnswerListeners.get(key);
396 if (listeners === undefined) filesViewedAnswerListeners.set(key, (listeners = new Set()));
397 listeners.add(onAnswer);
398 return () => {
399 listeners.delete(onAnswer);
400 if (listeners.size === 0) filesViewedAnswerListeners.delete(key);
401 };
403​
404// Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
405export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
406 filesViewed: (target, answer) =>
407 Effect.sync(() => {
408 for (const listener of filesViewedAnswerListeners.get(filesViewedAnswerKey(target)) ?? [])
409 listener(answer);
410 }),
411 list: ({ environmentId, input }, answer, registry) =>
412 Effect.map(Clock.currentTimeMillis, (observedAt) => {
413 rememberPullRequestListAnswer(snapshotStorage(), { environmentId, input }, answer);
414 for (const entry of answer.entries) {
415 observePullRequestSummary(
416 registry,
417 pullRequestSummaryKey(environmentId, entry),
418 pullRequestListEntryToSummary(entry),
419 observedAt,
420 );
421 }
422 }),
423 detail: ({ environmentId, input }, detail, registry) =>
424 Effect.map(Clock.currentTimeMillis, (at) => {
425 // Only fresh reads seed the cold-start snapshot; a stale one could replace a newer record.
426 if (input.allowStale === false) {
427 writePullRequestDetailSnapshot(snapshotStorage(), environmentId, input, detail);
428 }
429 observePullRequestSummary(
430 registry,
431 pullRequestSummaryKey(environmentId, input),
432 { ...detail, checksState: pullRequestChecksState(detail.checks) },
433 at,
434 );
435 }),
436 checks: ({ environmentId, input }, checks, registry) =>
437 Effect.map(Clock.currentTimeMillis, (observedAt) => {
438 if (checks === null) return;
439 recordObservation(registry, pullRequestSummaryKey(environmentId, input), (current) =>
440 observePullRequestChecks(current, {
441 checksState: pullRequestChecksState(checks.checks),
442 readAt: checks.observedAt,
443 observedAt,
444 }),
445 );
446 }),
447 // Covers runs started elsewhere (another client, an agent) as well as this client's own.
448 reviewGuide: ({ environmentId, input }, guide) =>
449 Effect.map(Clock.currentTimeMillis, (since) => {
450 if (guide.run?._tag !== "Running") return;
451 useGuideRunStore.getState().watch({
452 environmentId,
453 reference: input,
454 title: null,
455 previousGuideAt: guide.guide?.generatedAt ?? null,
456 previousFailedAt: null,
457 since,
458 answeredRunning: true,
459 });
460 }),
461});
462​
463export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(
464 connectionAtomRuntime,
465 pullRequestEnvironment.refreshes,
466 ({ environmentId, input }, summary, registry) =>
467 Effect.map(Clock.currentTimeMillis, (observedAt) =>
468 observePullRequestSummary(
469 registry,
470 pullRequestSummaryKey(environmentId, input),
471 summary,
472 observedAt,
473 ),
474 ),
475);
476​
477export function threadPullRequestLinkToSummary(
478 link: ThreadPullRequestLink,
479 projectId: ProjectId,
480): PullRequestSummary | null {
481 const updatedAt = link.snapshot?.updatedAt;
482 if (link.snapshot === null || updatedAt == null) return null;
483 return {
484 ...link.snapshot,
485 provider: (
486 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
487 ).kind,
488 projectId,
489 repository: link.repository,
490 number: link.number,
491 url: link.url,
492 updatedAt,
493 };
495​
496function savedPullRequestKey(
497 environmentId: EnvironmentId,
498 reference: Pick<PullRequestRef, "host" | "repository" | "number">,
499): string {
500 return reference.host === undefined
501 ? ""
502 : `${environmentId}:${threadPullRequestKeyOf({ ...reference, host: reference.host })}`;
504​
505const savedPullRequestSummariesAtom = Atom.make((get) => {
506 const summaries = new Map<string, PullRequestSummary>();
507 for (const thread of get(environmentThreadShells.threadShellsAtom)) {
508 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
509 const summary = threadPullRequestLinkToSummary(link, thread.projectId);
510 if (summary === null) continue;
511 const key = savedPullRequestKey(thread.environmentId, link);
512 summaries.set(key, newestPullRequestSummary(summaries.get(key) ?? null, summary) ?? summary);
513 }
514 }
515 return summaries;
516});
517​
518const savedPullRequestSummaryAtom = Atom.family((key: string) =>
519 Atom.make((get) => get(savedPullRequestSummariesAtom).get(key) ?? null).pipe(
520 Atom.withEquality((previous, next) => JSON.stringify(previous) === JSON.stringify(next)),
521 Atom.setIdleTTL(5 * 60_000),
522 ),
523);
524​
525export function observedPullRequestTitle(
526 registry: AtomRegistry.AtomRegistry,
527 environmentId: EnvironmentId,
528 reference: PullRequestRef,
529): string | null {
530 return (
531 registry.get(pullRequestObservationsAtom(pullRequestSummaryKey(environmentId, reference)))
532 .metadata?.summary.title ?? null
533 );
535​
536/** The newest of every list, detail, checks and linked-summary answer and the thread's saved link. */
537export function useSharedPullRequestSummary(
538 environmentId: EnvironmentId | null,
539 reference: PullRequestRef | null,
540): PullRequestSummary | null {
541 const key =
542 environmentId === null || reference === null
543 ? "none"
544 : pullRequestSummaryKey(environmentId, reference);
545 const observations = useAtomValue(pullRequestObservationsAtom(key));
546 const saved = useAtomValue(
547 savedPullRequestSummaryAtom(
548 environmentId === null || reference === null
549 ? ""
550 : savedPullRequestKey(environmentId, reference),
551 ),
552 );
553 return newestPullRequestSummary(observedPullRequestSummary(observations), saved);
555export const pullRequestStackAtom = createPullRequestStackAtomFamily(
556 connectionAtomRuntime,
557 pullRequestEnvironment.refreshes,
558);
559​
560export interface EnvironmentQueryTarget<Input> {
561 readonly environmentId: EnvironmentId;
562 readonly input: Input;
564​
565interface EnvironmentQueryError {
566 readonly environmentId: EnvironmentId;
567 readonly message: string;
569​
570interface MergedEnvironmentQueryView<A> {
571 readonly observations: ReadonlyArray<readonly [EnvironmentId, A, number]>;
572 readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
573 readonly error: EnvironmentQueryError | null;
574 readonly isPending: boolean;
576​
577const failedListObservedAt = new WeakMap<object, number>();
578const isUnavailableList = Schema.is(PullRequestUnavailableError);
579const isFailedList = Schema.is(PullRequestOperationError);
580​
581export function observeFailedPullRequestList(
582 result: AsyncResult.Failure<PullRequestListResult, unknown>,
583): { readonly value: PullRequestListResult; readonly observedAt: number } | undefined {
584 if (result.waiting) return undefined;
585 const error = Option.getOrNull(Cause.findErrorOption(result.cause));
586 if ((!isUnavailableList(error) && !isFailedList(error)) || error.listResult === undefined) {
587 return undefined;
588 }
589 let observedAt = failedListObservedAt.get(result.cause);
590 if (observedAt === undefined) {
591 observedAt = Date.now();
592 failedListObservedAt.set(result.cause, observedAt);
593 }
594 return { value: error.listResult, observedAt };
596​
597// Use one derived atom for variable fan-out; unreachable environments must not hide other rows.
598function createMergedEnvironmentQuery<Input, A>(
599 label: string,
600 atomFor: (
601 target: EnvironmentQueryTarget<Input>,
602 ) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
603 observeFailure?: (
604 result: AsyncResult.Failure<A, unknown>,
605 ) => { readonly value: A; readonly observedAt: number } | undefined,
606) {
607 const family = Atom.family((key: string) =>
608 Atom.make((get): MergedEnvironmentQueryView<A> => {
609 const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
610 const values: Array<readonly [EnvironmentId, A]> = [];
611 const observations: Array<readonly [EnvironmentId, A, number]> = [];
612 const pendingEnvironments = new Set<EnvironmentId>();
613 let error: EnvironmentQueryError | null = null;
614 let isPending = false;
615 for (const target of targets) {
616 const result = get(atomFor(target));
617 isPending ||= result.waiting;
618 if (result.waiting) pendingEnvironments.add(target.environmentId);
619 if (result._tag === "Failure" && error === null) {
620 error = {
621 environmentId: target.environmentId,
622 message: formatEnvironmentQueryError(result.cause),
623 };
624 }
625 const value = AsyncResult.getOrElse(result, () => null);
626 if (value !== null) values.push([target.environmentId, value]);
627 if (result._tag === "Success") {
628 observations.push([target.environmentId, result.value, result.timestamp]);
629 } else if (result._tag === "Failure") {
630 const observation = observeFailure?.(result);
631 if (observation !== undefined) {
632 observations.push([target.environmentId, observation.value, observation.observedAt]);
633 }
634 }
635 }
636 return {
637 values,
638 error,
639 isPending,
640 // Another batch can still find a readable checkout on this environment.
641 observations: observations.filter(
642 ([environmentId]) => !pendingEnvironments.has(environmentId),
643 ),
644 };
645 }).pipe(Atom.withLabel(`${label}:${key}`)),
646 );
647 const empty = Atom.make<MergedEnvironmentQueryView<A>>({
648 observations: [],
649 values: [],
650 error: null,
651 isPending: false,
652 }).pipe(Atom.withLabel(`${label}:empty`));
653 return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
654 const key = JSON.stringify(targets);
655 const view = useAtomValue(targets.length === 0 ? empty : family(key));
656 const refresh = (override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {
657 const refreshTargets =
658 override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);
659 for (const atom of new Set(refreshTargets.map(atomFor))) {
660 appAtomRegistry.refresh(atom);
661 }
662 };
663 return { ...view, refresh };
664 };
666​
667const usePullRequestListsQuery = createMergedEnvironmentQuery(
668 "web-pull-requests:list",
669 pullRequestEnvironment.list,
670 observeFailedPullRequestList,
671);
672​
673const usePullRequestStatsQuery = createMergedEnvironmentQuery(
674 "web-pull-requests:list-stats",
675 pullRequestEnvironment.listStats,
676);
677​
678const usePullRequestFilterOptionsQuery = createMergedEnvironmentQuery(
679 "web-pull-requests:filter-options",
680 pullRequestEnvironment.filterOptions,
681);
682​
683const usePullRequestTurnRefreshQuery = createMergedEnvironmentQuery(
684 "web-pull-requests:turn-refreshes",
685 ({ environmentId }: EnvironmentQueryTarget<Readonly<Record<string, never>>>) =>
686 pullRequestEnvironment.refreshes({ environmentId, input: {} }),
687);
688​
689export function usePullRequestTurnRefreshes(
690 environmentIds: ReadonlyArray<EnvironmentId>,
691): ReadonlyArray<readonly [EnvironmentId, number]> {
692 return usePullRequestTurnRefreshQuery(
693 environmentIds.map((environmentId) => ({ environmentId, input: {} })),
694 ).values;
696​
697export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number | null {
698 const result = useAtomValue(pullRequestEnvironment.refreshes({ environmentId, input: {} }));
699 return AsyncResult.getOrElse(result, () => null);
701​
702export interface MergedPullRequestListView {
703 readonly data: MergedPullRequestList | null;
704 readonly error: EnvironmentQueryError | null;
705 readonly isPending: boolean;
706 readonly observations: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult, number]>;
707 readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;
709​
710export function usePullRequestList(
711 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
712): MergedPullRequestListView {
713 const query = usePullRequestListsQuery(targets);
714 const data = mergePullRequestLists(query.values);
715 return {
716 data,
717 error: query.error,
718 isPending: query.isPending,
719 observations: query.observations,
720 refresh: query.refresh,
721 };
723​
724export function usePullRequestListStats(
725 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
726): {
727 readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
728 readonly isPending: boolean;
729 readonly refresh: (
730 targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
731 ) => void;
732} {
733 const query = usePullRequestStatsQuery(targets);
734 const stats =
735 query.values.length === 0
736 ? null
737 : query.values.flatMap(([environmentId, result]) =>
738 result.stats.map((stat) => ({ ...stat, environmentId })),
739 );
740 return { stats, isPending: query.isPending, refresh: query.refresh };
742​
743export function usePullRequestFilterOptions(
744 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestFilterOptionsInput>>,
745) {
746 const query = usePullRequestFilterOptionsQuery(targets);
747 return {
748 labels: query.values.flatMap(([, options]) => options.labels),
749 authors: query.values.flatMap(([, options]) => options.authors),
750 references: query.values.flatMap(([, options]) => options.references),
751 error: query.error,
752 isPending: query.isPending,
753 };