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 resolveAutoSettlementAt,
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 summary = yield* pullRequests.summary(
73 {
74 projectId: thread.linkedPullRequest.projectId,
75 repository: thread.linkedPullRequest.repository,
76 number: thread.linkedPullRequest.number,
77 },
78 { recoverTransientFailure: false },
79 );
80 return {
81 state: summary.state,
82 updatedAt: summary.updatedAt,
83 } satisfies SettlementPullRequest;
84 }
85 if (thread.branch === null) return null;
86 const project = projects.get(thread.projectId);
87 if (project === undefined) {
88 return yield* Effect.die(new Error("thread project not found"));
89 }
90 return yield* git.branchPullRequest({ cwd: project.workspaceRoot, branch: thread.branch });
91 });
92
93 yield* Effect.forEach(
94 groups.values(),
95 (group) =>
96 Effect.gen(function* () {
97 const pullRequest = yield* pullRequestFor(group[0]!);
98 yield* Effect.forEach(
99 group,
100 (thread) =>
101 Effect.gen(function* () {
102 const settings = yield* settingsService.getSettings;
103 const decisionNow = DateTime.formatIso(yield* DateTime.now);
104 const settledAt = resolveAutoSettlementAt({
105 thread,
106 pullRequest,
107 now: decisionNow,
108 autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
109 autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
110 });
111 if (settledAt === null) {
112 return;
113 }
114 const uuid = yield* crypto.randomUUIDv4;
115 yield* engine.dispatch({
116 type: "thread.auto-settle",
117 commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
118 threadId: thread.id,
119 snapshotSequence: snapshot.snapshotSequence,
120 settledAt,
121 });
122 }).pipe(
123 Effect.catchCause((cause) =>
124 Cause.hasInterruptsOnly(cause)
125 ? Effect.failCause(cause)
126 : Effect.logWarning("automatic thread settlement skipped", {
127 threadId: thread.id,
128 cause: Cause.pretty(cause),
129 }),
130 ),
131 ),
132 { discard: true },
133 );
134 }).pipe(
135 Effect.catchCause((cause) =>
136 Cause.hasInterruptsOnly(cause)
137 ? Effect.failCause(cause)
138 : Effect.logWarning("automatic thread settlement skipped", {
139 threadIds: group.map((thread) => thread.id),
140 cause: Cause.pretty(cause),
141 }),
142 ),
143 ),
144 { concurrency: 8, discard: true },
145 );
146 });
147
148 const worker = yield* makeDrainableWorker(() =>
149 sweep().pipe(
150 Effect.catchCause((cause) =>
151 Cause.hasInterruptsOnly(cause)
152 ? Effect.failCause(cause)
153 : Effect.logWarning("automatic thread settlement sweep failed", {
154 cause: Cause.pretty(cause),
155 }),
156 ),
157 ),
158 );
159
160 const start: ThreadSettlementReactor["Service"]["start"] = Effect.fn(
161 "ThreadSettlementReactor.start",
162 )(function* () {
163 const settingsChanges = yield* settingsService.subscribeChanges;
164 const initialSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
165 let lastAfterDays = initialSettings.sidebarAutoSettleAfterDays;
166 let lastOnMerge = initialSettings.sidebarAutoSettleOnMerge;
167 yield* forkParked(
168 Effect.gen(function* () {
169 yield* worker.enqueue(undefined);
170 yield* worker.drain;
171 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
172 );
173 yield* forkParked(
174 Stream.runForEach(settingsChanges, (settings) => {
175 if (
176 settings.sidebarAutoSettleAfterDays === lastAfterDays &&
177 settings.sidebarAutoSettleOnMerge === lastOnMerge
178 ) {
179 return Effect.void;
180 }
181 lastAfterDays = settings.sidebarAutoSettleAfterDays;
182 lastOnMerge = settings.sidebarAutoSettleOnMerge;
183 return worker.enqueue(undefined);
184 }),
185 );
186 });
187
188 return { start, drain: worker.drain } satisfies ThreadSettlementReactor["Service"];
189});
190
191export const layer = Layer.effect(ThreadSettlementReactor, make);