Open History to see the last commit
1import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
2import {
3 CommandId,
4 type PullRequestSummary,
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 "@t3tools/shared/threadPullRequests";
17import * as Cause from "effect/Cause";
18import * as Context from "effect/Context";
19import * as Crypto from "effect/Crypto";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as Schedule from "effect/Schedule";
24import type * as Scope from "effect/Scope";
25import * as Semaphore from "effect/Semaphore";
26import * as Stream from "effect/Stream";
27
28import * as PullRequestService from "../pullRequest/PullRequestService.ts";
29import { forkParked } from "../serverActivation.ts";
30import * as Orchestrator from "./Orchestrator.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32
33const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
34
35type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
36
37interface LinkEntry {
38 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
39 readonly link: ThreadPullRequestLink;
40}
41
42function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
43 return {
44 state: summary.state,
45 title: summary.title,
46 headBranch: summary.headBranch,
47 baseBranch: summary.baseBranch,
48 isDraft: summary.isDraft ?? false,
49 updatedAt: summary.updatedAt,
50 closedAt: summary.closedAt ?? null,
51 mergedAt: summary.mergedAt ?? null,
52 ...(summary.author === undefined ? {} : { author: summary.author }),
53 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
54 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
55 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
56 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
57 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
58 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
59 };
60}
61
62function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
63 return (
64 left.state === right.state &&
65 left.title === right.title &&
66 left.headBranch === right.headBranch &&
67 left.baseBranch === right.baseBranch &&
68 left.isDraft === right.isDraft &&
69 left.updatedAt === right.updatedAt &&
70 (left.closedAt ?? null) === (right.closedAt ?? null) &&
71 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
72 (left.author?.login ?? null) === (right.author?.login ?? null) &&
73 (left.author?.avatarUrl ?? null) === (right.author?.avatarUrl ?? null) &&
74 left.additions === right.additions &&
75 left.deletions === right.deletions &&
76 left.changedFiles === right.changedFiles &&
77 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
78 (left.checksState ?? null) === (right.checksState ?? null) &&
79 left.mergeability === right.mergeability
80 );
81}
82
83function stacksEqual(
84 left: ThreadPullRequestStack | null,
85 right: ThreadPullRequestStack | null,
86): boolean {
87 if (left === null || right === null) return left === right;
88 return (
89 left.kind === right.kind &&
90 left.id === right.id &&
91 left.number === right.number &&
92 left.url === right.url &&
93 left.base === right.base &&
94 left.layers.length === right.layers.length &&
95 left.layers.every((layer, index) => {
96 const other = right.layers[index]!;
97 return (
98 layer.number === other.number &&
99 layer.headBranch === other.headBranch &&
100 layer.state === other.state
101 );
102 })
103 );
104}
105
106function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
107 return thread.settledOverride !== "settled" && thread.settledAt === null;
108}
109
110/**
111 * Keeps every thread ↔ pull request link's host snapshot current. One sweep a minute reads
112 * only the active threads that have links, groups visible links by pull request so the host
113 * is asked once per PR no matter how many threads share it, and writes back only what
114 * changed. Native stacks the host reports are auto-linked to the thread as `source: "stack"`.
115 */
116export class PullRequestSyncReactor extends Context.Service<
117 PullRequestSyncReactor,
118 {
119 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
120 readonly drain: Effect.Effect<void>;
121 /** Force the next sweep to re-read this pull request, even when its snapshot is terminal. */
122 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
123 }
124>()("t3/orchestration-v2/PullRequestSyncReactor") {}
125
126/** @public Service construction is part of the canonical Effect module API. */
127export const make = Effect.gen(function* () {
128 const engine = yield* Orchestrator.OrchestratorV2;
129 const projections = yield* ProjectionStore.ProjectionStoreV2;
130 const pullRequests = yield* PullRequestService.PullRequestService;
131 const crypto = yield* Crypto.Crypto;
132
133 const lastSyncedAt = new Map<string, number>();
134 const requested = new Map<string, number>();
135 let requestGeneration = 0;
136 // Requested keys wait in `requested` for one queued sweep, so a burst of links (an agent
137 // linking dozens of pull requests) is read together and shares the summary batches.
138 let requestedSweepQueued = false;
139 const retryStacks = new Set<string>();
140
141 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
142 if (requested.has(key) || retryStacks.has(key)) return true;
143 if (entries.some((entry) => entry.link.snapshot === null)) return true;
144 if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
145 if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
146 return true;
147 // Closed requests can reopen on the host, including after the thread settles.
148 const last = lastSyncedAt.get(key);
149 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
150 };
151
152 const logSkipped =
153 (message: string, fields: Record<string, unknown>) =>
154 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
155 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
156
157 /** `requested` reads only keys asked for through `requestSync`; `all` is the periodic pass. */
158 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
159 const threads = yield* projections.getThreadsWithPullRequests();
160 const now = yield* DateTime.now;
161 const nowMs = DateTime.toEpochMillis(now);
162 const nowIso = DateTime.formatIso(now);
163
164 const groups = new Map<string, Array<LinkEntry>>();
165 for (const thread of threads) {
166 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
167 const key = threadPullRequestKeyOf(link);
168 const entries = groups.get(key) ?? [];
169 entries.push({ thread, link });
170 groups.set(key, entries);
171 }
172 }
173
174 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
175 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
176 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
177
178 // Layers auto-linked this sweep, so two links of one thread that share a
179 // stack do not both try to add the same sibling.
180 const linkedThisSweep = new Set<string>();
181 const persistence = yield* Semaphore.make(1);
182
183 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
184 entry: LinkEntry,
185 fields: SnapshotFields,
186 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
187 ) {
188 const { thread, link } = entry;
189 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
190 const changed =
191 link.snapshot === null ||
192 !snapshotFieldsEqual(link.snapshot, fields) ||
193 !stacksEqual(link.stack, nextStack);
194 // Persist discovered siblings before a terminal snapshot can trigger settlement.
195 for (const layer of fetchedStack?.stack?.layers ?? []) {
196 const layerKey = {
197 host: normalizeThreadPullRequestKey(link).host,
198 repository: link.repository,
199 number: layer.number,
200 };
201 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
202 if (linkedThisSweep.has(dedupeKey)) continue;
203 // Tombstones count as present: a dismissed layer is never re-added.
204 if (
205 (thread.pullRequests ?? []).some((existing) =>
206 threadPullRequestKeysEqual(existing, layerKey),
207 )
208 ) {
209 continue;
210 }
211 const url = siblingPullRequestUrl(link.url, layer.number);
212 if (url === null) continue;
213 const uuid = yield* crypto.randomUUIDv4;
214 yield* engine.dispatch({
215 type: "thread.pull-request.link",
216 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
217 threadId: thread.id,
218 ...layerKey,
219 url,
220 source: "stack",
221 });
222 linkedThisSweep.add(dedupeKey);
223 }
224 if (changed) {
225 const uuid = yield* crypto.randomUUIDv4;
226 yield* engine.dispatch({
227 type: "thread.pull-request-link.sync",
228 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
229 threadId: thread.id,
230 host: normalizeThreadPullRequestKey(link).host,
231 repository: link.repository,
232 number: link.number,
233 snapshot: { ...fields, syncedAt: nowIso },
234 stack: nextStack,
235 });
236 }
237 });
238
239 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
240 key: string,
241 entries: ReadonlyArray<LinkEntry>,
242 ) {
243 const first = entries[0]!;
244 const ref = {
245 projectId: first.thread.projectId,
246 host: normalizeThreadPullRequestKey(first.link).host,
247 repository: first.link.repository,
248 number: first.link.number,
249 };
250 const generation = requested.get(key);
251 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
252 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
253 const fields = snapshotFieldsOf(summary);
254 const needsStack =
255 generation !== undefined ||
256 retryStacks.has(key) ||
257 entries.some(
258 (entry) =>
259 entry.link.snapshot === null ||
260 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
261 (summary.stack !== undefined &&
262 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
263 );
264 // A summary that says the pull request is in no stack, for links that hold none, already
265 // answers what the stack read would.
266 const knownUnstacked =
267 summary.stack === null && entries.every((entry) => entry.link.stack === null);
268 const fetchedStack = !needsStack
269 ? null
270 : knownUnstacked
271 ? { stack: null }
272 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
273 Effect.map((stack) => ({
274 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
275 })),
276 Effect.catchCauseIf(
277 (cause) => !Cause.hasInterruptsOnly(cause),
278 () =>
279 Effect.logWarning("pull request stack lookup failed", {
280 key,
281 }).pipe(Effect.as(null)),
282 ),
283 );
284 if (needsStack) {
285 if (fetchedStack === null) {
286 retryStacks.add(key);
287 return;
288 }
289 retryStacks.delete(key);
290 }
291 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
292 lastSyncedAt.set(key, nowMs);
293 // A refresh requested while the host read was in flight belongs to the next sweep.
294 if (requested.get(key) === generation) requested.delete(key);
295 yield* Effect.forEach(
296 entries,
297 (entry) =>
298 syncEntry(entry, fields, fetchedStack).pipe(
299 persistence.withPermits(1),
300 Effect.catchCause((cause) => {
301 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
302 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
303 cause,
304 );
305 }),
306 ),
307 { discard: true },
308 );
309 });
310
311 yield* Effect.forEach(
312 groups,
313 ([key, entries]) =>
314 (scope === "all" || requested.has(key)) && isDue(key, entries, nowMs)
315 ? syncGroup(key, entries).pipe(
316 Effect.catchCause(logSkipped("pull request sync skipped", { key })),
317 )
318 : Effect.void,
319 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
320 // GitHub answers them in one request rather than one `gh pr view` apiece.
321 { concurrency: 25, discard: true },
322 );
323 });
324
325 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
326 Effect.suspend(() => {
327 // Requests from here on queue another sweep; the ones already recorded are read by this.
328 if (scope === "requested") requestedSweepQueued = false;
329 return sweep(scope);
330 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
331 );
332
333 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
334 "PullRequestSyncReactor.start",
335 )(function* () {
336 const events = engine.streamDomainEvents;
337 yield* forkParked(
338 Stream.runForEach(events, (event) =>
339 event.type === "thread.pull-request-synced"
340 ? Effect.forEach(
341 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
342 (link) => link.snapshot === null,
343 ),
344 requestSync,
345 { discard: true },
346 )
347 : Effect.void,
348 ).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
349 );
350 yield* forkParked(
351 Effect.gen(function* () {
352 yield* worker.enqueue("all");
353 yield* worker.drain;
354 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
355 );
356 });
357
358 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
359 Effect.suspend(() => {
360 requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
361 if (requestedSweepQueued) return Effect.void;
362 requestedSweepQueued = true;
363 return worker.enqueue("requested");
364 });
365
366 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
367});
368
369export const layer = Layer.effect(PullRequestSyncReactor, make);