Skip to main content

adk_graph/functional/
messages.rs

1//! Chat message container with ID-based deduplication.
2//!
3//! This module provides `MessagesValue`, a specialized state container for
4//! maintaining conversation history without duplicate messages when tasks
5//! retry or replay.
6
7use std::collections::HashMap;
8
9use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
10use serde::ser::{SerializeStruct, Serializer};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13
14/// A chat message role indicating the sender of a message.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum MessageRole {
18    /// A user message.
19    User,
20    /// An assistant message.
21    Assistant,
22    /// A system message.
23    System,
24    /// A tool message.
25    Tool,
26}
27
28/// A chat message with a unique identifier.
29///
30/// Messages are identified by their `id` field for deduplication purposes.
31/// When pushed to a `MessagesValue`, a message with the same `id` as an
32/// existing message will replace it (upsert semantics).
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct ChatMessage {
35    /// Unique identifier for deduplication.
36    pub id: String,
37    /// The role of the message sender.
38    pub role: MessageRole,
39    /// The message content.
40    pub content: String,
41    /// Optional metadata associated with the message.
42    pub metadata: Option<Value>,
43}
44
45/// Chat message container with ID-based deduplication.
46///
47/// Messages with the same ID are replaced (upsert semantics).
48/// The container maintains insertion order and provides O(1) dedup lookup
49/// via an internal index that is rebuilt on deserialization.
50///
51/// # Example
52///
53/// ```rust,ignore
54/// use adk_graph::functional::messages::{MessagesValue, ChatMessage, MessageRole};
55///
56/// let mut messages = MessagesValue::new();
57/// messages.push(ChatMessage {
58///     id: "msg_1".to_string(),
59///     role: MessageRole::User,
60///     content: "Hello".to_string(),
61///     metadata: None,
62/// });
63///
64/// // Pushing a message with the same ID replaces the existing one.
65/// messages.push(ChatMessage {
66///     id: "msg_1".to_string(),
67///     role: MessageRole::User,
68///     content: "Hello, updated!".to_string(),
69///     metadata: None,
70/// });
71///
72/// assert_eq!(messages.len(), 1);
73/// assert_eq!(messages.iter().next().unwrap().content, "Hello, updated!");
74/// ```
75#[derive(Debug, Clone, Default)]
76pub struct MessagesValue {
77    messages: Vec<ChatMessage>,
78    /// Index for O(1) dedup lookup. Maps message ID to index in `messages`.
79    id_index: HashMap<String, usize>,
80}
81
82impl MessagesValue {
83    /// Create an empty message collection.
84    pub fn new() -> Self {
85        Self { messages: Vec::new(), id_index: HashMap::new() }
86    }
87
88    /// Append a message (replaces existing if same ID — upsert semantics).
89    pub fn push(&mut self, message: ChatMessage) {
90        if let Some(&existing_idx) = self.id_index.get(&message.id) {
91            // Replace the existing message at the same position.
92            self.messages[existing_idx] = message;
93        } else {
94            let idx = self.messages.len();
95            self.id_index.insert(message.id.clone(), idx);
96            self.messages.push(message);
97        }
98    }
99
100    /// Extend with multiple messages, applying upsert semantics for each.
101    pub fn extend(&mut self, messages: impl IntoIterator<Item = ChatMessage>) {
102        for message in messages {
103            self.push(message);
104        }
105    }
106
107    /// Iterate over all messages in insertion order.
108    pub fn iter(&self) -> impl Iterator<Item = &ChatMessage> {
109        self.messages.iter()
110    }
111
112    /// Filter messages by role.
113    pub fn by_role(&self, role: MessageRole) -> Vec<&ChatMessage> {
114        self.messages.iter().filter(|m| m.role == role).collect()
115    }
116
117    /// Number of messages.
118    pub fn len(&self) -> usize {
119        self.messages.len()
120    }
121
122    /// Check if empty.
123    pub fn is_empty(&self) -> bool {
124        self.messages.is_empty()
125    }
126
127    /// Rebuild the `id_index` from the current messages Vec.
128    /// Called after deserialization to restore the index.
129    fn rebuild_index(&mut self) {
130        self.id_index.clear();
131        for (idx, msg) in self.messages.iter().enumerate() {
132            self.id_index.insert(msg.id.clone(), idx);
133        }
134    }
135}
136
137impl Serialize for MessagesValue {
138    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
139    where
140        S: Serializer,
141    {
142        let mut state = serializer.serialize_struct("MessagesValue", 1)?;
143        state.serialize_field("messages", &self.messages)?;
144        state.end()
145    }
146}
147
148impl<'de> Deserialize<'de> for MessagesValue {
149    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
150    where
151        D: Deserializer<'de>,
152    {
153        #[derive(Deserialize)]
154        #[serde(field_identifier, rename_all = "lowercase")]
155        enum Field {
156            Messages,
157        }
158
159        struct MessagesValueVisitor;
160
161        impl<'de> Visitor<'de> for MessagesValueVisitor {
162            type Value = MessagesValue;
163
164            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
165                formatter.write_str("struct MessagesValue")
166            }
167
168            fn visit_seq<V>(self, mut seq: V) -> Result<MessagesValue, V::Error>
169            where
170                V: SeqAccess<'de>,
171            {
172                let messages: Vec<ChatMessage> = seq.next_element()?.unwrap_or_default();
173                let mut value = MessagesValue { messages, id_index: HashMap::new() };
174                value.rebuild_index();
175                Ok(value)
176            }
177
178            fn visit_map<V>(self, mut map: V) -> Result<MessagesValue, V::Error>
179            where
180                V: MapAccess<'de>,
181            {
182                let mut messages: Option<Vec<ChatMessage>> = None;
183                while let Some(key) = map.next_key()? {
184                    match key {
185                        Field::Messages => {
186                            if messages.is_some() {
187                                return Err(de::Error::duplicate_field("messages"));
188                            }
189                            messages = Some(map.next_value()?);
190                        }
191                    }
192                }
193                let messages = messages.unwrap_or_default();
194                let mut value = MessagesValue { messages, id_index: HashMap::new() };
195                value.rebuild_index();
196                Ok(value)
197            }
198        }
199
200        const FIELDS: &[&str] = &["messages"];
201        deserializer.deserialize_struct("MessagesValue", FIELDS, MessagesValueVisitor)
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn test_push_new_message() {
211        let mut mv = MessagesValue::new();
212        mv.push(ChatMessage {
213            id: "msg_1".to_string(),
214            role: MessageRole::User,
215            content: "Hello".to_string(),
216            metadata: None,
217        });
218        assert_eq!(mv.len(), 1);
219        assert!(!mv.is_empty());
220    }
221
222    #[test]
223    fn test_push_upsert_replaces() {
224        let mut mv = MessagesValue::new();
225        mv.push(ChatMessage {
226            id: "msg_1".to_string(),
227            role: MessageRole::User,
228            content: "Original".to_string(),
229            metadata: None,
230        });
231        mv.push(ChatMessage {
232            id: "msg_1".to_string(),
233            role: MessageRole::User,
234            content: "Updated".to_string(),
235            metadata: None,
236        });
237        assert_eq!(mv.len(), 1);
238        assert_eq!(mv.iter().next().unwrap().content, "Updated");
239    }
240
241    #[test]
242    fn test_extend_with_upsert() {
243        let mut mv = MessagesValue::new();
244        mv.push(ChatMessage {
245            id: "msg_1".to_string(),
246            role: MessageRole::User,
247            content: "First".to_string(),
248            metadata: None,
249        });
250        mv.extend(vec![
251            ChatMessage {
252                id: "msg_1".to_string(),
253                role: MessageRole::User,
254                content: "Updated first".to_string(),
255                metadata: None,
256            },
257            ChatMessage {
258                id: "msg_2".to_string(),
259                role: MessageRole::Assistant,
260                content: "Second".to_string(),
261                metadata: None,
262            },
263        ]);
264        assert_eq!(mv.len(), 2);
265        let msgs: Vec<_> = mv.iter().collect();
266        assert_eq!(msgs[0].content, "Updated first");
267        assert_eq!(msgs[1].content, "Second");
268    }
269
270    #[test]
271    fn test_by_role() {
272        let mut mv = MessagesValue::new();
273        mv.push(ChatMessage {
274            id: "msg_1".to_string(),
275            role: MessageRole::User,
276            content: "User msg".to_string(),
277            metadata: None,
278        });
279        mv.push(ChatMessage {
280            id: "msg_2".to_string(),
281            role: MessageRole::Assistant,
282            content: "Assistant msg".to_string(),
283            metadata: None,
284        });
285        mv.push(ChatMessage {
286            id: "msg_3".to_string(),
287            role: MessageRole::User,
288            content: "Another user msg".to_string(),
289            metadata: None,
290        });
291
292        let user_msgs = mv.by_role(MessageRole::User);
293        assert_eq!(user_msgs.len(), 2);
294
295        let assistant_msgs = mv.by_role(MessageRole::Assistant);
296        assert_eq!(assistant_msgs.len(), 1);
297
298        let system_msgs = mv.by_role(MessageRole::System);
299        assert!(system_msgs.is_empty());
300    }
301
302    #[test]
303    fn test_serialization_round_trip() {
304        let mut mv = MessagesValue::new();
305        mv.push(ChatMessage {
306            id: "msg_1".to_string(),
307            role: MessageRole::User,
308            content: "Hello".to_string(),
309            metadata: Some(serde_json::json!({"key": "value"})),
310        });
311        mv.push(ChatMessage {
312            id: "msg_2".to_string(),
313            role: MessageRole::Assistant,
314            content: "Hi there".to_string(),
315            metadata: None,
316        });
317
318        let serialized = serde_json::to_string(&mv).unwrap();
319        let deserialized: MessagesValue = serde_json::from_str(&serialized).unwrap();
320
321        assert_eq!(deserialized.len(), 2);
322        let msgs: Vec<_> = deserialized.iter().collect();
323        assert_eq!(msgs[0].id, "msg_1");
324        assert_eq!(msgs[0].content, "Hello");
325        assert_eq!(msgs[1].id, "msg_2");
326        assert_eq!(msgs[1].content, "Hi there");
327    }
328
329    #[test]
330    fn test_dedup_after_deserialization() {
331        let mut mv = MessagesValue::new();
332        mv.push(ChatMessage {
333            id: "msg_1".to_string(),
334            role: MessageRole::User,
335            content: "Hello".to_string(),
336            metadata: None,
337        });
338
339        let serialized = serde_json::to_string(&mv).unwrap();
340        let mut deserialized: MessagesValue = serde_json::from_str(&serialized).unwrap();
341
342        // After deserialization, the id_index should be rebuilt
343        // so push with same ID should still deduplicate.
344        deserialized.push(ChatMessage {
345            id: "msg_1".to_string(),
346            role: MessageRole::User,
347            content: "Updated after deser".to_string(),
348            metadata: None,
349        });
350
351        assert_eq!(deserialized.len(), 1);
352        assert_eq!(deserialized.iter().next().unwrap().content, "Updated after deser");
353    }
354
355    #[test]
356    fn test_empty_messages_value() {
357        let mv = MessagesValue::new();
358        assert_eq!(mv.len(), 0);
359        assert!(mv.is_empty());
360        assert_eq!(mv.iter().count(), 0);
361        assert_eq!(mv.by_role(MessageRole::User).len(), 0);
362    }
363}