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

ThreadPullRequestService.ts

402 lines16.0 KB

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