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

ThreadSettlementReactor.ts

230 lines9.1 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 const candidates = snapshot.threads.filter(
50 (thread) =>
51 isAutoSettlementCandidate(thread, now) &&
52 (mergedPullRequest === null ||
53 (thread.linkedPullRequest != null &&
54 thread.linkedPullRequest.projectId === mergedPullRequest.projectId &&
55 thread.linkedPullRequest.repository.toLowerCase() ===
56 mergedPullRequest.repository.toLowerCase() &&
57 thread.linkedPullRequest.number === mergedPullRequest.number)),
58 );
59 // Use the same cwd as the sidebar so both paths share GitManager's PR cache.
60 const lookupCwdByThreadId = new Map<string, string>();
61 yield* Effect.forEach(
62 candidates,
63 (thread) =>
64 Effect.gen(function* () {
65 const project = projects.get(thread.projectId);
66 if (project === undefined || thread.linkedPullRequest != null) return;
67 const worktreeExists =
68 thread.worktreePath !== null &&
69 (yield* fileSystem.exists(thread.worktreePath).pipe(Effect.orElseSucceed(() => false)));
70 lookupCwdByThreadId.set(
71 thread.id,
72 worktreeExists && thread.worktreePath !== null
73 ? thread.worktreePath
74 : project.workspaceRoot,
75 );
76 }),
77 { concurrency: 8, discard: true },
78 );
79 const lookupKey = (thread: (typeof candidates)[number]) => {
80 if (thread.linkedPullRequest != null) {
81 return JSON.stringify([
82 "linked",
83 thread.linkedPullRequest.projectId,
84 thread.linkedPullRequest.repository,
85 thread.linkedPullRequest.number,
86 ]);
87 }
88 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
89 const cwd = lookupCwdByThreadId.get(thread.id);
90 return JSON.stringify(
91 cwd === undefined ? ["missing-project", thread.id] : ["branch", cwd, thread.branch],
92 );
93 };
94 const groups = Map.groupBy(candidates, lookupKey);
95​
96 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
97 thread: (typeof candidates)[number],
98 ) {
99 if (thread.linkedPullRequest != null) {
100 if (mergedPullRequest !== null) {
101 return {
102 state: "merged",
103 updatedAt: mergedPullRequest.mergedAt,
104 } satisfies SettlementPullRequest;
105 }
106 if (!projects.has(thread.linkedPullRequest.projectId)) {
107 return yield* Effect.die(new Error("linked pull request project not found"));
108 }
109 const summary = yield* pullRequests.summary(
110 {
111 projectId: thread.linkedPullRequest.projectId,
112 repository: thread.linkedPullRequest.repository,
113 number: thread.linkedPullRequest.number,
114 },
115 { recoverTransientFailure: false },
116 );
117 return {
118 state: summary.state,
119 updatedAt: summary.updatedAt,
120 } satisfies SettlementPullRequest;
121 }
122 if (thread.branch === null) return null;
123 const cwd = lookupCwdByThreadId.get(thread.id);
124 if (cwd === undefined) {
125 return yield* Effect.die(new Error("thread project not found"));
126 }
127 return yield* git.branchPullRequest({ cwd, branch: thread.branch });
128 });
129​
130 yield* Effect.forEach(
131 groups.values(),
132 (group) =>
133 Effect.gen(function* () {
134 const pullRequest = yield* pullRequestFor(group[0]!);
135 yield* Effect.forEach(
136 group,
137 (thread) =>
138 Effect.gen(function* () {
139 const settings = yield* settingsService.getSettings;
140 const decisionNow = DateTime.formatIso(yield* DateTime.now);
141 const settledAt = resolveAutoSettlementAt({
142 thread,
143 pullRequest,
144 now: decisionNow,
145 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
146 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
147 });
148 if (settledAt === null) {
149 return;
150 }
151 const uuid = yield* crypto.randomUUIDv4;
152 yield* engine.dispatch({
153 type: "thread.auto-settle",
154 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
155 threadId: thread.id,
156 snapshotSequence: snapshot.snapshotSequence,
157 settledAt,
158 });
159 }).pipe(
160 Effect.catchCause((cause) =>
161 Cause.hasInterruptsOnly(cause)
162 ? Effect.failCause(cause)
163 : Effect.logWarning("automatic thread settlement skipped", {
164 threadId: thread.id,
165 cause: Cause.pretty(cause),
166 }),
167 ),
168 ),
169 { discard: true },
170 );
171 }).pipe(
172 Effect.catchCause((cause) =>
173 Cause.hasInterruptsOnly(cause)
174 ? Effect.failCause(cause)
175 : Effect.logWarning("automatic thread settlement skipped", {
176 threadIds: group.map((thread) => thread.id),
177 cause: Cause.pretty(cause),
178 }),
179 ),
180 ),
181 { concurrency: 8, discard: true },
182 );
183 });
184​
185 const runSweep = (mergedPullRequest: PullRequestService.PullRequestMergeEvent | null) =>
186 sweep(mergedPullRequest).pipe(
187 Effect.catchCause((cause) =>
188 Cause.hasInterruptsOnly(cause)
189 ? Effect.failCause(cause)
190 : Effect.logWarning("automatic thread settlement sweep failed", {
191 cause: Cause.pretty(cause),
192 }),
193 ),
194 );
195 const worker = yield* makeDrainableWorker(() => runSweep(null));
196​
197 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
198 "ThreadSettlementReactor.start",
199 )(function* () {
200 const settingsChanges = yield* settingsService.subscribeChanges;
201 const mergedPullRequests = yield* pullRequests.subscribeMerges;
202 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
203 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
204 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
205 yield* forkParked(
206 Effect.gen(function* () {
207 yield* worker.enqueue(undefined);
208 yield* worker.drain;
209 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
210 );
211 yield* forkParked(
212 Stream.runForEach(settingsChanges, (settings) => {
213 if (
214 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
215 settings.sidebarAutoSettleOnMerge === lastOnMerge
216 ) {
217 return Effect.void;
218 }
219 lastAfterDays = settings.sidebarAutoSettleAfterDays;
220 lastOnMerge = settings.sidebarAutoSettleOnMerge;
221 return worker.enqueue(undefined);
222 }),
223 );
224 yield* forkParked(Stream.runForEach(mergedPullRequests, runSweep));
225 });
226​
227 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
228});
229​
230export const layer = Layer.effect(ThreadSettlementReactor, make);