import path from 'path' ; import type { Worker } from 'cluster' ; import cluster from 'cluster' ; import { createPool } from 'lightning-pool' ; import type { Container } from '@tinkoff/dippy' ; import { DEBUG_ARGV , TRACE_ARGV } from '../../../config/constants' ; import { SERVER_CONFIG_MANAGER_TOKEN } from '../tokens' ; import { STDOUT_TOKEN , STDERR_TOKEN , COMMAND_PARAMETERS_TOKEN , CONFIG_ROOT_DIR_TOKEN , } from '../../../di/tokens' ; import type { Params } from '../index' ; const POOL_OPTIONS = { minIdle : 1 , min : 2 , } ; export const createWorkerPool = ( di ) => { const { env } = di . get ( COMMAND_PARAMETERS_TOKEN as Params ) ; const configManager = di . get ( SERVER_CONFIG_MANAGER_TOKEN ) ; const stdout = di . get ( STDOUT_TOKEN ) ; const stderr = di . get ( STDERR_TOKEN ) ; cluster . setupMaster ( { exec : path . resolve ( __dirname , './worker.js' ) , execArgv : [ ] . concat ( configManager . debug ? DEBUG_ARGV : [ ] , configManager . trace ? TRACE_ARGV : [ ] ) , inspectPort : process . debugPort , silent : true , cwd : di . get ( CONFIG_ROOT_DIR_TOKEN ) , } ) ; const pool = createPool ( { create : async ( ) => { const worker = cluster . fork ( { ... env , NODE_ENV : 'development' , PORT : `${ configManager . port }` , PORT_SERVER : `${ configManager . port }` , } ) ; worker . process . stdout . pipe ( stdout ) ; worker . process . stderr . pipe ( stderr ) ; worker . on ( 'exit' , ( ) => { pool . destroy ( worker ) ; } ) ; return worker ; } , destroy : ( worker ) => { worker . process . kill ( 'SIGKILL' ) ; } , reset : ( worker ) => { if ( worker . isConnected ) { worker . removeAllListeners ( 'exit' ) ; return new Promise ( ( resolve , reject ) => { worker . on ( 'exit' , ( ) => { reject ( new Error ( 'please, destroy it' ) ) ; } ) ; worker . process . kill ( 'SIGKILL' ) ; } ) ; } } , } , POOL_OPTIONS ) ; return pool ; } ;