diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index c06c4dd..7189d4f 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -7,6 +7,7 @@ use crate::constant::{ use crate::database::{Database, EXAM_QUESTION_TABLE}; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; +use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; @@ -15,8 +16,12 @@ use crate::validate::{validate_question_kind, validate_question_points, validate pub struct ExamQuestionId(RecordId); impl ExamQuestionId { + /// Minted from the process-wide monotonic generator, not `Ulid::new()`: the + /// id *is* the question's presentation order ([`ExamQuestion::list_for_exam`] + /// sorts `id ASC`), and a random low half scrambles a burst of saves that + /// lands inside one millisecond. pub fn generate() -> Self { - Self(RecordId::new(EXAM_QUESTION_TABLE, Ulid::new().to_string())) + Self(RecordId::new(EXAM_QUESTION_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -109,6 +114,9 @@ impl ChoiceText { pub struct ChoiceId(String); impl ChoiceId { + /// Plain `Ulid::new()` deliberately: options are ordered by their position + /// in the stored `Vec`, never by id, so nothing here reads the id as a + /// clock — it only has to be unique. fn generate() -> Self { Self(Ulid::new().to_string()) } @@ -546,6 +554,21 @@ mod tests { QuestionSpec::try_new(kind("choice"), choices, correct.map(str::to_string), &[]) } + /// A teacher saving several questions back to back gets them back in that + /// order: `list_for_exam` sorts `id ASC`, so the ids minted inside one + /// millisecond have to sort in mint order. Revert `generate` to + /// `Ulid::new()` and this fails — the low 80 bits are redrawn per id, so a + /// same-tick burst comes out shuffled. + #[tokio::test] + async fn ids_sort_in_creation_order() { + let ids: Vec = (0..500) + .map(|_| ExamQuestionId::generate().key().to_string()) + .collect(); + let mut sorted = ids.clone(); + sorted.sort(); + assert_eq!(ids, sorted); + } + #[tokio::test] async fn text_is_required() { assert!(QuestionText::try_new("What is 2 + 2?").is_ok());