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

PullRequestWatchReactor.ts

646 lines22.7 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 "../sourceControl/threadPullRequests.ts";
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.owedChecks ?? []).join("\n") === (right.owedChecks ?? []).join("\n") &&
175 left.remarksThrough === right.remarksThrough &&
176 left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
177 left.conflicting === right.conflicting &&
178 left.wakes === right.wakes &&
179 left.checksAwaitedSince === right.checksAwaitedSince
180 );
182​
183export class PullRequestWatchReactor extends Context.Service<
184 PullRequestWatchReactor,
185 {
186 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
187 readonly sweep: Effect.Effect<void>;
188 }
189>()("t3/orchestration-v2/PullRequestWatchReactor") {}
190​
191/** @public Service construction is part of the canonical Effect module API. */
192export const make = Effect.gen(function* () {
193 const engine = yield* Orchestrator.OrchestratorV2;
194 const projections = yield* ProjectionStore.ProjectionStoreV2;
195 const pullRequests = yield* PullRequestService.PullRequestService;
196 const crypto = yield* Crypto.Crypto;
197 const bootedAt = yield* Clock.currentTimeMillis;
198 const lives = new Map<string, WatchLife>();
199​
200 const lifeOf = (target: WatchTarget): WatchLife => {
201 const existing = lives.get(lifeKey(target));
202 if (existing !== undefined) return existing;
203 const startedAt = Date.parse(target.watch.startedAt);
204 const life: WatchLife = {
205 threadId: target.thread.id,
206 pullRequest: threadPullRequestKeyOf(target.link),
207 startedAt,
208 headSha: target.watch.headSha,
209 pushedAt: startedAt,
210 longestQuietMs: 0,
211 wakes: 0,
212 reads: 0,
213 };
214 lives.set(lifeKey(target), life);
215 return life;
216 };
217 const woke = (target: WatchTarget) =>
218 Effect.sync(() => {
219 const life = lifeOf(target);
220 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
221 });
222​
223 const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
224 key: string,
225 life: WatchLife,
226 reason: WatchEndReason,
227 ) {
228 lives.delete(key);
229 const now = yield* Clock.currentTimeMillis;
230 const quietMs = now - life.pushedAt;
231 yield* Effect.logInfo("pull request watch ended", {
232 threadId: life.threadId,
233 pullRequest: life.pullRequest,
234 reason,
235 minutes: minutes(now - life.startedAt),
236 quietMinutes: minutes(quietMs),
237 longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
238 wakes: life.wakes,
239 reads: life.reads,
240 partial: life.startedAt < bootedAt,
241 });
242 });
243 const ended = (target: WatchTarget, reason: WatchEndReason) =>
244 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
245​
246 const readFailures = new Map<string, number>();
247 const lastReads = new Map<string, LastRead>();
248 const threadTails = new Map<
249 string,
250 {
251 readonly fetchedAt: number;
252 readonly visibleThrough: number;
253 readonly tails: ReadonlyMap<
254 string,
255 { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }
256 >;
257 }
258 >();
259​
260 const identityOf = (link: ThreadPullRequestLink) => ({
261 host: normalizeThreadPullRequestKey(link).host,
262 repository: link.repository,
263 number: link.number,
264 });
265​
266 /**
267 * The orchestrator applies this only while the same watch is on, so a stop or restart
268 * that lands during the host read wins.
269 */
270 const record = Effect.fn("PullRequestWatchReactor.record")(function* (
271 target: WatchTarget,
272 next: ThreadPullRequestWatch | null,
273 wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
274 endedWatch?: ThreadPullRequestWatch,
275 ) {
276 const uuid = yield* crypto.randomUUIDv4();
277 yield* engine.dispatch({
278 type: "thread.pull-request-watch.sync",
279 commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
280 threadId: target.thread.id,
281 ...identityOf(target.link),
282 startedAt: target.watch.startedAt,
283 watch: next,
284 ...(endedWatch === undefined ? {} : { endedWatch }),
285 ...(wake === undefined
286 ? {}
287 : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
288 });
289 });
290​
291 const giveUp = (target: WatchTarget) =>
292 record(target, null, {
293 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.`,
294 notification: {
295 source: { kind: "monitor" },
296 outcome: "failed",
297 summary: `#${target.link.number}: stopped watching, could not read it`,
298 },
299 }).pipe(
300 Effect.tap(() => woke(target)),
301 Effect.catch(() => record(target, null)),
302 Effect.tap(() => ended(target, "unreadable")),
303 );
304​
305 const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
306 function* (
307 key: string,
308 reference: PullRequestRef,
309 activity: PullRequestActivity,
310 now: number,
311 rereadMs: number,
312 ) {
313 // Comment cursors cannot account for missing threads. Only finish a truncated read
314 // when the host confirms that every thread was listed.
315 if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
316​
317 const visibleThrough = activity.comments.reduce(
318 (latest, comment) => Math.max(latest, Date.parse(comment.editedAt ?? comment.createdAt)),
319 0,
320 );
321 const paginated = activity.reviewThreads.filter(
322 (thread) => thread.nextCommentsCursor != null,
323 );
324 const cached = threadTails.get(key);
325 // All tails share one watermark, so newer visible remarks or a changed thread must
326 // refresh the entire group before any remarks can advance it.
327 const reuse =
328 cached !== undefined &&
329 now - cached.fetchedAt < rereadMs &&
330 cached.visibleThrough === visibleThrough &&
331 cached.tails.size === paginated.length &&
332 paginated.every(
333 (thread) => cached.tails.get(thread.id)?.count === (thread.commentCount ?? 0),
334 );
335 const tails = new Map<
336 string,
337 { count: number; comments: ReadonlyArray<PullRequestComment> }
338 >();
339 const remarks = [...activity.comments];
340 for (const thread of paginated) {
341 let cursor = thread.nextCommentsCursor ?? null;
342 const count = thread.commentCount ?? 0;
343 let tail = reuse ? cached.tails.get(thread.id) : undefined;
344 if (tail === undefined) {
345 const comments = new Map<string, PullRequestComment>();
346 const cursors = new Set<string>();
347 while (cursor !== null) {
348 if (cursors.has(cursor)) return null;
349 cursors.add(cursor);
350 const page: PullRequestThreadCommentsResult = yield* pullRequests.threadComments({
351 ...reference,
352 threadId: thread.id,
353 cursor,
354 });
355 for (const comment of page.comments) {
356 comments.set(comment.id, {
357 ...comment,
358 kind: "review-comment",
359 path: thread.path,
360 reviewState: null,
361 });
362 }
363 cursor = page.nextCursor;
364 }
365 if (thread.comments.length + comments.size < count) return null;
366 tail = { count, comments: [...comments.values()] };
367 }
368 tails.set(thread.id, tail);
369 remarks.push(...tail.comments);
370 }
371 threadTails.set(key, {
372 fetchedAt: reuse ? cached.fetchedAt : now,
373 visibleThrough,
374 tails,
375 });
376 return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
377 },
378 Effect.catch((error) =>
379 Effect.logWarning("pull request watch comment pagination failed", { error }).pipe(
380 Effect.as(null),
381 ),
382 ),
383 (effect, key) =>
384 effect.pipe(
385 Effect.onExit((exit) =>
386 Effect.sync(() => {
387 // A retry must refresh every tail before advancing the shared remark watermark.
388 if (Exit.isFailure(exit) || exit.value === null) threadTails.delete(key);
389 }),
390 ),
391 ),
392 );
393​
394 const closed = (target: WatchTarget) =>
395 record(target, null, {
396 text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
397 notification: {
398 source: { kind: "monitor" },
399 outcome: "updated",
400 summary: `#${target.link.number}: closed, stopped watching`,
401 },
402 }).pipe(
403 Effect.tap(() => woke(target)),
404 Effect.tap(() => ended(target, "closed")),
405 );
406​
407 const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
408 link.snapshot?.state === "merged"
409 ? "merged"
410 : thread.settledOverride === "settled" || thread.settledAt !== null
411 ? "settled"
412 : thread.lineage.relationshipToParent === "subagent"
413 ? "subagent"
414 : undefined;
415​
416 const eachTarget = <E>(
417 group: WatchGroup,
418 step: (target: WatchTarget) => Effect.Effect<void, E>,
419 ) =>
420 Effect.forEach(group.targets, (target) =>
421 step(target).pipe(
422 Effect.as(true),
423 Effect.catchCause((cause) => {
424 lastReads.delete(group.key);
425 return logFailure("pull request watch update failed", {
426 threadId: target.thread.id,
427 pullRequest: group.key,
428 })(cause).pipe(Effect.as(false));
429 }),
430 ),
431 ).pipe(Effect.map((landed) => landed.every(Boolean)));
432​
433 const referenceOf = (group: WatchGroup) => {
434 const first = group.targets[0]!;
435 return { projectId: first.thread.projectId, ...identityOf(first.link) };
436 };
437​
438 const fingerprintOf = (group: WatchGroup) =>
439 pullRequests.watchFingerprint(referenceOf(group)).pipe(
440 Effect.catchCause(
441 (cause): Effect.Effect<ProviderChangeRequestWatchFingerprint | null | "paused"> =>
442 Cause.hasInterruptsOnly(cause)
443 ? Effect.interrupt
444 : isRateLimited(cause)
445 ? Effect.succeed("paused")
446 : Effect.logDebug("pull request watch fingerprint failed", {
447 pullRequest: group.key,
448 cause,
449 }).pipe(Effect.as(null)),
450 ),
451 );
452​
453 const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* (
454 group: WatchGroup,
455 fingerprint: ProviderChangeRequestWatchFingerprint | null,
456 ) {
457 const now = yield* Clock.currentTimeMillis;
458 const last = lastReads.get(group.key);
459 const plan = planRead(group, last, fingerprint, now);
460 if (!plan.detail) return;
461 if (
462 last === undefined ||
463 group.targets.some((target) => !last.watches.has(watchKey(target))) ||
464 (fingerprint !== null && last.remarks !== fingerprint.remarks)
465 ) {
466 // A new watch or changed host remarks needs a fresh view of every tail.
467 threadTails.delete(group.key);
468 }
469 const reference = referenceOf(group);
470 // The reads are recorded against this fingerprint, so a cached answer older than it must not
471 // stand in for them. Clients are not told: this only drops this pull request's cached reads.
472 if (fingerprint !== null) yield* pullRequests.invalidate({ reference });
473 const read = yield* Effect.exit(
474 Effect.all(
475 [
476 pullRequests.detail({ ...reference, allowStale: false }),
477 plan.activity
478 ? pullRequests.activity(reference).pipe(Effect.map(Option.some))
479 : Effect.succeed(Option.none<PullRequestActivity>()),
480 ],
481 { concurrency: 2 },
482 ),
483 );
484 if (Exit.isFailure(read)) {
485 if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause);
486 lastReads.delete(group.key);
487 if (isRateLimited(read.cause)) return;
488 const failures = (readFailures.get(group.key) ?? 0) + 1;
489 readFailures.set(group.key, failures);
490 if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) {
491 readFailures.delete(group.key);
492 }
493 return yield* Effect.failCause(read.cause);
494 }
495 readFailures.delete(group.key);
496 const [detail, activity] = read.value;
497 const headSha = detail.headSha ?? null;
498 for (const target of group.targets) {
499 const life = lifeOf(target);
500 const pushed = life.headSha !== null && headSha !== life.headSha;
501 lives.set(lifeKey(target), {
502 ...life,
503 headSha,
504 reads: life.reads + 1,
505 ...(pushed
506 ? { pushedAt: now, longestQuietMs: Math.max(life.longestQuietMs, now - life.pushedAt) }
507 : {}),
508 });
509 }
510 if (detail.state !== "open") {
511 lastReads.delete(group.key);
512 return yield* eachTarget(group, (target) =>
513 detail.state === "closed"
514 ? closed(target)
515 : record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
516 );
517 }
518​
519 // Never advance the remark watermark past comments an incomplete read could have missed.
520 const remarks = Option.isSome(activity)
521 ? yield* readRemarks(
522 group.key,
523 reference,
524 activity.value,
525 now,
526 fingerprint === null ? QUIET_REREAD_MS : FINGERPRINT_REREAD_MS,
527 )
528 : null;
529 lastReads.set(group.key, {
530 at:
531 plan.activity || last === undefined
532 ? (threadTails.get(group.key)?.fetchedAt ?? now)
533 : last.at,
534 fingerprint: group.fingerprint,
535 inFlight:
536 detail.mergeability === "unknown" ||
537 detail.checks.some((check) => check.status === "pending"),
538 remarksComplete: plan.activity ? remarks !== null : (last?.remarksComplete ?? false),
539 watches: new Set(group.targets.map(watchKey)),
540 status: fingerprint?.status ?? null,
541 remarks: fingerprint?.remarks ?? null,
542 });
543 yield* eachTarget(group, (target) => {
544 const report = evaluatePullRequestWatch(target.watch, detail, remarks, now);
545 if (report.changes.length > 0) {
546 const wake = pullRequestWatchMessage({
547 number: target.link.number,
548 url: target.link.url,
549 baseBranch: detail.baseBranch,
550 headSha: report.next.headSha,
551 report,
552 });
553 // An ending watch keeps what this pass saw, so watching again starts from it.
554 return (
555 report.exhausted
556 ? record(target, null, wake, report.next)
557 : record(target, report.next, wake)
558 ).pipe(
559 Effect.tap(() => woke(target)),
560 Effect.tap(() => (report.exhausted ? ended(target, "comment-limit") : Effect.void)),
561 );
562 }
563 return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
564 });
565 });
566​
567 const sweep = Effect.gen(function* () {
568 const threads = yield* projections.getThreadsWithPullRequests();
569 const targets = threads.flatMap((thread) =>
570 visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
571 link.watch === undefined ? [] : [{ thread, link, watch: link.watch }],
572 ),
573 );
574 const present = new Set(targets.map(lifeKey));
575 yield* Effect.forEach(
576 [...lives].filter(([key]) => !present.has(key)),
577 ([key, life]) => reportEnd(key, life, "stopped"),
578 { discard: true },
579 );
580 for (const target of targets) lifeOf(target);
581 const byPullRequest = new Map<string, Array<WatchTarget>>();
582 const ending: Array<readonly [WatchTarget, WatchEndReason]> = [];
583 for (const target of targets) {
584 const reason = endsWithoutRead(target);
585 if (reason !== undefined) {
586 ending.push([target, reason]);
587 continue;
588 }
589 // Grouped per project too: each project reads through its own checkout, so one that cannot
590 // read the pull request must not end another project's watches.
591 const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`;
592 byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]);
593 }
594 const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({
595 key,
596 targets: members,
597 fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"),
598 }));
599 for (const cache of [readFailures, lastReads, threadTails]) {
600 for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
601 }
602 yield* Effect.forEach(
603 ending,
604 ([target, reason]) =>
605 record(target, null).pipe(
606 Effect.tap(() => ended(target, reason)),
607 Effect.catchCause(
608 logFailure("pull request watch stop failed", {
609 threadId: target.thread.id,
610 pullRequest: threadPullRequestKeyOf(target.link),
611 }),
612 ),
613 ),
614 { discard: true },
615 );
616 const fingerprints = yield* Effect.forEach(groups, fingerprintOf, {
617 concurrency: "unbounded",
618 });
619 yield* Effect.forEach(
620 groups,
621 (group, index) => {
622 const fingerprint = fingerprints[index]!;
623 return fingerprint === "paused"
624 ? Effect.void
625 : readGroup(group, fingerprint).pipe(
626 Effect.catchCause(
627 logFailure("pull request watch check failed", { pullRequest: group.key }),
628 ),
629 );
630 },
631 { concurrency: 4, discard: true },
632 );
633 }).pipe(
634 Effect.catchCause(logFailure("pull request watch sweep failed", {})),
635 Effect.withSpan("PullRequestWatchReactor.sweep"),
636 );
637​
638 const start: PullRequestWatchReactor["Service"]["start"] = () =>
639 forkParked(
640 sweep.pipe(Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)), Effect.asVoid),
641 );
642​
643 return { start, sweep } satisfies PullRequestWatchReactor["Service"];
644});
645​
646export const layer = Layer.effect(PullRequestWatchReactor, make);