use std::sync::mpsc;
use std::thread::JoinHandle;
use logforth_core::Error;
use crate::Overflow;
use crate::Task;
use crate::channel::Sender;
#[derive(Debug)]
pub(crate) struct AsyncState(Option<State>);
#[derive(Debug)]
struct State {
overflow: Overflow,
sender: Sender<Task>,
handle: JoinHandle<()>,
}
impl AsyncState {
pub(crate) fn new(overflow: Overflow, sender: Sender<Task>, handle: JoinHandle<()>) -> Self {
Self(Some(State {
overflow,
sender,
handle,
}))
}
pub(crate) fn send_task(&self, task: Task) -> Result<(), Error> {
let State {
overflow,
sender,
handle: _,
} = self.0.as_ref().unwrap();
match overflow {
Overflow::Block => sender.send(task).map_err(|err| {
Error::new(match err.0 {
Task::Log { .. } => "failed to send log task to async appender",
Task::Flush { .. } => "failed to send flush task to async appender",
})
}),
Overflow::DropIncoming => match sender.try_send(task) {
Ok(()) => Ok(()),
Err(mpsc::TrySendError::Full(_)) => Ok(()),
Err(mpsc::TrySendError::Disconnected(task)) => Err(Error::new(match task {
Task::Log { .. } => "failed to send log task to async appender",
Task::Flush { .. } => "failed to send flush task to async appender",
})),
},
}
}
}
impl Drop for AsyncState {
fn drop(&mut self) {
let State {
overflow: _,
sender,
handle,
} = self.0.take().unwrap();
drop(sender);
handle.join().expect("failed to join async appender thread");
}
}