diff --git a/src/constant.rs b/src/constant.rs index f110b7d..9c2aa75 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -85,6 +85,19 @@ pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; pub const MAX_SUBJECT_NAME_LEN: usize = 200; pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000; +pub const MAX_HOMEWORK_TITLE_LEN: usize = 200; +pub const MAX_HOMEWORK_DESCRIPTION_LEN: usize = 2_000; + +/// A homework submission's optional free-text note, sent alongside its files. +pub const MAX_HOMEWORK_TEXT_LEN: usize = 5_000; + +/// How many files one homework submission may carry. +pub const MAX_HOMEWORK_FILES_PER_SUBMISSION: usize = 10; + +/// How many students a homework may be narrowed to. The whole-course default +/// carries no assigned list at all, so this caps only an explicit subset. +pub const MAX_HOMEWORK_ASSIGNED: usize = 200; + /// The default attendance states, and also the mandatory core: a school may /// add its own statuses via `PATCH /settings`, but these four can never be /// removed — the attendance rate's semantics are defined over them. @@ -133,6 +146,13 @@ pub const COURSE_KINDS: [&str; 3] = ["course", "study", "club"]; /// exam with no mode at all is an offline-graded draft and cannot be sat. pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"]; +/// The only accepted homework grades. `done`: submitted and complete; +/// `incomplete`: submitted but lacking; `missing`: not done. A teacher-set +/// `missing` is a deliberate verdict, distinct from the roster's *computed* +/// missing (unsubmitted past due). The `HomeworkStatus` newtype enforces the +/// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`. +pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"]; + /// Inclusive bounds for an exam's per-attempt duration, milliseconds /// (1 minute to 24 hours). Required for `async`, optional for `open`. pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; diff --git a/src/database.rs b/src/database.rs index cc39e98..bf90923 100644 --- a/src/database.rs +++ b/src/database.rs @@ -50,6 +50,10 @@ pub const TERM_TABLE: &str = "term"; pub const SUBJECT_TABLE: &str = "subject"; pub const POOL_QUESTION_TABLE: &str = "pool_question"; pub const SOLUTION_TABLE: &str = "solution"; +pub const HOMEWORK_TABLE: &str = "homework"; +pub const HOMEWORK_SUBMISSION_TABLE: &str = "homework_submission"; +pub const HOMEWORK_FILE_TABLE: &str = "homework_file"; +pub const HOMEWORK_RESULT_TABLE: &str = "homework_result"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the @@ -307,6 +311,50 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; DEFINE FIELD IF NOT EXISTS max_file_bytes ON settings TYPE option; + + -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students + -- submit files + optional text, a teacher grades a status + optional mark. + -- `course`/`created_by`/`created_at` are READONLY (a homework never moves + -- course, and stamps never rewrite); `subject` is NOT — it is re-taggable + -- via PATCH. `assigned` NONE/empty means the whole course. No BACKFILL: the + -- tables are new, so the whole migration stays additive and idempotent. + DEFINE TABLE IF NOT EXISTS homework SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON homework TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS subject ON homework TYPE record; + DEFINE FIELD IF NOT EXISTS title ON homework TYPE string; + DEFINE FIELD IF NOT EXISTS description ON homework TYPE option; + DEFINE FIELD IF NOT EXISTS due_at ON homework TYPE int; + DEFINE FIELD IF NOT EXISTS assigned ON homework TYPE option>>; + DEFINE FIELD IF NOT EXISTS assigned[*] ON homework TYPE record; + DEFINE FIELD IF NOT EXISTS created_by ON homework TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON homework TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course; + + DEFINE TABLE IF NOT EXISTS homework_submission SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS homework ON homework_submission TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS user ON homework_submission TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS text ON homework_submission TYPE option; + DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int; + DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; + + DEFINE TABLE IF NOT EXISTS homework_file SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS submission ON homework_file TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS name ON homework_file TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON homework_file TYPE string; + DEFINE FIELD IF NOT EXISTS size ON homework_file TYPE int; + DEFINE FIELD IF NOT EXISTS file ON homework_file TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON homework_file TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission; + + DEFINE TABLE IF NOT EXISTS homework_result SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS homework ON homework_result TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS user ON homework_result TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS status ON homework_result TYPE string; + DEFINE FIELD IF NOT EXISTS mark ON homework_result TYPE option; + DEFINE FIELD IF NOT EXISTS graded_by ON homework_result TYPE record; + DEFINE FIELD IF NOT EXISTS created_at ON homework_result TYPE int; + DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework; "; /// Data backfills for rows written by older binaries. Runs *after* (and apart diff --git a/src/domain/homework.rs b/src/domain/homework.rs new file mode 100644 index 0000000..f49e162 --- /dev/null +++ b/src/domain/homework.rs @@ -0,0 +1,303 @@ +//! A homework assignment: a teacher hands it out per course, optionally +//! narrowed to a subset of the enrolled students, and every homework is tagged +//! with one of its course's subjects. Students submit against it +//! ([`crate::domain::homework_submission`]) and a teacher grades a status plus +//! an optional mark ([`crate::domain::homework_result`]). +//! +//! `course`, `created_by`, and `created_at` are fixed at creation (the schema +//! marks them `READONLY`): moving a homework between courses would strand the +//! submissions and grades of students not in the target course. `subject` is +//! deliberately *not* readonly — it is re-taggable through PATCH, validated +//! same-course by the web layer, exactly like an exam question's subject. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; +use crate::database::{Database, HOMEWORK_TABLE}; +use crate::domain::course::CourseId; +use crate::domain::subject::SubjectId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkId(RecordId); + +impl HomeworkId { + pub fn generate() -> Self { + Self(RecordId::new(HOMEWORK_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(HOMEWORK_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkTitle(String); + +impl HomeworkTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_HOMEWORK_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkDescription(String); + +impl HomeworkDescription { + pub fn try_new(value: &str) -> Result { + validate_optional("description", value, MAX_HOMEWORK_DESCRIPTION_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A homework assignment. `assigned` is the optional student subset: `None` +/// (the column absent) and an empty list both mean "the whole course" — see +/// [`Homework::student_sees`]. Because whole-course homework carries no roster, +/// a student who enrolls later is covered automatically; a subset is a fixed +/// snapshot of the students named at assign (or last PATCH) time. +#[derive(Debug, Clone, SurrealValue)] +pub struct Homework { + id: HomeworkId, + course: CourseId, + subject: SubjectId, + title: HomeworkTitle, + description: Option, + due_at: Timestamp, + assigned: Option>, + created_by: UserId, + created_at: Timestamp, +} + +impl Homework { + pub fn get_id(&self) -> &HomeworkId { + &self.id + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_subject(&self) -> &SubjectId { + &self.subject + } + + pub fn get_title(&self) -> &HomeworkTitle { + &self.title + } + + pub fn get_description(&self) -> Option<&HomeworkDescription> { + self.description.as_ref() + } + + pub fn get_due_at(&self) -> Timestamp { + self.due_at + } + + /// The assigned student subset, or `None` for a whole-course homework. + pub fn get_assigned(&self) -> Option<&[UserId]> { + self.assigned.as_deref() + } + + pub fn get_created_by(&self) -> &UserId { + &self.created_by + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// Whether `user` is in this homework's audience. A whole-course homework + /// (`assigned` absent or empty) is visible to every enrolled student; a + /// subset homework only to the students it names. Callers pair this with an + /// enrollment check — being named is visibility, not enrollment. + pub fn student_sees(&self, user: &UserId) -> bool { + match &self.assigned { + None => true, + Some(assigned) => assigned.is_empty() || assigned.contains(user), + } + } + + #[expect( + clippy::too_many_arguments, + reason = "mirrors the sibling entities' create(field, field, ..) shape" + )] + pub async fn create( + course: &CourseId, + subject: &SubjectId, + title: HomeworkTitle, + description: Option, + due_at: Timestamp, + assigned: Option>, + created_by: &UserId, + db: &Database, + ) -> Result { + let homework = Homework { + id: HomeworkId::generate(), + course: course.clone(), + subject: subject.clone(), + title, + description, + due_at, + assigned, + created_by: created_by.clone(), + created_at: Timestamp::now(), + }; + let created: Option = db.create(homework.id.record()).content(homework).await?; + created.ok_or_else(|| AppError::Internal("failed to create homework".into())) + } + + pub async fn read(id: &HomeworkId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// The course's homework, newest first (ULID ids sort by creation). The web + /// layer retains only the rows a given student `student_sees`. + pub async fn list_for_course( + course: &CourseId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The homework of `course` that `user` is meant to see — whole-course ones + /// plus any subset that names them — newest first. Backs a student's (or an + /// observer's) per-course homework report; mirrors [`Homework::student_sees`] + /// in SurQL so the filter runs in the database. + pub async fn list_for_user_in_course( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM homework + WHERE course = $course + AND (assigned = NONE OR assigned = [] OR $usr IN assigned) + ORDER BY id DESC", + ) + .bind(("course", course.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. + /// `course`, `created_by`, and `created_at` are untouched — the write + /// re-sends them unchanged, which the `READONLY` schema permits (only a + /// *changed* readonly value is refused). The web layer has already + /// re-checked the new `due_at` against now and the new `subject` against + /// the course, and refused a narrowing that would orphan a submission. + pub async fn update( + mut self, + subject: &SubjectId, + title: HomeworkTitle, + description: Option, + due_at: Timestamp, + assigned: Option>, + db: &Database, + ) -> Result { + self.subject = subject.clone(); + self.title = title; + self.description = description; + self.due_at = due_at; + self.assigned = assigned; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the homework and cascade its submissions, their files, and its + /// results — one transaction, so a crash can't orphan a submission under a + /// vanished homework. The submission file *blobs* are the web layer's to + /// unlink: it collects their names via + /// [`crate::domain::homework_file::HomeworkFile::file_keys_for_homework`] + /// before calling this, and removes them after the rows are gone. + pub async fn delete(self, db: &Database) -> Result { + let mut result = db + .query( + "BEGIN TRANSACTION; + DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); + DELETE homework_submission WHERE homework = $hw; + DELETE homework_result WHERE homework = $hw; + DELETE $hw RETURN BEFORE; + COMMIT TRANSACTION;", + ) + .bind(("hw", self.id.record())) + .await? + .check()?; + // BEGIN is slot 0; the homework's own DELETE is slot 4. + let deleted: Option = result.take::>(4)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn title_is_required() { + assert!(HomeworkTitle::try_new("Read chapter 3").is_ok()); + assert!(HomeworkTitle::try_new("").is_err()); + assert!(HomeworkTitle::try_new(" ").is_err()); + assert!(HomeworkTitle::try_new(&"x".repeat(201)).is_err()); + } + + #[tokio::test] + async fn description_is_optional_but_bounded() { + assert!(HomeworkDescription::try_new("").is_ok()); + assert!(HomeworkDescription::try_new(&"x".repeat(2_001)).is_err()); + } + + #[tokio::test] + async fn student_sees_covers_whole_course_and_named_subsets() { + let a = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let b = UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"); + let with = |assigned| Homework { + id: HomeworkId::generate(), + course: CourseId::from_key("01TESTCOURSEAAAAAAAAAAAAAA"), + subject: SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), + title: HomeworkTitle::try_new("hw").unwrap(), + description: None, + due_at: Timestamp::from_millis(1), + assigned, + created_by: a.clone(), + created_at: Timestamp::from_millis(1), + }; + // Whole course: absent or empty list means everyone sees it. + assert!(with(None).student_sees(&a)); + assert!(with(Some(vec![])).student_sees(&b)); + // Subset: only the named students. + assert!(with(Some(vec![a.clone()])).student_sees(&a)); + assert!(!with(Some(vec![a.clone()])).student_sees(&b)); + } +} diff --git a/src/domain/homework_file.rs b/src/domain/homework_file.rs new file mode 100644 index 0000000..bcbdb54 --- /dev/null +++ b/src/domain/homework_file.rs @@ -0,0 +1,281 @@ +//! A file attached to a homework submission. Like a note file, the row carries +//! metadata only (original filename, MIME type, byte size) and the bytes live +//! on disk under [`crate::config::Config::files_path`] — but named by this +//! row's own `file` field (a fresh server-generated ULID per upload, like a +//! question image), never by user input, so nothing a client sends shapes a +//! disk path. Files are immutable: created and deleted, never updated, so the +//! `READONLY` `submission`/`file`/`created_at` columns are only ever set once. +//! The web layer owns the blob I/O and its ordering (blob before row on +//! upload, row 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_HOMEWORK_FILES_PER_SUBMISSION; +use crate::database::{Database, HOMEWORK_FILE_TABLE}; +use crate::domain::course::CourseId; +use crate::domain::homework::HomeworkId; +use crate::domain::homework_submission::HomeworkSubmissionId; +use crate::domain::note_file::{FileContentType, FileName}; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; + +/// Serializes the files-per-submission cap check against the insert (see +/// [`HomeworkFile::insert`]). Its own lock, not note files' `FILE_CAP_LOCK`: +/// the two caps are independent counts and must not needlessly contend on one +/// mutex. This backend is the database's only writer, so one process-wide lock +/// suffices. +// ponytail: global lock, per-submission locks if uploads ever see real contention. +static SUBMISSION_FILE_LOCK: Mutex<()> = Mutex::const_new(()); + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkFileId(RecordId); + +impl HomeworkFileId { + pub fn generate() -> Self { + Self(RecordId::new(HOMEWORK_FILE_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(HOMEWORK_FILE_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// An attachment row. `file` is the blob's on-disk name (a fresh ULID per +/// upload), independent of the row id and reused as the GC key on cascade. +#[derive(Debug, Clone, SurrealValue)] +pub struct HomeworkFile { + id: HomeworkFileId, + submission: HomeworkSubmissionId, + name: FileName, + content_type: FileContentType, + size: i64, + file: String, + created_at: Timestamp, +} + +impl HomeworkFile { + /// Assemble a row (fresh blob name generated here) without persisting it. + /// The caller writes the blob under [`Self::get_file`] first, then calls + /// [`Self::insert`] — so a stored row always points at a real blob. + pub fn new( + submission: &HomeworkSubmissionId, + name: FileName, + content_type: FileContentType, + size: i64, + ) -> Self { + Self { + id: HomeworkFileId::generate(), + submission: submission.clone(), + name, + content_type, + size, + file: Ulid::new().to_string(), + created_at: Timestamp::now(), + } + } + + pub fn get_id(&self) -> &HomeworkFileId { + &self.id + } + + pub fn get_submission(&self) -> &HomeworkSubmissionId { + &self.submission + } + + pub fn get_name(&self) -> &FileName { + &self.name + } + + pub fn get_content_type(&self) -> &FileContentType { + &self.content_type + } + + pub fn get_size(&self) -> i64 { + self.size + } + + /// The blob's on-disk name — a fresh ULID, so no user input shapes a path. + pub fn get_file(&self) -> &str { + &self.file + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// Persist the row assembled by [`Self::new`], refusing once its submission + /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`]. The + /// count-then-create runs under [`SUBMISSION_FILE_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 `NoteFile::insert`. + pub async fn insert(self, db: &Database) -> Result { + let _guard = SUBMISSION_FILE_LOCK.lock().await; + if Self::count_for_submission(&self.submission, db).await? + >= MAX_HOMEWORK_FILES_PER_SUBMISSION + { + return Err(AppError::Conflict( + "the submission 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 homework file".into())) + } + + /// Read a file's row only if it belongs to `submission` — callers have + /// already checked the submission belongs to the requesting user. + pub async fn read_for( + id: &HomeworkFileId, + submission: &HomeworkSubmissionId, + db: &Database, + ) -> Result, AppError> { + let file: Option = db.select(id.record()).await?; + Ok(file.filter(|file| &file.submission == submission)) + } + + /// All of `submission`'s files, newest first. + pub async fn list_for_submission( + submission: &HomeworkSubmissionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") + .bind(("sub", submission.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// How many files `submission` holds — the cap check reads this under the + /// lock. Counting via the rows (not a `count()` query) keeps it identical + /// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. + pub async fn count_for_submission( + submission: &HomeworkSubmissionId, + db: &Database, + ) -> Result { + Ok(Self::list_for_submission(submission, db).await?.len()) + } + + /// The blob names behind every file of every submission to `homework` — + /// collected *before* the homework-delete cascade wipes the rows, so the + /// web layer can unlink them once the rows are gone. + pub async fn file_keys_for_homework( + homework: &HomeworkId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM homework_file \ + WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", + ) + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The blob names behind every homework file of `course` — collected + /// *before* the course-delete cascade wipes the rows. + pub async fn file_keys_for_course( + course: &CourseId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT VALUE file FROM homework_file WHERE submission IN ( \ + SELECT VALUE id FROM homework_submission \ + WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ + )", + ) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::homework_submission::HomeworkSubmission; + use crate::domain::user::UserId; + + fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { + HomeworkFile::new( + submission, + FileName::try_new("answer.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + } + + #[tokio::test] + async fn rows_scope_to_their_submission_gc_and_cap() { + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + // A real submission row, so the GC join through it resolves. + let submission = HomeworkSubmission::upsert(&homework, &user, None, &db) + .await + .unwrap(); + let sub_a = submission.get_id().clone(); + let sub_b = HomeworkSubmissionId::composite( + &homework, + &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), + ); + + let stored = a_file(&sub_a).insert(&db).await.unwrap(); + // Readable under its own submission, invisible under another. + assert!( + HomeworkFile::read_for(stored.get_id(), &sub_a, &db) + .await + .unwrap() + .is_some() + ); + assert!( + HomeworkFile::read_for(stored.get_id(), &sub_b, &db) + .await + .unwrap() + .is_none() + ); + assert_eq!( + HomeworkFile::count_for_submission(&sub_a, &db) + .await + .unwrap(), + 1 + ); + + // The blob name is collectable for GC before a cascade wipes the rows. + let keys = HomeworkFile::file_keys_for_homework(&homework, &db) + .await + .unwrap(); + assert_eq!(keys, vec![stored.get_file().to_string()]); + + // Fill to the cap, then the 11th is refused. + for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { + a_file(&sub_a).insert(&db).await.unwrap(); + } + assert!(matches!( + a_file(&sub_a).insert(&db).await, + Err(AppError::Conflict(_)) + )); + } +} diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs new file mode 100644 index 0000000..5d7abe3 --- /dev/null +++ b/src/domain/homework_result.rs @@ -0,0 +1,282 @@ +//! A teacher's grade on one student's homework: a status +//! (`done`/`incomplete`/`missing`) plus an optional numeric [`Mark`] (0..=100, +//! reused from exam results). Like an exam result, the row id is the +//! deterministic `{homework}_{user}` composite, so grading is one atomic UPSERT +//! and there is exactly one grade per (homework, user) by construction. +//! +//! A stored result is what *freezes* a submission: while a grade exists the +//! student's submission and files are locked (the web layer answers 409), until +//! the teacher removes the grade to reopen them. The teacher-set `missing` +//! status is a deliberate verdict, distinct from the roster's *computed* +//! "missing" (unsubmitted past due) — the latter is derived in the web layer, +//! never stored. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{Database, HOMEWORK_RESULT_TABLE}; +use crate::domain::course::CourseId; +use crate::domain::exam_result::Mark; +use crate::domain::homework::HomeworkId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_homework_status; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkResultId(RecordId); + +impl HomeworkResultId { + /// The one id a (homework, user) pair can have — a deterministic composite, + /// so grading is a single atomic UPSERT with no find-then-insert race and + /// one grade per pair by construction. ULID keys are alphanumeric, so `_` + /// is an unambiguous joiner. + pub fn composite(homework: &HomeworkId, user: &UserId) -> Self { + Self(RecordId::new( + HOMEWORK_RESULT_TABLE, + format!("{}_{}", homework.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A validated homework grade: `done` (submitted and complete), `incomplete` +/// (submitted but lacking), or `missing` (not done). Held to the +/// [`crate::constant::HOMEWORK_STATUSES`] set by [`HomeworkStatus::try_new`] — +/// the same validated-string-against-a-const shape as +/// [`crate::domain::exam::ExamMode`], which is why the `status` column needs no +/// DDL `ASSERT` (repo convention: enums live in Rust newtypes, not the schema). +/// It stores as the bare string. A stored `missing` is a teacher's deliberate +/// verdict, distinct from the roster's *computed* missing (unsubmitted past due, +/// derived in the web layer, never stored). +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkStatus(String); + +impl HomeworkStatus { + pub fn try_new(value: &str) -> Result { + validate_homework_status(value)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct HomeworkResult { + id: HomeworkResultId, + homework: HomeworkId, + user: UserId, + status: HomeworkStatus, + mark: Option, + graded_by: UserId, + created_at: Timestamp, +} + +impl HomeworkResult { + pub fn get_id(&self) -> &HomeworkResultId { + &self.id + } + + pub fn get_homework(&self) -> &HomeworkId { + &self.homework + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_status(&self) -> &HomeworkStatus { + &self.status + } + + /// The optional numeric mark; `None` when the teacher graded status only. + pub fn get_mark(&self) -> Option { + self.mark + } + + pub fn get_graded_by(&self) -> &UserId { + &self.graded_by + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// Record (or overwrite) the grade for (homework, user). One row per pair, + /// keyed by the deterministic composite id, so this is a single atomic + /// UPSERT — concurrent grades for the same pair converge on one row instead + /// of racing a unique index into a 500. Grading before the due date, or + /// before any submission exists, is allowed (the caller's policy call). + pub async fn grade( + homework: &HomeworkId, + user: &UserId, + status: HomeworkStatus, + mark: Option, + graded_by: &UserId, + db: &Database, + ) -> Result { + let result = HomeworkResult { + id: HomeworkResultId::composite(homework, user), + homework: homework.clone(), + user: user.clone(), + status, + mark, + graded_by: graded_by.clone(), + created_at: Timestamp::now(), + }; + let saved: Option = db.upsert(result.id.record()).content(result).await?; + saved.ok_or_else(|| AppError::Internal("failed to record homework result".into())) + } + + /// `user`'s grade for `homework`, if graded. + pub async fn read_for( + homework: &HomeworkId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + Ok(db + .select(HomeworkResultId::composite(homework, user).record()) + .await?) + } + + /// Every grade for `homework` — the roster joins these onto the submissions. + pub async fn list_for_homework( + homework: &HomeworkId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// `user`'s homework grades across one course — the raw rows behind the + /// per-course block of a homework report. Mirrors + /// `ExamResult::list_for_user_in_course`. + pub async fn list_for_user_in_course( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM homework_result WHERE user = $usr + AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) + ORDER BY id DESC", + ) + .bind(("usr", user.record())) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Un-grade (homework, user), returning the removed row (`None` if there + /// was none). Removing the grade unfreezes the student's submission. + pub async fn remove( + homework: &HomeworkId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE homework_result WHERE homework = $hw AND user = $usr RETURN BEFORE") + .bind(("hw", homework.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::HOMEWORK_STATUSES; + use surrealdb::types::Value; + + #[tokio::test] + async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { + // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL + // carries no ASSERT), and the stored value is the bare validated string + // the `status` column's `TYPE string` accepts. Guard both never drift. + for status in HOMEWORK_STATUSES { + let parsed = HomeworkStatus::try_new(status).unwrap(); + assert_eq!(parsed.as_str(), status); + assert_eq!(parsed.into_value(), Value::String(status.to_string())); + } + assert!(HomeworkStatus::try_new("late").is_err()); + assert!(HomeworkStatus::try_new("").is_err()); + } + + #[tokio::test] + async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + + let first = HomeworkResult::grade( + &homework, + &user, + HomeworkStatus::try_new("incomplete").unwrap(), + None, + &teacher, + &db, + ) + .await + .unwrap(); + // A regrade lands on the same row (composite id), overwriting the grade. + let second = HomeworkResult::grade( + &homework, + &user, + HomeworkStatus::try_new("done").unwrap(), + Some(Mark::try_new(80).unwrap()), + &teacher, + &db, + ) + .await + .unwrap(); + assert_eq!(first.get_id(), second.get_id()); + assert_eq!(second.get_status().as_str(), "done"); + assert_eq!(second.get_mark().unwrap().as_i64(), 80); + assert_eq!( + HomeworkResult::list_for_homework(&homework, &db) + .await + .unwrap() + .len(), + 1 + ); + + assert!( + HomeworkResult::read_for(&homework, &user, &db) + .await + .unwrap() + .is_some() + ); + assert!( + HomeworkResult::remove(&homework, &user, &db) + .await + .unwrap() + .is_some() + ); + assert!( + HomeworkResult::read_for(&homework, &user, &db) + .await + .unwrap() + .is_none() + ); + } +} diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs new file mode 100644 index 0000000..6fd824b --- /dev/null +++ b/src/domain/homework_submission.rs @@ -0,0 +1,233 @@ +//! One student's submission to a homework: an optional free-text note plus any +//! number of files ([`crate::domain::homework_file`]). The row id is the +//! deterministic `{homework}_{user}` composite, so a student has exactly one +//! submission per homework by construction and a re-submit is a single atomic +//! UPSERT. +//! +//! `submitted_at` — the first-submit stamp — is `READONLY` and survives every +//! re-submit; [`HomeworkSubmission::upsert`] preserves it inside one statement +//! rather than through `.content()`, see there. `updated_at` moves to now on +//! every (re-)submit (and, later, on a file add/delete) and drives the computed +//! "late" flag (`updated_at > homework.due_at`, judged in the web layer, never +//! stored): `submitted_at` answers "was the first hand-in on time", `updated_at` +//! "was it touched after the deadline". + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::MAX_HOMEWORK_TEXT_LEN; +use crate::database::{Database, HOMEWORK_SUBMISSION_TABLE}; +use crate::domain::homework::HomeworkId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_optional; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct HomeworkSubmissionId(RecordId); + +impl HomeworkSubmissionId { + /// The one id a (homework, user) pair can have. A deterministic composite + /// means one submission per pair with no unique index and no + /// find-then-insert race — a re-submit UPSERTs the same row. ULID keys are + /// alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(homework: &HomeworkId, user: &UserId) -> Self { + Self(RecordId::new( + HOMEWORK_SUBMISSION_TABLE, + format!("{}_{}", homework.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A submission's optional free-text note: may be empty, at most +/// `MAX_HOMEWORK_TEXT_LEN` characters. Files ride separately. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SubmissionText(String); + +impl SubmissionText { + pub fn try_new(value: &str) -> Result { + validate_optional("text", value, MAX_HOMEWORK_TEXT_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct HomeworkSubmission { + id: HomeworkSubmissionId, + homework: HomeworkId, + user: UserId, + text: Option, + submitted_at: Timestamp, + updated_at: Timestamp, +} + +impl HomeworkSubmission { + pub fn get_id(&self) -> &HomeworkSubmissionId { + &self.id + } + + pub fn get_homework(&self) -> &HomeworkId { + &self.homework + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_text(&self) -> Option<&SubmissionText> { + self.text.as_ref() + } + + pub fn get_submitted_at(&self) -> Timestamp { + self.submitted_at + } + + pub fn get_updated_at(&self) -> Timestamp { + self.updated_at + } + + /// Create or re-stamp `user`'s submission to `homework`. `updated_at` moves + /// to now every time; `submitted_at` (readonly, the first-submit stamp) is + /// kept on an existing row and set only on a fresh one. + /// + /// Hand-written rather than `.content()` on purpose: `.content()` re-sends + /// the whole row, so it would carry a `submitted_at`, and any value differing + /// from the stored one trips the readonly guard. The + /// `submitted_at = submitted_at ?? $now` expression preserves it inside the + /// one UPSERT statement — race-free without a lock, where a read-then-content + /// could let two concurrent first-submits pick different stamps and 500. + pub async fn upsert( + homework: &HomeworkId, + user: &UserId, + text: Option, + db: &Database, + ) -> Result { + let id = HomeworkSubmissionId::composite(homework, user); + let now = Timestamp::now(); + let text = text.map(|text| text.as_str().to_string()); + let mut saved = db + .query( + "UPSERT $id SET homework = $hw, user = $usr, text = $text, \ + updated_at = $now, submitted_at = submitted_at ?? $now RETURN AFTER", + ) + .bind(("id", id.record())) + .bind(("hw", homework.record())) + .bind(("usr", user.record())) + .bind(("text", text)) + .bind(("now", now)) + .await? + .check()?; + saved + .take::>(0)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to save homework submission".into())) + } + + /// `user`'s submission to `homework`, if they have one. + pub async fn read_for( + homework: &HomeworkId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + Ok(db + .select(HomeworkSubmissionId::composite(homework, user).record()) + .await?) + } + + /// Every submission to `homework`, in student (composite-id) order — the + /// roster's raw rows. + pub async fn list_for_homework( + homework: &HomeworkId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") + .bind(("hw", homework.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Delete this submission and its files in one transaction — so a crash + /// can't leave a file pointing at a vanished submission. The file *blobs* + /// are the web layer's to unlink: it lists them + /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`]) + /// before calling this. The caller has already refused the delete if the + /// submission is graded (a result exists). + pub async fn delete(self, db: &Database) -> Result { + let mut result = db + .query( + "BEGIN TRANSACTION; + DELETE homework_file WHERE submission = $sub; + DELETE $sub RETURN BEFORE; + COMMIT TRANSACTION;", + ) + .bind(("sub", self.id.record())) + .await? + .check()?; + // BEGIN is slot 0, the file wipe slot 1; the submission's DELETE is slot 2. + let deleted: Option = + result.take::>(2)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn text_is_optional_but_bounded() { + assert!(SubmissionText::try_new("").is_ok()); + assert!(SubmissionText::try_new(&"x".repeat(5_000)).is_ok()); + assert!(SubmissionText::try_new(&"x".repeat(5_001)).is_err()); + } + + #[tokio::test] + async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::generate(); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + + let first = HomeworkSubmission::upsert( + &homework, + &user, + Some(SubmissionText::try_new("draft").unwrap()), + &db, + ) + .await + .unwrap(); + // A re-submit lands on the same row: submitted_at (the first hand-in) + // pinned, updated_at moves forward, and the text can be cleared. + let second = HomeworkSubmission::upsert(&homework, &user, None, &db) + .await + .unwrap(); + assert_eq!(first.get_id(), second.get_id()); + assert_eq!(first.get_submitted_at(), second.get_submitted_at()); + assert!(second.get_updated_at() >= first.get_updated_at()); + assert!(second.get_text().is_none()); + // One row per (homework, user), whatever the re-submit count. + assert_eq!( + HomeworkSubmission::list_for_homework(&homework, &db) + .await + .unwrap() + .len(), + 1 + ); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index ac781aa..b262c79 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -13,6 +13,10 @@ pub mod exam_answer; pub mod exam_attempt; pub mod exam_question; pub mod exam_result; +pub mod homework; +pub mod homework_file; +pub mod homework_result; +pub mod homework_submission; pub mod message; pub mod note; pub mod note_file; diff --git a/src/validate.rs b/src/validate.rs index 70a7f6e..ad4cb80 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,10 +2,11 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - COURSE_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, - MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, - MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, - MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS, + COURSE_KINDS, EXAM_MODES, HOMEWORK_STATUSES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, + MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, + MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, + MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, + USERNAME_SEPARATORS, }; use crate::error::ValidationError; @@ -219,6 +220,17 @@ pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> { } } +pub fn validate_homework_status(value: &str) -> Result<(), ValidationError> { + if HOMEWORK_STATUSES.contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "status", + reason: "must be one of: done, incomplete, missing", + }) + } +} + pub fn validate_attempt_limit(value: i64) -> Result<(), ValidationError> { if value == UNLIMITED_EXAM_ATTEMPTS || (1..=MAX_EXAM_ATTEMPTS).contains(&value) { Ok(())