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 ProjectStore from "./ProjectStore.ts";
27import * as PullRequestService from "../pullRequest/PullRequestService.ts";
28import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29import { forkParked } from "../serverActivation.ts";
30import * as Orchestrator 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 options?: { readonly refresh?: boolean },
71) {
72 // Identities stay cached for 15 minutes. A finished turn may have added the
73 // remote its pull request lives on, so post-turn discovery refreshes.
74 const repositoryIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
75 refresh: options?.refresh ?? false,
76 });
77 return {
78 project: { ...project, repositoryIdentity },
79 repository: sourceControlRepositorySelector(repositoryIdentity),
80 };
81});
82
83export function projectWorkspaceMatchesSnapshot(
84 currentProject: Option.Option<Pick<OrchestrationProjectShell, "workspaceRoot">>,
85 expectedWorkspaceRoot: string,
86): boolean {
87 return (
88 Option.isSome(currentProject) && currentProject.value.workspaceRoot === expectedWorkspaceRoot
89 );
90}
91
92const BACKFILL_ATTEMPTS = 5;
93
94interface RefreshRequest {
95 readonly threadId: ThreadId | null;
96 readonly refresh: boolean;
97 readonly backfill?: boolean;
98}
99
100export const make = Effect.gen(function* () {
101 const orchestrator = yield* Orchestrator.OrchestratorV2;
102 const projectStore = yield* ProjectStore.ProjectStoreV2;
103 const git = yield* GitManager.GitManager;
104 const pullRequests = yield* PullRequestService.PullRequestService;
105 const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
106 const crypto = yield* Crypto.Crypto;
107 const fileSystem = yield* FileSystem.FileSystem;
108 const pendingBackfill = new Map<ThreadId, number>();
109
110 const finishBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
111 for (const thread of threads) pendingBackfill.delete(thread.id);
112 };
113 const failBackfill = (threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "id">>) => {
114 for (const thread of threads) {
115 const remaining = pendingBackfill.get(thread.id);
116 if (remaining === undefined) continue;
117 if (remaining <= 1) pendingBackfill.delete(thread.id);
118 else pendingBackfill.set(thread.id, remaining - 1);
119 }
120 };
121
122 /**
123 * A sweep for one thread reads only that thread's shell, not every thread's.
124 * Finished runs and checkpoints queue one of these each. A sweep over all
125 * threads reads only active, unsettled ones, since discovery skips the rest;
126 * backfill looks up settled threads, so its passes read every active thread.
127 */
128 const readThreadSnapshot = ({ threadId, backfill }: RefreshRequest) =>
129 threadId === null
130 ? orchestrator.getShellSnapshot({
131 location: "active",
132 unsettledOnly: !(backfill || pendingBackfill.size > 0),
133 })
134 : Effect.gen(function* () {
135 // Read the sequence first. The thread is then at least this new, so a
136 // sync guarded by the sequence is rejected rather than missing a change.
137 const snapshotSequence = yield* orchestrator.getThreadEventSequence(threadId);
138 const thread = yield* orchestrator.getThreadShell(threadId);
139 return { snapshotSequence, threads: thread === null ? [] : [thread] };
140 });
141
142 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
143 request: RefreshRequest,
144 ) {
145 const [threadSnapshot, projectShells] = yield* Effect.all([
146 readThreadSnapshot(request),
147 projectStore.listShells(),
148 ]);
149 const projects = new Map(projectShells.map((project) => [project.id, project]));
150 if (request.backfill) {
151 for (const thread of threadSnapshot.threads) {
152 if (
153 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
154 thread.branchPullRequest == null
155 ) {
156 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
157 }
158 }
159 }
160 // A single-thread read only shows whether its own thread is gone. A thread
161 // with no branch has nothing to look up, and its entry would keep every
162 // periodic pass on the full read.
163 const visibleThreadIds = new Set(
164 threadSnapshot.threads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
165 );
166 const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
167 for (const threadId of checkedIds) {
168 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
169 }
170 const threads = threadSnapshot.threads.filter(
171 (thread) =>
172 thread.archivedAt === null &&
173 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
174 request.threadId !== null ||
175 pendingBackfill.has(thread.id)) &&
176 (thread.branch !== null || thread.branchPullRequest != null),
177 );
178 const groups = Map.groupBy(threads, (thread) =>
179 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
180 );
181
182 yield* Effect.forEach(
183 groups.values(),
184 (group) =>
185 Effect.gen(function* () {
186 const first = group[0]!;
187 const project = projects.get(first.projectId);
188 if (project === undefined) return finishBackfill(group);
189 const { project: resolvedProject, repository } =
190 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
191 refresh: request.refresh,
192 });
193 if (first.branch !== null && repository === null) return finishBackfill(group);
194 const worktreeExists =
195 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
196 const cwd =
197 worktreeExists && first.worktreePath !== null
198 ? first.worktreePath
199 : project.workspaceRoot;
200 const detected =
201 first.branch === null
202 ? null
203 : yield* git.branchPullRequest(
204 { cwd, branch: first.branch },
205 { refresh: request.refresh },
206 );
207 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
208 return finishBackfill(group);
209 }
210 const detectedReference =
211 detected !== null && repository !== null
212 ? {
213 projectId: project.id,
214 repository,
215 number: detected.number,
216 url: detected.url,
217 }
218 : null;
219
220 const plans = yield* Effect.forEach(group, (thread) =>
221 Effect.gen(function* () {
222 let branchPullRequest = detectedReference;
223 if (
224 branchPullRequest === null &&
225 thread.branch !== null &&
226 thread.worktreePath === null &&
227 thread.branchPullRequest != null
228 ) {
229 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
230 recoverTransientFailure: false,
231 });
232 if (previous.state === "merged" || previous.state === "closed") {
233 branchPullRequest = thread.branchPullRequest;
234 }
235 }
236
237 let replacement: ThreadLinkedPullRequest | undefined;
238 if (
239 (thread.pullRequests ?? []).length === 0 &&
240 thread.linkedPullRequest != null &&
241 detected?.state === "open" &&
242 detectedReference !== null &&
243 !samePullRequest(thread.linkedPullRequest, detectedReference)
244 ) {
245 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
246 recoverTransientFailure: false,
247 });
248 if (linked.state === "merged" || linked.state === "closed") {
249 replacement = detectedReference;
250 }
251 }
252 if (
253 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
254 replacement === undefined
255 ) {
256 pendingBackfill.delete(thread.id);
257 return null;
258 }
259 return { thread, branchPullRequest, replacement };
260 }).pipe(
261 Effect.catchCauseIf(
262 (cause) => !Cause.hasInterruptsOnly(cause),
263 (cause) =>
264 Effect.logWarning("thread pull request discovery failed", {
265 threadId: thread.id,
266 cause: Cause.pretty(cause),
267 }).pipe(
268 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
269 Effect.as(null),
270 ),
271 ),
272 ),
273 );
274 const updates = plans.filter((plan) => plan !== null);
275 if (updates.length === 0) return;
276
277 if (detected !== null && first.branch !== null) {
278 const current = yield* git.branchPullRequest({ cwd, branch: first.branch });
279 const currentIdentity = yield* repositoryIdentities.resolve(project.workspaceRoot, {
280 refresh: true,
281 });
282 if (
283 current === null ||
284 current.number !== detected.number ||
285 current.url !== detected.url ||
286 current.state !== detected.state ||
287 current.repositoryKey !== detected.repositoryKey ||
288 !pullRequestMatchesProject(current, {
289 ...project,
290 repositoryIdentity: currentIdentity,
291 })
292 ) {
293 return failBackfill(updates.map((update) => update.thread));
294 }
295 }
296
297 yield* Effect.forEach(
298 updates,
299 ({ thread, branchPullRequest, replacement }) =>
300 Effect.gen(function* () {
301 // Discovery can perform network I/O. Re-read the project at
302 // the transaction boundary so a deleted project or changed
303 // workspace root cannot apply a result from the old checkout.
304 const currentProject = yield* projectStore.getShell(project.id);
305 if (!projectWorkspaceMatchesSnapshot(currentProject, project.workspaceRoot)) {
306 return failBackfill([thread]);
307 }
308 const uuid = yield* crypto.randomUUIDv4;
309 yield* orchestrator.dispatch({
310 type: "thread.pull-request.sync",
311 commandId: CommandId.make(`server:thread-pull-request:${thread.id}:${uuid}`),
312 threadId: thread.id,
313 projectId: project.id,
314 snapshotSequence: threadSnapshot.snapshotSequence,
315 expected: {
316 workspaceRoot: project.workspaceRoot,
317 branch: thread.branch,
318 worktreePath: thread.worktreePath,
319 linkedPullRequest: thread.linkedPullRequest ?? null,
320 branchPullRequest: thread.branchPullRequest ?? null,
321 },
322 branchPullRequest,
323 ...(replacement === undefined ? {} : { linkedPullRequest: replacement }),
324 });
325 pendingBackfill.delete(thread.id);
326 }).pipe(
327 Effect.catchCause((cause) =>
328 Cause.hasInterruptsOnly(cause)
329 ? Effect.failCause(cause)
330 : Effect.logWarning("thread pull request update failed", {
331 threadId: thread.id,
332 cause: Cause.pretty(cause),
333 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))),
334 ),
335 ),
336 { discard: true },
337 );
338 }).pipe(
339 Effect.catchCauseIf(
340 (cause) => !Cause.hasInterruptsOnly(cause),
341 (cause) =>
342 Effect.logWarning("thread branch pull request lookup failed", {
343 threadIds: group.map((thread) => thread.id),
344 cause: Cause.pretty(cause),
345 }).pipe(Effect.tap(() => Effect.sync(() => failBackfill(group)))),
346 ),
347 ),
348 // Wide enough that a sweep's GitHub branch lookups reach the GitHub provider together and share one
349 // GraphQL document, instead of one `gh pr list` per branch.
350 { concurrency: 32, discard: true },
351 );
352 });
353
354 const worker = yield* makeDrainableWorker((request: RefreshRequest) =>
355 synchronize(request).pipe(
356 Effect.catchCauseIf(
357 (cause) => !Cause.hasInterruptsOnly(cause),
358 (cause) =>
359 Effect.logWarning("thread pull request refresh failed", {
360 cause: Cause.pretty(cause),
361 }),
362 ),
363 ),
364 );
365
366 const processEvent = (event: OrchestrationV2DomainEvent) => {
367 switch (event.type) {
368 case "thread.created":
369 case "thread.unarchived":
370 case "thread.metadata-updated":
371 return worker.enqueue({ threadId: event.threadId, refresh: false });
372 case "thread.unsettled":
373 case "checkpoint.captured":
374 return worker.enqueue({ threadId: event.threadId, refresh: true });
375 case "run.updated":
376 if (
377 event.payload.status === "completed" ||
378 event.payload.status === "failed" ||
379 event.payload.status === "cancelled" ||
380 event.payload.status === "interrupted"
381 ) {
382 return worker.enqueue({ threadId: event.threadId, refresh: true });
383 }
384 break;
385 }
386 return Effect.void;
387 };
388
389 const start: ThreadPullRequestServiceV2["Service"]["start"] = Effect.fn(
390 "ThreadPullRequestServiceV2.start",
391 )(function* () {
392 yield* forkParked(Stream.runForEach(orchestrator.streamDomainEvents, processEvent));
393 yield* forkParked(
394 Effect.gen(function* () {
395 yield* worker.enqueue({ threadId: null, refresh: false, backfill: true });
396 yield* worker.drain;
397 yield* Effect.gen(function* () {
398 yield* worker.enqueue({ threadId: null, refresh: false });
399 yield* worker.drain;
400 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.delay("1 minute"));
401 }).pipe(Effect.asVoid),
402 );
403 });
404
405 return { start, drain: worker.drain } satisfies ThreadPullRequestServiceV2["Service"];
406});
407
408const layer = Layer.effect(ThreadPullRequestServiceV2, make);