Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestSyncReactor.ts

333 lines12.9 KB

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";
26​
27import * as PullRequestService from "../pullRequest/PullRequestService.ts";
28import { forkParked } from "../serverActivation.ts";
29import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
30import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
31​
32const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
33​
34type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
35​
36interface LinkEntry {
37 readonly thread: OrchestrationThreadShell;
38 readonly link: ThreadPullRequestLink;
40​
41function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
42 return {
43 state: summary.state,
44 title: summary.title,
45 headBranch: summary.headBranch,
46 baseBranch: summary.baseBranch,
47 isDraft: summary.isDraft ?? false,
48 updatedAt: summary.updatedAt,
49 closedAt: summary.closedAt ?? null,
50 mergedAt: summary.mergedAt ?? null,
51 ...(summary.author === undefined ? {} : { author: summary.author }),
52 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
53 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
54 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
55 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
56 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
57 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
58 };
60​
61function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
62 return (
63 left.state === right.state &&
64 left.title === right.title &&
65 left.headBranch === right.headBranch &&
66 left.baseBranch === right.baseBranch &&
67 left.isDraft === right.isDraft &&
68 left.updatedAt === right.updatedAt &&
69 (left.closedAt ?? null) === (right.closedAt ?? null) &&
70 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
71 (left.author?.login ?? null) === (right.author?.login ?? null) &&
72 (left.author?.avatarUrl ?? null) === (right.author?.avatarUrl ?? null) &&
73 left.additions === right.additions &&
74 left.deletions === right.deletions &&
75 left.changedFiles === right.changedFiles &&
76 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
77 (left.checksState ?? null) === (right.checksState ?? null) &&
78 left.mergeability === right.mergeability
79 );
81​
82function stacksEqual(
83 left: ThreadPullRequestStack | null,
84 right: ThreadPullRequestStack | null,
85): boolean {
86 if (left === null || right === null) return left === right;
87 return (
88 left.kind === right.kind &&
89 left.id === right.id &&
90 left.number === right.number &&
91 left.url === right.url &&
92 left.base === right.base &&
93 left.layers.length === right.layers.length &&
94 left.layers.every((layer, index) => {
95 const other = right.layers[index]!;
96 return (
97 layer.number === other.number &&
98 layer.headBranch === other.headBranch &&
99 layer.state === other.state
100 );
101 })
102 );
104​
105function isUnsettled(thread: OrchestrationThreadShell): boolean {
106 return thread.settledOverride !== "settled" && thread.settledAt === null;
108​
109/**
110 * Keeps every thread ↔ pull request link's host snapshot current. One sweep a minute reads
111 * the shell snapshot, groups visible links by pull request so the host is asked once per PR
112 * no matter how many threads share it, and writes back only what changed. Native stacks the
113 * host reports are auto-linked to the thread as `source: "stack"`.
114 */
115export class PullRequestSyncReactor extends Context.Service<
116 PullRequestSyncReactor,
117 {
118 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
119 readonly drain: Effect.Effect<void>;
120 /** Force the next sweep to re-read this pull request, even when its snapshot is terminal. */
121 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
122 }
123>()("t3/orchestration/PullRequestSyncReactor") {}
124​
125/** @public Service construction is part of the canonical Effect module API. */
126export const make = Effect.gen(function* () {
127 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
128 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
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* () {
154 const snapshot = yield* snapshots.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​
178 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
179 entry: LinkEntry,
180 fields: SnapshotFields,
181 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
182 ) {
183 const { thread, link } = entry;
184 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
185 const changed =
186 link.snapshot === null ||
187 !snapshotFieldsEqual(link.snapshot, fields) ||
188 !stacksEqual(link.stack, nextStack);
189 if (changed) {
190 const uuid = yield* crypto.randomUUIDv4;
191 yield* engine.dispatch({
192 type: "thread.pull-request-link.sync",
193 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
194 threadId: thread.id,
195 host: normalizeThreadPullRequestKey(link).host,
196 repository: link.repository,
197 number: link.number,
198 snapshot: { ...fields, syncedAt: nowIso },
199 stack: nextStack,
200 });
201 }
202 if (fetchedStack === null || fetchedStack.stack === null) return;
203 for (const layer of fetchedStack.stack.layers) {
204 const layerKey = {
205 host: normalizeThreadPullRequestKey(link).host,
206 repository: link.repository,
207 number: layer.number,
208 };
209 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
210 if (linkedThisSweep.has(dedupeKey)) continue;
211 // Tombstones count as present: a dismissed layer is never re-added.
212 if (
213 thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, layerKey))
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);