| 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::{BACKFILL, CHATBOT_PENDING_STALE_SECS, MIGRATION, PRE_REPAIR}; |
| 9 | use crate::error::AppError; |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | pub type Database = std::sync::Arc<Surreal<Any>>; |
| 26 | |
| 27 | |
| 28 | pub async fn init(cfg: &Config) -> Result<Database, AppError> { |
| 29 | let db = connect_with_retry(cfg).await; |
| 30 | db.signin(Root { |
| 31 | username: cfg.db_user.clone(), |
| 32 | password: cfg.db_pass.clone(), |
| 33 | }) |
| 34 | .await?; |
| 35 | db.use_ns(cfg.db_ns.clone()) |
| 36 | .use_db(cfg.db_name.clone()) |
| 37 | .await?; |
| 38 | migrate(&db).await?; |
| 39 | Ok(std::sync::Arc::new(db)) |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | async fn connect_with_retry(cfg: &Config) -> Surreal<Any> { |
| 53 | let mut backoff = 1; |
| 54 | loop { |
| 55 | match surrealdb::engine::any::connect(cfg.db_url.clone()).await { |
| 56 | Ok(db) => return db, |
| 57 | Err(err) => { |
| 58 | tracing::warn!( |
| 59 | "database at {} unreachable ({err}) — retrying in {backoff}s", |
| 60 | cfg.db_url |
| 61 | ); |
| 62 | tokio::time::sleep(std::time::Duration::from_secs(backoff)).await; |
| 63 | backoff = (backoff * 2).min(crate::constant::DB_CONNECT_BACKOFF_MAX_SECS); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | |
| 70 | pub async fn init_mem() -> Result<Database, AppError> { |
| 71 | let db = surrealdb::engine::any::connect("memory").await?; |
| 72 | db.use_ns("hezarfen").use_db("hezarfen").await?; |
| 73 | migrate(&db).await?; |
| 74 | Ok(std::sync::Arc::new(db)) |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { |
| 80 | db.query(PRE_REPAIR).await?.check()?; |
| 81 | db.query(MIGRATION).await?.check()?; |
| 82 | |
| 83 | |
| 84 | db.query(BACKFILL) |
| 85 | .bind(("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)) |
| 86 | .await? |
| 87 | .check()?; |
| 88 | Ok(()) |
| 89 | } |
| 90 | |
| 91 | #[cfg(test)] |
| 92 | mod tests { |
| 93 | #[tokio::test] |
| 94 | async fn boot_fails_chatbot_messages_left_pending() { |
| 95 | let db = super::init_mem().await.unwrap(); |
| 96 | db.query( |
| 97 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 98 | CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; |
| 99 | CREATE chatbot_message:m SET thread_id = chatbot_thread:c, user_id = user:u, |
| 100 | role = 'assistant', content = '', status = 'pending', created_at = 1; |
| 101 | CREATE chatbot_message:done SET thread_id = chatbot_thread:c, user_id = user:u, |
| 102 | role = 'assistant', content = 'hi', status = 'complete', created_at = 1;", |
| 103 | ) |
| 104 | .await |
| 105 | .unwrap() |
| 106 | .check() |
| 107 | .unwrap(); |
| 108 | |
| 109 | |
| 110 | |
| 111 | super::migrate(&db).await.unwrap(); |
| 112 | |
| 113 | let mut rows = db |
| 114 | .query("SELECT id, status, error_code, completed_at FROM chatbot_message ORDER BY id") |
| 115 | .await |
| 116 | .unwrap(); |
| 117 | let rows: Vec<serde_json::Value> = rows.take(0).unwrap(); |
| 118 | |
| 119 | let done = &rows[0]; |
| 120 | let interrupted = &rows[1]; |
| 121 | assert_eq!(done["status"], "complete"); |
| 122 | assert_eq!(done["error_code"], serde_json::Value::Null); |
| 123 | assert_eq!(interrupted["status"], "failed"); |
| 124 | assert_eq!(interrupted["error_code"], "interrupted"); |
| 125 | assert!(interrupted["completed_at"].as_i64().unwrap() > 0); |
| 126 | } |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | #[tokio::test] |
| 132 | async fn boot_spares_a_chatbot_message_pending_since_just_now() { |
| 133 | let db = super::init_mem().await.unwrap(); |
| 134 | db.query( |
| 135 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 136 | CREATE chatbot_thread:c SET user_id = user:u, created_at = 1, updated_at = 1; |
| 137 | CREATE chatbot_message:fresh SET thread_id = chatbot_thread:c, user_id = user:u, |
| 138 | role = 'assistant', content = '', status = 'pending', |
| 139 | created_at = time::unix(time::now()) * 1000 - 2000; |
| 140 | CREATE chatbot_message:old SET thread_id = chatbot_thread:c, user_id = user:u, |
| 141 | role = 'assistant', content = '', status = 'pending', |
| 142 | created_at = time::unix(time::now()) * 1000 |
| 143 | - ($stale + 1) * 1000;", |
| 144 | ) |
| 145 | .bind(("stale", crate::constant::CHATBOT_PENDING_STALE_SECS)) |
| 146 | .await |
| 147 | .unwrap() |
| 148 | .check() |
| 149 | .unwrap(); |
| 150 | |
| 151 | super::migrate(&db).await.unwrap(); |
| 152 | |
| 153 | let mut res = db |
| 154 | .query( |
| 155 | "SELECT status, error_code FROM ONLY chatbot_message:fresh; |
| 156 | SELECT VALUE status FROM ONLY chatbot_message:old;", |
| 157 | ) |
| 158 | .await |
| 159 | .unwrap(); |
| 160 | let fresh: Option<serde_json::Value> = res.take(0).unwrap(); |
| 161 | let fresh = fresh.unwrap(); |
| 162 | let old: Option<String> = res.take(1).unwrap(); |
| 163 | assert_eq!( |
| 164 | fresh["status"], "pending", |
| 165 | "a two-second-old turn is still being answered" |
| 166 | ); |
| 167 | assert_eq!(fresh["error_code"], serde_json::Value::Null); |
| 168 | assert_eq!(old.as_deref(), Some("failed"), "past the horizon it goes"); |
| 169 | } |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | #[tokio::test] |
| 175 | async fn boot_converts_positional_choices_and_keeps_the_same_option() { |
| 176 | let db = super::init_mem().await.unwrap(); |
| 177 | |
| 178 | |
| 179 | db.query( |
| 180 | "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question; |
| 181 | REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question; |
| 182 | REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question; |
| 183 | REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question; |
| 184 | DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>; |
| 185 | DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>; |
| 186 | DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>; |
| 187 | DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>; |
| 188 | DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>; |
| 189 | DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>; |
| 190 | DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>; |
| 191 | DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;", |
| 192 | ) |
| 193 | .await |
| 194 | .unwrap() |
| 195 | .check() |
| 196 | .unwrap(); |
| 197 | db.query( |
| 198 | "CREATE user:u SET username = 'u', password_hash = 'x'; |
| 199 | CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple', |
| 200 | points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1, |
| 201 | source_bank = 'bank_question:b'; |
| 202 | CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2, |
| 203 | file = 'f', content_type = 'image/png', size = 1; |
| 204 | CREATE question_image:whole SET exam = exam:e, question = exam_question:q, |
| 205 | file = 'w', content_type = 'image/png', size = 1; |
| 206 | CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u, |
| 207 | selected = 2, updated_at = 1; |
| 208 | CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple', |
| 209 | points = 3, choices = ['a', 'b'], correct = 0, created_at = 1; |
| 210 | CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1, |
| 211 | file = 'bf', content_type = 'image/png', size = 1;", |
| 212 | ) |
| 213 | .await |
| 214 | .unwrap() |
| 215 | .check() |
| 216 | .unwrap(); |
| 217 | |
| 218 | super::migrate(&db).await.unwrap(); |
| 219 | |
| 220 | let mut res = db |
| 221 | .query( |
| 222 | "SELECT choices, correct FROM ONLY exam_question:q; |
| 223 | SELECT VALUE slot FROM ONLY question_image:i; |
| 224 | SELECT VALUE slot FROM ONLY question_image:whole; |
| 225 | SELECT VALUE selected FROM ONLY exam_answer:a; |
| 226 | SELECT choices, correct FROM ONLY bank_question:b; |
| 227 | SELECT VALUE slot FROM ONLY bank_question_image:bi;", |
| 228 | ) |
| 229 | .await |
| 230 | .unwrap(); |
| 231 | let q: Option<serde_json::Value> = res.take(0).unwrap(); |
| 232 | let q = q.unwrap(); |
| 233 | let img_slot: Option<String> = res.take(1).unwrap(); |
| 234 | let whole_slot: Option<String> = res.take(2).unwrap(); |
| 235 | let selected: Option<String> = res.take(3).unwrap(); |
| 236 | let bank: Option<serde_json::Value> = res.take(4).unwrap(); |
| 237 | let bank = bank.unwrap(); |
| 238 | let bank_slot: Option<String> = res.take(5).unwrap(); |
| 239 | |
| 240 | let ids: Vec<&str> = q["choices"] |
| 241 | .as_array() |
| 242 | .unwrap() |
| 243 | .iter() |
| 244 | .map(|c| c["id"].as_str().unwrap()) |
| 245 | .collect(); |
| 246 | assert_eq!( |
| 247 | q["choices"][0]["text"], "3", |
| 248 | "option order (and so the meaning of every stored index) is preserved" |
| 249 | ); |
| 250 | assert_eq!(q["correct"], ids[1], "correct was index 1"); |
| 251 | assert_eq!( |
| 252 | img_slot.as_deref(), |
| 253 | Some(ids[2]), |
| 254 | "option picture was slot 2" |
| 255 | ); |
| 256 | assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2"); |
| 257 | assert_eq!(whole_slot, None, "a question-level picture has no index"); |
| 258 | let bank_ids: Vec<&str> = bank["choices"] |
| 259 | .as_array() |
| 260 | .unwrap() |
| 261 | .iter() |
| 262 | .map(|c| c["id"].as_str().unwrap()) |
| 263 | .collect(); |
| 264 | assert_eq!(bank["correct"], bank_ids[0]); |
| 265 | assert_eq!(bank_slot.as_deref(), Some(bank_ids[1])); |
| 266 | |
| 267 | |
| 268 | |
| 269 | db.query( |
| 270 | "UPDATE exam_question:q SET points = 7; |
| 271 | UPDATE question_image:i SET size = 2; |
| 272 | UPDATE exam_answer:a SET updated_at = 2; |
| 273 | UPDATE bank_question:b SET points = 4; |
| 274 | UPDATE bank_question_image:bi SET size = 2;", |
| 275 | ) |
| 276 | .await |
| 277 | .unwrap() |
| 278 | .check() |
| 279 | .unwrap(); |
| 280 | |
| 281 | |
| 282 | super::migrate(&db).await.unwrap(); |
| 283 | let mut res = db |
| 284 | .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q") |
| 285 | .await |
| 286 | .unwrap(); |
| 287 | let again: Vec<String> = res.take(0).unwrap(); |
| 288 | assert_eq!(again, ids, "conversion is idempotent"); |
| 289 | } |
| 290 | } |