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

GitLabPullRequestProvider.ts

532 lines18.0 KB

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