Open History to see the last commit
1import {
2 canonicalRepositoryKey,
3 sourceControlRepositorySelector,
4} from "@t3tools/shared/sourceControl";
5import {
6 CommandId,
7 type OrchestrationProjectShell,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2ThreadShell,
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 * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
27import * as PullRequestService from "../pullRequest/PullRequestService.ts";
28import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29import { forkParked } from "../serverActivation.ts";
30import { OrchestratorV2 } from "./Orchestrator.ts";
31
32class ThreadPullRequestServiceV2 extends Context.Service<
33 ThreadPullRequestServiceV2,
34 {
35 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
36 readonly drain: Effect.Effect<void>;
37 }
38>()("t3/orchestration-v2/ThreadPullRequestService/ThreadPullRequestServiceV2") {}
39
40function samePullRequest(
41 left: ThreadLinkedPullRequest | null | undefined,
42 right: ThreadLinkedPullRequest | null,
43): boolean {
44 if (left == null || right === null) return left == null && right === null;
45 return (
46 left.projectId === right.projectId &&
47 left.repository.toLowerCase() === right.repository.toLowerCase() &&
48 left.number === right.number &&
49 left.url === right.url
50 );
51}
52
53function pullRequestMatchesProject(
54 pullRequest: GitManager.GitBranchPullRequest,
55 project: OrchestrationProjectShell,
56): boolean {
57 return (
58 pullRequest.repositoryKey !== null &&
59 project.repositoryIdentity != null &&
60 canonicalRepositoryKey(pullRequest.repositoryKey) ===
61 canonicalRepositoryKey(project.repositoryIdentity.canonicalKey)
62 );
63}
64
65export const resolveProjectForPullRequestDiscovery = Effect.fn(
66 "ThreadPullRequestServiceV2.resolveProject",
67)(function* (
68 project: OrchestrationProjectShell,
69 repositoryIdentities: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"],
70) {
71 const repositoryIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot);
72 return {
73 project: { ...project, repositoryIdentity },
74 repository: sourceControlRepositorySelector(repositoryIdentity),
75 };
76});
77
78export function projectWorkspaceMatchesSnapshot(
79 currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
80 expectedWorkspaceRoot: string,
81): boolean {
82 return (
83 Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
84 );
85}
86
87const BACKFILL_ATTEMPTS = 5;
88
89interface RefreshRequest {
90 readonly threadId: ThreadId | null;
91 readonly refresh: boolean;
92 readonly backfill?: boolean;
93}
94
95export const make = Effect.gen(function* () {
96 const orchestrator = yield* OrchestratorV2;
97 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
98 const git = yield* GitManager.GitManager;
99 const pullRequests = yield* PullRequestService.PullRequestService;
100 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
101 const crypto = yield* Crypto.Crypto;
102 const fileSystem = yield* FileSystem.FileSystem;
103 const pendingBackfill = new Map<ThreadId, number>();
104
105 const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
106 for (const thread of threads) pendingBackfill.delete(thread.id);
107 };
108 const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
109 for (const thread of threads) {
110 const remaining = pendingBackfill.get(thread.id);
111 if (remaining === undefined) continue;
112 if (remaining <= 1) pendingBackfill.delete(thread.id);
113 else pendingBackfill.set(thread.id, remaining - 1);
114 }
115 };
116
117 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
118 request: RefreshRequest,
119 ) {
120 const [threadSnapshot, projectShells] = yield* Effect.all([
121 orchestrator.getShellSnapshot(),
122 snapshots.getProjectShellsWithoutEnrichment(),
123 ]);
124 const projects = new Map(projectShells.map((project) => [project.id, project]));
125 if (request.backfill) {
126 for (const thread of threadSnapshot.threads) {
127 if (
128 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
129 thread.branchPullRequest == null
130 ) {
131 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
132 }
133 }
134 }
135 const visibleThreadIds = new Set(threadSnapshot.threads.map((thread) => thread.id));
136 for (const threadId of pendingBackfill.keys()) {
137 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
138 }
139 const threads = threadSnapshot.threads.filter(
140 (thread) =>
141 thread.archivedAt === null &&
142 (request.threadId === null || thread.id === request.threadId) &&
143 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
144 request.threadId !== null ||
145 pendingBackfill.has(thread.id)) &&
146 (thread.branch !== null || thread.branchPullRequest != null),
147 );
148 const groups = Map.groupBy(threads, (thread) =>
149 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
150 );
151
152 yield* Effect.forEach(
153 groups.values(),
154 (group) =>
155 Effect.gen(function* () {
156 const first = group[0]!;
157 const project = projects.get(first.projectId);
158 if (project === undefined) return finishBackfill(group);
159 const { project: resolvedProject, repository } =
160 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities);
161 if (first.branch !== null && repository === null) return finishBackfill(group);
162 const worktreeExists =
163 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
164 const cwd =
165 worktreeExists && first.worktreePath !== null
166 ? first.worktreePath
167 : project.workspaceRoot;
168 const detected =
169 first.branch === null
170 ? null
171 : yield* git.branchPullRequest(
172 { cwd, branch: first.branch },
173 { refresh: request.refresh },
174 );
175 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
176 return finishBackfill(group);
177 }
178 const detectedReference =
179 detected !== null && repository !== null
180 ? {
181 projectId: project.id,
182 repository,
183 number: detected.number,
184 url: detected.url,
185 }
186 : null;
187
188 const plans = yield* Effect.forEach(group, (thread) =>
189 Effect.gen(function* () {
190 let branchPullRequest = detectedReference;
191 if (
192 branchPullRequest === null &&
193 thread.branch !== null &&
194 thread.worktreePath === null &&
195 thread.branchPullRequest != null
196 ) {
197 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
198 recoverTransientFailure: false,
199 });
200 if (previous.state === "merged" || previous.state === "closed") {
201 branchPullRequest = thread.branchPullRequest;
202 }
203 }
204
205 let replacement: ThreadLinkedPullRequest | undefined;
206 if (
207 (thread.pullRequests ?? []).length === 0 &&
208 thread.linkedPullRequest != null &&
209 detected?.state === "open" &&
210 detectedReference !== null &&
211 !samePullRequest(thread.linkedPullRequest, detectedReference)
212 ) {
213 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
214 recoverTransientFailure: false,
215 });
216 if (linked.state === "merged" || linked.state === "closed") {
217 replacement = detectedReference;
218 }
219 }
220 if (
221 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
222 replacement === undefined
223 ) {
224 pendingBackfill.delete(thread.id);
225 return null;
226 }
227 return { thread, branchPullRequest, replacement };
228 }).pipe(
229 Effect.catchCause((cause) =>
230 Cause.hasInterruptsOnly(cause)
231 ? Effect.failCause(cause)
232 : Effect.logWarning("thread pull request discovery failed", {
233 threadId: thread.id,
234 cause: Cause.pretty(cause),
235 }).pipe(
236 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
237 Effect.as(null),
238 ),
239 ),
240 ),
241 );
242 const updates = plans.filter((plan) => plan !== null);
243 if (updates.length === 0) return;
244
245 if (detected !== null && first.branch !== null) {
246 const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
247 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
248 refresh: true,
249 });
250 if (
251 current === null ||
252 current.number !== detected.number ||
253 current.url !== detected.url ||
254 current.state !== detected.state ||
255 current.repositoryKey !== detected.repositoryKey ||
256 !pullRequestMatchesProject(current, {
257 ...project,
258 repositoryIdentity: currentIdentity,
259 })
260 ) {
261 return failBackfill(updates.map((update) => update.thread));
262 }
263 }
264
265 yield* Effect.forEach(
266 updates,
267 ({ thread, branchPullRequest, replacement }) =>
268 Effect.gen(function* () {
269 // Discovery can perform network I/O. Re-read the project at
270 // the transaction boundary so a deleted project or changed
271 // workspace root cannot apply a result from the old checkout.
272 const currentProject = yield* snapshots.getProjectShellById(project.id);
273 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
274 return failBackfill([thread]);
275 }
276 const uuid = yield* crypto.randomUUIDv4;
277 yield* orchestrator.dispatch({
278 type: "thread.pull-request.sync",
279 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
280 threadId: thread.id,
281 projectId: project.id,
282 snapshotSequence: threadSnapshot.snapshotSequence,
283 expected: {
284 workspaceRoot: project.workspaceRoot,
285 branch: thread.branch,
286 worktreePath: thread.worktreePath,
287 linkedPullRequest: thread.linkedPullRequest ?? null,
288 branchPullRequest: thread.branchPullRequest ?? null,
289 },
290 branchPullRequest,
291 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
292 });
293 pendingBackfill.delete(thread.id);
294 }).pipe(
295 Effect.catchCause((cause) =>
296 Cause.hasInterruptsOnly(cause)
297 ? Effect.failCause(cause)
298 : Effect.logWarning("thread pull request update failed", {
299 threadId: thread.id,
300 cause: Cause.pretty(cause),
301 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
302 ),
303 ),
304 { discard: true },
305 );
306 }).pipe(
307 Effect.catchCause((cause) =>
308 Cause.hasInterruptsOnly(cause)
309 ? Effect.failCause(cause)
310 : Effect.logWarning("thread branch pull request lookup failed", {
311 threadIds: group.map((thread) => thread.id),
312 cause: Cause.pretty(cause),
313 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
314 ),
315 ),
316 { concurrency: 8, discard: true },
317 );
318 });
319
320 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
321 synchronize(request).pipe(
322 Effect.catchCause((cause) =>
323 Cause.hasInterruptsOnly(cause)
324 ? Effect.failCause(cause)
325 : Effect.logWarning("thread pull request refresh failed", {
326 cause: Cause.pretty(cause),
327 }),
328 ),
329 ),
330 );
331
332 const processEvent = (event: OrchestrationV2DomainEvent) => {
333 switch (event.type) {
334 case "thread.created":
335 case "thread.unarchived":
336 case "thread.metadata-updated":
337 return worker.enqueue({ threadId: event.threadId, refresh: false });
338 case "thread.unsettled":
339 case "checkpoint.captured":
340 return worker.enqueue({ threadId: event.threadId, refresh: true });
341 case "run.updated":
342 if (
343 event.payload.status === "completed" ||
344 event.payload.status === "failed" ||
345 event.payload.status === "cancelled" ||
346 event.payload.status === "interrupted"
347 ) {
348 return worker.enqueue({ threadId: event.threadId, refresh: true });
349 }
350 break;
351 }
352 return Effect.void;
353 };
354
355 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
356 "ThreadPullRequestServiceV2.start",
357 )(function* () {
358 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
359 yield* forkParked(
360 Effect.gen(function* () {
361 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
362 yield* worker.drain;
363 yield* Effect.gen(function* () {
364 yield* worker.enqueue({ threadId: null, refresh: false });
365 yield* worker.drain;
366 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
367 }).pipe(Effect.asVoid),
368 );
369 });
370
371 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
372});
373
374const layer = Layer.effect(ThreadPullRequestServiceV2, make);