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

PullRequestWatchReactor.ts

666 lines23.6 KB

1import {
2 CommandId,
3 MessageId,
4 type OrchestrationV2Notification,
5 type PullRequestActivity,
6 type PullRequestComment,
7 type PullRequestRef,
8 type PullRequestThreadCommentsResult,
9 type ThreadPullRequestLink,
10 type ThreadPullRequestWatch,
11} from "@t3tools/contracts";
12import {
13 normalizeThreadPullRequestKey,
14 threadPullRequestKeyOf,
15 visibleThreadPullRequests,
16} from "../sourceControl/threadPullRequests.ts";
17import * as Cause from "effect/Cause";
18import * as Clock from "effect/Clock";
19import * as Context from "effect/Context";
20import * as 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.remarksThrough === right.remarksThrough &&
182 left.remarkIds.join("\n") === right.remarkIds.join("\n") &&
183 left.conflicting === right.conflicting &&
184 left.wakes === right.wakes &&
185 left.checksAwaitedSince === right.checksAwaitedSince
186 );
188​
189export class PullRequestWatchReactor extends Context.Service<
190 PullRequestWatchReactor,
191 {
192 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
193 readonly sweep: Effect.Effect<void>;
194 }
195>()("t3/orchestration-v2/PullRequestWatchReactor") {}
196​
197/** @public */
198export const make = Effect.gen(function* () {
199 const engine = yield* Orchestrator.OrchestratorV2;
200 const projections = yield* ProjectionStore.ProjectionStoreV2;
201 const pullRequests = yield* PullRequestService.PullRequestService;
202 const random = yield* SecureRandom.SecureRandom;
203 const bootedAt = yield* Clock.currentTimeMillis;
204 const lives = new Map<string, WatchLife>();
205​
206 const lifeOf = (target: WatchTarget): WatchLife => {
207 const existing = lives.get(lifeKey(target));
208 if (existing !== undefined) return existing;
209 const startedAt = Date.parse(target.watch.startedAt);
210 const life: WatchLife = {
211 threadId: target.thread.id,
212 pullRequest: threadPullRequestKeyOf(target.link),
213 startedAt,
214 headSha: target.watch.headSha,
215 pushedAt: startedAt,
216 longestQuietMs: 0,
217 wakes: 0,
218 reads: 0,
219 };
220 lives.set(lifeKey(target), life);
221 return life;
222 };
223 const woke = (target: WatchTarget) =>
224 Effect.sync(() => {
225 const life = lifeOf(target);
226 lives.set(lifeKey(target), { ...life, wakes: life.wakes + 1 });
227 });
228​
229 const reportEnd = Effect.fn("PullRequestWatchReactor.reportEnd")(function* (
230 key: string,
231 life: WatchLife,
232 reason: WatchEndReason,
233 ) {
234 lives.delete(key);
235 const now = yield* Clock.currentTimeMillis;
236 const quietMs = now - life.pushedAt;
237 yield* Effect.logInfo("pull request watch ended", {
238 threadId: life.threadId,
239 pullRequest: life.pullRequest,
240 reason,
241 minutes: minutes(now - life.startedAt),
242 quietMinutes: minutes(quietMs),
243 longestQuietMinutes: minutes(Math.max(life.longestQuietMs, quietMs)),
244 wakes: life.wakes,
245 reads: life.reads,
246 partial: life.startedAt < bootedAt,
247 });
248 });
249 const ended = (target: WatchTarget, reason: WatchEndReason) =>
250 Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason));
251​
252 const readFailures = new Map<string, number>();
253 const lastReads = new Map<string, LastRead>();
254 const threadTails = new Map<
255 string,
256 {
257 readonly fetchedAt: number;
258 readonly visibleThrough: number;
259 readonly tails: ReadonlyMap<
260 string,
261 { readonly count: number; readonly comments: ReadonlyArray<PullRequestComment> }
262 >;
263 }
264 >();
265​
266 const identityOf = (link: ThreadPullRequestLink) => ({
267 host: normalizeThreadPullRequestKey(link).host,
268 repository: link.repository,
269 number: link.number,
270 });
271​
272 /**
273 * The orchestrator applies this only while the same watch is on, so a stop or restart
274 * that lands during the host read wins.
275 */
276 const record = Effect.fn("PullRequestWatchReactor.record")(function* (
277 target: WatchTarget,
278 next: ThreadPullRequestWatch | null,
279 wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
280 endedWatch?: ThreadPullRequestWatch,
281 ) {
282 const uuid = yield* random.uuidV4();
283 yield* engine.dispatch({
284 type: "thread.pull-request-watch.sync",
285 commandId: CommandId.make(`server:pr-watch:${target.thread.id}:${uuid}`),
286 threadId: target.thread.id,
287 ...identityOf(target.link),
288 startedAt: target.watch.startedAt,
289 watch: next,
290 ...(endedWatch === undefined ? {} : { endedWatch }),
291 ...(wake === undefined
292 ? {}
293 : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
294 });
295 });
296​
297 const giveUp = (target: WatchTarget) =>
298 record(target, null, {
299 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.`,
300 notification: {
301 source: { kind: "monitor" },
302 outcome: "failed",
303 summary: `#${target.link.number}: stopped watching, could not read it`,
304 },
305 }).pipe(
306 Effect.tap(() => woke(target)),
307 Effect.catch(() => record(target, null)),
308 Effect.tap(() => ended(target, "unreadable")),
309 );
310​
311 const readRemarks = Effect.fn("PullRequestWatchReactor.readRemarks")(
312 function* (
313 key: string,
314 reference: PullRequestRef,
315 activity: PullRequestActivity,
316 now: number,
317 rereadMs: number,
318 ) {
319 // Comment cursors cannot account for missing threads. Only finish a truncated read
320 // when the host confirms that every thread was listed.
321 if (activity.commentsTruncated && activity.reviewThreadsTruncated !== false) return null;
322​
323 const visibleThrough = activity.comments.reduce(
324 (latest, comment) => Math.max(latest, Date.parse(comment.editedAt ?? comment.createdAt)),
325 0,
326 );
327 const paginated = activity.reviewThreads.filter(
328 (thread) => thread.nextCommentsCursor != null,
329 );
330 const cached = threadTails.get(key);
331 // All tails share one watermark, so newer visible remarks or a changed thread must
332 // refresh the entire group before any remarks can advance it.
333 const reuse =
334 cached !== undefined &&
335 now - cached.fetchedAt < rereadMs &&
336 cached.visibleThrough === visibleThrough &&
337 cached.tails.size === paginated.length &&
338 paginated.every(
339 (thread) => cached.tails.get(thread.id)?.count === (thread.commentCount ?? 0),
340 );
341 const tails = new Map<
342 string,
343 { count: number; comments: ReadonlyArray<PullRequestComment> }
344 >();
345 const remarks = [...activity.comments];
346 for (const thread of paginated) {
347 let cursor = thread.nextCommentsCursor ?? null;
348 const count = thread.commentCount ?? 0;
349 let tail = reuse ? cached.tails.get(thread.id) : undefined;
350 if (tail === undefined) {
351 const comments = new Map<string, PullRequestComment>();
352 const cursors = new Set<string>();
353 while (cursor !== null) {
354 if (cursors.has(cursor)) return null;
355 cursors.add(cursor);
356 const page: PullRequestThreadCommentsResult = yield* pullRequests.threadComments({
357 ...reference,
358 threadId: thread.id,
359 cursor,
360 });
361 for (const comment of page.comments) {
362 comments.set(comment.id, {
363 ...comment,
364 kind: "review-comment",
365 path: thread.path,
366 reviewState: null,
367 });
368 }
369 cursor = page.nextCursor;
370 }
371 if (thread.comments.length + comments.size < count) return null;
372 tail = { count, comments: [...comments.values()] };
373 }
374 tails.set(thread.id, tail);
375 remarks.push(...tail.comments);
376 }
377 threadTails.set(key, {
378 fetchedAt: reuse ? cached.fetchedAt : now,
379 visibleThrough,
380 tails,
381 });
382 return remarks.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
383 },
384 Effect.catch((error) =>
385 Effect.logWarning("pull request watch comment pagination failed", { error }).pipe(
386 Effect.as(null),
387 ),
388 ),
389 (effect, key) =>
390 effect.pipe(
391 Effect.onExit((exit) =>
392 Effect.sync(() => {
393 // A retry must refresh every tail before advancing the shared remark watermark.
394 if (Exit.isFailure(exit) || exit.value === null) threadTails.delete(key);
395 }),
396 ),
397 ),
398 );
399​
400 const closed = (target: WatchTarget) =>
401 record(target, null, {
402 text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
403 notification: {
404 source: { kind: "monitor" },
405 outcome: "updated",
406 summary: `#${target.link.number}: closed, stopped watching`,
407 },
408 }).pipe(
409 Effect.tap(() => woke(target)),
410 Effect.tap(() => ended(target, "closed")),
411 );
412​
413 const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
414 link.snapshot?.state === "merged"
415 ? "merged"
416 : thread.settledOverride === "settled" || thread.settledAt !== null
417 ? "settled"
418 : thread.lineage.relationshipToParent === "subagent"
419 ? "subagent"
420 : undefined;
421​
422 const eachTarget = <E>(
423 group: WatchGroup,
424 step: (target: WatchTarget) => Effect.Effect<void, E>,
425 ) =>
426 Effect.forEach(group.targets, (target) =>
427 step(target).pipe(
428 Effect.as(true),
429 Effect.catchCause((cause) => {
430 lastReads.delete(group.key);
431 return logFailure("pull request watch update failed", {
432 threadId: target.thread.id,
433 pullRequest: group.key,
434 })(cause).pipe(Effect.as(false));
435 }),
436 ),
437 ).pipe(Effect.map((landed) => landed.every(Boolean)));
438​
439 const referenceOf = (group: WatchGroup) => {
440 const first = group.targets[0]!;
441 return { projectId: first.thread.projectId, ...identityOf(first.link) };
442 };
443​
444 const fingerprintOf = (group: WatchGroup) =>
445 pullRequests.watchFingerprint(referenceOf(group)).pipe(
446 Effect.catchCause(
447 (cause): Effect.Effect<ProviderChangeRequestWatchFingerprint | null | "paused"> =>
448 Cause.hasInterruptsOnly(cause)
449 ? Effect.interrupt
450 : providerFailureReason(cause) === "rate-limited"
451 ? Effect.succeed("paused")
452 : Effect.logDebug("pull request watch fingerprint failed", {
453 pullRequest: group.key,
454 cause,
455 }).pipe(Effect.as(null)),
456 ),
457 );
458​
459 const readGroup = Effect.fn("PullRequestWatchReactor.readGroup")(function* (
460 group: WatchGroup,
461 fingerprint: ProviderChangeRequestWatchFingerprint | null,
462 ) {
463 const now = yield* Clock.currentTimeMillis;
464 const last = lastReads.get(group.key);
465 const plan = planRead(group, last, fingerprint, now);
466 if (!plan.detail) return;
467 if (
468 last === undefined ||
469 group.targets.some((target) => !last.watches.has(watchKey(target))) ||
470 (fingerprint !== null && last.remarks !== fingerprint.remarks)
471 ) {
472 // A new watch or changed host remarks needs a fresh view of every tail.
473 threadTails.delete(group.key);
474 }
475 const reference = referenceOf(group);
476 // Invalidate cached reads before using the newer fingerprint; clients receive no notification.
477 if (fingerprint !== null) yield* pullRequests.invalidate({ reference });
478 const [detailRead, activityRead] = yield* Effect.all(
479 [
480 Effect.exit(pullRequests.detail({ ...reference, allowStale: false })),
481 Effect.exit(
482 plan.activity
483 ? pullRequests.activity(reference).pipe(Effect.asSome)
484 : Effect.succeed(Option.none<PullRequestActivity>()),
485 ),
486 ],
487 { concurrency: 2 },
488 );
489 // Activity failures must not cancel or hide a permanent detail failure.
490 const read = Exit.isFailure(detailRead)
491 ? Exit.failCause(detailRead.cause)
492 : Exit.isFailure(activityRead)
493 ? Exit.failCause(activityRead.cause)
494 : Exit.succeed([detailRead.value, activityRead.value] as const);
495 if (Exit.isFailure(read)) {
496 if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause);
497 lastReads.delete(group.key);
498 const reason = providerFailureReason(read.cause);
499 if (reason === "rate-limited") return;
500 // Transport and host failures can outlast the failure limit; keep the watch for recovery.
501 if (reason === "failed") {
502 readFailures.delete(group.key);
503 return yield* Effect.failCause(read.cause);
504 }
505 const failures = (readFailures.get(group.key) ?? 0) + 1;
506 readFailures.set(group.key, failures);
507 if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) {
508 readFailures.delete(group.key);
509 }
510 return yield* Effect.failCause(read.cause);
511 }
512 readFailures.delete(group.key);
513 const [detail, activity] = read.value;
514 for (const target of group.targets) {
515 const life = lifeOf(target);
516 const headSha = detail.headSha ?? life.headSha;
517 const pushed = life.headSha !== null && headSha !== life.headSha;
518 lives.set(lifeKey(target), {
519 ...life,
520 headSha,
521 reads: life.reads + 1,
522 ...(pushed
523 ? { pushedAt: now, longestQuietMs: Math.max(life.longestQuietMs, now - life.pushedAt) }
524 : {}),
525 });
526 }
527 if (detail.state !== "open") {
528 lastReads.delete(group.key);
529 return yield* eachTarget(group, (target) =>
530 detail.state === "closed"
531 ? closed(target)
532 : record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
533 );
534 }
535​
536 // Never advance the remark watermark past comments an incomplete read could have missed.
537 const remarks = Option.isSome(activity)
538 ? yield* readRemarks(
539 group.key,
540 reference,
541 activity.value,
542 now,
543 fingerprint === null ? QUIET_REREAD_MS : FINGERPRINT_REREAD_MS,
544 )
545 : null;
546 lastReads.set(group.key, {
547 at:
548 plan.activity || last === undefined
549 ? (threadTails.get(group.key)?.fetchedAt ?? now)
550 : last.at,
551 fingerprint: group.fingerprint,
552 inFlight:
553 detail.mergeability === "unknown" ||
554 detail.checks.some((check) => check.status === "pending"),
555 remarksComplete: plan.activity ? remarks !== null : (last?.remarksComplete ?? false),
556 watches: new Set(group.targets.map(watchKey)),
557 status: fingerprint?.status ?? null,
558 remarks: fingerprint?.remarks ?? null,
559 });
560 yield* eachTarget(group, (target) => {
561 const report = evaluatePullRequestWatch(target.watch, detail, remarks, now);
562 if (report.changes.length > 0) {
563 const wake = pullRequestWatchMessage({
564 number: target.link.number,
565 url: target.link.url,
566 baseBranch: detail.baseBranch,
567 headSha: report.next.headSha,
568 report,
569 });
570 // An ending watch keeps what this pass saw, so watching again starts from it.
571 return (
572 report.exhausted
573 ? record(target, null, wake, report.next)
574 : record(target, report.next, wake)
575 ).pipe(
576 Effect.tap(() => woke(target)),
577 Effect.tap(() => (report.exhausted ? ended(target, "comment-limit") : Effect.void)),
578 );
579 }
580 return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
581 });
582 });
583​
584 const sweep = Effect.gen(function* () {
585 const threads = yield* projections.getThreadsWithPullRequests();
586 const targets = threads.flatMap((thread) =>
587 visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
588 link.watch === undefined ? [] : [{ thread, link, watch: link.watch }],
589 ),
590 );
591 const present = new Set(targets.map(lifeKey));
592 yield* Effect.forEach(
593 [...lives].filter(([key]) => !present.has(key)),
594 ([key, life]) => reportEnd(key, life, "stopped"),
595 { discard: true },
596 );
597 for (const target of targets) lifeOf(target);
598 const byPullRequest = new Map<string, Array<WatchTarget>>();
599 const ending: Array<readonly [WatchTarget, WatchEndReason]> = [];
600 for (const target of targets) {
601 const reason = endsWithoutRead(target);
602 if (reason !== undefined) {
603 ending.push([target, reason]);
604 continue;
605 }
606 // Group by project because checkout access differs; one failure must not end another project's watches.
607 const key = `${target.thread.projectId} ${threadPullRequestKeyOf(target.link)}`;
608 byPullRequest.set(key, [...(byPullRequest.get(key) ?? []), target]);
609 }
610 const groups = [...byPullRequest].map(([key, members]): WatchGroup => ({
611 key,
612 targets: members,
613 fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"),
614 }));
615 for (const cache of [readFailures, lastReads, threadTails]) {
616 for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
617 }
618 yield* Effect.forEach(
619 ending,
620 ([target, reason]) =>
621 record(target, null).pipe(
622 Effect.tap(() => ended(target, reason)),
623 Effect.catchCause(
624 logFailure("pull request watch stop failed", {
625 threadId: target.thread.id,
626 pullRequest: threadPullRequestKeyOf(target.link),
627 }),
628 ),
629 ),
630 { discard: true },
631 );
632 // Every fingerprint is asked for at once so the host can batch them, and each group reads
633 // as soon as its own answer lands rather than waiting on the slowest host.
634 const reads = yield* Semaphore.make(GROUP_READS);
635 yield* Effect.forEach(
636 groups,
637 (group) =>
638 fingerprintOf(group).pipe(
639 Effect.flatMap((fingerprint) =>
640 fingerprint === "paused"
641 ? Effect.void
642 : reads.withPermit(
643 readGroup(group, fingerprint).pipe(
644 Effect.catchCause(
645 logFailure("pull request watch check failed", { pullRequest: group.key }),
646 ),
647 ),
648 ),
649 ),
650 ),
651 { concurrency: "unbounded", discard: true },
652 );
653 }).pipe(
654 Effect.catchCause(logFailure("pull request watch sweep failed", {})),
655 Effect.withSpan("PullRequestWatchReactor.sweep"),
656 );
657​
658 const start: PullRequestWatchReactor["Service"]["start"] = () =>
659 forkParked(
660 sweep.pipe(Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)), Effect.asVoid),
661 );
662​
663 return { start, sweep } satisfies PullRequestWatchReactor["Service"];
664});
665​
666export const layer = Layer.effect(PullRequestWatchReactor, make);