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

ThreadPullRequestReactor.ts

414 lines17.0 KB

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