forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

note.rs181 lines, 6.0 KiBHistoryRawDownload
1//! The `note` table: one user's rows, listed newest first, deleted together
2//! with their attachment rows.
3
4use surrealdb::types::SurrealValue;
5
6use crate::database::Database;
7use crate::db::field_update::FieldUpdate;
8use crate::db::page::PagedList;
9use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
10use crate::domain::note_file::NoteFile;
11use crate::domain::user::UserId;
12use crate::error::AppError;
13
14/// What [`delete`]'s transaction removed: the note row (empty if it had
15/// already vanished) and every attachment row the cascade took with it — the
16/// only set whose blobs are safe to unlink.
17#[derive(Debug, SurrealValue)]
18struct DeleteOutcome {
19 note: Vec<Note>,
20 files: Vec<NoteFile>,
21}
22
23pub async fn create(
24 db: &Database,
25 owner: &UserId,
26 title: NoteTitle,
27 content: NoteContent,
28) -> Result<Note, AppError> {
29 let note = Note {
30 id: NoteId::generate(),
31 user: owner.clone(),
32 title,
33 content,
34 };
35 let created: Option<Note> = db.create(note.id.record()).content(note).await?;
36 created.ok_or_else(|| AppError::Internal("failed to create note".into()))
37}
38
39/// Read a note only if it belongs to `owner`.
40pub async fn read_owned(
41 db: &Database,
42 id: &NoteId,
43 owner: &UserId,
44) -> Result<Option<Note>, AppError> {
45 let note: Option<Note> = db.select(id.record()).await?;
46 Ok(note.filter(|note| &note.user == owner))
47}
48
49pub async fn list_for(
50 db: &Database,
51 owner: &UserId,
52 limit: Option<i64>,
53 offset: i64,
54) -> Result<(Vec<Note>, i64), AppError> {
55 PagedList::new("note WHERE user = $usr", "ORDER BY id DESC")
56 .bind("usr", owner.record())
57 .run(limit, offset, db)
58 .await
59}
60
61/// Request-scoped: no lock spans the handler's read and this write, so an
62/// omitted field (`None`) is not written at all. Passing the snapshot's
63/// value back instead would revert a concurrent edit of that field —
64/// scoping the `SET` alone does not prevent that, the values have to come
65/// from the request. Neither column is nullable, so plain `Option` per
66/// field says everything there is to say.
67pub async fn update(
68 db: &Database,
69 note: Note,
70 title: Option<NoteTitle>,
71 content: Option<NoteContent>,
72) -> Result<Note, AppError> {
73 FieldUpdate::new(note.id.record())
74 .set("title", title)
75 .set("content", content)
76 .run::<Note>(db)
77 .await
78}
79
80/// Delete the note and cascade-remove its attachment rows, returning both:
81/// the note, and the attachment rows this transaction actually removed.
82/// Blob files on disk are the web layer's to remove, but only for *these*
83/// rows — a row uploaded after the caller listed the note's files is
84/// deleted here too, and a pre-read snapshot would strand its blob. A crash
85/// between commit and unlink leaves at worst an unreachable blob, never a
86/// row pointing at nothing.
87///
88/// Children first, in one transaction, the way
89/// [`crate::db::course::delete`] does it: as two queries, an
90/// upload that committed in between kept its row while the note went, and
91/// nothing could ever list or delete it again.
92pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {
93 let mut result = db
94 .query(
95 "BEGIN TRANSACTION;
96 LET $files = (DELETE note_file WHERE note = $note RETURN BEFORE);
97 LET $gone = (DELETE $note RETURN BEFORE);
98 RETURN { note: $gone, files: $files };
99 COMMIT TRANSACTION;",
100 )
101 .bind(("note", note.id.record()))
102 .await?
103 .check()?;
104 // BEGIN is slot 0, the two LETs slots 1-2; the RETURN is slot 3.
105 let outcome = result
106 .take::<Vec<DeleteOutcome>>(3)?
107 .into_iter()
108 .next()
109 .ok_or_else(|| AppError::Internal("failed to delete note".into()))?;
110 let note = outcome.note.into_iter().next().ok_or(AppError::NotFound)?;
111 Ok((note, outcome.files))
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 /// The blobs the handler unlinks are exactly the rows this transaction
119 /// removed — including one uploaded after any pre-read snapshot would have
120 /// been taken, which is the row whose blob used to leak.
121 #[tokio::test]
122 async fn delete_returns_the_attachment_rows_it_removed() {
123 use crate::domain::note_file::{FileContentType, FileName};
124
125 let db = crate::database::init_mem().await.unwrap();
126 let owner = crate::domain::user::UserId::generate();
127 let note = create(
128 &db,
129 &owner,
130 NoteTitle::try_new("a").unwrap(),
131 NoteContent::try_new("body").unwrap(),
132 )
133 .await
134 .unwrap();
135 // What a handler snapshot would have seen...
136 let early = NoteFile::new(
137 note.get_id(),
138 FileName::try_new("early.pdf").unwrap(),
139 FileContentType::try_new("application/pdf").unwrap(),
140 3,
141 )
142 .insert(&db)
143 .await
144 .unwrap();
145 let (snapshot, _) = NoteFile::list_for(note.get_id(), None, 0, &db)
146 .await
147 .unwrap();
148 assert_eq!(snapshot.len(), 1);
149 // ...and the upload that races in after it.
150 let late = NoteFile::new(
151 note.get_id(),
152 FileName::try_new("late.pdf").unwrap(),
153 FileContentType::try_new("application/pdf").unwrap(),
154 3,
155 )
156 .insert(&db)
157 .await
158 .unwrap();
159
160 let (gone, files) = delete(&db, note).await.unwrap();
161 assert_eq!(gone.get_title().as_str(), "a");
162 let mut keys: Vec<_> = files
163 .iter()
164 .map(|file| file.get_id().key().to_string())
165 .collect();
166 keys.sort();
167 let mut want = vec![
168 early.get_id().key().to_string(),
169 late.get_id().key().to_string(),
170 ];
171 want.sort();
172 assert_eq!(keys, want);
173 assert!(
174 NoteFile::list_for(gone.get_id(), None, 0, &db)
175 .await
176 .unwrap()
177 .0
178 .is_empty()
179 );
180 }
181}