Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadPullRequestService.ts

408 lines16.0 KB

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 { 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 );
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 );
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 );
92​
93const BACKFILL_ATTEMPTS = 5;
94​
95interface RefreshRequest {
96 readonly threadId: ThreadId | null;
97 readonly refresh: boolean;
98 readonly backfill?: boolean;
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 unsettledOnly: !(backfill || pendingBackfill.size > 0),
129 })
130 .pipe(NodeSqliteClient.readOnly)
131 : Effect.gen(function* () {
132 // Read the sequence first. The thread is then at least this new, so a
133 // sync guarded by the sequence is rejected rather than missing a change.
134 const snapshotSequence = yield* orchestrator.getThreadEventSequence(threadId);
135 const thread = yield* orchestrator.getThreadShell(threadId);
136 return { snapshotSequence, threads: thread === null ? [] : [thread] };
137 });
138​
139 const synchronize = Effect.fn("ThreadPullRequestServiceV2.synchronize")(function* (
140 request: RefreshRequest,
141 ) {
142 const [threadSnapshot, projectShells] = yield* Effect.all([
143 readThreadSnapshot(request),
144 projectStore.listShells(),
145 ]);
146 const projects = new Map(projectShells.map((project) => [project.id, project]));
147 if (request.backfill) {
148 for (const thread of threadSnapshot.threads) {
149 if (
150 (thread.settledOverride === "settled" || thread.settledAt !== null) &&
151 thread.branchPullRequest == null
152 ) {
153 pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS);
154 }
155 }
156 }
157 const visibleThreadIds = new Set(
158 threadSnapshot.threads.filter((thread) => thread.branch !== null).map((thread) => thread.id),
159 );
160 const checkedIds = request.threadId === null ? [...pendingBackfill.keys()] : [request.threadId];
161 for (const threadId of checkedIds) {
162 if (!visibleThreadIds.has(threadId)) pendingBackfill.delete(threadId);
163 }
164 const threads = threadSnapshot.threads.filter(
165 (thread) =>
166 thread.archivedAt === null &&
167 ((thread.settledOverride !== "settled" && thread.settledAt === null) ||
168 request.threadId !== null ||
169 pendingBackfill.has(thread.id)) &&
170 (thread.branch !== null || thread.branchPullRequest != null),
171 );
172 const groups = Map.groupBy(threads, (thread) =>
173 JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]),
174 );
175​
176 yield* Effect.forEach(
177 groups.values(),
178 (group) =>
179 Effect.gen(function* () {
180 const first = group[0]!;
181 const project = projects.get(first.projectId);
182 if (project === undefined) return finishBackfill(group);
183 const { project: resolvedProject, repository } =
184 yield* resolveProjectForPullRequestDiscovery(project, repositoryIdentities, {
185 refresh: request.refresh,
186 });
187 if (first.branch !== null && repository === null) return finishBackfill(group);
188 const worktreeExists =
189 first.worktreePath !== null && (yield* fileSystem.exists(first.worktreePath));
190 const cwd =
191 worktreeExists && first.worktreePath !== null
192 ? first.worktreePath
193 : project.workspaceRoot;
194 const detected =
195 first.branch === null
196 ? null
197 : yield* git.branchPullRequest(
198 { cwd, branch: first.branch },
199 { refresh: request.refresh },
200 );
201 if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
202 return finishBackfill(group);
203 }
204 const detectedReference =
205 detected !== null && repository !== null
206 ? {
207 projectId: project.id,
208 repository,
209 number: detected.number,
210 url: detected.url,
211 }
212 : null;
213​
214 const plans = yield* Effect.forEach(group, (thread) =>
215 Effect.gen(function* () {
216 let branchPullRequest = detectedReference;
217 if (
218 branchPullRequest === null &&
219 thread.branch !== null &&
220 thread.worktreePath === null &&
221 thread.branchPullRequest != null
222 ) {
223 const previous = yield* pullRequests.summary(thread.branchPullRequest, {
224 recoverTransientFailure: false,
225 });
226 if (
227 previous.headBranch === thread.branch &&
228 (previous.state === "merged" || previous.state === "closed")
229 ) {
230 branchPullRequest = thread.branchPullRequest;
231 }
232 }
233​
234 let replacement: ThreadLinkedPullRequest | undefined;
235 if (
236 (thread.pullRequests ?? []).length === 0 &&
237 thread.linkedPullRequest != null &&
238 detected?.state === "open" &&
239 detectedReference !== null &&
240 !samePullRequest(thread.linkedPullRequest, detectedReference)
241 ) {
242 const linked = yield* pullRequests.summary(thread.linkedPullRequest, {
243 recoverTransientFailure: false,
244 });
245 if (linked.state === "merged" || linked.state === "closed") {
246 replacement = detectedReference;
247 }
248 }
249 if (
250 samePullRequest(thread.branchPullRequest, branchPullRequest) &&
251 replacement === undefined
252 ) {
253 pendingBackfill.delete(thread.id);
254 return null;
255 }
256 return { thread, branchPullRequest, replacement };
257 }).pipe(
258 Effect.catchCauseIf(
259 (cause) => !Cause.hasInterruptsOnly(cause),
260 (cause) =>
261 Effect.logWarning("thread pull request discovery failed", {
262 threadId: thread.id,
263 cause: Cause.pretty(cause),
264 }).pipe(
265 Effect.tap(() => Effect.sync(() => failBackfill([thread]))),
266 Effect.as(null),
267 ),
268 ),
269 ),
270 );
271 const updates = plans.filter((plan) => plan !== null);
272 if (updates.length === 0) return;
273​
274 if (detected !== null && first.branch !== null) {
275 const current = yield* git.branchPullRequest(
276 { cwd, branch: first.branch },
277 { freshGitState: true },
278 );
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);