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

AzureDevOpsPullRequestProvider.test.ts

596 lines21.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import type { PullRequestCheck, PullRequestCheckStatus } from "@t3tools/contracts";
5​
6import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
7import {
8 BLOB_BATCH_FILES,
9 LOCATION_CACHE_CAPACITY,
10 make,
11 MAX_DIFF_SPAWNS,
12} from "./AzureDevOpsPullRequestProvider.ts";
13import {
14 byteLength,
15 MAX_DIFF_SLICE_BYTES,
16 MAX_DIFF_SLICE_FILES,
17 MAX_FILE_DIFF_EDITS,
18 parseAzureDevOpsDiffCursor,
19} from "./azureDevOpsDiff.ts";
20import type { AzureDevOpsChangeEntry } from "./azureDevOpsPullRequestJson.ts";
21​
22const ITERATION = { id: 3, headCommit: "head", mergeBaseCommit: "base" };
23​
24const PULL_REQUEST = {
25 number: 7,
26 title: "Pull request 7",
27 url: "https://dev.azure.com/acme/web/_git/web/pullrequest/7",
28 author: null,
29 headBranch: "feat/page",
30 baseBranch: "main",
31 state: "open" as const,
32 isDraft: false,
33 mergeability: "mergeable" as const,
34 createdAt: "2026-07-01T00:00:00Z",
35 updatedAt: "2026-07-02T00:00:00Z",
36 closedAt: null,
37 body: "",
38 reviewRequestLogins: [],
39 reviewers: [],
40 location: { project: "acme", repository: "web" },
41 autoMergeEnabled: false,
42};
43​
44function change(
45 path: string,
46 changeKind: AzureDevOpsChangeEntry["changeKind"] = "change",
47): AzureDevOpsChangeEntry {
48 return { path, oldPath: path, changeKind, objectId: "8f80", originalObjectId: "0ca4" };
50​
51/** A batch that returns nothing, so every file takes the per-file read. */
52const NO_BLOBS = { readBlobs: () => Effect.succeed(new Map()) };
53​
54function side(prefix: string, lines: number, width: number): string {
55 const pad = "z".repeat(width);
56 return `${Array.from({ length: lines }, (_, line) => `${prefix} ${line} ${pad}`).join("\n")}\n`;
58​
59const readSlice = (input: {
60 readonly paths: ReadonlyArray<string>;
61 readonly lines: number;
62 readonly width: number;
63 readonly refused?: ReadonlyArray<string>;
64 readonly created?: ReadonlyArray<string>;
65 readonly cursor?: string;
66}) =>
67 Effect.gen(function* () {
68 const reads: string[] = [];
69 const refused = new Set(input.refused ?? []);
70 const created = new Set(input.created ?? []);
71 let inFlight = 0;
72 let peakInFlight = 0;
73​
74 const provider = yield* make.pipe(
75 Effect.provide(
76 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
77 ...NO_BLOBS,
78 getPullRequest: () => Effect.succeed(PULL_REQUEST),
79 listIterations: () => Effect.succeed([ITERATION]),
80 listIterationChanges: () =>
81 Effect.succeed({
82 changes: input.paths.map((path) =>
83 change(path, created.has(path) ? "new" : "change"),
84 ),
85 truncated: false,
86 }),
87 readItemContent: (item) =>
88 Effect.gen(function* () {
89 reads.push(item.path);
90 inFlight += 1;
91 peakInFlight = Math.max(peakInFlight, inFlight);
92 // Yield like a subprocess to exercise concurrency.
93 const answersAfter = input.paths.length - input.paths.indexOf(item.path);
94 for (let turn = 0; turn < answersAfter; turn += 1) yield* Effect.yieldNow;
95 inFlight -= 1;
96 if (refused.has(item.path)) {
97 return yield* new AzureDevOpsPullRequestCli.AzureDevOpsPullRequestReadError({
98 command: "az",
99 cwd: "/w",
100 operation: "readItemContent",
101 cause: "refused",
102 });
103 }
104 const isOldSide = item.commit !== ITERATION.headCommit;
105 if (isOldSide && created.has(item.path)) return { contents: "", isBinary: false };
106 return {
107 contents: side(isOldSide ? "old" : "new", input.lines, input.width),
108 isBinary: false,
109 };
110 }),
111 }),
112 ),
113 );
114​
115 const slice = yield* provider.getDiff({
116 cwd: "/w",
117 repository: "acme/web",
118 host: "dev.azure.com",
119 number: 7,
120 ...(input.cursor === undefined ? {} : { cursor: input.cursor }),
121 });
122 return { slice, reads, peakInFlight };
123 });
124​
125function patchedPaths(patch: string): ReadonlyArray<string> {
126 return [...patch.matchAll(/^diff --git a\/(?<path>\S+) b\//gmu)].map(
127 (match) => match.groups?.path ?? "",
128 );
130​
131describe("getChangeRequest", () => {
132 it.effect("preserves the newest head when file counting fails", () =>
133 Effect.gen(function* () {
134 const provider = yield* make.pipe(
135 Effect.provide(
136 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
137 getPullRequest: () => Effect.succeed(PULL_REQUEST),
138 listPolicyChecks: () => Effect.succeed([]),
139 listIterations: () =>
140 Effect.succeed([ITERATION, { ...ITERATION, id: 4, headCommit: "new-head" }]),
141 listIterationChanges: () =>
142 Effect.fail(
143 new AzureDevOpsPullRequestCli.AzureDevOpsPullRequestReadError({
144 command: "az",
145 cwd: "/w",
146 operation: "listIterationChanges",
147 cause: "unavailable",
148 }),
149 ),
150 }),
151 ),
152 );
153​
154 const detail = yield* provider.getChangeRequest({
155 cwd: "/w",
156 repository: "acme/web",
157 host: "dev.azure.com",
158 number: 7,
159 });
160 expect(detail.headSha).toBe("new-head");
161 expect(detail.changedFiles).toBe(0);
162 }),
163 );
164​
165 it.effect.each(["missing", "failed"] as const)(
166 "leaves the head unavailable when the iteration read is %s",
167 (state) =>
168 Effect.gen(function* () {
169 const provider = yield* make.pipe(
170 Effect.provide(
171 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
172 getPullRequest: () => Effect.succeed(PULL_REQUEST),
173 listPolicyChecks: () => Effect.succeed([]),
174 listIterations: () =>
175 state === "missing"
176 ? Effect.succeed([])
177 : Effect.fail(
178 new AzureDevOpsPullRequestCli.AzureDevOpsPullRequestReadError({
179 command: "az",
180 cwd: "/w",
181 operation: "listIterations",
182 cause: "unavailable",
183 }),
184 ),
185 }),
186 ),
187 );
188 const detail = yield* provider.getChangeRequest({
189 cwd: "/w",
190 repository: "acme/web",
191 host: "dev.azure.com",
192 number: 7,
193 });
194 expect(detail.headSha).toBeUndefined();
195 expect(detail.changedFiles).toBe(0);
196 }),
197 );
198});
199​
200describe("policy checks", () => {
201 const REPOSITORY = {
202 cwd: "/w",
203 repository: "acme/web",
204 host: "dev.azure.com",
205 number: 7,
206 };
207 const check = (status: PullRequestCheckStatus): PullRequestCheck => ({
208 name: "PR validation",
209 status,
210 description: null,
211 url: null,
212 required: true,
213 });
214 const readFailure = new AzureDevOpsPullRequestCli.AzureDevOpsPullRequestReadError({
215 command: "az",
216 cwd: "/w",
217 operation: "listPolicyChecks",
218 cause: "unavailable",
219 });
220​
221 const provide = (
222 listPolicyChecks: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli["Service"]["listPolicyChecks"],
223 pullRequest = PULL_REQUEST,
224 ) =>
225 make.pipe(
226 Effect.provide(
227 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
228 getPullRequest: () => Effect.succeed(pullRequest),
229 listIterations: () => Effect.succeed([ITERATION]),
230 listIterationChanges: () => Effect.succeed({ changes: [], truncated: false }),
231 listPolicyChecks,
232 }),
233 ),
234 );
235​
236 it.effect("keeps the detail readable when the policies are not", () =>
237 Effect.gen(function* () {
238 const provider = yield* provide(() => Effect.fail(readFailure));
239 const detail = yield* provider.getChangeRequest(REPOSITORY);
240 expect(detail.checks).toEqual([]);
241 }),
242 );
243​
244 it.effect.each([
245 { statuses: ["pending", "failure"], expected: "failing" },
246 { statuses: [], expected: null },
247 ] as const)("summarizes $statuses as $expected", ({ statuses, expected }) =>
248 Effect.gen(function* () {
249 const provider = yield* provide(() => Effect.succeed(statuses.map(check)));
250 const summary = yield* provider.getChangeRequestSummary!(REPOSITORY);
251 expect(summary.checksState).toBe(expected);
252 }),
253 );
254​
255 it.effect("leaves the last known state alone when the policies cannot be read", () =>
256 Effect.gen(function* () {
257 const provider = yield* provide(() => Effect.fail(readFailure));
258 const summary = yield* provider.getChangeRequestSummary!(REPOSITORY);
259 expect(summary.checksState).toBeUndefined();
260 }),
261 );
262});
263​
264describe("getDiff reads", () => {
265 it.effect("holds every reader together to one request's worth of processes", () =>
266 Effect.gen(function* () {
267 const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];
268 let inFlight = 0;
269 let peakInFlight = 0;
270​
271 const provider = yield* make.pipe(
272 Effect.provide(
273 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
274 ...NO_BLOBS,
275 getPullRequest: () => Effect.succeed(PULL_REQUEST),
276 listIterations: () => Effect.succeed([ITERATION]),
277 listIterationChanges: () =>
278 Effect.succeed({ changes: paths.map((path) => change(path)), truncated: false }),
279 readItemContent: () =>
280 Effect.gen(function* () {
281 inFlight += 1;
282 peakInFlight = Math.max(peakInFlight, inFlight);
283 // Yield like a subprocess to exercise concurrency.
284 yield* Effect.yieldNow;
285 yield* Effect.yieldNow;
286 inFlight -= 1;
287 return { contents: side("new", 2, 4), isBinary: false };
288 }),
289 }),
290 ),
291 );
292​
293 const readDiff = (number: number) =>
294 provider.getDiff({ cwd: "/w", repository: "acme/web", host: "dev.azure.com", number });
295​
296 yield* Effect.all([readDiff(7), readDiff(8)], { concurrency: 2 });
297​
298 expect(peakInFlight).toBeLessThanOrEqual(MAX_DIFF_SPAWNS);
299 }),
300 );
301​
302 it.effect("reads a slice's files in one blob batch, and per file only what it missed", () =>
303 Effect.gen(function* () {
304 const paths = ["a.ts", "b.ts", "c.ts", "gone.ts", "added.ts"];
305 const changes = [
306 ...["a.ts", "b.ts", "c.ts"].map((path) => ({
307 ...change(path),
308 objectId: `${path.toUpperCase()}-NEW`,
309 originalObjectId: `${path.toUpperCase()}-OLD`,
310 })),
311 { ...change("gone.ts", "deleted"), objectId: null, originalObjectId: "GONE-OLD" },
312 { ...change("added.ts", "new"), objectId: "ADDED-NEW", originalObjectId: null },
313 ];
314 const batches: ReadonlyArray<string>[] = [];
315 const reads: string[] = [];
316​
317 const provider = yield* make.pipe(
318 Effect.provide(
319 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
320 getPullRequest: () => Effect.succeed(PULL_REQUEST),
321 listIterations: () => Effect.succeed([ITERATION]),
322 listIterationChanges: () => Effect.succeed({ changes, truncated: false }),
323 readBlobs: (input) =>
324 Effect.sync(() => {
325 batches.push(input.objectIds);
326 // Azure left one side of b.ts out, as it does for a file only it can decode.
327 return new Map(
328 input.objectIds
329 .filter((id) => id !== "B.TS-OLD")
330 .map((id) => [
331 id.toLowerCase(),
332 {
333 contents: side(id.endsWith("NEW") ? "new" : "old", 2, 4),
334 isBinary: false,
335 },
336 ]),
337 );
338 }),
339 readItemContent: (item) =>
340 Effect.sync(() => {
341 reads.push(`${item.commit}:${item.path}`);
342 return {
343 contents: side(item.commit === ITERATION.headCommit ? "new" : "old", 2, 4),
344 isBinary: false,
345 };
346 }),
347 }),
348 ),
349 );
350​
351 const slice = yield* provider.getDiff({
352 cwd: "/w",
353 repository: "acme/web",
354 host: "dev.azure.com",
355 number: 7,
356 });
357​
358 expect(patchedPaths(slice.patch)).toEqual(paths);
359 expect(slice.patch.match(/^@@ /gmu)).toHaveLength(paths.length);
360 expect(batches).toEqual([
361 [
362 "A.TS-OLD",
363 "A.TS-NEW",
364 "B.TS-OLD",
365 "B.TS-NEW",
366 "C.TS-OLD",
367 "C.TS-NEW",
368 "GONE-OLD",
369 "ADDED-NEW",
370 ],
371 ]);
372 expect(reads.toSorted()).toEqual(["base:b.ts", "head:b.ts"]);
373 }),
374 );
375​
376 it.effect("starts a new blob batch where the last one's files run out", () =>
377 Effect.gen(function* () {
378 const paths = Array.from({ length: BLOB_BATCH_FILES + 3 }, (_, at) => `f${at}.ts`);
379 // Added lines that bring the slice near its edit budget by file 96, so the read batches
380 // there narrow to 3 and the one from file 99 would reach past the blob batch.
381 const added = (at: number) => (at < 60 ? 41 : at < 96 ? 40 : at < 99 ? 0 : 10);
382 const batchSizes: number[] = [];
383 let fileReads = 0;
384​
385 const provider = yield* make.pipe(
386 Effect.provide(
387 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
388 getPullRequest: () => Effect.succeed(PULL_REQUEST),
389 listIterations: () => Effect.succeed([ITERATION]),
390 listIterationChanges: () =>
391 Effect.succeed({
392 changes: paths.map((path) => ({
393 ...change(path),
394 objectId: `${path}-new`,
395 originalObjectId: `${path}-old`,
396 })),
397 truncated: false,
398 }),
399 readBlobs: (input) =>
400 Effect.sync(() => {
401 batchSizes.push(input.objectIds.length);
402 return new Map(
403 input.objectIds.map((id) => {
404 const at = Number(id.slice(1, id.indexOf(".")));
405 const lines = id.endsWith("-new") ? added(at) : 0;
406 return [
407 id,
408 { contents: lines === 0 ? "" : side("+", lines, 1), isBinary: false },
409 ];
410 }),
411 );
412 }),
413 readItemContent: () =>
414 Effect.sync(() => ((fileReads += 1), { contents: "", isBinary: false })),
415 }),
416 ),
417 );
418​
419 const slice = yield* provider.getDiff({
420 cwd: "/w",
421 repository: "acme/web",
422 host: "dev.azure.com",
423 number: 7,
424 });
425​
426 expect(patchedPaths(slice.patch)).toHaveLength(paths.length);
427 expect(batchSizes).toEqual([2 * BLOB_BATCH_FILES, 6]);
428 expect(fileReads).toBe(0);
429 }),
430 );
431​
432 it.effect("serves a later slice from the iteration and change list the first one read", () =>
433 Effect.gen(function* () {
434 const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];
435 let iterationReads = 0;
436 let changeReads = 0;
437​
438 const provider = yield* make.pipe(
439 Effect.provide(
440 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
441 ...NO_BLOBS,
442 getPullRequest: () => Effect.succeed(PULL_REQUEST),
443 listIterations: () => Effect.sync(() => ((iterationReads += 1), [ITERATION])),
444 listIterationChanges: () =>
445 Effect.sync(() => {
446 changeReads += 1;
447 return { changes: paths.map((path) => change(path)), truncated: false };
448 }),
449 readItemContent: (item) =>
450 Effect.succeed({
451 contents: side(item.commit === ITERATION.headCommit ? "new" : "old", 100, 900),
452 isBinary: false,
453 }),
454 }),
455 ),
456 );
457 const readDiff = (cursor?: string) =>
458 provider.getDiff({
459 cwd: "/w",
460 repository: "acme/web",
461 host: "dev.azure.com",
462 number: 7,
463 ...(cursor === undefined ? {} : { cursor }),
464 });
465​
466 const first = yield* readDiff();
467 const second = yield* readDiff(first.nextCursor ?? undefined);
468​
469 expect(patchedPaths(second.patch)).toEqual(["c.ts", "d.ts"]);
470 expect(iterationReads).toBe(1);
471 expect(changeReads).toBe(1);
472 }),
473 );
474​
475 it.effect("leaves a run of files it could not diff at all for the next slice", () =>
476 Effect.gen(function* () {
477 const paths = Array.from({ length: MAX_DIFF_SLICE_FILES + 20 }, (_, at) => `gen/a${at}.bin`);
478 const read = yield* readSlice({ paths, lines: 2, width: 4, refused: paths });
479​
480 expect(patchedPaths(read.slice.patch)).toHaveLength(MAX_DIFF_SLICE_FILES);
481 expect(byteLength(read.slice.patch)).toBeLessThan(MAX_DIFF_SLICE_BYTES);
482 expect(parseAzureDevOpsDiffCursor(read.slice.nextCursor)?.fileIndex).toBe(
483 MAX_DIFF_SLICE_FILES,
484 );
485 }),
486 );
487​
488 it.effect("keeps the patch in the order the change was listed, whoever answered first", () =>
489 Effect.gen(function* () {
490 const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts"];
491 const read = yield* readSlice({ paths, lines: 2, width: 4 });
492​
493 expect(patchedPaths(read.slice.patch)).toEqual(paths);
494 expect(read.slice.nextCursor).toBeNull();
495 }),
496 );
497​
498 it.effect("leaves a file the host refused listed without its hunks, in its place", () =>
499 Effect.gen(function* () {
500 const paths = ["a.ts", "b.ts", "c.ts"];
501 const read = yield* readSlice({ paths, lines: 2, width: 4, refused: ["b.ts"] });
502​
503 expect(patchedPaths(read.slice.patch)).toEqual(paths);
504 expect(read.slice.truncated).toBe(true);
505 expect(read.slice.patch).toContain("+++ b/b.ts\ndiff --git a/c.ts");
506 expect(read.slice.patch.match(/^@@ /gmu)).toHaveLength(2);
507 }),
508 );
509});
510​
511describe("what one diff slice spends", () => {
512 it.effect("stops on the byte ceiling without carrying what it read past it", () =>
513 Effect.gen(function* () {
514 const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];
515 const read = yield* readSlice({ paths, lines: 100, width: 900 });
516​
517 expect(read.slice.patch.length).toBeGreaterThan(MAX_DIFF_SLICE_BYTES);
518 expect(patchedPaths(read.slice.patch)).toEqual(["a.ts", "b.ts"]);
519 expect(read.slice.nextCursor).toBe(`${ITERATION.id}:2`);
520 expect(new Set(read.reads)).toEqual(new Set(["a.ts", "b.ts", "c.ts", "d.ts"]));
521 }),
522 );
523​
524 it.effect("stops once the diff work one request may do is spent", () =>
525 Effect.gen(function* () {
526 const paths = Array.from({ length: 12 }, (_, file) => `file-${file}.ts`);
527 const read = yield* readSlice({ paths, lines: MAX_FILE_DIFF_EDITS / 4, width: 1 });
528​
529 expect(read.slice.patch.length).toBeLessThan(MAX_DIFF_SLICE_BYTES);
530 expect(patchedPaths(read.slice.patch)).toEqual(paths.slice(0, 5));
531 expect(read.slice.nextCursor).toBe(`${ITERATION.id}:5`);
532 }),
533 );
534​
535 it.effect("carries a whole new file and stops the slice on what it weighed", () =>
536 Effect.gen(function* () {
537 const paths = ["new.ts", "b.ts", "c.ts", "d.ts"];
538 const read = yield* readSlice({ paths, lines: 8_000, width: 30, created: ["new.ts"] });
539​
540 expect(patchedPaths(read.slice.patch)).toEqual(["new.ts"]);
541 expect(read.slice.patch).toContain("--- /dev/null");
542 expect(read.slice.patch).toContain("@@ -0,0 +1,8000 @@");
543 expect(read.slice.patch.length).toBeGreaterThan(MAX_DIFF_SLICE_BYTES);
544 expect(read.slice.nextCursor).toBe(`${ITERATION.id}:1`);
545 }),
546 );
547​
548 it.effect("carries on from where the last slice stopped", () =>
549 Effect.gen(function* () {
550 const paths = ["a.ts", "b.ts", "c.ts", "d.ts", "e.ts", "f.ts"];
551 const read = yield* readSlice({
552 paths,
553 lines: 100,
554 width: 900,
555 cursor: `${ITERATION.id}:2`,
556 });
557​
558 expect(patchedPaths(read.slice.patch)).toEqual(["c.ts", "d.ts"]);
559 expect(read.slice.nextCursor).toBe(`${ITERATION.id}:4`);
560 }),
561 );
562 it.effect("keeps the pull request being read, not the one looked up first", () =>
563 Effect.gen(function* () {
564 const HOT = 7;
565 const readsOf = new Map<number, number>();
566​
567 const provider = yield* make.pipe(
568 Effect.provide(
569 Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({
570 ...NO_BLOBS,
571 getPullRequest: (input) =>
572 Effect.sync(() => {
573 readsOf.set(input.number, (readsOf.get(input.number) ?? 0) + 1);
574 return { ...PULL_REQUEST, number: input.number };
575 }),
576 listIterations: () => Effect.succeed([ITERATION]),
577 listIterationChanges: () =>
578 Effect.succeed({ changes: [change("a.ts")], truncated: false }),
579 readItemContent: () => Effect.succeed({ contents: side("new", 2, 4), isBinary: false }),
580 }),
581 ),
582 );
583​
584 const readDiff = (number: number) =>
585 provider.getDiff({ cwd: "/w", repository: "acme/web", host: "dev.azure.com", number });
586​
587 yield* readDiff(HOT);
588 for (let filled = 0; filled < LOCATION_CACHE_CAPACITY; filled += 1) {
589 yield* readDiff(HOT + 1 + filled);
590 yield* readDiff(HOT);
591 }
592​
593 expect(readsOf.get(HOT)).toBe(1);
594 }),
595 );
596});