|
| 1 | +"""Persistent storage for chat messages and escalations using SQLAlchemy. |
| 2 | +
|
| 3 | +NOTE: Active WebSocket connections are intentionally kept in-memory only |
| 4 | +(in ChatManager). Only messages and escalation events are persisted here. |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import logging |
| 9 | +from datetime import datetime |
| 10 | +from typing import Any, Dict, List, Optional |
| 11 | + |
| 12 | +from sqlalchemy import Column, DateTime, Integer, String, Text, create_engine, text |
| 13 | +from sqlalchemy import MetaData, Table |
| 14 | +from sqlalchemy.dialects.postgresql import insert as pg_insert |
| 15 | + |
| 16 | +import src.db as _db |
| 17 | + |
| 18 | +logger = logging.getLogger("veritix.chat_store") |
| 19 | + |
| 20 | +_MESSAGES_TABLE = "chat_messages" |
| 21 | +_ESCALATIONS_TABLE = "chat_escalations" |
| 22 | + |
| 23 | + |
| 24 | +def _get_engine(): |
| 25 | + return _db.get_engine() |
| 26 | + |
| 27 | + |
| 28 | +def _ensure_tables(engine) -> None: |
| 29 | + metadata = MetaData() |
| 30 | + Table( |
| 31 | + _MESSAGES_TABLE, |
| 32 | + metadata, |
| 33 | + Column("id", String, primary_key=True), |
| 34 | + Column("conversation_id", String, nullable=False), |
| 35 | + Column("sender_id", String, nullable=False), |
| 36 | + Column("sender_type", String, nullable=False), |
| 37 | + Column("content", Text, nullable=False), |
| 38 | + Column("timestamp", DateTime, nullable=False), |
| 39 | + Column("metadata_json", Text), |
| 40 | + ) |
| 41 | + Table( |
| 42 | + _ESCALATIONS_TABLE, |
| 43 | + metadata, |
| 44 | + Column("id", String, primary_key=True), |
| 45 | + Column("conversation_id", String, nullable=False), |
| 46 | + Column("reason", String, nullable=False), |
| 47 | + Column("timestamp", DateTime, nullable=False), |
| 48 | + Column("metadata_json", Text), |
| 49 | + ) |
| 50 | + with engine.begin() as conn: |
| 51 | + metadata.create_all(conn) # type: ignore[arg-type] |
| 52 | + |
| 53 | + |
| 54 | +class ChatStore: |
| 55 | + """Persists chat messages and escalation events to Postgres.""" |
| 56 | + |
| 57 | + def __init__(self) -> None: |
| 58 | + self._ready = False |
| 59 | + |
| 60 | + def _init(self, engine) -> None: |
| 61 | + if not self._ready: |
| 62 | + try: |
| 63 | + _ensure_tables(engine) |
| 64 | + self._ready = True |
| 65 | + except Exception as exc: |
| 66 | + logger.error("ChatStore: failed to create tables: %s", exc) |
| 67 | + |
| 68 | + # ------------------------------------------------------------------ |
| 69 | + # Messages |
| 70 | + # ------------------------------------------------------------------ |
| 71 | + |
| 72 | + def save_message(self, message: Any) -> None: |
| 73 | + """Persist a ChatMessage to the DB (best-effort).""" |
| 74 | + engine = _get_engine() |
| 75 | + if engine is None: |
| 76 | + return |
| 77 | + self._init(engine) |
| 78 | + import json |
| 79 | + try: |
| 80 | + with engine.begin() as conn: |
| 81 | + conn.execute( |
| 82 | + text( |
| 83 | + f"INSERT INTO {_MESSAGES_TABLE} " # noqa: S608 |
| 84 | + "(id, conversation_id, sender_id, sender_type, content, timestamp, metadata_json) " |
| 85 | + "VALUES (:id, :conv, :sender, :stype, :content, :ts, :meta) " |
| 86 | + "ON CONFLICT (id) DO NOTHING" |
| 87 | + ), |
| 88 | + { |
| 89 | + "id": message.id, |
| 90 | + "conv": message.conversation_id, |
| 91 | + "sender": message.sender_id, |
| 92 | + "stype": message.sender_type, |
| 93 | + "content": message.content, |
| 94 | + "ts": message.timestamp, |
| 95 | + "meta": json.dumps(message.metadata or {}), |
| 96 | + }, |
| 97 | + ) |
| 98 | + except Exception as exc: |
| 99 | + logger.error("ChatStore: save_message failed: %s", exc) |
| 100 | + |
| 101 | + def get_messages(self, conversation_id: str, limit: int = 50) -> List[Dict[str, Any]]: |
| 102 | + """Retrieve the most recent messages for a conversation from DB.""" |
| 103 | + engine = _get_engine() |
| 104 | + if engine is None: |
| 105 | + return [] |
| 106 | + self._init(engine) |
| 107 | + try: |
| 108 | + with engine.connect() as conn: |
| 109 | + rows = conn.execute( |
| 110 | + text( |
| 111 | + f"SELECT id, conversation_id, sender_id, sender_type, content, timestamp, metadata_json " # noqa: S608 |
| 112 | + f"FROM {_MESSAGES_TABLE} " |
| 113 | + "WHERE conversation_id = :conv " |
| 114 | + "ORDER BY timestamp DESC " |
| 115 | + "LIMIT :lim" |
| 116 | + ), |
| 117 | + {"conv": conversation_id, "lim": limit}, |
| 118 | + ).fetchall() |
| 119 | + return [ |
| 120 | + { |
| 121 | + "id": r[0], |
| 122 | + "conversation_id": r[1], |
| 123 | + "sender_id": r[2], |
| 124 | + "sender_type": r[3], |
| 125 | + "content": r[4], |
| 126 | + "timestamp": r[5], |
| 127 | + "metadata": r[6], |
| 128 | + } |
| 129 | + for r in reversed(rows) |
| 130 | + ] |
| 131 | + except Exception as exc: |
| 132 | + logger.error("ChatStore: get_messages failed: %s", exc) |
| 133 | + return [] |
| 134 | + |
| 135 | + # ------------------------------------------------------------------ |
| 136 | + # Escalations |
| 137 | + # ------------------------------------------------------------------ |
| 138 | + |
| 139 | + def save_escalation(self, escalation: Any) -> None: |
| 140 | + """Persist an EscalationEvent to the DB (best-effort).""" |
| 141 | + engine = _get_engine() |
| 142 | + if engine is None: |
| 143 | + return |
| 144 | + self._init(engine) |
| 145 | + import json |
| 146 | + try: |
| 147 | + with engine.begin() as conn: |
| 148 | + conn.execute( |
| 149 | + text( |
| 150 | + f"INSERT INTO {_ESCALATIONS_TABLE} " # noqa: S608 |
| 151 | + "(id, conversation_id, reason, timestamp, metadata_json) " |
| 152 | + "VALUES (:id, :conv, :reason, :ts, :meta) " |
| 153 | + "ON CONFLICT (id) DO NOTHING" |
| 154 | + ), |
| 155 | + { |
| 156 | + "id": escalation.id, |
| 157 | + "conv": escalation.conversation_id, |
| 158 | + "reason": escalation.reason, |
| 159 | + "ts": escalation.timestamp, |
| 160 | + "meta": json.dumps(escalation.metadata or {}), |
| 161 | + }, |
| 162 | + ) |
| 163 | + except Exception as exc: |
| 164 | + logger.error("ChatStore: save_escalation failed: %s", exc) |
| 165 | + |
| 166 | + |
| 167 | +# Singleton |
| 168 | +chat_store = ChatStore() |
0 commit comments