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

rag_thread.rs115 lines, 3.9 KiBHistoryRawDownload
1//! A RAG thread. It only groups turns and carries the ordering key the
2//! list view sorts on: `updated_at` moves on every new turn, so a user's
3//! threads list newest-activity-first. The turns themselves live in
4//! [`crate::db::rag_message`], and deleting a thread cascades them; the
5//! threads' own persistence lives in [`crate::db::rag_thread`].
6//!
7//! A user's RAG threads are capped per nest but on the **chatbot's knob**:
8//! `app_user.rag_thread_count` holds this nest's seats, and the school's
9//! `max_chatbot_threads` is the number both nests are read against — the two
10//! are one package (`/chatbot` and `/rag` are both `Module::Chatbot`), and the
11//! cap exists to bound what one account may store in a school's database, so
12//! one knob governs the whole package. Each nest holds its own seats all the
13//! same: a user at the cap in one nest may still open a thread in the other,
14//! and the counter a claim moves counts exactly the rows it guards.
15
16use crate::constant::MAX_CHATBOT_THREAD_TITLE_LEN;
17use crate::domain::monotonic_id::next_uuid;
18use crate::domain::timestamp::Timestamp;
19use crate::domain::user::UserId;
20use crate::error::ValidationError;
21use crate::validate::validate_required;
22
23#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
24#[sqlx(transparent)]
25pub struct RagThreadId(uuid::Uuid);
26
27impl RagThreadId {
28 /// Mints from the process-wide monotonic generator, not a plain random
29 /// UUID: threads sort `updated_at DESC, id DESC` and the id breaks the tie
30 /// between two threads last touched in the same millisecond,
31 /// and a random low half sorts arbitrarily inside one millisecond.
32 pub fn generate() -> Self {
33 Self(next_uuid())
34 }
35
36 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
37 /// cannot take the newtype. Static `query!` binds take `self` directly.
38 pub fn uuid(&self) -> uuid::Uuid {
39 self.0
40 }
41
42 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
43 /// which matches no row.
44 pub fn from_key(key: &str) -> Self {
45 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
46 }
47
48 pub fn key(&self) -> String {
49 self.0.to_string()
50 }
51}
52
53/// A user-chosen thread name. Required-and-bounded here; "untitled" is
54/// `Option<RagThreadTitle>` on the row. Named like the chatbot's
55/// ([`crate::domain::chatbot_thread::ChatbotThreadTitle`]) and bounded by the
56/// same constant: a name is a line a user typed either way.
57#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
58#[sqlx(transparent)]
59pub struct RagThreadTitle(String);
60
61impl RagThreadTitle {
62 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
63 validate_required("title", value, MAX_CHATBOT_THREAD_TITLE_LEN)?;
64 Ok(Self(value.to_string()))
65 }
66
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70}
71
72#[derive(Debug, Clone, sqlx::FromRow)]
73pub struct RagThread {
74 pub(crate) id: RagThreadId,
75 /// The owning user. The column is `owner`, not the chatbot's `user_id` —
76 /// the RAG nest stores no second participant a name had to disambiguate.
77 pub(crate) owner: UserId,
78 pub(crate) title: Option<RagThreadTitle>,
79 pub(crate) created_at: Timestamp,
80 pub(crate) updated_at: Timestamp,
81}
82
83impl RagThread {
84 pub fn get_id(&self) -> &RagThreadId {
85 &self.id
86 }
87
88 pub fn get_owner(&self) -> &UserId {
89 &self.owner
90 }
91
92 pub fn get_title(&self) -> Option<&RagThreadTitle> {
93 self.title.as_ref()
94 }
95
96 pub fn get_created_at(&self) -> Timestamp {
97 self.created_at
98 }
99
100 pub fn get_updated_at(&self) -> Timestamp {
101 self.updated_at
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[tokio::test]
110 async fn title_is_required_and_bounded() {
111 assert_eq!(RagThreadTitle::try_new("Fizik").unwrap().as_str(), "Fizik");
112 assert!(RagThreadTitle::try_new(" ").is_err());
113 assert!(RagThreadTitle::try_new(&"x".repeat(201)).is_err());
114 }
115}