Skip to content

Commit

Permalink
refactor: find_free_port has preferred port
Browse files Browse the repository at this point in the history
  • Loading branch information
peterwht committed Dec 17, 2024
1 parent 8d14f8c commit 72b404c
Show file tree
Hide file tree
Showing 9 changed files with 24 additions and 17 deletions.
2 changes: 1 addition & 1 deletion crates/pop-cli/src/commands/up/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ mod tests {
}

async fn start_test_environment() -> anyhow::Result<(Child, u16, TempDir)> {
let random_port = find_free_port();
let random_port = find_free_port(None);
let temp_dir = new_environment("testing")?;
let current_dir = env::current_dir().expect("Failed to get current directory");
mock_build_process(
Expand Down
4 changes: 2 additions & 2 deletions crates/pop-cli/src/common/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub async fn request_signature(call_data: Vec<u8>, rpc: String) -> anyhow::Resul
let ui = FrontendFromString::new(include_str!("../assets/index.html").to_string());

let transaction_data = TransactionData::new(rpc, call_data);
// Starts server with random port.
let mut wallet = WalletIntegrationManager::new(ui, transaction_data, None);
// Starts server with port 9090.
let mut wallet = WalletIntegrationManager::new(ui, transaction_data, Some(9090));
let url = wallet.server_url.clone();
log::step(format!("Wallet signing portal started at http://{url}."))?;

Expand Down
9 changes: 4 additions & 5 deletions crates/pop-cli/src/wallet_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ impl WalletIntegrationManager {
pub fn new<F: Frontend>(
frontend: F,
payload: TransactionData,
maybe_port: Option<String>,
maybe_port: Option<u16>,
) -> Self {
let port = if let Some(port) = maybe_port { port } else { find_free_port().to_string() };
let port = if let Some(port) = maybe_port { port } else { find_free_port(maybe_port) };
Self::new_with_address(frontend, payload, format!("127.0.0.1:{}", port))
}

Expand Down Expand Up @@ -284,10 +284,9 @@ mod tests {
#[tokio::test]
async fn new_works() {
let frontend = FrontendFromString::new(TEST_HTML.to_string());
let mut wim =
WalletIntegrationManager::new(frontend, default_payload(), Some("9090".to_string()));
let mut wim = WalletIntegrationManager::new(frontend, default_payload(), Some(9190));

assert_eq!(wim.server_url, "127.0.0.1:9090");
assert_eq!(wim.server_url, "127.0.0.1:9190");
assert_eq!(wim.is_running(), true);
assert!(wim.state.lock().await.shutdown_tx.is_some());
assert!(wim.state.lock().await.signed_payload.is_none());
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-cli/tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl TransactionData {
async fn contract_lifecycle() -> Result<()> {
const WALLET_INT_URI: &str = "http://127.0.0.1:9090";
const WAIT_SECS: u64 = 240;
let endpoint_port = find_free_port();
let endpoint_port = find_free_port(None);
let default_endpoint: &str = &format!("ws://127.0.0.1:{}", endpoint_port);
let temp = tempfile::tempdir().unwrap();
let temp_dir = temp.path();
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-cli/tests/parachain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async fn parachain_lifecycle() -> Result<()> {
// Overwrite the config file to manually set the port to test pop call parachain.
let network_toml_path = temp_parachain_dir.join("network.toml");
fs::create_dir_all(&temp_parachain_dir)?;
let random_port = find_free_port();
let random_port = find_free_port(None);
let localhost_url = format!("ws://127.0.0.1:{}", random_port);
fs::write(
&network_toml_path,
Expand Down
16 changes: 12 additions & 4 deletions crates/pop-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,20 @@ pub fn target() -> Result<&'static str, Error> {
Err(Error::UnsupportedPlatform { arch: ARCH, os: OS })
}

/// Finds an available port by binding to port 0 and retrieving the assigned port.
pub fn find_free_port() -> u16 {
/// Checks if preferred port is available, otherwise returns a random available port.
pub fn find_free_port(preferred_port: Option<u16>) -> u16 {
// Try to bind to preferred port if provided.
if let Some(port) = preferred_port {
if TcpListener::bind(format!("127.0.0.1:{}", port)).is_ok() {
return port;
}
}

// Else, fallback to a random available port
TcpListener::bind("127.0.0.1:0")
.expect("Failed to bind to an available port")
.local_addr()
.expect("Failed to retrieve local address")
.expect("Failed to retrieve local address. This should never occur.")
.port()
}

Expand Down Expand Up @@ -105,7 +113,7 @@ mod test {

#[test]
fn find_free_port_works() -> Result<()> {
let port = find_free_port();
let port = find_free_port(None);
let addr = format!("127.0.0.1:{}", port);
// Constructs the TcpListener from the above port
let listener = TcpListener::bind(&addr);
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-contracts/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ mod tests {

#[tokio::test]
async fn call_works() -> Result<()> {
let random_port = find_free_port();
let random_port = find_free_port(None);
let localhost_url = format!("ws://127.0.0.1:{}", random_port);
let temp_dir = new_environment("testing")?;
let current_dir = env::current_dir().expect("Failed to get current directory");
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-contracts/src/node/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ mod tests {
#[ignore = "Works fine locally but is causing issues when running tests in parallel in the CI environment."]
#[tokio::test]
async fn run_contracts_node_works() -> Result<(), Error> {
let random_port = find_free_port();
let random_port = find_free_port(None);
let localhost_url = format!("ws://127.0.0.1:{}", random_port);
let local_url = url::Url::parse(&localhost_url)?;

Expand Down
2 changes: 1 addition & 1 deletion crates/pop-contracts/src/up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ mod tests {

#[tokio::test]
async fn instantiate_and_upload() -> Result<()> {
let random_port = find_free_port();
let random_port = find_free_port(None);
let localhost_url = format!("ws://127.0.0.1:{}", random_port);
let temp_dir = new_environment("testing")?;
let current_dir = env::current_dir().expect("Failed to get current directory");
Expand Down

0 comments on commit 72b404c

Please sign in to comment.