Skip to main content

eventail/
delivery.rs

1//! `Delivery` represents messages received from the EDA Bus.
2
3use amqprs::BasicProperties;
4use amqprs::Deliver;
5use serde::Deserialize;
6
7/// A message received from the EDA bus
8#[derive(Debug)]
9pub struct Delivery {
10    deliver: Deliver,
11    properties: BasicProperties,
12    payload: Vec<u8>,
13}
14
15/// Error type for `Delivery` methods.
16pub enum Error {
17    Deserialization(String),
18}
19
20impl<T: std::error::Error> From<T> for Error {
21    fn from(value: T) -> Self {
22        Error::Deserialization(value.to_string())
23    }
24}
25
26impl Delivery {
27    /// Create a new `Delivery` from lower level parts.
28    /// This method is private to the crate.
29    pub(crate) fn new(deliver: Deliver, properties: BasicProperties, payload: Vec<u8>) -> Self {
30        Self {
31            deliver,
32            properties,
33            payload,
34        }
35    }
36
37    /// Return the delivery tag.
38    pub fn tag(&self) -> u64 {
39        self.deliver.delivery_tag()
40    }
41
42    pub fn routing_key(&self) -> &str {
43        self.deliver.routing_key().as_str()
44    }
45
46    pub fn content_type(&self) -> Option<&str> {
47        self.properties.content_type().map(|s| s.as_str())
48    }
49
50    /// Return true if the message was already presented to this or another worker (and was nack'ed).
51    pub fn redelivered(&self) -> bool {
52        self.deliver.redelivered()
53    }
54
55    pub fn conversation_id(&self) -> Option<&str> {
56        self.properties
57            .headers()
58            .and_then(|h| h.get(&"conversation_id".try_into().unwrap()))
59            .and_then(|v| v.try_into().ok())
60    }
61
62    /// For Results to Commands, indicates "success" or "error".
63    pub fn status(&self) -> Option<&str> {
64        self.properties
65            .headers()
66            .and_then(|h| h.get(&"status".try_into().unwrap()))
67            .and_then(|v| v.try_into().ok())
68    }
69
70    pub fn correlation_id(&self) -> Option<&str> {
71        self.properties.correlation_id().map(|c| c.as_str())
72    }
73
74    pub fn exchange(&self) -> &str {
75        self.deliver.exchange().as_str()
76    }
77
78    pub fn reply_to(&self) -> Option<&str> {
79        self.properties.reply_to().map(|c| c.as_str())
80    }
81
82    pub fn deserialize_payload<'a, T: Deserialize<'a>>(&'a self) -> Result<T, Error> {
83        if let Some("application/json") = self.properties.content_type().map(|s| s.as_str()) {
84            Ok(serde_json::from_slice(&self.payload)?)
85        } else {
86            Ok(cbor4ii::serde::from_slice(&self.payload)?)
87        }
88    }
89}