diff options
| author | Arnaud Bailly <arnaud.bailly@iohk.io> | 2024-10-06 08:27:22 +0200 |
|---|---|---|
| committer | Arnaud Bailly <arnaud.bailly@iohk.io> | 2024-10-06 08:27:22 +0200 |
| commit | 8e2942b353cff3af8b20a040dca260a4420dd76e (patch) | |
| tree | 72b8f823903f0585b51f5bb47df38a4b1b6b76a3 | |
| parent | d96f415a2cfb55715c095cc9c2775b1413e06203 (diff) | |
| download | lambda-nantes-8e2942b353cff3af8b20a040dca260a4420dd76e.tar.gz | |
Spawn one thread per registered client
| -rw-r--r-- | rust/src/web.rs | 46 |
1 files changed, 22 insertions, 24 deletions
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<String, Client>, + clients: HashMap<String, Arc<Mutex<Client>>>, } 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<Mutex<State>> = app_state.clone(); let http_state: Arc<Mutex<dyn AppState>> = 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<Mutex<State>>) { +async fn send_tests(client_m: Arc<Mutex<Client>>) { 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 } } } |
