@@ -19,6 +19,28 @@ 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+ if ( taskCount < tasksPerProcess && currentChild ) {
29+ currentChild . removeAllListeners ( ) ;
30+ currentChild . stdout . removeAllListeners ( ) ;
31+ currentChild . stderr . removeAllListeners ( ) ;
32+ return currentChild ;
33+ }
34+ else {
35+ taskCount = 0 ;
36+ if ( currentChild ) {
37+ currentChild . kill ( 'SIGKILL' ) ;
38+ }
39+ currentChild = fork ( __dirname + '/child-process.js' , { silent : true } ) ;
40+ return currentChild ;
41+ }
42+ } ;
43+
2244module . exports = function ( hydraterFunction , logger , errLogger ) {
2345 if ( ! errLogger ) {
2446 errLogger = logger ;
@@ -39,7 +61,7 @@ module.exports = function(hydraterFunction, logger, errLogger) {
3961
4062 async . waterfall ( [
4163 function performHydration ( cb ) {
42- var child = fork ( __dirname + '/child-process.js' , { silent : true } ) ;
64+ var child = getOrForkChild ( ) ;
4365 var stderr = "" ;
4466 var stdout = "" ;
4567 var timeout ;
@@ -50,6 +72,10 @@ module.exports = function(hydraterFunction, logger, errLogger) {
5072 var cleaner = function ( err , changes ) {
5173 if ( ! cleaner . called ) {
5274 cleaner . called = true ;
75+ if ( err ) {
76+ currentChild . kill ( 'SIGKILL' ) ;
77+ currentChild = null ;
78+ }
5379 cb ( err , changes ) ;
5480 }
5581 if ( stdout !== "" ) {
@@ -132,6 +158,7 @@ module.exports = function(hydraterFunction, logger, errLogger) {
132158 if ( child . connected ) {
133159 child . kill ( 'SIGKILL' ) ;
134160 }
161+ currentChild = null ;
135162 cleaner ( null , changes ) ;
136163 } , process . env . TIMEOUT / 6 || 10 * 1000 ) ;
137164 }
0 commit comments