Finish src-side suite port + persistence re-expression
Browse files at this commitcfa11b2a22e79216e519d840e68799af5ca19ff4Parent: 8af2a2b- test
- finish src-side suite port + persistence re-expression
35 changed files +1035 -2484
- src/database.rs +25 -0
- src/db/appointment_slot.rs +7 -2
- src/db/board.rs +4 -2
- src/db/class_blueprint.rs +37 -0
- src/db/class_group.rs +13 -4
- src/db/course.rs +8 -8
- src/db/course_note.rs +2 -1
- src/db/course_session.rs +7 -4
- src/db/event.rs +4 -3
- src/db/exam_answer.rs +41 -6
- src/db/exam_attempt.rs +10 -0
- src/db/exam_result.rs +4 -1
- src/db/fee_plan.rs +2 -1
- src/db/homework.rs +3 -2
- src/db/homework_file.rs +5 -3
- src/db/homework_result.rs +39 -40
- src/db/homework_submission.rs +17 -2
- src/db/meal_booking.rs +21 -15
- src/db/message.rs +2 -2
- src/db/note.rs +1 -1
- src/db/question_image.rs +46 -4
- src/domain/text_fold.rs +7 -3
- src/service/appointment_slot.rs +79 -64
- src/service/class_blueprint.rs +37 -18
- src/service/class_course.rs +22 -13
- src/service/class_member.rs +4 -3
- src/service/exam_attempt.rs +12 -0
- src/service/meal_booking.rs +26 -18
- src/service/payment_ledger.rs +25 -10
- src/service/settings.rs +49 -30
- src/tenant.rs +4 -2
- src/web/bank_questions.rs +10 -1
- src/web/mod.rs +4 -5
- src/web/payments.rs +4 -2
- tests/persistence.rs +454 -2214
src/database.rsmodified+25 -0
| @@ -200,6 +200,19 @@ async fn migrator(set: &str) -> Result<Migrator, AppError> { | |||
| 200 | /// newly minted school at create — then sweep the chatbot turns the previous | 200 | /// newly minted school at create — then sweep the chatbot turns the previous |
| 201 | /// process owed an answer. Idempotent: an already-migrated database runs only | 201 | /// process owed an answer. Idempotent: an already-migrated database runs only |
| 202 | /// the sweep. | 202 | /// the sweep. |
| 203 | +/// Apply the control schema (schools, builders, the shared rate-limit | ||
| 204 | +/// window) to a control database. Idempotent: an already-migrated database | ||
| 205 | +/// runs nothing. The boot path folds this into [`boot_control`]; suites that | ||
| 206 | +/// re-boot an existing control database call it directly. | ||
| 207 | +pub async fn migrate_control(pool: &PgPool) -> Result<(), AppError> { | ||
| 208 | + migrator("control") | ||
| 209 | + .await? | ||
| 210 | + .run(pool) | ||
| 211 | + .await | ||
| 212 | + .map_err(|err| AppError::from(sqlx::Error::from(err)))?; | ||
| 213 | + Ok(()) | ||
| 214 | +} | ||
| 215 | + | ||
| 203 | pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { | 216 | pub async fn migrate_school(pool: &PgPool) -> Result<(), AppError> { |
| 204 | migrator("school") | 217 | migrator("school") |
| 205 | .await? | 218 | .await? |
| @@ -276,6 +289,18 @@ pub fn unique_violation(err: &sqlx::Error) -> Option<&str> { | |||
| 276 | } | 289 | } |
| 277 | } | 290 | } |
| 278 | 291 | ||
| 292 | +/// The violated `EXCLUDE` constraint's name, when `err` is an exclusion | ||
| 293 | +/// violation (`23P01`) — the SQLSTATE an exclusion constraint raises, as | ||
| 294 | +/// distinct from a plain `UNIQUE` (`23505`). | ||
| 295 | +pub fn exclusion_violation(err: &sqlx::Error) -> Option<&str> { | ||
| 296 | + let db = err.as_database_error()?; | ||
| 297 | + if db.code().as_deref() == Some("23P01") { | ||
| 298 | + db.constraint() | ||
| 299 | + } else { | ||
| 300 | + None | ||
| 301 | + } | ||
| 302 | +} | ||
| 303 | + | ||
| 279 | /// A foreign-key violation (`23503`): a parent row a statement names is gone. | 304 | /// A foreign-key violation (`23503`): a parent row a statement names is gone. |
| 280 | pub fn foreign_key_violation(err: &sqlx::Error) -> bool { | 305 | pub fn foreign_key_violation(err: &sqlx::Error) -> bool { |
| 281 | err.as_database_error() | 306 | err.as_database_error() |
src/db/appointment_slot.rsmodified+7 -2
| @@ -10,7 +10,7 @@ | |||
| 10 | //! [`crate::service::appointment_slot`] remain for their precise refusal | 10 | //! [`crate::service::appointment_slot`] remain for their precise refusal |
| 11 | //! texts; the constraint is the authority a racing publish answers to. | 11 | //! texts; the constraint is the authority a racing publish answers to. |
| 12 | 12 | ||
| 13 | -use crate::database::{Database, tx_with_retry, unique_violation}; | 13 | +use crate::database::{Database, exclusion_violation, tx_with_retry, unique_violation}; |
| 14 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; | 14 | use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; |
| 15 | use crate::domain::role::Role; | 15 | use crate::domain::role::Role; |
| 16 | use crate::domain::timestamp::Timestamp; | 16 | use crate::domain::timestamp::Timestamp; |
| @@ -96,7 +96,12 @@ pub async fn insert_claimed( | |||
| 96 | Ok(row) => saved.push(row), | 96 | Ok(row) => saved.push(row), |
| 97 | // A teacher cannot publish two overlapping windows: the | 97 | // A teacher cannot publish two overlapping windows: the |
| 98 | // exclusion constraint, answering the caller's overlap 409. | 98 | // exclusion constraint, answering the caller's overlap 409. |
| 99 | - Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => { | 99 | + // An EXCLUDE constraint answers 23P01 (exclusion), not the |
| 100 | + // 23505 a UNIQUE would — the overlap 409 rides this code. | ||
| 101 | + Err(err) | ||
| 102 | + if unique_violation(&err) == Some("appointment_slot_teacher_span") | ||
| 103 | + || exclusion_violation(&err) == Some("appointment_slot_teacher_span") => | ||
| 104 | + { | ||
| 100 | return Err(overlap_refusal.take().unwrap_or_else(|| { | 105 | return Err(overlap_refusal.take().unwrap_or_else(|| { |
| 101 | AppError::Internal("overlap refusal re-raised".into()) | 106 | AppError::Internal("overlap refusal re-raised".into()) |
| 102 | })); | 107 | })); |
src/db/board.rsmodified+4 -2
| @@ -332,7 +332,8 @@ mod tests { | |||
| 332 | #[tokio::test] | 332 | #[tokio::test] |
| 333 | async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { | 333 | async fn field_scoped_writes_return_the_row_and_a_gone_board_refuses() { |
| 334 | let (db, _leases) = crate::database::init_test_db().await; | 334 | let (db, _leases) = crate::database::init_test_db().await; |
| 335 | - let creator = UserId::generate(); | 335 | + let creator = |
| 336 | + crate::db::class_member::tests::fixture_user(&db, "board-creator").await; | ||
| 336 | let board = create( | 337 | let board = create( |
| 337 | &db, | 338 | &db, |
| 338 | &creator, | 339 | &creator, |
| @@ -363,7 +364,8 @@ mod tests { | |||
| 363 | #[tokio::test] | 364 | #[tokio::test] |
| 364 | async fn the_cap_refuses_and_delete_releases_the_seat() { | 365 | async fn the_cap_refuses_and_delete_releases_the_seat() { |
| 365 | let (db, _leases) = crate::database::init_test_db().await; | 366 | let (db, _leases) = crate::database::init_test_db().await; |
| 366 | - let creator = UserId::generate(); | 367 | + let creator = |
| 368 | + crate::db::class_member::tests::fixture_user(&db, "board-creator").await; | ||
| 367 | for index in 0..MAX_BOARDS_PER_CREATOR { | 369 | for index in 0..MAX_BOARDS_PER_CREATOR { |
| 368 | create( | 370 | create( |
| 369 | &db, | 371 | &db, |
src/db/class_blueprint.rsmodified+37 -0
| @@ -201,6 +201,43 @@ pub async fn delete_if_unchanged( | |||
| 201 | Ok(deleted.rows_affected() > 0) | 201 | Ok(deleted.rows_affected() > 0) |
| 202 | } | 202 | } |
| 203 | 203 | ||
| 204 | +/// [`delete_if_unchanged`] inside the caller's transaction — the blueprint | ||
| 205 | +/// delete rides the row lock its claim took, so the sourced links are swept | ||
| 206 | +/// while the window the claim opened is still closed. | ||
| 207 | +pub(crate) async fn delete_if_unchanged_in( | ||
| 208 | + tx: &mut sqlx::PgConnection, | ||
| 209 | + id: &ClassBlueprintId, | ||
| 210 | + held: &[CourseId], | ||
| 211 | +) -> Result<bool, AppError> { | ||
| 212 | + let deleted = sqlx::query!( | ||
| 213 | + r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#, | ||
| 214 | + id as _, | ||
| 215 | + held as _ | ||
| 216 | + ) | ||
| 217 | + .execute(&mut *tx) | ||
| 218 | + .await?; | ||
| 219 | + Ok(deleted.rows_affected() > 0) | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +/// The stored course list of one blueprint, read `FOR UPDATE` — the claim | ||
| 223 | +/// the delete holds across its sweep, so a sourced attach (whose own | ||
| 224 | +/// transaction takes `FOR KEY SHARE` on this row before inserting) either | ||
| 225 | +/// commits before the claim and is swept, or waits past it and finds no | ||
| 226 | +/// row. `None` when the blueprint is gone. | ||
| 227 | +pub(crate) async fn held_courses_for_update( | ||
| 228 | + tx: &mut sqlx::PgConnection, | ||
| 229 | + id: &ClassBlueprintId, | ||
| 230 | +) -> Result<Option<Vec<CourseId>>, AppError> { | ||
| 231 | + let row = sqlx::query!( | ||
| 232 | + r#"SELECT courses AS "courses: Vec<CourseId>" | ||
| 233 | + FROM class_blueprint WHERE grade = $1 FOR UPDATE"#, | ||
| 234 | + id as _ | ||
| 235 | + ) | ||
| 236 | + .fetch_optional(&mut *tx) | ||
| 237 | + .await?; | ||
| 238 | + Ok(row.map(|row| row.courses)) | ||
| 239 | +} | ||
| 240 | + | ||
| 204 | /// Every `class_course` row held by any of `classes`, projected down to the | 241 | /// Every `class_course` row held by any of `classes`, projected down to the |
| 205 | /// pair — the read [`crate::service::class_blueprint::status`] diffs the | 242 | /// pair — the read [`crate::service::class_blueprint::status`] diffs the |
| 206 | /// template against. | 243 | /// template against. |
src/db/class_group.rsmodified+13 -4
| @@ -299,17 +299,26 @@ mod tests { | |||
| 299 | /// A real `app_user` row: creator, teacher, and attached-by are foreign | 299 | /// A real `app_user` row: creator, teacher, and attached-by are foreign |
| 300 | /// keys now, so every fixture participant is a row, not a fabricated id. | 300 | /// keys now, so every fixture participant is a row, not a fabricated id. |
| 301 | async fn a_named_user(db: &Database, username: &str) -> UserId { | 301 | async fn a_named_user(db: &Database, username: &str) -> UserId { |
| 302 | - let user = UserId::generate(); | 302 | + // The username is unique: a second call for the same name must adopt |
| 303 | + // the existing row, not collide with it. | ||
| 303 | sqlx::query( | 304 | sqlx::query( |
| 304 | "INSERT INTO app_user (id, username, password_hash, role) \ | 305 | "INSERT INTO app_user (id, username, password_hash, role) \ |
| 305 | - VALUES ($1, $2, 'x', 'teacher')", | 306 | + VALUES ($1, $2, 'x', 'teacher') ON CONFLICT DO NOTHING", |
| 306 | ) | 307 | ) |
| 307 | - .bind(user.uuid()) | 308 | + .bind(UserId::generate().uuid()) |
| 308 | .bind(username) | 309 | .bind(username) |
| 309 | .execute(db) | 310 | .execute(db) |
| 310 | .await | 311 | .await |
| 311 | .unwrap(); | 312 | .unwrap(); |
| 312 | - user | 313 | + let id: uuid::Uuid = |
| 314 | + sqlx::query("SELECT id FROM app_user WHERE username = $1") | ||
| 315 | + .bind(username) | ||
| 316 | + .fetch_one(db) | ||
| 317 | + .await | ||
| 318 | + .unwrap() | ||
| 319 | + .try_get(0) | ||
| 320 | + .unwrap(); | ||
| 321 | + UserId::from_key(&id.to_string()) | ||
| 313 | } | 322 | } |
| 314 | 323 | ||
| 315 | async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup { | 324 | async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup { |
src/db/course.rsmodified+8 -8
| @@ -581,7 +581,7 @@ pub(crate) async fn a_test_course(db: &Database) -> CourseId { | |||
| 581 | VALUES ($1, $2, 'x', 'teacher')", | 581 | VALUES ($1, $2, 'x', 'teacher')", |
| 582 | ) | 582 | ) |
| 583 | .bind(creator.uuid()) | 583 | .bind(creator.uuid()) |
| 584 | - .bind(format!("course-fixture-{}", &creator.key()[..8])) | 584 | + .bind(format!("course-fixture-{}", &creator.key()[30..])) |
| 585 | .execute(db) | 585 | .execute(db) |
| 586 | .await | 586 | .await |
| 587 | .unwrap(); | 587 | .unwrap(); |
| @@ -721,7 +721,7 @@ mod tests { | |||
| 721 | VALUES ($1, $2, 'x', $3)", | 721 | VALUES ($1, $2, 'x', $3)", |
| 722 | ) | 722 | ) |
| 723 | .bind(user.uuid()) | 723 | .bind(user.uuid()) |
| 724 | - .bind(format!("{label}-{}", &user.key()[..8])) | 724 | + .bind(format!("{label}-{}", &user.key()[30..])) |
| 725 | .bind(role) | 725 | .bind(role) |
| 726 | .execute(db) | 726 | .execute(db) |
| 727 | .await | 727 | .await |
| @@ -859,9 +859,9 @@ mod tests { | |||
| 859 | .unwrap() | 859 | .unwrap() |
| 860 | } | 860 | } |
| 861 | 861 | ||
| 862 | - /// How many rows `sql` selects ids for. | 862 | + /// How many rows a table holds (the table name is a fixture literal). |
| 863 | - async fn rows(sql: &str, db: &Database) -> usize { | 863 | + async fn rows(table: &str, db: &Database) -> usize { |
| 864 | - sqlx::query(sqlx::AssertSqlSafe(sql.to_string())) | 864 | + sqlx::query(sqlx::AssertSqlSafe(format!("SELECT count(*) FROM {table}"))) |
| 865 | .fetch_one(db) | 865 | .fetch_one(db) |
| 866 | .await | 866 | .await |
| 867 | .unwrap() | 867 | .unwrap() |
| @@ -901,12 +901,12 @@ mod tests { | |||
| 901 | .expect_err("a term that is gone must not be linkable"); | 901 | .expect_err("a term that is gone must not be linkable"); |
| 902 | assert!(error.to_string().contains("term does not exist")); | 902 | assert!(error.to_string().contains("term does not exist")); |
| 903 | assert_eq!( | 903 | assert_eq!( |
| 904 | - rows("SELECT VALUE id FROM course", &db).await, | 904 | + rows("course", &db).await, |
| 905 | 0, | 905 | 0, |
| 906 | "a refused create may write no row" | 906 | "a refused create may write no row" |
| 907 | ); | 907 | ); |
| 908 | assert_eq!( | 908 | assert_eq!( |
| 909 | - rows("SELECT VALUE id FROM term", &db).await, | 909 | + rows("term", &db).await, |
| 910 | 0, | 910 | 0, |
| 911 | "…and least of all a count on a term it just brought back" | 911 | "…and least of all a count on a term it just brought back" |
| 912 | ); | 912 | ); |
| @@ -1148,7 +1148,7 @@ mod tests { | |||
| 1148 | "the release must roll back with the abort" | 1148 | "the release must roll back with the abort" |
| 1149 | ); | 1149 | ); |
| 1150 | assert_eq!( | 1150 | assert_eq!( |
| 1151 | - rows("SELECT VALUE id FROM term", &db).await, | 1151 | + rows("term", &db).await, |
| 1152 | 1, | 1152 | 1, |
| 1153 | "the dead term must not be resurrected by the claim" | 1153 | "the dead term must not be resurrected by the claim" |
| 1154 | ); | 1154 | ); |
src/db/course_note.rsmodified+2 -1
| @@ -158,7 +158,8 @@ mod tests { | |||
| 158 | #[tokio::test] | 158 | #[tokio::test] |
| 159 | async fn delete_returns_the_attachment_rows_it_removed() { | 159 | async fn delete_returns_the_attachment_rows_it_removed() { |
| 160 | let (db, _leases) = crate::database::init_test_db().await; | 160 | let (db, _leases) = crate::database::init_test_db().await; |
| 161 | - let creator = crate::domain::user::UserId::generate(); | 161 | + let creator = |
| 162 | + crate::db::class_member::tests::fixture_user(&db, "course-note-author").await; | ||
| 162 | let course = crate::db::course::create( | 163 | let course = crate::db::course::create( |
| 163 | &db, | 164 | &db, |
| 164 | &creator, | 165 | &creator, |
src/db/course_session.rsmodified+7 -4
| @@ -130,7 +130,11 @@ pub async fn update( | |||
| 130 | /// session-row lock makes a mark and this delete take turns — a mark | 130 | /// session-row lock makes a mark and this delete take turns — a mark |
| 131 | /// committing after this cascade cannot name a session that is gone. | 131 | /// committing after this cascade cannot name a session that is gone. |
| 132 | pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> { | 132 | pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> { |
| 133 | - tx_with_retry(db, false, async move |tx| { | 133 | + // Cascade mode: a roll-call row written *after* the sweep's snapshot (a |
| 134 | + // mark racing the delete) still references the session when the session | ||
| 135 | + // row goes, and that 23503 means "a racing writer is mid-flight" — the | ||
| 136 | + // re-send sweeps the settled rows and succeeds. | ||
| 137 | + tx_with_retry(db, true, async move |tx| { | ||
| 134 | // Roll-call rows first: the session row's own FK would refuse the | 138 | // Roll-call rows first: the session row's own FK would refuse the |
| 135 | // delete while they exist. An empty first sweep is fine — the | 139 | // delete while they exist. An empty first sweep is fine — the |
| 136 | // session may simply have had none. | 140 | // session may simply have had none. |
| @@ -158,7 +162,6 @@ pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSessi | |||
| 158 | #[cfg(test)] | 162 | #[cfg(test)] |
| 159 | mod tests { | 163 | mod tests { |
| 160 | use super::*; | 164 | use super::*; |
| 161 | - use crate::constant::COURSE_SESSION_TABLE; | ||
| 162 | 165 | ||
| 163 | /// A lesson must not outlive the course it is a lesson of: an orphan 404s | 166 | /// A lesson must not outlive the course it is a lesson of: an orphan 404s |
| 164 | /// forever through `session_with_course` — unreadable, unpatchable, | 167 | /// forever through `session_with_course` — unreadable, unpatchable, |
| @@ -181,7 +184,7 @@ mod tests { | |||
| 181 | VALUES ($1, $2, 'x', 'teacher')", | 184 | VALUES ($1, $2, 'x', 'teacher')", |
| 182 | ) | 185 | ) |
| 183 | .bind(creator.uuid()) | 186 | .bind(creator.uuid()) |
| 184 | - .bind(format!("session-race-{}", &creator.key()[..8])) | 187 | + .bind(format!("session-race-{}", &creator.key()[30..])) |
| 185 | .execute(&db) | 188 | .execute(&db) |
| 186 | .await | 189 | .await |
| 187 | .unwrap(); | 190 | .unwrap(); |
| @@ -197,6 +200,6 @@ mod tests { | |||
| 197 | .map(|_| ()) | 200 | .map(|_| ()) |
| 198 | }) | 201 | }) |
| 199 | } | 202 | } |
| 200 | - crate::db::course::assert_no_child_outlives_a_course_delete("session", make).await; | 203 | + crate::db::course::assert_no_child_outlives_a_course_delete("course_session", make).await; |
| 201 | } | 204 | } |
| 202 | } | 205 | } |
src/db/event.rsmodified+4 -3
| @@ -300,7 +300,7 @@ mod tests { | |||
| 300 | VALUES ($1, $2, 'x', 'teacher')", | 300 | VALUES ($1, $2, 'x', 'teacher')", |
| 301 | ) | 301 | ) |
| 302 | .bind(user.uuid()) | 302 | .bind(user.uuid()) |
| 303 | - .bind(format!("{label}-{}", &user.key()[..8])) | 303 | + .bind(format!("{label}-{}", &user.key()[30..])) |
| 304 | .execute(db) | 304 | .execute(db) |
| 305 | .await | 305 | .await |
| 306 | .unwrap(); | 306 | .unwrap(); |
| @@ -394,8 +394,9 @@ mod tests { | |||
| 394 | Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) | 394 | Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) |
| 395 | ); | 395 | ); |
| 396 | // Test-side copy of the sweep predicate in `service::user::set_role` | 396 | // Test-side copy of the sweep predicate in `service::user::set_role` |
| 397 | - // (src/db/user.rs): frozen == the demotion sweep would leave the row. | 397 | + // (src/db/user.rs): true == frozen, i.e. the demotion sweep would |
| 398 | - let sql = !sqlx::query_scalar::<_, bool>( | 398 | + // leave the signup rows exactly as they stand. |
| 399 | + let sql = sqlx::query_scalar::<_, bool>( | ||
| 399 | "SELECT audience_kind = 'registration' \ | 400 | "SELECT audience_kind = 'registration' \ |
| 400 | AND COALESCE(starts_at, ends_at) IS NOT NULL \ | 401 | AND COALESCE(starts_at, ends_at) IS NOT NULL \ |
| 401 | AND COALESCE(starts_at, ends_at) <= $2 \ | 402 | AND COALESCE(starts_at, ends_at) <= $2 \ |
src/db/exam_answer.rsmodified+41 -6
| @@ -328,25 +328,60 @@ mod tests { | |||
| 328 | .await | 328 | .await |
| 329 | .unwrap(); | 329 | .unwrap(); |
| 330 | let stored = async |db: &Database| -> Option<i64> { | 330 | let stored = async |db: &Database| -> Option<i64> { |
| 331 | - sqlx::query_scalar::<_, i64>("SELECT result_count FROM exam WHERE id = $1") | 331 | + sqlx::query_scalar::<_, Option<i64>>("SELECT result_count FROM exam WHERE id = $1") |
| 332 | .bind(exam.get_id().uuid()) | 332 | .bind(exam.get_id().uuid()) |
| 333 | .fetch_optional(db) | 333 | .fetch_optional(db) |
| 334 | .await | 334 | .await |
| 335 | .unwrap() | 335 | .unwrap() |
| 336 | .flatten() | 336 | .flatten() |
| 337 | }; | 337 | }; |
| 338 | - let question = choice_question(exam.get_id(), 10, 1); | 338 | + // The question is a foreign key: a real row, so the choice ids the |
| 339 | + // answer names exist in the store too. | ||
| 340 | + let spec = QuestionSpec::try_new( | ||
| 341 | + QuestionKind::try_new("choice").unwrap(), | ||
| 342 | + Some( | ||
| 343 | + ["a", "b", "c"] | ||
| 344 | + .iter() | ||
| 345 | + .map(|l| ChoiceInput { | ||
| 346 | + id: Some((*l).into()), | ||
| 347 | + text: (*l).into(), | ||
| 348 | + }) | ||
| 349 | + .collect(), | ||
| 350 | + ), | ||
| 351 | + Some("b".into()), | ||
| 352 | + &[], | ||
| 353 | + ) | ||
| 354 | + .unwrap(); | ||
| 355 | + let subject = crate::db::subject::create( | ||
| 356 | + &db, | ||
| 357 | + &crate::db::course::a_test_course(&db).await, | ||
| 358 | + crate::domain::subject::SubjectName::try_new("sorular").unwrap(), | ||
| 359 | + crate::domain::subject::SubjectDescription::try_new("").unwrap(), | ||
| 360 | + ) | ||
| 361 | + .await | ||
| 362 | + .unwrap(); | ||
| 363 | + let question = crate::db::exam_question::create( | ||
| 364 | + &db, | ||
| 365 | + exam.get_id(), | ||
| 366 | + subject.get_id().clone(), | ||
| 367 | + crate::domain::exam_question::QuestionText::try_new("pick one").unwrap(), | ||
| 368 | + crate::domain::exam_question::QuestionPoints::try_new(10).unwrap(), | ||
| 369 | + spec, | ||
| 370 | + ) | ||
| 371 | + .await | ||
| 372 | + .unwrap(); | ||
| 339 | let pick = choice_id(&question, 1).as_str().to_string(); | 373 | let pick = choice_id(&question, 1).as_str().to_string(); |
| 340 | 374 | ||
| 341 | - // A fresh exam carries no counter at all, and must still not after a save. | 375 | + // A fresh exam's counter is zero (the column is NOT NULL DEFAULT 0), |
| 342 | - assert_eq!(stored(&db).await, None, "the fixture must start absent"); | 376 | + // and a save must still not move it. |
| 377 | + assert_eq!(stored(&db).await, Some(0), "the fixture starts at zero"); | ||
| 343 | save(&db, &question, &student(), 1, Some(pick.clone()), None) | 378 | save(&db, &question, &student(), 1, Some(pick.clone()), None) |
| 344 | .await | 379 | .await |
| 345 | .unwrap(); | 380 | .unwrap(); |
| 346 | assert_eq!( | 381 | assert_eq!( |
| 347 | stored(&db).await, | 382 | stored(&db).await, |
| 348 | - None, | 383 | + Some(0), |
| 349 | - "the touch left the counter set — the backfill keys on NONE" | 384 | + "the touch left the counter alone" |
| 350 | ); | 385 | ); |
| 351 | 386 | ||
| 352 | // …and a counter that marks have moved is put back at its own value. | 387 | // …and a counter that marks have moved is put back at its own value. |
src/db/exam_attempt.rsmodified+10 -0
| @@ -390,6 +390,16 @@ mod tests { | |||
| 390 | /// rows to exercise the attempt lifecycle without the HTTP layer. | 390 | /// rows to exercise the attempt lifecycle without the HTTP layer. |
| 391 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { | 391 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { |
| 392 | let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | 392 | let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); |
| 393 | + // The creator is a foreign key now: a real `app_user` row under the | ||
| 394 | + // fixture's fixed key. | ||
| 395 | + sqlx::query( | ||
| 396 | + "INSERT INTO app_user (id, username, password_hash) \ | ||
| 397 | + VALUES ($1, 'acdc-fixture', 'x') ON CONFLICT DO NOTHING", | ||
| 398 | + ) | ||
| 399 | + .bind(creator.uuid()) | ||
| 400 | + .execute(db) | ||
| 401 | + .await | ||
| 402 | + .unwrap(); | ||
| 393 | let course = crate::db::course::a_test_course(db).await; | 403 | let course = crate::db::course::a_test_course(db).await; |
| 394 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); | 404 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 395 | let exam = crate::db::exam::create( | 405 | let exam = crate::db::exam::create( |
src/db/exam_result.rsmodified+4 -1
| @@ -402,6 +402,7 @@ mod tests { | |||
| 402 | let teacher = UserId::from_key(TEACHER); | 402 | let teacher = UserId::from_key(TEACHER); |
| 403 | // The exam has to be real: a mark is refused on one that isn't. | 403 | // The exam has to be real: a mark is refused on one that isn't. |
| 404 | an_exam(&db, &exam, "midterm").await; | 404 | an_exam(&db, &exam, "midterm").await; |
| 405 | + the_two_people(&db).await; | ||
| 405 | 406 | ||
| 406 | // Grade sitting #1, then a retake as sitting #2 — two rows, not one. | 407 | // Grade sitting #1, then a retake as sitting #2 — two rows, not one. |
| 407 | super::grade( | 408 | super::grade( |
| @@ -501,7 +502,8 @@ mod tests { | |||
| 501 | .unwrap() | 502 | .unwrap() |
| 502 | .map(|row| row.try_get::<i64, _>(0).unwrap()) | 503 | .map(|row| row.try_get::<i64, _>(0).unwrap()) |
| 503 | .unwrap_or(0); | 504 | .unwrap_or(0); |
| 504 | - let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0) FROM exam") | 505 | + let exam_count = |
| 506 | + sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam") | ||
| 505 | .fetch_one(db) | 507 | .fetch_one(db) |
| 506 | .await | 508 | .await |
| 507 | .unwrap() | 509 | .unwrap() |
| @@ -579,6 +581,7 @@ mod tests { | |||
| 579 | let (db, _leases) = init_test_db().await; | 581 | let (db, _leases) = init_test_db().await; |
| 580 | let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1c4"); | 582 | let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1c4"); |
| 581 | an_exam(&db, &exam, "midterm").await; | 583 | an_exam(&db, &exam, "midterm").await; |
| 584 | + the_two_people(&db).await; | ||
| 582 | 585 | ||
| 583 | grade(&db, &exam, 1, 40, "midterm").await.unwrap(); | 586 | grade(&db, &exam, 1, 40, "midterm").await.unwrap(); |
| 584 | assert_eq!(counters(&db, "midterm").await, (1, 1)); | 587 | assert_eq!(counters(&db, "midterm").await, (1, 1)); |
src/db/fee_plan.rsmodified+2 -1
| @@ -177,7 +177,8 @@ mod tests { | |||
| 177 | #[tokio::test] | 177 | #[tokio::test] |
| 178 | async fn installments_survive_a_round_trip_through_the_schema() { | 178 | async fn installments_survive_a_round_trip_through_the_schema() { |
| 179 | let (db, _leases) = crate::database::init_test_db().await; | 179 | let (db, _leases) = crate::database::init_test_db().await; |
| 180 | - let manager = UserId::from_key("mgr1"); | 180 | + let manager = |
| 181 | + crate::db::class_member::tests::fixture_user(&db, "fee-manager").await; | ||
| 181 | let installments = vec![ | 182 | let installments = vec![ |
| 182 | Installment::new( | 183 | Installment::new( |
| 183 | LedgerAmount::try_new(150_000).unwrap(), | 184 | LedgerAmount::try_new(150_000).unwrap(), |
src/db/homework.rsmodified+3 -2
| @@ -541,7 +541,7 @@ mod tests { | |||
| 541 | VALUES ($1, $2, 'x', 'teacher')", | 541 | VALUES ($1, $2, 'x', 'teacher')", |
| 542 | ) | 542 | ) |
| 543 | .bind(teacher.uuid()) | 543 | .bind(teacher.uuid()) |
| 544 | - .bind(format!("homework-fixture-{}", &teacher.key()[..8])) | 544 | + .bind(format!("homework-fixture-{}", &teacher.key()[30..])) |
| 545 | .execute(db) | 545 | .execute(db) |
| 546 | .await | 546 | .await |
| 547 | .unwrap(); | 547 | .unwrap(); |
| @@ -563,9 +563,10 @@ mod tests { | |||
| 563 | async fn count_on(subject: &SubjectId, db: &Database) -> i64 { | 563 | async fn count_on(subject: &SubjectId, db: &Database) -> i64 { |
| 564 | sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1") | 564 | sqlx::query_scalar::<_, i64>("SELECT homework_count FROM subject WHERE id = $1") |
| 565 | .bind(subject.uuid()) | 565 | .bind(subject.uuid()) |
| 566 | - .fetch_one(db) | 566 | + .fetch_optional(db) |
| 567 | .await | 567 | .await |
| 568 | .unwrap() | 568 | .unwrap() |
| 569 | + .unwrap_or(0) | ||
| 569 | } | 570 | } |
| 570 | 571 | ||
| 571 | /// How many rows `sql` selects ids for. | 572 | /// How many rows `sql` selects ids for. |
src/db/homework_file.rsmodified+5 -3
| @@ -312,7 +312,7 @@ mod tests { | |||
| 312 | let user = UserId::generate(); | 312 | let user = UserId::generate(); |
| 313 | sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')") | 313 | sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'student')") |
| 314 | .bind(user.uuid()) | 314 | .bind(user.uuid()) |
| 315 | - .bind(format!("s-{}", &user.key()[..8])) | 315 | + .bind(format!("s-{}", &user.key()[30..])) |
| 316 | .execute(db) | 316 | .execute(db) |
| 317 | .await | 317 | .await |
| 318 | .unwrap(); | 318 | .unwrap(); |
| @@ -324,7 +324,7 @@ mod tests { | |||
| 324 | let user = UserId::generate(); | 324 | let user = UserId::generate(); |
| 325 | sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')") | 325 | sqlx::query("INSERT INTO app_user (id, username, password_hash, role) VALUES ($1, $2, 'x', 'teacher')") |
| 326 | .bind(user.uuid()) | 326 | .bind(user.uuid()) |
| 327 | - .bind(format!("t-{}", &user.key()[..8])) | 327 | + .bind(format!("t-{}", &user.key()[30..])) |
| 328 | .execute(db) | 328 | .execute(db) |
| 329 | .await | 329 | .await |
| 330 | .unwrap(); | 330 | .unwrap(); |
| @@ -343,6 +343,8 @@ mod tests { | |||
| 343 | /// The counter as *stored* — the only witness that the seat and the row | 343 | /// The counter as *stored* — the only witness that the seat and the row |
| 344 | /// moved together, since every other read counts the rows themselves. | 344 | /// moved together, since every other read counts the rows themselves. |
| 345 | async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { | 345 | async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { |
| 346 | + use sqlx::Row as _; | ||
| 347 | + | ||
| 346 | sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1") | 348 | sqlx::query("SELECT file_count FROM homework_submission WHERE id = $1") |
| 347 | .bind(submission.uuid()) | 349 | .bind(submission.uuid()) |
| 348 | .fetch_one(db) | 350 | .fetch_one(db) |
| @@ -458,7 +460,7 @@ mod tests { | |||
| 458 | &user, | 460 | &user, |
| 459 | HomeworkStatus::try_new("done").unwrap(), | 461 | HomeworkStatus::try_new("done").unwrap(), |
| 460 | None, | 462 | None, |
| 461 | - &UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"), | 463 | + &a_teacher(&db).await, |
| 462 | ) | 464 | ) |
| 463 | .await | 465 | .await |
| 464 | .unwrap(); | 466 | .unwrap(); |
src/db/homework_result.rsmodified+39 -40
| @@ -321,7 +321,7 @@ mod tests { | |||
| 321 | None, | 321 | None, |
| 322 | Timestamp::from_millis(1), | 322 | Timestamp::from_millis(1), |
| 323 | None, | 323 | None, |
| 324 | - &UserId::from_key("teacher"), | 324 | + &a_teacher(db).await, |
| 325 | ) | 325 | ) |
| 326 | .await | 326 | .await |
| 327 | .unwrap() | 327 | .unwrap() |
| @@ -329,12 +329,42 @@ mod tests { | |||
| 329 | .clone() | 329 | .clone() |
| 330 | } | 330 | } |
| 331 | 331 | ||
| 332 | + /// A real `app_user` teacher row: graders are foreign keys too. | ||
| 333 | + async fn a_teacher(db: &Database) -> UserId { | ||
| 334 | + let user = UserId::generate(); | ||
| 335 | + sqlx::query( | ||
| 336 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 337 | + VALUES ($1, $2, 'x', 'teacher')", | ||
| 338 | + ) | ||
| 339 | + .bind(user.uuid()) | ||
| 340 | + .bind(format!("t-{}", &user.key()[30..])) | ||
| 341 | + .execute(db) | ||
| 342 | + .await | ||
| 343 | + .unwrap(); | ||
| 344 | + user | ||
| 345 | + } | ||
| 346 | + | ||
| 347 | + /// A real `app_user` student row: graded users are foreign keys too. | ||
| 348 | + async fn a_student(db: &Database) -> UserId { | ||
| 349 | + let user = UserId::generate(); | ||
| 350 | + sqlx::query( | ||
| 351 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 352 | + VALUES ($1, $2, 'x', 'student')", | ||
| 353 | + ) | ||
| 354 | + .bind(user.uuid()) | ||
| 355 | + .bind(format!("s-{}", &user.key()[30..])) | ||
| 356 | + .execute(db) | ||
| 357 | + .await | ||
| 358 | + .unwrap(); | ||
| 359 | + user | ||
| 360 | + } | ||
| 361 | + | ||
| 332 | #[tokio::test] | 362 | #[tokio::test] |
| 333 | async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { | 363 | async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { |
| 334 | let (db, _leases) = crate::database::init_test_db().await; | 364 | let (db, _leases) = crate::database::init_test_db().await; |
| 335 | let homework = a_homework(&db).await; | 365 | let homework = a_homework(&db).await; |
| 336 | - let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); | 366 | + let user = a_student(&db).await; |
| 337 | - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | 367 | + let teacher = a_teacher(&db).await; |
| 338 | 368 | ||
| 339 | let first = grade( | 369 | let first = grade( |
| 340 | &db, | 370 | &db, |
| @@ -374,25 +404,8 @@ mod tests { | |||
| 374 | async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { | 404 | async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { |
| 375 | let (db, _leases) = crate::database::init_test_db().await; | 405 | let (db, _leases) = crate::database::init_test_db().await; |
| 376 | let homework = a_homework(&db).await; | 406 | let homework = a_homework(&db).await; |
| 377 | - let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); | 407 | + let user = a_student(&db).await; |
| 378 | - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | 408 | + let teacher = a_teacher(&db).await; |
| 379 | - // `UPDATE` writes nothing to a user row that does not exist. | ||
| 380 | - sqlx::query( | ||
| 381 | - "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 382 | - VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", | ||
| 383 | - ) | ||
| 384 | - .bind(teacher.uuid()) | ||
| 385 | - .execute(&db) | ||
| 386 | - .await | ||
| 387 | - .unwrap(); | ||
| 388 | - sqlx::query( | ||
| 389 | - "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 390 | - VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", | ||
| 391 | - ) | ||
| 392 | - .bind(user.uuid()) | ||
| 393 | - .execute(&db) | ||
| 394 | - .await | ||
| 395 | - .unwrap(); | ||
| 396 | 409 | ||
| 397 | for status in ["incomplete", "done"] { | 410 | for status in ["incomplete", "done"] { |
| 398 | grade( | 411 | grade( |
| @@ -421,24 +434,8 @@ mod tests { | |||
| 421 | async fn ungrading_gives_the_grader_credit_back() { | 434 | async fn ungrading_gives_the_grader_credit_back() { |
| 422 | let (db, _leases) = crate::database::init_test_db().await; | 435 | let (db, _leases) = crate::database::init_test_db().await; |
| 423 | let homework = a_homework(&db).await; | 436 | let homework = a_homework(&db).await; |
| 424 | - let user = UserId::from_key("019732e3-7b00-7000-8000-00000000aaaa"); | 437 | + let user = a_student(&db).await; |
| 425 | - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | 438 | + let teacher = a_teacher(&db).await; |
| 426 | - sqlx::query( | ||
| 427 | - "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 428 | - VALUES ($1, 't', 'x', 'teacher') ON CONFLICT (id) DO NOTHING", | ||
| 429 | - ) | ||
| 430 | - .bind(teacher.uuid()) | ||
| 431 | - .execute(&db) | ||
| 432 | - .await | ||
| 433 | - .unwrap(); | ||
| 434 | - sqlx::query( | ||
| 435 | - "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 436 | - VALUES ($1, 'ali', 'x', 'student') ON CONFLICT (id) DO NOTHING", | ||
| 437 | - ) | ||
| 438 | - .bind(user.uuid()) | ||
| 439 | - .execute(&db) | ||
| 440 | - .await | ||
| 441 | - .unwrap(); | ||
| 442 | 439 | ||
| 443 | for _ in 0..3 { | 440 | for _ in 0..3 { |
| 444 | grade( | 441 | grade( |
| @@ -465,6 +462,8 @@ mod tests { | |||
| 465 | } | 462 | } |
| 466 | /// The grader's badge counter, re-read out of the store. | 463 | /// The grader's badge counter, re-read out of the store. |
| 467 | async fn marks_given(user: &UserId, db: &Database) -> i64 { | 464 | async fn marks_given(user: &UserId, db: &Database) -> i64 { |
| 465 | + use sqlx::Row as _; | ||
| 466 | + | ||
| 468 | sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1") | 467 | sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1") |
| 469 | .bind(user.uuid()) | 468 | .bind(user.uuid()) |
| 470 | .fetch_one(db) | 469 | .fetch_one(db) |
src/db/homework_submission.rsmodified+17 -2
| @@ -409,12 +409,27 @@ mod tests { | |||
| 409 | None, | 409 | None, |
| 410 | due_at, | 410 | due_at, |
| 411 | None, | 411 | None, |
| 412 | - &UserId::from_key("teacher"), | 412 | + &a_teacher(db).await, |
| 413 | ) | 413 | ) |
| 414 | .await | 414 | .await |
| 415 | .unwrap() | 415 | .unwrap() |
| 416 | } | 416 | } |
| 417 | 417 | ||
| 418 | + /// A real `app_user` teacher row: graders are foreign keys too. | ||
| 419 | + async fn a_teacher(db: &Database) -> UserId { | ||
| 420 | + let user = UserId::generate(); | ||
| 421 | + sqlx::query( | ||
| 422 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 423 | + VALUES ($1, $2, 'x', 'teacher')", | ||
| 424 | + ) | ||
| 425 | + .bind(user.uuid()) | ||
| 426 | + .bind(format!("t-{}", &user.key()[30..])) | ||
| 427 | + .execute(db) | ||
| 428 | + .await | ||
| 429 | + .unwrap(); | ||
| 430 | + user | ||
| 431 | + } | ||
| 432 | + | ||
| 418 | /// A deadline no test run can reach, so a submission is unambiguously on | 433 | /// A deadline no test run can reach, so a submission is unambiguously on |
| 419 | /// time; `Timestamp::from_millis(1)` is its late twin. | 434 | /// time; `Timestamp::from_millis(1)` is its late twin. |
| 420 | fn far_future() -> Timestamp { | 435 | fn far_future() -> Timestamp { |
| @@ -548,7 +563,7 @@ mod tests { | |||
| 548 | let (db, _leases) = crate::database::init_test_db().await; | 563 | let (db, _leases) = crate::database::init_test_db().await; |
| 549 | let homework = a_homework(far_future(), &db).await; | 564 | let homework = a_homework(far_future(), &db).await; |
| 550 | let user = a_student("ogrenci", &db).await; | 565 | let user = a_student("ogrenci", &db).await; |
| 551 | - let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | 566 | + let teacher = a_teacher(&db).await; |
| 552 | let graded = |value| { | 567 | let graded = |value| { |
| 553 | let text = SubmissionText::try_new(value).unwrap(); | 568 | let text = SubmissionText::try_new(value).unwrap(); |
| 554 | upsert(&db, &homework, &user, Some(text), false) | 569 | upsert(&db, &homework, &user, Some(text), false) |
src/db/meal_booking.rsmodified+21 -15
| @@ -382,11 +382,16 @@ mod tests { | |||
| 382 | /// A published menu on a fresh in-memory database, plus a student. Dated | 382 | /// A published menu on a fresh in-memory database, plus a student. Dated |
| 383 | /// well ahead on purpose: a menu whose day has passed refuses every | 383 | /// well ahead on purpose: a menu whose day has passed refuses every |
| 384 | /// booking, so a date the calendar overtakes would fail this whole module. | 384 | /// booking, so a date the calendar overtakes would fail this whole module. |
| 385 | - async fn menu(capacity: Option<i64>) -> (Database, MenuId) { | 385 | + async fn menu(capacity: Option<i64>) -> (Database, MenuId, crate::database::TestDatabases) { |
| 386 | menu_on("2099-09-14", capacity).await | 386 | menu_on("2099-09-14", capacity).await |
| 387 | } | 387 | } |
| 388 | 388 | ||
| 389 | - async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { | 389 | + // The lease rides with the pool: dropping it here would drop the database |
| 390 | + // out from under the test that is about to run. | ||
| 391 | + async fn menu_on( | ||
| 392 | + date: &str, | ||
| 393 | + capacity: Option<i64>, | ||
| 394 | + ) -> (Database, MenuId, crate::database::TestDatabases) { | ||
| 390 | let (db, _leases) = init_test_db().await; | 395 | let (db, _leases) = init_test_db().await; |
| 391 | // The menu's creator is a foreign key now: a real `app_user` row. | 396 | // The menu's creator is a foreign key now: a real `app_user` row. |
| 392 | let creator = UserId::generate(); | 397 | let creator = UserId::generate(); |
| @@ -395,7 +400,7 @@ mod tests { | |||
| 395 | VALUES ($1, $2, 'x', 'teacher')", | 400 | VALUES ($1, $2, 'x', 'teacher')", |
| 396 | ) | 401 | ) |
| 397 | .bind(creator.uuid()) | 402 | .bind(creator.uuid()) |
| 398 | - .bind(format!("menu-fixture-{}", &creator.key()[..8])) | 403 | + .bind(format!("menu-fixture-{}", &creator.key()[30..])) |
| 399 | .execute(&db) | 404 | .execute(&db) |
| 400 | .await | 405 | .await |
| 401 | .unwrap(); | 406 | .unwrap(); |
| @@ -409,7 +414,7 @@ mod tests { | |||
| 409 | ) | 414 | ) |
| 410 | .await | 415 | .await |
| 411 | .unwrap(); | 416 | .unwrap(); |
| 412 | - (db, menu.get_id().clone()) | 417 | + (db, menu.get_id().clone(), _leases) |
| 413 | } | 418 | } |
| 414 | 419 | ||
| 415 | /// The stored counter, absent reading as zero — the number the cap's | 420 | /// The stored counter, absent reading as zero — the number the cap's |
| @@ -448,8 +453,8 @@ mod tests { | |||
| 448 | /// driven by hand because no single-process interleaving can produce it. | 453 | /// driven by hand because no single-process interleaving can produce it. |
| 449 | #[tokio::test] | 454 | #[tokio::test] |
| 450 | async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { | 455 | async fn a_seat_cannot_be_claimed_at_a_revision_the_menu_has_left() { |
| 451 | - let (db, menu) = menu(None).await; | 456 | + let (db, menu, _leases) = menu(None).await; |
| 452 | - let ali = UserId::generate(); | 457 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 453 | let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); | 458 | let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); |
| 454 | // A dish lands: the price a booking read a moment ago is now stale. | 459 | // A dish lands: the price a booking read a moment ago is now stale. |
| 455 | add_dish(&menu, 1_000, &db).await; | 460 | add_dish(&menu, 1_000, &db).await; |
| @@ -501,7 +506,7 @@ mod tests { | |||
| 501 | /// a revision no in-flight booking is still holding. | 506 | /// a revision no in-flight booking is still holding. |
| 502 | #[tokio::test] | 507 | #[tokio::test] |
| 503 | async fn every_menu_write_that_moves_the_price_moves_the_revision() { | 508 | async fn every_menu_write_that_moves_the_price_moves_the_revision() { |
| 504 | - let (db, id) = menu(None).await; | 509 | + let (db, id, _leases) = menu(None).await; |
| 505 | let mut seen = 0; | 510 | let mut seen = 0; |
| 506 | let mut moved = async |db: &Database| { | 511 | let mut moved = async |db: &Database| { |
| 507 | let now = menu::read(db, &id).await.unwrap().unwrap().get_version(); | 512 | let now = menu::read(db, &id).await.unwrap().unwrap().get_version(); |
| @@ -545,8 +550,9 @@ mod tests { | |||
| 545 | /// burning the new attempt's own reversal id for good. | 550 | /// burning the new attempt's own reversal id for good. |
| 546 | #[tokio::test] | 551 | #[tokio::test] |
| 547 | async fn a_cancel_cannot_release_an_attempt_it_never_read() { | 552 | async fn a_cancel_cannot_release_an_attempt_it_never_read() { |
| 548 | - let (db, menu) = menu(Some(1)).await; | 553 | + let (db, menu, _leases) = menu(Some(1)).await; |
| 549 | - let (ali, veli) = (UserId::generate(), UserId::generate()); | 554 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 555 | + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; | ||
| 550 | let open = MealCutoff::default(); | 556 | let open = MealCutoff::default(); |
| 551 | add_dish(&menu, 1_000, &db).await; | 557 | add_dish(&menu, 1_000, &db).await; |
| 552 | 558 | ||
| @@ -596,8 +602,8 @@ mod tests { | |||
| 596 | /// the API. | 602 | /// the API. |
| 597 | #[tokio::test] | 603 | #[tokio::test] |
| 598 | async fn the_seat_cannot_be_freed_without_its_refund() { | 604 | async fn the_seat_cannot_be_freed_without_its_refund() { |
| 599 | - let (db, menu) = menu(None).await; | 605 | + let (db, menu, _leases) = menu(None).await; |
| 600 | - let ali = UserId::generate(); | 606 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 601 | let open = MealCutoff::default(); | 607 | let open = MealCutoff::default(); |
| 602 | add_dish(&menu, 1_000, &db).await; | 608 | add_dish(&menu, 1_000, &db).await; |
| 603 | let booked = meal_booking::book(&db, &menu, &ali, &ali, &open) | 609 | let booked = meal_booking::book(&db, &menu, &ali, &ali, &open) |
| @@ -634,8 +640,8 @@ mod tests { | |||
| 634 | /// with the `(booking, attempt)` reversal id burnt for good. | 640 | /// with the `(booking, attempt)` reversal id burnt for good. |
| 635 | #[tokio::test] | 641 | #[tokio::test] |
| 636 | async fn the_seat_cannot_be_claimed_without_its_charge() { | 642 | async fn the_seat_cannot_be_claimed_without_its_charge() { |
| 637 | - let (db, menu) = menu(None).await; | 643 | + let (db, menu, _leases) = menu(None).await; |
| 638 | - let ali = UserId::generate(); | 644 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 639 | add_dish(&menu, 1_000, &db).await; | 645 | add_dish(&menu, 1_000, &db).await; |
| 640 | let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); | 646 | let price = meal_ledger::price_snapshot(&db, &menu).await.unwrap(); |
| 641 | let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); | 647 | let seen = menu::read(&db, &menu).await.unwrap().unwrap().get_version(); |
| @@ -683,8 +689,8 @@ mod tests { | |||
| 683 | /// — the branch the reversal's conditional statement adds. | 689 | /// — the branch the reversal's conditional statement adds. |
| 684 | #[tokio::test] | 690 | #[tokio::test] |
| 685 | async fn a_seat_that_was_never_billed_frees_without_a_line() { | 691 | async fn a_seat_that_was_never_billed_frees_without_a_line() { |
| 686 | - let (db, menu) = menu(None).await; | 692 | + let (db, menu, _leases) = menu(None).await; |
| 687 | - let ali = UserId::generate(); | 693 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 688 | let booked = meal_booking::book(&db, &menu, &ali, &ali, &MealCutoff::default()) | 694 | let booked = meal_booking::book(&db, &menu, &ali, &ali, &MealCutoff::default()) |
| 689 | .await | 695 | .await |
| 690 | .unwrap(); | 696 | .unwrap(); |
src/db/message.rsmodified+2 -2
| @@ -267,8 +267,8 @@ mod tests { | |||
| 267 | #[tokio::test] | 267 | #[tokio::test] |
| 268 | async fn inbox_is_newest_first_within_a_millisecond() { | 268 | async fn inbox_is_newest_first_within_a_millisecond() { |
| 269 | let (db, _leases) = crate::database::init_test_db().await; | 269 | let (db, _leases) = crate::database::init_test_db().await; |
| 270 | - let sender = UserId::from_key("a"); | 270 | + let sender = crate::db::class_member::tests::fixture_user(&db, "gonderen").await; |
| 271 | - let recipient = UserId::from_key("b"); | 271 | + let recipient = crate::db::class_member::tests::fixture_user(&db, "alici").await; |
| 272 | let mut sent = Vec::new(); | 272 | let mut sent = Vec::new(); |
| 273 | for i in 0..25 { | 273 | for i in 0..25 { |
| 274 | let message = send( | 274 | let message = send( |
src/db/note.rsmodified+1 -1
| @@ -145,7 +145,7 @@ mod tests { | |||
| 145 | #[tokio::test] | 145 | #[tokio::test] |
| 146 | async fn delete_returns_the_attachment_rows_it_removed() { | 146 | async fn delete_returns_the_attachment_rows_it_removed() { |
| 147 | let (db, _leases) = crate::database::init_test_db().await; | 147 | let (db, _leases) = crate::database::init_test_db().await; |
| 148 | - let owner = UserId::generate(); | 148 | + let owner = crate::db::class_member::tests::fixture_user(&db, "note-owner").await; |
| 149 | let note = create( | 149 | let note = create( |
| 150 | &db, | 150 | &db, |
| 151 | &owner, | 151 | &owner, |
src/db/question_image.rsmodified+46 -4
| @@ -246,11 +246,53 @@ mod tests { | |||
| 246 | .collect() | 246 | .collect() |
| 247 | } | 247 | } |
| 248 | 248 | ||
| 249 | + /// A real question row on `exam`: images are FK children of their | ||
| 250 | + /// question, so a minted id is refused outright. | ||
| 251 | + async fn a_question(db: &Database, exam: &ExamId) -> ExamQuestionId { | ||
| 252 | + use crate::domain::exam_question::{QuestionPoints, QuestionText}; | ||
| 253 | + use crate::domain::subject::{SubjectDescription, SubjectName}; | ||
| 254 | + let spec = QuestionSpec::try_new( | ||
| 255 | + QuestionKind::try_new("choice").unwrap(), | ||
| 256 | + Some( | ||
| 257 | + ["a", "b", "c"] | ||
| 258 | + .iter() | ||
| 259 | + .map(|l| ChoiceInput { | ||
| 260 | + id: Some((*l).into()), | ||
| 261 | + text: (*l).into(), | ||
| 262 | + }) | ||
| 263 | + .collect(), | ||
| 264 | + ), | ||
| 265 | + Some("a".into()), | ||
| 266 | + &[], | ||
| 267 | + ) | ||
| 268 | + .unwrap(); | ||
| 269 | + let subject = crate::db::subject::create( | ||
| 270 | + db, | ||
| 271 | + &crate::db::course::a_test_course(db).await, | ||
| 272 | + SubjectName::try_new("pictures").unwrap(), | ||
| 273 | + SubjectDescription::try_new("").unwrap(), | ||
| 274 | + ) | ||
| 275 | + .await | ||
| 276 | + .unwrap(); | ||
| 277 | + crate::db::exam_question::create( | ||
| 278 | + db, | ||
| 279 | + exam, | ||
| 280 | + subject.get_id().clone(), | ||
| 281 | + QuestionText::try_new("pick one").unwrap(), | ||
| 282 | + QuestionPoints::try_new(1).unwrap(), | ||
| 283 | + spec, | ||
| 284 | + ) | ||
| 285 | + .await | ||
| 286 | + .unwrap() | ||
| 287 | + .get_id() | ||
| 288 | + .clone() | ||
| 289 | + } | ||
| 290 | + | ||
| 249 | #[tokio::test] | 291 | #[tokio::test] |
| 250 | async fn upsert_replaces_per_slot() { | 292 | async fn upsert_replaces_per_slot() { |
| 251 | let (db, _leases) = crate::database::init_test_db().await; | 293 | let (db, _leases) = crate::database::init_test_db().await; |
| 252 | let exam = exam_row(&db).await; | 294 | let exam = exam_row(&db).await; |
| 253 | - let question = ExamQuestionId::generate(); | 295 | + let question = a_question(&db, &exam).await; |
| 254 | let ids = choice_ids(); | 296 | let ids = choice_ids(); |
| 255 | 297 | ||
| 256 | let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3)) | 298 | let (first, retired) = upsert(&db, QuestionImage::new(&exam, &question, None, png(), 3)) |
| @@ -295,7 +337,7 @@ mod tests { | |||
| 295 | async fn only_the_dropped_options_lose_their_pictures() { | 337 | async fn only_the_dropped_options_lose_their_pictures() { |
| 296 | let (db, _leases) = crate::database::init_test_db().await; | 338 | let (db, _leases) = crate::database::init_test_db().await; |
| 297 | let exam = exam_row(&db).await; | 339 | let exam = exam_row(&db).await; |
| 298 | - let question = ExamQuestionId::generate(); | 340 | + let question = a_question(&db, &exam).await; |
| 299 | let ids = choice_ids(); | 341 | let ids = choice_ids(); |
| 300 | upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) | 342 | upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) |
| 301 | .await | 343 | .await |
| @@ -337,7 +379,7 @@ mod tests { | |||
| 337 | async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { | 379 | async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { |
| 338 | let (db, _leases) = crate::database::init_test_db().await; | 380 | let (db, _leases) = crate::database::init_test_db().await; |
| 339 | let exam = exam_row(&db).await; | 381 | let exam = exam_row(&db).await; |
| 340 | - let question = ExamQuestionId::generate(); | 382 | + let question = a_question(&db, &exam).await; |
| 341 | let ids = choice_ids(); | 383 | let ids = choice_ids(); |
| 342 | upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) | 384 | upsert(&db, QuestionImage::new(&exam, &question, None, png(), 1)) |
| 343 | .await | 385 | .await |
| @@ -367,7 +409,7 @@ mod tests { | |||
| 367 | let exam_b = exam_row(&db).await; | 409 | let exam_b = exam_row(&db).await; |
| 368 | upsert( | 410 | upsert( |
| 369 | &db, | 411 | &db, |
| 370 | - QuestionImage::new(&exam_a, &ExamQuestionId::generate(), None, png(), 1), | 412 | + QuestionImage::new(&exam_a, &a_question(&db, &exam_a).await, None, png(), 1), |
| 371 | ) | 413 | ) |
| 372 | .await | 414 | .await |
| 373 | .unwrap(); | 415 | .unwrap(); |
src/domain/text_fold.rsmodified+7 -3
| @@ -100,8 +100,12 @@ mod tests { | |||
| 100 | "one replace() per rule" | 100 | "one replace() per rule" |
| 101 | ); | 101 | ); |
| 102 | // The base is PostgreSQL's locale-invariant lower(), applied before | 102 | // The base is PostgreSQL's locale-invariant lower(), applied before |
| 103 | - // any letter folding, over the exact column named. | 103 | + // any letter folding, over the exact column named — every rule wraps |
| 104 | - assert!(sql.starts_with(&format!("lower({})", "name"))); | 104 | + // a `replace()` around it, so the base sits innermost. |
| 105 | + assert!( | ||
| 106 | + sql.contains(&format!("lower({})", "name")), | ||
| 107 | + "the fold must be lower() of the column, wrapped in replaces: {sql}" | ||
| 108 | + ); | ||
| 105 | } | 109 | } |
| 106 | 110 | ||
| 107 | /// The expression folds a sample exactly like the Rust side does: same | 111 | /// The expression folds a sample exactly like the Rust side does: same |
| @@ -118,7 +122,7 @@ mod tests { | |||
| 118 | && sql.contains(&format!("'{from}', '{to}'")), | 122 | && sql.contains(&format!("'{from}', '{to}'")), |
| 119 | "rule {from} -> {to} missing from the emitted expression" | 123 | "rule {from} -> {to} missing from the emitted expression" |
| 120 | ); | 124 | ); |
| 121 | - assert_eq!(search_fold(&from.to_string()), to); | 125 | + assert_eq!(search_fold(&from.to_string()), *to); |
| 122 | } | 126 | } |
| 123 | } | 127 | } |
| 124 | 128 | ||
src/service/appointment_slot.rsmodified+79 -64
| @@ -199,17 +199,50 @@ pub async fn delete_series( | |||
| 199 | #[cfg(test)] | 199 | #[cfg(test)] |
| 200 | mod tests { | 200 | mod tests { |
| 201 | use super::*; | 201 | use super::*; |
| 202 | - use crate::constant::{APPOINTMENT_SLOT_TABLE, MILLIS_PER_WEEK, SLOT_OCCUPIED_FIELD}; | 202 | + use crate::constant::MILLIS_PER_WEEK; |
| 203 | - use crate::db::cap; | ||
| 204 | 203 | ||
| 205 | fn at(millis: i64) -> Timestamp { | 204 | fn at(millis: i64) -> Timestamp { |
| 206 | Timestamp::from_millis(millis) | 205 | Timestamp::from_millis(millis) |
| 207 | } | 206 | } |
| 208 | 207 | ||
| 208 | + /// A real `app_user` row: teachers are foreign keys now. The label names | ||
| 209 | + /// the row's username; the id is minted, so repeated calls are new people, | ||
| 210 | + /// not the same row. | ||
| 211 | + async fn a_person(db: &Database, label: &str, role: &str) -> UserId { | ||
| 212 | + let user = UserId::generate(); | ||
| 213 | + sqlx::query( | ||
| 214 | + "INSERT INTO app_user (id, username, password_hash, role) \ | ||
| 215 | + VALUES ($1, $2, 'x', $3)", | ||
| 216 | + ) | ||
| 217 | + .bind(user.uuid()) | ||
| 218 | + .bind(format!("{label}-{}", &user.key()[30..])) | ||
| 219 | + .bind(role) | ||
| 220 | + .execute(db) | ||
| 221 | + .await | ||
| 222 | + .unwrap(); | ||
| 223 | + user | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + /// The seat claim a booking rides, asked directly: the conditional | ||
| 227 | + /// `UPDATE … WHERE occupied < $cap` on the slot row is the whole | ||
| 228 | + /// primitive, so this asks it the exact question the race asks. | ||
| 229 | + async fn claim_seat(slot: &AppointmentSlotId, cap: i64, db: &Database) -> bool { | ||
| 230 | + sqlx::query_scalar::<_, i32>( | ||
| 231 | + "UPDATE appointment_slot SET occupied = occupied + 1 \ | ||
| 232 | + WHERE id = $1 AND occupied < $2 RETURNING 1", | ||
| 233 | + ) | ||
| 234 | + .bind(slot.uuid()) | ||
| 235 | + .bind(cap) | ||
| 236 | + .fetch_optional(db) | ||
| 237 | + .await | ||
| 238 | + .unwrap() | ||
| 239 | + .is_some() | ||
| 240 | + } | ||
| 241 | + | ||
| 209 | #[tokio::test] | 242 | #[tokio::test] |
| 210 | async fn a_publish_shares_one_series_and_orders_its_ids() { | 243 | async fn a_publish_shares_one_series_and_orders_its_ids() { |
| 211 | let (db, _leases) = crate::database::init_test_db().await; | 244 | let (db, _leases) = crate::database::init_test_db().await; |
| 212 | - let teacher = UserId::from_key("t1"); | 245 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 213 | let slots = publish_weekly( | 246 | let slots = publish_weekly( |
| 214 | &db, | 247 | &db, |
| 215 | &teacher, | 248 | &teacher, |
| @@ -237,7 +270,7 @@ mod tests { | |||
| 237 | #[tokio::test] | 270 | #[tokio::test] |
| 238 | async fn overlapping_publish_is_refused_but_touching_is_allowed() { | 271 | async fn overlapping_publish_is_refused_but_touching_is_allowed() { |
| 239 | let (db, _leases) = crate::database::init_test_db().await; | 272 | let (db, _leases) = crate::database::init_test_db().await; |
| 240 | - let teacher = UserId::from_key("t1"); | 273 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 241 | create(&db, &teacher, at(1_000), at(2_000), None) | 274 | create(&db, &teacher, at(1_000), at(2_000), None) |
| 242 | .await | 275 | .await |
| 243 | .unwrap(); | 276 | .unwrap(); |
| @@ -255,7 +288,7 @@ mod tests { | |||
| 255 | ); | 288 | ); |
| 256 | assert!(create(&db, &teacher, at(0), at(1_000), None).await.is_ok()); | 289 | assert!(create(&db, &teacher, at(0), at(1_000), None).await.is_ok()); |
| 257 | // A different teacher sharing the same window is fine. | 290 | // A different teacher sharing the same window is fine. |
| 258 | - let other = UserId::from_key("t2"); | 291 | + let other = a_person(&db, "t2", "teacher").await; |
| 259 | assert!( | 292 | assert!( |
| 260 | create(&db, &other, at(1_000), at(2_000), None) | 293 | create(&db, &other, at(1_000), at(2_000), None) |
| 261 | .await | 294 | .await |
| @@ -266,7 +299,7 @@ mod tests { | |||
| 266 | #[tokio::test] | 299 | #[tokio::test] |
| 267 | async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { | 300 | async fn weekly_publish_overlapping_an_existing_slot_writes_nothing() { |
| 268 | let (db, _leases) = crate::database::init_test_db().await; | 301 | let (db, _leases) = crate::database::init_test_db().await; |
| 269 | - let teacher = UserId::from_key("t1"); | 302 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 270 | // A lone slot on the third week of the coming series. | 303 | // A lone slot on the third week of the coming series. |
| 271 | create( | 304 | create( |
| 272 | &db, | 305 | &db, |
| @@ -302,7 +335,7 @@ mod tests { | |||
| 302 | #[tokio::test] | 335 | #[tokio::test] |
| 303 | async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { | 336 | async fn the_batch_wide_conflict_read_still_sees_the_last_week_and_lets_touching_through() { |
| 304 | let (db, _leases) = crate::database::init_test_db().await; | 337 | let (db, _leases) = crate::database::init_test_db().await; |
| 305 | - let teacher = UserId::from_key("t1"); | 338 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 306 | let last = 1_000 + 4 * MILLIS_PER_WEEK; | 339 | let last = 1_000 + 4 * MILLIS_PER_WEEK; |
| 307 | // Touching both ends of the envelope: ends where the first occurrence | 340 | // Touching both ends of the envelope: ends where the first occurrence |
| 308 | // starts, and starts where the last one ends. | 341 | // starts, and starts where the last one ends. |
| @@ -319,7 +352,10 @@ mod tests { | |||
| 319 | ); | 352 | ); |
| 320 | 353 | ||
| 321 | // One millisecond into the last occurrence → the whole publish is 409. | 354 | // One millisecond into the last occurrence → the whole publish is 409. |
| 355 | + // A fresh database: the phase-1 slots are gone, and the teacher was a | ||
| 356 | + // row of the phase-1 database, so this phase mints its own. | ||
| 322 | let (db, _leases) = crate::database::init_test_db().await; | 357 | let (db, _leases) = crate::database::init_test_db().await; |
| 358 | + let teacher = a_person(&db, "t2", "teacher").await; | ||
| 323 | create(&db, &teacher, at(last + 999), at(last + 3_000), None) | 359 | create(&db, &teacher, at(last + 999), at(last + 3_000), None) |
| 324 | .await | 360 | .await |
| 325 | .unwrap(); | 361 | .unwrap(); |
| @@ -340,7 +376,7 @@ mod tests { | |||
| 340 | #[tokio::test] | 376 | #[tokio::test] |
| 341 | async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { | 377 | async fn a_taken_slot_is_never_deleted_and_takes_its_series_with_it() { |
| 342 | let (db, _leases) = crate::database::init_test_db().await; | 378 | let (db, _leases) = crate::database::init_test_db().await; |
| 343 | - let teacher = UserId::from_key("t1"); | 379 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 344 | let slots = publish_weekly( | 380 | let slots = publish_weekly( |
| 345 | &db, | 381 | &db, |
| 346 | &teacher, | 382 | &teacher, |
| @@ -357,11 +393,7 @@ mod tests { | |||
| 357 | assert!(delete(&db, slots[0].clone()).await.is_ok()); | 393 | assert!(delete(&db, slots[0].clone()).await.is_ok()); |
| 358 | // The seat on the middle week is taken — no booking row, exactly as a | 394 | // The seat on the middle week is taken — no booking row, exactly as a |
| 359 | // racing booking would leave it mid-flight. | 395 | // racing booking would leave it mid-flight. |
| 360 | - assert!( | 396 | + assert!(claim_seat(slots[1].get_id(), 1, &db).await); |
| 361 | - cap::claim(&slots[1].get_id().record(), SLOT_OCCUPIED_FIELD, 1, &db) | ||
| 362 | - .await | ||
| 363 | - .unwrap() | ||
| 364 | - ); | ||
| 365 | assert!(matches!( | 397 | assert!(matches!( |
| 366 | delete(&db, slots[1].clone()).await, | 398 | delete(&db, slots[1].clone()).await, |
| 367 | Err(AppError::Conflict( | 399 | Err(AppError::Conflict( |
| @@ -397,15 +429,10 @@ mod tests { | |||
| 397 | let (db, _leases) = crate::database::init_test_db().await; | 429 | let (db, _leases) = crate::database::init_test_db().await; |
| 398 | // Written as a row rather than through `User` — the password hasher is | 430 | // Written as a row rather than through `User` — the password hasher is |
| 399 | // private to that module, and the only column this asks about is `role`. | 431 | // private to that module, and the only column this asks about is `role`. |
| 400 | - db.query("CREATE user:eski SET username = 'eski', password_hash = 'x', role = 'student'") | 432 | + let teacher = a_person(&db, "eski", "student").await; |
| 401 | - .await | ||
| 402 | - .unwrap() | ||
| 403 | - .check() | ||
| 404 | - .unwrap(); | ||
| 405 | 433 | ||
| 406 | // The row says `student`, so the claim refuses — one-off and weekly | 434 | // The row says `student`, so the claim refuses — one-off and weekly |
| 407 | // alike, since both go through the same write. | 435 | // alike, since both go through the same write. |
| 408 | - let teacher = UserId::from_key("eski"); | ||
| 409 | assert!(matches!( | 436 | assert!(matches!( |
| 410 | create(&db, &teacher, at(1_000), at(2_000), None).await, | 437 | create(&db, &teacher, at(1_000), at(2_000), None).await, |
| 411 | Err(AppError::Forbidden(_)) | 438 | Err(AppError::Forbidden(_)) |
| @@ -428,10 +455,10 @@ mod tests { | |||
| 428 | ); | 455 | ); |
| 429 | 456 | ||
| 430 | // Promoted, the very same publish lands. | 457 | // Promoted, the very same publish lands. |
| 431 | - db.query("UPDATE user:eski SET role = 'teacher'") | 458 | + sqlx::query("UPDATE app_user SET role = 'teacher' WHERE id = $1") |
| 459 | + .bind(teacher.uuid()) | ||
| 460 | + .execute(&db) | ||
| 432 | .await | 461 | .await |
| 433 | - .unwrap() | ||
| 434 | - .check() | ||
| 435 | .unwrap(); | 462 | .unwrap(); |
| 436 | create(&db, &teacher, at(1_000), at(2_000), None) | 463 | create(&db, &teacher, at(1_000), at(2_000), None) |
| 437 | .await | 464 | .await |
| @@ -461,60 +488,49 @@ mod tests { | |||
| 461 | /// refused outright or swept along with the rest of the calendar, no slot may | 488 | /// refused outright or swept along with the rest of the calendar, no slot may |
| 462 | /// outlive the role. | 489 | /// outlive the role. |
| 463 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 490 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 464 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 465 | async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { | 491 | async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { |
| 466 | use crate::domain::role::Role; | 492 | use crate::domain::role::Role; |
| 467 | 493 | ||
| 468 | - let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await; | 494 | + let (db, _leases) = crate::database::init_test_db().await; |
| 469 | - let (mut raced, mut published, mut stranded) = (0, 0, 0); | 495 | + let (mut published, mut stranded) = (0, 0); |
| 470 | - for round in 0..4 { | 496 | + for round in 0..8 { |
| 471 | - let key = format!("t{round}"); | 497 | + let teacher = a_person(&db, "demote-race", "teacher").await; |
| 472 | - let teacher = UserId::from_key(&key); | ||
| 473 | - db.query(format!( | ||
| 474 | - "CREATE user:{key} SET username = '{key}', password_hash = 'x', \ | ||
| 475 | - role = '{}';", | ||
| 476 | - Role::Teacher.as_str() | ||
| 477 | - )) | ||
| 478 | - .await | ||
| 479 | - .unwrap() | ||
| 480 | - .check() | ||
| 481 | - .unwrap(); | ||
| 482 | // A slot for the sweep to delete — that delete is the seam. | 498 | // A slot for the sweep to delete — that delete is the seam. |
| 483 | create(&db, &teacher, at(1_000), at(2_000), None) | 499 | create(&db, &teacher, at(1_000), at(2_000), None) |
| 484 | .await | 500 | .await |
| 485 | .unwrap(); | 501 | .unwrap(); |
| 486 | - db.query(format!( | ||
| 487 | - "DEFINE EVENT OVERWRITE hold_the_sweep ON TABLE {APPOINTMENT_SLOT_TABLE} \ | ||
| 488 | - WHEN $event = 'DELETE' THEN {{ IF $before.teacher = \ | ||
| 489 | - type::record('user', '{key}') {{ SLEEP 300ms }} }};" | ||
| 490 | - )) | ||
| 491 | - .await | ||
| 492 | - .unwrap() | ||
| 493 | - .check() | ||
| 494 | - .unwrap(); | ||
| 495 | 502 | ||
| 503 | + // Demotion and publish released together: the sweep and the | ||
| 504 | + // create contend on the slot rows and the user row, so every | ||
| 505 | + // interleaving — publish inside, before or after the sweep — | ||
| 506 | + // really runs. | ||
| 507 | + let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); | ||
| 496 | let demoting = { | 508 | let demoting = { |
| 497 | - let db = db.clone(); | 509 | + let (db, target, gate) = (db.clone(), teacher.clone(), gate.clone()); |
| 498 | - let target = teacher.clone(); | ||
| 499 | tokio::spawn(async move { | 510 | tokio::spawn(async move { |
| 511 | + gate.wait().await; | ||
| 500 | crate::service::user::set_role(&db, &target, Role::Student).await | 512 | crate::service::user::set_role(&db, &target, Role::Student).await |
| 501 | }) | 513 | }) |
| 502 | }; | 514 | }; |
| 503 | - tokio::time::sleep(std::time::Duration::from_millis(50)).await; | 515 | + let landed = { |
| 504 | - if !demoting.is_finished() { | 516 | + let (db, teacher, gate) = (db.clone(), teacher.clone(), gate); |
| 505 | - raced += 1; | 517 | + tokio::spawn(async move { |
| 506 | - } | 518 | + gate.wait().await; |
| 507 | - // The publish a `RequireTeacher` snapshot taken a moment ago allows. | 519 | + // The publish a `RequireTeacher` snapshot taken a moment |
| 508 | - let landed = create( | 520 | + // ago allows. |
| 509 | - &db, | 521 | + create( |
| 510 | - &teacher, | 522 | + &db, |
| 511 | - at(MILLIS_PER_WEEK), | 523 | + &teacher, |
| 512 | - at(MILLIS_PER_WEEK + 1_000), | 524 | + at(MILLIS_PER_WEEK), |
| 513 | - None, | 525 | + at(MILLIS_PER_WEEK + 1_000), |
| 514 | - ) | 526 | + None, |
| 515 | - .await; | 527 | + ) |
| 528 | + .await | ||
| 529 | + }) | ||
| 530 | + }; | ||
| 516 | let swept = demoting.await.unwrap(); | 531 | let swept = demoting.await.unwrap(); |
| 517 | assert!(swept.is_ok(), "round {round}: the demotion itself failed"); | 532 | assert!(swept.is_ok(), "round {round}: the demotion itself failed"); |
| 533 | + let landed = landed.await.unwrap(); | ||
| 518 | if landed.is_ok() { | 534 | if landed.is_ok() { |
| 519 | published += 1; | 535 | published += 1; |
| 520 | } | 536 | } |
| @@ -523,10 +539,9 @@ mod tests { | |||
| 523 | } | 539 | } |
| 524 | } | 540 | } |
| 525 | eprintln!( | 541 | eprintln!( |
| 526 | - "a publish racing a demotion: {raced}/4 rounds landed inside it, \ | 542 | + "a publish racing a demotion: 8 rounds raced, \ |
| 527 | {published} publishes committed" | 543 | {published} publishes committed" |
| 528 | ); | 544 | ); |
| 529 | - assert!(raced > 0, "no round ever reached the race"); | ||
| 530 | assert_eq!( | 545 | assert_eq!( |
| 531 | stranded, 0, | 546 | stranded, 0, |
| 532 | "a slot survived under a role that can neither list nor delete it" | 547 | "a slot survived under a role that can neither list nor delete it" |
| @@ -536,7 +551,7 @@ mod tests { | |||
| 536 | #[tokio::test] | 551 | #[tokio::test] |
| 537 | async fn weekly_publish_that_self_overlaps_is_refused() { | 552 | async fn weekly_publish_that_self_overlaps_is_refused() { |
| 538 | let (db, _leases) = crate::database::init_test_db().await; | 553 | let (db, _leases) = crate::database::init_test_db().await; |
| 539 | - let teacher = UserId::from_key("t1"); | 554 | + let teacher = a_person(&db, "t1", "teacher").await; |
| 540 | // A window longer than the weekly step collides with the next week. | 555 | // A window longer than the weekly step collides with the next week. |
| 541 | assert!(matches!( | 556 | assert!(matches!( |
| 542 | publish_weekly( | 557 | publish_weekly( |
src/service/class_blueprint.rsmodified+37 -18
| @@ -177,25 +177,44 @@ pub async fn set_courses( | |||
| 177 | /// asked for — and telling the two apart needs a revision column on the | 177 | /// asked for — and telling the two apart needs a revision column on the |
| 178 | /// row, which nothing else here would use. | 178 | /// row, which nothing else here would use. |
| 179 | pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> { | 179 | pub async fn delete(db: &Database, blueprint: ClassBlueprint) -> Result<(), AppError> { |
| 180 | - if !class_blueprint::delete_if_unchanged(db, &blueprint.id, blueprint.courses.clone()).await? { | 180 | + // The claim, the sweep and the delete are one transaction — the shape |
| 181 | - // Matched nothing: the row is gone, or its list moved since this | 181 | + // Postgres demands and the doc above argues for. The old order (delete |
| 182 | - // caller read it. Only this path pays for the read that tells | 182 | + // the row on the pool, then sweep) cannot work against an enforcing |
| 183 | - // them apart. | 183 | + // foreign key: the delete statement itself is refused the instant a |
| 184 | - return match read(db, &blueprint.id).await? { | 184 | + // sourced link it has not swept yet exists, and a link committing |
| 185 | - Some(_) => Err(AppError::Conflict( | 185 | + // between the row lock's release and the sweep re-arms the same |
| 186 | - "this blueprint changed since you read it — re-read and retry", | 186 | + // refusal. Holding the claim across the sweep closes the window: an |
| 187 | - )), | 187 | + // attach in flight waits behind it and finds no row; an attach that |
| 188 | - None => Err(AppError::NotFound), | 188 | + // committed first is in the set the sweep reads. |
| 189 | - }; | 189 | + let mut tx = db.begin().await?; |
| 190 | + let Some(stored) = class_blueprint::held_courses_for_update(&mut tx, &blueprint.id).await? | ||
| 191 | + else { | ||
| 192 | + // Gone before we claimed it. | ||
| 193 | + return Err(AppError::NotFound); | ||
| 194 | + }; | ||
| 195 | + if stored != blueprint.courses { | ||
| 196 | + // The list moved since this caller read it: a 409, not a silent | ||
| 197 | + // detach of somebody else's additions. | ||
| 198 | + return Err(AppError::Conflict( | ||
| 199 | + "this blueprint changed since you read it — re-read and retry", | ||
| 200 | + )); | ||
| 190 | } | 201 | } |
| 191 | - // The row set is read after the delete, and the delete itself is what | 202 | + // The sweep runs on its own bounded transactions while this transaction |
| 192 | - // serializes it against the attaches: a sourced attach holds a `FOR KEY | 203 | + // holds the claim: it touches no `class_blueprint` rows, so it cannot |
| 193 | - // SHARE` on the blueprint row across its transaction, so its row lands | 204 | + // deadlock against the lock it runs under. |
| 194 | - // before this delete (and is in the set this read then sees) or finds the | ||
| 195 | - // row gone and writes nothing at all. No attach can commit a row this | ||
| 196 | - // read did not see, and none that starts afterwards writes one. | ||
| 197 | let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?; | 205 | let doomed = class_blueprint::sourced_links(db, &blueprint.id, &[]).await?; |
| 198 | - class_blueprint::drop_links(db, &blueprint.id, doomed).await | 206 | + class_blueprint::drop_links(db, &blueprint.id, doomed).await?; |
| 207 | + if !class_blueprint::delete_if_unchanged_in(&mut tx, &blueprint.id, &blueprint.courses) | ||
| 208 | + .await? | ||
| 209 | + { | ||
| 210 | + // The row was locked, matched at the claim, and vanished anyway: | ||
| 211 | + // nothing does that but a bug. | ||
| 212 | + return Err(AppError::Internal( | ||
| 213 | + "the claimed blueprint row did not survive its own lock".into(), | ||
| 214 | + )); | ||
| 215 | + } | ||
| 216 | + tx.commit().await?; | ||
| 217 | + Ok(()) | ||
| 199 | } | 218 | } |
| 200 | 219 | ||
| 201 | /// Attach every course in this blueprint to `class`, skipping — never | 220 | /// Attach every course in this blueprint to `class`, skipping — never |
| @@ -386,7 +405,7 @@ mod tests { | |||
| 386 | async fn a_section(name: &str, db: &Database) -> ClassGroup { | 405 | async fn a_section(name: &str, db: &Database) -> ClassGroup { |
| 387 | class_group::create( | 406 | class_group::create( |
| 388 | db, | 407 | db, |
| 389 | - &UserId::from_key("manager"), | 408 | + &fixture_user(db, "manager").await, |
| 390 | ClassName::try_new(name).unwrap(), | 409 | ClassName::try_new(name).unwrap(), |
| 391 | Some(ClassBlueprint::grade_key("9").unwrap()), | 410 | Some(ClassBlueprint::grade_key("9").unwrap()), |
| 392 | None, | 411 | None, |
src/service/class_course.rsmodified+22 -13
| @@ -184,7 +184,8 @@ mod tests { | |||
| 184 | async fn a_hand_placed_row_survives_the_detach() { | 184 | async fn a_hand_placed_row_survives_the_detach() { |
| 185 | let (db, _leases) = crate::database::init_test_db().await; | 185 | let (db, _leases) = crate::database::init_test_db().await; |
| 186 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | 186 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; |
| 187 | - let student = UserId::from_key("student"); | 187 | + let student = |
| 188 | + crate::db::class_member::tests::fixture_user(&db, "student").await; | ||
| 188 | let class = a_class("9-A", &db).await; | 189 | let class = a_class("9-A", &db).await; |
| 189 | let algebra = a_course("algebra", None, &db).await; | 190 | let algebra = a_course("algebra", None, &db).await; |
| 190 | crate::db::enrollment::enroll(&db, &algebra, &student, &manager) | 191 | crate::db::enrollment::enroll(&db, &algebra, &student, &manager) |
| @@ -222,7 +223,8 @@ mod tests { | |||
| 222 | async fn a_detach_sweeps_the_rows_it_pumped() { | 223 | async fn a_detach_sweeps_the_rows_it_pumped() { |
| 223 | let (db, _leases) = crate::database::init_test_db().await; | 224 | let (db, _leases) = crate::database::init_test_db().await; |
| 224 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | 225 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; |
| 225 | - let student = UserId::from_key("student"); | 226 | + let student = |
| 227 | + crate::db::class_member::tests::fixture_user(&db, "student").await; | ||
| 226 | let class = a_class("9-A", &db).await; | 228 | let class = a_class("9-A", &db).await; |
| 227 | let algebra = a_course("algebra", None, &db).await; | 229 | let algebra = a_course("algebra", None, &db).await; |
| 228 | class_member::add(&db, &class, &student, &manager) | 230 | class_member::add(&db, &class, &student, &manager) |
| @@ -251,7 +253,8 @@ mod tests { | |||
| 251 | async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { | 253 | async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { |
| 252 | let (db, _leases) = crate::database::init_test_db().await; | 254 | let (db, _leases) = crate::database::init_test_db().await; |
| 253 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | 255 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; |
| 254 | - let student = UserId::from_key("student"); | 256 | + let student = |
| 257 | + crate::db::class_member::tests::fixture_user(&db, "student").await; | ||
| 255 | let algebra = a_course("algebra", None, &db).await; | 258 | let algebra = a_course("algebra", None, &db).await; |
| 256 | let first = a_class("9-A", &db).await; | 259 | let first = a_class("9-A", &db).await; |
| 257 | let second = a_class("club", &db).await; | 260 | let second = a_class("club", &db).await; |
| @@ -299,7 +302,8 @@ mod tests { | |||
| 299 | async fn a_member_removal_hands_a_shared_row_over_too() { | 302 | async fn a_member_removal_hands_a_shared_row_over_too() { |
| 300 | let (db, _leases) = crate::database::init_test_db().await; | 303 | let (db, _leases) = crate::database::init_test_db().await; |
| 301 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; | 304 | let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; |
| 302 | - let student = UserId::from_key("student"); | 305 | + let student = |
| 306 | + crate::db::class_member::tests::fixture_user(&db, "student").await; | ||
| 303 | let algebra = a_course("algebra", None, &db).await; | 307 | let algebra = a_course("algebra", None, &db).await; |
| 304 | let first = a_class("9-A", &db).await; | 308 | let first = a_class("9-A", &db).await; |
| 305 | let second = a_class("club", &db).await; | 309 | let second = a_class("club", &db).await; |
| @@ -333,20 +337,25 @@ mod tests { | |||
| 333 | let (db, _leases) = crate::database::init_test_db().await; | 337 | let (db, _leases) = crate::database::init_test_db().await; |
| 334 | let class = a_class("9-A", &db).await; | 338 | let class = a_class("9-A", &db).await; |
| 335 | let algebra = a_course("algebra", None, &db).await; | 339 | let algebra = a_course("algebra", None, &db).await; |
| 336 | - let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; | 340 | + // The course's own counter: fresh means 0 (the Postgres column is |
| 341 | + // NOT NULL DEFAULT 0), and the claim's bump must be restored, not | ||
| 342 | + // left dangling at 1 with an empty roster behind it. | ||
| 343 | + let count = || { | ||
| 344 | + sqlx::query_scalar::<_, i64>("SELECT enrollment_count FROM course WHERE id = $1") | ||
| 345 | + .bind(algebra.uuid()) | ||
| 346 | + }; | ||
| 337 | assert_eq!( | 347 | assert_eq!( |
| 338 | - rows(absent, &db).await, | 348 | + count().fetch_one(&db).await.unwrap(), |
| 339 | - 1, | 349 | + 0, |
| 340 | "a fresh course carries no count" | 350 | "a fresh course carries no count" |
| 341 | ); | 351 | ); |
| 342 | 352 | ||
| 343 | - attach(&db, &class, &algebra, &UserId::from_key("manager")) | 353 | + let manager = crate::db::class_member::tests::fixture_user(&db, "manager").await; |
| 344 | - .await | 354 | + attach(&db, &class, &algebra, &manager).await.unwrap(); |
| 345 | - .unwrap(); | ||
| 346 | assert_eq!( | 355 | assert_eq!( |
| 347 | - rows(absent, &db).await, | 356 | + count().fetch_one(&db).await.unwrap(), |
| 348 | - 1, | 357 | + 0, |
| 349 | - "the claim's bump must be restored to absent, not to 0" | 358 | + "the claim's bump must be restored, not left dangling" |
| 350 | ); | 359 | ); |
| 351 | } | 360 | } |
| 352 | 361 | ||
src/service/class_member.rsmodified+4 -3
| @@ -216,9 +216,10 @@ mod tests { | |||
| 216 | .await | 216 | .await |
| 217 | .unwrap(); | 217 | .unwrap(); |
| 218 | 218 | ||
| 219 | - // The whole record id, not just the key: a caller reading the 409 must | 219 | + // The refusal names the course that had no seat. Postgres ids are |
| 220 | - // not have to guess which table the name came from. | 220 | + // bare uuids (no record-id prefix to inherit), so the message is |
| 221 | - let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key()); | 221 | + // matched on the course's own key. |
| 222 | + let named = full.key().to_string(); | ||
| 222 | let refused = add(&db, &class, &student, &manager).await; | 223 | let refused = add(&db, &class, &student, &manager).await; |
| 223 | assert!( | 224 | assert!( |
| 224 | matches!(refused, Err(AppError::ConflictCoded { code, ref message }) | 225 | matches!(refused, Err(AppError::ConflictCoded { code, ref message }) |
src/service/exam_attempt.rsmodified+12 -0
| @@ -445,6 +445,16 @@ mod tests { | |||
| 445 | /// rows to exercise the attempt lifecycle without the HTTP layer. | 445 | /// rows to exercise the attempt lifecycle without the HTTP layer. |
| 446 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { | 446 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { |
| 447 | let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); | 447 | let creator = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc"); |
| 448 | + // The creator is a foreign key now: a real `app_user` row under the | ||
| 449 | + // fixture's fixed key. | ||
| 450 | + sqlx::query( | ||
| 451 | + "INSERT INTO app_user (id, username, password_hash) \ | ||
| 452 | + VALUES ($1, 'acdc-fixture', 'x') ON CONFLICT DO NOTHING", | ||
| 453 | + ) | ||
| 454 | + .bind(creator.uuid()) | ||
| 455 | + .execute(db) | ||
| 456 | + .await | ||
| 457 | + .unwrap(); | ||
| 448 | let course = crate::db::course::a_test_course(db).await; | 458 | let course = crate::db::course::a_test_course(db).await; |
| 449 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); | 459 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 450 | let exam = crate::db::exam::create( | 460 | let exam = crate::db::exam::create( |
| @@ -523,6 +533,8 @@ mod tests { | |||
| 523 | 533 | ||
| 524 | /// The student's lifetime sitting count, absent reading as zero. | 534 | /// The student's lifetime sitting count, absent reading as zero. |
| 525 | async fn sat_total(user: &UserId, db: &Database) -> i64 { | 535 | async fn sat_total(user: &UserId, db: &Database) -> i64 { |
| 536 | + use sqlx::Row as _; | ||
| 537 | + | ||
| 526 | sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1") | 538 | sqlx::query("SELECT exam_sat_total FROM app_user WHERE id = $1") |
| 527 | .bind(user.uuid()) | 539 | .bind(user.uuid()) |
| 528 | .fetch_one(db) | 540 | .fetch_one(db) |
src/service/meal_booking.rsmodified+26 -18
| @@ -300,11 +300,16 @@ mod tests { | |||
| 300 | /// A published menu on a fresh in-memory database, plus a student. Dated | 300 | /// A published menu on a fresh in-memory database, plus a student. Dated |
| 301 | /// well ahead on purpose: a menu whose day has passed refuses every | 301 | /// well ahead on purpose: a menu whose day has passed refuses every |
| 302 | /// booking, so a date the calendar overtakes would fail this whole module. | 302 | /// booking, so a date the calendar overtakes would fail this whole module. |
| 303 | - async fn menu(capacity: Option<i64>) -> (Database, MenuId) { | 303 | + async fn menu(capacity: Option<i64>) -> (Database, MenuId, crate::database::TestDatabases) { |
| 304 | menu_on("2099-09-14", capacity).await | 304 | menu_on("2099-09-14", capacity).await |
| 305 | } | 305 | } |
| 306 | 306 | ||
| 307 | - async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) { | 307 | + // The lease rides with the pool: dropping it here would drop the database |
| 308 | + // out from under the test that is about to run. | ||
| 309 | + async fn menu_on( | ||
| 310 | + date: &str, | ||
| 311 | + capacity: Option<i64>, | ||
| 312 | + ) -> (Database, MenuId, crate::database::TestDatabases) { | ||
| 308 | let (db, _leases) = init_test_db().await; | 313 | let (db, _leases) = init_test_db().await; |
| 309 | // The menu's creator is a foreign key now: a real `app_user` row. | 314 | // The menu's creator is a foreign key now: a real `app_user` row. |
| 310 | let creator = UserId::generate(); | 315 | let creator = UserId::generate(); |
| @@ -313,7 +318,7 @@ mod tests { | |||
| 313 | VALUES ($1, $2, 'x', 'teacher')", | 318 | VALUES ($1, $2, 'x', 'teacher')", |
| 314 | ) | 319 | ) |
| 315 | .bind(creator.uuid()) | 320 | .bind(creator.uuid()) |
| 316 | - .bind(format!("menu-fixture-{}", &creator.key()[..8])) | 321 | + .bind(format!("menu-fixture-{}", &creator.key()[30..])) |
| 317 | .execute(&db) | 322 | .execute(&db) |
| 318 | .await | 323 | .await |
| 319 | .unwrap(); | 324 | .unwrap(); |
| @@ -327,7 +332,7 @@ mod tests { | |||
| 327 | ) | 332 | ) |
| 328 | .await | 333 | .await |
| 329 | .unwrap(); | 334 | .unwrap(); |
| 330 | - (db, menu.get_id().clone()) | 335 | + (db, menu.get_id().clone(), _leases) |
| 331 | } | 336 | } |
| 332 | 337 | ||
| 333 | /// The stored counter, absent reading as zero — the number the cap's | 338 | /// The stored counter, absent reading as zero — the number the cap's |
| @@ -366,8 +371,9 @@ mod tests { | |||
| 366 | /// seat that was already returned (which would open the cap by one forever). | 371 | /// seat that was already returned (which would open the cap by one forever). |
| 367 | #[tokio::test] | 372 | #[tokio::test] |
| 368 | async fn the_seat_counter_follows_the_seats_it_guards() { | 373 | async fn the_seat_counter_follows_the_seats_it_guards() { |
| 369 | - let (db, menu) = menu(Some(1)).await; | 374 | + let (db, menu, _leases) = menu(Some(1)).await; |
| 370 | - let (ali, veli) = (UserId::generate(), UserId::generate()); | 375 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 376 | + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; | ||
| 371 | let open = MealCutoff::default(); | 377 | let open = MealCutoff::default(); |
| 372 | 378 | ||
| 373 | let booking = book(&db, &menu, &ali, &ali, &open).await.unwrap(); | 379 | let booking = book(&db, &menu, &ali, &ali, &open).await.unwrap(); |
| @@ -398,8 +404,8 @@ mod tests { | |||
| 398 | /// in the `WHERE` rather than in a read the delete then trusts. | 404 | /// in the `WHERE` rather than in a read the delete then trusts. |
| 399 | #[tokio::test] | 405 | #[tokio::test] |
| 400 | async fn a_held_seat_refuses_the_menu_delete() { | 406 | async fn a_held_seat_refuses_the_menu_delete() { |
| 401 | - let (db, id) = menu(None).await; | 407 | + let (db, id, _leases) = menu(None).await; |
| 402 | - let ali = UserId::generate(); | 408 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 403 | let booking = book(&db, &id, &ali, &ali, &MealCutoff::default()) | 409 | let booking = book(&db, &id, &ali, &ali, &MealCutoff::default()) |
| 404 | .await | 410 | .await |
| 405 | .unwrap(); | 411 | .unwrap(); |
| @@ -419,8 +425,9 @@ mod tests { | |||
| 419 | /// never re-read from the menu. | 425 | /// never re-read from the menu. |
| 420 | #[tokio::test] | 426 | #[tokio::test] |
| 421 | async fn a_seat_keeps_the_price_it_was_taken_at() { | 427 | async fn a_seat_keeps_the_price_it_was_taken_at() { |
| 422 | - let (db, menu) = menu(None).await; | 428 | + let (db, menu, _leases) = menu(None).await; |
| 423 | - let (ali, veli) = (UserId::generate(), UserId::generate()); | 429 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 430 | + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; | ||
| 424 | let open = MealCutoff::default(); | 431 | let open = MealCutoff::default(); |
| 425 | add_dish(&menu, 1_000, &db).await; | 432 | add_dish(&menu, 1_000, &db).await; |
| 426 | 433 | ||
| @@ -451,8 +458,9 @@ mod tests { | |||
| 451 | /// single-process interleaving (and no in-memory engine) can stage. | 458 | /// single-process interleaving (and no in-memory engine) can stage. |
| 452 | #[tokio::test] | 459 | #[tokio::test] |
| 453 | async fn a_lost_flip_refunds_only_the_attempt_it_released() { | 460 | async fn a_lost_flip_refunds_only_the_attempt_it_released() { |
| 454 | - let (db, menu) = menu(None).await; | 461 | + let (db, menu, _leases) = menu(None).await; |
| 455 | - let (ali, veli) = (UserId::generate(), UserId::generate()); | 462 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 463 | + let veli = crate::db::class_member::tests::fixture_user(&db, "veli").await; | ||
| 456 | let open = MealCutoff::default(); | 464 | let open = MealCutoff::default(); |
| 457 | add_dish(&menu, 1_000, &db).await; | 465 | add_dish(&menu, 1_000, &db).await; |
| 458 | 466 | ||
| @@ -504,8 +512,8 @@ mod tests { | |||
| 504 | /// and mint no ledger line, with the shipped defaults in force. | 512 | /// and mint no ledger line, with the shipped defaults in force. |
| 505 | #[tokio::test] | 513 | #[tokio::test] |
| 506 | async fn a_past_day_takes_no_seat_and_writes_no_charge() { | 514 | async fn a_past_day_takes_no_seat_and_writes_no_charge() { |
| 507 | - let (db, menu) = menu_on("2020-01-06", None).await; | 515 | + let (db, menu, _leases) = menu_on("2020-01-06", None).await; |
| 508 | - let ali = UserId::generate(); | 516 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 509 | add_dish(&menu, 4550, &db).await; | 517 | add_dish(&menu, 4550, &db).await; |
| 510 | 518 | ||
| 511 | assert!(matches!( | 519 | assert!(matches!( |
| @@ -527,8 +535,8 @@ mod tests { | |||
| 527 | /// with the cutoff knob set *and* unset. | 535 | /// with the cutoff knob set *and* unset. |
| 528 | #[tokio::test] | 536 | #[tokio::test] |
| 529 | async fn todays_menu_still_books_without_a_serving_hour() { | 537 | async fn todays_menu_still_books_without_a_serving_hour() { |
| 530 | - let (db, menu) = menu_on(&today(), None).await; | 538 | + let (db, menu, _leases) = menu_on(&today(), None).await; |
| 531 | - let ali = UserId::generate(); | 539 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 532 | book(&db, &menu, &ali, &ali, &cutoff(Some(60), None)) | 540 | book(&db, &menu, &ali, &ali, &cutoff(Some(60), None)) |
| 533 | .await | 541 | .await |
| 534 | .expect("an unset serving hour is an unenforced cutoff"); | 542 | .expect("an unset serving hour is an unenforced cutoff"); |
| @@ -540,8 +548,8 @@ mod tests { | |||
| 540 | /// cutoff. The guard binds `book` alone. | 548 | /// cutoff. The guard binds `book` alone. |
| 541 | #[tokio::test] | 549 | #[tokio::test] |
| 542 | async fn a_past_day_still_gives_the_seat_and_the_money_back() { | 550 | async fn a_past_day_still_gives_the_seat_and_the_money_back() { |
| 543 | - let (db, menu) = menu_on("2020-01-06", None).await; | 551 | + let (db, menu, _leases) = menu_on("2020-01-06", None).await; |
| 544 | - let ali = UserId::generate(); | 552 | + let ali = crate::db::class_member::tests::fixture_user(&db, "ali").await; |
| 545 | add_dish(&menu, 4550, &db).await; | 553 | add_dish(&menu, 4550, &db).await; |
| 546 | // The seat this student is holding was taken while the day was still | 554 | // The seat this student is holding was taken while the day was still |
| 547 | // ahead — the shape the create-side check cannot reach. A test cannot | 555 | // ahead — the shape the create-side check cannot reach. A test cannot |
src/service/payment_ledger.rsmodified+25 -10
| @@ -330,8 +330,11 @@ mod tests { | |||
| 330 | use crate::db::fee_plan; | 330 | use crate::db::fee_plan; |
| 331 | use crate::domain::fee_plan::{FeePlanName, Installment}; | 331 | use crate::domain::fee_plan::{FeePlanName, Installment}; |
| 332 | 332 | ||
| 333 | - let manager = UserId::from_key("mgr1"); | 333 | + let manager = |
| 334 | - let student = UserId::from_key("stu1"); | 334 | + crate::db::class_member::tests::fixture_user(db, "ledger-manager") |
| 335 | + .await; | ||
| 336 | + let student = | ||
| 337 | + crate::db::class_member::tests::fixture_user(db, "ledger-student").await; | ||
| 335 | let plan = fee_plan::create( | 338 | let plan = fee_plan::create( |
| 336 | db, | 339 | db, |
| 337 | FeePlanName::try_new("Yearly").unwrap(), | 340 | FeePlanName::try_new("Yearly").unwrap(), |
| @@ -402,7 +405,7 @@ mod tests { | |||
| 402 | student: charge.student.clone(), | 405 | student: charge.student.clone(), |
| 403 | kind: PaymentLedgerKind::Credit, | 406 | kind: PaymentLedgerKind::Credit, |
| 404 | amount_minor: LedgerAmount::try_new(1).unwrap(), | 407 | amount_minor: LedgerAmount::try_new(1).unwrap(), |
| 405 | - source: Some(charge.id.record()), | 408 | + source: Some(charge.id.key().to_owned()), |
| 406 | due_at: None, | 409 | due_at: None, |
| 407 | method: None, | 410 | method: None, |
| 408 | note: None, | 411 | note: None, |
| @@ -441,7 +444,10 @@ mod tests { | |||
| 441 | let credit_line = pay(100).await.unwrap(); | 444 | let credit_line = pay(100).await.unwrap(); |
| 442 | // Still fully paid: a second payment has no room. | 445 | // Still fully paid: a second payment has no room. |
| 443 | assert!( | 446 | assert!( |
| 444 | - matches!(pay(100).await, Err(AppError::Conflict(_))), | 447 | + matches!( |
| 448 | + pay(100).await, | ||
| 449 | + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) | ||
| 450 | + ), | ||
| 445 | "a charge paid in full may not be paid twice" | 451 | "a charge paid in full may not be paid twice" |
| 446 | ); | 452 | ); |
| 447 | 453 | ||
| @@ -468,7 +474,10 @@ mod tests { | |||
| 468 | assert_eq!(balance_of(&db, &student).await.unwrap(), 0); | 474 | assert_eq!(balance_of(&db, &student).await.unwrap(), 0); |
| 469 | 475 | ||
| 470 | // And the room is gone again, so the cap still bites after all that. | 476 | // And the room is gone again, so the cap still bites after all that. |
| 471 | - assert!(matches!(pay(1).await, Err(AppError::Conflict(_)))); | 477 | + assert!(matches!( |
| 478 | + pay(1).await, | ||
| 479 | + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) | ||
| 480 | + )); | ||
| 472 | } | 481 | } |
| 473 | 482 | ||
| 474 | /// The other half of the fold: reversing a refund un-does the money going | 483 | /// The other half of the fold: reversing a refund un-does the money going |
| @@ -513,7 +522,7 @@ mod tests { | |||
| 513 | &manager | 522 | &manager |
| 514 | ) | 523 | ) |
| 515 | .await, | 524 | .await, |
| 516 | - Err(AppError::Conflict(_)) | 525 | + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) |
| 517 | ), | 526 | ), |
| 518 | "the refund was undone, so the charge is paid in full again" | 527 | "the refund was undone, so the charge is paid in full again" |
| 519 | ); | 528 | ); |
| @@ -529,8 +538,11 @@ mod tests { | |||
| 529 | use crate::domain::fee_plan::{FeePlanName, Installment}; | 538 | use crate::domain::fee_plan::{FeePlanName, Installment}; |
| 530 | 539 | ||
| 531 | let (db, _leases) = crate::database::init_test_db().await; | 540 | let (db, _leases) = crate::database::init_test_db().await; |
| 532 | - let manager = UserId::from_key("mgr1"); | 541 | + let manager = |
| 533 | - let student = UserId::from_key("stu1"); | 542 | + crate::db::class_member::tests::fixture_user(&db, "ledger-manager") |
| 543 | + .await; | ||
| 544 | + let student = | ||
| 545 | + crate::db::class_member::tests::fixture_user(&db, "ledger-student").await; | ||
| 534 | let plan = fee_plan::create( | 546 | let plan = fee_plan::create( |
| 535 | &db, | 547 | &db, |
| 536 | FeePlanName::try_new("Yearly").unwrap(), | 548 | FeePlanName::try_new("Yearly").unwrap(), |
| @@ -564,7 +576,10 @@ mod tests { | |||
| 564 | }; | 576 | }; |
| 565 | let first = paid(6_000).await.unwrap(); | 577 | let first = paid(6_000).await.unwrap(); |
| 566 | assert!( | 578 | assert!( |
| 567 | - matches!(paid(5_000).await, Err(AppError::Conflict(_))), | 579 | + matches!( |
| 580 | + paid(5_000).await, | ||
| 581 | + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) | ||
| 582 | + ), | ||
| 568 | "6 000 + 5 000 overshoots a 10 000 charge" | 583 | "6 000 + 5 000 overshoots a 10 000 charge" |
| 569 | ); | 584 | ); |
| 570 | paid(4_000).await.expect("the exact remainder is allowed"); | 585 | paid(4_000).await.expect("the exact remainder is allowed"); |
| @@ -584,7 +599,7 @@ mod tests { | |||
| 584 | }; | 599 | }; |
| 585 | assert!(matches!( | 600 | assert!(matches!( |
| 586 | refund_amount(6_001).await, | 601 | refund_amount(6_001).await, |
| 587 | - Err(AppError::Conflict(_)) | 602 | + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) |
| 588 | )); | 603 | )); |
| 589 | refund_amount(6_000).await.unwrap(); | 604 | refund_amount(6_000).await.unwrap(); |
| 590 | assert_eq!( | 605 | assert_eq!( |
src/service/settings.rsmodified+49 -30
| @@ -235,14 +235,6 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, App | |||
| 235 | /// The name still referenced (`count > 0`) is the caller's removal refusal, | 235 | /// The name still referenced (`count > 0`) is the caller's removal refusal, |
| 236 | /// byte for byte the old 409. | 236 | /// byte for byte the old 409. |
| 237 | async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { | 237 | async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { |
| 238 | - let was = sqlx::query!( | ||
| 239 | - r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#, | ||
| 240 | - name | ||
| 241 | - ) | ||
| 242 | - .fetch_optional(&mut *tx) | ||
| 243 | - .await? | ||
| 244 | - .map(|row| row.retired) | ||
| 245 | - .unwrap_or(false); | ||
| 246 | let landed = sqlx::query!( | 238 | let landed = sqlx::query!( |
| 247 | r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, TRUE) | 239 | r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, TRUE) |
| 248 | ON CONFLICT (name) DO UPDATE SET retired = TRUE | 240 | ON CONFLICT (name) DO UPDATE SET retired = TRUE |
| @@ -253,27 +245,39 @@ async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE | |||
| 253 | .fetch_optional(&mut *tx) | 245 | .fetch_optional(&mut *tx) |
| 254 | .await? | 246 | .await? |
| 255 | .is_some(); | 247 | .is_some(); |
| 256 | - match (landed, was) { | 248 | + if landed { |
| 257 | - // Still in use, and not already retired: the removal is refused. | 249 | + // Flipped by this call: nothing to do — the transaction decides |
| 258 | - (false, false) => Err(AppError::ConflictOwned(format!( | 250 | + // whether the retirement stands. |
| 251 | + return Ok(()); | ||
| 252 | + } | ||
| 253 | + // The upsert's `WHERE` refused the flip. Under READ COMMITTED the row it | ||
| 254 | + // conflicted with may have committed *after* this transaction's first | ||
| 255 | + // snapshot, so the settled state is read here rather than carried over: | ||
| 256 | + // still in use (`count > 0`) is the removal refusal, byte for byte the | ||
| 257 | + // old 409; already retired (with nothing referencing it) is a rival | ||
| 258 | + // having decided the same removal — success, same as a fresh flip. | ||
| 259 | + let row = sqlx::query!( | ||
| 260 | + r#"SELECT count AS "count!: i64", retired AS "retired!: bool" | ||
| 261 | + FROM kind_ref WHERE name = $1 FOR UPDATE"#, | ||
| 262 | + name | ||
| 263 | + ) | ||
| 264 | + .fetch_one(&mut *tx) | ||
| 265 | + .await?; | ||
| 266 | + if row.count > 0 { | ||
| 267 | + return Err(AppError::ConflictOwned(format!( | ||
| 259 | "exams of kind '{name}' are already graded — the kind cannot be removed" | 268 | "exams of kind '{name}' are already graded — the kind cannot be removed" |
| 260 | - ))), | 269 | + ))); |
| 261 | - // Flipped, or already retired by the rival that decided the same | ||
| 262 | - // removal: nothing to do — the transaction decides whether it stands. | ||
| 263 | - _ => Ok(()), | ||
| 264 | } | 270 | } |
| 271 | + let _ = row.retired; | ||
| 272 | + Ok(()) | ||
| 265 | } | 273 | } |
| 266 | 274 | ||
| 267 | /// [`retire_kind`] against the meal-slot counters. | 275 | /// [`retire_kind`] against the meal-slot counters. |
| 268 | async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { | 276 | async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { |
| 269 | - let was = sqlx::query!( | 277 | + // Same shape as [`retire_kind`]: the settled row is read *after* the |
| 270 | - r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#, | 278 | + // refused flip, never carried over from this transaction's first |
| 271 | - name | 279 | + // snapshot — a rival's retirement may have committed in between, and |
| 272 | - ) | 280 | + // that is success, not a refusal. |
| 273 | - .fetch_optional(&mut *tx) | ||
| 274 | - .await? | ||
| 275 | - .map(|row| row.retired) | ||
| 276 | - .unwrap_or(false); | ||
| 277 | let landed = sqlx::query!( | 281 | let landed = sqlx::query!( |
| 278 | r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, TRUE) | 282 | r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, TRUE) |
| 279 | ON CONFLICT (name) DO UPDATE SET retired = TRUE | 283 | ON CONFLICT (name) DO UPDATE SET retired = TRUE |
| @@ -284,12 +288,21 @@ async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppE | |||
| 284 | .fetch_optional(&mut *tx) | 288 | .fetch_optional(&mut *tx) |
| 285 | .await? | 289 | .await? |
| 286 | .is_some(); | 290 | .is_some(); |
| 287 | - match (landed, was) { | 291 | + if landed { |
| 288 | - (false, false) => Err(AppError::ConflictOwned(format!( | 292 | + return Ok(()); |
| 293 | + } | ||
| 294 | + let row = sqlx::query!( | ||
| 295 | + r#"SELECT count AS "count!: i64" FROM slot_ref WHERE name = $1 FOR UPDATE"#, | ||
| 296 | + name | ||
| 297 | + ) | ||
| 298 | + .fetch_one(&mut *tx) | ||
| 299 | + .await?; | ||
| 300 | + if row.count > 0 { | ||
| 301 | + return Err(AppError::ConflictOwned(format!( | ||
| 289 | "menus are already published for the '{name}' slot — it cannot be removed" | 302 | "menus are already published for the '{name}' slot — it cannot be removed" |
| 290 | - ))), | 303 | + ))); |
| 291 | - _ => Ok(()), | ||
| 292 | } | 304 | } |
| 305 | + Ok(()) | ||
| 293 | } | 306 | } |
| 294 | 307 | ||
| 295 | /// Put an exam kind back in service, inside the caller's transaction. One | 308 | /// Put an exam kind back in service, inside the caller's transaction. One |
| @@ -357,9 +370,11 @@ mod tests { | |||
| 357 | /// The `retired` bit as the store holds it, `None` when no counter row was | 370 | /// The `retired` bit as the store holds it, `None` when no counter row was |
| 358 | /// ever written — read back, never inferred from a return value. | 371 | /// ever written — read back, never inferred from a return value. |
| 359 | async fn ref_bit(db: &Database, table: &str, name: &str) -> Option<bool> { | 372 | async fn ref_bit(db: &Database, table: &str, name: &str) -> Option<bool> { |
| 360 | - let row = sqlx::query(&format!( | 373 | + use sqlx::Row as _; |
| 374 | + | ||
| 375 | + let row = sqlx::query(sqlx::AssertSqlSafe(format!( | ||
| 361 | "SELECT retired FROM {table} WHERE name = $1" | 376 | "SELECT retired FROM {table} WHERE name = $1" |
| 362 | - )) | 377 | + ))) |
| 363 | .bind(name) | 378 | .bind(name) |
| 364 | .fetch_optional(db) | 379 | .fetch_optional(db) |
| 365 | .await | 380 | .await |
| @@ -600,8 +615,12 @@ mod tests { | |||
| 600 | async move { apply(&db, &without).await.map(|_| ()) } | 615 | async move { apply(&db, &without).await.map(|_| ()) } |
| 601 | }); | 616 | }); |
| 602 | while !rival.is_finished() { | 617 | while !rival.is_finished() { |
| 603 | - let (kinds, _) = stored(&db).await; | 618 | + // The bit is read BEFORE the list: a `true` bit proves the edit's |
| 619 | + // commit already landed, so the list read that follows cannot | ||
| 620 | + // predate it. The other order races the commit between the two | ||
| 621 | + // probes and "sees" a split that never existed. | ||
| 604 | let retired = kind_bit(&db, "midterm").await; | 622 | let retired = kind_bit(&db, "midterm").await; |
| 623 | + let (kinds, _) = stored(&db).await; | ||
| 605 | if retired == Some(true) { | 624 | if retired == Some(true) { |
| 606 | assert!( | 625 | assert!( |
| 607 | !kinds.contains(&"midterm".to_string()), | 626 | !kinds.contains(&"midterm".to_string()), |
src/tenant.rsmodified+4 -2
| @@ -620,8 +620,10 @@ mod tests { | |||
| 620 | school_db_name(control, &slug("ata-koleji")), | 620 | school_db_name(control, &slug("ata-koleji")), |
| 621 | "hezarfen_control_school_ata_koleji" | 621 | "hezarfen_control_school_ata_koleji" |
| 622 | ); | 622 | ); |
| 623 | - for a in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { | 623 | + // Slugs are at least two characters, so the shortest pair stands in |
| 624 | - for b in ["a", "a-b", "ab", "a1b", "1a", "x-y-z"] { | 624 | + // for the old single-letter probe. |
| 625 | + for a in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] { | ||
| 626 | + for b in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] { | ||
| 625 | if a != b { | 627 | if a != b { |
| 626 | assert_ne!( | 628 | assert_ne!( |
| 627 | school_db_name(control, &slug(a)), | 629 | school_db_name(control, &slug(a)), |
src/web/bank_questions.rsmodified+10 -1
| @@ -948,10 +948,19 @@ mod tests { | |||
| 948 | async fn demoted_owner_loses_their_own_template() { | 948 | async fn demoted_owner_loses_their_own_template() { |
| 949 | let (db, _leases) = init_test_db().await; | 949 | let (db, _leases) = init_test_db().await; |
| 950 | let owner = user("ogretmen", Role::Teacher, &db).await; | 950 | let owner = user("ogretmen", Role::Teacher, &db).await; |
| 951 | + // The subject is a foreign key: a real row, via the course fixture. | ||
| 952 | + let subject = crate::db::subject::create( | ||
| 953 | + &db, | ||
| 954 | + &crate::db::course::a_test_course(&db).await, | ||
| 955 | + crate::domain::subject::SubjectName::try_new("matematik").unwrap(), | ||
| 956 | + crate::domain::subject::SubjectDescription::try_new("").unwrap(), | ||
| 957 | + ) | ||
| 958 | + .await | ||
| 959 | + .unwrap(); | ||
| 951 | let question = bank_question::create( | 960 | let question = bank_question::create( |
| 952 | &db, | 961 | &db, |
| 953 | owner.get_id().clone(), | 962 | owner.get_id().clone(), |
| 954 | - SubjectId::from_key("019732e3-7b00-7000-8000-00000000a2b3"), | 963 | + subject.get_id().clone(), |
| 955 | QuestionText::try_new("2 + 2 = ?").unwrap(), | 964 | QuestionText::try_new("2 + 2 = ?").unwrap(), |
| 956 | QuestionPoints::try_new(1).unwrap(), | 965 | QuestionPoints::try_new(1).unwrap(), |
| 957 | QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), | 966 | QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), |
src/web/mod.rsmodified+4 -5
| @@ -381,7 +381,7 @@ mod tests { | |||
| 381 | use crate::domain::user::{Password, Username}; | 381 | use crate::domain::user::{Password, Username}; |
| 382 | 382 | ||
| 383 | let (db, _leases) = crate::database::init_test_db().await; | 383 | let (db, _leases) = crate::database::init_test_db().await; |
| 384 | - let office = UserId::from_key("office"); | 384 | + let office = crate::db::class_member::tests::fixture_user(&db, "office").await; |
| 385 | let teacher = crate::service::user::create( | 385 | let teacher = crate::service::user::create( |
| 386 | &db, | 386 | &db, |
| 387 | Username::try_new("ada").unwrap(), | 387 | Username::try_new("ada").unwrap(), |
| @@ -463,11 +463,10 @@ mod tests { | |||
| 463 | ); | 463 | ); |
| 464 | 464 | ||
| 465 | // Demoted with no sweep — the state a lost race leaves. | 465 | // Demoted with no sweep — the state a lost race leaves. |
| 466 | - db.query("UPDATE $usr SET role = 'student'") | 466 | + sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1") |
| 467 | - .bind(("usr", teacher.get_id().record())) | 467 | + .bind(teacher.get_id().uuid()) |
| 468 | + .execute(&db) | ||
| 468 | .await | 469 | .await |
| 469 | - .unwrap() | ||
| 470 | - .check() | ||
| 471 | .unwrap(); | 470 | .unwrap(); |
| 472 | let refused = undo_if_demoted(teacher.get_id(), &db).await; | 471 | let refused = undo_if_demoted(teacher.get_id(), &db).await; |
| 473 | assert!( | 472 | assert!( |
src/web/payments.rsmodified+4 -2
| @@ -1087,8 +1087,10 @@ mod tests { | |||
| 1087 | #[tokio::test] | 1087 | #[tokio::test] |
| 1088 | async fn the_statement_rolls_each_charge_up_from_its_own_lines() { | 1088 | async fn the_statement_rolls_each_charge_up_from_its_own_lines() { |
| 1089 | let (db, _leases) = crate::database::init_test_db().await; | 1089 | let (db, _leases) = crate::database::init_test_db().await; |
| 1090 | - let manager = UserId::from_key("mgr1"); | 1090 | + let manager = |
| 1091 | - let student = UserId::from_key("stu1"); | 1091 | + crate::db::class_member::tests::fixture_user(&db, "stmt-manager").await; |
| 1092 | + let student = | ||
| 1093 | + crate::db::class_member::tests::fixture_user(&db, "stmt-student").await; | ||
| 1092 | let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; | 1094 | let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; |
| 1093 | let plan = service::fee_plan::create( | 1095 | let plan = service::fee_plan::create( |
| 1094 | &db, | 1096 | &db, |
tests/persistence.rsmodified+454 -2214
Diff too large; view file
| @@ -1,46 +1,37 @@ | |||
| 1 | -//! Boot-migration tests: age rows into the shapes old binaries left behind, | 1 | +//! Boot-migration tests: seed a real deployment through the API, re-run the |
| 2 | -//! then re-run the idempotent migration on the same database — a second boot — | 2 | +//! idempotent migration over the same live database — a second boot — and |
| 3 | -//! and assert the backfills repair (or deliberately destroy) them. The storage | 3 | +//! assert the seeded rows come back intact. The backfill-era machinery these |
| 4 | -//! engine itself is the SurrealDB server's concern since the embedded engine | 4 | +//! tests once exercised is gone with the old engine; what remains is the |
| 5 | -//! was retired; these tests run on the in-memory engine like every other suite. | 5 | +//! durability contract: a migration must never disturb data that is already |
| 6 | +//! there. | ||
| 6 | 7 | ||
| 7 | mod common; | 8 | mod common; |
| 8 | 9 | ||
| 9 | use axum::Router; | 10 | use axum::Router; |
| 10 | use axum::http::StatusCode; | 11 | use axum::http::StatusCode; |
| 11 | -use common::{create_course, create_exam, create_subject, enroll, me_id, send, set_role}; | 12 | +use common::{create_course, create_subject, enroll, me_id, send, set_role}; |
| 12 | use hezarfen_backend::database::Database; | 13 | use hezarfen_backend::database::Database; |
| 13 | -use hezarfen_backend::domain::timestamp::Timestamp; | ||
| 14 | use hezarfen_backend::module::ModuleSet; | 14 | use hezarfen_backend::module::ModuleSet; |
| 15 | use hezarfen_backend::rate_limit::RateLimitConfig; | 15 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 16 | use hezarfen_backend::state::AppState; | 16 | use hezarfen_backend::state::AppState; |
| 17 | -use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; | 17 | +use hezarfen_backend::tenant::{Slug, Tenants}; |
| 18 | use hezarfen_backend::{build_router, database}; | 18 | use hezarfen_backend::{build_router, database}; |
| 19 | use serde_json::json; | 19 | use serde_json::json; |
| 20 | 20 | ||
| 21 | -/// Simulate a reboot: re-run the migration on the same database and hand back | 21 | +/// Re-apply the school schema to the live school database and hand back a |
| 22 | -/// a fresh router over it. | 22 | +/// fresh router over the same deployment — a second boot in every way that |
| 23 | -async fn reboot(db: &Database) -> Router { | 23 | +/// matters to these tests. |
| 24 | - database::migrate(db).await.expect("re-migration"); | 24 | +async fn reboot(db: &Database, tenants: &Tenants) -> Router { |
| 25 | - // A new process: a new control database and a new connection cache, over | 25 | + database::migrate_school(db).await.expect("re-migration"); |
| 26 | - // the school store the old one left behind. | ||
| 27 | - let tenants = Tenants::new_mem_adopting( | ||
| 28 | - &Slug::try_new(DEMO_SLUG).unwrap(), | ||
| 29 | - "Demo School", | ||
| 30 | - db.clone(), | ||
| 31 | - ) | ||
| 32 | - .await | ||
| 33 | - .expect("adopt the demo school"); | ||
| 34 | build_router(AppState { | 26 | build_router(AppState { |
| 35 | db: tenants.control().clone(), | 27 | db: tenants.control().clone(), |
| 36 | - tenants, | 28 | + tenants: tenants.clone(), |
| 37 | files_path: common::files_dir(), | 29 | files_path: common::files_dir(), |
| 38 | cookie_secure: false, | 30 | cookie_secure: false, |
| 39 | rate_limit: RateLimitConfig::unlimited(), | 31 | rate_limit: RateLimitConfig::unlimited(), |
| 40 | chatbot_limit: Default::default(), | 32 | chatbot_limit: Default::default(), |
| 41 | exam_presence: Default::default(), | 33 | exam_presence: Default::default(), |
| 42 | board_hub: Default::default(), | 34 | board_hub: Default::default(), |
| 43 | - db_up: Default::default(), | ||
| 44 | ai: None, | 35 | ai: None, |
| 45 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 36 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 46 | }) | 37 | }) |
| @@ -51,7 +42,7 @@ async fn reboot(db: &Database) -> Router { | |||
| 51 | /// untouched by the re-applied idempotent migration. | 42 | /// untouched by the re-applied idempotent migration. |
| 52 | #[tokio::test] | 43 | #[tokio::test] |
| 53 | async fn settings_and_terms_survive_remigration() { | 44 | async fn settings_and_terms_survive_remigration() { |
| 54 | - let (app, db) = common::app_and_db().await; | 45 | + let (app, db, tenants) = common::app_and_tenants().await; |
| 55 | 46 | ||
| 56 | let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | 47 | let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); |
| 57 | send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | 48 | send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; |
| @@ -99,7 +90,7 @@ async fn settings_and_terms_survive_remigration() { | |||
| 99 | assert_eq!(res.status, StatusCode::CREATED); | 90 | assert_eq!(res.status, StatusCode::CREATED); |
| 100 | 91 | ||
| 101 | // Second boot: migration re-applied over live data. | 92 | // Second boot: migration re-applied over live data. |
| 102 | - let app = reboot(&db).await; | 93 | + let app = reboot(&db, &tenants).await; |
| 103 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | 94 | let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) |
| 104 | .await | 95 | .await |
| 105 | .cookie | 96 | .cookie |
| @@ -126,1841 +117,494 @@ async fn settings_and_terms_survive_remigration() { | |||
| 126 | assert_eq!(courses[0]["term"].as_str(), Some(term.as_str())); | 117 | assert_eq!(courses[0]["term"].as_str(), Some(term.as_str())); |
| 127 | } | 118 | } |
| 128 | 119 | ||
| 129 | -/// Event rows written before the `audience` column existed are backfilled to | 120 | +/// A weekly appointment series and a booking that carries a full proposal |
| 130 | -/// school-wide on the next boot (`UPDATE event SET audience = { kind: 'school' } | 121 | +/// triple survive the re-applied migration, exact unix-ms stamps and all. |
| 131 | -/// WHERE audience = NONE`), so an old volume keeps serving its events. | ||
| 132 | #[tokio::test] | 122 | #[tokio::test] |
| 133 | -async fn legacy_events_backfill_to_school_audience() { | 123 | +async fn appointments_survive_remigration() { |
| 134 | - let (app, db) = common::app_and_db().await; | 124 | + /// Far enough ahead to clear `check_not_past` without touching the clock, |
| 135 | - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | 125 | + /// and deliberately not a round number of seconds. |
| 126 | + const START: i64 = 1_900_000_000_123; | ||
| 127 | + const END: i64 = 1_900_000_003_777; | ||
| 128 | + const WEEK: i64 = 7 * 24 * 60 * 60 * 1000; | ||
| 129 | + const PROPOSED_START: i64 = START + 5_000_001; | ||
| 130 | + const PROPOSED_END: i64 = START + 8_000_003; | ||
| 136 | 131 | ||
| 137 | - // A normal event — then strip its audience the way an old binary's schema | 132 | + let (app, db, tenants) = common::app_and_tenants().await; |
| 138 | - // would have left it: drop the column definitions so SCHEMAFULL stops | 133 | + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); |
| 139 | - // enforcing them, and unset the field on the row. | 134 | + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); |
| 140 | - assert_eq!( | 135 | + for creds in [&teacher_creds, &student_creds] { |
| 141 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())) | 136 | + assert_eq!( |
| 142 | - .await | 137 | + send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| 143 | - .status, | 138 | + .await |
| 144 | - StatusCode::CREATED | 139 | + .status, |
| 145 | - ); | 140 | + StatusCode::CREATED |
| 141 | + ); | ||
| 142 | + } | ||
| 146 | set_role(&db, "ali", "teacher").await; | 143 | set_role(&db, "ali", "teacher").await; |
| 147 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | 144 | + let teacher = send( |
| 148 | - .await | ||
| 149 | - .cookie | ||
| 150 | - .unwrap(); | ||
| 151 | - let res = send( | ||
| 152 | &app, | 145 | &app, |
| 153 | "POST", | 146 | "POST", |
| 154 | - "/events", | 147 | + "/auth/login", |
| 155 | - Some(&cookie), | ||
| 156 | - Some(json!({ "title": "before audiences" })), | ||
| 157 | - ) | ||
| 158 | - .await; | ||
| 159 | - assert_eq!(res.status, StatusCode::CREATED); | ||
| 160 | - let event_id = common::id_of(&res.body); | ||
| 161 | - | ||
| 162 | - db.query( | ||
| 163 | - "REMOVE FIELD IF EXISTS audience.users ON TABLE event; | ||
| 164 | - REMOVE FIELD IF EXISTS audience.course ON TABLE event; | ||
| 165 | - REMOVE FIELD IF EXISTS audience.role ON TABLE event; | ||
| 166 | - REMOVE FIELD IF EXISTS audience.kind ON TABLE event; | ||
| 167 | - REMOVE FIELD IF EXISTS audience ON TABLE event; | ||
| 168 | - UPDATE event SET audience = NONE;", | ||
| 169 | - ) | ||
| 170 | - .await | ||
| 171 | - .expect("strip audience") | ||
| 172 | - .check() | ||
| 173 | - .expect("strip audience check"); | ||
| 174 | - | ||
| 175 | - // Second boot re-runs the migration: the field definitions come back and | ||
| 176 | - // the backfill stamps the legacy row school-wide — it reads, lists, and | ||
| 177 | - // rosters like any new event. | ||
| 178 | - let app = reboot(&db).await; | ||
| 179 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 180 | - .await | ||
| 181 | - .cookie | ||
| 182 | - .unwrap(); | ||
| 183 | - let res = send( | ||
| 184 | - &app, | ||
| 185 | - "GET", | ||
| 186 | - &format!("/events/{event_id}"), | ||
| 187 | - Some(&cookie), | ||
| 188 | None, | 148 | None, |
| 149 | + Some(teacher_creds.clone()), | ||
| 189 | ) | 150 | ) |
| 190 | - .await; | 151 | + .await |
| 191 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 152 | + .cookie |
| 192 | - assert_eq!(res.body["audience"]["kind"], "school"); | 153 | + .unwrap(); |
| 193 | - let res = send( | 154 | + let student = send( |
| 194 | &app, | 155 | &app, |
| 195 | - "GET", | 156 | + "POST", |
| 196 | - &format!("/events/{event_id}/roster"), | 157 | + "/auth/login", |
| 197 | - Some(&cookie), | ||
| 198 | None, | 158 | None, |
| 159 | + Some(student_creds.clone()), | ||
| 199 | ) | 160 | ) |
| 200 | - .await; | 161 | + .await |
| 201 | - assert_eq!(res.status, StatusCode::OK); | 162 | + .cookie |
| 202 | - assert_eq!(common::total(&res.body), 1, "whole school = the one user"); | 163 | + .unwrap(); |
| 203 | -} | ||
| 204 | - | ||
| 205 | -/// Event rows carrying the retired hand-picked (`users`) audience convert on | ||
| 206 | -/// the next boot: the audience becomes an uncapped registration list and each | ||
| 207 | -/// listed user gets a signup row credited to the event's creator — the old | ||
| 208 | -/// roster survives the clean break byte for byte. | ||
| 209 | -#[tokio::test] | ||
| 210 | -async fn legacy_users_audiences_convert_to_registrations() { | ||
| 211 | - let (app, db) = common::app_and_db().await; | ||
| 212 | - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 213 | - | ||
| 214 | - // A registration-audience event — then rewrite it into the shape an old | ||
| 215 | - // binary left behind: restore the `audience.users` column definition and | ||
| 216 | - // store a hand-picked list on the row. | ||
| 217 | - assert_eq!( | ||
| 218 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())) | ||
| 219 | - .await | ||
| 220 | - .status, | ||
| 221 | - StatusCode::CREATED | ||
| 222 | - ); | ||
| 223 | - set_role(&db, "ali", "teacher").await; | ||
| 224 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 225 | - .await | ||
| 226 | - .cookie | ||
| 227 | - .unwrap(); | ||
| 228 | - let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); | ||
| 229 | - assert_eq!( | ||
| 230 | - send(&app, "POST", "/auth/register", None, Some(student.clone())) | ||
| 231 | - .await | ||
| 232 | - .status, | ||
| 233 | - StatusCode::CREATED | ||
| 234 | - ); | ||
| 235 | - let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) | ||
| 236 | - .await | ||
| 237 | - .cookie | ||
| 238 | - .unwrap(); | ||
| 239 | - let student_id = common::me_id(&app, &student_cookie).await; | ||
| 240 | 164 | ||
| 165 | + // A weekly publish: three occurrences sharing one series id and one note. | ||
| 241 | let res = send( | 166 | let res = send( |
| 242 | &app, | 167 | &app, |
| 243 | "POST", | 168 | "POST", |
| 244 | - "/events", | 169 | + "/appointments/slots", |
| 245 | - Some(&cookie), | 170 | + Some(&teacher), |
| 246 | - Some(json!({ "title": "trip", "audience": { "kind": "registration" } })), | 171 | + Some(json!({ |
| 172 | + "starts_at": START, | ||
| 173 | + "ends_at": END, | ||
| 174 | + "note": "veli görüşmesi", | ||
| 175 | + "repeat_weekly": true, | ||
| 176 | + "until": START + 2 * WEEK, | ||
| 177 | + })), | ||
| 247 | ) | 178 | ) |
| 248 | .await; | 179 | .await; |
| 249 | - assert_eq!(res.status, StatusCode::CREATED); | 180 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 250 | - let event_id = common::id_of(&res.body); | 181 | + let published = res |
| 251 | - | 182 | + .body |
| 252 | - db.query(format!( | 183 | + .as_array() |
| 253 | - "DEFINE FIELD OVERWRITE audience.users ON TABLE event TYPE option<array<record<user>>>; | 184 | + .expect("publish returns an array") |
| 254 | - UPDATE event SET audience = {{ kind: 'users', users: [type::record('user', $usr)] }} | 185 | + .clone(); |
| 255 | - WHERE id = type::record('event', '{event_id}');" | 186 | + assert_eq!(published.len(), 3, "{}", res.body); |
| 256 | - )) | 187 | + let slot_id = published[0]["id"].as_str().unwrap().to_string(); |
| 257 | - .bind(("usr", student_id.clone())) | 188 | + let series = published[0]["series"].as_str().unwrap().to_string(); |
| 258 | - .await | 189 | + let slot_created_at = published[0]["created_at"].as_i64().unwrap(); |
| 259 | - .expect("rewrite to legacy users audience") | ||
| 260 | - .check() | ||
| 261 | - .expect("rewrite check"); | ||
| 262 | 190 | ||
| 263 | - // Second boot runs the conversion: the audience reads back as an uncapped | 191 | + // Book the first occurrence, counter-propose another time, accept it — the |
| 264 | - // registration list, the listed student holds a seat credited to the | 192 | + // row then carries every optional column at once. |
| 265 | - // creator, and the roster (and marking gate) see them. | ||
| 266 | - let app = reboot(&db).await; | ||
| 267 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 268 | - .await | ||
| 269 | - .cookie | ||
| 270 | - .unwrap(); | ||
| 271 | let res = send( | 193 | let res = send( |
| 272 | &app, | 194 | &app, |
| 273 | - "GET", | 195 | + "POST", |
| 274 | - &format!("/events/{event_id}"), | 196 | + "/appointments", |
| 275 | - Some(&cookie), | 197 | + Some(&student), |
| 276 | - None, | 198 | + Some(json!({ "slot": slot_id, "reason": "ödev" })), |
| 277 | ) | 199 | ) |
| 278 | .await; | 200 | .await; |
| 279 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 201 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 280 | - assert_eq!(res.body["audience"]["kind"], "registration"); | 202 | + let appointment = common::id_of(&res.body); |
| 281 | - assert!(res.body["audience"]["capacity"].is_null()); | 203 | + let created_at = res.body["created_at"].as_i64().unwrap(); |
| 282 | let res = send( | 204 | let res = send( |
| 283 | &app, | 205 | &app, |
| 284 | - "GET", | 206 | + "PATCH", |
| 285 | - &format!("/events/{event_id}/roster"), | 207 | + &format!("/appointments/{appointment}/reschedule"), |
| 286 | - Some(&cookie), | 208 | + Some(&teacher), |
| 287 | - None, | 209 | + Some(json!({ "starts_at": PROPOSED_START, "ends_at": PROPOSED_END })), |
| 288 | ) | 210 | ) |
| 289 | .await; | 211 | .await; |
| 290 | - assert_eq!(res.status, StatusCode::OK); | 212 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 291 | - assert_eq!(common::total(&res.body), 1, "the listed user became a seat"); | ||
| 292 | - assert_eq!(common::items(&res.body)[0]["user"]["id"], student_id); | ||
| 293 | let res = send( | 213 | let res = send( |
| 294 | &app, | 214 | &app, |
| 295 | - "POST", | 215 | + "PATCH", |
| 296 | - &format!("/events/{event_id}/attendance"), | 216 | + &format!("/appointments/{appointment}/reschedule/accept"), |
| 297 | - Some(&cookie), | 217 | + Some(&student), |
| 298 | - Some(json!({ "status": "present", "user_id": student_id })), | 218 | + Some(json!({ |
| 219 | + "proposed_starts_at": PROPOSED_START, | ||
| 220 | + "proposed_ends_at": PROPOSED_END, | ||
| 221 | + })), | ||
| 299 | ) | 222 | ) |
| 300 | .await; | 223 | .await; |
| 301 | - assert_eq!(res.status, StatusCode::OK, "converted seat is markable"); | 224 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 302 | -} | ||
| 303 | - | ||
| 304 | -/// Exam-question rows written before subjects existed (2026-07) are destroyed | ||
| 305 | -/// on the next boot, answers first — a subject is mandatory and there is | ||
| 306 | -/// nothing truthful to backfill. The exam and the course's subjects survive. | ||
| 307 | -#[tokio::test] | ||
| 308 | -async fn legacy_subjectless_questions_are_destroyed_on_boot() { | ||
| 309 | - let (app, db) = common::app_and_db().await; | ||
| 310 | - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 311 | 225 | ||
| 312 | - // A full exam — course, subject, open exam, one answered question — then | 226 | + // Second boot: migration re-applied over live data. |
| 313 | - // strip the question's subject the way an old binary's schema would have | 227 | + let app = reboot(&db, &tenants).await; |
| 314 | - // left it. | 228 | + let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) |
| 315 | - assert_eq!( | ||
| 316 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())) | ||
| 317 | - .await | ||
| 318 | - .status, | ||
| 319 | - StatusCode::CREATED | ||
| 320 | - ); | ||
| 321 | - set_role(&db, "ali", "teacher").await; | ||
| 322 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 323 | .await | 229 | .await |
| 324 | .cookie | 230 | .cookie |
| 325 | .unwrap(); | 231 | .unwrap(); |
| 326 | - let student = json!({ "school": "demo", "username": "veli", "password": "secret1" }); | 232 | + let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) |
| 327 | - assert_eq!( | ||
| 328 | - send(&app, "POST", "/auth/register", None, Some(student.clone())) | ||
| 329 | - .await | ||
| 330 | - .status, | ||
| 331 | - StatusCode::CREATED | ||
| 332 | - ); | ||
| 333 | - let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) | ||
| 334 | .await | 233 | .await |
| 335 | .cookie | 234 | .cookie |
| 336 | .unwrap(); | 235 | .unwrap(); |
| 337 | - let student_id = common::me_id(&app, &student_cookie).await; | ||
| 338 | 236 | ||
| 339 | - let course = create_course(&app, &cookie, "algebra").await; | 237 | + let res = send(&app, "GET", "/appointments/slots", Some(&teacher), None).await; |
| 340 | - enroll(&app, &cookie, &course, &student_id).await; | 238 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 341 | - let res = send( | 239 | + assert_eq!(common::total(&res.body), 3, "{}", res.body); |
| 240 | + let slots = common::items(&res.body); | ||
| 241 | + assert_eq!(slots[0]["id"], slot_id.as_str()); | ||
| 242 | + assert_eq!(slots[0]["starts_at"], START, "exact unix-ms, not rounded"); | ||
| 243 | + assert_eq!(slots[0]["ends_at"], END); | ||
| 244 | + assert_eq!(slots[0]["note"], "veli görüşmesi"); | ||
| 245 | + assert_eq!(slots[0]["created_at"], slot_created_at); | ||
| 246 | + for (week, slot) in slots.iter().enumerate() { | ||
| 247 | + assert_eq!(slot["series"], series.as_str(), "one series, all weeks"); | ||
| 248 | + assert_eq!(slot["starts_at"], START + week as i64 * WEEK); | ||
| 249 | + assert_eq!(slot["ends_at"], END + week as i64 * WEEK); | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + let res = send(&app, "GET", "/appointments", Some(&student), None).await; | ||
| 253 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 254 | + assert_eq!(common::total(&res.body), 1, "{}", res.body); | ||
| 255 | + let booking = &common::items(&res.body)[0]; | ||
| 256 | + assert_eq!(booking["id"], appointment.as_str()); | ||
| 257 | + assert_eq!(booking["slot"], slot_id.as_str()); | ||
| 258 | + assert_eq!(booking["status"], "approved"); | ||
| 259 | + assert_eq!(booking["reason"], "ödev"); | ||
| 260 | + assert_eq!(booking["proposed_starts_at"], PROPOSED_START); | ||
| 261 | + assert_eq!(booking["proposed_ends_at"], PROPOSED_END); | ||
| 262 | + assert_eq!(booking["proposed_by"]["username"], "ali"); | ||
| 263 | + assert_eq!(booking["decided_by"]["username"], "ayse"); | ||
| 264 | + // The accepted proposal *is* the meeting's time; the slot's own window lost. | ||
| 265 | + assert_eq!(booking["starts_at"], PROPOSED_START); | ||
| 266 | + assert_eq!(booking["ends_at"], PROPOSED_END); | ||
| 267 | + assert_eq!(booking["teacher"]["username"], "ali"); | ||
| 268 | + assert_eq!(booking["requester"]["username"], "ayse"); | ||
| 269 | + assert_eq!(booking["created_at"], created_at); | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// Per-attempt exam history is durable, not just an in-request join: two | ||
| 273 | +/// sittings' answers and marks (keyed by `seq`) written before a reboot come | ||
| 274 | +/// back with the right seq afterwards — the seq-1 answer keeps its own text and | ||
| 275 | +/// both marks survive, oldest first, with seq 2 as the grade-of-record. | ||
| 276 | +#[tokio::test] | ||
| 277 | +async fn attempt_history_survives_remigration() { | ||
| 278 | + let (app, db, tenants) = common::app_and_tenants().await; | ||
| 279 | + let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 280 | + let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | ||
| 281 | + for creds in [&teacher_creds, &student_creds] { | ||
| 282 | + assert_eq!( | ||
| 283 | + send(&app, "POST", "/auth/register", None, Some((*creds).clone())) | ||
| 284 | + .await | ||
| 285 | + .status, | ||
| 286 | + StatusCode::CREATED | ||
| 287 | + ); | ||
| 288 | + } | ||
| 289 | + set_role(&db, "ali", "teacher").await; | ||
| 290 | + let teacher = send( | ||
| 342 | &app, | 291 | &app, |
| 343 | "POST", | 292 | "POST", |
| 344 | - &format!("/courses/{course}/subjects"), | 293 | + "/auth/login", |
| 345 | - Some(&cookie), | 294 | + None, |
| 346 | - Some(json!({ "name": "arithmetic" })), | 295 | + Some(teacher_creds.clone()), |
| 347 | ) | 296 | ) |
| 348 | - .await; | 297 | + .await |
| 349 | - assert_eq!(res.status, StatusCode::CREATED); | 298 | + .cookie |
| 350 | - let subject_id = common::id_of(&res.body); | 299 | + .unwrap(); |
| 351 | - let res = send( | 300 | + let student = send( |
| 352 | &app, | 301 | &app, |
| 353 | "POST", | 302 | "POST", |
| 354 | - &format!("/courses/{course}/exams"), | 303 | + "/auth/login", |
| 355 | - Some(&cookie), | 304 | + None, |
| 356 | - Some(json!({ "title": "drill", "kind": "quiz", "mode": "open" })), | 305 | + Some(student_creds.clone()), |
| 357 | ) | 306 | ) |
| 358 | - .await; | 307 | + .await |
| 359 | - assert_eq!(res.status, StatusCode::CREATED); | 308 | + .cookie |
| 360 | - let exam_id = common::id_of(&res.body); | 309 | + .unwrap(); |
| 310 | + let student_id = me_id(&app, &student).await; | ||
| 311 | + | ||
| 312 | + let course = create_course(&app, &teacher, "biology").await; | ||
| 313 | + let subject = create_subject(&app, &teacher, &course, "cells").await; | ||
| 314 | + enroll(&app, &teacher, &course, &student_id).await; | ||
| 361 | let res = send( | 315 | let res = send( |
| 362 | &app, | 316 | &app, |
| 363 | "POST", | 317 | "POST", |
| 364 | - &format!("/exams/{exam_id}/questions"), | 318 | + &format!("/courses/{course}/exams"), |
| 365 | - Some(&cookie), | 319 | + Some(&teacher), |
| 366 | - Some( | 320 | + Some(json!({ "title": "quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 })), |
| 367 | - json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", | ||
| 368 | - "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), | ||
| 369 | - ), | ||
| 370 | ) | 321 | ) |
| 371 | .await; | 322 | .await; |
| 372 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 323 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 373 | - let question_id = common::id_of(&res.body); | 324 | + let exam = common::id_of(&res.body); |
| 374 | - // Choice ids are minted server-side, so the answer names one off the response. | ||
| 375 | - let picked = res.body["choices"][1]["id"] | ||
| 376 | - .as_str() | ||
| 377 | - .expect("choice id") | ||
| 378 | - .to_string(); | ||
| 379 | let res = send( | 325 | let res = send( |
| 380 | &app, | 326 | &app, |
| 381 | "POST", | 327 | "POST", |
| 382 | - &format!("/exams/{exam_id}/attempt"), | 328 | + &format!("/exams/{exam}/questions"), |
| 383 | - Some(&student_cookie), | 329 | + Some(&teacher), |
| 384 | - None, | 330 | + Some(json!({ "subject_id": subject, "text": "Name an organelle.", |
| 331 | + "kind": "text", "points": 10 })), | ||
| 385 | ) | 332 | ) |
| 386 | .await; | 333 | .await; |
| 387 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 334 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 388 | - let res = send( | 335 | + let question = common::id_of(&res.body); |
| 389 | - &app, | ||
| 390 | - "POST", | ||
| 391 | - &format!("/exams/{exam_id}/attempt/answers"), | ||
| 392 | - Some(&student_cookie), | ||
| 393 | - Some(json!({ "question_id": question_id, "selected": picked })), | ||
| 394 | - ) | ||
| 395 | - .await; | ||
| 396 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 397 | - | ||
| 398 | - db.query( | ||
| 399 | - "REMOVE FIELD IF EXISTS subject ON TABLE exam_question; | ||
| 400 | - UPDATE exam_question SET subject = NONE;", | ||
| 401 | - ) | ||
| 402 | - .await | ||
| 403 | - .expect("strip subject") | ||
| 404 | - .check() | ||
| 405 | - .expect("strip subject check"); | ||
| 406 | - | ||
| 407 | - // Second boot re-runs the migration and the destroy-backfill: the | ||
| 408 | - // subjectless question and its answer are gone, the exam and subject | ||
| 409 | - // still stand. | ||
| 410 | - let app = reboot(&db).await; | ||
| 411 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 412 | - .await | ||
| 413 | - .cookie | ||
| 414 | - .unwrap(); | ||
| 415 | - let res = send( | ||
| 416 | - &app, | ||
| 417 | - "GET", | ||
| 418 | - &format!("/exams/{exam_id}/questions"), | ||
| 419 | - Some(&cookie), | ||
| 420 | - None, | ||
| 421 | - ) | ||
| 422 | - .await; | ||
| 423 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 424 | - assert_eq!(common::total(&res.body), 0, "legacy questions destroyed"); | ||
| 425 | - let res = send( | ||
| 426 | - &app, | ||
| 427 | - "GET", | ||
| 428 | - &format!("/subjects/{subject_id}"), | ||
| 429 | - Some(&cookie), | ||
| 430 | - None, | ||
| 431 | - ) | ||
| 432 | - .await; | ||
| 433 | - assert_eq!(res.status, StatusCode::OK, "the subject itself survives"); | ||
| 434 | - let mut result = db | ||
| 435 | - .query("SELECT VALUE id FROM exam_answer") | ||
| 436 | - .await | ||
| 437 | - .expect("count answers") | ||
| 438 | - .check() | ||
| 439 | - .expect("count answers check"); | ||
| 440 | - let answers: Vec<surrealdb::types::RecordId> = result.take(0).expect("answer rows"); | ||
| 441 | - assert!(answers.is_empty(), "orphaned answers destroyed"); | ||
| 442 | -} | ||
| 443 | - | ||
| 444 | -/// Enrollment rows whose user is no longer a student — promoted before the | ||
| 445 | -/// role endpoint swept enrollments (2026-07-18), or deleted outright — are | ||
| 446 | -/// removed by the boot backfill. A real student's row survives. | ||
| 447 | -#[tokio::test] | ||
| 448 | -async fn stale_staff_enrollments_are_swept_on_boot() { | ||
| 449 | - let (app, db) = common::app_and_db().await; | ||
| 450 | - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 451 | - | ||
| 452 | - // A course with three enrolled students, then age two rows the way a | ||
| 453 | - // pre-fix binary could have — flip one student to teacher directly in the | ||
| 454 | - // DB, and delete the other's user record entirely. | ||
| 455 | - assert_eq!( | ||
| 456 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())) | ||
| 457 | - .await | ||
| 458 | - .status, | ||
| 459 | - StatusCode::CREATED | ||
| 460 | - ); | ||
| 461 | - set_role(&db, "ali", "teacher").await; | ||
| 462 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 463 | - .await | ||
| 464 | - .cookie | ||
| 465 | - .unwrap(); | ||
| 466 | - let course = create_course(&app, &cookie, "algebra").await; | ||
| 467 | - | ||
| 468 | - let mut ids = Vec::new(); | ||
| 469 | - for name in ["veli", "ayse", "can"] { | ||
| 470 | - let student = json!({ "school": "demo", "username": name, "password": "secret1" }); | ||
| 471 | - assert_eq!( | ||
| 472 | - send(&app, "POST", "/auth/register", None, Some(student.clone())) | ||
| 473 | - .await | ||
| 474 | - .status, | ||
| 475 | - StatusCode::CREATED | ||
| 476 | - ); | ||
| 477 | - let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) | ||
| 478 | - .await | ||
| 479 | - .cookie | ||
| 480 | - .unwrap(); | ||
| 481 | - let id = me_id(&app, &student_cookie).await; | ||
| 482 | - enroll(&app, &cookie, &course, &id).await; | ||
| 483 | - ids.push(id); | ||
| 484 | - } | ||
| 485 | - let keeper_id = ids[1].clone(); | ||
| 486 | - set_role(&db, "veli", "teacher").await; | ||
| 487 | - db.query("DELETE user WHERE username = 'can'") | ||
| 488 | - .await | ||
| 489 | - .expect("delete user") | ||
| 490 | - .check() | ||
| 491 | - .expect("delete user check"); | ||
| 492 | - | ||
| 493 | - // Second boot: the backfill swept the promoted user's row and the deleted | ||
| 494 | - // user's dangling row; the remaining student's enrollment is intact. | ||
| 495 | - let app = reboot(&db).await; | ||
| 496 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 497 | - .await | ||
| 498 | - .cookie | ||
| 499 | - .unwrap(); | ||
| 500 | - let roster = send( | ||
| 501 | - &app, | ||
| 502 | - "GET", | ||
| 503 | - &format!("/courses/{course}/enrollments"), | ||
| 504 | - Some(&cookie), | ||
| 505 | - None, | ||
| 506 | - ) | ||
| 507 | - .await; | ||
| 508 | - assert_eq!(roster.status, StatusCode::OK, "{}", roster.body); | ||
| 509 | - assert_eq!( | ||
| 510 | - common::total(&roster.body), | ||
| 511 | - 1, | ||
| 512 | - "stale rows swept: {}", | ||
| 513 | - roster.body | ||
| 514 | - ); | ||
| 515 | - assert_eq!( | ||
| 516 | - common::items(&roster.body)[0]["user"]["id"], | ||
| 517 | - keeper_id.as_str(), | ||
| 518 | - "the real student's row survives" | ||
| 519 | - ); | ||
| 520 | -} | ||
| 521 | - | ||
| 522 | -/// The seat goes back with the swept row. The sweep above deletes enrollments | ||
| 523 | -/// whose holder is no longer a student, and for every boot it ever ran it kept | ||
| 524 | -/// their seats: the course stayed as full as it was, so a real student was | ||
| 525 | -/// refused a place that nobody held. Two rows of the *same* course go here, | ||
| 526 | -/// because the counter has to come down once per row and not once per course. | ||
| 527 | -/// | ||
| 528 | -/// The repair pass runs *before* the sweep, so it cannot stand in for the | ||
| 529 | -/// decrement being asserted here: at that point both rows are still there and | ||
| 530 | -/// the counter already agrees with them. | ||
| 531 | -#[tokio::test] | ||
| 532 | -async fn a_swept_enrollment_gives_the_course_its_seat_back() { | ||
| 533 | - let (app, db) = common::app_and_db().await; | ||
| 534 | - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; | ||
| 535 | - let res = send( | ||
| 536 | - &app, | ||
| 537 | - "POST", | ||
| 538 | - "/courses", | ||
| 539 | - Some(&teacher), | ||
| 540 | - Some(json!({ "title": "small", "description": "", "capacity": 2 })), | ||
| 541 | - ) | ||
| 542 | - .await; | ||
| 543 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 544 | - let course = common::id_of(&res.body); | ||
| 545 | - | ||
| 546 | - for name in ["veli", "ayse"] { | ||
| 547 | - let cookie = common::login(&app, name).await; | ||
| 548 | - let id = me_id(&app, &cookie).await; | ||
| 549 | - enroll(&app, &teacher, &course, &id).await; | ||
| 550 | - } | ||
| 551 | - // Aged the way a pre-2026-07-18 promotion left them: the role moved on the | ||
| 552 | - // row itself, so no endpoint ever released the seat. | ||
| 553 | - set_role(&db, "veli", "teacher").await; | ||
| 554 | - set_role(&db, "ayse", "manager").await; | ||
| 555 | - | ||
| 556 | - let app = reboot(&db).await; | ||
| 557 | - let mut counter = db | ||
| 558 | - .query("SELECT VALUE enrollment_count FROM course") | ||
| 559 | - .await | ||
| 560 | - .expect("read the counter") | ||
| 561 | - .check() | ||
| 562 | - .expect("read the counter"); | ||
| 563 | - assert_eq!( | ||
| 564 | - counter.take::<Vec<i64>>(0).expect("enrollment_count"), | ||
| 565 | - vec![0], | ||
| 566 | - "both swept rows must hand their seats back" | ||
| 567 | - ); | ||
| 568 | - | ||
| 569 | - // The user-visible half: the capacity is free again, so a real student gets | ||
| 570 | - // the place the phantom seats were denying them. | ||
| 571 | - let can = common::login(&app, "can").await; | ||
| 572 | - let can_id = me_id(&app, &can).await; | ||
| 573 | - let res = send( | ||
| 574 | - &app, | ||
| 575 | - "POST", | ||
| 576 | - &format!("/courses/{course}/enrollments"), | ||
| 577 | - Some(&teacher), | ||
| 578 | - Some(json!({ "user_id": can_id })), | ||
| 579 | - ) | ||
| 580 | - .await; | ||
| 581 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 582 | -} | ||
| 583 | - | ||
| 584 | -/// The repair for the drift past boots already left behind: a course whose | ||
| 585 | -/// `enrollment_count` outran its roster is recounted from the rows it actually | ||
| 586 | -/// has. The symptom that makes it worth a boot pass is the delete guard — | ||
| 587 | -/// `Course::delete` refuses on `(enrollment_count ?? 0) = 0`, so a course | ||
| 588 | -/// carrying a phantom seat can never be deleted by anyone — so that is what is | ||
| 589 | -/// asserted, not just the number. | ||
| 590 | -/// | ||
| 591 | -/// The second course pins the other direction: the repair recounts to the | ||
| 592 | -/// roster, never to zero, so a course with real students keeps its seats. | ||
| 593 | -#[tokio::test] | ||
| 594 | -async fn a_course_whose_count_outran_its_roster_is_repaired_and_deletable() { | ||
| 595 | - let (app, db) = common::app_and_db().await; | ||
| 596 | - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; | ||
| 597 | - let stranded = create_course(&app, &teacher, "stranded").await; | ||
| 598 | - let live = create_course(&app, &teacher, "live").await; | ||
| 599 | - let student = common::login(&app, "veli").await; | ||
| 600 | - let student_id = me_id(&app, &student).await; | ||
| 601 | - enroll(&app, &teacher, &live, &student_id).await; | ||
| 602 | - | ||
| 603 | - // The state every past run of the sweep left: rows gone, seats not. | ||
| 604 | - db.query( | ||
| 605 | - "UPDATE type::record('course', $stranded) SET enrollment_count = 3; | ||
| 606 | - UPDATE type::record('course', $live) SET enrollment_count = 5;", | ||
| 607 | - ) | ||
| 608 | - .bind(("stranded", stranded.clone())) | ||
| 609 | - .bind(("live", live.clone())) | ||
| 610 | - .await | ||
| 611 | - .expect("age the counters") | ||
| 612 | - .check() | ||
| 613 | - .expect("age the counters"); | ||
| 614 | - | ||
| 615 | - let app = reboot(&db).await; | ||
| 616 | - let mut counters = db | ||
| 617 | - .query("SELECT VALUE enrollment_count FROM course ORDER BY id") | ||
| 618 | - .await | ||
| 619 | - .expect("read the counters") | ||
| 620 | - .check() | ||
| 621 | - .expect("read the counters"); | ||
| 622 | - let mut stored = counters.take::<Vec<i64>>(0).expect("enrollment_count"); | ||
| 623 | - stored.sort_unstable(); | ||
| 624 | - assert_eq!( | ||
| 625 | - stored, | ||
| 626 | - vec![0, 1], | ||
| 627 | - "each course is recounted from its own rows" | ||
| 628 | - ); | ||
| 629 | - | ||
| 630 | - let res = send( | ||
| 631 | - &app, | ||
| 632 | - "DELETE", | ||
| 633 | - &format!("/courses/{stranded}"), | ||
| 634 | - Some(&teacher), | ||
| 635 | - None, | ||
| 636 | - ) | ||
| 637 | - .await; | ||
| 638 | - assert_eq!( | ||
| 639 | - res.status, | ||
| 640 | - StatusCode::NO_CONTENT, | ||
| 641 | - "a repaired course is deletable again: {}", | ||
| 642 | - res.body | ||
| 643 | - ); | ||
| 644 | - // And the one with a real student on it is still guarded. | ||
| 645 | - let res = send( | ||
| 646 | - &app, | ||
| 647 | - "DELETE", | ||
| 648 | - &format!("/courses/{live}"), | ||
| 649 | - Some(&teacher), | ||
| 650 | - None, | ||
| 651 | - ) | ||
| 652 | - .await; | ||
| 653 | - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 654 | -} | ||
| 655 | - | ||
| 656 | -/// Exam rows written before the draft flag existed (2026-07-19) backfill to | ||
| 657 | -/// published (`draft = false`) on the next boot — an old volume's exams stay | ||
| 658 | -/// exactly as visible as they were. | ||
| 659 | -#[tokio::test] | ||
| 660 | -async fn legacy_exams_backfill_to_published() { | ||
| 661 | - let (app, db) = common::app_and_db().await; | ||
| 662 | - let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 663 | - let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | ||
| 664 | - | ||
| 665 | - // A normal exam — then strip `draft` the way an old binary's schema would | ||
| 666 | - // have left it. | ||
| 667 | - for creds in [&teacher_creds, &student_creds] { | ||
| 668 | - assert_eq!( | ||
| 669 | - send(&app, "POST", "/auth/register", None, Some((*creds).clone())) | ||
| 670 | - .await | ||
| 671 | - .status, | ||
| 672 | - StatusCode::CREATED | ||
| 673 | - ); | ||
| 674 | - } | ||
| 675 | - set_role(&db, "ali", "teacher").await; | ||
| 676 | - let teacher = send( | ||
| 677 | - &app, | ||
| 678 | - "POST", | ||
| 679 | - "/auth/login", | ||
| 680 | - None, | ||
| 681 | - Some(teacher_creds.clone()), | ||
| 682 | - ) | ||
| 683 | - .await | ||
| 684 | - .cookie | ||
| 685 | - .unwrap(); | ||
| 686 | - let student = send( | ||
| 687 | - &app, | ||
| 688 | - "POST", | ||
| 689 | - "/auth/login", | ||
| 690 | - None, | ||
| 691 | - Some(student_creds.clone()), | ||
| 692 | - ) | ||
| 693 | - .await | ||
| 694 | - .cookie | ||
| 695 | - .unwrap(); | ||
| 696 | - let student_id = me_id(&app, &student).await; | ||
| 697 | - let course = create_course(&app, &teacher, "algebra").await; | ||
| 698 | - enroll(&app, &teacher, &course, &student_id).await; | ||
| 699 | - let exam_id = create_exam(&app, &teacher, &course, "midterm", "midterm").await; | ||
| 700 | - | ||
| 701 | - db.query( | ||
| 702 | - "REMOVE FIELD IF EXISTS draft ON TABLE exam; | ||
| 703 | - UPDATE exam SET draft = NONE;", | ||
| 704 | - ) | ||
| 705 | - .await | ||
| 706 | - .expect("strip draft") | ||
| 707 | - .check() | ||
| 708 | - .expect("strip draft check"); | ||
| 709 | - | ||
| 710 | - // Second boot re-runs the migration: the legacy exam reads back published | ||
| 711 | - // and the enrolled student still sees it. | ||
| 712 | - let app = reboot(&db).await; | ||
| 713 | - let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) | ||
| 714 | - .await | ||
| 715 | - .cookie | ||
| 716 | - .unwrap(); | ||
| 717 | - let res = send( | ||
| 718 | - &app, | ||
| 719 | - "GET", | ||
| 720 | - &format!("/exams/{exam_id}"), | ||
| 721 | - Some(&student), | ||
| 722 | - None, | ||
| 723 | - ) | ||
| 724 | - .await; | ||
| 725 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 726 | - assert_eq!(res.body["draft"], false); | ||
| 727 | - let listed = send(&app, "GET", "/exams", Some(&student), None).await; | ||
| 728 | - assert_eq!(common::items(&listed.body).len(), 1); | ||
| 729 | -} | ||
| 730 | - | ||
| 731 | -/// A recurring publish and the booking sitting on it survive a second boot: | ||
| 732 | -/// the slot's `note` and shared `series`, and the booking's counter-proposal | ||
| 733 | -/// triple, `decided_by` and `status`, all come back untouched by the | ||
| 734 | -/// re-applied migration. Every time in this schema is a unix-millisecond | ||
| 735 | -/// `TYPE int` — never a `datetime` — so the round trip is asserted on odd | ||
| 736 | -/// millisecond values, which any lossy conversion would round off. | ||
| 737 | -#[tokio::test] | ||
| 738 | -async fn appointments_survive_remigration() { | ||
| 739 | - /// Far enough ahead to clear `check_not_past` without touching the clock, | ||
| 740 | - /// and deliberately not a round number of seconds. | ||
| 741 | - const START: i64 = 1_900_000_000_123; | ||
| 742 | - const END: i64 = 1_900_000_003_777; | ||
| 743 | - const WEEK: i64 = 7 * 24 * 60 * 60 * 1000; | ||
| 744 | - const PROPOSED_START: i64 = START + 5_000_001; | ||
| 745 | - const PROPOSED_END: i64 = START + 8_000_003; | ||
| 746 | - | ||
| 747 | - let (app, db) = common::app_and_db().await; | ||
| 748 | - let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 749 | - let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | ||
| 750 | - for creds in [&teacher_creds, &student_creds] { | ||
| 751 | - assert_eq!( | ||
| 752 | - send(&app, "POST", "/auth/register", None, Some((*creds).clone())) | ||
| 753 | - .await | ||
| 754 | - .status, | ||
| 755 | - StatusCode::CREATED | ||
| 756 | - ); | ||
| 757 | - } | ||
| 758 | - set_role(&db, "ali", "teacher").await; | ||
| 759 | - let teacher = send( | ||
| 760 | - &app, | ||
| 761 | - "POST", | ||
| 762 | - "/auth/login", | ||
| 763 | - None, | ||
| 764 | - Some(teacher_creds.clone()), | ||
| 765 | - ) | ||
| 766 | - .await | ||
| 767 | - .cookie | ||
| 768 | - .unwrap(); | ||
| 769 | - let student = send( | ||
| 770 | - &app, | ||
| 771 | - "POST", | ||
| 772 | - "/auth/login", | ||
| 773 | - None, | ||
| 774 | - Some(student_creds.clone()), | ||
| 775 | - ) | ||
| 776 | - .await | ||
| 777 | - .cookie | ||
| 778 | - .unwrap(); | ||
| 779 | - | ||
| 780 | - // A weekly publish: three occurrences sharing one series id and one note. | ||
| 781 | - let res = send( | ||
| 782 | - &app, | ||
| 783 | - "POST", | ||
| 784 | - "/appointments/slots", | ||
| 785 | - Some(&teacher), | ||
| 786 | - Some(json!({ | ||
| 787 | - "starts_at": START, | ||
| 788 | - "ends_at": END, | ||
| 789 | - "note": "veli görüşmesi", | ||
| 790 | - "repeat_weekly": true, | ||
| 791 | - "until": START + 2 * WEEK, | ||
| 792 | - })), | ||
| 793 | - ) | ||
| 794 | - .await; | ||
| 795 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 796 | - let published = res | ||
| 797 | - .body | ||
| 798 | - .as_array() | ||
| 799 | - .expect("publish returns an array") | ||
| 800 | - .clone(); | ||
| 801 | - assert_eq!(published.len(), 3, "{}", res.body); | ||
| 802 | - let slot_id = published[0]["id"].as_str().unwrap().to_string(); | ||
| 803 | - let series = published[0]["series"].as_str().unwrap().to_string(); | ||
| 804 | - let slot_created_at = published[0]["created_at"].as_i64().unwrap(); | ||
| 805 | - | ||
| 806 | - // Book the first occurrence, counter-propose another time, accept it — the | ||
| 807 | - // row then carries every optional column at once: a proposal triple, a | ||
| 808 | - // decider, and `approved`. | ||
| 809 | - let res = send( | ||
| 810 | - &app, | ||
| 811 | - "POST", | ||
| 812 | - "/appointments", | ||
| 813 | - Some(&student), | ||
| 814 | - Some(json!({ "slot": slot_id, "reason": "ödev" })), | ||
| 815 | - ) | ||
| 816 | - .await; | ||
| 817 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 818 | - let appointment = common::id_of(&res.body); | ||
| 819 | - let created_at = res.body["created_at"].as_i64().unwrap(); | ||
| 820 | - let res = send( | ||
| 821 | - &app, | ||
| 822 | - "PATCH", | ||
| 823 | - &format!("/appointments/{appointment}/reschedule"), | ||
| 824 | - Some(&teacher), | ||
| 825 | - Some(json!({ "starts_at": PROPOSED_START, "ends_at": PROPOSED_END })), | ||
| 826 | - ) | ||
| 827 | - .await; | ||
| 828 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 829 | - let res = send( | ||
| 830 | - &app, | ||
| 831 | - "PATCH", | ||
| 832 | - &format!("/appointments/{appointment}/reschedule/accept"), | ||
| 833 | - Some(&student), | ||
| 834 | - Some(json!({ | ||
| 835 | - "proposed_starts_at": PROPOSED_START, | ||
| 836 | - "proposed_ends_at": PROPOSED_END, | ||
| 837 | - })), | ||
| 838 | - ) | ||
| 839 | - .await; | ||
| 840 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 841 | - | ||
| 842 | - // Second boot: migration re-applied over live data. | ||
| 843 | - let app = reboot(&db).await; | ||
| 844 | - let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) | ||
| 845 | - .await | ||
| 846 | - .cookie | ||
| 847 | - .unwrap(); | ||
| 848 | - let student = send(&app, "POST", "/auth/login", None, Some(student_creds)) | ||
| 849 | - .await | ||
| 850 | - .cookie | ||
| 851 | - .unwrap(); | ||
| 852 | - | ||
| 853 | - let res = send(&app, "GET", "/appointments/slots", Some(&teacher), None).await; | ||
| 854 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 855 | - assert_eq!(common::total(&res.body), 3, "{}", res.body); | ||
| 856 | - let slots = common::items(&res.body); | ||
| 857 | - assert_eq!(slots[0]["id"], slot_id.as_str()); | ||
| 858 | - assert_eq!(slots[0]["starts_at"], START, "exact unix-ms, not rounded"); | ||
| 859 | - assert_eq!(slots[0]["ends_at"], END); | ||
| 860 | - assert_eq!(slots[0]["note"], "veli görüşmesi"); | ||
| 861 | - assert_eq!(slots[0]["created_at"], slot_created_at); | ||
| 862 | - for (week, slot) in slots.iter().enumerate() { | ||
| 863 | - assert_eq!(slot["series"], series.as_str(), "one series, all weeks"); | ||
| 864 | - assert_eq!(slot["starts_at"], START + week as i64 * WEEK); | ||
| 865 | - assert_eq!(slot["ends_at"], END + week as i64 * WEEK); | ||
| 866 | - } | ||
| 867 | - | ||
| 868 | - let res = send(&app, "GET", "/appointments", Some(&student), None).await; | ||
| 869 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 870 | - assert_eq!(common::total(&res.body), 1, "{}", res.body); | ||
| 871 | - let booking = &common::items(&res.body)[0]; | ||
| 872 | - assert_eq!(booking["id"], appointment.as_str()); | ||
| 873 | - assert_eq!(booking["slot"], slot_id.as_str()); | ||
| 874 | - assert_eq!(booking["status"], "approved"); | ||
| 875 | - assert_eq!(booking["reason"], "ödev"); | ||
| 876 | - assert_eq!(booking["proposed_starts_at"], PROPOSED_START); | ||
| 877 | - assert_eq!(booking["proposed_ends_at"], PROPOSED_END); | ||
| 878 | - assert_eq!(booking["proposed_by"]["username"], "ali"); | ||
| 879 | - assert_eq!(booking["decided_by"]["username"], "ayse"); | ||
| 880 | - // The accepted proposal *is* the meeting's time; the slot's own window lost. | ||
| 881 | - assert_eq!(booking["starts_at"], PROPOSED_START); | ||
| 882 | - assert_eq!(booking["ends_at"], PROPOSED_END); | ||
| 883 | - assert_eq!(booking["teacher"]["username"], "ali"); | ||
| 884 | - assert_eq!(booking["requester"]["username"], "ayse"); | ||
| 885 | - assert_eq!(booking["created_at"], created_at); | ||
| 886 | -} | ||
| 887 | - | ||
| 888 | -/// Per-attempt exam history is durable, not just an in-request join: two | ||
| 889 | -/// sittings' answers and marks (keyed by `seq`) written before a reboot come | ||
| 890 | -/// back with the right seq afterwards — the seq-1 answer keeps its own text and | ||
| 891 | -/// both marks survive, oldest first, with seq 2 as the grade-of-record. | ||
| 892 | -#[tokio::test] | ||
| 893 | -async fn attempt_history_survives_remigration() { | ||
| 894 | - let (app, db) = common::app_and_db().await; | ||
| 895 | - let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 896 | - let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" }); | ||
| 897 | - for creds in [&teacher_creds, &student_creds] { | ||
| 898 | - assert_eq!( | ||
| 899 | - send(&app, "POST", "/auth/register", None, Some((*creds).clone())) | ||
| 900 | - .await | ||
| 901 | - .status, | ||
| 902 | - StatusCode::CREATED | ||
| 903 | - ); | ||
| 904 | - } | ||
| 905 | - set_role(&db, "ali", "teacher").await; | ||
| 906 | - let teacher = send( | ||
| 907 | - &app, | ||
| 908 | - "POST", | ||
| 909 | - "/auth/login", | ||
| 910 | - None, | ||
| 911 | - Some(teacher_creds.clone()), | ||
| 912 | - ) | ||
| 913 | - .await | ||
| 914 | - .cookie | ||
| 915 | - .unwrap(); | ||
| 916 | - let student = send( | ||
| 917 | - &app, | ||
| 918 | - "POST", | ||
| 919 | - "/auth/login", | ||
| 920 | - None, | ||
| 921 | - Some(student_creds.clone()), | ||
| 922 | - ) | ||
| 923 | - .await | ||
| 924 | - .cookie | ||
| 925 | - .unwrap(); | ||
| 926 | - let student_id = me_id(&app, &student).await; | ||
| 927 | - | ||
| 928 | - let course = create_course(&app, &teacher, "biology").await; | ||
| 929 | - let subject = create_subject(&app, &teacher, &course, "cells").await; | ||
| 930 | - enroll(&app, &teacher, &course, &student_id).await; | ||
| 931 | - let res = send( | ||
| 932 | - &app, | ||
| 933 | - "POST", | ||
| 934 | - &format!("/courses/{course}/exams"), | ||
| 935 | - Some(&teacher), | ||
| 936 | - Some(json!({ "title": "quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 })), | ||
| 937 | - ) | ||
| 938 | - .await; | ||
| 939 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 940 | - let exam = common::id_of(&res.body); | ||
| 941 | - let res = send( | ||
| 942 | - &app, | ||
| 943 | - "POST", | ||
| 944 | - &format!("/exams/{exam}/questions"), | ||
| 945 | - Some(&teacher), | ||
| 946 | - Some(json!({ "subject_id": subject, "text": "Name an organelle.", | ||
| 947 | - "kind": "text", "points": 10 })), | ||
| 948 | - ) | ||
| 949 | - .await; | ||
| 950 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 951 | - let question = common::id_of(&res.body); | ||
| 952 | - | ||
| 953 | - // Two sittings: distinct answer text + distinct mark on each. | ||
| 954 | - for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] { | ||
| 955 | - assert_eq!( | ||
| 956 | - send( | ||
| 957 | - &app, | ||
| 958 | - "POST", | ||
| 959 | - &format!("/exams/{exam}/attempt"), | ||
| 960 | - Some(&student), | ||
| 961 | - None | ||
| 962 | - ) | ||
| 963 | - .await | ||
| 964 | - .status, | ||
| 965 | - StatusCode::CREATED | ||
| 966 | - ); | ||
| 967 | - let res = send( | ||
| 968 | - &app, | ||
| 969 | - "POST", | ||
| 970 | - &format!("/exams/{exam}/attempt/answers"), | ||
| 971 | - Some(&student), | ||
| 972 | - Some(json!({ "question_id": question, "text": text })), | ||
| 973 | - ) | ||
| 974 | - .await; | ||
| 975 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 976 | - let res = send( | ||
| 977 | - &app, | ||
| 978 | - "POST", | ||
| 979 | - &format!("/exams/{exam}/results"), | ||
| 980 | - Some(&teacher), | ||
| 981 | - Some(json!({ "mark": mark, "user_id": student_id })), | ||
| 982 | - ) | ||
| 983 | - .await; | ||
| 984 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 985 | - send( | ||
| 986 | - &app, | ||
| 987 | - "POST", | ||
| 988 | - &format!("/exams/{exam}/attempt/finish"), | ||
| 989 | - Some(&student), | ||
| 990 | - None, | ||
| 991 | - ) | ||
| 992 | - .await; | ||
| 993 | - } | ||
| 994 | - | ||
| 995 | - // Second boot: migration re-applied over the two sittings' live rows. | ||
| 996 | - let app = reboot(&db).await; | ||
| 997 | - let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) | ||
| 998 | - .await | ||
| 999 | - .cookie | ||
| 1000 | - .unwrap(); | ||
| 1001 | - | ||
| 1002 | - let res = send( | ||
| 1003 | - &app, | ||
| 1004 | - "GET", | ||
| 1005 | - &format!("/exams/{exam}/students/{student_id}/attempts"), | ||
| 1006 | - Some(&teacher), | ||
| 1007 | - None, | ||
| 1008 | - ) | ||
| 1009 | - .await; | ||
| 1010 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1011 | - assert_eq!(res.body, json!([1, 2]), "both sittings survived the reboot"); | ||
| 1012 | - | ||
| 1013 | - // The seq-1 answer kept its own text through the reopen. | ||
| 1014 | - let res = send( | ||
| 1015 | - &app, | ||
| 1016 | - "GET", | ||
| 1017 | - &format!("/exams/{exam}/students/{student_id}/attempts/1/answers"), | ||
| 1018 | - Some(&teacher), | ||
| 1019 | - None, | ||
| 1020 | - ) | ||
| 1021 | - .await; | ||
| 1022 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1023 | - assert_eq!(res.body["answers"][0]["text"], "mitochondria"); | ||
| 1024 | - | ||
| 1025 | - // Both marks survive, oldest first; the roster's grade-of-record is seq 2. | ||
| 1026 | - let res = send( | ||
| 1027 | - &app, | ||
| 1028 | - "GET", | ||
| 1029 | - &format!("/exams/{exam}/students/{student_id}/marks"), | ||
| 1030 | - Some(&teacher), | ||
| 1031 | - None, | ||
| 1032 | - ) | ||
| 1033 | - .await; | ||
| 1034 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1035 | - let marks: Vec<i64> = res | ||
| 1036 | - .body | ||
| 1037 | - .as_array() | ||
| 1038 | - .unwrap() | ||
| 1039 | - .iter() | ||
| 1040 | - .map(|r| r["mark"].as_i64().unwrap()) | ||
| 1041 | - .collect(); | ||
| 1042 | - assert_eq!( | ||
| 1043 | - marks, | ||
| 1044 | - vec![40, 90], | ||
| 1045 | - "both sittings' marks durable, oldest first" | ||
| 1046 | - ); | ||
| 1047 | - let res = send( | ||
| 1048 | - &app, | ||
| 1049 | - "GET", | ||
| 1050 | - &format!("/exams/{exam}/results"), | ||
| 1051 | - Some(&teacher), | ||
| 1052 | - None, | ||
| 1053 | - ) | ||
| 1054 | - .await; | ||
| 1055 | - assert_eq!( | ||
| 1056 | - common::items(&res.body)[0]["mark"], | ||
| 1057 | - 90, | ||
| 1058 | - "seq 2 is grade-of-record" | ||
| 1059 | - ); | ||
| 1060 | -} | ||
| 1061 | - | ||
| 1062 | -/// A chatbot thread and every turn in it die together: deleting the | ||
| 1063 | -/// thread cascades its `chatbot_message` rows in one transaction, so no | ||
| 1064 | -/// orphan survives a reboot. And the thread is owner-scoped end to end — a | ||
| 1065 | -/// second user reads neither the thread nor its messages. | ||
| 1066 | -#[tokio::test] | ||
| 1067 | -async fn chat_thread_delete_cascades_and_stays_owner_scoped() { | ||
| 1068 | - use hezarfen_backend::db::{chatbot_message, chatbot_thread}; | ||
| 1069 | - use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus}; | ||
| 1070 | - use hezarfen_backend::domain::user::UserId; | ||
| 1071 | - | ||
| 1072 | - let (app, db) = common::app_and_db().await; | ||
| 1073 | - let owner_cookie = common::login(&app, "ali").await; | ||
| 1074 | - let other_cookie = common::login(&app, "ayse").await; | ||
| 1075 | - let owner = UserId::from_key(&me_id(&app, &owner_cookie).await); | ||
| 1076 | - let other = UserId::from_key(&me_id(&app, &other_cookie).await); | ||
| 1077 | - | ||
| 1078 | - let thread = chatbot_thread::create_capped(&db, &owner, None) | ||
| 1079 | - .await | ||
| 1080 | - .expect("create"); | ||
| 1081 | - let id = thread.get_id().clone(); | ||
| 1082 | - let prompt = chatbot_message::append_user( | ||
| 1083 | - &db, | ||
| 1084 | - &id, | ||
| 1085 | - &owner, | ||
| 1086 | - ChatContent::try_new("selam").expect("content"), | ||
| 1087 | - ) | ||
| 1088 | - .await | ||
| 1089 | - .expect("append user"); | ||
| 1090 | - let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) | ||
| 1091 | - .await | ||
| 1092 | - .expect("append assistant"); | ||
| 1093 | - assert_eq!(reply.get_status(), MessageStatus::Pending); | ||
| 1094 | - | ||
| 1095 | - let reply = chatbot_message::complete( | ||
| 1096 | - &db, | ||
| 1097 | - reply.get_id(), | ||
| 1098 | - ChatContent::try_new("aleykum selam").expect("content"), | ||
| 1099 | - false, | ||
| 1100 | - ) | ||
| 1101 | - .await | ||
| 1102 | - .expect("complete"); | ||
| 1103 | - assert_eq!(reply.get_status(), MessageStatus::Complete); | ||
| 1104 | - assert_eq!(reply.get_content().as_str(), "aleykum selam"); | ||
| 1105 | - assert!(reply.get_completed_at().is_some()); | ||
| 1106 | - assert_eq!( | ||
| 1107 | - chatbot_message::list_for_thread(&db, &id, None, 0) | ||
| 1108 | - .await | ||
| 1109 | - .expect("thread") | ||
| 1110 | - .0 | ||
| 1111 | - .len(), | ||
| 1112 | - 2 | ||
| 1113 | - ); | ||
| 1114 | - | ||
| 1115 | - // The other user sees nothing of it, by thread or by message. | ||
| 1116 | - assert!( | ||
| 1117 | - chatbot_thread::read_for(&db, &id, &other) | ||
| 1118 | - .await | ||
| 1119 | - .expect("cross-user thread") | ||
| 1120 | - .is_none() | ||
| 1121 | - ); | ||
| 1122 | - assert!( | ||
| 1123 | - chatbot_message::read_for(&db, prompt.get_id(), &other) | ||
| 1124 | - .await | ||
| 1125 | - .expect("cross-user message") | ||
| 1126 | - .is_none() | ||
| 1127 | - ); | ||
| 1128 | - assert_eq!( | ||
| 1129 | - chatbot_thread::count_for_user(&db, &other) | ||
| 1130 | - .await | ||
| 1131 | - .expect("count"), | ||
| 1132 | - 0 | ||
| 1133 | - ); | ||
| 1134 | - assert_eq!( | ||
| 1135 | - chatbot_thread::count_for_user(&db, &owner) | ||
| 1136 | - .await | ||
| 1137 | - .expect("count"), | ||
| 1138 | - 1 | ||
| 1139 | - ); | ||
| 1140 | - | ||
| 1141 | - chatbot_thread::delete(&db, thread).await.expect("delete"); | ||
| 1142 | - assert!( | ||
| 1143 | - chatbot_thread::read_for(&db, &id, &owner) | ||
| 1144 | - .await | ||
| 1145 | - .expect("deleted thread") | ||
| 1146 | - .is_none() | ||
| 1147 | - ); | ||
| 1148 | - assert_eq!( | ||
| 1149 | - chatbot_thread::list_for_user(&db, &owner, None, 0) | ||
| 1150 | - .await | ||
| 1151 | - .unwrap() | ||
| 1152 | - .0 | ||
| 1153 | - .len(), | ||
| 1154 | - 0 | ||
| 1155 | - ); | ||
| 1156 | - // Not just the thread's own view: no `chatbot_message` row is left anywhere. | ||
| 1157 | - let mut left = db | ||
| 1158 | - .query("SELECT VALUE id FROM chatbot_message") | ||
| 1159 | - .await | ||
| 1160 | - .expect("sweep") | ||
| 1161 | - .check() | ||
| 1162 | - .expect("sweep check"); | ||
| 1163 | - assert!( | ||
| 1164 | - left.take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 1165 | - .expect("ids") | ||
| 1166 | - .is_empty() | ||
| 1167 | - ); | ||
| 1168 | -} | ||
| 1169 | - | ||
| 1170 | -/// Chat turns written before the clipped-answer flag existed (2026-07-23) | ||
| 1171 | -/// backfill to `truncated = false` on the next boot: an old volume's answers | ||
| 1172 | -/// read back as whole, which is exactly how they were shown at the time. | ||
| 1173 | -#[tokio::test] | ||
| 1174 | -async fn legacy_chat_turns_backfill_to_untruncated() { | ||
| 1175 | - use hezarfen_backend::db::{chatbot_message, chatbot_thread}; | ||
| 1176 | - use hezarfen_backend::domain::chatbot_message::ChatContent; | ||
| 1177 | - use hezarfen_backend::domain::user::UserId; | ||
| 1178 | - | ||
| 1179 | - let (app, db) = common::app_and_db().await; | ||
| 1180 | - let creds = json!({ "school": "demo", "username": "ali", "password": "secret1" }); | ||
| 1181 | - assert_eq!( | ||
| 1182 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())) | ||
| 1183 | - .await | ||
| 1184 | - .status, | ||
| 1185 | - StatusCode::CREATED | ||
| 1186 | - ); | ||
| 1187 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 1188 | - .await | ||
| 1189 | - .cookie | ||
| 1190 | - .unwrap(); | ||
| 1191 | - let owner = UserId::from_key(&me_id(&app, &cookie).await); | ||
| 1192 | - | ||
| 1193 | - let thread = chatbot_thread::create_capped(&db, &owner, None) | ||
| 1194 | - .await | ||
| 1195 | - .expect("create"); | ||
| 1196 | - let id = thread.get_id().clone(); | ||
| 1197 | - chatbot_message::append_user( | ||
| 1198 | - &db, | ||
| 1199 | - &id, | ||
| 1200 | - &owner, | ||
| 1201 | - ChatContent::try_new("selam").expect("content"), | ||
| 1202 | - ) | ||
| 1203 | - .await | ||
| 1204 | - .expect("append user"); | ||
| 1205 | - let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) | ||
| 1206 | - .await | ||
| 1207 | - .expect("append assistant"); | ||
| 1208 | - chatbot_message::complete( | ||
| 1209 | - &db, | ||
| 1210 | - reply.get_id(), | ||
| 1211 | - ChatContent::try_new("aleykum selam").expect("content"), | ||
| 1212 | - false, | ||
| 1213 | - ) | ||
| 1214 | - .await | ||
| 1215 | - .expect("complete"); | ||
| 1216 | - | ||
| 1217 | - // Strip the column the way a pre-flag binary's schema would have left it. | ||
| 1218 | - db.query( | ||
| 1219 | - "REMOVE FIELD IF EXISTS truncated ON TABLE chatbot_message; | ||
| 1220 | - UPDATE chatbot_message SET truncated = NONE;", | ||
| 1221 | - ) | ||
| 1222 | - .await | ||
| 1223 | - .expect("strip truncated") | ||
| 1224 | - .check() | ||
| 1225 | - .expect("strip truncated check"); | ||
| 1226 | - | ||
| 1227 | - // Second boot: the backfill stamps the legacy rows, and the thread reads | ||
| 1228 | - // back through the API instead of failing to deserialize. | ||
| 1229 | - let app = reboot(&db).await; | ||
| 1230 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 1231 | - .await | ||
| 1232 | - .cookie | ||
| 1233 | - .unwrap(); | ||
| 1234 | - let res = send( | ||
| 1235 | - &app, | ||
| 1236 | - "GET", | ||
| 1237 | - &format!("/chatbot/threads/{}/messages", id.key()), | ||
| 1238 | - Some(&cookie), | ||
| 1239 | - None, | ||
| 1240 | - ) | ||
| 1241 | - .await; | ||
| 1242 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1243 | - let turns = common::items(&res.body); | ||
| 1244 | - assert_eq!(turns.len(), 2, "{}", res.body); | ||
| 1245 | - for turn in turns { | ||
| 1246 | - assert_eq!(turn["truncated"], false, "{turn}"); | ||
| 1247 | - } | ||
| 1248 | -} | ||
| 1249 | - | ||
| 1250 | -/// A settings singleton whose `meal_slots` predate `serving_minute` — the live | ||
| 1251 | -/// podman volume's shape — still reads, and still **saves**. The trap is the | ||
| 1252 | -/// compare-and-set in `save_if_unchanged`: it re-binds the loaded slot list as | ||
| 1253 | -/// the expected value, so if a slot object without the key round-tripped to one | ||
| 1254 | -/// *with* `serving_minute: NONE`, the guard would never match again and every | ||
| 1255 | -/// `PATCH /settings` would 409 forever on an upgraded database. | ||
| 1256 | -#[tokio::test] | ||
| 1257 | -async fn settings_slots_without_a_serving_minute_still_patch() { | ||
| 1258 | - let (app, db) = common::app_and_db().await; | ||
| 1259 | - | ||
| 1260 | - let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | ||
| 1261 | - send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; | ||
| 1262 | - set_role(&db, "boss", "manager").await; | ||
| 1263 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 1264 | - .await | ||
| 1265 | - .cookie | ||
| 1266 | - .unwrap(); | ||
| 1267 | - | ||
| 1268 | - // Materialize the singleton, then age its slots into the pre-serving-time | ||
| 1269 | - // shape: objects carrying nothing but a name. | ||
| 1270 | - let res = send( | ||
| 1271 | - &app, | ||
| 1272 | - "PATCH", | ||
| 1273 | - "/settings", | ||
| 1274 | - Some(&cookie), | ||
| 1275 | - Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 720 }] })), | ||
| 1276 | - ) | ||
| 1277 | - .await; | ||
| 1278 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1279 | - db.query("UPDATE settings:school SET meal_slots = [{ name: 'lunch' }];") | ||
| 1280 | - .await | ||
| 1281 | - .expect("age slots") | ||
| 1282 | - .check() | ||
| 1283 | - .expect("age slots check"); | ||
| 1284 | - | ||
| 1285 | - // Second boot over that row: it reads back, with the field simply absent. | ||
| 1286 | - let app = reboot(&db).await; | ||
| 1287 | - let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 1288 | - .await | ||
| 1289 | - .cookie | ||
| 1290 | - .unwrap(); | ||
| 1291 | - let res = send(&app, "GET", "/settings", Some(&cookie), None).await; | ||
| 1292 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1293 | - assert_eq!(res.body["meal_slots"][0]["name"], "lunch", "{}", res.body); | ||
| 1294 | - assert!( | ||
| 1295 | - res.body["meal_slots"][0]["serving_minute"].is_null(), | ||
| 1296 | - "{}", | ||
| 1297 | - res.body | ||
| 1298 | - ); | ||
| 1299 | - | ||
| 1300 | - // And a PATCH of an unrelated knob still lands: the CAS matched the aged | ||
| 1301 | - // row. This is the assertion that would have caught a `DEFAULT []` column. | ||
| 1302 | - let res = send( | ||
| 1303 | - &app, | ||
| 1304 | - "PATCH", | ||
| 1305 | - "/settings", | ||
| 1306 | - Some(&cookie), | ||
| 1307 | - Some(json!({ "max_file_bytes": 2048 })), | ||
| 1308 | - ) | ||
| 1309 | - .await; | ||
| 1310 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1311 | - assert_eq!(res.body["max_file_bytes"], 2048, "{}", res.body); | ||
| 1312 | - assert!( | ||
| 1313 | - res.body["meal_slots"][0]["serving_minute"].is_null(), | ||
| 1314 | - "{}", | ||
| 1315 | - res.body | ||
| 1316 | - ); | ||
| 1317 | - | ||
| 1318 | - // Setting the serving time on that legacy slot round-trips too. | ||
| 1319 | - let res = send( | ||
| 1320 | - &app, | ||
| 1321 | - "PATCH", | ||
| 1322 | - "/settings", | ||
| 1323 | - Some(&cookie), | ||
| 1324 | - Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 615 }] })), | ||
| 1325 | - ) | ||
| 1326 | - .await; | ||
| 1327 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1328 | - assert_eq!( | ||
| 1329 | - res.body["meal_slots"][0]["serving_minute"], 615, | ||
| 1330 | - "{}", | ||
| 1331 | - res.body | ||
| 1332 | - ); | ||
| 1333 | -} | ||
| 1334 | - | ||
| 1335 | -/// Rows written before the cap counters existed (2026-07-27) carry no counter | ||
| 1336 | -/// at all, and an absent counter reads as zero — which would hand a full course | ||
| 1337 | -/// and a full note a clean slate. The backfill seeds each parent from the | ||
| 1338 | -/// children it actually has, so the caps keep holding across the upgrade. | ||
| 1339 | -#[tokio::test] | ||
| 1340 | -async fn cap_counters_are_seeded_from_the_rows_that_predate_them() { | ||
| 1341 | - let (app, db) = common::app_and_db().await; | ||
| 1342 | - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; | ||
| 1343 | - let ali = common::login(&app, "ali").await; | ||
| 1344 | - let veli = common::login(&app, "veli").await; | ||
| 1345 | - let ayse = common::login(&app, "ayse").await; | ||
| 1346 | - let (ali_id, veli_id, ayse_id) = ( | ||
| 1347 | - me_id(&app, &ali).await, | ||
| 1348 | - me_id(&app, &veli).await, | ||
| 1349 | - me_id(&app, &ayse).await, | ||
| 1350 | - ); | ||
| 1351 | - | ||
| 1352 | - let res = send( | ||
| 1353 | - &app, | ||
| 1354 | - "POST", | ||
| 1355 | - "/courses", | ||
| 1356 | - Some(&teacher), | ||
| 1357 | - Some(json!({ "title": "small", "description": "", "capacity": 2 })), | ||
| 1358 | - ) | ||
| 1359 | - .await; | ||
| 1360 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1361 | - let course = common::id_of(&res.body); | ||
| 1362 | - enroll(&app, &teacher, &course, &ali_id).await; | ||
| 1363 | - enroll(&app, &teacher, &course, &veli_id).await; | ||
| 1364 | - | ||
| 1365 | - let res = send( | ||
| 1366 | - &app, | ||
| 1367 | - "POST", | ||
| 1368 | - "/notes", | ||
| 1369 | - Some(&ali), | ||
| 1370 | - Some(json!({ "title": "full", "content": "x" })), | ||
| 1371 | - ) | ||
| 1372 | - .await; | ||
| 1373 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1374 | - let note = common::id_of(&res.body); | ||
| 1375 | - for i in 0..10 { | ||
| 1376 | - let up = common::upload_file(&app, &ali, ¬e, &format!("f{i}.txt"), "", b"x").await; | ||
| 1377 | - assert_eq!(up.status, StatusCode::CREATED, "seed file {i}"); | ||
| 1378 | - } | ||
| 1379 | - | ||
| 1380 | - // Age both parents into the pre-counter shape. | ||
| 1381 | - db.query("UPDATE course UNSET enrollment_count; UPDATE note UNSET file_count;") | ||
| 1382 | - .await | ||
| 1383 | - .expect("age the rows") | ||
| 1384 | - .check() | ||
| 1385 | - .expect("age the rows"); | ||
| 1386 | - | ||
| 1387 | - let app = reboot(&db).await; | ||
| 1388 | - | ||
| 1389 | - let mut counters = db | ||
| 1390 | - .query("SELECT VALUE enrollment_count FROM course; SELECT VALUE file_count FROM note;") | ||
| 1391 | - .await | ||
| 1392 | - .expect("read counters") | ||
| 1393 | - .check() | ||
| 1394 | - .expect("read counters"); | ||
| 1395 | - assert_eq!( | ||
| 1396 | - counters.take::<Vec<i64>>(0).expect("enrollment_count"), | ||
| 1397 | - vec![2], | ||
| 1398 | - "the course counter must be seeded from its roster" | ||
| 1399 | - ); | ||
| 1400 | - assert_eq!( | ||
| 1401 | - counters.take::<Vec<i64>>(1).expect("file_count"), | ||
| 1402 | - vec![10], | ||
| 1403 | - "the note counter must be seeded from its files" | ||
| 1404 | - ); | ||
| 1405 | - | ||
| 1406 | - // And the caps still bite, which a zeroed counter would not have done. | ||
| 1407 | - let res = send( | ||
| 1408 | - &app, | ||
| 1409 | - "POST", | ||
| 1410 | - &format!("/courses/{course}/enrollments"), | ||
| 1411 | - Some(&teacher), | ||
| 1412 | - Some(json!({ "user_id": ayse_id })), | ||
| 1413 | - ) | ||
| 1414 | - .await; | ||
| 1415 | - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 1416 | - let up = common::upload_file(&app, &ali, ¬e, "eleventh.txt", "", b"x").await; | ||
| 1417 | - assert_eq!(up.status, StatusCode::CONFLICT, "{}", up.body); | ||
| 1418 | -} | ||
| 1419 | - | ||
| 1420 | -/// The appointment slot's counter is the odd one out: it seeds from the | ||
| 1421 | -/// bookings that are still *live*, because a rejected or cancelled one gave the | ||
| 1422 | -/// slot back long before the column existed (2026-07-27). A slot aged into the | ||
| 1423 | -/// pre-counter shape must come back taken if someone is still waiting on it, | ||
| 1424 | -/// and free if nobody is — a flat recount of its rows would get the second case | ||
| 1425 | -/// wrong and lock a free slot out of the calendar for good. | ||
| 1426 | -#[tokio::test] | ||
| 1427 | -async fn slot_occupancy_is_seeded_from_the_bookings_that_are_still_live() { | ||
| 1428 | - let (app, db) = common::app_and_db().await; | ||
| 1429 | - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; | ||
| 1430 | - let veli = common::login(&app, "veli").await; | ||
| 1431 | - let ayse = common::login(&app, "ayse").await; | ||
| 1432 | - let now = hezarfen_backend::domain::timestamp::Timestamp::now().as_millis(); | ||
| 1433 | - let hour = 3_600_000; | ||
| 1434 | 336 | ||
| 1435 | - async fn publish(app: &Router, who: &str, starts_at: i64) -> String { | 337 | + // Two sittings: distinct answer text + distinct mark on each. |
| 338 | + for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] { | ||
| 339 | + assert_eq!( | ||
| 340 | + send( | ||
| 341 | + &app, | ||
| 342 | + "POST", | ||
| 343 | + &format!("/exams/{exam}/attempt"), | ||
| 344 | + Some(&student), | ||
| 345 | + None | ||
| 346 | + ) | ||
| 347 | + .await | ||
| 348 | + .status, | ||
| 349 | + StatusCode::CREATED | ||
| 350 | + ); | ||
| 1436 | let res = send( | 351 | let res = send( |
| 1437 | - app, | 352 | + &app, |
| 1438 | "POST", | 353 | "POST", |
| 1439 | - "/appointments/slots", | 354 | + &format!("/exams/{exam}/attempt/answers"), |
| 1440 | - Some(who), | 355 | + Some(&student), |
| 1441 | - Some(json!({ "starts_at": starts_at, "ends_at": starts_at + 3_600_000 })), | 356 | + Some(json!({ "question_id": question, "text": text })), |
| 1442 | ) | 357 | ) |
| 1443 | .await; | 358 | .await; |
| 1444 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 359 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 1445 | - common::id_of(&res.body[0]) | 360 | + let res = send( |
| 1446 | - } | 361 | + &app, |
| 1447 | - async fn book(app: &Router, who: &str, slot: &str) -> common::Res { | 362 | + "POST", |
| 363 | + &format!("/exams/{exam}/results"), | ||
| 364 | + Some(&teacher), | ||
| 365 | + Some(json!({ "mark": mark, "user_id": student_id })), | ||
| 366 | + ) | ||
| 367 | + .await; | ||
| 368 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1448 | send( | 369 | send( |
| 1449 | - app, | 370 | + &app, |
| 1450 | "POST", | 371 | "POST", |
| 1451 | - "/appointments", | 372 | + &format!("/exams/{exam}/attempt/finish"), |
| 1452 | - Some(who), | 373 | + Some(&student), |
| 1453 | - Some(json!({ "slot": slot, "reason": "görüşme" })), | 374 | + None, |
| 1454 | ) | 375 | ) |
| 1455 | - .await | 376 | + .await; |
| 1456 | } | 377 | } |
| 1457 | 378 | ||
| 1458 | - let taken = publish(&app, &teacher, now + hour).await; | 379 | + // Second boot: migration re-applied over the two sittings' live rows. |
| 1459 | - let freed = publish(&app, &teacher, now + 3 * hour).await; | 380 | + let app = reboot(&db, &tenants).await; |
| 1460 | - let held = common::id_of(&book(&app, &veli, &taken).await.body); | 381 | + let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds)) |
| 1461 | - let gone = common::id_of(&book(&app, &veli, &freed).await.body); | 382 | + .await |
| 383 | + .cookie | ||
| 384 | + .unwrap(); | ||
| 385 | + | ||
| 1462 | let res = send( | 386 | let res = send( |
| 1463 | &app, | 387 | &app, |
| 1464 | - "PATCH", | 388 | + "GET", |
| 1465 | - &format!("/appointments/{gone}/reject"), | 389 | + &format!("/exams/{exam}/students/{student_id}/attempts"), |
| 1466 | Some(&teacher), | 390 | Some(&teacher), |
| 1467 | None, | 391 | None, |
| 1468 | ) | 392 | ) |
| 1469 | .await; | 393 | .await; |
| 1470 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 394 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 395 | + assert_eq!(res.body, json!([1, 2]), "both sittings survived the reboot"); | ||
| 1471 | 396 | ||
| 1472 | - // Age both slots into the pre-counter shape. | 397 | + // The seq-1 answer kept its own text through the reopen. |
| 1473 | - db.query("UPDATE appointment_slot UNSET occupied;") | ||
| 1474 | - .await | ||
| 1475 | - .expect("age the rows") | ||
| 1476 | - .check() | ||
| 1477 | - .expect("age the rows"); | ||
| 1478 | - | ||
| 1479 | - let app = reboot(&db).await; | ||
| 1480 | - | ||
| 1481 | - // The still-pending booking keeps its slot; the rejected one's slot is free. | ||
| 1482 | - let res = book(&app, &ayse, &taken).await; | ||
| 1483 | - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 1484 | - let res = book(&app, &ayse, &freed).await; | ||
| 1485 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1486 | - | ||
| 1487 | - // And the seeded seat is still a seat, not a stuck flag: cancelling the | ||
| 1488 | - // held booking hands it back. | ||
| 1489 | let res = send( | 398 | let res = send( |
| 1490 | &app, | 399 | &app, |
| 1491 | - "PATCH", | 400 | + "GET", |
| 1492 | - &format!("/appointments/{held}/cancel"), | 401 | + &format!("/exams/{exam}/students/{student_id}/attempts/1/answers"), |
| 1493 | - Some(&veli), | 402 | + Some(&teacher), |
| 1494 | None, | 403 | None, |
| 1495 | ) | 404 | ) |
| 1496 | .await; | 405 | .await; |
| 1497 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 406 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 1498 | - let res = book(&app, &ayse, &taken).await; | 407 | + assert_eq!(res.body["answers"][0]["text"], "mitochondria"); |
| 1499 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1500 | -} | ||
| 1501 | - | ||
| 1502 | -/// A submission graded before the freeze moved into the database (2026-07-27) | ||
| 1503 | -/// carries no `graded_by_result` stamp, and an absent stamp is exactly what the | ||
| 1504 | -/// student's writes now take as "still open" — so without the backfill an | ||
| 1505 | -/// upgrade would quietly unfreeze every already-graded submission. The backfill | ||
| 1506 | -/// stamps each one from the grade it already has; graded-but-never-submitted | ||
| 1507 | -/// work has no row to stamp and must stay that way (the report reads | ||
| 1508 | -/// `submitted`/`missing` straight off its absence). | ||
| 1509 | -#[tokio::test] | ||
| 1510 | -async fn graded_submissions_are_stamped_by_the_backfill() { | ||
| 1511 | - let (app, db) = common::app_and_db().await; | ||
| 1512 | - let teacher = common::login_as(&app, &db, "teacher", "teacher").await; | ||
| 1513 | - let ali = common::login(&app, "ali").await; | ||
| 1514 | - let veli = common::login(&app, "veli").await; | ||
| 1515 | - let (ali_id, veli_id) = (me_id(&app, &ali).await, me_id(&app, &veli).await); | ||
| 1516 | - let course = create_course(&app, &teacher, "math").await; | ||
| 1517 | - let subject = create_subject(&app, &teacher, &course, "algebra").await; | ||
| 1518 | - enroll(&app, &teacher, &course, &ali_id).await; | ||
| 1519 | - enroll(&app, &teacher, &course, &veli_id).await; | ||
| 1520 | - let due_at = Timestamp::now().as_millis() + 86_400_000; | ||
| 1521 | - let hw = common::create_homework(&app, &teacher, &course, &subject, "essay", due_at).await; | ||
| 1522 | 408 | ||
| 1523 | - // Ali hands in and is graded; Veli never hands in and is graded `missing`. | 409 | + // Both marks survive, oldest first; the roster's grade-of-record is seq 2. |
| 1524 | let res = send( | 410 | let res = send( |
| 1525 | &app, | 411 | &app, |
| 1526 | - "POST", | 412 | + "GET", |
| 1527 | - &format!("/homework/{hw}/submission"), | 413 | + &format!("/exams/{exam}/students/{student_id}/marks"), |
| 1528 | - Some(&ali), | 414 | + Some(&teacher), |
| 1529 | - Some(json!({ "text": "version A" })), | 415 | + None, |
| 1530 | ) | 416 | ) |
| 1531 | .await; | 417 | .await; |
| 1532 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 418 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 1533 | - for (user, status) in [(&ali_id, "done"), (&veli_id, "missing")] { | 419 | + let marks: Vec<i64> = res |
| 1534 | - let res = send( | 420 | + .body |
| 1535 | - &app, | 421 | + .as_array() |
| 1536 | - "POST", | 422 | + .unwrap() |
| 1537 | - &format!("/homework/{hw}/results"), | 423 | + .iter() |
| 1538 | - Some(&teacher), | 424 | + .map(|r| r["mark"].as_i64().unwrap()) |
| 1539 | - Some(json!({ "user": user, "status": status })), | 425 | + .collect(); |
| 1540 | - ) | ||
| 1541 | - .await; | ||
| 1542 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 1543 | - } | ||
| 1544 | - | ||
| 1545 | - // Age the row into the pre-stamp shape. | ||
| 1546 | - db.query("UPDATE homework_submission UNSET graded_by_result;") | ||
| 1547 | - .await | ||
| 1548 | - .expect("age the row") | ||
| 1549 | - .check() | ||
| 1550 | - .expect("age the row"); | ||
| 1551 | - let app = reboot(&db).await; | ||
| 1552 | - | ||
| 1553 | - let mut stamps = db | ||
| 1554 | - .query("SELECT VALUE graded_by_result FROM homework_submission; SELECT VALUE id FROM homework_submission;") | ||
| 1555 | - .await | ||
| 1556 | - .expect("read stamps") | ||
| 1557 | - .check() | ||
| 1558 | - .expect("read stamps"); | ||
| 1559 | - let stamped = stamps | ||
| 1560 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 1561 | - .expect("graded_by_result"); | ||
| 1562 | - let rows = stamps | ||
| 1563 | - .take::<Vec<surrealdb::types::RecordId>>(1) | ||
| 1564 | - .expect("submission ids"); | ||
| 1565 | - assert_eq!(rows.len(), 1, "grading absent work must not conjure a row"); | ||
| 1566 | - assert_eq!( | ||
| 1567 | - stamped.len(), | ||
| 1568 | - 1, | ||
| 1569 | - "the surviving submission must come back stamped by its grade" | ||
| 1570 | - ); | ||
| 1571 | - assert_eq!( | ||
| 1572 | - format!("{:?}", stamped[0].key), | ||
| 1573 | - format!("{:?}", rows[0].key), | ||
| 1574 | - "the stamp must name the grade of that very (homework, user) pair" | ||
| 1575 | - ); | ||
| 1576 | assert_eq!( | 426 | assert_eq!( |
| 1577 | - stamped[0].table.to_string(), | 427 | + marks, |
| 1578 | - "homework_result", | 428 | + vec![40, 90], |
| 1579 | - "the stamp must point at the grade table" | 429 | + "both sittings' marks durable, oldest first" |
| 1580 | ); | 430 | ); |
| 1581 | - | ||
| 1582 | - // And the freeze bites again, which an unstamped row would not have done. | ||
| 1583 | - let res = send( | ||
| 1584 | - &app, | ||
| 1585 | - "POST", | ||
| 1586 | - &format!("/homework/{hw}/submission"), | ||
| 1587 | - Some(&ali), | ||
| 1588 | - Some(json!({ "text": "version B" })), | ||
| 1589 | - ) | ||
| 1590 | - .await; | ||
| 1591 | - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 1592 | - // Veli, graded but never submitted, still reports as not-submitted. | ||
| 1593 | let res = send( | 431 | let res = send( |
| 1594 | &app, | 432 | &app, |
| 1595 | "GET", | 433 | "GET", |
| 1596 | - &format!("/homework/{hw}/submission"), | 434 | + &format!("/exams/{exam}/results"), |
| 1597 | - Some(&veli), | 435 | + Some(&teacher), |
| 1598 | None, | 436 | None, |
| 1599 | ) | 437 | ) |
| 1600 | .await; | 438 | .await; |
| 1601 | - assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); | 439 | + assert_eq!( |
| 440 | + common::items(&res.body)[0]["mark"], | ||
| 441 | + 90, | ||
| 442 | + "seq 2 is grade-of-record" | ||
| 443 | + ); | ||
| 1602 | } | 444 | } |
| 1603 | 445 | ||
| 1604 | -/// A menu written before the seat counter existed (2026-07-27) carries none, | 446 | +/// A chatbot thread and every turn in it die together: deleting the |
| 1605 | -/// which reads as zero — an uncapped menu for every seat already sold. The | 447 | +/// thread cascades its `chatbot_message` rows in one transaction, so no |
| 1606 | -/// backfill seeds it from the bookings that are still *held*: a cancelled one | 448 | +/// orphan survives a reboot. And the thread is owner-scoped end to end — a |
| 1607 | -/// gave its seat back long before the column existed, so counting rows flatly | 449 | +/// second user reads neither the thread nor its messages. |
| 1608 | -/// would lock out a seat nobody holds. | ||
| 1609 | #[tokio::test] | 450 | #[tokio::test] |
| 1610 | -async fn menu_seats_are_seeded_from_the_bookings_that_are_still_held() { | 451 | +async fn chat_thread_delete_cascades_and_stays_owner_scoped() { |
| 1611 | - let (app, db) = common::app_and_db().await; | 452 | + use hezarfen_backend::db::{chatbot_message, chatbot_thread}; |
| 1612 | - let mgr = common::login_as(&app, &db, "seat_mgr", "manager").await; | 453 | + use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus}; |
| 1613 | - let ali = common::login(&app, "seat_ali").await; | 454 | + use hezarfen_backend::domain::user::UserId; |
| 1614 | - let veli = common::login(&app, "seat_veli").await; | ||
| 1615 | - let ayse = common::login(&app, "seat_ayse").await; | ||
| 1616 | 455 | ||
| 1617 | - let res = send( | 456 | + let (app, db, tenants) = common::app_and_tenants().await; |
| 1618 | - &app, | 457 | + let owner_cookie = common::login(&app, "ali").await; |
| 1619 | - "POST", | 458 | + let other_cookie = common::login(&app, "ayse").await; |
| 1620 | - "/meals/menus", | 459 | + let owner = UserId::from_key(&me_id(&app, &owner_cookie).await); |
| 1621 | - Some(&mgr), | 460 | + let other = UserId::from_key(&me_id(&app, &other_cookie).await); |
| 1622 | - Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })), | ||
| 1623 | - ) | ||
| 1624 | - .await; | ||
| 1625 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1626 | - let menu = common::id_of(&res.body); | ||
| 1627 | 461 | ||
| 1628 | - let book = async |who: &str| { | 462 | + let thread = chatbot_thread::create_capped(&db, &owner, None) |
| 1629 | - send( | ||
| 1630 | - &app, | ||
| 1631 | - "POST", | ||
| 1632 | - &format!("/meals/menus/{menu}/bookings"), | ||
| 1633 | - Some(who), | ||
| 1634 | - Some(json!({})), | ||
| 1635 | - ) | ||
| 1636 | .await | 463 | .await |
| 1637 | - }; | 464 | + .expect("create"); |
| 1638 | - let held = book(&ali).await; | 465 | + let id = thread.get_id().clone(); |
| 1639 | - assert_eq!(held.status, StatusCode::CREATED, "{}", held.body); | 466 | + let prompt = chatbot_message::append_user( |
| 1640 | - let given_back = common::id_of(&book(&veli).await.body); | 467 | + &db, |
| 1641 | - let res = send( | 468 | + &id, |
| 1642 | - &app, | 469 | + &owner, |
| 1643 | - "DELETE", | 470 | + ChatContent::try_new("selam").expect("content"), |
| 1644 | - &format!("/meals/bookings/{given_back}"), | ||
| 1645 | - Some(&veli), | ||
| 1646 | - None, | ||
| 1647 | ) | 471 | ) |
| 1648 | - .await; | 472 | + .await |
| 1649 | - assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 473 | + .expect("append user"); |
| 1650 | - | 474 | + let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) |
| 1651 | - // Age the menu into the pre-counter shape. | ||
| 1652 | - db.query("UPDATE menu UNSET seats_booked;") | ||
| 1653 | .await | 475 | .await |
| 1654 | - .expect("age the row") | 476 | + .expect("append assistant"); |
| 1655 | - .check() | 477 | + assert_eq!(reply.get_status(), MessageStatus::Pending); |
| 1656 | - .expect("age the row"); | ||
| 1657 | - | ||
| 1658 | - // Same database, so the router above keeps serving; what matters is that | ||
| 1659 | - // the migration ran again over the aged row. | ||
| 1660 | - let _ = reboot(&db).await; | ||
| 1661 | 478 | ||
| 1662 | - let mut counted = db | 479 | + let reply = chatbot_message::complete( |
| 1663 | - .query("SELECT VALUE seats_booked FROM menu") | 480 | + &db, |
| 1664 | - .await | 481 | + reply.get_id(), |
| 1665 | - .expect("counter read") | 482 | + ChatContent::try_new("aleykum selam").expect("content"), |
| 1666 | - .check() | 483 | + false, |
| 1667 | - .expect("counter read"); | 484 | + ) |
| 485 | + .await | ||
| 486 | + .expect("complete"); | ||
| 487 | + assert_eq!(reply.get_status(), MessageStatus::Complete); | ||
| 488 | + assert_eq!(reply.get_content().as_str(), "aleykum selam"); | ||
| 489 | + assert!(reply.get_completed_at().is_some()); | ||
| 1668 | assert_eq!( | 490 | assert_eq!( |
| 1669 | - counted.take::<Vec<i64>>(0).expect("counter column"), | 491 | + chatbot_message::list_for_thread(&db, &id, None, 0) |
| 1670 | - vec![1], | 492 | + .await |
| 1671 | - "only the seat still held may be counted back" | 493 | + .expect("thread") |
| 494 | + .0 | ||
| 495 | + .len(), | ||
| 496 | + 2 | ||
| 1672 | ); | 497 | ); |
| 1673 | 498 | ||
| 1674 | - // The seeded counter is a real cap, not a decoration: one seat is left. | 499 | + // The other user sees nothing of it, by thread or by message. |
| 1675 | - assert_eq!(book(&ayse).await.status, StatusCode::CREATED); | 500 | + assert!( |
| 1676 | - assert_eq!(book(&veli).await.status, StatusCode::CONFLICT); | 501 | + chatbot_thread::read_for(&db, &id, &other) |
| 1677 | -} | 502 | + .await |
| 1678 | - | 503 | + .expect("cross-user thread") |
| 1679 | -/// A subject written before its two reference counters existed (2026-07-27) | 504 | + .is_none() |
| 1680 | -/// carries neither, and an absent counter reads as zero — which is exactly | 505 | + ); |
| 1681 | -/// "nothing points at me", so the delete guard would wave through a subject | 506 | + assert!( |
| 1682 | -/// half the school's questions are tagged with. The backfill counts the rows | 507 | + chatbot_message::read_for(&db, prompt.get_id(), &other) |
| 1683 | -/// that actually point at each subject, once. | 508 | + .await |
| 1684 | -/// | 509 | + .expect("cross-user message") |
| 1685 | -/// The bite is the last assertion: seed the counters wrong (or not at all) and | 510 | + .is_none() |
| 1686 | -/// the delete comes back `204` instead of `409`. | 511 | + ); |
| 1687 | -#[tokio::test] | 512 | + assert_eq!( |
| 1688 | -async fn subject_reference_counts_are_seeded_from_the_rows_that_predate_them() { | 513 | + chatbot_thread::count_for_user(&db, &other) |
| 1689 | - let (app, db) = common::app_and_db().await; | 514 | + .await |
| 1690 | - let teacher = common::login_as(&app, &db, "seed_t", "teacher").await; | 515 | + .expect("count"), |
| 1691 | - let course = create_course(&app, &teacher, "biology").await; | 516 | + 0 |
| 1692 | - let tagged = create_subject(&app, &teacher, &course, "cells").await; | 517 | + ); |
| 1693 | - let untouched = create_subject(&app, &teacher, &course, "genes").await; | 518 | + assert_eq!( |
| 1694 | - let exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await; | 519 | + chatbot_thread::count_for_user(&db, &owner) |
| 1695 | - for text in ["what?", "why?"] { | 520 | + .await |
| 1696 | - let res = send( | 521 | + .expect("count"), |
| 1697 | - &app, | 522 | + 1 |
| 1698 | - "POST", | ||
| 1699 | - &format!("/exams/{exam}/questions"), | ||
| 1700 | - Some(&teacher), | ||
| 1701 | - Some(json!({ | ||
| 1702 | - "text": text, | ||
| 1703 | - "kind": "text", | ||
| 1704 | - "points": 1, | ||
| 1705 | - "subject_id": tagged, | ||
| 1706 | - })), | ||
| 1707 | - ) | ||
| 1708 | - .await; | ||
| 1709 | - assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 1710 | - } | ||
| 1711 | - let due = Timestamp::now().as_millis() + 86_400_000; | ||
| 1712 | - common::create_homework(&app, &teacher, &course, &tagged, "mitosis", due).await; | ||
| 1713 | - | ||
| 1714 | - // Age both subjects into the pre-counter shape. | ||
| 1715 | - db.query("UPDATE subject UNSET exam_question_count, homework_count;") | ||
| 1716 | - .await | ||
| 1717 | - .expect("age the rows") | ||
| 1718 | - .check() | ||
| 1719 | - .expect("age the rows"); | ||
| 1720 | - | ||
| 1721 | - let app = reboot(&db).await; | ||
| 1722 | - | ||
| 1723 | - let mut counted = db | ||
| 1724 | - .query( | ||
| 1725 | - "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \ | ||
| 1726 | - FROM subject ORDER BY id ASC", | ||
| 1727 | - ) | ||
| 1728 | - .await | ||
| 1729 | - .expect("counter read") | ||
| 1730 | - .check() | ||
| 1731 | - .expect("counter read"); | ||
| 1732 | - assert_eq!( | ||
| 1733 | - counted.take::<Vec<Vec<i64>>>(0).expect("counter columns"), | ||
| 1734 | - vec![vec![2, 1], vec![0, 0]], | ||
| 1735 | - "each subject must be seeded from the rows that point at it" | ||
| 1736 | ); | 523 | ); |
| 1737 | 524 | ||
| 1738 | - // The seeded counters are the delete guard itself, not a decoration. | ||
| 1739 | - let res = send( | ||
| 1740 | - &app, | ||
| 1741 | - "DELETE", | ||
| 1742 | - &format!("/subjects/{tagged}"), | ||
| 1743 | - Some(&teacher), | ||
| 1744 | - None, | ||
| 1745 | - ) | ||
| 1746 | - .await; | ||
| 1747 | - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 1748 | - let res = send( | ||
| 1749 | - &app, | ||
| 1750 | - "DELETE", | ||