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

board.rs212 lines, 6.9 KiBHistoryRawDownload
1//! A collaborative whiteboard room. Membership is an ad-hoc invite list the
2//! creator names — no course, session or appointment is involved — and the
3//! whole permission model is the two predicates [`Board::is_participant`]
4//! (draw) and [`Board::is_creator`] (clear / lock / close / delete). Every
5//! route and every socket frame gates on exactly those two.
6//!
7//! The marks themselves live in `board_stroke`, appended and never deleted: a
8//! clear bumps `epoch` so the canvas empties while the history stays
9//! replayable. The two stroke counters (`epoch_stroke_count`,
10//! `total_stroke_count`) are counter columns this struct deliberately does
11//! NOT carry — they are written only by the stroke path's conditional claim,
12//! so every mutation here is a field-scoped `UPDATE … SET`. A whole-row
13//! rewrite would silently wipe both.
14
15use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARD_TITLE_LEN};
16use crate::domain::monotonic_id::next_uuid;
17use crate::domain::timestamp::Timestamp;
18use crate::domain::user::UserId;
19use crate::error::ValidationError;
20use crate::validate::validate_required;
21
22#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
23#[sqlx(transparent)]
24pub struct BoardId(uuid::Uuid);
25
26impl BoardId {
27 /// Monotonic, not a plain random UUID: boards list newest-first by id, and
28 /// a random low half scrambles rows minted in the same millisecond.
29 pub fn generate() -> Self {
30 Self(next_uuid())
31 }
32
33 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
34 /// cannot take the newtype. Static `query!` binds take `self` directly.
35 pub fn uuid(&self) -> uuid::Uuid {
36 self.0
37 }
38
39 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
40 /// which matches no row — a malformed path param stays a 404, exactly
41 /// like a well-formed one that names nothing.
42 pub fn from_key(key: &str) -> Self {
43 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
44 }
45
46 pub fn key(&self) -> String {
47 self.0.to_string()
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
52#[sqlx(transparent)]
53pub struct BoardTitle(String);
54
55impl BoardTitle {
56 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
57 validate_required("title", value, MAX_BOARD_TITLE_LEN)?;
58 Ok(Self(value.to_string()))
59 }
60
61 pub fn as_str(&self) -> &str {
62 &self.0
63 }
64}
65
66/// The invite list, deduplicated and bounded. The creator is a participant by
67/// construction ([`Board::is_participant`]), so their presence in the list is
68/// neither required nor rejected.
69pub(crate) fn checked_participants(
70 participants: Vec<UserId>,
71) -> Result<Vec<UserId>, ValidationError> {
72 let mut unique: Vec<UserId> = Vec::with_capacity(participants.len());
73 for user in participants {
74 if !unique.contains(&user) {
75 unique.push(user);
76 }
77 }
78 if unique.len() > MAX_BOARD_PARTICIPANTS {
79 return Err(ValidationError::TooLong {
80 field: "participants",
81 max: MAX_BOARD_PARTICIPANTS,
82 got: unique.len(),
83 });
84 }
85 Ok(unique)
86}
87
88#[derive(Debug, Clone, sqlx::FromRow)]
89pub struct Board {
90 pub(crate) id: BoardId,
91 pub(crate) creator: UserId,
92 pub(crate) title: BoardTitle,
93 pub(crate) participants: Vec<UserId>,
94 pub(crate) locked: bool,
95 pub(crate) locked_by: Option<UserId>,
96 pub(crate) locked_at: Option<Timestamp>,
97 pub(crate) epoch: i64,
98 pub(crate) closed_at: Option<Timestamp>,
99 pub(crate) created_at: Timestamp,
100}
101
102impl Board {
103 pub fn get_id(&self) -> &BoardId {
104 &self.id
105 }
106
107 pub fn get_creator(&self) -> &UserId {
108 &self.creator
109 }
110
111 pub fn get_title(&self) -> &BoardTitle {
112 &self.title
113 }
114
115 pub fn get_participants(&self) -> &[UserId] {
116 &self.participants
117 }
118
119 pub fn is_locked(&self) -> bool {
120 self.locked
121 }
122
123 pub fn get_locked_by(&self) -> Option<&UserId> {
124 self.locked_by.as_ref()
125 }
126
127 pub fn get_locked_at(&self) -> Option<Timestamp> {
128 self.locked_at
129 }
130
131 pub fn get_epoch(&self) -> i64 {
132 self.epoch
133 }
134
135 pub fn get_closed_at(&self) -> Option<Timestamp> {
136 self.closed_at
137 }
138
139 pub fn get_created_at(&self) -> Timestamp {
140 self.created_at
141 }
142
143 /// May draw. The creator is always in, without being named on the list.
144 pub fn is_participant(&self, user: &UserId) -> bool {
145 &self.creator == user || self.participants.contains(user)
146 }
147
148 /// May clear, lock, close and delete. Nothing else is creator-only.
149 pub fn is_creator(&self, user: &UserId) -> bool {
150 &self.creator == user
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157 use crate::constant::MAX_BOARD_TITLE_LEN;
158
159 fn user(key: &str) -> UserId {
160 UserId::from_key(key)
161 }
162
163 /// A board row assembled in memory — the predicates under test are pure,
164 /// so no store is involved.
165 fn a_board() -> Board {
166 Board {
167 id: BoardId::from_key("0198f1a2-3b4c-7d5e-8f90-1a2b3c4d5e6f"),
168 creator: user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e"),
169 title: BoardTitle::try_new("Geometri").unwrap(),
170 participants: vec![user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f")],
171 locked: false,
172 locked_by: None,
173 locked_at: None,
174 epoch: 0,
175 closed_at: None,
176 created_at: Timestamp::now(),
177 }
178 }
179
180 #[test]
181 fn the_two_predicates_are_the_permission_model() {
182 let board = a_board();
183 // Creator: draws AND commands.
184 assert!(board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e")));
185 assert!(board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-aaaa2b3c4d5e")));
186 // Invited: draws only.
187 assert!(board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f")));
188 assert!(!board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f")));
189 // Stranger: neither.
190 assert!(!board.is_participant(&user("0198f1a2-3b4c-7d5e-8f90-cccc4d5e6f7a")));
191 assert!(!board.is_creator(&user("0198f1a2-3b4c-7d5e-8f90-cccc4d5e6f7a")));
192 }
193
194 #[test]
195 fn title_is_required_and_bounded() {
196 assert!(BoardTitle::try_new(" ").is_err());
197 assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN)).is_ok());
198 assert!(BoardTitle::try_new(&"x".repeat(MAX_BOARD_TITLE_LEN + 1)).is_err());
199 }
200
201 #[test]
202 fn participants_are_deduplicated_and_bounded() {
203 let one = user("0198f1a2-3b4c-7d5e-8f90-bbbb3c4d5e6f");
204 assert_eq!(checked_participants(vec![one, one]).unwrap().len(), 1);
205 // One over the ceiling is refused; each key must be a distinct
206 // *parseable* UUID, or the parser would collapse them all to nil.
207 let many = (0..=MAX_BOARD_PARTICIPANTS)
208 .map(|n| user(&format!("0198f1a2-3b4c-7d5e-8f90-{n:012x}")))
209 .collect();
210 assert!(checked_participants(many).is_err());
211 }
212}