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

GitCafeIssueTracker.ts

301 lines10.7 KB

1/** GitCafe's issues over its REST API, read-only. */
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import {
6 IsoDateTime,
7 IssueTrackerKind,
8 PositiveInt,
9 TrimmedNonEmptyString,
10 type IssueComment,
11 type IssueState,
12} from "@t3tools/contracts";
13import {
14 IssueTrackerError,
15 type IssueScopeTarget,
16 type IssueTrackerApi,
17 type TrackerIssueSummary,
18} from "@t3tools/source-control-core/server/IssueTracker";
19​
20import * as GitCafeApi from "./GitCafeApi.ts";
21import * as GitCafeHosts from "./gitCafeHosts.ts";
22import * as Json from "./gitCafePullRequestJson.ts";
23​
24const KIND = IssueTrackerKind.make("gitcafe");
25const PAGE_SIZE = 100;
26const MAX_COMMENT_PAGES = 30;
27const MAX_LABEL_PAGES = 10;
28​
29const Issue = Schema.Struct({
30 number: PositiveInt,
31 title: TrimmedNonEmptyString,
32 description: Schema.NullOr(Schema.String),
33 stateType: TrimmedNonEmptyString,
34 author: Json.Actor,
35 createdAt: IsoDateTime,
36 updatedAt: IsoDateTime,
37 closedAt: Schema.NullOr(IsoDateTime),
38 labels: Schema.Array(
39 Schema.Struct({ name: TrimmedNonEmptyString, color: Schema.NullOr(Schema.String) }),
40 ),
41 assignees: Schema.Array(Schema.Struct({ actor: Json.Actor })),
42});
43type Issue = typeof Issue.Type;
44​
45const IssuePage = Schema.Struct({ items: Schema.Array(Issue), next: Schema.NullOr(Schema.String) });
46​
47const CommentPage = Schema.Struct({
48 items: Schema.Array(
49 Schema.Struct({
50 id: TrimmedNonEmptyString,
51 author: Json.Actor,
52 body: Schema.String,
53 createdAt: IsoDateTime,
54 }),
55 ),
56 next: Schema.NullOr(Schema.String),
57});
58​
59const Principal = Schema.Struct({ actorId: TrimmedNonEmptyString, handle: TrimmedNonEmptyString });
60​
61const sameName = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
62​
63function issueState(issue: Issue): IssueState {
64 const name = issue.stateType.charAt(0).toUpperCase() + issue.stateType.slice(1);
65 if (issue.closedAt === null) return { category: "open", name };
66 return {
67 category: "closed",
68 name,
69 closeReason: issue.stateType === "canceled" ? "canceled" : "completed",
70 };
72​
73function toSummary(issue: Issue, target: IssueScopeTarget): TrackerIssueSummary {
74 return {
75 key: String(issue.number),
76 displayKey: `#${issue.number}`,
77 title: issue.title,
78 url: `https://${target.host}/${target.scope}/issues/${issue.number}`,
79 author: Json.toActor(issue.author, target.host),
80 state: issueState(issue),
81 createdAt: issue.createdAt,
82 updatedAt: issue.updatedAt,
83 closedAt: issue.closedAt,
84 assignees: issue.assignees.flatMap(({ actor }) => Json.toActor(actor, target.host) ?? []),
85 labels: issue.labels.map(({ name, color }) => ({ name, color })),
86 // Listings carry no comment count.
87 commentCount: 0,
88 };
90​
91export const make: Effect.Effect<IssueTrackerApi, never, GitCafeApi.GitCafeApi> = Effect.gen(
92 function* () {
93 const api = yield* GitCafeApi.GitCafeApi;
94​
95 const failure = (
96 operation: string,
97 reason: IssueTrackerError["reason"],
98 detail: string,
99 cause?: unknown,
100 ) =>
101 new IssueTrackerError({
102 tracker: KIND,
103 operation,
104 reason,
105 detail,
106 ...(cause === undefined ? {} : { cause }),
107 });
108​
109 const read = Effect.fn("GitCafeIssueTracker.read")(function* <
110 S extends Schema.Codec<unknown, unknown, never, never>,
111 >(
112 operation: string,
113 target: { readonly host: string; readonly scope?: string },
114 path: string,
115 schema: S,
116 ): Effect.fn.Return<S["Type"], IssueTrackerError> {
117 // The token goes to this host, so only GitCafe's own hosts and repository paths are read.
118 if (
119 !GitCafeHosts.isGitCafeHost(target.host) ||
120 (target.scope !== undefined &&
121 GitCafeHosts.gitCafeRepositoryPath(target.scope) !== target.scope)
122 ) {
123 return yield* failure(operation, "failed", "This is not a GitCafe repository.");
124 }
125 const raw = yield* api
126 .request({ host: target.host, operation, path })
127 .pipe(Effect.mapError((error) => failure(operation, error.reason, error.detail, error)));
128 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
129 Effect.mapError((cause) =>
130 failure(operation, "failed", "GitCafe returned an unreadable response.", cause),
131 ),
132 );
133 });
134​
135 const issuePath = (target: IssueScopeTarget & { readonly key: string }) =>
136 `/repos/${target.scope}/issues/${target.key}`;
137​
138 const allComments = Effect.fn("GitCafeIssueTracker.allComments")(function* (
139 target: IssueScopeTarget & { readonly key: string },
140 ) {
141 const comments: Array<IssueComment> = [];
142 let after: string | null = null;
143 for (let page = 0; page < MAX_COMMENT_PAGES; page++) {
144 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
145 if (after !== null) query.set("after", after);
146 const found: typeof CommentPage.Type = yield* read(
147 "getIssue",
148 target,
149 `${issuePath(target)}/comments/?${query}`,
150 CommentPage,
151 );
152 for (const comment of found.items) {
153 comments.push({
154 id: comment.id,
155 author: Json.toActor(comment.author, target.host),
156 body: comment.body,
157 createdAt: comment.createdAt,
158 url: null,
159 });
160 }
161 if (found.next === null) return comments;
162 after = found.next;
163 }
164 return yield* failure("getIssue", "failed", "This issue has too many comments to show here.");
165 });
166​
167 /**
168 * The id of the first wanted label, to narrow GitCafe's query by, or null when the
169 * repository lacks one of them. GitCafe matches any of several ids, so one is enough.
170 */
171 const labelToNarrowBy = Effect.fn("GitCafeIssueTracker.labelToNarrowBy")(function* (
172 target: IssueScopeTarget,
173 names: ReadonlyArray<string>,
174 ) {
175 const ids = new Map<string, string>();
176 let after: string | null = null;
177 for (let page = 0; page < MAX_LABEL_PAGES; page++) {
178 const query = new URLSearchParams({ limit: String(PAGE_SIZE) });
179 if (after !== null) query.set("after", after);
180 const found: typeof Json.GitCafeLabels.Type = yield* read(
181 "listIssues",
182 target,
183 `/repos/${target.scope}/labels?${query}`,
184 Json.GitCafeLabels,
185 );
186 for (const label of found.items) {
187 const name = names.find((wanted) => sameName(wanted, label.name));
188 if (name !== undefined) ids.set(name.toLowerCase(), label.id);
189 }
190 if (names.every((name) => ids.has(name.toLowerCase()))) {
191 return ids.get(names[0]!.toLowerCase())!;
192 }
193 if (found.next === null) return null;
194 after = found.next;
195 }
196 return yield* failure("listIssues", "failed", "This repository has too many labels.");
197 });
198​
199 return {
200 kind: KIND,
201 capabilities: {
202 create: false,
203 edit: false,
204 comment: false,
205 labels: false,
206 assignees: false,
207 reactions: false,
208 templates: false,
209 linkedPullRequests: false,
210 events: false,
211 search: true,
212 },
213​
214 getViewer: (input) =>
215 read("getViewer", { host: input.host }, "/auth/principal", Principal).pipe(
216 Effect.map((viewer) => viewer.handle),
217 ),
218​
219 listIssues: Effect.fn("GitCafeIssueTracker.listIssues")(function* (input) {
220 // GitCafe cannot tell who an issue mentions.
221 if (input.involvement === "mentioned") return { items: [], nextCursor: null };
222 const query = new URLSearchParams({
223 limit: String(Math.min(PAGE_SIZE, Math.max(1, input.limit))),
224 sort: input.sort,
225 direction: "desc",
226 });
227 if (input.state !== "all") query.set("statuses", input.state);
228 const text = input.query?.trim() ?? "";
229 if (text.length > 0) query.set("q", text);
230 if (input.involvement !== "all") {
231 const viewer = yield* read("listIssues", input, "/auth/principal", Principal);
232 query.set(input.involvement === "authored" ? "author" : "assignee", viewer.actorId);
233 }
234 const labels = input.labels ?? [];
235 if (labels.length > 0) {
236 // Without the label list, the rows below still apply every label.
237 const narrow = yield* labelToNarrowBy(input, labels).pipe(
238 Effect.orElseSucceed(() => undefined),
239 );
240 if (narrow === null) return { items: [], nextCursor: null };
241 if (narrow !== undefined) query.set("labels", narrow);
242 }
243 if (input.cursor !== undefined) query.set("after", input.cursor);
244​
245 const page = yield* read(
246 "listIssues",
247 input,
248 `/repos/${input.scope}/issues/?${query}`,
249 IssuePage,
250 );
251 // GitCafe filters by id, so label and assignee names are matched on the rows.
252 const assignee = input.assignee ?? null;
253 return {
254 items: page.items
255 .map((issue) => toSummary(issue, input))
256 .filter(
257 (issue) =>
258 labels.every((name) => issue.labels.some((label) => sameName(label.name, name))) &&
259 (assignee === null ||
260 issue.assignees.some((actor) => sameName(actor.login, assignee))),
261 ),
262 nextCursor: page.next === input.cursor ? null : page.next,
263 };
264 }),
265​
266 getIssue: Effect.fn("GitCafeIssueTracker.getIssue")(function* (input) {
267 if (!/^[1-9]\d{0,9}$/u.test(input.key)) {
268 return yield* failure("getIssue", "not-found", "GitCafe could not find the issue.");
269 }
270 // A token that may read issues but not comments still shows the issue.
271 const [issue, comments] = yield* Effect.all(
272 [read("getIssue", input, issuePath(input), Issue), Effect.option(allComments(input))],
273 { concurrency: 2 },
274 );
275 return {
276 ...toSummary(issue, input),
277 commentCount: Option.match(comments, { onNone: () => 0, onSome: (all) => all.length }),
278 body: issue.description ?? "",
279 viewer: null,
280 viewerPermissions: {
281 setState: false,
282 comment: false,
283 edit: false,
284 labels: false,
285 assignees: false,
286 },
287 states: [],
288 comments: Option.getOrElse(comments, () => []),
289 commentsCursor: null,
290 ...(Option.isNone(comments) ? { commentsUnavailable: true } : {}),
291 events: [],
292 linkedPullRequests: [],
293 };
294 }),
295​
296 // The detail reads every comment, so it hands out no cursor to page with.
297 getComments: () =>
298 Effect.fail(failure("getComments", "failed", "GitCafe issues show every comment at once.")),
299 };
300 },
301);