use super::{Tasks, said, signal};
use crate::channels::{Channel, MatchSearchFailed, MatchSearchRequested, MatchSearchResults};
use crate::client::SemiontClient;
use crate::event_bus::BusFrames;
use crate::state_unit::StateUnit;
use crate::transport::Envelope;
use crate::types;
use std::sync::Arc;
struct Shared {
client: Arc<SemiontClient>,
tasks: Tasks,
}
pub struct MatchStateUnit {
shared: Arc<Shared>,
}
impl MatchStateUnit {
pub fn new(client: Arc<SemiontClient>) -> MatchStateUnit {
let heard = client.bus().frames(MatchSearchRequested::NAME);
let shared = Arc::new(Shared {
client,
tasks: Tasks::new(),
});
shared.tasks.spawn(listen(shared.clone(), heard));
MatchStateUnit { shared }
}
}
async fn listen(shared: Arc<Shared>, mut heard: BusFrames) {
while let Some(frame) = heard.next().await {
let Ok(Ok(frame)) = frame else { continue };
let Some(request) = said::<MatchSearchRequested>(&frame) else {
continue;
};
let under = Envelope {
correlation_id: frame.correlation_id,
scope: None,
};
let searching = shared.clone();
shared.tasks.spawn(async move {
let reference_id = request.reference_id.clone();
match searching.client.match_.search(request).await {
Ok(found) => signal::<MatchSearchResults>(&searching.client, &found, under),
Err(error) => signal::<MatchSearchFailed>(
&searching.client,
&types::MatchSearchFailed {
reference_id,
message: error.to_string(),
code: None,
details: None,
},
under,
),
}
});
}
}
impl StateUnit for MatchStateUnit {
fn dispose(&self) {
self.shared.tasks.stop();
}
}
impl Drop for MatchStateUnit {
fn drop(&mut self) {
self.dispose();
}
}