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

PullRequestSyncReactor.ts

568 lines23.5 KB

1import {
2 CommandId,
3 type PullRequestSummary,
4 type ThreadId,
5 type ThreadPullRequestKey,
6 type ThreadPullRequestLink,
7 type ThreadPullRequestSnapshot,
8 type ThreadPullRequestStack,
9} from "@t3tools/contracts";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import {
12 threadPullRequestKeyOf,
13 normalizeThreadPullRequestKey,
14 threadPullRequestKeysEqual,
15 visibleThreadPullRequests,
16} from "../sourceControl/threadPullRequests.ts";
17import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
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 a host CLI's merge command still read it at once.
43const QUIET_AFTER_MS = 30 * 60 * 1_000;
44const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000;
45​
46const isChangeRequestCloseCommand = (command: string) =>
47 sourceControlDefinitions.definitions.some(
48 (definition) => definition.changeRequestCloseCommand?.test(command) === true,
49 );
50​
51const isPullRequestProviderError = Schema.is(PullRequestProviderError);
52​
53type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
54​
55interface LinkEntry {
56 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
57 readonly link: ThreadPullRequestLink;
59​
60/** Another layer of the stack `url` belongs to, in its host's canonical shape. */
61function siblingChangeRequestUrl(url: string, number: number): string | null {
62 if (!Number.isSafeInteger(number) || number < 1) return null;
63 const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
64 if (parsed === null) return null;
65 const { definition, link } = parsed;
66 return definition.changeRequestUrl({
67 host: link.host,
68 repository: link.repository,
69 number,
70 webUrl: link.repositoryUrl,
71 });
73​
74function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
75 return {
76 state: summary.state,
77 title: summary.title,
78 headBranch: summary.headBranch,
79 baseBranch: summary.baseBranch,
80 isDraft: summary.isDraft ?? false,
81 updatedAt: summary.updatedAt,
82 closedAt: summary.closedAt ?? null,
83 mergedAt: summary.mergedAt ?? null,
84 ...(summary.author === undefined ? {} : { author: summary.author }),
85 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
86 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
87 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
88 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
89 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
90 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
91 };
93​
94// Rotating ghe.com avatar tokens should not make otherwise identical snapshots differ.
95function avatarIdentity(avatarUrl: string | null | undefined): string | null {
96 if (avatarUrl === null || avatarUrl === undefined) return null;
97 const url = URL.parse(avatarUrl);
98 if (url === null || (url.hostname !== "ghe.com" && !url.hostname.endsWith(".ghe.com"))) {
99 return avatarUrl;
100 }
101 url.searchParams.delete("token");
102 return url.href;
104​
105function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
106 return (
107 left.state === right.state &&
108 left.title === right.title &&
109 left.headBranch === right.headBranch &&
110 left.baseBranch === right.baseBranch &&
111 left.isDraft === right.isDraft &&
112 left.updatedAt === right.updatedAt &&
113 (left.closedAt ?? null) === (right.closedAt ?? null) &&
114 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
115 (left.author?.login ?? null) === (right.author?.login ?? null) &&
116 avatarIdentity(left.author?.avatarUrl) === avatarIdentity(right.author?.avatarUrl) &&
117 left.additions === right.additions &&
118 left.deletions === right.deletions &&
119 left.changedFiles === right.changedFiles &&
120 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
121 (left.checksState ?? null) === (right.checksState ?? null) &&
122 left.mergeability === right.mergeability
123 );
125​
126function stacksEqual(
127 left: ThreadPullRequestStack | null,
128 right: ThreadPullRequestStack | null,
129): boolean {
130 if (left === null || right === null) return left === right;
131 return (
132 left.kind === right.kind &&
133 left.id === right.id &&
134 left.number === right.number &&
135 left.url === right.url &&
136 left.base === right.base &&
137 left.layers.length === right.layers.length &&
138 left.layers.every((layer, index) => {
139 const other = right.layers[index]!;
140 return (
141 layer.number === other.number &&
142 layer.headBranch === other.headBranch &&
143 layer.state === other.state
144 );
145 })
146 );
148​
149/** Stack ids are unique only within a repository, e.g. GitHub's fallback to the stack number. */
150function nativeStackKeyOf(link: ThreadPullRequestLink, stack: ThreadPullRequestStack): string {
151 const key = normalizeThreadPullRequestKey(link);
152 return `${key.host}/${key.repository}#stack:${stack.id}`;
154​
155function sameLayerNumbers(left: ThreadPullRequestStack, right: ThreadPullRequestStack): boolean {
156 return (
157 left.layers.length === right.layers.length &&
158 left.layers.every((layer, index) => layer.number === right.layers[index]!.number)
159 );
161​
162function skipReason(cause: Cause.Cause<unknown>): string {
163 const error = Cause.squash(cause);
164 return error instanceof Error ? error.message : String(error);
166​
167function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
168 let error: unknown = Cause.squash(cause);
169 while (error instanceof Error) {
170 if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
171 error = error.cause;
172 }
173 return undefined;
175​
176function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
177 return thread.settledOverride !== "settled" && thread.settledAt === null;
179​
180export class PullRequestSyncReactor extends Context.Service<
181 PullRequestSyncReactor,
182 {
183 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
184 readonly drain: Effect.Effect<void>;
185 /** Forces reread on the next sweep, including terminal snapshots; rate-limited hosts wait until the pause ends. */
186 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
187 }
188>()("t3/orchestration-v2/PullRequestSyncReactor") {}
189​
190/** @public */
191export const make = Effect.gen(function* () {
192 const engine = yield* Orchestrator.OrchestratorV2;
193 const projections = yield* ProjectionStore.ProjectionStoreV2;
194 const pullRequests = yield* PullRequestService.PullRequestService;
195 const git = yield* GitManager.GitManager;
196 const crypto = yield* Crypto.Crypto;
197​
198 const lastSyncedAt = new Map<string, number>();
199 const requested = new Set<string>();
200 // Requests arriving during a host read wait for the next sweep.
201 const pendingRequests = new Set<string>();
202 // PR keys wait in `pendingRequests` for one queued sweep, so a burst of links (an agent
203 // linking dozens of pull requests) is read together and shares the summary batches.
204 let requestedSweepQueued = false;
205 const retryStacks = new Set<string>();
206 // Pause per project and host because credentials are project-specific; leave paused PRs due until reset.
207 const pausedUntil = new Map<string, number>();
208​
209 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
210 if (requested.has(key) || retryStacks.has(key)) return true;
211 if (entries.some((entry) => entry.link.snapshot === null)) return true;
212 const active = entries.filter((entry) => isUnsettled(entry.thread));
213 // Merged snapshots without mergedAt cannot settle threads; reread slowly until supplied.
214 if (
215 active.every(
216 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt != null,
217 )
218 ) {
219 return false;
220 }
221 const last = lastSyncedAt.get(key);
222 const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last;
223 const open = active.filter((entry) => entry.link.snapshot?.state === "open");
224 if (open.length > 0) {
225 const quiet = open.every((entry) => {
226 const updatedAt = entry.link.snapshot?.updatedAt;
227 return updatedAt != null && nowMs - Date.parse(updatedAt) >= QUIET_AFTER_MS;
228 });
229 return !quiet || sinceLastMs >= QUIET_SYNC_INTERVAL_MS;
230 }
231 return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
232 };
233​
234 const logSkipped =
235 (message: string, fields: Record<string, unknown>) =>
236 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
237 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
238​
239 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
240 const threads = yield* projections.getThreadsWithPullRequests();
241 const now = yield* DateTime.now;
242 const nowMs = DateTime.toEpochMillis(now);
243 const nowIso = DateTime.formatIso(now);
244​
245 const groups = new Map<string, Array<LinkEntry>>();
246 for (const thread of threads) {
247 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
248 // Reads depend on the project's checkout and credentials, including their failures.
249 const key = `${thread.projectId}\0${threadPullRequestKeyOf(link)}`;
250 const entries = groups.get(key) ?? [];
251 entries.push({ thread, link });
252 groups.set(key, entries);
253 }
254 }
255​
256 // A host-level refresh reaches every project, each retaining its own pending retry.
257 for (const [key, entries] of groups) {
258 if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key);
259 }
260 pendingRequests.clear();
261​
262 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
263 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
264 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
265​
266 const linkedThisSweep = new Set<string>();
267 // Fresh stack reads by group, so a member flagged by a sibling is compared against what the
268 // host answered this sweep, not the saved layers that sibling is about to replace.
269 const stacksReadThisSweep = new Map<string, ThreadPullRequestStack | null>();
270 const persistence = yield* Semaphore.make(1);
271​
272 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
273 entry: LinkEntry,
274 fields: SnapshotFields,
275 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
276 ) {
277 const { thread, link } = entry;
278 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
279 const changed =
280 link.snapshot === null ||
281 !snapshotFieldsEqual(link.snapshot, fields) ||
282 !stacksEqual(link.stack, nextStack);
283 // Persist siblings before terminal snapshots trigger settlement; settled threads get snapshots without new links.
284 for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
285 const layerKey = {
286 host: normalizeThreadPullRequestKey(link).host,
287 repository: link.repository,
288 number: layer.number,
289 };
290 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
291 if (linkedThisSweep.has(dedupeKey)) continue;
292 // Tombstones count as present: a dismissed layer is never re-added.
293 if (
294 (thread.pullRequests ?? []).some((existing) =>
295 threadPullRequestKeysEqual(existing, layerKey),
296 )
297 ) {
298 continue;
299 }
300 const url = siblingChangeRequestUrl(link.url, layer.number);
301 if (url === null) continue;
302 const uuid = yield* crypto.randomUUIDv4();
303 yield* engine.dispatch({
304 type: "thread.pull-request.link",
305 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
306 threadId: thread.id,
307 ...layerKey,
308 url,
309 source: "stack",
310 });
311 linkedThisSweep.add(dedupeKey);
312 }
313 if (changed) {
314 const uuid = yield* crypto.randomUUIDv4();
315 yield* engine.dispatch({
316 type: "thread.pull-request-link.sync",
317 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
318 threadId: thread.id,
319 host: normalizeThreadPullRequestKey(link).host,
320 repository: link.repository,
321 number: link.number,
322 snapshot: { ...fields, syncedAt: nowIso },
323 stack: nextStack,
324 });
325 }
326 });
327​
328 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
329 key: string,
330 entries: ReadonlyArray<LinkEntry>,
331 ) {
332 const first = entries[0]!;
333 const ref = {
334 projectId: first.thread.projectId,
335 host: normalizeThreadPullRequestKey(first.link).host,
336 repository: first.link.repository,
337 number: first.link.number,
338 };
339 const refreshRequested = requested.has(key);
340 // A held merged summary is served without asking the host, so a snapshot still missing its
341 // merge time has to drop it or the slow-cadence re-read would hand back the same gap.
342 const missingMergedAt = entries.some(
343 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,
344 );
345 // A stack retry reads past the cache, or it could get back the layer list it is retrying.
346 const invalidated = refreshRequested || missingMergedAt || retryStacks.has(key);
347 if (invalidated) yield* pullRequests.invalidate({ reference: ref });
348 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
349 const fields = snapshotFieldsOf(summary);
350 const needsStack =
351 refreshRequested ||
352 retryStacks.has(key) ||
353 entries.some(
354 (entry) =>
355 entry.link.snapshot === null ||
356 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
357 (summary.stack !== undefined &&
358 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
359 );
360 const knownUnstacked =
361 summary.stack === null && entries.every((entry) => entry.link.stack === null);
362 // A sibling can flag this group while its summary read is in flight.
363 if (!invalidated && retryStacks.has(key) && !knownUnstacked) {
364 yield* pullRequests.invalidate({ reference: ref });
365 }
366 // The retry this read answers is consumed before the read, not after it: a sibling may
367 // flag this group again while the read is in flight, and that flag must survive to the
368 // next sweep because the answer below may predate the sibling's layers.
369 if (needsStack) retryStacks.delete(key);
370 const fetchedStack = !needsStack
371 ? null
372 : knownUnstacked
373 ? { stack: null }
374 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
375 Effect.map((stack) => ({
376 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
377 })),
378 Effect.catchCauseIf(
379 (cause) => !Cause.hasInterruptsOnly(cause),
380 (cause) =>
381 rateLimitRetryAt(cause) !== undefined
382 ? Effect.sync(() => retryStacks.add(key)).pipe(
383 Effect.andThen(Effect.failCause(cause)),
384 )
385 : Effect.logWarning("pull request stack lookup failed", {
386 key,
387 }).pipe(Effect.as(null)),
388 ),
389 );
390 if (needsStack) {
391 if (fetchedStack === null) {
392 retryStacks.add(key);
393 return;
394 }
395 const fetched = fetchedStack.stack;
396 stacksReadThisSweep.set(key, fetched);
397 // New upper layers leave older members' fields unchanged; differing layer lists need a stack read.
398 // Only flag siblings in the same project: different credentials can yield lists that never agree.
399 if (fetched !== null) {
400 const fetchedKey = nativeStackKeyOf(first.link, fetched);
401 for (const [siblingKey, siblingEntries] of groups) {
402 if (siblingKey === key) continue;
403 if (siblingEntries[0]!.thread.projectId !== first.thread.projectId) continue;
404 const readThisSweep = stacksReadThisSweep.get(siblingKey);
405 const stale = siblingEntries.some(({ link }) => {
406 const stack = readThisSweep === undefined ? link.stack : readThisSweep;
407 return (
408 stack !== null &&
409 nativeStackKeyOf(link, stack) === fetchedKey &&
410 !sameLayerNumbers(stack, fetched)
411 );
412 });
413 if (stale) retryStacks.add(siblingKey);
414 }
415 }
416 }
417 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
418 lastSyncedAt.set(key, nowMs);
419 requested.delete(key);
420 yield* Effect.forEach(
421 entries,
422 (entry) =>
423 syncEntry(entry, fields, fetchedStack).pipe(
424 persistence.withPermits(1),
425 Effect.catchCause((cause) => {
426 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
427 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
428 cause,
429 );
430 }),
431 ),
432 { discard: true },
433 );
434 });
435​
436 const skips = new Map<string, { count: number; readonly key: string }>();
437 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
438 syncGroup(key, entries).pipe(
439 Effect.catchCause((cause) => {
440 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
441 const retryAt = rateLimitRetryAt(cause);
442 if (retryAt !== undefined) {
443 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
444 }
445 const reason = skipReason(cause);
446 const skip = skips.get(reason);
447 if (skip === undefined) skips.set(reason, { count: 1, key });
448 else skip.count += 1;
449 return Effect.void;
450 }),
451 );
452 yield* Effect.forEach(
453 groups,
454 ([key, entries]) => {
455 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
456 return Effect.void;
457 }
458 const first = entries[0]!;
459 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
460 // Check pauses at each read so changes during the sweep apply immediately.
461 return Clock.currentTimeMillis.pipe(
462 Effect.flatMap((startedAtMs) =>
463 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
464 ? Effect.void
465 : readGroup(key, entries, pauseKey),
466 ),
467 );
468 },
469 // Match summary batch width so GitHub reads coalesce into one request.
470 { concurrency: 25, discard: true },
471 );
472 for (const [reason, { count, key }] of skips) {
473 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
474 }
475 });
476​
477 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
478 Effect.suspend(() => {
479 if (scope === "requested") requestedSweepQueued = false;
480 return sweep(scope);
481 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
482 );
483​
484 const closeCommandThreads = new Set<ThreadId>();
485 const refreshOpenLinks = (threadId: ThreadId) =>
486 projections.getThreadsWithPullRequests(threadId).pipe(
487 Effect.flatMap((threads) =>
488 Effect.forEach(
489 threads.flatMap((thread) =>
490 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
491 (link) => link.snapshot?.state === "open",
492 ),
493 ),
494 requestSync,
495 { discard: true },
496 ),
497 ),
498 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
499 );
500​
501 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
502 "PullRequestSyncReactor.start",
503 )(function* () {
504 const events = engine.streamDomainEvents;
505 const stateChanges = Stream.merge(
506 yield* pullRequests.subscribeStateChanges,
507 yield* git.subscribePullRequestStateChanges,
508 );
509 yield* forkParked(
510 Stream.runForEach(stateChanges, requestSync).pipe(
511 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
512 ),
513 );
514 yield* forkParked(
515 Stream.runForEach(events, (event) => {
516 switch (event.type) {
517 case "thread.pull-request-link-updated":
518 return event.payload.snapshot === null ? requestSync(event.payload) : Effect.void;
519 case "thread.pull-request-synced":
520 return Effect.forEach(
521 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
522 (link) => link.snapshot === null,
523 ),
524 requestSync,
525 { discard: true },
526 );
527 // An agent can merge or close its pull request from a shell with its host's CLI, which
528 // sends no merge notification. When a run that ran such a command ends, read the
529 // thread's open links fresh, so settlement does not wait for the next sweep and the
530 // cached summary. Other runs add no host reads.
531 case "turn-item.updated":
532 if (
533 event.payload.type === "command_execution" &&
534 isChangeRequestCloseCommand(event.payload.input)
535 ) {
536 closeCommandThreads.add(event.threadId);
537 }
538 return Effect.void;
539 case "run.updated":
540 return isTerminalRunStatus(event.payload.status) &&
541 closeCommandThreads.delete(event.threadId)
542 ? refreshOpenLinks(event.threadId)
543 : Effect.void;
544 default:
545 return Effect.void;
546 }
547 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
548 );
549 yield* forkParked(
550 Effect.gen(function* () {
551 yield* worker.enqueue("all");
552 yield* worker.drain;
553 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
554 );
555 });
556​
557 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
558 Effect.suspend(() => {
559 pendingRequests.add(threadPullRequestKeyOf(key));
560 if (requestedSweepQueued) return Effect.void;
561 requestedSweepQueued = true;
562 return worker.enqueue("requested");
563 });
564​
565 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
566});
567​
568export const layer = Layer.effect(PullRequestSyncReactor, make);