Port integration to the Postgres harness
Browse files at this commitdab83cbb39c248958e6ec1dd465490ed794f4de4Parent: f553d14- test
- port integration to the Postgres harness
1 changed file +382 -533
- tests/integration.rs +382 -533
tests/integration.rsmodified+382 -533
| @@ -1,12 +1,12 @@ | |||
| 1 | //! Integration tests: drive the assembled axum router directly (no network) | 1 | //! Integration tests: drive the assembled axum router directly (no network) |
| 2 | -//! against a fresh in-memory SurrealDB, via `tower::ServiceExt::oneshot`. | 2 | +//! against a fresh per-test Postgres deployment, via `tower::ServiceExt::oneshot`. |
| 3 | 3 | ||
| 4 | mod common; | 4 | mod common; |
| 5 | 5 | ||
| 6 | use axum::body::Body; | 6 | use axum::body::Body; |
| 7 | use axum::http::{Request, StatusCode}; | 7 | use axum::http::{Request, StatusCode}; |
| 8 | use common::{ | 8 | use common::{ |
| 9 | - app_and_db, app_with_ai_health, create_course, create_exam, create_exam_with, create_homework, | 9 | + app_and_db, app_and_tenants, create_course, create_exam, create_exam_with, create_homework, |
| 10 | create_session, create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, | 10 | create_session, create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, |
| 11 | unenroll, upload_course_note_file, | 11 | unenroll, upload_course_note_file, |
| 12 | }; | 12 | }; |
| @@ -25,11 +25,12 @@ use hezarfen_backend::domain::course_note::CourseNoteId; | |||
| 25 | use hezarfen_backend::domain::course_note_file::CourseNoteFileId; | 25 | use hezarfen_backend::domain::course_note_file::CourseNoteFileId; |
| 26 | use hezarfen_backend::domain::exam::ExamId; | 26 | use hezarfen_backend::domain::exam::ExamId; |
| 27 | use hezarfen_backend::domain::timestamp::Timestamp; | 27 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 28 | -use hezarfen_backend::domain::user::{Password, User, UserId, Username}; | 28 | +use hezarfen_backend::domain::user::{Password, UserId, Username}; |
| 29 | use hezarfen_backend::module::ModuleSet; | 29 | use hezarfen_backend::module::ModuleSet; |
| 30 | -use hezarfen_backend::state::{AppState, DbHealth}; | 30 | +use hezarfen_backend::state::AppState; |
| 31 | use serde_json::json; | 31 | use serde_json::json; |
| 32 | use tower::ServiceExt; | 32 | use tower::ServiceExt; |
| 33 | +use uuid::Uuid; | ||
| 33 | 34 | ||
| 34 | // --- health + auth ------------------------------------------------------- | 35 | // --- health + auth ------------------------------------------------------- |
| 35 | 36 | ||
| @@ -46,27 +47,26 @@ async fn health_reports_ok() { | |||
| 46 | assert_eq!(res.body["ai"]["workers"], 0); | 47 | assert_eq!(res.body["ai"]["workers"], 0); |
| 47 | } | 48 | } |
| 48 | 49 | ||
| 49 | -/// The probe must survive the outage it reports. `db_guard` refuses everything | 50 | +/// The probe must survive the outage it reports. A wedged database refuses |
| 50 | -/// else with a generic 503 while the socket is down; `/health` (and `/`) answer | 51 | +/// everything else with a generic timeout while `/health` (and `/`) answer |
| 51 | /// their own 503 that names the database, or the probe is useless exactly when | 52 | /// their own 503 that names the database, or the probe is useless exactly when |
| 52 | -/// it is needed. | 53 | +/// it is needed. The control pool is closed to play the outage: the probe then |
| 54 | +/// cannot reach its database, which is what a dead server looks like from a | ||
| 55 | +/// pool handle. | ||
| 53 | #[tokio::test] | 56 | #[tokio::test] |
| 54 | async fn health_reports_the_database_down_instead_of_being_refused() { | 57 | async fn health_reports_the_database_down_instead_of_being_refused() { |
| 55 | - let db_up = DbHealth::default(); | 58 | + let (app, _db, tenants) = app_and_tenants().await; |
| 56 | - let (app, _db) = app_with_ai_health(None, db_up.clone()).await; | 59 | + let res = send(&app, "GET", "/health", None, None).await; |
| 60 | + assert_eq!(res.status, StatusCode::OK); | ||
| 61 | + assert_eq!(res.body["db"], "up"); | ||
| 57 | 62 | ||
| 58 | - db_up.set(false); | 63 | + tenants.control().close().await; |
| 59 | for path in ["/health", "/"] { | 64 | for path in ["/health", "/"] { |
| 60 | let res = send(&app, "GET", path, None, None).await; | 65 | let res = send(&app, "GET", path, None, None).await; |
| 61 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{path}"); | 66 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{path}"); |
| 62 | assert_eq!(res.body["status"], "degraded", "{path}"); | 67 | assert_eq!(res.body["status"], "degraded", "{path}"); |
| 63 | assert_eq!(res.body["db"], "down", "{path}"); | 68 | assert_eq!(res.body["db"], "down", "{path}"); |
| 64 | } | 69 | } |
| 65 | - | ||
| 66 | - db_up.set(true); | ||
| 67 | - let res = send(&app, "GET", "/health", None, None).await; | ||
| 68 | - assert_eq!(res.status, StatusCode::OK); | ||
| 69 | - assert_eq!(res.body["db"], "up"); | ||
| 70 | } | 70 | } |
| 71 | 71 | ||
| 72 | #[tokio::test] | 72 | #[tokio::test] |
| @@ -187,10 +187,10 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() { | |||
| 187 | async fn limits_still_answers_while_the_database_is_down() { | 187 | async fn limits_still_answers_while_the_database_is_down() { |
| 188 | // A frontend booting against a backend whose database is reconnecting is | 188 | // A frontend booting against a backend whose database is reconnecting is |
| 189 | // precisely when it needs the validation contract. `/limits` touches no | 189 | // precisely when it needs the validation contract. `/limits` touches no |
| 190 | - // row, so the outage guard must let it through — otherwise the client | 190 | + // row, so the outage must not take it down with the database — otherwise |
| 191 | - // falls back to the hard-coded copy this endpoint exists to remove. | 191 | + // the client falls back to the hard-coded copy this endpoint exists to |
| 192 | - let db_up = hezarfen_backend::state::DbHealth::default(); | 192 | + // remove. The school pool is closed to play the outage. |
| 193 | - let (tenants, _db) = common::mem_deployment().await; | 193 | + let (tenants, db) = common::mem_deployment().await; |
| 194 | let app = build_router(AppState { | 194 | let app = build_router(AppState { |
| 195 | db: tenants.control().clone(), | 195 | db: tenants.control().clone(), |
| 196 | tenants, | 196 | tenants, |
| @@ -200,19 +200,19 @@ async fn limits_still_answers_while_the_database_is_down() { | |||
| 200 | chatbot_limit: Default::default(), | 200 | chatbot_limit: Default::default(), |
| 201 | exam_presence: Default::default(), | 201 | exam_presence: Default::default(), |
| 202 | board_hub: Default::default(), | 202 | board_hub: Default::default(), |
| 203 | - db_up: db_up.clone(), | ||
| 204 | ai: None, | 203 | ai: None, |
| 205 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 204 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 206 | }); | 205 | }); |
| 207 | - db_up.set(false); | 206 | + let ali = login(&app, "ali").await; |
| 207 | + db.close().await; | ||
| 208 | 208 | ||
| 209 | let res = send(&app, "GET", "/limits", None, None).await; | 209 | let res = send(&app, "GET", "/limits", None, None).await; |
| 210 | assert_eq!(res.status, StatusCode::OK); | 210 | assert_eq!(res.status, StatusCode::OK); |
| 211 | assert!(res.body["user"]["max_username_len"].is_number()); | 211 | assert!(res.body["user"]["max_username_len"].is_number()); |
| 212 | 212 | ||
| 213 | - // Everything that does touch the database still refuses, so the exemption | 213 | + // Everything that does touch the database still refuses, so the static |
| 214 | - // is scoped to the one static route and has not disarmed the guard. | 214 | + // route staying up is not the database silently passing for healthy. |
| 215 | - let res = send(&app, "GET", "/settings", None, None).await; | 215 | + let res = send(&app, "GET", "/settings", Some(&ali), None).await; |
| 216 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE); | 216 | assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE); |
| 217 | } | 217 | } |
| 218 | 218 | ||
| @@ -1194,11 +1194,11 @@ async fn note_file_count_is_capped() { | |||
| 1194 | 1194 | ||
| 1195 | /// Regression: the 10-file cap was a bare count-then-write — concurrent | 1195 | /// Regression: the 10-file cap was a bare count-then-write — concurrent |
| 1196 | /// uploads all read the same pre-count and pushed a note past the cap (the | 1196 | /// uploads all read the same pre-count and pushed a note past the cap (the |
| 1197 | -/// same write-skew as the event-capacity over-admit; SurrealDB transactions | 1197 | +/// same write-skew as the event-capacity over-admit; the old engine's |
| 1198 | -/// don't conflict-check a cross-record count against an insert). The insert | 1198 | +/// transactions did not conflict-check a cross-record count against an |
| 1199 | -/// now recounts under a lock, so the outcome is race-order independent: | 1199 | +/// insert). The insert now recounts under a lock, so the outcome is |
| 1200 | -/// exactly enough uploads win to land on the cap, the rest get the same 409 | 1200 | +/// race-order independent: exactly enough uploads win to land on the cap, |
| 1201 | -/// as a sequential over-fill. | 1201 | +/// the rest get the same 409 as a sequential over-fill. |
| 1202 | #[tokio::test] | 1202 | #[tokio::test] |
| 1203 | async fn concurrent_uploads_never_exceed_the_file_cap() { | 1203 | async fn concurrent_uploads_never_exceed_the_file_cap() { |
| 1204 | let app = mem_app().await; | 1204 | let app = mem_app().await; |
| @@ -1430,14 +1430,11 @@ async fn deleting_a_note_removes_its_files() { | |||
| 1430 | ); | 1430 | ); |
| 1431 | 1431 | ||
| 1432 | // Row and blob are both gone. | 1432 | // Row and blob are both gone. |
| 1433 | - let mut rows = db | 1433 | + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM note_file") |
| 1434 | - .query("SELECT * FROM note_file") | 1434 | + .fetch_one(&db) |
| 1435 | .await | 1435 | .await |
| 1436 | - .unwrap() | 1436 | + .expect("note_file count"); |
| 1437 | - .check() | 1437 | + assert_eq!(left, 0, "note_file rows must cascade"); |
| 1438 | - .unwrap(); | ||
| 1439 | - let left: Vec<serde_json::Value> = rows.take(0).unwrap(); | ||
| 1440 | - assert!(left.is_empty(), "note_file rows must cascade: {left:?}"); | ||
| 1441 | assert!( | 1438 | assert!( |
| 1442 | !common::blob_dir().join(&file_id).exists(), | 1439 | !common::blob_dir().join(&file_id).exists(), |
| 1443 | "blob must be unlinked when its note dies" | 1440 | "blob must be unlinked when its note dies" |
| @@ -4312,9 +4309,11 @@ async fn event_registration_follows_placement_rules() { | |||
| 4312 | // Deleting the event cascades its signup rows away. | 4309 | // Deleting the event cascades its signup rows away. |
| 4313 | let res = send(&app, "DELETE", &format!("/events/{ev}"), Some(&ali), None).await; | 4310 | let res = send(&app, "DELETE", &format!("/events/{ev}"), Some(&ali), None).await; |
| 4314 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 4311 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 4315 | - let left: Vec<hezarfen_backend::domain::registration::Registration> = | 4312 | + let left: i64 = sqlx::query_scalar("SELECT count(*) FROM registration") |
| 4316 | - db.select("registration").await.unwrap(); | 4313 | + .fetch_one(&db) |
| 4317 | - assert!(left.is_empty(), "event delete leaves no seats behind"); | 4314 | + .await |
| 4315 | + .expect("registration count"); | ||
| 4316 | + assert_eq!(left, 0, "event delete leaves no seats behind"); | ||
| 4318 | } | 4317 | } |
| 4319 | 4318 | ||
| 4320 | /// A capacity caps live seats, not history: re-registering never double-counts, | 4319 | /// A capacity caps live seats, not history: re-registering never double-counts, |
| @@ -4470,7 +4469,7 @@ async fn re_registering_returns_the_seat_untouched() { | |||
| 4470 | "re-registering must not rewrite who placed the student" | 4469 | "re-registering must not rewrite who placed the student" |
| 4471 | ); | 4470 | ); |
| 4472 | // Regression: the response used to resolve people only from {target, | 4471 | // Regression: the response used to resolve people only from {target, |
| 4473 | - // caller}, so the original registrar degraded to a bare ULID username. | 4472 | + // caller}, so the original registrar degraded to a bare id username. |
| 4474 | assert_eq!( | 4473 | assert_eq!( |
| 4475 | second.body["registered_by"]["username"], "ali", | 4474 | second.body["registered_by"]["username"], "ali", |
| 4476 | "the original registrar must resolve to a person, not a bare id" | 4475 | "the original registrar must resolve to a person, not a bare id" |
| @@ -4479,7 +4478,7 @@ async fn re_registering_returns_the_seat_untouched() { | |||
| 4479 | } | 4478 | } |
| 4480 | 4479 | ||
| 4481 | /// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose | 4480 | /// Regression: the capacity check used to run inside a `BEGIN…COMMIT` whose |
| 4482 | -/// cross-record `count()` SurrealDB does not conflict-check against a | 4481 | +/// cross-record `count()` the old engine did not conflict-check against a |
| 4483 | /// concurrent insert (write-skew) — two racing placements both saw the last | 4482 | /// concurrent insert (write-skew) — two racing placements both saw the last |
| 4484 | /// seat free and a capacity-1 event admitted 2. The register path now | 4483 | /// seat free and a capacity-1 event admitted 2. The register path now |
| 4485 | /// serializes the check-then-write, so exactly one wins and the loser gets | 4484 | /// serializes the check-then-write, so exactly one wins and the loser gets |
| @@ -4653,16 +4652,13 @@ async fn concurrent_enrolls_of_one_pair_claim_one_seat() { | |||
| 4653 | 4652 | ||
| 4654 | let roster = send(&app, "GET", &uri, Some(&teacher), None).await; | 4653 | let roster = send(&app, "GET", &uri, Some(&teacher), None).await; |
| 4655 | assert_eq!(common::total(&roster.body), 1, "one pair, one row"); | 4654 | assert_eq!(common::total(&roster.body), 1, "one pair, one row"); |
| 4656 | - let mut counted = db | 4655 | + let counted: i64 = sqlx::query_scalar("SELECT enrollment_count FROM course WHERE id = $1") |
| 4657 | - .query("SELECT VALUE enrollment_count FROM type::record('course', $c)") | 4656 | + .bind(Uuid::parse_str(&course).expect("course id")) |
| 4658 | - .bind(("c", course.clone())) | 4657 | + .fetch_one(&db) |
| 4659 | .await | 4658 | .await |
| 4660 | - .expect("counter read") | ||
| 4661 | - .check() | ||
| 4662 | .expect("counter read"); | 4659 | .expect("counter read"); |
| 4663 | assert_eq!( | 4660 | assert_eq!( |
| 4664 | - counted.take::<Vec<i64>>(0).expect("counter column"), | 4661 | + counted, 1, |
| 4665 | - vec![1], | ||
| 4666 | "one row on the roster must have cost exactly one seat" | 4662 | "one row on the roster must have cost exactly one seat" |
| 4667 | ); | 4663 | ); |
| 4668 | } | 4664 | } |
| @@ -4711,16 +4707,13 @@ async fn concurrent_enrolls_of_one_seat_never_refuse_their_own_winner() { | |||
| 4711 | 4707 | ||
| 4712 | let roster = send(&app, "GET", &uri, Some(&teacher), None).await; | 4708 | let roster = send(&app, "GET", &uri, Some(&teacher), None).await; |
| 4713 | assert_eq!(common::total(&roster.body), 1, "one seat: {}", roster.body); | 4709 | assert_eq!(common::total(&roster.body), 1, "one seat: {}", roster.body); |
| 4714 | - let mut counted = db | 4710 | + let counted: i64 = sqlx::query_scalar("SELECT enrollment_count FROM course WHERE id = $1") |
| 4715 | - .query("SELECT VALUE enrollment_count FROM type::record('course', $c)") | 4711 | + .bind(Uuid::parse_str(&course).expect("course id")) |
| 4716 | - .bind(("c", course.clone())) | 4712 | + .fetch_one(&db) |
| 4717 | .await | 4713 | .await |
| 4718 | - .expect("counter read") | ||
| 4719 | - .check() | ||
| 4720 | .expect("counter read"); | 4714 | .expect("counter read"); |
| 4721 | assert_eq!( | 4715 | assert_eq!( |
| 4722 | - counted.take::<Vec<i64>>(0).expect("counter column"), | 4716 | + counted, 1, |
| 4723 | - vec![1], | ||
| 4724 | "and the seat it cost is the one seat the course has" | 4717 | "and the seat it cost is the one seat the course has" |
| 4725 | ); | 4718 | ); |
| 4726 | } | 4719 | } |
| @@ -4744,22 +4737,13 @@ async fn subject_reference_counts_track_every_writer() { | |||
| 4744 | let due = Timestamp::now().as_millis() + 86_400_000; | 4737 | let due = Timestamp::now().as_millis() + 86_400_000; |
| 4745 | 4738 | ||
| 4746 | let counts = async |subject: &str| -> (i64, i64) { | 4739 | let counts = async |subject: &str| -> (i64, i64) { |
| 4747 | - let mut result = db | 4740 | + let pair: (i64, i64) = |
| 4748 | - .query( | 4741 | + sqlx::query_as("SELECT exam_question_count, homework_count FROM subject WHERE id = $1") |
| 4749 | - "SELECT VALUE [exam_question_count ?? 0, homework_count ?? 0] \ | 4742 | + .bind(Uuid::parse_str(subject).expect("subject id")) |
| 4750 | - FROM type::record('subject', $s)", | 4743 | + .fetch_one(&db) |
| 4751 | - ) | 4744 | + .await |
| 4752 | - .bind(("s", subject.to_string())) | 4745 | + .expect("counter read"); |
| 4753 | - .await | 4746 | + pair |
| 4754 | - .expect("counter read") | ||
| 4755 | - .check() | ||
| 4756 | - .expect("counter read"); | ||
| 4757 | - let pair = result | ||
| 4758 | - .take::<Vec<Vec<i64>>>(0) | ||
| 4759 | - .expect("counter columns") | ||
| 4760 | - .pop() | ||
| 4761 | - .expect("the subject row"); | ||
| 4762 | - (pair[0], pair[1]) | ||
| 4763 | }; | 4747 | }; |
| 4764 | 4748 | ||
| 4765 | let question = create_question( | 4749 | let question = create_question( |
| @@ -4947,33 +4931,24 @@ async fn a_subject_delete_racing_question_creates_leaves_no_orphan() { | |||
| 4947 | } | 4931 | } |
| 4948 | let killed = killer.await.unwrap(); | 4932 | let killed = killer.await.unwrap(); |
| 4949 | 4933 | ||
| 4950 | - let mut result = db | 4934 | + let counter: i64 = |
| 4951 | - .query("SELECT VALUE exam_question_count ?? 0 FROM type::record('subject', $s)") | 4935 | + sqlx::query_scalar("SELECT exam_question_count FROM subject WHERE id = $1") |
| 4952 | - .bind(("s", subject.clone())) | 4936 | + .bind(Uuid::parse_str(&subject).expect("subject id")) |
| 4953 | - .await | 4937 | + .fetch_one(&db) |
| 4954 | - .expect("counter read") | 4938 | + .await |
| 4955 | - .check() | 4939 | + .expect("counter read"); |
| 4956 | - .expect("counter read"); | 4940 | + let landed: i64 = sqlx::query_scalar("SELECT count(*) FROM exam_question WHERE subject = $1") |
| 4957 | - let counter = result.take::<Vec<i64>>(0).expect("counter column"); | 4941 | + .bind(Uuid::parse_str(&subject).expect("subject id")) |
| 4958 | - let mut rows = db | 4942 | + .fetch_one(&db) |
| 4959 | - .query("SELECT VALUE id FROM exam_question WHERE subject = type::record('subject', $s)") | ||
| 4960 | - .bind(("s", subject.clone())) | ||
| 4961 | .await | 4943 | .await |
| 4962 | - .expect("row read") | ||
| 4963 | - .check() | ||
| 4964 | .expect("row read"); | 4944 | .expect("row read"); |
| 4965 | - let landed = rows | ||
| 4966 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 4967 | - .expect("question rows") | ||
| 4968 | - .len() as i64; | ||
| 4969 | assert_eq!( | 4945 | assert_eq!( |
| 4970 | killed, | 4946 | killed, |
| 4971 | StatusCode::CONFLICT, | 4947 | StatusCode::CONFLICT, |
| 4972 | "a subject a question already points at may never be deleted" | 4948 | "a subject a question already points at may never be deleted" |
| 4973 | ); | 4949 | ); |
| 4974 | assert_eq!( | 4950 | assert_eq!( |
| 4975 | - counter.first().copied(), | 4951 | + counter, landed, |
| 4976 | - Some(landed), | ||
| 4977 | "the subject must survive with its counter equal to the rows it guards" | 4952 | "the subject must survive with its counter equal to the rows it guards" |
| 4978 | ); | 4953 | ); |
| 4979 | } | 4954 | } |
| @@ -5922,12 +5897,15 @@ async fn login_purges_expired_sessions() { | |||
| 5922 | let (app, db) = app_and_db().await; | 5897 | let (app, db) = app_and_db().await; |
| 5923 | let ali = login(&app, "ali").await; // one live session | 5898 | let ali = login(&app, "ali").await; // one live session |
| 5924 | 5899 | ||
| 5925 | - // Inject a session that has already expired. | 5900 | + // Inject a session that has already expired. The FK forces the row to |
| 5926 | - db.query("CREATE session SET user = type::record('user', $u), token = 'expired-token', expires_at = 1") | 5901 | + // point at a real user; the old engine allowed a dangling one. |
| 5927 | - .bind(("u", "nobody".to_string())) | 5902 | + let ali_id = me_id(&app, &ali).await; |
| 5903 | + sqlx::query("INSERT INTO user_session (id, app_user, token, expires_at) \ | ||
| 5904 | + VALUES ($1, $2, 'expired-token', 1)") | ||
| 5905 | + .bind(Uuid::now_v7()) | ||
| 5906 | + .bind(Uuid::parse_str(&ali_id).expect("user id")) | ||
| 5907 | + .execute(&db) | ||
| 5928 | .await | 5908 | .await |
| 5929 | - .unwrap() | ||
| 5930 | - .check() | ||
| 5931 | .unwrap(); | 5909 | .unwrap(); |
| 5932 | assert!( | 5910 | assert!( |
| 5933 | session::find_by_token(&db, "expired-token") | 5911 | session::find_by_token(&db, "expired-token") |
| @@ -5961,15 +5939,14 @@ async fn expired_session_is_unauthorized_before_any_purge() { | |||
| 5961 | 5939 | ||
| 5962 | // Copy ali's live session into a second row that expired long ago | 5940 | // Copy ali's live session into a second row that expired long ago |
| 5963 | // (epoch millis 1), pointing at the same real user. | 5941 | // (epoch millis 1), pointing at the same real user. |
| 5964 | - db.query( | 5942 | + sqlx::query( |
| 5965 | - "CREATE session SET \ | 5943 | + "INSERT INTO user_session (id, app_user, token, expires_at) \ |
| 5966 | - user = (SELECT VALUE user FROM ONLY session WHERE token = $live LIMIT 1), \ | 5944 | + SELECT $1, app_user, 'stale-token', 1 FROM user_session WHERE token = $2", |
| 5967 | - token = 'stale-token', expires_at = 1", | ||
| 5968 | ) | 5945 | ) |
| 5969 | - .bind(("live", common::cookie_token(&ali).to_string())) | 5946 | + .bind(Uuid::now_v7()) |
| 5947 | + .bind(common::cookie_token(&ali).to_string()) | ||
| 5948 | + .execute(&db) | ||
| 5970 | .await | 5949 | .await |
| 5971 | - .unwrap() | ||
| 5972 | - .check() | ||
| 5973 | .unwrap(); | 5950 | .unwrap(); |
| 5974 | 5951 | ||
| 5975 | // Row exists, but the clock says no. | 5952 | // Row exists, but the clock says no. |
| @@ -6025,24 +6002,16 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | |||
| 6025 | } | 6002 | } |
| 6026 | 6003 | ||
| 6027 | // One row, not four — the padded forms collided with the canonical name. | 6004 | // One row, not four — the padded forms collided with the canonical name. |
| 6028 | - let rows: Vec<User> = db | 6005 | + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE username = 'ali'") |
| 6029 | - .query("SELECT * FROM user WHERE username = 'ali'") | 6006 | + .fetch_one(&db) |
| 6030 | .await | 6007 | .await |
| 6031 | - .unwrap() | ||
| 6032 | - .check() | ||
| 6033 | - .unwrap() | ||
| 6034 | - .take(0) | ||
| 6035 | .unwrap(); | 6008 | .unwrap(); |
| 6036 | - assert_eq!(rows.len(), 1, "padding minted a lookalike account"); | 6009 | + assert_eq!(rows, 1, "padding minted a lookalike account"); |
| 6037 | - let all: Vec<User> = db | 6010 | + let all: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user") |
| 6038 | - .query("SELECT * FROM user") | 6011 | + .fetch_one(&db) |
| 6039 | .await | 6012 | .await |
| 6040 | - .unwrap() | ||
| 6041 | - .check() | ||
| 6042 | - .unwrap() | ||
| 6043 | - .take(0) | ||
| 6044 | .unwrap(); | 6013 | .unwrap(); |
| 6045 | - assert_eq!(all.len(), 1, "unexpected extra user rows"); | 6014 | + assert_eq!(all, 1, "unexpected extra user rows"); |
| 6046 | 6015 | ||
| 6047 | // That one account still belongs to the first registration, and every | 6016 | // That one account still belongs to the first registration, and every |
| 6048 | // spelling of the name resolves to it. | 6017 | // spelling of the name resolves to it. |
| @@ -6355,14 +6324,11 @@ async fn promotion_via_role_endpoint_sweeps_enrollments() { | |||
| 6355 | ); | 6324 | ); |
| 6356 | 6325 | ||
| 6357 | // Really deleted, not merely filtered out of the listing. | 6326 | // Really deleted, not merely filtered out of the listing. |
| 6358 | - let mut result = db | 6327 | + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM enrollment") |
| 6359 | - .query("SELECT VALUE id FROM enrollment") | 6328 | + .fetch_one(&db) |
| 6360 | .await | 6329 | .await |
| 6361 | - .expect("count enrollments") | 6330 | + .expect("count enrollments"); |
| 6362 | - .check() | 6331 | + assert_eq!(rows, 0, "enrollment rows deleted from the DB"); |
| 6363 | - .expect("count enrollments check"); | ||
| 6364 | - let rows: Vec<surrealdb::types::RecordId> = result.take(0).expect("enrollment rows"); | ||
| 6365 | - assert!(rows.is_empty(), "enrollment rows deleted from the DB"); | ||
| 6366 | } | 6332 | } |
| 6367 | 6333 | ||
| 6368 | /// Regression: `db::user::create` pre-checks the username and then inserts, so two | 6334 | /// Regression: `db::user::create` pre-checks the username and then inserts, so two |
| @@ -6401,17 +6367,12 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | |||
| 6401 | } | 6367 | } |
| 6402 | 6368 | ||
| 6403 | // Exactly one row exists for the name. | 6369 | // Exactly one row exists for the name. |
| 6404 | - let users: Vec<hezarfen_backend::domain::user::User> = db | 6370 | + let users: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE username = 'dup'") |
| 6405 | - .query("SELECT * FROM user WHERE username = 'dup'") | 6371 | + .fetch_one(&db) |
| 6406 | .await | 6372 | .await |
| 6407 | - .unwrap() | ||
| 6408 | - .check() | ||
| 6409 | - .unwrap() | ||
| 6410 | - .take(0) | ||
| 6411 | .unwrap(); | 6373 | .unwrap(); |
| 6412 | assert_eq!( | 6374 | assert_eq!( |
| 6413 | - users.len(), | 6375 | + users, 1, |
| 6414 | - 1, | ||
| 6415 | "exactly one user row for the duplicated name" | 6376 | "exactly one user row for the duplicated name" |
| 6416 | ); | 6377 | ); |
| 6417 | 6378 | ||
| @@ -6561,7 +6522,6 @@ async fn session_cookie_secure_attribute_follows_config() { | |||
| 6561 | chatbot_limit: Default::default(), | 6522 | chatbot_limit: Default::default(), |
| 6562 | exam_presence: Default::default(), | 6523 | exam_presence: Default::default(), |
| 6563 | board_hub: Default::default(), | 6524 | board_hub: Default::default(), |
| 6564 | - db_up: Default::default(), | ||
| 6565 | ai: None, | 6525 | ai: None, |
| 6566 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 6526 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 6567 | }); | 6527 | }); |
| @@ -6576,40 +6536,38 @@ async fn session_cookie_secure_attribute_follows_config() { | |||
| 6576 | ); | 6536 | ); |
| 6577 | } | 6537 | } |
| 6578 | 6538 | ||
| 6579 | -/// A query issued while the database socket is down does not fail — the SDK | 6539 | +/// A request issued against a closed pool does not wait — the acquire fails at |
| 6580 | -/// parks it until the connection returns and *then* runs it, so a handler that | 6540 | +/// once and the error is classified as "nothing executed" (`PoolClosed` → |
| 6581 | -/// reaches the database mid-outage waits out the whole outage and any write it | 6541 | +/// `DbUnavailable`), so the 503 advertises a safe retry. A closed school pool |
| 6582 | -/// carries lands late. The guard layer refuses at the edge instead, before the | 6542 | +/// is the honest stand-in for an unreachable socket: no statement can even be |
| 6583 | -/// request can touch the database, which is what makes the 503 safe to retry. | 6543 | +/// sent, which is what makes "nothing was written" true by construction. |
| 6584 | #[tokio::test] | 6544 | #[tokio::test] |
| 6585 | async fn db_down_refuses_before_touching_the_database() { | 6545 | async fn db_down_refuses_before_touching_the_database() { |
| 6586 | - async fn count_rows(db: &hezarfen_backend::database::Database, table: &str) -> usize { | 6546 | + async fn count_rows(db: &hezarfen_backend::database::Database, table: &str) -> i64 { |
| 6587 | - let mut rows = db | 6547 | + sqlx::query_scalar::<sqlx::Postgres, i64>(sqlx::AssertSqlSafe(format!( |
| 6588 | - .query(format!("SELECT id FROM {table}")) | 6548 | + "SELECT count(*) FROM {table}" |
| 6589 | - .await | 6549 | + ))) |
| 6590 | - .expect("count query"); | 6550 | + .fetch_one(db) |
| 6591 | - let ids: Vec<surrealdb::types::RecordId> = rows.take(0).expect("ids"); | 6551 | + .await |
| 6592 | - ids.len() | 6552 | + .expect("count query") |
| 6593 | } | 6553 | } |
| 6594 | 6554 | ||
| 6595 | let (tenants, db) = common::mem_deployment().await; | 6555 | let (tenants, db) = common::mem_deployment().await; |
| 6596 | - let db_up = hezarfen_backend::state::DbHealth::default(); | ||
| 6597 | let app = build_router(AppState { | 6556 | let app = build_router(AppState { |
| 6598 | db: tenants.control().clone(), | 6557 | db: tenants.control().clone(), |
| 6599 | - tenants, | 6558 | + tenants: tenants.clone(), |
| 6600 | files_path: common::files_dir(), | 6559 | files_path: common::files_dir(), |
| 6601 | cookie_secure: false, | 6560 | cookie_secure: false, |
| 6602 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), | 6561 | rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), |
| 6603 | chatbot_limit: Default::default(), | 6562 | chatbot_limit: Default::default(), |
| 6604 | exam_presence: Default::default(), | 6563 | exam_presence: Default::default(), |
| 6605 | board_hub: Default::default(), | 6564 | board_hub: Default::default(), |
| 6606 | - db_up: db_up.clone(), | ||
| 6607 | ai: None, | 6565 | ai: None, |
| 6608 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 6566 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 6609 | }); | 6567 | }); |
| 6610 | 6568 | ||
| 6611 | // Healthy: a login against the seeded user reaches the handler as usual. | 6569 | // Healthy: a login against the seeded user reaches the handler as usual. |
| 6612 | - let before: usize = count_rows(&db, "user").await; | 6570 | + let before: i64 = count_rows(&db, "app_user").await; |
| 6613 | let ok = app | 6571 | let ok = app |
| 6614 | .clone() | 6572 | .clone() |
| 6615 | .oneshot( | 6573 | .oneshot( |
| @@ -6627,14 +6585,13 @@ async fn db_down_refuses_before_touching_the_database() { | |||
| 6627 | .unwrap(); | 6585 | .unwrap(); |
| 6628 | assert_eq!(ok.status(), StatusCode::CREATED); | 6586 | assert_eq!(ok.status(), StatusCode::CREATED); |
| 6629 | assert_eq!( | 6587 | assert_eq!( |
| 6630 | - count_rows(&db, "user").await, | 6588 | + count_rows(&db, "app_user").await, |
| 6631 | before + 1, | 6589 | before + 1, |
| 6632 | "the write landed" | 6590 | "the write landed" |
| 6633 | ); | 6591 | ); |
| 6634 | 6592 | ||
| 6635 | - // Socket reported down: refused with a retryable 503, and — the point of | 6593 | + // Pool closed: refused with a retryable 503. |
| 6636 | - // refusing at the edge rather than timing out — nothing was written. | 6594 | + db.close().await; |
| 6637 | - db_up.set(false); | ||
| 6638 | let refused = app | 6595 | let refused = app |
| 6639 | .clone() | 6596 | .clone() |
| 6640 | .oneshot( | 6597 | .oneshot( |
| @@ -6656,14 +6613,17 @@ async fn db_down_refuses_before_touching_the_database() { | |||
| 6656 | "1", | 6613 | "1", |
| 6657 | "a pre-execution refusal must advertise that retrying is safe" | 6614 | "a pre-execution refusal must advertise that retrying is safe" |
| 6658 | ); | 6615 | ); |
| 6616 | + | ||
| 6617 | + // Recovery is eviction: the dead pool leaves the cache, the next request | ||
| 6618 | + // dials fresh — and the refused write is still not in the database. | ||
| 6619 | + let slug = Slug::try_new("demo").expect("slug"); | ||
| 6620 | + tenants.evict(&slug).await; | ||
| 6621 | + let live = tenants.get(&slug).await.expect("redial after eviction"); | ||
| 6659 | assert_eq!( | 6622 | assert_eq!( |
| 6660 | - count_rows(&db, "user").await, | 6623 | + count_rows(&live, "app_user").await, |
| 6661 | before + 1, | 6624 | before + 1, |
| 6662 | "a refused request must not have reached the database" | 6625 | "a refused request must not have reached the database" |
| 6663 | ); | 6626 | ); |
| 6664 | - | ||
| 6665 | - // Recovery flips back without a restart. | ||
| 6666 | - db_up.set(true); | ||
| 6667 | let healed = app | 6627 | let healed = app |
| 6668 | .oneshot( | 6628 | .oneshot( |
| 6669 | Request::builder() | 6629 | Request::builder() |
| @@ -6679,7 +6639,7 @@ async fn db_down_refuses_before_touching_the_database() { | |||
| 6679 | .await | 6639 | .await |
| 6680 | .unwrap(); | 6640 | .unwrap(); |
| 6681 | assert_eq!(healed.status(), StatusCode::CREATED); | 6641 | assert_eq!(healed.status(), StatusCode::CREATED); |
| 6682 | - assert_eq!(count_rows(&db, "user").await, before + 2); | 6642 | + assert_eq!(count_rows(&live, "app_user").await, before + 2); |
| 6683 | } | 6643 | } |
| 6684 | 6644 | ||
| 6685 | /// Regression: PATCH could set an event's times but never clear them — a JSON | 6645 | /// Regression: PATCH could set an event's times but never clear them — a JSON |
| @@ -9711,11 +9671,10 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 9711 | matches!(exam_question::delete(&db, frozen).await, Err(err) if err.to_string().contains("after attempts")), | 9671 | matches!(exam_question::delete(&db, frozen).await, Err(err) if err.to_string().contains("after attempts")), |
| 9712 | "the gate must refuse a question delete while an attempt exists" | 9672 | "the gate must refuse a question delete while an attempt exists" |
| 9713 | ); | 9673 | ); |
| 9714 | - db.query("DELETE exam_attempt WHERE exam = $ex") | 9674 | + sqlx::query("DELETE FROM exam_attempt WHERE exam = $1") |
| 9715 | - .bind(("ex", exam_id.record())) | 9675 | + .bind(exam_id.uuid()) |
| 9676 | + .execute(&db) | ||
| 9716 | .await | 9677 | .await |
| 9717 | - .unwrap() | ||
| 9718 | - .check() | ||
| 9719 | .unwrap(); | 9678 | .unwrap(); |
| 9720 | let question = exam_question::list_for_exam(&db, &exam_id, None, 0) | 9679 | let question = exam_question::list_for_exam(&db, &exam_id, None, 0) |
| 9721 | .await | 9680 | .await |
| @@ -11299,7 +11258,7 @@ async fn search_rejects_a_blank_query() { | |||
| 11299 | } | 11258 | } |
| 11300 | 11259 | ||
| 11301 | /// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130) | 11260 | /// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130) |
| 11302 | -/// lowercases to `i` + U+0307 in both Rust and SurrealQL, which used to make | 11261 | +/// lowercases to `i` + U+0307 in both Rust and SQL, which used to make |
| 11303 | /// `ilker` and `İLKER` two disjoint searches — a teacher typing lowercase got | 11262 | /// `ilker` and `İLKER` two disjoint searches — a teacher typing lowercase got |
| 11304 | /// an empty picker. Same defect, same fix as the bank-question search. | 11263 | /// an empty picker. Same defect, same fix as the bank-question search. |
| 11305 | #[tokio::test] | 11264 | #[tokio::test] |
| @@ -12391,35 +12350,26 @@ async fn post_image( | |||
| 12391 | 12350 | ||
| 12392 | /// Every stored question-image blob name, straight from the table. | 12351 | /// Every stored question-image blob name, straight from the table. |
| 12393 | async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { | 12352 | async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 12394 | - let mut result = db | 12353 | + sqlx::query_scalar("SELECT file FROM question_image") |
| 12395 | - .query("SELECT VALUE file FROM question_image") | 12354 | + .fetch_all(db) |
| 12396 | .await | 12355 | .await |
| 12397 | .unwrap() | 12356 | .unwrap() |
| 12398 | - .check() | ||
| 12399 | - .unwrap(); | ||
| 12400 | - result.take::<Vec<String>>(0).unwrap() | ||
| 12401 | } | 12357 | } |
| 12402 | 12358 | ||
| 12403 | /// Every stored bank-question-image blob name, straight from the table. | 12359 | /// Every stored bank-question-image blob name, straight from the table. |
| 12404 | async fn bank_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { | 12360 | async fn bank_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 12405 | - let mut result = db | 12361 | + sqlx::query_scalar("SELECT file FROM bank_question_image") |
| 12406 | - .query("SELECT VALUE file FROM bank_question_image") | 12362 | + .fetch_all(db) |
| 12407 | .await | 12363 | .await |
| 12408 | .unwrap() | 12364 | .unwrap() |
| 12409 | - .check() | ||
| 12410 | - .unwrap(); | ||
| 12411 | - result.take::<Vec<String>>(0).unwrap() | ||
| 12412 | } | 12365 | } |
| 12413 | 12366 | ||
| 12414 | /// Every stored answer-image (student drawing) blob name, straight from the table. | 12367 | /// Every stored answer-image (student drawing) blob name, straight from the table. |
| 12415 | async fn answer_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { | 12368 | async fn answer_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 12416 | - let mut result = db | 12369 | + sqlx::query_scalar("SELECT file FROM answer_image") |
| 12417 | - .query("SELECT VALUE file FROM answer_image") | 12370 | + .fetch_all(db) |
| 12418 | .await | 12371 | .await |
| 12419 | .unwrap() | 12372 | .unwrap() |
| 12420 | - .check() | ||
| 12421 | - .unwrap(); | ||
| 12422 | - result.take::<Vec<String>>(0).unwrap() | ||
| 12423 | } | 12373 | } |
| 12424 | 12374 | ||
| 12425 | /// The full life of question images: teacher uploads (question + choice slots, | 12375 | /// The full life of question images: teacher uploads (question + choice slots, |
| @@ -13321,14 +13271,14 @@ async fn parent_links_are_admin_managed_and_role_checked() { | |||
| 13321 | "POST", | 13271 | "POST", |
| 13322 | &format!("/users/{parent_id}/students"), | 13272 | &format!("/users/{parent_id}/students"), |
| 13323 | Some(&admin), | 13273 | Some(&admin), |
| 13324 | - Some(json!({ "user_id": "01ZZZZZZZZZZZZZZZZZZZZZZZZ" })), | 13274 | + Some(json!({ "user_id": common::ABSENT_ID })), |
| 13325 | ) | 13275 | ) |
| 13326 | .await; | 13276 | .await; |
| 13327 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | 13277 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 13328 | let res = send( | 13278 | let res = send( |
| 13329 | &app, | 13279 | &app, |
| 13330 | "POST", | 13280 | "POST", |
| 13331 | - "/users/01ZZZZZZZZZZZZZZZZZZZZZZZZ/students", | 13281 | + &format!("/users/{}/students", common::ABSENT_ID), |
| 13332 | Some(&admin), | 13282 | Some(&admin), |
| 13333 | Some(json!({ "user_id": ali_id })), | 13283 | Some(json!({ "user_id": ali_id })), |
| 13334 | ) | 13284 | ) |
| @@ -13575,14 +13525,11 @@ async fn role_change_sweeps_parent_links() { | |||
| 13575 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 13525 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 13576 | 13526 | ||
| 13577 | // Really deleted, not merely hidden by the role checks. | 13527 | // Really deleted, not merely hidden by the role checks. |
| 13578 | - let mut result = db | 13528 | + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM parent_link") |
| 13579 | - .query("SELECT VALUE id FROM parent_link") | 13529 | + .fetch_one(&db) |
| 13580 | .await | 13530 | .await |
| 13581 | - .expect("count parent links") | 13531 | + .expect("count parent links"); |
| 13582 | - .check() | 13532 | + assert_eq!(rows, 0, "parent_link rows deleted from the DB"); |
| 13583 | - .expect("count parent links check"); | ||
| 13584 | - let rows: Vec<surrealdb::types::RecordId> = result.take(0).expect("parent link rows"); | ||
| 13585 | - assert!(rows.is_empty(), "parent_link rows deleted from the DB"); | ||
| 13586 | } | 13533 | } |
| 13587 | 13534 | ||
| 13588 | // --- messages ------------------------------------------------------------ | 13535 | // --- messages ------------------------------------------------------------ |
| @@ -13747,14 +13694,11 @@ async fn messages_flow_through_folders_per_side() { | |||
| 13747 | ) | 13694 | ) |
| 13748 | .await; | 13695 | .await; |
| 13749 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 13696 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13750 | - let mut result = db | 13697 | + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM message") |
| 13751 | - .query("SELECT VALUE id FROM message") | 13698 | + .fetch_one(&db) |
| 13752 | .await | 13699 | .await |
| 13753 | - .expect("count messages") | 13700 | + .expect("count messages"); |
| 13754 | - .check() | 13701 | + assert_eq!(rows, 0, "both-sides-deleted row is removed"); |
| 13755 | - .expect("count messages check"); | ||
| 13756 | - let rows: Vec<surrealdb::types::RecordId> = result.take(0).expect("message rows"); | ||
| 13757 | - assert!(rows.is_empty(), "both-sides-deleted row is removed"); | ||
| 13758 | } | 13702 | } |
| 13759 | 13703 | ||
| 13760 | /// A filed copy remembers the folder it left, so restoring lands where it | 13704 | /// A filed copy remembers the folder it left, so restoring lands where it |
| @@ -13833,13 +13777,11 @@ async fn messages_remember_the_folder_a_filed_copy_came_from() { | |||
| 13833 | ) | 13777 | ) |
| 13834 | .await; | 13778 | .await; |
| 13835 | assert_eq!(res.status, StatusCode::NO_CONTENT); | 13779 | assert_eq!(res.status, StatusCode::NO_CONTENT); |
| 13836 | - let mut result = db | 13780 | + let origins: Vec<Option<String>> = |
| 13837 | - .query("SELECT VALUE sender_origin FROM message") | 13781 | + sqlx::query_scalar("SELECT sender_origin FROM message") |
| 13838 | - .await | 13782 | + .fetch_all(&db) |
| 13839 | - .expect("read origins") | 13783 | + .await |
| 13840 | - .check() | 13784 | + .expect("read origins"); |
| 13841 | - .expect("read origins check"); | ||
| 13842 | - let origins: Vec<Option<String>> = result.take(0).expect("origin rows"); | ||
| 13843 | assert_eq!(origins, vec![None], "the deleted side keeps no origin"); | 13785 | assert_eq!(origins, vec![None], "the deleted side keeps no origin"); |
| 13844 | } | 13786 | } |
| 13845 | 13787 | ||
| @@ -13919,7 +13861,7 @@ async fn messages_guard_parties_recipients_and_folders() { | |||
| 13919 | "POST", | 13861 | "POST", |
| 13920 | "/messages", | 13862 | "/messages", |
| 13921 | Some(&ali), | 13863 | Some(&ali), |
| 13922 | - Some(json!({ "recipient_id": "01J8XZ0K3Q8G7X2M4N5P6R7S8T", "subject": "hi" })), | 13864 | + Some(json!({ "recipient_id": common::GHOST_ID, "subject": "hi" })), |
| 13923 | ) | 13865 | ) |
| 13924 | .await; | 13866 | .await; |
| 13925 | assert_eq!(res.status, StatusCode::NOT_FOUND); | 13867 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| @@ -15012,28 +14954,21 @@ async fn grade_hw( | |||
| 15012 | 14954 | ||
| 15013 | /// Every stored homework-file blob name, straight from the table. | 14955 | /// Every stored homework-file blob name, straight from the table. |
| 15014 | async fn homework_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { | 14956 | async fn homework_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 15015 | - let mut result = db | 14957 | + sqlx::query_scalar("SELECT file FROM homework_file") |
| 15016 | - .query("SELECT VALUE file FROM homework_file") | 14958 | + .fetch_all(db) |
| 15017 | .await | 14959 | .await |
| 15018 | .unwrap() | 14960 | .unwrap() |
| 15019 | - .check() | ||
| 15020 | - .unwrap(); | ||
| 15021 | - result.take::<Vec<String>>(0).unwrap() | ||
| 15022 | } | 14961 | } |
| 15023 | 14962 | ||
| 15024 | /// Row count of `table`, straight from the database — a cascade must really | 14963 | /// Row count of `table`, straight from the database — a cascade must really |
| 15025 | /// delete, not merely hide behind the role checks. | 14964 | /// delete, not merely hide behind the role checks. |
| 15026 | -async fn hw_row_count(db: &hezarfen_backend::database::Database, table: &str) -> usize { | 14965 | +async fn hw_row_count(db: &hezarfen_backend::database::Database, table: &str) -> i64 { |
| 15027 | - let mut result = db | 14966 | + sqlx::query_scalar::<sqlx::Postgres, i64>(sqlx::AssertSqlSafe(format!( |
| 15028 | - .query(format!("SELECT VALUE id FROM {table}")) | 14967 | + "SELECT count(*) FROM {table}" |
| 15029 | - .await | 14968 | + ))) |
| 15030 | - .unwrap() | 14969 | + .fetch_one(db) |
| 15031 | - .check() | 14970 | + .await |
| 15032 | - .unwrap(); | 14971 | + .unwrap() |
| 15033 | - result | ||
| 15034 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 15035 | - .unwrap() | ||
| 15036 | - .len() | ||
| 15037 | } | 14972 | } |
| 15038 | 14973 | ||
| 15039 | /// Creation validates the due date (60s grace), the subject's course, the | 14974 | /// Creation validates the due date (60s grace), the subject's course, the |
| @@ -15479,7 +15414,7 @@ async fn homework_grading_gates_and_bounds() { | |||
| 15479 | &app, | 15414 | &app, |
| 15480 | &w.teacher, | 15415 | &w.teacher, |
| 15481 | &hw, | 15416 | &hw, |
| 15482 | - "01ZZZZZZZZZZZZZZZZZZZZZZZZ", | 15417 | + common::ABSENT_ID, |
| 15483 | "done", | 15418 | "done", |
| 15484 | None, | 15419 | None, |
| 15485 | ) | 15420 | ) |
| @@ -16072,7 +16007,7 @@ async fn homework_report_serves_observers_only() { | |||
| 16072 | let res = send( | 16007 | let res = send( |
| 16073 | &app, | 16008 | &app, |
| 16074 | "GET", | 16009 | "GET", |
| 16075 | - "/homework/report/01ZZZZZZZZZZZZZZZZZZZZZZZZ", | 16010 | + &format!("/homework/report/{}", common::ABSENT_ID), |
| 16076 | Some(&admin), | 16011 | Some(&admin), |
| 16077 | None, | 16012 | None, |
| 16078 | ) | 16013 | ) |
| @@ -16586,7 +16521,6 @@ async fn chat_app_limited( | |||
| 16586 | chatbot_limit, | 16521 | chatbot_limit, |
| 16587 | exam_presence: Default::default(), | 16522 | exam_presence: Default::default(), |
| 16588 | board_hub: Default::default(), | 16523 | board_hub: Default::default(), |
| 16589 | - db_up: Default::default(), | ||
| 16590 | ai, | 16524 | ai, |
| 16591 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 16525 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 16592 | }); | 16526 | }); |
| @@ -16595,15 +16529,15 @@ async fn chat_app_limited( | |||
| 16595 | 16529 | ||
| 16596 | /// How many `thread` and `chatbot_message` rows exist, anywhere. | 16530 | /// How many `thread` and `chatbot_message` rows exist, anywhere. |
| 16597 | async fn chat_rows(db: &Database) -> (usize, usize) { | 16531 | async fn chat_rows(db: &Database) -> (usize, usize) { |
| 16598 | - let mut res = db | 16532 | + let threads: i64 = sqlx::query_scalar("SELECT count(*) FROM chatbot_thread") |
| 16599 | - .query("SELECT VALUE id FROM chatbot_thread; SELECT VALUE id FROM chatbot_message;") | 16533 | + .fetch_one(db) |
| 16534 | + .await | ||
| 16535 | + .expect("count query"); | ||
| 16536 | + let messages: i64 = sqlx::query_scalar("SELECT count(*) FROM chatbot_message") | ||
| 16537 | + .fetch_one(db) | ||
| 16600 | .await | 16538 | .await |
| 16601 | - .expect("count query") | ||
| 16602 | - .check() | ||
| 16603 | .expect("count check"); | 16539 | .expect("count check"); |
| 16604 | - let threads: Vec<surrealdb::types::RecordId> = res.take(0).expect("thread ids"); | 16540 | + (threads as usize, messages as usize) |
| 16605 | - let messages: Vec<surrealdb::types::RecordId> = res.take(1).expect("chatbot_message ids"); | ||
| 16606 | - (threads.len(), messages.len()) | ||
| 16607 | } | 16541 | } |
| 16608 | 16542 | ||
| 16609 | /// Open a thread (asserts 201) and return its id. | 16543 | /// Open a thread (asserts 201) and return its id. |
| @@ -19304,7 +19238,7 @@ async fn bank_question_list_filters_by_visibility() { | |||
| 19304 | } | 19238 | } |
| 19305 | 19239 | ||
| 19306 | /// The app is EN/TR, so `?q=` must fold Turkish casing: `İ` lowercases to | 19240 | /// The app is EN/TR, so `?q=` must fold Turkish casing: `İ` lowercases to |
| 19307 | -/// `i` + U+0307 in both Rust and SurrealQL, which used to make `istanbul` and | 19241 | +/// `i` + U+0307 in both Rust and SQL, which used to make `istanbul` and |
| 19308 | /// `İSTANBUL` two disjoint searches — a teacher typing lowercase got an empty | 19242 | /// `İSTANBUL` two disjoint searches — a teacher typing lowercase got an empty |
| 19309 | /// bank. | 19243 | /// bank. |
| 19310 | #[tokio::test] | 19244 | #[tokio::test] |
| @@ -22112,8 +22046,8 @@ async fn meal_booking_capacity_caps_and_a_cancel_frees_a_seat() { | |||
| 22112 | assert_eq!(book(students[0].clone()).await.status, StatusCode::CONFLICT); | 22046 | assert_eq!(book(students[0].clone()).await.status, StatusCode::CONFLICT); |
| 22113 | } | 22047 | } |
| 22114 | 22048 | ||
| 22115 | -/// The cap is a count-then-write pair, which SurrealDB does not serialize: | 22049 | +/// The cap is a conditional claim the store enforces: under a stampede it |
| 22116 | -/// under a stampede it must still admit exactly `capacity` seats, and the | 22050 | +/// must still admit exactly `capacity` seats, and the |
| 22117 | /// losers must get a 409 rather than a 500. Mirrors | 22051 | /// losers must get a 409 rather than a 500. Mirrors |
| 22118 | /// `concurrent_duplicate_registrations_conflict_not_500`. | 22052 | /// `concurrent_duplicate_registrations_conflict_not_500`. |
| 22119 | #[tokio::test] | 22053 | #[tokio::test] |
| @@ -22176,16 +22110,13 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() { | |||
| 22176 | // The rows are downstream of the counter, so assert the counter itself: | 22110 | // The rows are downstream of the counter, so assert the counter itself: |
| 22177 | // it is what every booking's `WHERE` compares, and a drift here would open | 22111 | // it is what every booking's `WHERE` compares, and a drift here would open |
| 22178 | // the cap on the next booking however tidy the listing looks. | 22112 | // the cap on the next booking however tidy the listing looks. |
| 22179 | - let mut counted = db | 22113 | + let counted: i64 = sqlx::query_scalar("SELECT seats_booked FROM menu WHERE id = $1") |
| 22180 | - .query("SELECT VALUE seats_booked FROM type::record('menu', $m)") | 22114 | + .bind(&menu) |
| 22181 | - .bind(("m", menu.clone())) | 22115 | + .fetch_one(&db) |
| 22182 | .await | 22116 | .await |
| 22183 | - .expect("counter read") | ||
| 22184 | - .check() | ||
| 22185 | .expect("counter read"); | 22117 | .expect("counter read"); |
| 22186 | assert_eq!( | 22118 | assert_eq!( |
| 22187 | - counted.take::<Vec<i64>>(0).expect("counter column"), | 22119 | + counted, 3, |
| 22188 | - vec![3], | ||
| 22189 | "the stored seat counter must agree with the seats handed out" | 22120 | "the stored seat counter must agree with the seats handed out" |
| 22190 | ); | 22121 | ); |
| 22191 | } | 22122 | } |
| @@ -23639,16 +23570,13 @@ async fn concurrent_bookings_of_one_seat_never_refuse_their_own_winner() { | |||
| 23639 | 23570 | ||
| 23640 | let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; | 23571 | let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; |
| 23641 | assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body); | 23572 | assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body); |
| 23642 | - let mut counted = db | 23573 | + let counted: i64 = sqlx::query_scalar("SELECT seats_booked FROM menu WHERE id = $1") |
| 23643 | - .query("SELECT VALUE seats_booked FROM type::record('menu', $m)") | 23574 | + .bind(&menu) |
| 23644 | - .bind(("m", menu.clone())) | 23575 | + .fetch_one(&db) |
| 23645 | .await | 23576 | .await |
| 23646 | - .expect("counter read") | ||
| 23647 | - .check() | ||
| 23648 | .expect("counter read"); | 23577 | .expect("counter read"); |
| 23649 | assert_eq!( | 23578 | assert_eq!( |
| 23650 | - counted.take::<Vec<i64>>(0).expect("counter column"), | 23579 | + counted, 1, |
| 23651 | - vec![1], | ||
| 23652 | "and the seat it cost is the one seat the menu has" | 23580 | "and the seat it cost is the one seat the menu has" |
| 23653 | ); | 23581 | ); |
| 23654 | } | 23582 | } |
| @@ -23986,8 +23914,8 @@ async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() { | |||
| 23986 | /// This deliberately does **not** race the two requests. It used to (40 rounds, | 23914 | /// This deliberately does **not** race the two requests. It used to (40 rounds, |
| 23987 | /// two spawned tasks), and that assertion could not be honest here: the | 23915 | /// two spawned tasks), and that assertion could not be honest here: the |
| 23988 | /// production guard is a store-detected conflict — both transactions write | 23916 | /// production guard is a store-detected conflict — both transactions write |
| 23989 | -/// `menu:<id>`'s revision, so one is refused — and the embedded engine behind | 23917 | +/// `menu:<id>`'s revision, so one is refused — and the old embedded engine |
| 23990 | -/// `init_mem` does not conflict-check concurrent writes to one record at all. | 23918 | +/// did not conflict-check concurrent writes to one record at all. |
| 23991 | /// It committed **both** and answered `Ok` to each, orphaning 4 of 3600 and 13 | 23919 | /// It committed **both** and answered `Ok` to each, orphaning 4 of 3600 and 13 |
| 23992 | /// of 6000 rounds, which surfaced as a whole-suite failure a few percent of | 23920 | /// of 6000 rounds, which surfaced as a whole-suite failure a few percent of |
| 23993 | /// runs. The same code orphaned 0 of 9600 rounds against a real server. So the | 23921 | /// runs. The same code orphaned 0 of 9600 rounds against a real server. So the |
| @@ -23999,13 +23927,12 @@ async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() { | |||
| 23999 | async fn a_dish_never_lands_on_a_deleted_menu() { | 23927 | async fn a_dish_never_lands_on_a_deleted_menu() { |
| 24000 | let (app, db) = app_and_db().await; | 23928 | let (app, db) = app_and_db().await; |
| 24001 | let mgr = login_as(&app, &db, "orphan_mgr", "manager").await; | 23929 | let mgr = login_as(&app, &db, "orphan_mgr", "manager").await; |
| 24002 | - let dishes_on = async |menu: &str| -> Vec<surrealdb::types::RecordId> { | 23930 | + let dishes_on = async |menu: &str| -> i64 { |
| 24003 | - let mut res = db | 23931 | + sqlx::query_scalar("SELECT count(*) FROM menu_dish WHERE menu = $1") |
| 24004 | - .query("SELECT VALUE id FROM menu_dish WHERE menu = $menu") | 23932 | + .bind(menu) |
| 24005 | - .bind(("menu", surrealdb::types::RecordId::new("menu", menu))) | 23933 | + .fetch_one(&db) |
| 24006 | .await | 23934 | .await |
| 24007 | - .unwrap(); | 23935 | + .unwrap() |
| 24008 | - res.take(0).unwrap() | ||
| 24009 | }; | 23936 | }; |
| 24010 | let publish = async |date: &str| -> String { | 23937 | let publish = async |date: &str| -> String { |
| 24011 | let res = send( | 23938 | let res = send( |
| @@ -24043,8 +23970,9 @@ async fn a_dish_never_lands_on_a_deleted_menu() { | |||
| 24043 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | 23970 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 24044 | let res = add_dish(&menu).await; | 23971 | let res = add_dish(&menu).await; |
| 24045 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); | 23972 | assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); |
| 24046 | - assert!( | 23973 | + assert_eq!( |
| 24047 | - dishes_on(&menu).await.is_empty(), | 23974 | + dishes_on(&menu).await, |
| 23975 | + 0, | ||
| 24048 | "a refused add left a dish behind" | 23976 | "a refused add left a dish behind" |
| 24049 | ); | 23977 | ); |
| 24050 | 23978 | ||
| @@ -24054,7 +23982,7 @@ async fn a_dish_never_lands_on_a_deleted_menu() { | |||
| 24054 | let menu = publish("2027-10-01").await; | 23982 | let menu = publish("2027-10-01").await; |
| 24055 | let res = add_dish(&menu).await; | 23983 | let res = add_dish(&menu).await; |
| 24056 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 23984 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 24057 | - assert_eq!(dishes_on(&menu).await.len(), 1); | 23985 | + assert_eq!(dishes_on(&menu).await, 1); |
| 24058 | let res = send( | 23986 | let res = send( |
| 24059 | &app, | 23987 | &app, |
| 24060 | "DELETE", | 23988 | "DELETE", |
| @@ -24064,8 +23992,9 @@ async fn a_dish_never_lands_on_a_deleted_menu() { | |||
| 24064 | ) | 23992 | ) |
| 24065 | .await; | 23993 | .await; |
| 24066 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | 23994 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 24067 | - assert!( | 23995 | + assert_eq!( |
| 24068 | - dishes_on(&menu).await.is_empty(), | 23996 | + dishes_on(&menu).await, |
| 23997 | + 0, | ||
| 24069 | "the delete's cascade left a dish on a menu that is gone" | 23998 | "the delete's cascade left a dish on a menu that is gone" |
| 24070 | ); | 23999 | ); |
| 24071 | } | 24000 | } |
| @@ -24216,20 +24145,15 @@ async fn reverse(app: &axum::Router, cookie: &str, line: &str) -> common::Res { | |||
| 24216 | .await | 24145 | .await |
| 24217 | } | 24146 | } |
| 24218 | 24147 | ||
| 24219 | -/// Row count of `table`, straight from the database. The in-memory engine | 24148 | +/// Row count of `table`, straight from the database — a response is never |
| 24220 | -/// drops writes under concurrency and still answers `201`, so a response is | 24149 | +/// proof that a line landed; stored state is. |
| 24221 | -/// never proof that a line landed — stored state is. | 24150 | +async fn pay_row_count(db: &hezarfen_backend::database::Database, table: &str) -> i64 { |
| 24222 | -async fn pay_row_count(db: &hezarfen_backend::database::Database, table: &str) -> usize { | 24151 | + sqlx::query_scalar::<sqlx::Postgres, i64>(sqlx::AssertSqlSafe(format!( |
| 24223 | - let mut result = db | 24152 | + "SELECT count(*) FROM {table}" |
| 24224 | - .query(format!("SELECT VALUE id FROM {table}")) | 24153 | + ))) |
| 24225 | - .await | 24154 | + .fetch_one(db) |
| 24226 | - .unwrap() | 24155 | + .await |
| 24227 | - .check() | 24156 | + .unwrap() |
| 24228 | - .unwrap(); | ||
| 24229 | - result | ||
| 24230 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 24231 | - .unwrap() | ||
| 24232 | - .len() | ||
| 24233 | } | 24157 | } |
| 24234 | 24158 | ||
| 24235 | /// A manager, a student, and a plan the student is on — the starting point of | 24159 | /// A manager, a student, and a plan the student is on — the starting point of |
| @@ -25042,56 +24966,43 @@ async fn stored_board(db: &Database, board: &str) -> Option<Board> { | |||
| 25042 | } | 24966 | } |
| 25043 | 24967 | ||
| 25044 | /// Every stroke row of a board, oldest first, straight out of the table. | 24968 | /// Every stroke row of a board, oldest first, straight out of the table. |
| 25045 | -/// `SELECT *`, because SurrealDB 3 refuses `ORDER BY id` on a projection that | ||
| 25046 | -/// omits `id`. | ||
| 25047 | async fn stroke_rows(db: &Database, board: &str) -> Vec<BoardStroke> { | 24969 | async fn stroke_rows(db: &Database, board: &str) -> Vec<BoardStroke> { |
| 25048 | - let mut result = db | 24970 | + sqlx::query_as::<_, BoardStroke>("SELECT * FROM board_stroke WHERE board = $1 ORDER BY id") |
| 25049 | - .query("SELECT * FROM board_stroke WHERE board = $b ORDER BY id") | 24971 | + .bind(Uuid::parse_str(board).expect("board id")) |
| 25050 | - .bind(("b", BoardId::from_key(board).record())) | 24972 | + .fetch_all(db) |
| 25051 | .await | 24973 | .await |
| 25052 | .unwrap() | 24974 | .unwrap() |
| 25053 | - .check() | ||
| 25054 | - .unwrap(); | ||
| 25055 | - result.take(0).unwrap() | ||
| 25056 | } | 24975 | } |
| 25057 | 24976 | ||
| 25058 | /// The stored `[epoch_stroke_count, total_stroke_count]` pair. | 24977 | /// The stored `[epoch_stroke_count, total_stroke_count]` pair. |
| 25059 | async fn stored_counters(db: &Database, board: &str) -> Vec<i64> { | 24978 | async fn stored_counters(db: &Database, board: &str) -> Vec<i64> { |
| 25060 | - let mut result = db | 24979 | + let (epoch_stroke_count, total_stroke_count) = |
| 25061 | - .query( | 24980 | + sqlx::query_as("SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1") |
| 25062 | - "SELECT VALUE [epoch_stroke_count ?? 0, total_stroke_count ?? 0] \ | 24981 | + .bind(Uuid::parse_str(board).expect("board id")) |
| 25063 | - FROM $id", | 24982 | + .fetch_one(db) |
| 25064 | - ) | 24983 | + .await |
| 25065 | - .bind(("id", BoardId::from_key(board).record())) | 24984 | + .unwrap(); |
| 25066 | - .await | 24985 | + vec![epoch_stroke_count, total_stroke_count] |
| 25067 | - .unwrap() | ||
| 25068 | - .check() | ||
| 25069 | - .unwrap(); | ||
| 25070 | - result.take::<Vec<Vec<i64>>>(0).unwrap().remove(0) | ||
| 25071 | } | 24986 | } |
| 25072 | 24987 | ||
| 25073 | async fn set_counters(db: &Database, board: &str, epoch: i64, total: i64) { | 24988 | async fn set_counters(db: &Database, board: &str, epoch: i64, total: i64) { |
| 25074 | - db.query("UPDATE $id SET epoch_stroke_count = $e, total_stroke_count = $t") | 24989 | + sqlx::query("UPDATE board SET epoch_stroke_count = $2, total_stroke_count = $3 WHERE id = $1") |
| 25075 | - .bind(("id", BoardId::from_key(board).record())) | 24990 | + .bind(Uuid::parse_str(board).expect("board id")) |
| 25076 | - .bind(("e", epoch)) | 24991 | + .bind(epoch) |
| 25077 | - .bind(("t", total)) | 24992 | + .bind(total) |
| 24993 | + .execute(db) | ||
| 25078 | .await | 24994 | .await |
| 25079 | - .unwrap() | ||
| 25080 | - .check() | ||
| 25081 | .unwrap(); | 24995 | .unwrap(); |
| 25082 | } | 24996 | } |
| 25083 | 24997 | ||
| 25084 | /// The creator's stored `board_count` — the authority on how many boards they | 24998 | /// The creator's stored `board_count` — the authority on how many boards they |
| 25085 | /// hold, so the per-creator cap is asserted here and not off a 409. | 24999 | /// hold, so the per-creator cap is asserted here and not off a 409. |
| 25086 | async fn stored_board_count(db: &Database, user: &str) -> i64 { | 25000 | async fn stored_board_count(db: &Database, user: &str) -> i64 { |
| 25087 | - let mut result = db | 25001 | + sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1") |
| 25088 | - .query("SELECT VALUE board_count ?? 0 FROM $id") | 25002 | + .bind(Uuid::parse_str(user).expect("user id")) |
| 25089 | - .bind(("id", UserId::from_key(user).record())) | 25003 | + .fetch_one(db) |
| 25090 | .await | 25004 | .await |
| 25091 | .unwrap() | 25005 | .unwrap() |
| 25092 | - .check() | ||
| 25093 | - .unwrap(); | ||
| 25094 | - result.take::<Vec<i64>>(0).unwrap()[0] | ||
| 25095 | } | 25006 | } |
| 25096 | 25007 | ||
| 25097 | /// Every id-scoped board route, with a body where the route needs one. The | 25008 | /// Every id-scoped board route, with a body where the route needs one. The |
| @@ -25237,12 +25148,11 @@ async fn a_parent_gets_no_whiteboard_at_all() { | |||
| 25237 | // 3. The stale row: a parent already on a roster, written before this rule. | 25148 | // 3. The stale row: a parent already on a roster, written before this rule. |
| 25238 | // Every id-scoped route must still answer exactly like a board that was | 25149 | // Every id-scoped route must still answer exactly like a board that was |
| 25239 | // never minted — a 403 anywhere here leaks the board's existence. | 25150 | // never minted — a 403 anywhere here leaks the board's existence. |
| 25240 | - db.query("UPDATE $b SET participants = [$u]") | 25151 | + sqlx::query("UPDATE board SET participants = $2 WHERE id = $1") |
| 25241 | - .bind(("b", BoardId::from_key(&board).record())) | 25152 | + .bind(Uuid::parse_str(&board).expect("board id")) |
| 25242 | - .bind(("u", UserId::from_key(&anne_id).record())) | 25153 | + .bind(vec![Uuid::parse_str(&anne_id).expect("user id")]) |
| 25154 | + .execute(&db) | ||
| 25243 | .await | 25155 | .await |
| 25244 | - .unwrap() | ||
| 25245 | - .check() | ||
| 25246 | .unwrap(); | 25156 | .unwrap(); |
| 25247 | let ghost = board_routes("nosuchboard"); | 25157 | let ghost = board_routes("nosuchboard"); |
| 25248 | for (n, (method, uri, body)) in board_routes(&board).into_iter().enumerate() { | 25158 | for (n, (method, uri, body)) in board_routes(&board).into_iter().enumerate() { |
| @@ -25283,13 +25193,7 @@ async fn a_creator_can_patch_back_a_roster_holding_a_participant_who_no_longer_q | |||
| 25283 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; | 25193 | let board = create_board(&app, &ali, "Geometri", &[&veli_id]).await; |
| 25284 | // Demoted straight in the store: `set_role` would sweep the roster, and the | 25194 | // Demoted straight in the store: `set_role` would sweep the roster, and the |
| 25285 | // stale row is exactly the shape a volume written before that sweep holds. | 25195 | // stale row is exactly the shape a volume written before that sweep holds. |
| 25286 | - db.query("UPDATE $u SET role = 'parent'") | 25196 | + common::set_role(&db, "veli", "parent").await; |
| 25287 | - .bind(("u", UserId::from_key(&veli_id).record())) | ||
| 25288 | - .await | ||
| 25289 | - .unwrap() | ||
| 25290 | - .check() | ||
| 25291 | - .unwrap(); | ||
| 25292 | - | ||
| 25293 | // What the client sees, and sends straight back. | 25197 | // What the client sees, and sends straight back. |
| 25294 | let read = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; | 25198 | let read = send(&app, "GET", &format!("/boards/{board}"), Some(&ali), None).await; |
| 25295 | assert_eq!(read.status, StatusCode::OK, "{}", read.body); | 25199 | assert_eq!(read.status, StatusCode::OK, "{}", read.body); |
| @@ -25897,12 +25801,11 @@ async fn the_per_creator_cap_refuses_and_a_delete_frees_a_seat() { | |||
| 25897 | assert_eq!(stored_board_count(&db, &ali_id).await, 1); | 25801 | assert_eq!(stored_board_count(&db, &ali_id).await, 1); |
| 25898 | 25802 | ||
| 25899 | // Age the counter to full rather than open 200 boards. | 25803 | // Age the counter to full rather than open 200 boards. |
| 25900 | - db.query("UPDATE $id SET board_count = $full") | 25804 | + sqlx::query("UPDATE app_user SET board_count = $1 WHERE id = $2") |
| 25901 | - .bind(("id", UserId::from_key(&ali_id).record())) | 25805 | + .bind(MAX_BOARDS_PER_CREATOR) |
| 25902 | - .bind(("full", MAX_BOARDS_PER_CREATOR)) | 25806 | + .bind(Uuid::parse_str(&ali_id).expect("user id")) |
| 25807 | + .execute(&db) | ||
| 25903 | .await | 25808 | .await |
| 25904 | - .unwrap() | ||
| 25905 | - .check() | ||
| 25906 | .unwrap(); | 25809 | .unwrap(); |
| 25907 | 25810 | ||
| 25908 | let res = send( | 25811 | let res = send( |
| @@ -25919,20 +25822,11 @@ async fn the_per_creator_cap_refuses_and_a_delete_frees_a_seat() { | |||
| 25919 | MAX_BOARDS_PER_CREATOR, | 25822 | MAX_BOARDS_PER_CREATOR, |
| 25920 | "the refusal must not have claimed a seat" | 25823 | "the refusal must not have claimed a seat" |
| 25921 | ); | 25824 | ); |
| 25922 | - let mut result = db | 25825 | + let boards: i64 = sqlx::query_scalar("SELECT count(*) FROM board") |
| 25923 | - .query("SELECT VALUE id FROM board") | 25826 | + .fetch_one(&db) |
| 25924 | .await | 25827 | .await |
| 25925 | - .unwrap() | ||
| 25926 | - .check() | ||
| 25927 | .unwrap(); | 25828 | .unwrap(); |
| 25928 | - assert_eq!( | 25829 | + assert_eq!(boards, 1, "no row was written by the refused create"); |
| 25929 | - result | ||
| 25930 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 25931 | - .unwrap() | ||
| 25932 | - .len(), | ||
| 25933 | - 1, | ||
| 25934 | - "no row was written by the refused create" | ||
| 25935 | - ); | ||
| 25936 | 25830 | ||
| 25937 | // Deleting frees exactly one seat, and the next create takes it. | 25831 | // Deleting frees exactly one seat, and the next create takes it. |
| 25938 | let res = send( | 25832 | let res = send( |
| @@ -25960,10 +25854,10 @@ async fn the_per_creator_cap_refuses_and_a_delete_frees_a_seat() { | |||
| 25960 | assert_eq!(res.status, StatusCode::NOT_FOUND); | 25854 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 25961 | } | 25855 | } |
| 25962 | 25856 | ||
| 25963 | -/// The `next_ulid` hazard, over HTTP: a burst of marks all lands inside one or | 25857 | +/// The id-ordering hazard, over HTTP: a burst of marks all lands inside one |
| 25964 | -/// two milliseconds, and `Ulid::new()` would sort those rows at random | 25858 | +/// or two milliseconds, and an id scheme without within-millisecond |
| 25965 | -/// (src/domain/monotonic_id.rs:41-46). The canvas is a drawing, so an order | 25859 | +/// monotonicity would sort those rows at random. The canvas is a drawing, so |
| 25966 | -/// that shuffles is a drawing that redraws wrong. | 25860 | +/// an order that shuffles is a drawing that redraws wrong. |
| 25967 | #[tokio::test] | 25861 | #[tokio::test] |
| 25968 | async fn a_burst_of_strokes_comes_back_in_mint_order() { | 25862 | async fn a_burst_of_strokes_comes_back_in_mint_order() { |
| 25969 | let (app, db) = app_and_db().await; | 25863 | let (app, db) = app_and_db().await; |
| @@ -26418,41 +26312,35 @@ async fn a_demotion_sweeps_the_class_membership_and_what_it_pumped() { | |||
| 26418 | assert_eq!(common::total(&res.body), 0, "and so did the course"); | 26312 | assert_eq!(common::total(&res.body), 0, "and so did the course"); |
| 26419 | 26313 | ||
| 26420 | // Both tables and both counters, read off the store itself. | 26314 | // Both tables and both counters, read off the store itself. |
| 26421 | - let mut result = db | 26315 | + let count = |sql: &'static str| { |
| 26422 | - .query( | 26316 | + let db = &db; |
| 26423 | - "SELECT VALUE id FROM class_member; \ | 26317 | + async move { |
| 26424 | - SELECT VALUE id FROM enrollment; \ | 26318 | + sqlx::query_scalar::<_, i64>(sql) |
| 26425 | - SELECT VALUE class_member_count FROM class_group; \ | 26319 | + .fetch_one(db) |
| 26426 | - SELECT VALUE enrollment_count FROM course;", | 26320 | + .await |
| 26427 | - ) | 26321 | + .expect("read the swept state") |
| 26428 | - .await | 26322 | + } |
| 26429 | - .expect("read the swept state") | 26323 | + }; |
| 26430 | - .check() | ||
| 26431 | - .expect("read the swept state"); | ||
| 26432 | - assert!( | ||
| 26433 | - result | ||
| 26434 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 26435 | - .expect("class_member rows") | ||
| 26436 | - .is_empty(), | ||
| 26437 | - "the membership row is deleted, not merely filtered out" | ||
| 26438 | - ); | ||
| 26439 | - assert!( | ||
| 26440 | - result | ||
| 26441 | - .take::<Vec<surrealdb::types::RecordId>>(1) | ||
| 26442 | - .expect("enrollment rows") | ||
| 26443 | - .is_empty(), | ||
| 26444 | - "the pumped enrollment is deleted too" | ||
| 26445 | - ); | ||
| 26446 | assert_eq!( | 26324 | assert_eq!( |
| 26447 | - result.take::<Vec<i64>>(2).expect("class_member_count"), | 26325 | + count("SELECT count(*) FROM class_member").await, |
| 26448 | - vec![0], | 26326 | + 0, |
| 26449 | - "the class counter came back" | 26327 | + "the membership row is deleted, not merely filtered out" |
| 26450 | ); | 26328 | ); |
| 26451 | assert_eq!( | 26329 | assert_eq!( |
| 26452 | - result.take::<Vec<i64>>(3).expect("enrollment_count"), | 26330 | + count("SELECT count(*) FROM enrollment").await, |
| 26453 | - vec![0], | 26331 | + 0, |
| 26454 | - "the course counter came back" | 26332 | + "the pumped enrollment is deleted too" |
| 26455 | ); | 26333 | ); |
| 26334 | + let class_members: i64 = sqlx::query_scalar("SELECT class_member_count FROM class_group") | ||
| 26335 | + .fetch_one(&db) | ||
| 26336 | + .await | ||
| 26337 | + .expect("read the swept state"); | ||
| 26338 | + assert_eq!(class_members, 0, "the class counter came back"); | ||
| 26339 | + let enrolled: i64 = sqlx::query_scalar("SELECT enrollment_count FROM course") | ||
| 26340 | + .fetch_one(&db) | ||
| 26341 | + .await | ||
| 26342 | + .expect("read the swept state"); | ||
| 26343 | + assert_eq!(enrolled, 0, "the course counter came back"); | ||
| 26456 | 26344 | ||
| 26457 | // The bite: a membership left behind (or a counter never released) makes | 26345 | // The bite: a membership left behind (or a counter never released) makes |
| 26458 | // the class undeletable forever. | 26346 | // the class undeletable forever. |
| @@ -26626,7 +26514,7 @@ async fn a_course_that_cannot_seat_the_whole_class_seats_none_of_it() { | |||
| 26626 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | 26514 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 26627 | let message = res.body["error"].as_str().unwrap_or_default(); | 26515 | let message = res.body["error"].as_str().unwrap_or_default(); |
| 26628 | assert!( | 26516 | assert!( |
| 26629 | - message.contains(&format!("course:{course}")), | 26517 | + message.contains(&course), |
| 26630 | "the refusal must name the full course: {message}" | 26518 | "the refusal must name the full course: {message}" |
| 26631 | ); | 26519 | ); |
| 26632 | 26520 | ||
| @@ -26655,23 +26543,16 @@ async fn a_course_that_cannot_seat_the_whole_class_seats_none_of_it() { | |||
| 26655 | .await; | 26543 | .await; |
| 26656 | assert_eq!(common::total(&res.body), 0); | 26544 | assert_eq!(common::total(&res.body), 0); |
| 26657 | assert!(common::items(&res.body).is_empty(), "no link row"); | 26545 | assert!(common::items(&res.body).is_empty(), "no link row"); |
| 26658 | - let mut result = db | 26546 | + let enrolled: i64 = sqlx::query_scalar("SELECT enrollment_count FROM course") |
| 26659 | - .query("SELECT VALUE enrollment_count FROM course; SELECT VALUE id FROM class_course;") | 26547 | + .fetch_one(&db) |
| 26660 | .await | 26548 | .await |
| 26661 | - .expect("read the refused state") | ||
| 26662 | - .check() | ||
| 26663 | .expect("read the refused state"); | 26549 | .expect("read the refused state"); |
| 26664 | - assert_eq!( | 26550 | + assert_eq!(enrolled, 1, "the counter must not have moved"); |
| 26665 | - result.take::<Vec<i64>>(0).expect("enrollment_count"), | 26551 | + let links: i64 = sqlx::query_scalar("SELECT count(*) FROM class_course") |
| 26666 | - vec![1], | 26552 | + .fetch_one(&db) |
| 26667 | - "the counter must not have moved" | 26553 | + .await |
| 26668 | - ); | 26554 | + .expect("read the refused state"); |
| 26669 | - assert!( | 26555 | + assert_eq!(links, 0, "no class_course row was written"); |
| 26670 | - result | ||
| 26671 | - .take::<Vec<surrealdb::types::RecordId>>(1) | ||
| 26672 | - .expect("class_course rows") | ||
| 26673 | - .is_empty(), | ||
| 26674 | - ); | ||
| 26675 | 26556 | ||
| 26676 | // It really was a seat shortfall: a class of one fits, and lands. | 26557 | // It really was a seat shortfall: a class of one fits, and lands. |
| 26677 | assert_eq!( | 26558 | assert_eq!( |
| @@ -27465,12 +27346,12 @@ async fn two_schools() -> ( | |||
| 27465 | (app, db_a, db_b, tenants) | 27346 | (app, db_a, db_b, tenants) |
| 27466 | } | 27347 | } |
| 27467 | 27348 | ||
| 27468 | -/// The same two schools for a remote deployment: [`common::remote_deployment`] | 27349 | +/// The second school for [`common::deployment_with`], which creates the named |
| 27469 | -/// creates them itself, since there is no `init_mem_tenants` to seed a demo. | 27350 | +/// schools itself — the demo school comes with the deployment it boots, so |
| 27470 | -const TWO_SCHOOLS: &[(&str, &str)] = &[(DEMO_SLUG, "Demo School"), ("beta", "Beta Koleji")]; | 27351 | +/// only `beta` is named here. |
| 27352 | +const TWO_SCHOOLS: &[(&str, &str)] = &[("beta", "Beta Koleji")]; | ||
| 27471 | 27353 | ||
| 27472 | -/// One school's handle out of the registry — the one lookup that works in both | 27354 | +/// One school's handle out of the registry. |
| 27473 | -/// modes, where `two_schools()`'s return values are memory-mode only. | ||
| 27474 | async fn school_db(tenants: &Tenants, slug: &str) -> hezarfen_backend::database::Database { | 27355 | async fn school_db(tenants: &Tenants, slug: &str) -> hezarfen_backend::database::Database { |
| 27475 | tenants | 27356 | tenants |
| 27476 | .get(&Slug::try_new(slug).expect("a school slug")) | 27357 | .get(&Slug::try_new(slug).expect("a school slug")) |
| @@ -27607,13 +27488,11 @@ async fn probe_cross_school_lists_show_only_own_rows() { | |||
| 27607 | probe_cross_school_lists_show_only_own_rows_on(&app, &tenants).await; | 27488 | probe_cross_school_lists_show_only_own_rows_on(&app, &tenants).await; |
| 27608 | } | 27489 | } |
| 27609 | 27490 | ||
| 27610 | -/// [`probe_cross_school_lists_show_only_own_rows`] on a **real remote deployment** — production's `Mode::Remote`, | 27491 | +/// [`probe_cross_school_lists_show_only_own_rows`] against a second, |
| 27611 | -/// where isolation rests on each connection's `use_db` pin. | 27492 | +/// independent deployment — the probe body is shared, the deployment is not. |
| 27612 | #[tokio::test] | 27493 | #[tokio::test] |
| 27613 | async fn remote_probe_cross_school_lists_show_only_own_rows() { | 27494 | async fn remote_probe_cross_school_lists_show_only_own_rows() { |
| 27614 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 27495 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 27615 | - return; | ||
| 27616 | - }; | ||
| 27617 | probe_cross_school_lists_show_only_own_rows_on(&d.app, &d.tenants).await; | 27496 | probe_cross_school_lists_show_only_own_rows_on(&d.app, &d.tenants).await; |
| 27618 | } | 27497 | } |
| 27619 | 27498 | ||
| @@ -27667,13 +27546,11 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie() { | |||
| 27667 | probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&app, &tenants).await; | 27546 | probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&app, &tenants).await; |
| 27668 | } | 27547 | } |
| 27669 | 27548 | ||
| 27670 | -/// [`probe_cross_school_ids_are_not_found_under_the_other_cookie`] on a **real remote deployment** — production's `Mode::Remote`, | 27549 | +/// [`probe_cross_school_ids_are_not_found_under_the_other_cookie`] against a |
| 27671 | -/// where isolation rests on each connection's `use_db` pin. | 27550 | +/// second, independent deployment — the probe body is shared, the deployment is not. |
| 27672 | #[tokio::test] | 27551 | #[tokio::test] |
| 27673 | async fn remote_probe_cross_school_ids_are_not_found_under_the_other_cookie() { | 27552 | async fn remote_probe_cross_school_ids_are_not_found_under_the_other_cookie() { |
| 27674 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 27553 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 27675 | - return; | ||
| 27676 | - }; | ||
| 27677 | probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&d.app, &d.tenants).await; | 27554 | probe_cross_school_ids_are_not_found_under_the_other_cookie_on(&d.app, &d.tenants).await; |
| 27678 | } | 27555 | } |
| 27679 | 27556 | ||
| @@ -27778,13 +27655,11 @@ async fn probe_cross_school_ids_in_bodies_are_refused() { | |||
| 27778 | probe_cross_school_ids_in_bodies_are_refused_on(&app, &tenants).await; | 27655 | probe_cross_school_ids_in_bodies_are_refused_on(&app, &tenants).await; |
| 27779 | } | 27656 | } |
| 27780 | 27657 | ||
| 27781 | -/// [`probe_cross_school_ids_in_bodies_are_refused`] on a **real remote deployment** — production's `Mode::Remote`, | 27658 | +/// [`probe_cross_school_ids_in_bodies_are_refused`] against a second, |
| 27782 | -/// where isolation rests on each connection's `use_db` pin. | 27659 | +/// independent deployment — the probe body is shared, the deployment is not. |
| 27783 | #[tokio::test] | 27660 | #[tokio::test] |
| 27784 | async fn remote_probe_cross_school_ids_in_bodies_are_refused() { | 27661 | async fn remote_probe_cross_school_ids_in_bodies_are_refused() { |
| 27785 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 27662 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 27786 | - return; | ||
| 27787 | - }; | ||
| 27788 | probe_cross_school_ids_in_bodies_are_refused_on(&d.app, &d.tenants).await; | 27663 | probe_cross_school_ids_in_bodies_are_refused_on(&d.app, &d.tenants).await; |
| 27789 | } | 27664 | } |
| 27790 | 27665 | ||
| @@ -27881,13 +27756,11 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | |||
| 27881 | .await; | 27756 | .await; |
| 27882 | } | 27757 | } |
| 27883 | 27758 | ||
| 27884 | -/// [`probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it`] on a **real remote deployment** — production's `Mode::Remote`, | 27759 | +/// [`probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it`] |
| 27885 | -/// where isolation rests on each connection's `use_db` pin. | 27760 | +/// against a second, independent deployment — shared body, own deployment. |
| 27886 | #[tokio::test] | 27761 | #[tokio::test] |
| 27887 | async fn remote_probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { | 27762 | async fn remote_probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it() { |
| 27888 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 27763 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 27889 | - return; | ||
| 27890 | - }; | ||
| 27891 | probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on(&d.app, &d.tenants) | 27764 | probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it_on(&d.app, &d.tenants) |
| 27892 | .await; | 27765 | .await; |
| 27893 | } | 27766 | } |
| @@ -27987,13 +27860,11 @@ async fn probe_cookie_confusion_is_impossible_both_ways() { | |||
| 27987 | probe_cookie_confusion_is_impossible_both_ways_on(&app, &tenants).await; | 27860 | probe_cookie_confusion_is_impossible_both_ways_on(&app, &tenants).await; |
| 27988 | } | 27861 | } |
| 27989 | 27862 | ||
| 27990 | -/// [`probe_cookie_confusion_is_impossible_both_ways`] on a **real remote deployment** — production's `Mode::Remote`, | 27863 | +/// [`probe_cookie_confusion_is_impossible_both_ways`] against a second, |
| 27991 | -/// where isolation rests on each connection's `use_db` pin. | 27864 | +/// independent deployment — the probe body is shared, the deployment is not. |
| 27992 | #[tokio::test] | 27865 | #[tokio::test] |
| 27993 | async fn remote_probe_cookie_confusion_is_impossible_both_ways() { | 27866 | async fn remote_probe_cookie_confusion_is_impossible_both_ways() { |
| 27994 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 27867 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 27995 | - return; | ||
| 27996 | - }; | ||
| 27997 | probe_cookie_confusion_is_impossible_both_ways_on(&d.app, &d.tenants).await; | 27868 | probe_cookie_confusion_is_impossible_both_ways_on(&d.app, &d.tenants).await; |
| 27998 | } | 27869 | } |
| 27999 | 27870 | ||
| @@ -28117,13 +27988,11 @@ async fn probe_register_is_scoped_to_the_named_school() { | |||
| 28117 | probe_register_is_scoped_to_the_named_school_on(&app, &tenants).await; | 27988 | probe_register_is_scoped_to_the_named_school_on(&app, &tenants).await; |
| 28118 | } | 27989 | } |
| 28119 | 27990 | ||
| 28120 | -/// [`probe_register_is_scoped_to_the_named_school`] on a **real remote deployment** — production's `Mode::Remote`, | 27991 | +/// [`probe_register_is_scoped_to_the_named_school`] against a second, |
| 28121 | -/// where isolation rests on each connection's `use_db` pin. | 27992 | +/// independent deployment — the probe body is shared, the deployment is not. |
| 28122 | #[tokio::test] | 27993 | #[tokio::test] |
| 28123 | async fn remote_probe_register_is_scoped_to_the_named_school() { | 27994 | async fn remote_probe_register_is_scoped_to_the_named_school() { |
| 28124 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 27995 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28125 | - return; | ||
| 28126 | - }; | ||
| 28127 | probe_register_is_scoped_to_the_named_school_on(&d.app, &d.tenants).await; | 27996 | probe_register_is_scoped_to_the_named_school_on(&d.app, &d.tenants).await; |
| 28128 | } | 27997 | } |
| 28129 | 27998 | ||
| @@ -28163,17 +28032,12 @@ async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, ten | |||
| 28163 | "register into {slug}: {}", | 28032 | "register into {slug}: {}", |
| 28164 | res.body | 28033 | res.body |
| 28165 | ); | 28034 | ); |
| 28166 | - let found: Vec<String> = db | 28035 | + let found: i64 = |
| 28167 | - .query("SELECT VALUE username FROM user WHERE username = 'ayse'") | 28036 | + sqlx::query_scalar("SELECT count(*) FROM app_user WHERE username = 'ayse'") |
| 28168 | - .await | 28037 | + .fetch_one(db) |
| 28169 | - .unwrap() | 28038 | + .await |
| 28170 | - .take(0) | 28039 | + .unwrap(); |
| 28171 | - .unwrap(); | 28040 | + assert_eq!(found, 1, "exactly one 'ayse' in {slug}"); |
| 28172 | - assert_eq!( | ||
| 28173 | - found, | ||
| 28174 | - vec!["ayse".to_string()], | ||
| 28175 | - "exactly one 'ayse' in {slug}" | ||
| 28176 | - ); | ||
| 28177 | } | 28041 | } |
| 28178 | 28042 | ||
| 28179 | // Unknown school: same 401 and same body as a bad credential — no | 28043 | // Unknown school: same 401 and same body as a bad credential — no |
| @@ -28228,13 +28092,11 @@ async fn probe_uploaded_files_are_school_scoped() { | |||
| 28228 | probe_uploaded_files_are_school_scoped_on(&app, &tenants, common::files_dir().as_path()).await; | 28092 | probe_uploaded_files_are_school_scoped_on(&app, &tenants, common::files_dir().as_path()).await; |
| 28229 | } | 28093 | } |
| 28230 | 28094 | ||
| 28231 | -/// [`probe_uploaded_files_are_school_scoped`] on a **real remote deployment** — production's `Mode::Remote`, | 28095 | +/// [`probe_uploaded_files_are_school_scoped`] against a second, independent |
| 28232 | -/// where isolation rests on each connection's `use_db` pin. | 28096 | +/// deployment — the probe body is shared, the deployment is not. |
| 28233 | #[tokio::test] | 28097 | #[tokio::test] |
| 28234 | async fn remote_probe_uploaded_files_are_school_scoped() { | 28098 | async fn remote_probe_uploaded_files_are_school_scoped() { |
| 28235 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 28099 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28236 | - return; | ||
| 28237 | - }; | ||
| 28238 | probe_uploaded_files_are_school_scoped_on(&d.app, &d.tenants, &d.files).await; | 28100 | probe_uploaded_files_are_school_scoped_on(&d.app, &d.tenants, &d.files).await; |
| 28239 | } | 28101 | } |
| 28240 | 28102 | ||
| @@ -28309,13 +28171,11 @@ async fn probe_school_rows_never_reach_the_control_database() { | |||
| 28309 | probe_school_rows_never_reach_the_control_database_on(&app, &tenants).await; | 28171 | probe_school_rows_never_reach_the_control_database_on(&app, &tenants).await; |
| 28310 | } | 28172 | } |
| 28311 | 28173 | ||
| 28312 | -/// [`probe_school_rows_never_reach_the_control_database`] on a **real remote deployment** — production's `Mode::Remote`, | 28174 | +/// [`probe_school_rows_never_reach_the_control_database`] against a second, |
| 28313 | -/// where isolation rests on each connection's `use_db` pin. | 28175 | +/// independent deployment — the probe body is shared, the deployment is not. |
| 28314 | #[tokio::test] | 28176 | #[tokio::test] |
| 28315 | async fn remote_probe_school_rows_never_reach_the_control_database() { | 28177 | async fn remote_probe_school_rows_never_reach_the_control_database() { |
| 28316 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 28178 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28317 | - return; | ||
| 28318 | - }; | ||
| 28319 | probe_school_rows_never_reach_the_control_database_on(&d.app, &d.tenants).await; | 28179 | probe_school_rows_never_reach_the_control_database_on(&d.app, &d.tenants).await; |
| 28320 | } | 28180 | } |
| 28321 | 28181 | ||
| @@ -28334,8 +28194,8 @@ async fn probe_school_rows_never_reach_the_control_database_on( | |||
| 28334 | // Nothing a school writes may appear in the control database. | 28194 | // Nothing a school writes may appear in the control database. |
| 28335 | let control = tenants.control(); | 28195 | let control = tenants.control(); |
| 28336 | for table in [ | 28196 | for table in [ |
| 28337 | - "user", | 28197 | + "app_user", |
| 28338 | - "session", | 28198 | + "user_session", |
| 28339 | "note", | 28199 | "note", |
| 28340 | "course", | 28200 | "course", |
| 28341 | "event", | 28201 | "event", |
| @@ -28347,24 +28207,23 @@ async fn probe_school_rows_never_reach_the_control_database_on( | |||
| 28347 | "chatbot_thread", | 28207 | "chatbot_thread", |
| 28348 | "exam", | 28208 | "exam", |
| 28349 | ] { | 28209 | ] { |
| 28350 | - let rows: Vec<surrealdb::types::RecordId> = control | 28210 | + let tables: i64 = sqlx::query_scalar( |
| 28351 | - .query(format!("SELECT VALUE id FROM {table}")) | 28211 | + "SELECT count(*) FROM information_schema.tables \ |
| 28352 | - .await | 28212 | + WHERE table_schema = 'public' AND table_name = $1", |
| 28353 | - .expect("control query") | 28213 | + ) |
| 28354 | - .take(0) | 28214 | + .bind(table) |
| 28355 | - .unwrap_or_default(); | 28215 | + .fetch_one(control) |
| 28356 | - assert!( | 28216 | + .await |
| 28357 | - rows.is_empty(), | 28217 | + .expect("control query"); |
| 28358 | - "the control database holds {} `{table}` row(s): {rows:?}", | 28218 | + assert_eq!( |
| 28359 | - rows.len() | 28219 | + tables, 0, |
| 28220 | + "the control database holds a school table `{table}`" | ||
| 28360 | ); | 28221 | ); |
| 28361 | } | 28222 | } |
| 28362 | // And the control database does hold the two schools. | 28223 | // And the control database does hold the two schools. |
| 28363 | - let schools: Vec<String> = control | 28224 | + let schools: Vec<String> = sqlx::query_scalar("SELECT slug FROM school ORDER BY slug") |
| 28364 | - .query("SELECT VALUE slug FROM school ORDER BY slug") | 28225 | + .fetch_all(control) |
| 28365 | .await | 28226 | .await |
| 28366 | - .unwrap() | ||
| 28367 | - .take(0) | ||
| 28368 | .unwrap(); | 28227 | .unwrap(); |
| 28369 | assert_eq!(schools, vec!["beta".to_string(), "demo".to_string()]); | 28228 | assert_eq!(schools, vec!["beta".to_string(), "demo".to_string()]); |
| 28370 | 28229 | ||
| @@ -28421,19 +28280,16 @@ async fn probe_school_rows_never_reach_the_control_database_on( | |||
| 28421 | } | 28280 | } |
| 28422 | } | 28281 | } |
| 28423 | 28282 | ||
| 28424 | -/// Invariant 1 on the path production actually uses: `Mode::Remote`, where every | 28283 | +/// Invariant 1 on the path production actually uses: every school is its own |
| 28425 | -/// school is a *database inside one namespace on one server* and isolation rests | 28284 | +/// *database on one server*, and isolation rests on the server, not on the |
| 28426 | -/// entirely on each connection's `use_db` pin — unlike `Mode::Mem`, where a | 28285 | +/// handle — a school's rows are simply not visible from another school's |
| 28427 | -/// school is its own embedded datastore and isolation cannot fail. | 28286 | +/// database. |
| 28428 | /// | 28287 | /// |
| 28429 | /// The two slugs are the ones that are not bare identifiers: `ata-koleji` parses | 28288 | /// The two slugs are the ones that are not bare identifiers: `ata-koleji` parses |
| 28430 | /// as a subtraction unquoted, `2024school` as a duration. | 28289 | /// as a subtraction unquoted, `2024school` as a duration. |
| 28431 | #[tokio::test] | 28290 | #[tokio::test] |
| 28432 | async fn remote_probe_remote_mode_keeps_two_schools_apart() { | 28291 | async fn remote_probe_remote_mode_keeps_two_schools_apart() { |
| 28433 | - let Some(d) = common::remote_deployment(&[("ata-koleji", "Ata"), ("2024school", "2024")]).await | 28292 | + let d = common::deployment_with(&[("ata-koleji", "Ata"), ("2024school", "2024")]).await; |
| 28434 | - else { | ||
| 28435 | - return; | ||
| 28436 | - }; | ||
| 28437 | let (app, tenants) = (&d.app, &d.tenants); | 28293 | let (app, tenants) = (&d.app, &d.tenants); |
| 28438 | let slug_a = Slug::try_new("ata-koleji").unwrap(); | 28294 | let slug_a = Slug::try_new("ata-koleji").unwrap(); |
| 28439 | let slug_b = Slug::try_new("2024school").unwrap(); | 28295 | let slug_b = Slug::try_new("2024school").unwrap(); |
| @@ -28521,47 +28377,49 @@ async fn remote_probe_remote_mode_keeps_two_schools_apart() { | |||
| 28521 | } | 28377 | } |
| 28522 | 28378 | ||
| 28523 | // ------------------------------------------------------------------------- | 28379 | // ------------------------------------------------------------------------- |
| 28524 | -// Remote-only invariants: things `Mode::Mem` cannot even express, because a | 28380 | +// Database-per-school invariants: a school is its own database on the server, |
| 28525 | -// memory-mode school is its own datastore rather than a database on a server. | 28381 | +// so its rows are unreachable from any other school's handle. |
| 28526 | // ------------------------------------------------------------------------- | 28382 | // ------------------------------------------------------------------------- |
| 28527 | 28383 | ||
| 28528 | -/// The namespace's database list, out of `INFO FOR NS` on the control handle. | 28384 | +/// The server's database list, off the control handle: the control database |
| 28385 | +/// itself plus every school database, named `{control}_school_{slug}`. | ||
| 28529 | async fn namespace_databases(tenants: &Tenants) -> Vec<String> { | 28386 | async fn namespace_databases(tenants: &Tenants) -> Vec<String> { |
| 28530 | - let mut info = tenants | 28387 | + let control = tenants.control(); |
| 28531 | - .control() | 28388 | + let control_db: String = sqlx::query_scalar("SELECT current_database()") |
| 28532 | - .query("INFO FOR NS") | 28389 | + .fetch_one(control) |
| 28533 | .await | 28390 | .await |
| 28534 | - .expect("INFO FOR NS"); | 28391 | + .expect("current database"); |
| 28535 | - let info: serde_json::Value = info | 28392 | + let mut names: Vec<String> = sqlx::query_scalar( |
| 28536 | - .take::<Option<serde_json::Value>>(0) | 28393 | + "SELECT datname FROM pg_database \ |
| 28537 | - .expect("INFO FOR NS row") | 28394 | + WHERE datname = $1 OR datname LIKE $2", |
| 28538 | - .expect("INFO FOR NS is never empty"); | 28395 | + ) |
| 28539 | - let mut names: Vec<String> = info["databases"] | 28396 | + .bind(&control_db) |
| 28540 | - .as_object() | 28397 | + .bind(format!("{control_db}\\_school\\_%")) |
| 28541 | - .unwrap_or_else(|| panic!("INFO FOR NS has no databases map: {info}")) | 28398 | + .fetch_all(control) |
| 28542 | - .keys() | 28399 | + .await |
| 28543 | - .cloned() | 28400 | + .expect("database list"); |
| 28544 | - .collect(); | ||
| 28545 | names.sort(); | 28401 | names.sort(); |
| 28546 | names | 28402 | names |
| 28547 | } | 28403 | } |
| 28548 | 28404 | ||
| 28549 | -/// Remote-only: a school **is** a database, so the namespace must hold exactly | 28405 | +/// A school **is** a database, so the server must hold exactly the created |
| 28550 | -/// the created schools plus `control` — and `DELETE /schools/{slug}` must | 28406 | +/// schools plus the control database — and `DELETE /schools/{slug}` must drop |
| 28551 | -/// `REMOVE DATABASE`, not merely delete the registry row. | 28407 | +/// the database, not merely delete the registry row. |
| 28552 | #[tokio::test] | 28408 | #[tokio::test] |
| 28553 | async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { | 28409 | async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { |
| 28554 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 28410 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28555 | - return; | 28411 | + let control_db: String = sqlx::query_scalar("SELECT current_database()") |
| 28556 | - }; | 28412 | + .fetch_one(d.tenants.control()) |
| 28413 | + .await | ||
| 28414 | + .expect("control name"); | ||
| 28557 | assert_eq!( | 28415 | assert_eq!( |
| 28558 | namespace_databases(&d.tenants).await, | 28416 | namespace_databases(&d.tenants).await, |
| 28559 | vec![ | 28417 | vec![ |
| 28560 | - "beta".to_string(), | 28418 | + control_db.clone(), |
| 28561 | - "control".to_string(), | 28419 | + format!("{control_db}_school_beta"), |
| 28562 | - "demo".to_string() | 28420 | + format!("{control_db}_school_demo"), |
| 28563 | ], | 28421 | ], |
| 28564 | - "the namespace holds exactly the two schools and the control database" | 28422 | + "the server holds exactly the two schools and the control database" |
| 28565 | ); | 28423 | ); |
| 28566 | 28424 | ||
| 28567 | hezarfen_backend::service::builder::ensure( | 28425 | hezarfen_backend::service::builder::ensure( |
| @@ -28586,18 +28444,16 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { | |||
| 28586 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | 28444 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 28587 | assert_eq!( | 28445 | assert_eq!( |
| 28588 | namespace_databases(&d.tenants).await, | 28446 | namespace_databases(&d.tenants).await, |
| 28589 | - vec!["control".to_string(), "demo".to_string()], | 28447 | + vec![control_db.clone(), format!("{control_db}_school_demo")], |
| 28590 | - "DELETE /schools/beta left beta's database standing" | 28448 | + "DELETE /schools/beta dropped beta's database" |
| 28591 | ); | 28449 | ); |
| 28592 | } | 28450 | } |
| 28593 | 28451 | ||
| 28594 | -/// Remote-only: raw SQL on a school's own handle sees that school's rows and | 28452 | +/// Raw SQL on a school's own handle sees that school's rows and no others — |
| 28595 | -/// no others — the `use_db` pin, checked under the API rather than through it. | 28453 | +/// isolation by database, checked under the API rather than through it. |
| 28596 | #[tokio::test] | 28454 | #[tokio::test] |
| 28597 | async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | 28455 | async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { |
| 28598 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 28456 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28599 | - return; | ||
| 28600 | - }; | ||
| 28601 | // Different counts, so a leak cannot hide behind equal numbers. | 28457 | // Different counts, so a leak cannot hide behind equal numbers. |
| 28602 | for (slug, users) in [ | 28458 | for (slug, users) in [ |
| 28603 | (DEMO_SLUG, ["ada", "ali", "ayse"].as_slice()), | 28459 | (DEMO_SLUG, ["ada", "ali", "ayse"].as_slice()), |
| @@ -28622,14 +28478,10 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | |||
| 28622 | } | 28478 | } |
| 28623 | 28479 | ||
| 28624 | let count = async |db: &hezarfen_backend::database::Database| -> i64 { | 28480 | let count = async |db: &hezarfen_backend::database::Database| -> i64 { |
| 28625 | - db.query("SELECT count() FROM user GROUP ALL") | 28481 | + sqlx::query_scalar("SELECT count(*) FROM app_user") |
| 28482 | + .fetch_one(db) | ||
| 28626 | .await | 28483 | .await |
| 28627 | .expect("count query") | 28484 | .expect("count query") |
| 28628 | - .take::<Vec<serde_json::Value>>(0) | ||
| 28629 | - .expect("count row") | ||
| 28630 | - .first() | ||
| 28631 | - .and_then(|row| row["count"].as_i64()) | ||
| 28632 | - .unwrap_or_default() | ||
| 28633 | }; | 28485 | }; |
| 28634 | let db_a = school_db(&d.tenants, DEMO_SLUG).await; | 28486 | let db_a = school_db(&d.tenants, DEMO_SLUG).await; |
| 28635 | let db_b = school_db(&d.tenants, "beta").await; | 28487 | let db_b = school_db(&d.tenants, "beta").await; |
| @@ -28637,14 +28489,12 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | |||
| 28637 | assert_eq!(count(&db_b).await, 1, "beta's own users"); | 28489 | assert_eq!(count(&db_b).await, 1, "beta's own users"); |
| 28638 | } | 28490 | } |
| 28639 | 28491 | ||
| 28640 | -/// Remote-only: one namespace, so the *same record id string* exists in both | 28492 | +/// The same uuid *string* is well-formed everywhere, but the row it names |
| 28641 | -/// databases' address space. Selected on the other school's handle it must | 28493 | +/// exists only in the database that minted it: selecting it on the other |
| 28642 | -/// still find nothing — record ids are not global. | 28494 | +/// school's handle must find nothing. |
| 28643 | #[tokio::test] | 28495 | #[tokio::test] |
| 28644 | async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other() { | 28496 | async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other() { |
| 28645 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 28497 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28646 | - return; | ||
| 28647 | - }; | ||
| 28648 | let res = send( | 28498 | let res = send( |
| 28649 | &d.app, | 28499 | &d.app, |
| 28650 | "POST", | 28500 | "POST", |
| @@ -28657,32 +28507,33 @@ async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other() | |||
| 28657 | 28507 | ||
| 28658 | let db_a = school_db(&d.tenants, DEMO_SLUG).await; | 28508 | let db_a = school_db(&d.tenants, DEMO_SLUG).await; |
| 28659 | let db_b = school_db(&d.tenants, "beta").await; | 28509 | let db_b = school_db(&d.tenants, "beta").await; |
| 28660 | - let id: surrealdb::types::RecordId = db_a | 28510 | + let id: Uuid = sqlx::query_scalar("SELECT id FROM app_user LIMIT 1") |
| 28661 | - .query("SELECT VALUE id FROM user LIMIT 1") | 28511 | + .fetch_one(&db_a) |
| 28662 | .await | 28512 | .await |
| 28663 | - .expect("A's user id") | 28513 | + .expect("A's user id"); |
| 28664 | - .take::<Vec<surrealdb::types::RecordId>>(0) | 28514 | + |
| 28665 | - .expect("id row") | 28515 | + let mine: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE id = $1") |
| 28666 | - .pop() | 28516 | + .bind(id) |
| 28667 | - .expect("A minted exactly one user"); | 28517 | + .fetch_one(&db_a) |
| 28668 | - | 28518 | + .await |
| 28669 | - let mine: Option<serde_json::Value> = db_a.select(id.clone()).await.expect("select in A"); | 28519 | + .expect("select in A"); |
| 28670 | - assert!(mine.is_some(), "{id:?} is A's own row"); | 28520 | + assert_eq!(mine, 1, "{id} is A's own row"); |
| 28671 | - let theirs: Option<serde_json::Value> = db_b.select(id.clone()).await.expect("select in B"); | 28521 | + let theirs: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user WHERE id = $1") |
| 28672 | - assert!( | 28522 | + .bind(id) |
| 28673 | - theirs.is_none(), | 28523 | + .fetch_one(&db_b) |
| 28674 | - "{id:?} — minted in demo — resolved on beta's handle: {theirs:?}" | 28524 | + .await |
| 28525 | + .expect("select in B"); | ||
| 28526 | + assert_eq!( | ||
| 28527 | + theirs, 0, | ||
| 28528 | + "{id} — minted in demo — resolved on beta's handle" | ||
| 28675 | ); | 28529 | ); |
| 28676 | } | 28530 | } |
| 28677 | 28531 | ||
| 28678 | -/// Remote-only: eviction really drops the socket here (in memory mode the | 28532 | +/// Suspension evicts the cached pool; a resume must therefore dial fresh and |
| 28679 | -/// cached handle *is* the store, so it is never dropped). A suspend/resume must | 28533 | +/// find the school's rows exactly as they were. |
| 28680 | -/// therefore reconnect and find the school's rows exactly as they were. | ||
| 28681 | #[tokio::test] | 28534 | #[tokio::test] |
| 28682 | async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { | 28535 | async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { |
| 28683 | - let Some(d) = common::remote_deployment(TWO_SCHOOLS).await else { | 28536 | + let d = common::deployment_with(TWO_SCHOOLS).await; |
| 28684 | - return; | ||
| 28685 | - }; | ||
| 28686 | let slug = Slug::try_new(DEMO_SLUG).unwrap(); | 28537 | let slug = Slug::try_new(DEMO_SLUG).unwrap(); |
| 28687 | let db = school_db(&d.tenants, DEMO_SLUG).await; | 28538 | let db = school_db(&d.tenants, DEMO_SLUG).await; |
| 28688 | let cookie = common::login_as_school(&d.app, &db, DEMO_SLUG, "ada", "admin").await; | 28539 | let cookie = common::login_as_school(&d.app, &db, DEMO_SLUG, "ada", "admin").await; |
| @@ -28710,12 +28561,10 @@ async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { | |||
| 28710 | 28561 | ||
| 28711 | // A fresh connection (the old one was evicted) onto the same database. | 28562 | // A fresh connection (the old one was evicted) onto the same database. |
| 28712 | let reconnected = school_db(&d.tenants, DEMO_SLUG).await; | 28563 | let reconnected = school_db(&d.tenants, DEMO_SLUG).await; |
| 28713 | - let titles: Vec<String> = reconnected | 28564 | + let titles: Vec<String> = sqlx::query_scalar("SELECT title FROM note") |
| 28714 | - .query("SELECT VALUE title FROM note") | 28565 | + .fetch_all(&reconnected) |
| 28715 | .await | 28566 | .await |
| 28716 | - .expect("notes after the resume") | 28567 | + .expect("notes after the resume"); |
| 28717 | - .take(0) | ||
| 28718 | - .expect("title rows"); | ||
| 28719 | assert_eq!(titles, vec!["before".to_string()], "the rows survived"); | 28568 | assert_eq!(titles, vec!["before".to_string()], "the rows survived"); |
| 28720 | let res = send( | 28569 | let res = send( |
| 28721 | &d.app, | 28570 | &d.app, |