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.rs952 lines, 39.3 KiBHistoryRawDownload
1//! The chatbot relay: browser ⇄ backend ⇄ AI service (over the QUIC bridge).
2//!
3//! The backend owns everything except the answer itself — auth, the per-user
4//! rate limit, the thread, the payload format, and the last look at the reply
5//! before it is stored. There are no intent or rule tables: the thread is
6//! free-form on purpose.
7//!
8//! Sending is asynchronous by design. `POST .../messages` writes the user's
9//! turn plus an empty `pending` assistant row and answers `202` immediately;
10//! an inference can outlast the request-timeout layer that guards every HTTP
11//! handler, so nothing is awaited on the request path. The client then either
12//! polls `GET .../messages/{mid}` or opens its SSE stream — both read the same
13//! row, so they can never disagree.
14//!
15//! The bridge round trip runs in a `tokio::spawn` the POST leaves behind. A
16//! restart therefore orphans a turn in flight: its row stays `pending` until a
17//! reader projects it failed, and the boot sweep stamps that verdict durably.
18//! Acceptable because the backend is one process with stop-the-world deploys —
19//! there is no peer that could have picked the turn up anyway.
20
21use std::time::Duration;
22
23use crate::tenant::ResolvedTenant;
24use crate::web::tenant_state::{SchoolIdCookie, State, TenantExt};
25use axum::Json;
26use axum::extract::{Path, Query};
27use axum::http::StatusCode;
28use axum::response::sse::{Event, KeepAlive, Sse};
29use axum::response::{IntoResponse, Response};
30use serde::{Deserialize, Serialize};
31use serde_json::json;
32use tokio::sync::mpsc;
33use tokio_stream::Stream;
34use tokio_stream::wrappers::ReceiverStream;
35use utoipa::ToSchema;
36use utoipa_axum::router::OpenApiRouter;
37use utoipa_axum::routes;
38
39use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn};
40use crate::ai::{AiBridge, AiError};
41use crate::constant::{
42 AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, REPLY_CHUNKS,
43};
44use crate::database::Database;
45use crate::domain::chatbot_message::{
46 ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,
47};
48use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
49use crate::domain::role::Role;
50use crate::domain::settings::Settings;
51use crate::domain::user::UserId;
52use crate::error::{AppError, ErrorResponse, ValidationError};
53use crate::service;
54use crate::state::{AppState, scoped_key};
55
56use super::{CurrentUser, Page, PageParams, ai_unavailable, slice_reply, sse_error, sse_send};
57
58pub fn routes() -> OpenApiRouter<AppState> {
59 OpenApiRouter::new()
60 .routes(routes!(create_thread, list_threads))
61 .routes(routes!(rename_thread, delete_thread))
62 .routes(routes!(list_messages, send_message))
63 .routes(routes!(read_message))
64 .routes(routes!(stream_message))
65}
66
67// ---- threads ----------------------------------------------------------
68
69#[derive(Deserialize, ToSchema)]
70struct CreateChatbotThread {
71 /// Optional thread name, up to 200 characters. Blank counts as absent —
72 /// an untitled thread is normal (the UI labels it from its first turn).
73 #[schema(max_length = 200, example = "Fizik ödevi")]
74 title: Option<String>,
75}
76
77/// One chatbot thread. `updated_at` moves on every turn, and the list is
78/// sorted by it, so the thread just written to is always first.
79#[derive(Serialize, ToSchema)]
80struct ChatbotThreadResponse {
81 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
82 id: String,
83 #[schema(example = "Fizik ödevi")]
84 title: Option<String>,
85 /// UTC unix-milliseconds, server-stamped.
86 created_at: i64,
87 /// UTC unix-milliseconds of the last turn, server-stamped.
88 updated_at: i64,
89}
90
91impl ChatbotThreadResponse {
92 fn new(thread: &ChatbotThread) -> Self {
93 Self {
94 id: thread.get_id().key().to_string(),
95 title: thread.get_title().map(|title| title.as_str().to_string()),
96 created_at: thread.get_created_at().as_millis(),
97 updated_at: thread.get_updated_at().as_millis(),
98 }
99 }
100}
101
102/// Start a new chatbot thread, optionally named. Every authenticated role may
103/// chat, parents included. A user may keep up to the school's
104/// `max_chatbot_threads` threads; at the cap the request is refused (409)
105/// until an old thread is deleted — the cap is storage protection, not a
106/// usage quota (that is the per-minute message limit).
107#[utoipa::path(
108 post,
109 path = "/threads",
110 tag = "chatbot",
111 security(("session_cookie" = [])),
112 request_body = CreateChatbotThread,
113 responses(
114 (status = 201, description = "The new thread", body = ChatbotThreadResponse),
115 (status = 400, description = "Invalid title", body = ErrorResponse),
116 (status = 401, description = "Not authenticated", body = ErrorResponse),
117 (status = 409, description = "At the school's thread cap", body = ErrorResponse),
118 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
119 ),
120)]
121async fn create_thread(
122 State(st): State<AppState>,
123 CurrentUser(user): CurrentUser,
124 Json(req): Json<CreateChatbotThread>,
125) -> Result<(StatusCode, Json<ChatbotThreadResponse>), AppError> {
126 // Blank is "untitled", not an error — same rule as a message's label.
127 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
128 "" => None,
129 value => Some(ChatbotThreadTitle::try_new(value)?),
130 };
131
132 // The cap is checked and the row written as one critical section in the
133 // domain: counting here and creating after would over-admit under
134 // concurrency (the database does not serialize a count against inserts).
135 let thread = service::chatbot_thread::create_capped(&st.db, user.get_id(), title).await?;
136 Ok((
137 StatusCode::CREATED,
138 Json(ChatbotThreadResponse::new(&thread)),
139 ))
140}
141
142/// The caller's own threads, most recently active first. Paged via
143/// `?limit=&offset=`. Nobody — no teacher, no admin — reads anyone else's.
144#[utoipa::path(
145 get,
146 path = "/threads",
147 tag = "chatbot",
148 security(("session_cookie" = [])),
149 params(PageParams),
150 responses(
151 (status = 200, description = "A page of the caller's threads", body = Page<ChatbotThreadResponse>),
152 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
153 (status = 401, description = "Not authenticated", body = ErrorResponse),
154 ),
155)]
156async fn list_threads(
157 State(st): State<AppState>,
158 CurrentUser(user): CurrentUser,
159 Query(page): Query<PageParams>,
160) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {
161 let (limit, offset) = page.resolve()?;
162 let (threads, total) =
163 service::chatbot_thread::list_for_user(&st.db, user.get_id(), limit, offset).await?;
164 let items = threads.iter().map(ChatbotThreadResponse::new).collect();
165 Ok(Json(Page::new(items, total, limit, offset)))
166}
167
168#[derive(Deserialize, ToSchema)]
169struct RenameChatbotThread {
170 /// The new name, up to 200 characters. `null` — or blank — clears it back
171 /// to untitled, the same rule the create route applies.
172 #[schema(max_length = 200, example = "Fizik ödevi")]
173 title: Option<String>,
174}
175
176/// Rename a thread, or clear its name (`title: null`). Owner only; someone
177/// else's thread is a `404`, never a `403`. The edit counts as activity, so the
178/// thread moves to the top of the list — renaming is how a user files a thread,
179/// and a rename that left it buried would be useless.
180///
181/// Nothing names a thread automatically: the first message is not turned into a
182/// title, and the AI service is never asked for one.
183#[utoipa::path(
184 patch,
185 path = "/threads/{id}",
186 tag = "chatbot",
187 security(("session_cookie" = [])),
188 params(("id" = String, Path, description = "ChatbotThread id")),
189 request_body = RenameChatbotThread,
190 responses(
191 (status = 200, description = "The renamed thread", body = ChatbotThreadResponse),
192 (status = 400, description = "Invalid title", body = ErrorResponse),
193 (status = 401, description = "Not authenticated", body = ErrorResponse),
194 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
195 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
196 ),
197)]
198async fn rename_thread(
199 State(st): State<AppState>,
200 CurrentUser(user): CurrentUser,
201 Path(id): Path<String>,
202 Json(req): Json<RenameChatbotThread>,
203) -> Result<Json<ChatbotThreadResponse>, AppError> {
204 let title = match req.title.as_deref().map(str::trim).unwrap_or_default() {
205 "" => None,
206 value => Some(ChatbotThreadTitle::try_new(value)?),
207 };
208 let thread = own_thread(&id, user.get_id(), &st.db).await?;
209 let renamed = service::chatbot_thread::rename(&st.db, &thread, title).await?;
210 Ok(Json(ChatbotThreadResponse::new(&renamed)))
211}
212
213/// Delete a thread and every turn in it, permanently. Owner only; someone
214/// else's thread is a `404`, never a `403` (its existence is not leaked).
215#[utoipa::path(
216 delete,
217 path = "/threads/{id}",
218 tag = "chatbot",
219 security(("session_cookie" = [])),
220 params(("id" = String, Path, description = "ChatbotThread id")),
221 responses(
222 (status = 204, description = "Deleted, with its messages"),
223 (status = 401, description = "Not authenticated", body = ErrorResponse),
224 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
225 ),
226)]
227async fn delete_thread(
228 State(st): State<AppState>,
229 CurrentUser(user): CurrentUser,
230 Path(id): Path<String>,
231) -> Result<StatusCode, AppError> {
232 let thread = own_thread(&id, user.get_id(), &st.db).await?;
233 service::chatbot_thread::delete(&st.db, thread).await?;
234 Ok(StatusCode::NO_CONTENT)
235}
236
237/// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
238/// from a missing one.
239async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<ChatbotThread, AppError> {
240 service::chatbot_thread::read_for(db, &ChatbotThreadId::from_key(id), user)
241 .await?
242 .ok_or(AppError::NotFound)
243}
244
245// ---- turns ------------------------------------------------------------------
246
247#[derive(Deserialize, ToSchema)]
248struct SendChatbotMessage {
249 /// What to ask. Required. `maxLength` here is the server's hard ceiling;
250 /// the live cap is the school's `max_chatbot_message_len` (`GET /settings`),
251 /// which is always at or below it.
252 #[schema(
253 example = "Newton'un ikinci yasasını açıklar mısın?",
254 max_length = 8_000
255 )]
256 content: String,
257}
258
259/// The receipt for an accepted turn. The answer is *not* here: it is being
260/// fetched. Poll `GET /chatbot/threads/{id}/messages/{mid}` or open its
261/// `/stream`.
262#[derive(Serialize, ToSchema)]
263struct AcceptedResponse {
264 /// The assistant row reserved for the answer.
265 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
266 message_id: String,
267 /// Always `pending` — that is what "accepted" means here.
268 #[schema(example = "pending")]
269 status: String,
270}
271
272/// One turn. `content` is empty while `status` is `pending`; `error_code` is
273/// set only when `status` is `failed`.
274#[derive(Serialize, ToSchema)]
275struct ChatbotMessageResponse {
276 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
277 id: String,
278 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
279 thread_id: String,
280 /// `user` or `assistant`.
281 #[schema(example = "assistant")]
282 role: String,
283 /// `pending`, `complete`, or `failed`. A user turn is always `complete`.
284 #[schema(example = "complete")]
285 status: String,
286 content: String,
287 /// `true` when `content` is only the first part of what the assistant
288 /// answered — the rest was over the school's `max_chatbot_message_len` and was
289 /// cut. Always `false` for a user turn and for a failed one. Show the user
290 /// that the answer is incomplete; asking again shortens nothing, so the way
291 /// out is a narrower question (or a bigger cap).
292 #[schema(example = false)]
293 truncated: bool,
294 /// Short machine-readable reason when `status` is `failed`:
295 /// `unavailable`, `busy`, `timed_out`, `transport`, `protocol`,
296 /// `bad_reply`, `empty_reply`, `interrupted`, or a code the AI service
297 /// itself returned.
298 #[schema(example = "timed_out")]
299 error_code: Option<String>,
300 /// UTC unix-milliseconds, server-stamped.
301 created_at: i64,
302 /// When the turn settled (complete or failed); `null` while pending.
303 completed_at: Option<i64>,
304}
305
306impl ChatbotMessageResponse {
307 fn new(message: &ChatbotMessage) -> Self {
308 Self {
309 id: message.get_id().key().to_string(),
310 thread_id: message.get_thread_id().key().to_string(),
311 role: message.get_role().as_str().to_string(),
312 status: message.get_status().as_str().to_string(),
313 content: message.get_content().as_str().to_string(),
314 truncated: message.is_truncated(),
315 error_code: message.get_error_code().map(str::to_string),
316 created_at: message.get_created_at().as_millis(),
317 completed_at: message.get_completed_at().map(|at| at.as_millis()),
318 }
319 }
320}
321
322/// The whole thread, oldest first. Paged via `?limit=&offset=`. Owner only.
323#[utoipa::path(
324 get,
325 path = "/threads/{id}/messages",
326 tag = "chatbot",
327 security(("session_cookie" = [])),
328 params(("id" = String, Path, description = "ChatbotThread id"), PageParams),
329 responses(
330 (status = 200, description = "A page of the thread's turns", body = Page<ChatbotMessageResponse>),
331 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
332 (status = 401, description = "Not authenticated", body = ErrorResponse),
333 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
334 ),
335)]
336async fn list_messages(
337 State(st): State<AppState>,
338 CurrentUser(user): CurrentUser,
339 Path(id): Path<String>,
340 Query(page): Query<PageParams>,
341) -> Result<Json<Page<ChatbotMessageResponse>>, AppError> {
342 let (limit, offset) = page.resolve()?;
343 let thread = own_thread(&id, user.get_id(), &st.db).await?;
344 let (messages, total) =
345 service::chatbot_message::list_for_thread(&st.db, thread.get_id(), limit, offset).await?;
346 let items = messages.iter().map(ChatbotMessageResponse::new).collect();
347 Ok(Json(Page::new(items, total, limit, offset)))
348}
349
350/// Ask the chatbot: `{content}`, at most the school's
351/// `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the
352/// moment both rows are written — the answer itself lands later, in the
353/// reserved assistant row. `503` when no AI service offers `chat.reply`, and
354/// nothing is written; `429` + `Retry-After` over the per-user send limit.
355///
356/// Order matters and is deliberate: the per-user rate limit is charged
357/// *before* anything is written, so a refused turn leaves no trace;
358/// availability is checked *before* the rows exist, so an unavailable service
359/// produces a `503` and no dead pending row. Once the rows are written the turn
360/// always settles — the answering task stamps `complete`/`failed`, a reader
361/// projects a long-stale `pending` as failed, and the boot sweep repairs
362/// whatever a process death left behind.
363#[utoipa::path(
364 post,
365 path = "/threads/{id}/messages",
366 tag = "chatbot",
367 security(("session_cookie" = [])),
368 params(("id" = String, Path, description = "ChatbotThread id")),
369 request_body = SendChatbotMessage,
370 responses(
371 (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse),
372 (status = 400, description = "Empty message, or longer than the school's `max_chatbot_message_len`", body = ErrorResponse),
373 (status = 401, description = "Not authenticated", body = ErrorResponse),
374 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
375 (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse),
376 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
377 (status = 503, description = "No AI service is available — nothing was written, retry later", body = ErrorResponse),
378 ),
379)]
380async fn send_message(
381 State(st): State<AppState>,
382 SchoolIdCookie(school): SchoolIdCookie,
383 tenant: ResolvedTenant,
384 CurrentUser(user): CurrentUser,
385 Path(id): Path<String>,
386 Json(req): Json<SendChatbotMessage>,
387) -> Result<Response, AppError> {
388 // Charged first: a rejected turn must cost nothing and leave no row.
389 st.chatbot_limit
390 .enforce_user(&scoped_key(&school, user.get_id().key().as_str()))?;
391
392 let thread = own_thread(&id, user.get_id(), &st.db).await?;
393 let settings = service::settings::load(&st.db).await?;
394 let reply_cap = content_cap(&settings);
395 let length = req.content.chars().count();
396 if length > reply_cap {
397 return Err(AppError::Validation(ValidationError::TooLong {
398 field: "content",
399 max: reply_cap,
400 got: length,
401 }));
402 }
403 let content = ChatContent::try_new(&req.content)?;
404
405 // The 503 gate, and the only place it is evaluated. `has_capability` is
406 // documented racy — that is fine here: it never guards a write, it only
407 // spares the user a thread full of rows nothing could ever answer.
408 let Some(bridge) = st.ai.clone() else {
409 return Ok(ai_unavailable(
410 "the AI service is not enabled on this deployment",
411 ));
412 };
413 if !bridge.has_capability(AI_CHAT_CAPABILITY) {
414 return Ok(ai_unavailable("no AI service is connected right now"));
415 }
416
417 // Each create rides the thread's own row — it moves `updated_at` (the
418 // list's sort key, so this is also the activity stamp) inside its own
419 // transaction. That is what serializes a turn against `DELETE
420 // /chatbot/threads/{id}`: the read above cannot, since reads do not
421 // conflict, and a row written into the delete's window survived it as a
422 // turn under a thread that is gone. A thread deleted between the two
423 // creates therefore refuses the second one with a 404 — and the first is
424 // swept by that same delete, so the turn leaves no half of itself behind.
425 let prompt =
426 service::chatbot_message::append_user(&st.db, thread.get_id(), user.get_id(), content)
427 .await?;
428 let answer =
429 service::chatbot_message::append_pending_assistant(&st.db, thread.get_id(), user.get_id())
430 .await?;
431
432 let message_id = answer.get_id().key().to_string();
433 // Never awaited inline: the bridge round trip can outlast the request
434 // timeout that guards every handler, and the POST must return now. The
435 // settings snapshot goes with it, so the whole turn is judged by the policy
436 // that was live when it was accepted.
437 // The prompt travels by id, not by write order: two POSTs on one thread
438 // interleave across the two creates above, and picking "the newest user row
439 // before this answer" out of the thread then answers the *other* request's
440 // question twice.
441 // The asker's role goes with the turn so the service can scope its answer.
442 // Read here, from the session's own user row (roles are re-read on every
443 // request), so it is the live role at the moment the question was asked —
444 // never a stored copy, and never anything the body could assert.
445 tokio::spawn(answer_turn(
446 // The school and its database travel together — they are the pair the
447 // request was already resolved into, and one without the other is how
448 // an answer lands in the wrong school.
449 TenantExt {
450 id: school,
451 db: st.db.clone(),
452 modules: tenant.modules,
453 },
454 bridge,
455 prompt.get_id().clone(),
456 answer,
457 user.get_role(),
458 settings.get_chatbot_history_turns().max(0) as usize,
459 reply_cap,
460 ));
461
462 Ok((
463 StatusCode::ACCEPTED,
464 Json(AcceptedResponse {
465 message_id,
466 status: MessageStatus::Pending.as_str().to_string(),
467 }),
468 )
469 .into_response())
470}
471
472/// The school's per-message character cap, never above the domain's hard
473/// ceiling. Applied to what the user sends *and* to what the service answers.
474fn content_cap(settings: &Settings) -> usize {
475 (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN)
476}
477
478/// Fetch one turn's answer and settle its row. Runs detached from the request.
479///
480/// Every path settles: a row left `pending` would show as a spinner forever.
481async fn answer_turn(
482 tenant: TenantExt,
483 bridge: AiBridge,
484 prompt_id: ChatbotMessageId,
485 answer: ChatbotMessage,
486 asker_role: Role,
487 history_turns: usize,
488 reply_cap: usize,
489) {
490 let db = tenant.db.clone();
491 let answer_id = answer.get_id().clone();
492 let thread = answer.get_thread_id().clone();
493 // This request's own question, read back by id — the text is already
494 // stored, so carrying the id rather than the string keeps the prompt and
495 // its answer paired however two POSTs on one thread interleave.
496 let prompt = match service::chatbot_message::prompt_of(&db, &prompt_id).await {
497 Ok(Some(prompt)) => prompt,
498 Ok(None) => {
499 // The prompt row is gone — only reachable if the thread was deleted
500 // out from under this task. There is nothing to ask, so settle.
501 tracing::warn!("chat answer {} has no prompt to send", answer_id.key());
502 let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await;
503 return;
504 }
505 Err(err) => {
506 // Nothing to ask, and nothing will ask again: the claim queue that
507 // used to reclaim an unsettled row is gone, so leaving it `pending`
508 // means a spinner until the 300s stale horizon. Settle it here.
509 tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());
510 let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await;
511 return;
512 }
513 };
514 let fresh = [prompt.get_id().clone(), answer_id.clone()];
515 let settled = match fetch_reply(
516 &bridge,
517 &tenant,
518 &thread,
519 &fresh,
520 prompt.get_content().as_str().to_string(),
521 asker_role,
522 (history_turns, reply_cap),
523 )
524 .await
525 {
526 Ok((text, truncated)) => {
527 service::chatbot_message::complete(&db, &answer_id, text, truncated).await
528 }
529 Err(code) => {
530 tracing::warn!("chat answer {} failed: {code}", answer_id.key());
531 service::chatbot_message::fail(&db, &answer_id, &code).await
532 }
533 };
534 match settled {
535 Ok(_) => {}
536 // The row was no longer `pending`: the boot sweep or a stale-timeout
537 // already spoke for it, or the thread was deleted mid-flight.
538 // Benign — the user is not waiting on this row any more.
539 Err(AppError::NotFound) => {
540 tracing::info!("chat answer {} was already settled", answer_id.key());
541 }
542 Err(err) => tracing::error!("could not settle chat answer {}: {err}", answer_id.key()),
543 }
544}
545
546/// The bridge round trip, with every failure mapped to a stable code.
547async fn fetch_reply(
548 bridge: &AiBridge,
549 tenant: &TenantExt,
550 thread: &ChatbotThreadId,
551 fresh: &[ChatbotMessageId; 2],
552 prompt: String,
553 asker_role: Role,
554 caps: (usize, usize),
555) -> Result<(ChatContent, bool), String> {
556 let (history_turns, reply_cap) = caps;
557 let db = &tenant.db;
558 let history = match history_for(db, thread, fresh, history_turns).await {
559 Ok(history) => history,
560 Err(err) => {
561 tracing::warn!("could not load chat history: {err}");
562 return Err("internal".to_string());
563 }
564 };
565 let payload = serde_json::to_value(ChatRequestPayload {
566 message: prompt,
567 asker_role: asker_role.as_str().to_string(),
568 history,
569 })
570 .map_err(|err| {
571 tracing::error!("could not encode a chat request: {err}");
572 "internal".to_string()
573 })?;
574
575 let raw = bridge
576 .dispatch(&tenant.id, AI_CHAT_CAPABILITY, payload)
577 .await
578 .map_err(failure_code)?;
579 let reply: ChatReplyPayload = serde_json::from_value(raw).map_err(|err| {
580 tracing::warn!("AI service answered with an unreadable chat payload: {err}");
581 "bad_reply".to_string()
582 })?;
583
584 // The service is a trust boundary: cap what it wrote before it reaches a
585 // row (or a browser). Truncation over rejection — a clipped answer still
586 // helps, a discarded one does not — but the clip is recorded, so the UI can
587 // tell the user the text was cut instead of passing it off as the whole
588 // answer.
589 let text: String = reply.text.chars().take(reply_cap).collect();
590 if text.trim().is_empty() {
591 // Nothing to show, and `ChatContent` would refuse it anyway. A blank
592 // bubble is indistinguishable from a bug, so it is reported as one.
593 return Err("empty_reply".to_string());
594 }
595 let truncated = text.chars().count() < reply.text.chars().count();
596 if truncated {
597 tracing::warn!("clipped an AI chat reply to the school's {reply_cap}-character limit");
598 }
599 let content = ChatContent::try_new(&text).map_err(|err| {
600 tracing::error!("a clipped AI reply was still not storable: {err}");
601 "bad_reply".to_string()
602 })?;
603 Ok((content, truncated))
604}
605
606/// The tail of the thread replayed to the service: oldest first, only
607/// settled turns with text, and never the two rows this turn just wrote (the
608/// new prompt rides in `message`, the answer does not exist yet).
609async fn history_for(
610 db: &Database,
611 thread: &ChatbotThreadId,
612 fresh: &[ChatbotMessageId; 2],
613 turns: usize,
614) -> Result<Vec<ChatTurn>, AppError> {
615 // The query counts only settled rows with text, so a run of failed answers
616 // makes the window reach *further back* instead of shrinking it — that is
617 // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping
618 // this turn's own two rows cannot shorten it either (only the user one can
619 // match: the assistant row is still `pending`).
620 let tail =
621 service::chatbot_message::list_settled_tail(db, thread, turns.saturating_add(2)).await?;
622 let mut history: Vec<ChatTurn> = tail
623 .iter()
624 .filter(|message| !fresh.contains(message.get_id()))
625 .map(|message| ChatTurn {
626 role: match message.get_role() {
627 MessageRole::User => ChatRole::User,
628 MessageRole::Assistant => ChatRole::Assistant,
629 },
630 content: message.get_content().as_str().to_string(),
631 })
632 .collect();
633 if history.len() > turns {
634 history.drain(..history.len() - turns);
635 }
636 Ok(history)
637}
638
639/// A dispatch failure as a short, stable code the frontend can branch on.
640fn failure_code(err: AiError) -> String {
641 match err {
642 AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(),
643 AiError::Busy(_) => "busy".to_string(),
644 AiError::Timeout(_) => "timed_out".to_string(),
645 AiError::Transport(_) => "transport".to_string(),
646 AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(),
647 // The service's own verdict. Kept verbatim (the domain trims it) so a
648 // service can define codes the backend has never heard of.
649 AiError::Remote { code, message } => {
650 tracing::warn!("AI chat service refused the request: {code}: {message}");
651 if code.trim().is_empty() {
652 "service_error".to_string()
653 } else {
654 code
655 }
656 }
657 }
658}
659
660/// Poll one turn. The non-SSE fallback for `/stream`, reading the same row —
661/// including the projection that presents a long-stale `pending` as `failed`,
662/// so the two can never disagree about a turn's state.
663#[utoipa::path(
664 get,
665 path = "/threads/{id}/messages/{mid}",
666 tag = "chatbot",
667 security(("session_cookie" = [])),
668 params(
669 ("id" = String, Path, description = "ChatbotThread id"),
670 ("mid" = String, Path, description = "Message id"),
671 ),
672 responses(
673 (status = 200, description = "The turn, in whatever state it is", body = ChatbotMessageResponse),
674 (status = 401, description = "Not authenticated", body = ErrorResponse),
675 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
676 ),
677)]
678async fn read_message(
679 State(st): State<AppState>,
680 CurrentUser(user): CurrentUser,
681 Path((id, mid)): Path<(String, String)>,
682) -> Result<Json<ChatbotMessageResponse>, AppError> {
683 let message = own_message(&id, &mid, user.get_id(), &st.db).await?;
684 Ok(Json(ChatbotMessageResponse::new(&message)))
685}
686
687/// Read one turn only if the caller owns it *and* it belongs to the named
688/// thread — a mismatched pair is a `404`, like a foreign one.
689///
690/// The thread is re-read rather than inferred from the message's `thread_id`,
691/// and that is defence in depth for rows written by an older binary: a turn
692/// accepted into the window of its thread's delete used to survive it, and
693/// nothing sweeps such a row, so on a live volume the text of a deleted thread
694/// stayed readable through these two routes. Turns can no longer be orphaned
695/// (see [`ChatbotMessage`]'s insert), but the ones already there must read as
696/// gone. Cheap where it sits: the SSE poll loop re-reads only the message row,
697/// so this is one extra record read per polling client, not per tick of every
698/// stream.
699async fn own_message(
700 thread: &str,
701 message: &str,
702 user: &UserId,
703 db: &Database,
704) -> Result<ChatbotMessage, AppError> {
705 own_thread(thread, user, db).await?;
706 service::chatbot_message::read_for(db, &ChatbotMessageId::from_key(message), user)
707 .await?
708 .filter(|message| message.get_thread_id().key() == thread)
709 .ok_or(AppError::NotFound)
710}
711
712/// Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a
713/// single `done` carrying the finished message, or one `error`. The stream
714/// closes after `done`/`error` — one stream per turn, not per thread.
715///
716/// Works whatever state the turn is in when the stream opens: an answer that
717/// already landed replays as `delta`s and a `done` straight away, so a client
718/// that reconnects late is never left hanging. Consume with `EventSource`
719/// (cookies ride along on same-site / credentialed requests).
720#[utoipa::path(
721 get,
722 path = "/threads/{id}/messages/{mid}/stream",
723 tag = "chatbot",
724 security(("session_cookie" = [])),
725 params(
726 ("id" = String, Path, description = "ChatbotThread id"),
727 ("mid" = String, Path, description = "Message id"),
728 ),
729 responses(
730 (status = 200, description = "SSE: `delta` (`{text}`) chunks, then `done` (`{message}`) or `error` (`{code, message}`)", content_type = "text/event-stream"),
731 (status = 401, description = "Not authenticated", body = ErrorResponse),
732 (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse),
733 ),
734)]
735async fn stream_message(
736 State(st): State<AppState>,
737 CurrentUser(user): CurrentUser,
738 Path((id, mid)): Path<(String, String)>,
739) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> {
740 // Ownership is settled before the response becomes a stream — after this
741 // point the only way to say "no" is an `error` event.
742 own_message(&id, &mid, user.get_id(), &st.db).await?;
743
744 let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2);
745 let (message_id, user_id, db) = (
746 ChatbotMessageId::from_key(&mid),
747 *user.get_id(),
748 st.db.clone(),
749 );
750 tokio::spawn(async move {
751 let mut ticker = tokio::time::interval(Duration::from_millis(CHAT_STREAM_POLL_MS));
752 loop {
753 // The first tick fires immediately: an already-finished turn is
754 // delivered on connect rather than one poll interval later.
755 //
756 // The wait also watches the receiver, because a `pending` turn
757 // sends nothing and would otherwise never learn that the client
758 // hung up: axum drops the response body — and with it this
759 // channel's receiver — the moment the connection dies, so this is
760 // where an abandoned stream stops polling the database, instead of
761 // running on for the whole 300-second staleness window.
762 tokio::select! {
763 _ = ticker.tick() => {}
764 _ = tx.closed() => return,
765 }
766 let message = match service::chatbot_message::read_for(&db, &message_id, &user_id).await
767 {
768 Ok(Some(message)) => message,
769 // Deleted mid-stream (the thread went away) — say so and stop.
770 Ok(None) => {
771 sse_error(&tx, "not_found", "this message no longer exists").await;
772 return;
773 }
774 Err(err) => {
775 tracing::warn!("chat stream read failed: {err}");
776 sse_error(&tx, "internal", "could not read the message").await;
777 return;
778 }
779 };
780
781 match message.get_status() {
782 // Includes the read-time projection: a `pending` row past its
783 // staleness window arrives here as `failed`, so this loop
784 // always terminates.
785 MessageStatus::Pending => continue,
786 MessageStatus::Complete => {
787 for chunk in slice_reply(message.get_content().as_str()) {
788 if sse_send(&tx, "delta", json!({ "text": chunk })).await.is_err() {
789 return;
790 }
791 }
792 let done = json!({ "message": ChatbotMessageResponse::new(&message) });
793 let _ = sse_send(&tx, "done", done).await;
794 return;
795 }
796 MessageStatus::Failed => {
797 let code = message.get_error_code().unwrap_or("failed");
798 sse_error(&tx, code, "the assistant could not answer this message").await;
799 return;
800 }
801 }
802 }
803 });
804
805 Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default()))
806}
807
808#[cfg(test)]
809mod tests {
810 use super::*;
811
812 #[tokio::test]
813 async fn slicing_preserves_the_answer_exactly() {
814 for text in [
815 "",
816 "x",
817 "kısa cevap",
818 &"é".repeat(1_000),
819 &"a".repeat(7_999),
820 ] {
821 let chunks = slice_reply(text);
822 assert_eq!(
823 chunks.concat(),
824 text,
825 "chunks must rejoin into the original answer"
826 );
827 assert!(
828 chunks.iter().all(|chunk| !chunk.is_empty()),
829 "an empty delta says nothing"
830 );
831 assert!(
832 chunks.len() <= REPLY_CHUNKS,
833 "{} chunks for {} chars",
834 chunks.len(),
835 text.chars().count()
836 );
837 }
838 // Empty in, nothing out — a failed turn emits no deltas at all.
839 assert!(slice_reply("").is_empty());
840 // Short answers are not padded into REPLY_CHUNKS pieces.
841 assert_eq!(slice_reply("hi"), vec!["hi".to_string()]);
842 }
843
844 #[tokio::test]
845 async fn history_reaches_past_failed_answers_to_fill_the_window() {
846 // A run of failed answers must make the window reach further back, not
847 // shrink it: filtering a fixed-size tail after the fact handed the
848 // service a handful of unanswered prompts and nothing older.
849 let (db, _leases) = crate::database::init_test_db().await;
850 // A real thread row: every turn is written through it, so a turn with
851 // no thread is refused. The owner is a foreign key now, so both
852 // fixture rows are real, under fixed keys.
853 let user = UserId::from_key("019732e3-7b00-7000-8000-00000000cafe");
854 let thread = ChatbotThreadId::from_key("019732e3-7b00-7000-8000-00000000beef");
855 sqlx::query(
856 "INSERT INTO app_user (id, username, created_at) \
857 VALUES ($1, 'chat-web-fixture', 0)",
858 )
859 .bind(user.uuid())
860 .execute(&db)
861 .await
862 .unwrap();
863 sqlx::query(
864 "INSERT INTO chatbot_thread (id, user_id, created_at, updated_at) \
865 VALUES ($1, $2, 0, 0)",
866 )
867 .bind(thread.uuid())
868 .bind(user.uuid())
869 .execute(&db)
870 .await
871 .unwrap();
872 let say = |text: String| ChatContent::try_new(&text).unwrap();
873
874 for turn in 0..10 {
875 service::chatbot_message::append_user(&db, &thread, &user, say(format!("soru {turn}")))
876 .await
877 .unwrap();
878 let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user)
879 .await
880 .unwrap();
881 service::chatbot_message::complete(
882 &db,
883 answer.get_id(),
884 say(format!("cevap {turn}")),
885 false,
886 )
887 .await
888 .unwrap();
889 }
890 // Five turns in a row whose answer never landed.
891 for turn in 0..5 {
892 service::chatbot_message::append_user(
893 &db,
894 &thread,
895 &user,
896 say(format!("kayıp {turn}")),
897 )
898 .await
899 .unwrap();
900 let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user)
901 .await
902 .unwrap();
903 service::chatbot_message::fail(&db, answer.get_id(), "timed_out")
904 .await
905 .unwrap();
906 }
907 // And this turn's own two rows, which never belong in the history.
908 let prompt = service::chatbot_message::append_user(&db, &thread, &user, say("yeni".into()))
909 .await
910 .unwrap();
911 let pending = service::chatbot_message::append_pending_assistant(&db, &thread, &user)
912 .await
913 .unwrap();
914 let fresh = [prompt.get_id().clone(), pending.get_id().clone()];
915
916 let history = history_for(&db, &thread, &fresh, 6).await.unwrap();
917 let texts: Vec<&str> = history.iter().map(|turn| turn.content.as_str()).collect();
918 assert_eq!(
919 texts,
920 [
921 "cevap 9", "kayıp 0", "kayıp 1", "kayıp 2", "kayıp 3", "kayıp 4"
922 ],
923 "six settled turns, oldest first, reaching back over the failures"
924 );
925 // Nothing unsettled and neither of this turn's rows ever rides along.
926 assert!(!texts.contains(&"yeni"));
927 }
928
929 #[tokio::test]
930 async fn failure_codes_are_stable() {
931 assert_eq!(
932 failure_code(AiError::NoWorker("chat.reply".into())),
933 "unavailable"
934 );
935 assert_eq!(failure_code(AiError::Timeout(30_000)), "timed_out");
936 assert_eq!(
937 failure_code(AiError::Remote {
938 code: "quota_exhausted".into(),
939 message: "no credit".into(),
940 }),
941 "quota_exhausted"
942 );
943 // A service that returns a blank code still yields something branchable.
944 assert_eq!(
945 failure_code(AiError::Remote {
946 code: " ".into(),
947 message: String::new(),
948 }),
949 "service_error"
950 );
951 }
952}