use crate::core::util::close::CloseableRef;
use crate::core::util::error::lucene_error::Result;
use crate::core::util::info_stream::{InfoStream, InfoStreamEnum};
use chrono::Utc;
use parking_lot::Mutex;
use std::any::TypeId;
use std::io::{self, Write};
use std::sync::atomic::{AtomicI32, Ordering};
static MESSAGE_ID: AtomicI32 = AtomicI32::new(0);
pub struct PrintStreamInfoStream<W> {
message_id: i32,
pub(crate) stream: Mutex<Option<W>>,
}
impl<W> PrintStreamInfoStream<W> {
pub fn new(stream: W) -> Self {
Self::with_message_id(stream, MESSAGE_ID.fetch_add(1, Ordering::SeqCst))
}
pub fn with_message_id(stream: W, message_id: i32) -> Self {
Self {
message_id,
stream: Mutex::new(Some(stream)),
}
}
}
impl<W> InfoStream for PrintStreamInfoStream<W>
where
W: Write + Send + 'static,
{
fn message(&self, component: &str, message: &str) -> Result<()> {
let current_thread = std::thread::current();
let thread_name = current_thread.name().unwrap_or("<unnamed>");
let timestamp = self.get_timestamp();
let mut stream = self.stream.lock();
if let Some(stream) = stream.as_mut() {
let _ = writeln!(
stream,
"{} {} [{}; {}]: {}",
component, self.message_id, timestamp, thread_name, message
);
let _ = stream.flush();
}
Ok(())
}
fn is_enabled(&self, _component: &str) -> bool {
true
}
}
impl<W> CloseableRef for PrintStreamInfoStream<W>
where
W: Write + Send + 'static,
{
fn close(&self) -> Result<()> {
if !self.is_system_stream() {
let mut stream = self.stream.lock();
if let Some(mut stream) = stream.take() {
let _ = stream.flush();
}
}
Ok(())
}
}
impl<W> PrintStreamInfoStream<W> {
pub fn is_system_stream(&self) -> bool
where
W: 'static,
{
TypeId::of::<W>() == TypeId::of::<io::Stdout>()
|| TypeId::of::<W>() == TypeId::of::<io::Stderr>()
}
pub fn get_timestamp(&self) -> String {
Utc::now().to_rfc3339()
}
}
impl PrintStreamInfoStream<io::Stdout> {
pub fn stdout() -> Self {
Self::new(io::stdout())
}
}
impl PrintStreamInfoStream<io::Stderr> {
pub fn stderr() -> Self {
Self::new(io::stderr())
}
}
impl<W> From<PrintStreamInfoStream<W>> for InfoStreamEnum
where
W: Write + Send + 'static,
{
fn from(info_stream: PrintStreamInfoStream<W>) -> Self {
InfoStreamEnum::Custom(Box::new(info_stream))
}
}