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

GitHubIssueTracker.ts

467 lines16.8 KB

1import * as Effect from "effect/Effect";
2import * as Result from "effect/Result";
3import { GraphQLClient, GraphQLClientError, GraphQLGroup } from "effect/graphql";
4import {
5 IssueTrackerKind,
6 type IssueCapabilities,
7 type IssueInvolvement,
8 type IssueListSort,
9} from "@t3tools/contracts";
10import {
11 IssueTrackerError,
12 type IssueInvolvementFilter,
13 type IssueTrackerApi,
14} from "@t3tools/source-control-core/server/IssueTracker";
15​
16import * as GitHubRest from "./GitHubRest.ts";
17import { readIssueTemplates } from "./gitHubIssueTemplates.ts";
18import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
19import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
20import { IssuesGraphQLGroup } from "./issues.graphql.ts";
21import { AddReaction, RemoveReaction } from "./pullRequestMutations.graphql.ts";
22import { gitHubReactionContent } from "./gitHubPullRequestJson.ts";
23import {
24 ISSUE_STATES,
25 decodeCreatedIssueJson,
26 decodeIssueMetadataJson,
27 toIssueCandidates,
28 toIssueComments,
29 toIssueDetail,
30 toIssueSearch,
31} from "./gitHubIssueJson.ts";
32​
33const KIND = IssueTrackerKind.make("github");
34​
35const CAPABILITIES: IssueCapabilities = {
36 create: true,
37 edit: true,
38 comment: true,
39 labels: true,
40 assignees: true,
41 reactions: true,
42 templates: true,
43 linkedPullRequests: true,
44 events: true,
45 search: true,
46};
47​
48const REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/;
49​
50/** Quoted, so no character in it can start a qualifier of its own. */
51function quotedTerm(value: string): string {
52 return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
54​
55function searchTerms(query: string): ReadonlyArray<string> {
56 return query
57 .split(/\s+/)
58 .filter((word) => word.length > 0)
59 .map(quotedTerm);
61​
62const INVOLVEMENT_QUALIFIER: Record<Exclude<IssueInvolvement, "all">, string> = {
63 assigned: "assignee",
64 authored: "author",
65 mentioned: "mentions",
66};
67​
68function searchQuery(
69 input: IssueInvolvementFilter & {
70 readonly scope: string;
71 readonly state: "all" | "open" | "closed";
72 readonly query?: string | undefined;
73 readonly labels?: ReadonlyArray<string> | undefined;
74 readonly assignee?: string | undefined;
75 readonly sort: IssueListSort;
76 },
77): string {
78 return [
79 "is:issue",
80 `repo:${input.scope.trim()}`,
81 ...(input.state === "all" ? [] : [`is:${input.state}`]),
82 ...(input.involvement === "all"
83 ? []
84 : [`${INVOLVEMENT_QUALIFIER[input.involvement]}:${input.viewer}`]),
85 ...(input.labels ?? []).map((label) => `label:${quotedTerm(label)}`),
86 ...(input.assignee === undefined ? [] : [`assignee:${quotedTerm(input.assignee)}`]),
87 `sort:${input.sort}-desc`,
88 ...searchTerms(input.query ?? ""),
89 ].join(" ");
91​
92function reasonFor(
93 error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError,
94): IssueTrackerError["reason"] {
95 switch (error._tag) {
96 case "GitHubCliMissingError":
97 return "missing-tool";
98 case "GitHubNotSignedInError":
99 case "GitHubHostDisabledError":
100 case "GitHubApiAuthenticationError":
101 return "unauthenticated";
102 case "GitHubApiRateLimitError":
103 case "SourceControlRateLimitPausedError":
104 return "rate-limited";
105 case "GitHubApiNotFoundError":
106 return "not-found";
107 default:
108 return "failed";
109 }
111​
112const FAILURE_DETAIL: Record<IssueTrackerError["reason"], string> = {
113 "missing-tool": "GitHub CLI is not installed.",
114 unauthenticated: "GitHub authentication is unavailable. Sign in and retry.",
115 "rate-limited": "GitHub API rate limit exceeded.",
116 "not-found": "GitHub could not find the requested issue.",
117 failed: "The GitHub issue request failed.",
118};
119​
120const group = GraphQLGroup.merge(
121 IssuesGraphQLGroup,
122 GraphQLGroup.make(AddReaction, RemoveReaction),
123).middleware(GitHubGraphQlClient.GitHubGraphQlAuth);
124​
125export const make = Effect.gen(function* () {
126 const api = yield* GitHubRest.GitHubRest;
127 const client = yield* GraphQLClient.make(group).pipe(Effect.provide(GitHubGraphQlClient.layer));
128​
129 const fail =
130 (operation: string) =>
131 (error: GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError) =>
132 new IssueTrackerError({
133 tracker: KIND,
134 operation,
135 reason: reasonFor(error),
136 detail: GraphQLClientError.isGraphQLClientError(error)
137 ? `GitHub returned an unreadable ${operation} response.`
138 : FAILURE_DETAIL[reasonFor(error)],
139 ...("retryAt" in error && error.retryAt !== undefined ? { retryAt: error.retryAt } : {}),
140 cause: error,
141 });
142​
143 const invalid = (operation: string, detail: string, reason: "failed" | "not-found" = "failed") =>
144 new IssueTrackerError({ tracker: KIND, operation, reason, detail });
145​
146 const notFound = (operation: string) =>
147 invalid(operation, "GitHub could not find the requested issue.", "not-found");
148​
149 const repository = Effect.fn("GitHubIssueTracker.repository")(function* (
150 scope: string,
151 operation: string,
152 ) {
153 if (!REPOSITORY.test(scope) || scope.endsWith("/.") || scope.endsWith("/..")) {
154 return yield* invalid(operation, "A repository was named that GitHub cannot address.");
155 }
156 const [owner = "", name = ""] = scope.split("/");
157 return { owner, name };
158 });
159​
160 const issue = Effect.fn("GitHubIssueTracker.issue")(function* (
161 input: { readonly scope: string; readonly key: string },
162 operation: string,
163 ) {
164 const repo = yield* repository(input.scope, operation);
165 const number = Number(input.key);
166 if (!/^[1-9]\d*$/.test(input.key) || !Number.isSafeInteger(number) || number > 2_147_483_647) {
167 return yield* notFound(operation);
168 }
169 return { ...repo, number, path: `repos/${repo.owner}/${repo.name}/issues/${number}` };
170 });
171​
172 const graphql =
173 (host: string, operation: string) =>
174 <A, E extends GitHubRequestPolicy.GitHubApiError | GraphQLClientError.GraphQLClientError, R>(
175 effect: Effect.Effect<A, E, R>,
176 ) =>
177 effect.pipe(GitHubGraphQlClient.call({ host, operation }), Effect.mapError(fail(operation)));
178​
179 const verifiedIssue = Effect.fn("GitHubIssueTracker.verifiedIssue")(function* (
180 input: { readonly host: string; readonly scope: string; readonly key: string },
181 operation: string,
182 ) {
183 const target = yield* issue(input, operation);
184 const { owner, name, number } = target;
185 // REST issue endpoints also accept pull requests; resolve an Issue before writing.
186 const result = yield* client
187 .IssueNodeId({ owner, name, number })
188 .pipe(graphql(input.host, operation));
189 const found = result.repository?.issue;
190 if (found == null) return yield* notFound(operation);
191 return { ...target, id: found.id, state: found.state, stateReason: found.stateReason };
192 });
193​
194 // As sets: GitHub applies a name asked for twice once.
195 const sameNames = (wanted: ReadonlyArray<string>, applied: ReadonlyArray<string>) => {
196 const names = new Set(wanted.map((name) => name.trim().toLowerCase()));
197 return (
198 names.size === new Set(applied).size && [...names].every((name) => applied.includes(name))
199 );
200 };
201​
202 return {
203 kind: KIND,
204 capabilities: CAPABILITIES,
205​
206 getViewer: (input) =>
207 client.IssueViewer({}).pipe(
208 graphql(input.host, "getViewer"),
209 Effect.map(({ viewer }) => viewer.login),
210 ),
211​
212 listIssues: (input) =>
213 repository(input.scope, "listIssues").pipe(
214 Effect.flatMap(() =>
215 client
216 .IssueSearch({
217 q: searchQuery(input),
218 cursor: input.cursor,
219 rows: Math.min(Math.max(Math.trunc(input.limit), 1), 100),
220 })
221 .pipe(graphql(input.host, "listIssues"), Effect.map(toIssueSearch)),
222 ),
223 ),
224​
225 getIssue: Effect.fn("GitHubIssueTracker.getIssue")(function* (input) {
226 const { owner, name, number } = yield* issue(input, "getIssue");
227 const result = yield* client
228 .IssueDetail({ owner, name, number })
229 .pipe(graphql(input.host, "getIssue"));
230 const detail = toIssueDetail(result);
231 const raw = result.repository?.issue;
232 if (detail === null || raw == null) return yield* notFound("getIssue");
233 // Editing replaces these sets. Finish their pages before handing them to a client.
234 let labels = raw.labels;
235 let assignees = raw.assignees;
236 const seen = new Set<string>();
237 const allLabels = [...detail.labels];
238 const allAssignees = [...detail.assignees];
239 while (labels?.pageInfo.hasNextPage === true || assignees.pageInfo.hasNextPage) {
240 const labelsCursor = labels?.pageInfo.hasNextPage ? labels.pageInfo.endCursor : null;
241 const assigneesCursor = assignees.pageInfo.hasNextPage
242 ? assignees.pageInfo.endCursor
243 : null;
244 const key = `${labelsCursor ?? ""} ${assigneesCursor ?? ""}`;
245 if (
246 (labels?.pageInfo.hasNextPage && labelsCursor === null) ||
247 (assignees.pageInfo.hasNextPage && assigneesCursor === null) ||
248 seen.has(key)
249 ) {
250 return yield* invalid(
251 "getIssue",
252 "GitHub did not return complete issue labels or assignees.",
253 );
254 }
255 seen.add(key);
256 const page = yield* client
257 .IssueCollections({ owner, name, number, labelsCursor, assigneesCursor })
258 .pipe(graphql(input.host, "getIssue"));
259 const next = page.repository?.issue;
260 if (next == null) return yield* notFound("getIssue");
261 if (labels?.pageInfo.hasNextPage) {
262 labels = next.labels;
263 if (next.labels === null) {
264 return yield* invalid("getIssue", "GitHub did not return complete issue labels.");
265 }
266 allLabels.push(
267 ...(next.labels.nodes ?? []).flatMap((node) =>
268 node === null ? [] : [{ name: node.name, color: node.color }],
269 ),
270 );
271 }
272 if (assignees.pageInfo.hasNextPage) {
273 assignees = next.assignees;
274 allAssignees.push(
275 ...(next.assignees.nodes ?? []).flatMap((node) =>
276 node === null
277 ? []
278 : [{ login: node.login, name: node.name, avatarUrl: node.avatarUrl }],
279 ),
280 );
281 }
282 }
283 return { ...detail, labels: allLabels, assignees: allAssignees };
284 }),
285​
286 getComments: (input) =>
287 issue(input, "getComments").pipe(
288 Effect.flatMap(({ owner, name, number }) =>
289 client
290 .IssueComments({ owner, name, number, cursor: input.cursor })
291 .pipe(graphql(input.host, "getComments")),
292 ),
293 Effect.flatMap((result) =>
294 result.repository?.issue == null
295 ? Effect.fail(notFound("getComments"))
296 : Effect.succeed(toIssueComments(result)),
297 ),
298 ),
299​
300 create: (input) =>
301 repository(input.scope, "create").pipe(
302 Effect.flatMap(({ owner, name }) =>
303 api
304 .rest({
305 host: input.host,
306 operation: "create",
307 method: "POST",
308 path: `repos/${owner}/${name}/issues`,
309 body: {
310 title: input.title,
311 body: input.body,
312 labels: input.labels,
313 assignees: input.assignees,
314 },
315 })
316 .pipe(Effect.mapError(fail("create"))),
317 ),
318 Effect.flatMap((response) => {
319 const decoded = decodeCreatedIssueJson(response.body);
320 return Result.isSuccess(decoded)
321 ? Effect.succeed({
322 key: String(decoded.success.number),
323 displayKey: `#${decoded.success.number}`,
324 url: decoded.success.url,
325 })
326 : Effect.fail(
327 new IssueTrackerError({
328 tracker: KIND,
329 operation: "create",
330 reason: "failed",
331 detail: "GitHub returned an unreadable create response.",
332 cause: decoded.failure,
333 }),
334 );
335 }),
336 ),
337​
338 comment: (input) =>
339 verifiedIssue(input, "comment").pipe(
340 Effect.flatMap(({ path }) =>
341 api
342 .rest({
343 host: input.host,
344 operation: "comment",
345 method: "POST",
346 path: `${path}/comments`,
347 body: { body: input.body },
348 })
349 .pipe(Effect.asVoid, Effect.mapError(fail("comment"))),
350 ),
351 ),
352​
353 update: Effect.fn("GitHubIssueTracker.update")(function* (input) {
354 const { path } = yield* verifiedIssue(input, "update");
355 const response = yield* api
356 .rest({
357 host: input.host,
358 operation: "update",
359 method: "PATCH",
360 path,
361 body: {
362 ...(input.title === undefined ? {} : { title: input.title }),
363 ...(input.body === undefined ? {} : { body: input.body }),
364 ...(input.labels === undefined ? {} : { labels: input.labels }),
365 ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
366 },
367 })
368 .pipe(Effect.mapError(fail("update")));
369 // Without triage access GitHub drops labels and assignees and still answers with success.
370 const applied = decodeIssueMetadataJson(response.body);
371 if (
372 Result.isSuccess(applied) &&
373 ((input.labels !== undefined && !sameNames(input.labels, applied.success.labels)) ||
374 (input.assignees !== undefined && !sameNames(input.assignees, applied.success.assignees)))
375 ) {
376 return yield* invalid(
377 "update",
378 "GitHub did not apply the labels or assignees. Changing them needs triage access to the repository.",
379 );
380 }
381 }),
382​
383 setState: Effect.fn("GitHubIssueTracker.setState")(function* (input) {
384 const { path, state, stateReason } = yield* verifiedIssue(input, "setState");
385 const wanted = ISSUE_STATES.find((candidate) => candidate.name === input.state);
386 if (wanted === undefined) {
387 return yield* invalid("setState", `A GitHub issue has no "${input.state}" state.`);
388 }
389 const reason = wanted.closeReason?.replace("-", "_");
390 // GitHub ignores `state_reason` unless the state changes, and would answer with success.
391 if (reason !== undefined && state === "CLOSED" && stateReason?.toLowerCase() !== reason) {
392 return yield* invalid(
393 "setState",
394 "GitHub cannot change why a closed issue was closed. Reopen it, then close it again.",
395 );
396 }
397 yield* api
398 .rest({
399 host: input.host,
400 operation: "setState",
401 method: "PATCH",
402 path,
403 body: {
404 state: wanted.category,
405 ...(reason === undefined ? {} : { state_reason: reason }),
406 },
407 })
408 .pipe(Effect.mapError(fail("setState")));
409 }),
410​
411 setReaction: Effect.fn("GitHubIssueTracker.setReaction")(function* (input) {
412 let subjectId: string;
413 if (input.subjectId === undefined) {
414 const target = yield* verifiedIssue(input, "setReaction");
415 subjectId = target.id;
416 } else {
417 const { owner, name, number } = yield* issue(input, "setReaction");
418 // Node ids are global: prove the comment belongs to this issue before writing.
419 const result = yield* client
420 .IssueCommentScope({ owner, name, number, commentId: input.subjectId })
421 .pipe(graphql(input.host, "setReaction"));
422 const expected = result.repository?.issue?.id;
423 if (
424 expected === undefined ||
425 result.node?.__typename !== "IssueComment" ||
426 result.node.issue.id !== expected
427 ) {
428 return yield* invalid(
429 "setReaction",
430 "The comment does not belong to the selected issue.",
431 );
432 }
433 subjectId = input.subjectId;
434 }
435 const variables = { subjectId, content: gitHubReactionContent(input.content) };
436 yield* (
437 input.reacted
438 ? client.AddReaction(variables).pipe(Effect.asVoid)
439 : client.RemoveReaction(variables).pipe(Effect.asVoid)
440 ).pipe(graphql(input.host, "setReaction"));
441 }),
442​
443 listTemplates: (input) =>
444 repository(input.scope, "listTemplates").pipe(
445 Effect.flatMap(({ owner, name }) =>
446 client.IssueTemplates({ owner, name }).pipe(graphql(input.host, "listTemplates")),
447 ),
448 Effect.flatMap(({ repository }) =>
449 repository === null
450 ? Effect.fail(notFound("listTemplates"))
451 : readIssueTemplates(repository),
452 ),
453 ),
454​
455 listCandidates: (input) =>
456 repository(input.scope, "listCandidates").pipe(
457 Effect.flatMap(({ owner, name }) =>
458 client.IssueCandidates({ owner, name }).pipe(graphql(input.host, "listCandidates")),
459 ),
460 Effect.flatMap(({ repository }) =>
461 repository === null
462 ? Effect.fail(notFound("listCandidates"))
463 : Effect.succeed(toIssueCandidates(repository)),
464 ),
465 ),
466 } satisfies IssueTrackerApi;
467});