Skip to content

Commit

Permalink
Convert smartrest_serializer to SmartrestPayload
Browse files Browse the repository at this point in the history
Signed-off-by: Marcel Guzik <[email protected]>
  • Loading branch information
Bravo555 committed Oct 21, 2024
1 parent 7bc52d1 commit a2353c7
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 74 deletions.
46 changes: 39 additions & 7 deletions crates/core/c8y_api/src/smartrest/message.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::fmt::Display;

use serde::Serialize;
use tracing::error;

// The actual limit defined by c8y is 16184 including header and body.
Expand Down Expand Up @@ -36,11 +39,23 @@ impl SmartrestPayload {
let payload = super::csv::fields_to_csv_string(fields);

if payload.len() > super::message::MAX_PAYLOAD_LIMIT_IN_BYTES {
return Err(SmartrestPayloadError(anyhow::anyhow!(
"Message is larger ({}) than size limit ({})",
payload.len(),
MAX_PAYLOAD_LIMIT_IN_BYTES
)));
return Err(SmartrestPayloadError::TooLarge(payload.len()));
}

Ok(Self(payload))
}

pub fn serialize<S: Serialize>(record: S) -> Result<Self, SmartrestPayloadError> {
let mut wtr = csv::Writer::from_writer(vec![]);
wtr.serialize(record)?;
let mut vec = wtr.into_inner().unwrap();
// remove newline character
vec.pop();
let payload = String::from_utf8(vec)
.expect("TODO: should SmartrestPayload wrap a string or a byte array?");

if payload.len() > super::message::MAX_PAYLOAD_LIMIT_IN_BYTES {
return Err(SmartrestPayloadError::TooLarge(payload.len()));
}

Ok(Self(payload))
Expand All @@ -59,8 +74,25 @@ impl SmartrestPayload {

/// Errors that can occur when trying to create a SmartREST payload.
#[derive(Debug, thiserror::Error)]
#[error("Could not create SmartrestPayload: {0:#}")]
pub struct SmartrestPayloadError(#[from] anyhow::Error);
pub enum SmartrestPayloadError {
#[error("Payload size ({0}) would be bigger than the limit ({MAX_PAYLOAD_LIMIT_IN_BYTES})")]
TooLarge(usize),

#[error("Could not serialize the record")]
SerializeError(#[from] csv::Error),
}

impl From<SmartrestPayload> for Vec<u8> {
fn from(value: SmartrestPayload) -> Self {
value.0.into_bytes()
}
}

impl Display for SmartrestPayload {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}

/// Extract the Device ID from the SmartREST payload.
///
Expand Down
Loading

0 comments on commit a2353c7

Please sign in to comment.