wabot_addon_chat_bot_pg/
lib.rs1use std::sync::Arc;
35
36use async_trait::async_trait;
37use serde::{Deserialize, Serialize};
38use sqlx::PgPool;
39use uuid::Uuid;
40
41use wabot_core::entity::{Entity, EntityData, EntityFields};
42use wabot_feature_chat_bot::chat::{Chat, ChatData, ChatRepository};
43use wabot_feature_chat_bot::chat_item::ChatItem;
44use wabot_feature_chat_bot::memory::ChatMemory;
45use wabot_feature_chat_bot::types::ChatConnection;
46use wabot_feature_pg::{PgJsonbStore, PromotedColumn};
47
48pub const CHATS_TABLE: &str = "chats";
49pub const CHAT_ITEMS_TABLE: &str = "chat_items";
50
51pub struct PgChatRepository {
54 store: PgJsonbStore<ChatData>,
55}
56
57impl PgChatRepository {
58 pub fn new(pool: PgPool) -> Self {
59 Self::with_table(pool, CHATS_TABLE)
60 }
61
62 pub fn with_table(pool: PgPool, table: &str) -> Self {
63 let store = PgJsonbStore::new(pool, table).with_index(
67 "CREATE INDEX IF NOT EXISTS chats_data_gin_idx ON \"public\".\"chats\" \
68 USING GIN (data jsonb_path_ops)",
69 );
70 Self { store }
71 }
72
73 pub fn store(&self) -> &PgJsonbStore<ChatData> {
74 &self.store
75 }
76
77 pub async fn ensure_ready(&self) -> wabot_feature_pg::PgResult<()> {
78 self.store.ensure_ready().await
79 }
80}
81
82#[async_trait]
83impl ChatRepository for PgChatRepository {
84 async fn find_by_connection(&self, connection: &ChatConnection) -> Option<Chat> {
85 let sql = format!(
86 "SELECT data FROM {t} WHERE data->'connections' @> $1::jsonb LIMIT 1",
87 t = self.store.table()
88 );
89 let needle = match serde_json::to_value([connection]) {
90 Ok(v) => v,
91 Err(e) => {
92 tracing::error!(error = %e, "failed to encode chat connection");
93 return None;
94 }
95 };
96 match self.store.query_opt(&sql, |q| q.bind(needle)).await {
100 Ok(found) => found,
101 Err(e) => {
102 tracing::error!(error = %e, "find_by_connection failed");
103 None
104 }
105 }
106 }
107
108 async fn find_by_id(&self, id: &str) -> Option<Chat> {
109 match self.store.find_by_id(id).await {
110 Ok(found) => found,
111 Err(e) => {
112 tracing::error!(error = %e, "find_by_id failed");
113 None
114 }
115 }
116 }
117
118 async fn create(&self, chat: &Chat) {
119 if let Err(e) = self.store.save(chat).await {
120 tracing::error!(chat_id = %chat.id(), error = %e, "failed to persist chat");
121 }
122 }
123}
124
125impl wabot_core::injection::IsSingleton for PgChatRepository {
126 fn register_in(c: &wabot_core::injection::Container) {
127 c.register_singleton_factory::<PgChatRepository, _>(|c2| {
128 let db: Arc<wabot_feature_pg::PgDatabase> = c2.resolve();
129 Arc::new(PgChatRepository::new(db.pool().clone()))
130 });
131 }
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct ChatItemData {
140 #[serde(flatten)]
141 pub base: EntityData,
142 #[serde(rename = "chatId")]
143 pub chat_id: String,
144 #[serde(flatten)]
149 pub item: ChatItem,
150}
151
152impl EntityFields for ChatItemData {
153 fn entity(&self) -> &EntityData {
154 &self.base
155 }
156 fn entity_mut(&mut self) -> &mut EntityData {
157 &mut self.base
158 }
159}
160
161fn chat_items_store(pool: PgPool, table: &str) -> PgJsonbStore<ChatItemData> {
162 PgJsonbStore::new(pool, table)
163 .with_promoted_column(PromotedColumn {
164 name: "chat_id",
165 ddl_type: "TEXT",
166 value: |d: &ChatItemData| Some(d.chat_id.clone()),
167 })
168 .with_index(
169 "CREATE INDEX IF NOT EXISTS chat_items_chat_id_created_at_idx \
170 ON \"public\".\"chat_items\" (chat_id, created_at DESC)",
171 )
172}
173
174pub struct PgChatMemoryFactory {
178 pool: PgPool,
179 table: String,
180}
181
182impl PgChatMemoryFactory {
183 pub fn new(pool: PgPool) -> Self {
184 Self {
185 pool,
186 table: CHAT_ITEMS_TABLE.to_string(),
187 }
188 }
189
190 pub fn with_table(pool: PgPool, table: impl Into<String>) -> Self {
191 Self {
192 pool,
193 table: table.into(),
194 }
195 }
196
197 pub fn for_chat(&self, chat_id: impl Into<String>) -> Arc<PgChatMemory> {
198 Arc::new(PgChatMemory {
199 store: chat_items_store(self.pool.clone(), &self.table),
200 chat_id: chat_id.into(),
201 })
202 }
203}
204
205pub struct PgChatMemory {
207 store: PgJsonbStore<ChatItemData>,
208 chat_id: String,
209}
210
211impl PgChatMemory {
212 pub fn new(pool: PgPool, chat_id: impl Into<String>) -> Self {
213 Self {
214 store: chat_items_store(pool, CHAT_ITEMS_TABLE),
215 chat_id: chat_id.into(),
216 }
217 }
218
219 pub fn chat_id(&self) -> &str {
220 &self.chat_id
221 }
222
223 pub async fn ensure_ready(&self) -> wabot_feature_pg::PgResult<()> {
224 self.store.ensure_ready().await
225 }
226}
227
228#[async_trait]
229impl ChatMemory for PgChatMemory {
230 async fn find_last_items(&self, n: usize) -> Vec<ChatItem> {
231 let sql = format!(
232 "SELECT data FROM {t} WHERE chat_id = $1 ORDER BY created_at DESC LIMIT $2",
233 t = self.store.table()
234 );
235 let rows = match self
236 .store
237 .query(&sql, |q| q.bind(self.chat_id.clone()).bind(n as i64))
238 .await
239 {
240 Ok(rows) => rows,
241 Err(e) => {
242 tracing::error!(chat_id = %self.chat_id, error = %e, "failed to read chat memory");
243 return Vec::new();
244 }
245 };
246 rows.into_iter()
249 .rev()
250 .map(|entity| entity.data().item.clone())
251 .collect()
252 }
253
254 async fn create(&self, item: ChatItem) {
255 let entity = Entity::create(ChatItemData {
256 base: EntityData {
257 id: Some(Uuid::new_v4().to_string()),
258 ..EntityData::default()
259 },
260 chat_id: self.chat_id.clone(),
261 item,
262 });
263 if let Err(e) = self.store.save(&entity).await {
264 tracing::error!(chat_id = %self.chat_id, error = %e, "failed to append chat item");
265 }
266 }
267}