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

ThreadPullRequestReactor.ts

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