fix(server): propagate linked pr changes and settle threads immediately (#12161)

This commit is contained in:
maria authored and GitHub committed 2026-09-16 22:22:08 -03:00
1 parent c12ba7581a
commit 19ee856ec0
8 files changed
+617 -102

No files matched your search

@@ -1,9 +1,11 @@
import {
EventId,
ProjectId,
ProviderInstanceId,
PullRequestOperationError,
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationProjectShell,
type OrchestrationShellSnapshot,
type OrchestrationThreadShell,
@@ -18,6 +20,7 @@ import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
@@ -31,6 +34,7 @@ import {
} from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts";
import { resolveAutoSettlementAt } from "./ThreadSettlementPolicy.ts";
const NOW = "2026-08-28T12:00:00.000Z";
const PROJECT_ID = ProjectId.make("sync-project");
@@ -152,6 +156,7 @@ function makeSummary(
}
interface HarnessOptions {
readonly onDispatch?: (command: SyncCommand | LinkCommand) => Effect.Effect<void>;
readonly invalidate?: PullRequestService["Service"]["invalidate"];
readonly snapshot: OrchestrationShellSnapshot;
readonly summary?: (
@@ -165,6 +170,7 @@ interface HarnessOptions {
const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) {
const activation = yield* Deferred.make<void>();
const snapshots = yield* Ref.make(options.snapshot);
const events = yield* PubSub.unbounded<OrchestrationEvent>();
const snapshotReads = yield* Queue.unbounded<void>();
const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
@@ -188,11 +194,13 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
if (command.type === "thread.pull-request-link.sync") {
return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe(
Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
Effect.as({ sequence: 1 }),
);
}
if (command.type === "thread.pull-request.link") {
return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe(
Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
Effect.as({ sequence: 1 }),
);
}
@@ -213,6 +221,9 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
readEvents: () => Stream.empty,
dispatch,
streamDomainEvents: Stream.empty,
subscribeDomainEvents: PubSub.subscribe(events).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
latestSequence: Effect.succeed(0),
}),
Layer.succeed(ServerActivation, Deferred.await(activation)),
@@ -220,6 +231,7 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
);
return {
events,
activation,
snapshots,
snapshotReads,
@@ -274,6 +286,42 @@ function applySync(
}
describe("PullRequestSyncReactor", () => {
it.effect("syncs a newly linked merged PR without waiting for the periodic sweep", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fixture = yield* makeHarness({
snapshot: makeSnapshot([makeThread("one")]),
summary: (input) =>
Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
const link = makeLink(42);
yield* Ref.set(
fixture.snapshots,
makeSnapshot([makeThread("one", { pullRequests: [link] })]),
);
yield* PubSub.publish(fixture.events, {
type: "thread.pull-request-linked",
sequence: 2,
eventId: EventId.make("linked"),
aggregateKind: "thread",
aggregateId: ThreadId.make("one"),
occurredAt: NOW,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
payload: { threadId: ThreadId.make("one"), link, updatedAt: NOW },
});
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.snapshot.state, "merged");
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("retries a failed stack read after the summary becomes terminal", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -303,6 +351,7 @@ describe("PullRequestSyncReactor", () => {
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
const commands = yield* Ref.get(fixture.syncCommands);
assert.deepStrictEqual(commands, []);
yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
yield* sweepAgain(fixture, reactor);
assert.strictEqual(attempts, 2);
@@ -315,6 +364,85 @@ describe("PullRequestSyncReactor", () => {
),
);
it.effect("retries a failed sibling link before publishing a terminal snapshot", () =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
let failSibling = true;
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("one", { pullRequests: [makeLink(7, { state: "closed" })] }),
]),
summary: (input) =>
Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
stack: () =>
Effect.succeed({
id: "stack",
number: 7,
url: "https://github.com/owner/repository/stacks/7",
base: "main",
layers: [
{ number: 7, headBranch: "feature", state: "merged" },
{ number: 8, headBranch: "sibling", state: "open" },
],
}),
onDispatch: (command) =>
command.type === "thread.pull-request.link" && failSibling
? Effect.die("temporary link failure")
: Effect.void,
});
yield* Effect.gen(function* () {
const reactor = yield* startAndSweep(fixture);
assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
failSibling = false;
yield* sweepAgain(fixture, reactor);
assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.snapshot.state, "merged");
assert.strictEqual((yield* Ref.get(fixture.linkCommands)).at(-1)?.number, 8);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("concurrent stack reads persist a shared sibling once before syncing both roots", () =>
Effect.scoped(
Effect.gen(function* () {
const readsReady = yield* Deferred.make<void>();
let reads = 0;
let linked = false;
const fixture = yield* makeHarness({
snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7), makeLink(8)] })]),
stack: () =>
Effect.gen(function* () {
if (++reads === 2) yield* Deferred.succeed(readsReady, undefined);
yield* Deferred.await(readsReady);
return {
id: "stack",
number: 7,
url: "https://github.com/owner/repository/stacks/7",
base: "main",
layers: [{ number: 9, headBranch: "sibling", state: "open" as const }],
};
}),
onDispatch: (command) =>
Effect.gen(function* () {
if (command.type === "thread.pull-request.link") {
yield* Effect.yieldNow;
assert.strictEqual(linked, false);
linked = true;
} else {
assert.strictEqual(linked, true);
}
}),
});
yield* Effect.gen(function* () {
yield* startAndSweep(fixture);
assert.strictEqual((yield* Ref.get(fixture.linkCommands)).length, 1);
assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 2);
}).pipe(Effect.provide(fixture.layer));
}),
),
);
it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -656,20 +784,38 @@ describe("PullRequestSyncReactor", () => {
base: "main",
layers: [
{ number: 41, headBranch: "layer-1", state: "merged" },
{ number: 42, headBranch: "layer-2", state: "open" },
{ number: 42, headBranch: "layer-2", state: "merged" },
{ number: 43, headBranch: "layer-3", state: "open" },
],
};
let thread = makeThread("one", {
pullRequests: [
makeLink(42, { state: "open" }),
makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
],
});
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("one", {
pullRequests: [
makeLink(42),
makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
],
}),
]),
snapshot: makeSnapshot([thread]),
summary: (input) =>
Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
stack: () => Effect.succeed(stack),
onDispatch: (command) =>
Effect.sync(() => {
thread =
command.type === "thread.pull-request.link"
? { ...thread, pullRequests: [...thread.pullRequests, makeLink(command.number)] }
: applySync(makeSnapshot([thread]), [command]).threads[0]!;
// Every projected event may wake settlement, including the terminal root update.
assert.isNull(
resolveAutoSettlementAt({
thread,
pullRequest: null,
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: true,
}),
);
}),
});
yield* Effect.gen(function* () {
@@ -23,6 +23,8 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as PullRequestService from "../pullRequest/PullRequestService.ts";
import { forkParked } from "../serverActivation.ts";
@@ -150,7 +152,7 @@ export const make = Effect.gen(function* () {
<E>(cause: Cause.Cause<E>): Effect.Effect<void, E> =>
Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.logWarning(message, fields);
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* () {
const sweep = Effect.fn("PullRequestSyncReactor.sweep")(function* (requestedKey?: string) {
const snapshot = yield* snapshots.getShellSnapshot();
const now = yield* DateTime.now;
const nowMs = DateTime.toEpochMillis(now);
@@ -174,6 +176,7 @@ export const make = Effect.gen(function* () {
// Layers auto-linked this sweep, so two links of one thread that share a
// stack do not both try to add the same sibling.
const linkedThisSweep = new Set<string>();
const persistence = yield* Semaphore.make(1);
const syncEntry = Effect.fn("PullRequestSyncReactor.syncEntry")(function* (
entry: LinkEntry,
@@ -186,21 +189,8 @@ export const make = Effect.gen(function* () {
link.snapshot === null ||
!snapshotFieldsEqual(link.snapshot, fields) ||
!stacksEqual(link.stack, nextStack);
if (changed) {
const uuid = yield* crypto.randomUUIDv4;
yield* engine.dispatch({
type: "thread.pull-request-link.sync",
commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
threadId: thread.id,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
snapshot: { ...fields, syncedAt: nowIso },
stack: nextStack,
});
}
if (fetchedStack === null || fetchedStack.stack === null) return;
for (const layer of fetchedStack.stack.layers) {
// Persist discovered siblings before a terminal snapshot can trigger settlement.
for (const layer of fetchedStack?.stack?.layers ?? []) {
const layerKey = {
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
@@ -216,25 +206,29 @@ export const make = Effect.gen(function* () {
}
const url = siblingPullRequestUrl(link.url, layer.number);
if (url === null) continue;
linkedThisSweep.add(dedupeKey);
const uuid = yield* crypto.randomUUIDv4;
yield* engine
.dispatch({
type: "thread.pull-request.link",
commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
threadId: thread.id,
...layerKey,
url,
source: "stack",
})
.pipe(
Effect.catchCause(
logSkipped("pull request stack layer link skipped", {
threadId: thread.id,
number: layer.number,
}),
),
);
yield* engine.dispatch({
type: "thread.pull-request.link",
commandId: CommandId.make(`server:pr-stack-link:${thread.id}:${uuid}`),
threadId: thread.id,
...layerKey,
url,
source: "stack",
});
linkedThisSweep.add(dedupeKey);
}
if (changed) {
const uuid = yield* crypto.randomUUIDv4;
yield* engine.dispatch({
type: "thread.pull-request-link.sync",
commandId: CommandId.make(`server:pr-sync:${thread.id}:${uuid}`),
threadId: thread.id,
host: normalizeThreadPullRequestKey(link).host,
repository: link.repository,
number: link.number,
snapshot: { ...fields, syncedAt: nowIso },
stack: nextStack,
});
}
});
@@ -275,8 +269,11 @@ export const make = Effect.gen(function* () {
)
: null;
if (needsStack) {
if (fetchedStack === null) retryStacks.add(key);
else retryStacks.delete(key);
if (fetchedStack === null) {
retryStacks.add(key);
return;
}
retryStacks.delete(key);
}
// The host answered, so the cadence clock ticks even if a dispatch below is rejected.
lastSyncedAt.set(key, nowMs);
@@ -286,9 +283,13 @@ export const make = Effect.gen(function* () {
entries,
(entry) =>
syncEntry(entry, fields, fetchedStack).pipe(
Effect.catchCause(
logSkipped("pull request sync skipped", { threadId: entry.thread.id, key }),
),
persistence.withPermits(1),
Effect.catchCause((cause) => {
if (!Cause.hasInterruptsOnly(cause)) retryStacks.add(key);
return logSkipped("pull request sync skipped", { threadId: entry.thread.id, key })(
cause,
);
}),
),
{ discard: true },
);
@@ -297,7 +298,7 @@ export const make = Effect.gen(function* () {
yield* Effect.forEach(
groups,
([key, entries]) =>
isDue(key, entries, nowMs)
(requestedKey === undefined || requestedKey === key) && isDue(key, entries, nowMs)
? syncGroup(key, entries).pipe(
Effect.catchCause(logSkipped("pull request sync skipped", { key })),
)
@@ -306,13 +307,19 @@ export const make = Effect.gen(function* () {
);
});
const worker = yield* makeDrainableWorker(() =>
sweep().pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
const worker = yield* makeDrainableWorker((key: string | undefined) =>
sweep(key).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
);
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
"PullRequestSyncReactor.start",
)(function* () {
const events = yield* engine.subscribeDomainEvents;
yield* forkParked(
Stream.runForEach(events, (event) =>
event.type === "thread.pull-request-linked" ? requestSync(event.payload.link) : Effect.void,
),
);
yield* forkParked(
Effect.gen(function* () {
yield* worker.enqueue(undefined);
@@ -323,8 +330,9 @@ export const make = Effect.gen(function* () {
const requestSync: PullRequestSyncReactor["Service"]["requestSync"] = (key) =>
Effect.suspend(() => {
requested.set(threadPullRequestKeyOf(key), ++requestGeneration);
return worker.enqueue(undefined);
const syncKey = threadPullRequestKeyOf(key);
requested.set(syncKey, ++requestGeneration);
return worker.enqueue(syncKey);
});
return { start, drain: worker.drain, requestSync } satisfies PullRequestSyncReactor["Service"];
@@ -1,10 +1,12 @@
import {
DEFAULT_SERVER_SETTINGS,
EventId,
ProjectId,
ProviderInstanceId,
PullRequestOperationError,
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationProjectShell,
type OrchestrationShellSnapshot,
type OrchestrationThreadShell,
@@ -171,6 +173,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
const settingsReads = yield* Queue.unbounded<ServerSettings>();
const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
const domainEvents = yield* PubSub.unbounded<OrchestrationEvent>();
const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
const branchCalls = yield* Ref.make<
ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
@@ -258,6 +261,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
readEvents: () => Stream.empty,
dispatch,
streamDomainEvents: Stream.empty,
subscribeDomainEvents: PubSub.subscribe(domainEvents).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
latestSequence: Effect.succeed(0),
}),
Layer.succeed(ServerSettingsService, serverSettings),
@@ -280,6 +286,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
summaryRecovery,
invalidatedCwds,
updateSettings,
publishEvent: (event: OrchestrationEvent) => PubSub.publish(domainEvents, event),
publishMerge: PubSub.publish(mergedPullRequests, {
projectId: PROJECT_ID,
repository: "owner/repository",
@@ -332,12 +339,12 @@ describe("ThreadSettlementReactor", () => {
});
it.effect(
"settles all-terminal links from snapshots and keeps open or unsynced links active",
"settles synced terminal links immediately while open, unsynced, or running threads wait",
() =>
Effect.scoped(
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const link = (number: number, state: "open" | "merged" | null) => ({
const link = (number: number, state: "open" | "closed" | "merged" | null) => ({
host: "example.test",
repository: "owner/repository",
number,
@@ -357,14 +364,30 @@ describe("ThreadSettlementReactor", () => {
updatedAt: NOW,
syncedAt: NOW,
mergedAt: state === "merged" ? NOW : null,
closedAt: state === "closed" ? NOW : null,
},
});
const runningSession = {
threadId: ThreadId.make("running"),
status: "running" as const,
providerName: "Codex",
runtimeMode: "full-access" as const,
activeTurnId: null,
lastError: null,
updatedAt: NOW,
};
const threads = [
makeThread("merged", { pullRequests: [link(1, "open"), link(2, "merged")] }),
makeThread("closed", { pullRequests: [link(1, "open")] }),
makeThread("open", { pullRequests: [link(1, "open"), link(2, "open")] }),
makeThread("unsynced", { pullRequests: [link(1, "open"), link(2, null)] }),
makeThread("running", {
pullRequests: [link(1, "open")],
session: runningSession,
}),
];
const fixture = yield* makeHarness({
snapshot: makeSnapshot([
makeThread("merged", { pullRequests: [link(1, "merged"), link(2, "merged")] }),
makeThread("open", { pullRequests: [link(1, "merged"), link(2, "open")] }),
makeThread("unsynced", { pullRequests: [link(1, "merged"), link(2, null)] }),
]),
snapshot: makeSnapshot(threads),
settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleOnMerge: true },
branchPullRequest: () => Effect.die("linked threads must not query the branch"),
pullRequestSummary: () => Effect.die("linked threads must use their snapshots"),
@@ -372,9 +395,66 @@ describe("ThreadSettlementReactor", () => {
yield* Effect.gen(function* () {
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
const eventBase = {
sequence: 2,
eventId: EventId.make("pull-request-synced"),
aggregateKind: "thread" as const,
occurredAt: NOW,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
};
for (const thread of threads) {
const terminalLink = link(1, thread.id === "closed" ? "closed" : "merged");
yield* Ref.update(fixture.snapshots, (snapshot) => ({
...snapshot,
threads: snapshot.threads.map((current) =>
current.id === thread.id
? { ...current, pullRequests: [terminalLink, ...current.pullRequests.slice(1)] }
: current,
),
}));
yield* fixture.publishEvent({
...eventBase,
type: "thread.pull-request-synced",
aggregateId: thread.id,
payload: {
threadId: thread.id,
host: terminalLink.host,
repository: terminalLink.repository,
number: terminalLink.number,
snapshot: terminalLink.snapshot!,
stack: null,
updatedAt: NOW,
},
});
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
}
assert.deepStrictEqual(
(yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
[ThreadId.make("merged")],
[ThreadId.make("merged"), ThreadId.make("closed")],
);
const readySession = { ...runningSession, status: "ready" as const };
yield* Ref.update(fixture.snapshots, (snapshot) => ({
...snapshot,
threads: snapshot.threads.map((thread) =>
thread.id === readySession.threadId ? { ...thread, session: readySession } : thread,
),
}));
yield* fixture.publishEvent({
...eventBase,
type: "thread.session-set",
aggregateId: readySession.threadId,
payload: { threadId: readySession.threadId, session: readySession },
});
yield* Queue.take(fixture.snapshotReads);
yield* reactor.drain;
assert.deepStrictEqual(
(yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
[ThreadId.make("merged"), ThreadId.make("closed"), ThreadId.make("running")],
);
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
@@ -1,4 +1,9 @@
import { CommandId, type ServerSettings as ServerSettingsValue } from "@t3tools/contracts";
import {
CommandId,
type OrchestrationEvent,
type ServerSettings as ServerSettingsValue,
type ThreadId,
} from "@t3tools/contracts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import * as Cause from "effect/Cause";
@@ -84,6 +89,7 @@ export const make = Effect.gen(function* () {
const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
threadId?: ThreadId,
) {
const settings = yield* settingsService.getSettings;
if (!autoSettlementConfigured(settings)) {
@@ -94,7 +100,11 @@ export const make = Effect.gen(function* () {
const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
// A merge rechecks all candidates, including branches that discovery has
// not linked yet. Those lookups can still have cached the PR as open.
const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
const candidates = snapshot.threads.filter(
(thread) =>
(threadId === undefined || thread.id === threadId) &&
isAutoSettlementCandidate(thread, now),
);
// Return the thread when it still needs a pull request decision. A rejected
// dispatch skips it for this snapshot instead of retrying through a lookup.
@@ -279,8 +289,11 @@ export const make = Effect.gen(function* () {
);
});
const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
sweep(mergedPullRequest).pipe(
const runSweep = (
mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
threadId?: ThreadId,
) =>
sweep(mergedPullRequest, threadId).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause)
@@ -289,13 +302,36 @@ export const make = Effect.gen(function* () {
}),
),
);
const worker = yield* makeDrainableWorker(() => runSweep(null));
const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
runSweep(null, threadId),
);
const processEvent = (event: OrchestrationEvent) => {
switch (event.type) {
case "thread.pull-request-linked":
case "thread.pull-request-synced":
case "thread.pull-request-unlinked":
// Merge notifications can arrive before the linked snapshot is projected.
// Recheck the persisted state so terminal links settle without the timer.
return worker.enqueue(event.payload.threadId);
case "thread.session-set":
if (
event.payload.session.status !== "running" &&
event.payload.session.status !== "starting"
) {
return worker.enqueue(event.payload.threadId);
}
break;
}
return Effect.void;
};
const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
"ThreadSettlementReactor.start",
)(function* () {
const settingsChanges = yield* settingsService.subscribeChanges;
const mergedPullRequests = yield* pullRequests.subscribeMerges;
const events = yield* engine.subscribeDomainEvents;
const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
yield* forkParked(
@@ -314,7 +350,8 @@ export const make = Effect.gen(function* () {
return worker.enqueue(undefined);
}),
);
yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
yield* forkParked(Stream.runForEach(events, processEvent));
});
return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];