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 OrchestrationEngine from "./Services/OrchestrationEngine.ts";
31import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
32
33const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
34
35type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
36
37interface LinkEntry {
38 readonly thread: ProjectionSnapshotQuery.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: ProjectionSnapshotQuery.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/PullRequestSyncReactor") {}
125
126/** @public Service construction is part of the canonical Effect module API. */
127export const make = Effect.gen(function* () {
128 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
129 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
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 const retryStacks = new Set<string>();
137
138 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
139 if (requested.has(key) || retryStacks.has(key)) return true;
140 if (entries.some((entry) => entry.link.snapshot === null)) return true;
141 if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
142 if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
143 return true;
144 // Closed requests can reopen on the host, including after the thread settles.
145 const last = lastSyncedAt.get(key);
146 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
147 };
148
149 const logSkipped =
150 (message: string, fields: Record<string, unknown>) =>
151 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
152 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
153
154 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
155 const threads = yield* snapshots.listThreadsWithPullRequests();
156 const now = yield* DateTime.now;
157 const nowMs = DateTime.toEpochMillis(now);
158 const nowIso = DateTime.formatIso(now);
159
160 const groups = new Map<string, Array<LinkEntry>>();
161 for (const thread of threads) {
162 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
163 const key = threadPullRequestKeyOf(link);
164 const entries = groups.get(key) ?? [];
165 entries.push({ thread, link });
166 groups.set(key, entries);
167 }
168 }
169
170 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
171 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
172 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
173
174 // Layers auto-linked this sweep, so two links of one thread that share a
175 // stack do not both try to add the same sibling.
176 const linkedThisSweep = new Set<string>();
177 const persistence = yield* Semaphore.make(1);
178
179 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
180 entry: LinkEntry,
181 fields: SnapshotFields,
182 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
183 ) {
184 const { thread, link } = entry;
185 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
186 const changed =
187 link.snapshot === null ||
188 !snapshotFieldsEqual(link.snapshot, fields) ||
189 !stacksEqual(link.stack, nextStack);
190 // Persist discovered siblings before a terminal snapshot can trigger settlement.
191 for (const layer of fetchedStack?.stack?.layers ?? []) {
192 const layerKey = {
193 host: normalizeThreadPullRequestKey(link).host,
194 repository: link.repository,
195 number: layer.number,
196 };
197 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
198 if (linkedThisSweep.has(dedupeKey)) continue;
199 // Tombstones count as present: a dismissed layer is never re-added.
200 if (
201 thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, layerKey))
202 ) {
203 continue;
204 }
205 const url = siblingPullRequestUrl(link.url, layer.number);
206 if (url === null) continue;
207 const uuid = yield* crypto.randomUUIDv4;
208 yield* engine.dispatch({
209 type: "thread.pull-request.link",
210 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
211 threadId: thread.id,
212 ...layerKey,
213 url,
214 source: "stack",
215 });
216 linkedThisSweep.add(dedupeKey);
217 }
218 if (changed) {
219 const uuid = yield* crypto.randomUUIDv4;
220 yield* engine.dispatch({
221 type: "thread.pull-request-link.sync",
222 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
223 threadId: thread.id,
224 host: normalizeThreadPullRequestKey(link).host,
225 repository: link.repository,
226 number: link.number,
227 snapshot: { ...fields, syncedAt: nowIso },
228 stack: nextStack,
229 });
230 }
231 });
232
233 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
234 key: string,
235 entries: ReadonlyArray<LinkEntry>,
236 ) {
237 const first = entries[0]!;
238 const ref = {
239 projectId: first.thread.projectId,
240 host: normalizeThreadPullRequestKey(first.link).host,
241 repository: first.link.repository,
242 number: first.link.number,
243 };
244 const generation = requested.get(key);
245 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
246 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
247 const fields = snapshotFieldsOf(summary);
248 const needsStack =
249 generation !== undefined ||
250 retryStacks.has(key) ||
251 entries.some(
252 (entry) =>
253 entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
254 );
255 const fetchedStack = needsStack
256 ? yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
257 Effect.map((stack) => ({
258 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
259 })),
260 Effect.catchCauseIf(
261 (cause) => !Cause.hasInterruptsOnly(cause),
262 () =>
263 Effect.logWarning("pull request stack lookup failed", {
264 key,
265 }).pipe(Effect.as(null)),
266 ),
267 )
268 : null;
269 if (needsStack) {
270 if (fetchedStack === null) {
271 retryStacks.add(key);
272 return;
273 }
274 retryStacks.delete(key);
275 }
276 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
277 lastSyncedAt.set(key, nowMs);
278 // A refresh requested while the host read was in flight belongs to the next sweep.
279 if (requested.get(key) === generation) requested.delete(key);
280 yield* Effect.forEach(
281 entries,
282 (entry) =>
283 syncEntry(entry, fields, fetchedStack).pipe(
284 persistence.withPermits(1),
285 Effect.catchCause((cause) => {
286 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
287 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
288 cause,
289 );
290 }),
291 ),
292 { discard: true },
293 );
294 });
295
296 yield* Effect.forEach(
297 groups,
298 ([key, entries]) =>
299 (requestedKey === undefined || requestedKey === key) && isDue(key, entries, nowMs)
300 ? syncGroup(key, entries).pipe(
301 Effect.catchCause(logSkipped("pull request sync skipped", { key })),
302 )
303 : Effect.void,
304 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
305 // GitHub answers them in one request rather than one `gh pr view` apiece.
306 { concurrency: 25, discard: true },
307 );
308 });
309
310 const worker = yield* makeDrainableWorker((key: string | undefined) =>
311 sweep(key).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
312 );
313
314 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
315 "PullRequestSyncReactor.start",
316 )(function* () {
317 const events = yield* engine.subscribeDomainEvents;
318 yield* forkParked(
319 Stream.runForEach(events, (event) =>
320 event.type === "thread.pull-request-linked" ? requestSync(event.payload.link) : Effect.void,
321 ),
322 );
323 yield* forkParked(
324 Effect.gen(function* () {
325 yield* worker.enqueue(undefined);
326 yield* worker.drain;
327 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
328 );
329 });
330
331 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
332 Effect.suspend(() => {
333 const syncKey = threadPullRequestKeyOf(key);
334 requested.set(syncKey, ++requestGeneration);
335 return worker.enqueue(syncKey);
336 });
337
338 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
339});
340
341export const layer = Layer.effect(PullRequestSyncReactor, make);