forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBf77d48aAhmet Kaan Gümüş4 months ago152 commits

database.rs290 lines, 12.7 KiBHistoryRawDownload
1//! SurrealDB connection (WebSocket to a server; in-memory for tests) + schema.
2
3use surrealdb::Surreal;
4use surrealdb::engine::any::Any;
5use surrealdb::opt::auth::Root;
6
7use crate::config::Config;
8use crate::constant::{BACKFILL, CHATBOT_PENDING_STALE_SECS, MIGRATION, PRE_REPAIR};
9use crate::error::AppError;
10
11/// The shared database handle.
12///
13/// `Arc` is load-bearing, not decoration. `Surreal`'s own `Clone` mints a
14/// fresh server-side session per clone (`Uuid::new_v4()` + a fire-and-forget
15/// `SessionId::Clone` to the router, SDK `lib.rs:340`), and axum clones the
16/// application state on every request — so a bare `Surreal<Any>` here means a
17/// new session, and a matching `SessionId::Drop`, for each request served.
18/// Under concurrency those lifecycle events race the queries riding on them:
19/// sessions disappear ("Session not found"), and a session whose signin has
20/// not been replayed answers "Anonymous access not allowed" / "Specify a
21/// namespace" — the same strings [`crate::error::is_session_replay_error`]
22/// treats as a transient reconnect, so the failures masquerade as one.
23///
24/// Cloning the `Arc` shares the single session established at boot instead.
25pub type Database = std::sync::Arc<Surreal<Any>>;
26
27/// Connect to the SurrealDB server, sign in as root, and apply the schema.
28pub 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/// Dial the database, retrying until it answers.
43///
44/// Never gives up, because giving up is worse than waiting: the database is
45/// normally a sibling container booting in parallel, and a process that exits
46/// on the first refusal gets restarted by the runtime, fails again in ~100ms,
47/// and burns its whole restart budget inside a second — leaving the backend
48/// permanently down over a startup skew that would have cleared on its own.
49///
50/// Only the dial is retried. Bad credentials or a broken migration still fail
51/// hard, since no amount of waiting fixes those.
52async 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/// A fresh in-memory database with the schema applied. For tests.
70pub 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/// Apply the schema + backfills. Idempotent — `init` runs it on every boot,
78/// and tests re-run it on a live handle to simulate a second boot.
79pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> {
80 db.query(PRE_REPAIR).await?.check()?;
81 db.query(MIGRATION).await?.check()?;
82 // Bound, not baked into the SQL string: a `const` cannot be interpolated
83 // into another `const`, and a hand-copied 300000 would drift silently.
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)]
92mod 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 // A second boot: the task that would have answered `m` died with the
110 // previous process, so the row is failed rather than left waiting.
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 // An already-answered turn is untouched; the pending one is failed.
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 /// The other half of the sweep: a restart seconds after a dispatch must not
129 /// kill the turn — the answering task may still be alive on the other side
130 /// of the bridge, and the row is not yet past the stale horizon.
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 /// A row written before choices had ids survives the retyped columns: it is
172 /// converted, it is writable again, and its stored *position* still names
173 /// the same option — a wrong remap here silently regrades exams.
174 #[tokio::test]
175 async fn boot_converts_positional_choices_and_keeps_the_same_option() {
176 let db = super::init_mem().await.unwrap();
177 // Roll the columns back to their pre-2026-07-24 shapes and write the
178 // kind of row an older binary left behind, `source_bank` included.
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 // Writable again — every one of these failed coercion before the
268 // backfill existed, and `source_bank` outlived its own column.
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 // A second boot re-mints nothing.
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}