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

ThreadSettlementReactor.ts

249 lines10.3 KB

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 {
21 isAutoSettlementCandidate,
22 resolveAutoSettlementAt,
23 type SettlementPullRequest,
24} from "./ThreadSettlementPolicy.ts";
25​
26export class ThreadSettlementReactor extends Context.Service<
27 ThreadSettlementReactor,
28 {
29 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
30 readonly drain: Effect.Effect<void>;
31 }
32>()("t3/orchestration/ThreadSettlementReactor") {}
33​
34export const make = Effect.gen(function* () {
35 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
36 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
37 const settingsService = yield* ServerSettings.ServerSettingsService;
38 const git = yield* GitManager.GitManager;
39 const pullRequests = yield* PullRequestService.PullRequestService;
40 const crypto = yield* Crypto.Crypto;
41 const fileSystem = yield* FileSystem.FileSystem;
42​
43 const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* (
44 mergedPullRequest: PullRequestService.PullRequestMergeEvent | null,
45 ) {
46 const snapshot = yield* snapshots.getShellSnapshot();
47 const now = DateTime.formatIso(yield* DateTime.now);
48 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
49 // A merge event re-sweeps every candidate, not just the threads linked to
50 // the merged pull request: most threads carry no link and settle from
51 // their branch lookup, which would otherwise wait for the next minute's
52 // sweep on a possibly stale cached answer.
53 const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
54 // Use the same cwd as the sidebar so both paths share GitManager's PR cache.
55 const lookupCwdByThreadId = new Map<string, string>();
56 yield* Effect.forEach(
57 candidates,
58 (thread) =>
59 Effect.gen(function* () {
60 const project = projects.get(thread.projectId);
61 if (project === undefined || thread.linkedPullRequest != null) return;
62 const worktreeExists =
63 thread.worktreePath !== null &&
64 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
65 lookupCwdByThreadId.set(
66 thread.id,
67 worktreeExists && thread.worktreePath !== null
68 ? thread.worktreePath
69 : project.workspaceRoot,
70 );
71 }),
72 { concurrency: 8, discard: true },
73 );
74 if (mergedPullRequest !== null) {
75 // The merge just confirmed a terminal state the lookup caches can still
76 // call open (branch answers live two minutes, the sweep runs every
77 // minute). Drop the swept checkouts' cached answers so the merge settles
78 // its branch threads now instead of on a later sweep. Threads linked to
79 // the merged pull request settle from the event itself below and need no
80 // lookup, so they are absent from this map by construction.
81 const cwds = [...new Set(lookupCwdByThreadId.values())];
82 yield* Effect.forEach(cwds, (cwd) => git.invalidateStatus(cwd), {
83 concurrency: 8,
84 discard: true,
85 });
86 }
87 const lookupKey = (thread: (typeof candidates)[number]) => {
88 if (thread.linkedPullRequest != null) {
89 return JSON.stringify([
90 "linked",
91 thread.linkedPullRequest.projectId,
92 thread.linkedPullRequest.repository,
93 thread.linkedPullRequest.number,
94 ]);
95 }
96 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
97 const cwd = lookupCwdByThreadId.get(thread.id);
98 return JSON.stringify(
99 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
100 );
101 };
102 const groups = Map.groupBy(candidates, lookupKey);
103​
104 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
105 thread: (typeof candidates)[number],
106 ) {
107 if (thread.linkedPullRequest != null) {
108 // The event carries the merged state, so only the threads linked to
109 // that exact pull request settle from it. Every other linked thread
110 // falls through to a fresh summary lookup below: the merge sweep
111 // covers all candidates, and an unrelated merge must never settle
112 // them.
113 if (
114 mergedPullRequest !== null &&
115 thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&
116 thread.linkedPullRequest.repository.toLowerCase() ===
117 mergedPullRequest.repository.toLowerCase() &&
118 thread.linkedPullRequest.number === mergedPullRequest.number
119 ) {
120 return {
121 state: "merged",
122 updatedAt: mergedPullRequest.mergedAt,
123 } satisfies SettlementPullRequest;
124 }
125 if (!projects.has(thread.linkedPullRequest.projectId)) {
126 return yield* Effect.die(new Error("linked pull request project not found"));
127 }
128 const summary = yield* pullRequests.summary(
129 {
130 projectId: thread.linkedPullRequest.projectId,
131 repository: thread.linkedPullRequest.repository,
132 number: thread.linkedPullRequest.number,
133 },
134 { recoverTransientFailure: false },
135 );
136 return {
137 state: summary.state,
138 updatedAt: summary.updatedAt,
139 } satisfies SettlementPullRequest;
140 }
141 if (thread.branch === null) return null;
142 const cwd = lookupCwdByThreadId.get(thread.id);
143 if (cwd === undefined) {
144 return yield* Effect.die(new Error("thread project not found"));
145 }
146 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
147 });
148​
149 yield* Effect.forEach(
150 groups.values(),
151 (group) =>
152 Effect.gen(function* () {
153 const pullRequest = yield* pullRequestFor(group[0]!);
154 yield* Effect.forEach(
155 group,
156 (thread) =>
157 Effect.gen(function* () {
158 const settings = yield* settingsService.getSettings;
159 const decisionNow = DateTime.formatIso(yield* DateTime.now);
160 const settledAt = resolveAutoSettlementAt({
161 thread,
162 pullRequest,
163 now: decisionNow,
164 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
165 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
166 });
167 if (settledAt === null) {
168 return;
169 }
170 const uuid = yield* crypto.randomUUIDv4;
171 yield* engine.dispatch({
172 type: "thread.auto-settle",
173 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
174 threadId: thread.id,
175 snapshotSequence: snapshot.snapshotSequence,
176 settledAt,
177 });
178 }).pipe(
179 Effect.catchCause((cause) =>
180 Cause.hasInterruptsOnly(cause)
181 ? Effect.failCause(cause)
182 : Effect.logWarning("automatic thread settlement skipped", {
183 threadId: thread.id,
184 cause: Cause.pretty(cause),
185 }),
186 ),
187 ),
188 { discard: true },
189 );
190 }).pipe(
191 Effect.catchCause((cause) =>
192 Cause.hasInterruptsOnly(cause)
193 ? Effect.failCause(cause)
194 : Effect.logWarning("automatic thread settlement skipped", {
195 threadIds: group.map((thread) => thread.id),
196 cause: Cause.pretty(cause),
197 }),
198 ),
199 ),
200 { concurrency: 8, discard: true },
201 );
202 });
203​
204 const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
205 sweep(mergedPullRequest).pipe(
206 Effect.catchCause((cause) =>
207 Cause.hasInterruptsOnly(cause)
208 ? Effect.failCause(cause)
209 : Effect.logWarning("automatic thread settlement sweep failed", {
210 cause: Cause.pretty(cause),
211 }),
212 ),
213 );
214 const worker = yield* makeDrainableWorker(() => runSweep(null));
215​
216 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
217 "ThreadSettlementReactor.start",
218 )(function* () {
219 const settingsChanges = yield* settingsService.subscribeChanges;
220 const mergedPullRequests = yield* pullRequests.subscribeMerges;
221 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
222 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
223 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
224 yield* forkParked(
225 Effect.gen(function* () {
226 yield* worker.enqueue(undefined);
227 yield* worker.drain;
228 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
229 );
230 yield* forkParked(
231 Stream.runForEach(settingsChanges, (settings) => {
232 if (
233 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
234 settings.sidebarAutoSettleOnMerge === lastOnMerge
235 ) {
236 return Effect.void;
237 }
238 lastAfterDays = settings.sidebarAutoSettleAfterDays;
239 lastOnMerge = settings.sidebarAutoSettleOnMerge;
240 return worker.enqueue(undefined);
241 }),
242 );
243 yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
244 });
245​
246 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
247});
248​
249export const layer = Layer.effect(ThreadSettlementReactor, make);