Open History to see the last commit
1/**
2 * Forgejo's issue tracker over `ForgejoCli.api`, which resolves the server and login from the
3 * checkout's remote. Forgejo pages by number and announces a next page in a `Link` header the
4 * CLI surfaces on stderr, so every cursor here is the next page number.
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 IssueLinkedPullRequest,
14 type IssueViewerPermissions,
15} from "@t3tools/contracts";
16import { decodeJsonResult } from "@t3tools/shared/schemaJson";
17import {
18 IssueTrackerError,
19 type IssueTrackerApi,
20} from "@t3tools/source-control-core/server/IssueTracker";
21
22import * as ForgejoCli from "./ForgejoCli.ts";
23import {
24 ForgejoIssue,
25 ForgejoIssueConfig,
26 ForgejoIssueRepository,
27 ForgejoIssueTemplate,
28 ForgejoTimelineEntry,
29 ISSUE_STATES,
30 forgejoIssue,
31 forgejoIssueComment,
32 forgejoIssueEvent,
33 forgejoIssueTemplate,
34} from "./forgejoIssueJson.ts";
35import {
36 FORGEJO_REACTIONS,
37 ForgejoComment,
38 ForgejoLabel,
39 ForgejoReaction,
40 ForgejoUser,
41 forgejoActor,
42 forgejoReactions,
43} from "./forgejoPullRequestJson.ts";
44
45const KIND = IssueTrackerKind.make("forgejo");
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/** Forgejo's own ceiling on a page, which a self-hosted server may lower. */
61const PAGE_SIZE = 50;
62/** How many pages of a listing with no cursor of its own are read before giving up on the rest. */
63const MAX_PAGES = 10;
64
65const INVOLVEMENT_PARAM: Record<Exclude<IssueInvolvement, "all">, string> = {
66 assigned: "assigned_by",
67 authored: "created_by",
68 mentioned: "mentioned_by",
69};
70
71const repoPath = (scope: string) => `repos/${scope.split("/").map(encodeURIComponent).join("/")}`;
72const issuePath = (scope: string, number: number) => `${repoPath(scope)}/issues/${number}`;
73
74function parseNumber(key: string): number | null {
75 return /^[1-9]\d*$/.test(key) ? Number(key) : null;
76}
77
78function parsePage(cursor: string | undefined): number | null {
79 if (cursor === undefined) return 1;
80 return /^[1-9]\d{0,6}$/.test(cursor) ? Number(cursor) : null;
81}
82
83function reasonFor(error: ForgejoCli.ForgejoCliError): IssueTrackerError["reason"] {
84 switch (error.reason) {
85 case "missing-cli":
86 case "wrong-cli":
87 return "missing-tool";
88 case "authentication":
89 return "unauthenticated";
90 case "rate-limit":
91 return "rate-limited";
92 case "not-found":
93 return "not-found";
94 default:
95 return "failed";
96 }
97}
98
99/**
100 * What the signed-in account may do. Forgejo reports push access on the repository, and an
101 * issue's author may edit and close their own; an archived repository takes everything away, and
102 * a locked issue takes commenting away from anyone without push.
103 */
104function permissions(
105 repository: typeof ForgejoIssueRepository.Type,
106 issue: typeof ForgejoIssue.Type,
107 viewer: string,
108): IssueViewerPermissions {
109 const active = !repository.archived;
110 const canWrite = repository.permissions?.push ?? false;
111 const canEdit = canWrite || issue.user?.login === viewer;
112 return {
113 setState: active && canEdit,
114 comment: active && (!issue.is_locked || canWrite),
115 edit: active && canEdit,
116 labels: active && canWrite,
117 assignees: active && canWrite,
118 };
119}
120
121export const make: Effect.Effect<IssueTrackerApi, never, ForgejoCli.ForgejoCli> = Effect.gen(
122 function* () {
123 const cli = yield* ForgejoCli.ForgejoCli;
124
125 const refused = (operation: string, detail: string, cause?: unknown) =>
126 new IssueTrackerError({
127 tracker: KIND,
128 operation,
129 reason: "failed",
130 detail,
131 ...(cause === undefined ? {} : { cause }),
132 });
133
134 const notFound = (operation: string) =>
135 new IssueTrackerError({
136 tracker: KIND,
137 operation,
138 reason: "not-found",
139 detail: "Forgejo could not find the requested issue.",
140 });
141
142 type Target = { readonly cwd: string; readonly host: string; readonly scope: string };
143
144 const request = (
145 target: Target,
146 operation: string,
147 input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
148 ) =>
149 cli.api({ cwd: target.cwd, repository: target.scope, host: target.host, ...input }).pipe(
150 Effect.mapError(
151 (error) =>
152 new IssueTrackerError({
153 tracker: KIND,
154 operation,
155 reason: reasonFor(error),
156 detail: error.detail,
157 cause: error,
158 }),
159 ),
160 );
161
162 const read = <A>(
163 target: Target,
164 operation: string,
165 input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
166 schema: Schema.Codec<A, unknown, never, never>,
167 ): Effect.Effect<A, IssueTrackerError> =>
168 request(target, operation, input).pipe(
169 Effect.flatMap((result) => {
170 if (result.stdoutTruncated) {
171 return Effect.fail(refused(operation, "Forgejo response exceeded the output limit."));
172 }
173 const decoded = decodeJsonResult(schema)(result.stdout);
174 return Result.isSuccess(decoded)
175 ? Effect.succeed(decoded.success)
176 : Effect.fail(
177 refused(operation, "Forgejo returned an invalid response.", decoded.failure),
178 );
179 }),
180 );
181
182 const readArray = <A>(
183 target: Target,
184 operation: string,
185 path: string,
186 schema: Schema.Codec<A, unknown, never, never>,
187 ) =>
188 read(target, operation, { path }, Schema.NullOr(Schema.Array(schema))).pipe(
189 Effect.map((rows) => rows ?? []),
190 );
191
192 /** One page of a listing, and whether Forgejo's `Link` header announced another. */
193 const readPage = <A>(
194 target: Target,
195 operation: string,
196 path: string,
197 page: number,
198 schema: Schema.Codec<A, unknown, never, never>,
199 ): Effect.Effect<
200 { readonly rows: ReadonlyArray<A>; readonly nextCursor: string | null },
201 IssueTrackerError
202 > =>
203 request(target, operation, {
204 path: `${path}${path.includes("?") ? "&" : "?"}limit=${PAGE_SIZE}&page=${page}`,
205 }).pipe(
206 Effect.flatMap((result) => {
207 const decoded = decodeJsonResult(Schema.NullOr(Schema.Array(schema)))(result.stdout);
208 if (Result.isFailure(decoded)) {
209 return Effect.fail(
210 refused(operation, "Forgejo returned an invalid response.", decoded.failure),
211 );
212 }
213 const rows = decoded.success ?? [];
214 const links = /^link:\s*(.*)$/im.exec(result.stderr)?.[1];
215 const more = rows.length > 0 && (links === undefined || /rel="?next"?/i.test(links));
216 return Effect.succeed({ rows, nextCursor: more ? String(page + 1) : null });
217 }),
218 );
219
220 const write = (
221 target: Target,
222 operation: string,
223 input: Omit<ForgejoCli.ForgejoApiInput, "cwd" | "repository" | "host">,
224 ) => request(target, operation, input).pipe(Effect.asVoid);
225
226 const getViewer = (target: Target, operation: string) =>
227 read(target, operation, { path: "user" }, ForgejoUser).pipe(Effect.map((user) => user.login));
228
229 const getRepository = (target: Target, operation: string) =>
230 read(target, operation, { path: repoPath(target.scope) }, ForgejoIssueRepository);
231
232 /** The issue as the API addresses it, or a not-found for a key that names no number. */
233 const issueTarget = (
234 operation: string,
235 input: Target & { readonly key: string },
236 ): Effect.Effect<{ readonly number: number; readonly path: string }, IssueTrackerError> => {
237 const number = parseNumber(input.key);
238 return number === null
239 ? Effect.fail(notFound(operation))
240 : Effect.succeed({ number, path: issuePath(input.scope, number) });
241 };
242
243 const getIssue = (target: Target, operation: string, path: string) =>
244 read(target, operation, { path }, ForgejoIssue).pipe(
245 // The issues API answers for a pull request's number too; that is not an issue here.
246 Effect.filterOrFail(
247 (issue) => !issue.pull_request,
248 () => notFound(operation),
249 ),
250 );
251
252 /** Every page of a listing the caller gets no cursor for, up to `MAX_PAGES`. */
253 const readEveryPage = Effect.fn("ForgejoIssueTracker.readEveryPage")(function* <A>(
254 target: Target,
255 operation: string,
256 path: string,
257 schema: Schema.Codec<A, unknown, never, never>,
258 ) {
259 const rows: A[] = [];
260 for (let page = 1; page <= MAX_PAGES; page++) {
261 const next = yield* readPage(target, operation, path, page, schema);
262 rows.push(...next.rows);
263 if (next.nextCursor === null) break;
264 }
265 return rows;
266 });
267
268 /**
269 * Labels are written by id, so names are resolved against the repository's own, page by page
270 * until each is found. A name the repository lacks refuses the write rather than dropping it.
271 */
272 const labelIds = Effect.fn("ForgejoIssueTracker.labelIds")(function* (
273 target: Target,
274 operation: string,
275 names: ReadonlyArray<string>,
276 ) {
277 const ids = new Map<string, number>();
278 for (let page = 1; ids.size < new Set(names).size && page <= MAX_PAGES; page++) {
279 const next = yield* readPage(
280 target,
281 operation,
282 `${repoPath(target.scope)}/labels`,
283 page,
284 ForgejoLabel,
285 );
286 for (const label of next.rows) {
287 if (names.includes(label.name)) ids.set(label.name, label.id);
288 }
289 if (next.nextCursor === null) break;
290 }
291 if (names.some((name) => !ids.has(name))) {
292 return yield* refused(operation, "Forgejo found no label by one of the names given.");
293 }
294 return [...ids.values()];
295 });
296
297 /** `/comments` takes no page and answers with every comment, so the pages are cut here. */
298 const commentsPage = (
299 target: Target,
300 operation: string,
301 path: string,
302 page: number,
303 viewer: string,
304 ) =>
305 readArray(target, operation, `${path}/comments`, ForgejoComment).pipe(
306 Effect.flatMap((rows) => {
307 const end = page * PAGE_SIZE;
308 return Effect.forEach(
309 rows.slice(end - PAGE_SIZE, end),
310 (comment) =>
311 readArray(
312 target,
313 operation,
314 `${repoPath(target.scope)}/issues/comments/${comment.id}/reactions`,
315 ForgejoReaction,
316 ).pipe(
317 Effect.map((reactions) => ({
318 ...forgejoIssueComment(comment),
319 reactions: forgejoReactions(reactions, viewer),
320 })),
321 ),
322 { concurrency: 4 },
323 ).pipe(
324 Effect.map((comments) => ({
325 comments,
326 nextCursor: rows.length > end ? String(page + 1) : null,
327 })),
328 );
329 }),
330 );
331
332 /** Pull requests the timeline shows citing this issue, each read once for its state. */
333 const linkedPullRequests = (
334 target: Target,
335 timeline: ReadonlyArray<typeof ForgejoTimelineEntry.Type>,
336 ): Effect.Effect<ReadonlyArray<IssueLinkedPullRequest>, IssueTrackerError> => {
337 // A reference may come from another repository, which is where that pull request is read.
338 const cited = new Map<string, { readonly repository: string; readonly number: number }>();
339 for (const entry of timeline) {
340 if (entry.type !== "pull_ref" || !entry.ref_issue?.pull_request) continue;
341 const named = entry.ref_issue.repository?.full_name;
342 // The scope may carry the server's mount path in front of the same repository.
343 const repository =
344 named === undefined || target.scope.endsWith(`/${named}`) ? target.scope : named;
345 cited.set(`${repository}#${entry.ref_issue.number}`, {
346 repository,
347 number: entry.ref_issue.number,
348 });
349 }
350 return Effect.forEach(
351 cited.values(),
352 ({ repository, number }) =>
353 read(
354 target,
355 "getIssue",
356 { path: `${repoPath(repository)}/pulls/${number}` },
357 Schema.Struct({
358 number: Schema.Int,
359 title: Schema.String,
360 html_url: Schema.String,
361 state: Schema.String,
362 merged: Schema.Boolean,
363 draft: Schema.optional(Schema.Boolean),
364 }),
365 ).pipe(
366 Effect.map((pull) => [
367 {
368 repository,
369 number: pull.number,
370 title: pull.title,
371 url: pull.html_url,
372 state: pull.merged
373 ? ("merged" as const)
374 : pull.state === "closed"
375 ? ("closed" as const)
376 : ("open" as const),
377 isDraft: pull.draft ?? false,
378 // Forgejo's timeline cites the pull request without saying whether it closes the issue.
379 closesIssue: false,
380 },
381 ]),
382 Effect.catchIf(
383 (error) => error.reason === "not-found",
384 () => Effect.succeed([]),
385 ),
386 ),
387 { concurrency: 2 },
388 ).pipe(Effect.map((links) => links.flat()));
389 };
390
391 return {
392 kind: KIND,
393 capabilities: CAPABILITIES,
394
395 getViewer: (input) => getViewer({ ...input, scope: "" }, "getViewer"),
396
397 listIssues: Effect.fn("ForgejoIssueTracker.listIssues")(function* (input) {
398 const page = parsePage(input.cursor);
399 if (page === null) {
400 return yield* refused("listIssues", "The cursor was not one Forgejo handed out.");
401 }
402 const params = new URLSearchParams({
403 type: "issues",
404 state: input.state,
405 sort: input.sort === "created" ? "latest" : "recentupdate",
406 });
407 const labels = input.labels ?? [];
408 if (labels.length > 0) params.set("labels", labels.join(","));
409 const text = input.query?.trim() ?? "";
410 if (text.length > 0) params.set("q", text);
411 if (input.involvement !== "all") {
412 params.set(INVOLVEMENT_PARAM[input.involvement], input.viewer);
413 }
414 if (input.assignee !== undefined) params.set("assigned_by", input.assignee);
415 // `assigned_by` names one person, so "assigned to me" is kept here beside a named assignee.
416 const alsoAssignedTo =
417 input.involvement === "assigned" && input.assignee !== undefined
418 ? input.viewer.toLowerCase()
419 : null;
420 const { rows, nextCursor } = yield* readPage(
421 input,
422 "listIssues",
423 `${repoPath(input.scope)}/issues?${params}`,
424 page,
425 ForgejoIssue,
426 );
427 return {
428 items: rows
429 .flatMap((issue) => (issue.pull_request ? [] : [forgejoIssue(issue)]))
430 // Forgejo documents `labels` as matching any of them; every one is what was asked.
431 .filter(
432 (issue) =>
433 labels.every((label) => issue.labels.some((carried) => carried.name === label)) &&
434 (alsoAssignedTo === null ||
435 issue.assignees.some((actor) => actor.login.toLowerCase() === alsoAssignedTo)),
436 ),
437 nextCursor,
438 };
439 }),
440
441 getIssue: (input) =>
442 issueTarget("getIssue", input).pipe(
443 Effect.flatMap(({ path }) =>
444 Effect.all(
445 [
446 getIssue(input, "getIssue", path),
447 getRepository(input, "getIssue"),
448 getViewer(input, "getIssue"),
449 readEveryPage(input, "getIssue", `${path}/timeline`, ForgejoTimelineEntry),
450 readArray(input, "getIssue", `${path}/reactions`, ForgejoReaction),
451 ],
452 { concurrency: 3 },
453 ),
454 ),
455 Effect.flatMap(([issue, repository, viewer, timeline, reactions]) =>
456 Effect.all([
457 commentsPage(input, "getIssue", issuePath(input.scope, issue.number), 1, viewer),
458 linkedPullRequests(input, timeline),
459 ]).pipe(
460 Effect.map(([conversation, links]) => ({
461 ...forgejoIssue(issue),
462 body: issue.body ?? "",
463 viewer,
464 viewerPermissions: permissions(repository, issue, viewer),
465 states: ISSUE_STATES,
466 reactions: forgejoReactions(reactions, viewer),
467 comments: conversation.comments,
468 commentsCursor: conversation.nextCursor,
469 events: timeline.flatMap((entry) => forgejoIssueEvent(entry) ?? []),
470 linkedPullRequests: links,
471 })),
472 ),
473 ),
474 ),
475
476 getComments: (input) => {
477 const page = parsePage(input.cursor);
478 return page === null
479 ? Effect.fail(refused("getComments", "The cursor was not one Forgejo handed out."))
480 : Effect.all([issueTarget("getComments", input), getViewer(input, "getComments")]).pipe(
481 Effect.flatMap(([{ path }, viewer]) =>
482 commentsPage(input, "getComments", path, page, viewer),
483 ),
484 );
485 },
486
487 create: (input) =>
488 labelIds(input, "create", input.labels).pipe(
489 Effect.flatMap((labels) =>
490 read(
491 input,
492 "create",
493 {
494 path: `${repoPath(input.scope)}/issues`,
495 method: "POST",
496 body: {
497 title: input.title,
498 body: input.body,
499 labels,
500 assignees: input.assignees,
501 },
502 },
503 ForgejoIssue,
504 ),
505 ),
506 Effect.map((issue) => ({
507 key: String(issue.number),
508 displayKey: `#${issue.number}`,
509 url: issue.html_url,
510 })),
511 ),
512
513 comment: (input) =>
514 issueTarget("comment", input).pipe(
515 Effect.flatMap(({ path }) =>
516 write(input, "comment", {
517 path: `${path}/comments`,
518 method: "POST",
519 body: { body: input.body },
520 }),
521 ),
522 ),
523
524 update: (input) =>
525 Effect.all([
526 issueTarget("update", input),
527 // Resolved before anything is written, so an unknown label changes nothing.
528 input.labels === undefined ? Effect.void : labelIds(input, "update", input.labels),
529 ]).pipe(
530 Effect.flatMap(([{ path }, labels]) =>
531 Effect.all([
532 input.title === undefined && input.body === undefined && input.assignees === undefined
533 ? Effect.void
534 : write(input, "update", {
535 path,
536 method: "PATCH",
537 body: {
538 ...(input.title === undefined ? {} : { title: input.title }),
539 ...(input.body === undefined ? {} : { body: input.body }),
540 ...(input.assignees === undefined ? {} : { assignees: input.assignees }),
541 },
542 }),
543 labels === undefined
544 ? Effect.void
545 : write(input, "update", {
546 path: `${path}/labels`,
547 method: "PUT",
548 body: { labels },
549 }),
550 ]),
551 ),
552 Effect.asVoid,
553 ),
554
555 setState: (input) => {
556 const wanted = ISSUE_STATES.find((state) => state.name === input.state);
557 if (wanted === undefined) {
558 return Effect.fail(refused("setState", `A Forgejo issue has no "${input.state}" state.`));
559 }
560 return issueTarget("setState", input).pipe(
561 Effect.flatMap(({ path }) =>
562 write(input, "setState", { path, method: "PATCH", body: { state: wanted.category } }),
563 ),
564 );
565 },
566
567 setReaction: (input) =>
568 issueTarget("setReaction", input).pipe(
569 Effect.flatMap(({ path }) => {
570 if (input.subjectId !== undefined && !/^[1-9]\d*$/.test(input.subjectId)) {
571 return Effect.fail(
572 refused("setReaction", "The comment id names no Forgejo comment."),
573 );
574 }
575 return write(input, "setReaction", {
576 path:
577 input.subjectId === undefined
578 ? `${path}/reactions`
579 : `${repoPath(input.scope)}/issues/comments/${input.subjectId}/reactions`,
580 method: input.reacted ? "POST" : "DELETE",
581 body: { content: FORGEJO_REACTIONS[input.content] },
582 });
583 }),
584 ),
585
586 listTemplates: (input) =>
587 Effect.all(
588 [
589 readArray(
590 input,
591 "listTemplates",
592 `${repoPath(input.scope)}/issue_templates`,
593 ForgejoIssueTemplate,
594 ),
595 // A repository with no config leaves the blank issue where Forgejo puts it.
596 read(
597 input,
598 "listTemplates",
599 { path: `${repoPath(input.scope)}/issue_config` },
600 ForgejoIssueConfig,
601 ).pipe(
602 Effect.map((config) => config.blank_issues_enabled !== false),
603 Effect.catchIf(
604 (error) => error.reason === "not-found" || error.reason === "failed",
605 () => Effect.succeed(true),
606 ),
607 ),
608 ],
609 { concurrency: 2 },
610 ).pipe(
611 Effect.map(([templates, blankIssuesEnabled]) => ({
612 templates: templates.flatMap((template) => forgejoIssueTemplate(template) ?? []),
613 blankIssuesEnabled,
614 })),
615 ),
616
617 listCandidates: (input) =>
618 Effect.all(
619 [
620 readPage(input, "listCandidates", `${repoPath(input.scope)}/labels`, 1, ForgejoLabel),
621 readPage(input, "listCandidates", `${repoPath(input.scope)}/assignees`, 1, ForgejoUser),
622 ],
623 { concurrency: 2 },
624 ).pipe(
625 Effect.map(([labels, assignees]) => ({
626 labels: labels.rows.map((label) => ({
627 name: label.name,
628 color: label.color ?? null,
629 description: label.description ?? null,
630 })),
631 assignees: assignees.rows.flatMap((user) => {
632 const actor = forgejoActor(user);
633 return actor === null ? [] : [{ ...actor, id: actor.login }];
634 }),
635 truncated: labels.nextCursor !== null || assignees.nextCursor !== null,
636 })),
637 ),
638 };
639 },
640);