refactor(controller): use state to find available port range
This commit is contained in:
@@ -122,7 +122,7 @@ impl Controller {
|
||||
let config = PGDConfig {
|
||||
version: *latest_version,
|
||||
password: utils::generate_password(),
|
||||
port: utils::find_available_port()?,
|
||||
port: utils::find_available_port(&self.ctx.state)?,
|
||||
};
|
||||
let project = Project::new(config)?;
|
||||
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
use miette::Result;
|
||||
use rand::{Rng, distr::Alphanumeric};
|
||||
|
||||
use crate::state::StateManager;
|
||||
const DEFAULT_POSTGRES_PORT: u16 = 5432;
|
||||
const PORT_SEARCH_RANGE: u16 = 100;
|
||||
|
||||
pub fn find_available_port() -> Result<u16> {
|
||||
pub fn find_available_port(state: &StateManager) -> Result<u16> {
|
||||
use std::net::TcpListener;
|
||||
|
||||
for port in DEFAULT_POSTGRES_PORT..(DEFAULT_POSTGRES_PORT + PORT_SEARCH_RANGE) {
|
||||
let starting_port = state
|
||||
.get_highest_used_port()
|
||||
.unwrap_or(DEFAULT_POSTGRES_PORT);
|
||||
|
||||
for port in starting_port..(starting_port + PORT_SEARCH_RANGE) {
|
||||
if TcpListener::bind(("127.0.0.1", port)).is_ok() {
|
||||
return Ok(port);
|
||||
}
|
||||
|
||||
@@ -88,8 +88,8 @@ impl StateManager {
|
||||
self.0.borrow_mut().instances.insert(project_name, state);
|
||||
}
|
||||
|
||||
pub fn remove(&self, project_name: &str) -> Option<InstanceState> {
|
||||
self.0.borrow_mut().instances.remove(project_name)
|
||||
pub fn get_highest_used_port(&self) -> Option<u16> {
|
||||
self.0.borrow().instances.values().map(|i| i.port).max()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user