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