Open History to see the last commit
1import { siblingPullRequestUrl } from "@t3tools/shared/changeRequestUrl";
2import {
3 CommandId,
4 type OrchestrationThreadShell,
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 * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
32import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
33
34const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
35
36type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
37
38interface LinkEntry {
39 readonly thread: OrchestrationThreadShell;
40 readonly link: ThreadPullRequestLink;
41}
42
43function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
44 return {
45 state: summary.state,
46 title: summary.title,
47 headBranch: summary.headBranch,
48 baseBranch: summary.baseBranch,
49 isDraft: summary.isDraft ?? false,
50 updatedAt: summary.updatedAt,
51 closedAt: summary.closedAt ?? null,
52 mergedAt: summary.mergedAt ?? null,
53 ...(summary.author === undefined ? {} : { author: summary.author }),
54 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
55 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
56 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
57 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
58 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
59 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
60 };
61}
62
63function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
64 return (
65 left.state === right.state &&
66 left.title === right.title &&
67 left.headBranch === right.headBranch &&
68 left.baseBranch === right.baseBranch &&
69 left.isDraft === right.isDraft &&
70 left.updatedAt === right.updatedAt &&
71 (left.closedAt ?? null) === (right.closedAt ?? null) &&
72 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
73 (left.author?.login ?? null) === (right.author?.login ?? null) &&
74 (left.author?.avatarUrl ?? null) === (right.author?.avatarUrl ?? null) &&
75 left.additions === right.additions &&
76 left.deletions === right.deletions &&
77 left.changedFiles === right.changedFiles &&
78 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
79 (left.checksState ?? null) === (right.checksState ?? null) &&
80 left.mergeability === right.mergeability
81 );
82}
83
84function stacksEqual(
85 left: ThreadPullRequestStack | null,
86 right: ThreadPullRequestStack | null,
87): boolean {
88 if (left === null || right === null) return left === right;
89 return (
90 left.kind === right.kind &&
91 left.id === right.id &&
92 left.number === right.number &&
93 left.url === right.url &&
94 left.base === right.base &&
95 left.layers.length === right.layers.length &&
96 left.layers.every((layer, index) => {
97 const other = right.layers[index]!;
98 return (
99 layer.number === other.number &&
100 layer.headBranch === other.headBranch &&
101 layer.state === other.state
102 );
103 })
104 );
105}
106
107function isUnsettled(thread: OrchestrationThreadShell): boolean {
108 return thread.settledOverride !== "settled" && thread.settledAt === null;
109}
110
111/**
112 * Keeps every thread ↔ pull request link's host snapshot current. One sweep a minute reads
113 * the shell snapshot, groups visible links by pull request so the host is asked once per PR
114 * no matter how many threads share it, and writes back only what changed. Native stacks the
115 * host reports are auto-linked to the thread as `source: "stack"`.
116 */
117export class PullRequestSyncReactor extends Context.Service<
118 PullRequestSyncReactor,
119 {
120 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
121 readonly drain: Effect.Effect<void>;
122 /** Force the next sweep to re-read this pull request, even when its snapshot is terminal. */
123 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
124 }
125>()("t3/orchestration/PullRequestSyncReactor") {}
126
127/** @public Service construction is part of the canonical Effect module API. */
128export const make = Effect.gen(function* () {
129 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
130 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
131 const pullRequests = yield* PullRequestService.PullRequestService;
132 const crypto = yield* Crypto.Crypto;
133
134 const lastSyncedAt = new Map<string, number>();
135 const requested = new Map<string, number>();
136 let requestGeneration = 0;
137 const retryStacks = new Set<string>();
138
139 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
140 if (requested.has(key) || retryStacks.has(key)) return true;
141 if (entries.some((entry) => entry.link.snapshot === null)) return true;
142 if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
143 if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
144 return true;
145 // Closed requests can reopen on the host, including after the thread settles.
146 const last = lastSyncedAt.get(key);
147 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
148 };
149
150 const logSkipped =
151 (message: string, fields: Record<string, unknown>) =>
152 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
153 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
154
155 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
156 const snapshot = yield* snapshots.getShellSnapshot();
157 const now = yield* DateTime.now;
158 const nowMs = DateTime.toEpochMillis(now);
159 const nowIso = DateTime.formatIso(now);
160
161 const groups = new Map<string, Array<LinkEntry>>();
162 for (const thread of snapshot.threads) {
163 if (thread.archivedAt !== null) continue;
164 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
165 const key = threadPullRequestKeyOf(link);
166 const entries = groups.get(key) ?? [];
167 entries.push({ thread, link });
168 groups.set(key, entries);
169 }
170 }
171
172 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
173 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
174 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
175
176 // Layers auto-linked this sweep, so two links of one thread that share a
177 // stack do not both try to add the same sibling.
178 const linkedThisSweep = new Set<string>();
179 const persistence = yield* Semaphore.make(1);
180
181 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
182 entry: LinkEntry,
183 fields: SnapshotFields,
184 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
185 ) {
186 const { thread, link } = entry;
187 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
188 const changed =
189 link.snapshot === null ||
190 !snapshotFieldsEqual(link.snapshot, fields) ||
191 !stacksEqual(link.stack, nextStack);
192 // Persist discovered siblings before a terminal snapshot can trigger settlement.
193 for (const layer of fetchedStack?.stack?.layers ?? []) {
194 const layerKey = {
195 host: normalizeThreadPullRequestKey(link).host,
196 repository: link.repository,
197 number: layer.number,
198 };
199 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
200 if (linkedThisSweep.has(dedupeKey)) continue;
201 // Tombstones count as present: a dismissed layer is never re-added.
202 if (
203 thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, layerKey))
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 = 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);