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

ThreadPullRequestService.ts

405 lines15.9 KB

1import {
2 canonicalRepositoryKey,
3 sourceControlRepositorySelector,
4} from "@t3tools/shared/sourceControl";
5import {
6 CommandId,
7 type OrchestrationProjectShell,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2ThreadShell,
10 type ThreadId,
11 type ThreadLinkedPullRequest,
12} from "@t3tools/contracts";
13import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
14import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
15import * as Cause from "effect/Cause";
16import * as Context from "effect/Context";
17import * as Crypto from "effect/Crypto";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Schedule from "effect/Schedule";
23import type * as Scope from "effect/Scope";
24import * as Stream from "effect/Stream";
25​
26import * as GitManager from "../git/GitManager.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as PullRequestService from "../pullRequest/PullRequestService.ts";
29import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
30import { forkParked } from "../serverActivation.ts";
31import * as Orchestrator from "./Orchestrator.ts";
32​
33class ThreadPullRequestServiceV2 extends Context.Service<
34 ThreadPullRequestServiceV2,
35 {
36 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
37 readonly drain: Effect.Effect<void>;
38 }
39>()("t3/orchestration-v2/ThreadPullRequestService/ThreadPullRequestServiceV2") {}
40​
41function samePullRequest(
42 left: ThreadLinkedPullRequest | null | undefined,
43 right: ThreadLinkedPullRequest | null,
44): boolean {
45 if (left == null || right === null) return left == null && right === null;
46 return (
47 left.projectId === right.projectId &&
48 left.repository.toLowerCase() === right.repository.toLowerCase() &&
49 left.number === right.number &&
50 left.url === right.url
51 );
53​
54function pullRequestMatchesProject(
55 pullRequest: GitManager.GitBranchPullRequest,
56 project: OrchestrationProjectShell,
57): boolean {
58 return (
59 pullRequest.repositoryKey !== null &&
60 project.repositoryIdentity != null &&
61 canonicalRepositoryKey(pullRequest.repositoryKey) ===
62 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
63 );
65​
66export const resolveProjectForPullRequestDiscovery = Effect.fn(
67 "ThreadPullRequestServiceV2.resolveProject",
68)(function* (
69 project: OrchestrationProjectShell,
70 repositoryIdentities: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
71 options?: { readonly refresh?: boolean },
72) {
73 // Identities stay cached for 15 minutes. A finished turn may have added the
74 // remote its pull request lives on, so post-turn discovery refreshes.
75 const repositoryIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
76 refresh: options?.refresh ?? false,
77 });
78 return {
79 project: { ...project, repositoryIdentity },
80 repository: sourceControlRepositorySelector(repositoryIdentity),
81 };
82});
83​
84export function projectWorkspaceMatchesSnapshot(
85 currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
86 expectedWorkspaceRoot: string,
87): boolean {
88 return (
89 Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
90 );
92​
93const BACKFILL_ATTEMPTS = 5;
94​
95interface RefreshRequest {
96 readonly threadId: ThreadId | null;
97 readonly refresh: boolean;
98 readonly backfill?: boolean;
100​
101export const make = Effect.gen(function* () {
102 const orchestrator = yield* Orchestrator.OrchestratorV2;
103 const projectStore = yield* ProjectStore.ProjectStoreV2;
104 const git = yield* GitManager.GitManager;
105 const pullRequests = yield* PullRequestService.PullRequestService;
106 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
107 const crypto = yield* Crypto.Crypto;
108 const fileSystem = yield* FileSystem.FileSystem;
109 const pendingBackfill = new Map<ThreadId, number>();
110​
111 const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
112 for (const thread of threads) pendingBackfill.delete(thread.id);
113 };
114 const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
115 for (const thread of threads) {
116 const remaining = pendingBackfill.get(thread.id);
117 if (remaining === undefined) continue;
118 if (remaining <= 1) pendingBackfill.delete(thread.id);
119 else pendingBackfill.set(thread.id, remaining - 1);
120 }
121 };
122​
123 const readThreadSnapshot = ({ threadId, backfill }: RefreshRequest) =>
124 threadId === null
125 ? orchestrator
126 .getShellSnapshot({
127 location: "active",
128 unsettledOnly: !(backfill || pendingBackfill.size > 0),
129 })
130 .pipe(NodeSqliteClient.readOnly)
131 : Effect.gen(function* () {
132 // Read the sequence first. The thread is then at least this new, so a
133 // sync guarded by the sequence is rejected rather than missing a change.
134 const snapshotSequence = yield* orchestrator.getThreadEventSequence(threadId);
135 const thread = yield* orchestrator.getThreadShell(threadId);
136 return { snapshotSequence, threads: thread === null ? [] : [thread] };
137 });
138​
139 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
140 request: RefreshRequest,
141 ) {
142 const [threadSnapshot, projectShells] = yield* Effect.all([
143 readThreadSnapshot(request),
144 projectStore.listShells(),
145 ]);
146 const projects = new Map(projectShells.map((project) => [project.id, project]));
147 if (request.backfill) {
148 for (const thread of threadSnapshot.threads) {
149 if (
150 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
151 thread.branchPullRequest == null
152 ) {
153 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
154 }
155 }
156 }
157 const visibleThreadIds = new Set(
158 threadSnapshot.threads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
159 );
160 const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
161 for (const threadId of checkedIds) {
162 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
163 }
164 const threads = threadSnapshot.threads.filter(
165 (thread) =>
166 thread.archivedAt === null &&
167 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
168 request.threadId !== null ||
169 pendingBackfill.has(thread.id)) &&
170 (thread.branch !== null || thread.branchPullRequest != null),
171 );
172 const groups = Map.groupBy(threads, (thread) =>
173 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
174 );
175​
176 yield* Effect.forEach(
177 groups.values(),
178 (group) =>
179 Effect.gen(function* () {
180 const first = group[0]!;
181 const project = projects.get(first.projectId);
182 if (project === undefined) return finishBackfill(group);
183 const { project: resolvedProject, repository } =
184 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
185 refresh: request.refresh,
186 });
187 if (first.branch !== null && repository === null) return finishBackfill(group);
188 const worktreeExists =
189 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
190 const cwd =
191 worktreeExists && first.worktreePath !== null
192 ? first.worktreePath
193 : project.workspaceRoot;
194 const detected =
195 first.branch === null
196 ? null
197 : yield* git.branchPullRequest(
198 { cwd, branch: first.branch },
199 { refresh: request.refresh },
200 );
201 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
202 return finishBackfill(group);
203 }
204 const detectedReference =
205 detected !== null && repository !== null
206 ? {
207 projectId: project.id,
208 repository,
209 number: detected.number,
210 url: detected.url,
211 }
212 : null;
213​
214 const plans = yield* Effect.forEach(group, (thread) =>
215 Effect.gen(function* () {
216 let branchPullRequest = detectedReference;
217 if (
218 branchPullRequest === null &&
219 thread.branch !== null &&
220 thread.worktreePath === null &&
221 thread.branchPullRequest != null
222 ) {
223 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
224 recoverTransientFailure: false,
225 });
226 if (previous.state === "merged" || previous.state === "closed") {
227 branchPullRequest = thread.branchPullRequest;
228 }
229 }
230​
231 let replacement: ThreadLinkedPullRequest | undefined;
232 if (
233 (thread.pullRequests ?? []).length === 0 &&
234 thread.linkedPullRequest != null &&
235 detected?.state === "open" &&
236 detectedReference !== null &&
237 !samePullRequest(thread.linkedPullRequest, detectedReference)
238 ) {
239 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
240 recoverTransientFailure: false,
241 });
242 if (linked.state === "merged" || linked.state === "closed") {
243 replacement = detectedReference;
244 }
245 }
246 if (
247 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
248 replacement === undefined
249 ) {
250 pendingBackfill.delete(thread.id);
251 return null;
252 }
253 return { thread, branchPullRequest, replacement };
254 }).pipe(
255 Effect.catchCauseIf(
256 (cause) => !Cause.hasInterruptsOnly(cause),
257 (cause) =>
258 Effect.logWarning("thread pull request discovery failed", {
259 threadId: thread.id,
260 cause: Cause.pretty(cause),
261 }).pipe(
262 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
263 Effect.as(null),
264 ),
265 ),
266 ),
267 );
268 const updates = plans.filter((plan) => plan !== null);
269 if (updates.length === 0) return;
270​
271 if (detected !== null && first.branch !== null) {
272 const current = yield* git.branchPullRequest(
273 { cwd, branch: first.branch },
274 { freshGitState: true },
275 );
276 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
277 refresh: true,
278 });
279 if (
280 current === null ||
281 current.number !== detected.number ||
282 current.url !== detected.url ||
283 current.state !== detected.state ||
284 current.repositoryKey !== detected.repositoryKey ||
285 !pullRequestMatchesProject(current, {
286 ...project,
287 repositoryIdentity: currentIdentity,
288 })
289 ) {
290 return failBackfill(updates.map((update) => update.thread));
291 }
292 }
293​
294 yield* Effect.forEach(
295 updates,
296 ({ thread, branchPullRequest, replacement }) =>
297 Effect.gen(function* () {
298 // Discovery can perform network I/O. Re-read the project at
299 // the transaction boundary so a deleted project or changed
300 // workspace root cannot apply a result from the old checkout.
301 const currentProject = yield* projectStore.getShell(project.id);
302 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
303 return failBackfill([thread]);
304 }
305 const uuid = yield* crypto.randomUUIDv4();
306 yield* orchestrator.dispatch({
307 type: "thread.pull-request.sync",
308 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
309 threadId: thread.id,
310 projectId: project.id,
311 snapshotSequence: threadSnapshot.snapshotSequence,
312 expected: {
313 workspaceRoot: project.workspaceRoot,
314 branch: thread.branch,
315 worktreePath: thread.worktreePath,
316 linkedPullRequest: thread.linkedPullRequest ?? null,
317 branchPullRequest: thread.branchPullRequest ?? null,
318 },
319 branchPullRequest,
320 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
321 });
322 pendingBackfill.delete(thread.id);
323 }).pipe(
324 Effect.catchCause((cause) =>
325 Cause.hasInterruptsOnly(cause)
326 ? Effect.failCause(cause)
327 : Effect.logWarning("thread pull request update failed", {
328 threadId: thread.id,
329 cause: Cause.pretty(cause),
330 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
331 ),
332 ),
333 { discard: true },
334 );
335 }).pipe(
336 Effect.catchCauseIf(
337 (cause) => !Cause.hasInterruptsOnly(cause),
338 (cause) =>
339 Effect.logWarning("thread branch pull request lookup failed", {
340 threadIds: group.map((thread) => thread.id),
341 cause: Cause.pretty(cause),
342 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
343 ),
344 ),
345 // Wide enough that a sweep's GitHub branch lookups reach the GitHub provider together and share one
346 // GraphQL document, instead of one `gh pr list` per branch.
347 { concurrency: 32, discard: true },
348 );
349 });
350​
351 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
352 synchronize(request).pipe(
353 Effect.catchCauseIf(
354 (cause) => !Cause.hasInterruptsOnly(cause),
355 (cause) =>
356 Effect.logWarning("thread pull request refresh failed", {
357 cause: Cause.pretty(cause),
358 }),
359 ),
360 ),
361 );
362​
363 const processEvent = (event: OrchestrationV2DomainEvent) => {
364 switch (event.type) {
365 case "thread.created":
366 case "thread.unarchived":
367 case "thread.metadata-updated":
368 return worker.enqueue({ threadId: event.threadId, refresh: false });
369 case "thread.unsettled":
370 case "checkpoint.captured":
371 return worker.enqueue({ threadId: event.threadId, refresh: true });
372 case "run.updated":
373 if (
374 event.payload.status === "completed" ||
375 event.payload.status === "failed" ||
376 event.payload.status === "cancelled" ||
377 event.payload.status === "interrupted"
378 ) {
379 return worker.enqueue({ threadId: event.threadId, refresh: true });
380 }
381 break;
382 }
383 return Effect.void;
384 };
385​
386 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
387 "ThreadPullRequestServiceV2.start",
388 )(function* () {
389 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
390 yield* forkParked(
391 Effect.gen(function* () {
392 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
393 yield* worker.drain;
394 yield* Effect.gen(function* () {
395 yield* worker.enqueue({ threadId: null, refresh: false });
396 yield* worker.drain;
397 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
398 }).pipe(Effect.asVoid),
399 );
400 });
401​
402 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
403});
404​
405const layer = Layer.effect(ThreadPullRequestServiceV2, make);