@@ -58,13 +58,13 @@ async function uploadToCFR2(s3Client, relativePath, data) {
5858 return ;
5959}
6060
61- function taskFinishHandler (
62- { id , success , failedTasks , usedCacheFiles } ,
63- allUsedCacheFiles
64- ) {
65- // Collect cache files used by this worker
66- if ( usedCacheFiles ) {
67- usedCacheFiles . forEach ( file => allUsedCacheFiles . add ( file ) ) ;
61+ // Global set to track which cache files are used across all workers
62+ let globalUsedCacheFiles = null ;
63+
64+ function taskFinishHandler ( { id , success , failedTasks , usedCacheFiles } ) {
65+ // Collect cache files used by this worker into the global set
66+ if ( usedCacheFiles && globalUsedCacheFiles ) {
67+ usedCacheFiles . forEach ( file => globalUsedCacheFiles . add ( file ) ) ;
6868 }
6969
7070 if ( failedTasks . length === 0 ) {
@@ -104,7 +104,7 @@ async function createWork() {
104104 }
105105
106106 // Track which cache files are used during this build
107- const usedCacheFiles = new Set ( ) ;
107+ globalUsedCacheFiles = new Set ( ) ;
108108
109109 // On a 16-core machine, 8 workers were optimal (and slightly faster than 16)
110110 const numWorkers = Math . max ( Math . floor ( cpus ( ) . length / 2 ) , 2 ) ;
@@ -174,7 +174,7 @@ async function createWork() {
174174 } ,
175175 } ) ;
176176 let hasErrors = false ;
177- worker . on ( 'message' , data => ( hasErrors = taskFinishHandler ( data , usedCacheFiles ) ) ) ;
177+ worker . on ( 'message' , data => ( hasErrors = taskFinishHandler ( data ) ) ) ;
178178 worker . on ( 'error' , reject ) ;
179179 worker . on ( 'exit' , code => {
180180 if ( code !== 0 ) {
@@ -195,7 +195,7 @@ async function createWork() {
195195 noCache,
196196 usedCacheFiles : mainThreadUsedFiles ,
197197 } ) . then ( data => {
198- if ( taskFinishHandler ( data , usedCacheFiles ) ) {
198+ if ( taskFinishHandler ( data ) ) {
199199 throw new Error ( `Worker[${ data . id } ] had some errors.` ) ;
200200 }
201201 } )
@@ -207,17 +207,13 @@ async function createWork() {
207207 if ( ! noCache ) {
208208 try {
209209 const allFiles = await readdir ( CACHE_DIR ) ;
210- let cleanedCount = 0 ;
211-
212- for ( const file of allFiles ) {
213- if ( ! usedCacheFiles . has ( file ) ) {
214- await rm ( path . join ( CACHE_DIR , file ) , { force : true } ) ;
215- cleanedCount ++ ;
216- }
217- }
210+ const filesToDelete = allFiles . filter ( file => ! globalUsedCacheFiles . has ( file ) ) ;
218211
219- if ( cleanedCount > 0 ) {
220- console . log ( `🧹 Cleaned up ${ cleanedCount } unused cache files` ) ;
212+ if ( filesToDelete . length > 0 ) {
213+ await Promise . all (
214+ filesToDelete . map ( file => rm ( path . join ( CACHE_DIR , file ) , { force : true } ) )
215+ ) ;
216+ console . log ( `🧹 Cleaned up ${ filesToDelete . length } unused cache files` ) ;
221217 }
222218 } catch ( err ) {
223219 console . warn ( 'Failed to clean unused cache files:' , err ) ;
0 commit comments