| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use std::collections::HashMap; |
| 13 | |
| 14 | use crate::database::{Database, tx_with_retry}; |
| 15 | use crate::db::page::PagedList; |
| 16 | use crate::domain::course::CourseId; |
| 17 | use crate::domain::course_note::CourseNoteId; |
| 18 | use crate::domain::course_note_file::CourseNoteFileId; |
| 19 | use crate::domain::rag_output::{RagOutput, RagOutputId}; |
| 20 | use crate::domain::timestamp::Timestamp; |
| 21 | use crate::error::AppError; |
| 22 | use serde_json::Value; |
| 23 | use sqlx::types::Json; |
| 24 | use uuid::Uuid; |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | #[derive(Debug, sqlx::FromRow)] |
| 32 | struct RagOutputRow { |
| 33 | id: RagOutputId, |
| 34 | course_note: CourseNoteId, |
| 35 | course: CourseId, |
| 36 | payload: Json<Value>, |
| 37 | generated_at: Timestamp, |
| 38 | } |
| 39 | |
| 40 | impl RagOutputRow { |
| 41 | fn into_rag_output(self, sources: Vec<CourseNoteFileId>) -> RagOutput { |
| 42 | RagOutput { |
| 43 | id: self.id, |
| 44 | course_note: self.course_note, |
| 45 | course: self.course, |
| 46 | sources, |
| 47 | payload: self.payload, |
| 48 | generated_at: self.generated_at, |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | async fn sources_for_many( |
| 58 | db: &Database, |
| 59 | outputs: &[RagOutputId], |
| 60 | ) -> Result<HashMap<Uuid, Vec<CourseNoteFileId>>, AppError> { |
| 61 | let keys: Vec<Uuid> = outputs.iter().map(|output| output.uuid()).collect(); |
| 62 | let links = sqlx::query!( |
| 63 | r#"SELECT output, source AS "source: CourseNoteFileId" |
| 64 | FROM rag_output_source WHERE output = ANY($1) ORDER BY source"#, |
| 65 | &keys |
| 66 | ) |
| 67 | .fetch_all(db) |
| 68 | .await?; |
| 69 | let mut grouped: HashMap<Uuid, Vec<CourseNoteFileId>> = HashMap::new(); |
| 70 | for link in links { |
| 71 | grouped.entry(link.output).or_default().push(link.source); |
| 72 | } |
| 73 | Ok(grouped) |
| 74 | } |
| 75 | |
| 76 | |
| 77 | async fn sources_for( |
| 78 | db: &Database, |
| 79 | output: &RagOutputId, |
| 80 | ) -> Result<Vec<CourseNoteFileId>, AppError> { |
| 81 | let mut grouped = sources_for_many(db, std::slice::from_ref(output)).await?; |
| 82 | Ok(grouped.remove(&output.uuid()).unwrap_or_default()) |
| 83 | } |
| 84 | |
| 85 | pub async fn create( |
| 86 | db: &Database, |
| 87 | note: &CourseNoteId, |
| 88 | course: &CourseId, |
| 89 | mut sources: Vec<CourseNoteFileId>, |
| 90 | payload: Value, |
| 91 | ) -> Result<RagOutput, AppError> { |
| 92 | |
| 93 | |
| 94 | sources.sort_by_key(|file| file.uuid()); |
| 95 | let keys: Vec<Uuid> = sources.iter().map(|file| file.uuid()).collect(); |
| 96 | let id = RagOutputId::generate(); |
| 97 | let generated_at = Timestamp::now(); |
| 98 | |
| 99 | |
| 100 | let id_u = id.uuid(); |
| 101 | let note_u = note.uuid(); |
| 102 | let course_u = course.uuid(); |
| 103 | let at = generated_at.as_millis(); |
| 104 | let row = tx_with_retry(db, false, async move |tx| { |
| 105 | let created = sqlx::query_as!( |
| 106 | RagOutputRow, |
| 107 | r#"INSERT INTO rag_output (id, course_note, course, payload, generated_at) |
| 108 | VALUES ($1, $2, $3, $4, $5) |
| 109 | RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", |
| 110 | course AS "course: CourseId", |
| 111 | payload AS "payload: Json<Value>", |
| 112 | generated_at AS "generated_at: Timestamp""#, |
| 113 | id_u, |
| 114 | note_u, |
| 115 | course_u, |
| 116 | &payload, |
| 117 | at |
| 118 | ) |
| 119 | .fetch_one(&mut *tx) |
| 120 | .await?; |
| 121 | sqlx::query!( |
| 122 | "INSERT INTO rag_output_source (output, source) |
| 123 | SELECT $1, s FROM unnest($2::uuid[]) AS t(s)", |
| 124 | created.id.uuid(), |
| 125 | &keys |
| 126 | ) |
| 127 | .execute(&mut *tx) |
| 128 | .await?; |
| 129 | Ok(created) |
| 130 | }) |
| 131 | .await?; |
| 132 | Ok(row.into_rag_output(sources)) |
| 133 | } |
| 134 | |
| 135 | pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> { |
| 136 | let row = sqlx::query_as!( |
| 137 | RagOutputRow, |
| 138 | r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", |
| 139 | course AS "course: CourseId", |
| 140 | payload AS "payload: Json<Value>", |
| 141 | generated_at AS "generated_at: Timestamp" |
| 142 | FROM rag_output WHERE id = $1"#, |
| 143 | id.uuid() |
| 144 | ) |
| 145 | .fetch_optional(db) |
| 146 | .await?; |
| 147 | match row { |
| 148 | Some(row) => { |
| 149 | let sources = sources_for(db, &row.id).await?; |
| 150 | Ok(Some(row.into_rag_output(sources))) |
| 151 | } |
| 152 | None => Ok(None), |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | |
| 157 | pub async fn list_for( |
| 158 | db: &Database, |
| 159 | note: &CourseNoteId, |
| 160 | limit: Option<i64>, |
| 161 | offset: i64, |
| 162 | ) -> Result<(Vec<RagOutput>, i64), AppError> { |
| 163 | let (rows, total) = PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC") |
| 164 | .bind(note.uuid()) |
| 165 | .run::<RagOutputRow>(limit, offset, db) |
| 166 | .await?; |
| 167 | let ids: Vec<RagOutputId> = rows.iter().map(|row| row.id).collect(); |
| 168 | let grouped = sources_for_many(db, &ids).await?; |
| 169 | let items = rows |
| 170 | .into_iter() |
| 171 | .map(|row| { |
| 172 | let sources = grouped.get(&row.id.uuid()).cloned().unwrap_or_default(); |
| 173 | row.into_rag_output(sources) |
| 174 | }) |
| 175 | .collect(); |
| 176 | Ok((items, total)) |
| 177 | } |
| 178 | |
| 179 | pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> { |
| 180 | let id_u = id.uuid(); |
| 181 | let (row, sources) = tx_with_retry(db, false, async move |tx| { |
| 182 | let sources = sqlx::query!( |
| 183 | r#"SELECT source AS "source: CourseNoteFileId" |
| 184 | FROM rag_output_source WHERE output = $1 ORDER BY source"#, |
| 185 | id_u |
| 186 | ) |
| 187 | .fetch_all(&mut *tx) |
| 188 | .await? |
| 189 | .into_iter() |
| 190 | .map(|link| link.source) |
| 191 | .collect::<Vec<_>>(); |
| 192 | sqlx::query!("DELETE FROM rag_output_source WHERE output = $1", id_u) |
| 193 | .execute(&mut *tx) |
| 194 | .await?; |
| 195 | sqlx::query_as!( |
| 196 | RagOutputRow, |
| 197 | r#"DELETE FROM rag_output WHERE id = $1 |
| 198 | RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId", |
| 199 | course AS "course: CourseId", |
| 200 | payload AS "payload: Json<Value>", |
| 201 | generated_at AS "generated_at: Timestamp""#, |
| 202 | id_u |
| 203 | ) |
| 204 | .fetch_optional(&mut *tx) |
| 205 | .await? |
| 206 | .map(|row| (row, sources)) |
| 207 | .ok_or(AppError::NotFound) |
| 208 | }) |
| 209 | .await?; |
| 210 | Ok(row.into_rag_output(sources)) |
| 211 | } |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { |
| 217 | sqlx::query!( |
| 218 | "DELETE FROM rag_output_source WHERE output IN |
| 219 | (SELECT id FROM rag_output WHERE course_note = $1)", |
| 220 | note.uuid() |
| 221 | ) |
| 222 | .execute(db) |
| 223 | .await?; |
| 224 | sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid()) |
| 225 | .execute(db) |
| 226 | .await?; |
| 227 | Ok(()) |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | pub async fn replace_for_note( |
| 238 | db: &Database, |
| 239 | note: &CourseNoteId, |
| 240 | course: &CourseId, |
| 241 | sources: Vec<CourseNoteFileId>, |
| 242 | payload: Value, |
| 243 | ) -> Result<RagOutput, AppError> { |
| 244 | let created = create(db, note, course, sources, payload).await?; |
| 245 | |
| 246 | |
| 247 | |
| 248 | sqlx::query!( |
| 249 | "DELETE FROM rag_output_source WHERE output IN |
| 250 | (SELECT id FROM rag_output WHERE course_note = $1 AND id < $2)", |
| 251 | note.uuid(), |
| 252 | created.id.uuid() |
| 253 | ) |
| 254 | .execute(db) |
| 255 | .await?; |
| 256 | sqlx::query!( |
| 257 | "DELETE FROM rag_output WHERE course_note = $1 AND id < $2", |
| 258 | note.uuid(), |
| 259 | created.id.uuid() |
| 260 | ) |
| 261 | .execute(db) |
| 262 | .await?; |
| 263 | Ok(created) |
| 264 | } |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { |
| 273 | sqlx::query!( |
| 274 | "DELETE FROM rag_output_source WHERE source = $1", |
| 275 | file.uuid() |
| 276 | ) |
| 277 | .execute(db) |
| 278 | .await?; |
| 279 | Ok(()) |
| 280 | } |
| 281 | |
| 282 | #[cfg(test)] |
| 283 | mod tests { |
| 284 | use super::*; |
| 285 | use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 286 | use crate::domain::course_note::CourseNote; |
| 287 | use crate::domain::course_note::CourseNoteContent; |
| 288 | use crate::domain::course_note::CourseNoteTitle; |
| 289 | use crate::domain::course_note_file::CourseNoteFile; |
| 290 | use crate::domain::course_note_file::FileContentType; |
| 291 | use crate::domain::course_note_file::FileName; |
| 292 | use serde_json::json; |
| 293 | |
| 294 | |
| 295 | async fn a_person(db: &Database) -> crate::domain::user::UserId { |
| 296 | let user = crate::domain::user::UserId::generate(); |
| 297 | sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") |
| 298 | .bind(user.uuid()) |
| 299 | .bind(format!("rag-{}", &user.key()[30..])) |
| 300 | .execute(db) |
| 301 | .await |
| 302 | .unwrap(); |
| 303 | user |
| 304 | } |
| 305 | |
| 306 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 307 | |
| 308 | let creator = a_person(db).await; |
| 309 | let course = crate::db::course::create( |
| 310 | db, |
| 311 | &creator, |
| 312 | CourseTitle::try_new("c").unwrap(), |
| 313 | CourseDescription::try_new("").unwrap(), |
| 314 | CourseKind::try_new("course").unwrap(), |
| 315 | ) |
| 316 | .await |
| 317 | .unwrap(); |
| 318 | crate::db::course_note::create( |
| 319 | db, |
| 320 | course.get_id(), |
| 321 | &creator, |
| 322 | CourseNoteTitle::try_new(title).unwrap(), |
| 323 | CourseNoteContent::try_new("body").unwrap(), |
| 324 | ) |
| 325 | .await |
| 326 | .unwrap() |
| 327 | } |
| 328 | |
| 329 | async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile { |
| 330 | crate::db::course_note_file::insert( |
| 331 | db, |
| 332 | CourseNoteFile::new( |
| 333 | note.get_id(), |
| 334 | FileName::try_new("f").unwrap(), |
| 335 | FileContentType::try_new("text/plain").unwrap(), |
| 336 | 1, |
| 337 | ), |
| 338 | ) |
| 339 | .await |
| 340 | .unwrap() |
| 341 | } |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | #[tokio::test] |
| 347 | async fn create_reads_back_and_cascades_from_the_note() { |
| 348 | let (db, _leases) = crate::database::init_test_db().await; |
| 349 | let note = note_of(&db, "n").await; |
| 350 | let file = a_file(&db, ¬e).await; |
| 351 | let row = create( |
| 352 | &db, |
| 353 | note.get_id(), |
| 354 | note.get_course(), |
| 355 | vec![file.get_id().clone()], |
| 356 | json!({"answer": "x"}), |
| 357 | ) |
| 358 | .await |
| 359 | .unwrap(); |
| 360 | let read_back = read(&db, row.get_id()).await.unwrap().unwrap(); |
| 361 | assert_eq!(read_back.get_payload(), &json!({"answer": "x"})); |
| 362 | assert_eq!(read_back.get_sources(), &[file.get_id().clone()]); |
| 363 | |
| 364 | let refused = sqlx::query("DELETE FROM course_note_file WHERE id = $1") |
| 365 | .bind(file.get_id().uuid()) |
| 366 | .execute(&db) |
| 367 | .await; |
| 368 | let err = refused.unwrap_err(); |
| 369 | assert!(crate::database::foreign_key_violation(&err), "{err}"); |
| 370 | |
| 371 | delete_for_note(&db, note.get_id()).await.unwrap(); |
| 372 | assert!(read(&db, row.get_id()).await.unwrap().is_none()); |
| 373 | |
| 374 | sqlx::query("DELETE FROM course_note_file WHERE id = $1") |
| 375 | .bind(file.get_id().uuid()) |
| 376 | .execute(&db) |
| 377 | .await |
| 378 | .unwrap(); |
| 379 | } |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | #[tokio::test] |
| 386 | async fn replace_is_newest_wins_and_source_cascade_empties_the_citations() { |
| 387 | let (db, _leases) = crate::database::init_test_db().await; |
| 388 | let note = note_of(&db, "n").await; |
| 389 | let file = a_file(&db, ¬e).await; |
| 390 | let first = create( |
| 391 | &db, |
| 392 | note.get_id(), |
| 393 | note.get_course(), |
| 394 | vec![file.get_id().clone()], |
| 395 | json!({"v": 1}), |
| 396 | ) |
| 397 | .await |
| 398 | .unwrap(); |
| 399 | let second = replace_for_note( |
| 400 | &db, |
| 401 | note.get_id(), |
| 402 | note.get_course(), |
| 403 | vec![file.get_id().clone()], |
| 404 | json!({"v": 2}), |
| 405 | ) |
| 406 | .await |
| 407 | .unwrap(); |
| 408 | let (rows, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); |
| 409 | assert_eq!(total, 1); |
| 410 | assert_eq!(rows[0].get_id(), second.get_id()); |
| 411 | assert!(first.get_id() != second.get_id()); |
| 412 | |
| 413 | delete_with_source(&db, file.get_id()).await.unwrap(); |
| 414 | let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap(); |
| 415 | assert_eq!(total, 1); |
| 416 | let survivor = read(&db, second.get_id()).await.unwrap().unwrap(); |
| 417 | assert!(survivor.get_sources().is_empty()); |
| 418 | |
| 419 | sqlx::query("DELETE FROM course_note_file WHERE id = $1") |
| 420 | .bind(file.get_id().uuid()) |
| 421 | .execute(&db) |
| 422 | .await |
| 423 | .unwrap(); |
| 424 | } |
| 425 | |
| 426 | |
| 427 | |
| 428 | #[tokio::test] |
| 429 | async fn delete_returns_the_row_then_refuses() { |
| 430 | let (db, _leases) = crate::database::init_test_db().await; |
| 431 | let note = note_of(&db, "n").await; |
| 432 | let file = a_file(&db, ¬e).await; |
| 433 | let row = create( |
| 434 | &db, |
| 435 | note.get_id(), |
| 436 | note.get_course(), |
| 437 | vec![file.get_id().clone()], |
| 438 | json!({}), |
| 439 | ) |
| 440 | .await |
| 441 | .unwrap(); |
| 442 | let gone = delete(&db, row.get_id()).await.unwrap(); |
| 443 | assert_eq!(gone.get_id(), row.get_id()); |
| 444 | assert_eq!(gone.get_sources(), &[file.get_id().clone()]); |
| 445 | assert!(matches!( |
| 446 | delete(&db, row.get_id()).await, |
| 447 | Err(AppError::NotFound) |
| 448 | )); |
| 449 | } |
| 450 | } |