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

ThreadPullRequestService.ts

410 lines16.4 KB

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