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

PullRequestWatchReactor.ts

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