diff --git a/Cargo.lock b/Cargo.lock index be60f86..09311dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -976,6 +976,7 @@ checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21" name = "nostr-rs-relay" version = "0.6.2" dependencies = [ + "anyhow", "bitcoin_hashes", "config", "console-subscriber", diff --git a/Cargo.toml b/Cargo.toml index ab1de06..0307961 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,3 +31,6 @@ hyper-tls = "0.5" http = { version = "0.2" } parse_duration = "2" rand = "0.8" + +[dev-dependencies] +anyhow = "1" diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 03e8a5d..e1d8a54 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,29 +1,52 @@ +use anyhow::Result; use log::*; use nostr_rs_relay::config; use nostr_rs_relay::server::start_server; +use std::net::TcpListener; use std::sync::mpsc as syncmpsc; use std::sync::mpsc::{Receiver as MpscReceiver, Sender as MpscSender}; use std::thread; use std::thread::JoinHandle; pub struct Relay { + pub port: u16, pub handle: JoinHandle<()>, pub shutdown_tx: MpscSender<()>, } -pub fn start_relay(port: u16) -> Relay { +pub fn start_relay() -> Result { let _ = env_logger::try_init(); info!("Starting up from main"); // replace default settings let mut settings = config::Settings::default(); - settings.database.in_memory = true; + // identify open port + let port = get_available_port().unwrap(); + info!("Starting relay on port {}", port); + // bind to local interface only + settings.network.address = "127.0.0.1".to_owned(); settings.network.port = port; + // create an in-memory DB with multiple readers + settings.database.in_memory = true; + settings.database.min_conn = 4; + settings.database.max_conn = 8; let (shutdown_tx, shutdown_rx): (MpscSender<()>, MpscReceiver<()>) = syncmpsc::channel(); let handle = thread::spawn(|| { let _ = start_server(settings, shutdown_rx); }); - return Relay { + return Ok(Relay { + port, handle, shutdown_tx, - }; + }); +} + +// from https://elliotekj.com/posts/2017/07/25/find-available-tcp-port-rust/ +fn get_available_port() -> Option { + (4000..20000).find(|port| port_is_available(*port)) +} +fn port_is_available(port: u16) -> bool { + match TcpListener::bind(("127.0.0.1", port)) { + Ok(_) => true, + Err(_) => false, + } } diff --git a/tests/integration_test.rs b/tests/integration_test.rs index b77864f..1f9efae 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -1,11 +1,12 @@ +use anyhow::Result; use std::thread; use std::time::Duration; mod common; #[test] -fn startup() { - let relay = common::start_relay(8080); +fn startup() -> Result<()> { + let relay = common::start_relay()?; // just make sure we can startup and shut down. // if we send a shutdown message before the server is listening, // we will get a SendError. Keep sending until someone is @@ -24,4 +25,5 @@ fn startup() { // wait for relay to shutdown let thread_join = relay.handle.join(); assert!(thread_join.is_ok()); + Ok(()) }