Skip to main content

rskit_messaging/
message.rs

1use std::collections::HashMap;
2
3use chrono::{DateTime, Utc};
4use uuid::Uuid;
5
6/// A generic message that can be sent to or received from a message broker.
7#[derive(Debug, Clone)]
8pub struct Message<T> {
9    /// The topic or channel the message belongs to.
10    pub topic: String,
11    /// Optional partitioning key.
12    pub key: Option<String>,
13    /// The message payload.
14    pub payload: T,
15    /// Arbitrary key-value headers attached to the message.
16    pub headers: HashMap<String, String>,
17    /// Timestamp when the message was created.
18    pub timestamp: DateTime<Utc>,
19    /// The partition the message was sent to or read from.
20    pub partition: Option<i32>,
21    /// The offset within the partition.
22    pub offset: Option<i64>,
23}
24
25impl<T> Message<T> {
26    /// Create a new message for the given topic with the provided payload.
27    pub fn new(topic: impl Into<String>, payload: T) -> Self {
28        Self {
29            topic: topic.into(),
30            key: None,
31            payload,
32            headers: HashMap::new(),
33            timestamp: Utc::now(),
34            partition: None,
35            offset: None,
36        }
37    }
38
39    /// Set the partitioning key.
40    #[must_use]
41    pub fn with_key(mut self, key: impl Into<String>) -> Self {
42        self.key = Some(key.into());
43        self
44    }
45
46    /// Attach a single header.
47    #[must_use]
48    pub fn with_header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
49        self.headers.insert(key.into(), value.into());
50        self
51    }
52
53    /// Attach a unique message-id header.
54    #[must_use]
55    pub fn with_message_id(self) -> Self {
56        self.with_header("message-id", Uuid::new_v4().to_string())
57    }
58}