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