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

PullRequestSyncReactor.ts

485 lines19.6 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 // A merged snapshot without its merge time cannot settle the thread, so it keeps the slow
171 // cadence until the host supplies one (Bitbucket snapshots saved before it was read).
172 if (
173 active.every(
174 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt != null,
175 )
176 ) {
177 return false;
178 }
179 if (active.some((entry) => entry.link.snapshot?.state === "open")) return true;
180 const last = lastSyncedAt.get(key);
181 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
182 };
183​
184 const logSkipped =
185 (message: string, fields: Record<string, unknown>) =>
186 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
187 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
188​
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 const linkedThisSweep = new Set<string>();
210 const persistence = yield* Semaphore.make(1);
211​
212 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
213 entry: LinkEntry,
214 fields: SnapshotFields,
215 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
216 ) {
217 const { thread, link } = entry;
218 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
219 const changed =
220 link.snapshot === null ||
221 !snapshotFieldsEqual(link.snapshot, fields) ||
222 !stacksEqual(link.stack, nextStack);
223 // Persist discovered siblings before a terminal snapshot can trigger settlement. A settled
224 // thread that shares this pull request with an active one takes the fresh snapshot, but
225 // gains no links.
226 for (const layer of isUnsettled(thread) ? (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 // A held merged summary is served without asking the host, so a snapshot still missing its
283 // merge time has to drop it or the slow-cadence re-read would hand back the same gap.
284 const missingMergedAt = entries.some(
285 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,
286 );
287 if (generation !== undefined || missingMergedAt) {
288 yield* pullRequests.invalidate({ reference: ref });
289 }
290 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
291 const fields = snapshotFieldsOf(summary);
292 const needsStack =
293 generation !== undefined ||
294 retryStacks.has(key) ||
295 entries.some(
296 (entry) =>
297 entry.link.snapshot === null ||
298 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
299 (summary.stack !== undefined &&
300 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
301 );
302 const knownUnstacked =
303 summary.stack === null && entries.every((entry) => entry.link.stack === null);
304 const fetchedStack = !needsStack
305 ? null
306 : knownUnstacked
307 ? { stack: null }
308 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
309 Effect.map((stack) => ({
310 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
311 })),
312 Effect.catchCauseIf(
313 (cause) => !Cause.hasInterruptsOnly(cause),
314 (cause) =>
315 rateLimitRetryAt(cause) !== undefined
316 ? Effect.sync(() => retryStacks.add(key)).pipe(
317 Effect.andThen(Effect.failCause(cause)),
318 )
319 : Effect.logWarning("pull request stack lookup failed", {
320 key,
321 }).pipe(Effect.as(null)),
322 ),
323 );
324 if (needsStack) {
325 if (fetchedStack === null) {
326 retryStacks.add(key);
327 return;
328 }
329 retryStacks.delete(key);
330 }
331 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
332 lastSyncedAt.set(key, nowMs);
333 // A refresh requested while the host read was in flight belongs to the next sweep.
334 if (requested.get(key) === generation) requested.delete(key);
335 yield* Effect.forEach(
336 entries,
337 (entry) =>
338 syncEntry(entry, fields, fetchedStack).pipe(
339 persistence.withPermits(1),
340 Effect.catchCause((cause) => {
341 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
342 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
343 cause,
344 );
345 }),
346 ),
347 { discard: true },
348 );
349 });
350​
351 const skips = new Map<string, { count: number; readonly key: string }>();
352 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
353 syncGroup(key, entries).pipe(
354 Effect.catchCause((cause) => {
355 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
356 const retryAt = rateLimitRetryAt(cause);
357 if (retryAt !== undefined) {
358 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
359 }
360 const reason = skipReason(cause);
361 const skip = skips.get(reason);
362 if (skip === undefined) skips.set(reason, { count: 1, key });
363 else skip.count += 1;
364 return Effect.void;
365 }),
366 );
367 yield* Effect.forEach(
368 groups,
369 ([key, entries]) => {
370 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
371 return Effect.void;
372 }
373 const first = entries[0]!;
374 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
375 // Checked against the clock as each read starts, so a pause found earlier in this sweep
376 // holds the rest, and one that ends during the sweep lets the rest through.
377 return Clock.currentTimeMillis.pipe(
378 Effect.flatMap((startedAtMs) =>
379 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
380 ? Effect.void
381 : readGroup(key, entries, pauseKey),
382 ),
383 );
384 },
385 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
386 // GitHub answers them in one request rather than one `gh pr view` apiece.
387 { concurrency: 25, discard: true },
388 );
389 for (const [reason, { count, key }] of skips) {
390 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
391 }
392 });
393​
394 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
395 Effect.suspend(() => {
396 if (scope === "requested") requestedSweepQueued = false;
397 return sweep(scope);
398 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
399 );
400​
401 const closeCommandThreads = new Set<ThreadId>();
402 const refreshOpenLinks = (threadId: ThreadId) =>
403 projections.getThreadsWithPullRequests(threadId).pipe(
404 Effect.flatMap((threads) =>
405 Effect.forEach(
406 threads.flatMap((thread) =>
407 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
408 (link) => link.snapshot?.state === "open",
409 ),
410 ),
411 requestSync,
412 { discard: true },
413 ),
414 ),
415 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
416 );
417​
418 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
419 "PullRequestSyncReactor.start",
420 )(function* () {
421 const events = engine.streamDomainEvents;
422 const stateChanges = Stream.merge(
423 yield* pullRequests.subscribeStateChanges,
424 yield* git.subscribePullRequestStateChanges,
425 );
426 yield* forkParked(
427 Stream.runForEach(stateChanges, requestSync).pipe(
428 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
429 ),
430 );
431 yield* forkParked(
432 Stream.runForEach(events, (event) => {
433 switch (event.type) {
434 case "thread.pull-request-link-updated":
435 return event.payload.snapshot === null ? requestSync(event.payload) : Effect.void;
436 case "thread.pull-request-synced":
437 return Effect.forEach(
438 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
439 (link) => link.snapshot === null,
440 ),
441 requestSync,
442 { discard: true },
443 );
444 // An agent can merge or close its pull request from a shell (`gh pr merge`), which
445 // sends no merge notification. When a run that ran such a command ends, read the
446 // thread's open links fresh, so settlement does not wait for the next sweep and the
447 // cached summary. Other runs add no host reads.
448 case "turn-item.updated":
449 if (
450 event.payload.type === "command_execution" &&
451 PULL_REQUEST_CLOSE_COMMAND.test(event.payload.input)
452 ) {
453 closeCommandThreads.add(event.threadId);
454 }
455 return Effect.void;
456 case "run.updated":
457 return isTerminalRunStatus(event.payload.status) &&
458 closeCommandThreads.delete(event.threadId)
459 ? refreshOpenLinks(event.threadId)
460 : Effect.void;
461 default:
462 return Effect.void;
463 }
464 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
465 );
466 yield* forkParked(
467 Effect.gen(function* () {
468 yield* worker.enqueue("all");
469 yield* worker.drain;
470 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
471 );
472 });
473​
474 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
475 Effect.suspend(() => {
476 requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
477 if (requestedSweepQueued) return Effect.void;
478 requestedSweepQueued = true;
479 return worker.enqueue("requested");
480 });
481​
482 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
483});
484​
485export const layer = Layer.effect(PullRequestSyncReactor, make);