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

PullRequestSyncReactor.ts

475 lines19.7 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 { PullRequestProviderError } from "../pullRequest/PullRequestProvider.ts";
32import * as PullRequestService from "../pullRequest/PullRequestService.ts";
33import { forkParked } from "../serverActivation.ts";
34import * as Orchestrator from "./Orchestrator.ts";
35import * as ProjectionStore from "./ProjectionStore.ts";
36import { isTerminalRunStatus } from "./ThreadManagementService.ts";
37​
38const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
39/** Shell commands that can merge or close a pull request without a merge notification. */
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​
120/** When a host read failed because the host is rate limited, the time that pause ends. */
121function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
122 let error: unknown = Cause.squash(cause);
123 while (error instanceof Error) {
124 if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
125 error = error.cause;
126 }
127 return undefined;
129​
130function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
131 return thread.settledOverride !== "settled" && thread.settledAt === null;
133​
134/**
135 * Keeps every thread ↔ pull request link's host snapshot current. One sweep a minute reads
136 * only the active threads that have links, groups visible links by pull request so the host
137 * is asked once per PR no matter how many threads share it, and writes back only what
138 * changed. Native stacks the host reports are auto-linked to the thread as `source: "stack"`.
139 */
140export class PullRequestSyncReactor extends Context.Service<
141 PullRequestSyncReactor,
142 {
143 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
144 readonly drain: Effect.Effect<void>;
145 /**
146 * Force the next sweep to re-read this pull request, even when its snapshot is terminal.
147 * While its host is rate limited, the read waits for the first sweep after the pause.
148 */
149 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
150 }
151>()("t3/orchestration-v2/PullRequestSyncReactor") {}
152​
153/** @public Service construction is part of the canonical Effect module API. */
154export const make = Effect.gen(function* () {
155 const engine = yield* Orchestrator.OrchestratorV2;
156 const projections = yield* ProjectionStore.ProjectionStoreV2;
157 const pullRequests = yield* PullRequestService.PullRequestService;
158 const crypto = yield* Crypto.Crypto;
159​
160 const lastSyncedAt = new Map<string, number>();
161 const requested = new Map<string, number>();
162 let requestGeneration = 0;
163 // Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent
164 // linking dozens of pull requests) is read together and shares the summary batches.
165 let requestedSweepQueued = false;
166 const retryStacks = new Set<string>();
167 // Rate limit pauses by project and host, since each project reads with its own credential.
168 // A paused host refuses every read without asking it, so the sweep leaves its pull requests
169 // due until the pause ends rather than failing each of them every minute.
170 const pausedUntil = new Map<string, number>();
171​
172 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
173 if (requested.has(key) || retryStacks.has(key)) return true;
174 if (entries.some((entry) => entry.link.snapshot === null)) return true;
175 if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
176 if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
177 return true;
178 // Closed requests can reopen on the host, including after the thread settles.
179 const last = lastSyncedAt.get(key);
180 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
181 };
182​
183 const logSkipped =
184 (message: string, fields: Record<string, unknown>) =>
185 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
186 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
187​
188 /** `requested` reads only keys asked for through `requestSync`; `all` is the periodic pass. */
189 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
190 const threads = yield* projections.getThreadsWithPullRequests();
191 const now = yield* DateTime.now;
192 const nowMs = DateTime.toEpochMillis(now);
193 const nowIso = DateTime.formatIso(now);
194​
195 const groups = new Map<string, Array<LinkEntry>>();
196 for (const thread of threads) {
197 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
198 const key = threadPullRequestKeyOf(link);
199 const entries = groups.get(key) ?? [];
200 entries.push({ thread, link });
201 groups.set(key, entries);
202 }
203 }
204​
205 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
206 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
207 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
208​
209 // Layers auto-linked this sweep, so two links of one thread that share a
210 // stack do not both try to add the same sibling.
211 const linkedThisSweep = new Set<string>();
212 const persistence = yield* Semaphore.make(1);
213​
214 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
215 entry: LinkEntry,
216 fields: SnapshotFields,
217 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
218 ) {
219 const { thread, link } = entry;
220 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
221 const changed =
222 link.snapshot === null ||
223 !snapshotFieldsEqual(link.snapshot, fields) ||
224 !stacksEqual(link.stack, nextStack);
225 // Persist discovered siblings before a terminal snapshot can trigger settlement.
226 for (const layer of fetchedStack?.stack?.layers ?? []) {
227 const layerKey = {
228 host: normalizeThreadPullRequestKey(link).host,
229 repository: link.repository,
230 number: layer.number,
231 };
232 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
233 if (linkedThisSweep.has(dedupeKey)) continue;
234 // Tombstones count as present: a dismissed layer is never re-added.
235 if (
236 (thread.pullRequests ?? []).some((existing) =>
237 threadPullRequestKeysEqual(existing, layerKey),
238 )
239 ) {
240 continue;
241 }
242 const url = siblingPullRequestUrl(link.url, layer.number);
243 if (url === null) continue;
244 const uuid = yield* crypto.randomUUIDv4;
245 yield* engine.dispatch({
246 type: "thread.pull-request.link",
247 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
248 threadId: thread.id,
249 ...layerKey,
250 url,
251 source: "stack",
252 });
253 linkedThisSweep.add(dedupeKey);
254 }
255 if (changed) {
256 const uuid = yield* crypto.randomUUIDv4;
257 yield* engine.dispatch({
258 type: "thread.pull-request-link.sync",
259 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
260 threadId: thread.id,
261 host: normalizeThreadPullRequestKey(link).host,
262 repository: link.repository,
263 number: link.number,
264 snapshot: { ...fields, syncedAt: nowIso },
265 stack: nextStack,
266 });
267 }
268 });
269​
270 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
271 key: string,
272 entries: ReadonlyArray<LinkEntry>,
273 ) {
274 const first = entries[0]!;
275 const ref = {
276 projectId: first.thread.projectId,
277 host: normalizeThreadPullRequestKey(first.link).host,
278 repository: first.link.repository,
279 number: first.link.number,
280 };
281 const generation = requested.get(key);
282 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
283 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
284 const fields = snapshotFieldsOf(summary);
285 const needsStack =
286 generation !== undefined ||
287 retryStacks.has(key) ||
288 entries.some(
289 (entry) =>
290 entry.link.snapshot === null ||
291 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
292 (summary.stack !== undefined &&
293 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
294 );
295 // A summary that says the pull request is in no stack, for links that hold none, already
296 // answers what the stack read would.
297 const knownUnstacked =
298 summary.stack === null && entries.every((entry) => entry.link.stack === null);
299 const fetchedStack = !needsStack
300 ? null
301 : knownUnstacked
302 ? { stack: null }
303 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
304 Effect.map((stack) => ({
305 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
306 })),
307 Effect.catchCauseIf(
308 (cause) => !Cause.hasInterruptsOnly(cause),
309 (cause) =>
310 rateLimitRetryAt(cause) !== undefined
311 ? // The sweep records the pause and holds the host's other reads until it ends.
312 Effect.sync(() => retryStacks.add(key)).pipe(
313 Effect.andThen(Effect.failCause(cause)),
314 )
315 : Effect.logWarning("pull request stack lookup failed", {
316 key,
317 }).pipe(Effect.as(null)),
318 ),
319 );
320 if (needsStack) {
321 if (fetchedStack === null) {
322 retryStacks.add(key);
323 return;
324 }
325 retryStacks.delete(key);
326 }
327 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
328 lastSyncedAt.set(key, nowMs);
329 // A refresh requested while the host read was in flight belongs to the next sweep.
330 if (requested.get(key) === generation) requested.delete(key);
331 yield* Effect.forEach(
332 entries,
333 (entry) =>
334 syncEntry(entry, fields, fetchedStack).pipe(
335 persistence.withPermits(1),
336 Effect.catchCause((cause) => {
337 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
338 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
339 cause,
340 );
341 }),
342 ),
343 { discard: true },
344 );
345 });
346​
347 // Failed host reads by reason: how many, and the first key that failed that way.
348 const skips = new Map<string, { count: number; readonly key: string }>();
349 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
350 syncGroup(key, entries).pipe(
351 Effect.catchCause((cause) => {
352 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
353 const retryAt = rateLimitRetryAt(cause);
354 if (retryAt !== undefined) {
355 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
356 }
357 const reason = skipReason(cause);
358 const skip = skips.get(reason);
359 if (skip === undefined) skips.set(reason, { count: 1, key });
360 else skip.count += 1;
361 return Effect.void;
362 }),
363 );
364 yield* Effect.forEach(
365 groups,
366 ([key, entries]) => {
367 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
368 return Effect.void;
369 }
370 const first = entries[0]!;
371 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
372 // Checked against the clock as each read starts, so a pause found earlier in this sweep
373 // holds the rest, and one that ends during the sweep lets the rest through.
374 return Clock.currentTimeMillis.pipe(
375 Effect.flatMap((startedAtMs) =>
376 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
377 ? Effect.void
378 : readGroup(key, entries, pauseKey),
379 ),
380 );
381 },
382 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
383 // GitHub answers them in one request rather than one `gh pr view` apiece.
384 { concurrency: 25, discard: true },
385 );
386 // A host failure such as a signed-out CLI fails every due pull request the same way, so a
387 // sweep reports one line per reason rather than one per pull request.
388 for (const [reason, { count, key }] of skips) {
389 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
390 }
391 });
392​
393 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
394 Effect.suspend(() => {
395 // Requests from here on queue another sweep; the ones already recorded are read by this.
396 if (scope === "requested") requestedSweepQueued = false;
397 return sweep(scope);
398 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
399 );
400​
401 // Threads whose current run ran a merge or close command, until that run ends.
402 const closeCommandThreads = new Set<ThreadId>();
403 const refreshOpenLinks = (threadId: ThreadId) =>
404 projections.getThreadsWithPullRequests(threadId).pipe(
405 Effect.flatMap((threads) =>
406 Effect.forEach(
407 threads.flatMap((thread) =>
408 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
409 (link) => link.snapshot?.state === "open",
410 ),
411 ),
412 requestSync,
413 { discard: true },
414 ),
415 ),
416 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
417 );
418​
419 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
420 "PullRequestSyncReactor.start",
421 )(function* () {
422 const events = engine.streamDomainEvents;
423 yield* forkParked(
424 Stream.runForEach(events, (event) => {
425 switch (event.type) {
426 case "thread.pull-request-synced":
427 return Effect.forEach(
428 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
429 (link) => link.snapshot === null,
430 ),
431 requestSync,
432 { discard: true },
433 );
434 // An agent can merge or close its pull request from a shell (`gh pr merge`), which
435 // sends no merge notification. When a run that ran such a command ends, read the
436 // thread's open links fresh, so settlement does not wait for the next sweep and the
437 // cached summary. Other runs add no host reads.
438 case "turn-item.updated":
439 if (
440 event.payload.type === "command_execution" &&
441 PULL_REQUEST_CLOSE_COMMAND.test(event.payload.input)
442 ) {
443 closeCommandThreads.add(event.threadId);
444 }
445 return Effect.void;
446 case "run.updated":
447 return isTerminalRunStatus(event.payload.status) &&
448 closeCommandThreads.delete(event.threadId)
449 ? refreshOpenLinks(event.threadId)
450 : Effect.void;
451 default:
452 return Effect.void;
453 }
454 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
455 );
456 yield* forkParked(
457 Effect.gen(function* () {
458 yield* worker.enqueue("all");
459 yield* worker.drain;
460 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
461 );
462 });
463​
464 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
465 Effect.suspend(() => {
466 requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
467 if (requestedSweepQueued) return Effect.void;
468 requestedSweepQueued = true;
469 return worker.enqueue("requested");
470 });
471​
472 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
473});
474​
475export const layer = Layer.effect(PullRequestSyncReactor, make);