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.rs247 lines, 8.6 KiBHistoryRawDownload
1//! One turn of a chatbot thread — the row shape and its read-time
2//! presentation. `user_id` is duplicated from the thread onto every message
3//! so an ownership check is one read, with no join.
4//!
5//! Persistence lives in [`crate::db::chatbot_message`]: the assistant's row
6//! is written `pending` *before* the AI call and flipped to `complete` or
7//! `failed` by the task that owns the bridge round trip, and a read
8//! projects a long-stale `pending` as failed without writing
9//! ([`ChatbotMessage::projected`]) — the durable repair for a dead process
10//! happens once, at mint, in `database.rs`'s school migration sweep.
11
12use crate::constant::{CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE};
13use crate::domain::chatbot_thread::ChatbotThreadId;
14use crate::domain::monotonic_id::next_uuid;
15use crate::domain::timestamp::Timestamp;
16use crate::domain::user::UserId;
17use crate::error::ValidationError;
18use crate::validate::validate_required;
19
20#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
21#[sqlx(transparent)]
22pub struct ChatbotMessageId(uuid::Uuid);
23
24impl ChatbotMessageId {
25 /// Mints in write order. Unlike a plain random UUID, whose random low bits
26 /// sort arbitrarily among ids minted in the same millisecond, the
27 /// process-wide context increments — so the `id` tie-break in the
28 /// `ORDER BY` of
29 /// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) /
30 /// [`list_tail`](crate::db::chatbot_message::list_tail) is the
31 /// order the rows were written. The user prompt and the assistant row one
32 /// POST writes back-to-back routinely share a millisecond, and a random
33 /// tie-break there renders the answer *above* its own question — and
34 /// hands the AI service a `[assistant, user]` history, breaking the
35 /// oldest-first contract.
36 pub fn generate() -> Self {
37 Self(next_uuid())
38 }
39
40 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
41 /// cannot take the newtype. Static `query!` binds take `self` directly.
42 pub fn uuid(&self) -> uuid::Uuid {
43 self.0
44 }
45
46 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
47 /// which matches no row.
48 pub fn from_key(key: &str) -> Self {
49 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
50 }
51
52 pub fn key(&self) -> String {
53 self.0.to_string()
54 }
55}
56
57/// Who said a turn. Stored as the bare lowercase string the `role` column's
58/// CHECK allows; a value the enum doesn't know comes back as a decode error,
59/// never a panic.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
61#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
62pub enum MessageRole {
63 User,
64 Assistant,
65}
66
67impl MessageRole {
68 /// The wire/storage form. Must stay in lockstep with `rename_all`.
69 pub fn as_str(self) -> &'static str {
70 match self {
71 MessageRole::User => "user",
72 MessageRole::Assistant => "assistant",
73 }
74 }
75}
76
77/// Where an assistant turn is in its lifecycle. A user turn is born
78/// `Complete` — nothing is ever awaited for it.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
80#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
81pub enum MessageStatus {
82 Pending,
83 Complete,
84 Failed,
85}
86
87impl MessageStatus {
88 pub fn as_str(self) -> &'static str {
89 match self {
90 MessageStatus::Pending => "pending",
91 MessageStatus::Complete => "complete",
92 MessageStatus::Failed => "failed",
93 }
94 }
95}
96
97/// One turn's text. The hard ceiling only — the school-adjustable
98/// `max_chatbot_message_len` is the web layer's to enforce, below this.
99#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
100#[sqlx(transparent)]
101pub struct ChatContent(String);
102
103impl ChatContent {
104 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
105 validate_required("content", value, MAX_CHATBOT_MESSAGE_LEN)?;
106 Ok(Self(value.to_string()))
107 }
108
109 /// The placeholder a `pending` assistant row carries until its answer
110 /// lands. Crate-visible: only the persistence layer writes it, for the
111 /// reserved row before the answer exists.
112 pub(crate) fn empty() -> Self {
113 Self(String::new())
114 }
115
116 pub fn as_str(&self) -> &str {
117 &self.0
118 }
119}
120
121#[derive(Debug, Clone, sqlx::FromRow)]
122pub struct ChatbotMessage {
123 pub(crate) id: ChatbotMessageId,
124 pub(crate) thread_id: ChatbotThreadId,
125 pub(crate) user_id: UserId,
126 pub(crate) role: MessageRole,
127 pub(crate) content: ChatContent,
128 pub(crate) status: MessageStatus,
129 /// Whether the stored `content` is a clipped version of what the AI
130 /// service actually answered. Only an assistant turn can ever set it: a
131 /// user prompt over the cap is refused (400), never trimmed.
132 pub(crate) truncated: bool,
133 pub(crate) error_code: Option<String>,
134 pub(crate) created_at: Timestamp,
135 pub(crate) completed_at: Option<Timestamp>,
136}
137
138impl ChatbotMessage {
139 pub fn get_id(&self) -> &ChatbotMessageId {
140 &self.id
141 }
142
143 pub fn get_thread_id(&self) -> &ChatbotThreadId {
144 &self.thread_id
145 }
146
147 pub fn get_user_id(&self) -> &UserId {
148 &self.user_id
149 }
150
151 pub fn get_role(&self) -> MessageRole {
152 self.role
153 }
154
155 pub fn get_content(&self) -> &ChatContent {
156 &self.content
157 }
158
159 pub fn get_status(&self) -> MessageStatus {
160 self.status
161 }
162
163 pub fn is_truncated(&self) -> bool {
164 self.truncated
165 }
166
167 pub fn get_error_code(&self) -> Option<&str> {
168 self.error_code.as_deref()
169 }
170
171 pub fn get_created_at(&self) -> Timestamp {
172 self.created_at
173 }
174
175 pub fn get_completed_at(&self) -> Option<Timestamp> {
176 self.completed_at
177 }
178
179 /// A row still `pending` past [`CHATBOT_PENDING_STALE_SECS`] has lost the task
180 /// that owed it an answer; present it as failed.
181 ///
182 /// Read-time projection, not a lazy write-back: the read paths (poll loop,
183 /// thread load) run on every page and must not write, a write-back would
184 /// race the answering task that is merely slow — closing the door on a
185 /// reply that is still coming — and the durable repair for the real cause
186 /// (a dead process) already happens once, at mint. The stored row stays
187 /// truthful; only the answer handed to the caller is projected.
188 pub(crate) fn projected(mut self) -> Self {
189 let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000;
190 if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at {
191 self.status = MessageStatus::Failed;
192 self.error_code = Some(STALE_ERROR_CODE.to_string());
193 }
194 self
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 #[tokio::test]
203 async fn content_is_required_and_capped() {
204 assert!(ChatContent::try_new("").is_err());
205 assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN)).is_ok());
206 assert!(ChatContent::try_new(&"x".repeat(MAX_CHATBOT_MESSAGE_LEN + 1)).is_err());
207 }
208
209 /// The `role`/`status` columns are `TEXT` with CHECKs listing exactly
210 /// these spellings — queries match on them, so the storage form may not
211 /// drift from `as_str` (which `rename_all` mirrors).
212 #[test]
213 fn role_and_status_spellings_are_frozen() {
214 assert_eq!(MessageRole::User.as_str(), "user");
215 assert_eq!(MessageRole::Assistant.as_str(), "assistant");
216 assert_eq!(MessageStatus::Pending.as_str(), "pending");
217 assert_eq!(MessageStatus::Complete.as_str(), "complete");
218 assert_eq!(MessageStatus::Failed.as_str(), "failed");
219 }
220
221 #[tokio::test]
222 async fn stale_pending_projects_as_failed() {
223 let aged = |secs: i64| {
224 ChatbotMessage {
225 id: ChatbotMessageId::generate(),
226 thread_id: ChatbotThreadId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"),
227 user_id: UserId::from_key("0198f1a2-3b4c-7d5e-8f90-aa2b3c4d5e6f"),
228 role: MessageRole::Assistant,
229 content: ChatContent::empty(),
230 status: MessageStatus::Pending,
231 truncated: false,
232 error_code: None,
233 created_at: Timestamp::from_millis(Timestamp::now().as_millis() - secs * 1_000),
234 completed_at: None,
235 }
236 .projected()
237 };
238
239 let fresh = aged(1);
240 assert_eq!(fresh.get_status(), MessageStatus::Pending);
241 assert_eq!(fresh.get_error_code(), None);
242
243 let stale = aged(CHATBOT_PENDING_STALE_SECS + 1);
244 assert_eq!(stale.get_status(), MessageStatus::Failed);
245 assert_eq!(stale.get_error_code(), Some(STALE_ERROR_CODE));
246 }
247}