| 1 | |
| 2 | |
| 3 | use surrealdb::Surreal; |
| 4 | use surrealdb::engine::any::Any; |
| 5 | use surrealdb::opt::auth::Root; |
| 6 | |
| 7 | use crate::config::Config; |
| 8 | use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; |
| 9 | use crate::domain::timestamp::Timestamp; |
| 10 | use crate::domain::user::{Password, User, Username}; |
| 11 | use crate::error::AppError; |
| 12 | use crate::migration_sql::MIGRATION_BATCHES; |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | pub type Database = std::sync::Arc<Surreal<Any>>; |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | pub async fn init(cfg: &Config) -> Result<Database, AppError> { |
| 34 | |
| 35 | |
| 36 | |
| 37 | let admin = admin_credentials(cfg)?; |
| 38 | let db = connect_with_retry(cfg).await; |
| 39 | db.signin(Root { |
| 40 | username: cfg.db_user.clone(), |
| 41 | password: cfg.db_pass.clone(), |
| 42 | }) |
| 43 | .await?; |
| 44 | db.use_ns(cfg.db_ns.clone()) |
| 45 | .use_db(cfg.db_name.clone()) |
| 46 | .await?; |
| 47 | let db = std::sync::Arc::new(db); |
| 48 | migrate(&db).await?; |
| 49 | if let Some((username, password)) = admin { |
| 50 | User::ensure_admin(username, password, &db).await?; |
| 51 | } |
| 52 | Ok(db) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | fn admin_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, AppError> { |
| 59 | match (&cfg.admin_username, &cfg.admin_password) { |
| 60 | (Some(username), Some(password)) => Ok(Some(( |
| 61 | Username::try_new(username) |
| 62 | .map_err(|err| AppError::Internal(format!("invalid ADMIN_USERNAME: {err}")))?, |
| 63 | Password::try_new(password) |
| 64 | .map_err(|err| AppError::Internal(format!("invalid ADMIN_PASSWORD: {err}")))?, |
| 65 | ))), |
| 66 | (None, None) => Ok(None), |
| 67 | _ => Err(AppError::Internal( |
| 68 | "ADMIN_USERNAME and ADMIN_PASSWORD must be set together".into(), |
| 69 | )), |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | pub(crate) fn lost_the_race(err: &surrealdb::Error) -> bool { |
| 93 | use surrealdb::types::{ErrorDetails, QueryError}; |
| 94 | if err.is_already_exists() |
| 95 | || matches!( |
| 96 | err.details(), |
| 97 | ErrorDetails::Query(Some(QueryError::TransactionConflict)) |
| 98 | ) |
| 99 | { |
| 100 | return true; |
| 101 | } |
| 102 | let message = err.to_string(); |
| 103 | message.contains("already exists") || message.contains("can be retried") |
| 104 | } |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | pub(crate) async fn write_with_retry<T: surrealdb::types::SurrealValue>( |
| 117 | db: &Database, |
| 118 | sql: &str, |
| 119 | bindings: &[(String, surrealdb::types::Value)], |
| 120 | ) -> Result<Vec<T>, AppError> { |
| 121 | let mut last = None; |
| 122 | for attempt in 0..CAP_WRITE_TRIES { |
| 123 | backoff(attempt).await; |
| 124 | let mut query = db.query(sql); |
| 125 | for (name, value) in bindings { |
| 126 | query = query.bind((name.clone(), value.clone())); |
| 127 | } |
| 128 | match async { query.await?.check()?.take::<Vec<T>>(0) }.await { |
| 129 | Ok(rows) => return Ok(rows), |
| 130 | Err(err) if lost_the_race(&err) => last = Some(err), |
| 131 | Err(err) => return Err(err.into()), |
| 132 | } |
| 133 | } |
| 134 | Err(last |
| 135 | .map(AppError::from) |
| 136 | .unwrap_or_else(|| AppError::Internal("a guarded write never ran".into()))) |
| 137 | } |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | pub(crate) async fn transaction_with_retry( |
| 177 | db: &Database, |
| 178 | sql: &str, |
| 179 | bindings: &[(String, surrealdb::types::Value)], |
| 180 | refusals: &[&str], |
| 181 | ) -> Result< |
| 182 | ( |
| 183 | surrealdb::IndexedResults, |
| 184 | std::collections::HashMap<usize, surrealdb::Error>, |
| 185 | ), |
| 186 | AppError, |
| 187 | > { |
| 188 | let mut last = None; |
| 189 | for attempt in 0..CAP_WRITE_TRIES { |
| 190 | backoff(attempt).await; |
| 191 | let mut query = db.query(sql); |
| 192 | for (name, value) in bindings { |
| 193 | query = query.bind((name.clone(), value.clone())); |
| 194 | } |
| 195 | let mut result = match query.await { |
| 196 | Ok(result) => result, |
| 197 | Err(err) if lost_the_race(&err) => { |
| 198 | last = Some(err); |
| 199 | continue; |
| 200 | } |
| 201 | Err(err) => return Err(err.into()), |
| 202 | }; |
| 203 | let mut errors = result.take_errors(); |
| 204 | let refused = |error: &surrealdb::Error| { |
| 205 | let message = error.to_string(); |
| 206 | refusals.iter().any(|marker| message.contains(marker)) |
| 207 | }; |
| 208 | if errors.values().any(refused) || !errors.values().any(lost_the_race) { |
| 209 | return Ok((result, errors)); |
| 210 | } |
| 211 | last = errors.drain().map(|(_, error)| error).find(lost_the_race); |
| 212 | } |
| 213 | Err(last |
| 214 | .map(AppError::from) |
| 215 | .unwrap_or_else(|| AppError::Internal("a guarded cascade never ran".into()))) |
| 216 | } |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | pub(crate) async fn backoff(attempt: usize) { |
| 222 | if attempt == 0 { |
| 223 | return; |
| 224 | } |
| 225 | let step = CAP_WRITE_BACKOFF_MS << (attempt - 1); |
| 226 | let jitter = Timestamp::now().as_millis().unsigned_abs() % step.max(1); |
| 227 | tokio::time::sleep(std::time::Duration::from_millis(step + jitter)).await; |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | |
| 240 | async fn connect_with_retry(cfg: &Config) -> Surreal<Any> { |
| 241 | let mut backoff = 1; |
| 242 | loop { |
| 243 | match surrealdb::engine::any::connect(cfg.db_url.clone()).await { |
| 244 | Ok(db) => return db, |
| 245 | Err(err) => { |
| 246 | tracing::warn!( |
| 247 | "database at {} unreachable ({err}) — retrying in {backoff}s", |
| 248 | cfg.db_url |
| 249 | ); |
| 250 | tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; |
| 251 | backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS); |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | |
| 258 | pub async fn init_mem() -> Result<Database, AppError> { |
| 259 | let db = surrealdb::engine::any::connect("memory").await?; |
| 260 | db.use_ns("hezarfen").use_db("hezarfen").await?; |
| 261 | migrate(&db).await?; |
| 262 | Ok(std::sync::Arc::new(db)) |
| 263 | } |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | #[cfg(test)] |
| 286 | pub(crate) static RACE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); |
| 287 | |
| 288 | #[cfg(test)] |
| 289 | pub(crate) async fn init_test_server( |
| 290 | scratch: &str, |
| 291 | ) -> (Database, tokio::sync::MutexGuard<'static, ()>) { |
| 292 | let serialized = RACE_LOCK.lock().await; |
| 293 | let url = |
| 294 | std::env::var("HEZARFEN_TEST_DB").unwrap_or_else(|_| "ws://127.0.0.1:8000".to_string()); |
| 295 | let db = surrealdb::engine::any::connect(url.clone()) |
| 296 | .await |
| 297 | .unwrap_or_else(|err| panic!("no SurrealDB server at {url} ({err})")); |
| 298 | db.signin(Root { |
| 299 | username: "root".into(), |
| 300 | password: "root".into(), |
| 301 | }) |
| 302 | .await |
| 303 | .expect("sign in to the test server"); |
| 304 | let ns = format!("test_{scratch}"); |
| 305 | db.query(format!("REMOVE NAMESPACE IF EXISTS {ns}")) |
| 306 | .await |
| 307 | .expect("clear the scratch namespace") |
| 308 | .check() |
| 309 | .expect("clear the scratch namespace"); |
| 310 | db.use_ns(ns.clone()).use_db(ns).await.expect("scratch ns"); |
| 311 | let db = std::sync::Arc::new(db); |
| 312 | migrate(&db).await.expect("migrate the scratch namespace"); |
| 313 | (db, serialized) |
| 314 | } |
| 315 | |
| 316 | |
| 317 | |
| 318 | pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { |
| 319 | for sql in MIGRATION_BATCHES { |
| 320 | let mut query = db.query(sql); |
| 321 | for (name, value) in migration_binds() { |
| 322 | query = query.bind((name, value)); |
| 323 | } |
| 324 | query.await?.check()?; |
| 325 | } |
| 326 | Ok(()) |
| 327 | } |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | fn migration_binds() -> [(&'static str, i64); 1] { |
| 333 | [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)] |
| 334 | } |
| 335 | |
| 336 | #[cfg(test)] |
| 337 | mod tests { |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | #[test] |
| 346 | fn the_admin_seed_mints_the_role_with_the_row() { |
| 347 | let source = |
| 348 | std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs")) |
| 349 | .expect("read user.rs"); |
| 350 | let start = source |
| 351 | .find("pub async fn ensure_admin") |
| 352 | .expect("ensure_admin is declared"); |
| 353 | let body = &source[start..start + source[start..].find("\n }\n").expect("body ends")]; |
| 354 | assert!( |
| 355 | !body.contains("set_role"), |
| 356 | "ensure_admin promotes after creating; an interruption between those two writes \ |
| 357 | leaves a student account on ADMIN_USERNAME that no boot can heal:\n{body}" |
| 358 | ); |
| 359 | assert!( |
| 360 | body.contains("create_with_role"), |
| 361 | "the seed must mint the row with Role::Admin in one statement" |
| 362 | ); |
| 363 | } |
| 364 | |
| 365 | #[tokio::test] |
| 366 | async fn boot_fails_chatbot_messages_left_pending() { |
| 367 | let db = super::init_mem().await.unwrap(); |
| 368 | db.query( |
| 369 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 370 | CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; |
| 371 | CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, |
| 372 | role = 'assistant', content = '', status = 'pending', created_at = 1; |
| 373 | CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u, |
| 374 | role = 'assistant', content = 'hi', status = 'complete', created_at = 1;", |
| 375 | ) |
| 376 | .await |
| 377 | .unwrap() |
| 378 | .check() |
| 379 | .unwrap(); |
| 380 | |
| 381 | |
| 382 | |
| 383 | super::migrate(&db).await.unwrap(); |
| 384 | |
| 385 | let mut rows = db |
| 386 | .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id") |
| 387 | .await |
| 388 | .unwrap(); |
| 389 | let rows: Vec<serde_json::Value> = rows.take(0).unwrap(); |
| 390 | |
| 391 | let done = &rows[0]; |
| 392 | let interrupted = &rows[1]; |
| 393 | assert_eq!(done["status"], "complete"); |
| 394 | assert_eq!(done["error_code"], serde_json::Value::Null); |
| 395 | assert_eq!(interrupted["status"], "failed"); |
| 396 | assert_eq!(interrupted["error_code"], "interrupted"); |
| 397 | assert!(interrupted["completed_at"].as_i64().unwrap() > 0); |
| 398 | } |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | #[tokio::test] |
| 407 | async fn a_plan_assigned_before_the_counter_existed_is_still_refused() { |
| 408 | use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName}; |
| 409 | use crate::error::AppError; |
| 410 | |
| 411 | let db = super::init_mem().await.unwrap(); |
| 412 | |
| 413 | |
| 414 | |
| 415 | db.query( |
| 416 | "CREATE user:m SET username = 'm', password_hash = 'x'; |
| 417 | CREATE user:s SET username = 's', password_hash = 'x'; |
| 418 | CREATE fee_plan:used SET name = 'Yearly', |
| 419 | installments = [{ amount_minor: 100, due_at: 1 }], |
| 420 | created_by = user:m, created_at = 1; |
| 421 | CREATE fee_plan:free SET name = 'Unused', |
| 422 | installments = [{ amount_minor: 100, due_at: 1 }], |
| 423 | created_by = user:m, created_at = 1; |
| 424 | CREATE fee_plan_assignment:used_s SET plan = fee_plan:used, |
| 425 | student = user:s, assigned_by = user:m, created_at = 1;", |
| 426 | ) |
| 427 | .await |
| 428 | .unwrap() |
| 429 | .check() |
| 430 | .unwrap(); |
| 431 | |
| 432 | |
| 433 | |
| 434 | super::migrate(&db).await.unwrap(); |
| 435 | super::migrate(&db).await.unwrap(); |
| 436 | |
| 437 | let mut counts = db |
| 438 | .query("SELECT VALUE assignment_count FROM fee_plan ORDER BY id") |
| 439 | .await |
| 440 | .unwrap(); |
| 441 | let counts: Vec<Option<i64>> = counts.take(0).unwrap(); |
| 442 | |
| 443 | |
| 444 | assert_eq!(counts, vec![None, Some(1)]); |
| 445 | |
| 446 | |
| 447 | |
| 448 | let used = FeePlan::read(&FeePlanId::from_key("used"), &db) |
| 449 | .await |
| 450 | .unwrap() |
| 451 | .unwrap(); |
| 452 | assert!(matches!( |
| 453 | used.clone() |
| 454 | .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) |
| 455 | .await, |
| 456 | Err(AppError::Conflict(_)) |
| 457 | )); |
| 458 | assert!(!used.delete(&db).await.unwrap()); |
| 459 | let free = FeePlan::read(&FeePlanId::from_key("free"), &db) |
| 460 | .await |
| 461 | .unwrap() |
| 462 | .unwrap(); |
| 463 | assert!( |
| 464 | free.clone() |
| 465 | .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) |
| 466 | .await |
| 467 | .is_ok() |
| 468 | ); |
| 469 | assert!(free.delete(&db).await.unwrap()); |
| 470 | } |
| 471 | |
| 472 | |
| 473 | |
| 474 | |
| 475 | |
| 476 | |
| 477 | #[tokio::test] |
| 478 | async fn a_board_roster_written_before_the_sweep_is_repaired_at_boot() { |
| 479 | let db = super::init_mem().await.unwrap(); |
| 480 | db.query( |
| 481 | "CREATE user:s SET username = 's', password_hash = 'x', role = 'student'; |
| 482 | CREATE user:p SET username = 'p', password_hash = 'x', role = 'parent'; |
| 483 | CREATE board:keep SET creator = user:s, title = 'B', |
| 484 | participants = [user:s, user:p, user:ghost], created_at = 1; |
| 485 | CREATE board:gone SET creator = user:s, title = 'C', |
| 486 | participants = [user:p], created_at = 1; |
| 487 | CREATE board:clean SET creator = user:s, title = 'D', |
| 488 | participants = [user:s], created_at = 1; |
| 489 | DELETE migration_mark:board_roster;", |
| 490 | ) |
| 491 | .await |
| 492 | .unwrap() |
| 493 | .check() |
| 494 | .unwrap(); |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | |
| 501 | db.query( |
| 502 | "DEFINE TABLE board_write_probe SCHEMALESS; |
| 503 | DEFINE EVENT board_write ON board WHEN $event = 'UPDATE' THEN { |
| 504 | UPSERT type::record('board_write_probe', 'n') SET n = (n ?? 0) + 1; |
| 505 | };", |
| 506 | ) |
| 507 | .await |
| 508 | .unwrap() |
| 509 | .check() |
| 510 | .unwrap(); |
| 511 | |
| 512 | super::migrate(&db).await.unwrap(); |
| 513 | |
| 514 | async fn rosters(db: &super::Database) -> Vec<Vec<surrealdb::types::RecordId>> { |
| 515 | let mut rows = db |
| 516 | .query("SELECT VALUE participants FROM board ORDER BY id") |
| 517 | .await |
| 518 | .unwrap(); |
| 519 | rows.take(0).unwrap() |
| 520 | } |
| 521 | let after_first = rosters(&db).await; |
| 522 | let s = surrealdb::types::RecordId::new("user", "s"); |
| 523 | |
| 524 | |
| 525 | |
| 526 | assert_eq!( |
| 527 | after_first, |
| 528 | vec![vec![s.clone()], vec![], vec![s.clone()]], |
| 529 | "{after_first:?}" |
| 530 | ); |
| 531 | |
| 532 | async fn writes(db: &super::Database) -> Vec<i64> { |
| 533 | let mut rows = db |
| 534 | .query("SELECT VALUE n FROM board_write_probe:n") |
| 535 | .await |
| 536 | .unwrap(); |
| 537 | rows.take(0).unwrap() |
| 538 | } |
| 539 | assert_eq!( |
| 540 | writes(&db).await, |
| 541 | vec![2], |
| 542 | "only the two stale rows repaired" |
| 543 | ); |
| 544 | |
| 545 | |
| 546 | |
| 547 | super::migrate(&db).await.unwrap(); |
| 548 | assert_eq!(rosters(&db).await, after_first); |
| 549 | assert_eq!(writes(&db).await, vec![2], "the second pass wrote nothing"); |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | let mut mark = db |
| 557 | .query("SELECT VALUE done_at FROM migration_mark:board_roster") |
| 558 | .await |
| 559 | .unwrap(); |
| 560 | assert_eq!( |
| 561 | mark.take::<Vec<i64>>(0).unwrap().len(), |
| 562 | 1, |
| 563 | "the repair marks itself finished" |
| 564 | ); |
| 565 | db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1") |
| 566 | .await |
| 567 | .unwrap() |
| 568 | .check() |
| 569 | .unwrap(); |
| 570 | super::migrate(&db).await.unwrap(); |
| 571 | assert_eq!( |
| 572 | rosters(&db).await, |
| 573 | vec![ |
| 574 | vec![s.clone()], |
| 575 | vec![], |
| 576 | vec![s.clone()], |
| 577 | vec![surrealdb::types::RecordId::new("user", "p")] |
| 578 | ], |
| 579 | "a marked database skips the scan entirely" |
| 580 | ); |
| 581 | assert_eq!(writes(&db).await, vec![2]); |
| 582 | } |
| 583 | |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | #[tokio::test] |
| 590 | async fn the_badge_counters_are_seeded_from_history_exactly_once() { |
| 591 | let db = super::init_mem().await.unwrap(); |
| 592 | db.query( |
| 593 | "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; |
| 594 | CREATE user:b SET username = 'b', password_hash = 'x', role = 'student'; |
| 595 | CREATE user:c SET username = 'c', password_hash = 'x', role = 'student'; |
| 596 | CREATE homework:h SET course = course:c, subject = subject:s, title = 'H', |
| 597 | due_at = 100, created_by = user:a, created_at = 1; |
| 598 | -- Three on time (the equal case counts as on time) and one whose |
| 599 | -- homework was deleted out from under it: that last one is |
| 600 | -- submitted but not on time, because the traversal yields nothing. |
| 601 | CREATE homework_submission:s1 SET homework = homework:h, user = user:a, |
| 602 | submitted_at = 50, updated_at = 50; |
| 603 | CREATE homework_submission:s2 SET homework = homework:h, user = user:a, |
| 604 | submitted_at = 60, updated_at = 100; |
| 605 | -- Handed in before the deadline, then edited well after it — a |
| 606 | -- `touch()` from a single file add does this. On time, because the |
| 607 | -- live path credits the hand-in and debits by `submitted_at`; if |
| 608 | -- the seed judged this one by `updated_at` a later withdrawal |
| 609 | -- would decrement a credit that was never given. |
| 610 | CREATE homework_submission:s3 SET homework = homework:h, user = user:a, |
| 611 | submitted_at = 70, updated_at = 200; |
| 612 | CREATE homework_submission:s4 SET homework = homework:gone, user = user:a, |
| 613 | submitted_at = 80, updated_at = 1; |
| 614 | CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; |
| 615 | CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2; |
| 616 | -- Two finished stints and one still open, which counts for neither. |
| 617 | CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000; |
| 618 | CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500; |
| 619 | CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000; |
| 620 | -- One real stint beside one written with a backwards clock. The |
| 621 | -- floor is per row, like the live close, so the negative one |
| 622 | -- contributes zero and the real 1000ms survives; flooring the |
| 623 | -- per-user sum instead would seed 0 and lose the real stint. |
| 624 | CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000; |
| 625 | CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000; |
| 626 | DELETE migration_mark:profile_counters;", |
| 627 | ) |
| 628 | .await |
| 629 | .unwrap() |
| 630 | .check() |
| 631 | .unwrap(); |
| 632 | |
| 633 | |
| 634 | |
| 635 | |
| 636 | |
| 637 | |
| 638 | db.query( |
| 639 | "DEFINE TABLE user_write_probe SCHEMALESS; |
| 640 | DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { |
| 641 | UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; |
| 642 | };", |
| 643 | ) |
| 644 | .await |
| 645 | .unwrap() |
| 646 | .check() |
| 647 | .unwrap(); |
| 648 | |
| 649 | super::migrate(&db).await.unwrap(); |
| 650 | |
| 651 | async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> { |
| 652 | let mut rows = db |
| 653 | .query( |
| 654 | "SELECT VALUE [homework_submitted_total, homework_on_time_total, |
| 655 | exam_sat_total, pomodoro_finished_total, |
| 656 | pomodoro_focus_ms_total] |
| 657 | FROM user ORDER BY id", |
| 658 | ) |
| 659 | .await |
| 660 | .unwrap(); |
| 661 | rows.take::<Vec<Vec<i64>>>(0) |
| 662 | .unwrap() |
| 663 | .into_iter() |
| 664 | .map(|row| (row[0], row[1], row[2], row[3], row[4])) |
| 665 | .collect() |
| 666 | } |
| 667 | let after_first = counters(&db).await; |
| 668 | |
| 669 | |
| 670 | assert_eq!( |
| 671 | after_first, |
| 672 | vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)], |
| 673 | "{after_first:?}" |
| 674 | ); |
| 675 | |
| 676 | |
| 677 | |
| 678 | |
| 679 | |
| 680 | |
| 681 | |
| 682 | async fn stamped(db: &super::Database, cond: &str) -> Vec<String> { |
| 683 | let mut rows = db |
| 684 | .query(format!( |
| 685 | "SELECT VALUE record::id(id) FROM homework_submission |
| 686 | WHERE {cond} ORDER BY id" |
| 687 | )) |
| 688 | .await |
| 689 | .unwrap(); |
| 690 | rows.take(0).unwrap() |
| 691 | } |
| 692 | |
| 693 | |
| 694 | |
| 695 | |
| 696 | |
| 697 | assert_eq!( |
| 698 | stamped(&db, "counted_on_time = true").await, |
| 699 | ["s1", "s2", "s3"] |
| 700 | ); |
| 701 | assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]); |
| 702 | |
| 703 | async fn writes(db: &super::Database) -> Vec<i64> { |
| 704 | let mut rows = db |
| 705 | .query("SELECT VALUE n FROM user_write_probe:n") |
| 706 | .await |
| 707 | .unwrap(); |
| 708 | rows.take(0).unwrap() |
| 709 | } |
| 710 | let first_writes = writes(&db).await; |
| 711 | |
| 712 | |
| 713 | |
| 714 | assert!( |
| 715 | matches!(first_writes.as_slice(), [n] if *n > 0), |
| 716 | "{first_writes:?}" |
| 717 | ); |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | |
| 723 | super::migrate(&db).await.unwrap(); |
| 724 | assert_eq!(counters(&db).await, after_first); |
| 725 | assert_eq!( |
| 726 | writes(&db).await, |
| 727 | first_writes, |
| 728 | "the second pass wrote nothing" |
| 729 | ); |
| 730 | |
| 731 | |
| 732 | |
| 733 | |
| 734 | |
| 735 | let mut mark = db |
| 736 | .query("SELECT VALUE done_at FROM migration_mark:profile_counters") |
| 737 | .await |
| 738 | .unwrap(); |
| 739 | assert_eq!( |
| 740 | mark.take::<Vec<i64>>(0).unwrap().len(), |
| 741 | 1, |
| 742 | "the seed marks itself finished" |
| 743 | ); |
| 744 | db.query( |
| 745 | "CREATE homework_submission:late SET homework = homework:h, user = user:b, |
| 746 | submitted_at = 90, updated_at = 90;", |
| 747 | ) |
| 748 | .await |
| 749 | .unwrap() |
| 750 | .check() |
| 751 | .unwrap(); |
| 752 | super::migrate(&db).await.unwrap(); |
| 753 | assert_eq!( |
| 754 | counters(&db).await, |
| 755 | after_first, |
| 756 | "a marked database skips the seed entirely" |
| 757 | ); |
| 758 | assert_eq!(writes(&db).await, first_writes); |
| 759 | } |
| 760 | |
| 761 | #[tokio::test] |
| 762 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | let db = super::init_mem().await.unwrap(); |
| 770 | db.query( |
| 771 | "DEFINE FIELD claimed_by ON chatbot_message TYPE option<string>; |
| 772 | DEFINE FIELD claimed_at ON chatbot_message TYPE option<int>; |
| 773 | DEFINE TABLE ai_worker SCHEMAFULL; |
| 774 | DEFINE FIELD seen_at ON ai_worker TYPE int; |
| 775 | DEFINE TABLE migration_lock SCHEMALESS;", |
| 776 | ) |
| 777 | .await |
| 778 | .unwrap() |
| 779 | .check() |
| 780 | .unwrap(); |
| 781 | db.query( |
| 782 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 783 | CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; |
| 784 | CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, |
| 785 | role = 'assistant', content = '', status = 'pending', |
| 786 | created_at = time::unix(time::now()) * 1000, |
| 787 | claimed_by = 'a-dead-replica', claimed_at = 1; |
| 788 | CREATE ai_worker:w SET seen_at = 1; |
| 789 | CREATE migration_lock:the_lock SET holder = 'a-dead-replica', expires_at = 1;", |
| 790 | ) |
| 791 | .await |
| 792 | .unwrap() |
| 793 | .check() |
| 794 | .unwrap(); |
| 795 | |
| 796 | |
| 797 | |
| 798 | super::migrate(&db).await.unwrap(); |
| 799 | super::migrate(&db).await.unwrap(); |
| 800 | |
| 801 | let mut info = db.query("INFO FOR TABLE chatbot_message").await.unwrap(); |
| 802 | let table: serde_json::Value = info.take::<Option<serde_json::Value>>(0).unwrap().unwrap(); |
| 803 | let fields = table["fields"].as_object().expect("fields"); |
| 804 | assert!(!fields.contains_key("claimed_by"), "{table}"); |
| 805 | assert!(!fields.contains_key("claimed_at"), "{table}"); |
| 806 | let mut tables = db.query("INFO FOR DB").await.unwrap(); |
| 807 | let dbinfo: serde_json::Value = tables |
| 808 | .take::<Option<serde_json::Value>>(0) |
| 809 | .unwrap() |
| 810 | .unwrap(); |
| 811 | let tables = dbinfo["tables"].as_object().expect("tables"); |
| 812 | assert!(!tables.contains_key("ai_worker"), "{dbinfo}"); |
| 813 | |
| 814 | |
| 815 | assert!(!tables.contains_key("migration_lock"), "{dbinfo}"); |
| 816 | |
| 817 | |
| 818 | |
| 819 | db.query("UPDATE chatbot_message:m SET status = 'complete', content = 'ok'") |
| 820 | .await |
| 821 | .unwrap() |
| 822 | .check() |
| 823 | .unwrap(); |
| 824 | let mut row = db |
| 825 | .query("SELECT * FROM ONLY chatbot_message:m") |
| 826 | .await |
| 827 | .unwrap(); |
| 828 | let row: serde_json::Value = row.take::<Option<serde_json::Value>>(0).unwrap().unwrap(); |
| 829 | assert_eq!(row["status"], "complete", "{row}"); |
| 830 | assert!(row.get("claimed_by").is_none(), "{row}"); |
| 831 | } |
| 832 | |
| 833 | |
| 834 | |
| 835 | |
| 836 | #[tokio::test] |
| 837 | async fn boot_spares_a_chatbot_message_pending_since_just_now() { |
| 838 | let db = super::init_mem().await.unwrap(); |
| 839 | db.query( |
| 840 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 841 | CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; |
| 842 | CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u, |
| 843 | role = 'assistant', content = '', status = 'pending', |
| 844 | created_at = time::unix(time::now()) * 1000 - 2000; |
| 845 | CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u, |
| 846 | role = 'assistant', content = '', status = 'pending', |
| 847 | created_at = time::unix(time::now()) * 1000 |
| 848 | - ($stale + 1) * 1000;", |
| 849 | ) |
| 850 | .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS)) |
| 851 | .await |
| 852 | .unwrap() |
| 853 | .check() |
| 854 | .unwrap(); |
| 855 | |
| 856 | super::migrate(&db).await.unwrap(); |
| 857 | |
| 858 | let mut res = db |
| 859 | .query( |
| 860 | "SELECT status, error_code FROM ONLY chatbot_message:fresh; |
| 861 | SELECT VALUE status FROM ONLY chatbot_message:old;", |
| 862 | ) |
| 863 | .await |
| 864 | .unwrap(); |
| 865 | let fresh: Option<serde_json::Value> = res.take(0).unwrap(); |
| 866 | let fresh = fresh.unwrap(); |
| 867 | let old: Option<String> = res.take(1).unwrap(); |
| 868 | assert_eq!( |
| 869 | fresh["status"], "pending", |
| 870 | "a two-second-old turn is still being answered" |
| 871 | ); |
| 872 | assert_eq!(fresh["error_code"], serde_json::Value::Null); |
| 873 | assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes"); |
| 874 | } |
| 875 | |
| 876 | |
| 877 | |
| 878 | |
| 879 | #[tokio::test] |
| 880 | async fn boot_converts_positional_choices_and_keeps_the_same_option() { |
| 881 | let db = super::init_mem().await.unwrap(); |
| 882 | |
| 883 | |
| 884 | db.query( |
| 885 | "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question; |
| 886 | REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question; |
| 887 | REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question; |
| 888 | REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question; |
| 889 | DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>; |
| 890 | DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>; |
| 891 | DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>; |
| 892 | DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>; |
| 893 | DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>; |
| 894 | DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>; |
| 895 | DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>; |
| 896 | DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;", |
| 897 | ) |
| 898 | .await |
| 899 | .unwrap() |
| 900 | .check() |
| 901 | .unwrap(); |
| 902 | db.query( |
| 903 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 904 | CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple', |
| 905 | points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1, |
| 906 | source_bank = 'bank_question:b'; |
| 907 | CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2, |
| 908 | file = 'f', content_type = 'image/png', size = 1; |
| 909 | CREATE question_image:whole SET exam = exam:e, question = exam_question:q, |
| 910 | file = 'w', content_type = 'image/png', size = 1; |
| 911 | CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u, |
| 912 | selected = 2, updated_at = 1; |
| 913 | CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple', |
| 914 | points = 3, choices = ['a', 'b'], correct = 0, created_at = 1; |
| 915 | CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1, |
| 916 | file = 'bf', content_type = 'image/png', size = 1;", |
| 917 | ) |
| 918 | .await |
| 919 | .unwrap() |
| 920 | .check() |
| 921 | .unwrap(); |
| 922 | |
| 923 | super::migrate(&db).await.unwrap(); |
| 924 | |
| 925 | let mut res = db |
| 926 | .query( |
| 927 | "SELECT choices, correct FROM ONLY exam_question:q; |
| 928 | SELECT VALUE slot FROM ONLY question_image:i; |
| 929 | SELECT VALUE slot FROM ONLY question_image:whole; |
| 930 | SELECT VALUE selected FROM ONLY exam_answer:a; |
| 931 | SELECT choices, correct FROM ONLY bank_question:b; |
| 932 | SELECT VALUE slot FROM ONLY bank_question_image:bi;", |
| 933 | ) |
| 934 | .await |
| 935 | .unwrap(); |
| 936 | let q: Option<serde_json::Value> = res.take(0).unwrap(); |
| 937 | let q = q.unwrap(); |
| 938 | let img_slot: Option<String> = res.take(1).unwrap(); |
| 939 | let whole_slot: Option<String> = res.take(2).unwrap(); |
| 940 | let selected: Option<String> = res.take(3).unwrap(); |
| 941 | let bank: Option<serde_json::Value> = res.take(4).unwrap(); |
| 942 | let bank = bank.unwrap(); |
| 943 | let bank_slot: Option<String> = res.take(5).unwrap(); |
| 944 | |
| 945 | let ids: Vec<&str> = q["choices"] |
| 946 | .as_array() |
| 947 | .unwrap() |
| 948 | .iter() |
| 949 | .map(|c| c["id"].as_str().unwrap()) |
| 950 | .collect(); |
| 951 | assert_eq!( |
| 952 | q["choices"][0]["text"], "3", |
| 953 | "option order (and so the meaning of every stored index) is preserved" |
| 954 | ); |
| 955 | assert_eq!(q["correct"], ids[1], "correct was index 1"); |
| 956 | assert_eq!( |
| 957 | img_slot.as_deref(), |
| 958 | Some(ids[2]), |
| 959 | "option picture was slot 2" |
| 960 | ); |
| 961 | assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2"); |
| 962 | assert_eq!(whole_slot, None, "a question-level picture has no index"); |
| 963 | let bank_ids: Vec<&str> = bank["choices"] |
| 964 | .as_array() |
| 965 | .unwrap() |
| 966 | .iter() |
| 967 | .map(|c| c["id"].as_str().unwrap()) |
| 968 | .collect(); |
| 969 | assert_eq!(bank["correct"], bank_ids[0]); |
| 970 | assert_eq!(bank_slot.as_deref(), Some(bank_ids[1])); |
| 971 | |
| 972 | |
| 973 | |
| 974 | db.query( |
| 975 | "UPDATE exam_question:q SET points = 7; |
| 976 | UPDATE question_image:i SET size = 2; |
| 977 | UPDATE exam_answer:a SET updated_at = 2; |
| 978 | UPDATE bank_question:b SET points = 4; |
| 979 | UPDATE bank_question_image:bi SET size = 2;", |
| 980 | ) |
| 981 | .await |
| 982 | .unwrap() |
| 983 | .check() |
| 984 | .unwrap(); |
| 985 | |
| 986 | |
| 987 | super::migrate(&db).await.unwrap(); |
| 988 | let mut res = db |
| 989 | .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q") |
| 990 | .await |
| 991 | .unwrap(); |
| 992 | let again: Vec<String> = res.take(0).unwrap(); |
| 993 | assert_eq!(again, ids, "conversion is idempotent"); |
| 994 | } |
| 995 | } |