Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add decode method in DataProcess trait #22

Merged
merged 5 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions examples/consumer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::str::from_utf8;
use std::fmt::{Display, Formatter};
use std::time::Duration;

use shm_ringbuf::consumer::process::{DataProcess, ResultSender};
Expand All @@ -23,8 +23,15 @@ async fn main() {
pub struct StringPrint;

impl DataProcess for StringPrint {
async fn process(&self, data: &[u8], result_sender: ResultSender) {
if let Err(e) = self.do_process(data).await {
type Message = String;
type Error = Error;

fn decode(&self, data: &[u8]) -> Result<Self::Message, Self::Error> {
String::from_utf8(data.to_vec()).map_err(|_| Error::DecodeError)
}

async fn process(&self, msg: Self::Message, result_sender: ResultSender) {
if let Err(e) = self.do_process(&msg).await {
result_sender.push_result(e).await;
} else {
result_sender.push_ok().await;
Expand All @@ -33,8 +40,7 @@ impl DataProcess for StringPrint {
}

impl StringPrint {
async fn do_process(&self, data: &[u8]) -> Result<(), Error> {
let msg = from_utf8(data).map_err(|_| Error::DecodeError)?;
async fn do_process(&self, msg: &str) -> Result<(), Error> {
info!("receive: {}", msg);
Ok(())
}
Expand Down Expand Up @@ -70,3 +76,11 @@ impl From<Error> for DataProcessResult {
}
}
}

impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message())
}
}

impl std::error::Error for Error {}
18 changes: 16 additions & 2 deletions src/consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ use tokio::time::sleep;
use tokio_util::sync::CancellationToken;
use tracing::warn;

use crate::error::DataProcessResult;
use crate::error::CHECKSUM_MISMATCH;
use crate::error::{DataProcessResult, DECODE_ERROR};
use crate::fd_pass::FdRecvServer;
use crate::grpc::proto::shm_control_server::ShmControlServer;
use crate::grpc::server::ShmCtlHandler;
Expand Down Expand Up @@ -231,8 +231,22 @@ where
session: session.clone(),
};

processor.process(data_slice, result_sender).await;
let result = processor.decode(data_slice);

unsafe { ringbuf.advance_consume_offset(data_block.total_len()) }
drop(data_block);

match result {
Ok(message) => {
processor.process(message, result_sender).await;
}
Err(e) => {
let result = DataProcessResult {
status_code: DECODE_ERROR,
message: e.to_string(),
};
result_sender.push_result(result).await;
}
};
}
}
9 changes: 8 additions & 1 deletion src/consumer/process.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::error::Error;
use std::fmt::Debug;
use std::future::Future;

Expand All @@ -6,9 +7,15 @@ use crate::error::DataProcessResult;
use super::session_manager::SessionRef;

pub trait DataProcess: Send + Sync {
type Message: Debug;

type Error: Error;

fn decode(&self, data: &[u8]) -> Result<Self::Message, Self::Error>;

fn process(
&self,
data: &[u8],
message: Self::Message,
result_sender: ResultSender,
) -> impl Future<Output = ()>;
}
Expand Down
1 change: 1 addition & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,4 @@ impl DataProcessResult {
/// 100000 - 200000 are error codes used internally by shm-ringbuf and should
/// not be used as business codes.
pub const CHECKSUM_MISMATCH: u32 = 100000;
pub const DECODE_ERROR: u32 = 100001;
1 change: 0 additions & 1 deletion src/producer/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ impl ResultFetcher {
};

fetcher.inner.normal.store(false, Ordering::Relaxed);
fetcher.inner.subscriptions.clear();
sleep(fetcher.inner.retry_interval).await;
}
});
Expand Down
27 changes: 20 additions & 7 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::{str::from_utf8, sync::Arc, time::Duration};

use shm_ringbuf::{
consumer::process::{DataProcess, ResultSender},
error::DataProcessResult,
producer::{prealloc::PreAlloc, RingbufProducer},
};
use std::fmt::{Display, Formatter};
use std::{sync::Arc, time::Duration};
use tokio::{sync::mpsc::Sender, time::sleep};
use tracing::{error, warn};

Expand All @@ -13,8 +13,15 @@ pub struct MsgForward {
}

impl DataProcess for MsgForward {
async fn process(&self, data: &[u8], result_sender: ResultSender) {
if let Err(e) = self.do_process(data).await {
type Message = String;
type Error = Error;

fn decode(&self, data: &[u8]) -> Result<Self::Message, Self::Error> {
String::from_utf8(data.to_vec()).map_err(|_| Error::DecodeError)
}

async fn process(&self, msg: Self::Message, result_sender: ResultSender) {
if let Err(e) = self.do_process(&msg).await {
result_sender.push_result(e).await;
} else {
result_sender.push_ok().await;
Expand All @@ -23,9 +30,7 @@ impl DataProcess for MsgForward {
}

impl MsgForward {
async fn do_process(&self, data: &[u8]) -> Result<(), Error> {
let msg = from_utf8(data).map_err(|_| Error::DecodeError)?;

async fn do_process(&self, msg: &str) -> Result<(), Error> {
let _ = self.sender.send(msg.to_string()).await;

Ok(())
Expand Down Expand Up @@ -63,6 +68,14 @@ impl From<Error> for DataProcessResult {
}
}

impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message())
}
}

impl std::error::Error for Error {}

pub fn msg_num() -> usize {
std::env::var("MSG_NUM")
.unwrap_or_else(|_| "10000".to_string())
Expand Down