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 function projectWorkspaceMatchesSnapshot(
66 currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
67 expectedWorkspaceRoot: string,
68): boolean {
69 return (
70 Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
71 );
72}
73
74const BACKFILL_ATTEMPTS = 5;
75
76interface RefreshRequest {
77 readonly threadId: ThreadId | null;
78 readonly refresh: boolean;
79 readonly backfill?: boolean;
80}
81
82export const make = Effect.gen(function* () {
83 const orchestrator = yield* OrchestratorV2;
84 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
85 const git = yield* GitManager.GitManager;
86 const pullRequests = yield* PullRequestService.PullRequestService;
87 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
88 const crypto = yield* Crypto.Crypto;
89 const fileSystem = yield* FileSystem.FileSystem;
90 const pendingBackfill = new Map<ThreadId, number>();
91
92 const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
93 for (const thread of threads) pendingBackfill.delete(thread.id);
94 };
95 const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
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("ThreadPullRequestServiceV2.synchronize")(function* (
105 request: RefreshRequest,
106 ) {
107 const [threadSnapshot, projectShells] = yield* Effect.all([
108 orchestrator.getShellSnapshot(),
109 snapshots.getProjectShellsWithoutEnrichment(),
110 ]);
111 const projects = new Map(projectShells.map((project) => [project.id, project]));
112 if (request.backfill) {
113 for (const thread of threadSnapshot.threads) {
114 if (
115 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
116 thread.branchPullRequest == null
117 ) {
118 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
119 }
120 }
121 }
122 const visibleThreadIds = new Set(threadSnapshot.threads.map((thread) => thread.id));
123 for (const threadId of pendingBackfill.keys()) {
124 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
125 }
126 const threads = threadSnapshot.threads.filter(
127 (thread) =>
128 thread.archivedAt === null &&
129 (request.threadId === null || thread.id === request.threadId) &&
130 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
131 request.threadId !== null ||
132 pendingBackfill.has(thread.id)) &&
133 (thread.branch !== null || thread.branchPullRequest != null),
134 );
135 const groups = Map.groupBy(threads, (thread) =>
136 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
137 );
138
139 yield* Effect.forEach(
140 groups.values(),
141 (group) =>
142 Effect.gen(function* () {
143 const first = group[0]!;
144 const project = projects.get(first.projectId);
145 if (project === undefined) return finishBackfill(group);
146 const repository = sourceControlRepositorySelector(project.repositoryIdentity);
147 if (first.branch !== null && repository === null) return finishBackfill(group);
148 const worktreeExists =
149 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
150 const cwd =
151 worktreeExists && first.worktreePath !== null
152 ? first.worktreePath
153 : project.workspaceRoot;
154 const detected =
155 first.branch === null
156 ? null
157 : yield* git.branchPullRequest(
158 { cwd, branch: first.branch },
159 { refresh: request.refresh },
160 );
161 if (detected !== null && !pullRequestMatchesProject(detected, project)) {
162 return finishBackfill(group);
163 }
164 const detectedReference =
165 detected !== null && repository !== null
166 ? {
167 projectId: project.id,
168 repository,
169 number: detected.number,
170 url: detected.url,
171 }
172 : null;
173
174 const plans = yield* Effect.forEach(group, (thread) =>
175 Effect.gen(function* () {
176 let branchPullRequest = detectedReference;
177 if (
178 branchPullRequest === null &&
179 thread.branch !== null &&
180 thread.worktreePath === null &&
181 thread.branchPullRequest != null
182 ) {
183 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
184 recoverTransientFailure: false,
185 });
186 if (previous.state === "merged" || previous.state === "closed") {
187 branchPullRequest = thread.branchPullRequest;
188 }
189 }
190
191 let replacement: ThreadLinkedPullRequest | undefined;
192 if (
193 (thread.pullRequests ?? []).length === 0 &&
194 thread.linkedPullRequest != null &&
195 detected?.state === "open" &&
196 detectedReference !== null &&
197 !samePullRequest(thread.linkedPullRequest, detectedReference)
198 ) {
199 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
200 recoverTransientFailure: false,
201 });
202 if (linked.state === "merged" || linked.state === "closed") {
203 replacement = detectedReference;
204 }
205 }
206 if (
207 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
208 replacement === undefined
209 ) {
210 pendingBackfill.delete(thread.id);
211 return null;
212 }
213 return { thread, branchPullRequest, replacement };
214 }).pipe(
215 Effect.catchCause((cause) =>
216 Cause.hasInterruptsOnly(cause)
217 ? Effect.failCause(cause)
218 : Effect.logWarning("thread pull request discovery failed", {
219 threadId: thread.id,
220 cause: Cause.pretty(cause),
221 }).pipe(
222 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
223 Effect.as(null),
224 ),
225 ),
226 ),
227 );
228 const updates = plans.filter((plan) => plan !== null);
229 if (updates.length === 0) return;
230
231 if (detected !== null && first.branch !== null) {
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 // Discovery can perform network I/O. Re-read the project at
256 // the transaction boundary so a deleted project or changed
257 // workspace root cannot apply a result from the old checkout.
258 const currentProject = yield* snapshots.getProjectShellById(project.id);
259 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
260 return failBackfill([thread]);
261 }
262 const uuid = yield* crypto.randomUUIDv4;
263 yield* orchestrator.dispatch({
264 type: "thread.pull-request.sync",
265 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
266 threadId: thread.id,
267 projectId: project.id,
268 snapshotSequence: threadSnapshot.snapshotSequence,
269 expected: {
270 workspaceRoot: project.workspaceRoot,
271 branch: thread.branch,
272 worktreePath: thread.worktreePath,
273 linkedPullRequest: thread.linkedPullRequest ?? null,
274 branchPullRequest: thread.branchPullRequest ?? null,
275 },
276 branchPullRequest,
277 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
278 });
279 pendingBackfill.delete(thread.id);
280 }).pipe(
281 Effect.catchCause((cause) =>
282 Cause.hasInterruptsOnly(cause)
283 ? Effect.failCause(cause)
284 : Effect.logWarning("thread pull request update failed", {
285 threadId: thread.id,
286 cause: Cause.pretty(cause),
287 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
288 ),
289 ),
290 { discard: true },
291 );
292 }).pipe(
293 Effect.catchCause((cause) =>
294 Cause.hasInterruptsOnly(cause)
295 ? Effect.failCause(cause)
296 : Effect.logWarning("thread branch pull request lookup failed", {
297 threadIds: group.map((thread) => thread.id),
298 cause: Cause.pretty(cause),
299 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
300 ),
301 ),
302 { concurrency: 8, discard: true },
303 );
304 });
305
306 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
307 synchronize(request).pipe(
308 Effect.catchCause((cause) =>
309 Cause.hasInterruptsOnly(cause)
310 ? Effect.failCause(cause)
311 : Effect.logWarning("thread pull request refresh failed", {
312 cause: Cause.pretty(cause),
313 }),
314 ),
315 ),
316 );
317
318 const processEvent = (event: OrchestrationV2DomainEvent) => {
319 switch (event.type) {
320 case "thread.created":
321 case "thread.unarchived":
322 case "thread.metadata-updated":
323 return worker.enqueue({ threadId: event.threadId, refresh: false });
324 case "thread.unsettled":
325 case "checkpoint.captured":
326 return worker.enqueue({ threadId: event.threadId, refresh: true });
327 case "run.updated":
328 if (
329 event.payload.status === "completed" ||
330 event.payload.status === "failed" ||
331 event.payload.status === "cancelled" ||
332 event.payload.status === "interrupted"
333 ) {
334 return worker.enqueue({ threadId: event.threadId, refresh: true });
335 }
336 break;
337 }
338 return Effect.void;
339 };
340
341 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
342 "ThreadPullRequestServiceV2.start",
343 )(function* () {
344 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
345 yield* forkParked(
346 Effect.gen(function* () {
347 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
348 yield* worker.drain;
349 yield* Effect.gen(function* () {
350 yield* worker.enqueue({ threadId: null, refresh: false });
351 yield* worker.drain;
352 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
353 }).pipe(Effect.asVoid),
354 );
355 });
356
357 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
358});
359
360const layer = Layer.effect(ThreadPullRequestServiceV2, make);