@@ -22,32 +22,49 @@ const workerScriptPath = path.join(
2222 './profiler-worker-child.mjs' ,
2323) ;
2424
25- await createBufferedEvents ( ) ;
26-
27- const profiler = new NodejsProfiler ( getProfilerConfig ( ) ) ;
28-
29- await profiler . measureAsync ( 'profiler-worker' , async ( ) => {
30- const processes = Array . from (
31- { length : numProcs } ,
32- ( _ , i ) =>
33- new Promise ( ( resolve , reject ) => {
34- const child = spawn ( 'npx' , [ 'tsx' , workerScriptPath ] , {
35- stdio : 'pipe' ,
36- } ) ;
37-
38- child . on ( 'close' , code => {
39- if ( code === 0 ) {
40- resolve ( code ) ;
41- } else {
42- reject ( new Error ( `Process ${ i + 1 } exited with code ${ code } ` ) ) ;
43- }
44- } ) ;
45-
46- child . on ( 'error' , reject ) ;
47- } ) ,
48- ) ;
49- await Promise . all ( processes ) ;
50- } ) ;
51-
52- profiler . close ( ) ;
53- console . log ( JSON . stringify ( profiler . stats , null , 2 ) ) ;
25+ let profiler ;
26+ try {
27+ await createBufferedEvents ( ) ;
28+
29+ profiler = new NodejsProfiler ( getProfilerConfig ( ) ) ;
30+
31+ await profiler . measureAsync ( 'profiler-worker' , async ( ) => {
32+ const processes = Array . from (
33+ { length : numProcs } ,
34+ ( _ , i ) =>
35+ new Promise ( ( resolve , reject ) => {
36+ const child = spawn ( 'npx' , [ 'tsx' , workerScriptPath ] , {
37+ stdio : 'pipe' ,
38+ } ) ;
39+
40+ child . on ( 'close' , code => {
41+ if ( code === 0 ) {
42+ resolve ( code ) ;
43+ } else {
44+ reject ( new Error ( `Process ${ i + 1 } exited with code ${ code } ` ) ) ;
45+ }
46+ } ) ;
47+
48+ child . on ( 'error' , reject ) ;
49+ } ) ,
50+ ) ;
51+ await Promise . all ( processes ) ;
52+ } ) ;
53+
54+ profiler . close ( ) ;
55+ console . log ( JSON . stringify ( profiler . stats , null , 2 ) ) ;
56+ } catch ( error ) {
57+ // Ensure profiler is closed and stats are output even on error
58+ if ( profiler && profiler . stats . profilerState !== 'closed' ) {
59+ profiler . close ( ) ;
60+ }
61+ // Output stats if profiler was initialized, otherwise exit with error
62+ if ( profiler ) {
63+ console . log ( JSON . stringify ( profiler . stats , null , 2 ) ) ;
64+ // Exit successfully since we've output the stats that the test needs
65+ process . exit ( 0 ) ;
66+ } else {
67+ console . error ( 'Failed to initialize profiler:' , error ) ;
68+ process . exit ( 1 ) ;
69+ }
70+ }
0 commit comments