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