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

note_file.rs192 lines, 7.3 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::NoteContent;
118 use crate::domain::note::NoteTitle;
119 use crate::domain::note_file::FileContentType;
120 use crate::domain::note_file::FileName;
121
122 async fn a_note(db: &Database) -> Note {
123 let owner = crate::domain::user::UserId::generate();
124 crate::db::note::create(
125 db,
126 &owner,
127 NoteTitle::try_new("n").unwrap(),
128 NoteContent::try_new("b").unwrap(),
129 )
130 .await
131 .unwrap()
132 }
133
134 /// The cap answers with a conflict, and neither the refused row nor its
135 /// slot was written: the count is still what the last accepted upload
136 /// left.
137 #[tokio::test]
138 async fn insert_refuses_at_the_cap_without_leaking_a_slot() {
139 let db = crate::database::init_mem().await.unwrap();
140 let note = a_note(&db).await;
141 for index in 0..MAX_NOTE_FILES {
142 let file = NoteFile::new(
143 note.get_id(),
144 FileName::try_new(&format!("f{index}")).unwrap(),
145 FileContentType::try_new("text/plain").unwrap(),
146 1,
147 );
148 insert(&db, file).await.unwrap();
149 }
150 let over = NoteFile::new(
151 note.get_id(),
152 FileName::try_new("over").unwrap(),
153 FileContentType::try_new("text/plain").unwrap(),
154 1,
155 );
156 assert!(matches!(
157 insert(&db, over).await,
158 Err(AppError::Conflict(_))
159 ));
160 let (files, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
161 assert_eq!(total, MAX_NOTE_FILES as i64);
162 assert_eq!(files.len(), MAX_NOTE_FILES);
163 }
164
165 /// Deleting a row hands its slot back: after one delete a new upload is
166 /// accepted again, and the count never dips below zero.
167 #[tokio::test]
168 async fn delete_returns_the_slot_to_the_note() {
169 let db = crate::database::init_mem().await.unwrap();
170 let note = a_note(&db).await;
171 let file = NoteFile::new(
172 note.get_id(),
173 FileName::try_new("f").unwrap(),
174 FileContentType::try_new("text/plain").unwrap(),
175 1,
176 );
177 let file = insert(&db, file).await.unwrap();
178 let gone = delete(&db, file.clone()).await.unwrap();
179 assert_eq!(gone.get_id(), file.get_id());
180 // Deleting it a second time is a 404, not a second decrement.
181 assert!(matches!(delete(&db, file).await, Err(AppError::NotFound)));
182 let next = NoteFile::new(
183 note.get_id(),
184 FileName::try_new("next").unwrap(),
185 FileContentType::try_new("text/plain").unwrap(),
186 1,
187 );
188 insert(&db, next).await.unwrap();
189 let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
190 assert_eq!(total, 1);
191 }
192}