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

PullRequestSyncReactor.ts

328 lines12.7 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 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";
25​
26import * as PullRequestService from "../pullRequest/PullRequestService.ts";
27import { forkParked } from "../serverActivation.ts";
28import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
29import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
30​
31const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
32​
33type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
34​
35interface LinkEntry {
36 readonly thread: OrchestrationThreadShell;
37 readonly link: ThreadPullRequestLink;
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 };
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 );
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 );
103​
104function isUnsettled(thread: OrchestrationThreadShell): boolean {
105 return thread.settledOverride !== "settled" && thread.settledAt === null;
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* OrchestrationEngine.OrchestrationEngineService;
127 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
128 const pullRequests = yield* PullRequestService.PullRequestService;
129 const crypto = yield* Crypto.Crypto;
130​
131 const lastSyncedAt = new Map<string, number>();
132 const requested = new Map<string, number>();
133 let requestGeneration = 0;
134 const retryStacks = new Set<string>();
135​
136 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
137 if (requested.has(key) || retryStacks.has(key)) return true;
138 if (entries.some((entry) => entry.link.snapshot === null)) return true;
139 if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;
140 if (entries.some((entry) => entry.link.snapshot?.state === "open" && isUnsettled(entry.thread)))
141 return true;
142 // Closed requests can reopen on the host, including after the thread settles.
143 const last = lastSyncedAt.get(key);
144 return last === undefined || nowMs - last >= SLOW_SYNC_INTERVAL_MS;
145 };
146​
147 const logSkipped =
148 (message: string, fields: Record<string, unknown>) =>
149 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
150 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
151​
152 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* () {
153 const snapshot = yield* snapshots.getShellSnapshot();
154 const now = yield* DateTime.now;
155 const nowMs = DateTime.toEpochMillis(now);
156 const nowIso = DateTime.formatIso(now);
157​
158 const groups = new Map<string, Array<LinkEntry>>();
159 for (const thread of snapshot.threads) {
160 if (thread.archivedAt !== null) continue;
161 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
162 const key = threadPullRequestKeyOf(link);
163 const entries = groups.get(key) ?? [];
164 entries.push({ thread, link });
165 groups.set(key, entries);
166 }
167 }
168​
169 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
170 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
171 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
172​
173 // Layers auto-linked this sweep, so two links of one thread that share a
174 // stack do not both try to add the same sibling.
175 const linkedThisSweep = new Set<string>();
176​
177 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
178 entry: LinkEntry,
179 fields: SnapshotFields,
180 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
181 ) {
182 const { thread, link } = entry;
183 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
184 const changed =
185 link.snapshot === null ||
186 !snapshotFieldsEqual(link.snapshot, fields) ||
187 !stacksEqual(link.stack, nextStack);
188 if (changed) {
189 const uuid = yield* crypto.randomUUIDv4;
190 yield* engine.dispatch({
191 type: "thread.pull-request-link.sync",
192 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
193 threadId: thread.id,
194 host: link.host,
195 repository: link.repository,
196 number: link.number,
197 snapshot: { ...fields, syncedAt: nowIso },
198 stack: nextStack,
199 });
200 }
201 if (fetchedStack === null || fetchedStack.stack === null) return;
202 for (const layer of fetchedStack.stack.layers) {
203 const layerKey = { host: link.host, repository: link.repository, number: layer.number };
204 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
205 if (linkedThisSweep.has(dedupeKey)) continue;
206 // Tombstones count as present: a dismissed layer is never re-added.
207 if (
208 thread.pullRequests.some((existing) => threadPullRequestKeysEqual(existing, layerKey))
209 ) {
210 continue;
211 }
212 const url = siblingPullRequestUrl(link.url, layer.number);
213 if (url === null) continue;
214 linkedThisSweep.add(dedupeKey);
215 const uuid = yield* crypto.randomUUIDv4;
216 yield* engine
217 .dispatch({
218 type: "thread.pull-request.link",
219 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
220 threadId: thread.id,
221 ...layerKey,
222 url,
223 source: "stack",
224 })
225 .pipe(
226 Effect.catchCause(
227 logSkipped("pull request stack layer link skipped", {
228 threadId: thread.id,
229 number: layer.number,
230 }),
231 ),
232 );
233 }
234 });
235​
236 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
237 key: string,
238 entries: ReadonlyArray<LinkEntry>,
239 ) {
240 const first = entries[0]!;
241 const ref = {
242 projectId: first.thread.projectId,
243 host: first.link.host,
244 repository: first.link.repository,
245 number: first.link.number,
246 };
247 const generation = requested.get(key);
248 if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });
249 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
250 const fields = snapshotFieldsOf(summary);
251 const needsStack =
252 generation !== undefined ||
253 retryStacks.has(key) ||
254 entries.some(
255 (entry) =>
256 entry.link.snapshot === null || !snapshotFieldsEqual(entry.link.snapshot, fields),
257 );
258 const fetchedStack = needsStack
259 ? yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
260 Effect.map((stack) => ({
261 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
262 })),
263 Effect.catchCause((cause) =>
264 Cause.hasInterruptsOnly(cause)
265 ? Effect.failCause(cause)
266 : Effect.logWarning("pull request stack lookup failed", {
267 key,
268 }).pipe(Effect.as(null)),
269 ),
270 )
271 : null;
272 if (needsStack) {
273 if (fetchedStack === null) retryStacks.add(key);
274 else 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 Effect.catchCause(
285 logSkipped("pull request sync skipped", { threadId: entry.thread.id, key }),
286 ),
287 ),
288 { discard: true },
289 );
290 });
291​
292 yield* Effect.forEach(
293 groups,
294 ([key, entries]) =>
295 isDue(key, entries, nowMs)
296 ? syncGroup(key, entries).pipe(
297 Effect.catchCause(logSkipped("pull request sync skipped", { key })),
298 )
299 : Effect.void,
300 { concurrency: 8, discard: true },
301 );
302 });
303​
304 const worker = yield* makeDrainableWorker(() =>
305 sweep().pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
306 );
307​
308 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
309 "PullRequestSyncReactor.start",
310 )(function* () {
311 yield* forkParked(
312 Effect.gen(function* () {
313 yield* worker.enqueue(undefined);
314 yield* worker.drain;
315 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
316 );
317 });
318​
319 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
320 Effect.suspend(() => {
321 requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
322 return worker.enqueue(undefined);
323 });
324​
325 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
326});
327​
328export const layer = Layer.effect(PullRequestSyncReactor, make);