use moloch_core::{AuditEvent, Block, EventId, Hash, Result};
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum BatchOp {
PutEvent(AuditEvent),
PutBlock(Block),
PutMmrNode { pos: u64, hash: Hash },
SetMmrMeta { size: u64, leaf_count: u64 },
}
#[derive(Debug, Default)]
pub struct StorageBatch {
ops: Vec<BatchOp>,
}
impl StorageBatch {
pub fn new() -> Self {
Self { ops: Vec::new() }
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
ops: Vec::with_capacity(capacity),
}
}
pub fn put_event(&mut self, event: AuditEvent) -> &mut Self {
self.ops.push(BatchOp::PutEvent(event));
self
}
pub fn put_block(&mut self, block: Block) -> &mut Self {
self.ops.push(BatchOp::PutBlock(block));
self
}
pub fn put_mmr_node(&mut self, pos: u64, hash: Hash) -> &mut Self {
self.ops.push(BatchOp::PutMmrNode { pos, hash });
self
}
pub fn set_mmr_meta(&mut self, size: u64, leaf_count: u64) -> &mut Self {
self.ops.push(BatchOp::SetMmrMeta { size, leaf_count });
self
}
pub fn len(&self) -> usize {
self.ops.len()
}
pub fn is_empty(&self) -> bool {
self.ops.is_empty()
}
pub fn clear(&mut self) {
self.ops.clear();
}
pub fn ops(&self) -> &[BatchOp] {
&self.ops
}
pub fn into_ops(self) -> Vec<BatchOp> {
self.ops
}
}
pub trait BatchWriter {
fn batch(&self) -> StorageBatch {
StorageBatch::new()
}
fn commit(&self, batch: StorageBatch) -> Result<()>;
}
pub trait BulkReader {
fn get_events(&self, ids: &[EventId]) -> Result<Vec<Option<AuditEvent>>>;
fn get_block_range(&self, start: u64, end: u64) -> Result<Vec<Block>>;
fn get_mmr_nodes(&self, positions: &[u64]) -> Result<Vec<Option<Hash>>>;
}
#[cfg(test)]
mod tests {
use super::*;
use moloch_core::hash;
#[test]
fn test_batch_builder() {
let mut batch = StorageBatch::new();
assert!(batch.is_empty());
batch
.put_mmr_node(0, hash(b"node0"))
.put_mmr_node(1, hash(b"node1"))
.set_mmr_meta(2, 2);
assert_eq!(batch.len(), 3);
assert!(!batch.is_empty());
}
#[test]
fn test_batch_clear() {
let mut batch = StorageBatch::with_capacity(10);
batch.put_mmr_node(0, hash(b"test"));
assert_eq!(batch.len(), 1);
batch.clear();
assert!(batch.is_empty());
}
}