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

checkpointCaptureIndex.ts

453 lines17.2 KB

1import * as Clock from "effect/Clock";
2import * as Effect from "effect/Effect";
3import type * as FileSystem from "effect/FileSystem";
4import * as Hash from "effect/Hash";
5import * as Option from "effect/Option";
6import type * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8​
9import type * as VcsDriver from "./VcsDriver.ts";
10import * as VcsProcess from "./VcsProcess.ts";
11​
12/**
13 * Each checkpoint scope keeps the scratch index of its last capture, so the next capture's
14 * `git add` trusts the stat data of files it already hashed instead of rehashing every untracked
15 * or modified file. The index lives in the common Git directory, never in the worktree.
16 */
17const DIRECTORY = "t3-checkpoint-indexes";
18// Archived threads stop capturing; their indexes age out instead of waiting for a delete.
19const IDLE_MS = 14 * 24 * 60 * 60 * 1000;
20const MAX_INDEXES = 32;
21const LIST_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
22​
23const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
24​
25const Meta = Schema.Struct({
26 scope: Schema.String,
27 cwd: Schema.String,
28 tree: Schema.String,
29 fingerprint: Schema.String,
30});
31const MetaJson = Schema.fromJsonString(Meta);
32const decodeMeta = Schema.decodeEffect(MetaJson);
33const encodeMeta = Schema.encodeEffect(MetaJson);
34​
35/** The capture index no longer matches what a rebuilt index would stage; capture again without it. */
36export class StaleCaptureIndex extends Schema.TaggedError<StaleCaptureIndex>()(
37 "StaleCaptureIndex",
38 {},
39) {}
40​
41/** Refs of one scope differ only in their last segment, the ordinal. */
42const scopeOf = (checkpointRef: string) =>
43 checkpointRef.slice(0, checkpointRef.lastIndexOf("/") + 1);
44​
45const hex = (value: string) => (Hash.string(value) >>> 0).toString(16).padStart(8, "0");
46​
47/** Names every capture index of a scope, whatever folder it captured. */
48export const scopeDirectoryPrefix = (scopeRefPrefix: string) => `${hex(scopeRefPrefix)}-`;
49​
50export const storeRoot = (path: Path.Path, gitCommonDir: string) =>
51 path.join(gitCommonDir, DIRECTORY);
52​
53/** Removes the capture indexes of scopes whose refs were deleted. */
54export const removeForScopes = Effect.fn("GitVcsDriver.checkpoints.removeCaptureIndexes")(
55 function* (
56 fileSystem: FileSystem.FileSystem,
57 path: Path.Path,
58 gitCommonDir: string,
59 scopeRefPrefixes: Iterable<string>,
60 ) {
61 const root = storeRoot(path, gitCommonDir);
62 const prefixes = [...scopeRefPrefixes].map(scopeDirectoryPrefix);
63 const entries = yield* fileSystem.readDirectory(root);
64 yield* Effect.forEach(
65 entries.filter((entry) => prefixes.some((prefix) => entry.startsWith(prefix))),
66 (entry) => fileSystem.remove(path.join(root, entry), { recursive: true, force: true }),
67 { discard: true },
68 );
69 },
70 (effect) => Effect.ignore(effect),
71);
72​
73/**
74 * The value Git uses for `key` in `git config --null --get-regexp` output: the last one, as local
75 * config follows global and system. Null marks a key written without a value.
76 */
77export const lastConfigValue = (stdout: string, key: string) => {
78 let value: string | null | undefined;
79 for (const record of stdout.split("\0")) {
80 const newline = record.indexOf("\n");
81 if ((newline === -1 ? record : record.slice(0, newline)) === key)
82 value = newline === -1 ? null : record.slice(newline + 1);
83 }
84 return value;
85};
86​
87/**
88 * Git's boolean rules: a valueless key is true, an empty value false, and an integer true unless
89 * zero. Integers parse as strtoimax base 0 does (leading space, 0x hex, 0 octal), then a k/m/g unit.
90 */
91export const gitBool = (value: string | null) => {
92 if (value === null) return true;
93 if (/^(?:true|yes|on)$/i.test(value)) return true;
94 const integer = /^\s*[+-]?(?:0x([\da-f]+)|([1-9]\d*|0[0-7]*))[kmg]?$/i.exec(value);
95 return integer !== null && /[1-9a-f]/i.test(integer[1] ?? integer[2]!);
96};
97​
98const statSignature = (fileSystem: FileSystem.FileSystem, file: string) =>
99 fileSystem.stat(file).pipe(
100 Effect.map(
101 (info) =>
102 `${Option.match(info.mtime, { onNone: () => "", onSome: (at) => at.getTime() })}:${info.size}:${Option.getOrElse(info.ino, () => "")}`,
103 ),
104 Effect.orElseSucceed(() => "-"),
105 );
106​
107export const make = (
108 execute: VcsDriver.VcsDriver["Service"]["execute"],
109 fileSystem: FileSystem.FileSystem,
110 path: Path.Path,
111) => {
112 const locate = (input: {
113 readonly gitCommonDir: string;
114 readonly checkpointRef: string;
115 readonly cwd: string;
116 }) => {
117 const scope = scopeOf(input.checkpointRef);
118 const directory = path.join(
119 storeRoot(path, input.gitCommonDir),
120 `${scopeDirectoryPrefix(scope)}${hex(input.cwd)}`,
121 );
122 return { scope, cwd: input.cwd, directory };
123 };
124 type Location = ReturnType<typeof locate>;
125​
126 /**
127 * What decides the blob `git add` records for a file whose stat is unchanged, outside the files
128 * a capture stages: conversion config and attribute files above the folder or outside the tree.
129 */
130 const fingerprint = Effect.fn("GitVcsDriver.checkpoints.captureIndexFingerprint")(
131 function* (input: {
132 readonly cwd: string;
133 readonly config: string;
134 readonly gitCommonDir: string;
135 readonly topLevel: string;
136 readonly prefix: string;
137 readonly hostEnv: NodeJS.ProcessEnv;
138 }) {
139 const { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } = input.hostEnv;
140 // Git expands ~, ~user and %(prefix) itself, so only a configured value costs a command.
141 const globalAttributes =
142 lastConfigValue(input.config, "core.attributesfile") === undefined
143 ? xdgConfigHome
144 ? path.join(xdgConfigHome, "git", "attributes")
145 : home
146 ? path.join(home, ".config", "git", "attributes")
147 : ""
148 : (yield* execute({
149 operation,
150 cwd: input.cwd,
151 args: ["config", "--type=path", "--get", "core.attributesFile"],
152 allowNonZeroExit: true,
153 })).stdout.replace(/\n$/, "");
154 // Files inside the folder are staged, so a change to a tracked or untracked .gitattributes
155 // there shows in the tree; an ignored one above it, the root included, does not.
156 const parents = [""];
157 for (
158 let end = input.prefix.indexOf("/");
159 end !== -1;
160 end = input.prefix.indexOf("/", end + 1)
161 ) {
162 if (end + 1 < input.prefix.length) parents.push(input.prefix.slice(0, end + 1));
163 }
164 const signatures = yield* Effect.forEach(
165 [
166 path.join(input.gitCommonDir, "info", "attributes"),
167 // Git reads relative paths after moving to the working-tree root.
168 globalAttributes === "" ? "" : path.resolve(input.topLevel, globalAttributes),
169 ...parents.map((parent) => path.join(input.topLevel, parent, ".gitattributes")),
170 ],
171 (file) => (file === "" ? Effect.succeed("-") : statSignature(fileSystem, file)),
172 );
173 return `${input.config}\0${signatures.join("\0")}`;
174 },
175 );
176​
177 /**
178 * Moves the scope's index to `indexFile` and makes it hold exactly what a rebuilt index would
179 * before `git add`: HEAD outside the staged pathspec, and inside it every previously captured
180 * path that `git add -A` would still stage, except a nested checkout HEAD does not track.
181 * Returns the tree it held, or undefined to rebuild.
182 */
183 const claim = Effect.fn("GitVcsDriver.checkpoints.claimCaptureIndex")(
184 function* (input: {
185 readonly location: Location;
186 readonly fingerprint: string;
187 readonly topLevel: string;
188 readonly prefix: string;
189 readonly excludePaths: ReadonlyArray<string>;
190 readonly head: string;
191 readonly indexFile: string;
192 readonly env: NodeJS.ProcessEnv;
193 readonly indexConfig: ReadonlyArray<string>;
194 }) {
195 const metaFile = path.join(input.location.directory, "meta.json");
196 const raw = yield* fileSystem.readFileString(metaFile);
197 // Claimed before use: a capture that fails from here on leaves nothing to trust.
198 yield* fileSystem.remove(metaFile);
199 const meta = yield* decodeMeta(raw);
200 // A rename keeps the index's timestamp, which Git's racy-entry check depends on.
201 yield* fileSystem.rename(
202 path.join(input.location.directory, `index.${meta.tree}`),
203 input.indexFile,
204 );
205 if (
206 meta.scope !== input.location.scope ||
207 meta.cwd !== input.location.cwd ||
208 meta.fingerprint !== input.fingerprint
209 ) {
210 return undefined;
211 }
212 const excluded = input.excludePaths.map(
213 (entry) => `${input.prefix}${entry.replace(/^\.\//, "").replace(/\/+$/, "")}`,
214 );
215 if (excluded.some((entry) => entry === input.prefix || /(?:^|\/)\.\.(?:\/|$)/.test(entry))) {
216 return undefined;
217 }
218 const staged = (entryPath: string) =>
219 entryPath.startsWith(input.prefix) &&
220 !excluded.some((entry) => entryPath === entry || entryPath.startsWith(`${entry}/`));
221​
222 const diff = yield* execute({
223 operation,
224 cwd: input.topLevel,
225 args: [
226 "diff-tree",
227 "-r",
228 "-z",
229 "--raw",
230 "--no-abbrev",
231 "--no-renames",
232 meta.tree,
233 input.head,
234 ],
235 maxOutputBytes: LIST_MAX_OUTPUT_BYTES,
236 outputMode: "error",
237 });
238 // Records are ":<old mode> <new mode> <old oid> <new oid> <status> NUL <path> NUL".
239 const fields = diff.stdout.split("\0");
240 const updates: string[] = [];
241 const candidates: Array<{ path: string; oid: string }> = [];
242 const kept = new Set<string>();
243 for (let field = 0; field + 1 < fields.length; field += 2) {
244 const [oldMode = "", newMode = "", oldOid = "", newOid = ""] =
245 fields[field]!.slice(1).split(" ");
246 const entryPath = fields[field + 1]!;
247 // U+FFFD marks a name that is not UTF-8 and so cannot be fed back to Git from here.
248 if (entryPath.includes("�")) return undefined;
249 if (
250 !staged(entryPath) ||
251 oldMode === "000000" ||
252 // A kept gitlink HEAD lacks makes add -A run git status inside that nested checkout.
253 (oldMode === "160000" && newMode === "000000")
254 ) {
255 // HEAD's entry, as a rebuilt index holds it; add -A then decides as it would there.
256 updates.push(
257 newMode === "000000"
258 ? `0 ${oldOid}\t${entryPath}`
259 : `${newMode} ${newOid}\t${entryPath}`,
260 );
261 } else if (newMode === "000000") {
262 candidates.push({ path: entryPath, oid: oldOid });
263 } else if (oldMode !== "160000") {
264 kept.add(oldOid);
265 }
266 }
267​
268 if (candidates.length > 0) {
269 // Paths HEAD lacks are untracked to a rebuilt index: add -A skips them once ignored,
270 // and stages a directory that became a repository as one gitlink.
271 // ./ avoids leading : pathspec magic; check-ignore rejects --literal-pathspecs.
272 const stdin = candidates.map((entry) => `./${entry.path}\0`).join("");
273 const ignored = yield* execute({
274 operation,
275 cwd: input.topLevel,
276 args: ["check-ignore", "--no-index", "-z", "--stdin"],
277 stdin,
278 allowNonZeroExit: true,
279 maxOutputBytes: Buffer.byteLength(stdin),
280 outputMode: "error",
281 });
282 if (ignored.exitCode > 1) return undefined;
283 const ignoredPaths = new Set(
284 ignored.stdout.split("\0").map((entryPath) => entryPath.replace(/^\.\//, "")),
285 );
286 const directories = new Set<string>();
287 for (const entry of candidates) {
288 for (
289 let end = entry.path.lastIndexOf("/");
290 end > 0 && !directories.has(entry.path.slice(0, end));
291 end = entry.path.lastIndexOf("/", end - 1)
292 ) {
293 directories.add(entry.path.slice(0, end));
294 }
295 }
296 const repositories = new Set<string>();
297 yield* Effect.forEach(
298 directories,
299 (directory) =>
300 fileSystem.exists(path.join(input.topLevel, directory, ".git")).pipe(
301 Effect.map((exists) => {
302 if (exists) repositories.add(directory);
303 }),
304 ),
305 { concurrency: 64, discard: true },
306 );
307 const insideRepository = (entryPath: string) => {
308 for (
309 let end = entryPath.lastIndexOf("/");
310 end > 0;
311 end = entryPath.lastIndexOf("/", end - 1)
312 ) {
313 if (repositories.has(entryPath.slice(0, end))) return true;
314 }
315 return false;
316 };
317 for (const entry of candidates) {
318 if (ignoredPaths.has(entry.path) || insideRepository(entry.path)) {
319 updates.push(`0 ${entry.oid}\t${entry.path}`);
320 } else {
321 kept.add(entry.oid);
322 }
323 }
324 }
325​
326 if (kept.size > 0) {
327 // Only refs keep objects from gc; a blob whose checkpoint was deleted may be gone.
328 const objects = yield* execute({
329 operation,
330 cwd: input.topLevel,
331 args: ["cat-file", "--batch-check=%(objectname) %(objecttype)"],
332 stdin: `${[...kept].join("\n")}\n`,
333 maxOutputBytes: kept.size * 128,
334 outputMode: "error",
335 });
336 const present = new Set(objects.stdout.split("\n"));
337 for (const oid of kept) if (!present.has(`${oid} blob`)) return undefined;
338 }
339​
340 if (updates.length > 0) {
341 // Restore the timestamp Git's racy check reads; update-index advances it.
342 const { mtime } = yield* fileSystem.stat(input.indexFile);
343 const indexTime = Option.isSome(mtime) ? Math.floor(mtime.value.getTime() / 1000) : 0;
344 if (indexTime <= 0) return undefined;
345 yield* execute({
346 operation,
347 cwd: input.topLevel,
348 args: [...input.indexConfig, "update-index", "-z", "--index-info"],
349 stdin: `${updates.join("\0")}\0`,
350 env: input.env,
351 });
352 yield* fileSystem.utimes(input.indexFile, indexTime, indexTime);
353 }
354 return meta.tree;
355 },
356 Effect.orElseSucceed(() => undefined),
357 );
358​
359 /** Throws a capture's index away when `git add` may have trusted stale conversion rules. */
360 const attributesChanged = (input: {
361 readonly cwd: string;
362 readonly previousTree: string;
363 readonly tree: string;
364 /** The capture's environment, whose private object store holds the new tree. */
365 readonly env: NodeJS.ProcessEnv;
366 }) =>
367 execute({
368 operation,
369 cwd: input.cwd,
370 env: input.env,
371 args: [
372 "diff-tree",
373 "-r",
374 "-z",
375 "--name-only",
376 "--no-renames",
377 input.previousTree,
378 input.tree,
379 "--",
380 ":(top,glob)**/.gitattributes",
381 ],
382 maxOutputBytes: 1,
383 outputMode: "truncate",
384 }).pipe(Effect.map((result) => result.stdout.length > 0));
385​
386 /** Keeps a published capture's index, hard-linked before anything else rewrote it, for the next. */
387 const save = Effect.fn("GitVcsDriver.checkpoints.saveCaptureIndex")(
388 function* (input: {
389 readonly location: Location;
390 readonly indexFile: string;
391 readonly tree: string;
392 readonly fingerprint: string;
393 }) {
394 const { directory } = input.location;
395 const root = path.dirname(directory);
396 yield* fileSystem.makeDirectory(directory, { recursive: true });
397 // Named by its tree, so a racing save can never pair one capture's index with another's meta.
398 const indexName = `index.${input.tree}`;
399 yield* fileSystem.rename(input.indexFile, path.join(directory, indexName));
400 const metaFile = path.join(directory, "meta.json");
401 yield* fileSystem.writeFileString(
402 `${metaFile}.tmp`,
403 yield* encodeMeta({
404 scope: input.location.scope,
405 cwd: input.location.cwd,
406 tree: input.tree,
407 fingerprint: input.fingerprint,
408 }),
409 );
410 yield* fileSystem.rename(`${metaFile}.tmp`, metaFile);
411 yield* Effect.forEach(
412 (yield* fileSystem.readDirectory(directory)).filter(
413 (entry) => entry.startsWith("index.") && entry !== indexName,
414 ),
415 (entry) => fileSystem.remove(path.join(directory, entry), { force: true }),
416 { discard: true },
417 );
418​
419 const now = yield* Clock.currentTimeMillis;
420 const others = yield* Effect.forEach(
421 (yield* fileSystem.readDirectory(root)).filter(
422 (entry) => path.join(root, entry) !== directory,
423 ),
424 (entry) =>
425 fileSystem.stat(path.join(root, entry)).pipe(
426 Effect.map((info) => ({
427 entry,
428 at: Option.match(info.mtime, { onNone: () => 0, onSome: (at) => at.getTime() }),
429 })),
430 Effect.orElseSucceed(() => ({ entry, at: 0 })),
431 ),
432 );
433 const stale = others
434 .toSorted((left, right) => right.at - left.at)
435 .filter((other, index) => index >= MAX_INDEXES - 1 || now - other.at > IDLE_MS);
436 yield* Effect.forEach(
437 stale,
438 ({ entry }) =>
439 fileSystem
440 .remove(path.join(root, entry), { recursive: true, force: true })
441 .pipe(Effect.ignore),
442 { discard: true },
443 );
444 },
445 (effect, input) =>
446 effect.pipe(
447 Effect.ignore,
448 Effect.ensuring(fileSystem.remove(input.indexFile, { force: true }).pipe(Effect.ignore)),
449 ),
450 );
451​
452 return { locate, fingerprint, claim, attributesChanged, save };
453};