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