use crate::{processor::Processor, Content, Error, MessageBatch};
use async_trait::async_trait;
use datafusion::arrow;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchProcessorConfig {
pub count: usize,
pub timeout_ms: u64,
pub data_type: String,
}
pub struct BatchProcessor {
config: BatchProcessorConfig,
batch: Arc<RwLock<Vec<MessageBatch>>>,
last_batch_time: Arc<Mutex<std::time::Instant>>,
}
impl BatchProcessor {
pub fn new(config: &BatchProcessorConfig) -> Result<Self, Error> {
Ok(Self {
config: config.clone(),
batch: Arc::new(RwLock::new(Vec::with_capacity(config.count))),
last_batch_time: Arc::new(Mutex::new(std::time::Instant::now())),
})
}
async fn should_flush(&self) -> bool {
let batch = self.batch.read().await;
if batch.len() >= self.config.count {
return true;
}
let last_batch_time = self.last_batch_time.lock().await;
if !batch.is_empty()
&& last_batch_time.elapsed().as_millis() >= self.config.timeout_ms as u128
{
return true;
}
false
}
async fn flush(&self) -> Result<Vec<MessageBatch>, Error> {
let mut batch = self.batch.write().await;
if batch.is_empty() {
return Ok(vec![]);
}
let new_batch = match self.config.data_type.as_str() {
"arrow" => {
let mut combined_content = Vec::new();
for msg in batch.iter() {
if let Content::Arrow(v) = &msg.content {
combined_content.push(v.clone());
}
}
let schema = combined_content[0].schema();
let batch = arrow::compute::concat_batches(&schema, &combined_content)
.map_err(|e| Error::Processing(format!("合并批次失败: {}", e)))?;
Ok(vec![MessageBatch::new_arrow(batch)])
}
"binary" => {
let mut combined_content = Vec::new();
for msg in batch.iter() {
if let Content::Binary(v) = &msg.content {
combined_content.extend(v.clone());
}
}
Ok(vec![MessageBatch::new_binary(combined_content)])
}
_ => Err(Error::Processing("Invalid data type".to_string())),
};
batch.clear();
let mut last_batch_time = self.last_batch_time.lock().await;
*last_batch_time = std::time::Instant::now();
new_batch
}
}
#[async_trait]
impl Processor for BatchProcessor {
async fn process(&self, msg: MessageBatch) -> Result<Vec<MessageBatch>, Error> {
match &msg.content {
Content::Arrow(_) => {
if self.config.data_type != "arrow" {
return Err(Error::Processing("Invalid data type".to_string()));
}
}
Content::Binary(_) => {
if self.config.data_type != "binary" {
return Err(Error::Processing("Invalid data type".to_string()));
}
}
}
{
let mut batch = self.batch.write().await;
batch.push(msg);
}
if self.should_flush().await {
self.flush().await
} else {
Ok(vec![])
}
}
async fn close(&self) -> Result<(), Error> {
let mut batch = self.batch.write().await;
batch.clear();
Ok(())
}
}