fix: consolidate boundary ownership and cleanup failure paths (#477)
This commit is contained in:
+14
-5
@@ -1,7 +1,8 @@
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { open, stat } from "node:fs/promises";
|
||||
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import { readBoundedFileBytes } from "./process/BoundedFileBytes.js";
|
||||
|
||||
const MAX_JSON_INPUT_BYTES = 64 * 1_024 * 1_024;
|
||||
|
||||
@@ -13,6 +14,8 @@ export const parseCliJsonInput = async (
|
||||
| { readonly ok: true; readonly value: unknown }
|
||||
| { readonly ok: false; readonly error: JsonValue }
|
||||
> => {
|
||||
if (Buffer.byteLength(value, "utf8") > MAX_JSON_INPUT_BYTES)
|
||||
return jsonFileError(undefined, operation, "too-large");
|
||||
const inline = parseJson(value);
|
||||
if (inline !== undefined) return { ok: true, value: inline };
|
||||
if (["{", "["].includes(value.trimStart()[0] ?? ""))
|
||||
@@ -22,8 +25,14 @@ export const parseCliJsonInput = async (
|
||||
if (!metadata.isFile()) return jsonFileError(value, operation, "not-file");
|
||||
if (metadata.size > MAX_JSON_INPUT_BYTES)
|
||||
return jsonFileError(value, operation, "too-large");
|
||||
const bytes = await readFile(value);
|
||||
if (bytes.byteLength > MAX_JSON_INPUT_BYTES)
|
||||
const handle = await open(value, "r");
|
||||
let bytes: Buffer | undefined;
|
||||
try {
|
||||
bytes = await readBoundedFileBytes(handle, MAX_JSON_INPUT_BYTES);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
if (bytes === undefined)
|
||||
return jsonFileError(value, operation, "too-large");
|
||||
const parsed = parseJson(bytes.toString("utf8"));
|
||||
return parsed === undefined
|
||||
@@ -52,7 +61,7 @@ const inputError = (operation: string): JsonValue => ({
|
||||
});
|
||||
|
||||
const jsonFileError = (
|
||||
path: string,
|
||||
path: string | undefined,
|
||||
operation: string,
|
||||
reason: "not-file" | "too-large" | "invalid-json" | "read-failed",
|
||||
) => ({
|
||||
@@ -68,7 +77,7 @@ const jsonFileError = (
|
||||
: [],
|
||||
),
|
||||
),
|
||||
input_path: path,
|
||||
...(path === undefined ? {} : { input_path: path }),
|
||||
input_reason: reason,
|
||||
maximum_input_bytes: MAX_JSON_INPUT_BYTES,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user