Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Semaphore from "effect/Semaphore";
4import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
5
6import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
7import {
8 azureDevOpsFilePatch,
9 azureDevOpsUnreadableFilePatch,
10 formatAzureDevOpsDiffCursor,
11 parseAzureDevOpsDiffCursor,
12 MAX_DIFF_SLICE_BYTES,
13 MAX_DIFF_SLICE_EDITS,
14 MAX_DIFF_SLICE_FILES,
15 byteLength,
16 MAX_FILE_DIFF_EDITS,
17 type AzureDevOpsFileTexts,
18} from "./azureDevOpsDiff.ts";
19import {
20 PullRequestProviderError,
21 type PullRequestProviderFailure,
22 type ProviderChangeRequest,
23 type ProviderChangeRequestActivity,
24 type ProviderChangeRequestDetail,
25 type ProviderChangeRequestSummary,
26 type ProviderDiffSlice,
27 type PullRequestProviderApi,
28} from "@t3tools/source-control-core/server/PullRequestProvider";
29import type {
30 AzureDevOpsChangeEntry,
31 AzureDevOpsItemContent,
32 AzureDevOpsIteration,
33 AzureDevOpsPullRequest,
34 AzureDevOpsRepositoryLocation,
35} from "./azureDevOpsPullRequestJson.ts";
36import { definition } from "../client/definition.ts";
37
38/**
39 * Every file is two `az` invocations, each paying a Python interpreter's start-up, so reading them
40 * one after another is most of what the Code tab waits for.
41 */
42const DIFF_FILE_CONCURRENCY = 4;
43
44/**
45 * How many `az` processes this build will have out at once, counted across every reader rather than
46 * per request. Held at what one request at full width spends, so a second reader waits behind the
47 * first instead of adding to it.
48 */
49export const MAX_DIFF_SPAWNS = 2 * DIFF_FILE_CONCURRENCY;
50
51export const LOCATION_CACHE_CAPACITY = 128;
52
53const CAPABILITIES: PullRequestCapabilities = {
54 diff: true,
55 comment: false,
56 actions: [...definition.changeRequestActions],
57 // Azure squashes as a completion option; it has no rebase strategy of its own.
58 mergeMethods: ["merge", "squash"],
59 // `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.
60 search: false,
61 reactions: false,
62 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
63 // `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`
64 // lists the ones this repository could name — that lives behind the identity and graph APIs, a
65 // different service with its own permissions.
66 reviewers: { request: true, listCandidates: false },
67 edit: { changeRequest: true, comment: false },
68 // Azure does keep a viewed record of its own, but only behind the undocumented contribution
69 // endpoint its web UI talks to, keyed on an iteration so a push would drop every mark anyway.
70 viewedFiles: "environment",
71};
72
73/**
74 * Azure DevOps states no permission anywhere `az repos pr show` or `az repos pr list` reach: the
75 * answer lives in the security namespaces, behind identity descriptors and token paths that would
76 * be several calls per pull request to resolve.
77 */
78const AZURE_DEVOPS_VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
79 actions: CAPABILITIES.actions,
80 comment: CAPABILITIES.comment,
81 resolve: CAPABILITIES.review.resolve,
82 verdicts: CAPABILITIES.review.verdicts,
83 requestReviewers: CAPABILITIES.reviewers.request,
84};
85
86export function azureDevOpsProviderFailure(
87 error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError,
88): PullRequestProviderFailure {
89 if (error._tag === "AzureDevOpsCliUnavailableError") return { reason: "missing-tool" };
90 if (error._tag === "AzureDevOpsCliAuthenticationError") return { reason: "unauthenticated" };
91 if (error._tag === "AzureDevOpsCliRateLimitError") return { reason: "rate-limited" };
92 if (error._tag === "AzureDevOpsPullRequestNotFoundError") return { reason: "not-found" };
93 return { reason: "failed" };
94}
95
96function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequest {
97 return {
98 number: pullRequest.number,
99 title: pullRequest.title,
100 url: pullRequest.url,
101 author: pullRequest.author,
102 headBranch: pullRequest.headBranch,
103 baseBranch: pullRequest.baseBranch,
104 state: pullRequest.state,
105 isDraft: pullRequest.isDraft,
106 mergeability: pullRequest.mergeability,
107 // Azure counts a pull request's files but never its lines, and counting them here would mean
108 // reading every file on both sides of every row of a listing.
109 additions: 0,
110 deletions: 0,
111 createdAt: pullRequest.createdAt,
112 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
113 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
114 updatedAt: pullRequest.updatedAt,
115 reviewRequestLogins: pullRequest.reviewRequestLogins,
116 // Azure keeps labels on work items rather than on the pull request.
117 labels: [],
118 };
119}
120
121export const make = Effect.gen(function* () {
122 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
123 const diffSpawns = yield* Semaphore.make(MAX_DIFF_SPAWNS);
124 const readItemContent = (input: Parameters<typeof cli.readItemContent>[0]) =>
125 diffSpawns.withPermits(1)(cli.readItemContent(input));
126
127 const fail =
128 (operation: string) => (error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError) =>
129 new PullRequestProviderError({
130 provider: SourceControlProviderKind.make("azure-devops"),
131 operation,
132 ...azureDevOpsProviderFailure(error),
133 detail: error.detail,
134 cause: error,
135 });
136
137 const unsupported = (operation: string) =>
138 Effect.fail(
139 new PullRequestProviderError({
140 provider: SourceControlProviderKind.make("azure-devops"),
141 operation,
142 reason: "failed",
143 detail: "Azure DevOps reviews cannot be written from here yet.",
144 }),
145 );
146
147 const EMPTY_DIFF_SLICE: ProviderDiffSlice = { patch: "", truncated: false, nextCursor: null };
148
149 /**
150 * A pull request cannot move between repositories, so it is remembered rather than re-read: the
151 * marks alone would otherwise pay for a whole pull request read every time they checked whether a
152 * file had been pushed to. Least recently used, so a listing walking cold pull requests cannot
153 * evict the one being read.
154 */
155 const locations = new Map<string, AzureDevOpsRepositoryLocation>();
156
157 const locationOf = (input: { readonly cwd: string; readonly number: number }) => {
158 const key = `${input.cwd} ${input.number}`;
159 const held = locations.get(key);
160 if (held !== undefined) {
161 locations.delete(key);
162 locations.set(key, held);
163 return Effect.succeed(held);
164 }
165 return cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
166 Effect.map((pullRequest) => {
167 const location = pullRequest.location;
168 if (location === null) return null;
169 if (locations.size >= LOCATION_CACHE_CAPACITY) {
170 const oldest = locations.keys().next().value;
171 if (oldest !== undefined) locations.delete(oldest);
172 }
173 locations.set(key, location);
174 return location;
175 }),
176 );
177 };
178
179 const diffScope = (input: { readonly cwd: string; readonly number: number }) =>
180 Effect.gen(function* () {
181 const location = yield* locationOf(input);
182 if (location === null) return null;
183 const iterations = yield* cli.listIterations({
184 cwd: input.cwd,
185 location,
186 number: input.number,
187 });
188 return { location, iterations };
189 });
190
191 const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };
192
193 /**
194 * Only the sides a change actually has are asked for: Azure answers for a file that is not at a
195 * commit with a failure rather than with nothing.
196 */
197 const readTexts = (input: {
198 readonly cwd: string;
199 readonly location: AzureDevOpsRepositoryLocation;
200 readonly iteration: AzureDevOpsIteration;
201 readonly change: Pick<AzureDevOpsChangeEntry, "changeKind" | "path" | "oldPath">;
202 }) =>
203 Effect.all(
204 [
205 input.change.changeKind === "new"
206 ? Effect.succeed(EMPTY_ITEM)
207 : readItemContent({
208 cwd: input.cwd,
209 location: input.location,
210 path: input.change.oldPath,
211 commit: input.iteration.mergeBaseCommit,
212 }),
213 input.change.changeKind === "deleted"
214 ? Effect.succeed(EMPTY_ITEM)
215 : readItemContent({
216 cwd: input.cwd,
217 location: input.location,
218 path: input.change.path,
219 commit: input.iteration.headCommit,
220 }),
221 ],
222 { concurrency: 2 },
223 ).pipe(
224 Effect.map(([oldItem, newItem]): AzureDevOpsFileTexts => ({
225 oldContents: oldItem.contents,
226 newContents: newItem.contents,
227 // Azure hands a file it calls binary over in an encoding of its own, so its own word on
228 // that is taken rather than looked for in bytes it may never have sent verbatim.
229 binary: oldItem.isBinary || newItem.isBinary,
230 })),
231 );
232
233 /**
234 * An iteration's changes are reported against the merge base rather than against the push before
235 * it, so the newest one is the whole of the change rather than the last slice of it.
236 */
237 const listLatestChanges = (input: {
238 readonly cwd: string;
239 readonly location: AzureDevOpsRepositoryLocation;
240 readonly number: number;
241 readonly iterations: ReadonlyArray<AzureDevOpsIteration>;
242 }) => {
243 const latest = input.iterations.at(-1);
244 return latest === undefined
245 ? Effect.succeed({
246 changes: [],
247 truncated: false,
248 } as AzureDevOpsPullRequestCli.AzureDevOpsIterationChanges)
249 : cli.listIterationChanges({
250 cwd: input.cwd,
251 location: input.location,
252 number: input.number,
253 iterationId: latest.id,
254 });
255 };
256
257 const provider: PullRequestProviderApi = {
258 kind: SourceControlProviderKind.make("azure-devops"),
259 capabilities: CAPABILITIES,
260 // The bare repository name repeats across an organization; the project path does not.
261 repositoryKey: ({ canonicalKey }) => canonicalKey,
262
263 getViewer: (input) =>
264 cli.getViewer({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
265
266 listChangeRequests: (input) =>
267 cli
268 .listPullRequests({
269 cwd: input.cwd,
270 repository: input.repository,
271 state: input.state,
272 involvement: input.involvement,
273 viewer: input.viewer,
274 limit: input.limit,
275 cursor: input.cursor,
276 })
277 .pipe(
278 Effect.mapError(fail("listChangeRequests")),
279 Effect.map((batch) => ({
280 items: batch.items.map(toChangeRequest),
281 truncated: batch.truncated,
282 cursorAdvance: batch.cursorAdvance,
283 // Azure answers in one order whether or not it is being carried on from, so a slice
284 // can always be stepped past — by counting, which is all Azure offers.
285 continues: true,
286 })),
287 ),
288
289 getChangeRequestSummary: (input) =>
290 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
291 Effect.mapError(fail("getChangeRequestSummary")),
292 Effect.map((pullRequest): ProviderChangeRequestSummary => ({
293 number: pullRequest.number,
294 title: pullRequest.title,
295 url: pullRequest.url,
296 author: pullRequest.author,
297 headBranch: pullRequest.headBranch,
298 baseBranch: pullRequest.baseBranch,
299 state: pullRequest.state,
300 isDraft: pullRequest.isDraft,
301 mergeability: pullRequest.mergeability,
302 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
303 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
304 updatedAt: pullRequest.updatedAt,
305 })),
306 ),
307
308 getChangeRequest: (input) =>
309 Effect.gen(function* () {
310 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
311 const location = pullRequest.location;
312 const changedFiles =
313 location === null
314 ? 0
315 : yield* cli.listIterations({ cwd: input.cwd, location, number: input.number }).pipe(
316 Effect.flatMap((iterations) =>
317 listLatestChanges({
318 cwd: input.cwd,
319 location,
320 number: input.number,
321 iterations,
322 }),
323 ),
324 Effect.map((listed) => listed.changes.length),
325 Effect.orElseSucceed(() => 0),
326 );
327 const detail: ProviderChangeRequestDetail = {
328 ...toChangeRequest(pullRequest),
329 body: pullRequest.body,
330 changedFiles,
331 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
332 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
333 reviewers: pullRequest.reviewers,
334 checks: [],
335 mergeCapabilities: { merge: true, squash: true, rebase: false },
336 viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
337 autoMergeEnabled: pullRequest.autoMergeEnabled,
338 ...(pullRequest.autoMergeMethod === undefined
339 ? {}
340 : { autoMergeMethod: pullRequest.autoMergeMethod }),
341 };
342 return detail;
343 }).pipe(Effect.mapError(fail("getChangeRequest"))),
344
345 getChangeRequestActivity: (input) =>
346 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
347 Effect.mapError(fail("getChangeRequestActivity")),
348 Effect.flatMap((pullRequest) =>
349 (pullRequest.location === null
350 ? Effect.succeed({ comments: [], truncated: true })
351 : cli
352 .listThreads({
353 cwd: input.cwd,
354 location: pullRequest.location,
355 number: input.number,
356 })
357 .pipe(
358 Effect.map((comments) => ({ comments, truncated: false })),
359 Effect.orElseSucceed(() => ({ comments: [], truncated: true })),
360 )
361 ).pipe(
362 Effect.map((conversation): ProviderChangeRequestActivity => ({
363 comments: conversation.comments,
364 commentCount: conversation.comments.length,
365 commentsTruncated: conversation.truncated,
366 reviewThreads: [],
367 commits: [],
368 })),
369 ),
370 ),
371 ),
372
373 getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),
374
375 // `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so
376 // the Code tab has nothing to scope itself to and always asks for the whole change.
377 getDiff: (input) =>
378 Effect.gen(function* () {
379 const scope = yield* diffScope(input);
380 if (scope === null) return EMPTY_DIFF_SLICE;
381 const cursor = parseAzureDevOpsDiffCursor(input.cursor);
382 // Reading on stays with the push the first slice was taken against. A push landing
383 // mid-read would otherwise renumber the files and hand the reader one twice, or none.
384 const iteration =
385 cursor === null
386 ? scope.iterations.at(-1)
387 : scope.iterations.find((candidate) => candidate.id === cursor.iterationId);
388 if (iteration === undefined) return EMPTY_DIFF_SLICE;
389 const listed = yield* cli.listIterationChanges({
390 cwd: input.cwd,
391 location: scope.location,
392 number: input.number,
393 iterationId: iteration.id,
394 });
395 const changes = listed.changes;
396
397 const sections: string[] = [];
398 let truncated = listed.truncated;
399 let bytes = 0;
400 let edits = 0;
401 let index = cursor?.fileIndex ?? 0;
402 let full = false;
403 // Every file costs a request a side, and everything read past the point the slice fills is
404 // thrown away and read again by the next slice, so the batch narrows as the budgets do:
405 // what is left of each, over what a file has spent of it on average so far, which is the
406 // only estimate there is before a file is read.
407 const batchWidth = () => {
408 if (sections.length === 0) return DIFF_FILE_CONCURRENCY;
409 const admits = (left: number, spent: number) =>
410 Math.ceil(left / Math.max(1, spent / sections.length));
411 return Math.max(
412 1,
413 Math.min(
414 DIFF_FILE_CONCURRENCY,
415 MAX_DIFF_SLICE_FILES - sections.length,
416 admits(MAX_DIFF_SLICE_BYTES - bytes, bytes),
417 admits(MAX_DIFF_SLICE_EDITS - MAX_FILE_DIFF_EDITS - edits, edits),
418 ),
419 );
420 };
421 while (!full && index < changes.length) {
422 const batch = changes.slice(index, index + batchWidth());
423 const read = yield* Effect.forEach(
424 batch,
425 (change) =>
426 readTexts({ cwd: input.cwd, location: scope.location, iteration, change }).pipe(
427 // Only what is this one file's problem. A signed-out CLI, a rate limit or no `az`
428 // at all is the read failing rather than the file, and belongs to the caller,
429 // which pauses the host rather than showing every file as unreadable.
430 Effect.catchTags({
431 AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(null),
432 AzureDevOpsCommandFailedError: () => Effect.succeed(null),
433 AzureDevOpsPullRequestReadError: () => Effect.succeed(null),
434 }),
435 Effect.map((texts) => ({ change, texts })),
436 ),
437 { concurrency: DIFF_FILE_CONCURRENCY },
438 );
439 for (const { change, texts } of read) {
440 // The diff is synchronous and the reads no longer stand between one file and the next
441 // to let anything else on the server run, so the thread is handed back here.
442 yield* Effect.yieldNow;
443 const file =
444 texts === null
445 ? azureDevOpsUnreadableFilePatch(change)
446 : azureDevOpsFilePatch({ change, texts });
447 sections.push(file.section);
448 bytes += byteLength(file.section);
449 edits += file.edits;
450 truncated = truncated || file.truncated;
451 index += 1;
452 // Checked after the file is added rather than before it, so every slice carries at
453 // least one: a section heavier than the whole budget would otherwise never be added,
454 // and the read would answer the same slice forever without moving the cursor.
455 if (
456 bytes >= MAX_DIFF_SLICE_BYTES ||
457 edits + MAX_FILE_DIFF_EDITS > MAX_DIFF_SLICE_EDITS ||
458 sections.length >= MAX_DIFF_SLICE_FILES ||
459 file.abandoned
460 ) {
461 full = true;
462 break;
463 }
464 }
465 }
466
467 const slice: ProviderDiffSlice = {
468 patch: sections.join(""),
469 truncated,
470 nextCursor:
471 index >= changes.length
472 ? null
473 : formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),
474 };
475 return slice;
476 }).pipe(Effect.mapError(fail("getDiff"))),
477
478 getDiffFileContents: (input) =>
479 Effect.gen(function* () {
480 const scope = yield* diffScope(input);
481 const iteration = scope?.iterations.at(-1);
482 if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };
483 return yield* readTexts({
484 cwd: input.cwd,
485 location: scope.location,
486 iteration,
487 change: {
488 changeKind: input.changeType,
489 path: input.newPath,
490 oldPath: input.oldPath,
491 },
492 });
493 }).pipe(Effect.mapError(fail("getDiffFileContents"))),
494
495 /**
496 * A path the change does not carry is at the empty revision, which is where a file the pull
497 * request deletes sits. When the change was too long to follow to its end, those paths are left
498 * out instead: reporting them as deleted would clear a file nobody has read.
499 */
500 getFileRevisions: (input) =>
501 Effect.gen(function* () {
502 const revisions = new Map<string, string>();
503 if (input.paths.length === 0) return { revisions };
504 const scope = yield* diffScope(input);
505 if (scope === null) return { revisions };
506 const listed = yield* listLatestChanges({
507 ...scope,
508 cwd: input.cwd,
509 number: input.number,
510 });
511 const marked = new Set(input.paths);
512 for (const change of listed.changes) {
513 if (!marked.has(change.path) || change.objectId === null) continue;
514 revisions.set(change.path, change.objectId);
515 }
516 if (!listed.truncated) {
517 for (const path of input.paths) {
518 if (!revisions.has(path)) revisions.set(path, "");
519 }
520 }
521 return { revisions };
522 }).pipe(Effect.mapError(fail("getFileRevisions"))),
523
524 runAction: (input) =>
525 cli
526 .runPullRequestAction({
527 cwd: input.cwd,
528 number: input.number,
529 action: input.action,
530 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
531 })
532 .pipe(Effect.mapError(fail("runAction"))),
533
534 updateChangeRequest: (input) =>
535 cli
536 .updatePullRequest({
537 cwd: input.cwd,
538 number: input.number,
539 title: input.title,
540 body: input.body,
541 })
542 .pipe(Effect.mapError(fail("updateChangeRequest"))),
543
544 listReviewerCandidates: () =>
545 Effect.fail(
546 new PullRequestProviderError({
547 provider: SourceControlProviderKind.make("azure-devops"),
548 operation: "listReviewerCandidates",
549 reason: "failed",
550 detail: "Azure DevOps cannot say who may review a pull request.",
551 }),
552 ),
553
554 setReviewerRequest: (input) =>
555 cli
556 .setPullRequestReviewers({
557 cwd: input.cwd,
558 number: input.number,
559 reviewers: input.reviewers.map((reviewer) => reviewer.id),
560 requested: input.requested,
561 })
562 .pipe(Effect.mapError(fail("setReviewerRequest"))),
563
564 comment: () => unsupported("comment"),
565
566 submitReview: () => unsupported("submitReview"),
567
568 replyToThread: () => unsupported("replyToThread"),
569
570 setThreadResolution: () => unsupported("setThreadResolution"),
571
572 setReaction: () => unsupported("setReaction"),
573 };
574
575 return provider;
576});