|
| 1 | +use crate::network::BeaconNetwork; |
| 2 | +use discv5::TalkRequest; |
| 3 | +use portalnet::types::messages::Message; |
| 4 | +use std::sync::Arc; |
| 5 | +use tokio::sync::mpsc::UnboundedReceiver; |
| 6 | +use tracing::{error, warn, Instrument}; |
| 7 | + |
| 8 | +pub struct BeaconEvents { |
| 9 | + pub network: Arc<BeaconNetwork>, |
| 10 | + pub event_rx: UnboundedReceiver<TalkRequest>, |
| 11 | +} |
| 12 | + |
| 13 | +impl BeaconEvents { |
| 14 | + pub async fn start(mut self) { |
| 15 | + loop { |
| 16 | + tokio::select! { |
| 17 | + Some(talk_request) = self.event_rx.recv() => { |
| 18 | + self.handle_beacon_talk_request(talk_request); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + /// Handle beacon network TalkRequest event |
| 25 | + fn handle_beacon_talk_request(&self, talk_request: TalkRequest) { |
| 26 | + let network = Arc::clone(&self.network); |
| 27 | + let talk_request_id = talk_request.id().clone(); |
| 28 | + tokio::spawn(async move { |
| 29 | + let reply = match network |
| 30 | + .overlay |
| 31 | + .process_one_request(&talk_request) |
| 32 | + .instrument(tracing::info_span!("beacon_network", req = %talk_request_id)) |
| 33 | + .await |
| 34 | + { |
| 35 | + Ok(response) => Message::from(response).into(), |
| 36 | + Err(error) => { |
| 37 | + error!( |
| 38 | + error = %error, |
| 39 | + request.discv5.id = %talk_request_id, |
| 40 | + "Error processing portal beacon request, responding with empty TALKRESP" |
| 41 | + ); |
| 42 | + // Return an empty TALKRESP if there was an error executing the request |
| 43 | + "".into() |
| 44 | + } |
| 45 | + }; |
| 46 | + if let Err(error) = talk_request.respond(reply) { |
| 47 | + warn!(error = %error, request.discv5.id = %talk_request_id, "Error responding to TALKREQ"); |
| 48 | + } |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
0 commit comments