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

ThreadPullRequestReactor.ts

371 lines14.8 KB

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