diff --git a/src/domain/event.rs b/src/domain/event.rs index c9efd61..352e068 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -192,6 +192,29 @@ impl Event { &self.creator == user } + /// The shared gate for touching a signup list: the event must carry the + /// registration audience, and the list must still be open — it closes the + /// moment the event starts, or, for an ends_at-only event (a pure signup + /// deadline), the moment that end passes (a truly timeless event never + /// closes). Returns the seat cap for the register path. + pub fn registration_capacity(&self) -> Result, AppError> { + let EventAudience::Registration { capacity } = &self.audience else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "audience", + reason: "this event does not take registrations", + })); + }; + // ends_at can't precede starts_at, so when both exist starts_at governs. + if let Some(closes_at) = self.starts_at.or(self.ends_at) + && Timestamp::now().as_millis() >= closes_at.as_millis() + { + return Err(AppError::Conflict( + "registration closed — the event has started or ended", + )); + } + Ok(*capacity) + } + pub async fn create( creator: &UserId, title: EventTitle, @@ -316,6 +339,55 @@ mod tests { } } + fn event_with( + audience: EventAudience, + starts_at: Option, + ends_at: Option, + ) -> Event { + Event { + id: EventId::generate(), + creator: UserId::from_key("u1"), + title: EventTitle::try_new("signup").unwrap(), + description: EventDescription::try_new("").unwrap(), + audience, + starts_at, + ends_at, + } + } + + #[tokio::test] + async fn registration_capacity_gates_and_echoes_cap() { + let open = |capacity| EventAudience::Registration { capacity }; + let past = Some(Timestamp::from_millis(Timestamp::now().as_millis() - 1)); + + assert!(matches!( + event_with(EventAudience::School, None, None).registration_capacity(), + Err(AppError::Validation(_)) + )); + assert_eq!( + event_with(open(None), None, None) + .registration_capacity() + .unwrap(), + None + ); + assert_eq!( + event_with(open(Some(30)), None, None) + .registration_capacity() + .unwrap(), + Some(30) + ); + // Started events close the list; an ends_at-only deadline in the past + // does too. + assert!(matches!( + event_with(open(Some(30)), past, None).registration_capacity(), + Err(AppError::Conflict(_)) + )); + assert!(matches!( + event_with(open(None), None, past).registration_capacity(), + Err(AppError::Conflict(_)) + )); + } + /// The database strips `NONE`-valued optional columns and the boot /// conversion writes a bare `{kind: 'registration'}` — an object with no /// `capacity` key at all must decode as an uncapped registration. diff --git a/src/domain/registration.rs b/src/domain/registration.rs index bdbfdc4..71b25bb 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -2,7 +2,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; use crate::database::{Database, REGISTRATION_TABLE}; -use crate::domain::event::EventId; +use crate::domain::event::{Event, EventId}; use crate::domain::user::UserId; use crate::error::AppError; @@ -71,22 +71,27 @@ impl Registration { &self.registered_by } - /// Register (idempotently) `user` onto `event`, refusing when a `capacity` + /// Register (idempotently) `user` onto `event`, refusing when a capacity /// cap is set and every seat is taken. Someone already listed gets their /// existing row back untouched — a true no-op that never counts against /// the cap and never rewrites who placed them. The whole check-then-write - /// runs under [`REGISTER_LOCK`], so a full event never over-admits. + /// runs under [`REGISTER_LOCK`], and the gate + cap are re-derived from a + /// fresh event read under that lock, so neither a racing registration nor + /// a concurrent capacity/audience/schedule PATCH can over-admit. pub async fn register( event: &EventId, user: &UserId, registered_by: &UserId, - capacity: Option, db: &Database, ) -> Result { let _guard = REGISTER_LOCK.lock().await; if let Some(existing) = Self::read_for_user(event, user, db).await? { return Ok(existing); } + let capacity = Event::read(event, db) + .await? + .ok_or(AppError::NotFound)? + .registration_capacity()?; if let Some(capacity) = capacity && Self::list_for_event(event, db).await?.len() as i64 >= capacity { diff --git a/src/web/events.rs b/src/web/events.rs index 2550e63..2e1ad50 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -654,29 +654,6 @@ struct RegistrationResponse { registered_by: PersonRef, } -/// The shared gate for touching a signup list: the event must carry the -/// registration audience, and the list must still be open — it closes the -/// moment the event starts, or, for an ends_at-only event (a pure signup -/// deadline), the moment that end passes (a truly timeless event never -/// closes). Returns the seat cap for the register path. -fn check_registration_open(event: &Event) -> Result, AppError> { - let EventAudience::Registration { capacity } = event.get_audience() else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "audience", - reason: "this event does not take registrations", - })); - }; - // ends_at can't precede starts_at, so when both exist starts_at governs. - if let Some(closes_at) = event.get_starts_at().or(event.get_ends_at()) - && Timestamp::now().as_millis() >= closes_at.as_millis() - { - return Err(AppError::Conflict( - "registration closed — the event has started or ended", - )); - } - Ok(*capacity) -} - /// Put a user on a registration-audience event's signup list. Requires /// teacher+. `user_id` must name a student — students are placed by staff and /// never register themselves; omit it to take a seat yourself (staff @@ -710,7 +687,9 @@ async fn register( let event = Event::read(&event_id, &st.db) .await? .ok_or(AppError::NotFound)?; - let capacity = check_registration_open(&event)?; + // Fast-fail gate; the authoritative re-check runs inside + // `Registration::register` under its lock. + event.registration_capacity()?; let target = match req.user_id { Some(ref key) => UserId::from_key(key), @@ -729,8 +708,7 @@ async fn register( )); } - let registration = - Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?; + let registration = Registration::register(&event_id, &target, user.get_id(), &st.db).await?; // Resolve from the row, not the request: a re-register returns the // existing seat, whose registered_by is the *original* placer — someone // the {target, caller} pair may not contain. @@ -781,7 +759,7 @@ async fn unregister( let event = Event::read(&event_id, &st.db) .await? .ok_or(AppError::NotFound)?; - check_registration_open(&event)?; + event.registration_capacity()?; let target = UserId::from_key(&target); // A deleted account's leftover seat is fair game for any teacher+; a