Open History to see the last commit
1import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
2import {
3 CommandId,
4 type OrchestrationV2ThreadShell,
5 type PullRequestSummary,
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 Context from "effect/Context";
20import * as Crypto from "effect/Crypto";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import * as Schedule from "effect/Schedule";
25import type * as Scope from "effect/Scope";
26import * as Semaphore from "effect/Semaphore";
27import * as Stream from "effect/Stream";
28
29import * as PullRequestService from "../pullRequest/PullRequestService.ts";
30import { forkParked } from "../serverActivation.ts";
31import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts";
32
33const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
34
35type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
36
37interface LinkEntry {
38 readonly thread: OrchestrationV2ThreadShell;
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: OrchestrationV2ThreadShell): 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 * the shell snapshot, groups visible links by pull request so the host is asked once per PR
113 * no matter how many threads share it, and writes back only what changed. Native stacks the
114 * 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* OrchestratorV2;
129 const pullRequests = yield* PullRequestService.PullRequestService;
130 const crypto = yield* Crypto.Crypto;
131
132 const lastSyncedAt = new Map<string, number>();
133 const requested = new Map<string, number>();
134 let requestGeneration = 0;
135 const retryStacks = new Set<string>();
136
137 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
138 if (requested.has(key) || retryStacks.has(key)) return true;
139 if (entries.some((entry) => entry.link.snapshot === null)) return true;
140 if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
141 if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
142 return true;
143 // Closed requests can reopen on the host, including after the thread settles.
144 const last = lastSyncedAt.get(key);
145 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
146 };
147
148 const logSkipped =
149 (message: string, fields: Record<string, unknown>) =>
150 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
151 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
152
153 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
154 const snapshot = yield* engine.getShellSnapshot();
155 const now = yield* DateTime.now;
156 const nowMs = DateTime.toEpochMillis(now);
157 const nowIso = DateTime.formatIso(now);
158
159 const groups = new Map<string, Array<LinkEntry>>();
160 for (const thread of snapshot.threads) {
161 if (thread.archivedAt !== null) continue;
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) =>
202 threadPullRequestKeysEqual(existing, layerKey),
203 )
204 ) {
205 continue;
206 }
207 const url = siblingPullRequestUrl(link.url, layer.number);
208 if (url === null) continue;
209 const uuid = yield* crypto.randomUUIDv4;
210 yield* engine.dispatch({
211 type: "thread.pull-request.link",
212 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
213 threadId: thread.id,
214 ...layerKey,
215 url,
216 source: "stack",
217 });
218 linkedThisSweep.add(dedupeKey);
219 }
220 if (changed) {
221 const uuid = yield* crypto.randomUUIDv4;
222 yield* engine.dispatch({
223 type: "thread.pull-request-link.sync",
224 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
225 threadId: thread.id,
226 host: normalizeThreadPullRequestKey(link).host,
227 repository: link.repository,
228 number: link.number,
229 snapshot: { ...fields, syncedAt: nowIso },
230 stack: nextStack,
231 });
232 }
233 });
234
235 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
236 key: string,
237 entries: ReadonlyArray<LinkEntry>,
238 ) {
239 const first = entries[0]!;
240 const ref = {
241 projectId: first.thread.projectId,
242 host: normalizeThreadPullRequestKey(first.link).host,
243 repository: first.link.repository,
244 number: first.link.number,
245 };
246 const generation = requested.get(key);
247 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
248 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
249 const fields = snapshotFieldsOf(summary);
250 const needsStack =
251 generation !== undefined ||
252 retryStacks.has(key) ||
253 entries.some(
254 (entry) =>
255 entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
256 );
257 const fetchedStack = needsStack
258 ? yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
259 Effect.map((stack) => ({
260 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
261 })),
262 Effect.catchCause((cause) =>
263 Cause.hasInterruptsOnly(cause)
264 ? Effect.failCause(cause)
265 : Effect.logWarning("pull request stack lookup failed", {
266 key,
267 }).pipe(Effect.as(null)),
268 ),
269 )
270 : null;
271 if (needsStack) {
272 if (fetchedStack === null) {
273 retryStacks.add(key);
274 return;
275 }
276 retryStacks.delete(key);
277 }
278 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
279 lastSyncedAt.set(key, nowMs);
280 // A refresh requested while the host read was in flight belongs to the next sweep.
281 if (requested.get(key) === generation) requested.delete(key);
282 yield* Effect.forEach(
283 entries,
284 (entry) =>
285 syncEntry(entry, fields, fetchedStack).pipe(
286 persistence.withPermits(1),
287 Effect.catchCause((cause) => {
288 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
289 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
290 cause,
291 );
292 }),
293 ),
294 { discard: true },
295 );
296 });
297
298 yield* Effect.forEach(
299 groups,
300 ([key, entries]) =>
301 (requestedKey === undefined || requestedKey === key) && isDue(key, entries, nowMs)
302 ? syncGroup(key, entries).pipe(
303 Effect.catchCause(logSkipped("pull request sync skipped", { key })),
304 )
305 : Effect.void,
306 { concurrency: 8, 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 = engine.streamDomainEvents;
318 yield* forkParked(
319 Stream.runForEach(events, (event) =>
320 event.type === "thread.pull-request-synced"
321 ? Effect.forEach(
322 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
323 (link) => link.snapshot === null,
324 ),
325 requestSync,
326 { discard: true },
327 )
328 : Effect.void,
329 ).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
330 );
331 yield* forkParked(
332 Effect.gen(function* () {
333 yield* worker.enqueue(undefined);
334 yield* worker.drain;
335 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
336 );
337 });
338
339 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
340 Effect.suspend(() => {
341 const syncKey = threadPullRequestKeyOf(key);
342 requested.set(syncKey, ++requestGeneration);
343 return worker.enqueue(syncKey);
344 });
345
346 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
347});
348
349export const layer = Layer.effect(PullRequestSyncReactor, make);