Open History to see the last commit
1import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage";
2import { SourceControlProviderKind } from "@t3tools/contracts";
3import * as Cache from "effect/Cache";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import type {
8 PullRequestActor,
9 PullRequestCapabilities,
10 PullRequestReaction,
11 PullRequestViewerPermissions,
12} from "@t3tools/contracts";
13
14import * as GitLabPullRequestCli from "./GitLabPullRequestCli.ts";
15import type { GitLabDiffRefs, GitLabMergeRequestListState } from "./gitLabMergeRequestJson.ts";
16import {
17 PullRequestProviderError,
18 type PullRequestProviderFailure,
19 type ProviderChangeRequestActivity,
20 type ProviderChangeRequestDetail,
21 type PullRequestProviderApi,
22} from "@t3tools/source-control-core/server/PullRequestProvider";
23import { definition } from "../shared/definition.ts";
24
25const CAPABILITIES: PullRequestCapabilities = {
26 diff: true,
27 comment: true,
28 actions: [...definition.changeRequestActions],
29 mergeMethods: ["merge", "squash", "rebase"],
30 deleteBranch: true,
31 // GitLab has no merge-target-into-source operation.
32 updateMethods: ["rebase"],
33 search: true,
34 reactions: true,
35 mentions: true,
36 referenceSigils: ["#", "!"],
37 // GitLab's viewed marks live in browser-local storage.
38 viewedFiles: "environment",
39 review: {
40 inlineComment: true,
41 rangeComment: true,
42 reply: true,
43 resolve: true,
44 verdicts: ["comment", "approve", "request-changes"],
45 },
46 reviewers: { request: true, listCandidates: true, searchCandidates: true },
47 labels: true,
48 edit: { changeRequest: true, comment: true, maintainerEdits: true },
49};
50
51const UNAVAILABLE_REQUIREMENT = {
52 missing:
53 "GitLab CLI (`glab`) is required to browse change requests on this host. Install it from https://gitlab.com/gitlab-org/cli and reload.",
54 unauthenticated: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
55};
56
57/**
58 * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to
59 * the target, so it is not literally the same permission — but GitLab reports nothing narrower,
60 * and someone it will not let land this change has no business rewriting its branch either.
61 */
62const MERGE_ACTIONS: ReadonlySet<string> = new Set([
63 "merge",
64 "update-branch",
65 "enable-auto-merge",
66 "disable-auto-merge",
67]);
68
69/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
70export function gitLabViewerPermissions(input: {
71 readonly viewerCanMerge: boolean;
72 readonly viewerCanEditMaintainerEdits?: boolean | undefined;
73 readonly viewerCanDeleteBranch?: boolean;
74 readonly viewerCanEditLabels?: boolean | undefined;
75}): PullRequestViewerPermissions {
76 return {
77 actions: CAPABILITIES.actions.filter((action) =>
78 action === "delete-branch"
79 ? input.viewerCanDeleteBranch === true
80 : !MERGE_ACTIONS.has(action) || input.viewerCanMerge,
81 ),
82 comment: true,
83 resolve: true,
84 verdicts: CAPABILITIES.review.verdicts,
85 requestReviewers: true,
86 maintainerEdits: input.viewerCanEditMaintainerEdits === true,
87 labels: input.viewerCanEditLabels === true,
88 ...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
89 };
90}
91
92/**
93 * One page view asks for the detail and then its checks within a second, and the poll that
94 * follows asks again. A minute keeps those to one `glab` call without hiding a pipeline for long;
95 * a refresh or a finished turn drops it sooner through `forgetChangeRequestReads`.
96 */
97const MERGE_REQUEST_DETAIL_TTL = Duration.minutes(1);
98/** A project's merge methods change in its settings, which nobody does between page views. */
99const PROJECT_MERGE_CAPABILITIES_TTL = Duration.minutes(15);
100const READ_CACHE_CAPACITY = 256;
101/** A host's GitLab version only changes on upgrade. */
102const GRAPHQL_LIST_SUPPORT_TTL = Duration.hours(1);
103
104function gitLabProviderFailure(
105 error: GitLabPullRequestCli.GitLabPullRequestCliError,
106): PullRequestProviderFailure {
107 if (error._tag === "GitLabCliUnavailableError") return { reason: "missing-tool" };
108 if (error._tag === "GitLabCliAuthenticationError") return { reason: "unauthenticated" };
109 if (error._tag === "GitLabCliRateLimitError") return { reason: "rate-limited" };
110 if (error._tag === "GitLabMergeRequestNotFoundError") return { reason: "not-found" };
111 return { reason: "failed" };
112}
113
114// GitLab keeps a thread on the latest diff while its line survives, so older refs mean the code moved.
115const isOutdated = (
116 thread: GitLabDiffRefs | undefined,
117 current: GitLabDiffRefs | undefined,
118): boolean =>
119 thread !== undefined &&
120 current !== undefined &&
121 (thread.baseSha !== current.baseSha ||
122 thread.startSha !== current.startSha ||
123 thread.headSha !== current.headSha);
124
125export const make = Effect.gen(function* () {
126 const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
127
128 // Keyed on the checkout as well: `glab` picks the host and the account to answer as from the
129 // checkout's remote and config, so two checkouts may read the same project as different people.
130 const mergeRequestDetails = yield* Cache.makeWith(
131 (key: string) => {
132 const [cwd, repository, number, host] = JSON.parse(key) as [string, string, number, string];
133 return cli.getMergeRequestDetail({ cwd, repository, number, host });
134 },
135 {
136 capacity: READ_CACHE_CAPACITY,
137 timeToLive: (exit) => (Exit.isSuccess(exit) ? MERGE_REQUEST_DETAIL_TTL : Duration.zero),
138 },
139 );
140 const graphqlListSupport = yield* Cache.makeWith(
141 (key: string) => {
142 const [cwd, host] = JSON.parse(key) as [string, string | undefined];
143 // A host whose version read fails keeps failing it; remember REST rather than ask each poll.
144 return cli.supportsGraphqlList({ cwd, host }).pipe(
145 Effect.catchIf(
146 (cause) =>
147 cause._tag !== "GitLabCliUnavailableError" &&
148 cause._tag !== "GitLabCliAuthenticationError" &&
149 cause._tag !== "GitLabCliRateLimitError",
150 () => Effect.succeed(false),
151 ),
152 );
153 },
154 {
155 capacity: READ_CACHE_CAPACITY,
156 timeToLive: (exit) => (Exit.isSuccess(exit) ? GRAPHQL_LIST_SUPPORT_TTL : Duration.zero),
157 },
158 );
159 const projectMergeCapabilities = yield* Cache.makeWith(
160 (key: string) => {
161 const [cwd, repository, host] = JSON.parse(key) as [string, string, string];
162 return cli.getProjectMergeCapabilities({ cwd, repository, host });
163 },
164 {
165 capacity: READ_CACHE_CAPACITY,
166 timeToLive: (exit) => (Exit.isSuccess(exit) ? PROJECT_MERGE_CAPABILITIES_TTL : Duration.zero),
167 },
168 );
169
170 const detailKey = (input: {
171 readonly cwd: string;
172 readonly host: string;
173 readonly repository: string;
174 readonly number: number;
175 }) => JSON.stringify([input.cwd, input.repository, input.number, input.host]);
176 const mergeRequestDetail = (input: {
177 readonly cwd: string;
178 readonly host: string;
179 readonly repository: string;
180 readonly number: number;
181 }) => Cache.get(mergeRequestDetails, detailKey(input));
182
183 // Dropped on both sides, as the service does with its own reads: a read that starts while the
184 // write is in flight must not outlive it.
185 const writing =
186 <
187 I extends {
188 readonly cwd: string;
189 readonly host: string;
190 readonly repository: string;
191 readonly number: number;
192 },
193 A,
194 E,
195 >(
196 write: (input: I) => Effect.Effect<A, E>,
197 ) =>
198 (input: I): Effect.Effect<A, E> => {
199 const invalidate = Cache.invalidate(mergeRequestDetails, detailKey(input));
200 return invalidate.pipe(Effect.andThen(write(input)), Effect.ensuring(invalidate));
201 };
202
203 const fail = (operation: string) => (error: GitLabPullRequestCli.GitLabPullRequestCliError) =>
204 new PullRequestProviderError({
205 provider: SourceControlProviderKind.make("gitlab"),
206 operation,
207 ...gitLabProviderFailure(error),
208 detail: error.detail,
209 cause: error,
210 });
211
212 // Optional endpoints may lose part of the activity, but an unusable CLI or account must
213 // reach the caller so it can report authentication failures and pause a throttled host.
214 const recoverRead = <A>(
215 read: Effect.Effect<A, GitLabPullRequestCli.GitLabPullRequestCliError>,
216 fallback: A,
217 ) =>
218 read.pipe(
219 Effect.catch((error) => {
220 const { reason } = gitLabProviderFailure(error);
221 return reason === "rate-limited" ||
222 reason === "unauthenticated" ||
223 reason === "missing-tool"
224 ? Effect.fail(error)
225 : Effect.succeed(fallback);
226 }),
227 );
228
229 // The rows were already read, so even a rate limit only leaves their states unknown.
230 const listStates = (input: Parameters<typeof cli.getListStates>[0]) =>
231 cli.getListStates(input).pipe(
232 Effect.catch((error) =>
233 Effect.logWarning("GitLab merge request approval and pipeline read failed", {
234 repository: input.repository,
235 reason: error._tag,
236 }).pipe(Effect.as<ReadonlyMap<number, GitLabMergeRequestListState>>(new Map())),
237 ),
238 );
239
240 // REST omits line counts; the CLI recovers optional stats failures per batch.
241 const mergeRequestWithStats = (
242 input: {
243 readonly cwd: string;
244 readonly host: string;
245 readonly repository: string;
246 readonly number: number;
247 },
248 detail = cli.getMergeRequestDetail(input),
249 ) =>
250 Effect.all(
251 [
252 detail,
253 cli.listMergeRequestStats({ cwd: input.cwd, host: input.host, changeRequests: [input] }),
254 ],
255 {
256 concurrency: 2,
257 },
258 ).pipe(
259 Effect.map(([mergeRequest, [stat]]) =>
260 stat === undefined
261 ? mergeRequest
262 : { ...mergeRequest, additions: stat.additions, deletions: stat.deletions },
263 ),
264 );
265
266 const provider: PullRequestProviderApi = {
267 kind: SourceControlProviderKind.make("gitlab"),
268 capabilities: CAPABILITIES,
269 mergeMessageRewrite: removeAgentCredits,
270 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
271
272 getViewer: (input) => cli.getViewerUsername(input).pipe(Effect.mapError(fail("getViewer"))),
273
274 listChangeRequests: (input) =>
275 Cache.get(graphqlListSupport, JSON.stringify([input.cwd, input.host])).pipe(
276 // Without a known version the REST list still answers, only with fewer filters.
277 Effect.orElseSucceed(() => false),
278 Effect.flatMap((graphql) =>
279 cli.listMergeRequests({
280 cwd: input.cwd,
281 host: input.host,
282 repository: input.repository,
283 state: input.state,
284 involvement: input.involvement,
285 viewer: input.viewer,
286 limit: input.limit,
287 query: input.query,
288 cursor: input.cursor,
289 filters: input.filters,
290 graphql,
291 }),
292 ),
293 Effect.flatMap(({ listStates: carried, ...batch }) =>
294 (carried === undefined
295 ? listStates({
296 cwd: input.cwd,
297 host: input.host,
298 repository: input.repository,
299 numbers: batch.items.map((item) => item.number),
300 })
301 : Effect.succeed(carried)
302 ).pipe(
303 Effect.map((states) => ({
304 ...batch,
305 items: batch.items.map((item) => withListState(item, states)),
306 continues: true,
307 })),
308 ),
309 ),
310 Effect.mapError(fail("listChangeRequests")),
311 ),
312
313 getFileStats: (input) =>
314 cli.getMergeRequestFileStats(input).pipe(Effect.mapError(fail("getFileStats"))),
315
316 listChangeRequestStats: (input) =>
317 cli.listMergeRequestStats(input).pipe(Effect.mapError(fail("listChangeRequestStats"))),
318
319 getChangeRequestChecks: (input) =>
320 mergeRequestDetail(input).pipe(
321 Effect.map(({ state, checks }) => ({ state, checks })),
322 Effect.mapError(fail("getChangeRequestChecks")),
323 ),
324
325 // Merge settings only affect the detail panel's actions.
326 getChangeRequestPreview: (input) =>
327 cli
328 .getMergeRequestDetail({ ...input, maintainerEdits: false })
329 .pipe(Effect.mapError(fail("getChangeRequestPreview"))),
330
331 getChangeRequestSummary: (input) =>
332 Effect.all(
333 [
334 mergeRequestWithStats(
335 input,
336 cli.getMergeRequestDetail({ ...input, maintainerEdits: false }),
337 ),
338 listStates({
339 cwd: input.cwd,
340 host: input.host,
341 repository: input.repository,
342 numbers: [input.number],
343 }),
344 ],
345 { concurrency: 2 },
346 ).pipe(
347 Effect.map(([mergeRequest, states]) => withListState(mergeRequest, states)),
348 Effect.mapError(fail("getChangeRequestSummary")),
349 ),
350
351 getChangeRequest: (input) =>
352 Effect.all(
353 [
354 mergeRequestWithStats(input, mergeRequestDetail(input)),
355 Cache.get(
356 projectMergeCapabilities,
357 JSON.stringify([input.cwd, input.repository, input.host]),
358 ),
359 ],
360 { concurrency: 2 },
361 ).pipe(
362 Effect.mapError(fail("getChangeRequest")),
363 Effect.map(([mergeRequest, mergeCapabilities]): ProviderChangeRequestDetail => ({
364 ...mergeRequest,
365 mergeCapabilities,
366 viewerPermissions: gitLabViewerPermissions(mergeRequest),
367 // Missing divergence counts mean unknown, not up to date.
368 baseComparison:
369 mergeRequest.divergedCommits === undefined
370 ? "unknown"
371 : mergeRequest.divergedCommits > 0
372 ? "behind"
373 : "up-to-date",
374 ...(mergeRequest.divergedCommits === undefined
375 ? {}
376 : { behindBy: mergeRequest.divergedCommits }),
377 })),
378 ),
379
380 getChangeRequestActivity: (input) =>
381 Effect.all(
382 [
383 recoverRead(cli.listNotes(input), { comments: [], truncated: true }),
384 recoverRead(cli.listCommits(input), []),
385 recoverRead(cli.listDiscussions(input), {
386 threads: [],
387 diffRefsByThreadId: new Map(),
388 overviewFindingIds: [],
389 truncated: true,
390 }),
391 recoverRead(cli.listReactions(input), {
392 reactions: [] as ReadonlyArray<PullRequestReaction>,
393 reactionsByNoteId: new Map<string, ReadonlyArray<PullRequestReaction>>(),
394 editedAtByNoteId: new Map<string, string>(),
395 botLogins: new Set<string>(),
396 }),
397 // Fresh, not the cached detail: refs from before a push would mark every thread outdated.
398 recoverRead(
399 cli.getMergeRequestDetail({ ...input, downstreamChecks: false }).pipe(
400 Effect.map((mergeRequest) => ({
401 url: mergeRequest.url,
402 diffRefs: mergeRequest.diffRefs,
403 })),
404 ),
405 null,
406 ),
407 ],
408 { concurrency: 5 },
409 ).pipe(
410 Effect.mapError(fail("getChangeRequestActivity")),
411 Effect.map(
412 ([notes, commits, discussions, awards, detail]): ProviderChangeRequestActivity => {
413 const noteUrl = (id: string) => (detail === null ? null : `${detail.url}#note_${id}`);
414 const findingIds = new Set(discussions.overviewFindingIds);
415 const edited = (id: string) => {
416 const editedAt = awards.editedAtByNoteId.get(id);
417 return editedAt === undefined ? {} : { editedAt };
418 };
419 const botLogins = new Set([...awards.botLogins].map((login) => login.toLowerCase()));
420 const withBotFlag = (author: PullRequestActor | null) =>
421 author !== null && botLogins.has(author.login.toLowerCase())
422 ? { ...author, isBot: true }
423 : author;
424 return {
425 reactions: awards.reactions,
426 comments: notes.comments.map((comment) => ({
427 ...comment,
428 ...(findingIds.has(comment.id) ? { kind: "review-comment" as const } : {}),
429 ...edited(comment.id),
430 author: withBotFlag(comment.author),
431 url: noteUrl(comment.id),
432 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
433 })),
434 commentCount: notes.comments.length,
435 commentsTruncated: notes.truncated || discussions.truncated,
436 reviewThreads: discussions.threads.map((thread) => ({
437 ...thread,
438 isOutdated: isOutdated(
439 discussions.diffRefsByThreadId.get(thread.id),
440 detail?.diffRefs,
441 ),
442 comments: thread.comments.map((comment) => ({
443 ...comment,
444 ...edited(comment.id),
445 author: withBotFlag(comment.author),
446 url: noteUrl(comment.id),
447 reactions: awards.reactionsByNoteId.get(comment.id) ?? [],
448 })),
449 })),
450 commits,
451 };
452 },
453 ),
454 ),
455
456 // Straight from the host, never the shared read: this is what a write is refused or let
457 // through on, and access granted or withdrawn within the minute must count.
458 getViewerPermissions: (input) =>
459 cli
460 .getMergeRequestDetail({ ...input, downstreamChecks: false })
461 .pipe(Effect.mapError(fail("getViewerPermissions")), Effect.map(gitLabViewerPermissions)),
462
463 forgetChangeRequestReads: (scope) =>
464 Cache.keys(mergeRequestDetails).pipe(
465 Effect.flatMap((keys) =>
466 Effect.forEach(
467 Array.from(keys).filter((key) => {
468 if (scope === undefined) return true;
469 const [, repository, number] = JSON.parse(key) as [string, string, number];
470 return (
471 repository.toLowerCase() === scope.repository.toLowerCase() &&
472 (scope.number === undefined || number === scope.number)
473 );
474 }),
475 (key) => Cache.invalidate(mergeRequestDetails, key),
476 { discard: true },
477 ),
478 ),
479 ),
480
481 getDiff: (input) => cli.getMergeRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),
482
483 getDiffFileContents: (input) =>
484 cli.getMergeRequestDiffFileContents(input).pipe(Effect.mapError(fail("getDiffFileContents"))),
485
486 getFileRevisions: (input) =>
487 cli.getFileRevisions(input).pipe(
488 Effect.mapError(fail("getFileRevisions")),
489 Effect.map((revisions) => ({ revisions })),
490 ),
491
492 // MR reviewers are users; groups belong to approval rules.
493 listReviewerCandidates: (input) =>
494 cli
495 .listReviewerCandidates({
496 cwd: input.cwd,
497 host: input.host,
498 repository: input.repository,
499 number: input.number,
500 query: input.query,
501 })
502 .pipe(Effect.mapError(fail("listReviewerCandidates"))),
503
504 listLabelCandidates: (input) =>
505 cli
506 .listLabelCandidates({
507 cwd: input.cwd,
508 host: input.host,
509 repository: input.repository,
510 number: input.number,
511 })
512 .pipe(Effect.mapError(fail("listLabelCandidates"))),
513
514 setLabels: writing((input) =>
515 cli
516 .setLabels({
517 cwd: input.cwd,
518 host: input.host,
519 repository: input.repository,
520 number: input.number,
521 labels: input.labels,
522 applied: input.applied,
523 })
524 .pipe(Effect.mapError(fail("setLabels"))),
525 ),
526
527 listRepositoryLabels: (input) =>
528 cli
529 .listProjectLabels({
530 cwd: input.cwd,
531 host: input.host,
532 repository: input.repository,
533 search: input.query,
534 })
535 .pipe(Effect.mapError(fail("listRepositoryLabels"))),
536
537 searchRepositoryAuthors: (input) =>
538 cli
539 .listProjectUsers({
540 cwd: input.cwd,
541 host: input.host,
542 repository: input.repository,
543 search: input.query,
544 })
545 .pipe(Effect.mapError(fail("searchRepositoryAuthors"))),
546
547 searchRepositoryReferences: (input) =>
548 cli
549 .searchProjectReferences({
550 cwd: input.cwd,
551 host: input.host,
552 repository: input.repository,
553 search: input.query,
554 sigil: input.sigil,
555 })
556 .pipe(Effect.mapError(fail("searchRepositoryReferences"))),
557
558 setReviewerRequest: writing((input) =>
559 cli
560 .setReviewerRequest({
561 cwd: input.cwd,
562 host: input.host,
563 repository: input.repository,
564 number: input.number,
565 reviewers: input.reviewers,
566 requested: input.requested,
567 })
568 .pipe(Effect.mapError(fail("setReviewerRequest"))),
569 ),
570
571 runAction: writing((input) =>
572 cli
573 .runMergeRequestAction({
574 cwd: input.cwd,
575 host: input.host,
576 repository: input.repository,
577 number: input.number,
578 action: input.action,
579 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
580 ...(input.removeAgentCreditsOnMerge === true ? { removeAgentCreditsOnMerge: true } : {}),
581 })
582 .pipe(Effect.mapError(fail("runAction"))),
583 ),
584
585 updateChangeRequest: writing((input) =>
586 cli
587 .updateMergeRequest({
588 cwd: input.cwd,
589 host: input.host,
590 repository: input.repository,
591 number: input.number,
592 ...(input.title === undefined ? {} : { title: input.title }),
593 ...(input.body === undefined ? {} : { description: input.body }),
594 ...(input.maintainerCanModify === undefined
595 ? {}
596 : { allowCollaboration: input.maintainerCanModify }),
597 })
598 .pipe(Effect.mapError(fail("updateChangeRequest"))),
599 ),
600
601 comment: writing((input) =>
602 cli.commentOnMergeRequest(input).pipe(Effect.mapError(fail("comment"))),
603 ),
604
605 updateComment: writing((input) =>
606 cli
607 .updateNote({
608 cwd: input.cwd,
609 host: input.host,
610 repository: input.repository,
611 number: input.number,
612 noteId: input.commentId,
613 body: input.body,
614 })
615 .pipe(Effect.mapError(fail("updateComment"))),
616 ),
617
618 submitReview: writing((input) =>
619 cli.submitReview(input).pipe(Effect.mapError(fail("submitReview"))),
620 ),
621
622 replyToThread: writing((input) =>
623 cli
624 .replyToDiscussion({
625 cwd: input.cwd,
626 host: input.host,
627 repository: input.repository,
628 number: input.number,
629 discussionId: input.threadId,
630 body: input.body,
631 })
632 .pipe(Effect.mapError(fail("replyToThread"))),
633 ),
634
635 setReaction: writing((input) =>
636 cli
637 .setReaction({
638 cwd: input.cwd,
639 host: input.host,
640 repository: input.repository,
641 number: input.number,
642 ...(input.subjectId === undefined ? {} : { noteId: input.subjectId }),
643 content: input.content,
644 reacted: input.reacted,
645 })
646 .pipe(Effect.mapError(fail("setReaction"))),
647 ),
648
649 setThreadResolution: writing((input) =>
650 cli
651 .setDiscussionResolution({
652 cwd: input.cwd,
653 host: input.host,
654 repository: input.repository,
655 number: input.number,
656 discussionId: input.threadId,
657 resolved: input.resolved,
658 })
659 .pipe(Effect.mapError(fail("setThreadResolution"))),
660 ),
661 };
662
663 return provider;
664});
665
666function withListState<Item extends { readonly number: number }>(
667 item: Item,
668 states: ReadonlyMap<number, GitLabMergeRequestListState>,
669): Item & Partial<GitLabMergeRequestListState> {
670 const state = states.get(item.number);
671 return state === undefined ? item : { ...item, ...state };
672}