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

PullRequestWatchReactor.ts

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