Open History to see the last commit
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;
19}
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 /** How many pages "Load more" laid over the first page, per cursor. */
37 readonly depth: Readonly<Record<string, number>>;
38 /** A newer first page these rows are being read again under. */
39 readonly rereading: IssueListResult | null;
40}
41
42export function issueTrackerKey(tracker: Pick<IssueTrackerSummary, "tracker" | "host">): string {
43 return `${tracker.tracker} ${tracker.host.toLowerCase()}`;
44}
45
46function freshIssuePage(answer: IssueListResult, list: string): HeldIssuePage {
47 return {
48 list,
49 answer,
50 entries: answer.entries,
51 errors: answer.errors,
52 moreErrors: [],
53 nextCursors: answer.nextCursors,
54 moreFailure: null,
55 depth: {},
56 rereading: null,
57 };
58}
59
60/**
61 * Continuations are laid over the first page they continue. A new first page of the same list
62 * (`list` names its filters) keeps showing the pages held, marked `rereading`, until
63 * `rereadIssuePage` has read as deep again under it; another list starts over.
64 */
65export function holdIssuePages(
66 answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
67 pages: ReadonlyMap<EnvironmentId, HeldIssuePage>,
68 list = "",
69): ReadonlyMap<EnvironmentId, HeldIssuePage> {
70 const next = new Map<EnvironmentId, HeldIssuePage>();
71 for (const [environmentId, answer] of answers) {
72 const previous = pages.get(environmentId);
73 next.set(
74 environmentId,
75 previous?.list !== list
76 ? freshIssuePage(answer, list)
77 : previous.answer === answer
78 ? previous
79 : Object.keys(previous.depth).length > 0
80 ? { ...previous, rereading: answer }
81 : freshIssuePage(answer, list),
82 );
83 }
84 return next;
85}
86
87/** Reads the pages "Load more" had reached again under the newer first page, so they show what changed. */
88export async function rereadIssuePage(
89 page: HeldIssuePage & { readonly rereading: IssueListResult },
90 load: (cursors: IssueListCursors) => Promise<IssueListResult | { readonly failure: string }>,
91): Promise<HeldIssuePage> {
92 let next = freshIssuePage(page.rereading, page.list);
93 for (;;) {
94 const asked = Object.fromEntries(
95 Object.entries(next.nextCursors).filter(
96 ([key]) => (next.depth[key] ?? 0) < (page.depth[key] ?? 0),
97 ),
98 );
99 if (Object.keys(asked).length === 0) return next;
100 next = continueIssuePage(next, await load(asked), asked);
101 if (next.moreFailure !== null) return next;
102 }
103}
104
105/**
106 * Starts one reread per newer first page an environment shows. Only the reread of the first page
107 * it shows last is committed, so an older one that answers later cannot overwrite it.
108 */
109export function createIssuePageRereader() {
110 const latest = new Map<EnvironmentId, IssueListResult>();
111 return (
112 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
113 load: (
114 environmentId: EnvironmentId,
115 cursors: IssueListCursors,
116 ) => Promise<IssueListResult | { readonly failure: string }>,
117 commit: (environmentId: EnvironmentId, page: HeldIssuePage) => void,
118 ) => {
119 for (const [environmentId, page] of held) {
120 const rereading = page.rereading;
121 if (rereading === null) latest.delete(environmentId);
122 if (rereading === null || latest.get(environmentId) === rereading) continue;
123 latest.set(environmentId, rereading);
124 void rereadIssuePage({ ...page, rereading }, (cursors) => load(environmentId, cursors)).then(
125 (next) => {
126 if (latest.get(environmentId) === rereading) commit(environmentId, next);
127 },
128 );
129 }
130 };
131}
132
133/** The cursors of one tracker host, so its "Load more" leaves the other trackers where they are. */
134export function issueCursorsForHost(cursors: IssueListCursors, host: string): IssueListCursors {
135 return Object.fromEntries(Object.entries(cursors).filter(([key]) => key.startsWith(`${host} `)));
136}
137
138/**
139 * Lays the next page over the rows held; a failure keeps them and says why. `asked` is the
140 * cursors the page was asked to carry on: only those move, and what an earlier continuation
141 * reported for any of them is replaced, so a retry that works takes its error away.
142 */
143export function continueIssuePage(
144 page: HeldIssuePage,
145 next: IssueListResult | { readonly failure: string },
146 asked: IssueListCursors = page.nextCursors,
147): HeldIssuePage {
148 if ("failure" in next) return { ...page, moreFailure: next.failure };
149 const moreErrors = page.moreErrors.filter((more) => !more.asked.some((key) => key in asked));
150 if (next.errors.length > 0) moreErrors.push({ asked: Object.keys(asked), errors: next.errors });
151 return {
152 list: page.list,
153 answer: page.answer,
154 entries: mergeIssueListPage(page.entries, next.entries),
155 errors: [...page.answer.errors, ...moreErrors.flatMap((more) => more.errors)],
156 moreErrors,
157 nextCursors: {
158 ...Object.fromEntries(Object.entries(page.nextCursors).filter(([key]) => !(key in asked))),
159 ...next.nextCursors,
160 },
161 moreFailure: null,
162 depth: {
163 ...page.depth,
164 ...Object.fromEntries(Object.keys(asked).map((key) => [key, (page.depth[key] ?? 0) + 1])),
165 },
166 rereading: page.rereading,
167 };
168}
169
170/** Newest first by the date the trackers were asked to sort on, so merged rows keep that order. */
171export function issueOrder(sort: IssueListSort) {
172 const date = (issue: IssueListEntry) =>
173 Date.parse(sort === "created" ? issue.createdAt : issue.updatedAt);
174 return (left: IssueListEntry, right: IssueListEntry) => date(right) - date(left);
175}
176
177export function groupIssues(
178 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
179 query: string,
180 projects: ReadonlyArray<EnvironmentProject>,
181 sort: IssueListSort = "updated",
182) {
183 const byTracker = new Map<
184 string,
185 {
186 tracker: IssueTrackerSummary;
187 rows: EnvironmentIssueEntry[];
188 errors: Array<{ projectTitle: string; message: string; environmentId: EnvironmentId }>;
189 more: EnvironmentId[];
190 }
191 >();
192 const listed = new Set<string>();
193 const needle = query.toLowerCase();
194 for (const [environmentId, page] of held) {
195 for (const tracker of page.answer.trackers) {
196 const key = issueTrackerKey(tracker);
197 if (!byTracker.has(key)) byTracker.set(key, { tracker, rows: [], errors: [], more: [] });
198 const group = byTracker.get(key)!;
199 if (!group.tracker.configured && tracker.configured) group.tracker = tracker;
200 if (Object.keys(page.nextCursors).some((c) => c.startsWith(`${tracker.host} `)))
201 group.more.push(environmentId);
202 }
203 for (const entry of page.entries) {
204 const key = issueTrackerKey(entry);
205 const group = byTracker.get(key);
206 if (!group) continue;
207 // A tracker that cannot search is narrowed here instead.
208 if (
209 needle.length > 0 &&
210 group.tracker.capabilities?.search !== true &&
211 !entry.title.toLowerCase().includes(needle) &&
212 !entry.displayKey.toLowerCase().includes(needle)
213 )
214 continue;
215 // Environments holding the same repository answer the same issue; the first one keeps it.
216 if (listed.has(entry.url)) continue;
217 listed.add(entry.url);
218 group.rows.push({ ...entry, environmentId });
219 }
220 for (const error of page.errors) {
221 const project = projects.find(
222 (p) => p.environmentId === environmentId && p.id === error.projectId,
223 );
224 const kind = project?.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
225 const host = kind
226 ? sourceControlClients.changeRequestHost(project?.repositoryIdentity, kind)
227 : null;
228 const group =
229 (host ? byTracker.get(`${kind} ${host.toLowerCase()}`) : undefined) ??
230 [...byTracker.values()][0];
231 group?.errors.push({ ...error, environmentId });
232 }
233 }
234 for (const group of byTracker.values()) group.rows.sort(issueOrder(sort));
235 return [...byTracker.values()].sort((a, b) =>
236 issueTrackerKey(a.tracker).localeCompare(issueTrackerKey(b.tracker)),
237 );
238}
239
240/** The scopes whose labels and people a list filter offers, each reached through one project. */
241export function issueFilterScopes(
242 held: ReadonlyMap<EnvironmentId, HeldIssuePage>,
243 projects: ReadonlyArray<EnvironmentProject>,
244) {
245 const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> =
246 [];
247 // A repository's scope is the same scope on every server. A bound tracker's scope is not: two
248 // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only.
249 const fromRepository = new Set<IssueScopeRef>();
250 for (const [environmentId, page] of held) {
251 for (const project of projects) {
252 if (project.environmentId !== environmentId) continue;
253 for (const { tracker: kind, host, scope } of sourceControlClients.issueBindings(
254 project.repositoryIdentity,
255 )) {
256 const tracker = page.answer.trackers.find(
257 (t) => String(t.tracker) === kind && t.host.toLowerCase() === host.toLowerCase(),
258 );
259 if (!tracker?.configured || tracker.capabilities === null) continue;
260 if (
261 scopes.some(
262 (s) => s.input.scope.toLowerCase() === scope.toLowerCase() && s.input.host === host,
263 )
264 )
265 continue;
266 const input = { projectId: project.id, tracker: tracker.tracker, host, scope };
267 fromRepository.add(input);
268 scopes.push({ environmentId, input });
269 }
270 }
271 // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope,
272 // matched or not. Older servers do not, so their rows stand in.
273 const covered: ReadonlyArray<IssueScopeRef> =
274 page.answer.scopes ??
275 page.entries.map(({ projectId, tracker, host, scope }) => ({
276 projectId,
277 tracker,
278 host,
279 scope,
280 }));
281 for (const input of covered) {
282 const host = input.host?.toLowerCase();
283 const tracker = page.answer.trackers.find(
284 (t) => t.tracker === input.tracker && t.host.toLowerCase() === host,
285 );
286 if (!tracker?.configured) continue;
287 if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue;
288 // An answer names each scope once per account; rows standing in for one repeat.
289 if (
290 scopes.some(
291 (s) =>
292 (fromRepository.has(s.input) ||
293 (page.answer.scopes === undefined && s.environmentId === environmentId)) &&
294 s.input.scope.toLowerCase() === input.scope.toLowerCase() &&
295 s.input.host?.toLowerCase() === host,
296 )
297 )
298 continue;
299 scopes.push({ environmentId, input });
300 }
301 }
302 return scopes;
303}