Skip to main content

wabot_feature_chat_bot/
chat.rs

1//! Chat entity + in-memory ChatRepository + ChatResolver.
2//!
3//! Phase 3a homed these in `wabot-feature-chat-controller`; Phase 4
4//! relocated them here so the chat-bot orchestrator has direct access
5//! to chat state without a circular dep. `wabot-feature-chat-controller`
6//! now re-exports them.
7//!
8//! The in-memory implementation is fine for examples and tests; a
9//! Postgres-backed implementation will land in Phase 5.
10
11use std::collections::HashMap;
12use std::sync::Arc;
13
14use parking_lot::Mutex;
15use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18use wabot_core::entity::{Entity, EntityData, EntityFields};
19
20use crate::types::{ChatConnection, ChatType};
21
22/// Persistent chat state. Multi-channel-capable.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct ChatData {
26    #[serde(flatten)]
27    pub base: EntityData,
28    /// `type` on the wire: what TS calls it, and these tables are
29    /// meant to be readable by either stack.
30    #[serde(rename = "type")]
31    pub chat_type: ChatType,
32    pub connections: Vec<ChatConnection>,
33}
34
35impl EntityFields for ChatData {
36    fn entity(&self) -> &EntityData {
37        &self.base
38    }
39    fn entity_mut(&mut self) -> &mut EntityData {
40        &mut self.base
41    }
42}
43
44pub type Chat = Entity<ChatData>;
45
46/// Build a fresh `Chat` from a single connection. Free function rather
47/// than an inherent impl because `Chat` is a type alias (orphan rule).
48pub fn chat_from_connection(connection: ChatConnection) -> Chat {
49    Entity::create(ChatData {
50        base: EntityData::default(),
51        chat_type: connection.chat_type,
52        connections: vec![connection],
53    })
54}
55
56/// Convenience id generator for channels that need to mint a session id
57/// when no platform-supplied one exists (e.g. CLI).
58pub fn fresh_chat_id() -> String {
59    Uuid::new_v4().to_string()
60}
61
62/// Storage interface for `Chat` lookups.
63#[async_trait::async_trait]
64pub trait ChatRepository: Send + Sync {
65    async fn find_by_connection(&self, connection: &ChatConnection) -> Option<Chat>;
66    async fn find_by_id(&self, id: &str) -> Option<Chat>;
67    async fn create(&self, chat: &Chat);
68}
69
70/// In-memory repository — fine for examples and tests.
71#[derive(Debug, Default)]
72pub struct InMemoryChatRepository {
73    by_connection: Mutex<HashMap<(String, String), Chat>>,
74    by_id: Mutex<HashMap<String, Chat>>,
75}
76
77impl InMemoryChatRepository {
78    pub fn new() -> Self {
79        Self::default()
80    }
81
82    fn key(c: &ChatConnection) -> (String, String) {
83        (c.channel_name.clone(), c.id.clone())
84    }
85}
86
87/// DI helper — pair with `register_singletons!(&c, InMemoryChatRepository)`.
88impl wabot_core::injection::IsSingleton for InMemoryChatRepository {
89    fn register_in(c: &wabot_core::injection::Container) {
90        c.register_singleton_factory::<InMemoryChatRepository, _>(|_| {
91            Arc::new(InMemoryChatRepository::new())
92        });
93    }
94}
95
96#[async_trait::async_trait]
97impl ChatRepository for InMemoryChatRepository {
98    async fn find_by_connection(&self, connection: &ChatConnection) -> Option<Chat> {
99        self.by_connection
100            .lock()
101            .get(&Self::key(connection))
102            .cloned()
103    }
104
105    async fn find_by_id(&self, id: &str) -> Option<Chat> {
106        self.by_id.lock().get(id).cloned()
107    }
108
109    async fn create(&self, chat: &Chat) {
110        let id = chat.id().to_string();
111        for conn in &chat.data().connections {
112            self.by_connection
113                .lock()
114                .insert(Self::key(conn), chat.clone());
115        }
116        self.by_id.lock().insert(id, chat.clone());
117    }
118}
119
120/// Make-or-find lookup keyed on `(channel_name, connection_id)`. Uses a
121/// per-key `tokio::sync::Mutex` so concurrent first-time messages from
122/// the same connection serialize their create attempts; horizontal
123/// scaling needs the full Locker port (Phase 5).
124pub struct ChatResolver {
125    repository: Arc<dyn ChatRepository>,
126    locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
127}
128
129impl ChatResolver {
130    pub fn new(repository: Arc<dyn ChatRepository>) -> Self {
131        Self {
132            repository,
133            locks: Mutex::new(HashMap::new()),
134        }
135    }
136
137    pub async fn resolve(&self, connection: &ChatConnection) -> Chat {
138        if let Some(chat) = self.repository.find_by_connection(connection).await {
139            return chat;
140        }
141        let lock = self.lock_for(connection);
142        let _guard = lock.lock().await;
143        if let Some(chat) = self.repository.find_by_connection(connection).await {
144            return chat;
145        }
146        let chat = chat_from_connection(connection.clone());
147        self.repository.create(&chat).await;
148        chat
149    }
150
151    fn lock_for(&self, c: &ChatConnection) -> Arc<tokio::sync::Mutex<()>> {
152        let key = format!("{}:{}", c.channel_name, c.id);
153        let mut map = self.locks.lock();
154        map.entry(key)
155            .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
156            .clone()
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    fn conn(id: &str) -> ChatConnection {
165        ChatConnection {
166            id: id.into(),
167            chat_type: ChatType::Private,
168            channel_name: "Test".into(),
169        }
170    }
171
172    #[tokio::test]
173    async fn resolve_creates_then_finds() {
174        let repo = Arc::new(InMemoryChatRepository::new());
175        let resolver = ChatResolver::new(repo.clone());
176        let c = conn("u-1");
177        let a = resolver.resolve(&c).await;
178        let b = resolver.resolve(&c).await;
179        assert_eq!(a.id(), b.id());
180        assert_eq!(a.data().connections.len(), 1);
181    }
182
183    #[tokio::test]
184    async fn distinct_connections_get_distinct_chats() {
185        let repo = Arc::new(InMemoryChatRepository::new());
186        let resolver = ChatResolver::new(repo.clone());
187        let a = resolver.resolve(&conn("u-1")).await;
188        let b = resolver.resolve(&conn("u-2")).await;
189        assert_ne!(a.id(), b.id());
190    }
191}