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

message.rs319 lines, 10.4 KiBHistoryRawDownload
1use sqlx::Type;
2use uuid::Uuid;
3
4use crate::constant::{MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN};
5use crate::domain::monotonic_id::next_uuid;
6use crate::domain::timestamp::Timestamp;
7use crate::domain::user::UserId;
8use crate::error::ValidationError;
9use crate::validate::{validate_optional, validate_required};
10
11/// The mailbox folders a copy can sit in — the single source of folder names
12/// for the whole stack. Nothing else may spell a folder: the DB columns, the
13/// query filter and the restore stamp all pass through this enum, so a typo
14/// is a compile error rather than a silently empty folder.
15///
16/// Each variant stores as a bare lowercase TEXT value (`"inbox"`,
17/// `"archive"`, …) and round-trips straight back — same trick as
18/// `domain::role`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
20#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
21pub enum Folder {
22 Inbox,
23 Sent,
24 Archive,
25 Trash,
26 /// The hidden "my copy is gone" folder; never a valid move or list
27 /// target — reached only through [`crate::db::message::delete_for`].
28 Deleted,
29}
30
31impl Folder {
32 /// The storage/wire form. Must stay in lockstep with `rename_all`.
33 pub fn as_str(self) -> &'static str {
34 match self {
35 Folder::Inbox => "inbox",
36 Folder::Sent => "sent",
37 Folder::Archive => "archive",
38 Folder::Trash => "trash",
39 Folder::Deleted => "deleted",
40 }
41 }
42
43 /// Parse a caller-supplied folder name. `deleted` is internal, so it is
44 /// rejected here like any other unknown word — a caller can never name it.
45 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
46 match value {
47 "inbox" => Ok(Folder::Inbox),
48 "sent" => Ok(Folder::Sent),
49 "archive" => Ok(Folder::Archive),
50 "trash" => Ok(Folder::Trash),
51 _ => Err(ValidationError::Invalid {
52 field: "folder",
53 reason: "must be one of: inbox, sent, archive, trash",
54 }),
55 }
56 }
57
58 /// Where a side's copy lives when nothing has been filed away.
59 pub fn home(is_sender: bool) -> Self {
60 if is_sender {
61 Folder::Sent
62 } else {
63 Folder::Inbox
64 }
65 }
66
67 /// The folders a side may move its copy to.
68 pub fn allowed_for(is_sender: bool) -> &'static [Folder] {
69 if is_sender {
70 &SENDER_FOLDERS
71 } else {
72 &RECIPIENT_FOLDERS
73 }
74 }
75
76 /// A filed-away copy — one that has somewhere to be restored to.
77 pub(crate) fn is_filed(self) -> bool {
78 matches!(self, Folder::Archive | Folder::Trash)
79 }
80
81 /// Whether this folder is worth remembering as a restore target. The
82 /// trash is not: pulling a copy out of the trash and into the archive
83 /// must not leave it pointing back at the trash.
84 pub(crate) fn is_restore_target(self) -> bool {
85 matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive)
86 }
87}
88
89/// Folders a sender may file their side into (`Sent` is their home).
90pub const SENDER_FOLDERS: [Folder; 3] = [Folder::Sent, Folder::Archive, Folder::Trash];
91/// Folders a recipient may file their side into (`Inbox` is their home).
92pub const RECIPIENT_FOLDERS: [Folder; 3] = [Folder::Inbox, Folder::Archive, Folder::Trash];
93
94/// Typed message row id. A UUIDv7 minted by the process-wide monotonic
95/// generator, so `id` order is mint order.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
97#[sqlx(transparent)]
98pub struct MessageId(Uuid);
99
100impl MessageId {
101 /// Minted from the process-wide monotonic generator, not a random v4:
102 /// the folder listings sort `id DESC` (newest first,
103 /// [`crate::db::message::list_folder`]),
104 /// and a random low half scrambles rows minted in the same millisecond.
105 pub fn generate() -> Self {
106 Self(next_uuid())
107 }
108
109 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
110 /// cannot take the newtype. Static `query!` binds take `self` directly.
111 pub fn uuid(&self) -> Uuid {
112 self.0
113 }
114
115 /// Parse a wire key. A key that parses as no UUID — a malformed path
116 /// segment — reads as the nil id, which matches no row: exactly the 404 a
117 /// dangling record key produced under the old store, without turning a
118 /// typo into a panic.
119 pub fn from_key(key: &str) -> Self {
120 Self(Uuid::parse_str(key).unwrap_or(Uuid::nil()))
121 }
122
123 /// The hyphenated wire form.
124 pub fn key(&self) -> String {
125 self.0.to_string()
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
130#[sqlx(transparent)]
131pub struct MessageSubject(String);
132
133impl MessageSubject {
134 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
135 validate_required("subject", value, MAX_MESSAGE_SUBJECT_LEN)?;
136 Ok(Self(value.to_string()))
137 }
138
139 pub fn as_str(&self) -> &str {
140 &self.0
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
145#[sqlx(transparent)]
146pub struct MessageBody(String);
147
148impl MessageBody {
149 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
150 validate_optional("body", value, MAX_MESSAGE_BODY_LEN)?;
151 Ok(Self(value.to_string()))
152 }
153
154 pub fn as_str(&self) -> &str {
155 &self.0
156 }
157}
158
159/// A sender-chosen tag ("Study", "Exam", …) the UI renders as a badge.
160/// Required-and-bounded here; "no label" is `Option<MessageLabel>` on the row.
161#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
162#[sqlx(transparent)]
163pub struct MessageLabel(String);
164
165impl MessageLabel {
166 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
167 validate_required("label", value, MAX_MESSAGE_LABEL_LEN)?;
168 Ok(Self(value.to_string()))
169 }
170
171 pub fn as_str(&self) -> &str {
172 &self.0
173 }
174}
175
176#[derive(Debug, Clone, sqlx::FromRow)]
177pub struct Message {
178 pub(crate) id: MessageId,
179 pub(crate) sender: UserId,
180 pub(crate) recipient: UserId,
181 pub(crate) subject: MessageSubject,
182 pub(crate) body: MessageBody,
183 pub(crate) label: Option<MessageLabel>,
184 pub(crate) sent_at: Timestamp,
185 pub(crate) read: bool,
186 pub(crate) sender_folder: Folder,
187 pub(crate) recipient_folder: Folder,
188 /// Where each side's copy sat before it was filed into archive/trash —
189 /// the restore target. `None` while the copy sits in its home folder.
190 pub(crate) sender_origin: Option<Folder>,
191 pub(crate) recipient_origin: Option<Folder>,
192}
193
194impl Message {
195 pub fn get_id(&self) -> &MessageId {
196 &self.id
197 }
198
199 pub fn get_sender(&self) -> &UserId {
200 &self.sender
201 }
202
203 pub fn get_recipient(&self) -> &UserId {
204 &self.recipient
205 }
206
207 pub fn get_subject(&self) -> &MessageSubject {
208 &self.subject
209 }
210
211 pub fn get_body(&self) -> &MessageBody {
212 &self.body
213 }
214
215 pub fn get_label(&self) -> Option<&MessageLabel> {
216 self.label.as_ref()
217 }
218
219 pub fn get_sent_at(&self) -> Timestamp {
220 self.sent_at
221 }
222
223 pub fn is_read(&self) -> bool {
224 self.read
225 }
226
227 pub fn is_sender(&self, user: &UserId) -> bool {
228 &self.sender == user
229 }
230
231 /// The folder `user`'s side of this message currently sits in.
232 pub fn folder_of(&self, user: &UserId) -> Folder {
233 if self.is_sender(user) {
234 self.sender_folder
235 } else {
236 self.recipient_folder
237 }
238 }
239
240 /// Where `user`'s copy came from before it was filed away — `None` when
241 /// it isn't filed away (or was filed by a binary older than the memory),
242 /// in which case restoring means [`Folder::home`].
243 pub fn origin_of(&self, user: &UserId) -> Option<Folder> {
244 if self.is_sender(user) {
245 self.sender_origin
246 } else {
247 self.recipient_origin
248 }
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[tokio::test]
257 async fn subject_is_required_body_is_not() {
258 assert_eq!(MessageSubject::try_new("hi").unwrap().as_str(), "hi");
259 assert!(MessageSubject::try_new(" ").is_err());
260 assert_eq!(MessageBody::try_new("").unwrap().as_str(), "");
261 }
262
263 #[tokio::test]
264 async fn folder_sides_resolve_by_membership() {
265 let sender = UserId::from_key("018f1a00-0000-7000-8000-000000000001");
266 let recipient = UserId::from_key("018f1a00-0000-7000-8000-000000000002");
267 let message = Message {
268 id: MessageId::generate(),
269 sender,
270 recipient,
271 subject: MessageSubject::try_new("s").unwrap(),
272 body: MessageBody::try_new("").unwrap(),
273 label: None,
274 sent_at: Timestamp::now(),
275 read: false,
276 sender_folder: Folder::Sent,
277 recipient_folder: Folder::Archive,
278 sender_origin: None,
279 recipient_origin: Some(Folder::Inbox),
280 };
281 assert!(message.is_sender(&sender));
282 assert_eq!(message.folder_of(&sender), Folder::Sent);
283 assert_eq!(message.folder_of(&recipient), Folder::Archive);
284 assert_eq!(message.origin_of(&sender), None);
285 assert_eq!(message.origin_of(&recipient), Some(Folder::Inbox));
286 }
287
288 #[tokio::test]
289 async fn folder_names_parse_and_the_hidden_one_does_not() {
290 assert_eq!(Folder::try_new("archive").unwrap(), Folder::Archive);
291 assert!(Folder::try_new("deleted").is_err());
292 assert!(Folder::try_new("spam").is_err());
293 assert_eq!(Folder::home(true), Folder::Sent);
294 assert_eq!(Folder::home(false), Folder::Inbox);
295 // Both sides may archive their own copy; neither may reach the inbox
296 // that isn't theirs — the sender's home is `sent`, not `inbox`.
297 assert!(Folder::allowed_for(true).contains(&Folder::Archive));
298 assert!(Folder::allowed_for(false).contains(&Folder::Archive));
299 assert!(!Folder::allowed_for(true).contains(&Folder::Inbox));
300 }
301
302 #[test]
303 fn sqlx_encodes_the_storage_form() {
304 // The folder columns are TEXT with a CHECK on these exact words; the
305 // sqlx encoding must never drift from `as_str`.
306 let mut buf = sqlx::postgres::PgArgumentBuffer::default();
307 for folder in [
308 Folder::Inbox,
309 Folder::Sent,
310 Folder::Archive,
311 Folder::Trash,
312 Folder::Deleted,
313 ] {
314 buf.clear();
315 let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&folder, &mut buf).unwrap();
316 assert_eq!(std::str::from_utf8(&buf).unwrap(), folder.as_str());
317 }
318 }
319}