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

ThreadPullRequestReactor.ts

370 lines14.9 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 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
178 recoverTransientFailure: false,
179 });
180 if (previous.state === "merged" || previous.state === "closed") {
181 branchPullRequest = thread.branchPullRequest;
182 }
183 }
184​
185 let replacement: ThreadLinkedPullRequest | undefined;
186 if (
187 thread.pullRequests.length === 0 &&
188 thread.linkedPullRequest != null &&
189 detected?.state === "open" &&
190 detectedReference !== null &&
191 !samePullRequest(thread.linkedPullRequest, detectedReference)
192 ) {
193 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
194 recoverTransientFailure: false,
195 });
196 if (linked.state === "merged" || linked.state === "closed") {
197 replacement = detectedReference;
198 }
199 }
200​
201 if (
202 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
203 replacement === undefined
204 ) {
205 pendingBackfill.delete(thread.id);
206 return null;
207 }
208 return { thread, branchPullRequest, replacement };
209 }).pipe(
210 Effect.catchCauseIf(
211 (cause) => !Cause.hasInterruptsOnly(cause),
212 (cause) =>
213 Effect.logWarning("thread pull request discovery failed", {
214 threadId: thread.id,
215 cause: Cause.pretty(cause),
216 }).pipe(
217 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
218 Effect.as(null),
219 ),
220 ),
221 ),
222 );
223 const updates = plans.filter((plan) => plan !== null);
224 if (updates.length === 0) return;
225​
226 if (detected !== null && first.branch !== null) {
227 // Summary reads can outlast a remote edit. Recheck the branch and
228 // the project's primary remote before saving the group's links.
229 const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
230 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
231 refresh: true,
232 });
233 if (
234 current === null ||
235 current.number !== detected.number ||
236 current.url !== detected.url ||
237 current.state !== detected.state ||
238 current.repositoryKey !== detected.repositoryKey ||
239 !pullRequestMatchesProject(current, {
240 ...project,
241 repositoryIdentity: currentIdentity,
242 })
243 ) {
244 return failBackfill(updates.map((update) => update.thread));
245 }
246 }
247​
248 yield* Effect.forEach(
249 updates,
250 ({ thread, branchPullRequest, replacement }) =>
251 Effect.gen(function* () {
252 const uuid = yield* crypto.randomUUIDv4;
253 yield* engine.dispatch({
254 type: "thread.pull-request.sync",
255 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
256 threadId: thread.id,
257 projectId: project.id,
258 snapshotSequence: snapshot.snapshotSequence,
259 expected: {
260 workspaceRoot: project.workspaceRoot,
261 branch: thread.branch,
262 worktreePath: thread.worktreePath,
263 linkedPullRequest: thread.linkedPullRequest ?? null,
264 branchPullRequest: thread.branchPullRequest ?? null,
265 },
266 branchPullRequest,
267 ...(replacement !== undefined ? { linkedPullRequest: replacement } : {}),
268 });
269 pendingBackfill.delete(thread.id);
270 }).pipe(
271 // The thread changed since the lookup. Its own events requeue it.
272 Effect.catchTags({
273 OrchestrationCommandInvariantError: () =>
274 Effect.sync(() => finishBackfill([thread])),
275 }),
276 Effect.catchCauseIf(
277 (cause) => !Cause.hasInterruptsOnly(cause),
278 (cause) =>
279 Effect.logWarning("thread pull request update failed", {
280 threadId: thread.id,
281 cause: Cause.pretty(cause),
282 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
283 ),
284 ),
285 { discard: true },
286 );
287 }).pipe(
288 Effect.catchCauseIf(
289 (cause) => !Cause.hasInterruptsOnly(cause),
290 (cause) =>
291 Effect.logWarning("thread branch pull request lookup failed", {
292 threadIds: group.map((thread) => thread.id),
293 cause: Cause.pretty(cause),
294 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
295 ),
296 ),
297 { concurrency: 8, discard: true },
298 );
299 });
300​
301 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
302 synchronize(request).pipe(
303 Effect.catchCauseIf(
304 (cause) => !Cause.hasInterruptsOnly(cause),
305 (cause) =>
306 Effect.logWarning("thread pull request refresh failed", {
307 cause: Cause.pretty(cause),
308 }),
309 ),
310 ),
311 );
312​
313 const processEvent = (event: OrchestrationEvent) => {
314 switch (event.type) {
315 case "thread.created":
316 case "thread.unarchived":
317 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
318 case "thread.meta-updated":
319 if (
320 event.payload.branchPullRequest === undefined &&
321 (event.payload.branch !== undefined ||
322 event.payload.worktreePath !== undefined ||
323 event.payload.linkedPullRequest !== undefined)
324 ) {
325 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
326 }
327 break;
328 case "thread.session-set":
329 if (
330 event.payload.session.status !== "running" &&
331 event.payload.session.status !== "starting"
332 ) {
333 // Checkpoint completion forces the post-turn read. Session lifecycle
334 // events reuse it regardless of which event reaches this worker first.
335 return worker.enqueue({ threadId: event.payload.threadId, refresh: false });
336 }
337 break;
338 case "thread.turn-diff-completed":
339 case "thread.unsettled":
340 return worker.enqueue({ threadId: event.payload.threadId, refresh: true });
341 case "project.meta-updated":
342 if (event.payload.workspaceRoot !== undefined) {
343 return worker.enqueue({ threadId: null, refresh: false });
344 }
345 break;
346 }
347 return Effect.void;
348 };
349​
350 const start = Effect.fn("ThreadPullRequestReactor.start")(function* () {
351 const events = yield* engine.subscribeDomainEvents;
352 yield* forkParked(Stream.runForEach(events, processEvent));
353 // Run without client demand. Saved branch lookups share GitManager's
354 // provider cache and retry backoff with status and automatic settlement.
355 yield* forkParked(
356 Effect.gen(function* () {
357 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
358 yield* worker.drain;
359 yield* Effect.gen(function* () {
360 yield* worker.enqueue({ threadId: null, refresh: false });
361 yield* worker.drain;
362 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
363 }).pipe(Effect.asVoid),
364 );
365 });
366​
367 return { start, drain: worker.drain } satisfies ThreadPullRequestReactor["Service"];
368});
369​
370export const layer = Layer.effect(ThreadPullRequestReactor, make);