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

RunFinalizationService.ts

212 lines8.6 KB

1import { CheckpointScopeId, ProjectId, RunId, ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FiberMap from "effect/FiberMap";
5import * as FiberSet from "effect/FiberSet";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9​
10import * as ProjectEnrichment from "../project/ProjectEnrichmentService.ts";
11import * as ProjectService from "../project/ProjectService.ts";
12import * as PullRequestService from "../pullRequest/PullRequestService.ts";
13import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
14import * as WorkspaceEntries from "../workspace/WorkspaceEntries.ts";
15import * as CheckpointCapture from "./CheckpointCaptureService.ts";
16import * as ProjectionStore from "./ProjectionStore.ts";
17​
18const REPOSITORY_REFRESH_CONCURRENCY = 4;
19​
20export class RunFinalizationError extends Schema.TaggedError<RunFinalizationError>()(
21 "RunFinalizationError",
22 {
23 threadId: ThreadId,
24 runId: RunId,
25 scopeId: CheckpointScopeId,
26 operation: Schema.Literals(["capture-checkpoint", "refresh-workspace"]),
27 cause: Schema.Defect(),
28 },
29) {}
30​
31export class RunFinalizationRefreshError extends Schema.TaggedError<RunFinalizationRefreshError>()(
32 "RunFinalizationRefreshError",
33 { cwd: Schema.String, cause: Schema.Defect() },
34) {}
35​
36export class RunFinalizationObserver extends Context.Reference<{
37 readonly refreshAfterTurn: (projectId: ProjectId) => Effect.Effect<void>;
38 readonly refresh: (input: {
39 readonly cwd: string;
40 readonly threadId: ThreadId;
41 readonly runId: RunId;
42 }) => Effect.Effect<void, RunFinalizationRefreshError>;
43 /** Local status of the tracked repositories a run checkpointed. Returns before it finishes. */
44 readonly refreshRepositories: (input: {
45 readonly threadId: ThreadId;
46 readonly cwds: ReadonlyArray<string>;
47 }) => Effect.Effect<void>;
48}>("t3/orchestration-v2/RunFinalizationObserver", {
49 defaultValue: () => ({
50 refresh: () => Effect.void,
51 refreshAfterTurn: () => Effect.void,
52 refreshRepositories: () => Effect.void,
53 }),
54}) {}
55​
56export class RunFinalizationService extends Context.Service<
57 RunFinalizationService,
58 {
59 readonly finalize: (input: {
60 readonly threadId: ThreadId;
61 readonly runId: RunId;
62 readonly scopeId: CheckpointScopeId;
63 }) => Effect.Effect<void, RunFinalizationError>;
64 }
65>()("t3/orchestration-v2/RunFinalizationService") {}
66​
67const make = Effect.gen(function* () {
68 const checkpointCapture = yield* CheckpointCapture.CheckpointCaptureServiceV2;
69 const projections = yield* ProjectionStore.ProjectionStoreV2;
70 const observer = yield* RunFinalizationObserver;
71 const refreshes = yield* FiberSet.make<void>();
72​
73 const finalize: RunFinalizationService["Service"]["finalize"] = Effect.fn(
74 "RunFinalizationService.finalize",
75 )(function* (input) {
76 yield* checkpointCapture
77 .execute(input)
78 .pipe(
79 Effect.mapError(
80 (cause) => new RunFinalizationError({ ...input, operation: "capture-checkpoint", cause }),
81 ),
82 );
83 const projection = yield* projections
84 .getCheckpointContext(input.threadId)
85 .pipe(
86 Effect.mapError(
87 (cause) => new RunFinalizationError({ ...input, operation: "refresh-workspace", cause }),
88 ),
89 );
90 const cwd = projection.checkpointScopes.find((scope) => scope.id === input.scopeId)?.cwd;
91 if (cwd !== undefined) {
92 // The refresh only updates the display, so the thread's next turn must not wait for it.
93 // Never replaced by a newer one: back-to-back turns would interrupt each before it publishes.
94 yield* observer.refresh({ cwd, threadId: input.threadId, runId: input.runId }).pipe(
95 Effect.catchTags({
96 RunFinalizationRefreshError: (cause) =>
97 Effect.logWarning("Failed to refresh workspace after checkpoint capture", {
98 ...input,
99 cause,
100 }),
101 }),
102 FiberSet.run(refreshes),
103 );
104 }
105 const repositoryScopeIds = new Set(
106 projection.checkpoints.flatMap((checkpoint) =>
107 checkpoint.runId === input.runId ? [checkpoint.scopeId] : [],
108 ),
109 );
110 const cwds = projection.checkpointScopes.flatMap((scope) =>
111 typeof scope.repositoryPath === "string" && repositoryScopeIds.has(scope.id)
112 ? [scope.cwd]
113 : [],
114 );
115 if (cwds.length > 0) yield* observer.refreshRepositories({ threadId: input.threadId, cwds });
116 });
117 return RunFinalizationService.of({ finalize });
118});
119​
120export const layer = Layer.effect(RunFinalizationService, make);
121​
122export const layerObserver = Layer.effect(
123 RunFinalizationObserver,
124 Effect.gen(function* () {
125 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
126 const vcsStatus = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
127 const projections = yield* ProjectionStore.ProjectionStoreV2;
128 const pullRequests = yield* PullRequestService.PullRequestService;
129 const projects = yield* ProjectService.ProjectService;
130 const enrichment = yield* ProjectEnrichment.ProjectEnrichmentService;
131 const pullRequestLookups = yield* FiberMap.make<string>();
132 const repositoryRefreshes = yield* FiberMap.make<ThreadId>();
133 const identityRefreshes = yield* FiberMap.make<ProjectId>();
134 // A turn can add the first remote (`git remote add`, `gh repo create --push`), which the
135 // enrichment and resolver caches would otherwise keep reporting as missing for a minute.
136 const refreshMissingRepositoryIdentity = Effect.fn(
137 "RunFinalizationService.refreshMissingRepositoryIdentity",
138 )(
139 function* (projectId: ProjectId) {
140 const project = yield* projects.getById(projectId);
141 if (Option.isNone(project)) return;
142 const { workspaceRoot } = project.value;
143 if ((yield* enrichment.readRepositoryIdentity(workspaceRoot)) !== null) return;
144 yield* enrichment.refreshRepositoryIdentity(workspaceRoot);
145 },
146 (effect, projectId) =>
147 effect.pipe(
148 Effect.catch((error) =>
149 Effect.logWarning("failed to refresh repository identity after run completion", {
150 projectId,
151 detail: error.message,
152 }),
153 ),
154 ),
155 );
156 return {
157 refreshAfterTurn: pullRequests.refreshAfterTurn,
158 // A project can track dozens of repositories, so the next turn must not wait for them all.
159 // A newer turn's refresh replaces a running one.
160 refreshRepositories: Effect.fn("RunFinalizationService.refreshRepositories")(function* ({
161 threadId,
162 cwds,
163 }) {
164 yield* Effect.forEach(
165 cwds,
166 (cwd) =>
167 vcsStatus.refreshLocalStatus(cwd).pipe(
168 Effect.catch((error) =>
169 Effect.logWarning("failed to refresh repository status after run completion", {
170 threadId,
171 cwd,
172 detail: error.message,
173 }),
174 ),
175 ),
176 { concurrency: REPOSITORY_REFRESH_CONCURRENCY, discard: true },
177 ).pipe(FiberMap.run(repositoryRefreshes, threadId));
178 }),
179 refresh: Effect.fn("RunFinalizationService.refresh")(
180 function* ({ cwd, threadId, runId }) {
181 const [, local] = yield* Effect.all(
182 [workspaceEntries.refresh(cwd, "passive"), vcsStatus.refreshLocalStatus(cwd)],
183 { concurrency: "unbounded" },
184 );
185 const thread = yield* projections.getThreadShell(threadId);
186 if (!thread) return;
187 // Forge discovery probes can take seconds; like the PR lookup, the next turn must not wait.
188 yield* refreshMissingRepositoryIdentity(thread.projectId).pipe(
189 FiberMap.run(identityRefreshes, thread.projectId),
190 );
191 if (local.refName === null || local.isDefaultRef) return;
192 if (thread.branch !== local.refName) return;
193 if (thread.activeRunId !== null && thread.activeRunId !== runId) return;
194 // The forge CLI can take minutes, so the next turn must not wait for it. A newer
195 // turn's lookup replaces a running one instead of queueing behind the cwd's lock.
196 yield* vcsStatus.refreshPullRequestStatus(cwd).pipe(
197 Effect.catch((error) =>
198 Effect.logWarning("failed to refresh pull request status after run completion", {
199 threadId,
200 cwd,
201 detail: error.message,
202 }),
203 ),
204 FiberMap.run(pullRequestLookups, cwd),
205 );
206 },
207 (effect, { cwd }) =>
208 effect.pipe(Effect.mapError((cause) => new RunFinalizationRefreshError({ cwd, cause }))),
209 ),
210 };
211 }),
212);