@@ -4,21 +4,17 @@ const loaderWorkers: Record<string, Array<Worker>> = {}
44
55const KillMsg = '__kill__'
66
7- async function gracefullyKillWorker ( worker : Worker ) {
8- await new Promise < void > ( ( resolve ) => {
9- const onMessage = ( msg : any ) => {
10- if ( msg === KillMsg ) {
11- worker . off ( 'message' , onMessage )
12- resolve ( )
13- }
14- }
15- worker . on ( 'message' , onMessage )
16- worker . postMessage ( KillMsg )
17- } )
18- await worker . terminate ( )
7+ export async function runLoaderWorkerPool (
8+ binding : typeof import ( './generated-native' ) ,
9+ bindingPath : string
10+ ) {
11+ await Promise . all ( [
12+ runPoolScaler ( binding , bindingPath ) ,
13+ runWorkerTerminator ( binding ) ,
14+ ] )
1915}
2016
21- export async function createOrScalePool (
17+ async function runPoolScaler (
2218 binding : typeof import ( './generated-native' ) ,
2319 bindingPath : string
2420) {
@@ -45,7 +41,7 @@ export async function createOrScalePool(
4541 }
4642 } else if ( workers . length > concurrency ) {
4743 const workersToKill = workers . splice ( 0 , workers . length - concurrency )
48- workersToKill . forEach ( gracefullyKillWorker )
44+ workersToKill . forEach ( terminateWorker )
4945 }
5046 } catch ( _ ) {
5147 // rust channel closed, do nothing
@@ -54,7 +50,7 @@ export async function createOrScalePool(
5450 }
5551}
5652
57- export async function waitingForWorkerTermination (
53+ async function runWorkerTerminator (
5854 binding : typeof import ( './generated-native' )
5955) {
6056 while ( true ) {
@@ -66,11 +62,25 @@ export async function waitingForWorkerTermination(
6662 )
6763 if ( workerIdx > - 1 ) {
6864 const workersToKill = workers . splice ( workerIdx , 1 )
69- workersToKill . forEach ( gracefullyKillWorker )
65+ workersToKill . forEach ( terminateWorker )
7066 }
7167 } catch ( _ ) {
7268 // rust channel closed, do nothing
7369 return
7470 }
7571 }
7672}
73+
74+ async function terminateWorker ( worker : Worker ) {
75+ await new Promise < void > ( ( resolve ) => {
76+ const onMessage = ( msg : any ) => {
77+ if ( msg === KillMsg ) {
78+ worker . off ( 'message' , onMessage )
79+ resolve ( )
80+ }
81+ }
82+ worker . on ( 'message' , onMessage )
83+ worker . postMessage ( KillMsg )
84+ } )
85+ await worker . terminate ( )
86+ }
0 commit comments