Open History to see the last commit
1import { CommandId } from "@t3tools/contracts";
2import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
3import * as Cause from "effect/Cause";
4import * as Context from "effect/Context";
5import * as Crypto from "effect/Crypto";
6import * as DateTime from "effect/DateTime";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Schedule from "effect/Schedule";
11import type * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13
14import * as GitManager from "../git/GitManager.ts";
15import * as PullRequestService from "../pullRequest/PullRequestService.ts";
16import * as ServerSettings from "../serverSettings.ts";
17import { forkParked } from "../serverActivation.ts";
18import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
19import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
20import { pullRequestMatchesProject } from "./ThreadPullRequestReactor.ts";
21import {
22 isAutoSettlementCandidate,
23 resolveAutoSettlementAt,
24 type SettlementPullRequest,
25} from "./ThreadSettlementPolicy.ts";
26
27export class ThreadSettlementReactor extends Context.Service<
28 ThreadSettlementReactor,
29 {
30 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
31 readonly drain: Effect.Effect<void>;
32 }
33>()("t3/orchestration/ThreadSettlementReactor") {}
34
35export const make = Effect.gen(function* () {
36 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
37 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
38 const settingsService = yield* ServerSettings.ServerSettingsService;
39 const git = yield* GitManager.GitManager;
40 const pullRequests = yield* PullRequestService.PullRequestService;
41 const crypto = yield* Crypto.Crypto;
42 const fileSystem = yield* FileSystem.FileSystem;
43
44 const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
45 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
46 ) {
47 const snapshot = yield* snapshots.getShellSnapshot();
48 const now = DateTime.formatIso(yield* DateTime.now);
49 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
50 // A merge rechecks all candidates, including branches that discovery has
51 // not linked yet. Those lookups can still have cached the PR as open.
52 const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
53
54 // Return the thread when it still needs a pull request decision. A rejected
55 // dispatch skips it for this snapshot instead of retrying through a lookup.
56 const settleThread = Effect.fn("ThreadSettlementReactor.settleThread")(
57 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
58 const settings = yield* settingsService.getSettings;
59 const decisionNow = DateTime.formatIso(yield* DateTime.now);
60 const settledAt = resolveAutoSettlementAt({
61 thread,
62 pullRequest,
63 now: decisionNow,
64 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
65 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
66 });
67 if (settledAt === null) {
68 return thread;
69 }
70 const uuid = yield* crypto.randomUUIDv4;
71 yield* engine.dispatch({
72 type: "thread.auto-settle",
73 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
74 threadId: thread.id,
75 snapshotSequence: snapshot.snapshotSequence,
76 settledAt,
77 });
78 return null;
79 },
80 (effect, thread) =>
81 effect.pipe(
82 Effect.catchCause((cause) =>
83 Cause.hasInterruptsOnly(cause)
84 ? Effect.failCause(cause)
85 : Effect.logWarning("automatic thread settlement skipped", {
86 threadId: thread.id,
87 cause: Cause.pretty(cause),
88 }).pipe(Effect.as(null)),
89 ),
90 ),
91 );
92
93 // Inactivity needs no host state. Finish these decisions before any lookup
94 // can fail or wait on the network, including lookups shared by recent threads.
95 const lookupCandidates = (yield* Effect.forEach(
96 candidates,
97 (thread) => settleThread(thread, null),
98 {
99 concurrency: 8,
100 },
101 )).filter((thread) => thread !== null);
102
103 // Use the same cwd as PR discovery so both paths share GitManager's cache.
104 const lookupCwdByThreadId = new Map<string, string>();
105 yield* Effect.forEach(
106 lookupCandidates,
107 (thread) =>
108 Effect.gen(function* () {
109 const project = projects.get(thread.projectId);
110 if (project === undefined || thread.branch === null) return;
111 const worktreeExists =
112 thread.worktreePath !== null &&
113 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
114 lookupCwdByThreadId.set(
115 thread.id,
116 worktreeExists && thread.worktreePath !== null
117 ? thread.worktreePath
118 : project.workspaceRoot,
119 );
120 }),
121 { concurrency: 8, discard: true },
122 );
123 if (mergedPullRequest !== null) {
124 // The merge confirmed a state the branch cache can still call open.
125 // Recheck those branches now instead of waiting for cache expiry.
126 const cwds = [...new Set(lookupCwdByThreadId.values())];
127 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
128 concurrency: 8,
129 discard: true,
130 });
131 }
132 const lookupKey = (thread: (typeof candidates)[number]) => {
133 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
134 if (reference != null) {
135 return JSON.stringify([
136 "linked",
137 reference.projectId,
138 reference.repository,
139 reference.number,
140 lookupCwdByThreadId.get(thread.id),
141 thread.branch,
142 ]);
143 }
144 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
145 const cwd = lookupCwdByThreadId.get(thread.id);
146 return JSON.stringify(
147 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
148 );
149 };
150 const groups = Map.groupBy(lookupCandidates, lookupKey);
151
152 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
153 thread: (typeof candidates)[number],
154 ) {
155 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
156 if (reference != null) {
157 const matchesMerge =
158 mergedPullRequest !== null &&
159 reference.projectId === mergedPullRequest.projectId &&
160 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
161 reference.number === mergedPullRequest.number;
162 if (!matchesMerge && !projects.has(reference.projectId)) {
163 return yield* Effect.die(new Error("linked pull request project not found"));
164 }
165 const summary = matchesMerge
166 ? ({
167 state: "merged",
168 closedAt: null,
169 mergedAt: mergedPullRequest.mergedAt,
170 } satisfies SettlementPullRequest)
171 : yield* pullRequests.summary(
172 {
173 projectId: reference.projectId,
174 repository: reference.repository,
175 number: reference.number,
176 },
177 { recoverTransientFailure: false },
178 );
179 const cwd = lookupCwdByThreadId.get(thread.id);
180 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
181 // A reused branch can already have a new open PR while discovery
182 // is replacing its old link. Do not let settlement win that race.
183 const current = yield* git.branchPullRequest(
184 { cwd, branch: thread.branch },
185 { refresh: true },
186 );
187 const project = projects.get(thread.projectId);
188 if (
189 current?.state === "open" &&
190 project !== undefined &&
191 pullRequestMatchesProject(current, project)
192 ) {
193 return current;
194 }
195 }
196 return {
197 state: summary.state,
198 closedAt: summary.closedAt ?? null,
199 mergedAt: summary.mergedAt ?? null,
200 } satisfies SettlementPullRequest;
201 }
202 if (thread.branch === null) return null;
203 const cwd = lookupCwdByThreadId.get(thread.id);
204 if (cwd === undefined) {
205 return yield* Effect.die(new Error("thread project not found"));
206 }
207 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
208 });
209
210 yield* Effect.forEach(
211 groups.values(),
212 (group) =>
213 Effect.gen(function* () {
214 const pullRequest = yield* pullRequestFor(group[0]!);
215 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
216 discard: true,
217 });
218 }).pipe(
219 Effect.catchCause((cause) =>
220 Cause.hasInterruptsOnly(cause)
221 ? Effect.failCause(cause)
222 : Effect.logWarning("automatic thread settlement skipped", {
223 threadIds: group.map((thread) => thread.id),
224 cause: Cause.pretty(cause),
225 }),
226 ),
227 ),
228 { concurrency: 8, discard: true },
229 );
230 });
231
232 const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
233 sweep(mergedPullRequest).pipe(
234 Effect.catchCause((cause) =>
235 Cause.hasInterruptsOnly(cause)
236 ? Effect.failCause(cause)
237 : Effect.logWarning("automatic thread settlement sweep failed", {
238 cause: Cause.pretty(cause),
239 }),
240 ),
241 );
242 const worker = yield* makeDrainableWorker(() => runSweep(null));
243
244 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
245 "ThreadSettlementReactor.start",
246 )(function* () {
247 const settingsChanges = yield* settingsService.subscribeChanges;
248 const mergedPullRequests = yield* pullRequests.subscribeMerges;
249 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
250 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
251 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
252 yield* forkParked(
253 Effect.gen(function* () {
254 yield* worker.enqueue(undefined);
255 yield* worker.drain;
256 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
257 );
258 yield* forkParked(
259 Stream.runForEach(settingsChanges, (settings) => {
260 if (
261 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
262 settings.sidebarAutoSettleOnMerge === lastOnMerge
263 ) {
264 return Effect.void;
265 }
266 lastAfterDays = settings.sidebarAutoSettleAfterDays;
267 lastOnMerge = settings.sidebarAutoSettleOnMerge;
268 return worker.enqueue(undefined);
269 }),
270 );
271 yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
272 });
273
274 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
275});
276
277export const layer = Layer.effect(ThreadSettlementReactor, make);