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

CheckpointStore.ts

346 lines12.7 KB

1import { VcsUnsupportedOperationError, type CheckpointRef } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Path from "effect/Path";
6​
7import type { CheckpointStoreError } from "./Errors.ts";
8import type { VcsCheckpointOps } from "../vcs/VcsDriver.ts";
9import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
10import * as WorkspaceRepositories from "../workspace/WorkspaceRepositories.ts";
11import { parseTurnDiffFilesFromNumstat, prefixNumstatPaths, prefixPatchPaths } from "./Diffs.ts";
12​
13export interface CaptureCheckpointInput {
14 readonly cwd: string;
15 readonly checkpointRef: CheckpointRef;
16 /** Capture only in repositories without the ref, keeping checkpoints already taken. */
17 readonly missingOnly?: boolean;
19​
20export interface RestoreCheckpointInput {
21 readonly cwd: string;
22 readonly checkpointRef: CheckpointRef;
23 readonly fallbackToHead?: boolean;
25​
26export interface DiffCheckpointsInput {
27 readonly cwd: string;
28 readonly fromCheckpointRef: CheckpointRef;
29 readonly toCheckpointRef: CheckpointRef;
30 readonly fallbackFromToHead?: boolean;
31 readonly ignoreWhitespace: boolean;
32 readonly format?: "patch" | "numstat";
33 /** Maximum bytes collected from the diff command. */
34 readonly maxOutputBytes?: number;
35 /** Limits the diff to these exact paths. An empty list yields an empty diff. */
36 readonly filePaths?: ReadonlyArray<string>;
38​
39export interface ListAuthoredPathsInput {
40 readonly cwd: string;
41 readonly fromCheckpointRef: CheckpointRef;
42 readonly toCheckpointRef: CheckpointRef;
44​
45export interface DeleteCheckpointRefsInput {
46 readonly cwd: string;
47 readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
49​
50/**
51 * A multi-repo workspace folder (see `WorkspaceRepositories`) is checkpointed as
52 * one unit: every operation fans out to each repository under the same ref, and
53 * diffs report paths relative to the workspace folder. Restores check every
54 * repository has the ref first, but are not atomic across repositories.
55 */
56export class CheckpointStore extends Context.Service<
57 CheckpointStore,
58 {
59 /** Check whether cwd is inside a Git worktree or is a multi-repo workspace folder. */
60 readonly isCheckpointable: (cwd: string) => Effect.Effect<boolean, CheckpointStoreError>;
61​
62 readonly captureCheckpoint: (
63 input: CaptureCheckpointInput,
64 ) => Effect.Effect<void, CheckpointStoreError>;
65​
66 readonly hasCheckpointRef: (
67 input: Omit<RestoreCheckpointInput, "fallbackToHead">,
68 ) => Effect.Effect<boolean, CheckpointStoreError>;
69​
70 readonly restoreCheckpoint: (
71 input: RestoreCheckpointInput,
72 ) => Effect.Effect<boolean, CheckpointStoreError>;
73​
74 readonly diffCheckpoints: (
75 input: DiffCheckpointsInput,
76 ) => Effect.Effect<string, CheckpointStoreError>;
77​
78 /** Null means HEAD is unchanged or unrecorded; all changed paths then belong to the turn. */
79 readonly listAuthoredPaths: (
80 input: ListAuthoredPathsInput,
81 ) => Effect.Effect<ReadonlySet<string> | null, CheckpointStoreError>;
82​
83 readonly deleteCheckpointRefs: (
84 input: DeleteCheckpointRefsInput,
85 ) => Effect.Effect<void, CheckpointStoreError>;
86 }
87>()("t3/checkpointing/CheckpointStore") {}
88​
89/** One repository a checkpoint operation runs in, and where its paths sit under the cwd. */
90interface CheckpointTarget {
91 readonly cwd: string;
92 readonly pathPrefix: string | null;
94​
95const MULTI_REPO_CONCURRENCY = 4;
96​
97/** @public */
98export const make = Effect.gen(function* () {
99 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
100 const workspaceRepositories = yield* WorkspaceRepositories.WorkspaceRepositories;
101 const path = yield* Path.Path;
102​
103 const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
104 operation: string,
105 cwd: string,
106 ) {
107 const handle = yield* vcsRegistry.resolve({ cwd });
108 if (!handle.driver.checkpoints) {
109 return yield* new VcsUnsupportedOperationError({
110 operation,
111 kind: handle.kind,
112 detail: `${handle.kind} driver does not implement checkpoint operations.`,
113 });
114 }
115 return handle.driver.checkpoints satisfies VcsCheckpointOps;
116 });
117​
118 const isGitRepository = (cwd: string) =>
119 vcsRegistry
120 .detect({ cwd, requestedKind: "git" })
121 .pipe(Effect.map((repository) => repository !== null));
122​
123 // A cwd that is no repository and holds none stays a single target, so its operations
124 // fail the way they always have.
125 const resolveTargets = Effect.fn("CheckpointStore.resolveTargets")(function* (cwd: string) {
126 if (yield* isGitRepository(cwd)) return [{ cwd, pathPrefix: null }];
127 const repositories = yield* workspaceRepositories.list(cwd);
128 if (repositories.length === 0) return [{ cwd, pathPrefix: null }];
129 return repositories.map((repository): CheckpointTarget => ({
130 cwd: path.join(cwd, ...repository.relativePath.split("/")),
131 pathPrefix: repository.relativePath,
132 }));
133 });
134​
135 const forEachTarget = <A, E, R>(
136 targets: ReadonlyArray<CheckpointTarget>,
137 run: (target: CheckpointTarget) => Effect.Effect<A, E, R>,
138 ) => Effect.forEach(targets, run, { concurrency: MULTI_REPO_CONCURRENCY });
139​
140 const isCheckpointable: CheckpointStore["Service"]["isCheckpointable"] = Effect.fn(
141 "isCheckpointable",
142 )(function* (cwd) {
143 if (yield* isGitRepository(cwd)) return true;
144 return (yield* workspaceRepositories.list(cwd)).length > 0;
145 });
146​
147 const hasRefIn = (target: CheckpointTarget, checkpointRef: CheckpointRef) =>
148 resolveCheckpoints("CheckpointStore.hasCheckpointRef", target.cwd).pipe(
149 Effect.flatMap((checkpoints) =>
150 checkpoints.hasCheckpointRef({ cwd: target.cwd, checkpointRef }),
151 ),
152 );
153​
154 const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn(
155 "captureCheckpoint",
156 )(function* (input) {
157 yield* forEachTarget(yield* resolveTargets(input.cwd), (target) =>
158 Effect.gen(function* () {
159 if (input.missingOnly && (yield* hasRefIn(target, input.checkpointRef))) return;
160 const checkpoints = yield* resolveCheckpoints(
161 "CheckpointStore.captureCheckpoint",
162 target.cwd,
163 );
164 yield* checkpoints.captureCheckpoint({
165 cwd: target.cwd,
166 checkpointRef: input.checkpointRef,
167 });
168 }),
169 );
170 });
171​
172 const hasCheckpointRef: CheckpointStore["Service"]["hasCheckpointRef"] = Effect.fn(
173 "hasCheckpointRef",
174 )(function* (input) {
175 const found = yield* forEachTarget(yield* resolveTargets(input.cwd), (target) =>
176 hasRefIn(target, input.checkpointRef),
177 );
178 return found.every(Boolean);
179 });
180​
181 const restoreCheckpoint: CheckpointStore["Service"]["restoreCheckpoint"] = Effect.fn(
182 "restoreCheckpoint",
183 )(function* (input) {
184 const targets = yield* resolveTargets(input.cwd);
185 // Refuse up front rather than restore some repositories and then find one without the ref.
186 if (targets.length > 1 && input.fallbackToHead !== true) {
187 const found = yield* forEachTarget(targets, (target) =>
188 hasRefIn(target, input.checkpointRef),
189 );
190 if (!found.every(Boolean)) return false;
191 }
192 // One at a time, so a failure can name the repositories that were already restored.
193 const restored = yield* Effect.forEach(targets, (target, index) =>
194 resolveCheckpoints("CheckpointStore.restoreCheckpoint", target.cwd).pipe(
195 Effect.flatMap((checkpoints) =>
196 checkpoints.restoreCheckpoint({ ...input, cwd: target.cwd }),
197 ),
198 Effect.tapError(() =>
199 index === 0
200 ? Effect.void
201 : Effect.logWarning("Checkpoint restore failed after restoring other repositories", {
202 failed: target.cwd,
203 restored: targets.slice(0, index).map((done) => done.cwd),
204 }),
205 ),
206 ),
207 );
208 return restored.every(Boolean);
209 });
210​
211 const diffCheckpoints: CheckpointStore["Service"]["diffCheckpoints"] = Effect.fn(
212 "diffCheckpoints",
213 )(function* (input) {
214 const targets = yield* resolveTargets(input.cwd);
215 const diffs = yield* forEachTarget(targets, (target) =>
216 Effect.gen(function* () {
217 const checkpoints = yield* resolveCheckpoints(
218 "CheckpointStore.diffCheckpoints",
219 target.cwd,
220 );
221 if (target.pathPrefix === null) {
222 return yield* checkpoints.diffCheckpoints({ ...input, cwd: target.cwd });
223 }
224 // A repository added to the workspace after either checkpoint has nothing to compare.
225 const comparable =
226 (yield* checkpoints.hasCheckpointRef({
227 cwd: target.cwd,
228 checkpointRef: input.toCheckpointRef,
229 })) &&
230 (input.fallbackFromToHead === true ||
231 (yield* checkpoints.hasCheckpointRef({
232 cwd: target.cwd,
233 checkpointRef: input.fromCheckpointRef,
234 })));
235 if (!comparable) return "";
236 // Requested paths are relative to the workspace folder.
237 const repositoryPrefix = `${target.pathPrefix}/`;
238 const diff = yield* checkpoints.diffCheckpoints({
239 ...input,
240 cwd: target.cwd,
241 ...(input.filePaths
242 ? {
243 filePaths: input.filePaths.flatMap((filePath) =>
244 filePath.startsWith(repositoryPrefix)
245 ? [filePath.slice(repositoryPrefix.length)]
246 : [],
247 ),
248 }
249 : {}),
250 });
251 return input.format === "numstat"
252 ? prefixNumstatPaths(diff, target.pathPrefix)
253 : prefixPatchPaths(diff, target.pathPrefix);
254 }),
255 );
256 return diffs.join("");
257 });
258​
259 const listAuthoredPaths: CheckpointStore["Service"]["listAuthoredPaths"] = Effect.fn(
260 "listAuthoredPaths",
261 )(function* (input) {
262 const targets = yield* resolveTargets(input.cwd);
263 if (targets.length === 1 && targets[0]!.pathPrefix === null) {
264 const checkpoints = yield* resolveCheckpoints("CheckpointStore.listAuthoredPaths", input.cwd);
265 return yield* checkpoints.listAuthoredPaths(input);
266 }
267 const perRepository = yield* forEachTarget(targets, (target) =>
268 Effect.gen(function* () {
269 const checkpoints = yield* resolveCheckpoints(
270 "CheckpointStore.listAuthoredPaths",
271 target.cwd,
272 );
273 // A repository without both checkpoints has no diff, so nothing of it is listed.
274 const comparable =
275 (yield* checkpoints.hasCheckpointRef({
276 cwd: target.cwd,
277 checkpointRef: input.fromCheckpointRef,
278 })) &&
279 (yield* checkpoints.hasCheckpointRef({
280 cwd: target.cwd,
281 checkpointRef: input.toCheckpointRef,
282 }));
283 if (!comparable) return { target, paths: new Set<string>() };
284 return {
285 target,
286 paths: yield* checkpoints.listAuthoredPaths({ ...input, cwd: target.cwd }),
287 };
288 }),
289 );
290 if (perRepository.every(({ paths }) => paths === null)) return null;
291 // The result is one set for the workspace, so a repository whose HEAD did not move lists
292 // every path it changed.
293 const authored = new Set<string>();
294 for (const { target, paths } of perRepository) {
295 let repositoryPaths: Iterable<string> | null = paths;
296 if (repositoryPaths === null) {
297 const numstat = yield* resolveCheckpoints(
298 "CheckpointStore.listAuthoredPaths",
299 target.cwd,
300 ).pipe(
301 Effect.flatMap((checkpoints) =>
302 checkpoints.diffCheckpoints({
303 ...input,
304 cwd: target.cwd,
305 ignoreWhitespace: false,
306 format: "numstat",
307 }),
308 ),
309 );
310 repositoryPaths = parseTurnDiffFilesFromNumstat(numstat).flatMap((file) =>
311 file.previousPath === undefined ? [file.path] : [file.path, file.previousPath],
312 );
313 }
314 for (const repositoryPath of repositoryPaths) {
315 authored.add(`${target.pathPrefix}/${repositoryPath}`);
316 }
317 }
318 return authored;
319 });
320​
321 const deleteCheckpointRefs: CheckpointStore["Service"]["deleteCheckpointRefs"] = Effect.fn(
322 "deleteCheckpointRefs",
323 )(function* (input) {
324 yield* forEachTarget(yield* resolveTargets(input.cwd), (target) =>
325 resolveCheckpoints("CheckpointStore.deleteCheckpointRefs", target.cwd).pipe(
326 Effect.flatMap((checkpoints) =>
327 checkpoints.deleteCheckpointRefs({ ...input, cwd: target.cwd }),
328 ),
329 ),
330 );
331 });
332​
333 return CheckpointStore.of({
334 isCheckpointable,
335 captureCheckpoint,
336 hasCheckpointRef,
337 restoreCheckpoint,
338 diffCheckpoints,
339 listAuthoredPaths,
340 deleteCheckpointRefs,
341 });
342});
343​
344export const layer = Layer.effect(CheckpointStore, make).pipe(
345 Layer.provide(WorkspaceRepositories.layer),
346);