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 Layer from "effect/Layer";
9import * as Schedule from "effect/Schedule";
10import type * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12
13import * as GitManager from "../git/GitManager.ts";
14import * as PullRequestService from "../pullRequest/PullRequestService.ts";
15import * as ServerSettings from "../serverSettings.ts";
16import { forkParked } from "../serverActivation.ts";
17import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
18import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
19import {
20 isAutoSettlementCandidate,
21 shouldAutoSettleThread,
22 type SettlementPullRequest,
23} from "./ThreadSettlementPolicy.ts";
24
25export class ThreadSettlementReactor extends Context.Service<
26 ThreadSettlementReactor,
27 {
28 readonly start: () => Effect.Effect<void, never, Scope.Scope>;
29 readonly drain: Effect.Effect<void>;
30 }
31>()("t3/orchestration/ThreadSettlementReactor") {}
32
33export const make = Effect.gen(function* () {
34 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
35 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
36 const settingsService = yield* ServerSettings.ServerSettingsService;
37 const git = yield* GitManager.GitManager;
38 const pullRequests = yield* PullRequestService.PullRequestService;
39 const crypto = yield* Crypto.Crypto;
40
41 const sweep = Effect.fn("ThreadSettlementReactor.sweep")(function* () {
42 const snapshot = yield* snapshots.getShellSnapshot();
43 const now = DateTime.formatIso(yield* DateTime.now);
44 const projects = new Map(snapshot.projects.map((project) => [project.id, project]));
45 const candidates = snapshot.threads.filter((thread) => isAutoSettlementCandidate(thread, now));
46 const lookupKey = (thread: (typeof candidates)[number]) => {
47 if (thread.linkedPullRequest != null) {
48 return JSON.stringify([
49 "linked",
50 thread.linkedPullRequest.projectId,
51 thread.linkedPullRequest.repository,
52 thread.linkedPullRequest.number,
53 ]);
54 }
55 if (thread.branch === null) return JSON.stringify(["none", thread.id]);
56 const project = projects.get(thread.projectId);
57 return JSON.stringify(
58 project === undefined
59 ? ["missing-project", thread.id]
60 : ["branch", project.workspaceRoot, thread.branch],
61 );
62 };
63 const groups = Map.groupBy(candidates, lookupKey);
64
65 const pullRequestFor = Effect.fn("ThreadSettlementReactor.pullRequestFor")(function* (
66 thread: (typeof candidates)[number],
67 ) {
68 if (thread.linkedPullRequest != null) {
69 if (!projects.has(thread.linkedPullRequest.projectId)) {
70 return yield* Effect.die(new Error("linked pull request project not found"));
71 }
72 const detail = yield* pullRequests.detail({
73 projectId: thread.linkedPullRequest.projectId,
74 repository: thread.linkedPullRequest.repository,
75 number: thread.linkedPullRequest.number,
76 });
77 return { state: detail.state, updatedAt: detail.updatedAt } satisfies SettlementPullRequest;
78 }
79 if (thread.branch === null) return null;
80 const project = projects.get(thread.projectId);
81 if (project === undefined) {
82 return yield* Effect.die(new Error("thread project not found"));
83 }
84 return yield* git.branchPullRequest({ cwd: project.workspaceRoot, branch: thread.branch });
85 });
86
87 yield* Effect.forEach(
88 groups.values(),
89 (group) =>
90 Effect.gen(function* () {
91 const pullRequest = yield* pullRequestFor(group[0]!);
92 yield* Effect.forEach(
93 group,
94 (thread) =>
95 Effect.gen(function* () {
96 const settings = yield* settingsService.getSettings;
97 const decisionNow = DateTime.formatIso(yield* DateTime.now);
98 if (
99 !shouldAutoSettleThread({
100 thread,
101 pullRequest,
102 now: decisionNow,
103 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
104 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
105 })
106 ) {
107 return;
108 }
109 const uuid = yield* crypto.randomUUIDv4;
110 yield* engine.dispatch({
111 type: "thread.auto-settle",
112 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
113 threadId: thread.id,
114 snapshotSequence: snapshot.snapshotSequence,
115 });
116 }).pipe(
117 Effect.catchCause((cause) =>
118 Cause.hasInterruptsOnly(cause)
119 ? Effect.failCause(cause)
120 : Effect.logWarning("automatic thread settlement skipped", {
121 threadId: thread.id,
122 cause: Cause.pretty(cause),
123 }),
124 ),
125 ),
126 { discard: true },
127 );
128 }).pipe(
129 Effect.catchCause((cause) =>
130 Cause.hasInterruptsOnly(cause)
131 ? Effect.failCause(cause)
132 : Effect.logWarning("automatic thread settlement skipped", {
133 threadIds: group.map((thread) => thread.id),
134 cause: Cause.pretty(cause),
135 }),
136 ),
137 ),
138 { concurrency: 8, discard: true },
139 );
140 });
141
142 const worker = yield* makeDrainableWorker(() =>
143 sweep().pipe(
144 Effect.catchCause((cause) =>
145 Cause.hasInterruptsOnly(cause)
146 ? Effect.failCause(cause)
147 : Effect.logWarning("automatic thread settlement sweep failed", {
148 cause: Cause.pretty(cause),
149 }),
150 ),
151 ),
152 );
153
154 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
155 "ThreadSettlementReactor.start",
156 )(function* () {
157 const settingsChanges = yield* settingsService.subscribeChanges;
158 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
159 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
160 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
161 yield* forkParked(
162 Effect.gen(function* () {
163 yield* worker.enqueue(undefined);
164 yield* worker.drain;
165 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
166 );
167 yield* forkParked(
168 Stream.runForEach(settingsChanges, (settings) => {
169 if (
170 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
171 settings.sidebarAutoSettleOnMerge === lastOnMerge
172 ) {
173 return Effect.void;
174 }
175 lastAfterDays = settings.sidebarAutoSettleAfterDays;
176 lastOnMerge = settings.sidebarAutoSettleOnMerge;
177 return worker.enqueue(undefined);
178 }),
179 );
180 });
181
182 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
183});
184
185export const layer = Layer.effect(ThreadSettlementReactor, make);