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

PullRequestSyncReactor.ts

470 lines18.9 KB

1import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
2import {
3 CommandId,
4 type PullRequestSummary,
5 type ThreadId,
6 type ThreadPullRequestKey,
7 type ThreadPullRequestLink,
8 type ThreadPullRequestSnapshot,
9 type ThreadPullRequestStack,
10} from "@t3tools/contracts";
11import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
12import {
13 threadPullRequestKeyOf,
14 normalizeThreadPullRequestKey,
15 threadPullRequestKeysEqual,
16 visibleThreadPullRequests,
17} from "@t3tools/shared/threadPullRequests";
18import * as Cause from "effect/Cause";
19import * as Clock from "effect/Clock";
20import * as Context from "effect/Context";
21import * as Crypto from "effect/Crypto";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import * as Schema from "effect/Schema";
26import * as Schedule from "effect/Schedule";
27import type * as Scope from "effect/Scope";
28import * as Semaphore from "effect/Semaphore";
29import * as Stream from "effect/Stream";
30​
31import * as GitManager from "../git/GitManager.ts";
32import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider";
33import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34import { forkParked } from "../serverActivation.ts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ProjectionStore from "./ProjectionStore.ts";
37import { isTerminalRunStatus } from "./ThreadManagementService.ts";
38​
39const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
40const PULL_REQUEST_CLOSE_COMMAND = /\b(?:gh\s+pr|glab\s+mr)\s+(?:merge|close)\b/u;
41​
42const isPullRequestProviderError = Schema.is(PullRequestProviderError);
43​
44type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
45​
46interface LinkEntry {
47 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
48 readonly link: ThreadPullRequestLink;
50​
51function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
52 return {
53 state: summary.state,
54 title: summary.title,
55 headBranch: summary.headBranch,
56 baseBranch: summary.baseBranch,
57 isDraft: summary.isDraft ?? false,
58 updatedAt: summary.updatedAt,
59 closedAt: summary.closedAt ?? null,
60 mergedAt: summary.mergedAt ?? null,
61 ...(summary.author === undefined ? {} : { author: summary.author }),
62 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
63 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
64 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
65 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
66 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
67 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
68 };
70​
71function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
72 return (
73 left.state === right.state &&
74 left.title === right.title &&
75 left.headBranch === right.headBranch &&
76 left.baseBranch === right.baseBranch &&
77 left.isDraft === right.isDraft &&
78 left.updatedAt === right.updatedAt &&
79 (left.closedAt ?? null) === (right.closedAt ?? null) &&
80 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
81 (left.author?.login ?? null) === (right.author?.login ?? null) &&
82 (left.author?.avatarUrl ?? null) === (right.author?.avatarUrl ?? null) &&
83 left.additions === right.additions &&
84 left.deletions === right.deletions &&
85 left.changedFiles === right.changedFiles &&
86 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
87 (left.checksState ?? null) === (right.checksState ?? null) &&
88 left.mergeability === right.mergeability
89 );
91​
92function stacksEqual(
93 left: ThreadPullRequestStack | null,
94 right: ThreadPullRequestStack | null,
95): boolean {
96 if (left === null || right === null) return left === right;
97 return (
98 left.kind === right.kind &&
99 left.id === right.id &&
100 left.number === right.number &&
101 left.url === right.url &&
102 left.base === right.base &&
103 left.layers.length === right.layers.length &&
104 left.layers.every((layer, index) => {
105 const other = right.layers[index]!;
106 return (
107 layer.number === other.number &&
108 layer.headBranch === other.headBranch &&
109 layer.state === other.state
110 );
111 })
112 );
114​
115function skipReason(cause: Cause.Cause<unknown>): string {
116 const error = Cause.squash(cause);
117 return error instanceof Error ? error.message : String(error);
119​
120function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
121 let error: unknown = Cause.squash(cause);
122 while (error instanceof Error) {
123 if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
124 error = error.cause;
125 }
126 return undefined;
128​
129function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
130 return thread.settledOverride !== "settled" && thread.settledAt === null;
132​
133export class PullRequestSyncReactor extends Context.Service<
134 PullRequestSyncReactor,
135 {
136 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
137 readonly drain: Effect.Effect<void>;
138 /**
139 * Force the next sweep to re-read this pull request, even when its snapshot is terminal.
140 * While its host is rate limited, the read waits for the first sweep after the pause.
141 */
142 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
143 }
144>()("t3/orchestration-v2/PullRequestSyncReactor") {}
145​
146/** @public Service construction is part of the canonical Effect module API. */
147export const make = Effect.gen(function* () {
148 const engine = yield* Orchestrator.OrchestratorV2;
149 const projections = yield* ProjectionStore.ProjectionStoreV2;
150 const pullRequests = yield* PullRequestService.PullRequestService;
151 const git = yield* GitManager.GitManager;
152 const crypto = yield* Crypto.Crypto;
153​
154 const lastSyncedAt = new Map<string, number>();
155 const requested = new Map<string, number>();
156 let requestGeneration = 0;
157 // Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent
158 // linking dozens of pull requests) is read together and shares the summary batches.
159 let requestedSweepQueued = false;
160 const retryStacks = new Set<string>();
161 // Rate limit pauses by project and host, since each project reads with its own credential.
162 // A paused host refuses every read without asking it, so the sweep leaves its pull requests
163 // due until the pause ends rather than failing each of them every minute.
164 const pausedUntil = new Map<string, number>();
165​
166 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
167 if (requested.has(key) || retryStacks.has(key)) return true;
168 if (entries.some((entry) => entry.link.snapshot === null)) return true;
169 const active = entries.filter((entry) => isUnsettled(entry.thread));
170 if (active.every((entry) => entry.link.snapshot?.state === "merged")) return false;
171 if (active.some((entry) => entry.link.snapshot?.state === "open")) return true;
172 const last = lastSyncedAt.get(key);
173 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
174 };
175​
176 const logSkipped =
177 (message: string, fields: Record<string, unknown>) =>
178 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
179 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
180​
181 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
182 const threads = yield* projections.getThreadsWithPullRequests();
183 const now = yield* DateTime.now;
184 const nowMs = DateTime.toEpochMillis(now);
185 const nowIso = DateTime.formatIso(now);
186​
187 const groups = new Map<string, Array<LinkEntry>>();
188 for (const thread of threads) {
189 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
190 const key = threadPullRequestKeyOf(link);
191 const entries = groups.get(key) ?? [];
192 entries.push({ thread, link });
193 groups.set(key, entries);
194 }
195 }
196​
197 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
198 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
199 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
200​
201 const linkedThisSweep = new Set<string>();
202 const persistence = yield* Semaphore.make(1);
203​
204 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
205 entry: LinkEntry,
206 fields: SnapshotFields,
207 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
208 ) {
209 const { thread, link } = entry;
210 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
211 const changed =
212 link.snapshot === null ||
213 !snapshotFieldsEqual(link.snapshot, fields) ||
214 !stacksEqual(link.stack, nextStack);
215 // Persist discovered siblings before a terminal snapshot can trigger settlement. A settled
216 // thread that shares this pull request with an active one takes the fresh snapshot, but
217 // gains no links.
218 for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
219 const layerKey = {
220 host: normalizeThreadPullRequestKey(link).host,
221 repository: link.repository,
222 number: layer.number,
223 };
224 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
225 if (linkedThisSweep.has(dedupeKey)) continue;
226 // Tombstones count as present: a dismissed layer is never re-added.
227 if (
228 (thread.pullRequests ?? []).some((existing) =>
229 threadPullRequestKeysEqual(existing, layerKey),
230 )
231 ) {
232 continue;
233 }
234 const url = siblingPullRequestUrl(link.url, layer.number);
235 if (url === null) continue;
236 const uuid = yield* crypto.randomUUIDv4();
237 yield* engine.dispatch({
238 type: "thread.pull-request.link",
239 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
240 threadId: thread.id,
241 ...layerKey,
242 url,
243 source: "stack",
244 });
245 linkedThisSweep.add(dedupeKey);
246 }
247 if (changed) {
248 const uuid = yield* crypto.randomUUIDv4();
249 yield* engine.dispatch({
250 type: "thread.pull-request-link.sync",
251 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
252 threadId: thread.id,
253 host: normalizeThreadPullRequestKey(link).host,
254 repository: link.repository,
255 number: link.number,
256 snapshot: { ...fields, syncedAt: nowIso },
257 stack: nextStack,
258 });
259 }
260 });
261​
262 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
263 key: string,
264 entries: ReadonlyArray<LinkEntry>,
265 ) {
266 const first = entries[0]!;
267 const ref = {
268 projectId: first.thread.projectId,
269 host: normalizeThreadPullRequestKey(first.link).host,
270 repository: first.link.repository,
271 number: first.link.number,
272 };
273 const generation = requested.get(key);
274 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
275 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
276 const fields = snapshotFieldsOf(summary);
277 const needsStack =
278 generation !== undefined ||
279 retryStacks.has(key) ||
280 entries.some(
281 (entry) =>
282 entry.link.snapshot === null ||
283 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
284 (summary.stack !== undefined &&
285 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
286 );
287 const knownUnstacked =
288 summary.stack === null && entries.every((entry) => entry.link.stack === null);
289 const fetchedStack = !needsStack
290 ? null
291 : knownUnstacked
292 ? { stack: null }
293 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
294 Effect.map((stack) => ({
295 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
296 })),
297 Effect.catchCauseIf(
298 (cause) => !Cause.hasInterruptsOnly(cause),
299 (cause) =>
300 rateLimitRetryAt(cause) !== undefined
301 ? Effect.sync(() => retryStacks.add(key)).pipe(
302 Effect.andThen(Effect.failCause(cause)),
303 )
304 : Effect.logWarning("pull request stack lookup failed", {
305 key,
306 }).pipe(Effect.as(null)),
307 ),
308 );
309 if (needsStack) {
310 if (fetchedStack === null) {
311 retryStacks.add(key);
312 return;
313 }
314 retryStacks.delete(key);
315 }
316 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
317 lastSyncedAt.set(key, nowMs);
318 // A refresh requested while the host read was in flight belongs to the next sweep.
319 if (requested.get(key) === generation) requested.delete(key);
320 yield* Effect.forEach(
321 entries,
322 (entry) =>
323 syncEntry(entry, fields, fetchedStack).pipe(
324 persistence.withPermits(1),
325 Effect.catchCause((cause) => {
326 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
327 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
328 cause,
329 );
330 }),
331 ),
332 { discard: true },
333 );
334 });
335​
336 const skips = new Map<string, { count: number; readonly key: string }>();
337 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
338 syncGroup(key, entries).pipe(
339 Effect.catchCause((cause) => {
340 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
341 const retryAt = rateLimitRetryAt(cause);
342 if (retryAt !== undefined) {
343 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
344 }
345 const reason = skipReason(cause);
346 const skip = skips.get(reason);
347 if (skip === undefined) skips.set(reason, { count: 1, key });
348 else skip.count += 1;
349 return Effect.void;
350 }),
351 );
352 yield* Effect.forEach(
353 groups,
354 ([key, entries]) => {
355 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
356 return Effect.void;
357 }
358 const first = entries[0]!;
359 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
360 // Checked against the clock as each read starts, so a pause found earlier in this sweep
361 // holds the rest, and one that ends during the sweep lets the rest through.
362 return Clock.currentTimeMillis.pipe(
363 Effect.flatMap((startedAtMs) =>
364 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
365 ? Effect.void
366 : readGroup(key, entries, pauseKey),
367 ),
368 );
369 },
370 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
371 // GitHub answers them in one request rather than one `gh pr view` apiece.
372 { concurrency: 25, discard: true },
373 );
374 for (const [reason, { count, key }] of skips) {
375 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
376 }
377 });
378​
379 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
380 Effect.suspend(() => {
381 if (scope === "requested") requestedSweepQueued = false;
382 return sweep(scope);
383 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
384 );
385​
386 const closeCommandThreads = new Set<ThreadId>();
387 const refreshOpenLinks = (threadId: ThreadId) =>
388 projections.getThreadsWithPullRequests(threadId).pipe(
389 Effect.flatMap((threads) =>
390 Effect.forEach(
391 threads.flatMap((thread) =>
392 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
393 (link) => link.snapshot?.state === "open",
394 ),
395 ),
396 requestSync,
397 { discard: true },
398 ),
399 ),
400 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
401 );
402​
403 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
404 "PullRequestSyncReactor.start",
405 )(function* () {
406 const events = engine.streamDomainEvents;
407 const stateChanges = Stream.merge(
408 yield* pullRequests.subscribeStateChanges,
409 yield* git.subscribePullRequestStateChanges,
410 );
411 yield* forkParked(
412 Stream.runForEach(stateChanges, requestSync).pipe(
413 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
414 ),
415 );
416 yield* forkParked(
417 Stream.runForEach(events, (event) => {
418 switch (event.type) {
419 case "thread.pull-request-link-updated":
420 return event.payload.snapshot === null ? requestSync(event.payload) : Effect.void;
421 case "thread.pull-request-synced":
422 return Effect.forEach(
423 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
424 (link) => link.snapshot === null,
425 ),
426 requestSync,
427 { discard: true },
428 );
429 // An agent can merge or close its pull request from a shell (`gh pr merge`), which
430 // sends no merge notification. When a run that ran such a command ends, read the
431 // thread's open links fresh, so settlement does not wait for the next sweep and the
432 // cached summary. Other runs add no host reads.
433 case "turn-item.updated":
434 if (
435 event.payload.type === "command_execution" &&
436 PULL_REQUEST_CLOSE_COMMAND.test(event.payload.input)
437 ) {
438 closeCommandThreads.add(event.threadId);
439 }
440 return Effect.void;
441 case "run.updated":
442 return isTerminalRunStatus(event.payload.status) &&
443 closeCommandThreads.delete(event.threadId)
444 ? refreshOpenLinks(event.threadId)
445 : Effect.void;
446 default:
447 return Effect.void;
448 }
449 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
450 );
451 yield* forkParked(
452 Effect.gen(function* () {
453 yield* worker.enqueue("all");
454 yield* worker.drain;
455 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
456 );
457 });
458​
459 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
460 Effect.suspend(() => {
461 requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
462 if (requestedSweepQueued) return Effect.void;
463 requestedSweepQueued = true;
464 return worker.enqueue("requested");
465 });
466​
467 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
468});
469​
470export const layer = Layer.effect(PullRequestSyncReactor, make);