forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

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