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

PullRequestWatchReactor.ts

854 lines31.0 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 SecureRandom from "effect/crypto/SecureRandom";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as FiberMap from "effect/FiberMap";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Schedule from "effect/Schedule";
27import * as Schema from "effect/Schema";
28import * as Semaphore from "effect/Semaphore";
29import type * as Scope from "effect/Scope";
30import * as Stream from "effect/Stream";
31​
32import {
33 type ProviderChangeRequestWatchFingerprint,
34 PullRequestProviderError,
35} from "@t3tools/source-control-core/server/PullRequestProvider";
36import * as PullRequestService from "../pullRequest/PullRequestService.ts";
37import { forkParked } from "../serverActivation.ts";
38import * as Orchestrator from "./Orchestrator.ts";
39import * as ProjectionStore from "./ProjectionStore.ts";
40import {
41 combinePullRequestWatchWakes,
42 evaluatePullRequestWatch,
43 PULL_REQUEST_WATCH_NO_CHECKS_MS,
44 pullRequestWatchMessage,
45} from "./pullRequestWatch.ts";
46​
47/** Checks take minutes; faster sweeps waste the account's shared host quota. */
48const SWEEP_MINUTES = 2;
49const READ_FAILURE_LIMIT = 8;
50/** Group reads in flight at once, inside the host's own request limit. */
51const GROUP_READS = 4;
52/** Without fingerprints, reread quiet PRs on snapshot changes or this interval to catch edits. */
53const QUIET_REREAD_MS = 10 * 60_000;
54/** Reread despite unchanged fingerprints; they miss review-thread comment edits. */
55const FINGERPRINT_REREAD_MS = 30 * 60_000;
56​
57const isProviderError = Schema.is(PullRequestProviderError);
58​
59const providerFailureReason = (cause: Cause.Cause<PullRequestService.PullRequestError>) =>
60 Option.match(Cause.findErrorOption(cause), {
61 onNone: () => null,
62 onSome: (error) =>
63 error._tag === "PullRequestOperationError" && isProviderError(error.cause)
64 ? error.cause.reason
65 : null,
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​
102interface Wake {
103 readonly text: string;
104 readonly notification: OrchestrationV2Notification;
105 readonly includesRemarks?: boolean;
107​
108/** A wake a pass holds back so each thread gets one for everything the pass found. */
109interface HeldWake {
110 readonly groupKey: string;
111 readonly target: WatchTarget;
112 readonly next: ThreadPullRequestWatch | null;
113 readonly endedWatch?: ThreadPullRequestWatch;
114 readonly wake: Wake;
115 readonly reason?: WatchEndReason;
117​
118const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`;
119​
120type WatchEndReason =
121 | "merged"
122 | "closed"
123 | "unreadable"
124 | "comment-limit"
125 | "settled"
126 | "subagent"
127 | "stopped";
128​
129interface WatchLife {
130 readonly threadId: string;
131 readonly pullRequest: string;
132 readonly startedAt: number;
133 readonly headSha: string | null;
134 readonly pushedAt: number;
135 readonly longestQuietMs: number;
136 readonly wakes: number;
137 readonly reads: number;
139​
140const lifeKey = ({ thread, link, watch }: WatchTarget) =>
141 `${thread.id} ${threadPullRequestKeyOf(link)} ${watch.startedAt}`;
142​
143const minutes = (ms: number) => Math.max(0, Math.round(ms / 60_000));
144​
145const snapshotFingerprint = ({ link }: WatchTarget) => {
146 const snapshot = link.snapshot;
147 return snapshot === null
148 ? ""
149 : [
150 snapshot.state,
151 snapshot.updatedAt,
152 snapshot.checksState,
153 snapshot.mergeability,
154 snapshot.reviewDecision,
155 snapshot.isDraft,
156 ].join(" ");
157};
158​
159function planRead(
160 group: WatchGroup,
161 last: LastRead | undefined,
162 fingerprint: ProviderChangeRequestWatchFingerprint | null,
163 now: number,
164): ReadPlan {
165 if (last === undefined || group.targets.some((target) => !last.watches.has(watchKey(target)))) {
166 return { detail: true, activity: true };
167 }
168 // Nothing on the host changes when the no-checks deadline passes, so it alone prompts a read.
169 const checksDue = group.targets.some(
170 ({ watch }) =>
171 watch.checksAwaitedSince != null &&
172 now - Date.parse(watch.checksAwaitedSince) >= PULL_REQUEST_WATCH_NO_CHECKS_MS,
173 );
174 if (fingerprint === null) {
175 const read =
176 last.inFlight ||
177 !last.remarksComplete ||
178 last.fingerprint !== group.fingerprint ||
179 now - last.at >= QUIET_REREAD_MS;
180 return { detail: read || checksDue, activity: read };
181 }
182 const activity =
183 last.remarks !== fingerprint.remarks ||
184 !last.remarksComplete ||
185 now - last.at >= FINGERPRINT_REREAD_MS;
186 return {
187 detail: activity || checksDue || last.status !== fingerprint.status || last.inFlight,
188 activity,
189 };
191​
192function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean {
193 return (
194 left.startedAt === right.startedAt &&
195 left.headSha === right.headSha &&
196 left.failedChecks.join("\n") === right.failedChecks.join("\n") &&
197 left.passed === right.passed &&
198 left.passedChecks.join("\n") === right.passedChecks.join("\n") &&
199 (left.owedChecks ?? []).join("\n") === (right.owedChecks ?? []).join("\n") &&
200 (left.awaitingApproval ?? []).join("\n") === (right.awaitingApproval ?? []).join("\n") &&
201 (left.approvalAnnounced ?? false) === (right.approvalAnnounced ?? false) &&
202 left.remarksThrough === right.remarksThrough &&
203 left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
204 left.conflicting === right.conflicting &&
205 left.wakes === right.wakes &&
206 left.checksAwaitedSince === right.checksAwaitedSince
207 );
209​
210export class PullRequestWatchReactor extends Context.Service<
211 PullRequestWatchReactor,
212 {
213 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
214 readonly sweep: Effect.Effect<void>;
215 }
216>()("t3/orchestration-v2/PullRequestWatchReactor") {}
217​
218/** @public */
219export const make = Effect.gen(function* () {
220 const engine = yield* Orchestrator.OrchestratorV2;
221 const projections = yield* ProjectionStore.ProjectionStoreV2;
222 const pullRequests = yield* PullRequestService.PullRequestService;
223 const random = yield* SecureRandom.SecureRandom;
224 const bootedAt = yield* Clock.currentTimeMillis;
225 const lives = new Map<string, WatchLife>();
226​
227 const lifeOf = (target: WatchTarget): WatchLife => {
228 const existing = lives.get(lifeKey(target));
229 if (existing !== undefined) return existing;
230 const startedAt = Date.parse(target.watch.startedAt);
231 const life: WatchLife = {
232 threadId: target.thread.id,
233 pullRequest: threadPullRequestKeyOf(target.link),
234 startedAt,
235 headSha: target.watch.headSha,
236 pushedAt: startedAt,
237 longestQuietMs: 0,
238 wakes: 0,
239 reads: 0,
240 };
241 lives.set(lifeKey(target), life);
242 return life;
243 };
244 const woke = (target: WatchTarget) =>
245 Effect.sync(() => {
246 const life = lifeOf(target);
247 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
248 });
249​
250 const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
251 key: string,
252 life: WatchLife,
253 reason: WatchEndReason,
254 ) {
255 lives.delete(key);
256 const now = yield* Clock.currentTimeMillis;
257 const quietMs = now - life.pushedAt;
258 yield* Effect.logInfo("pull request watch ended", {
259 threadId: life.threadId,
260 pullRequest: life.pullRequest,
261 reason,
262 minutes: minutes(now - life.startedAt),
263 quietMinutes: minutes(quietMs),
264 longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
265 wakes: life.wakes,
266 reads: life.reads,
267 partial: life.startedAt < bootedAt,
268 });
269 });
270 const ended = (target: WatchTarget, reason: WatchEndReason) =>
271 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
272​
273 const readFailures = new Map<string, number>();
274 /** The last sweep's groups, whose pull requests get host change feeds. */
275 let currentGroups: ReadonlyArray<WatchGroup> = [];
276 // A pass reads watches and records new ones, so passes must not overlap.
277 const passes = Semaphore.makeUnsafe(1);
278 const lastReads = new Map<string, LastRead>();
279 const threadTails = new Map<
280 string,
281 {
282 readonly fetchedAt: number;
283 readonly visibleThrough: number;
284 readonly tails: ReadonlyMap<
285 string,
286 { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }
287 >;
288 }
289 >();
290​
291 const identityOf = (link: ThreadPullRequestLink) => ({
292 host: normalizeThreadPullRequestKey(link).host,
293 repository: link.repository,
294 number: link.number,
295 });
296​
297 /**
298 * The orchestrator applies this only while the same watch is on, so a stop or restart
299 * that lands during the host read wins.
300 */
301 const record = Effect.fn("PullRequestWatchReactor.record")(function* (
302 target: WatchTarget,
303 next: ThreadPullRequestWatch | null,
304 wake?: Wake,
305 endedWatch?: ThreadPullRequestWatch,
306 ) {
307 const uuid = yield* random.uuidV4();
308 yield* engine.dispatch({
309 type: "thread.pull-request-watch.sync",
310 commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
311 threadId: target.thread.id,
312 ...identityOf(target.link),
313 startedAt: target.watch.startedAt,
314 watch: next,
315 ...(endedWatch === undefined ? {} : { endedWatch }),
316 ...(wake === undefined
317 ? {}
318 : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
319 });
320 });
321​
322 const giveUp = (target: WatchTarget) =>
323 record(target, null, {
324 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 only if it is still open.`,
325 notification: {
326 source: { kind: "monitor" },
327 outcome: "failed",
328 summary: `#${target.link.number}: stopped watching, could not read it`,
329 },
330 }).pipe(
331 Effect.tap(() => woke(target)),
332 Effect.catch(() => record(target, null)),
333 Effect.tap(() => ended(target, "unreadable")),
334 );
335​
336 const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
337 function* (
338 key: string,
339 reference: PullRequestRef,
340 activity: PullRequestActivity,
341 now: number,
342 rereadMs: number,
343 ) {
344 // Comment cursors cannot account for missing threads. Only finish a truncated read
345 // when the host confirms that every thread was listed.
346 if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
347​
348 const visibleThrough = activity.comments.reduce(
349 (latest, comment) => Math.max(latest, Date.parse(comment.editedAt ?? comment.createdAt)),
350 0,
351 );
352 const paginated = activity.reviewThreads.filter(
353 (thread) => thread.nextCommentsCursor != null,
354 );
355 const cached = threadTails.get(key);
356 // All tails share one watermark, so newer visible remarks or a changed thread must
357 // refresh the entire group before any remarks can advance it.
358 const reuse =
359 cached !== undefined &&
360 now - cached.fetchedAt < rereadMs &&
361 cached.visibleThrough === visibleThrough &&
362 cached.tails.size === paginated.length &&
363 paginated.every(
364 (thread) => cached.tails.get(thread.id)?.count === (thread.commentCount ?? 0),
365 );
366 const tails = new Map<
367 string,
368 { count: number; comments: ReadonlyArray<PullRequestComment> }
369 >();
370 const remarks = [...activity.comments];
371 for (const thread of paginated) {
372 let cursor = thread.nextCommentsCursor ?? null;
373 const count = thread.commentCount ?? 0;
374 let tail = reuse ? cached.tails.get(thread.id) : undefined;
375 if (tail === undefined) {
376 const comments = new Map<string, PullRequestComment>();
377 const cursors = new Set<string>();
378 let hidden = 0;
379 while (cursor !== null) {
380 if (cursors.has(cursor)) return null;
381 cursors.add(cursor);
382 const page: PullRequestThreadCommentsResult = yield* pullRequests.threadComments({
383 ...reference,
384 threadId: thread.id,
385 cursor,
386 });
387 for (const comment of page.comments) {
388 comments.set(comment.id, {
389 ...comment,
390 kind: "review-comment",
391 path: thread.path,
392 reviewState: null,
393 });
394 }
395 hidden += page.hiddenCount ?? 0;
396 cursor = page.nextCursor;
397 }
398 if (thread.comments.length + comments.size + hidden < count) return null;
399 tail = { count, comments: [...comments.values()] };
400 }
401 tails.set(thread.id, tail);
402 remarks.push(...tail.comments);
403 }
404 threadTails.set(key, {
405 fetchedAt: reuse ? cached.fetchedAt : now,
406 visibleThrough,
407 tails,
408 });
409 return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
410 },
411 Effect.catch((error) =>
412 Effect.logWarning("pull request watch comment pagination failed", { error }).pipe(
413 Effect.as(null),
414 ),
415 ),
416 (effect, key) =>
417 effect.pipe(
418 Effect.onExit((exit) =>
419 Effect.sync(() => {
420 // A retry must refresh every tail before advancing the shared remark watermark.
421 if (Exit.isFailure(exit) || exit.value === null) threadTails.delete(key);
422 }),
423 ),
424 ),
425 );
426​
427 /** Wakes the current pass found, sent by `sendHeld` once every read of the pass is done. */
428 let held: Array<HeldWake> = [];
429 const hold = (wake: HeldWake) => Effect.sync(() => void held.push(wake));
430​
431 const sendOne = (item: HeldWake) =>
432 record(item.target, item.next, item.wake, item.endedWatch).pipe(
433 Effect.tap(() => woke(item.target)),
434 Effect.tap(() => (item.reason === undefined ? Effect.void : ended(item.target, item.reason))),
435 Effect.catchCause((cause) => {
436 lastReads.delete(item.groupKey);
437 return logFailure("pull request watch update failed", {
438 threadId: item.target.thread.id,
439 pullRequest: item.groupKey,
440 })(cause);
441 }),
442 );
443​
444 const sendTogether = Effect.fn("PullRequestWatchReactor.sendTogether")(function* (
445 items: readonly [HeldWake, ...ReadonlyArray<HeldWake>],
446 ) {
447 const [first, ...rest] = items;
448 const uuid = yield* random.uuidV4();
449 yield* engine.dispatch({
450 type: "thread.pull-request-watch.sync",
451 commandId: CommandId.make(`server:pr-watch:${first.target.thread.id}:${uuid}`),
452 threadId: first.target.thread.id,
453 ...identityOf(first.target.link),
454 startedAt: first.target.watch.startedAt,
455 watch: first.next,
456 ...(first.endedWatch === undefined ? {} : { endedWatch: first.endedWatch }),
457 others: rest.map((item) => ({
458 ...identityOf(item.target.link),
459 startedAt: item.target.watch.startedAt,
460 watch: item.next,
461 ...(item.endedWatch === undefined ? {} : { endedWatch: item.endedWatch }),
462 ...(item.wake.includesRemarks === true ? { includesRemarks: true } : {}),
463 })),
464 wake: {
465 ...combinePullRequestWatchWakes([first.wake, ...rest.map((item) => item.wake)]),
466 ...(first.wake.includesRemarks === true ? { includesRemarks: true } : {}),
467 sections: items.map(({ wake }) => ({
468 text: wake.text,
469 outcome: wake.notification.outcome,
470 summary: wake.notification.summary,
471 })),
472 messageId: MessageId.make(`message:pr-watch:${uuid}`),
473 },
474 });
475 yield* Effect.forEach(
476 items,
477 (item) =>
478 woke(item.target).pipe(
479 Effect.andThen(item.reason === undefined ? Effect.void : ended(item.target, item.reason)),
480 ),
481 { discard: true },
482 );
483 });
484​
485 const sendHeld = Effect.suspend(() => {
486 const byThread = new Map<string, Array<HeldWake>>();
487 for (const item of held) {
488 byThread.set(item.target.thread.id, [...(byThread.get(item.target.thread.id) ?? []), item]);
489 }
490 held = [];
491 return Effect.forEach(
492 byThread.values(),
493 ([first, ...rest]) =>
494 rest.length === 0
495 ? sendOne(first!)
496 : // A watch that ended or moved during the pass fails the whole command; each then
497 // goes on its own, as the orchestrator decides for it alone.
498 sendTogether([first!, ...rest]).pipe(
499 Effect.catchCauseIf(
500 (cause) => !Cause.hasInterruptsOnly(cause),
501 () => Effect.forEach([first!, ...rest], sendOne, { discard: true }),
502 ),
503 ),
504 { discard: true },
505 );
506 });
507​
508 const closed = (groupKey: string, target: WatchTarget) =>
509 hold({
510 groupKey,
511 target,
512 next: null,
513 wake: {
514 text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
515 notification: {
516 source: { kind: "monitor" },
517 outcome: "updated",
518 summary: `#${target.link.number}: closed, stopped watching`,
519 },
520 },
521 reason: "closed",
522 });
523​
524 const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
525 link.snapshot?.state === "merged"
526 ? "merged"
527 : thread.settledOverride === "settled" || thread.settledAt !== null
528 ? "settled"
529 : thread.lineage.relationshipToParent === "subagent"
530 ? "subagent"
531 : undefined;
532​
533 const eachTarget = <E>(
534 group: WatchGroup,
535 step: (target: WatchTarget) => Effect.Effect<void, E>,
536 ) =>
537 Effect.forEach(group.targets, (target) =>
538 step(target).pipe(
539 Effect.as(true),
540 Effect.catchCause((cause) => {
541 lastReads.delete(group.key);
542 return logFailure("pull request watch update failed", {
543 threadId: target.thread.id,
544 pullRequest: group.key,
545 })(cause).pipe(Effect.as(false));
546 }),
547 ),
548 ).pipe(Effect.map((landed) => landed.every(Boolean)));
549​
550 const referenceOf = (group: WatchGroup) => {
551 const first = group.targets[0]!;
552 return { projectId: first.thread.projectId, ...identityOf(first.link) };
553 };
554​
555 const fingerprintOf = (group: WatchGroup) =>
556 pullRequests.watchFingerprint(referenceOf(group)).pipe(
557 Effect.catchCause(
558 (cause): Effect.Effect<ProviderChangeRequestWatchFingerprint | null | "paused"> =>
559 Cause.hasInterruptsOnly(cause)
560 ? Effect.interrupt
561 : providerFailureReason(cause) === "rate-limited"
562 ? Effect.succeed("paused")
563 : Effect.logDebug("pull request watch fingerprint failed", {
564 pullRequest: group.key,
565 cause,
566 }).pipe(Effect.as(null)),
567 ),
568 );
569​
570 const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* (
571 group: WatchGroup,
572 fingerprint: ProviderChangeRequestWatchFingerprint | null,
573 ) {
574 const now = yield* Clock.currentTimeMillis;
575 const last = lastReads.get(group.key);
576 const plan = planRead(group, last, fingerprint, now);
577 if (!plan.detail) return;
578 if (
579 last === undefined ||
580 group.targets.some((target) => !last.watches.has(watchKey(target))) ||
581 (fingerprint !== null && last.remarks !== fingerprint.remarks)
582 ) {
583 // A new watch or changed host remarks needs a fresh view of every tail.
584 threadTails.delete(group.key);
585 }
586 const reference = referenceOf(group);
587 // Invalidate cached reads before using the newer fingerprint; clients receive no notification.
588 if (fingerprint !== null) yield* pullRequests.invalidate({ reference });
589 const [detailRead, activityRead] = yield* Effect.all(
590 [
591 Effect.exit(pullRequests.detail({ ...reference, allowStale: false })),
592 Effect.exit(
593 plan.activity
594 ? pullRequests.activity(reference).pipe(Effect.asSome)
595 : Effect.succeed(Option.none<PullRequestActivity>()),
596 ),
597 ],
598 { concurrency: 2 },
599 );
600 // Activity failures must not cancel or hide a permanent detail failure.
601 // Activity is irrelevant once the pull request is closed or merged, so it cannot block ending.
602 const read = Exit.isFailure(detailRead)
603 ? Exit.failCause(detailRead.cause)
604 : detailRead.value.state !== "open"
605 ? Exit.succeed([detailRead.value, Option.none<PullRequestActivity>()] as const)
606 : Exit.isFailure(activityRead)
607 ? Exit.failCause(activityRead.cause)
608 : Exit.succeed([detailRead.value, activityRead.value] as const);
609 if (Exit.isFailure(read)) {
610 if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause);
611 lastReads.delete(group.key);
612 const reason = providerFailureReason(read.cause);
613 if (reason === "rate-limited") return;
614 // Transport and host failures can outlast the failure limit; keep the watch for recovery.
615 if (reason === "failed") {
616 readFailures.delete(group.key);
617 return yield* Effect.failCause(read.cause);
618 }
619 const failures = (readFailures.get(group.key) ?? 0) + 1;
620 readFailures.set(group.key, failures);
621 if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) {
622 readFailures.delete(group.key);
623 }
624 return yield* Effect.failCause(read.cause);
625 }
626 readFailures.delete(group.key);
627 const [detail, activity] = read.value;
628 for (const target of group.targets) {
629 const life = lifeOf(target);
630 const headSha = detail.headSha ?? life.headSha;
631 const pushed = life.headSha !== null && headSha !== life.headSha;
632 lives.set(lifeKey(target), {
633 ...life,
634 headSha,
635 reads: life.reads + 1,
636 ...(pushed
637 ? { pushedAt: now, longestQuietMs: Math.max(life.longestQuietMs, now - life.pushedAt) }
638 : {}),
639 });
640 }
641 if (detail.state !== "open") {
642 lastReads.delete(group.key);
643 return yield* eachTarget(group, (target) =>
644 detail.state === "closed"
645 ? closed(group.key, target)
646 : record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
647 );
648 }
649​
650 // Never advance the remark watermark past comments an incomplete read could have missed.
651 const remarks = Option.isSome(activity)
652 ? yield* readRemarks(
653 group.key,
654 reference,
655 activity.value,
656 now,
657 fingerprint === null ? QUIET_REREAD_MS : FINGERPRINT_REREAD_MS,
658 )
659 : null;
660 lastReads.set(group.key, {
661 at:
662 plan.activity || last === undefined
663 ? (threadTails.get(group.key)?.fetchedAt ?? now)
664 : last.at,
665 fingerprint: group.fingerprint,
666 inFlight:
667 detail.mergeability === "unknown" ||
668 detail.checks.some((check) => check.status === "pending"),
669 remarksComplete: plan.activity ? remarks !== null : (last?.remarksComplete ?? false),
670 watches: new Set(group.targets.map(watchKey)),
671 status: fingerprint?.status ?? null,
672 remarks: fingerprint?.remarks ?? null,
673 });
674 yield* eachTarget(group, (target) => {
675 const report = evaluatePullRequestWatch(target.watch, detail, remarks, now);
676 if (report.changes.length > 0) {
677 const wake = {
678 ...pullRequestWatchMessage({
679 number: target.link.number,
680 url: target.link.url,
681 baseBranch: detail.baseBranch,
682 headSha: report.next.headSha,
683 report,
684 }),
685 includesRemarks: report.changes.some((change) => change.kind === "remarks"),
686 };
687 // An ending watch keeps what this pass saw, so watching again starts from it.
688 return hold(
689 report.exhausted
690 ? {
691 groupKey: group.key,
692 target,
693 next: null,
694 endedWatch: report.next,
695 wake,
696 reason: "comment-limit",
697 }
698 : { groupKey: group.key, target, next: report.next, wake },
699 );
700 }
701 return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
702 });
703 });
704​
705 /** Every watch, or with `changed`, only that pull request's after its host reported a change. */
706 // The sweep and change reads each name their own span.
707 const pass = Effect.fnUntraced(function* (changed: string | undefined) {
708 held = [];
709 const threads = yield* projections.getThreadsWithPullRequests();
710 const targets = threads.flatMap((thread) =>
711 visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
712 link.watch === undefined ||
713 (changed !== undefined && threadPullRequestKeyOf(link) !== changed)
714 ? []
715 : [{ thread, link, watch: link.watch }],
716 ),
717 );
718 if (changed === undefined) {
719 const present = new Set(targets.map(lifeKey));
720 yield* Effect.forEach(
721 [...lives].filter(([key]) => !present.has(key)),
722 ([key, life]) => reportEnd(key, life, "stopped"),
723 { discard: true },
724 );
725 }
726 for (const target of targets) lifeOf(target);
727 const byPullRequest = new Map<string, Array<WatchTarget>>();
728 const ending: Array<readonly [WatchTarget, WatchEndReason]> = [];
729 for (const target of targets) {
730 const reason = endsWithoutRead(target);
731 if (reason !== undefined) {
732 ending.push([target, reason]);
733 continue;
734 }
735 // Group by project because checkout access differs; one failure must not end another project's watches.
736 const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`;
737 byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]);
738 }
739 const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({
740 key,
741 targets: members,
742 fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"),
743 }));
744 if (changed === undefined) {
745 currentGroups = groups;
746 for (const cache of [readFailures, lastReads, threadTails]) {
747 for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
748 }
749 }
750 yield* Effect.forEach(
751 ending,
752 ([target, reason]) =>
753 record(target, null).pipe(
754 Effect.tap(() => ended(target, reason)),
755 Effect.catchCause(
756 logFailure("pull request watch stop failed", {
757 threadId: target.thread.id,
758 pullRequest: threadPullRequestKeyOf(target.link),
759 }),
760 ),
761 ),
762 { discard: true },
763 );
764 // Every fingerprint is asked for at once so the host can batch them, and each group reads
765 // as soon as its own answer lands rather than waiting on the slowest host.
766 const reads = yield* Semaphore.make(GROUP_READS);
767 yield* Effect.forEach(
768 groups,
769 (group) =>
770 // The host just reported a change, so a cached fingerprint may predate it.
771 (changed === undefined
772 ? Effect.void
773 : pullRequests.invalidate({ reference: referenceOf(group) })
774 ).pipe(
775 Effect.andThen(fingerprintOf(group)),
776 Effect.tap((fingerprint) => {
777 const last = lastReads.get(group.key);
778 // Open pull request views refresh only when the host state moved.
779 return changed !== undefined &&
780 fingerprint !== null &&
781 fingerprint !== "paused" &&
782 (last === undefined ||
783 last.status !== fingerprint.status ||
784 last.remarks !== fingerprint.remarks)
785 ? pullRequests.invalidate({ reference: referenceOf(group) }, { notifyReaders: true })
786 : Effect.void;
787 }),
788 Effect.flatMap((fingerprint) =>
789 fingerprint === "paused"
790 ? Effect.void
791 : reads.withPermit(
792 readGroup(group, fingerprint).pipe(
793 Effect.catchCause(
794 logFailure("pull request watch check failed", { pullRequest: group.key }),
795 ),
796 ),
797 ),
798 ),
799 ),
800 { concurrency: "unbounded", discard: true },
801 );
802 yield* sendHeld;
803 }, passes.withPermit);
804​
805 const sweep = pass(undefined).pipe(
806 Effect.catchCause(logFailure("pull request watch sweep failed", {})),
807 Effect.withSpan("PullRequestWatchReactor.sweep"),
808 );
809​
810 const pullRequestOf = (group: WatchGroup) => threadPullRequestKeyOf(group.targets[0]!.link);
811​
812 const readOnChange = (pullRequest: string) =>
813 pass(pullRequest).pipe(
814 Effect.catchCause(logFailure("pull request watch change read failed", { pullRequest })),
815 Effect.withSpan("PullRequestWatchReactor.readOnChange"),
816 );
817​
818 const start: PullRequestWatchReactor["Service"]["start"] = Effect.fn(
819 "PullRequestWatchReactor.start",
820 )(function* () {
821 // One feed per pull request: the host keeps one subscription per pull request and account.
822 const feeds = yield* FiberMap.make<string>();
823 const follow = Effect.gen(function* () {
824 const wanted = new Map(currentGroups.map((group) => [pullRequestOf(group), group]));
825 const stale = Array.from(feeds, ([pullRequest]) => pullRequest).filter(
826 (pullRequest) => !wanted.has(pullRequest),
827 );
828 yield* Effect.forEach(stale, (pullRequest) => FiberMap.remove(feeds, pullRequest), {
829 discard: true,
830 });
831 for (const [pullRequest, group] of wanted) {
832 // An ended feed restarts here, so a host that refused it is asked again each sweep.
833 yield* FiberMap.run(feeds, pullRequest, { onlyIfMissing: true })(
834 pullRequests.changes(referenceOf(group)).pipe(
835 // A review sends an event per comment; those landing during a read make one more.
836 Stream.buffer({ capacity: 1, strategy: "sliding" }),
837 Stream.runForEach(() => readOnChange(pullRequest)),
838 ),
839 );
840 }
841 });
842 yield* forkParked(
843 sweep.pipe(
844 Effect.andThen(follow),
845 Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)),
846 Effect.asVoid,
847 ),
848 );
849 });
850​
851 return { start, sweep } satisfies PullRequestWatchReactor["Service"];
852});
853​
854export const layer = Layer.effect(PullRequestWatchReactor, make);