messagebus/tests/test_batch.rs

116 lines
2.3 KiB
Rust
Raw Normal View History

use std::sync::Arc;
2021-06-24 13:32:19 +04:00
use async_trait::async_trait;
2021-09-20 16:48:20 +04:00
use messagebus::{
derive::{Error as MbError, Message},
error,
receivers::BufferUnorderedBatchedConfig,
AsyncBatchHandler, Bus, Message,
};
2021-09-15 19:54:59 +04:00
use parking_lot::Mutex;
use thiserror::Error;
#[derive(Debug, Error, Clone, MbError)]
enum Error {
#[error("Error({0})")]
Error(Arc<anyhow::Error>),
}
2021-06-24 13:32:19 +04:00
impl<M: Message> From<error::Error<M>> for Error {
fn from(err: error::Error<M>) -> Self {
Self::Error(Arc::new(err.into()))
}
}
#[derive(Debug, Clone, Message)]
#[message(clone)]
struct MsgI32(i32);
#[derive(Debug, Clone, Message)]
#[message(clone)]
struct MsgI16(i16);
2021-09-15 19:54:59 +04:00
struct TmpReceiver {
2021-09-20 16:48:20 +04:00
batches: Arc<Mutex<Vec<Vec<i32>>>>,
2021-09-15 19:54:59 +04:00
}
2021-06-24 13:32:19 +04:00
#[async_trait]
impl AsyncBatchHandler<MsgI32> for TmpReceiver {
2021-06-24 13:32:19 +04:00
type Error = Error;
type Response = ();
type InBatch = Vec<MsgI32>;
type OutBatch = Vec<()>;
2021-06-24 13:32:19 +04:00
async fn handle(
&self,
msg: Vec<MsgI32>,
_bus: &Bus,
) -> Result<Vec<Self::Response>, Self::Error> {
2021-09-20 16:48:20 +04:00
self.batches
.lock()
.push(msg.into_iter().map(|x| x.0).collect());
2021-06-24 13:32:19 +04:00
Ok(vec![])
}
}
2021-09-15 19:54:59 +04:00
#[tokio::test]
async fn test_batch() {
let batches = Arc::new(Mutex::new(Vec::new()));
2021-06-24 13:32:19 +04:00
let (b, poller) = Bus::build()
2021-09-20 16:48:20 +04:00
.register(TmpReceiver {
batches: batches.clone(),
2021-09-15 19:54:59 +04:00
})
2021-09-20 16:48:20 +04:00
.subscribe_batch_async::<MsgI32>(
16,
BufferUnorderedBatchedConfig {
batch_size: 8,
..Default::default()
},
)
2021-06-24 13:32:19 +04:00
.done()
.build();
for i in 1..100i32 {
b.send(MsgI32(i)).await.unwrap();
2021-06-24 13:32:19 +04:00
}
2021-09-20 16:48:20 +04:00
2021-09-15 19:54:59 +04:00
let mut re = Vec::new();
let mut counter = 1i32;
for _ in 1..100i32 {
let mut v = Vec::new();
for _ in 0..8 {
if counter >= 100 {
break;
}
v.push(counter);
counter += 1;
}
re.push(v);
if counter >= 100 {
break;
}
}
2021-06-24 13:32:19 +04:00
println!("flush");
b.flush().await;
2021-09-15 19:54:59 +04:00
let mut lock = batches.lock();
lock.sort_by(|a, b| a[0].cmp(&b[0]));
assert_eq!(lock.as_slice(), re.as_slice());
2021-06-24 13:32:19 +04:00
println!("close");
b.close().await;
println!("closed");
poller.await;
println!("[done]");
}