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

AzureDevOpsPullRequestProvider.ts

582 lines21.2 KB

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 "../shared/definition.ts";
37​
38/** Each file pays for two Python startups. */
39const DIFF_FILE_CONCURRENCY = 4;
40​
41/** Readers share a spawn budget across requests. */
42export const MAX_DIFF_SPAWNS = 2 * DIFF_FILE_CONCURRENCY;
43​
44export const LOCATION_CACHE_CAPACITY = 128;
45​
46const CAPABILITIES: PullRequestCapabilities = {
47 diff: true,
48 comment: false,
49 actions: [...definition.changeRequestActions],
50 // Azure has no rebase strategy.
51 mergeMethods: ["merge", "squash"],
52 // `az repos pr list` has no text filter.
53 search: false,
54 reactions: false,
55 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
56 // Reviewer candidates require separate identity/graph APIs and permissions.
57 reviewers: { request: true, listCandidates: false },
58 edit: { changeRequest: true, comment: false },
59 // Azure's viewed marks use an undocumented endpoint and are invalidated by each push.
60 viewedFiles: "environment",
61};
62​
63const UNAVAILABLE_REQUIREMENT = {
64 missing:
65 "Azure CLI (`az`) with the Azure DevOps extension is required. Install `az`, then run `az extension add --name azure-devops`.",
66 unauthenticated: "Azure CLI is not signed in. Run `az login` and retry.",
67};
68​
69/**
70 * Azure DevOps states no permission anywhere `az repos pr show` or `az repos pr list` reach: the
71 * answer lives in the security namespaces, behind identity descriptors and token paths that would
72 * be several calls per pull request to resolve.
73 */
74const AZURE_DEVOPS_VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
75 actions: CAPABILITIES.actions,
76 comment: CAPABILITIES.comment,
77 resolve: CAPABILITIES.review.resolve,
78 verdicts: CAPABILITIES.review.verdicts,
79 requestReviewers: CAPABILITIES.reviewers.request,
80};
81​
82function azureDevOpsProviderFailure(
83 error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError,
84): PullRequestProviderFailure {
85 if (error._tag === "AzureDevOpsCliUnavailableError") return { reason: "missing-tool" };
86 if (error._tag === "AzureDevOpsCliAuthenticationError") return { reason: "unauthenticated" };
87 if (error._tag === "AzureDevOpsCliRateLimitError") return { reason: "rate-limited" };
88 if (error._tag === "AzureDevOpsPullRequestNotFoundError") return { reason: "not-found" };
89 return { reason: "failed" };
91​
92function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequest {
93 return {
94 number: pullRequest.number,
95 title: pullRequest.title,
96 url: pullRequest.url,
97 author: pullRequest.author,
98 headBranch: pullRequest.headBranch,
99 baseBranch: pullRequest.baseBranch,
100 state: pullRequest.state,
101 isDraft: pullRequest.isDraft,
102 mergeability: pullRequest.mergeability,
103 // Azure omits line counts; computing them requires both sides of every file.
104 additions: 0,
105 deletions: 0,
106 createdAt: pullRequest.createdAt,
107 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
108 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
109 updatedAt: pullRequest.updatedAt,
110 reviewRequestLogins: pullRequest.reviewRequestLogins,
111 // Azure keeps labels on work items rather than on the pull request.
112 labels: [],
113 };
115​
116export const make = Effect.gen(function* () {
117 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
118 const diffSpawns = yield* Semaphore.make(MAX_DIFF_SPAWNS);
119 const readItemContent = (input: Parameters<typeof cli.readItemContent>[0]) =>
120 diffSpawns.withPermits(1)(cli.readItemContent(input));
121​
122 const fail =
123 (operation: string) => (error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError) =>
124 new PullRequestProviderError({
125 provider: SourceControlProviderKind.make("azure-devops"),
126 operation,
127 ...azureDevOpsProviderFailure(error),
128 detail: error.detail,
129 cause: error,
130 });
131​
132 const unsupported = (operation: string) =>
133 Effect.fail(
134 new PullRequestProviderError({
135 provider: SourceControlProviderKind.make("azure-devops"),
136 operation,
137 reason: "failed",
138 detail: "Azure DevOps reviews cannot be written from here yet.",
139 }),
140 );
141​
142 const EMPTY_DIFF_SLICE: ProviderDiffSlice = { patch: "", truncated: false, nextCursor: null };
143​
144 // PR locations are immutable; caching avoids full PR reads for viewed-file checks.
145 const locations = new Map<string, AzureDevOpsRepositoryLocation>();
146​
147 const locationOf = (input: { readonly cwd: string; readonly number: number }) => {
148 const key = `${input.cwd} ${input.number}`;
149 const held = locations.get(key);
150 if (held !== undefined) {
151 locations.delete(key);
152 locations.set(key, held);
153 return Effect.succeed(held);
154 }
155 return cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
156 Effect.map((pullRequest) => {
157 const location = pullRequest.location;
158 if (location === null) return null;
159 if (locations.size >= LOCATION_CACHE_CAPACITY) {
160 const oldest = locations.keys().next().value;
161 if (oldest !== undefined) locations.delete(oldest);
162 }
163 locations.set(key, location);
164 return location;
165 }),
166 );
167 };
168​
169 const diffScope = Effect.fn("AzureDevOpsPullRequestProvider.diffScope")(function* (input: {
170 readonly cwd: string;
171 readonly number: number;
172 }) {
173 const location = yield* locationOf(input);
174 if (location === null) return null;
175 const iterations = yield* cli.listIterations({
176 cwd: input.cwd,
177 location,
178 number: input.number,
179 });
180 return { location, iterations };
181 });
182​
183 const EMPTY_ITEM: AzureDevOpsItemContent = { contents: "", isBinary: false };
184​
185 /** Azure fails reads of absent files. */
186 const readTexts = (input: {
187 readonly cwd: string;
188 readonly location: AzureDevOpsRepositoryLocation;
189 readonly iteration: AzureDevOpsIteration;
190 readonly change: Pick<AzureDevOpsChangeEntry, "changeKind" | "path" | "oldPath">;
191 }) =>
192 Effect.all(
193 [
194 input.change.changeKind === "new"
195 ? Effect.succeed(EMPTY_ITEM)
196 : readItemContent({
197 cwd: input.cwd,
198 location: input.location,
199 path: input.change.oldPath,
200 commit: input.iteration.mergeBaseCommit,
201 }),
202 input.change.changeKind === "deleted"
203 ? Effect.succeed(EMPTY_ITEM)
204 : readItemContent({
205 cwd: input.cwd,
206 location: input.location,
207 path: input.change.path,
208 commit: input.iteration.headCommit,
209 }),
210 ],
211 { concurrency: 2 },
212 ).pipe(
213 Effect.map(([oldItem, newItem]): AzureDevOpsFileTexts => ({
214 oldContents: oldItem.contents,
215 newContents: newItem.contents,
216 // Encoded bytes cannot identify binaries; trust Azure's metadata.
217 binary: oldItem.isBinary || newItem.isBinary,
218 })),
219 );
220​
221 const listLatestChanges = (input: {
222 readonly cwd: string;
223 readonly location: AzureDevOpsRepositoryLocation;
224 readonly number: number;
225 readonly iterations: ReadonlyArray<AzureDevOpsIteration>;
226 }) => {
227 const latest = input.iterations.at(-1);
228 return latest === undefined
229 ? Effect.succeed({
230 changes: [],
231 truncated: false,
232 } as AzureDevOpsPullRequestCli.AzureDevOpsIterationChanges)
233 : cli.listIterationChanges({
234 cwd: input.cwd,
235 location: input.location,
236 number: input.number,
237 iterationId: latest.id,
238 });
239 };
240​
241 const provider: PullRequestProviderApi = {
242 kind: SourceControlProviderKind.make("azure-devops"),
243 capabilities: CAPABILITIES,
244 unavailableRequirement: UNAVAILABLE_REQUIREMENT,
245 // The bare repository name repeats across an organization; the project path does not.
246 repositoryKey: ({ canonicalKey }) => canonicalKey,
247​
248 getViewer: (input) =>
249 cli.getViewer({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
250​
251 listChangeRequests: (input) =>
252 cli
253 .listPullRequests({
254 cwd: input.cwd,
255 repository: input.repository,
256 state: input.state,
257 involvement: input.involvement,
258 viewer: input.viewer,
259 limit: input.limit,
260 cursor: input.cursor,
261 author:
262 input.filters?.author === undefined
263 ? undefined
264 : resolvePullRequestAuthorFilter(input.filters.author, input.viewer),
265 })
266 .pipe(
267 Effect.mapError(fail("listChangeRequests")),
268 Effect.map((batch) => ({
269 items: batch.items.map(toChangeRequest),
270 truncated: batch.truncated,
271 cursorAdvance: batch.cursorAdvance,
272 // Azure's ordering is stable across offset-based pages.
273 continues: true,
274 })),
275 ),
276​
277 getChangeRequestPreview: (input) =>
278 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
279 Effect.mapError(fail("getChangeRequestPreview")),
280 Effect.map((pullRequest) => ({
281 number: pullRequest.number,
282 title: pullRequest.title,
283 url: pullRequest.url,
284 author: pullRequest.author,
285 state: pullRequest.state,
286 isDraft: pullRequest.isDraft,
287 createdAt: pullRequest.createdAt,
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 const iteration =
393 cursor === null
394 ? scope.iterations.at(-1)
395 : scope.iterations.find((candidate) => candidate.id === cursor.iterationId);
396 if (iteration === undefined) return EMPTY_DIFF_SLICE;
397 const listed = yield* cli.listIterationChanges({
398 cwd: input.cwd,
399 location: scope.location,
400 number: input.number,
401 iterationId: iteration.id,
402 });
403 const changes = listed.changes;
404​
405 const sections: string[] = [];
406 let truncated = listed.truncated;
407 let bytes = 0;
408 let edits = 0;
409 let index = cursor?.fileIndex ?? 0;
410 let full = false;
411 // Prefetched files beyond the slice must be read again.
412 const batchWidth = () => {
413 if (sections.length === 0) return DIFF_FILE_CONCURRENCY;
414 const admits = (left: number, spent: number) =>
415 Math.ceil(left / Math.max(1, spent / sections.length));
416 return Math.max(
417 1,
418 Math.min(
419 DIFF_FILE_CONCURRENCY,
420 MAX_DIFF_SLICE_FILES - sections.length,
421 admits(MAX_DIFF_SLICE_BYTES - bytes, bytes),
422 admits(MAX_DIFF_SLICE_EDITS - MAX_FILE_DIFF_EDITS - edits, edits),
423 ),
424 );
425 };
426 while (!full && index < changes.length) {
427 const batch = changes.slice(index, index + batchWidth());
428 const read = yield* Effect.forEach(
429 batch,
430 (change) =>
431 readTexts({ cwd: input.cwd, location: scope.location, iteration, change }).pipe(
432 // Auth, rate-limit and CLI failures must reach the caller.
433 Effect.catchTags({
434 AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(null),
435 AzureDevOpsCommandFailedError: () => Effect.succeed(null),
436 AzureDevOpsPullRequestReadError: () => Effect.succeed(null),
437 }),
438 Effect.map((texts) => ({ change, texts })),
439 ),
440 { concurrency: DIFF_FILE_CONCURRENCY },
441 );
442 for (const { change, texts } of read) {
443 // Synchronous diffs need yields to let other server work run.
444 yield* Effect.yieldNow;
445 const file =
446 texts === null
447 ? azureDevOpsUnreadableFilePatch(change)
448 : azureDevOpsFilePatch({ change, texts });
449 sections.push(file.section);
450 bytes += byteLength(file.section);
451 edits += file.edits;
452 truncated = truncated || file.truncated;
453 index += 1;
454 // Add a file before checking budgets so oversized files cannot stall 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 },
477 Effect.mapError(fail("getDiff")),
478 ),
479​
480 getDiffFileContents: Effect.fn("AzureDevOpsPullRequestProvider.getDiffFileContents")(
481 function* (input) {
482 const scope = yield* diffScope(input);
483 const iteration = scope?.iterations.at(-1);
484 if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };
485 return yield* readTexts({
486 cwd: input.cwd,
487 location: scope.location,
488 iteration,
489 change: {
490 changeKind: input.changeType,
491 path: input.newPath,
492 oldPath: input.oldPath,
493 },
494 });
495 },
496 Effect.mapError(fail("getDiffFileContents")),
497 ),
498​
499 /**
500 * A path the change does not carry is at the empty revision, which is where a file the pull
501 * request deletes sits. When the change was too long to follow to its end, those paths are left
502 * out instead: reporting them as deleted would clear a file nobody has read.
503 */
504 getFileRevisions: Effect.fn("AzureDevOpsPullRequestProvider.getFileRevisions")(
505 function* (input) {
506 const revisions = new Map<string, string>();
507 if (input.paths.length === 0) return { revisions };
508 const scope = yield* diffScope(input);
509 if (scope === null) return { revisions };
510 const listed = yield* listLatestChanges({
511 ...scope,
512 cwd: input.cwd,
513 number: input.number,
514 });
515 const marked = new Set(input.paths);
516 for (const change of listed.changes) {
517 if (!marked.has(change.path) || change.objectId === null) continue;
518 revisions.set(change.path, change.objectId);
519 }
520 if (!listed.truncated) {
521 for (const path of input.paths) {
522 if (!revisions.has(path)) revisions.set(path, "");
523 }
524 }
525 return { revisions };
526 },
527 Effect.mapError(fail("getFileRevisions")),
528 ),
529​
530 runAction: (input) =>
531 cli
532 .runPullRequestAction({
533 cwd: input.cwd,
534 number: input.number,
535 action: input.action,
536 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
537 })
538 .pipe(Effect.mapError(fail("runAction"))),
539​
540 updateChangeRequest: (input) =>
541 cli
542 .updatePullRequest({
543 cwd: input.cwd,
544 number: input.number,
545 title: input.title,
546 body: input.body,
547 })
548 .pipe(Effect.mapError(fail("updateChangeRequest"))),
549​
550 listReviewerCandidates: () =>
551 Effect.fail(
552 new PullRequestProviderError({
553 provider: SourceControlProviderKind.make("azure-devops"),
554 operation: "listReviewerCandidates",
555 reason: "failed",
556 detail: "Azure DevOps cannot say who may review a pull request.",
557 }),
558 ),
559​
560 setReviewerRequest: (input) =>
561 cli
562 .setPullRequestReviewers({
563 cwd: input.cwd,
564 number: input.number,
565 reviewers: input.reviewers.map((reviewer) => reviewer.id),
566 requested: input.requested,
567 })
568 .pipe(Effect.mapError(fail("setReviewerRequest"))),
569​
570 comment: () => unsupported("comment"),
571​
572 submitReview: () => unsupported("submitReview"),
573​
574 replyToThread: () => unsupported("replyToThread"),
575​
576 setThreadResolution: () => unsupported("setThreadResolution"),
577​
578 setReaction: () => unsupported("setReaction"),
579 };
580​
581 return provider;
582});