use std::{net::IpAddr, str::FromStr}; use crate::{DbConnection, SnowDb}; use hickory_resolver::Name; use rocket::futures::channel::mpsc as rocket_mpsc; use rocket::futures::StreamExt; use rocket::tokio; use snow_scanner_worker::detection::{detect_scanner_from_name, validate_ip}; use crate::Scanner; /// Handles all the raw events being streamed from balancers and parses and filters them into only the events we care about. pub struct EventBus { events_rx: rocket_mpsc::Receiver, events_tx: rocket_mpsc::Sender, bus_tx: tokio::sync::broadcast::Sender, } impl EventBus { pub fn new() -> Self { let (events_tx, events_rx) = rocket_mpsc::channel(100); let (bus_tx, _) = tokio::sync::broadcast::channel(100); Self { events_rx, events_tx, bus_tx, } } // db: &Connection pub async fn run(&mut self, mut conn: DbConnection) { info!("EventBus started"); loop { tokio::select! { Some(event) = self.events_rx.next() => { self.handle_event(event, &mut conn).await; } else => { warn!("EventBus stopped"); break; } } } } async fn handle_event(&self, event: EventBusWriterEvent, db: &mut DbConnection) { info!("Received event"); if self.bus_tx.receiver_count() == 0 { return; } match event { EventBusWriterEvent::ScannerFoundResponse { name, address } => { let ip: IpAddr = address.into(); if !validate_ip(ip) { error!("Invalid IP address: {ip}"); return; } let name = Name::from_str(name.as_str()).unwrap(); match detect_scanner_from_name(&name) { Ok(Some(scanner_type)) => { match Scanner::find_or_new(ip, scanner_type, Some(name), db).await { Ok(scanner) => { let _ = scanner.save(db).await; } Err(err) => { error!("Error find or save: {:?}", err); } } } Ok(None) => { error!("No name detected for: {:?}", name); } Err(err) => { error!("No name detected error: {:?}", err); } }; } EventBusWriterEvent::BroadcastMessage(msg) => match self.bus_tx.send(msg) { Ok(count) => { info!("Event sent to {count} subscribers"); } Err(err) => { error!("Error sending event to subscribers: {}", err); } }, } } pub fn subscriber(&self) -> EventBusSubscriber { EventBusSubscriber::new(self.bus_tx.clone()) } pub fn writer(&self) -> EventBusWriter { EventBusWriter::new(self.events_tx.clone()) } } pub type EventBusEvent = rocket_ws::Message; /// Enables subscriptions to the event bus pub struct EventBusSubscriber { bus_tx: tokio::sync::broadcast::Sender, } /// Enables subscriptions to the event bus pub struct EventBusWriter { bus_tx: rocket_mpsc::Sender, } pub enum EventBusWriterEvent { BroadcastMessage(rocket_ws::Message), ScannerFoundResponse { name: String, address: IpAddr }, } impl EventBusWriter { pub fn new(bus_tx: rocket_mpsc::Sender) -> Self { Self { bus_tx } } pub fn write(&self) -> rocket_mpsc::Sender { self.bus_tx.clone() } } impl EventBusSubscriber { pub fn new(bus_tx: tokio::sync::broadcast::Sender) -> Self { Self { bus_tx } } pub fn subscribe(&self) -> tokio::sync::broadcast::Receiver { self.bus_tx.subscribe() } }