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

ThreadSettlementReactor.ts

389 lines15.3 KB

1import {
2 CommandId,
3 type OrchestrationEvent,
4 type ServerSettings as ServerSettingsValue,
5 type ThreadId,
6} from "@t3tools/contracts";
7import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
8import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Schedule from "effect/Schedule";
17import type * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19​
20import * as GitManager from "../git/GitManager.ts";
21import * as PullRequestService from "../pullRequest/PullRequestService.ts";
22import * as ServerSettings from "../serverSettings.ts";
23import { forkParked } from "../serverActivation.ts";
24import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
25import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
26import { pullRequestMatchesProject } from "./ThreadPullRequestReactor.ts";
27import {
28 isAutoSettlementCandidate,
29 resolveAutoSettlementAt,
30 type SettlementPullRequest,
31} from "./ThreadSettlementPolicy.ts";
32​
33export class ThreadSettlementReactor extends Context.Service<
34 ThreadSettlementReactor,
35 {
36 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
37 readonly drain: Effect.Effect<void>;
38 }
39>()("t3/orchestration/ThreadSettlementReactor") {}
40​
41/** @public Service construction is part of the canonical Effect module API. */
42/** Whether any environment default or project override can settle a thread. */
43function autoSettlementConfigured(settings: ServerSettingsValue): boolean {
44 if (settings.sidebarAutoSettleOnMerge || settings.sidebarAutoSettleAfterDays !== null) {
45 return true;
46 }
47 return Object.values(settings.projectSettingsOverrides).some(
48 (entry) =>
49 entry.sidebarAutoSettleOnMerge === true ||
50 (entry.sidebarAutoSettleAfterDays !== undefined && entry.sidebarAutoSettleAfterDays !== null),
51 );
53​
54/** Identity of every settlement input, so unrelated settings edits do not trigger a sweep. */
55/** @internal Exported for tests. */
56export function autoSettlementSettingsKey(settings: ServerSettingsValue): string {
57 return JSON.stringify([
58 settings.sidebarAutoSettleOnMerge,
59 settings.sidebarAutoSettleAfterDays,
60 // Only entries that touch settlement, in a stable order, so a project
61 // override on an unrelated key does not queue a sweep. JSON drops
62 // undefined, so inherit (absent) and never (null) need distinct marks.
63 Object.entries(settings.projectSettingsOverrides)
64 .filter(
65 ([, entry]) =>
66 entry.sidebarAutoSettleOnMerge !== undefined ||
67 entry.sidebarAutoSettleAfterDays !== undefined,
68 )
69 .sort(([left], [right]) => left.localeCompare(right))
70 .map(([projectId, entry]) => [
71 projectId,
72 entry.sidebarAutoSettleOnMerge ?? "inherit",
73 entry.sidebarAutoSettleAfterDays === undefined
74 ? "inherit"
75 : entry.sidebarAutoSettleAfterDays,
76 ]),
77 ]);
79​
80/** @public Service construction is part of the canonical Effect module API. */
81export const make = Effect.gen(function* () {
82 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
83 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
84 const settingsService = yield* ServerSettings.ServerSettingsService;
85 const git = yield* GitManager.GitManager;
86 const pullRequests = yield* PullRequestService.PullRequestService;
87 const crypto = yield* Crypto.Crypto;
88 const fileSystem = yield* FileSystem.FileSystem;
89​
90 const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
91 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
92 threadId?: ThreadId,
93 ) {
94 const settings = yield* settingsService.getSettings;
95 if (!autoSettlementConfigured(settings)) {
96 return;
97 }
98 const snapshot = yield* snapshots.getShellSnapshot();
99 const now = DateTime.formatIso(yield* DateTime.now);
100 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
101 // A merge rechecks all candidates, including branches that discovery has
102 // not linked yet. Those lookups can still have cached the PR as open.
103 const candidates = snapshot.threads.filter(
104 (thread) =>
105 (threadId === undefined || thread.id === threadId) &&
106 isAutoSettlementCandidate(thread, now),
107 );
108​
109 // Return the thread when it still needs a pull request decision. A rejected
110 // dispatch skips it for this snapshot instead of retrying through a lookup.
111 const settleThread = Effect.fn("ThreadSettlementReactor.settleThread")(
112 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
113 const settings = resolveProjectSettings(
114 yield* settingsService.getSettings,
115 thread.projectId,
116 ).settings;
117 const decisionNow = DateTime.formatIso(yield* DateTime.now);
118 const settledAt = resolveAutoSettlementAt({
119 thread,
120 pullRequest,
121 now: decisionNow,
122 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
123 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
124 });
125 if (settledAt === null) {
126 return thread;
127 }
128 const uuid = yield* crypto.randomUUIDv4;
129 yield* engine.dispatch({
130 type: "thread.auto-settle",
131 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
132 threadId: thread.id,
133 snapshotSequence: snapshot.snapshotSequence,
134 settledAt,
135 });
136 return null;
137 },
138 (effect, thread) =>
139 effect.pipe(
140 Effect.catchCause((cause) =>
141 Cause.hasInterruptsOnly(cause)
142 ? Effect.failCause(cause)
143 : Effect.logWarning("automatic thread settlement skipped", {
144 threadId: thread.id,
145 cause: Cause.pretty(cause),
146 }).pipe(Effect.as(null)),
147 ),
148 ),
149 );
150​
151 // Inactivity needs no host state. Finish these decisions before any lookup
152 // can fail or wait on the network, including lookups shared by recent threads.
153 const lookupCandidates = (yield* Effect.forEach(
154 candidates,
155 (thread) => settleThread(thread, null),
156 {
157 concurrency: 8,
158 },
159 ))
160 .filter((thread) => thread !== null)
161 .filter((thread) => !thread.pullRequests.some((link) => link.source !== "stack-dismissed"));
162​
163 // Use the same cwd as PR discovery so both paths share GitManager's cache.
164 const lookupCwdByThreadId = new Map<string, string>();
165 yield* Effect.forEach(
166 lookupCandidates,
167 (thread) =>
168 Effect.gen(function* () {
169 const project = projects.get(thread.projectId);
170 if (project === undefined || thread.branch === null) return;
171 const worktreeExists =
172 thread.worktreePath !== null &&
173 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
174 lookupCwdByThreadId.set(
175 thread.id,
176 worktreeExists && thread.worktreePath !== null
177 ? thread.worktreePath
178 : project.workspaceRoot,
179 );
180 }),
181 { concurrency: 8, discard: true },
182 );
183 if (mergedPullRequest !== null) {
184 // The merge confirmed a state the branch cache can still call open.
185 // Recheck those branches now instead of waiting for cache expiry.
186 const cwds = [...new Set(lookupCwdByThreadId.values())];
187 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
188 concurrency: 8,
189 discard: true,
190 });
191 }
192 const lookupKey = (thread: (typeof candidates)[number]) => {
193 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
194 if (reference != null) {
195 return JSON.stringify([
196 "linked",
197 reference.projectId,
198 reference.repository,
199 reference.number,
200 lookupCwdByThreadId.get(thread.id),
201 thread.branch,
202 ]);
203 }
204 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
205 const cwd = lookupCwdByThreadId.get(thread.id);
206 return JSON.stringify(
207 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
208 );
209 };
210 const groups = Map.groupBy(lookupCandidates, lookupKey);
211​
212 const wouldSettle = Effect.fn("ThreadSettlementReactor.wouldSettle")(function* (
213 group: ReadonlyArray<(typeof candidates)[number]>,
214 pullRequest: SettlementPullRequest,
215 ) {
216 const currentSettings = yield* settingsService.getSettings;
217 const decisionNow = DateTime.formatIso(yield* DateTime.now);
218 return group.some((thread) => {
219 const { settings } = resolveProjectSettings(currentSettings, thread.projectId);
220 return (
221 resolveAutoSettlementAt({
222 thread,
223 pullRequest,
224 now: decisionNow,
225 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
226 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
227 }) !== null
228 );
229 });
230 });
231​
232 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
233 group: ReadonlyArray<(typeof candidates)[number]>,
234 ) {
235 const thread = group[0]!;
236 const reference = thread.linkedPullRequest ?? thread.branchPullRequest;
237 if (reference != null) {
238 const matchesMerge =
239 mergedPullRequest !== null &&
240 reference.projectId === mergedPullRequest.projectId &&
241 reference.repository.toLowerCase() === mergedPullRequest.repository.toLowerCase() &&
242 reference.number === mergedPullRequest.number;
243 if (!matchesMerge && !projects.has(reference.projectId)) {
244 return yield* Effect.die(new Error("linked pull request project not found"));
245 }
246 const summary = matchesMerge
247 ? ({
248 state: "merged",
249 closedAt: null,
250 mergedAt: mergedPullRequest.mergedAt,
251 } satisfies SettlementPullRequest)
252 : yield* pullRequests.summary(
253 {
254 projectId: reference.projectId,
255 repository: reference.repository,
256 number: reference.number,
257 },
258 { recoverTransientFailure: false },
259 );
260 const terminal = {
261 state: summary.state,
262 closedAt: summary.closedAt ?? null,
263 mergedAt: summary.mergedAt ?? null,
264 } satisfies SettlementPullRequest;
265 const cwd = lookupCwdByThreadId.get(thread.id);
266 if (summary.state !== "open" && thread.branch !== null && cwd !== undefined) {
267 // A reused branch can already have a new open PR while discovery
268 // is replacing its old link. Do not let settlement win that race.
269 // Only pay for the uncached lookup when this sweep would otherwise
270 // settle: a terminal link that settles nothing (resumed thread,
271 // settle-on-merge off) would re-query the host every minute. A
272 // group that becomes eligible after this check waits for the next
273 // sweep rather than settling on the unverified link.
274 if (!(yield* wouldSettle(group, terminal))) return undefined;
275 const current = yield* git.branchPullRequest(
276 { cwd, branch: thread.branch },
277 { refresh: true },
278 );
279 const project = projects.get(thread.projectId);
280 if (
281 current?.state === "open" &&
282 project !== undefined &&
283 pullRequestMatchesProject(current, project)
284 ) {
285 return current;
286 }
287 }
288 return terminal;
289 }
290 if (thread.branch === null) return null;
291 const cwd = lookupCwdByThreadId.get(thread.id);
292 if (cwd === undefined) {
293 return yield* Effect.die(new Error("thread project not found"));
294 }
295 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
296 });
297​
298 yield* Effect.forEach(
299 groups.values(),
300 (group) =>
301 Effect.gen(function* () {
302 const pullRequest = yield* pullRequestFor(group);
303 if (pullRequest === undefined) return;
304 yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), {
305 discard: true,
306 });
307 }).pipe(
308 Effect.catchCause((cause) =>
309 Cause.hasInterruptsOnly(cause)
310 ? Effect.failCause(cause)
311 : Effect.logWarning("automatic thread settlement skipped", {
312 threadIds: group.map((thread) => thread.id),
313 cause: Cause.pretty(cause),
314 }),
315 ),
316 ),
317 { concurrency: 8, discard: true },
318 );
319 });
320​
321 const runSweep = (
322 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
323 threadId?: ThreadId,
324 ) =>
325 sweep(mergedPullRequest, threadId).pipe(
326 Effect.catchCause((cause) =>
327 Cause.hasInterruptsOnly(cause)
328 ? Effect.failCause(cause)
329 : Effect.logWarning("automatic thread settlement sweep failed", {
330 cause: Cause.pretty(cause),
331 }),
332 ),
333 );
334 const worker = yield* makeDrainableWorker((threadId: ThreadId | undefined) =>
335 runSweep(null, threadId),
336 );
337​
338 const processEvent = (event: OrchestrationEvent) => {
339 switch (event.type) {
340 case "thread.pull-request-linked":
341 case "thread.pull-request-synced":
342 case "thread.pull-request-unlinked":
343 // Merge notifications can arrive before the linked snapshot is projected.
344 // Recheck the persisted state so terminal links settle without the timer.
345 return worker.enqueue(event.payload.threadId);
346 case "thread.session-set":
347 if (
348 event.payload.session.status !== "running" &&
349 event.payload.session.status !== "starting"
350 ) {
351 return worker.enqueue(event.payload.threadId);
352 }
353 break;
354 }
355 return Effect.void;
356 };
357​
358 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
359 "ThreadSettlementReactor.start",
360 )(function* () {
361 const settingsChanges = yield* settingsService.subscribeChanges;
362 const mergedPullRequests = yield* pullRequests.subscribeMerges;
363 const events = yield* engine.subscribeDomainEvents;
364 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
365 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
366 yield* forkParked(
367 Effect.gen(function* () {
368 yield* worker.enqueue(undefined);
369 yield* worker.drain;
370 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
371 );
372 yield* forkParked(
373 Stream.runForEach(settingsChanges, (settings) => {
374 const key = autoSettlementSettingsKey(settings);
375 if (key === lastSettlementSettings) {
376 return Effect.void;
377 }
378 lastSettlementSettings = key;
379 return worker.enqueue(undefined);
380 }),
381 );
382 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));
383 yield* forkParked(Stream.runForEach(events, processEvent));
384 });
385​
386 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
387});
388​
389export const layer = Layer.effect(ThreadSettlementReactor, make);