Skip to content

Commit

Permalink
Just use serialize
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 ba1ac4b commit ffc956c
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 39 deletions.
4 changes: 2 additions & 2 deletions crates/core/c8y_api/src/smartrest/alarm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ pub fn serialize_alarm(c8y_alarm: &C8yAlarm) -> Result<SmartrestPayload, time::e
AlarmSeverity::Minor => "303",
AlarmSeverity::Warning => "304",
};
SmartrestPayload::from_fields([
SmartrestPayload::serialize([
smartrest_code,
&alarm.alarm_type,
&alarm.text,
&alarm.time.format(&Rfc3339)?,
])
.expect("TODO: should alarm text be trimmed?")
}
C8yAlarm::Clear(alarm) => SmartrestPayload::from_fields(["306", &alarm.alarm_type])
C8yAlarm::Clear(alarm) => SmartrestPayload::serialize((306, &alarm.alarm_type))
.expect("alarm type should be shorter than payload size limit"),
};
Ok(smartrest)
Expand Down
23 changes: 9 additions & 14 deletions crates/core/c8y_api/src/smartrest/inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ pub fn child_device_creation_message(
});
}

let payload = SmartrestPayload::from_fields([
"101",
let payload = SmartrestPayload::serialize((
101,
child_id,
device_name.unwrap_or(child_id),
device_type.unwrap_or("thin-edge.io-child"),
])
))
.expect("child_id, device_name, device_type should not increase payload size over the limit");

Ok(MqttMessage::new(
Expand Down Expand Up @@ -115,16 +115,11 @@ pub fn service_creation_message_payload(
});
}

let payload = SmartrestPayload::from_fields([
"102",
service_id,
service_type,
service_name,
service_status,
])
.expect(
"TODO: message can get over the limit but none of the fields can be reasonably trimmed",
);
let payload =
SmartrestPayload::serialize((102, service_id, service_type, service_name, service_status))
.expect(
"TODO: message can get over the limit but none of the fields can be reasonably trimmed",
);

Ok(payload)
}
Expand All @@ -145,7 +140,7 @@ impl From<C8ySmartRestSetInterval117> for MqttMessage {
fn from(value: C8ySmartRestSetInterval117) -> Self {
let topic = value.c8y_topic.to_topic(&value.prefix).unwrap();
let interval_in_minutes = value.interval.as_secs() / 60;
let payload = SmartrestPayload::from_fields(["117", &interval_in_minutes.to_string()])
let payload = SmartrestPayload::serialize((117, &interval_in_minutes))
.expect("interval should not increase size over the limit");
MqttMessage::new(&topic, payload.into_inner())
}
Expand Down
33 changes: 18 additions & 15 deletions crates/core/c8y_api/src/smartrest/payload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,6 @@ impl SmartrestPayload {
/// Creates a payload that consists of a single record.
///
/// Doesn't trim any fields, so if the resulting payload is above size limit, returns an error.
pub fn from_fields<T>(
fields: impl IntoIterator<Item = T>,
) -> Result<Self, SmartrestPayloadError>
where
T: AsRef<str> + AsRef<[u8]>,
{
let payload = super::csv::fields_to_csv_string(fields);

if 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)?;
Expand Down Expand Up @@ -93,3 +78,21 @@ impl Display for SmartrestPayload {
f.write_str(&self.0)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn serializes_payload() {
let payload = SmartrestPayload::serialize((121, true)).unwrap();
assert_eq!(payload.as_str(), "121,true");
}

#[test]
fn returns_err_when_over_size_limit() {
let payload = "A".repeat(MAX_PAYLOAD_LIMIT_IN_BYTES + 1);
let payload = SmartrestPayload::serialize(payload);
assert!(matches!(payload, Err(SmartrestPayloadError::TooLarge(_))))
}
}
15 changes: 7 additions & 8 deletions crates/core/c8y_api/src/smartrest/smartrest_serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ pub fn request_pending_operations() -> &'static str {

/// Generates a SmartREST message to set the provided operation to executing
pub fn set_operation_executing_with_name(operation: impl C8yOperation) -> SmartrestPayload {
SmartrestPayload::from_fields(["501", operation.name()])
SmartrestPayload::serialize(("501", operation.name()))
.expect("operation name shouldn't put payload over size limit")
}

/// Generates a SmartREST message to set the provided operation ID to executing
pub fn set_operation_executing_with_id(op_id: &str) -> SmartrestPayload {
SmartrestPayload::from_fields(["504", op_id])
SmartrestPayload::serialize(("504", op_id))
.expect("op_id shouldn't put payload over size limit")
}

Expand All @@ -41,11 +41,11 @@ pub fn fail_operation_with_id(op_id: &str, reason: &str) -> SmartrestPayload {
fn fail_operation(template_id: &str, operation: &str, reason: &str) -> SmartrestPayload {
// If the failure reason exceeds 500 bytes, truncate it
if reason.len() <= 500 {
SmartrestPayload::from_fields([template_id, operation, reason])
SmartrestPayload::serialize((template_id, operation, reason))
.expect("operation name shouldn't put payload over size limit")
} else {
warn!("Failure reason too long, message truncated to 500 bytes");
SmartrestPayload::from_fields([template_id, operation, &reason[..500]])
SmartrestPayload::serialize((template_id, operation, &reason[..500]))
.expect("operation name shouldn't put payload over size limit")
}
}
Expand Down Expand Up @@ -84,8 +84,8 @@ fn succeed_static_operation(
payload: Option<impl AsRef<str>>,
) -> SmartrestPayload {
match payload {
Some(payload) => SmartrestPayload::from_fields([template_id, operation, payload.as_ref()]),
None => SmartrestPayload::from_fields([template_id, operation]),
Some(payload) => SmartrestPayload::serialize((template_id, operation, payload.as_ref())),
None => SmartrestPayload::serialize((template_id, operation)),
}
.expect("operation name shouldn't put payload over size limit")
}
Expand Down Expand Up @@ -201,8 +201,7 @@ impl From<CumulocitySupportedOperations> for &'static str {
}

pub fn declare_supported_operations(ops: &[&str]) -> SmartrestPayload {
SmartrestPayload::from_fields(["114"].iter().chain(ops))
.expect("TODO: ops list can increase payload over limit")
SmartrestPayload::serialize((114, ops)).expect("TODO: ops list can increase payload over limit")
}

#[derive(Debug, Clone, PartialEq)]
Expand Down

0 comments on commit ffc956c

Please sign in to comment.