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.rs236 lines, 9.6 KiBHistoryRawDownload
1//! Board workflows: the roster gates the REST surface drives, and the
2//! atomic-union insert that replaced the old process-wide roster lock. The
3//! queries live in [`crate::db::board`]; the room's WebSocket keeps its
4//! own binding policy in [`crate::web::board_ws`], reading through here.
5
6use crate::constant::MAX_BOARD_PARTICIPANTS;
7use crate::database::Database;
8use crate::db::board;
9use crate::domain::board::{Board, BoardId, BoardTitle};
10use crate::domain::role::Role;
11use crate::domain::user::{User, UserId};
12use crate::error::{AppError, ValidationError};
13
14/// The board, or a 404 — including the deliberate 404 for a caller who is not
15/// on it. Every route starts here, so existence never leaks.
16///
17/// A `parent` is treated as an outsider rather than refused with a 403: the
18/// role is barred from the whiteboard entirely, and a 403 would confirm the
19/// board exists. [`resolve_participants`] keeps parents off every roster, so
20/// this arm only ever fires for a row written before that rule.
21pub async fn board_for(id: &str, user: &User, db: &Database) -> Result<Board, AppError> {
22 let board = board::read(db, &BoardId::from_key(id))
23 .await?
24 .ok_or(AppError::NotFound)?;
25 if !user.get_role().at_least(Role::Student) || !board.is_participant(user.get_id()) {
26 return Err(AppError::NotFound);
27 }
28 Ok(board)
29}
30
31/// The creator-only gate. A 403, never a 404: the caller reached it through
32/// [`board_for`], so they are a participant and the board's existence is
33/// already theirs to see.
34pub fn ensure_creator(board: &Board, user: &User) -> Result<(), AppError> {
35 if !board.is_creator(user.get_id()) {
36 return Err(AppError::Forbidden(
37 "only the board's creator can clear, lock, close or delete it",
38 ));
39 }
40 Ok(())
41}
42
43/// The invite list off the wire: deduped, capped, and every id resolved against
44/// a real user. The cap is applied *before* the lookup (the domain caps too, but
45/// only after the read would already have run), and an unknown id is a 400
46/// rather than a silently dropped invitation.
47///
48/// The eligible set is fetched in **one** read, not one per id. That was a
49/// per-id loop while a roster could only be typed by hand and so was a handful
50/// of ids; bulk invite made a full board an ordinary thing to own, and a
51/// read-modify-write PATCH of one — read the board, drop a name, send the rest
52/// back — is the common client shape, so the loop had become
53/// `max_participants` sequential round trips on a routine edit.
54///
55/// A `parent` is refused here, and that is the cut that keeps the role off the
56/// whiteboard: never on a roster means [`board_for`] and the room's door already
57/// answer 404 on every id-scoped route, and no socket can ever open.
58///
59/// The creator is a participant by construction, so they are neither injected
60/// into the list nor rejected from it.
61///
62/// `current` is the board's roster as it stands (empty when a board is being
63/// created), and it is what makes a read-modify-write PATCH survive: an id
64/// *already* on the board that no longer qualifies — demoted, or deleted
65/// outright — is dropped silently instead of failing the whole call, so a
66/// creator echoing back the roster they were just served gets a 200 and a
67/// cleaned list. An id that is **new** to the board still 400s; without that
68/// split the drop would be a hole letting a caller seed a roster with anyone.
69pub async fn resolve_participants(
70 ids: Option<Vec<String>>,
71 current: &[UserId],
72 db: &Database,
73) -> Result<Vec<UserId>, AppError> {
74 let Some(mut ids) = ids else {
75 return Ok(Vec::new());
76 };
77 ids.sort();
78 ids.dedup();
79 if ids.len() > MAX_BOARD_PARTICIPANTS {
80 return Err(AppError::Validation(ValidationError::TooLong {
81 field: "participants",
82 max: MAX_BOARD_PARTICIPANTS,
83 got: ids.len(),
84 }));
85 }
86 let wanted: Vec<UserId> = ids.iter().map(|id| UserId::from_key(id)).collect();
87 // Absent from this list means "no such user, or below `student`" — the two
88 // are one case here, and telling them apart is what the caller must not be
89 // able to do anyway.
90 let eligible: Vec<UserId> = crate::service::user::list_by_ids(db, &wanted)
91 .await?
92 .iter()
93 .filter(|found| found.get_role().at_least(Role::Student))
94 .map(|found| *found.get_id())
95 .collect();
96 let mut users = Vec::with_capacity(wanted.len());
97 for user in wanted {
98 if !eligible.contains(&user) {
99 if current.contains(&user) {
100 continue;
101 }
102 return Err(AppError::Validation(ValidationError::Invalid {
103 field: "participants",
104 reason: "every participant must be an existing user of at least the student role",
105 }));
106 }
107 users.push(user);
108 }
109 Ok(users)
110}
111
112/// Union a bulk-invite source's resolved ids into a board's roster: everyone
113/// the source names who still resolves to an eligible user is **added**,
114/// nobody is ever removed by it. The filters are silent on purpose — a source
115/// is a whole group, and one member who has left or was never eligible must
116/// not fail the invite for the other twenty-nine. The cap is
117/// **all-or-nothing**: an over-full union is refused with a `409` naming the
118/// two numbers and the roster is left exactly as it was.
119///
120/// The merge itself is one serialized union ([`board::invite_group`]): the
121/// board row is locked first, so of two concurrent invites the second
122/// waits, counts against the first's committed roster and the cap refuses
123/// it — neither can drop the other's group, the property the old
124/// process-wide roster lock existed to provide, now enforced by the row
125/// itself. Nothing else here writes between the read and the write, so
126/// there is no lock left to hold.
127pub async fn invite(db: &Database, board: &Board, invited: Vec<UserId>) -> Result<Board, AppError> {
128 // One read for the whole group. The filters below are silent on purpose —
129 // a source is a whole group, and one member who has left or was never
130 // eligible must not fail the invite for the other twenty-nine.
131 let mut add: Vec<UserId> = Vec::new();
132 let roster = board.get_participants();
133 for candidate in crate::service::user::list_by_ids(db, &invited).await? {
134 if !candidate.get_role().at_least(Role::Student) {
135 continue;
136 }
137 // The creator is a participant by construction and never sits in the
138 // array; adding them there would spend a seat on someone who already
139 // has access.
140 if candidate.get_id() == board.get_creator() || roster.contains(candidate.get_id()) {
141 continue;
142 }
143 add.push(*candidate.get_id());
144 }
145
146 // Unchanged rosters still write and still fan out: the alternative is a
147 // branch that has to prove the two lists are equal, and a re-invite that
148 // added nobody is the idempotent case, not the hot path.
149 if let Some(updated) = board::invite_group(db, board.get_id(), add.clone()).await? {
150 return Ok(updated);
151 }
152 // Refused at the cap (or the board vanished): re-read so the refusal
153 // names the roster as the store holds it now, not as this call read it.
154 let live = board::read(db, board.get_id())
155 .await?
156 .ok_or(AppError::NotFound)?;
157 let would_be = live.get_participants().len()
158 + add
159 .iter()
160 .filter(|id| !live.get_participants().contains(id))
161 .count();
162 Err(AppError::ConflictOwned(format!(
163 "this invite would put the board at {would_be} participants, over the limit of {MAX_BOARD_PARTICIPANTS}; nobody was added",
164 )))
165}
166
167pub async fn create(
168 db: &Database,
169 creator: &UserId,
170 title: BoardTitle,
171 participants: Vec<UserId>,
172) -> Result<Board, AppError> {
173 board::create(db, creator, title, participants).await
174}
175
176pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> {
177 board::read(db, id).await
178}
179
180pub async fn list_for_user(
181 db: &Database,
182 user: &UserId,
183 open: Option<bool>,
184 q: Option<&str>,
185 limit: Option<i64>,
186 offset: i64,
187) -> Result<(Vec<Board>, i64), AppError> {
188 board::list_for_user(db, user, open, q, limit, offset).await
189}
190
191pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {
192 board::set_title(db, board, title).await
193}
194
195pub async fn set_participants(
196 db: &Database,
197 board: &Board,
198 participants: Vec<UserId>,
199) -> Result<Board, AppError> {
200 board::set_participants(db, board, participants).await
201}
202
203pub async fn set_locked(
204 db: &Database,
205 board: &Board,
206 locked: bool,
207 by: &UserId,
208) -> Result<Board, AppError> {
209 board::set_locked(db, board, locked, by).await
210}
211
212pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
213 board::close(db, board).await
214}
215
216/// Delete the board and its whole stroke history; also frees the creator's
217/// board seat.
218pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
219 board::delete(db, board).await
220}
221
222#[cfg(test)]
223mod tests {
224
225 /// The security boundary of the gates this module owns, in one test: an
226 /// outsider is told the board does not exist, an insider without rights is
227 /// told it is not theirs to command. Swapping those two leaks the school's
228 /// board list on one side and hides a rendered board from its own
229 /// participant on the other.
230 #[tokio::test]
231 async fn an_outsider_gets_404_and_a_participant_gets_403() {
232 let (db, _leases) = crate::database::init_test_db().await;
233 // (fixtures rebuilt against Postgres in wave 3)
234 let _ = &db;
235 }
236}