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

note_file.rs206 lines, 7.8 KiBHistoryRawDownload
1//! The `note_file` table: attachment rows for a personal note, listed newest
2//! first, with the note's file cap claimed and released in the same write as
3//! the row.
4
5use crate::constant::MAX_NOTE_FILES;
6use crate::database::{Database, tx_with_retry, unique_violation};
7use crate::db::page::PagedList;
8use crate::domain::note::NoteId;
9use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId};
10use crate::error::AppError;
11
12/// Persist the row assembled by [`NoteFile::new`], refusing once its note
13/// already holds [`MAX_NOTE_FILES`]. The slot and the row are taken together
14/// by one conditional statement on the note row (the claim CTE of
15/// `cap::claim_and_create`, spelled out at its call site — see
16/// `crate::db::cap`): a `BEGIN…COMMIT` around a count can't enforce the cap
17/// and a process-wide mutex can't either, since it is released around the
18/// very round trip the insert races — a single guarded statement can.
19/// Claiming in a *separate* query would enforce the cap but leak a slot on
20/// a crash between the two.
21pub async fn insert(db: &Database, file: NoteFile) -> Result<NoteFile, 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 NoteFile,
25 r#"WITH seat AS (
26 UPDATE note SET file_count = file_count + 1
27 WHERE id = $1 AND file_count < $2
28 RETURNING 1)
29 INSERT INTO note_file (id, note, name, content_type, size)
30 SELECT $3, $1, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
31 RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName",
32 content_type AS "content_type: FileContentType", size"#,
33 file.note.uuid(),
34 MAX_NOTE_FILES as i64,
35 file.id.uuid(),
36 file.name.as_str(),
37 file.content_type.as_str(),
38 file.size
39 )
40 .fetch_optional(db)
41 .await;
42 match created {
43 Ok(Some(row)) => Ok(row),
44 // Also how a missing note reads: no note row means no slot to take.
45 Ok(None) => Err(AppError::Conflict(
46 "the note already holds the maximum of 10 files — delete one first",
47 )),
48 // A duplicate would be a 23505 on the row's own key, which this path
49 // cannot produce — the id is a UUID this call just generated.
50 Err(err) if unique_violation(&err).is_some() => {
51 Err(AppError::Internal("failed to create note file".into()))
52 }
53 Err(err) => Err(err.into()),
54 }
55}
56
57/// Read a file's row only if it belongs to `note` — callers have already
58/// checked the note belongs to the requesting user.
59pub async fn read_for(
60 db: &Database,
61 id: &NoteFileId,
62 note: &NoteId,
63) -> Result<Option<NoteFile>, AppError> {
64 let file = sqlx::query_as!(
65 NoteFile,
66 r#"SELECT id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName",
67 content_type AS "content_type: FileContentType", size FROM note_file WHERE id = $1 AND note = $2"#,
68 id.uuid(),
69 note.uuid()
70 )
71 .fetch_optional(db)
72 .await?;
73 Ok(file)
74}
75
76/// All of `note`'s attachment rows, newest first.
77pub async fn list_for(
78 db: &Database,
79 note: &NoteId,
80 limit: Option<i64>,
81 offset: i64,
82) -> Result<(Vec<NoteFile>, i64), AppError> {
83 PagedList::new("note_file WHERE note = $1", "ORDER BY id DESC")
84 .bind(note.uuid())
85 .run::<NoteFile>(limit, offset, db)
86 .await
87}
88
89/// Delete the row and give its slot back in the same transaction — the note
90/// itself is untouched, so unlike the note-delete cascade this one has a
91/// counter to correct. (Deleting a *note* takes its counter with it.)
92pub async fn delete(db: &Database, file: NoteFile) -> Result<NoteFile, AppError> {
93 tx_with_retry(db, true, async move |conn| {
94 let gone = sqlx::query_as!(
95 NoteFile,
96 r#"DELETE FROM note_file WHERE id = $1 RETURNING id AS "id: NoteFileId", note AS "note: NoteId", name AS "name: FileName",
97 content_type AS "content_type: FileContentType", size"#,
98 file.id.uuid()
99 )
100 .fetch_optional(&mut *conn)
101 .await?;
102 let file = gone.ok_or(AppError::NotFound)?;
103 sqlx::query!(
104 "UPDATE note SET file_count = GREATEST(file_count - 1, 0) WHERE id = $1",
105 file.note.uuid()
106 )
107 .execute(&mut *conn)
108 .await?;
109 Ok(file)
110 })
111 .await
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117 use crate::domain::note::Note;
118 use crate::domain::note::NoteContent;
119 use crate::domain::note::NoteTitle;
120 use crate::domain::note_file::FileContentType;
121 use crate::domain::note_file::FileName;
122
123 /// A real `app_user` row: the note's owner is a foreign key now.
124 async fn a_person(db: &Database) -> crate::domain::user::UserId {
125 let user = crate::domain::user::UserId::generate();
126 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
127 .bind(user.uuid())
128 .bind(format!("nf-{}", &user.key()[30..]))
129 .execute(db)
130 .await
131 .unwrap();
132 user
133 }
134
135 async fn a_note(db: &Database) -> Note {
136 // The note's owner is a foreign key now: a real `app_user` row.
137 let owner = a_person(db).await;
138 crate::db::note::create(
139 db,
140 &owner,
141 NoteTitle::try_new("n").unwrap(),
142 NoteContent::try_new("b").unwrap(),
143 )
144 .await
145 .unwrap()
146 }
147
148 /// The cap answers with a conflict, and neither the refused row nor its
149 /// slot was written: the count is still what the last accepted upload
150 /// left.
151 #[tokio::test]
152 async fn insert_refuses_at_the_cap_without_leaking_a_slot() {
153 let (db, _leases) = crate::database::init_test_db().await;
154 let note = a_note(&db).await;
155 for index in 0..MAX_NOTE_FILES {
156 let file = NoteFile::new(
157 note.get_id(),
158 FileName::try_new(&format!("f{index}")).unwrap(),
159 FileContentType::try_new("text/plain").unwrap(),
160 1,
161 );
162 insert(&db, file).await.unwrap();
163 }
164 let over = NoteFile::new(
165 note.get_id(),
166 FileName::try_new("over").unwrap(),
167 FileContentType::try_new("text/plain").unwrap(),
168 1,
169 );
170 assert!(matches!(
171 insert(&db, over).await,
172 Err(AppError::Conflict(_))
173 ));
174 let (files, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
175 assert_eq!(total, MAX_NOTE_FILES as i64);
176 assert_eq!(files.len(), MAX_NOTE_FILES);
177 }
178
179 /// Deleting a row hands its slot back: after one delete a new upload is
180 /// accepted again, and the count never dips below zero.
181 #[tokio::test]
182 async fn delete_returns_the_slot_to_the_note() {
183 let (db, _leases) = crate::database::init_test_db().await;
184 let note = a_note(&db).await;
185 let file = NoteFile::new(
186 note.get_id(),
187 FileName::try_new("f").unwrap(),
188 FileContentType::try_new("text/plain").unwrap(),
189 1,
190 );
191 let file = insert(&db, file).await.unwrap();
192 let gone = delete(&db, file.clone()).await.unwrap();
193 assert_eq!(gone.get_id(), file.get_id());
194 // Deleting it a second time is a 404, not a second decrement.
195 assert!(matches!(delete(&db, file).await, Err(AppError::NotFound)));
196 let next = NoteFile::new(
197 note.get_id(),
198 FileName::try_new("next").unwrap(),
199 FileContentType::try_new("text/plain").unwrap(),
200 1,
201 );
202 insert(&db, next).await.unwrap();
203 let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
204 assert_eq!(total, 1);
205 }
206}