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