forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

chatbot_message.rs362 lines, 14.4 KiBHistoryRawDownload
1//! The `chatbot_message` table: the turns of a thread, both sides persisted.
2//! The user's prompt lands `complete`, and the assistant's row is written
3//! `pending` *before* the AI call so a reload never loses an answer in
4//! flight. The task that owns the bridge round trip then flips it to
5//! `complete` (with the text) or `failed` (with a code), and the boot sweep
6//! in `database.rs` fails whatever a process death left behind past the
7//! staleness window. Every turn is written *through* its thread's own row —
8//! its guarded statement bumps `updated_at`, so a turn can never outlive
9//! the thread it belongs to. The row shape lives in
10//! [`crate::domain::chatbot_message`].
11
12use crate::constant::MAX_ERROR_CODE_LEN;
13use crate::database::Database;
14use crate::db::page::PagedList;
15use crate::domain::chatbot_message::{
16 ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,
17};
18use crate::domain::chatbot_thread::ChatbotThreadId;
19use crate::domain::timestamp::Timestamp;
20use crate::domain::user::UserId;
21use crate::error::AppError;
22use sqlx::query_as;
23
24/// Write one turn *through its thread's own row*: the thread's activity
25/// bump and the turn's insert are a single guarded statement, which is what
26/// makes the thread's existence something this write writes rather than
27/// something the caller read and then trusted — a
28/// [`delete`](crate::db::chatbot_thread::delete) racing it touches the very
29/// row this statement's gate updates, so under Postgres's row locking the
30/// two serialize and no turn is left under a thread that is gone. It also
31/// carries the thread's activity stamp, so a turn and its `updated_at` land
32/// together. The stamp is written strictly upwards —
33/// `GREATEST($now, updated_at + 1)` — because a turn's two rows routinely
34/// land inside one millisecond and `updated_at` is the thread list's
35/// ordering key.
36///
37/// [`AppError::NotFound`] = the thread is gone, and nothing was written.
38async fn insert(db: &Database, message: ChatbotMessage) -> Result<ChatbotMessage, AppError> {
39 let inserted = query_as!(
40 ChatbotMessage,
41 "WITH touch AS (
42 UPDATE chatbot_thread SET updated_at = GREATEST($2, updated_at + 1)
43 WHERE id = $1
44 RETURNING 1)
45 INSERT INTO chatbot_message (id, thread_id, user_id, role, content, status, \
46 truncated, error_code, created_at, completed_at)
47 SELECT $3, $1, $4, $5, $6, $7, $8, $9, $10, $11
48 WHERE EXISTS (SELECT 1 FROM touch)
49 RETURNING id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
50 user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
51 status AS \"status: MessageStatus\", truncated, \
52 error_code AS \"error_code: String\", \
53 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
54 message.get_thread_id().uuid(),
55 Timestamp::now().as_millis(),
56 message.get_id().uuid(),
57 message.user_id.uuid(),
58 message.role.as_str(),
59 message.content.as_str(),
60 message.status.as_str(),
61 message.truncated,
62 message.error_code,
63 message.created_at.as_millis(),
64 message.completed_at.map(|t| t.as_millis()),
65 )
66 .fetch_optional(db)
67 .await?;
68 // No row out of the conditional insert means the thread's touch matched
69 // nothing: the thread is gone, and nothing was written.
70 inserted.ok_or(AppError::NotFound)
71}
72
73/// Append the user's prompt. Nothing is awaited for it, so it is born
74/// complete.
75pub async fn append_user(
76 db: &Database,
77 thread: &ChatbotThreadId,
78 user: &UserId,
79 content: ChatContent,
80) -> Result<ChatbotMessage, AppError> {
81 let now = Timestamp::now();
82 insert(
83 db,
84 ChatbotMessage {
85 id: ChatbotMessageId::generate(),
86 thread_id: thread.clone(),
87 user_id: *user,
88 role: crate::domain::chatbot_message::MessageRole::User,
89 content,
90 status: MessageStatus::Complete,
91 truncated: false,
92 error_code: None,
93 created_at: now,
94 completed_at: Some(now),
95 },
96 )
97 .await
98}
99
100/// Reserve the assistant's answer *before* the AI call: the row exists,
101/// empty and `pending`, so a reload finds the turn and can wait on it.
102pub async fn append_pending_assistant(
103 db: &Database,
104 thread: &ChatbotThreadId,
105 user: &UserId,
106) -> Result<ChatbotMessage, AppError> {
107 insert(
108 db,
109 ChatbotMessage {
110 id: ChatbotMessageId::generate(),
111 thread_id: thread.clone(),
112 user_id: *user,
113 role: crate::domain::chatbot_message::MessageRole::Assistant,
114 content: ChatContent::empty(),
115 status: MessageStatus::Pending,
116 truncated: false,
117 error_code: None,
118 created_at: Timestamp::now(),
119 completed_at: None,
120 },
121 )
122 .await
123}
124
125/// The whole thread, oldest first — the order both the UI and the AI
126/// history payload read in.
127pub async fn list_for_thread(
128 db: &Database,
129 thread: &ChatbotThreadId,
130 limit: Option<i64>,
131 offset: i64,
132) -> Result<(Vec<ChatbotMessage>, i64), AppError> {
133 let (rows, total) = PagedList::new(
134 "chatbot_message WHERE thread_id = $1",
135 "ORDER BY created_at ASC, id ASC",
136 )
137 .bind(thread.uuid())
138 .run::<ChatbotMessage>(limit, offset, db)
139 .await?;
140 Ok((
141 rows.into_iter().map(ChatbotMessage::projected).collect(),
142 total,
143 ))
144}
145
146/// The last `limit` turns, still oldest-first — the tail replayed to the
147/// AI service as context. Taken newest-first in the database (so the
148/// `LIMIT` keeps the *recent* end) and flipped back here.
149pub async fn list_tail(
150 db: &Database,
151 thread: &ChatbotThreadId,
152 limit: usize,
153) -> Result<Vec<ChatbotMessage>, AppError> {
154 let mut messages: Vec<ChatbotMessage> = query_as!(
155 ChatbotMessage,
156 "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
157 user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
158 status AS \"status: MessageStatus\", truncated, \
159 error_code AS \"error_code: String\", \
160 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
161 FROM chatbot_message WHERE thread_id = $1 \
162 ORDER BY created_at DESC, id DESC LIMIT $2",
163 thread.uuid(),
164 limit as i64
165 )
166 .fetch_all(db)
167 .await?;
168 messages.reverse();
169 Ok(messages)
170}
171
172/// The last `limit` *settled* turns that carry text, still oldest-first —
173/// the tail replayed to the AI service as context. The filter runs in the
174/// query, not after it: a `LIMIT` over the raw tail hands back fewer usable
175/// rows the moment a run of answers fails, silently shrinking the context
176/// instead of reaching further back. No projection is applied — it only
177/// ever rewrites a `pending` row, and none is selected here.
178pub async fn list_settled_tail(
179 db: &Database,
180 thread: &ChatbotThreadId,
181 limit: usize,
182) -> Result<Vec<ChatbotMessage>, AppError> {
183 let mut messages: Vec<ChatbotMessage> = query_as!(
184 ChatbotMessage,
185 "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
186 user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
187 status AS \"status: MessageStatus\", truncated, \
188 error_code AS \"error_code: String\", \
189 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
190 FROM chatbot_message WHERE thread_id = $1 \
191 AND status = 'complete' AND content <> '' \
192 ORDER BY created_at DESC, id DESC LIMIT $2",
193 thread.uuid(),
194 limit as i64
195 )
196 .fetch_all(db)
197 .await?;
198 messages.reverse();
199 Ok(messages)
200}
201
202/// The user turn a reserved answer belongs to, by *identity*: the prompt
203/// row of the very POST that reserved it, whose id the answering task
204/// carries.
205///
206/// Never derived from write order. Two POSTs on one thread interleave
207/// across the two creates — the rows land `userA, userB, asstA, asstB` —
208/// so "the newest user row written before this answer" resolves *both*
209/// answers to prompt B, and prompt A is never answered.
210pub async fn prompt_of(
211 db: &Database,
212 id: &ChatbotMessageId,
213) -> Result<Option<ChatbotMessage>, AppError> {
214 let message = query_as!(
215 ChatbotMessage,
216 "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
217 user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
218 status AS \"status: MessageStatus\", truncated, \
219 error_code AS \"error_code: String\", \
220 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
221 FROM chatbot_message WHERE id = $1",
222 id.uuid()
223 )
224 .fetch_optional(db)
225 .await?;
226 Ok(message)
227}
228
229/// Read one turn only if `user` owns it — the poll loop's read.
230pub async fn read_for(
231 db: &Database,
232 id: &ChatbotMessageId,
233 user: &UserId,
234) -> Result<Option<ChatbotMessage>, AppError> {
235 let message = query_as!(
236 ChatbotMessage,
237 "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
238 user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
239 status AS \"status: MessageStatus\", truncated, \
240 error_code AS \"error_code: String\", \
241 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
242 FROM chatbot_message WHERE id = $1",
243 id.uuid()
244 )
245 .fetch_optional(db)
246 .await?;
247 Ok(message
248 .filter(|message| &message.user_id == user)
249 .map(ChatbotMessage::projected))
250}
251
252/// Land the answer, recording whether it had to be clipped to fit the
253/// school's cap. Field-scoped and gated on `status = 'pending'` in the
254/// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a
255/// timeout) already failed, and two answers can't both apply.
256pub async fn complete(
257 db: &Database,
258 id: &ChatbotMessageId,
259 text: ChatContent,
260 truncated: bool,
261) -> Result<ChatbotMessage, AppError> {
262 settle(db, id, Some(text), truncated, None).await
263}
264
265/// Mark the answer failed with a short code (`unavailable`, the service's
266/// own error code, …). Same pending gate as [`complete`].
267pub async fn fail(
268 db: &Database,
269 id: &ChatbotMessageId,
270 error_code: &str,
271) -> Result<ChatbotMessage, AppError> {
272 // A failed turn has no text, so there is nothing that could be clipped.
273 settle(db, id, None, false, Some(error_code)).await
274}
275
276async fn settle(
277 db: &Database,
278 id: &ChatbotMessageId,
279 text: Option<ChatContent>,
280 truncated: bool,
281 error_code: Option<&str>,
282) -> Result<ChatbotMessage, AppError> {
283 let status = if text.is_some() {
284 MessageStatus::Complete
285 } else {
286 MessageStatus::Failed
287 };
288 let settled = query_as!(
289 ChatbotMessage,
290 "UPDATE chatbot_message SET content = $2, status = $3, truncated = $4, \
291 error_code = $5, completed_at = $6 \
292 WHERE id = $1 AND status = 'pending' \
293 RETURNING id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
294 user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
295 status AS \"status: MessageStatus\", truncated, \
296 error_code AS \"error_code: String\", \
297 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
298 id.uuid(),
299 text.map(|t| t.as_str().to_string()).unwrap_or_default(),
300 status.as_str(),
301 truncated,
302 error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()),
303 Timestamp::now().as_millis(),
304 )
305 .fetch_optional(db)
306 .await?;
307 settled.ok_or(AppError::NotFound)
308}
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use crate::domain::chatbot_message::MessageRole;
313
314 #[tokio::test]
315 async fn a_turns_two_rows_never_sort_inverted() {
316 // Both rows of a turn land in the same millisecond routinely, so the
317 // `id` tie-break decides the thread's order. With a random ULID this
318 // inverted a fifth of the pairs; here every pair must read back
319 // question-then-answer, from both read paths.
320 let (db, _leases) = crate::database::init_test_db().await;
321 // A real thread row: every turn is written through it, so a turn with
322 // no thread is refused (see [`insert`]). The owner is a foreign key
323 // now, so both fixture rows are real, under fixed keys.
324 let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe");
325 let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef");
326 sqlx::query(
327 "INSERT INTO app_user (id, username, created_at) \
328 VALUES ($1, 'chat-fixture', 0)",
329 )
330 .bind(user.uuid())
331 .execute(&db)
332 .await
333 .unwrap();
334 sqlx::query(
335 "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \
336 VALUES ($1, $2, 0, 0)",
337 )
338 .bind(thread.uuid())
339 .bind(user.uuid())
340 .execute(&db)
341 .await
342 .unwrap();
343 const TURNS: usize = 200;
344
345 for turn in 0..TURNS {
346 let content = ChatContent::try_new(&format!("soru {turn}")).unwrap();
347 append_user(&db, &thread, &user, content).await.unwrap();
348 append_pending_assistant(&db, &thread, &user).await.unwrap();
349 }
350
351 let (whole, _) = list_for_thread(&db, &thread, None, 0).await.unwrap();
352 let tail = list_tail(&db, &thread, TURNS * 2).await.unwrap();
353 for messages in [&whole, &tail] {
354 assert_eq!(messages.len(), TURNS * 2);
355 for (turn, pair) in messages.chunks(2).enumerate() {
356 assert_eq!(pair[0].get_role(), MessageRole::User, "turn {turn}");
357 assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}"));
358 assert_eq!(pair[1].get_role(), MessageRole::Assistant, "turn {turn}");
359 }
360 }
361 }
362}