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

AzureDevOpsPullRequestProvider.ts

568 lines20.7 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 getChangeRequestSummary: (input) =>
278 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
279 Effect.mapError(fail("getChangeRequestSummary")),
280 Effect.map((pullRequest): ProviderChangeRequestSummary => ({
281 number: pullRequest.number,
282 title: pullRequest.title,
283 url: pullRequest.url,
284 author: pullRequest.author,
285 headBranch: pullRequest.headBranch,
286 baseBranch: pullRequest.baseBranch,
287 state: pullRequest.state,
288 isDraft: pullRequest.isDraft,
289 mergeability: pullRequest.mergeability,
290 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
291 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
292 updatedAt: pullRequest.updatedAt,
293 })),
294 ),
295​
296 getChangeRequest: Effect.fn("AzureDevOpsPullRequestProvider.getChangeRequest")(
297 function* (input) {
298 const pullRequest = yield* cli.getPullRequest({ cwd: input.cwd, number: input.number });
299 const location = pullRequest.location;
300 const iterations =
301 location === null
302 ? []
303 : yield* cli
304 .listIterations({ cwd: input.cwd, location, number: input.number })
305 .pipe(Effect.orElseSucceed(() => []));
306 // The trial merge's lastMergeSourceCommit can lag behind a new source push.
307 const headSha = iterations.at(-1)?.headCommit;
308 const changedFiles =
309 location === null
310 ? 0
311 : yield* listLatestChanges({
312 cwd: input.cwd,
313 location,
314 number: input.number,
315 iterations,
316 }).pipe(
317 Effect.map((listed) => listed.changes.length),
318 Effect.orElseSucceed(() => 0),
319 );
320 const detail: ProviderChangeRequestDetail = {
321 ...toChangeRequest(pullRequest),
322 body: pullRequest.body,
323 ...(headSha === undefined ? {} : { headSha }),
324 changedFiles,
325 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
326 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
327 reviewers: pullRequest.reviewers,
328 checks: [],
329 mergeCapabilities: { merge: true, squash: true, rebase: false },
330 viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
331 autoMergeEnabled: pullRequest.autoMergeEnabled,
332 ...(pullRequest.autoMergeMethod === undefined
333 ? {}
334 : { autoMergeMethod: pullRequest.autoMergeMethod }),
335 };
336 return detail;
337 },
338 Effect.mapError(fail("getChangeRequest")),
339 ),
340​
341 getChangeRequestActivity: (input) =>
342 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
343 Effect.mapError(fail("getChangeRequestActivity")),
344 Effect.flatMap((pullRequest) =>
345 (pullRequest.location === null
346 ? Effect.succeed({ comments: [], truncated: true })
347 : cli
348 .listThreads({
349 cwd: input.cwd,
350 location: pullRequest.location,
351 number: input.number,
352 })
353 .pipe(
354 Effect.map((comments) => ({ comments, truncated: false })),
355 Effect.orElseSucceed(() => ({ comments: [], truncated: true })),
356 )
357 ).pipe(
358 Effect.map((conversation): ProviderChangeRequestActivity => ({
359 comments: conversation.comments,
360 commentCount: conversation.comments.length,
361 commentsTruncated: conversation.truncated,
362 reviewThreads: [],
363 commits: [],
364 })),
365 ),
366 ),
367 ),
368​
369 getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),
370​
371 // `input.commit` is deliberately dropped: Azure states no commit list on a pull request, so
372 // the Code tab has nothing to scope itself to and always asks for the whole change.
373 getDiff: Effect.fn("AzureDevOpsPullRequestProvider.getDiff")(
374 function* (input) {
375 const scope = yield* diffScope(input);
376 if (scope === null) return EMPTY_DIFF_SLICE;
377 const cursor = parseAzureDevOpsDiffCursor(input.cursor);
378 const iteration =
379 cursor === null
380 ? scope.iterations.at(-1)
381 : scope.iterations.find((candidate) => candidate.id === cursor.iterationId);
382 if (iteration === undefined) return EMPTY_DIFF_SLICE;
383 const listed = yield* cli.listIterationChanges({
384 cwd: input.cwd,
385 location: scope.location,
386 number: input.number,
387 iterationId: iteration.id,
388 });
389 const changes = listed.changes;
390​
391 const sections: string[] = [];
392 let truncated = listed.truncated;
393 let bytes = 0;
394 let edits = 0;
395 let index = cursor?.fileIndex ?? 0;
396 let full = false;
397 // Prefetched files beyond the slice must be read again.
398 const batchWidth = () => {
399 if (sections.length === 0) return DIFF_FILE_CONCURRENCY;
400 const admits = (left: number, spent: number) =>
401 Math.ceil(left / Math.max(1, spent / sections.length));
402 return Math.max(
403 1,
404 Math.min(
405 DIFF_FILE_CONCURRENCY,
406 MAX_DIFF_SLICE_FILES - sections.length,
407 admits(MAX_DIFF_SLICE_BYTES - bytes, bytes),
408 admits(MAX_DIFF_SLICE_EDITS - MAX_FILE_DIFF_EDITS - edits, edits),
409 ),
410 );
411 };
412 while (!full && index < changes.length) {
413 const batch = changes.slice(index, index + batchWidth());
414 const read = yield* Effect.forEach(
415 batch,
416 (change) =>
417 readTexts({ cwd: input.cwd, location: scope.location, iteration, change }).pipe(
418 // Auth, rate-limit and CLI failures must reach the caller.
419 Effect.catchTags({
420 AzureDevOpsPullRequestNotFoundError: () => Effect.succeed(null),
421 AzureDevOpsCommandFailedError: () => Effect.succeed(null),
422 AzureDevOpsPullRequestReadError: () => Effect.succeed(null),
423 }),
424 Effect.map((texts) => ({ change, texts })),
425 ),
426 { concurrency: DIFF_FILE_CONCURRENCY },
427 );
428 for (const { change, texts } of read) {
429 // Synchronous diffs need yields to let other server work run.
430 yield* Effect.yieldNow;
431 const file =
432 texts === null
433 ? azureDevOpsUnreadableFilePatch(change)
434 : azureDevOpsFilePatch({ change, texts });
435 sections.push(file.section);
436 bytes += byteLength(file.section);
437 edits += file.edits;
438 truncated = truncated || file.truncated;
439 index += 1;
440 // Add a file before checking budgets so oversized files cannot stall the cursor.
441 if (
442 bytes >= MAX_DIFF_SLICE_BYTES ||
443 edits + MAX_FILE_DIFF_EDITS > MAX_DIFF_SLICE_EDITS ||
444 sections.length >= MAX_DIFF_SLICE_FILES ||
445 file.abandoned
446 ) {
447 full = true;
448 break;
449 }
450 }
451 }
452​
453 const slice: ProviderDiffSlice = {
454 patch: sections.join(""),
455 truncated,
456 nextCursor:
457 index >= changes.length
458 ? null
459 : formatAzureDevOpsDiffCursor({ iterationId: iteration.id, fileIndex: index }),
460 };
461 return slice;
462 },
463 Effect.mapError(fail("getDiff")),
464 ),
465​
466 getDiffFileContents: Effect.fn("AzureDevOpsPullRequestProvider.getDiffFileContents")(
467 function* (input) {
468 const scope = yield* diffScope(input);
469 const iteration = scope?.iterations.at(-1);
470 if (scope === null || iteration === undefined) return { oldContents: "", newContents: "" };
471 return yield* readTexts({
472 cwd: input.cwd,
473 location: scope.location,
474 iteration,
475 change: {
476 changeKind: input.changeType,
477 path: input.newPath,
478 oldPath: input.oldPath,
479 },
480 });
481 },
482 Effect.mapError(fail("getDiffFileContents")),
483 ),
484​
485 /**
486 * A path the change does not carry is at the empty revision, which is where a file the pull
487 * request deletes sits. When the change was too long to follow to its end, those paths are left
488 * out instead: reporting them as deleted would clear a file nobody has read.
489 */
490 getFileRevisions: Effect.fn("AzureDevOpsPullRequestProvider.getFileRevisions")(
491 function* (input) {
492 const revisions = new Map<string, string>();
493 if (input.paths.length === 0) return { revisions };
494 const scope = yield* diffScope(input);
495 if (scope === null) return { revisions };
496 const listed = yield* listLatestChanges({
497 ...scope,
498 cwd: input.cwd,
499 number: input.number,
500 });
501 const marked = new Set(input.paths);
502 for (const change of listed.changes) {
503 if (!marked.has(change.path) || change.objectId === null) continue;
504 revisions.set(change.path, change.objectId);
505 }
506 if (!listed.truncated) {
507 for (const path of input.paths) {
508 if (!revisions.has(path)) revisions.set(path, "");
509 }
510 }
511 return { revisions };
512 },
513 Effect.mapError(fail("getFileRevisions")),
514 ),
515​
516 runAction: (input) =>
517 cli
518 .runPullRequestAction({
519 cwd: input.cwd,
520 number: input.number,
521 action: input.action,
522 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
523 })
524 .pipe(Effect.mapError(fail("runAction"))),
525​
526 updateChangeRequest: (input) =>
527 cli
528 .updatePullRequest({
529 cwd: input.cwd,
530 number: input.number,
531 title: input.title,
532 body: input.body,
533 })
534 .pipe(Effect.mapError(fail("updateChangeRequest"))),
535​
536 listReviewerCandidates: () =>
537 Effect.fail(
538 new PullRequestProviderError({
539 provider: SourceControlProviderKind.make("azure-devops"),
540 operation: "listReviewerCandidates",
541 reason: "failed",
542 detail: "Azure DevOps cannot say who may review a pull request.",
543 }),
544 ),
545​
546 setReviewerRequest: (input) =>
547 cli
548 .setPullRequestReviewers({
549 cwd: input.cwd,
550 number: input.number,
551 reviewers: input.reviewers.map((reviewer) => reviewer.id),
552 requested: input.requested,
553 })
554 .pipe(Effect.mapError(fail("setReviewerRequest"))),
555​
556 comment: () => unsupported("comment"),
557​
558 submitReview: () => unsupported("submitReview"),
559​
560 replyToThread: () => unsupported("replyToThread"),
561​
562 setThreadResolution: () => unsupported("setThreadResolution"),
563​
564 setReaction: () => unsupported("setReaction"),
565 };
566​
567 return provider;
568});