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

PullRequestReviewGuideService.ts

529 lines20.3 KB

1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Ref from "effect/Ref";
10import * as Result from "effect/Result";
11import * as Semaphore from "effect/Semaphore";
12​
13import {
14 PullRequestOperationError,
15 type PullRequestDetail,
16 type PullRequestRef,
17 type PullRequestReviewGuide,
18 type PullRequestReviewGuideResult,
19 type PullRequestReviewGuideRun,
20 type PullRequestStack,
21 ProjectId,
22 type RepositoryIdentity,
23 type ThreadPullRequestKey,
24} from "@t3tools/contracts";
25import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration";
26import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
27import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
28​
29import * as ServerConfig from "../config.ts";
30import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts";
31import * as ProjectService from "../project/ProjectService.ts";
32import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as TextGeneration from "../textGeneration/TextGeneration.ts";
35import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
36import { PATCH_RENDER_PREFIX_ARGS } from "../vcs/GitVcsDriverCore.ts";
37import * as PullRequestService from "./PullRequestService.ts";
38import { pullRequestSyncKey } from "./pullRequestSyncKey.ts";
39import { reviewGuideInputFromPullRequest } from "./pullRequestReviewGuideInput.ts";
40import { normalizeReviewGuide, parseReviewGuideChange } from "./pullRequestReviewGuideNormalize.ts";
41​
42const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,64}$/;
43​
44export class PullRequestReviewGuideService extends Context.Service<
45 PullRequestReviewGuideService,
46 {
47 readonly get: (
48 input: PullRequestRef,
49 ) => Effect.Effect<PullRequestReviewGuideResult, PullRequestService.PullRequestError>;
50 readonly generate: (
51 input: PullRequestRef,
52 ) => Effect.Effect<
53 PullRequestReviewGuideResult & { readonly started: boolean },
54 PullRequestService.PullRequestError
55 >;
56 }
57>()("t3/pullRequest/PullRequestReviewGuideService") {}
58​
59const keyString = (key: ThreadPullRequestKey) => `${key.host}/${key.repository}#${key.number}`;
60​
61const nowIso = Clock.currentTimeMillis.pipe(
62 Effect.map((millis) => DateTime.formatIso(DateTime.makeUnsafe(millis))),
63);
64​
65const make = Effect.gen(function* () {
66 const pullRequests = yield* PullRequestService.PullRequestService;
67 const guides = yield* PullRequestReviewGuides.PullRequestReviewGuideRepository;
68 const projects = yield* ProjectService.ProjectService;
69 const serverSettings = yield* ServerSettings.ServerSettingsService;
70 const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
71 const textGeneration = yield* TextGeneration.TextGeneration;
72 const git = yield* GitVcsDriver.GitVcsDriver;
73 const fileSystem = yield* FileSystem.FileSystem;
74 const config = yield* ServerConfig.ServerConfig;
75 const serviceScope = yield* Effect.scope;
76 const runs = yield* Ref.make<ReadonlyMap<string, PullRequestReviewGuideRun>>(new Map());
77 let runCounter = 0;
78 // Claiming a run and storing a finished guide take turns, so a run that still owns its pull
79 // request when it checks is the one whose guide is stored: a newer claim cannot land between.
80 const ownership = yield* Semaphore.make(1);
81​
82 const keyFor = Effect.fn("PullRequestReviewGuideService.keyFor")(function* (
83 input: PullRequestRef,
84 ) {
85 const project = Option.getOrUndefined(
86 yield* projects.getShell(input.projectId).pipe(Effect.orElseSucceed(() => Option.none())),
87 );
88 const key = pullRequestSyncKey(input, project?.repositoryIdentity ?? undefined);
89 if (key === null || project === undefined) {
90 return yield* new PullRequestOperationError({
91 operation: "reviewGuide",
92 detail: "Could not identify this pull request's host.",
93 });
94 }
95 return { key, workspaceRoot: project.workspaceRoot, identity: project.repositoryIdentity };
96 });
97​
98 const requireOwnRepository = Effect.fn("PullRequestReviewGuideService.requireOwnRepository")(
99 function* (key: ThreadPullRequestKey, identity: RepositoryIdentity | null | undefined) {
100 const own =
101 identity == null
102 ? null
103 : pullRequestSyncKey(
104 {
105 projectId: ProjectId.make("own"),
106 number: key.number,
107 repository: sourceControlDefinitions.repositorySelector(identity) ?? "",
108 },
109 identity,
110 );
111 if (
112 identity == null ||
113 own === null ||
114 own.host !== key.host ||
115 own.repository !== key.repository
116 ) {
117 return yield* new PullRequestOperationError({
118 operation: "generateReviewGuide",
119 detail:
120 "Guides are written from this project's checkout, and this pull request is in another repository. Write it from a project that is a checkout of that repository.",
121 });
122 }
123 return identity.locator;
124 },
125 );
126​
127 const readStored = (key: ThreadPullRequestKey) =>
128 guides.get(key).pipe(
129 Effect.mapError(
130 (cause) =>
131 new PullRequestOperationError({
132 operation: "reviewGuide",
133 detail: "Could not read the stored review guide.",
134 cause,
135 }),
136 ),
137 Effect.map(Option.getOrNull),
138 );
139​
140 const get: PullRequestReviewGuideService["Service"]["get"] = Effect.fn(
141 "PullRequestReviewGuideService.get",
142 )(function* (input) {
143 const { key } = yield* keyFor(input);
144 const [guide, detail, current] = yield* Effect.all(
145 [readStored(key), pullRequests.detail(input), Ref.get(runs)],
146 { concurrency: "unbounded" },
147 );
148 return {
149 guide,
150 run: current.get(keyString(key)) ?? null,
151 currentHeadSha: detail.headSha ?? null,
152 };
153 });
154​
155 const checkoutHead = Effect.fn("PullRequestReviewGuideService.checkoutHead")(function* (
156 workspaceRoot: string,
157 locator: RepositoryIdentity["locator"],
158 detail: PullRequestDetail,
159 headSha: string,
160 stack: PullRequestStack | null,
161 runId: string,
162 ) {
163 // Identity names can be stale; match effective fetch URLs, including insteadOf rewrites.
164 const names = yield* git
165 .execute({
166 operation: "PullRequestReviewGuideService.listRemotes",
167 cwd: workspaceRoot,
168 args: ["remote"],
169 })
170 .pipe(Effect.map((result) => result.stdout.split("\n").filter((name) => name.length > 0)));
171 const remote = yield* Effect.findFirst(
172 [locator.remoteName, ...names.filter((name) => name !== locator.remoteName)],
173 (name) =>
174 git
175 .execute({
176 operation: "PullRequestReviewGuideService.remoteUrl",
177 cwd: workspaceRoot,
178 args: ["remote", "get-url", "--", name],
179 })
180 .pipe(
181 Effect.map((result) => result.stdout.trim() === locator.remoteUrl),
182 Effect.orElseSucceed(() => false),
183 ),
184 ).pipe(Effect.map(Option.getOrUndefined));
185 if (remote === undefined) {
186 return yield* new PullRequestOperationError({
187 operation: "generateReviewGuide",
188 detail: "This project's checkout no longer has a remote for the pull request's repository.",
189 });
190 }
191 const fetch = (args: ReadonlyArray<string>) =>
192 git.execute({
193 operation: "PullRequestReviewGuideService.fetch",
194 cwd: workspaceRoot,
195 args: ["fetch", "--quiet", "--no-tags", "--", remote, ...args],
196 timeoutMs: 5 * 60_000,
197 });
198 // The host names the base branch. A name git rejects, or one that would change the refspec
199 // (a leading `+`, a `:`), is refused before it reaches `git fetch`.
200 yield* git
201 .execute({
202 operation: "PullRequestReviewGuideService.checkBaseBranch",
203 cwd: workspaceRoot,
204 args: ["check-ref-format", "--branch", detail.baseBranch],
205 })
206 .pipe(
207 Effect.filterOrFail(
208 () => !detail.baseBranch.startsWith("+") && !detail.baseBranch.includes(":"),
209 () =>
210 new PullRequestOperationError({
211 operation: "generateReviewGuide",
212 detail: "The pull request's base branch name is not one git can fetch.",
213 }),
214 ),
215 );
216 // Fetched into a ref of this run's own: FETCH_HEAD is shared by every fetch in the
217 // workspace, so a concurrent run could otherwise measure this change from its base.
218 const baseRef = `refs/t3/review-guide/${runId}/base`;
219 yield* fetch([`+refs/heads/${detail.baseBranch}:${baseRef}`]);
220 yield* Effect.addFinalizer(() =>
221 git
222 .execute({
223 operation: "PullRequestReviewGuideService.dropBaseRef",
224 cwd: workspaceRoot,
225 args: ["update-ref", "-d", baseRef],
226 })
227 .pipe(Effect.ignore({ log: true })),
228 );
229 const baseTip = yield* git.resolveCommit({ cwd: workspaceRoot, revision: baseRef });
230 const fetchHead = Effect.fn("PullRequestReviewGuideService.fetchHead")(function* (
231 number: number,
232 reportedSha: string,
233 branch: string,
234 ) {
235 const sha = reportedSha.toLowerCase();
236 if (!COMMIT_HASH_PATTERN.test(sha)) {
237 return yield* new PullRequestOperationError({
238 operation: "generateReviewGuide",
239 detail: `The host reported a head for #${number} that is not a commit hash.`,
240 });
241 }
242 // Not redundant: rev-parse prefers a branch or tag named like a short hash over the commit.
243 const resolveHead = git.resolveCommit({ cwd: workspaceRoot, revision: sha }).pipe(
244 Effect.filterOrFail(
245 ({ commitSha }) => commitSha.startsWith(sha),
246 ({ commitSha }) =>
247 new PullRequestOperationError({
248 operation: "generateReviewGuide",
249 detail: `${sha} names ${commitSha} here, a branch or tag rather than the commit.`,
250 }),
251 ),
252 );
253 const fetchAndResolve = (ref: string) => fetch([ref]).pipe(Effect.andThen(resolveHead));
254 const headRef = sourceControlDefinitions.get(detail.provider).changeRequestHeadRef?.(number);
255 const branchRef = `refs/heads/${branch}`;
256 const checkBranch = git.execute({
257 operation: "PullRequestReviewGuideService.checkHeadBranch",
258 cwd: workspaceRoot,
259 args: ["check-ref-format", branchRef],
260 });
261 const sources = [
262 { source: "local objects", head: resolveHead },
263 ...(sha.length === 40 || sha.length === 64
264 ? [{ source: "the commit", head: fetchAndResolve(sha) }]
265 : []),
266 {
267 source: `branch ${branch}`,
268 head: checkBranch.pipe(Effect.andThen(fetchAndResolve(branchRef))),
269 },
270 ...(headRef === undefined ? [] : [{ source: headRef, head: fetchAndResolve(headRef) }]),
271 ];
272 const failures: Array<string> = [];
273 for (const { source, head } of sources) {
274 const result = yield* Effect.result(head);
275 if (Result.isSuccess(result)) return result.success;
276 failures.push(`${source}: ${result.failure.detail}`);
277 }
278 return yield* new PullRequestOperationError({
279 operation: "generateReviewGuide",
280 detail: `Could not find head ${sha} of #${number}. ${failures.join(" ")}`,
281 });
282 });
283 const resolvedHead = yield* fetchHead(detail.number, headSha, detail.headBranch);
284 const layers: ReadonlyArray<ReviewGuideStackLayer> = yield* Effect.forEach(
285 stack?.layers ?? [],
286 (layer) => {
287 const described = { number: layer.number, title: layer.title ?? null, state: layer.state };
288 if (layer.number === detail.number) return Effect.succeed({ ...described, headSha });
289 const sha = layer.headSha;
290 if (sha === undefined) return Effect.succeed({ ...described, headSha: null });
291 return fetchHead(layer.number, sha, layer.headBranch).pipe(
292 Effect.map(({ commitSha }) => ({ ...described, headSha: commitSha })),
293 Effect.catch((error) =>
294 Effect.logInfo("Review guide could not read a stack layer's head", {
295 layer: layer.number,
296 detail: error.detail,
297 }).pipe(Effect.as({ ...described, headSha: null })),
298 ),
299 );
300 },
301 { concurrency: 4 },
302 );
303 const directory = yield* fileSystem.makeTempDirectoryScoped({
304 directory: config.worktreesDir,
305 prefix: "review-guide-",
306 });
307 const path = `${directory}/checkout`;
308 yield* git.execute({
309 operation: "PullRequestReviewGuideService.addWorktree",
310 cwd: workspaceRoot,
311 args: ["worktree", "add", "--detach", "--quiet", path, resolvedHead.commitSha],
312 timeoutMs: 5 * 60_000,
313 });
314 yield* Effect.addFinalizer(() =>
315 git
316 .removeWorktree({ cwd: workspaceRoot, path, force: true })
317 .pipe(Effect.ignore({ log: true })),
318 );
319 const mergeBase = yield* git.execute({
320 operation: "PullRequestReviewGuideService.mergeBase",
321 cwd: path,
322 args: ["merge-base", baseTip.commitSha, "HEAD"],
323 });
324 return { path, baseCommit: mergeBase.stdout.trim(), stack: layers };
325 });
326​
327 const readChange = Effect.fn("PullRequestReviewGuideService.readChange")(function* (
328 cwd: string,
329 baseCommit: string,
330 ) {
331 const diff = (args: ReadonlyArray<string>) =>
332 git
333 .execute({
334 operation: "PullRequestReviewGuideService.readChange",
335 cwd,
336 // Fixed prefixes: a user's diff.noPrefix or custom prefixes would hide the headers the
337 // parser reads.
338 args: [
339 "-c",
340 "core.quotePath=false",
341 "diff",
342 ...PATCH_RENDER_PREFIX_ARGS,
343 ...args,
344 `${baseCommit}...HEAD`,
345 ],
346 timeoutMs: 60_000,
347 maxOutputBytes: 64 * 1024 * 1024,
348 })
349 .pipe(Effect.map((result) => result.stdout));
350 const [nameOnly, patch] = yield* Effect.all(
351 [diff(["--name-only", "-z"]), diff(["--unified=0", "--no-color", "--no-ext-diff"])],
352 { concurrency: "unbounded" },
353 );
354 return parseReviewGuideChange(nameOnly, patch);
355 });
356​
357 const write = Effect.fn("PullRequestReviewGuideService.write")(function* (
358 input: PullRequestRef,
359 key: ThreadPullRequestKey,
360 workspaceRoot: string,
361 locator: RepositoryIdentity["locator"],
362 detail: PullRequestDetail,
363 headSha: string,
364 runId: string,
365 owns: Effect.Effect<boolean>,
366 ) {
367 const [activity, settings, providers, stack] = yield* Effect.all(
368 [
369 pullRequests.activity(input),
370 serverSettings.getSettings,
371 providerRegistry.getProviders,
372 pullRequests.stack(input).pipe(Effect.orElseSucceed(() => null)),
373 ],
374 { concurrency: "unbounded" },
375 );
376 const projectSettings = resolveProjectSettings(settings, input.projectId).settings;
377 const modelSelection = ServerSettings.resolveReviewGuideModelSelection(
378 projectSettings,
379 providers,
380 input.projectId,
381 );
382 const { generated, change } = yield* checkoutHead(
383 workspaceRoot,
384 locator,
385 detail,
386 headSha,
387 stack,
388 runId,
389 ).pipe(
390 Effect.flatMap((checkout) =>
391 Effect.all(
392 {
393 generated: textGeneration.generateReviewGuide({
394 ...reviewGuideInputFromPullRequest(detail, activity, checkout.baseCommit),
395 cwd: checkout.path,
396 modelSelection,
397 instructions: projectSettings.reviewGuideInstructions,
398 stack: checkout.stack,
399 }),
400 change: readChange(checkout.path, checkout.baseCommit),
401 },
402 { concurrency: "unbounded" },
403 ),
404 ),
405 Effect.scoped,
406 );
407 const guide: PullRequestReviewGuide = {
408 headSha,
409 generatedAt: yield* nowIso,
410 modelSelection,
411 ...normalizeReviewGuide(generated, change),
412 };
413 yield* ownership.withPermits(1)(
414 Effect.gen(function* () {
415 if (yield* owns) yield* guides.put(key, guide);
416 }),
417 );
418 });
419​
420 const failureDetail = (cause: Cause.Cause<unknown>): string => {
421 const error = Cause.squash(cause);
422 if (error instanceof Error && "detail" in error && typeof error.detail === "string") {
423 return error.detail;
424 }
425 return "The review guide could not be written.";
426 };
427​
428 const generate: PullRequestReviewGuideService["Service"]["generate"] = Effect.fn(
429 "PullRequestReviewGuideService.generate",
430 )(function* (input) {
431 const settings = yield* serverSettings.getSettings.pipe(
432 Effect.mapError(
433 (cause) =>
434 new PullRequestOperationError({
435 operation: "generateReviewGuide",
436 detail: "Could not read the server settings.",
437 cause,
438 }),
439 ),
440 );
441 if (!settings.reviewGuidesEnabled) {
442 return yield* new PullRequestOperationError({
443 operation: "generateReviewGuide",
444 detail: "Review guides are off. Turn them on in Settings → Source Control.",
445 });
446 }
447 const { key, workspaceRoot, identity } = yield* keyFor(input);
448 const locator = yield* requireOwnRepository(key, identity);
449 const runKey = keyString(key);
450 yield* pullRequests.invalidate({ reference: input });
451 const [detail, stored] = yield* Effect.all([pullRequests.detail(input), readStored(key)], {
452 concurrency: "unbounded",
453 });
454 const currentHeadSha = detail.headSha ?? null;
455 if (currentHeadSha === null) {
456 return yield* new PullRequestOperationError({
457 operation: "generateReviewGuide",
458 detail: "This host did not report the pull request's head commit.",
459 });
460 }
461 const running: PullRequestReviewGuideRun = {
462 _tag: "Running",
463 headSha: currentHeadSha,
464 startedAt: yield* nowIso,
465 };
466 // Claimed atomically, so two readers pressing Generate start one run between them. The head
467 // is read again under the claim: a press that read an older head before a push must not
468 // replace a run another press started for the new one, so it asks to be pressed again.
469 const claimed = yield* ownership.withPermits(1)(
470 pullRequests.detail(input).pipe(
471 Effect.flatMap((latest) =>
472 (latest.headSha ?? null) !== currentHeadSha
473 ? Effect.fail(
474 new PullRequestOperationError({
475 operation: "generateReviewGuide",
476 detail: "The pull request changed while the guide was starting. Try again.",
477 }),
478 )
479 : Ref.modify(runs, (current) => {
480 const existing = current.get(runKey);
481 if (existing?._tag === "Running" && existing.headSha === currentHeadSha) {
482 return [existing, current] as const;
483 }
484 return [running, new Map(current).set(runKey, running)] as const;
485 }),
486 ),
487 ),
488 );
489 if (claimed !== running) return { guide: stored, run: claimed, currentHeadSha, started: false };
490​
491 const owns = Ref.get(runs).pipe(Effect.map((current) => current.get(runKey) === running));
492 const finish = (next: PullRequestReviewGuideRun | null) =>
493 Ref.update(runs, (current) => {
494 if (current.get(runKey) !== running) return current;
495 const updated = new Map(current);
496 if (next === null) updated.delete(runKey);
497 else updated.set(runKey, next);
498 return updated;
499 });
500 const runId = `${runCounter++}`;
501 yield* write(input, key, workspaceRoot, locator, detail, currentHeadSha, runId, owns).pipe(
502 Effect.andThen(finish(null)),
503 Effect.catchCause((cause) =>
504 Cause.hasInterruptsOnly(cause)
505 ? finish(null)
506 : Effect.logWarning("Review guide generation failed", {
507 key: runKey,
508 cause: Cause.pretty(cause),
509 }).pipe(
510 Effect.andThen(nowIso),
511 Effect.flatMap((failedAt) =>
512 finish({
513 _tag: "Failed",
514 headSha: currentHeadSha,
515 failedAt,
516 detail: failureDetail(cause),
517 }),
518 ),
519 ),
520 ),
521 Effect.forkIn(serviceScope),
522 );
523 return { guide: stored, run: running, currentHeadSha, started: true };
524 });
525​
526 return PullRequestReviewGuideService.of({ get, generate });
527});
528​
529export const layer = Layer.effect(PullRequestReviewGuideService, make);