mirror of
https://github.com/morluto/rea.git
synced 2026-12-05 14:31:22 +00:00
refactor(api-contract): share parser heap admission (#15725)
* refactor(api-contract): share parser heap admission * refactor(errors): centralize measured heap refusals * test(api-contract): isolate parser heap regression
This commit is contained in:
1 parent
3c79efe719
commit
cacaefe8f8
7 files changed
+133
-70
No files matched your search
@@ -9,11 +9,9 @@
|
||||
"src/apkSignature/apkSignatureFailures.ts": 3,
|
||||
"src/apktool/ApktoolConfiguration.ts": 1,
|
||||
"src/application/JsonAuthenticationHeadroom.ts": 2,
|
||||
"src/application/JsonInputFile.ts": 3,
|
||||
"src/application/JsonInputFile.ts": 1,
|
||||
"src/application/Utf8JsonInput.ts": 1,
|
||||
"src/application/apiContract/ApiContractRead.ts": 1,
|
||||
"src/application/apiContract/ApiContractService.ts": 1,
|
||||
"src/application/apiContract/GraphqlContractImport.ts": 1,
|
||||
"src/application/binaryDiagnostics/ByteEntropyService.ts": 1,
|
||||
"src/application/decompileDirectory/exportTree.ts": 1,
|
||||
"src/application/desktop/DesktopBuildSolves.ts": 1,
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
measuredHeapConstraint,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
|
||||
import { hostRangeErrorKind } from "../domain/parseFailure.js";
|
||||
@@ -701,9 +702,8 @@ const admitJsonAssembly = (
|
||||
const requiredBytes =
|
||||
projectedBytes * retainedMultiplier + READ_CHUNK_BYTES;
|
||||
if (requiredBytes > heap.total_available_size)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
throw measuredHeapConstraint(
|
||||
operation,
|
||||
"memory",
|
||||
"Insufficient heap headroom to materialize the complete JSON value",
|
||||
{
|
||||
input_path: path,
|
||||
@@ -713,10 +713,7 @@ const admitJsonAssembly = (
|
||||
available_heap_bytes: heap.total_available_size,
|
||||
heap_size_limit_bytes: heap.heap_size_limit,
|
||||
},
|
||||
{
|
||||
measuredExhaustion: true,
|
||||
remediationAction: JSON_INPUT_RESOURCE_REMEDIATION,
|
||||
},
|
||||
JSON_INPUT_RESOURCE_REMEDIATION,
|
||||
);
|
||||
nextCheck = projectedBytes + READ_CHUNK_BYTES;
|
||||
}
|
||||
@@ -737,9 +734,8 @@ const requireStringAssemblyHeadroom = (
|
||||
// UTF-16 representation and the next coalesced part before that allocation.
|
||||
const requiredBytes = 2 * (stringCodeUnits + PACKED_TOKEN_PART_CODE_UNITS);
|
||||
if (requiredBytes > heap.total_available_size)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
throw measuredHeapConstraint(
|
||||
operation,
|
||||
"memory",
|
||||
"Insufficient heap headroom to assemble a complete JSON string",
|
||||
{
|
||||
input_path: path,
|
||||
@@ -749,10 +745,7 @@ const requireStringAssemblyHeadroom = (
|
||||
available_heap_bytes: heap.total_available_size,
|
||||
heap_size_limit_bytes: heap.heap_size_limit,
|
||||
},
|
||||
{
|
||||
measuredExhaustion: true,
|
||||
remediationAction: JSON_INPUT_RESOURCE_REMEDIATION,
|
||||
},
|
||||
JSON_INPUT_RESOURCE_REMEDIATION,
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getHeapStatistics } from "node:v8";
|
||||
import {
|
||||
artifactFileCancellationError,
|
||||
artifactFilePrimaryFacts,
|
||||
@@ -13,6 +14,7 @@ import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
measuredHeapConstraint,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
|
||||
import {
|
||||
@@ -23,6 +25,8 @@ import {
|
||||
import { apiContractFileBytesLimit } from "../../domain/apiContract/apiContractQuery.js";
|
||||
import { err, ok } from "../../domain/result.js";
|
||||
|
||||
import { nativeJsonParseRequiredBytes } from "../JsonInputFile.js";
|
||||
|
||||
interface ContractDocumentInput {
|
||||
readonly path: string;
|
||||
readonly max_file_bytes: number;
|
||||
@@ -136,3 +140,26 @@ export const readApiContract = async (
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Sample heap headroom before expanding one verified document into text or a parsed tree. */
|
||||
export const apiContractParseMemoryFailure = (
|
||||
inputBytes: number,
|
||||
reason: string,
|
||||
remediationAction: string,
|
||||
): AnalysisResourceConstraintError | undefined => {
|
||||
const required = nativeJsonParseRequiredBytes(inputBytes);
|
||||
const available = getHeapStatistics().total_available_size;
|
||||
if (required > available) {
|
||||
return measuredHeapConstraint(
|
||||
operation,
|
||||
reason,
|
||||
{
|
||||
input_bytes: inputBytes,
|
||||
required_bytes: required,
|
||||
available_heap_bytes: available,
|
||||
},
|
||||
remediationAction,
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
@@ -1,10 +1,6 @@
|
||||
import { getHeapStatistics } from "node:v8";
|
||||
import type { ArtifactResourceScope } from "../../resources/index.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import { jsonValueValidationSteps } from "../../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
@@ -19,10 +15,12 @@ import {
|
||||
} from "../../domain/apiContract/apiContractQuery.js";
|
||||
import { parseApiContractSteps } from "../../domain/apiContract/parseApiContract.js";
|
||||
import { parseAnalysisInput } from "../AnalysisInput.js";
|
||||
import { nativeJsonParseRequiredBytes } from "../JsonInputFile.js";
|
||||
import { parseUtf8Json } from "../Utf8JsonInput.js";
|
||||
import { apiContractEvidence } from "./ApiContractEvidence.js";
|
||||
import { readApiContract } from "./ApiContractRead.js";
|
||||
import {
|
||||
apiContractParseMemoryFailure,
|
||||
readApiContract,
|
||||
} from "./ApiContractRead.js";
|
||||
import { completeApiContractSteps } from "./ApiContractTraversal.js";
|
||||
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
|
||||
|
||||
@@ -35,26 +33,12 @@ const decodeDocument = (
|
||||
bytes: Buffer,
|
||||
path: string,
|
||||
): Result<unknown, AnalysisError> => {
|
||||
const required = nativeJsonParseRequiredBytes(bytes.length);
|
||||
const available = getHeapStatistics().total_available_size;
|
||||
if (required > available)
|
||||
return err(
|
||||
new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"Insufficient parser headroom for the admitted JSON representation expansion.",
|
||||
{
|
||||
input_bytes: bytes.length,
|
||||
required_bytes: required,
|
||||
available_heap_bytes: available,
|
||||
},
|
||||
{
|
||||
measuredExhaustion: true,
|
||||
remediationAction:
|
||||
"Select a smaller complete document or free parser memory; paging a reply does not reduce JSON parsing work.",
|
||||
},
|
||||
),
|
||||
);
|
||||
const memoryFailure = apiContractParseMemoryFailure(
|
||||
bytes.length,
|
||||
"Insufficient parser headroom for the admitted JSON representation expansion.",
|
||||
"Select a smaller complete document or free parser memory; paging a reply does not reduce JSON parsing work.",
|
||||
);
|
||||
if (memoryFailure !== undefined) return err(memoryFailure);
|
||||
try {
|
||||
const parsed = parseUtf8Json(bytes, operation, path);
|
||||
return parsed.ok
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { decodeStrictUtf8 } from "../../domain/strictUtf8.js";
|
||||
import { getHeapStatistics } from "node:v8";
|
||||
import { version } from "graphql";
|
||||
import type { ArtifactResourceScope } from "../../resources/index.js";
|
||||
import {
|
||||
primaryAnalysisError,
|
||||
type AnalysisError,
|
||||
} from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import { fileSnapshotPartialObservationSchema } from "../../domain/fileSnapshotObservation.js";
|
||||
import {
|
||||
API_CONTRACT_OPERATION as operation,
|
||||
@@ -20,11 +16,13 @@ import { graphqlContractSchema } from "../../domain/apiContract/graphqlContract.
|
||||
import { GraphqlInventory } from "../../domain/apiContract/GraphqlInventory.js";
|
||||
import { parseGraphqlContractSteps } from "../../domain/apiContract/parseGraphqlContract.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { nativeJsonParseRequiredBytes } from "../JsonInputFile.js";
|
||||
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
|
||||
import { completeApiContractSteps } from "./ApiContractTraversal.js";
|
||||
import { apiContractEvidence } from "./ApiContractEvidence.js";
|
||||
import { readApiContract } from "./ApiContractRead.js";
|
||||
import {
|
||||
apiContractParseMemoryFailure,
|
||||
readApiContract,
|
||||
} from "./ApiContractRead.js";
|
||||
|
||||
type GraphqlInput = Extract<InspectApiContractInput, { format: "graphql-sdl" }>;
|
||||
const inputFailure = (parameter: string, message: string, cause?: unknown) =>
|
||||
@@ -36,27 +34,12 @@ const decode = (
|
||||
bytes: Buffer,
|
||||
parameter: string,
|
||||
): Result<string, AnalysisError> => {
|
||||
// Reuse the existing conservative document-expansion admission before text/AST allocation.
|
||||
const required = nativeJsonParseRequiredBytes(bytes.length);
|
||||
const available = getHeapStatistics().total_available_size;
|
||||
if (required > available)
|
||||
return err(
|
||||
new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"Insufficient parser headroom for GraphQL text and AST expansion.",
|
||||
{
|
||||
input_bytes: bytes.length,
|
||||
required_bytes: required,
|
||||
available_heap_bytes: available,
|
||||
},
|
||||
{
|
||||
measuredExhaustion: true,
|
||||
remediationAction:
|
||||
"Select a smaller complete document or free parser memory; reply paging does not reduce parsing work.",
|
||||
},
|
||||
),
|
||||
);
|
||||
const memoryFailure = apiContractParseMemoryFailure(
|
||||
bytes.length,
|
||||
"Insufficient parser headroom for GraphQL text and AST expansion.",
|
||||
"Select a smaller complete document or free parser memory; reply paging does not reduce parsing work.",
|
||||
);
|
||||
if (memoryFailure !== undefined) return err(memoryFailure);
|
||||
try {
|
||||
return ok(decodeStrictUtf8(bytes, "preserve"));
|
||||
} catch (cause) {
|
||||
|
||||
@@ -160,6 +160,24 @@ export class AnalysisResourceConstraintError extends AnalysisError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Refuse a measured heap shortfall while retaining the producer's byte counts and recovery. */
|
||||
export const measuredHeapConstraint = (
|
||||
operation: string,
|
||||
reason: string,
|
||||
reportedLimits: Readonly<Record<string, JsonValue>>,
|
||||
remediationAction: string,
|
||||
): AnalysisResourceConstraintError =>
|
||||
new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
reason,
|
||||
reportedLimits,
|
||||
{
|
||||
measuredExhaustion: true,
|
||||
remediationAction,
|
||||
},
|
||||
);
|
||||
|
||||
const resourceConstraintRecoveryFrom = (
|
||||
options: ResourceConstraintRecovery | undefined,
|
||||
): ResourceConstraintRecovery => {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { getHeapStatistics } from "node:v8";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { inspectApiContractEvidence } from "../../src/application/apiContract/ApiContractService.js";
|
||||
import { nativeJsonParseRequiredBytes } from "../../src/application/JsonInputFile.js";
|
||||
import { graphqlContractSchema } from "../../src/domain/apiContract/graphqlContract.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { ArtifactResourceScope } from "../../src/resources/ArtifactResourceScope.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
vi.mock("node:v8", { spy: true });
|
||||
|
||||
it("rechecks parser heap headroom for independently read GraphQL operations", async () => {
|
||||
const schema = "type Query { greeting: String }";
|
||||
const ops = "{ greeting }";
|
||||
const root = await createTestTempDirectory("rea-graphql-heap-");
|
||||
const path = join(root, "schema.graphql");
|
||||
const operations_path = join(root, "operations.graphql");
|
||||
await writeFile(path, schema);
|
||||
await writeFile(operations_path, ops);
|
||||
const sample = getHeapStatistics();
|
||||
const required = nativeJsonParseRequiredBytes(Buffer.byteLength(ops));
|
||||
vi.mocked(getHeapStatistics)
|
||||
.mockReturnValueOnce({
|
||||
...sample,
|
||||
total_available_size: nativeJsonParseRequiredBytes(
|
||||
Buffer.byteLength(schema),
|
||||
),
|
||||
})
|
||||
.mockReturnValueOnce({ ...sample, total_available_size: required - 1 });
|
||||
const resources = new ArtifactResourceScope();
|
||||
try {
|
||||
const result = await inspectApiContractEvidence(
|
||||
{ path, operations_path, format: "graphql-sdl" },
|
||||
resources,
|
||||
);
|
||||
if (result.ok) throw new Error("Expected an operations heap refusal");
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "memory",
|
||||
reportedLimits: {
|
||||
required_bytes: required,
|
||||
available_heap_bytes: required - 1,
|
||||
},
|
||||
recovery: { measuredExhaustion: true },
|
||||
});
|
||||
const evidence = parseEvidence(result.error.partialObservation);
|
||||
const partial = graphqlContractSchema.parse(evidence.normalized_result);
|
||||
expect(partial.artifact.path).toBe(path);
|
||||
expect(partial.operations_artifact?.path).toBe(operations_path);
|
||||
expect(partial.operations_artifact?.sha256).toBe(
|
||||
createHash("sha256").update(ops).digest("hex"),
|
||||
);
|
||||
} finally {
|
||||
vi.mocked(getHeapStatistics).mockReset();
|
||||
await resources.close();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user