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_stroke.rs367 lines, 15.3 KiBHistoryRawDownload
1//! The `board_stroke` table: every mark a board ever carried, plus the `clear`
2//! markers that index its epochs, and the board's two stroke counters — all
3//! written through the guarded claims in here and nowhere else.
4
5use crate::constant::{
6 BOARD_REPLAY_CHUNK, MAX_BOARD_STROKES, MAX_EPOCH_STROKES, MAX_STROKE_PAYLOAD_LEN,
7};
8use crate::database::{Database, tx_with_retry};
9use crate::db::cap;
10use crate::db::page::PagedList;
11use crate::domain::board::{Board, BoardId, BoardTitle};
12use crate::domain::board_stroke::{
13 BOARD_CLOSED, BOARD_MOVED, BoardStroke, BoardStrokeId, CANVAS_BLANK, CLEAR_REFUSED, EPOCH_FULL,
14 KIND_CLEAR, KIND_STROKE, NOT_THE_CREATOR, state_refusal,
15};
16use crate::domain::timestamp::Timestamp;
17use crate::domain::user::UserId;
18use crate::error::AppError;
19use crate::validate::validate_required;
20
21/// Append one mark to `board`'s current `epoch`.
22///
23/// Both stroke counters and the row commit together or not at all: the
24/// resettable epoch counter, the lifetime counter, and the open-board guard
25/// are one conditional write (the `cap::claim_two_when_and_create` recipe —
26/// the lifetime cap's conditions first, both counters bumped by the single
27/// `UPDATE` — spelled out at its call site), so a locked or closed board can
28/// never be drawn on by a writer that read it a moment earlier.
29///
30/// `epoch` rides in that guard too. Without it a clear landing between the
31/// caller's board read and this write filed the row under the epoch that
32/// just ended while its increment counted against the *new* epoch's
33/// counter — one race, two markers corrupted for good (the closed one short
34/// by a stroke, the next one claiming a stroke that is not there), and
35/// markers are never rewritten. Now such a stroke is refused instead.
36pub async fn append(
37 db: &Database,
38 board: &BoardId,
39 author: &UserId,
40 payload: &str,
41 epoch: i64,
42) -> Result<BoardStroke, AppError> {
43 validate_required("payload", payload, MAX_STROKE_PAYLOAD_LEN)?;
44 let saved = sqlx::query_as!(
45 BoardStroke,
46 r#"WITH bump AS (
47 UPDATE board
48 SET epoch_stroke_count = epoch_stroke_count + 1,
49 total_stroke_count = total_stroke_count + 1
50 WHERE id = $1
51 AND total_stroke_count < $2
52 AND locked = false AND closed_at IS NULL
53 AND epoch = $3
54 AND epoch_stroke_count < $4
55 RETURNING 1)
56 INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at)
57 SELECT $5, $1, $6, $7, $8, NULL, $3, $9
58 WHERE EXISTS (SELECT 1 FROM bump)
59 RETURNING id AS "id: BoardStrokeId", board AS "board: BoardId",
60 author AS "author: UserId", kind, payload, count, epoch,
61 created_at AS "created_at: Timestamp""#,
62 board.uuid(),
63 MAX_BOARD_STROKES,
64 epoch,
65 MAX_EPOCH_STROKES,
66 BoardStrokeId::generate().uuid(),
67 author.uuid(),
68 KIND_STROKE,
69 payload,
70 Timestamp::now().as_millis()
71 )
72 .fetch_optional(db)
73 .await?;
74 match saved {
75 Some(stroke) => Ok(stroke),
76 // Zero rows means "lifetime full, guard failed, board gone, or soft
77 // full" — one marker, as the recipe keeps it. The re-read below maps
78 // them with `cap::full_kind` semantics: the terminal cap outranks
79 // the recoverable one.
80 None => Err(why_refused(db, board).await?),
81 }
82}
83
84/// The one place `closed` is ordered above `locked` lives in
85/// [`state_refusal`]; both refusal paths re-read the board and
86/// ask it.
87async fn why_refused(db: &Database, board: &BoardId) -> Result<AppError, AppError> {
88 let board = crate::db::board::read(db, board)
89 .await?
90 .ok_or(AppError::NotFound)?;
91 if let Some(refusal) = state_refusal(&board) {
92 return Ok(AppError::Conflict(refusal));
93 }
94 // Neither flag, so the counters have to say so *themselves* — this is
95 // [`cap::full_kind`]'s mapping, read off the live row: soft full with
96 // lifetime room is the recoverable `EPOCH_FULL`. A board that was
97 // locked (or a clear that moved the epoch) when the claim ran and is
98 // open again now must not be stamped read-only at one stroke of a
99 // 50 000 budget — irreversibly, with no reopen — so only a re-read that
100 // *proves* the lifetime counter is spent may stamp `closed_at`.
101 let (epoch_count, total_count): (i64, i64) = sqlx::query!(
102 r#"SELECT epoch_stroke_count AS "epoch_count: i64",
103 total_stroke_count AS "total_count: i64"
104 FROM board WHERE id = $1"#,
105 board.get_id().uuid()
106 )
107 .fetch_one(db)
108 .await
109 .map(|row| (row.epoch_count, row.total_count))?;
110 if matches!(
111 cap::full_kind(
112 epoch_count,
113 MAX_EPOCH_STROKES,
114 total_count,
115 MAX_BOARD_STROKES
116 ),
117 cap::FullKind::Soft
118 ) {
119 return Ok(AppError::Conflict(EPOCH_FULL));
120 }
121 if total_count < MAX_BOARD_STROKES {
122 return Ok(AppError::Conflict(BOARD_MOVED));
123 }
124 // `Board::close` is the one-way idempotent stamp: a second append takes
125 // this branch too and leaves the first `closed_at` standing.
126 crate::db::board::close(db, &board).await?;
127 Ok(AppError::Conflict(BOARD_CLOSED))
128}
129
130/// End the current epoch: the canvas empties, the history does not.
131///
132/// The bump and the marker are one transaction, because the marker carries
133/// the epoch's final count — written apart, a crash between them would
134/// leave an epoch no marker indexes, and the playback would silently join
135/// two sessions into one.
136///
137/// **The marker pays the lifetime counter.** It is a real `board_stroke`
138/// row, so a marker that claimed nothing left `total_stroke_count` counting
139/// strokes *drawn* rather than rows *stored*, and `MAX_BOARD_STROKES`
140/// stopped bounding the table. Charged here, the counter is exactly the row
141/// count again — the transaction takes the board row's write lock (`SELECT
142/// … FOR UPDATE`) and reads the epoch and its count from the locked row, so
143/// the increment cannot be split off from the marker it pays for, and a
144/// stroke claiming under a concurrent writer either lands before this read
145/// or waits for this commit — never inside it.
146///
147/// **A blank canvas cannot be cleared.** Without it every call minted a row
148/// for free, one per press of a button the creator can hold down. Requiring
149/// the epoch counter to be non-zero pays for each marker with at least one
150/// stroke it closes — and "there is nothing on this canvas to clear" is the
151/// honest answer to the call it refuses. The epochs index keeps its meaning
152/// too: no zero-stroke epoch can enter it.
153///
154/// **A locked board cannot be cleared.** The lock is the creator's own
155/// pause on the canvas, and it holds against every write to it including
156/// theirs — the guard is the same condition the stroke path claims under,
157/// so "locked" means one thing everywhere. The cost is accepted: a locked
158/// board sitting at `MAX_EPOCH_STROKES` is recovered by unlock, clear,
159/// relock.
160///
161/// The marker's own increment is not capped: the last stroke of a board's
162/// budget may be closed by a marker, so a board holds at most
163/// `MAX_BOARD_STROKES + 1` rows. Capping it would refuse the clear that
164/// files the final epoch in the index, which is the one clear the history
165/// needs.
166pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardStroke, AppError> {
167 // Owned captures (`Send` rule of `tx_with_retry` closures).
168 let board = board.clone();
169 let by = *by;
170 tx_with_retry(db, false, async move |conn| {
171 // The pre-image, under the row's write lock: the epoch the marker
172 // closes, the count it carries, and the guards it must satisfy all
173 // come from this read, and nothing interlocks between it and the
174 // guarded bump below.
175 let live = sqlx::query_as!(
176 Board,
177 r#"SELECT id AS "id: BoardId", creator AS "creator: UserId",
178 title AS "title: BoardTitle",
179 ARRAY(SELECT p.participant FROM board_participant p
180 WHERE p.board = board.id ORDER BY p.participant)
181 AS "participants!: Vec<UserId>", locked,
182 locked_by AS "locked_by: UserId",
183 locked_at AS "locked_at: Timestamp", epoch,
184 closed_at AS "closed_at: Timestamp",
185 created_at AS "created_at: Timestamp"
186 FROM board WHERE id = $1 FOR UPDATE"#,
187 board.uuid()
188 )
189 .fetch_optional(&mut *conn)
190 .await?
191 .ok_or(AppError::NotFound)?;
192 // Refusal precedence, the old THROW-then-reread order preserved
193 // against the locked row: the terminal answer outranks the caller's
194 // identity, and identity outranks the recoverable pause.
195 if let Some(BOARD_CLOSED) = state_refusal(&live) {
196 return Err(AppError::Conflict(BOARD_CLOSED));
197 }
198 if !live.is_creator(&by) {
199 return Err(AppError::Forbidden(NOT_THE_CREATOR));
200 }
201 if let Some(refusal) = state_refusal(&live) {
202 return Err(AppError::Conflict(refusal));
203 }
204 let (epoch, epoch_count): (i64, i64) = sqlx::query!(
205 r#"SELECT epoch AS "epoch: i64", epoch_stroke_count AS "epoch_count: i64"
206 FROM board WHERE id = $1"#,
207 board.uuid()
208 )
209 .fetch_one(&mut *conn)
210 .await
211 .map(|row| (row.epoch, row.epoch_count))?;
212 if epoch_count == 0 {
213 return Err(AppError::Conflict(CANVAS_BLANK));
214 }
215 // The bump itself is still guarded — the row lock already
216 // guarantees these hold, so a clear can never land on a state it
217 // did not read.
218 let bumped = sqlx::query!(
219 r#"UPDATE board
220 SET epoch = epoch + 1,
221 epoch_stroke_count = 0,
222 total_stroke_count = total_stroke_count + 1
223 WHERE id = $1 AND epoch = $2 AND epoch_stroke_count = $3"#,
224 board.uuid(),
225 epoch,
226 epoch_count
227 )
228 .execute(&mut *conn)
229 .await?;
230 if bumped.rows_affected() != 1 {
231 // Unreachable under the row lock; the text is the old
232 // refusal marker, kept for the audit trail.
233 return Err(AppError::Internal(CLEAR_REFUSED.to_string()));
234 }
235 let marker = sqlx::query_as!(
236 BoardStroke,
237 r#"INSERT INTO board_stroke (id, board, author, kind, payload, count, epoch, created_at)
238 VALUES ($1, $2, $3, $4, NULL, $5, $6, $7)
239 RETURNING id AS "id: BoardStrokeId", board AS "board: BoardId",
240 author AS "author: UserId", kind, payload, count, epoch,
241 created_at AS "created_at: Timestamp""#,
242 BoardStrokeId::generate().uuid(),
243 board.uuid(),
244 by.uuid(),
245 KIND_CLEAR,
246 epoch_count,
247 epoch,
248 Timestamp::now().as_millis()
249 )
250 .fetch_one(&mut *conn)
251 .await?;
252 Ok(marker)
253 })
254 .await
255}
256
257/// What a joining socket draws: the current epoch's marks only, in mint
258/// order, one [`BOARD_REPLAY_CHUNK`] at a time.
259///
260/// Paged by `id`, never `created_at` — a millisecond stamp has ties by
261/// construction, and the UUIDv7 monotonic time field is exactly what breaks
262/// them. `after` is the key of the last stroke already drawn; a key that
263/// parses as no UUID reads as the nil id, which every real stroke sorts
264/// above — the same full replay a cursor from before the epoch would get.
265pub async fn replay_current(
266 db: &Database,
267 board: &BoardId,
268 epoch: i64,
269 after: Option<&str>,
270) -> Result<Vec<BoardStroke>, AppError> {
271 let chunk = BOARD_REPLAY_CHUNK as i64;
272 match after.map(BoardStrokeId::from_key) {
273 Some(after) => Ok(sqlx::query_as!(
274 BoardStroke,
275 r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId",
276 author AS "author: UserId", kind, payload, count, epoch,
277 created_at AS "created_at: Timestamp"
278 FROM board_stroke
279 WHERE board = $1 AND epoch = $2 AND kind = $3 AND id > $4
280 ORDER BY id LIMIT $5"#,
281 board.uuid(),
282 epoch,
283 KIND_STROKE,
284 after.uuid(),
285 chunk
286 )
287 .fetch_all(db)
288 .await?),
289 None => Ok(sqlx::query_as!(
290 BoardStroke,
291 r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId",
292 author AS "author: UserId", kind, payload, count, epoch,
293 created_at AS "created_at: Timestamp"
294 FROM board_stroke
295 WHERE board = $1 AND epoch = $2 AND kind = $3
296 ORDER BY id LIMIT $4"#,
297 board.uuid(),
298 epoch,
299 KIND_STROKE,
300 chunk
301 )
302 .fetch_all(db)
303 .await?),
304 }
305}
306
307/// The whole log, oldest first — every epoch, or one named epoch. Both
308/// kinds of row come back: the `clear` markers are what tell a reader where
309/// one epoch ended and the next began.
310///
311/// `marks_only` drops the markers, which is what the *live canvas* wants:
312/// the current epoch holds no marker by construction, except in the one
313/// race where a clear commits between the board read and this read and
314/// files its marker under the epoch just named. The room's replay filters
315/// to `kind = 'stroke'` ([`replay_current`]), so without this the two
316/// views disagree in exactly that window.
317pub async fn history(
318 db: &Database,
319 board: &BoardId,
320 epoch: Option<i64>,
321 marks_only: bool,
322 limit: Option<i64>,
323 offset: i64,
324) -> Result<(Vec<BoardStroke>, i64), AppError> {
325 // The builder binds positionally in call order, so each optional clause
326 // takes the placeholder number its position in the bind sequence gives
327 // it — epoch (when present) is always $2, the marker filter $3 only
328 // when the epoch clause is there too.
329 let (scope, kinds) = match (epoch.is_some(), marks_only) {
330 (true, true) => (" AND epoch = $2", " AND kind != $3"),
331 (true, false) => (" AND epoch = $2", ""),
332 (false, true) => ("", " AND kind != $2"),
333 (false, false) => ("", ""),
334 };
335 let mut list = PagedList::new(
336 format!("board_stroke WHERE board = $1{scope}{kinds}"),
337 "ORDER BY id",
338 )
339 .bind(board.uuid());
340 if let Some(epoch) = epoch {
341 list = list.bind(epoch);
342 }
343 if marks_only {
344 list = list.bind(KIND_CLEAR.to_string());
345 }
346 list.run::<BoardStroke>(limit, offset, db).await
347}
348
349/// The epoch index: every `clear` marker this board has, oldest first.
350pub async fn epochs(db: &Database, board: &BoardId) -> Result<Vec<BoardStroke>, AppError> {
351 Ok(sqlx::query_as!(
352 BoardStroke,
353 r#"SELECT id AS "id: BoardStrokeId", board AS "board: BoardId",
354 author AS "author: UserId", kind, payload, count, epoch,
355 created_at AS "created_at: Timestamp"
356 FROM board_stroke WHERE board = $1 AND kind = $2 ORDER BY id"#,
357 board.uuid(),
358 KIND_CLEAR
359 )
360 .fetch_all(db)
361 .await?)
362}
363
364#[cfg(test)]
365mod tests {
366 // Rebuilt against Postgres in wave 3 (the fixtures were raw SurrealQL).
367}