Port e2e, rate_limit, ai_bridge, ai_protocol to the Postgres harness
Browse files at this commite0e3597fff1f8ed4c8a2d922ebbc93686500f07dParent: 0466c1a- test
- port e2e, rate_limit, ai_bridge, ai_protocol to the Postgres harness
5 changed files +210 -163
- src/rate_limit.rs +57 -0
- tests/ai_bridge.rs +28 -20
- tests/ai_protocol.rs +1 -4
- tests/e2e.rs +52 -84
- tests/rate_limit.rs +72 -55
src/rate_limit.rsmodified+57 -0
| @@ -938,4 +938,61 @@ mod tests { | |||
| 938 | ); | 938 | ); |
| 939 | } | 939 | } |
| 940 | } | 940 | } |
| 941 | + | ||
| 942 | + /// How many of `tries` requests the limiter admits for `user`. | ||
| 943 | + fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { | ||
| 944 | + (0..tries) | ||
| 945 | + .filter(|_| limiter.enforce_user(user).is_ok()) | ||
| 946 | + .count() | ||
| 947 | + } | ||
| 948 | + | ||
| 949 | + /// A wall-window roll must not bill one request to two shared rows: the | ||
| 950 | + /// fold reports only a bucket's *unreported* delta, so when the wall | ||
| 951 | + /// window rolls under a still-live local window, the new row receives | ||
| 952 | + /// nothing the old row had already taken. (Rebuilt over the control | ||
| 953 | + /// database — `rate_limit` is a control table — after the SurrealDB port | ||
| 954 | + /// dropped it along with the embedded engine.) | ||
| 955 | + #[tokio::test] | ||
| 956 | + async fn a_wall_epoch_roll_charges_no_request_twice() { | ||
| 957 | + const MAX: u32 = 5; | ||
| 958 | + let tenants = crate::database::init_test_tenants().await; | ||
| 959 | + let db = tenants.control().clone(); | ||
| 960 | + let limiter = UserRateLimiter::per_user_minute(MAX); | ||
| 961 | + let window = Duration::from_secs(60); | ||
| 962 | + let epoch = current_epoch(window); | ||
| 963 | + assert_eq!(window.as_millis() as i64, 60_000, "epochs are 60s apart"); | ||
| 964 | + | ||
| 965 | + // A burst early in the client's local window, folded into row `epoch`. | ||
| 966 | + for _ in 0..MAX { | ||
| 967 | + assert!(limiter.enforce_user("user:a").is_ok()); | ||
| 968 | + } | ||
| 969 | + sync_once("test", &limiter.buckets, window, epoch, &db).await; | ||
| 970 | + | ||
| 971 | + // The wall clock rolls while that local window is still running. | ||
| 972 | + sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; | ||
| 973 | + | ||
| 974 | + // The local window lapses, so the client opens a fresh one — inside | ||
| 975 | + // the *same* new wall window — and spends one request in it. | ||
| 976 | + tokio::time::pause(); | ||
| 977 | + tokio::time::advance(Duration::from_secs(61)).await; | ||
| 978 | + tokio::time::resume(); | ||
| 979 | + assert_eq!(admits(&limiter, "user:a", 1), 1, "a fresh local window"); | ||
| 980 | + sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; | ||
| 981 | + | ||
| 982 | + let rows = | ||
| 983 | + sqlx::query_scalar::<_, i64>("SELECT hits FROM rate_limit ORDER BY window_start") | ||
| 984 | + .fetch_all(&db) | ||
| 985 | + .await | ||
| 986 | + .expect("read shared counters"); | ||
| 987 | + assert_eq!( | ||
| 988 | + rows, | ||
| 989 | + vec![i64::from(MAX), 1], | ||
| 990 | + "the new wall row may hold only what was admitted inside it" | ||
| 991 | + ); | ||
| 992 | + assert_eq!( | ||
| 993 | + admits(&limiter, "user:a", 4), | ||
| 994 | + 4, | ||
| 995 | + "the client spent 1 of {MAX} in this window and must keep the rest" | ||
| 996 | + ); | ||
| 997 | + } | ||
| 941 | } | 998 | } |
tests/ai_bridge.rsmodified+28 -20
| @@ -865,7 +865,6 @@ async fn fetch_certificate(ai: Option<AiBridge>) -> (axum::http::StatusCode, Val | |||
| 865 | chatbot_limit: Default::default(), | 865 | chatbot_limit: Default::default(), |
| 866 | exam_presence: Default::default(), | 866 | exam_presence: Default::default(), |
| 867 | board_hub: Default::default(), | 867 | board_hub: Default::default(), |
| 868 | - db_up: Default::default(), | ||
| 869 | ai, | 868 | ai, |
| 870 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 869 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 871 | }); | 870 | }); |
| @@ -985,7 +984,7 @@ use axum::Router; | |||
| 985 | use axum::http::StatusCode; | 984 | use axum::http::StatusCode; |
| 986 | use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHATBOT_MESSAGE_LEN}; | 985 | use hezarfen_backend::constant::{AI_CHAT_CAPABILITY, DEFAULT_MAX_CHATBOT_MESSAGE_LEN}; |
| 987 | use hezarfen_backend::database::Database; | 986 | use hezarfen_backend::database::Database; |
| 988 | -use surrealdb::types::RecordId; | 987 | +use uuid::Uuid; |
| 989 | 988 | ||
| 990 | /// A router wired to `bridge`, plus a handle to its in-memory database. | 989 | /// A router wired to `bridge`, plus a handle to its in-memory database. |
| 991 | async fn chat_app(bridge: &AiBridge) -> (Router, Database) { | 990 | async fn chat_app(bridge: &AiBridge) -> (Router, Database) { |
| @@ -999,7 +998,6 @@ async fn chat_app(bridge: &AiBridge) -> (Router, Database) { | |||
| 999 | chatbot_limit: Default::default(), | 998 | chatbot_limit: Default::default(), |
| 1000 | exam_presence: Default::default(), | 999 | exam_presence: Default::default(), |
| 1001 | board_hub: Default::default(), | 1000 | board_hub: Default::default(), |
| 1002 | - db_up: Default::default(), | ||
| 1003 | ai: Some(bridge.clone()), | 1001 | ai: Some(bridge.clone()), |
| 1004 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 1002 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 1005 | }); | 1003 | }); |
| @@ -1119,15 +1117,18 @@ async fn the_history_a_service_receives_is_oldest_first_without_the_new_turn() { | |||
| 1119 | "complete" | 1117 | "complete" |
| 1120 | ); | 1118 | ); |
| 1121 | 1119 | ||
| 1122 | - db.query( | 1120 | + // History is ordered by `created_at`, so this seeded row's 1002 timestamp |
| 1123 | - "CREATE chatbot_message:h3 SET thread_id = $conv, user_id = $usr, role = 'assistant', | 1121 | + // sorts it before everything the turns above minted — the never-answered |
| 1124 | - content = '', status = 'pending', created_at = 1002;", | 1122 | + // prior turn the new prompt must not duplicate into. |
| 1123 | + sqlx::query( | ||
| 1124 | + "INSERT INTO chatbot_message (id, thread_id, user_id, role, content, status, created_at) \ | ||
| 1125 | + VALUES ($1, $2, $3, 'assistant', '', 'pending', 1002)", | ||
| 1125 | ) | 1126 | ) |
| 1126 | - .bind(("conv", RecordId::new("chatbot_thread", thread.as_str()))) | 1127 | + .bind(Uuid::now_v7()) |
| 1127 | - .bind(("usr", RecordId::new("user", user.as_str()))) | 1128 | + .bind(Uuid::parse_str(&thread).expect("thread id")) |
| 1129 | + .bind(Uuid::parse_str(&user).expect("user id")) | ||
| 1130 | + .execute(&db) | ||
| 1128 | .await | 1131 | .await |
| 1129 | - .expect("seed history") | ||
| 1130 | - .check() | ||
| 1131 | .expect("seed history"); | 1132 | .expect("seed history"); |
| 1132 | 1133 | ||
| 1133 | let mid = ask(&app, &cookie, &thread, "ikinci soru").await; | 1134 | let mid = ask(&app, &cookie, &thread, "ikinci soru").await; |
| @@ -1559,10 +1560,11 @@ async fn a_router_status_rides_back_as_an_ok_answer_not_a_refusal() { | |||
| 1559 | 1560 | ||
| 1560 | #[tokio::test] | 1561 | #[tokio::test] |
| 1561 | async fn a_down_database_socket_is_refused_as_unavailable_rather_than_parked() { | 1562 | async fn a_down_database_socket_is_refused_as_unavailable_rather_than_parked() { |
| 1562 | - // This path skips the HTTP layers, the db guard among them, so it re-checks | 1563 | + // This path skips the HTTP layers, so the bridge resolves the school's |
| 1563 | - // liveness itself: a query issued while the socket is down does not fail, | 1564 | + // registry row itself, on the control database, before every read. Take |
| 1564 | - // it parks until the socket returns. A service has to be told to retry | 1565 | + // that table away and the read is refused as `unavailable` — promptly, |
| 1565 | - // instead of waiting out its own deadline on a read nobody is running. | 1566 | + // never parked waiting on a store nobody is running — instead of hanging |
| 1567 | + // out the service's own deadline. | ||
| 1566 | let bridge = bridge().await; | 1568 | let bridge = bridge().await; |
| 1567 | let service = connect_service( | 1569 | let service = connect_service( |
| 1568 | &bridge, | 1570 | &bridge, |
| @@ -1571,10 +1573,13 @@ async fn a_down_database_socket_is_refused_as_unavailable_rather_than_parked() { | |||
| 1571 | ) | 1573 | ) |
| 1572 | .await; | 1574 | .await; |
| 1573 | await_workers(&bridge, 1).await; | 1575 | await_workers(&bridge, 1).await; |
| 1574 | - let health = hezarfen_backend::state::DbHealth::default(); | 1576 | + let (_app, _db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; |
| 1575 | - let (_app, _db) = common::app_with_ai_health(Some(bridge.clone()), health.clone()).await; | 1577 | + let control = tenants.control(); |
| 1576 | 1578 | ||
| 1577 | - health.set(false); | 1579 | + sqlx::query("ALTER TABLE school RENAME TO school_out") |
| 1580 | + .execute(control) | ||
| 1581 | + .await | ||
| 1582 | + .expect("take the registry away"); | ||
| 1578 | match api_read(&service.conn, read_of("/notes", None)).await { | 1583 | match api_read(&service.conn, read_of("/notes", None)).await { |
| 1579 | ApiResponse::Err { code, id, .. } => { | 1584 | ApiResponse::Err { code, id, .. } => { |
| 1580 | assert_eq!(code, "unavailable"); | 1585 | assert_eq!(code, "unavailable"); |
| @@ -1583,9 +1588,12 @@ async fn a_down_database_socket_is_refused_as_unavailable_rather_than_parked() { | |||
| 1583 | other => panic!("a read against a down database must be refused: {other:?}"), | 1588 | other => panic!("a read against a down database must be refused: {other:?}"), |
| 1584 | } | 1589 | } |
| 1585 | 1590 | ||
| 1586 | - // And that refusal is the flag's doing, not a broken bridge: the same read | 1591 | + // And that refusal is the outage's doing, not a broken bridge: the same |
| 1587 | - // on the same stream-opening service answers once the socket is back. | 1592 | + // read on the same stream-opening service answers once the store is back. |
| 1588 | - health.set(true); | 1593 | + sqlx::query("ALTER TABLE school_out RENAME TO school") |
| 1594 | + .execute(control) | ||
| 1595 | + .await | ||
| 1596 | + .expect("give the registry back"); | ||
| 1589 | let (status, _) = ok_answer(api_read(&service.conn, read_of("/notes", None)).await); | 1597 | let (status, _) = ok_answer(api_read(&service.conn, read_of("/notes", None)).await); |
| 1590 | assert_eq!(status, 200); | 1598 | assert_eq!(status, 200); |
| 1591 | } | 1599 | } |
tests/ai_protocol.rsmodified+1 -4
| @@ -954,9 +954,7 @@ async fn a_chat_request_names_the_askers_school_role() { | |||
| 954 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; | 954 | let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; |
| 955 | await_workers(&bridge, 1).await; | 955 | await_workers(&bridge, 1).await; |
| 956 | 956 | ||
| 957 | - let tenants = hezarfen_backend::database::init_mem_tenants() | 957 | + let tenants = hezarfen_backend::database::init_test_tenants().await; |
| 958 | - .await | ||
| 959 | - .expect("in-memory deployment"); | ||
| 960 | let db = tenants | 958 | let db = tenants |
| 961 | .get(&hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap()) | 959 | .get(&hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap()) |
| 962 | .await | 960 | .await |
| @@ -970,7 +968,6 @@ async fn a_chat_request_names_the_askers_school_role() { | |||
| 970 | chatbot_limit: Default::default(), | 968 | chatbot_limit: Default::default(), |
| 971 | exam_presence: Default::default(), | 969 | exam_presence: Default::default(), |
| 972 | board_hub: Default::default(), | 970 | board_hub: Default::default(), |
| 973 | - db_up: Default::default(), | ||
| 974 | ai: Some(bridge.clone()), | 971 | ai: Some(bridge.clone()), |
| 975 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 972 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 976 | }); | 973 | }); |
tests/e2e.rsmodified+52 -84
| @@ -6,8 +6,11 @@ use hezarfen_backend::rate_limit::RateLimitConfig; | |||
| 6 | use hezarfen_backend::state::AppState; | 6 | use hezarfen_backend::state::AppState; |
| 7 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | 7 | use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; |
| 8 | use hezarfen_backend::{build_router, database}; | 8 | use hezarfen_backend::{build_router, database}; |
| 9 | +mod common; | ||
| 10 | + | ||
| 9 | use reqwest::{Client, StatusCode}; | 11 | use reqwest::{Client, StatusCode}; |
| 10 | use serde_json::{Value, json}; | 12 | use serde_json::{Value, json}; |
| 13 | +use uuid::Uuid; | ||
| 11 | 14 | ||
| 12 | /// Start the server on a random port. Returns its base URL (e.g. | 15 | /// Start the server on a random port. Returns its base URL (e.g. |
| 13 | /// `http://127.0.0.1:54321`) plus a handle to its database, so a test can grant | 16 | /// `http://127.0.0.1:54321`) plus a handle to its database, so a test can grant |
| @@ -18,9 +21,7 @@ async fn spawn_server() -> (String, Database) { | |||
| 18 | 21 | ||
| 19 | /// [`spawn_server`], with the AI bridge the chatbot relays through wired in. | 22 | /// [`spawn_server`], with the AI bridge the chatbot relays through wired in. |
| 20 | async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) { | 23 | async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) { |
| 21 | - let tenants = database::init_mem_tenants() | 24 | + let tenants = database::init_test_tenants().await; |
| 22 | - .await | ||
| 23 | - .expect("in-memory deployment"); | ||
| 24 | let db = tenants | 25 | let db = tenants |
| 25 | .get(&Slug::try_new(DEMO_SLUG).unwrap()) | 26 | .get(&Slug::try_new(DEMO_SLUG).unwrap()) |
| 26 | .await | 27 | .await |
| @@ -48,7 +49,6 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St | |||
| 48 | chatbot_limit: Default::default(), | 49 | chatbot_limit: Default::default(), |
| 49 | exam_presence: Default::default(), | 50 | exam_presence: Default::default(), |
| 50 | board_hub: Default::default(), | 51 | board_hub: Default::default(), |
| 51 | - db_up: Default::default(), | ||
| 52 | ai, | 52 | ai, |
| 53 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 53 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 54 | }); | 54 | }); |
| @@ -69,12 +69,11 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St | |||
| 69 | 69 | ||
| 70 | /// Grant `user` a role directly (the manual bootstrap path). | 70 | /// Grant `user` a role directly (the manual bootstrap path). |
| 71 | async fn promote(db: &Database, user: &str, role: &str) { | 71 | async fn promote(db: &Database, user: &str, role: &str) { |
| 72 | - db.query("UPDATE user SET role = $r WHERE username = $u") | 72 | + sqlx::query("UPDATE app_user SET role = $1 WHERE username = $2") |
| 73 | - .bind(("r", role.to_string())) | 73 | + .bind(role) |
| 74 | - .bind(("u", user.to_string())) | 74 | + .bind(user) |
| 75 | + .execute(db) | ||
| 75 | .await | 76 | .await |
| 76 | - .unwrap() | ||
| 77 | - .check() | ||
| 78 | .unwrap(); | 77 | .unwrap(); |
| 79 | } | 78 | } |
| 80 | 79 | ||
| @@ -2201,41 +2200,34 @@ async fn board_frame_of_type(ws: &mut WsStream, kind: &str) -> Value { | |||
| 2201 | } | 2200 | } |
| 2202 | } | 2201 | } |
| 2203 | 2202 | ||
| 2204 | -fn board_record(board: &str) -> surrealdb::types::RecordId { | ||
| 2205 | - surrealdb::types::RecordId::new("board", board.to_string()) | ||
| 2206 | -} | ||
| 2207 | - | ||
| 2208 | /// The stored stroke ids of one epoch, in mint order, read straight out of the | 2203 | /// The stored stroke ids of one epoch, in mint order, read straight out of the |
| 2209 | /// database — the only proof that survives a lying frame. | 2204 | /// database — the only proof that survives a lying frame. |
| 2210 | async fn stored_stroke_ids(db: &Database, board: &str, epoch: i64) -> Vec<String> { | 2205 | async fn stored_stroke_ids(db: &Database, board: &str, epoch: i64) -> Vec<String> { |
| 2211 | - let mut result = db | 2206 | + sqlx::query_scalar::<_, Uuid>( |
| 2212 | - .query( | 2207 | + "SELECT id FROM board_stroke \ |
| 2213 | - "SELECT VALUE record::id(id) FROM board_stroke \ | 2208 | + WHERE board = $1 AND epoch = $2 AND kind = 'stroke' ORDER BY id", |
| 2214 | - WHERE board = $b AND epoch = $e AND kind = 'stroke' ORDER BY id", | 2209 | + ) |
| 2215 | - ) | 2210 | + .bind(Uuid::parse_str(board).unwrap()) |
| 2216 | - .bind(("b", board_record(board))) | 2211 | + .bind(epoch) |
| 2217 | - .bind(("e", epoch)) | 2212 | + .fetch_all(db) |
| 2218 | - .await | 2213 | + .await |
| 2219 | - .unwrap() | 2214 | + .unwrap() |
| 2220 | - .check() | 2215 | + .into_iter() |
| 2221 | - .unwrap(); | 2216 | + .map(|id| id.to_string()) |
| 2222 | - result.take::<Vec<String>>(0).unwrap() | 2217 | + .collect() |
| 2223 | } | 2218 | } |
| 2224 | 2219 | ||
| 2225 | /// The stored payloads of one epoch, in mint order. | 2220 | /// The stored payloads of one epoch, in mint order. |
| 2226 | async fn stored_payloads(db: &Database, board: &str, epoch: i64) -> Vec<String> { | 2221 | async fn stored_payloads(db: &Database, board: &str, epoch: i64) -> Vec<String> { |
| 2227 | - let mut result = db | 2222 | + sqlx::query_scalar::<_, String>( |
| 2228 | - .query( | 2223 | + "SELECT payload FROM board_stroke \ |
| 2229 | - "SELECT VALUE payload FROM board_stroke \ | 2224 | + WHERE board = $1 AND epoch = $2 AND kind = 'stroke' ORDER BY id", |
| 2230 | - WHERE board = $b AND epoch = $e AND kind = 'stroke' ORDER BY id", | 2225 | + ) |
| 2231 | - ) | 2226 | + .bind(Uuid::parse_str(board).unwrap()) |
| 2232 | - .bind(("b", board_record(board))) | 2227 | + .bind(epoch) |
| 2233 | - .bind(("e", epoch)) | 2228 | + .fetch_all(db) |
| 2234 | - .await | 2229 | + .await |
| 2235 | - .unwrap() | 2230 | + .unwrap() |
| 2236 | - .check() | ||
| 2237 | - .unwrap(); | ||
| 2238 | - result.take::<Vec<String>>(0).unwrap() | ||
| 2239 | } | 2231 | } |
| 2240 | 2232 | ||
| 2241 | /// Draw one mark and wait for its ack, ignoring the fan-out of everyone else's | 2233 | /// Draw one mark and wait for its ack, ignoring the fan-out of everyone else's |
| @@ -2332,28 +2324,17 @@ async fn a_participants_clear_is_refused_and_the_socket_keeps_drawing() { | |||
| 2332 | vec!["before".to_string(), "after".to_string()] | 2324 | vec!["before".to_string(), "after".to_string()] |
| 2333 | ); | 2325 | ); |
| 2334 | // The refusal wrote nothing: no clear marker, and the epoch never moved. | 2326 | // The refusal wrote nothing: no clear marker, and the epoch never moved. |
| 2335 | - let mut result = room | 2327 | + let epochs = sqlx::query_scalar::<_, i64>("SELECT epoch FROM board WHERE id = $1") |
| 2336 | - .db | 2328 | + .bind(Uuid::parse_str(board).unwrap()) |
| 2337 | - .query("SELECT VALUE epoch FROM $b") | 2329 | + .fetch_all(&room.db) |
| 2338 | - .bind(("b", board_record(board))) | ||
| 2339 | .await | 2330 | .await |
| 2340 | - .unwrap() | ||
| 2341 | - .check() | ||
| 2342 | .unwrap(); | 2331 | .unwrap(); |
| 2343 | - assert_eq!(result.take::<Vec<i64>>(0).unwrap(), vec![0]); | 2332 | + assert_eq!(epochs, vec![0]); |
| 2344 | - let mut result = room | 2333 | + let clears = sqlx::query_scalar::<_, Uuid>("SELECT id FROM board_stroke WHERE kind = 'clear'") |
| 2345 | - .db | 2334 | + .fetch_all(&room.db) |
| 2346 | - .query("SELECT VALUE id FROM board_stroke WHERE kind = 'clear'") | ||
| 2347 | .await | 2335 | .await |
| 2348 | - .unwrap() | ||
| 2349 | - .check() | ||
| 2350 | .unwrap(); | 2336 | .unwrap(); |
| 2351 | - assert!( | 2337 | + assert!(clears.is_empty()); |
| 2352 | - result | ||
| 2353 | - .take::<Vec<surrealdb::types::RecordId>>(0) | ||
| 2354 | - .unwrap() | ||
| 2355 | - .is_empty() | ||
| 2356 | - ); | ||
| 2357 | 2338 | ||
| 2358 | // A lock is creator-only on the same terms, and equally non-fatal. | 2339 | // A lock is creator-only on the same terms, and equally non-fatal. |
| 2359 | ws_send(&mut veli, json!({ "type": "lock", "locked": true })).await; | 2340 | ws_send(&mut veli, json!({ "type": "lock", "locked": true })).await; |
| @@ -2563,13 +2544,9 @@ async fn the_door_is_a_404_for_an_outsider_and_an_unknown_board() { | |||
| 2563 | "a non-participant must not learn the board exists" | 2544 | "a non-participant must not learn the board exists" |
| 2564 | ); | 2545 | ); |
| 2565 | assert_eq!( | 2546 | assert_eq!( |
| 2566 | - board_open( | 2547 | + board_open(base, common::ABSENT_ID, Some(&room.creator_cookie)) |
| 2567 | - base, | 2548 | + .await |
| 2568 | - "01JZZZZZZZZZZZZZZZZZZZZZZZ", | 2549 | + .err(), |
| 2569 | - Some(&room.creator_cookie) | ||
| 2570 | - ) | ||
| 2571 | - .await | ||
| 2572 | - .err(), | ||
| 2573 | Some(404), | 2550 | Some(404), |
| 2574 | "indistinguishable from an unknown board" | 2551 | "indistinguishable from an unknown board" |
| 2575 | ); | 2552 | ); |
| @@ -2614,20 +2591,14 @@ async fn a_parent_cannot_enter_the_room_or_draw() { | |||
| 2614 | .unwrap(); | 2591 | .unwrap(); |
| 2615 | // Beside `veli`, who stays: the two differ only by role, so the refusal | 2592 | // Beside `veli`, who stays: the two differ only by role, so the refusal |
| 2616 | // below cannot be blamed on the roster. | 2593 | // below cannot be blamed on the roster. |
| 2617 | - room.db | 2594 | + sqlx::query("UPDATE board SET participants = $1 WHERE id = $2") |
| 2618 | - .query("UPDATE $b SET participants = [$v, $u]") | 2595 | + .bind(vec![ |
| 2619 | - .bind(("b", board_record(board))) | 2596 | + Uuid::parse_str(&room.veli_id).unwrap(), |
| 2620 | - .bind(( | 2597 | + Uuid::parse_str(me["id"].as_str().unwrap()).unwrap(), |
| 2621 | - "v", | 2598 | + ]) |
| 2622 | - surrealdb::types::RecordId::new("user", room.veli_id.clone()), | 2599 | + .bind(Uuid::parse_str(board).unwrap()) |
| 2623 | - )) | 2600 | + .execute(&room.db) |
| 2624 | - .bind(( | ||
| 2625 | - "u", | ||
| 2626 | - surrealdb::types::RecordId::new("user", me["id"].as_str().unwrap().to_string()), | ||
| 2627 | - )) | ||
| 2628 | .await | 2601 | .await |
| 2629 | - .unwrap() | ||
| 2630 | - .check() | ||
| 2631 | .unwrap(); | 2602 | .unwrap(); |
| 2632 | 2603 | ||
| 2633 | assert_eq!( | 2604 | assert_eq!( |
| @@ -2637,7 +2608,7 @@ async fn a_parent_cannot_enter_the_room_or_draw() { | |||
| 2637 | ); | 2608 | ); |
| 2638 | // Not a 403 anywhere: identical to a board that was never minted. | 2609 | // Not a 403 anywhere: identical to a board that was never minted. |
| 2639 | assert_eq!( | 2610 | assert_eq!( |
| 2640 | - board_open(base, "01JZZZZZZZZZZZZZZZZZZZZZZZ", Some(&cookie)) | 2611 | + board_open(base, common::ABSENT_ID, Some(&cookie)) |
| 2641 | .await | 2612 | .await |
| 2642 | .err(), | 2613 | .err(), |
| 2643 | Some(404) | 2614 | Some(404) |
| @@ -2671,12 +2642,11 @@ async fn a_removed_participant_can_no_longer_draw() { | |||
| 2671 | 2642 | ||
| 2672 | // The silent removal first: write the roster straight into the database, | 2643 | // The silent removal first: write the roster straight into the database, |
| 2673 | // so no frame is published and only the per-stroke gate can catch it. | 2644 | // so no frame is published and only the per-stroke gate can catch it. |
| 2674 | - room.db | 2645 | + sqlx::query("UPDATE board SET participants = $1 WHERE id = $2") |
| 2675 | - .query("UPDATE $b SET participants = []") | 2646 | + .bind(Vec::<Uuid>::new()) |
| 2676 | - .bind(("b", board_record(board))) | 2647 | + .bind(Uuid::parse_str(board).unwrap()) |
| 2648 | + .execute(&room.db) | ||
| 2677 | .await | 2649 | .await |
| 2678 | - .unwrap() | ||
| 2679 | - .check() | ||
| 2680 | .unwrap(); | 2650 | .unwrap(); |
| 2681 | ws_send( | 2651 | ws_send( |
| 2682 | &mut veli, | 2652 | &mut veli, |
| @@ -3856,9 +3826,7 @@ async fn probe_a_suspended_school_refuses_websocket_upgrades() { | |||
| 3856 | ); | 3826 | ); |
| 3857 | // So is the exam room, on any id. | 3827 | // So is the exam room, on any id. |
| 3858 | assert_eq!( | 3828 | assert_eq!( |
| 3859 | - ws_open(&base, "01J8XZ0K3Q8G7X2M4N5P6R7S8T", Some(&cookie)) | 3829 | + ws_open(&base, common::ABSENT_ID, Some(&cookie)).await.err(), |
| 3860 | - .await | ||
| 3861 | - .err(), | ||
| 3862 | Some(403), | 3830 | Some(403), |
| 3863 | "the exam socket opened for a suspended school" | 3831 | "the exam socket opened for a suspended school" |
| 3864 | ); | 3832 | ); |
tests/rate_limit.rsmodified+72 -55
| @@ -16,11 +16,9 @@ use hezarfen_backend::{build_router, database}; | |||
| 16 | use serde_json::{Value, json}; | 16 | use serde_json::{Value, json}; |
| 17 | use tower::ServiceExt; | 17 | use tower::ServiceExt; |
| 18 | 18 | ||
| 19 | -/// App with the given limits, backed by a fresh in-memory database. | 19 | +/// App with the given limits, backed by a fresh per-test Postgres deployment. |
| 20 | async fn app_with(rate_limit: RateLimitConfig) -> Router { | 20 | async fn app_with(rate_limit: RateLimitConfig) -> Router { |
| 21 | - let tenants = database::init_mem_tenants() | 21 | + let tenants = database::init_test_tenants().await; |
| 22 | - .await | ||
| 23 | - .expect("in-memory deployment"); | ||
| 24 | build_router(AppState { | 22 | build_router(AppState { |
| 25 | db: tenants.control().clone(), | 23 | db: tenants.control().clone(), |
| 26 | tenants, | 24 | tenants, |
| @@ -30,7 +28,6 @@ async fn app_with(rate_limit: RateLimitConfig) -> Router { | |||
| 30 | chatbot_limit: Default::default(), | 28 | chatbot_limit: Default::default(), |
| 31 | exam_presence: Default::default(), | 29 | exam_presence: Default::default(), |
| 32 | board_hub: Default::default(), | 30 | board_hub: Default::default(), |
| 33 | - db_up: Default::default(), | ||
| 34 | ai: None, | 31 | ai: None, |
| 35 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 32 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 36 | }) | 33 | }) |
| @@ -383,29 +380,31 @@ async fn keyless_clients_share_one_budget_once_the_map_is_saturated() { | |||
| 383 | 380 | ||
| 384 | // --- the window outlives the process ------------------------------------ | 381 | // --- the window outlives the process ------------------------------------ |
| 385 | // | 382 | // |
| 386 | -// Two `UserRateLimiter`s over one database stand in for the process before and | 383 | +// Two `UserRateLimiter`s over one control database stand in for the process |
| 387 | -// after a restart: two separate sets of in-memory buckets sharing only the | 384 | +// before and after a restart: two separate sets of in-memory buckets sharing |
| 388 | -// `rate_limit` table, which is what stops a restart mid-window from handing | 385 | +// only the `rate_limit` table, which is what stops a restart mid-window from |
| 389 | -// every client a fresh budget. Time is paused, so a round of the sync task is | 386 | +// handing every client a fresh budget. Time is paused, so a round of the sync |
| 390 | -// driven by advancing past `RATE_SYNC_INTERVAL_SECS` — and because the task | 387 | +// task is driven by advancing past `RATE_SYNC_INTERVAL_SECS` — and because the |
| 391 | -// blocks on the database (not on time) mid-round, the short sleep afterwards | 388 | +// task blocks on the database (not on time) mid-round, the short sleep |
| 392 | -// cannot resolve until the round has finished. Assertions are on admissions, | 389 | +// afterwards cannot resolve until the round has finished. Assertions stay on |
| 393 | -// never on which limiter won a race: the embedded engine can drop one of two | 390 | +// admissions and on the rows the fold wrote: which limiter's statement lands |
| 394 | -// concurrent writes and still answer `Ok`. | 391 | +// first cannot matter, a round is one atomic statement per limiter. |
| 395 | 392 | ||
| 396 | use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS; | 393 | use hezarfen_backend::constant::RATE_SYNC_INTERVAL_SECS; |
| 397 | use hezarfen_backend::database::Database; | 394 | use hezarfen_backend::database::Database; |
| 398 | use hezarfen_backend::rate_limit::UserRateLimiter; | 395 | use hezarfen_backend::rate_limit::UserRateLimiter; |
| 399 | -use hezarfen_backend::state::DbHealth; | 396 | +use hezarfen_backend::tenant::Tenants; |
| 400 | use std::time::Duration; | 397 | use std::time::Duration; |
| 401 | 398 | ||
| 402 | -/// A migrated in-memory database, with the clock frozen only afterwards: the | 399 | +/// A fresh per-test deployment — the trio shares its **control** database, |
| 403 | -/// embedded engine has internal deadlines of its own and cannot start up under | 400 | +/// where the `rate_limit` table lives — with the clock frozen only afterwards: |
| 404 | -/// a paused clock ("Insert node failed after 5 attempts due to timeout"). | 401 | +/// every pool dials on the real clock, since a paused clock never fires a |
| 405 | -async fn shared_db() -> Database { | 402 | +/// connect deadline and a stalled dial would hang the test. |
| 406 | - let db = database::init_mem().await.expect("in-memory db"); | 403 | +async fn shared_db() -> (Tenants, Database) { |
| 404 | + let tenants = database::init_test_tenants().await; | ||
| 405 | + let db = tenants.control().clone(); | ||
| 407 | tokio::time::pause(); | 406 | tokio::time::pause(); |
| 408 | - db | 407 | + (tenants, db) |
| 409 | } | 408 | } |
| 410 | 409 | ||
| 411 | /// Let the sync task run one round: fire its timer, then hand it *real* time | 410 | /// Let the sync task run one round: fire its timer, then hand it *real* time |
| @@ -419,8 +418,22 @@ async fn sync_round() { | |||
| 419 | tokio::task::yield_now().await; | 418 | tokio::task::yield_now().await; |
| 420 | tokio::time::advance(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await; | 419 | tokio::time::advance(Duration::from_secs(RATE_SYNC_INTERVAL_SECS)).await; |
| 421 | tokio::time::resume(); | 420 | tokio::time::resume(); |
| 422 | - tokio::time::sleep(Duration::from_millis(250)).await; | 421 | + tokio::time::sleep(Duration::from_millis(750)).await; |
| 422 | + tokio::time::pause(); | ||
| 423 | +} | ||
| 424 | + | ||
| 425 | +/// The `rate_limit` rows, read in a resumed window: a pool statement run | ||
| 426 | +/// directly under the paused clock cannot dial — auto-advance fires the | ||
| 427 | +/// connect deadline the instant the runtime idles — so every direct | ||
| 428 | +/// statement here hands the clock back first. | ||
| 429 | +async fn read_shared_hits(db: &Database) -> Vec<i64> { | ||
| 430 | + tokio::time::resume(); | ||
| 431 | + let rows = sqlx::query_scalar::<_, i64>("SELECT hits FROM rate_limit") | ||
| 432 | + .fetch_all(db) | ||
| 433 | + .await | ||
| 434 | + .expect("read shared counters"); | ||
| 423 | tokio::time::pause(); | 435 | tokio::time::pause(); |
| 436 | + rows | ||
| 424 | } | 437 | } |
| 425 | 438 | ||
| 426 | /// One fixed wall window for every round below. The sync task reads the real | 439 | /// One fixed wall window for every round below. The sync task reads the real |
| @@ -435,15 +448,14 @@ const PINNED_WINDOW: i64 = 60_000; | |||
| 435 | /// Two limiters of one tier, sharing `db` and one wall window — the process | 448 | /// Two limiters of one tier, sharing `db` and one wall window — the process |
| 436 | /// before a restart and the process after, which is the only way one deployment | 449 | /// before a restart and the process after, which is the only way one deployment |
| 437 | /// runs two sets of buckets over one `rate_limit` row. | 450 | /// runs two sets of buckets over one `rate_limit` row. |
| 438 | -fn two_processes(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter, DbHealth) { | 451 | +fn two_processes(max: u32, db: &Database) -> (UserRateLimiter, UserRateLimiter) { |
| 439 | - let health = DbHealth::default(); | ||
| 440 | let (a, b) = ( | 452 | let (a, b) = ( |
| 441 | UserRateLimiter::per_user_minute(max), | 453 | UserRateLimiter::per_user_minute(max), |
| 442 | UserRateLimiter::per_user_minute(max), | 454 | UserRateLimiter::per_user_minute(max), |
| 443 | ); | 455 | ); |
| 444 | - a.share_pinned("test", db.clone(), health.clone(), PINNED_WINDOW); | 456 | + a.share_pinned("test", db.clone(), PINNED_WINDOW); |
| 445 | - b.share_pinned("test", db.clone(), health.clone(), PINNED_WINDOW); | 457 | + b.share_pinned("test", db.clone(), PINNED_WINDOW); |
| 446 | - (a, b, health) | 458 | + (a, b) |
| 447 | } | 459 | } |
| 448 | 460 | ||
| 449 | /// How many of `tries` requests a limiter admits for `user`. | 461 | /// How many of `tries` requests a limiter admits for `user`. |
| @@ -455,8 +467,8 @@ fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { | |||
| 455 | 467 | ||
| 456 | #[tokio::test] | 468 | #[tokio::test] |
| 457 | async fn a_restarted_process_inherits_the_windows_spend() { | 469 | async fn a_restarted_process_inherits_the_windows_spend() { |
| 458 | - let db = shared_db().await; | 470 | + let (_tenants, db) = shared_db().await; |
| 459 | - let (a, b, _health) = two_processes(6, &db); | 471 | + let (a, b) = two_processes(6, &db); |
| 460 | 472 | ||
| 461 | // Each spends freely until its first sync — the accepted one-interval | 473 | // Each spends freely until its first sync — the accepted one-interval |
| 462 | // overshoot, and the whole reason the shared row exists at all. | 474 | // overshoot, and the whole reason the shared row exists at all. |
| @@ -473,17 +485,14 @@ async fn a_restarted_process_inherits_the_windows_spend() { | |||
| 473 | ); | 485 | ); |
| 474 | 486 | ||
| 475 | // And the shared row agrees with what was actually admitted. | 487 | // And the shared row agrees with what was actually admitted. |
| 476 | - let mut rows = db | 488 | + let rows = read_shared_hits(&db).await; |
| 477 | - .query("SELECT VALUE hits FROM rate_limit") | 489 | + assert_eq!(rows, vec![spent as i64]); |
| 478 | - .await | ||
| 479 | - .expect("read shared counters"); | ||
| 480 | - assert_eq!(rows.take::<Vec<i64>>(0).unwrap(), vec![spent as i64]); | ||
| 481 | } | 490 | } |
| 482 | 491 | ||
| 483 | #[tokio::test] | 492 | #[tokio::test] |
| 484 | async fn a_process_that_never_admitted_still_learns_the_budget_is_gone() { | 493 | async fn a_process_that_never_admitted_still_learns_the_budget_is_gone() { |
| 485 | - let db = shared_db().await; | 494 | + let (_tenants, db) = shared_db().await; |
| 486 | - let (a, b, _health) = two_processes(4, &db); | 495 | + let (a, b) = two_processes(4, &db); |
| 487 | 496 | ||
| 488 | // b spends one request, so it has a bucket to sync; a spends the rest. | 497 | // b spends one request, so it has a bucket to sync; a spends the rest. |
| 489 | assert_eq!(admits(&b, "user:a", 1), 1); | 498 | assert_eq!(admits(&b, "user:a", 1), 1); |
| @@ -501,9 +510,18 @@ async fn a_process_that_never_admitted_still_learns_the_budget_is_gone() { | |||
| 501 | 510 | ||
| 502 | #[tokio::test] | 511 | #[tokio::test] |
| 503 | async fn a_down_database_leaves_each_process_on_its_local_budget() { | 512 | async fn a_down_database_leaves_each_process_on_its_local_budget() { |
| 504 | - let db = shared_db().await; | 513 | + let (_tenants, db) = shared_db().await; |
| 505 | - let (a, b, health) = two_processes(3, &db); | 514 | + let (a, b) = two_processes(3, &db); |
| 506 | - health.set(false); | 515 | + |
| 516 | + // The shared store goes down: the fold's table is taken away — the one | ||
| 517 | + // statement a round needs fails outright — and comes back without either | ||
| 518 | + // limiter being restarted. | ||
| 519 | + tokio::time::resume(); | ||
| 520 | + sqlx::query("ALTER TABLE rate_limit RENAME TO rate_limit_out") | ||
| 521 | + .execute(&db) | ||
| 522 | + .await | ||
| 523 | + .expect("take the shared table away"); | ||
| 524 | + tokio::time::pause(); | ||
| 507 | 525 | ||
| 508 | // Nothing is shared while the database is down — and nothing stalls: both | 526 | // Nothing is shared while the database is down — and nothing stalls: both |
| 509 | // limiters keep serving their own budgets at full speed. | 527 | // limiters keep serving their own budgets at full speed. |
| @@ -515,28 +533,28 @@ async fn a_down_database_leaves_each_process_on_its_local_budget() { | |||
| 515 | assert_eq!(admits(&a, "user:a", 1), 0, "the local budget still binds"); | 533 | assert_eq!(admits(&a, "user:a", 1), 0, "the local budget still binds"); |
| 516 | assert_eq!(admits(&b, "user:a", 1), 0); | 534 | assert_eq!(admits(&b, "user:a", 1), 0); |
| 517 | 535 | ||
| 518 | - // Nothing was written, so the row the sync would have made does not exist. | 536 | + // The table comes back before the read, so the assertion reads the state |
| 519 | - let mut rows = db | 537 | + // the outage left: no round landed, so there is no row at all — and the |
| 520 | - .query("SELECT VALUE hits FROM rate_limit") | 538 | + // unreported deltas are still sitting in the buckets. |
| 539 | + tokio::time::resume(); | ||
| 540 | + sqlx::query("ALTER TABLE rate_limit_out RENAME TO rate_limit") | ||
| 541 | + .execute(&db) | ||
| 521 | .await | 542 | .await |
| 522 | - .expect("read shared counters"); | 543 | + .expect("give the shared table back"); |
| 523 | - assert_eq!(rows.take::<Vec<i64>>(0).unwrap(), Vec::<i64>::new()); | 544 | + tokio::time::pause(); |
| 545 | + let rows = read_shared_hits(&db).await; | ||
| 546 | + assert_eq!(rows, Vec::<i64>::new()); | ||
| 524 | 547 | ||
| 525 | - // Recovery needs no restart: the next round shares again. | 548 | + // Recovery needs no restart: the next round carries the deltas, and the |
| 526 | - health.set(true); | 549 | + // shared row holds everything both processes admitted while it was down. |
| 527 | sync_round().await; | 550 | sync_round().await; |
| 528 | - let mut rows = db | 551 | + let rows = read_shared_hits(&db).await; |
| 529 | - .query("SELECT VALUE hits FROM rate_limit") | 552 | + assert_eq!(rows, vec![6]); |
| 530 | - .await | ||
| 531 | - .expect("read shared counters"); | ||
| 532 | - assert_eq!(rows.take::<Vec<i64>>(0).unwrap(), vec![6]); | ||
| 533 | } | 553 | } |
| 534 | 554 | ||
| 535 | /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`. | 555 | /// Boot the app on a real TCP port, `ConnectInfo` wired exactly like `main`. |
| 536 | async fn spawn_server(rate_limit: RateLimitConfig) -> String { | 556 | async fn spawn_server(rate_limit: RateLimitConfig) -> String { |
| 537 | - let tenants = database::init_mem_tenants() | 557 | + let tenants = database::init_test_tenants().await; |
| 538 | - .await | ||
| 539 | - .expect("in-memory deployment"); | ||
| 540 | let app = build_router(AppState { | 558 | let app = build_router(AppState { |
| 541 | db: tenants.control().clone(), | 559 | db: tenants.control().clone(), |
| 542 | tenants, | 560 | tenants, |
| @@ -546,7 +564,6 @@ async fn spawn_server(rate_limit: RateLimitConfig) -> String { | |||
| 546 | chatbot_limit: Default::default(), | 564 | chatbot_limit: Default::default(), |
| 547 | exam_presence: Default::default(), | 565 | exam_presence: Default::default(), |
| 548 | board_hub: Default::default(), | 566 | board_hub: Default::default(), |
| 549 | - db_up: Default::default(), | ||
| 550 | ai: None, | 567 | ai: None, |
| 551 | metrics: hezarfen_backend::telemetry::Metrics::noop(), | 568 | metrics: hezarfen_backend::telemetry::Metrics::noop(), |
| 552 | }); | 569 | }); |