#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::string_slice,
clippy::panic_in_result_fn,
clippy::as_conversions,
clippy::arithmetic_side_effects,
clippy::pedantic,
clippy::nursery
)]
use segment_buffer::{FlushPolicy, SegmentBuffer, SegmentConfig};
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct Event {
seq: u64,
payload: String,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let tmp = tempfile::tempdir()?;
let config = SegmentConfig::builder()
.flush_policy(FlushPolicy::BatchOrIntervalMin {
batch_size: 100,
min_batch: 10,
interval: Duration::from_secs(5),
max_interval: Duration::from_secs(60),
})
.max_size_bytes(10 * 1024 * 1024)
.compression_level(3)
.build();
let buf: SegmentBuffer<Event> = SegmentBuffer::open(tmp.path(), config)?;
for i in 0..100 {
buf.append(Event {
seq: i,
payload: format!("burst-event-{i}"),
})?;
}
println!(
"After 100-item burst: {} segment file on disk",
count_segments(tmp.path())?
);
for i in 100..103 {
buf.append(Event {
seq: i,
payload: format!("drip-{i}"),
})?;
}
println!(
"After 3-item drip (below min_batch): {} segment file on disk",
count_segments(tmp.path())?
);
println!("Total backlog (pending_count): {}", buf.pending_count());
buf.flush()?;
println!(
"After manual flush: {} segment files on disk",
count_segments(tmp.path())?
);
let all = buf.read_from(0, usize::MAX)?;
println!("Total items readable: {}", all.len());
Ok(())
}
fn count_segments(dir: &std::path::Path) -> Result<usize, Box<dyn std::error::Error>> {
let count = std::fs::read_dir(dir)?
.filter_map(Result::ok)
.filter(|e| {
let name = e.file_name();
let name = name.to_string_lossy();
name.starts_with("seg_") && name.ends_with(".zst")
})
.count();
Ok(count)
}