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

PullRequestWatchReactor.ts

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