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

PullRequestWatchReactor.ts

578 lines20.4 KB

1import {
2 CommandId,
3 MessageId,
4 type OrchestrationV2Notification,
5 type PullRequestActivity,
6 type PullRequestComment,
7 type PullRequestRef,
8 type PullRequestThreadCommentsResult,
9 type ThreadPullRequestLink,
10 type ThreadPullRequestWatch,
11} from "@t3tools/contracts";
12import {
13 normalizeThreadPullRequestKey,
14 threadPullRequestKeyOf,
15 visibleThreadPullRequests,
16} from "@t3tools/shared/threadPullRequests";
17import * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as Crypto from "effect/Crypto";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Schedule from "effect/Schedule";
26import * as Schema from "effect/Schema";
27import type * as Scope from "effect/Scope";
28​
29import {
30 type ProviderChangeRequestWatchFingerprint,
31 PullRequestProviderError,
32} from "@t3tools/source-control-core/server/PullRequestProvider";
33import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34import { forkParked } from "../serverActivation.ts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ProjectionStore from "./ProjectionStore.ts";
37import { evaluatePullRequestWatch, pullRequestWatchMessage } from "./pullRequestWatch.ts";
38​
39/**
40 * Checks take minutes, so a faster pass mostly spends the host's rate limit,
41 * which every machine on the same account shares.
42 */
43const SWEEP_MINUTES = 2;
44const READ_FAILURE_LIMIT = 8;
45/**
46 * Without a host fingerprint, a pull request with nothing in flight is read again only when its
47 * sync snapshot moves, or after this long, for news the snapshot cannot show, such as a bot
48 * editing its review.
49 */
50const QUIET_REREAD_MS = 10 * 60_000;
51/**
52 * With a host fingerprint, how long until the activity is read again anyway: the fingerprint
53 * does not see edits to comments inside review threads.
54 */
55const FINGERPRINT_REREAD_MS = 30 * 60_000;
56​
57const isProviderError = Schema.is(PullRequestProviderError);
58​
59const isRateLimited = (cause: Cause.Cause<PullRequestService.PullRequestError>) =>
60 Option.match(Cause.findErrorOption(cause), {
61 onNone: () => false,
62 onSome: (error) =>
63 error._tag === "PullRequestOperationError" &&
64 isProviderError(error.cause) &&
65 error.cause.reason === "rate-limited",
66 });
67​
68const logFailure =
69 (message: string, fields: Record<string, unknown>) =>
70 <E>(cause: Cause.Cause<E>): Effect.Effect<void> =>
71 Cause.hasInterruptsOnly(cause)
72 ? Effect.interrupt
73 : Effect.logWarning(message, { ...fields, cause });
74​
75interface WatchTarget {
76 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
77 readonly link: ThreadPullRequestLink;
78 readonly watch: ThreadPullRequestWatch;
80​
81interface WatchGroup {
82 readonly key: string;
83 readonly targets: ReadonlyArray<WatchTarget>;
84 readonly fingerprint: string;
86​
87interface LastRead {
88 readonly at: number;
89 readonly fingerprint: string;
90 readonly inFlight: boolean;
91 readonly remarksComplete: boolean;
92 readonly watches: ReadonlySet<string>;
93 readonly status: string | null;
94 readonly remarks: string | null;
96​
97interface ReadPlan {
98 readonly detail: boolean;
99 readonly activity: boolean;
101​
102const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`;
103​
104type WatchEndReason =
105 | "merged"
106 | "closed"
107 | "unreadable"
108 | "comment-limit"
109 | "settled"
110 | "subagent"
111 | "stopped";
112​
113interface WatchLife {
114 readonly threadId: string;
115 readonly pullRequest: string;
116 readonly startedAt: number;
117 readonly headSha: string | null;
118 readonly pushedAt: number;
119 readonly longestQuietMs: number;
120 readonly wakes: number;
121 readonly reads: number;
123​
124const lifeKey = ({ thread, link, watch }: WatchTarget) =>
125 `${thread.id} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`;
126​
127const minutes = (ms: number) => Math.max(0, Math.round(ms / 60_000));
128​
129const snapshotFingerprint = ({ link }: WatchTarget) => {
130 const snapshot = link.snapshot;
131 return snapshot === null
132 ? ""
133 : [
134 snapshot.state,
135 snapshot.updatedAt,
136 snapshot.checksState,
137 snapshot.mergeability,
138 snapshot.reviewDecision,
139 snapshot.isDraft,
140 ].join(" ");
141};
142​
143function planRead(
144 group: WatchGroup,
145 last: LastRead | undefined,
146 fingerprint: ProviderChangeRequestWatchFingerprint | null,
147 now: number,
148): ReadPlan {
149 if (last === undefined || group.targets.some((target) => !last.watches.has(watchKey(target)))) {
150 return { detail: true, activity: true };
151 }
152 if (fingerprint === null) {
153 const read =
154 last.inFlight ||
155 !last.remarksComplete ||
156 last.fingerprint !== group.fingerprint ||
157 now - last.at >= QUIET_REREAD_MS;
158 return { detail: read, activity: read };
159 }
160 const activity =
161 last.remarks !== fingerprint.remarks ||
162 !last.remarksComplete ||
163 now - last.at >= FINGERPRINT_REREAD_MS;
164 return { detail: activity || last.status !== fingerprint.status || last.inFlight, activity };
166​
167function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean {
168 return (
169 left.startedAt === right.startedAt &&
170 left.headSha === right.headSha &&
171 left.failedChecks.join("\n") === right.failedChecks.join("\n") &&
172 left.passed === right.passed &&
173 left.passedChecks.join("\n") === right.passedChecks.join("\n") &&
174 left.remarksThrough === right.remarksThrough &&
175 left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
176 left.conflicting === right.conflicting &&
177 left.wakes === right.wakes
178 );
180​
181export class PullRequestWatchReactor extends Context.Service<
182 PullRequestWatchReactor,
183 {
184 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
185 readonly sweep: Effect.Effect<void>;
186 }
187>()("t3/orchestration-v2/PullRequestWatchReactor") {}
188​
189/** @public Service construction is part of the canonical Effect module API. */
190export const make = Effect.gen(function* () {
191 const engine = yield* Orchestrator.OrchestratorV2;
192 const projections = yield* ProjectionStore.ProjectionStoreV2;
193 const pullRequests = yield* PullRequestService.PullRequestService;
194 const crypto = yield* Crypto.Crypto;
195 const bootedAt = yield* Clock.currentTimeMillis;
196 const lives = new Map<string, WatchLife>();
197​
198 const lifeOf = (target: WatchTarget): WatchLife => {
199 const existing = lives.get(lifeKey(target));
200 if (existing !== undefined) return existing;
201 const startedAt = Date.parse(target.watch.startedAt);
202 const life: WatchLife = {
203 threadId: target.thread.id,
204 pullRequest: threadPullRequestKeyOf(target.link),
205 startedAt,
206 headSha: target.watch.headSha,
207 pushedAt: startedAt,
208 longestQuietMs: 0,
209 wakes: 0,
210 reads: 0,
211 };
212 lives.set(lifeKey(target), life);
213 return life;
214 };
215 const woke = (target: WatchTarget) =>
216 Effect.sync(() => {
217 const life = lifeOf(target);
218 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
219 });
220​
221 const reportEnd = (key: string, life: WatchLife, reason: WatchEndReason) =>
222 Effect.gen(function* () {
223 lives.delete(key);
224 const now = yield* Clock.currentTimeMillis;
225 const quietMs = now - life.pushedAt;
226 yield* Effect.logInfo("pull request watch ended", {
227 threadId: life.threadId,
228 pullRequest: life.pullRequest,
229 reason,
230 minutes: minutes(now - life.startedAt),
231 quietMinutes: minutes(quietMs),
232 longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
233 wakes: life.wakes,
234 reads: life.reads,
235 partial: life.startedAt < bootedAt,
236 });
237 });
238 const ended = (target: WatchTarget, reason: WatchEndReason) =>
239 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
240​
241 const readFailures = new Map<string, number>();
242 const lastReads = new Map<string, LastRead>();
243 const threadTails = new Map<
244 string,
245 Map<string, { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }>
246 >();
247​
248 const identityOf = (link: ThreadPullRequestLink) => ({
249 host: normalizeThreadPullRequestKey(link).host,
250 repository: link.repository,
251 number: link.number,
252 });
253​
254 /**
255 * The orchestrator applies this only while the same watch is on, so a stop or restart
256 * that lands during the host read wins.
257 */
258 const record = (
259 target: WatchTarget,
260 next: ThreadPullRequestWatch | null,
261 wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
262 ) =>
263 Effect.gen(function* () {
264 const uuid = yield* crypto.randomUUIDv4();
265 yield* engine.dispatch({
266 type: "thread.pull-request-watch.sync",
267 commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
268 threadId: target.thread.id,
269 ...identityOf(target.link),
270 startedAt: target.watch.startedAt,
271 watch: next,
272 ...(wake === undefined
273 ? {}
274 : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
275 });
276 });
277​
278 const giveUp = (target: WatchTarget) =>
279 record(target, null, {
280 text: `T3 Code stopped watching pull request #${target.link.number} (${target.link.url}) because it failed to read it from the host ${READ_FAILURE_LIMIT} times in a row. Check it yourself, and call watch_pull_request to watch it again.`,
281 notification: {
282 source: { kind: "monitor" },
283 outcome: "failed",
284 summary: `#${target.link.number}: stopped watching, could not read it`,
285 },
286 }).pipe(
287 Effect.tap(() => woke(target)),
288 Effect.catch(() => record(target, null)),
289 Effect.tap(() => ended(target, "unreadable")),
290 );
291​
292 const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
293 function* (key: string, reference: PullRequestRef, activity: PullRequestActivity) {
294 // Comment cursors cannot account for missing threads. Only finish a truncated read
295 // when the host confirms that every thread was listed.
296 if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
297​
298 let tails = threadTails.get(key);
299 if (tails === undefined) {
300 tails = new Map();
301 threadTails.set(key, tails);
302 }
303 const remarks = [...activity.comments];
304 for (const thread of activity.reviewThreads) {
305 let cursor = thread.nextCommentsCursor ?? null;
306 if (cursor === null) continue;
307 const count = thread.commentCount ?? 0;
308 let tail = tails.get(thread.id);
309 if (tail?.count !== count) {
310 const comments = new Map<string, PullRequestComment>();
311 const cursors = new Set<string>();
312 while (cursor !== null) {
313 if (cursors.has(cursor)) return null;
314 cursors.add(cursor);
315 const page: PullRequestThreadCommentsResult = yield* pullRequests.threadComments({
316 ...reference,
317 threadId: thread.id,
318 cursor,
319 });
320 for (const comment of page.comments) {
321 comments.set(comment.id, {
322 ...comment,
323 kind: "review-comment",
324 path: thread.path,
325 reviewState: null,
326 });
327 }
328 cursor = page.nextCursor;
329 }
330 if (thread.comments.length + comments.size < count) return null;
331 tail = { count, comments: [...comments.values()] };
332 tails.set(thread.id, tail);
333 }
334 remarks.push(...tail.comments);
335 }
336 return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
337 },
338 Effect.catch((error) =>
339 Effect.logWarning("pull request watch comment pagination failed", { error }).pipe(
340 Effect.as(null),
341 ),
342 ),
343 );
344​
345 const closed = (target: WatchTarget) =>
346 record(target, null, {
347 text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
348 notification: {
349 source: { kind: "monitor" },
350 outcome: "updated",
351 summary: `#${target.link.number}: closed, stopped watching`,
352 },
353 }).pipe(
354 Effect.tap(() => woke(target)),
355 Effect.tap(() => ended(target, "closed")),
356 );
357​
358 const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
359 link.snapshot?.state === "merged"
360 ? "merged"
361 : thread.settledOverride === "settled" || thread.settledAt !== null
362 ? "settled"
363 : thread.lineage.relationshipToParent === "subagent"
364 ? "subagent"
365 : undefined;
366​
367 const eachTarget = <E>(
368 group: WatchGroup,
369 step: (target: WatchTarget) => Effect.Effect<void, E>,
370 ) =>
371 Effect.forEach(group.targets, (target) =>
372 step(target).pipe(
373 Effect.as(true),
374 Effect.catchCause((cause) => {
375 lastReads.delete(group.key);
376 return logFailure("pull request watch update failed", {
377 threadId: target.thread.id,
378 pullRequest: group.key,
379 })(cause).pipe(Effect.as(false));
380 }),
381 ),
382 ).pipe(Effect.map((landed) => landed.every(Boolean)));
383​
384 const referenceOf = (group: WatchGroup) => {
385 const first = group.targets[0]!;
386 return { projectId: first.thread.projectId, ...identityOf(first.link) };
387 };
388​
389 const fingerprintOf = (group: WatchGroup) =>
390 pullRequests.watchFingerprint(referenceOf(group)).pipe(
391 Effect.catchCause(
392 (cause): Effect.Effect<ProviderChangeRequestWatchFingerprint | null | "paused"> =>
393 Cause.hasInterruptsOnly(cause)
394 ? Effect.interrupt
395 : isRateLimited(cause)
396 ? Effect.succeed("paused")
397 : Effect.logDebug("pull request watch fingerprint failed", {
398 pullRequest: group.key,
399 cause,
400 }).pipe(Effect.as(null)),
401 ),
402 );
403​
404 const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* (
405 group: WatchGroup,
406 fingerprint: ProviderChangeRequestWatchFingerprint | null,
407 ) {
408 const now = yield* Clock.currentTimeMillis;
409 const last = lastReads.get(group.key);
410 const plan = planRead(group, last, fingerprint, now);
411 if (!plan.detail) return;
412 const reference = referenceOf(group);
413 // The reads are recorded against this fingerprint, so a cached answer older than it must not
414 // stand in for them. Clients are not told: this only drops this pull request's cached reads.
415 if (fingerprint !== null) yield* pullRequests.invalidate({ reference });
416 const read = yield* Effect.exit(
417 Effect.all(
418 [
419 pullRequests.detail({ ...reference, allowStale: false }),
420 plan.activity
421 ? pullRequests.activity(reference).pipe(Effect.map(Option.some))
422 : Effect.succeed(Option.none<PullRequestActivity>()),
423 ],
424 { concurrency: 2 },
425 ),
426 );
427 if (Exit.isFailure(read)) {
428 if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause);
429 lastReads.delete(group.key);
430 if (isRateLimited(read.cause)) return;
431 const failures = (readFailures.get(group.key) ?? 0) + 1;
432 readFailures.set(group.key, failures);
433 if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) {
434 readFailures.delete(group.key);
435 }
436 return yield* Effect.failCause(read.cause);
437 }
438 readFailures.delete(group.key);
439 const [detail, activity] = read.value;
440 const headSha = detail.headSha ?? null;
441 for (const target of group.targets) {
442 const life = lifeOf(target);
443 const pushed = life.headSha !== null && headSha !== life.headSha;
444 lives.set(lifeKey(target), {
445 ...life,
446 headSha,
447 reads: life.reads + 1,
448 ...(pushed
449 ? { pushedAt: now, longestQuietMs: Math.max(life.longestQuietMs, now - life.pushedAt) }
450 : {}),
451 });
452 }
453 if (detail.state !== "open") {
454 lastReads.delete(group.key);
455 return yield* eachTarget(group, (target) =>
456 detail.state === "closed"
457 ? closed(target)
458 : record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
459 );
460 }
461​
462 // Never advance the remark watermark past comments an incomplete read could have missed.
463 const remarks = Option.isSome(activity)
464 ? yield* readRemarks(group.key, reference, activity.value)
465 : null;
466 lastReads.set(group.key, {
467 at: plan.activity || last === undefined ? now : last.at,
468 fingerprint: group.fingerprint,
469 inFlight:
470 detail.mergeability === "unknown" ||
471 detail.checks.some((check) => check.status === "pending"),
472 remarksComplete: plan.activity ? remarks !== null : (last?.remarksComplete ?? false),
473 watches: new Set(group.targets.map(watchKey)),
474 status: fingerprint?.status ?? null,
475 remarks: fingerprint?.remarks ?? null,
476 });
477 yield* eachTarget(group, (target) => {
478 const report = evaluatePullRequestWatch(target.watch, detail, remarks);
479 if (report.changes.length > 0) {
480 return record(
481 target,
482 report.exhausted ? null : report.next,
483 pullRequestWatchMessage({
484 number: target.link.number,
485 url: target.link.url,
486 baseBranch: detail.baseBranch,
487 headSha: report.next.headSha,
488 report,
489 }),
490 ).pipe(
491 Effect.tap(() => woke(target)),
492 Effect.tap(() => (report.exhausted ? ended(target, "comment-limit") : Effect.void)),
493 );
494 }
495 return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
496 });
497 });
498​
499 const sweep = Effect.gen(function* () {
500 const threads = yield* projections.getThreadsWithPullRequests();
501 const targets = threads.flatMap((thread) =>
502 visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
503 link.watch === undefined ? [] : [{ thread, link, watch: link.watch }],
504 ),
505 );
506 const present = new Set(targets.map(lifeKey));
507 yield* Effect.forEach(
508 [...lives].filter(([key]) => !present.has(key)),
509 ([key, life]) => reportEnd(key, life, "stopped"),
510 { discard: true },
511 );
512 for (const target of targets) lifeOf(target);
513 const byPullRequest = new Map<string, Array<WatchTarget>>();
514 const ending: Array<readonly [WatchTarget, WatchEndReason]> = [];
515 for (const target of targets) {
516 const reason = endsWithoutRead(target);
517 if (reason !== undefined) {
518 ending.push([target, reason]);
519 continue;
520 }
521 // Grouped per project too: each project reads through its own checkout, so one that cannot
522 // read the pull request must not end another project's watches.
523 const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`;
524 byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]);
525 }
526 const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({
527 key,
528 targets: members,
529 fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"),
530 }));
531 for (const cache of [readFailures, lastReads, threadTails]) {
532 for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
533 }
534 yield* Effect.forEach(
535 ending,
536 ([target, reason]) =>
537 record(target, null).pipe(
538 Effect.tap(() => ended(target, reason)),
539 Effect.catchCause(
540 logFailure("pull request watch stop failed", {
541 threadId: target.thread.id,
542 pullRequest: threadPullRequestKeyOf(target.link),
543 }),
544 ),
545 ),
546 { discard: true },
547 );
548 const fingerprints = yield* Effect.forEach(groups, fingerprintOf, {
549 concurrency: "unbounded",
550 });
551 yield* Effect.forEach(
552 groups,
553 (group, index) => {
554 const fingerprint = fingerprints[index]!;
555 return fingerprint === "paused"
556 ? Effect.void
557 : readGroup(group, fingerprint).pipe(
558 Effect.catchCause(
559 logFailure("pull request watch check failed", { pullRequest: group.key }),
560 ),
561 );
562 },
563 { concurrency: 4, discard: true },
564 );
565 }).pipe(
566 Effect.catchCause(logFailure("pull request watch sweep failed", {})),
567 Effect.withSpan("PullRequestWatchReactor.sweep"),
568 );
569​
570 const start: PullRequestWatchReactor["Service"]["start"] = () =>
571 forkParked(
572 sweep.pipe(Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)), Effect.asVoid),
573 );
574​
575 return { start, sweep } satisfies PullRequestWatchReactor["Service"];
576});
577​
578export const layer = Layer.effect(PullRequestWatchReactor, make);