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