Skip to content

Commit

Permalink
Studio: Reclaim unavailable port after site deletion (#195)
Browse files Browse the repository at this point in the history
  • Loading branch information
Siobhan Bamber committed Jun 5, 2024
1 parent 2c218d2 commit 5c06f42
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"archiver": "^6.0.1",
"compressible": "2.0.18",
"compression": "1.7.4",
"cross-port-killer": "^1.4.0",
"date-fns": "^3.3.1",
"electron-squirrel-startup": "^1.0.0",
"express": "4.19.2",
Expand Down
21 changes: 21 additions & 0 deletions src/lib/port-finder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import http from 'http';
import killPort from 'cross-port-killer';

const DEFAULT_PORT = 8881;

Expand Down Expand Up @@ -72,6 +73,26 @@ class PortFinder {
this.#unavailablePorts.push( port );
}
}

public releasePort( port?: number ): void {
if ( port && this.#unavailablePorts.includes( port ) ) {
killPort( port )
.then( () => {
console.log( `Killed processes using port ${ port }` );
} )
.catch( ( err ) => {
console.error( `Failed to kill processes using port ${ port }: ${ err.message }` );
} )
.finally( () => {
// Ensure port finder cycles through newly reclaimed ports by removing
// from #unavailablePorts list and resetting #openPort.
this.#unavailablePorts = this.#unavailablePorts.filter(
( unavailablePort ) => unavailablePort !== port
);
this.#openPort = DEFAULT_PORT;
} );
}
}
}

export const portFinder = PortFinder.getInstance();
1 change: 1 addition & 0 deletions src/site-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export class SiteServer {
}
await this.stop();
servers.delete( this.details.id );
portFinder.releasePort( this.details.port );
}

async start() {
Expand Down

0 comments on commit 5c06f42

Please sign in to comment.