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

checkpointCaptureIndex.ts

448 lines16.9 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. Returns the tree it held, or undefined to rebuild.
181 */
182 const claim = Effect.fn("GitVcsDriver.checkpoints.claimCaptureIndex")(
183 function* (input: {
184 readonly location: Location;
185 readonly fingerprint: string;
186 readonly topLevel: string;
187 readonly prefix: string;
188 readonly excludePaths: ReadonlyArray<string>;
189 readonly head: string;
190 readonly indexFile: string;
191 readonly env: NodeJS.ProcessEnv;
192 readonly indexConfig: ReadonlyArray<string>;
193 }) {
194 const metaFile = path.join(input.location.directory, "meta.json");
195 const raw = yield* fileSystem.readFileString(metaFile);
196 // Claimed before use: a capture that fails from here on leaves nothing to trust.
197 yield* fileSystem.remove(metaFile);
198 const meta = yield* decodeMeta(raw);
199 // A rename keeps the index's timestamp, which Git's racy-entry check depends on.
200 yield* fileSystem.rename(
201 path.join(input.location.directory, `index.${meta.tree}`),
202 input.indexFile,
203 );
204 if (
205 meta.scope !== input.location.scope ||
206 meta.cwd !== input.location.cwd ||
207 meta.fingerprint !== input.fingerprint
208 ) {
209 return undefined;
210 }
211 const excluded = input.excludePaths.map(
212 (entry) => `${input.prefix}${entry.replace(/^\.\//, "").replace(/\/+$/, "")}`,
213 );
214 if (excluded.some((entry) => entry === input.prefix || /(?:^|\/)\.\.(?:\/|$)/.test(entry))) {
215 return undefined;
216 }
217 const staged = (entryPath: string) =>
218 entryPath.startsWith(input.prefix) &&
219 !excluded.some((entry) => entryPath === entry || entryPath.startsWith(`${entry}/`));
220​
221 const diff = yield* execute({
222 operation,
223 cwd: input.topLevel,
224 args: [
225 "diff-tree",
226 "-r",
227 "-z",
228 "--raw",
229 "--no-abbrev",
230 "--no-renames",
231 meta.tree,
232 input.head,
233 ],
234 maxOutputBytes: LIST_MAX_OUTPUT_BYTES,
235 outputMode: "error",
236 });
237 // Records are ":<old mode> <new mode> <old oid> <new oid> <status> NUL <path> NUL".
238 const fields = diff.stdout.split("\0");
239 const updates: string[] = [];
240 const candidates: Array<{ path: string; mode: string; oid: string }> = [];
241 const kept = new Set<string>();
242 for (let field = 0; field + 1 < fields.length; field += 2) {
243 const [oldMode = "", newMode = "", oldOid = "", newOid = ""] =
244 fields[field]!.slice(1).split(" ");
245 const entryPath = fields[field + 1]!;
246 // U+FFFD marks a name that is not UTF-8 and so cannot be fed back to Git from here.
247 if (entryPath.includes("�")) return undefined;
248 if (!staged(entryPath) || oldMode === "000000") {
249 // HEAD's entry, as a rebuilt index holds it; add -A then decides as it would there.
250 updates.push(
251 newMode === "000000"
252 ? `0 ${oldOid}\t${entryPath}`
253 : `${newMode} ${newOid}\t${entryPath}`,
254 );
255 } else if (newMode === "000000") {
256 candidates.push({ path: entryPath, mode: oldMode, oid: oldOid });
257 } else if (oldMode !== "160000") {
258 kept.add(oldOid);
259 }
260 }
261​
262 if (candidates.length > 0) {
263 // Paths HEAD lacks are untracked to a rebuilt index: add -A skips them once ignored,
264 // and stages a directory that became a repository as one gitlink.
265 // ./ avoids leading : pathspec magic; check-ignore rejects --literal-pathspecs.
266 const stdin = candidates.map((entry) => `./${entry.path}\0`).join("");
267 const ignored = yield* execute({
268 operation,
269 cwd: input.topLevel,
270 args: ["check-ignore", "--no-index", "-z", "--stdin"],
271 stdin,
272 allowNonZeroExit: true,
273 maxOutputBytes: Buffer.byteLength(stdin),
274 outputMode: "error",
275 });
276 if (ignored.exitCode > 1) return undefined;
277 const ignoredPaths = new Set(
278 ignored.stdout.split("\0").map((entryPath) => entryPath.replace(/^\.\//, "")),
279 );
280 const directories = new Set<string>();
281 for (const entry of candidates) {
282 for (
283 let end = entry.path.lastIndexOf("/");
284 end > 0 && !directories.has(entry.path.slice(0, end));
285 end = entry.path.lastIndexOf("/", end - 1)
286 ) {
287 directories.add(entry.path.slice(0, end));
288 }
289 }
290 // A gitlink whose directory lost its repository is a plain folder that add -A descends into.
291 for (const entry of candidates) if (entry.mode === "160000") directories.add(entry.path);
292 const repositories = new Set<string>();
293 yield* Effect.forEach(
294 directories,
295 (directory) =>
296 fileSystem.exists(path.join(input.topLevel, directory, ".git")).pipe(
297 Effect.map((exists) => {
298 if (exists) repositories.add(directory);
299 }),
300 ),
301 { concurrency: 64, discard: true },
302 );
303 const insideRepository = (entryPath: string) => {
304 for (
305 let end = entryPath.lastIndexOf("/");
306 end > 0;
307 end = entryPath.lastIndexOf("/", end - 1)
308 ) {
309 if (repositories.has(entryPath.slice(0, end))) return true;
310 }
311 return false;
312 };
313 for (const entry of candidates) {
314 if (
315 ignoredPaths.has(entry.path) ||
316 insideRepository(entry.path) ||
317 (entry.mode === "160000" && !repositories.has(entry.path))
318 ) {
319 updates.push(`0 ${entry.oid}\t${entry.path}`);
320 } else if (entry.mode !== "160000") {
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 yield* execute({
342 operation,
343 cwd: input.topLevel,
344 args: [...input.indexConfig, "update-index", "-z", "--index-info"],
345 stdin: `${updates.join("\0")}\0`,
346 env: input.env,
347 });
348 }
349 return meta.tree;
350 },
351 Effect.orElseSucceed(() => undefined),
352 );
353​
354 /** Throws a capture's index away when `git add` may have trusted stale conversion rules. */
355 const attributesChanged = (input: {
356 readonly cwd: string;
357 readonly previousTree: string;
358 readonly tree: string;
359 /** The capture's environment, whose private object store holds the new tree. */
360 readonly env: NodeJS.ProcessEnv;
361 }) =>
362 execute({
363 operation,
364 cwd: input.cwd,
365 env: input.env,
366 args: [
367 "diff-tree",
368 "-r",
369 "-z",
370 "--name-only",
371 "--no-renames",
372 input.previousTree,
373 input.tree,
374 "--",
375 ":(top,glob)**/.gitattributes",
376 ],
377 maxOutputBytes: 1,
378 outputMode: "truncate",
379 }).pipe(Effect.map((result) => result.stdout.length > 0));
380​
381 /** Keeps a published capture's index, hard-linked before anything else rewrote it, for the next. */
382 const save = Effect.fn("GitVcsDriver.checkpoints.saveCaptureIndex")(
383 function* (input: {
384 readonly location: Location;
385 readonly indexFile: string;
386 readonly tree: string;
387 readonly fingerprint: string;
388 }) {
389 const { directory } = input.location;
390 const root = path.dirname(directory);
391 yield* fileSystem.makeDirectory(directory, { recursive: true });
392 // Named by its tree, so a racing save can never pair one capture's index with another's meta.
393 const indexName = `index.${input.tree}`;
394 yield* fileSystem.rename(input.indexFile, path.join(directory, indexName));
395 const metaFile = path.join(directory, "meta.json");
396 yield* fileSystem.writeFileString(
397 `${metaFile}.tmp`,
398 yield* encodeMeta({
399 scope: input.location.scope,
400 cwd: input.location.cwd,
401 tree: input.tree,
402 fingerprint: input.fingerprint,
403 }),
404 );
405 yield* fileSystem.rename(`${metaFile}.tmp`, metaFile);
406 yield* Effect.forEach(
407 (yield* fileSystem.readDirectory(directory)).filter(
408 (entry) => entry.startsWith("index.") && entry !== indexName,
409 ),
410 (entry) => fileSystem.remove(path.join(directory, entry), { force: true }),
411 { discard: true },
412 );
413​
414 const now = yield* Clock.currentTimeMillis;
415 const others = yield* Effect.forEach(
416 (yield* fileSystem.readDirectory(root)).filter(
417 (entry) => path.join(root, entry) !== directory,
418 ),
419 (entry) =>
420 fileSystem.stat(path.join(root, entry)).pipe(
421 Effect.map((info) => ({
422 entry,
423 at: Option.match(info.mtime, { onNone: () => 0, onSome: (at) => at.getTime() }),
424 })),
425 Effect.orElseSucceed(() => ({ entry, at: 0 })),
426 ),
427 );
428 const stale = others
429 .toSorted((left, right) => right.at - left.at)
430 .filter((other, index) => index >= MAX_INDEXES - 1 || now - other.at > IDLE_MS);
431 yield* Effect.forEach(
432 stale,
433 ({ entry }) =>
434 fileSystem
435 .remove(path.join(root, entry), { recursive: true, force: true })
436 .pipe(Effect.ignore),
437 { discard: true },
438 );
439 },
440 (effect, input) =>
441 effect.pipe(
442 Effect.ignore,
443 Effect.ensuring(fileSystem.remove(input.indexFile, { force: true }).pipe(Effect.ignore)),
444 ),
445 );
446​
447 return { locate, fingerprint, claim, attributesChanged, save };
448};