diff --git a/README.md b/README.md index d6fbf87..34b8380 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,8 @@ present / absent / late / excused (students never self-mark), and a **roster report** shows who was expected and who missed. Registration lists fill seat by seat: teachers register students (never the other way round), staff register only themselves, an optional `capacity` caps the seats, and the list -closes the moment the event starts. Every event stays visible to everyone — +closes the moment the event starts (or, for an event with only an end time — +a pure signup deadline — the moment that end passes). Every event stays visible to everyone — the audience is a roster, not a wall. Marks are course-shaped (Google Classroom style): a teacher creates a course — kind **`course`** (a regular class) or **`study`** (a supervised study session — *etüt*; same @@ -423,7 +424,8 @@ A registration list fills through `POST /events/{id}/register`: teachers place students (a student never registers, not even themselves) and take seats only for themselves — registering another staff member is refused. Re-registering someone is a no-op, a full list is a `409`, and the list freezes the moment -the event starts (register and unregister both). Signup rows survive an +the event starts — or, when only `ends_at` is set (a pure signup deadline), +the moment it passes (register and unregister both). Signup rows survive an audience switch inertly and resurface if the event returns to the registration kind; deleting the event deletes them. Pre-existing hand-picked (`users`) audiences convert on boot: each listed user becomes a signup row credited to diff --git a/src/domain/exam.rs b/src/domain/exam.rs index b304eef..e176959 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -429,20 +429,25 @@ impl Exam { } /// Delete the exam and cascade-remove its result, attempt, question, and - /// answer rows. + /// answer rows — all in one transaction, so a failure can't leave an + /// emptied-out exam shell behind. pub async fn delete(self, db: &Database) -> Result { - db.query( - "BEGIN TRANSACTION; - DELETE exam_result WHERE exam = $ex; - DELETE exam_attempt WHERE exam = $ex; - DELETE exam_answer WHERE exam = $ex; - DELETE exam_question WHERE exam = $ex; - COMMIT TRANSACTION;", - ) - .bind(("ex", self.id.record())) - .await? - .check()?; - let deleted: Option = db.delete(self.id.record()).await?; + let mut result = db + .query( + "BEGIN TRANSACTION; + DELETE exam_result WHERE exam = $ex; + DELETE exam_attempt WHERE exam = $ex; + DELETE exam_answer WHERE exam = $ex; + DELETE exam_question WHERE exam = $ex; + DELETE $ex RETURN BEFORE; + COMMIT TRANSACTION;", + ) + .bind(("ex", self.id.record())) + .await? + .check()?; + // Statement slots count BEGIN and the child deletes: the exam's own + // DELETE is slot 5. + let deleted: Option = result.take::>(5)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index f6cabfd..ff8c393 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -197,9 +197,17 @@ impl ExamAttempt { match created { Ok(Some(created)) => Ok((created, true)), Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())), + // Only a still-running row proves the loss was a double-start + // collision (the winner's fresh sitting); a terminal or missing + // latest means the create genuinely failed — surface that instead + // of passing a finished sitting off as a resume. Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? { - Some(existing) => Ok((existing, false)), - None => Err(err.into()), + Some(existing) + if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress => + { + Ok((existing, false)) + } + _ => Err(err.into()), }, } } diff --git a/src/domain/note_file.rs b/src/domain/note_file.rs index fe0b731..2f76d26 100644 --- a/src/domain/note_file.rs +++ b/src/domain/note_file.rs @@ -6,13 +6,20 @@ //! before blob on delete); this module owns the rows. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use ulid::Ulid; -use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN}; +use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN, MAX_NOTE_FILES}; use crate::database::{Database, NOTE_FILE_TABLE}; use crate::domain::note::NoteId; use crate::error::{AppError, ValidationError}; +/// Serializes the files-per-note cap check against the insert (see +/// [`NoteFile::insert`]). The database is embedded — this process is the only +/// writer — so one process-wide lock is sufficient. +// ponytail: global lock, per-note locks if uploads ever see real contention. +static FILE_CAP_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct NoteFileId(RecordId); @@ -148,8 +155,19 @@ impl NoteFile { self.size } - /// Persist the row assembled by [`Self::new`]. + /// Persist the row assembled by [`Self::new`], refusing once its note + /// already holds [`MAX_NOTE_FILES`]. The count-then-create runs under + /// [`FILE_CAP_LOCK`] — a `BEGIN…COMMIT` can't enforce the cap because + /// SurrealDB doesn't conflict-check a cross-record count against a + /// concurrent insert (write-skew), the same story as + /// `Registration::register`. pub async fn insert(self, db: &Database) -> Result { + let _guard = FILE_CAP_LOCK.lock().await; + if Self::list_for(&self.note, db).await?.len() >= MAX_NOTE_FILES { + return Err(AppError::Conflict( + "the note already holds the maximum of 10 files — delete one first", + )); + } let created: Option = db.create(self.id.record()).content(self).await?; created.ok_or_else(|| AppError::Internal("failed to create note file".into())) } diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index 97d849d..ab44379 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -99,29 +99,43 @@ impl WorkEntry { .ok_or(AppError::Conflict("already checked in — check out first")) } - /// Close `user`'s open stint. The `DELETE .. RETURN BEFORE` is an atomic - /// take: of two racing check-outs exactly one receives the row (the other - /// gets the conflict). The closed stint is then re-filed under a ULID id, - /// freeing the open slot for the next check-in. + /// Close `user`'s open stint: atomically take the open row and re-file it + /// under a ULID id, freeing the open slot for the next check-in. Take and + /// re-file share one transaction — a failed re-file rolls the take back, + /// so a stint can never vanish half-closed. Of two racing check-outs + /// exactly one receives the row (the other gets the conflict). pub async fn check_out(user: &UserId, db: &Database) -> Result { let mut result = db - .query("DELETE $open RETURN BEFORE") + .query( + "BEGIN TRANSACTION; + LET $before = (DELETE $open RETURN BEFORE); + IF array::len($before) = 0 { THROW 'not_checked_in' }; + CREATE $closed CONTENT { + user: $before[0].user, + check_in: $before[0].check_in, + check_out: $out, + }; + COMMIT TRANSACTION;", + ) .bind(("open", WorkEntryId::open_for(user).record())) - .await? - .check()?; - let open = result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::Conflict("not checked in"))?; - - let closed = WorkEntry { - id: WorkEntryId::generate(), - user: open.user, - check_in: open.check_in, - check_out: Some(Timestamp::now()), - }; - let saved: Option = db.create(closed.id.record()).content(closed).await?; + .bind(("closed", WorkEntryId::generate().record())) + .bind(("out", Timestamp::now())) + .await?; + // An aborted transaction errors *every* slot, most with a generic + // "not executed" — only the THROW's own slot names the reason, so scan + // them all for the marker instead of trusting the first. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("not_checked_in")) + { + return Err(AppError::Conflict("not checked in")); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. + let saved: Option = result.take::>(3)?.into_iter().next(); saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) } diff --git a/src/web/events.rs b/src/web/events.rs index 0debaee..2550e63 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -656,8 +656,9 @@ struct RegistrationResponse { /// 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 (a timeless event never closes). Returns the seat -/// cap for the register path. +/// 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 { @@ -665,11 +666,12 @@ fn check_registration_open(event: &Event) -> Result, AppError> { reason: "this event does not take registrations", })); }; - if let Some(starts_at) = event.get_starts_at() - && Timestamp::now().as_millis() >= starts_at.as_millis() + // 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 when the event started", + "registration closed — the event has started or ended", )); } Ok(*capacity) @@ -680,7 +682,8 @@ fn check_registration_open(event: &Event) -> Result, AppError> { /// never register themselves; omit it to take a seat yourself (staff /// self-serve, so registering another teacher/manager is refused). Registering /// the same person twice is a no-op returning the existing seat. The list -/// closes when the event starts and refuses to grow past `capacity`. +/// closes when the event starts (or its ends_at-only deadline passes) and +/// refuses to grow past `capacity`. #[utoipa::path( post, path = "/{id}/register", @@ -694,7 +697,7 @@ fn check_registration_open(event: &Event) -> Result, AppError> { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), (status = 404, description = "Event not found", body = ErrorResponse), - (status = 409, description = "The event is full, or it already started", body = ErrorResponse), + (status = 409, description = "The event is full, or it already started or ended", body = ErrorResponse), ), )] async fn register( @@ -728,7 +731,17 @@ async fn register( let registration = Registration::register(&event_id, &target, user.get_id(), capacity, &st.db).await?; - let people = PersonRef::map_of(&[&target_user, &user]); + // 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. + let people = person_map( + [ + registration.get_user().clone(), + registration.get_registered_by().clone(), + ], + &st.db, + ) + .await?; Ok(Json(RegistrationResponse { event: registration.get_event().key().to_string(), user: PersonRef::resolve(&people, registration.get_user()), @@ -739,7 +752,8 @@ async fn register( /// Take a user off the signup list — the register rules mirrored: teacher+, /// students' seats or your own (another staff member's seat only if their /// account no longer exists), and only while the list is open (the event -/// hasn't started). Attendance already marked stays recorded. +/// hasn't started or, ends_at-only, passed). Attendance already marked stays +/// recorded. #[utoipa::path( delete, path = "/{id}/register/{user}", @@ -755,7 +769,7 @@ async fn register( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher, or the target is another staff member", body = ErrorResponse), (status = 404, description = "Event not found, or the user holds no seat", body = ErrorResponse), - (status = 409, description = "The event already started", body = ErrorResponse), + (status = 409, description = "The event already started or ended", body = ErrorResponse), ), )] async fn unregister( diff --git a/src/web/notes.rs b/src/web/notes.rs index 0701443..738ae0c 100644 --- a/src/web/notes.rs +++ b/src/web/notes.rs @@ -11,7 +11,7 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::{MAX_MAX_FILE_BYTES, MAX_NOTE_FILES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; use crate::domain::note_file::{FileContentType, FileName, NoteFile, NoteFileId}; use crate::domain::settings::Settings; @@ -283,11 +283,8 @@ async fn upload_file( let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; - if NoteFile::list_for(note.get_id(), &st.db).await?.len() >= MAX_NOTE_FILES { - return Err(AppError::Conflict( - "the note already holds the maximum of 10 files — delete one first", - )); - } + // The 10-file cap is enforced inside `NoteFile::insert` (count and create + // under one lock) — checking it here too would just race. let limit = Settings::load(&st.db).await?.get_max_file_bytes(); let mut field = loop { diff --git a/tests/integration.rs b/tests/integration.rs index b83564d..da83816 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -717,6 +717,59 @@ async fn note_file_count_is_capped() { assert_eq!(retry.status, StatusCode::CREATED); } +/// Regression: the 10-file cap was a bare count-then-write — concurrent +/// uploads all read the same pre-count and pushed a note past the cap (the +/// same write-skew as the event-capacity over-admit; SurrealDB transactions +/// don't conflict-check a cross-record count against an insert). The insert +/// now recounts under a lock, so the outcome is race-order independent: +/// exactly enough uploads win to land on the cap, the rest get the same 409 +/// as a sequential over-fill. +#[tokio::test] +async fn concurrent_uploads_never_exceed_the_file_cap() { + let app = mem_app().await; + let ali = login(&app, "ali").await; + let note = create_note(&app, &ali, "contested").await; + + for i in 0..8 { + let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; + assert_eq!(up.status, StatusCode::CREATED, "seed file {i}"); + } + + // Four racers for the two remaining slots. + let results = tokio::join!( + common::upload_file(&app, &ali, ¬e, "r0.txt", "", b"x"), + common::upload_file(&app, &ali, ¬e, "r1.txt", "", b"x"), + common::upload_file(&app, &ali, ¬e, "r2.txt", "", b"x"), + common::upload_file(&app, &ali, ¬e, "r3.txt", "", b"x"), + ); + let statuses = [ + results.0.status, + results.1.status, + results.2.status, + results.3.status, + ]; + for status in statuses { + assert!( + status == StatusCode::CREATED || status == StatusCode::CONFLICT, + "a lost cap race must be a 409, got {status}" + ); + } + + let list = send( + &app, + "GET", + &format!("/notes/{note}/files"), + Some(&ali), + None, + ) + .await; + assert_eq!( + common::total(&list.body), + 10, + "the cap must hold exactly under concurrency, statuses={statuses:?}" + ); +} + #[tokio::test] async fn note_file_upload_validation() { let app = mem_app().await; @@ -3467,6 +3520,13 @@ async fn re_registering_returns_the_seat_untouched() { second.body["registered_by"]["id"], ali_id, "re-registering must not rewrite who placed the student" ); + // Regression: the response used to resolve people only from {target, + // caller}, so the original registrar degraded to a bare ULID username. + assert_eq!( + second.body["registered_by"]["username"], "ali", + "the original registrar must resolve to a person, not a bare id" + ); + assert_eq!(second.body["user"]["username"], "veli"); } /// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose @@ -3580,10 +3640,41 @@ async fn event_registration_closes_at_start() { .await; assert_eq!(res.status, StatusCode::CONFLICT, "unregister freezes too"); - // A future or timeless event keeps its list open. + // Regression: an ends_at-only event (a pure signup deadline) used to stay + // open forever — the gate read starts_at alone. Ended 30s ago: inside the + // creation grace, but the list is closed. + let res = send( + &app, + "POST", + "/events", + Some(&ali), + Some(json!({ "title": "deadline passed", "ends_at": now - 30_000, + "audience": { "kind": "registration" } })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let ev = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/events/{ev}/register"), + Some(&ali), + Some(json!({ "user_id": veli_id })), + ) + .await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "an event whose end has passed takes no signups" + ); + + // A future or timeless event keeps its list open — a future signup + // deadline (ends_at only) included. for body in [ json!({ "title": "later", "starts_at": now + 3_600_000, "audience": { "kind": "registration" } }), + json!({ "title": "deadline ahead", "ends_at": now + 3_600_000, + "audience": { "kind": "registration" } }), json!({ "title": "whenever", "audience": { "kind": "registration" } }), ] { let res = send(&app, "POST", "/events", Some(&ali), Some(body)).await;