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