beavers 0.0.2

Typed message processing for Kafka, Pulsar, RabbitMQ, SQS, Azure Service Bus, and HTTP with explicit delivery semantics
Documentation
use crate::propagation::PropagationCarrier;
use serde::Serialize;
use std::collections::BTreeMap;

/// A typed AMQP field value, as carried in message headers.
///
/// The variants follow the AMQP 0-9-1 field types that RabbitMQ accepts, so a
/// header keeps its type when a record is forwarded. Short and long strings are
/// both read as `String`; a long string that is not UTF-8 is read as `Bytes`.
/// `String` is published as a long string and `Bytes` as a byte array.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum RabbitMqValue {
    /// A field without a value.
    Void,
    /// A boolean.
    Bool(bool),
    /// A signed 8-bit integer (short-short int).
    I8(i8),
    /// An unsigned 8-bit integer (short-short uint).
    U8(u8),
    /// A signed 16-bit integer (short int).
    I16(i16),
    /// An unsigned 16-bit integer (short uint).
    U16(u16),
    /// A signed 32-bit integer (long int).
    I32(i32),
    /// An unsigned 32-bit integer (long uint).
    U32(u32),
    /// A signed 64-bit integer (long-long int).
    I64(i64),
    /// A 32-bit float.
    F32(f32),
    /// A 64-bit float.
    F64(f64),
    /// `value` divided by 10 to the power of `scale`.
    Decimal {
        /// Number of decimal places.
        scale: u8,
        /// Unscaled value.
        value: u32,
    },
    /// A UTF-8 string, read from a short or long string.
    String(String),
    /// A byte array, or a long string that is not UTF-8.
    Bytes(Vec<u8>),
    /// Seconds since the Unix epoch.
    Timestamp(u64),
    /// A field array.
    Array(Vec<RabbitMqValue>),
    /// A nested field table, by name.
    Table(BTreeMap<String, RabbitMqValue>),
}

impl RabbitMqValue {
    /// The text of a `String` value.
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            _ => None,
        }
    }
}

impl From<&str> for RabbitMqValue {
    fn from(value: &str) -> Self {
        Self::String(value.to_owned())
    }
}

impl From<String> for RabbitMqValue {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

impl From<bool> for RabbitMqValue {
    fn from(value: bool) -> Self {
        Self::Bool(value)
    }
}

impl From<i64> for RabbitMqValue {
    fn from(value: i64) -> Self {
        Self::I64(value)
    }
}

/// Message headers, the AMQP `headers` property, by name.
pub type RabbitMqHeaders = BTreeMap<String, RabbitMqValue>;

/// AMQP basic properties that applications set and read.
///
/// The delivery mode is chosen by the sink's
/// [`persistent`](super::RabbitMqSink::persistent) setting and reported
/// in [`RabbitMqMetadata::persistent`]. Text properties are limited to 255
/// bytes by the protocol.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct RabbitMqProperties {
    /// MIME type of the body, such as `application/json`.
    pub content_type: Option<String>,
    /// Encoding of the body, such as `gzip`.
    pub content_encoding: Option<String>,
    /// Message priority, honored by queues declared with a maximum priority.
    pub priority: Option<u8>,
    /// Application correlation identifier, such as the ID of a request being
    /// answered.
    pub correlation_id: Option<String>,
    /// Name of the queue a reply should be sent to.
    pub reply_to: Option<String>,
    /// Per-message TTL in milliseconds, as text.
    pub expiration: Option<String>,
    /// Application message identifier.
    pub message_id: Option<String>,
    /// Seconds since the Unix epoch.
    pub timestamp: Option<u64>,
    /// The AMQP `type` property.
    pub kind: Option<String>,
    /// Checked by RabbitMQ against the publishing connection's user.
    pub user_id: Option<String>,
    /// Identifier of the publishing application.
    pub app_id: Option<String>,
}

/// Read-only facts about a received message.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct RabbitMqMetadata {
    /// The queue the source consumes.
    pub queue: String,
    /// The exchange the message was published to; empty for the default exchange.
    pub exchange: String,
    /// The routing key the message was published with.
    pub routing_key: String,
    /// Whether the broker delivered the message before, to this or another consumer,
    /// without receiving an acknowledgement.
    pub redelivered: bool,
    /// Whether the message was published with the persistent delivery mode.
    pub persistent: bool,
    /// The delivery's tag on the source's channel.
    pub delivery_tag: u64,
}

/// A decoded RabbitMQ delivery. AMQP has no null body, so the value is always present.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct RabbitMqRecord<T> {
    /// Body decoded by the source codec.
    pub value: T,
    /// The AMQP `headers` table.
    pub headers: RabbitMqHeaders,
    /// Basic properties of the message.
    pub properties: RabbitMqProperties,
    /// Queue, exchange, routing key, and delivery facts of the message.
    pub metadata: RabbitMqMetadata,
}

impl<T> RabbitMqRecord<T> {
    /// Queue, exchange, routing key, and delivery facts of the message.
    pub fn metadata(&self) -> &RabbitMqMetadata {
        &self.metadata
    }
}

/// User-controlled RabbitMQ output. The exchange comes from the sink configuration.
#[derive(Clone, Debug, PartialEq)]
pub struct RabbitMqPublish<T> {
    /// Body encoded by the sink codec.
    pub value: T,
    /// Overrides the sink's configured routing key.
    pub routing_key: Option<String>,
    /// The AMQP `headers` table.
    pub headers: RabbitMqHeaders,
    /// Basic properties of the message.
    pub properties: RabbitMqProperties,
}

impl<T> RabbitMqPublish<T> {
    /// Creates an output with `value`, the configured routing key, and no
    /// headers or properties.
    pub fn new(value: T) -> Self {
        Self {
            value,
            routing_key: None,
            headers: RabbitMqHeaders::new(),
            properties: RabbitMqProperties::default(),
        }
    }

    /// Sets a routing key that overrides the sink's configured one.
    pub fn with_routing_key(mut self, routing_key: impl Into<String>) -> Self {
        self.routing_key = Some(routing_key.into());
        self
    }
}

/// Fields are string headers.
impl<T> PropagationCarrier for RabbitMqPublish<T> {
    fn set_propagation_field(&mut self, name: &str, value: String) {
        self.headers
            .insert(name.to_owned(), RabbitMqValue::String(value));
    }
}

/// String headers, in name order.
#[cfg(feature = "testing")]
pub(crate) fn text_headers(headers: &RabbitMqHeaders) -> Vec<(&str, &str)> {
    headers
        .iter()
        .filter_map(|(name, value)| Some((name.as_str(), value.as_str()?)))
        .collect()
}