Open History to see the last commit
1/**
2 * GitLab's issue tracker over `glab api`. GitLab pages by offset and reports no total, so every
3 * cursor is a page number and a full page is the only sign that more exists. Notes, label
4 * events, linked merge requests and awards are separate endpoints, joined into the detail.
5 */
6import * as Effect from "effect/Effect";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import {
10 IssueTrackerKind,
11 type IssueCapabilities,
12 type IssueInvolvement,
13 type IssueViewerPermissions,
14} from "@t3tools/contracts";
15import {
16 IssueTrackerError,
17 type IssueTrackerApi,
18} from "@t3tools/source-control-core/server/IssueTracker";
19
20import * as GitLabCli from "./GitLabCli.ts";
21import {
22 decodeCreatedIssueJson,
23 decodeUserIdsJson,
24 decodeIssueDetailJson,
25 decodeIssueListJson,
26 decodeIssueNotesJson,
27 decodeLabelEventsJson,
28 decodeLinkedMergeRequestsJson,
29 decodeProjectLabelsJson,
30 decodeProjectMembersJson,
31 decodeTemplateEntriesJson,
32 decodeTemplateJson,
33 ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
34 ISSUE_STATES,
35 PAGE_SIZE,
36 type GitLabTemplateEntry,
37} from "./gitLabIssueJson.ts";
38import {
39 decodeAwardEmojiJson,
40 decodeOwnAwardIdJson,
41 decodeViewerJson,
42 gitLabAwardName,
43} from "./gitLabMergeRequestJson.ts";
44
45const KIND = IssueTrackerKind.make("gitlab");
46
47const CAPABILITIES: IssueCapabilities = {
48 create: true,
49 edit: true,
50 comment: true,
51 labels: true,
52 assignees: true,
53 reactions: true,
54 templates: true,
55 linkedPullRequests: true,
56 events: true,
57 search: true,
58};
59
60/**
61 * Everything granted. GitLab's REST API reports the viewer's role on the project but never whether
62 * they opened this issue, and an issue's author may close, reopen and edit it whatever their role.
63 * Withholding those controls from the one person entitled to them is the worse mistake, so they
64 * are offered and GitLab explains any refusal itself.
65 */
66const VIEWER_PERMISSIONS: IssueViewerPermissions = {
67 setState: true,
68 comment: true,
69 edit: true,
70 labels: true,
71 assignees: true,
72};
73
74/** How many of a scope's templates are read in full; each one is a request of its own. */
75const TEMPLATE_LIMIT = 20;
76
77const encodeBody = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
78
79/** The REST API addresses a project by its URL-encoded full path. */
80function projectPath(scope: string): string {
81 return encodeURIComponent(scope.trim());
82}
83
84/** An issue key is its iid; anything else names no GitLab issue. */
85function parseNumber(key: string): number | null {
86 return /^[1-9]\d*$/.test(key) ? Number(key) : null;
87}
88
89/** A page cursor this tracker handed out, or null for anything it could not have issued. */
90function parsePage(cursor: string | undefined): number | null {
91 if (cursor === undefined) return 1;
92 return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
93}
94
95/**
96 * A comments cursor: the next REST page of notes and, after a colon, where GraphQL's awards for
97 * that page start. The two page alike, so a page of comments is joined with its own awards.
98 */
99function parseCommentsCursor(
100 cursor: string,
101): { readonly page: number; readonly awards: string | null } | null {
102 const match = /^([1-9]\d{0,6})(?::(.{1,512}))?$/.exec(cursor);
103 return match === null ? null : { page: Number(match[1]), awards: match[2] ?? null };
104}
105
106function commentsCursor(notesNext: string | null, awardsNext: string | null): string | null {
107 if (notesNext === null) return null;
108 return awardsNext === null ? notesNext : `${notesNext}:${awardsNext}`;
109}
110
111function query(params: ReadonlyArray<readonly [string, string]>): string {
112 return params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
113}
114
115function involvementParams(input: {
116 readonly involvement: IssueInvolvement;
117 readonly viewer: string;
118 readonly assignee?: string | undefined;
119}): ReadonlyArray<readonly [string, string]> {
120 switch (input.involvement) {
121 case "authored":
122 return [["author_username", input.viewer]];
123 case "assigned":
124 // A named assignee takes the one assignee parameter GitLab reads; `listIssues` keeps the
125 // viewer by dropping rows.
126 return input.assignee === undefined ? [["assignee_username", input.viewer]] : [];
127 // GitLab's `my_reaction_emoji` and `iteration` filters aside, nothing narrows to mentions, so
128 // the listing stays as wide as `all` rather than guessing.
129 case "mentioned":
130 case "all":
131 return [];
132 }
133}
134
135function reasonFor(error: GitLabCli.GitLabCliError): IssueTrackerError["reason"] {
136 switch (error._tag) {
137 case "GitLabCliUnavailableError":
138 return "missing-tool";
139 case "GitLabCliAuthenticationError":
140 return "unauthenticated";
141 case "GitLabCliRateLimitError":
142 return "rate-limited";
143 default:
144 return "failed";
145 }
146}
147
148export const make: Effect.Effect<IssueTrackerApi, never, GitLabCli.GitLabCli> = Effect.gen(
149 function* () {
150 const gitlab = yield* GitLabCli.GitLabCli;
151
152 const fail = (operation: string) => (error: GitLabCli.GitLabCliError) =>
153 new IssueTrackerError({
154 tracker: KIND,
155 operation,
156 reason: reasonFor(error),
157 detail: error.detail,
158 cause: error,
159 });
160
161 const unreadable = (operation: string, cause: unknown) =>
162 new IssueTrackerError({
163 tracker: KIND,
164 operation,
165 reason: "failed",
166 detail: `GitLab returned an unreadable ${operation} response.`,
167 cause,
168 });
169
170 const notFound = (operation: string) =>
171 new IssueTrackerError({
172 tracker: KIND,
173 operation,
174 reason: "not-found",
175 detail: "GitLab could not find the requested issue.",
176 });
177
178 const refused = (operation: string, detail: string) =>
179 new IssueTrackerError({ tracker: KIND, operation, reason: "failed", detail });
180
181 const api = (input: {
182 readonly cwd: string;
183 readonly host: string;
184 readonly operation: string;
185 readonly path: string;
186 readonly method?: string;
187 readonly body?: unknown;
188 }) =>
189 gitlab
190 .execute({
191 cwd: input.cwd,
192 host: input.host,
193 args: [
194 "api",
195 input.path,
196 ...(input.method === undefined ? [] : ["--method", input.method]),
197 // A JSON body from stdin: argv is visible in process listings, and `glab api --input`
198 // sends no Content-Type of its own, which GitLab answers with HTTP 415.
199 ...(input.body === undefined
200 ? []
201 : ["--input", "-", "--header", "Content-Type: application/json"]),
202 ],
203 ...(input.body === undefined ? {} : { stdin: encodeBody(input.body) }),
204 })
205 .pipe(
206 Effect.map((result) => result.stdout.trim()),
207 Effect.mapError(fail(input.operation)),
208 );
209
210 const read = <A>(input: {
211 readonly cwd: string;
212 readonly host: string;
213 readonly operation: string;
214 readonly path: string;
215 readonly method?: string;
216 readonly body?: unknown;
217 readonly decode: (raw: string) => Result.Result<A, unknown>;
218 }): Effect.Effect<A, IssueTrackerError> =>
219 api(input).pipe(
220 Effect.flatMap((raw) => {
221 const decoded = input.decode(raw);
222 return Result.isSuccess(decoded)
223 ? Effect.succeed(decoded.success)
224 : Effect.fail(unreadable(input.operation, decoded.failure));
225 }),
226 );
227
228 const write = (input: {
229 readonly cwd: string;
230 readonly host: string;
231 readonly operation: string;
232 readonly path: string;
233 readonly method: string;
234 readonly body?: unknown;
235 }) => api(input).pipe(Effect.asVoid);
236
237 /** The signed-in account; an answer naming nobody is a failure, since every comparison needs a login. */
238 const viewer = (input: {
239 readonly cwd: string;
240 readonly host: string;
241 readonly operation: string;
242 }): Effect.Effect<string, IssueTrackerError> =>
243 read({
244 cwd: input.cwd,
245 host: input.host,
246 operation: input.operation,
247 path: "user",
248 decode: decodeViewerJson,
249 }).pipe(
250 Effect.filterOrFail(
251 (login) => login !== null,
252 () => refused(input.operation, "GitLab returned no username for the signed-in account."),
253 ),
254 );
255
256 /** The issue as REST addresses it, or a not-found for a key that names no iid. */
257 const issuePath = (
258 input: { readonly scope: string; readonly key: string },
259 operation: string,
260 ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
261 const number = parseNumber(input.key);
262 return number === null
263 ? Effect.fail(notFound(operation))
264 : Effect.succeed({ number, path: `projects/${projectPath(input.scope)}/issues/${number}` });
265 };
266
267 /**
268 * GitLab writes assignees by numeric id, which is what the candidates carry as `id`. An issue
269 * names the people it already has by username, so a kept assignee is looked up.
270 */
271 const assigneeIds = (
272 input: { readonly cwd: string; readonly host: string },
273 operation: string,
274 assignees: ReadonlyArray<string>,
275 ): Effect.Effect<ReadonlyArray<number>, IssueTrackerError> =>
276 Effect.forEach(assignees, (assignee) =>
277 /^[1-9]\d*$/.test(assignee)
278 ? Effect.succeed(Number(assignee))
279 : read({
280 cwd: input.cwd,
281 host: input.host,
282 operation,
283 path: `users?${query([["username", assignee]])}`,
284 decode: decodeUserIdsJson,
285 }).pipe(
286 Effect.flatMap(([id]) =>
287 id === undefined
288 ? Effect.fail(refused(operation, `GitLab has no user named ${assignee}.`))
289 : Effect.succeed(id),
290 ),
291 ),
292 );
293
294 const paged = (path: string, page: number) =>
295 `${path}?${query([
296 ["per_page", String(PAGE_SIZE)],
297 ["page", String(page)],
298 ])}`;
299
300 const notesPage = (input: {
301 readonly cwd: string;
302 readonly host: string;
303 readonly path: string;
304 readonly page: number;
305 readonly operation: string;
306 }) =>
307 read({
308 cwd: input.cwd,
309 host: input.host,
310 operation: input.operation,
311 path: `${input.path}/notes?${query([
312 ["per_page", String(PAGE_SIZE)],
313 ["page", String(input.page)],
314 ["order_by", "created_at"],
315 ["sort", "asc"],
316 ])}`,
317 decode: decodeIssueNotesJson,
318 }).pipe(
319 Effect.map((notes) => ({
320 ...notes,
321 nextCursor: notes.rawCount < PAGE_SIZE ? null : String(input.page + 1),
322 })),
323 );
324
325 const awards = (input: {
326 readonly cwd: string;
327 readonly host: string;
328 readonly scope: string;
329 readonly number: number;
330 readonly operation: string;
331 readonly cursor?: string | undefined;
332 }) =>
333 read({
334 cwd: input.cwd,
335 host: input.host,
336 operation: input.operation,
337 path: "graphql",
338 method: "POST",
339 body: {
340 query: ISSUE_AWARD_EMOJI_GRAPHQL_QUERY,
341 variables: {
342 fullPath: input.scope.trim(),
343 iid: String(input.number),
344 cursor: input.cursor ?? null,
345 },
346 },
347 decode: decodeAwardEmojiJson,
348 });
349
350 const linked = (input: {
351 readonly cwd: string;
352 readonly host: string;
353 readonly path: string;
354 readonly endpoint: "closed_by" | "related_merge_requests";
355 }) =>
356 read({
357 cwd: input.cwd,
358 host: input.host,
359 operation: "getIssue",
360 path: paged(`${input.path}/${input.endpoint}`, 1),
361 decode: (raw) => decodeLinkedMergeRequestsJson(raw, input.endpoint === "closed_by"),
362 });
363
364 const template =
365 (input: { readonly cwd: string; readonly host: string; readonly scope: string }) =>
366 (entry: GitLabTemplateEntry) =>
367 read({
368 cwd: input.cwd,
369 host: input.host,
370 operation: "listTemplates",
371 path: `projects/${projectPath(input.scope)}/templates/issues/${encodeURIComponent(entry.key)}`,
372 decode: (raw) => decodeTemplateJson(entry, raw),
373 });
374
375 return {
376 kind: KIND,
377 capabilities: CAPABILITIES,
378
379 getViewer: (input) => viewer({ cwd: input.cwd, host: input.host, operation: "getViewer" }),
380
381 listIssues: Effect.fn("GitLabIssueTracker.listIssues")(function* (input) {
382 const page = parsePage(input.cursor);
383 if (page === null) {
384 return yield* refused("listIssues", "The cursor was not one GitLab handed out.");
385 }
386 const perPage = Math.min(Math.max(input.limit, 1), PAGE_SIZE);
387 const text = input.query?.trim() ?? "";
388 const alsoAssignedTo =
389 input.involvement === "assigned" && input.assignee !== undefined
390 ? input.viewer.toLowerCase()
391 : null;
392 return yield* read({
393 cwd: input.cwd,
394 host: input.host,
395 operation: "listIssues",
396 path: `projects/${projectPath(input.scope)}/issues?${query([
397 ["state", input.state === "open" ? "opened" : input.state],
398 ...involvementParams(input),
399 // GitLab's own `search` matches title and description, URL-encoded like every other
400 // value here, so no text in it can become a parameter of its own.
401 ...(text.length === 0 ? [] : [["search", text] as const]),
402 ...(input.labels === undefined || input.labels.length === 0
403 ? []
404 : [["labels", input.labels.join(",")] as const]),
405 ...(input.assignee === undefined
406 ? []
407 : [["assignee_username", input.assignee] as const]),
408 ["order_by", input.sort === "created" ? "created_at" : "updated_at"],
409 ["sort", "desc"],
410 ["per_page", String(perPage)],
411 ["page", String(page)],
412 ])}`,
413 decode: decodeIssueListJson,
414 }).pipe(
415 Effect.map((list) => ({
416 items:
417 alsoAssignedTo === null
418 ? list.items
419 : list.items.filter((issue) =>
420 issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo),
421 ),
422 nextCursor: list.rawCount < perPage ? null : String(page + 1),
423 })),
424 );
425 }),
426
427 getIssue: (input) =>
428 issuePath(input, "getIssue").pipe(
429 Effect.flatMap(({ number, path }) =>
430 Effect.all(
431 [
432 read({
433 cwd: input.cwd,
434 host: input.host,
435 operation: "getIssue",
436 path,
437 decode: decodeIssueDetailJson,
438 }),
439 viewer({ cwd: input.cwd, host: input.host, operation: "getIssue" }),
440 notesPage({
441 cwd: input.cwd,
442 host: input.host,
443 path,
444 page: 1,
445 operation: "getIssue",
446 }),
447 read({
448 cwd: input.cwd,
449 host: input.host,
450 operation: "getIssue",
451 path: paged(`${path}/resource_label_events`, 1),
452 decode: decodeLabelEventsJson,
453 }),
454 linked({ cwd: input.cwd, host: input.host, path, endpoint: "closed_by" }),
455 linked({
456 cwd: input.cwd,
457 host: input.host,
458 path,
459 endpoint: "related_merge_requests",
460 }),
461 awards({
462 cwd: input.cwd,
463 host: input.host,
464 scope: input.scope,
465 number,
466 operation: "getIssue",
467 }),
468 ],
469 { concurrency: 4 },
470 ),
471 ),
472 Effect.map(([issue, viewerLogin, notes, labelEvents, closing, related, awardPage]) => {
473 const closingKeys = new Set(closing.map((link) => `${link.repository}!${link.number}`));
474 return {
475 ...issue,
476 viewer: viewerLogin,
477 viewerPermissions: VIEWER_PERMISSIONS,
478 states: ISSUE_STATES,
479 reactions: awardPage.reactions,
480 comments: notes.comments.map((comment) => ({
481 ...comment,
482 reactions: awardPage.reactionsByNoteId.get(comment.id) ?? [],
483 })),
484 commentsCursor: commentsCursor(notes.nextCursor, awardPage.nextCursor),
485 events: [...notes.events, ...labelEvents].sort((left, right) =>
486 left.createdAt.localeCompare(right.createdAt),
487 ),
488 // A merge request that closes the issue outranks its sighting as a mere mention.
489 linkedPullRequests: [
490 ...closing,
491 ...related.filter((link) => !closingKeys.has(`${link.repository}!${link.number}`)),
492 ],
493 };
494 }),
495 ),
496
497 getComments: (input) => {
498 const cursor = parseCommentsCursor(input.cursor);
499 return cursor === null
500 ? Effect.fail(refused("getComments", "The cursor was not one GitLab handed out."))
501 : issuePath(input, "getComments").pipe(
502 Effect.flatMap(({ number, path }) =>
503 Effect.all(
504 [
505 notesPage({
506 cwd: input.cwd,
507 host: input.host,
508 path,
509 page: cursor.page,
510 operation: "getComments",
511 }),
512 // Without its awards cursor a later page's awards cannot be found.
513 cursor.awards === null && cursor.page > 1
514 ? Effect.succeed(null)
515 : awards({
516 cwd: input.cwd,
517 host: input.host,
518 scope: input.scope,
519 number,
520 operation: "getComments",
521 cursor: cursor.awards ?? undefined,
522 }),
523 ],
524 { concurrency: 2 },
525 ),
526 ),
527 Effect.map(([notes, awardPage]) => ({
528 comments: notes.comments.map((comment) => ({
529 ...comment,
530 reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [],
531 })),
532 nextCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null),
533 })),
534 );
535 },
536
537 create: (input) =>
538 assigneeIds(input, "create", input.assignees).pipe(
539 Effect.flatMap((assignee_ids) =>
540 read({
541 cwd: input.cwd,
542 host: input.host,
543 operation: "create",
544 path: `projects/${projectPath(input.scope)}/issues`,
545 method: "POST",
546 body: {
547 title: input.title,
548 description: input.body,
549 labels: input.labels.join(","),
550 assignee_ids,
551 },
552 decode: decodeCreatedIssueJson,
553 }),
554 ),
555 Effect.map((issue) => ({
556 key: String(issue.number),
557 displayKey: `#${issue.number}`,
558 url: issue.url,
559 })),
560 ),
561
562 comment: (input) =>
563 issuePath(input, "comment").pipe(
564 Effect.flatMap(({ path }) =>
565 write({
566 cwd: input.cwd,
567 host: input.host,
568 operation: "comment",
569 path: `${path}/notes`,
570 method: "POST",
571 body: { body: input.body },
572 }),
573 ),
574 ),
575
576 update: (input) =>
577 Effect.all([
578 issuePath(input, "update"),
579 input.assignees === undefined
580 ? Effect.void
581 : assigneeIds(input, "update", input.assignees),
582 ]).pipe(
583 Effect.flatMap(([{ path }, assignee_ids]) =>
584 write({
585 cwd: input.cwd,
586 host: input.host,
587 operation: "update",
588 path,
589 method: "PUT",
590 body: {
591 ...(input.title === undefined ? {} : { title: input.title }),
592 ...(input.body === undefined ? {} : { description: input.body }),
593 ...(input.labels === undefined ? {} : { labels: input.labels.join(",") }),
594 ...(assignee_ids === undefined ? {} : { assignee_ids }),
595 },
596 }),
597 ),
598 ),
599
600 setState: (input) => {
601 const wanted = ISSUE_STATES.find((state) => state.name === input.state);
602 if (wanted === undefined) {
603 return Effect.fail(refused("setState", `A GitLab issue has no "${input.state}" state.`));
604 }
605 return issuePath(input, "setState").pipe(
606 Effect.flatMap(({ path }) =>
607 write({
608 cwd: input.cwd,
609 host: input.host,
610 operation: "setState",
611 path,
612 method: "PUT",
613 body: { state_event: wanted.category === "closed" ? "close" : "reopen" },
614 }),
615 ),
616 );
617 },
618
619 setReaction: Effect.fn("GitLabIssueTracker.setReaction")(function* (input) {
620 const { path } = yield* issuePath(input, "setReaction");
621 if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
622 return yield* refused("setReaction", "The comment id names no GitLab note.");
623 }
624 const subject =
625 input.subjectId === undefined
626 ? `${path}/award_emoji`
627 : `${path}/notes/${input.subjectId}/award_emoji`;
628 if (input.reacted) {
629 return yield* write({
630 cwd: input.cwd,
631 host: input.host,
632 operation: "setReaction",
633 path: `${subject}?${query([["name", gitLabAwardName(input.content)]])}`,
634 method: "POST",
635 });
636 }
637 // GitLab deletes an award by its id and takes no emoji name there, so the reader's own
638 // award of that name is looked up first. Nothing to delete is success.
639 const login = yield* viewer({
640 cwd: input.cwd,
641 host: input.host,
642 operation: "setReaction",
643 });
644 for (let page = 1; ; page++) {
645 const own = yield* read({
646 cwd: input.cwd,
647 host: input.host,
648 operation: "setReaction",
649 path: paged(subject, page),
650 decode: (raw) => decodeOwnAwardIdJson(raw, { content: input.content, viewer: login }),
651 });
652 if (own.id !== null) {
653 return yield* write({
654 cwd: input.cwd,
655 host: input.host,
656 operation: "setReaction",
657 path: `${subject}/${own.id}`,
658 method: "DELETE",
659 });
660 }
661 // An empty raw page establishes exhaustion even when the host caps page size.
662 if (own.empty) return;
663 }
664 }),
665
666 listTemplates: (input) =>
667 read({
668 cwd: input.cwd,
669 host: input.host,
670 operation: "listTemplates",
671 path: `projects/${projectPath(input.scope)}/templates/issues`,
672 decode: decodeTemplateEntriesJson,
673 }).pipe(
674 Effect.flatMap((entries) =>
675 Effect.forEach(entries.slice(0, TEMPLATE_LIMIT), template(input), { concurrency: 4 }),
676 ),
677 // GitLab has no switch that forbids an issue filed from nothing.
678 Effect.map((templates) => ({ templates, blankIssuesEnabled: true })),
679 ),
680
681 listCandidates: (input) =>
682 Effect.all(
683 [
684 read({
685 cwd: input.cwd,
686 host: input.host,
687 operation: "listCandidates",
688 path: paged(`projects/${projectPath(input.scope)}/labels`, 1),
689 decode: decodeProjectLabelsJson,
690 }),
691 read({
692 cwd: input.cwd,
693 host: input.host,
694 operation: "listCandidates",
695 path: paged(`projects/${projectPath(input.scope)}/members/all`, 1),
696 decode: decodeProjectMembersJson,
697 }),
698 ],
699 { concurrency: 2 },
700 ).pipe(
701 Effect.map(([labels, assignees]) => ({
702 labels,
703 assignees,
704 truncated: labels.length >= PAGE_SIZE || assignees.length >= PAGE_SIZE,
705 })),
706 ),
707 };
708 },
709);