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

PullRequestWatchReactor.ts

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