use std::{
fs,
io::{
BufReader,
BufWriter,
Write,
},
path::Path,
};
use serde::{
Deserialize,
Serialize,
};
use crate::{
audit::{
AuditEventRecord,
AuditProbeEvent,
AuditProbeEventHandler,
AuditProbeEventStub,
AuditProbeEventView,
audit_probe::match_events_at,
},
errors::{
BunsenError,
BunsenErrorKind,
BunsenResult,
ParseError,
ValueMismatch,
sys_at,
},
};
pub const AUDIT_STREAM_FORMAT: &str = "bunsen-audit-stream";
pub const AUDIT_STREAM_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditStreamFile {
pub format: String,
pub version: u32,
pub events: Vec<AuditEventRecord>,
}
pub fn save_audit_stream(
path: &Path,
events: &[AuditProbeEvent],
) -> BunsenResult<()> {
let file = AuditStreamFile {
format: AUDIT_STREAM_FORMAT.to_string(),
version: AUDIT_STREAM_VERSION,
events: events.iter().map(AuditEventRecord::from).collect(),
};
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(sys_at("create directory", parent))?;
}
let mut out = BufWriter::new(fs::File::create(path).map_err(sys_at("create", path))?);
ciborium::into_writer(&file, &mut out).map_err(|e| match e {
ciborium::ser::Error::Io(err) => sys_at("write", path)(err),
value => BunsenError::internal(format!("cannot encode audit stream {}", path.display()))
.with_cause(value),
})?;
out.flush().map_err(sys_at("write", path))
}
pub fn load_audit_stream(path: &Path) -> BunsenResult<Vec<AuditProbeEvent>> {
let input = fs::File::open(path).map_err(sys_at("open", path))?;
let file: AuditStreamFile =
ciborium::from_reader(BufReader::new(input)).map_err(|e| match e {
ciborium::de::Error::Io(err) => sys_at("read", path)(err),
other => BunsenError::from_cause(
BunsenErrorKind::InvalidResource,
ParseError::new("audit stream")
.at(path.display())
.with_source(other),
),
})?;
if file.format != AUDIT_STREAM_FORMAT || file.version != AUDIT_STREAM_VERSION {
return Err(BunsenError::invalid_resource(format!(
"{}: format {:?} version {}, expected {AUDIT_STREAM_FORMAT:?} version \
{AUDIT_STREAM_VERSION}",
path.display(),
file.format,
file.version,
)));
}
Ok(file.events.into_iter().map(AuditProbeEvent::from).collect())
}
#[derive(Debug, Clone, Default)]
pub struct AuditStreamRecorder {
events: Vec<AuditProbeEvent>,
}
impl AuditProbeEventHandler for AuditStreamRecorder {
fn on_event(
&mut self,
stub: &AuditProbeEventStub<'_>,
) -> BunsenResult<()> {
self.events.push(stub.to_event());
Ok(())
}
}
impl AuditStreamRecorder {
pub fn events(&self) -> &[AuditProbeEvent] {
&self.events
}
pub fn into_verifier(self) -> AuditStreamVerifier {
AuditStreamVerifier::new(self.events)
}
pub fn save(
&self,
path: &Path,
) -> BunsenResult<()> {
save_audit_stream(path, &self.events)
}
}
#[derive(Debug, Clone)]
pub struct AuditStreamVerifier {
events: Vec<AuditProbeEvent>,
next: usize,
}
impl AuditProbeEventHandler for AuditStreamVerifier {
fn on_event(
&mut self,
stub: &AuditProbeEventStub<'_>,
) -> BunsenResult<()> {
let Some(expected) = self.events.get(self.next) else {
return Err(ValueMismatch::Other {
summary: format!(
"unexpected audit event {:?}: the expected stream has only {} events",
stub.header.label,
self.events.len(),
),
details: None,
}
.into());
};
let index = self.next;
self.next += 1;
match_events_at(Some(index), stub, expected)
}
}
impl AuditStreamVerifier {
pub fn new(events: Vec<AuditProbeEvent>) -> Self {
Self { events, next: 0 }
}
pub fn load(path: &Path) -> BunsenResult<Self> {
Ok(Self::new(load_audit_stream(path)?))
}
pub fn finish(&self) -> BunsenResult<()> {
match self.events.get(self.next) {
None => Ok(()),
Some(missing) => Err(ValueMismatch::Other {
summary: format!(
"audit stream ended early: saw {} of {} events; next expected {:?}",
self.next,
self.events.len(),
missing.header.label,
),
details: None,
}
.into()),
}
}
}