Open History to see the last commit
1import {
2 CommandId,
3 type PullRequestSummary,
4 type ThreadId,
5 type ThreadPullRequestKey,
6 type ThreadPullRequestLink,
7 type ThreadPullRequestSnapshot,
8 type ThreadPullRequestStack,
9} from "@t3tools/contracts";
10import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11import {
12 threadPullRequestKeyOf,
13 normalizeThreadPullRequestKey,
14 threadPullRequestKeysEqual,
15 visibleThreadPullRequests,
16} from "../sourceControl/threadPullRequests.ts";
17import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
18import * as Cause from "effect/Cause";
19import * as Clock from "effect/Clock";
20import * as Context from "effect/Context";
21import * as Crypto from "effect/Crypto";
22import * as DateTime from "effect/DateTime";
23import * as Effect from "effect/Effect";
24import * as Layer from "effect/Layer";
25import * as Schema from "effect/Schema";
26import * as Schedule from "effect/Schedule";
27import type * as Scope from "effect/Scope";
28import * as Semaphore from "effect/Semaphore";
29import * as Stream from "effect/Stream";
30
31import * as GitManager from "../git/GitManager.ts";
32import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider";
33import * as PullRequestService from "../pullRequest/PullRequestService.ts";
34import { forkParked } from "../serverActivation.ts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ProjectionStore from "./ProjectionStore.ts";
37import { isTerminalRunStatus } from "./ThreadManagementService.ts";
38
39const SLOW_SYNC_INTERVAL_MS = 15 * 60 * 1_000;
40// Every server polls every open linked pull request, and most of them sit untouched for days.
41// One nobody has updated for QUIET_AFTER_MS is read on the quiet cadence instead of each sweep;
42// requested refreshes, watches and a host CLI's merge command still read it at once.
43const QUIET_AFTER_MS = 30 * 60 * 1_000;
44const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000;
45
46const isChangeRequestCloseCommand = (command: string) =>
47 sourceControlDefinitions.definitions.some(
48 (definition) => definition.changeRequestCloseCommand?.test(command) === true,
49 );
50
51const isPullRequestProviderError = Schema.is(PullRequestProviderError);
52
53type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
54
55interface LinkEntry {
56 readonly thread: ProjectionStore.ProjectionThreadPullRequests;
57 readonly link: ThreadPullRequestLink;
58}
59
60/** Another layer of the stack `url` belongs to, in its host's canonical shape. */
61function siblingChangeRequestUrl(url: string, number: number): string | null {
62 if (!Number.isSafeInteger(number) || number < 1) return null;
63 const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
64 if (parsed === null) return null;
65 const { definition, link } = parsed;
66 return definition.changeRequestUrl({
67 host: link.host,
68 repository: link.repository,
69 number,
70 webUrl: link.repositoryUrl,
71 });
72}
73
74function snapshotFieldsOf(summary: PullRequestSummary): SnapshotFields {
75 return {
76 state: summary.state,
77 title: summary.title,
78 headBranch: summary.headBranch,
79 baseBranch: summary.baseBranch,
80 isDraft: summary.isDraft ?? false,
81 updatedAt: summary.updatedAt,
82 closedAt: summary.closedAt ?? null,
83 mergedAt: summary.mergedAt ?? null,
84 ...(summary.author === undefined ? {} : { author: summary.author }),
85 ...(summary.additions === undefined ? {} : { additions: summary.additions }),
86 ...(summary.deletions === undefined ? {} : { deletions: summary.deletions }),
87 ...(summary.changedFiles === undefined ? {} : { changedFiles: summary.changedFiles }),
88 ...(summary.reviewDecision === undefined ? {} : { reviewDecision: summary.reviewDecision }),
89 ...(summary.checksState === undefined ? {} : { checksState: summary.checksState }),
90 ...(summary.mergeability === undefined ? {} : { mergeability: summary.mergeability }),
91 };
92}
93
94// Rotating ghe.com avatar tokens should not make otherwise identical snapshots differ.
95function avatarIdentity(avatarUrl: string | null | undefined): string | null {
96 if (avatarUrl === null || avatarUrl === undefined) return null;
97 const url = URL.parse(avatarUrl);
98 if (url === null || (url.hostname !== "ghe.com" && !url.hostname.endsWith(".ghe.com"))) {
99 return avatarUrl;
100 }
101 url.searchParams.delete("token");
102 return url.href;
103}
104
105function snapshotFieldsEqual(left: SnapshotFields, right: SnapshotFields): boolean {
106 return (
107 left.state === right.state &&
108 left.title === right.title &&
109 left.headBranch === right.headBranch &&
110 left.baseBranch === right.baseBranch &&
111 left.isDraft === right.isDraft &&
112 left.updatedAt === right.updatedAt &&
113 (left.closedAt ?? null) === (right.closedAt ?? null) &&
114 (left.mergedAt ?? null) === (right.mergedAt ?? null) &&
115 (left.author?.login ?? null) === (right.author?.login ?? null) &&
116 avatarIdentity(left.author?.avatarUrl) === avatarIdentity(right.author?.avatarUrl) &&
117 left.additions === right.additions &&
118 left.deletions === right.deletions &&
119 left.changedFiles === right.changedFiles &&
120 (left.reviewDecision ?? null) === (right.reviewDecision ?? null) &&
121 (left.checksState ?? null) === (right.checksState ?? null) &&
122 left.mergeability === right.mergeability
123 );
124}
125
126function stacksEqual(
127 left: ThreadPullRequestStack | null,
128 right: ThreadPullRequestStack | null,
129): boolean {
130 if (left === null || right === null) return left === right;
131 return (
132 left.kind === right.kind &&
133 left.id === right.id &&
134 left.number === right.number &&
135 left.url === right.url &&
136 left.base === right.base &&
137 left.layers.length === right.layers.length &&
138 left.layers.every((layer, index) => {
139 const other = right.layers[index]!;
140 return (
141 layer.number === other.number &&
142 layer.headBranch === other.headBranch &&
143 layer.state === other.state
144 );
145 })
146 );
147}
148
149/** Stack ids are unique only within a repository, e.g. GitHub's fallback to the stack number. */
150function nativeStackKeyOf(link: ThreadPullRequestLink, stack: ThreadPullRequestStack): string {
151 const key = normalizeThreadPullRequestKey(link);
152 return `${key.host}/${key.repository}#stack:${stack.id}`;
153}
154
155function sameLayerNumbers(left: ThreadPullRequestStack, right: ThreadPullRequestStack): boolean {
156 return (
157 left.layers.length === right.layers.length &&
158 left.layers.every((layer, index) => layer.number === right.layers[index]!.number)
159 );
160}
161
162function skipReason(cause: Cause.Cause<unknown>): string {
163 const error = Cause.squash(cause);
164 return error instanceof Error ? error.message : String(error);
165}
166
167function rateLimitRetryAt(cause: Cause.Cause<unknown>): number | undefined {
168 let error: unknown = Cause.squash(cause);
169 while (error instanceof Error) {
170 if (isPullRequestProviderError(error) && error.reason === "rate-limited") return error.retryAt;
171 error = error.cause;
172 }
173 return undefined;
174}
175
176function isUnsettled(thread: ProjectionStore.ProjectionThreadPullRequests): boolean {
177 return thread.settledOverride !== "settled" && thread.settledAt === null;
178}
179
180export class PullRequestSyncReactor extends Context.Service<
181 PullRequestSyncReactor,
182 {
183 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
184 readonly drain: Effect.Effect<void>;
185 /**
186 * Force the next sweep to re-read this pull request, even when its snapshot is terminal.
187 * While its host is rate limited, the read waits for the first sweep after the pause.
188 */
189 readonly requestSync: (key: ThreadPullRequestKey) => Effect.Effect<void>;
190 }
191>()("t3/orchestration-v2/PullRequestSyncReactor") {}
192
193/** @public Service construction is part of the canonical Effect module API. */
194export const make = Effect.gen(function* () {
195 const engine = yield* Orchestrator.OrchestratorV2;
196 const projections = yield* ProjectionStore.ProjectionStoreV2;
197 const pullRequests = yield* PullRequestService.PullRequestService;
198 const git = yield* GitManager.GitManager;
199 const crypto = yield* Crypto.Crypto;
200
201 const lastSyncedAt = new Map<string, number>();
202 const requested = new Set<string>();
203 // Requests arriving during a host read wait for the next sweep.
204 const pendingRequests = new Set<string>();
205 // PR keys wait in `pendingRequests` for one queued sweep, so a burst of links (an agent
206 // linking dozens of pull requests) is read together and shares the summary batches.
207 let requestedSweepQueued = false;
208 const retryStacks = new Set<string>();
209 // Rate limit pauses by project and host, since each project reads with its own credential.
210 // A paused host refuses every read without asking it, so the sweep leaves its pull requests
211 // due until the pause ends rather than failing each of them every minute.
212 const pausedUntil = new Map<string, number>();
213
214 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {
215 if (requested.has(key) || retryStacks.has(key)) return true;
216 if (entries.some((entry) => entry.link.snapshot === null)) return true;
217 const active = entries.filter((entry) => isUnsettled(entry.thread));
218 // A merged snapshot without its merge time cannot settle the thread, so it keeps the slow
219 // cadence until the host supplies one (Bitbucket snapshots saved before it was read).
220 if (
221 active.every(
222 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt != null,
223 )
224 ) {
225 return false;
226 }
227 const last = lastSyncedAt.get(key);
228 const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last;
229 const open = active.filter((entry) => entry.link.snapshot?.state === "open");
230 if (open.length > 0) {
231 const quiet = open.every((entry) => {
232 const updatedAt = entry.link.snapshot?.updatedAt;
233 return updatedAt != null && nowMs - Date.parse(updatedAt) >= QUIET_AFTER_MS;
234 });
235 return !quiet || sinceLastMs >= QUIET_SYNC_INTERVAL_MS;
236 }
237 return sinceLastMs >= SLOW_SYNC_INTERVAL_MS;
238 };
239
240 const logSkipped =
241 (message: string, fields: Record<string, unknown>) =>
242 <E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
243 Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
244
245 const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (scope: "all" | "requested") {
246 const threads = yield* projections.getThreadsWithPullRequests();
247 const now = yield* DateTime.now;
248 const nowMs = DateTime.toEpochMillis(now);
249 const nowIso = DateTime.formatIso(now);
250
251 const groups = new Map<string, Array<LinkEntry>>();
252 for (const thread of threads) {
253 for (const link of visibleThreadPullRequests(thread.pullRequests ?? [])) {
254 // Reads depend on the project's checkout and credentials, including their failures.
255 const key = `${thread.projectId}\0${threadPullRequestKeyOf(link)}`;
256 const entries = groups.get(key) ?? [];
257 entries.push({ thread, link });
258 groups.set(key, entries);
259 }
260 }
261
262 // A host-level refresh reaches every project, each retaining its own pending retry.
263 for (const [key, entries] of groups) {
264 if (pendingRequests.has(threadPullRequestKeyOf(entries[0]!.link))) requested.add(key);
265 }
266 pendingRequests.clear();
267
268 for (const key of lastSyncedAt.keys()) if (!groups.has(key)) lastSyncedAt.delete(key);
269 for (const key of retryStacks) if (!groups.has(key)) retryStacks.delete(key);
270 for (const key of requested.keys()) if (!groups.has(key)) requested.delete(key);
271
272 const linkedThisSweep = new Set<string>();
273 // Fresh stack reads by group, so a member flagged by a sibling is compared against what the
274 // host answered this sweep, not the saved layers that sibling is about to replace.
275 const stacksReadThisSweep = new Map<string, ThreadPullRequestStack | null>();
276 const persistence = yield* Semaphore.make(1);
277
278 const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
279 entry: LinkEntry,
280 fields: SnapshotFields,
281 fetchedStack: { readonly stack: ThreadPullRequestStack | null } | null,
282 ) {
283 const { thread, link } = entry;
284 const nextStack = fetchedStack === null ? link.stack : fetchedStack.stack;
285 const changed =
286 link.snapshot === null ||
287 !snapshotFieldsEqual(link.snapshot, fields) ||
288 !stacksEqual(link.stack, nextStack);
289 // Persist discovered siblings before a terminal snapshot can trigger settlement. A settled
290 // thread that shares this pull request with an active one takes the fresh snapshot, but
291 // gains no links.
292 for (const layer of isUnsettled(thread) ? (fetchedStack?.stack?.layers ?? []) : []) {
293 const layerKey = {
294 host: normalizeThreadPullRequestKey(link).host,
295 repository: link.repository,
296 number: layer.number,
297 };
298 const dedupeKey = `${thread.id}:${threadPullRequestKeyOf(layerKey)}`;
299 if (linkedThisSweep.has(dedupeKey)) continue;
300 // Tombstones count as present: a dismissed layer is never re-added.
301 if (
302 (thread.pullRequests ?? []).some((existing) =>
303 threadPullRequestKeysEqual(existing, layerKey),
304 )
305 ) {
306 continue;
307 }
308 const url = siblingChangeRequestUrl(link.url, layer.number);
309 if (url === null) continue;
310 const uuid = yield* crypto.randomUUIDv4();
311 yield* engine.dispatch({
312 type: "thread.pull-request.link",
313 commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
314 threadId: thread.id,
315 ...layerKey,
316 url,
317 source: "stack",
318 });
319 linkedThisSweep.add(dedupeKey);
320 }
321 if (changed) {
322 const uuid = yield* crypto.randomUUIDv4();
323 yield* engine.dispatch({
324 type: "thread.pull-request-link.sync",
325 commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
326 threadId: thread.id,
327 host: normalizeThreadPullRequestKey(link).host,
328 repository: link.repository,
329 number: link.number,
330 snapshot: { ...fields, syncedAt: nowIso },
331 stack: nextStack,
332 });
333 }
334 });
335
336 const syncGroup = Effect.fn("PullRequestSyncReactor.syncGroup")(function* (
337 key: string,
338 entries: ReadonlyArray<LinkEntry>,
339 ) {
340 const first = entries[0]!;
341 const ref = {
342 projectId: first.thread.projectId,
343 host: normalizeThreadPullRequestKey(first.link).host,
344 repository: first.link.repository,
345 number: first.link.number,
346 };
347 const refreshRequested = requested.has(key);
348 // A held merged summary is served without asking the host, so a snapshot still missing its
349 // merge time has to drop it or the slow-cadence re-read would hand back the same gap.
350 const missingMergedAt = entries.some(
351 (entry) => entry.link.snapshot?.state === "merged" && entry.link.snapshot.mergedAt == null,
352 );
353 // A stack retry reads past the cache, or it could get back the layer list it is retrying.
354 const invalidated = refreshRequested || missingMergedAt || retryStacks.has(key);
355 if (invalidated) yield* pullRequests.invalidate({ reference: ref });
356 const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });
357 const fields = snapshotFieldsOf(summary);
358 const needsStack =
359 refreshRequested ||
360 retryStacks.has(key) ||
361 entries.some(
362 (entry) =>
363 entry.link.snapshot === null ||
364 !snapshotFieldsEqual(entry.link.snapshot, fields) ||
365 (summary.stack !== undefined &&
366 (entry.link.stack?.number ?? null) !== (summary.stack?.number ?? null)),
367 );
368 const knownUnstacked =
369 summary.stack === null && entries.every((entry) => entry.link.stack === null);
370 // A sibling can flag this group while its summary read is in flight.
371 if (!invalidated && retryStacks.has(key) && !knownUnstacked) {
372 yield* pullRequests.invalidate({ reference: ref });
373 }
374 // The retry this read answers is consumed before the read, not after it: a sibling may
375 // flag this group again while the read is in flight, and that flag must survive to the
376 // next sweep because the answer below may predate the sibling's layers.
377 if (needsStack) retryStacks.delete(key);
378 const fetchedStack = !needsStack
379 ? null
380 : knownUnstacked
381 ? { stack: null }
382 : yield* pullRequests.stack(ref, { includeDetails: false }).pipe(
383 Effect.map((stack) => ({
384 stack: stack === null ? null : ({ kind: "native", ...stack } as const),
385 })),
386 Effect.catchCauseIf(
387 (cause) => !Cause.hasInterruptsOnly(cause),
388 (cause) =>
389 rateLimitRetryAt(cause) !== undefined
390 ? Effect.sync(() => retryStacks.add(key)).pipe(
391 Effect.andThen(Effect.failCause(cause)),
392 )
393 : Effect.logWarning("pull request stack lookup failed", {
394 key,
395 }).pipe(Effect.as(null)),
396 ),
397 );
398 if (needsStack) {
399 if (fetchedStack === null) {
400 retryStacks.add(key);
401 return;
402 }
403 const fetched = fetchedStack.stack;
404 stacksReadThisSweep.set(key, fetched);
405 // A layer pushed above an older member changes none of that member's own fields, so it
406 // would keep its shorter layer list. Members of this stack whose layer list differs read
407 // their stack once, in this sweep if still pending or the next; agreeing ones read none.
408 // Only groups of the same project: another project reads with its own credential and
409 // may see a different layer list, so flagging across projects would never settle.
410 if (fetched !== null) {
411 const fetchedKey = nativeStackKeyOf(first.link, fetched);
412 for (const [siblingKey, siblingEntries] of groups) {
413 if (siblingKey === key) continue;
414 if (siblingEntries[0]!.thread.projectId !== first.thread.projectId) continue;
415 const readThisSweep = stacksReadThisSweep.get(siblingKey);
416 const stale = siblingEntries.some(({ link }) => {
417 const stack = readThisSweep === undefined ? link.stack : readThisSweep;
418 return (
419 stack !== null &&
420 nativeStackKeyOf(link, stack) === fetchedKey &&
421 !sameLayerNumbers(stack, fetched)
422 );
423 });
424 if (stale) retryStacks.add(siblingKey);
425 }
426 }
427 }
428 // The host answered, so the cadence clock ticks even if a dispatch below is rejected.
429 lastSyncedAt.set(key, nowMs);
430 requested.delete(key);
431 yield* Effect.forEach(
432 entries,
433 (entry) =>
434 syncEntry(entry, fields, fetchedStack).pipe(
435 persistence.withPermits(1),
436 Effect.catchCause((cause) => {
437 if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
438 return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
439 cause,
440 );
441 }),
442 ),
443 { discard: true },
444 );
445 });
446
447 const skips = new Map<string, { count: number; readonly key: string }>();
448 const readGroup = (key: string, entries: ReadonlyArray<LinkEntry>, pauseKey: string) =>
449 syncGroup(key, entries).pipe(
450 Effect.catchCause((cause) => {
451 if (Cause.hasInterruptsOnly(cause)) return Effect.failCause(cause);
452 const retryAt = rateLimitRetryAt(cause);
453 if (retryAt !== undefined) {
454 pausedUntil.set(pauseKey, Math.max(retryAt, pausedUntil.get(pauseKey) ?? 0));
455 }
456 const reason = skipReason(cause);
457 const skip = skips.get(reason);
458 if (skip === undefined) skips.set(reason, { count: 1, key });
459 else skip.count += 1;
460 return Effect.void;
461 }),
462 );
463 yield* Effect.forEach(
464 groups,
465 ([key, entries]) => {
466 if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) {
467 return Effect.void;
468 }
469 const first = entries[0]!;
470 const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`;
471 // Checked against the clock as each read starts, so a pause found earlier in this sweep
472 // holds the rest, and one that ends during the sweep lets the rest through.
473 return Clock.currentTimeMillis.pipe(
474 Effect.flatMap((startedAtMs) =>
475 (pausedUntil.get(pauseKey) ?? 0) > startedAtMs
476 ? Effect.void
477 : readGroup(key, entries, pauseKey),
478 ),
479 );
480 },
481 // As wide as one batched summary read, so the sweep's reads on a host arrive together and
482 // GitHub answers them in one request rather than one `gh pr view` apiece.
483 { concurrency: 25, discard: true },
484 );
485 for (const [reason, { count, key }] of skips) {
486 yield* Effect.logWarning("pull request sync skipped", { count, key, reason });
487 }
488 });
489
490 const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
491 Effect.suspend(() => {
492 if (scope === "requested") requestedSweepQueued = false;
493 return sweep(scope);
494 }).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
495 );
496
497 const closeCommandThreads = new Set<ThreadId>();
498 const refreshOpenLinks = (threadId: ThreadId) =>
499 projections.getThreadsWithPullRequests(threadId).pipe(
500 Effect.flatMap((threads) =>
501 Effect.forEach(
502 threads.flatMap((thread) =>
503 visibleThreadPullRequests(thread.pullRequests ?? []).filter(
504 (link) => link.snapshot?.state === "open",
505 ),
506 ),
507 requestSync,
508 { discard: true },
509 ),
510 ),
511 Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
512 );
513
514 const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
515 "PullRequestSyncReactor.start",
516 )(function* () {
517 const events = engine.streamDomainEvents;
518 const stateChanges = Stream.merge(
519 yield* pullRequests.subscribeStateChanges,
520 yield* git.subscribePullRequestStateChanges,
521 );
522 yield* forkParked(
523 Stream.runForEach(stateChanges, requestSync).pipe(
524 Effect.catchCause(logSkipped("pull request state change stream failed", {})),
525 ),
526 );
527 yield* forkParked(
528 Stream.runForEach(events, (event) => {
529 switch (event.type) {
530 case "thread.pull-request-link-updated":
531 return event.payload.snapshot === null ? requestSync(event.payload) : Effect.void;
532 case "thread.pull-request-synced":
533 return Effect.forEach(
534 visibleThreadPullRequests(event.payload.pullRequests ?? []).filter(
535 (link) => link.snapshot === null,
536 ),
537 requestSync,
538 { discard: true },
539 );
540 // An agent can merge or close its pull request from a shell with its host's CLI, which
541 // sends no merge notification. When a run that ran such a command ends, read the
542 // thread's open links fresh, so settlement does not wait for the next sweep and the
543 // cached summary. Other runs add no host reads.
544 case "turn-item.updated":
545 if (
546 event.payload.type === "command_execution" &&
547 isChangeRequestCloseCommand(event.payload.input)
548 ) {
549 closeCommandThreads.add(event.threadId);
550 }
551 return Effect.void;
552 case "run.updated":
553 return isTerminalRunStatus(event.payload.status) &&
554 closeCommandThreads.delete(event.threadId)
555 ? refreshOpenLinks(event.threadId)
556 : Effect.void;
557 default:
558 return Effect.void;
559 }
560 }).pipe(Effect.catchCause(logSkipped("pull request sync event stream failed", {}))),
561 );
562 yield* forkParked(
563 Effect.gen(function* () {
564 yield* worker.enqueue("all");
565 yield* worker.drain;
566 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
567 );
568 });
569
570 const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
571 Effect.suspend(() => {
572 pendingRequests.add(threadPullRequestKeyOf(key));
573 if (requestedSweepQueued) return Effect.void;
574 requestedSweepQueued = true;
575 return worker.enqueue("requested");
576 });
577
578 return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
579});
580
581export const layer = Layer.effect(PullRequestSyncReactor, make);