Skip to content

Commit

Permalink
Kill process upon server stop
Browse files Browse the repository at this point in the history
  • Loading branch information
fluiddot committed May 7, 2024
1 parent 3566662 commit 8e17947
Showing 1 changed file with 42 additions and 18 deletions.
60 changes: 42 additions & 18 deletions src/lib/site-server-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,27 @@ export default class SiteServerProcess {

async start(): Promise< void > {
return new Promise( ( resolve, reject ) => {
const spawnListener = async () => {
const messageId = this.sendMessage( 'start-server' );
try {
const { php } = await this.waitForResponse< Pick< SiteServerProcess, 'php' > >(
'start-server',
messageId
);
this.php = php;
// Removing exit listener as we only need it upon starting
this.process?.off( 'exit', exitListener );
resolve();
} catch ( error ) {
reject( error );
}
};
const exitListener = ( code: number ) => {
if ( code !== 0 ) {
reject( new Error( `Site server process exited with code ${ code } upon starting` ) );
}
};

this.process = utilityProcess
.fork( SITE_SERVER_PROCESS_MODULE_PATH, [ JSON.stringify( this.options ) ], {
serviceName: 'studio-site-server',
Expand All @@ -36,31 +57,16 @@ export default class SiteServerProcess {
STUDIO_APP_LOGS_PATH: app.getPath( 'logs' ),
},
} )
.on( 'spawn', async () => {
const messageId = this.sendMessage( 'start-server' );
try {
const { php } = await this.waitForResponse< Pick< SiteServerProcess, 'php' > >(
'start-server',
messageId
);
this.php = php;
resolve();
} catch ( error ) {
reject( error );
}
} )
.on( 'exit', ( code ) => {
if ( code !== 0 ) {
reject( new Error( `Site server process exited with code: ${ code }` ) );
}
} );
.on( 'spawn', spawnListener )
.on( 'exit', exitListener );
} );
}

async stop() {
const message = 'stop-server';
const messageId = this.sendMessage( message );
await this.waitForResponse( message, messageId );
await this.#killProcess();
}

async runPhp( data: PHPRunOptions ): Promise< string > {
Expand Down Expand Up @@ -122,4 +128,22 @@ export default class SiteServerProcess {
process.addListener( 'message', handler );
} );
}

async #killProcess(): Promise< void > {
const process = this.process;
if ( ! process ) {
throw Error( 'Server process is not running' );
}

return new Promise( ( resolve, reject ) => {
process.once( 'exit', ( code ) => {
if ( code !== 0 ) {
reject( new Error( `Site server process exited with code ${ code } upon stopping` ) );
return;
}
resolve();
} );
process.kill();
} );
}
}

0 comments on commit 8e17947

Please sign in to comment.