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