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

PullRequestSyncReactor.ts

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