@@ -6,61 +6,76 @@ import { getHeapStatistics } from "node:v8";
66import parser from "stream-json/parser.js" ;
77import streamValues from "stream-json/streamers/stream-values.js" ;
88
9- import { withRegularFile } from "./application/RegularFileRead.js" ;
9+ import { RegularFileChangedError } from "../filesystem/RegularFile.js" ;
10+ import { withRegularFile } from "./RegularFileRead.js" ;
1011import {
1112 JSON_BYTE_ORDER_MARK_MESSAGE ,
1213 JSON_INPUT_RESOURCE_REMEDIATION ,
1314 parseUtf8Json ,
14- } from "./application/ Utf8JsonInput.js" ;
15+ } from "./Utf8JsonInput.js" ;
1516import {
1617 AnalysisInputError ,
1718 AnalysisResourceConstraintError ,
18- } from "./domain/analysisErrorCore.js" ;
19- import { err , ok , type Result } from "./domain/result.js" ;
19+ } from ".. /domain/analysisErrorCore.js" ;
20+ import { err , ok , type Result } from ".. /domain/result.js" ;
2021
21- type JsonFileFailure = AnalysisInputError | AnalysisResourceConstraintError ;
22+ type JsonInputFileFailure =
23+ | AnalysisInputError
24+ | AnalysisResourceConstraintError ;
2225const READ_CHUNK_BYTES = 64 * 1024 ;
23- const PACKED_STRING_PART_CODE_UNITS = 64 * 1024 ;
26+ const PACKED_TOKEN_PART_CODE_UNITS = 64 * 1024 ;
2427// Retain native-parser speed for modest inputs while bounding its extra copies.
2528// This selects an implementation; larger files remain accepted through streaming.
2629const NATIVE_PARSE_READ_BUDGET = 8 * 1024 * 1024 ;
2730
31+ /** Keep native parsing only when input copies and value expansion fit live headroom. */
32+ const nativeParseFits = ( inputBytes : number ) : boolean =>
33+ inputBytes <= NATIVE_PARSE_READ_BUDGET &&
34+ // The assembler estimate reserves up to 128 bytes per two-byte container.
35+ // Allow that 64x expansion plus byte/text copies before native JSON.parse,
36+ // whose individual container allocations cannot be intercepted.
37+ inputBytes * 72 + READ_CHUNK_BYTES <=
38+ getHeapStatistics ( ) . total_available_size ;
39+
2840/** Parse strict UTF-8 JSON without requiring a whole-document string. */
29- export const readCliJsonFile = (
41+ export const readJsonInputFile = (
3042 path : string ,
3143 operation : string ,
3244 signal ?: AbortSignal ,
33- ) : Promise < Result < unknown , JsonFileFailure > > =>
45+ ) : Promise < Result < unknown , JsonInputFileFailure > > =>
3446 withRegularFile (
3547 path ,
3648 async ( handle , stats ) => {
3749 let found = false ;
3850 let value : unknown ;
3951 try {
40- const prefix =
41- stats . size <= NATIVE_PARSE_READ_BUDGET
42- ? await readPrefix ( handle , stats . size + 1 , signal )
43- : undefined ;
44- if ( prefix ?. complete === true ) {
52+ const prefix = nativeParseFits ( stats . size )
53+ ? await readPrefix ( handle , stats . size + 1 , signal )
54+ : undefined ;
55+ if ( prefix !== undefined ) {
56+ if ( ! prefix . complete || prefix . bytes . length !== stats . size )
57+ throw new RegularFileChangedError ( path ) ;
4558 const parsed = parseUtf8Json (
4659 prefix . bytes ,
4760 operation ,
4861 path ,
49- "cli- json-input" ,
62+ "json-file -input" ,
5063 ) ;
5164 return parsed . ok
5265 ? ok ( parsed . value )
5366 : err ( invalidJson ( operation , parsed . error , parsed . cause ) ) ;
5467 }
5568 await pipeline (
56- decodedChunks ( handle , signal , prefix ?. bytes ) ,
69+ decodedChunks ( handle , stats . size , path , signal ) ,
5770 parser . asStream ( {
5871 jsonStreaming : false ,
5972 streamValues : false ,
6073 packKeys : false ,
6174 packStrings : false ,
75+ packNumbers : false ,
6276 } ) ,
63- packJsonStrings ( operation , stats . size ) ,
77+ packJsonScalars ( operation , stats . size , path ) ,
78+ admitJsonAssembly ( operation , stats . size , path ) ,
6479 streamValues . asStream ( ) ,
6580 async ( rows : AsyncIterable < unknown > ) => {
6681 for await ( const row of rows ) {
@@ -107,8 +122,9 @@ export const readCliJsonFile = (
107122 new AnalysisResourceConstraintError (
108123 operation ,
109124 "memory" ,
110- "An individual JSON string exceeds the runtime string limit" ,
125+ "An individual JSON string or number token exceeds the runtime string limit" ,
111126 {
127+ input_path : path ,
112128 input_file_bytes : stats . size ,
113129 max_string_code_units : constants . MAX_STRING_LENGTH ,
114130 } ,
@@ -121,12 +137,16 @@ export const readCliJsonFile = (
121137 throw cause ;
122138 }
123139 } ,
124- signal ,
140+ { signal } ,
125141 ) ;
126142
127- const packJsonStrings = ( operation : string , inputFileBytes : number ) =>
143+ const packJsonScalars = (
144+ operation : string ,
145+ inputFileBytes : number ,
146+ path : string ,
147+ ) =>
128148 async function * ( tokens : AsyncIterable < unknown > ) : AsyncGenerator < unknown > {
129- let kind : "keyValue" | "stringValue" | undefined ;
149+ let kind : "keyValue" | "stringValue" | "numberValue" | undefined ;
130150 let length = 0 ;
131151 let value = "" ;
132152 let parts : string [ ] = [ ] ;
@@ -139,32 +159,47 @@ const packJsonStrings = (operation: string, inputFileBytes: number) =>
139159 case "startString" :
140160 kind = token . name === "startKey" ? "keyValue" : "stringValue" ;
141161 break ;
162+ case "startNumber" :
163+ kind = "numberValue" ;
164+ break ;
165+ case "numberChunk" :
142166 case "stringChunk" :
143167 if (
144168 kind === undefined ||
145169 ! ( "value" in token ) ||
146170 typeof token . value !== "string"
147171 )
148- throw new Error ( "Unexpected JSON string fragment" ) ;
172+ throw new Error ( "Unexpected JSON scalar fragment" ) ;
149173 length += token . value . length ;
150174 if ( length > constants . MAX_STRING_LENGTH )
151175 throw new RangeError ( "Invalid string length" ) ;
152176 parts . push ( token . value ) ;
153177 partLength += token . value . length ;
154- if ( partLength >= PACKED_STRING_PART_CODE_UNITS ) {
178+ if ( partLength >= PACKED_TOKEN_PART_CODE_UNITS ) {
155179 // The tokenizer emits short fragments. Coalesce them before retaining
156- // a string so millions of substring/rope nodes cannot exhaust the heap
180+ // a scalar so millions of substring/rope nodes cannot exhaust the heap
157181 // before the native string-length constraint can be reported.
158- requireStringAssemblyHeadroom ( operation , inputFileBytes , length ) ;
182+ requireStringAssemblyHeadroom (
183+ operation ,
184+ inputFileBytes ,
185+ path ,
186+ length ,
187+ ) ;
159188 value += parts . join ( "" ) ;
160189 parts = [ ] ;
161190 partLength = 0 ;
162191 }
163192 break ;
164193 case "endKey" :
165194 case "endString" :
166- if ( kind === undefined ) throw new Error ( "Unexpected JSON string end" ) ;
167- requireStringAssemblyHeadroom ( operation , inputFileBytes , length ) ;
195+ case "endNumber" :
196+ if ( kind === undefined ) throw new Error ( "Unexpected JSON scalar end" ) ;
197+ requireStringAssemblyHeadroom (
198+ operation ,
199+ inputFileBytes ,
200+ path ,
201+ length ,
202+ ) ;
168203 yield { name : kind , value : value + parts . join ( "" ) } ;
169204 kind = undefined ;
170205 length = 0 ;
@@ -178,22 +213,78 @@ const packJsonStrings = (operation: string, inputFileBytes: number) =>
178213 }
179214 } ;
180215
216+ /** Admit the retained value graph before the upstream assembler grows it. */
217+ const admitJsonAssembly = (
218+ operation : string ,
219+ inputFileBytes : number ,
220+ path : string ,
221+ ) =>
222+ async function * ( tokens : AsyncIterable < unknown > ) : AsyncGenerator < unknown > {
223+ let projectedBytes = 0 ;
224+ let nextCheck = 0 ;
225+ for await ( const token of tokens ) {
226+ if ( typeof token !== "object" || token === null || ! ( "name" in token ) )
227+ throw new Error ( "Unexpected JSON assembly token" ) ;
228+ if ( token . name === "startObject" || token . name === "startArray" ) {
229+ projectedBytes += 128 ;
230+ } else if ( token . name === "keyValue" || token . name === "stringValue" ) {
231+ if ( ! ( "value" in token ) || typeof token . value !== "string" )
232+ throw new Error ( "Unexpected packed JSON string" ) ;
233+ projectedBytes += 64 + token . value . length * 2 ;
234+ } else if (
235+ token . name === "numberValue" ||
236+ token . name === "nullValue" ||
237+ token . name === "trueValue" ||
238+ token . name === "falseValue"
239+ ) {
240+ projectedBytes += 64 ;
241+ }
242+ if ( projectedBytes >= nextCheck ) {
243+ const heap = getHeapStatistics ( ) ;
244+ // Conservative capacity for containers, property/array slots and UTF-16
245+ // values. Keep another whole projection available for container growth,
246+ // plus the next chunk of estimates between samples. This is admission
247+ // against live runtime headroom, not a fixed document-size policy.
248+ const requiredBytes = projectedBytes + READ_CHUNK_BYTES ;
249+ if ( requiredBytes > heap . total_available_size )
250+ throw new AnalysisResourceConstraintError (
251+ operation ,
252+ "memory" ,
253+ "Insufficient heap headroom to materialize the complete JSON value" ,
254+ {
255+ input_path : path ,
256+ input_file_bytes : inputFileBytes ,
257+ projected_value_bytes : projectedBytes ,
258+ assembly_headroom_bytes : requiredBytes ,
259+ available_heap_bytes : heap . total_available_size ,
260+ heap_size_limit_bytes : heap . heap_size_limit ,
261+ } ,
262+ { remediationAction : JSON_INPUT_RESOURCE_REMEDIATION } ,
263+ ) ;
264+ nextCheck = projectedBytes + READ_CHUNK_BYTES ;
265+ }
266+ yield token ;
267+ }
268+ } ;
269+
181270const requireStringAssemblyHeadroom = (
182271 operation : string ,
183272 inputFileBytes : number ,
273+ path : string ,
184274 stringCodeUnits : number ,
185275) : void => {
186- if ( stringCodeUnits < PACKED_STRING_PART_CODE_UNITS ) return ;
276+ if ( stringCodeUnits < PACKED_TOKEN_PART_CODE_UNITS ) return ;
187277 const heap = getHeapStatistics ( ) ;
188278 // Concatenation or key interning may flatten the retained rope. Reserve its
189279 // UTF-16 representation and the next coalesced part before that allocation.
190- const requiredBytes = 2 * ( stringCodeUnits + PACKED_STRING_PART_CODE_UNITS ) ;
280+ const requiredBytes = 2 * ( stringCodeUnits + PACKED_TOKEN_PART_CODE_UNITS ) ;
191281 if ( requiredBytes > heap . total_available_size )
192282 throw new AnalysisResourceConstraintError (
193283 operation ,
194284 "memory" ,
195285 "Insufficient heap headroom to assemble a complete JSON string" ,
196286 {
287+ input_path : path ,
197288 input_file_bytes : inputFileBytes ,
198289 string_code_units : stringCodeUnits ,
199290 string_assembly_headroom_bytes : requiredBytes ,
@@ -208,8 +299,9 @@ const requireStringAssemblyHeadroom = (
208299
209300async function * decodedChunks (
210301 handle : FileHandle ,
302+ admittedBytes : number ,
303+ path : string ,
211304 signal : AbortSignal | undefined ,
212- prefix ?: Uint8Array ,
213305) : AsyncGenerator < string > {
214306 const decoder = new TextDecoder ( "utf-8" , { fatal : true , ignoreBOM : true } ) ;
215307 let leading = true ;
@@ -220,25 +312,25 @@ async function* decodedChunks(
220312 }
221313 return text ;
222314 } ;
223- if ( prefix !== undefined )
224- for ( let offset = 0 ; offset < prefix . length ; offset += READ_CHUNK_BYTES ) {
225- signal ?. throwIfAborted ( ) ;
226- yield checked (
227- decoder . decode ( prefix . subarray ( offset , offset + READ_CHUNK_BYTES ) , {
228- stream : true ,
229- } ) ,
230- ) ;
231- }
232315 const bytes = Buffer . allocUnsafe ( READ_CHUNK_BYTES ) ;
316+ let observedBytes = 0 ;
233317 while ( true ) {
234318 signal ?. throwIfAborted ( ) ;
235- const read = await handle . read ( bytes , 0 , bytes . length , null ) ;
319+ const read = await handle . read (
320+ bytes ,
321+ 0 ,
322+ Math . min ( bytes . length , admittedBytes - observedBytes + 1 ) ,
323+ null ,
324+ ) ;
236325 signal ?. throwIfAborted ( ) ;
237326 if ( read . bytesRead === 0 ) break ;
327+ observedBytes += read . bytesRead ;
328+ if ( observedBytes > admittedBytes ) throw new RegularFileChangedError ( path ) ;
238329 yield checked (
239330 decoder . decode ( bytes . subarray ( 0 , read . bytesRead ) , { stream : true } ) ,
240331 ) ;
241332 }
333+ if ( observedBytes !== admittedBytes ) throw new RegularFileChangedError ( path ) ;
242334 yield checked ( decoder . decode ( ) ) ;
243335}
244336
@@ -264,8 +356,7 @@ const readPrefix = async (
264356 return { bytes : bytes . subarray ( 0 , offset ) , complete : true } ;
265357 offset += read . bytesRead ;
266358 }
267- // The file grew after admission. Continue from this same handle, preserving
268- // the prefix already read rather than reopening or dropping its bytes.
359+ // One byte beyond the admitted extent proves the selected file changed.
269360 return { bytes, complete : false } ;
270361} ;
271362
0 commit comments