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

issueList.ts

358 lines14.2 KB

1import type {
2 EnvironmentId,
3 IssueListCursors,
4 IssueListEntry,
5 IssueListProjectError,
6 IssueListResult,
7 IssueListSort,
8 IssueScopeRef,
9 IssueTrackerSummary,
10 SourceControlProviderKind,
11} from "@t3tools/contracts";
12​
13import { mergeIssueListPage } from "./state/issues.ts";
14import { sourceControlClients } from "./sourceControlClients.ts";
15import type { EnvironmentProject } from "./state/shell.ts";
16​
17export interface EnvironmentIssueEntry extends IssueListEntry {
18 readonly environmentId: EnvironmentId;
20​
21/** Rows from every environment that answered, with any continuation pages laid over them. */
22export interface HeldIssuePage {
23 /** Which listing (its filters) the pages belong to; another listing starts over. */
24 readonly list: string;
25 readonly answer: IssueListResult;
26 readonly entries: ReadonlyArray<IssueListEntry>;
27 readonly errors: ReadonlyArray<IssueListProjectError>;
28 /** What continuations reported, each beside the cursors it was asked to carry on. */
29 readonly moreErrors: ReadonlyArray<{
30 readonly asked: ReadonlyArray<string>;
31 readonly errors: ReadonlyArray<IssueListProjectError>;
32 }>;
33 readonly nextCursors: IssueListCursors;
34 /** Why the last "Load more" failed, until a retry succeeds or a new first page arrives. */
35 readonly moreFailure: string | null;
36 /** Why "Load more" last failed for each cursor it asked for, so only that tracker says so. */
37 readonly moreFailures: Readonly<Record<string, string>>;
38 /** The last "Load more" failed, whole or for a scope that keeps its cursor: only a retry asks again. */
39 readonly moreFailed: boolean;
40 /** How many pages "Load more" laid over the first page, per cursor. */
41 readonly depth: Readonly<Record<string, number>>;
42 /** A newer first page these rows are being read again under. */
43 readonly rereading: IssueListResult | null;
45​
46export function issueTrackerKey(tracker: Pick<IssueTrackerSummary, "tracker" | "host">): string {
47 return `${tracker.tracker} ${tracker.host.toLowerCase()}`;
49​
50function freshIssuePage(answer: IssueListResult, list: string): HeldIssuePage {
51 return {
52 list,
53 answer,
54 entries: answer.entries,
55 errors: answer.errors,
56 moreErrors: [],
57 nextCursors: answer.nextCursors,
58 moreFailure: null,
59 moreFailures: {},
60 moreFailed: false,
61 depth: {},
62 rereading: null,
63 };
65​
66/**
67 * Continuations are laid over the first page they continue. A new first page of the same list
68 * (`list` names its filters) keeps showing the pages held, marked `rereading`, until
69 * `rereadIssuePage` has read as deep again under it; another list starts over.
70 */
71export function holdIssuePages(
72 answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
73 pages: ReadonlyMap<EnvironmentId, HeldIssuePage>,
74 list = "",
75): ReadonlyMap<EnvironmentId, HeldIssuePage> {
76 const next = new Map<EnvironmentId, HeldIssuePage>();
77 for (const [environmentId, answer] of answers) {
78 const previous = pages.get(environmentId);
79 next.set(
80 environmentId,
81 previous?.list !== list
82 ? freshIssuePage(answer, list)
83 : previous.answer === answer
84 ? previous
85 : Object.keys(previous.depth).length > 0
86 ? { ...previous, rereading: answer }
87 : freshIssuePage(answer, list),
88 );
89 }
90 return next;
92​
93/** Applies settled continuations against the first pages available at the time of the write. */
94export function applyIssueContinuations(
95 pages: ReadonlyMap<EnvironmentId, HeldIssuePage>,
96 answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
97 list: string,
98 continuations: ReadonlyArray<{
99 readonly environmentId: EnvironmentId;
100 readonly page: HeldIssuePage;
101 readonly result: IssueListResult | { readonly failure: string };
102 readonly cursors?: IssueListCursors;
103 }>,
104): ReadonlyMap<EnvironmentId, HeldIssuePage> {
105 const held = holdIssuePages(answers, pages, list);
106 let updated: Map<EnvironmentId, HeldIssuePage> | undefined;
107 for (const { environmentId, page, result, cursors } of continuations) {
108 const current = held.get(environmentId);
109 if (
110 current?.list === page.list &&
111 current.answer === page.answer &&
112 current.rereading === null &&
113 current.nextCursors === page.nextCursors
114 ) {
115 updated ??= new Map(pages);
116 updated.set(environmentId, continueIssuePage(current, result, cursors));
117 }
118 }
119 return updated ?? pages;
121​
122/** Reads the pages "Load more" had reached again under the newer first page, so they show what changed. */
123export async function rereadIssuePage(
124 page: HeldIssuePage & { readonly rereading: IssueListResult },
125 load: (cursors: IssueListCursors) => Promise<IssueListResult | { readonly failure: string }>,
126): Promise<HeldIssuePage> {
127 let next = freshIssuePage(page.rereading, page.list);
128 for (;;) {
129 const asked = Object.fromEntries(
130 Object.entries(next.nextCursors).filter(
131 ([key]) => (next.depth[key] ?? 0) < (page.depth[key] ?? 0),
132 ),
133 );
134 if (Object.keys(asked).length === 0) return next;
135 next = continueIssuePage(next, await load(asked), asked);
136 if (next.moreFailure !== null) return next;
137 }
139​
140/**
141 * Starts one reread per newer first page an environment shows. Only the reread of the first page
142 * it shows last is committed, so an older one that answers later cannot overwrite it.
143 */
144export function createIssuePageRereader() {
145 const latest = new Map<EnvironmentId, IssueListResult>();
146 return (
147 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
148 load: (
149 environmentId: EnvironmentId,
150 cursors: IssueListCursors,
151 ) => Promise<IssueListResult | { readonly failure: string }>,
152 commit: (environmentId: EnvironmentId, page: HeldIssuePage) => void,
153 ) => {
154 for (const [environmentId, page] of held) {
155 const rereading = page.rereading;
156 if (rereading === null) latest.delete(environmentId);
157 if (rereading === null || latest.get(environmentId) === rereading) continue;
158 latest.set(environmentId, rereading);
159 void rereadIssuePage({ ...page, rereading }, (cursors) => load(environmentId, cursors)).then(
160 (next) => {
161 if (latest.get(environmentId) === rereading) commit(environmentId, next);
162 },
163 );
164 }
165 };
167​
168/** The cursors of one tracker host, so its "Load more" leaves the other trackers where they are. */
169export function issueCursorsForHost(cursors: IssueListCursors, host: string): IssueListCursors {
170 return Object.fromEntries(Object.entries(cursors).filter(([key]) => key.startsWith(`${host} `)));
172​
173export function issueMoreFailureForHost(page: HeldIssuePage, host: string): string | null {
174 return Object.entries(issueCursorsForHost(page.moreFailures, host))[0]?.[1] ?? null;
176​
177/**
178 * Lays the next page over the rows held; a failure keeps them and says why. `asked` is the
179 * cursors the page was asked to carry on: only those move, and what an earlier continuation
180 * reported for any of them is replaced, so a retry that works takes its error away.
181 */
182export function continueIssuePage(
183 page: HeldIssuePage,
184 next: IssueListResult | { readonly failure: string },
185 asked: IssueListCursors = page.nextCursors,
186): HeldIssuePage {
187 if ("failure" in next) {
188 const failed = Object.fromEntries(Object.keys(asked).map((key) => [key, next.failure]));
189 const moreFailures = { ...page.moreFailures, ...failed };
190 return { ...page, moreFailure: next.failure, moreFailures, moreFailed: true };
191 }
192 const moreErrors = page.moreErrors.filter((more) => !more.asked.some((key) => key in asked));
193 if (next.errors.length > 0) moreErrors.push({ asked: Object.keys(asked), errors: next.errors });
194 return {
195 list: page.list,
196 answer: page.answer,
197 entries: mergeIssueListPage(page.entries, next.entries),
198 errors: [...page.answer.errors, ...moreErrors.flatMap((more) => more.errors)],
199 moreErrors,
200 nextCursors: {
201 ...Object.fromEntries(Object.entries(page.nextCursors).filter(([key]) => !(key in asked))),
202 ...next.nextCursors,
203 },
204 moreFailure: null,
205 moreFailures: Object.fromEntries(
206 Object.entries(page.moreFailures).filter(([key]) => !(key in asked)),
207 ),
208 // A scope that failed keeps its cursor, so the page failed even though the request answered.
209 moreFailed: next.errors.length > 0,
210 depth: {
211 ...page.depth,
212 ...Object.fromEntries(Object.keys(asked).map((key) => [key, (page.depth[key] ?? 0) + 1])),
213 },
214 rereading: page.rereading,
215 };
217​
218/** Newest first by the date the trackers were asked to sort on, so merged rows keep that order. */
219export function issueOrder(sort: IssueListSort) {
220 const date = (issue: IssueListEntry) =>
221 Date.parse(sort === "created" ? issue.createdAt : issue.updatedAt);
222 return (left: IssueListEntry, right: IssueListEntry) => date(right) - date(left);
224​
225export function groupIssues(
226 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
227 query: string,
228 projects: ReadonlyArray<EnvironmentProject>,
229 sort: IssueListSort = "updated",
230) {
231 const byTracker = new Map<
232 string,
233 {
234 tracker: IssueTrackerSummary;
235 rows: EnvironmentIssueEntry[];
236 errors: Array<{ projectTitle: string; message: string; environmentId: EnvironmentId }>;
237 more: EnvironmentId[];
238 }
239 >();
240 const listed = new Set<string>();
241 const reported = new Map<string, EnvironmentId>();
242 const needle = query.toLowerCase();
243 for (const [environmentId, page] of held) {
244 for (const tracker of page.answer.trackers) {
245 const key = issueTrackerKey(tracker);
246 if (!byTracker.has(key)) byTracker.set(key, { tracker, rows: [], errors: [], more: [] });
247 const group = byTracker.get(key)!;
248 if (!group.tracker.configured && tracker.configured) group.tracker = tracker;
249 if (Object.keys(page.nextCursors).some((c) => c.startsWith(`${tracker.host} `)))
250 group.more.push(environmentId);
251 }
252 for (const entry of page.entries) {
253 const key = issueTrackerKey(entry);
254 const group = byTracker.get(key);
255 if (!group) continue;
256 // A tracker that cannot search is narrowed here instead.
257 if (
258 needle.length > 0 &&
259 group.tracker.capabilities?.search !== true &&
260 !entry.title.toLowerCase().includes(needle) &&
261 !entry.displayKey.toLowerCase().includes(needle)
262 )
263 continue;
264 // Environments holding the same repository answer the same issue; the first one keeps it.
265 if (listed.has(entry.url)) continue;
266 listed.add(entry.url);
267 group.rows.push({ ...entry, environmentId });
268 }
269 for (const error of page.errors) {
270 const project = projects.find(
271 (p) => p.environmentId === environmentId && p.id === error.projectId,
272 );
273 const kind = project?.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
274 const host = kind
275 ? sourceControlClients.changeRequestHost(project?.repositoryIdentity, kind)
276 : null;
277 const group =
278 (host ? byTracker.get(`${kind} ${host.toLowerCase()}`) : undefined) ??
279 [...byTracker.values()][0];
280 const repository = project?.repositoryIdentity?.canonicalKey ?? error.projectTitle;
281 const reportedKey = `${repository}\n${error.message}`;
282 const reportedBy = reported.get(reportedKey) ?? environmentId;
283 // One environment can fail a repository's scopes separately (a fork and its upstream).
284 if (!group || reportedBy !== environmentId) continue;
285 reported.set(reportedKey, environmentId);
286 group.errors.push({ ...error, environmentId });
287 }
288 }
289 for (const group of byTracker.values()) group.rows.sort(issueOrder(sort));
290 return [...byTracker.values()].sort((a, b) =>
291 issueTrackerKey(a.tracker).localeCompare(issueTrackerKey(b.tracker)),
292 );
294​
295/** The scopes whose labels and people a list filter offers, each reached through one project. */
296export function issueFilterScopes(
297 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
298 projects: ReadonlyArray<EnvironmentProject>,
299) {
300 const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> =
301 [];
302 // A repository's scope is the same scope on every server. A bound tracker's scope is not: two
303 // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only.
304 const fromRepository = new Set<IssueScopeRef>();
305 for (const [environmentId, page] of held) {
306 for (const project of projects) {
307 if (project.environmentId !== environmentId) continue;
308 for (const { tracker: kind, host, scope } of sourceControlClients.issueBindings(
309 project.repositoryIdentity,
310 )) {
311 const tracker = page.answer.trackers.find(
312 (t) => String(t.tracker) === kind && t.host.toLowerCase() === host.toLowerCase(),
313 );
314 if (!tracker?.configured || tracker.capabilities === null) continue;
315 if (
316 scopes.some(
317 (s) => s.input.scope.toLowerCase() === scope.toLowerCase() && s.input.host === host,
318 )
319 )
320 continue;
321 const input = { projectId: project.id, tracker: tracker.tracker, host, scope };
322 fromRepository.add(input);
323 scopes.push({ environmentId, input });
324 }
325 }
326 // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope,
327 // matched or not. Older servers do not, so their rows stand in.
328 const covered: ReadonlyArray<IssueScopeRef> =
329 page.answer.scopes ??
330 page.entries.map(({ projectId, tracker, host, scope }) => ({
331 projectId,
332 tracker,
333 host,
334 scope,
335 }));
336 for (const input of covered) {
337 const host = input.host?.toLowerCase();
338 const tracker = page.answer.trackers.find(
339 (t) => t.tracker === input.tracker && t.host.toLowerCase() === host,
340 );
341 if (!tracker?.configured) continue;
342 if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue;
343 // An answer names each scope once per account; rows standing in for one repeat.
344 if (
345 scopes.some(
346 (s) =>
347 (fromRepository.has(s.input) ||
348 (page.answer.scopes === undefined && s.environmentId === environmentId)) &&
349 s.input.scope.toLowerCase() === input.scope.toLowerCase() &&
350 s.input.host?.toLowerCase() === host,
351 )
352 )
353 continue;
354 scopes.push({ environmentId, input });
355 }
356 }
357 return scopes;