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

PullRequestSyncReactor.ts

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