use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use crate::QlogSeq;
use crate::SQLOG_EXT;
use crate::SQLOG_GZ_EXT;
use crate::SQLOG_ZST_EXT;
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
pub enum Event {
Qlog(crate::events::Event),
Json(crate::events::JsonEvent),
}
pub struct QlogSeqReader<'a> {
pub qlog: QlogSeq,
reader: Box<dyn std::io::BufRead + Send + Sync + 'a>,
}
impl<'a> QlogSeqReader<'a> {
pub fn new(
mut reader: Box<dyn std::io::BufRead + Send + Sync + 'a>,
) -> Result<Self, Box<dyn std::error::Error>> {
Self::read_record(reader.as_mut());
let header = Self::read_record(reader.as_mut()).ok_or_else(|| {
std::io::Error::other("error reading file header bytes")
})?;
let res: Result<QlogSeq, serde_json::Error> =
serde_json::from_slice(&header);
match res {
Ok(qlog) => Ok(Self { qlog, reader }),
Err(e) => Err(e.into()),
}
}
pub fn with_file(
path: impl AsRef<Path>,
) -> Result<Self, Box<dyn std::error::Error>> {
let path = path.as_ref();
let file = File::open(path)?;
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name.ends_with(SQLOG_GZ_EXT) {
#[cfg(feature = "gzip")]
{
let reader: Box<dyn std::io::BufRead + Send + Sync> =
Box::new(BufReader::new(flate2::read::GzDecoder::new(file)));
return Self::new(reader);
}
#[cfg(not(feature = "gzip"))]
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!(
"qlog file {name:?} requires the `gzip` feature on \
the qlog crate to decode"
),
)
.into());
}
if name.ends_with(SQLOG_ZST_EXT) {
#[cfg(feature = "zstd")]
{
let decoder = zstd::Decoder::new(file)?;
let reader: Box<dyn std::io::BufRead + Send + Sync> =
Box::new(BufReader::new(decoder));
return Self::new(reader);
}
#[cfg(not(feature = "zstd"))]
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!(
"qlog file {name:?} requires the `zstd` feature on \
the qlog crate to decode"
),
)
.into());
}
if name.ends_with(SQLOG_EXT) {
let reader: Box<dyn std::io::BufRead + Send + Sync> =
Box::new(BufReader::new(file));
return Self::new(reader);
}
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!(
"qlog file {name:?} does not match a known qlog \
extension ({SQLOG_EXT}, {SQLOG_GZ_EXT}, {SQLOG_ZST_EXT})"
),
)
.into())
}
fn read_record(
reader: &mut (dyn std::io::BufRead + Send + Sync),
) -> Option<Vec<u8>> {
let mut buf = Vec::<u8>::new();
let size = reader.read_until(b'', &mut buf).unwrap();
if size <= 1 {
return None;
}
buf.truncate(buf.len() - 1);
Some(buf)
}
}
impl Iterator for QlogSeqReader<'_> {
type Item = Event;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
while let Some(bytes) = Self::read_record(&mut self.reader) {
let r: serde_json::Result<crate::events::Event> =
serde_json::from_slice(&bytes);
if let Ok(event) = r {
return Some(Event::Qlog(event));
}
let r: serde_json::Result<crate::events::JsonEvent> =
serde_json::from_slice(&bytes);
if let Ok(event) = r {
return Some(Event::Json(event));
}
}
None
}
}