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

AzureDevOpsPullRequestProvider.ts

582 lines22.5 KB

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