File size: 13,153 Bytes
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13de702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55320cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3950291
 
 
 
 
 
 
 
 
 
 
 
 
 
89096eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import os
import json
import uuid
import pymysql
from typing import Optional, List, Dict, Any
from urllib.parse import urlparse

# Default TiDB / MySQL URI provided
DEFAULT_DB_URI = os.getenv(
    "DATABASE_URL",
    "mysql://5fxLTeA3XBn76L2.root:bxxGgvOPDMT7mAun@gateway01.ap-southeast-1.prod.aws.tidbcloud.com:4000/test"
)

def get_connection():
    parsed = urlparse(DEFAULT_DB_URI)
    user = parsed.username
    password = parsed.password
    host = parsed.hostname
    port = parsed.port or 4000
    db = parsed.path.lstrip("/") or "test"

    return pymysql.connect(
        host=host,
        port=port,
        user=user,
        password=password,
        database=db,
        ssl_verify_cert=False,
        autocommit=True,
        charset="utf8mb4",
        cursorclass=pymysql.cursors.DictCursor
    )

def init_db():
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            # Create users table (simple name and username)
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS users (
                username VARCHAR(64) PRIMARY KEY,
                name VARCHAR(128) NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );
            """)

            # Create sessions table
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS sessions (
                id VARCHAR(64) PRIMARY KEY,
                username VARCHAR(64),
                title VARCHAR(255) NOT NULL,
                model VARCHAR(128),
                chapter_filter VARCHAR(128),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX (username)
            );
            """)

            # Ensure username column exists in sessions if table already existed
            try:
                cursor.execute("ALTER TABLE sessions ADD COLUMN username VARCHAR(64);")
            except Exception:
                pass

            # Create messages table
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS messages (
                id INT AUTO_INCREMENT PRIMARY KEY,
                session_id VARCHAR(64) NOT NULL,
                role VARCHAR(32) NOT NULL,
                content MEDIUMTEXT NOT NULL,
                thinking MEDIUMTEXT,
                findings JSON,
                citations JSON,
                `usage` JSON,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX (session_id)
            );
            """)
        conn.close()
        print("TiDB database tables initialized successfully.")
    except Exception as e:
        print(f"Warning: Failed to initialize TiDB database: {e}")

# Run schema setup
init_db()

def get_user(username: str) -> Optional[Dict[str, Any]]:
    username = username.strip().lower()
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,))
            user = cursor.fetchone()
        conn.close()
        return user
    except Exception as e:
        print(f"Error in get_user: {e}")
        return None

def create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]:
    username = username.strip().lower()
    disp_name = (name or username).strip()
    if not username:
        raise ValueError("Username cannot be empty")
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,))
            existing = cursor.fetchone()
            if existing:
                conn.close()
                raise ValueError(f"Username '@{username}' is already taken. Please choose another username.")
            cursor.execute("INSERT INTO users (username, name) VALUES (%s, %s);", (username, disp_name))
        conn.close()
        return {"username": username, "name": disp_name}
    except ValueError:
        raise
    except Exception as e:
        print(f"Database error creating user: {e}")
        raise RuntimeError(f"Database error creating user: {e}")

def get_or_create_user(username: str, name: Optional[str] = None) -> Dict[str, Any]:
    username = username.strip().lower()
    disp_name = (name or username).strip()
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT username, name, created_at FROM users WHERE username = %s;", (username,))
            user = cursor.fetchone()
            if not user:
                cursor.execute("INSERT INTO users (username, name) VALUES (%s, %s);", (username, disp_name))
                user = {"username": username, "name": disp_name}
            else:
                if name and name != user.get("name"):
                    cursor.execute("UPDATE users SET name = %s WHERE username = %s;", (disp_name, username))
                    user["name"] = disp_name
        conn.close()
        return user
    except Exception as e:
        print(f"Error in get_or_create_user: {e}")
        return {"username": username, "name": disp_name}

def create_session(session_id: Optional[str] = None, username: Optional[str] = None, title: str = "New Chat", model: Optional[str] = None, chapter_filter: Optional[str] = "All") -> str:
    sid = session_id or str(uuid.uuid4())[:12]
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("""
                INSERT INTO sessions (id, username, title, model, chapter_filter)
                VALUES (%s, %s, %s, %s, %s)
                ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP;
            """, (sid, username, title[:250], model, chapter_filter))
        conn.close()
    except Exception as e:
        print(f"Error in create_session: {e}")
    return sid

def update_session_title_if_default(session_id: str, new_title: str):
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT title FROM sessions WHERE id = %s", (session_id,))
            row = cursor.fetchone()
            if row and (row["title"] == "New Chat" or not row["title"]):
                cursor.execute("UPDATE sessions SET title = %s WHERE id = %s", (new_title[:250], session_id))
        conn.close()
    except Exception as e:
        print(f"Error in update_session_title_if_default: {e}")

def list_sessions(username: Optional[str] = None, limit: int = 50) -> List[Dict[str, Any]]:
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            if username:
                cursor.execute("""
                    SELECT id, username, title, model, chapter_filter, created_at, updated_at
                    FROM sessions
                    WHERE username = %s
                    ORDER BY updated_at DESC
                    LIMIT %s;
                """, (username.strip().lower(), limit))
            else:
                cursor.execute("""
                    SELECT id, username, title, model, chapter_filter, created_at, updated_at
                    FROM sessions
                    ORDER BY updated_at DESC
                    LIMIT %s;
                """, (limit,))
            rows = cursor.fetchall()
        conn.close()
        # Convert timestamps to iso strings
        for r in rows:
            if r.get("created_at"):
                r["created_at"] = r["created_at"].isoformat()
            if r.get("updated_at"):
                r["updated_at"] = r["updated_at"].isoformat()
        return rows
    except Exception as e:
        print(f"Error in list_sessions: {e}")
        return []

def get_session(session_id: str) -> Optional[Dict[str, Any]]:
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("SELECT id, username, title, model, chapter_filter, created_at, updated_at FROM sessions WHERE id = %s", (session_id,))
            session = cursor.fetchone()
            if not session:
                conn.close()
                return None
            
            if session.get("created_at"):
                session["created_at"] = session["created_at"].isoformat()
            if session.get("updated_at"):
                session["updated_at"] = session["updated_at"].isoformat()

            cursor.execute("""
                SELECT role, content, thinking, findings, citations, `usage`, created_at
                FROM messages
                WHERE session_id = %s
                ORDER BY id ASC;
            """, (session_id,))
            messages = cursor.fetchall()
            
            for m in messages:
                if m.get("created_at"):
                    m["created_at"] = m["created_at"].isoformat()
                for json_col in ["findings", "citations", "usage"]:
                    if isinstance(m.get(json_col), str):
                        try:
                            m[json_col] = json.loads(m[json_col])
                        except Exception:
                            pass
            session["messages"] = messages
        conn.close()
        return session
    except Exception as e:
        print(f"Error in get_session: {e}")
        return None

def save_message(
    session_id: str,
    role: str,
    content: str,
    thinking: Optional[str] = None,
    findings: Optional[Any] = None,
    citations: Optional[Any] = None,
    usage: Optional[Any] = None
):
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("""
                INSERT INTO messages (session_id, role, content, thinking, findings, citations, `usage`)
                VALUES (%s, %s, %s, %s, %s, %s, %s);
            """, (
                session_id,
                role,
                content,
                thinking,
                json.dumps(findings) if findings is not None else None,
                json.dumps(citations) if citations is not None else None,
                json.dumps(usage) if usage is not None else None,
            ))
            # Also update session updated_at
            cursor.execute("UPDATE sessions SET updated_at = CURRENT_TIMESTAMP WHERE id = %s;", (session_id,))
        conn.close()
    except Exception as e:
        print(f"Error in save_message: {e}")

def delete_session(session_id: str) -> bool:
    """Delete a session and all its messages. Returns True on success."""
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("DELETE FROM messages WHERE session_id = %s;", (session_id,))
            cursor.execute("DELETE FROM sessions WHERE id = %s;", (session_id,))
        conn.close()
        return True
    except Exception as e:
        print(f"Error in delete_session: {e}")
        return False

def compact_session_messages(session_id: str, keep_last: int = 2) -> bool:
    """
    Failsafe compaction: Condenses older messages in a session,
    keeping only the last `keep_last` user/assistant pairs plus a compact summary note.
    """
    try:
        conn = get_connection()
        with conn.cursor() as cursor:
            cursor.execute("""
                SELECT id, role, content FROM messages
                WHERE session_id = %s
                ORDER BY id ASC;
            """, (session_id,))
            rows = cursor.fetchall()

            if len(rows) <= keep_last * 2:
                conn.close()
                return True

            # Keep the last keep_last * 2 rows
            keep_rows = rows[-(keep_last * 2):]
            keep_ids = [r["id"] for r in keep_rows]

            # Collect topic highlights from pruned user messages
            pruned_user_topics = [
                r["content"][:60].strip() for r in rows[:-(keep_last * 2)]
                if r["role"] == "user"
            ]
            topics_summary = " • ".join(pruned_user_topics) if pruned_user_topics else "Earlier inquiries"

            # Delete older rows
            cursor.execute("""
                DELETE FROM messages
                WHERE session_id = %s AND id NOT IN ({seq});
            """.format(seq=",".join(["%s"] * len(keep_ids))), (session_id, *keep_ids))

            # Insert an archived summary marker
            cursor.execute("""
                INSERT INTO messages (session_id, role, content, thinking)
                VALUES (%s, %s, %s, %s);
            """, (
                session_id,
                "assistant",
                f"🗜️ *[Conversation Compacted: Context preserved for {len(pruned_user_topics)} prior topics ({topics_summary}) to optimize token window and responsiveness]*",
                "Conversation history was compacted to prevent token overflow and context bleeding."
            ))
            cursor.execute("UPDATE sessions SET updated_at = CURRENT_TIMESTAMP WHERE id = %s;", (session_id,))

        conn.close()
        return True
    except Exception as e:
        print(f"Error in compact_session_messages: {e}")
        return False