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