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

course_note_file.rs301 lines, 11.4 KiBHistoryRawDownload
1//! The `course_note_file` table: attachment rows for a course note, listed
2//! newest first, with the note's file cap claimed and released in the same
3//! write as the row.
4//!
5//! The `rag_doc_id` column belongs to the RAG index path alone — stamped by
6//! [`set_rag_doc_id`] and read back by [`find_by_rag_doc_id`] — and is
7//! deliberately absent from [`CourseNoteFile`]: no other query has to know
8//! the column exists.
9
10use crate::constant::MAX_COURSE_NOTE_FILES;
11use crate::database::{Database, tx_with_retry, unique_violation};
12use crate::db::page::PagedList;
13use crate::domain::course::CourseId;
14use crate::domain::course_note::CourseNoteId;
15use crate::domain::course_note_file::{
16 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
17};
18use crate::error::AppError;
19
20/// Persist the row assembled by [`CourseNoteFile::new`], refusing once its
21/// note already holds [`MAX_COURSE_NOTE_FILES`]. The slot and the row are
22/// taken together by one conditional statement on the note row (the claim
23/// CTE of `cap::claim_and_create`, spelled out at its call site — see
24/// `crate::db::cap`) — see [`crate::db::note_file::insert`] for why that is
25/// the only guard a concurrent insert cannot outrun.
26pub async fn insert(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {
27 // whole-row-save-ok: insert of a fresh UUID row built in place by `new` — there is no prior row to clobber
28 let created = sqlx::query_as!(
29 CourseNoteFile,
30 r#"WITH seat AS (
31 UPDATE course_note SET file_count = file_count + 1
32 WHERE id = $1 AND file_count < $2
33 RETURNING 1)
34 INSERT INTO course_note_file (id, course_note, name, content_type, size)
35 SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
36 RETURNING id AS "id: CourseNoteFileId",
37 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
38 content_type AS "content_type: FileContentType", size"#,
39 file.course_note.uuid(),
40 MAX_COURSE_NOTE_FILES as i64,
41 file.id.uuid(),
42 file.name.as_str(),
43 file.content_type.as_str(),
44 file.size
45 )
46 .fetch_optional(db)
47 .await;
48 match created {
49 Ok(Some(row)) => Ok(row),
50 // Also how a missing note reads: no note row means no slot to take.
51 Ok(None) => Err(AppError::Conflict(
52 "the course note already holds the maximum of 10 files — delete one first",
53 )),
54 // A duplicate would be a 23505 on the row's own key, which this path
55 // cannot produce — the id is a UUID this call just generated.
56 Err(err) if unique_violation(&err).is_some() => Err(AppError::Internal(
57 "failed to create course note file".into(),
58 )),
59 Err(err) => Err(err.into()),
60 }
61}
62
63/// Read a file's row by id alone, for the callers that have no note in
64/// hand yet and reach the note *through* the file (the AI bridge's blob
65/// stream). An id from any other table simply reads as `None`, which is
66/// what keeps a personal note's file id unreachable here.
67pub async fn read(
68 db: &Database,
69 id: &CourseNoteFileId,
70) -> Result<Option<CourseNoteFile>, AppError> {
71 let file = sqlx::query_as!(
72 CourseNoteFile,
73 r#"SELECT id AS "id: CourseNoteFileId",
74 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
75 content_type AS "content_type: FileContentType", size FROM course_note_file WHERE id = $1"#,
76 id.uuid()
77 )
78 .fetch_optional(db)
79 .await?;
80 Ok(file)
81}
82
83/// Read a file's row only if it belongs to `note` — callers have already
84/// checked the note belongs to a course the caller may act on.
85pub async fn read_for(
86 db: &Database,
87 id: &CourseNoteFileId,
88 note: &CourseNoteId,
89) -> Result<Option<CourseNoteFile>, AppError> {
90 let file = sqlx::query_as!(
91 CourseNoteFile,
92 r#"SELECT id AS "id: CourseNoteFileId",
93 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
94 content_type AS "content_type: FileContentType", size FROM course_note_file
95 WHERE id = $1 AND course_note = $2"#,
96 id.uuid(),
97 note.uuid()
98 )
99 .fetch_optional(db)
100 .await?;
101 Ok(file)
102}
103
104/// All of `note`'s attachment rows, newest first.
105pub async fn list_for(
106 db: &Database,
107 note: &CourseNoteId,
108 limit: Option<i64>,
109 offset: i64,
110) -> Result<(Vec<CourseNoteFile>, i64), AppError> {
111 PagedList::new(
112 "course_note_file WHERE course_note = $1",
113 "ORDER BY id DESC",
114 )
115 .bind(note.uuid())
116 .run::<CourseNoteFile>(limit, offset, db)
117 .await
118}
119
120/// Every file row claiming `doc_id` — the content hash an indexing service
121/// minted for a file's bytes. The column is deliberately not unique
122/// (identical bytes produce the same doc id), so one doc may be claimed by
123/// several files, and a file's next re-index may find its bytes already
124/// covered. Ordered by id so callers presenting the rows do not shuffle
125/// between reads.
126pub async fn find_by_rag_doc_id(
127 db: &Database,
128 doc_id: &str,
129) -> Result<Vec<CourseNoteFile>, AppError> {
130 let files = sqlx::query_as!(
131 CourseNoteFile,
132 r#"SELECT id AS "id: CourseNoteFileId",
133 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
134 content_type AS "content_type: FileContentType", size FROM course_note_file
135 WHERE rag_doc_id = $1 ORDER BY id"#,
136 doc_id
137 )
138 .fetch_all(db)
139 .await?;
140 Ok(files)
141}
142
143/// Stamp the indexing service's `doc_id` onto a file row — what a service
144/// staged, so the next refresh can tell whether those bytes are already
145/// covered. A plain id-keyed update: the column is owned by the RAG index
146/// path alone, and no cap or counter moves with it. An unknown id updates
147/// nothing, which the caller already tolerates as best-effort.
148pub async fn set_rag_doc_id(
149 db: &Database,
150 file: &CourseNoteFileId,
151 doc_id: &str,
152) -> Result<(), AppError> {
153 sqlx::query!(
154 r#"UPDATE course_note_file SET rag_doc_id = $2 WHERE id = $1"#,
155 file.uuid(),
156 doc_id
157 )
158 .execute(db)
159 .await?;
160 Ok(())
161}
162
163/// The blob names (the rows' own ids, since a file's blob is named by its
164/// id) behind every note attachment of `course` — collected *before* the
165/// course-delete cascade wipes the rows.
166pub async fn file_keys_for_course(
167 db: &Database,
168 course: &CourseId,
169) -> Result<Vec<String>, AppError> {
170 let rows = sqlx::query!(
171 r#"SELECT course_note_file.id AS "id: CourseNoteFileId" FROM course_note_file
172 WHERE course_note IN (SELECT id FROM course_note WHERE course = $1)"#,
173 course.uuid()
174 )
175 .fetch_all(db)
176 .await?;
177 Ok(rows.into_iter().map(|row| row.id.key()).collect())
178}
179
180/// Delete the row and give its slot back in the same transaction — the
181/// note itself is untouched, so unlike the note-delete cascade this one
182/// has a counter to correct.
183pub async fn delete(db: &Database, file: CourseNoteFile) -> Result<CourseNoteFile, AppError> {
184 tx_with_retry(db, true, async move |conn| {
185 let gone = sqlx::query_as!(
186 CourseNoteFile,
187 r#"DELETE FROM course_note_file WHERE id = $1
188 RETURNING id AS "id: CourseNoteFileId",
189 course_note AS "course_note: CourseNoteId", name AS "name: FileName",
190 content_type AS "content_type: FileContentType", size"#,
191 file.id.uuid()
192 )
193 .fetch_optional(&mut *conn)
194 .await?;
195 let file = gone.ok_or(AppError::NotFound)?;
196 sqlx::query!(
197 "UPDATE course_note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1",
198 file.course_note.uuid()
199 )
200 .execute(&mut *conn)
201 .await?;
202 Ok(file)
203 })
204 .await
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
211 use crate::domain::course_note::CourseNote;
212 use crate::domain::course_note::{CourseNoteContent, CourseNoteTitle};
213 use crate::domain::course_note_file::FileContentType;
214 use crate::domain::course_note_file::FileName;
215
216 /// A real `app_user` row: authors and creators are foreign keys now.
217 async fn a_person(db: &Database) -> crate::domain::user::UserId {
218 let user = crate::domain::user::UserId::generate();
219 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
220 .bind(user.uuid())
221 .bind(format!("cnf-{}", &user.key()[30..]))
222 .execute(db)
223 .await
224 .unwrap();
225 user
226 }
227
228 async fn note_of(db: &Database, title: &str) -> CourseNote {
229 // The note's author is a foreign key now: a real `app_user` row.
230 let creator = a_person(db).await;
231 let course = crate::db::course::create(
232 db,
233 &creator,
234 CourseTitle::try_new("c").unwrap(),
235 CourseDescription::try_new("").unwrap(),
236 CourseKind::try_new("course").unwrap(),
237 )
238 .await
239 .unwrap();
240 crate::db::course_note::create(
241 db,
242 course.get_id(),
243 &creator,
244 CourseNoteTitle::try_new(title).unwrap(),
245 CourseNoteContent::try_new("body").unwrap(),
246 )
247 .await
248 .unwrap()
249 }
250
251 /// The cap answers with a conflict and the refused upload wrote nothing:
252 /// the count stays at the accepted rows.
253 #[tokio::test]
254 async fn insert_refuses_at_the_cap() {
255 let (db, _leases) = crate::database::init_test_db().await;
256 let note = note_of(&db, "n").await;
257 for index in 0..MAX_COURSE_NOTE_FILES {
258 let file = CourseNoteFile::new(
259 note.get_id(),
260 FileName::try_new(&format!("f{index}")).unwrap(),
261 FileContentType::try_new("text/plain").unwrap(),
262 1,
263 );
264 insert(&db, file).await.unwrap();
265 }
266 let over = CourseNoteFile::new(
267 note.get_id(),
268 FileName::try_new("over").unwrap(),
269 FileContentType::try_new("text/plain").unwrap(),
270 1,
271 );
272 assert!(matches!(
273 insert(&db, over).await,
274 Err(AppError::Conflict(_))
275 ));
276 let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
277 assert_eq!(total, MAX_COURSE_NOTE_FILES as i64);
278 }
279
280 /// The blob-key collection sees attachments through the course, and a
281 /// delete hands its slot back to the note.
282 #[tokio::test]
283 async fn file_keys_and_delete_slot_release() {
284 let (db, _leases) = crate::database::init_test_db().await;
285 let note = note_of(&db, "n").await;
286 let course = note.get_course().clone();
287 let file = CourseNoteFile::new(
288 note.get_id(),
289 FileName::try_new("f").unwrap(),
290 FileContentType::try_new("text/plain").unwrap(),
291 1,
292 );
293 let file = insert(&db, file).await.unwrap();
294 let keys = file_keys_for_course(&db, &course).await.unwrap();
295 assert_eq!(keys, vec![file.get_id().key().to_string()]);
296 let gone = delete(&db, file.clone()).await.unwrap();
297 assert_eq!(gone.get_id(), file.get_id());
298 assert!(matches!(delete(&db, file).await, Err(AppError::NotFound)));
299 assert!(file_keys_for_course(&db, &course).await.unwrap().is_empty());
300 }
301}