use anyhow::Context;
use slog::{warn, Logger};
use std::fmt::Debug;
use tokio::sync::mpsc::UnboundedSender;
use mithril_common::{logging::LoggerExtensions, StdResult};
use super::EventMessage;
pub struct TransmitterService<MSG>
where
MSG: Debug + Sync + Send,
{
transmitter: UnboundedSender<MSG>,
logger: Logger,
}
impl<MSG> TransmitterService<MSG>
where
MSG: Debug + Sync + Send,
{
pub fn new(transmitter: UnboundedSender<MSG>, logger: Logger) -> Self {
Self {
transmitter,
logger: logger.new_with_component_name::<Self>(),
}
}
pub fn get_transmitter(&self) -> UnboundedSender<MSG> {
self.transmitter.clone()
}
}
impl TransmitterService<EventMessage> {
pub fn try_send(&self, message: EventMessage) -> StdResult<()> {
self.get_transmitter()
.send(message.clone())
.with_context(|| {
format!("An error occurred when sending message {message:?} to monitoring.")
})
}
pub fn send(&self, message: EventMessage) {
if let Err(e) = self.try_send(message.clone()) {
warn!(self.logger, "Event message error"; "error" => ?e);
};
}
}