| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use crate::constant::DEFAULT_MAX_CHATBOT_THREADS; |
| 8 | use crate::database::{Database, tx_with_retry}; |
| 9 | use crate::db::page::PagedList; |
| 10 | use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; |
| 11 | use crate::domain::timestamp::Timestamp; |
| 12 | use crate::domain::user::UserId; |
| 13 | use crate::error::AppError; |
| 14 | use sqlx::query_as; |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | pub async fn create_capped( |
| 34 | db: &Database, |
| 35 | user: &UserId, |
| 36 | title: Option<ChatbotThreadTitle>, |
| 37 | ) -> Result<ChatbotThread, AppError> { |
| 38 | let now = Timestamp::now(); |
| 39 | match query_as!( |
| 40 | ChatbotThread, |
| 41 | "WITH seat AS ( |
| 42 | UPDATE app_user SET chatbot_thread_count = chatbot_thread_count + 1 |
| 43 | WHERE id = $1 |
| 44 | AND chatbot_thread_count < COALESCE( |
| 45 | (SELECT max_chatbot_threads FROM settings WHERE id = 'school'), |
| 46 | $2) |
| 47 | RETURNING 1) |
| 48 | INSERT INTO chatbot_thread (id, user_id, title, created_at, updated_at) |
| 49 | SELECT $3, $1, $4, $5, $5 |
| 50 | WHERE EXISTS (SELECT 1 FROM seat) |
| 51 | RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ |
| 52 | created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", |
| 53 | user.uuid(), |
| 54 | DEFAULT_MAX_CHATBOT_THREADS, |
| 55 | ChatbotThreadId::generate().uuid(), |
| 56 | title.map(|t| t.as_str().to_string()), |
| 57 | now.as_millis(), |
| 58 | ) |
| 59 | .fetch_optional(db) |
| 60 | .await? |
| 61 | { |
| 62 | Some(saved) => Ok(saved), |
| 63 | |
| 64 | |
| 65 | None => Err(AppError::Conflict( |
| 66 | "you have reached the school's limit on saved threads — delete one first", |
| 67 | )), |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | |
| 72 | |
| 73 | pub async fn list_for_user( |
| 74 | db: &Database, |
| 75 | user: &UserId, |
| 76 | limit: Option<i64>, |
| 77 | offset: i64, |
| 78 | ) -> Result<(Vec<ChatbotThread>, i64), AppError> { |
| 79 | PagedList::new( |
| 80 | "chatbot_thread WHERE user_id = $1", |
| 81 | "ORDER BY updated_at DESC, id DESC", |
| 82 | ) |
| 83 | .bind(user.uuid()) |
| 84 | .run(limit, offset, db) |
| 85 | .await |
| 86 | } |
| 87 | |
| 88 | |
| 89 | pub async fn count_for_user(db: &Database, user: &UserId) -> Result<usize, AppError> { |
| 90 | let row = sqlx::query!( |
| 91 | "SELECT count(*) AS threads FROM chatbot_thread WHERE user_id = $1", |
| 92 | user.uuid() |
| 93 | ) |
| 94 | .fetch_one(db) |
| 95 | .await?; |
| 96 | Ok(row.threads.unwrap_or(0).max(0) as usize) |
| 97 | } |
| 98 | |
| 99 | |
| 100 | |
| 101 | pub async fn read_for( |
| 102 | db: &Database, |
| 103 | id: &ChatbotThreadId, |
| 104 | user: &UserId, |
| 105 | ) -> Result<Option<ChatbotThread>, AppError> { |
| 106 | let thread = query_as!( |
| 107 | ChatbotThread, |
| 108 | "SELECT id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM chatbot_thread WHERE id = $1", |
| 109 | id.uuid() |
| 110 | ) |
| 111 | .fetch_optional(db) |
| 112 | .await?; |
| 113 | Ok(thread.filter(|thread| &thread.user_id == user)) |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | pub async fn rename( |
| 130 | db: &Database, |
| 131 | thread: &ChatbotThread, |
| 132 | title: Option<ChatbotThreadTitle>, |
| 133 | ) -> Result<ChatbotThread, AppError> { |
| 134 | let updated = query_as!( |
| 135 | ChatbotThread, |
| 136 | "UPDATE chatbot_thread SET title = $2, updated_at = GREATEST($3, updated_at + 1) \ |
| 137 | WHERE id = $1 \ |
| 138 | RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ |
| 139 | created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", |
| 140 | thread.get_id().uuid(), |
| 141 | title.map(|t| t.as_str().to_string()), |
| 142 | Timestamp::now().as_millis(), |
| 143 | ) |
| 144 | .fetch_optional(db) |
| 145 | .await?; |
| 146 | updated.ok_or(AppError::NotFound) |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> { |
| 162 | tx_with_retry(db, false, async move |tx| { |
| 163 | |
| 164 | |
| 165 | sqlx::query!( |
| 166 | "DELETE FROM chatbot_message WHERE thread_id = $1", |
| 167 | thread.get_id().uuid() |
| 168 | ) |
| 169 | .execute(&mut *tx) |
| 170 | .await?; |
| 171 | let gone = query_as!( |
| 172 | ChatbotThread, |
| 173 | "DELETE FROM chatbot_thread WHERE id = $1 \ |
| 174 | RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ |
| 175 | created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", |
| 176 | thread.get_id().uuid() |
| 177 | ) |
| 178 | .fetch_optional(&mut *tx) |
| 179 | .await?; |
| 180 | if let Some(gone) = &gone { |
| 181 | sqlx::query!( |
| 182 | "UPDATE app_user SET chatbot_thread_count = GREATEST(chatbot_thread_count - 1, 0) \ |
| 183 | WHERE id = $1", |
| 184 | gone.get_user_id().uuid() |
| 185 | ) |
| 186 | .execute(&mut *tx) |
| 187 | .await?; |
| 188 | } |
| 189 | gone.ok_or(AppError::NotFound) |
| 190 | }) |
| 191 | .await |
| 192 | } |
| 193 | #[cfg(test)] |
| 194 | mod tests { |
| 195 | use super::*; |
| 196 | use sqlx::Row as _; |
| 197 | |
| 198 | use crate::db::chatbot_message; |
| 199 | use crate::domain::chatbot_message::ChatContent; |
| 200 | use crate::domain::settings::{Settings, SettingsParams}; |
| 201 | |
| 202 | |
| 203 | const U: &str = "019732e3-7b00-7000-8000-00000000aaaa"; |
| 204 | |
| 205 | |
| 206 | |
| 207 | async fn stored(db: &Database) -> (i64, usize) { |
| 208 | let counter = sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1") |
| 209 | .bind(UserId::from_key(U).uuid()) |
| 210 | .fetch_one(db) |
| 211 | .await |
| 212 | .unwrap() |
| 213 | .try_get::<i64, _>(0) |
| 214 | .unwrap(); |
| 215 | let rows = sqlx::query("SELECT count(*) FROM chatbot_thread") |
| 216 | .fetch_one(db) |
| 217 | .await |
| 218 | .unwrap() |
| 219 | .try_get::<i64, _>(0) |
| 220 | .unwrap(); |
| 221 | (counter, rows as usize) |
| 222 | } |
| 223 | |
| 224 | async fn a_user_capped_at(threads: i64) -> (Database, crate::database::TestDatabases) { |
| 225 | let (db, leases) = crate::database::init_test_db().await; |
| 226 | sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'u', 0)") |
| 227 | .bind(UserId::from_key(U).uuid()) |
| 228 | .execute(&db) |
| 229 | .await |
| 230 | .unwrap(); |
| 231 | crate::db::settings::save( |
| 232 | &db, |
| 233 | Settings::try_new(SettingsParams { |
| 234 | max_chatbot_threads: threads, |
| 235 | ..Settings::defaults().params() |
| 236 | }) |
| 237 | .unwrap(), |
| 238 | ) |
| 239 | .await |
| 240 | .unwrap(); |
| 241 | (db, leases) |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | #[tokio::test] |
| 248 | async fn a_capped_create_moves_the_counter_with_the_row() { |
| 249 | let (db, _leases) = a_user_capped_at(1).await; |
| 250 | let user = UserId::from_key(U); |
| 251 | |
| 252 | create_capped(&db, &user, None).await.expect("first thread"); |
| 253 | assert_eq!(stored(&db).await, (1, 1)); |
| 254 | |
| 255 | let refused = create_capped(&db, &user, None).await; |
| 256 | assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap"); |
| 257 | assert_eq!( |
| 258 | stored(&db).await, |
| 259 | (1, 1), |
| 260 | "a refused create advances neither" |
| 261 | ); |
| 262 | } |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | #[tokio::test] |
| 269 | async fn a_turn_writes_its_thread_and_dies_with_it() { |
| 270 | let (db, _leases) = a_user_capped_at(2).await; |
| 271 | let user = UserId::from_key(U); |
| 272 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 273 | let opened = thread.get_updated_at().as_millis(); |
| 274 | |
| 275 | let say = || ChatContent::try_new("selam").unwrap(); |
| 276 | chatbot_message::append_user(&db, thread.get_id(), &user, say()) |
| 277 | .await |
| 278 | .expect("append"); |
| 279 | let stamped = read_for(&db, thread.get_id(), &user) |
| 280 | .await |
| 281 | .expect("re-read") |
| 282 | .expect("still there") |
| 283 | .get_updated_at() |
| 284 | .as_millis(); |
| 285 | |
| 286 | |
| 287 | |
| 288 | assert!(stamped > opened, "{stamped} !> {opened}"); |
| 289 | |
| 290 | let id = thread.get_id().clone(); |
| 291 | delete(&db, thread).await.expect("delete"); |
| 292 | let orphan = chatbot_message::append_user(&db, &id, &user, say()).await; |
| 293 | assert!( |
| 294 | matches!(orphan, Err(AppError::NotFound)), |
| 295 | "a turn on a deleted thread must be refused: {orphan:?}" |
| 296 | ); |
| 297 | assert_eq!( |
| 298 | chatbot_message::list_for_thread(&db, &id, None, 0) |
| 299 | .await |
| 300 | .expect("list") |
| 301 | .1, |
| 302 | 0, |
| 303 | "the refused turn wrote nothing" |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | #[tokio::test] |
| 327 | async fn a_stamp_ahead_of_the_clock_still_climbs() { |
| 328 | const LEAD: i64 = 1_000; |
| 329 | |
| 330 | let (db, _leases) = a_user_capped_at(1).await; |
| 331 | let user = UserId::from_key(U); |
| 332 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 333 | |
| 334 | let parked = Timestamp::now().as_millis() + LEAD; |
| 335 | sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2") |
| 336 | .bind(parked) |
| 337 | .bind(thread.get_id().uuid()) |
| 338 | .execute(&db) |
| 339 | .await |
| 340 | .unwrap(); |
| 341 | |
| 342 | for _ in 0..2 { |
| 343 | chatbot_message::append_user( |
| 344 | &db, |
| 345 | thread.get_id(), |
| 346 | &user, |
| 347 | ChatContent::try_new("selam").unwrap(), |
| 348 | ) |
| 349 | .await |
| 350 | .expect("append"); |
| 351 | } |
| 352 | let stamped = read_for(&db, thread.get_id(), &user) |
| 353 | .await |
| 354 | .expect("re-read") |
| 355 | .expect("still there") |
| 356 | .get_updated_at() |
| 357 | .as_millis(); |
| 358 | |
| 359 | assert!( |
| 360 | Timestamp::now().as_millis() < parked, |
| 361 | "the clock caught the {LEAD}ms lead up during two appends, so this \ |
| 362 | probe proves nothing" |
| 363 | ); |
| 364 | assert_eq!( |
| 365 | stamped, |
| 366 | parked + 2, |
| 367 | "two appends off a stamp of {parked} must leave {}: a stamp that \ |
| 368 | follows the clock instead is one an unchanged-row UPDATE elides", |
| 369 | parked + 2 |
| 370 | ); |
| 371 | } |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 394 | async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { |
| 395 | |
| 396 | |
| 397 | let (db, _leases) = a_user_capped_at(6).await; |
| 398 | let user = UserId::from_key(U); |
| 399 | |
| 400 | async fn append( |
| 401 | db: &Database, |
| 402 | id: &ChatbotThreadId, |
| 403 | user: &UserId, |
| 404 | ) -> Result<(), AppError> { |
| 405 | chatbot_message::append_user(db, id, user, ChatContent::try_new("selam").unwrap()) |
| 406 | .await |
| 407 | .map(|_| ()) |
| 408 | } |
| 409 | |
| 410 | |
| 411 | { |
| 412 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 413 | let id = thread.get_id().clone(); |
| 414 | let dropped = delete(&db, thread).await; |
| 415 | assert!( |
| 416 | !matches!(dropped, Err(AppError::Db(_))), |
| 417 | "delete-first: a delete must be answered, not 500: {dropped:?}" |
| 418 | ); |
| 419 | assert!( |
| 420 | read_for(&db, &id, &user).await.unwrap().is_none(), |
| 421 | "delete-first: the thread is still there after delete: {dropped:?}" |
| 422 | ); |
| 423 | let turn = append(&db, &id, &user).await; |
| 424 | assert!( |
| 425 | !matches!(turn, Err(AppError::Db(_))), |
| 426 | "delete-first: a turn must be answered, not 500: {turn:?}" |
| 427 | ); |
| 428 | assert_eq!( |
| 429 | chatbot_message::list_for_thread(&db, &id, None, 0) |
| 430 | .await |
| 431 | .unwrap() |
| 432 | .1, |
| 433 | 0, |
| 434 | "a turn outlived its thread" |
| 435 | ); |
| 436 | } |
| 437 | |
| 438 | |
| 439 | { |
| 440 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 441 | let id = thread.get_id().clone(); |
| 442 | let turn = append(&db, &id, &user).await; |
| 443 | assert!( |
| 444 | turn.is_ok(), |
| 445 | "write-first: the turn must land before the delete: {turn:?}" |
| 446 | ); |
| 447 | let dropped = delete(&db, thread).await; |
| 448 | assert!( |
| 449 | !matches!(dropped, Err(AppError::Db(_))), |
| 450 | "write-first: a delete must be answered, not 500: {dropped:?}" |
| 451 | ); |
| 452 | assert!( |
| 453 | read_for(&db, &id, &user).await.unwrap().is_none(), |
| 454 | "write-first: the thread is still there" |
| 455 | ); |
| 456 | assert_eq!( |
| 457 | chatbot_message::list_for_thread(&db, &id, None, 0) |
| 458 | .await |
| 459 | .unwrap() |
| 460 | .1, |
| 461 | 0, |
| 462 | "a turn outlived its thread" |
| 463 | ); |
| 464 | } |
| 465 | |
| 466 | |
| 467 | let mut swept = 0; |
| 468 | for round in 0..4 { |
| 469 | let thread = create_capped(&db, &user, None).await.expect("thread"); |
| 470 | let id = thread.get_id().clone(); |
| 471 | |
| 472 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 473 | let drop_it = { |
| 474 | let (db, thread, gate) = (db.clone(), thread, gate.clone()); |
| 475 | tokio::spawn(async move { |
| 476 | gate.wait().await; |
| 477 | delete(&db, thread).await |
| 478 | }) |
| 479 | }; |
| 480 | let turn = { |
| 481 | let (id, db, user, gate) = (id.clone(), db.clone(), user, gate); |
| 482 | tokio::spawn(async move { |
| 483 | gate.wait().await; |
| 484 | append(&db, &id, &user).await |
| 485 | }) |
| 486 | }; |
| 487 | let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); |
| 488 | assert!( |
| 489 | !matches!(turn, Err(AppError::Db(_))), |
| 490 | "round {round}: a raced turn must be answered, not 500: {turn:?}" |
| 491 | ); |
| 492 | |
| 493 | |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | let parent_gone = read_for(&db, &id, &user).await.unwrap().is_none(); |
| 500 | if let Err(AppError::Db(err)) = &drop_it { |
| 501 | let lost_the_gap = crate::database::foreign_key_violation(err) && !parent_gone; |
| 502 | assert!( |
| 503 | lost_the_gap, |
| 504 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 505 | ); |
| 506 | } |
| 507 | if parent_gone { |
| 508 | swept += 1; |
| 509 | assert_eq!( |
| 510 | chatbot_message::list_for_thread(&db, &id, None, 0) |
| 511 | .await |
| 512 | .unwrap() |
| 513 | .1, |
| 514 | 0, |
| 515 | "round {round}: a turn outlived its thread" |
| 516 | ); |
| 517 | } else if drop_it.is_ok() { |
| 518 | panic!("round {round}: the delete reported success but the thread is still there"); |
| 519 | } |
| 520 | } |
| 521 | eprintln!( |
| 522 | "chatbot_thread::delete raced by a turn: {swept}/4 concurrent rounds deleted the thread" |
| 523 | ); |
| 524 | } |
| 525 | } |