One less listen address race (#5718)

* One less listen address race
This commit is contained in:
Michael Sproul
2024-05-06 11:59:47 +10:00
committed by GitHub
parent 1af3f0f9d8
commit fe20ef955b
2 changed files with 15 additions and 11 deletions

View File

@@ -31,7 +31,7 @@ pub async fn serve(config: FullConfig) -> Result<(), Error> {
)
})?;
let server = start_server(&config, slots_per_epoch as u64, db)?;
let (_addr, server) = start_server(&config, slots_per_epoch as u64, db)?;
server.await?;
@@ -58,7 +58,13 @@ pub fn start_server(
config: &FullConfig,
slots_per_epoch: u64,
pool: PgPool,
) -> Result<impl Future<Output = Result<(), std::io::Error>> + 'static, Error> {
) -> Result<
(
SocketAddr,
impl Future<Output = Result<(), std::io::Error>> + 'static,
),
Error,
> {
let mut routes = Router::new()
.route("/v1/slots", get(handler::get_slots_by_range))
.route("/v1/slots/:slot", get(handler::get_slot))
@@ -106,11 +112,15 @@ pub fn start_server(
let addr = SocketAddr::new(config.server.listen_addr, config.server.listen_port);
let listener = TcpListener::bind(addr)?;
listener.set_nonblocking(true)?;
// Read the socket address (it may be different from `addr` if listening on port 0).
let socket_addr = listener.local_addr()?;
let serve = axum::serve(tokio::net::TcpListener::from_std(listener)?, app);
info!("HTTP server listening on {}", addr);
Ok(serve.into_future())
Ok((socket_addr, serve.into_future()))
}
// The default route indicating that no available routes matched the request.

View File

@@ -14,7 +14,6 @@ use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::collections::HashMap;
use std::env;
use std::net::SocketAddr;
use std::time::Duration;
use testcontainers::{clients::Cli, core::WaitFor, Image, RunnableImage};
use tokio::{runtime, task::JoinHandle};
@@ -154,7 +153,7 @@ impl TesterBuilder {
* Create a watch configuration
*/
let database_port = unused_tcp4_port().expect("Unable to find unused port.");
let server_port = unused_tcp4_port().expect("Unable to find unused port.");
let server_port = 0;
let config = Config {
database: DatabaseConfig {
dbname: random_dbname(),
@@ -187,14 +186,9 @@ impl TesterBuilder {
/*
* Spawn a Watch HTTP API.
*/
let watch_server = start_server(&self.config, SLOTS_PER_EPOCH, pool).unwrap();
let (addr, watch_server) = start_server(&self.config, SLOTS_PER_EPOCH, pool).unwrap();
tokio::spawn(watch_server);
let addr = SocketAddr::new(
self.config.server.listen_addr,
self.config.server.listen_port,
);
/*
* Create a HTTP client to talk to the watch HTTP API.
*/