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

ThreadPullRequestReactor.ts

381 lines15.5 KB

1import {
2 canonicalRepositoryKey,
3 sourceControlRepositorySelector,
4} from "@t3tools/shared/sourceControl";
5import {
6 CommandId,
7 type OrchestrationEvent,
8 type OrchestrationProjectShell,
9 type ThreadId,
10 type ThreadLinkedPullRequest,
11} from "@t3tools/contracts";
12import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
13import * as Cause from "effect/Cause";
14import * as Context from "effect/Context";
15import * as Crypto from "effect/Crypto";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Schedule from "effect/Schedule";
20import type * as Scope from "effect/Scope";
21import * as Stream from "effect/Stream";
22​
23import * as GitManager from "../git/GitManager.ts";
24import * as PullRequestService from "../pullRequest/PullRequestService.ts";
25import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
26import { forkParked } from "../serverActivation.ts";
27import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
28import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
29​
30export class ThreadPullRequestReactor extends Context.Service<
31 ThreadPullRequestReactor,
32 {
33 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
34 readonly drain: Effect.Effect<void>;
35 }
36>()("t3/orchestration/ThreadPullRequestReactor") {}
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​
51/** Startup lookups per settled thread before discovery gives up on it. */
52export const BACKFILL_ATTEMPTS = 5;
53​
54interface RefreshRequest {
55 readonly threadId: ThreadId | null;
56 readonly refresh: boolean;
57 readonly backfill?: boolean;
59​
60export function pullRequestMatchesProject(
61 pullRequest: GitManager.GitBranchPullRequest,
62 project: OrchestrationProjectShell,
63): boolean {
64 return (
65 pullRequest.repositoryKey !== null &&
66 project.repositoryIdentity != null &&
67 canonicalRepositoryKey(pullRequest.repositoryKey) ===
68 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
69 );
71​
72/** @public Service construction is part of the canonical Effect module API. */
73export const make = Effect.gen(function* () {
74 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
75 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
76 const git = yield* GitManager.GitManager;
77 const pullRequests = yield* PullRequestService.PullRequestService;
78 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
79 const crypto = yield* Crypto.Crypto;
80 const fileSystem = yield* FileSystem.FileSystem;
81 // Settled threads get one link discovery at startup. Failed lookups retry on
82 // the periodic pass a few times, then stop until the thread changes or the
83 // server restarts, so a missing or logged-out CLI cannot loop forever.
84 const pendingBackfill = new Map<ThreadId, number>();
85 const finishBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
86 for (const thread of threads) pendingBackfill.delete(thread.id);
87 };
88 const failBackfill = (threads: ReadonlyArray<{ readonly id: ThreadId }>) => {
89 for (const thread of threads) {
90 const remaining = pendingBackfill.get(thread.id);
91 if (remaining === undefined) continue;
92 if (remaining <= 1) pendingBackfill.delete(thread.id);
93 else pendingBackfill.set(thread.id, remaining - 1);
94 }
95 };
96​
97 const synchronize = Effect.fn("ThreadPullRequestReactor.synchronize")(function* (
98 request: RefreshRequest,
99 ) {
100 const snapshot = yield* snapshots.getShellSnapshot();
101 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
102 if (request.backfill) {
103 for (const thread of snapshot.threads) {
104 if (
105 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
106 thread.branchPullRequest == null
107 ) {
108 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
109 }
110 }
111 }
112 const threadIds = new Set(snapshot.threads.map((thread) => thread.id));
113 for (const threadId of pendingBackfill.keys()) {
114 if (!threadIds.has(threadId)) pendingBackfill.delete(threadId);
115 }
116 const threads = snapshot.threads.filter(
117 (thread) =>
118 thread.archivedAt === null &&
119 (request.threadId === null || thread.id === request.threadId) &&
120 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
121 request.threadId !== null ||
122 pendingBackfill.has(thread.id)) &&
123 (thread.branch !== null || thread.branchPullRequest != null),
124 );
125 const groups = Map.groupBy(threads, (thread) =>
126 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
127 );
128​
129 yield* Effect.forEach(
130 groups.values(),
131 (group) =>
132 Effect.gen(function* () {
133 const first = group[0]!;
134 const project = projects.get(first.projectId);
135 if (project === undefined) return finishBackfill(group);
136 const repository = sourceControlRepositorySelector(project.repositoryIdentity);
137 if (first.branch !== null && repository === null) return finishBackfill(group);
138 const worktreeExists =
139 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
140 const cwd =
141 worktreeExists && first.worktreePath !== null
142 ? first.worktreePath
143 : project.workspaceRoot;
144 const detected =
145 first.branch === null
146 ? null
147 : yield* git.branchPullRequest(
148 { cwd, branch: first.branch },
149 { refresh: request.refresh },
150 );
151 // A worktree can have different remotes, and the project identity
152 // can lag a remote edit. Do not attach its PR to the wrong repository.
153 if (detected !== null && !pullRequestMatchesProject(detected, project)) {
154 return finishBackfill(group);
155 }
156 const detectedReference =
157 detected !== null && repository !== null
158 ? {
159 projectId: project.id,
160 repository,
161 number: detected.number,
162 url: detected.url,
163 }
164 : null;
165​
166 const plans = yield* Effect.forEach(group, (thread) =>
167 Effect.gen(function* () {
168 let branchPullRequest = detectedReference;
169 // Shared checkouts often return to the default branch after
170 // a merge. Keep that thread's terminal PR across the change.
171 if (
172 branchPullRequest === null &&
173 thread.branch !== null &&
174 thread.worktreePath === null &&
175 thread.branchPullRequest != null
176 ) {
177 // Unless the branch is why the lookup reported nothing. A
178 // long-lived branch reused after its release merged has moved
179 // off that change request, so restoring it here would put back
180 // the stale reference the lookup just rejected.
181 const superseded = yield* git.branchSupersededPullRequest({
182 cwd,
183 branch: thread.branch,
184 pullRequest: thread.branchPullRequest,
185 });
186 if (!superseded) {
187 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
188 recoverTransientFailure: false,
189 });
190 if (previous.state === "merged" || previous.state === "closed") {
191 branchPullRequest = thread.branchPullRequest;
192 }
193 }
194 }
195​
196 let replacement: ThreadLinkedPullRequest | undefined;
197 if (
198 thread.pullRequests.length === 0 &&
199 thread.linkedPullRequest != null &&
200 detected?.state === "open" &&
201 detectedReference !== null &&
202 !samePullRequest(thread.linkedPullRequest, detectedReference)
203 ) {
204 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
205 recoverTransientFailure: false,
206 });
207 if (linked.state === "merged" || linked.state === "closed") {
208 replacement = detectedReference;
209 }
210 }
211​
212 if (
213 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
214 replacement === undefined
215 ) {
216 pendingBackfill.delete(thread.id);
217 return null;
218 }
219 return { thread, branchPullRequest, replacement };
220 }).pipe(
221 Effect.catchCause((cause) =>
222 Cause.hasInterruptsOnly(cause)
223 ? Effect.failCause(cause)
224 : Effect.logWarning("thread pull request discovery failed", {
225 threadId: thread.id,
226 cause: Cause.pretty(cause),
227 }).pipe(
228 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
229 Effect.as(null),
230 ),
231 ),
232 ),
233 );
234 const updates = plans.filter((plan) => plan !== null);
235 if (updates.length === 0) return;
236​
237 if (detected !== null && first.branch !== null) {
238 // Summary reads can outlast a remote edit. Recheck the branch and
239 // the project's primary remote before saving the group's links.
240 const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
241 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
242 refresh: true,
243 });
244 if (
245 current === null ||
246 current.number !== detected.number ||
247 current.url !== detected.url ||
248 current.state !== detected.state ||
249 current.repositoryKey !== detected.repositoryKey ||
250 !pullRequestMatchesProject(current, {
251 ...project,
252 repositoryIdentity: currentIdentity,
253 })
254 ) {
255 return failBackfill(updates.map((update) => update.thread));
256 }
257 }
258​
259 yield* Effect.forEach(
260 updates,
261 ({ thread, branchPullRequest, replacement }) =>
262 Effect.gen(function* () {
263 const uuid = yield* crypto.randomUUIDv4;
264 yield* engine.dispatch({
265 type: "thread.pull-request.sync",
266 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
267 threadId: thread.id,
268 projectId: project.id,
269 snapshotSequence: snapshot.snapshotSequence,
270 expected: {
271 workspaceRoot: project.workspaceRoot,
272 branch: thread.branch,
273 worktreePath: thread.worktreePath,
274 linkedPullRequest: thread.linkedPullRequest ?? null,
275 branchPullRequest: thread.branchPullRequest ?? null,
276 },
277 branchPullRequest,
278 ...(replacement !== undefined ? { linkedPullRequest: replacement } : {}),
279 });
280 pendingBackfill.delete(thread.id);
281 }).pipe(
282 // The thread changed since the lookup. Its own events requeue it.
283 Effect.catchTags({
284 OrchestrationCommandInvariantError: () =>
285 Effect.sync(() => finishBackfill([thread])),
286 }),
287 Effect.catchCause((cause) =>
288 Cause.hasInterruptsOnly(cause)
289 ? Effect.failCause(cause)
290 : Effect.logWarning("thread pull request update failed", {
291 threadId: thread.id,
292 cause: Cause.pretty(cause),
293 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
294 ),
295 ),
296 { discard: true },
297 );
298 }).pipe(
299 Effect.catchCause((cause) =>
300 Cause.hasInterruptsOnly(cause)
301 ? Effect.failCause(cause)
302 : Effect.logWarning("thread branch pull request lookup failed", {
303 threadIds: group.map((thread) => thread.id),
304 cause: Cause.pretty(cause),
305 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
306 ),
307 ),
308 { concurrency: 8, discard: true },
309 );
310 });
311​
312 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
313 synchronize(request).pipe(
314 Effect.catchCause((cause) =>
315 Cause.hasInterruptsOnly(cause)
316 ? Effect.failCause(cause)
317 : Effect.logWarning("thread pull request refresh failed", {
318 cause: Cause.pretty(cause),
319 }),
320 ),
321 ),
322 );
323​
324 const processEvent = (event: OrchestrationEvent) => {
325 switch (event.type) {
326 case "thread.created":
327 case "thread.unarchived":
328 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
329 case "thread.meta-updated":
330 if (
331 event.payload.branchPullRequest === undefined &&
332 (event.payload.branch !== undefined ||
333 event.payload.worktreePath !== undefined ||
334 event.payload.linkedPullRequest !== undefined)
335 ) {
336 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
337 }
338 break;
339 case "thread.session-set":
340 if (
341 event.payload.session.status !== "running" &&
342 event.payload.session.status !== "starting"
343 ) {
344 // Checkpoint completion forces the post-turn read. Session lifecycle
345 // events reuse it regardless of which event reaches this worker first.
346 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
347 }
348 break;
349 case "thread.turn-diff-completed":
350 case "thread.unsettled":
351 return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
352 case "project.meta-updated":
353 if (event.payload.workspaceRoot !== undefined) {
354 return worker.enqueue({ threadId: null, refresh: false });
355 }
356 break;
357 }
358 return Effect.void;
359 };
360​
361 const start = Effect.fn("ThreadPullRequestReactor.start")(function* () {
362 const events = yield* engine.subscribeDomainEvents;
363 yield* forkParked(Stream.runForEach(events, processEvent));
364 // Run without client demand. Saved branch lookups share GitManager's
365 // provider cache and retry backoff with status and automatic settlement.
366 yield* forkParked(
367 Effect.gen(function* () {
368 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
369 yield* worker.drain;
370 yield* Effect.gen(function* () {
371 yield* worker.enqueue({ threadId: null, refresh: false });
372 yield* worker.drain;
373 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
374 }).pipe(Effect.asVoid),
375 );
376 });
377​
378 return { start, drain: worker.drain } satisfies ThreadPullRequestReactor["Service"];
379});
380​
381export const layer = Layer.effect(ThreadPullRequestReactor, make);