forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

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