@@ -19,6 +19,29 @@ var lib = require('../index.js');
1919
2020var HydrationError = lib . HydrationError ;
2121
22+ var tasksPerProcess = process . env . TASKS_PER_PROCESS || 100 ;
23+ var taskCount = 0 ;
24+ var currentChild ;
25+
26+ var getOrForkChild = function ( ) {
27+ taskCount += 1 ;
28+ //console.log("currentChild", currentChild)
29+ if ( taskCount < tasksPerProcess && currentChild ) {
30+ currentChild . removeAllListeners ( ) ;
31+ currentChild . stdout . removeAllListeners ( ) ;
32+ currentChild . stderr . removeAllListeners ( ) ;
33+ return currentChild ;
34+ }
35+ else {
36+ taskCount = 0 ;
37+ if ( currentChild ) {
38+ currentChild . kill ( 'SIGKILL' ) ;
39+ }
40+ currentChild = fork ( __dirname + '/child-process.js' , { silent : true } ) ;
41+ return currentChild ;
42+ }
43+ } ;
44+
2245module . exports = function ( hydraterFunction , logger , errLogger ) {
2346 if ( ! errLogger ) {
2447 errLogger = logger ;
@@ -39,7 +62,7 @@ module.exports = function(hydraterFunction, logger, errLogger) {
3962
4063 async . waterfall ( [
4164 function performHydration ( cb ) {
42- var child = fork ( __dirname + '/child-process.js' , { silent : true } ) ;
65+ var child = getOrForkChild ( ) ;
4366 var stderr = "" ;
4467 var stdout = "" ;
4568 var timeout ;
@@ -50,6 +73,10 @@ module.exports = function(hydraterFunction, logger, errLogger) {
5073 var cleaner = function ( err , changes ) {
5174 if ( ! cleaner . called ) {
5275 cleaner . called = true ;
76+ if ( err ) {
77+ currentChild . kill ( 'SIGKILL' ) ;
78+ currentChild = null ;
79+ }
5380 cb ( err , changes ) ;
5481 }
5582 if ( stdout !== "" ) {
@@ -132,6 +159,7 @@ module.exports = function(hydraterFunction, logger, errLogger) {
132159 if ( child . connected ) {
133160 child . kill ( 'SIGKILL' ) ;
134161 }
162+ currentChild = null ;
135163 cleaner ( null , changes ) ;
136164 } , process . env . TIMEOUT / 6 || 10 * 1000 ) ;
137165 }
0 commit comments