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.rs597 lines, 23.3 KiBHistoryRawDownload
1//! The `board` table: whiteboard rooms and their rosters. Every write here is
2//! field-scoped `UPDATE … SET` — a stroke landing concurrently is moving the
3//! two counters this table's struct does not carry.
4
5use crate::constant::{MAX_BOARD_PARTICIPANTS, MAX_BOARDS_PER_CREATOR};
6use crate::database::{Database, tx_with_retry, unique_violation};
7use crate::db::page::PagedList;
8use crate::domain::board::{Board, BoardId, BoardTitle, checked_participants};
9use crate::domain::timestamp::Timestamp;
10use crate::domain::text_fold::{search_fold, search_fold_sql};
11use crate::domain::user::UserId;
12use crate::error::AppError;
13
14pub async fn create(
15 db: &Database,
16 creator: &UserId,
17 title: BoardTitle,
18 participants: Vec<UserId>,
19) -> Result<Board, AppError> {
20 let board = Board {
21 id: BoardId::generate(),
22 creator: *creator,
23 title,
24 participants: checked_participants(participants)?,
25 locked: false,
26 locked_by: None,
27 locked_at: None,
28 epoch: 0,
29 closed_at: None,
30 created_at: Timestamp::now(),
31 };
32 // The seat claim, the row and the roster are one statement (the
33 // `cap::claim_and_create` CTE, spelled out at its call site): a refused
34 // insert takes its own seat bump back, so the counter can never count a
35 // row that did not commit, and the roster can never trail the row. The
36 // `participants` array is aggregated from the roster CTE's RETURNING —
37 // the statement cannot see its own writes to `board_participant`.
38 let saved = sqlx::query_as!(
39 Board,
40 r#"WITH seat AS (
41 UPDATE app_user SET board_count = board_count + 1
42 WHERE id = $1 AND board_count < $2
43 RETURNING 1),
44 new_board AS (
45 INSERT INTO board (id, creator, title, locked, locked_by, locked_at,
46 epoch, closed_at, created_at)
47 SELECT $3, $1, $4, false, NULL, NULL, 0, NULL, $6
48 WHERE EXISTS (SELECT 1 FROM seat)
49 RETURNING id, creator, title, locked, locked_by, locked_at,
50 epoch, closed_at, created_at),
51 roster AS (
52 INSERT INTO board_participant (board, participant)
53 SELECT $3, t.x FROM unnest($5::uuid[]) AS t(x)
54 WHERE EXISTS (SELECT 1 FROM new_board)
55 RETURNING participant)
56 SELECT nb.id AS "id: BoardId", nb.creator AS "creator: UserId",
57 nb.title AS "title: BoardTitle",
58 COALESCE((SELECT array_agg(r.participant ORDER BY r.participant)
59 FROM roster r), '{}')
60 AS "participants!: Vec<UserId>",
61 nb.locked, nb.locked_by AS "locked_by: UserId",
62 nb.locked_at AS "locked_at: Timestamp", nb.epoch,
63 nb.closed_at AS "closed_at: Timestamp",
64 nb.created_at AS "created_at: Timestamp"
65 FROM new_board nb"#,
66 board.creator.uuid(),
67 MAX_BOARDS_PER_CREATOR,
68 board.id.uuid(),
69 board.title.as_str(),
70 &board
71 .participants
72 .iter()
73 .map(UserId::uuid)
74 .collect::<Vec<uuid::Uuid>>(),
75 board.created_at.as_millis()
76 )
77 .fetch_optional(db)
78 .await;
79 match saved {
80 Ok(Some(saved)) => Ok(saved),
81 // Full, or the creator's row is gone — the conditional write
82 // matches nothing either way.
83 Ok(None) => Err(AppError::Conflict(
84 "you have reached the limit on boards — delete one first",
85 )),
86 // The id is a freshly minted UUID on a table whose only UNIQUE index
87 // is its own primary key, so no rival can have aimed at it.
88 Err(err) if unique_violation(&err).is_some() => {
89 Err(AppError::Internal("board id collided".into()))
90 }
91 Err(err) => Err(err.into()),
92 }
93}
94
95/// The one board read: row columns plus the roster, re-assembled from
96/// `board_participant` (the array column is gone). The junction keeps no
97/// insertion order, so every reader sorts by participant and the wire list
98/// is deterministic.
99async fn read_row<'e, E>(db: E, id: &BoardId) -> Result<Option<Board>, AppError>
100where
101 E: sqlx::PgExecutor<'e>,
102{
103 let board = sqlx::query_as!(
104 Board,
105 r#"SELECT b.id AS "id: BoardId", b.creator AS "creator: UserId",
106 b.title AS "title: BoardTitle",
107 ARRAY(SELECT p.participant FROM board_participant p
108 WHERE p.board = b.id ORDER BY p.participant)
109 AS "participants!: Vec<UserId>",
110 b.locked, b.locked_by AS "locked_by: UserId",
111 b.locked_at AS "locked_at: Timestamp", b.epoch,
112 b.closed_at AS "closed_at: Timestamp",
113 b.created_at AS "created_at: Timestamp"
114 FROM board b WHERE b.id = $1"#,
115 id.uuid()
116 )
117 .fetch_optional(db)
118 .await?;
119 Ok(board)
120}
121
122pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> {
123 read_row(db, id).await
124}
125
126/// Every board `user` may open: the ones they created and the ones they
127/// were invited to. Newest first — the ids are monotonic, so `id` is the
128/// creation order.
129///
130/// `open` narrows by `closed_at`, and it means exactly that flag: a board
131/// that is locked, or full at its lifetime cap but never drawn on again, is
132/// never stamped and so reads as **open** — because it is. Only a creator's
133/// `/close` and the lifetime cap's own refusal ever stamp one.
134///
135/// `q` is an optional free-text needle over the title, folded case- and
136/// diacritic-insensitively on both sides ([`search_fold`] /
137/// [`search_fold_sql`]); a blank needle searches nothing.
138pub async fn list_for_user(
139 db: &Database,
140 user: &UserId,
141 open: Option<bool>,
142 q: Option<&str>,
143 limit: Option<i64>,
144 offset: i64,
145) -> Result<(Vec<Board>, i64), AppError> {
146 // A blank needle searches nothing, exactly like an absent one.
147 let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
148 let open_clause = match open {
149 Some(true) => " AND b.closed_at IS NULL",
150 Some(false) => " AND b.closed_at IS NOT NULL",
151 None => "",
152 };
153 // The needle rides the same fold on both sides (`position`, not `LIKE`,
154 // keeps `%` and `_` literal); `$1` and `$2` are always spent on the
155 // membership predicate, so the needle is `$3`.
156 let q_clause = match needle {
157 Some(_) => format!(" AND position($3 in {}) > 0", search_fold_sql("b.title")),
158 None => String::new(),
159 };
160 // `PagedList` wraps `from_where` in `SELECT * FROM (…)`, so the window
161 // is a whole derived table: the row columns plus the roster
162 // re-assembled from `board_participant`, and the membership half of the
163 // predicate as an `EXISTS` over it (the participant-side index covers
164 // it, as the GIN index once did).
165 let mut builder = PagedList::new(
166 format!(
167 "(SELECT b.id, b.creator, b.title,
168 ARRAY(SELECT p.participant FROM board_participant p
169 WHERE p.board = b.id ORDER BY p.participant) AS participants,
170 b.locked, b.locked_by, b.locked_at, b.epoch, b.closed_at, b.created_at
171 FROM board b
172 WHERE (b.creator = $1
173 OR EXISTS (SELECT 1 FROM board_participant bp
174 WHERE bp.board = b.id AND bp.participant = $2)){open_clause}{q_clause})"
175 ),
176 "ORDER BY id DESC",
177 )
178 .bind(user.uuid())
179 .bind(user.uuid());
180 if let Some(needle) = needle {
181 builder = builder.bind(needle);
182 }
183 builder.run::<Board>(limit, offset, db).await
184}
185
186/// Re-invite: the creator-driven roster replace. The write is the
187/// junction's — rows go in one transaction with the read-back, because the
188/// old single `UPDATE` both wrote the array and returned the row; a read
189/// issued apart from the write could answer a roster someone else had
190/// replaced in between.
191pub async fn set_participants(
192 db: &Database,
193 board: &Board,
194 participants: Vec<UserId>,
195) -> Result<Board, AppError> {
196 let participants = checked_participants(participants)?;
197 let ids: Vec<uuid::Uuid> = participants.iter().map(UserId::uuid).collect();
198 let id = board.id.clone();
199 tx_with_retry(db, true, async move |tx| {
200 sqlx::query!("DELETE FROM board_participant WHERE board = $1", id.uuid())
201 .execute(&mut *tx)
202 .await?;
203 sqlx::query!(
204 "INSERT INTO board_participant (board, participant)
205 SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)
206 ON CONFLICT DO NOTHING",
207 id.uuid(),
208 &ids,
209 )
210 .execute(&mut *tx)
211 .await?;
212 // The read-back is under the write path's own transaction: None here
213 // means the board vanished between the caller's read and this tx,
214 // which is the same 404 the old `UPDATE … RETURNING` produced.
215 read_row(&mut *tx, &id).await?.ok_or(AppError::NotFound)
216 })
217 .await
218}
219
220pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {
221 let updated = sqlx::query_as!(
222 Board,
223 r#"UPDATE board SET title = $2 WHERE id = $1
224 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
225 title AS "title: BoardTitle",
226 ARRAY(SELECT p.participant FROM board_participant p
227 WHERE p.board = board.id ORDER BY p.participant)
228 AS "participants!: Vec<UserId>", locked,
229 locked_by AS "locked_by: UserId",
230 locked_at AS "locked_at: Timestamp", epoch,
231 closed_at AS "closed_at: Timestamp",
232 created_at AS "created_at: Timestamp""#,
233 board.id.uuid(),
234 title.as_str()
235 )
236 .fetch_optional(db)
237 .await?;
238 one(updated)
239}
240
241/// Freeze or thaw drawing. `locked_by`/`locked_at` are cleared on unlock so
242/// the row never claims a lock that is not held.
243pub async fn set_locked(
244 db: &Database,
245 board: &Board,
246 locked: bool,
247 by: &UserId,
248) -> Result<Board, AppError> {
249 let now = Timestamp::now();
250 let updated = sqlx::query_as!(
251 Board,
252 r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1
253 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
254 title AS "title: BoardTitle",
255 ARRAY(SELECT p.participant FROM board_participant p
256 WHERE p.board = board.id ORDER BY p.participant)
257 AS "participants!: Vec<UserId>", locked,
258 locked_by AS "locked_by: UserId",
259 locked_at AS "locked_at: Timestamp", epoch,
260 closed_at AS "closed_at: Timestamp",
261 created_at AS "created_at: Timestamp""#,
262 board.id.uuid(),
263 locked,
264 locked.then(|| by.uuid()),
265 locked.then(|| now.as_millis())
266 )
267 .fetch_optional(db)
268 .await?;
269 one(updated)
270}
271
272/// Union a bulk invite's resolved ids into the roster — the atomic-union
273/// replacement for the old process-wide roster lock. The merge is `INSERT
274/// … ON CONFLICT DO NOTHING`, and the board row is locked (`FOR NO KEY
275/// UPDATE`) before the cap counts: that lock is what the old guarded array
276/// `UPDATE` got from its own row write, and it keeps the same property —
277/// of two concurrent invites the second waits, counts against the first's
278/// committed roster, and the cap refuses it — neither can drop the other's
279/// group.
280///
281/// `None` means the guard refused (or the board is gone): the roster was
282/// left exactly as it was, and the caller re-reads to pick the message.
283pub(crate) async fn invite_group(
284 db: &Database,
285 board: &BoardId,
286 invited: Vec<UserId>,
287) -> Result<Option<Board>, AppError> {
288 let invited: Vec<uuid::Uuid> = invited.iter().map(UserId::uuid).collect();
289 let board = board.clone();
290 tx_with_retry(db, true, async move |tx| {
291 // The serialization point; a vanished board refuses here, exactly
292 // like the old conditional `UPDATE` matching nothing.
293 let live = sqlx::query!(
294 "SELECT id FROM board WHERE id = $1 FOR NO KEY UPDATE",
295 board.uuid()
296 )
297 .fetch_optional(&mut *tx)
298 .await?;
299 if live.is_none() {
300 return Ok(None);
301 }
302 let would_be: i64 = sqlx::query_scalar!(
303 r#"SELECT ((SELECT count(*) FROM board_participant WHERE board = $1)
304 + (SELECT count(*) FROM unnest($2::uuid[]) AS t(x)
305 WHERE NOT EXISTS (SELECT 1 FROM board_participant bp
306 WHERE bp.board = $1 AND bp.participant = t.x)))
307 AS "filled!""#,
308 board.uuid(),
309 &invited,
310 )
311 .fetch_one(&mut *tx)
312 .await?;
313 if would_be > MAX_BOARD_PARTICIPANTS as i64 {
314 return Ok(None);
315 }
316 sqlx::query!(
317 "INSERT INTO board_participant (board, participant)
318 SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)
319 ON CONFLICT DO NOTHING",
320 board.uuid(),
321 &invited,
322 )
323 .execute(&mut *tx)
324 .await?;
325 read_row(&mut *tx, &board).await
326 })
327 .await
328}
329
330// The demotion sweep — stripping a user off every roster they are listed
331// on, deleting nothing, and handing the affected rooms back so the caller
332// can prompt them — lives in [`crate::service::user::set_role`], where
333// it commits with the role write that invalidates the membership.
334
335/// Retire the board: permanently read-only, history still readable.
336/// Idempotent by the `WHERE` — a second call matches nothing and the first
337/// stamp stands, which is what the stroke path's open-guard reads.
338pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
339 let closed = sqlx::query_as!(
340 Board,
341 r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL
342 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
343 title AS "title: BoardTitle",
344 ARRAY(SELECT p.participant FROM board_participant p
345 WHERE p.board = board.id ORDER BY p.participant)
346 AS "participants!: Vec<UserId>", locked,
347 locked_by AS "locked_by: UserId",
348 locked_at AS "locked_at: Timestamp", epoch,
349 closed_at AS "closed_at: Timestamp",
350 created_at AS "created_at: Timestamp""#,
351 board.id.uuid(),
352 Timestamp::now().as_millis()
353 )
354 .fetch_optional(db)
355 .await?;
356 match closed {
357 Some(board) => Ok(board),
358 // Already closed: the row is unchanged, so read it back rather
359 // than report a 404 for a board that plainly exists.
360 None => read(db, &board.id).await?.ok_or(AppError::NotFound),
361 }
362}
363
364/// Delete the board and give the creator's slot back in the *same*
365/// transaction — a release issued afterwards can be lost, and the counter
366/// would then ratchet the creator's limit shut forever.
367///
368/// The roster and the stroke cascade ride in that same transaction: the FK
369/// is NO ACTION, so the junction rows go before the board row they name,
370/// and the stroke delete is the one and only legitimate delete of
371/// `board_stroke` rows (a clear deletes nothing) — issued separately it
372/// could leave a board's whole history orphaned under a record that no
373/// longer exists.
374pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
375 tx_with_retry(db, true, async move |conn| {
376 sqlx::query!(
377 "DELETE FROM board_participant WHERE board = $1",
378 board.id.uuid()
379 )
380 .execute(&mut *conn)
381 .await?;
382 sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid())
383 .execute(&mut *conn)
384 .await?;
385 let gone = sqlx::query_as!(
386 Board,
387 r#"DELETE FROM board WHERE id = $1
388 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
389 title AS "title: BoardTitle",
390 ARRAY(SELECT p.participant FROM board_participant p
391 WHERE p.board = board.id ORDER BY p.participant)
392 AS "participants!: Vec<UserId>", locked,
393 locked_by AS "locked_by: UserId",
394 locked_at AS "locked_at: Timestamp", epoch,
395 closed_at AS "closed_at: Timestamp",
396 created_at AS "created_at: Timestamp""#,
397 board.id.uuid()
398 )
399 .fetch_optional(&mut *conn)
400 .await?;
401 let board = gone.ok_or(AppError::NotFound)?;
402 // Exactly one row was deleted above, so the release is one seat —
403 // the counter floor keeps a stray double-release from ratcheting
404 // the limit shut.
405 sqlx::query!(
406 "UPDATE app_user SET board_count = GREATEST(board_count - 1, 0) WHERE id = $1",
407 board.creator.uuid()
408 )
409 .execute(&mut *conn)
410 .await?;
411 Ok(board)
412 })
413 .await
414}
415
416fn one(board: Option<Board>) -> Result<Board, AppError> {
417 board.ok_or(AppError::NotFound)
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423 use crate::domain::board::BoardTitle;
424
425 /// A roster write lands, and a write against a board that vanished in
426 /// the meantime is a 404 — not a silent success.
427 #[tokio::test]
428 async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() {
429 let (db, _leases) = crate::database::init_test_db().await;
430 let creator = crate::db::class_member::tests::fixture_user(&db, "board-creator").await;
431 let board = create(
432 &db,
433 &creator,
434 BoardTitle::try_new("Geometri").unwrap(),
435 Vec::new(),
436 )
437 .await
438 .unwrap();
439
440 let retitled = set_title(&db, &board, BoardTitle::try_new("Cebir").unwrap())
441 .await
442 .unwrap();
443 assert_eq!(retitled.get_title().as_str(), "Cebir");
444
445 let locked = set_locked(&db, &board, true, &creator).await.unwrap();
446 assert!(locked.is_locked());
447 let member = crate::db::class_member::tests::fixture_user(&db, "board-member").await;
448 let roster = vec![member];
449 let re_rostered = set_participants(&db, &board, roster).await.unwrap();
450 assert_eq!(re_rostered.get_participants().len(), 1);
451
452 delete(&db, re_rostered).await.unwrap();
453 assert!(read(&db, board.get_id()).await.unwrap().is_none());
454 }
455
456 /// The seat and the row commit together: a create over the cap writes no
457 /// board row, and deleting a board hands the seat back.
458 #[tokio::test]
459 async fn the_cap_refuses_and_delete_releases_the_seat() {
460 let (db, _leases) = crate::database::init_test_db().await;
461 let creator = crate::db::class_member::tests::fixture_user(&db, "board-creator").await;
462 for index in 0..MAX_BOARDS_PER_CREATOR {
463 create(
464 &db,
465 &creator,
466 BoardTitle::try_new(&format!("b{index}")).unwrap(),
467 Vec::new(),
468 )
469 .await
470 .unwrap();
471 }
472 let over = create(
473 &db,
474 &creator,
475 BoardTitle::try_new("over").unwrap(),
476 Vec::new(),
477 )
478 .await;
479 assert!(matches!(over, Err(AppError::Conflict(_))));
480
481 let last = list_for_user(&db, &creator, None, None, None, 0)
482 .await
483 .unwrap()
484 .0
485 .into_iter()
486 .next()
487 .unwrap();
488 delete(&db, last).await.unwrap();
489 // The freed seat admits one more board.
490 let again = create(
491 &db,
492 &creator,
493 BoardTitle::try_new("again").unwrap(),
494 Vec::new(),
495 )
496 .await;
497 assert!(again.is_ok());
498 }
499
500 /// `q` narrows by title through the search fold (`geometri` finds
501 /// `Geometri`), composes with `open`, and pages after the filter
502 /// (`total` counts matches, not rows) — while the membership predicate
503 /// still scopes every row: a non-participant searching a real title
504 /// sees nothing.
505 #[tokio::test]
506 async fn q_searches_titles_and_composes_with_open() {
507 let (db, _leases) = crate::database::init_test_db().await;
508 let creator = crate::db::class_member::tests::fixture_user(&db, "q-board-kurucu").await;
509 let outsider = crate::db::class_member::tests::fixture_user(&db, "q-board-disari").await;
510
511 let open_hit = create(
512 &db,
513 &creator,
514 BoardTitle::try_new("Geometri Kampı").unwrap(),
515 Vec::new(),
516 )
517 .await
518 .unwrap();
519 create(
520 &db,
521 &creator,
522 BoardTitle::try_new("Cebir").unwrap(),
523 Vec::new(),
524 )
525 .await
526 .unwrap();
527 let closed_hit = create(
528 &db,
529 &creator,
530 BoardTitle::try_new("Geometri Kapanış").unwrap(),
531 Vec::new(),
532 )
533 .await
534 .unwrap();
535 close(&db, &closed_hit).await.unwrap();
536
537 // Absent and blank needles both see every board.
538 let (_, total) = list_for_user(&db, &creator, None, None, None, 0)
539 .await
540 .unwrap();
541 assert_eq!(total, 3);
542 let (_, total) = list_for_user(&db, &creator, None, Some(" "), None, 0)
543 .await
544 .unwrap();
545 assert_eq!(total, 3);
546
547 // Title hits through the fold, in both directions.
548 for needle in ["geometri", "GEOMETRİ"] {
549 let (hits, total) =
550 list_for_user(&db, &creator, None, Some(needle), None, 0)
551 .await
552 .unwrap();
553 assert_eq!(total, 2);
554 let keys: Vec<String> = hits
555 .iter()
556 .map(|board| board.get_id().key().to_string())
557 .collect();
558 assert!(keys.contains(&open_hit.get_id().key().to_string()));
559 assert!(keys.contains(&closed_hit.get_id().key().to_string()));
560 }
561
562 // Composes with `open`.
563 let (hits, total) =
564 list_for_user(&db, &creator, Some(true), Some("geometri"), None, 0)
565 .await
566 .unwrap();
567 assert_eq!(total, 1);
568 assert_eq!(hits[0].get_id().key().to_string(), open_hit.get_id().key().to_string());
569 let (_, total) = list_for_user(&db, &creator, Some(false), Some("geometri"), None, 0)
570 .await
571 .unwrap();
572 assert_eq!(total, 1);
573
574 // The window runs after the filter: `total` counts matches.
575 let (hits, total) = list_for_user(&db, &creator, None, Some("geometri"), Some(1), 0)
576 .await
577 .unwrap();
578 assert_eq!(total, 2);
579 assert_eq!(hits.len(), 1);
580
581 // A needle matching nothing: an empty page, not an error.
582 let (hits, total) = list_for_user(&db, &creator, None, Some("yok boyle bir tahta"), None, 0)
583 .await
584 .unwrap();
585 assert_eq!(total, 0);
586 assert!(hits.is_empty());
587
588 // The membership predicate still scopes the search: a non-participant
589 // searching a title that exists finds nothing.
590 let (hits, total) =
591 list_for_user(&db, &outsider, None, Some("geometri"), None, 0)
592 .await
593 .unwrap();
594 assert_eq!(total, 0);
595 assert!(hits.is_empty());
596 }
597}