Simplify and harden investigation workflows
This commit is contained in:
@@ -23,7 +23,7 @@ import {
|
||||
type ArtifactOccurrence,
|
||||
} from "../domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { inventoryArtifact } from "./ArtifactInventory.js";
|
||||
import { scanArtifactInventory } from "./ArtifactInventory.js";
|
||||
import {
|
||||
digestCanonical,
|
||||
pageOf,
|
||||
@@ -43,7 +43,7 @@ export interface ArtifactExtractionInput {
|
||||
readonly limits: ArtifactLimits;
|
||||
}
|
||||
|
||||
/** Extract only explicitly selected inventory occurrences into an absent root. */
|
||||
/** Extract selected inventory occurrences into an exclusively owned absent root. */
|
||||
export const extractArtifact = async (
|
||||
input: ArtifactExtractionInput,
|
||||
signal?: AbortSignal,
|
||||
@@ -172,13 +172,6 @@ const materializeSelection = async ({
|
||||
selected,
|
||||
extracted,
|
||||
);
|
||||
const verifiedSource = await inventoryArtifact(
|
||||
sourcePath,
|
||||
input.limits,
|
||||
pageInput(0, 0),
|
||||
signal,
|
||||
);
|
||||
assertSameManifest(inventory.manifest, verifiedSource.manifest);
|
||||
await output.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
@@ -233,62 +226,20 @@ const loadInventory = async (
|
||||
selectedIds: ReadonlySet<string>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<LoadedInventory> => {
|
||||
const first = await inventoryArtifact(path, limits, pageInput(0, 0), signal);
|
||||
const snapshot = await scanArtifactInventory(path, limits, signal);
|
||||
const occurrences = new Map<string, ArtifactOccurrence>();
|
||||
const neededNodes = new Set<string>();
|
||||
collectOccurrences(
|
||||
first.occurrences.items,
|
||||
snapshot.occurrences,
|
||||
selectedIds,
|
||||
occurrences,
|
||||
neededNodes,
|
||||
);
|
||||
for (
|
||||
let offset = first.occurrences.next_offset;
|
||||
offset !== null && occurrences.size < selectedIds.size;
|
||||
offset += PAGE_SIZE
|
||||
) {
|
||||
const page = await inventoryArtifact(
|
||||
path,
|
||||
limits,
|
||||
pageInput(0, offset),
|
||||
signal,
|
||||
);
|
||||
assertSameManifest(first.manifest, page.manifest);
|
||||
collectOccurrences(
|
||||
page.occurrences.items,
|
||||
selectedIds,
|
||||
occurrences,
|
||||
neededNodes,
|
||||
);
|
||||
}
|
||||
const nodes = new Map<string, ArtifactNode>();
|
||||
collectNodes(first.nodes.items, neededNodes, nodes);
|
||||
for (
|
||||
let offset = first.nodes.next_offset;
|
||||
offset !== null && nodes.size < neededNodes.size;
|
||||
offset += PAGE_SIZE
|
||||
) {
|
||||
const page = await inventoryArtifact(
|
||||
path,
|
||||
limits,
|
||||
pageInput(offset, 0),
|
||||
signal,
|
||||
);
|
||||
assertSameManifest(first.manifest, page.manifest);
|
||||
collectNodes(page.nodes.items, neededNodes, nodes);
|
||||
}
|
||||
return { manifest: first.manifest, occurrences, nodes };
|
||||
collectNodes(snapshot.nodes, neededNodes, nodes);
|
||||
return { manifest: snapshot.manifest, occurrences, nodes };
|
||||
};
|
||||
|
||||
const pageInput = (nodeOffset: number, occurrenceOffset: number) => ({
|
||||
nodeOffset,
|
||||
nodeLimit: PAGE_SIZE,
|
||||
occurrenceOffset,
|
||||
occurrenceLimit: PAGE_SIZE,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 1,
|
||||
});
|
||||
|
||||
const collectOccurrences = (
|
||||
items: readonly ArtifactOccurrence[],
|
||||
selected: ReadonlySet<string>,
|
||||
@@ -363,14 +314,3 @@ const preflight = (entry: ArtifactEntry, limits: ArtifactLimits): void => {
|
||||
`Selected artifact exceeds compression ratio limit: ${entry.path}`,
|
||||
);
|
||||
};
|
||||
|
||||
const assertSameManifest = (
|
||||
expected: ArtifactGraphManifest,
|
||||
observed: ArtifactGraphManifest,
|
||||
): void => {
|
||||
if (expected.manifest_id !== observed.manifest_id)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Artifact changed while resolving extraction selection",
|
||||
);
|
||||
};
|
||||
|
||||
@@ -49,6 +49,19 @@ interface InventoryPageInput {
|
||||
readonly edgeLimit: number;
|
||||
}
|
||||
|
||||
/** Immutable inventory produced by one complete artifact scan. */
|
||||
export interface ArtifactInventorySnapshot {
|
||||
readonly manifest: ArtifactInventoryResult["manifest"];
|
||||
readonly nodes: readonly ArtifactNode[];
|
||||
readonly occurrences: ArtifactInventoryResult["occurrences"]["items"];
|
||||
readonly edges: ArtifactInventoryResult["edges"]["items"];
|
||||
readonly limits: ArtifactInventoryResult["limits"];
|
||||
readonly provenance: ReadonlyArray<
|
||||
ArtifactInventoryResult["provenance"][number]
|
||||
>;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Inventory one local artifact without extracting or mounting it. */
|
||||
export const inventoryArtifact = async (
|
||||
inputPath: string,
|
||||
@@ -56,6 +69,16 @@ export const inventoryArtifact = async (
|
||||
page: InventoryPageInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactInventoryResult> => {
|
||||
const snapshot = await scanArtifactInventory(inputPath, limits, signal);
|
||||
return paginateArtifactInventory(snapshot, page);
|
||||
};
|
||||
|
||||
/** Scan an artifact once and retain the complete immutable graph for projection. */
|
||||
export const scanArtifactInventory = async (
|
||||
inputPath: string,
|
||||
limits: ArtifactLimits,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
abortIfNeeded(signal);
|
||||
const path = await realpath(inputPath);
|
||||
const metadata = await lstat(path);
|
||||
@@ -122,8 +145,8 @@ export const inventoryArtifact = async (
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
graph_sha256: graphSha256,
|
||||
})}`;
|
||||
return artifactInventoryResultSchema.parse({
|
||||
manifest: {
|
||||
return {
|
||||
manifest: artifactInventoryResultSchema.shape.manifest.parse({
|
||||
schema_version: 1,
|
||||
manifest_id: manifestId,
|
||||
root_artifact_id: rootNode.artifact_id,
|
||||
@@ -133,23 +156,35 @@ export const inventoryArtifact = async (
|
||||
node_count: orderedNodes.length,
|
||||
occurrence_count: orderedOccurrences.length,
|
||||
edge_count: orderedEdges.length,
|
||||
},
|
||||
nodes: pageOf(orderedNodes, page.nodeOffset, page.nodeLimit),
|
||||
occurrences: pageOf(
|
||||
orderedOccurrences,
|
||||
page.occurrenceOffset,
|
||||
page.occurrenceLimit,
|
||||
),
|
||||
edges: pageOf(orderedEdges, page.edgeOffset, page.edgeLimit),
|
||||
}),
|
||||
nodes: orderedNodes,
|
||||
occurrences: orderedOccurrences,
|
||||
edges: orderedEdges,
|
||||
limits: toOutputLimits(limits),
|
||||
provenance: reader?.provenance() ?? [],
|
||||
limitations: inventoryLimitations(rootFormat, reader),
|
||||
});
|
||||
};
|
||||
} finally {
|
||||
await reader?.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Project independently paged graph collections from one inventory snapshot. */
|
||||
export const paginateArtifactInventory = (
|
||||
snapshot: ArtifactInventorySnapshot,
|
||||
page: InventoryPageInput,
|
||||
): ArtifactInventoryResult =>
|
||||
artifactInventoryResultSchema.parse({
|
||||
...snapshot,
|
||||
nodes: pageOf(snapshot.nodes, page.nodeOffset, page.nodeLimit),
|
||||
occurrences: pageOf(
|
||||
snapshot.occurrences,
|
||||
page.occurrenceOffset,
|
||||
page.occurrenceLimit,
|
||||
),
|
||||
edges: pageOf(snapshot.edges, page.edgeOffset, page.edgeLimit),
|
||||
});
|
||||
|
||||
const inventoryLimitations = (
|
||||
format: ArtifactNode["format"],
|
||||
reader: ArtifactReader | undefined,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { constants as fsConstants } from "node:fs";
|
||||
import { lstat, open, readdir, readlink } from "node:fs/promises";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import type { FileState, ProcessScenario } from "../domain/processCapture.js";
|
||||
import type { Stats } from "node:fs";
|
||||
|
||||
export interface SnapshotResult {
|
||||
readonly files: readonly FileState[];
|
||||
@@ -13,9 +14,29 @@ const isWithin = (candidate: string, root: string): boolean =>
|
||||
candidate === root ||
|
||||
candidate.startsWith(`${root.endsWith("/") ? root.slice(0, -1) : root}/`);
|
||||
|
||||
const hasSameIdentity = (
|
||||
before: Stats,
|
||||
after: Stats,
|
||||
expected: "directory" | "symlink",
|
||||
): boolean =>
|
||||
before.dev === after.dev &&
|
||||
before.ino === after.ino &&
|
||||
(expected === "directory" ? after.isDirectory() : after.isSymbolicLink());
|
||||
|
||||
const lstatIfPresent = async (path: string): Promise<Stats | undefined> => {
|
||||
try {
|
||||
return await lstat(path);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return undefined;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const hashFile = async (
|
||||
path: string,
|
||||
maxBytes: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string | null> => {
|
||||
const handle = await open(
|
||||
path,
|
||||
@@ -24,9 +45,25 @@ const hashFile = async (
|
||||
try {
|
||||
const stats = await handle.stat();
|
||||
if (!stats.isFile() || stats.size > maxBytes) return null;
|
||||
return createHash("sha256")
|
||||
.update(await handle.readFile())
|
||||
.digest("hex");
|
||||
const hash = createHash("sha256");
|
||||
const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes));
|
||||
let position = 0;
|
||||
while (position < stats.size) {
|
||||
signal?.throwIfAborted();
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
0,
|
||||
Math.min(buffer.length, stats.size - position),
|
||||
position,
|
||||
);
|
||||
if (bytesRead === 0) return null;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
position += bytesRead;
|
||||
}
|
||||
const after = await handle.stat();
|
||||
if (after.size !== stats.size || after.mtimeMs !== stats.mtimeMs)
|
||||
return null;
|
||||
return hash.digest("hex");
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
@@ -35,6 +72,7 @@ const hashFile = async (
|
||||
/** Capture bounded, root-aliased filesystem state without following symlinks. */
|
||||
export const snapshotRoots = async (
|
||||
scenario: ProcessScenario,
|
||||
signal?: AbortSignal,
|
||||
): Promise<SnapshotResult> => {
|
||||
const entries: FileState[] = [];
|
||||
let remainingBytes = scenario.limits.file_bytes;
|
||||
@@ -45,6 +83,7 @@ export const snapshotRoots = async (
|
||||
path: string,
|
||||
depth: number,
|
||||
): Promise<void> => {
|
||||
signal?.throwIfAborted();
|
||||
if (
|
||||
entries.length >= scenario.limits.files ||
|
||||
depth > scenario.limits.filesystem_depth
|
||||
@@ -52,17 +91,16 @@ export const snapshotRoots = async (
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
let stats;
|
||||
try {
|
||||
stats = await lstat(path);
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
||||
return;
|
||||
throw error;
|
||||
}
|
||||
const stats = await lstatIfPresent(path);
|
||||
if (stats === undefined) return;
|
||||
const relativePath = relative(root, path) || ".";
|
||||
if (stats.isSymbolicLink()) {
|
||||
const target = resolve(dirname(path), await readlink(path));
|
||||
const afterRead = await lstat(path);
|
||||
if (!hasSameIdentity(stats, afterRead, "symlink")) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
const safeTarget = isWithin(target, root)
|
||||
? relative(root, target) || "."
|
||||
: "<outside-declared-root>";
|
||||
@@ -80,7 +118,7 @@ export const snapshotRoots = async (
|
||||
if (stats.isFile()) {
|
||||
const sha256 =
|
||||
remainingBytes >= stats.size
|
||||
? await hashFile(path, remainingBytes)
|
||||
? await hashFile(path, remainingBytes, signal)
|
||||
: null;
|
||||
remainingBytes -= sha256 === null ? 0 : stats.size;
|
||||
if (sha256 === null) truncated = true;
|
||||
@@ -104,7 +142,13 @@ export const snapshotRoots = async (
|
||||
symlink_target: null,
|
||||
});
|
||||
if (type !== "directory") return;
|
||||
for (const child of (await readdir(path)).sort())
|
||||
const children = await readdir(path);
|
||||
const afterRead = await lstat(path);
|
||||
if (!hasSameIdentity(stats, afterRead, "directory")) {
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
for (const child of children.sort())
|
||||
await visit(root, rootAlias, join(path, child), depth + 1);
|
||||
};
|
||||
for (const [index, root] of scenario.filesystem_roots.entries())
|
||||
|
||||
@@ -183,6 +183,7 @@ interface CaptureResultOptions {
|
||||
readonly truncated: boolean;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly rootPid: number;
|
||||
readonly samplingPartial: boolean;
|
||||
}
|
||||
|
||||
const classifyFilesystemEffects = (
|
||||
@@ -236,6 +237,9 @@ const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
|
||||
truncated: options.truncated,
|
||||
limitations: [
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
...(options.samplingPartial
|
||||
? ["Process-tree sampling ended with an incomplete observation."]
|
||||
: []),
|
||||
"Filesystem observations are before/after snapshots, not syscall traces.",
|
||||
"The harness does not enforce external network isolation.",
|
||||
],
|
||||
@@ -269,7 +273,14 @@ const awaitTerminalExit = async ({
|
||||
}> =>
|
||||
new Promise((resolveExit) => {
|
||||
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
|
||||
terminal.onExit((exit) => resolveExit({ ...exit, reason }));
|
||||
terminal.onExit((exit) => {
|
||||
for (const timer of timers) {
|
||||
clearTimeout(timer);
|
||||
clearInterval(timer);
|
||||
}
|
||||
timers.clear();
|
||||
resolveExit({ ...exit, reason });
|
||||
});
|
||||
const timeout = setInterval(() => {
|
||||
if (signal?.aborted === true) {
|
||||
reason = "cancelled";
|
||||
@@ -361,34 +372,51 @@ const resolveProcessResult = (
|
||||
executionFailure: unknown,
|
||||
cleanupFailure: string | undefined,
|
||||
): ProcessCapture => {
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ProcessCaptureError(cleanupFailure);
|
||||
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
|
||||
if (executionFailure !== undefined)
|
||||
throw new ProcessCaptureError("process capture failed", {
|
||||
cause: executionFailure,
|
||||
});
|
||||
if (cleanupFailure !== undefined)
|
||||
throw new ProcessCaptureError(cleanupFailure);
|
||||
if (capture === undefined)
|
||||
throw new ProcessCaptureError("process capture produced no result");
|
||||
return capture;
|
||||
};
|
||||
|
||||
const prepareProcessCapture = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<{
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
readonly home: string;
|
||||
readonly before: SnapshotResult;
|
||||
}> => {
|
||||
const decision = authorizeProcessScenario(scenario, policy);
|
||||
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
|
||||
await assertRealPathAuthority(scenario, policy);
|
||||
assertNotCancelled(signal);
|
||||
const before = await snapshotRoots(scenario, signal);
|
||||
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
|
||||
return { temporaryRoot, runId, home, before };
|
||||
};
|
||||
|
||||
/** Execute one authorized scenario and return bounded observations. */
|
||||
const runProcessScenario = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProcessCapture> => {
|
||||
const decision = authorizeProcessScenario(scenario, policy);
|
||||
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
|
||||
await assertRealPathAuthority(scenario, policy);
|
||||
assertNotCancelled(signal);
|
||||
|
||||
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
|
||||
const before = await snapshotRoots(scenario);
|
||||
const { temporaryRoot, runId, home, before } = await prepareProcessCapture(
|
||||
scenario,
|
||||
policy,
|
||||
signal,
|
||||
);
|
||||
const frames: TerminalFrame[] = [];
|
||||
const samples: ProcessSample[] = [];
|
||||
let truncated = before.truncated;
|
||||
@@ -400,7 +428,8 @@ const runProcessScenario = async (
|
||||
let capture: ProcessCapture | undefined;
|
||||
let executionFailure: unknown;
|
||||
let framesTruncated = (): boolean => false;
|
||||
let stopSampler: () => Promise<void> = async () => undefined;
|
||||
let stopSampler = async () => ({ partial: false });
|
||||
let samplingPartial = false;
|
||||
|
||||
try {
|
||||
replay = await startLoopbackReplay(scenario);
|
||||
@@ -439,18 +468,20 @@ const runProcessScenario = async (
|
||||
timers,
|
||||
});
|
||||
const exitReason = exit.reason;
|
||||
await stopSampler();
|
||||
samplingPartial = (await stopSampler()).partial;
|
||||
if (exitReason === "cancelled")
|
||||
throw new ProcessCaptureError("process capture was cancelled");
|
||||
await new Promise((resolveSettle) =>
|
||||
setTimeout(resolveSettle, scenario.settle_ms),
|
||||
);
|
||||
const after = await snapshotRoots(scenario);
|
||||
assertNotCancelled(signal);
|
||||
const after = await snapshotRoots(scenario, signal);
|
||||
truncated ||=
|
||||
after.truncated ||
|
||||
replay.truncated ||
|
||||
framesTruncated() ||
|
||||
samples.length >= scenario.limits.processes;
|
||||
truncated ||= samplingPartial;
|
||||
capture = buildCaptureResult({
|
||||
frames,
|
||||
exit: { ...exit, reason: exitReason },
|
||||
@@ -461,12 +492,13 @@ const runProcessScenario = async (
|
||||
truncated,
|
||||
scenario,
|
||||
rootPid: terminal.pid,
|
||||
samplingPartial,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
terminal?.kill("SIGKILL");
|
||||
executionFailure = cause;
|
||||
}
|
||||
await stopSampler();
|
||||
samplingPartial ||= (await stopSampler()).partial;
|
||||
const cleanupFailure = await releaseProcessResources({
|
||||
timers,
|
||||
replay,
|
||||
|
||||
@@ -26,6 +26,19 @@ interface SampleProcessContext {
|
||||
readonly signal: AbortSignal;
|
||||
}
|
||||
|
||||
const isExpectedProcReadFailure = (cause: unknown): boolean =>
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "ENOENT" ||
|
||||
cause.code === "ESRCH" ||
|
||||
cause.code === "EACCES" ||
|
||||
cause.code === "EPERM");
|
||||
|
||||
const handleProcReadFailure = (cause: unknown): undefined => {
|
||||
if (isExpectedProcReadFailure(cause)) return undefined;
|
||||
throw cause;
|
||||
};
|
||||
|
||||
const parseProcStat = (
|
||||
identifier: string,
|
||||
stat: string,
|
||||
@@ -66,8 +79,8 @@ const readProcessStat = async (
|
||||
signal,
|
||||
});
|
||||
return parseProcStat(String(pid), stat);
|
||||
} catch {
|
||||
return undefined;
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -77,8 +90,8 @@ const readProcessCommand = async (
|
||||
): Promise<Buffer | undefined> => {
|
||||
try {
|
||||
return await readFile(`/proc/${String(pid)}/cmdline`, { signal });
|
||||
} catch {
|
||||
return undefined;
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -92,8 +105,8 @@ const readLinuxChildren = async (
|
||||
encoding: "utf8",
|
||||
signal,
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
} catch (cause: unknown) {
|
||||
return handleProcReadFailure(cause);
|
||||
}
|
||||
return text
|
||||
.trim()
|
||||
@@ -303,12 +316,13 @@ export const startProcessSampler = (
|
||||
started: number,
|
||||
limit: number,
|
||||
samples: ProcessSample[],
|
||||
): (() => Promise<void>) => {
|
||||
): (() => Promise<{ readonly partial: boolean }>) => {
|
||||
const identities = new Map<number, string>();
|
||||
const sampledPids = new Set<number>(samples.map(({ pid }) => pid));
|
||||
let pending: Promise<void> | undefined;
|
||||
let stopped = false;
|
||||
let abortCurrent: (() => void) | undefined;
|
||||
let partial = false;
|
||||
|
||||
const sample = (): void => {
|
||||
if (stopped || pending !== undefined || sampledPids.size >= limit) return;
|
||||
@@ -331,7 +345,10 @@ export const startProcessSampler = (
|
||||
samples.push(value);
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.catch((cause: unknown) => {
|
||||
if (!(cause instanceof Error && cause.name === "AbortError"))
|
||||
partial = true;
|
||||
})
|
||||
.then(() => {
|
||||
abortCurrent = undefined;
|
||||
pending = undefined;
|
||||
@@ -346,5 +363,6 @@ export const startProcessSampler = (
|
||||
clearInterval(timer);
|
||||
abortCurrent?.();
|
||||
await pending;
|
||||
return { partial };
|
||||
};
|
||||
};
|
||||
|
||||
@@ -175,7 +175,7 @@ export const importReferenceSource = async (
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
shouldExclude,
|
||||
}),
|
||||
readReferenceSourceVcs(root),
|
||||
readReferenceSourceVcs(root, options.signal),
|
||||
]);
|
||||
|
||||
if (!readResult.ok) {
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import fs from "node:fs";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { log, statusMatrix } from "isomorphic-git";
|
||||
import { resolveRef } from "isomorphic-git";
|
||||
|
||||
export type ReferenceSourceVcsInfo =
|
||||
| { readonly kind: "git"; readonly head: string; readonly dirty: boolean }
|
||||
| {
|
||||
readonly kind: "git";
|
||||
readonly head: string;
|
||||
readonly dirty: boolean | null;
|
||||
}
|
||||
| { readonly kind: "none"; readonly head: null; readonly dirty: null }
|
||||
| { readonly kind: "unknown"; readonly head: null; readonly dirty: null };
|
||||
|
||||
@@ -14,42 +20,28 @@ export type ReferenceSourceVcsInfo =
|
||||
*/
|
||||
export const readReferenceSourceVcs = async (
|
||||
root: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReferenceSourceVcsInfo> => {
|
||||
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
|
||||
try {
|
||||
const commits = await log({
|
||||
fs,
|
||||
dir: root,
|
||||
ref: "HEAD",
|
||||
depth: 1,
|
||||
cache: {},
|
||||
});
|
||||
if (commits.length === 0)
|
||||
return { kind: "unknown", head: null, dirty: null };
|
||||
|
||||
const head = commits[0]?.oid;
|
||||
if (head === undefined) return { kind: "unknown", head: null, dirty: null };
|
||||
|
||||
let dirty = false;
|
||||
try {
|
||||
const matrix = await statusMatrix({
|
||||
fs,
|
||||
dir: root,
|
||||
ref: head,
|
||||
cache: {},
|
||||
});
|
||||
for (const row of matrix) {
|
||||
const [, headStatus, workdirStatus, stageStatus] = row;
|
||||
if (headStatus !== 1 || workdirStatus !== 1 || stageStatus !== 1) {
|
||||
dirty = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
return { kind: "git", head, dirty };
|
||||
await lstat(join(root, ".git"));
|
||||
} catch (cause: unknown) {
|
||||
return errorCode(cause) === "ENOENT"
|
||||
? { kind: "none", head: null, dirty: null }
|
||||
: { kind: "unknown", head: null, dirty: null };
|
||||
}
|
||||
try {
|
||||
const head = await resolveRef({ fs, dir: root, ref: "HEAD" });
|
||||
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
|
||||
return { kind: "git", head, dirty: null };
|
||||
} catch {
|
||||
return { kind: "none", head: null, dirty: null };
|
||||
return { kind: "unknown", head: null, dirty: null };
|
||||
}
|
||||
};
|
||||
|
||||
const errorCode = (cause: unknown): string | undefined =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? String(cause.code)
|
||||
: undefined;
|
||||
|
||||
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
|
||||
|
||||
Reference in New Issue
Block a user