~james/core

core/web/src/lib/components/repo/diffQueue.test.ts -rw-r--r-- 8.4 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RepoDiff, RepoDiffDeps, RepoDiffFile } from "#lib/api/repoDiff.ts";
import { createDiffQueue, type DiffEntry } from "#lib/components/repo/diffQueue.ts";

const { fetchSides, parseDiffInWorker, streamPatchInWorker } = vi.hoisted(() => ({
	fetchSides: vi.fn(),
	parseDiffInWorker: vi.fn(),
	streamPatchInWorker: vi.fn()
}));

vi.mock("#lib/api/repoDiff.ts", () => ({ fetchSides }));
vi.mock("#lib/components/repo/diffRpc.ts", () => ({ parseDiffInWorker, streamPatchInWorker }));

// the real one fetches and parses in a worker, answering in batches; the mock
// just replays whatever batches a test hands it
const patchYielding = (...batches: { name: string; hunks: never[]; prevName?: string }[][]) =>
	streamPatchInWorker.mockImplementation(
		async (_url: string, onFiles: (files: unknown[]) => void) => {
			for (const batch of batches) onFiles(batch);
		}
	);

const base = (name: string) => ({
	key: `${name}\u2192${name}`,
	name,
	kind: "changed" as const,
	stat: { insertions: 1, deletions: 0 },
	lines: 4
});

const side = (name: string, oid: string) => ({
	path: name,
	oid,
	isBinary: false,
	isSubmodule: false,
	size: 12
});

const file = (name: string): RepoDiffFile => ({
	...base(name),
	sides: { lhs: side(name, "a"), rhs: side(name, "b") }
});

const noteFile = (name: string): RepoDiffFile => ({ ...base(name), note: "binary" });

const diffOf = (...files: RepoDiffFile[]): RepoDiff => ({
	files,
	stat: { insertions: 1, deletions: 0, files_changed: files.length },
	contents: { oldRef: "old", newRef: "new" }
});

const harness = (diff: RepoDiff) => {
	let entries: Record<string, DiffEntry> = {};
	let patchExpected = false;
	const queue = createDiffQueue({
		deps: () => ({}) as RepoDiffDeps,
		diff: () => diff,
		entry: (key) => entries[key],
		put: (parsed) => (entries = { ...entries, ...parsed }),
		patchExpected: () => patchExpected
	});
	return {
		queue,
		get entries() {
			return entries;
		},
		expectPatch: (expected: boolean) => (patchExpected = expected)
	};
};

const deferred = <T>() => {
	let resolve!: (value: T) => void;
	const promise = new Promise<T>((r) => (resolve = r));
	return { promise, resolve };
};

const settle = () => new Promise((resolve) => setTimeout(resolve, 0));

describe("createDiffQueue", () => {
	beforeEach(() => vi.clearAllMocks());

	it("leaves a wanted file to the patch while one is still expected", async () => {
		fetchSides.mockResolvedValue({ note: "should never be asked for" });
		const { queue, entries, expectPatch } = harness(diffOf(file("a.ts")));
		expectPatch(true);

		queue.want("a.ts\u2192a.ts");
		await settle();

		expect(fetchSides).not.toHaveBeenCalled();
		expect(entries).toEqual({});
	});

	it("fetches what the patch never carried once it settles", async () => {
		fetchSides.mockResolvedValue({ note: "binary" });
		const held = harness(diffOf(file("a.ts")));
		held.expectPatch(true);
		held.queue.want("a.ts\u2192a.ts");
		await settle();

		held.expectPatch(false);
		held.queue.drain();
		await settle();

		expect(fetchSides).toHaveBeenCalledTimes(1);
		expect(held.entries["a.ts\u2192a.ts"]).toEqual({ note: "binary" });
	});

	it("parses a file's two sides and keeps the result", async () => {
		fetchSides.mockResolvedValue({
			oldFile: { name: "a.ts", contents: "old" },
			newFile: { name: "a.ts", contents: "new" }
		});
		parseDiffInWorker.mockResolvedValue({ name: "a.ts", hunks: [] });
		const a = file("a.ts");
		const h = harness(diffOf(a));

		h.queue.want(a.key);
		await settle();

		expect(h.entries[a.key]).toEqual({ name: "a.ts", hunks: [] });
		expect(parseDiffInWorker).toHaveBeenCalledOnce();
	});

	it("notes a file whose contents cannot be loaded, once the retries are spent", async () => {
		vi.useFakeTimers();
		try {
			fetchSides.mockRejectedValue(new Error("gone"));
			const a = file("a.ts");
			const h = harness(diffOf(a));

			h.queue.want(a.key);
			await vi.runAllTimersAsync();

			expect(h.entries[a.key]).toEqual({ note: "Contents could not be loaded." });
			// the first call plus its retries
			expect(fetchSides).toHaveBeenCalledTimes(4);
		} finally {
			vi.useRealTimers();
		}
	});

	it("retries a file the mirror briefly refused", async () => {
		vi.useFakeTimers();
		try {
			fetchSides.mockRejectedValueOnce(new Error("429")).mockResolvedValue({
				oldFile: { name: "a.ts", contents: "old" },
				newFile: { name: "a.ts", contents: "new" }
			});
			parseDiffInWorker.mockResolvedValue({ name: "a.ts", hunks: [] });
			const a = file("a.ts");
			const h = harness(diffOf(a));

			h.queue.want(a.key);
			await vi.runAllTimersAsync();

			expect(h.entries[a.key]).toEqual({ name: "a.ts", hunks: [] });
		} finally {
			vi.useRealTimers();
		}
	});

	it("never queues a file that has no sides to fetch", async () => {
		const binary = noteFile("logo.png");
		const h = harness(diffOf(binary));

		h.queue.want(binary.key);
		await settle();

		expect(fetchSides).not.toHaveBeenCalled();
	});

	it("keeps the note on a file the patch also carries", async () => {
		patchYielding([{ name: "Cargo.nix", hunks: [] }]);
		const noted = noteFile("Cargo.nix");
		const h = harness(diffOf(noted));

		await h.queue.applyPatch("/commit.diff", new AbortController().signal);
		h.queue.adopt({ [noted.key]: { name: "Cargo.nix", hunks: [] } as never });

		expect(h.entries[noted.key]).toBeUndefined();
	});

	it("fills every file the patch covers in one write", async () => {
		patchYielding([
			{ name: "a.ts", hunks: [] },
			{ name: "b.ts", hunks: [] }
		]);
		const a = file("a.ts");
		const b = file("b.ts");
		const h = harness(diffOf(a, b));

		await h.queue.applyPatch("/commit.diff", new AbortController().signal);

		expect(h.entries[a.key]).toEqual({ name: "a.ts", hunks: [] });
		expect(h.entries[b.key]).toEqual({ name: "b.ts", hunks: [] });
	});

	it("lands each streamed batch as it arrives, not only at the end", async () => {
		const a = file("a.ts");
		const b = file("b.ts");
		const seen: number[] = [];
		streamPatchInWorker.mockImplementation(
			async (_url: string, onFiles: (files: unknown[]) => void) => {
				onFiles([{ name: "a.ts", hunks: [] }]);
				seen.push(Object.keys(h.entries).length);
				onFiles([{ name: "b.ts", hunks: [] }]);
				seen.push(Object.keys(h.entries).length);
			}
		);
		const h = harness(diffOf(a, b));

		await h.queue.applyPatch("/commit.patch", new AbortController().signal);

		// the first batch is readable before the second one is parsed
		expect(seen).toEqual([1, 2]);
		expect(h.entries[b.key]).toEqual({ name: "b.ts", hunks: [] });
	});

	it("leaves a file the patch covers alone while its own fetch is in flight", async () => {
		const sides = deferred<{ oldFile: unknown; newFile: unknown }>();
		fetchSides.mockReturnValue(sides.promise);
		parseDiffInWorker.mockResolvedValue({ name: "a.ts", hunks: ["full"] });
		patchYielding([{ name: "a.ts", hunks: ["partial"] as never[] }]);
		const a = file("a.ts");
		const h = harness(diffOf(a));

		h.queue.want(a.key);
		await h.queue.applyPatch("/commit.diff", new AbortController().signal);
		expect(h.entries[a.key]).toBeUndefined();

		sides.resolve({
			oldFile: { name: "a.ts", contents: "old" },
			newFile: { name: "a.ts", contents: "new" }
		});
		await settle();

		expect(h.entries[a.key]).toEqual({ name: "a.ts", hunks: ["full"] });
	});

	it("matches a renamed file through the patch's previous name", async () => {
		patchYielding([{ name: "new.ts", prevName: "old.ts", hunks: [] }]);
		const renamed: RepoDiffFile = { ...file("new.ts"), oldName: "old.ts" };
		const h = harness(diffOf(renamed));

		await h.queue.applyPatch("/commit.diff", new AbortController().signal);

		expect(h.entries[renamed.key]).toMatchObject({ name: "new.ts" });
	});

	it("drains the file nearest the cursor first", async () => {
		const order: string[] = [];
		const gate = deferred<void>();
		fetchSides.mockImplementation(
			async (_deps: unknown, _contents: unknown, f: RepoDiffFile) => {
				order.push(f.name);
				await gate.promise;
				return {
					oldFile: { name: f.name, contents: "" },
					newFile: { name: f.name, contents: "" }
				};
			}
		);
		parseDiffInWorker.mockResolvedValue({ name: "x", hunks: [] });
		const files = Array.from({ length: 9 }, (_, index) => file(`f${index}.ts`));
		const h = harness(diffOf(...files));

		for (const f of files) h.queue.want(f.key);
		h.queue.focus(files[8].key);
		for (const f of files) h.queue.want(f.key);
		gate.resolve();
		await settle();

		expect(order.slice(0, 6)).toHaveLength(6);
		expect(order).toContain("f8.ts");
	});
});