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 = Effect.fn("AzureDevOpsPullRequestProvider.diffScope")(function* (input: {
180 readonly cwd: string;
181 readonly number: number;
182 }) {
183 const location = yield* locationOf(input);
184 if (location === null) return null;
185 const iterations = yield* cli.listIterations({
186 cwd: input.cwd,
187 location,
188 number: input.number,
189 });
190 return { location, iterations };
191 });
192
193 const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };
194
195 /**
196 * Only the sides a change actually has are asked for: Azure answers for a file that is not at a
197 * commit with a failure rather than with nothing.
198 */
199 const readTexts = (input: {
200 readonly cwd: string;
201 readonly location: AzureDevOpsRepositoryLocation;
202 readonly iteration: AzureDevOpsIteration;
203 readonly change: Pick<AzureDevOpsChangeEntry, "changeKind" | "path" | "oldPath">;
204 }) =>
205 Effect.all(
206 [
207 input.change.changeKind === "new"
208 ? Effect.succeed(EMPTY_ITEM)
209 : readItemContent({
210 cwd: input.cwd,
211 location: input.location,
212 path: input.change.oldPath,
213 commit: input.iteration.mergeBaseCommit,
214 }),
215 input.change.changeKind === "deleted"
216 ? Effect.succeed(EMPTY_ITEM)
217 : readItemContent({
218 cwd: input.cwd,
219 location: input.location,
220 path: input.change.path,
221 commit: input.iteration.headCommit,
222 }),
223 ],
224 { concurrency: 2 },
225 ).pipe(
226 Effect.map(([oldItem, newItem]): AzureDevOpsFileTexts => ({
227 oldContents: oldItem.contents,
228 newContents: newItem.contents,
229 // Azure hands a file it calls binary over in an encoding of its own, so its own word on
230 // that is taken rather than looked for in bytes it may never have sent verbatim.
231 binary: oldItem.isBinary || newItem.isBinary,
232 })),
233 );
234
235 /**
236 * An iteration's changes are reported against the merge base rather than against the push before
237 * it, so the newest one is the whole of the change rather than the last slice of it.
238 */
239 const listLatestChanges = (input: {
240 readonly cwd: string;
241 readonly location: AzureDevOpsRepositoryLocation;
242 readonly number: number;
243 readonly iterations: ReadonlyArray<AzureDevOpsIteration>;
244 }) => {
245 const latest = input.iterations.at(-1);
246 return latest === undefined
247 ? Effect.succeed({
248 changes: [],
249 truncated: false,
250 } as AzureDevOpsPullRequestCli.AzureDevOpsIterationChanges)
251 : cli.listIterationChanges({
252 cwd: input.cwd,
253 location: input.location,
254 number: input.number,
255 iterationId: latest.id,
256 });
257 };
258
259 const provider: PullRequestProviderApi = {
260 kind: SourceControlProviderKind.make("azure-devops"),
261 capabilities: CAPABILITIES,
262 // The bare repository name repeats across an organization; the project path does not.
263 repositoryKey: ({ canonicalKey }) => canonicalKey,
264
265 getViewer: (input) =>
266 cli.getViewer({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
267
268 listChangeRequests: (input) =>
269 cli
270 .listPullRequests({
271 cwd: input.cwd,
272 repository: input.repository,
273 state: input.state,
274 involvement: input.involvement,
275 viewer: input.viewer,
276 limit: input.limit,
277 cursor: input.cursor,
278 })
279 .pipe(
280 Effect.mapError(fail("listChangeRequests")),
281 Effect.map((batch) => ({
282 items: batch.items.map(toChangeRequest),
283 truncated: batch.truncated,
284 cursorAdvance: batch.cursorAdvance,
285 // Azure answers in one order whether or not it is being carried on from, so a slice
286 // can always be stepped past — by counting, which is all Azure offers.
287 continues: true,
288 })),
289 ),
290
291 getChangeRequestSummary: (input) =>
292 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
293 Effect.mapError(fail("getChangeRequestSummary")),
294 Effect.map((pullRequest): ProviderChangeRequestSummary => ({
295 number: pullRequest.number,
296 title: pullRequest.title,
297 url: pullRequest.url,
298 author: pullRequest.author,
299 headBranch: pullRequest.headBranch,
300 baseBranch: pullRequest.baseBranch,
301 state: pullRequest.state,
302 isDraft: pullRequest.isDraft,
303 mergeability: pullRequest.mergeability,
304 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
305 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
306 updatedAt: pullRequest.updatedAt,
307 })),
308 ),
309
310 getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(
311 function* (input) {
312 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
313 const location = pullRequest.location;
314 const iterations =
315 location === null
316 ? []
317 : yield* cli
318 .listIterations({ cwd: input.cwd, location, number: input.number })
319 .pipe(Effect.orElseSucceed(() => []));
320 // The trial merge's lastMergeSourceCommit can lag behind a new source push.
321 const headSha = iterations.at(-1)?.headCommit;
322 const changedFiles =
323 location === null
324 ? 0
325 : yield* listLatestChanges({
326 cwd: input.cwd,
327 location,
328 number: input.number,
329 iterations,
330 }).pipe(
331 Effect.map((listed) => listed.changes.length),
332 Effect.orElseSucceed(() => 0),
333 );
334 const detail: ProviderChangeRequestDetail = {
335 ...toChangeRequest(pullRequest),
336 body: pullRequest.body,
337 ...(headSha === undefined ? {} : { headSha }),
338 changedFiles,
339 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
340 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
341 reviewers: pullRequest.reviewers,
342 checks: [],
343 mergeCapabilities: { merge: true, squash: true, rebase: false },
344 viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
345 autoMergeEnabled: pullRequest.autoMergeEnabled,
346 ...(pullRequest.autoMergeMethod === undefined
347 ? {}
348 : { autoMergeMethod: pullRequest.autoMergeMethod }),
349 };
350 return detail;
351 },
352 Effect.mapError(fail("getChangeRequest")),
353 ),
354
355 getChangeRequestActivity: (input) =>
356 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
357 Effect.mapError(fail("getChangeRequestActivity")),
358 Effect.flatMap((pullRequest) =>
359 (pullRequest.location === null
360 ? Effect.succeed({ comments: [], truncated: true })
361 : cli
362 .listThreads({
363 cwd: input.cwd,
364 location: pullRequest.location,
365 number: input.number,
366 })
367 .pipe(
368 Effect.map((comments) => ({ comments, truncated: false })),
369 Effect.orElseSucceed(() => ({ comments: [], truncated: true })),
370 )
371 ).pipe(
372 Effect.map((conversation): ProviderChangeRequestActivity => ({
373 comments: conversation.comments,
374 commentCount: conversation.comments.length,
375 commentsTruncated: conversation.truncated,
376 reviewThreads: [],
377 commits: [],
378 })),
379 ),
380 ),
381 ),
382
383 getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),
384
385 // `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so
386 // the Code tab has nothing to scope itself to and always asks for the whole change.
387 getDiff: Effect.fn("AzureDevOpsPullRequestProvider.getDiff")(
388 function* (input) {
389 const scope = yield* diffScope(input);
390 if (scope === null) return EMPTY_DIFF_SLICE;
391 const cursor = parseAzureDevOpsDiffCursor(input.cursor);
392 // Reading on stays with the push the first slice was taken against. A push landing
393 // mid-read would otherwise renumber the files and hand the reader one twice, or none.
394 const iteration =
395 cursor === null
396 ? scope.iterations.at(-1)
397 : scope.iterations.find((candidate) => candidate.id === cursor.iterationId);
398 if (iteration === undefined) return EMPTY_DIFF_SLICE;
399 const listed = yield* cli.listIterationChanges({
400 cwd: input.cwd,
401 location: scope.location,
402 number: input.number,
403 iterationId: iteration.id,
404 });
405 const changes = listed.changes;
406
407 const sections: string[] = [];
408 let truncated = listed.truncated;
409 let bytes = 0;
410 let edits = 0;
411 let index = cursor?.fileIndex ?? 0;
412 let full = false;
413 // Every file costs a request a side, and everything read past the point the slice fills is
414 // thrown away and read again by the next slice, so the batch narrows as the budgets do:
415 // what is left of each, over what a file has spent of it on average so far, which is the
416 // only estimate there is before a file is read.
417 const batchWidth = () => {
418 if (sections.length === 0) return DIFF_FILE_CONCURRENCY;
419 const admits = (left: number, spent: number) =>
420 Math.ceil(left / Math.max(1, spent / sections.length));
421 return Math.max(
422 1,
423 Math.min(
424 DIFF_FILE_CONCURRENCY,
425 MAX_DIFF_SLICE_FILES - sections.length,
426 admits(MAX_DIFF_SLICE_BYTES - bytes, bytes),
427 admits(MAX_DIFF_SLICE_EDITS - MAX_FILE_DIFF_EDITS - edits, edits),
428 ),
429 );
430 };
431 while (!full && index < changes.length) {
432 const batch = changes.slice(index, index + batchWidth());
433 const read = yield* Effect.forEach(
434 batch,
435 (change) =>
436 readTexts({ cwd: input.cwd, location: scope.location, iteration, change }).pipe(
437 // Only what is this one file's problem. A signed-out CLI, a rate limit or no `az`
438 // at all is the read failing rather than the file, and belongs to the caller,
439 // which pauses the host rather than showing every file as unreadable.
440 Effect.catchTags({
441 AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(null),
442 AzureDevOpsCommandFailedError: () => Effect.succeed(null),
443 AzureDevOpsPullRequestReadError: () => Effect.succeed(null),
444 }),
445 Effect.map((texts) => ({ change, texts })),
446 ),
447 { concurrency: DIFF_FILE_CONCURRENCY },
448 );
449 for (const { change, texts } of read) {
450 // The diff is synchronous and the reads no longer stand between one file and the next
451 // to let anything else on the server run, so the thread is handed back here.
452 yield* Effect.yieldNow;
453 const file =
454 texts === null
455 ? azureDevOpsUnreadableFilePatch(change)
456 : azureDevOpsFilePatch({ change, texts });
457 sections.push(file.section);
458 bytes += byteLength(file.section);
459 edits += file.edits;
460 truncated = truncated || file.truncated;
461 index += 1;
462 // Checked after the file is added rather than before it, so every slice carries at
463 // least one: a section heavier than the whole budget would otherwise never be added,
464 // and the read would answer the same slice forever without moving the cursor.
465 if (
466 bytes >= MAX_DIFF_SLICE_BYTES ||
467 edits + MAX_FILE_DIFF_EDITS > MAX_DIFF_SLICE_EDITS ||
468 sections.length >= MAX_DIFF_SLICE_FILES ||
469 file.abandoned
470 ) {
471 full = true;
472 break;
473 }
474 }
475 }
476
477 const slice: ProviderDiffSlice = {
478 patch: sections.join(""),
479 truncated,
480 nextCursor:
481 index >= changes.length
482 ? null
483 : formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),
484 };
485 return slice;
486 },
487 Effect.mapError(fail("getDiff")),
488 ),
489
490 getDiffFileContents: Effect.fn("AzureDevOpsPullRequestProvider.getDiffFileContents")(
491 function* (input) {
492 const scope = yield* diffScope(input);
493 const iteration = scope?.iterations.at(-1);
494 if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };
495 return yield* readTexts({
496 cwd: input.cwd,
497 location: scope.location,
498 iteration,
499 change: {
500 changeKind: input.changeType,
501 path: input.newPath,
502 oldPath: input.oldPath,
503 },
504 });
505 },
506 Effect.mapError(fail("getDiffFileContents")),
507 ),
508
509 /**
510 * A path the change does not carry is at the empty revision, which is where a file the pull
511 * request deletes sits. When the change was too long to follow to its end, those paths are left
512 * out instead: reporting them as deleted would clear a file nobody has read.
513 */
514 getFileRevisions: Effect.fn("AzureDevOpsPullRequestProvider.getFileRevisions")(
515 function* (input) {
516 const revisions = new Map<string, string>();
517 if (input.paths.length === 0) return { revisions };
518 const scope = yield* diffScope(input);
519 if (scope === null) return { revisions };
520 const listed = yield* listLatestChanges({
521 ...scope,
522 cwd: input.cwd,
523 number: input.number,
524 });
525 const marked = new Set(input.paths);
526 for (const change of listed.changes) {
527 if (!marked.has(change.path) || change.objectId === null) continue;
528 revisions.set(change.path, change.objectId);
529 }
530 if (!listed.truncated) {
531 for (const path of input.paths) {
532 if (!revisions.has(path)) revisions.set(path, "");
533 }
534 }
535 return { revisions };
536 },
537 Effect.mapError(fail("getFileRevisions")),
538 ),
539
540 runAction: (input) =>
541 cli
542 .runPullRequestAction({
543 cwd: input.cwd,
544 number: input.number,
545 action: input.action,
546 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
547 })
548 .pipe(Effect.mapError(fail("runAction"))),
549
550 updateChangeRequest: (input) =>
551 cli
552 .updatePullRequest({
553 cwd: input.cwd,
554 number: input.number,
555 title: input.title,
556 body: input.body,
557 })
558 .pipe(Effect.mapError(fail("updateChangeRequest"))),
559
560 listReviewerCandidates: () =>
561 Effect.fail(
562 new PullRequestProviderError({
563 provider: SourceControlProviderKind.make("azure-devops"),
564 operation: "listReviewerCandidates",
565 reason: "failed",
566 detail: "Azure DevOps cannot say who may review a pull request.",
567 }),
568 ),
569
570 setReviewerRequest: (input) =>
571 cli
572 .setPullRequestReviewers({
573 cwd: input.cwd,
574 number: input.number,
575 reviewers: input.reviewers.map((reviewer) => reviewer.id),
576 requested: input.requested,
577 })
578 .pipe(Effect.mapError(fail("setReviewerRequest"))),
579
580 comment: () => unsupported("comment"),
581
582 submitReview: () => unsupported("submitReview"),
583
584 replyToThread: () => unsupported("replyToThread"),
585
586 setThreadResolution: () => unsupported("setThreadResolution"),
587
588 setReaction: () => unsupported("setReaction"),
589 };
590
591 return provider;
592});