From 8e2942b353cff3af8b20a040dca260a4420dd76e Mon Sep 17 00:00:00 2001 From: Arnaud Bailly Date: Sun, 6 Oct 2024 08:27:22 +0200 Subject: Spawn one thread per registered client --- rust/src/web.rs | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) (limited to 'rust/src/web.rs') diff --git a/rust/src/web.rs b/rust/src/web.rs index b48900e..e805da7 100644 --- a/rust/src/web.rs +++ b/rust/src/web.rs @@ -42,9 +42,9 @@ struct Client { grade: u8, } -#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] +#[derive(Debug)] struct State { - clients: HashMap, + clients: HashMap>>, } impl State { @@ -63,14 +63,17 @@ impl AppState for State { } } else { let id = Uuid::new_v4(); - self.clients.insert( - registration.url.clone(), - Client { - id, - url: registration.url.clone(), - grade: 1, - }, - ); + let client = Arc::new(Mutex::new(Client { + id, + url: registration.url.clone(), + grade: 1, + })); + let client_s = client.clone(); + self.clients.insert(registration.url.clone(), client); + // let it run in the background + // FIXME: should find a way to handle graceful termination + task::spawn(async move { send_tests(client_s).await }); + RegistrationResult::RegistrationSuccess { id: id.to_string(), url: registration.url.clone(), @@ -119,11 +122,8 @@ struct Options { async fn main() -> std::io::Result<()> { let options = Options::parse(); let app_state = Arc::new(Mutex::new(State::new())); - let send_state: Arc> = app_state.clone(); let http_state: Arc> = app_state; env_logger::init(); - // let it run in the background - task::spawn(async move { send_tests(send_state).await }); HttpServer::new(move || { App::new() .wrap(Logger::default()) @@ -136,19 +136,17 @@ async fn main() -> std::io::Result<()> { .await } -async fn send_tests(state_ref: Arc>) { +async fn send_tests(client_m: Arc>) { loop { tokio::time::sleep(std::time::Duration::from_secs(1)).await; - let mut state = state_ref.lock().await; - for (_, client) in state.clients.iter_mut() { - let result = send_test(client.grade, &client.url).await; - match result { - Ok(_) => { - client.grade += 1; - } - Err(_) => { - // FIXME - } + let mut client = client_m.lock().await; + let result = send_test(client.grade, &client.url).await; + match result { + Ok(_) => { + client.grade += 1; + } + Err(_) => { + // FIXME } } } -- cgit v1.2.3