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

PullRequestSyncReactor.ts

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