Skip to main content

rullst_messaging/
types.rs

1//! Validated identifiers, configuration, and bounded message headers.
2
3use crate::validation::{
4    MAX_CONSUMER_BYTES, MAX_EVENT_KIND_BYTES, MAX_GROUP_BYTES, MAX_HEADER_COUNT,
5    MAX_HEADER_TOTAL_BYTES, MAX_NAMESPACE_BYTES, MAX_TOPIC_BYTES, validate_content_type,
6    validate_failure_code, validate_header_name, validate_header_value, validate_idempotency_key,
7    validate_route_identifier,
8};
9use crate::{MessagingError, Result};
10use serde::Serialize;
11use std::collections::BTreeMap;
12use std::fmt;
13
14macro_rules! route_identifier {
15    ($name:ident, $field:literal, $max:expr) => {
16        #[doc = concat!("Validated broker ", $field, ".")]
17        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
18        #[serde(transparent)]
19        pub struct $name(String);
20
21        impl $name {
22            #[doc = concat!("Creates a validated ", $field, ".")]
23            pub fn try_new(value: impl Into<String>) -> Result<Self> {
24                let value = value.into();
25                validate_route_identifier($field, &value, $max)?;
26                Ok(Self(value))
27            }
28
29            #[doc = concat!("Returns the validated ", $field, ".")]
30            pub fn as_str(&self) -> &str {
31                &self.0
32            }
33        }
34
35        impl fmt::Display for $name {
36            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
37                formatter.write_str(&self.0)
38            }
39        }
40    };
41}
42
43route_identifier!(Namespace, "namespace", MAX_NAMESPACE_BYTES);
44route_identifier!(TopicName, "topic", MAX_TOPIC_BYTES);
45route_identifier!(ConsumerGroup, "consumer group", MAX_GROUP_BYTES);
46route_identifier!(ConsumerName, "consumer name", MAX_CONSUMER_BYTES);
47route_identifier!(EventKind, "event kind", MAX_EVENT_KIND_BYTES);
48
49/// Caller-owned idempotency key, redacted from debug output.
50#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
51#[serde(transparent)]
52pub struct IdempotencyKey(String);
53
54impl IdempotencyKey {
55    /// Creates a bounded idempotency key.
56    pub fn try_new(value: impl Into<String>) -> Result<Self> {
57        let value = value.into();
58        validate_idempotency_key(&value)?;
59        Ok(Self(value))
60    }
61
62    pub(crate) fn as_str(&self) -> &str {
63        &self.0
64    }
65}
66
67impl fmt::Debug for IdempotencyKey {
68    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69        formatter.write_str("IdempotencyKey([REDACTED])")
70    }
71}
72
73/// Validated parameter-free MIME type.
74#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
75#[serde(transparent)]
76pub struct ContentType(String);
77
78impl ContentType {
79    /// Creates a validated MIME type such as `application/json`.
80    pub fn try_new(value: impl Into<String>) -> Result<Self> {
81        let value = value.into();
82        validate_content_type(&value)?;
83        Ok(Self(value))
84    }
85
86    /// Returns the MIME type.
87    pub fn as_str(&self) -> &str {
88        &self.0
89    }
90
91    pub(crate) fn binary() -> Self {
92        Self("application/octet-stream".to_string())
93    }
94}
95
96/// Stable low-cardinality processing failure code.
97#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
98#[serde(transparent)]
99pub struct FailureCode(String);
100
101impl FailureCode {
102    /// Creates a bounded code such as `handler.transient`.
103    pub fn try_new(value: impl Into<String>) -> Result<Self> {
104        let value = value.into();
105        validate_failure_code(&value)?;
106        Ok(Self(value))
107    }
108
109    /// Returns the validated code.
110    pub fn as_str(&self) -> &str {
111        &self.0
112    }
113
114    pub(crate) fn max_attempts() -> Self {
115        Self("delivery.max_attempts".to_string())
116    }
117}
118
119/// Broker-assigned opaque message identifier.
120#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
121#[serde(transparent)]
122pub struct MessageId(String);
123
124impl MessageId {
125    pub(crate) fn random() -> Self {
126        Self(format!("msg_{}", uuid::Uuid::new_v4().simple()))
127    }
128
129    pub(crate) fn from_stored(value: String) -> Result<Self> {
130        let valid = value.len() == 36
131            && value.starts_with("msg_")
132            && value[4..]
133                .bytes()
134                .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'));
135        if !valid {
136            return Err(MessagingError::CorruptStorage {
137                context: "message identifier",
138            });
139        }
140        Ok(Self(value))
141    }
142
143    /// Returns the opaque identifier.
144    pub fn as_str(&self) -> &str {
145        &self.0
146    }
147}
148
149/// Single-use acknowledgement capability, redacted from debug output.
150#[derive(Clone, PartialEq, Eq, Hash)]
151pub struct AckToken(String);
152
153impl AckToken {
154    pub(crate) fn random() -> Self {
155        Self(format!("ack_{}", uuid::Uuid::new_v4().simple()))
156    }
157
158    pub(crate) fn as_str(&self) -> &str {
159        &self.0
160    }
161}
162
163impl fmt::Debug for AckToken {
164    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165        formatter.write_str("AckToken([REDACTED])")
166    }
167}
168
169/// Bounded, deterministic message metadata.
170#[derive(Clone, Default, PartialEq, Eq, Serialize)]
171#[serde(transparent)]
172pub struct MessageHeaders(BTreeMap<String, String>);
173
174impl MessageHeaders {
175    /// Creates an empty header collection.
176    pub fn new() -> Self {
177        Self::default()
178    }
179
180    #[cfg(feature = "sqlite")]
181    pub(crate) fn from_stored(entries: BTreeMap<String, String>) -> Result<Self> {
182        let mut headers = Self::new();
183        for (name, value) in entries {
184            headers
185                .try_insert(name, value)
186                .map_err(|_| MessagingError::CorruptStorage {
187                    context: "message headers",
188                })?;
189        }
190        Ok(headers)
191    }
192
193    /// Adds one unique header after validating name, value, count, and total bytes.
194    pub fn try_insert(&mut self, name: impl Into<String>, value: impl Into<String>) -> Result<()> {
195        let name = name.into();
196        let value = value.into();
197        validate_header_name(&name)?;
198        validate_header_value(&value)?;
199        if self.0.contains_key(&name) {
200            return Err(MessagingError::Invalid {
201                field: "message header name",
202                reason: "duplicate names are not allowed",
203            });
204        }
205        if self.0.len() >= MAX_HEADER_COUNT {
206            return Err(MessagingError::CapacityExceeded {
207                resource: "message headers",
208                limit: MAX_HEADER_COUNT,
209            });
210        }
211        let current = self
212            .0
213            .iter()
214            .try_fold(0usize, |total, (key, item)| {
215                total.checked_add(key.len())?.checked_add(item.len())
216            })
217            .ok_or(MessagingError::InternalState {
218                context: "message header byte accounting",
219            })?;
220        let proposed = current
221            .checked_add(name.len())
222            .and_then(|total| total.checked_add(value.len()))
223            .ok_or(MessagingError::InternalState {
224                context: "message header byte accounting",
225            })?;
226        if proposed > MAX_HEADER_TOTAL_BYTES {
227            return Err(MessagingError::CapacityExceeded {
228                resource: "message header bytes",
229                limit: MAX_HEADER_TOTAL_BYTES,
230            });
231        }
232        self.0.insert(name, value);
233        Ok(())
234    }
235
236    /// Returns a header without modifying the collection.
237    pub fn get(&self, name: &str) -> Option<&str> {
238        self.0.get(name).map(String::as_str)
239    }
240
241    /// Iterates over validated names and values in deterministic order.
242    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
243        self.0
244            .iter()
245            .map(|(name, value)| (name.as_str(), value.as_str()))
246    }
247
248    /// Returns the number of headers.
249    pub fn len(&self) -> usize {
250        self.0.len()
251    }
252
253    /// Returns whether the collection is empty.
254    pub fn is_empty(&self) -> bool {
255        self.0.is_empty()
256    }
257}
258
259impl fmt::Debug for MessageHeaders {
260    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
261        formatter
262            .debug_struct("MessageHeaders")
263            .field("names", &self.0.keys().collect::<Vec<_>>())
264            .field("count", &self.0.len())
265            .finish()
266    }
267}
268
269/// Position used when a consumer group is first registered.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271#[non_exhaustive]
272pub enum StartPosition {
273    /// Deliver every message still retained by the broker.
274    Earliest,
275    /// Deliver only messages published after registration.
276    Latest,
277}
278
279/// Hard bounds for a broker instance.
280#[derive(Debug, Clone, PartialEq, Eq)]
281#[non_exhaustive]
282pub struct BrokerConfig {
283    namespace: Namespace,
284    max_retained_messages: usize,
285    max_subscriptions: usize,
286    max_attempts: u32,
287    max_payload_bytes: usize,
288}
289
290impl BrokerConfig {
291    /// Default retained-message bound.
292    pub const DEFAULT_MAX_RETAINED_MESSAGES: usize = 10_000;
293    /// Absolute retained-message configuration ceiling.
294    pub const MAX_RETAINED_MESSAGES: usize = 100_000;
295    /// Default subscription bound.
296    pub const DEFAULT_MAX_SUBSCRIPTIONS: usize = 128;
297    /// Absolute subscription configuration ceiling.
298    pub const MAX_SUBSCRIPTIONS: usize = 1_024;
299    /// Default delivery-attempt bound.
300    pub const DEFAULT_MAX_ATTEMPTS: u32 = 5;
301    /// Absolute attempt configuration ceiling.
302    pub const MAX_ATTEMPTS: u32 = 100;
303    /// Default payload limit (one MiB).
304    pub const DEFAULT_MAX_PAYLOAD_BYTES: usize = 1024 * 1024;
305    /// Absolute payload configuration ceiling (sixteen MiB).
306    pub const MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
307
308    /// Creates a bounded configuration with conservative defaults.
309    pub fn try_new(namespace: impl Into<String>) -> Result<Self> {
310        Ok(Self {
311            namespace: Namespace::try_new(namespace)?,
312            max_retained_messages: Self::DEFAULT_MAX_RETAINED_MESSAGES,
313            max_subscriptions: Self::DEFAULT_MAX_SUBSCRIPTIONS,
314            max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
315            max_payload_bytes: Self::DEFAULT_MAX_PAYLOAD_BYTES,
316        })
317    }
318
319    /// Replaces all operational limits after validating their ceilings.
320    pub fn with_limits(
321        mut self,
322        max_retained_messages: usize,
323        max_subscriptions: usize,
324        max_attempts: u32,
325        max_payload_bytes: usize,
326    ) -> Result<Self> {
327        if !(1..=Self::MAX_RETAINED_MESSAGES).contains(&max_retained_messages) {
328            return Err(MessagingError::Invalid {
329                field: "retained message limit",
330                reason: "must be within the documented configuration ceiling",
331            });
332        }
333        if !(1..=Self::MAX_SUBSCRIPTIONS).contains(&max_subscriptions) {
334            return Err(MessagingError::Invalid {
335                field: "subscription limit",
336                reason: "must be within the documented configuration ceiling",
337            });
338        }
339        if !(1..=Self::MAX_ATTEMPTS).contains(&max_attempts) {
340            return Err(MessagingError::Invalid {
341                field: "delivery attempt limit",
342                reason: "must be within the documented configuration ceiling",
343            });
344        }
345        if !(1..=Self::MAX_PAYLOAD_BYTES).contains(&max_payload_bytes) {
346            return Err(MessagingError::Invalid {
347                field: "payload byte limit",
348                reason: "must be within the documented configuration ceiling",
349            });
350        }
351        self.max_retained_messages = max_retained_messages;
352        self.max_subscriptions = max_subscriptions;
353        self.max_attempts = max_attempts;
354        self.max_payload_bytes = max_payload_bytes;
355        Ok(self)
356    }
357
358    /// Returns the immutable namespace.
359    pub fn namespace(&self) -> &Namespace {
360        &self.namespace
361    }
362
363    /// Returns the retained-message bound.
364    pub fn max_retained_messages(&self) -> usize {
365        self.max_retained_messages
366    }
367
368    /// Returns the subscription bound.
369    pub fn max_subscriptions(&self) -> usize {
370        self.max_subscriptions
371    }
372
373    /// Returns the maximum delivery attempts before automatic dead-lettering.
374    pub fn max_attempts(&self) -> u32 {
375        self.max_attempts
376    }
377
378    /// Returns the payload byte bound.
379    pub fn max_payload_bytes(&self) -> usize {
380        self.max_payload_bytes
381    }
382}