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

AzureDevOpsPullRequestProvider.ts

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