Skip to main content

wabot_addon_chat_bot_pg/
lib.rs

1//! Postgres `ChatRepository` + `ChatMemory` — port of wabot-ts
2//! `addon/chat-bot/pg` (`ChatPgQueries` / `ChatItemPgQueries`).
3//!
4//! ```ignore
5//! let db = PgDatabase::from_env().await?;
6//! let chats = Arc::new(PgChatRepository::new(db.pool().clone()));
7//! let memories = PgChatMemoryFactory::new(db.pool().clone());
8//!
9//! // one memory per chat, same as the in-memory wiring
10//! let memory: Arc<dyn ChatMemory> = memories.for_chat(chat.id());
11//! ```
12//!
13//! ## Two lookup strategies, mirroring TS
14//!
15//! * **Chat by connection** uses JSONB containment
16//!   (`data->'connections' @> $1`), which a GIN index on `data` can
17//!   serve. A chat can be reachable from several channels, so the
18//!   match has to be "contains this connection", not equality.
19//! * **Chat items by chat** reads a *promoted* `chat_id` column rather
20//!   than digging into the document, because it runs on every single
21//!   turn and wants a plain btree index on `(chat_id, created_at)`.
22//!
23//! ## Storage shape note
24//!
25//! wabot-rust's [`ChatItem`] is a bare enum with no identity, whereas
26//! TS's `ChatItem` is an `Entity`. This addon wraps it in
27//! [`ChatItemData`], which adds the entity fields and the `chatId`
28//! the promoted column reads. That makes the *table* compatible with
29//! TS's, but the document body nests the item under `item` rather
30//! than spreading it — see the Phase 5b notes in CLAUDE.md about
31//! cross-stack JSON compatibility before pointing both frameworks at
32//! one chat-items table.
33
34use 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
51// ---------- Chat repository ---------------------------------------------
52
53pub 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        // GIN over the whole document: `@>` containment on
64        // `data->'connections'` is the only query, and a jsonb_path_ops
65        // GIN is the index Postgres can use for it.
66        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        // The trait returns Option, so a database failure is
97        // indistinguishable from "not found" to the caller. Log it
98        // loudly — a silent None here would mint a duplicate chat.
99        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// ---------- Chat memory --------------------------------------------------
135
136/// Stored form of a [`ChatItem`]: entity fields + the owning chat id
137/// + the item itself.
138#[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    /// Flattened, so the row reads `{ id, createdAt, chatId, type,
145    /// humanMessage }` — the shape wabot-ts stores. Nesting it under
146    /// `item` was the last thing keeping the chat tables from being
147    /// readable by both stacks.
148    #[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
174/// Builds one [`PgChatMemory`] per chat off a shared pool. The
175/// chat-bot layer wants a `ChatMemory` scoped to a single chat, so the
176/// chat id is bound at construction, not passed per call.
177pub 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
205/// Postgres-backed [`ChatMemory`] for one chat.
206pub 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        // Newest first out of the database, oldest first for the
247        // caller — same reversal as the TS implementation.
248        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}