forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

course_notes.rs805 lines, 32.8 KiBHistoryRawDownload
1//! Course notes: a teacher-authored note attached to a course, with file
2//! attachments. Mirrors [`super::notes`] (personal notes) handler for
3//! handler, with authorization swapped for the course-management wall:
4//! writes need [`super::courses::can_manage_course`] (its creator or a
5//! manager/admin, while teacher+), reads need
6//! [`super::courses::can_view_course`] (the above, or anyone the course
7//! reaches).
8
9use crate::tenant::ResolvedTenant;
10use crate::web::tenant_state::State;
11use axum::Json;
12use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
13use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
14use axum::http::{HeaderValue, StatusCode};
15use axum::response::{IntoResponse, Response};
16use serde::{Deserialize, Serialize};
17use utoipa::{IntoParams, ToSchema};
18use utoipa_axum::router::OpenApiRouter;
19use utoipa_axum::routes;
20
21use crate::ai::rag::spawn_index;
22use crate::constant::{AI_RAG_INDEX_CAPABILITY, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
23use crate::database::Database;
24use crate::domain::course::{Course, CourseId};
25use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle};
26use crate::domain::course_note_file::{
27 CourseNoteFile, CourseNoteFileId, FileContentType, FileName,
28};
29use crate::domain::rag_output::{RagOutput, RagOutputId};
30use crate::error::{AppError, ErrorResponse, ValidationError};
31use crate::module::Module;
32use crate::service;
33use crate::service::course::{can_manage_course, can_view_course};
34use crate::state::AppState;
35
36use super::notes::content_disposition;
37use super::{
38 CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, ai_unavailable, blob_path,
39 read_upload, remove_blob,
40};
41
42pub fn routes() -> OpenApiRouter<AppState> {
43 // Same body-cap split as `notes`' file routes: the server-wide hard
44 // ceiling plus multipart framing headroom, with the school's actual
45 // (usually smaller) limit enforced while the stream is read.
46 let files = OpenApiRouter::new()
47 .routes(routes!(upload_file, list_files))
48 .routes(routes!(download_file, delete_file))
49 .layer(DefaultBodyLimit::max(
50 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
51 ));
52 OpenApiRouter::new()
53 .routes(routes!(create, list))
54 .routes(routes!(get_one, update, delete_one))
55 .routes(routes!(list_rag))
56 .routes(routes!(reindex_rag))
57 .routes(routes!(delete_rag))
58 .merge(files)
59}
60
61/// The note plus its course, or a 404 — every entity handler here gates on
62/// the parent course, so they always travel together.
63async fn note_with_course(id: String, db: Database) -> Result<(CourseNote, Course), AppError> {
64 let id = CourseNoteId::from_key(&id);
65 let note = service::course_note::read(&db, &id)
66 .await?
67 .ok_or(AppError::NotFound)?;
68 let course = crate::service::course::read(&db, note.get_course())
69 .await?
70 .ok_or(AppError::NotFound)?;
71 Ok((note, course))
72}
73
74#[derive(Deserialize, ToSchema)]
75struct CreateCourseNote {
76 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
77 course: String,
78 #[schema(example = "Chapter 3 recap", max_length = 200)]
79 title: String,
80 #[schema(
81 example = "Covered quadratics; homework due Friday",
82 max_length = 10000
83 )]
84 content: Option<String>,
85}
86
87#[derive(Deserialize, ToSchema)]
88struct UpdateCourseNote {
89 #[schema(max_length = 200)]
90 title: Option<String>,
91 #[schema(max_length = 10000)]
92 content: Option<String>,
93}
94
95#[derive(Serialize, ToSchema)]
96struct CourseNoteResponse {
97 id: String,
98 course: String,
99 title: String,
100 content: String,
101}
102
103impl CourseNoteResponse {
104 fn new(note: &CourseNote) -> Self {
105 Self {
106 id: note.get_id().key().to_string(),
107 course: note.get_course().key().to_string(),
108 title: note.get_title().as_str().to_string(),
109 content: note.get_content().as_str().to_string(),
110 }
111 }
112}
113
114/// Create a note on a course. Requires teacher+ and catalog rights over the
115/// course (its creator or a manager/admin).
116#[utoipa::path(
117 post,
118 path = "/",
119 tag = "course-notes",
120 security(("session_cookie" = [])),
121 request_body = CreateCourseNote,
122 responses(
123 (status = 201, description = "Note created", body = CourseNoteResponse),
124 (status = 400, description = "Invalid title or content", body = ErrorResponse),
125 (status = 401, description = "Not authenticated", body = ErrorResponse),
126 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
127 (status = 404, description = "Course not found", body = ErrorResponse),
128 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
129 ),
130)]
131async fn create(
132 State(st): State<AppState>,
133 tenant: ResolvedTenant,
134 RequireTeacher(user): RequireTeacher,
135 Json(req): Json<CreateCourseNote>,
136) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> {
137 let course = crate::service::course::read(&st.db, &CourseId::from_key(&req.course))
138 .await?
139 .ok_or(AppError::NotFound)?;
140 if !can_manage_course(&course, &user) {
141 return Err(AppError::Forbidden(
142 "only the course creator or a manager/admin can add a course note",
143 ));
144 }
145 let title = CourseNoteTitle::try_new(&req.title)?;
146 let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?;
147 let note = service::course_note::create(&st.db, course.get_id(), user.get_id(), title, content)
148 .await?;
149 // Indexing is a background bonus, never a condition of storing the note:
150 // the dispatch runs in its own task, so a slow or absent AI service cannot
151 // delay or fail this 201.
152 spawn_index(&st, &tenant, note.clone());
153 Ok((StatusCode::CREATED, Json(CourseNoteResponse::new(&note))))
154}
155
156#[derive(Deserialize, IntoParams)]
157struct CourseFilter {
158 /// The course to list notes for (required).
159 #[param(example = "019732e3-7b00-7000-8000-00000000dead")]
160 course: String,
161}
162
163impl CourseFilter {
164 /// Validate: `course` is required, so an empty key is a 400 ("must not
165 /// be empty") and a non-uuid is a 400 naming the field — never the nil
166 /// id silently 404ing as a missing course. A well-formed id that names
167 /// no course stays a 404: the course read below must succeed for the
168 /// auth check.
169 fn resolve(&self) -> Result<CourseId, AppError> {
170 let key = self.course.trim();
171 if key.is_empty() {
172 return Err(ValidationError::Invalid {
173 field: "course",
174 reason: "must not be empty",
175 }
176 .into());
177 }
178 let id = CourseId::from_key(key);
179 if id.uuid().is_nil() {
180 return Err(ValidationError::Invalid {
181 field: "course",
182 reason: "must be a hyphenated uuid",
183 }
184 .into());
185 }
186 Ok(id)
187 }
188}
189
190/// List a course's notes, newest first. Visible to whoever can view the
191/// course (its creator, a manager/admin, or anyone the course reaches).
192/// Paged via `?limit=&offset=`.
193///
194/// `course` must be a hyphenated uuid: empty or malformed is a 400 naming
195/// the field; a well-formed id that names no course stays a 404, since the
196/// course must be read for the auth check.
197#[utoipa::path(
198 get,
199 path = "/",
200 tag = "course-notes",
201 security(("session_cookie" = [])),
202 params(CourseFilter, PageParams),
203 responses(
204 (status = 200, description = "A page of the course's notes (all of them when unpaged)", body = Page<CourseNoteResponse>),
205 (status = 400, description = "Invalid limit, offset, or course key", body = ErrorResponse),
206 (status = 401, description = "Not authenticated", body = ErrorResponse),
207 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
208 (status = 404, description = "Course not found", body = ErrorResponse),
209 ),
210)]
211async fn list(
212 State(st): State<AppState>,
213 CurrentUser(user): CurrentUser,
214 Query(filter): Query<CourseFilter>,
215 Query(page): Query<PageParams>,
216) -> Result<Json<Page<CourseNoteResponse>>, AppError> {
217 let course_id = filter.resolve()?;
218 let course = crate::service::course::read(&st.db, &course_id)
219 .await?
220 .ok_or(AppError::NotFound)?;
221 if !can_view_course(&course, &user, &st.db).await? {
222 return Err(AppError::Forbidden(
223 "only a user this course reaches, its creator, or a manager/admin can view this course's notes",
224 ));
225 }
226 let (limit, offset) = page.resolve()?;
227 let (notes, total) =
228 service::course_note::list_for_course(&st.db, course.get_id(), limit, offset).await?;
229 let items = notes.iter().map(CourseNoteResponse::new).collect();
230 Ok(Json(Page::new(items, total, limit, offset)))
231}
232
233/// Fetch a single course note by id. Visible to whoever can view its course.
234#[utoipa::path(
235 get,
236 path = "/{id}",
237 tag = "course-notes",
238 security(("session_cookie" = [])),
239 params(("id" = String, Path, description = "Course note id")),
240 responses(
241 (status = 200, description = "The note", body = CourseNoteResponse),
242 (status = 401, description = "Not authenticated", body = ErrorResponse),
243 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
244 (status = 404, description = "Not found", body = ErrorResponse),
245 ),
246)]
247async fn get_one(
248 State(st): State<AppState>,
249 CurrentUser(user): CurrentUser,
250 Path(id): Path<String>,
251) -> Result<Json<CourseNoteResponse>, AppError> {
252 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
253 if !can_view_course(&course, &user, &st.db).await? {
254 return Err(AppError::Forbidden(
255 "only a user this course reaches, its creator, or a manager/admin can view this course note",
256 ));
257 }
258 Ok(Json(CourseNoteResponse::new(&note)))
259}
260
261/// Update a course note's title and/or content. Omitted fields keep their
262/// value. Requires teacher+ and management rights over the course.
263#[utoipa::path(
264 patch,
265 path = "/{id}",
266 tag = "course-notes",
267 security(("session_cookie" = [])),
268 params(("id" = String, Path, description = "Course note id")),
269 request_body = UpdateCourseNote,
270 responses(
271 (status = 200, description = "Updated note", body = CourseNoteResponse),
272 (status = 400, description = "Invalid title or content", body = ErrorResponse),
273 (status = 401, description = "Not authenticated", body = ErrorResponse),
274 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
275 (status = 404, description = "Not found", body = ErrorResponse),
276 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
277 ),
278)]
279async fn update(
280 State(st): State<AppState>,
281 tenant: ResolvedTenant,
282 RequireTeacher(user): RequireTeacher,
283 Path(id): Path<String>,
284 Json(req): Json<UpdateCourseNote>,
285) -> Result<Json<CourseNoteResponse>, AppError> {
286 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
287 if !can_manage_course(&course, &user) {
288 return Err(AppError::Forbidden(
289 "only the course creator or a manager/admin can edit this course note",
290 ));
291 }
292
293 let title = req
294 .title
295 .as_deref()
296 .map(CourseNoteTitle::try_new)
297 .transpose()?;
298 let content = req
299 .content
300 .as_deref()
301 .map(CourseNoteContent::try_new)
302 .transpose()?;
303
304 let updated = service::course_note::update(&st.db, note, title, content).await?;
305 // The stored index describes the old text — refresh it.
306 spawn_index(&st, &tenant, updated.clone());
307 Ok(Json(CourseNoteResponse::new(&updated)))
308}
309
310/// Delete a course note, along with its files. Requires teacher+ and
311/// management rights over the course.
312#[utoipa::path(
313 delete,
314 path = "/{id}",
315 tag = "course-notes",
316 security(("session_cookie" = [])),
317 params(("id" = String, Path, description = "Course note id")),
318 responses(
319 (status = 204, description = "Deleted"),
320 (status = 401, description = "Not authenticated", body = ErrorResponse),
321 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
322 (status = 404, description = "Not found", body = ErrorResponse),
323 ),
324)]
325async fn delete_one(
326 State(st): State<AppState>,
327 RequireTeacher(user): RequireTeacher,
328 Path(id): Path<String>,
329) -> Result<StatusCode, AppError> {
330 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
331 if !can_manage_course(&course, &user) {
332 return Err(AppError::Forbidden(
333 "only the course creator or a manager/admin can delete this course note",
334 ));
335 }
336 // Derived rows first, outside the note's own cascade transaction: they are
337 // disposable, so failing here leaves the note intact and the 500 truthful,
338 // whereas dropping them after the note would strand every blob on an error
339 // — and if the note delete then fails, the next change regenerates them.
340 service::rag_output::delete_for_note(&st.db, note.get_id()).await?;
341 // Rows go first (the note delete cascades them), blobs after: a crash in
342 // between strands at worst an unreachable blob, never a row whose blob is
343 // already gone. The files to unlink come from the delete itself, not a
344 // pre-read list — an upload that landed in between is in the cascade too.
345 let (_, files) = service::course_note::delete(&st.db, note).await?;
346 for file in &files {
347 remove_blob(&st.files_path, &file.get_id().key()).await;
348 }
349 Ok(StatusCode::NO_CONTENT)
350}
351
352/// A course note file's stored metadata; the bytes themselves come from the
353/// download endpoint.
354#[derive(Serialize, ToSchema)]
355struct CourseNoteFileResponse {
356 id: String,
357 /// The uploader's original filename.
358 #[schema(example = "recap.pdf")]
359 name: String,
360 /// MIME type as declared on upload.
361 #[schema(example = "application/pdf")]
362 content_type: String,
363 /// File size in bytes.
364 #[schema(example = 24_576)]
365 size: i64,
366}
367
368impl CourseNoteFileResponse {
369 fn new(file: &CourseNoteFile) -> Self {
370 Self {
371 id: file.get_id().key().to_string(),
372 name: file.get_name().as_str().to_string(),
373 content_type: file.get_content_type().as_str().to_string(),
374 size: file.get_size(),
375 }
376 }
377}
378
379/// Attach a file to a course note. `multipart/form-data` with the file under
380/// a `file` field; its `filename` is required. At most 10 files per note,
381/// each at most the school's `max_file_bytes` (settings, default 5 MiB).
382/// Requires teacher+ and management rights over the course.
383#[utoipa::path(
384 post,
385 path = "/{id}/files",
386 tag = "course-notes",
387 security(("session_cookie" = [])),
388 params(("id" = String, Path, description = "Course note id")),
389 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
390 responses(
391 (status = 201, description = "File stored", body = CourseNoteFileResponse),
392 (status = 400, description = "Missing file field, invalid filename or content type, or empty file", body = ErrorResponse),
393 (status = 401, description = "Not authenticated", body = ErrorResponse),
394 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
395 (status = 404, description = "Note not found", body = ErrorResponse),
396 (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse),
397 (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse),
398 ),
399)]
400async fn upload_file(
401 State(st): State<AppState>,
402 tenant: ResolvedTenant,
403 RequireTeacher(user): RequireTeacher,
404 Path(id): Path<String>,
405 mut multipart: Multipart,
406) -> Result<(StatusCode, Json<CourseNoteFileResponse>), AppError> {
407 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
408 if !can_manage_course(&course, &user) {
409 return Err(AppError::Forbidden(
410 "only the course creator or a manager/admin can add a file to this course note",
411 ));
412 }
413 // The 10-file cap is enforced inside `service::course_note_file::insert`
414 // (count and create in one conditional write) — checking it here too would
415 // just race.
416 let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
417
418 let upload = read_upload(&mut multipart, limit).await?;
419 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
420 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
421
422 // Blob first, row second — a stored row always points at a real blob. If
423 // the row insert fails, take the fresh blob back out.
424 let file = CourseNoteFile::new(note.get_id(), name, content_type, upload.data.len() as i64);
425 let path = blob_path(&st.files_path, &file.get_id().key());
426 crate::web::ensure_files_dir(&st.files_path).await?;
427 tokio::fs::write(&path, &upload.data)
428 .await
429 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
430 match service::course_note_file::insert(&st.db, file).await {
431 Ok(created) => {
432 // The note now holds one more source than the stored index knows.
433 spawn_index(&st, &tenant, note);
434 Ok((
435 StatusCode::CREATED,
436 Json(CourseNoteFileResponse::new(&created)),
437 ))
438 }
439 Err(err) => {
440 let _ = tokio::fs::remove_file(&path).await;
441 Err(err)
442 }
443 }
444}
445
446/// List a course note's files (metadata only), newest first. Paged via
447/// `?limit=&offset=`.
448#[utoipa::path(
449 get,
450 path = "/{id}/files",
451 tag = "course-notes",
452 security(("session_cookie" = [])),
453 params(("id" = String, Path, description = "Course note id"), PageParams),
454 responses(
455 (status = 200, description = "A page of the note's files", body = Page<CourseNoteFileResponse>),
456 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
457 (status = 401, description = "Not authenticated", body = ErrorResponse),
458 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
459 (status = 404, description = "Note not found", body = ErrorResponse),
460 ),
461)]
462async fn list_files(
463 State(st): State<AppState>,
464 CurrentUser(user): CurrentUser,
465 Path(id): Path<String>,
466 Query(page): Query<PageParams>,
467) -> Result<Json<Page<CourseNoteFileResponse>>, AppError> {
468 let (limit, offset) = page.resolve()?;
469 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
470 if !can_view_course(&course, &user, &st.db).await? {
471 return Err(AppError::Forbidden(
472 "only a user this course reaches, its creator, or a manager/admin can view this course note's files",
473 ));
474 }
475 let (files, total) =
476 service::course_note_file::list_for(&st.db, note.get_id(), limit, offset).await?;
477 let items = files.iter().map(CourseNoteFileResponse::new).collect();
478 Ok(Json(Page::new(items, total, limit, offset)))
479}
480
481/// Download a course note file's bytes. `Content-Type` is the one declared on
482/// upload; `Content-Disposition` carries the original filename.
483#[utoipa::path(
484 get,
485 path = "/{id}/files/{file_id}",
486 tag = "course-notes",
487 security(("session_cookie" = [])),
488 params(
489 ("id" = String, Path, description = "Course note id"),
490 ("file_id" = String, Path, description = "File id"),
491 ),
492 responses(
493 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
494 (status = 401, description = "Not authenticated", body = ErrorResponse),
495 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
496 (status = 404, description = "Note or file not found", body = ErrorResponse),
497 ),
498)]
499async fn download_file(
500 State(st): State<AppState>,
501 CurrentUser(user): CurrentUser,
502 Path((id, file_id)): Path<(String, String)>,
503) -> Result<Response, AppError> {
504 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
505 if !can_view_course(&course, &user, &st.db).await? {
506 return Err(AppError::Forbidden(
507 "only a user this course reaches, its creator, or a manager/admin can download this course note's files",
508 ));
509 }
510 let file = service::course_note_file::read_for(
511 &st.db,
512 &CourseNoteFileId::from_key(&file_id),
513 note.get_id(),
514 )
515 .await?
516 .ok_or(AppError::NotFound)?;
517 let bytes = tokio::fs::read(blob_path(&st.files_path, &file.get_id().key()))
518 .await
519 .map_err(|err| {
520 // The row exists but its blob doesn't — that's server-side damage
521 // (a lost volume path), not a client 404.
522 AppError::Internal(format!(
523 "missing blob for course note file {}: {err}",
524 file.get_id().key()
525 ))
526 })?;
527 let content_type = HeaderValue::from_str(file.get_content_type().as_str())
528 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
529 let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str()))
530 .unwrap_or_else(|_| HeaderValue::from_static("attachment"));
531 Ok((
532 [
533 (CONTENT_TYPE, content_type),
534 (CONTENT_DISPOSITION, disposition),
535 ],
536 bytes,
537 )
538 .into_response())
539}
540
541/// Delete a course note file (row first, then its blob). Requires teacher+
542/// and management rights over the course.
543#[utoipa::path(
544 delete,
545 path = "/{id}/files/{file_id}",
546 tag = "course-notes",
547 security(("session_cookie" = [])),
548 params(
549 ("id" = String, Path, description = "Course note id"),
550 ("file_id" = String, Path, description = "File id"),
551 ),
552 responses(
553 (status = 204, description = "Deleted"),
554 (status = 401, description = "Not authenticated", body = ErrorResponse),
555 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
556 (status = 404, description = "Note or file not found", body = ErrorResponse),
557 ),
558)]
559async fn delete_file(
560 State(st): State<AppState>,
561 tenant: ResolvedTenant,
562 RequireTeacher(user): RequireTeacher,
563 Path((id, file_id)): Path<(String, String)>,
564) -> Result<StatusCode, AppError> {
565 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
566 if !can_manage_course(&course, &user) {
567 return Err(AppError::Forbidden(
568 "only the course creator or a manager/admin can delete this course note's files",
569 ));
570 }
571 let file = service::course_note_file::read_for(
572 &st.db,
573 &CourseNoteFileId::from_key(&file_id),
574 note.get_id(),
575 )
576 .await?
577 .ok_or(AppError::NotFound)?;
578 // Drop every link citing this file before the file itself — the file
579 // row refuses to go while one stands — so a failure here leaves the file
580 // whole instead of stranding its blob; the re-index rebuilds the
581 // outputs from what is left, if a service is connected.
582 service::rag_output::delete_with_source(&st.db, file.get_id()).await?;
583 let file = service::course_note_file::delete(&st.db, file).await?;
584 remove_blob(&st.files_path, &file.get_id().key()).await;
585 spawn_index(&st, &tenant, note);
586 Ok(StatusCode::NO_CONTENT)
587}
588
589/// One AI service output stored against a course note. `payload` is the
590/// service's own shape — the backend stores and serves it unread.
591#[derive(Serialize, ToSchema)]
592struct RagOutputResponse {
593 id: String,
594 course_note: String,
595 course: String,
596 /// The note's file attachments the output was built from.
597 sources: Vec<String>,
598 /// The service's answer, verbatim.
599 #[schema(value_type = Object)]
600 payload: serde_json::Value,
601 /// When the backend stored it, epoch milliseconds.
602 #[schema(example = 1_735_689_600_000i64)]
603 generated_at: i64,
604}
605
606impl RagOutputResponse {
607 fn new(output: &RagOutput) -> Self {
608 Self {
609 id: output.get_id().key().to_string(),
610 course_note: output.get_course_note().key().to_string(),
611 course: output.get_course().key().to_string(),
612 sources: output
613 .get_sources()
614 .iter()
615 .map(|file| file.key().to_string())
616 .collect(),
617 payload: output.get_payload().clone(),
618 generated_at: output.get_generated_at().as_millis(),
619 }
620 }
621}
622
623/// List a course note's AI outputs, newest first. Visible to whoever can view
624/// the course. Paged via `?limit=&offset=`.
625#[utoipa::path(
626 get,
627 path = "/{id}/rag",
628 tag = "course-notes",
629 security(("session_cookie" = [])),
630 params(("id" = String, Path, description = "Course note id"), PageParams),
631 responses(
632 (status = 200, description = "A page of the note's stored AI outputs", body = Page<RagOutputResponse>),
633 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
634 (status = 401, description = "Not authenticated", body = ErrorResponse),
635 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
636 (status = 404, description = "Note not found", body = ErrorResponse),
637 ),
638)]
639async fn list_rag(
640 State(st): State<AppState>,
641 CurrentUser(user): CurrentUser,
642 Path(id): Path<String>,
643 Query(page): Query<PageParams>,
644) -> Result<Json<Page<RagOutputResponse>>, AppError> {
645 let (limit, offset) = page.resolve()?;
646 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
647 if !can_view_course(&course, &user, &st.db).await? {
648 return Err(AppError::Forbidden(
649 "only a user this course reaches, its creator, or a manager/admin can view this course note's AI outputs",
650 ));
651 }
652 let (outputs, total) =
653 service::rag_output::list_for(&st.db, note.get_id(), limit, offset).await?;
654 let items = outputs.iter().map(RagOutputResponse::new).collect();
655 Ok(Json(Page::new(items, total, limit, offset)))
656}
657
658/// Delete one stored AI output. Requires teacher+ and management rights over
659/// the course. Dropping an output does not stop the next note or file change
660/// from regenerating one.
661#[utoipa::path(
662 delete,
663 path = "/{id}/rag/{output_id}",
664 tag = "course-notes",
665 security(("session_cookie" = [])),
666 params(
667 ("id" = String, Path, description = "Course note id"),
668 ("output_id" = String, Path, description = "AI output id"),
669 ),
670 responses(
671 (status = 204, description = "Deleted"),
672 (status = 401, description = "Not authenticated", body = ErrorResponse),
673 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
674 (status = 404, description = "Note or output not found", body = ErrorResponse),
675 ),
676)]
677async fn delete_rag(
678 State(st): State<AppState>,
679 RequireTeacher(user): RequireTeacher,
680 Path((id, output_id)): Path<(String, String)>,
681) -> Result<StatusCode, AppError> {
682 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
683 if !can_manage_course(&course, &user) {
684 return Err(AppError::Forbidden(
685 "only the course creator or a manager/admin can delete this course note's AI outputs",
686 ));
687 }
688 // Scoped to the note in the path, like `service::course_note_file::read_for`: an
689 // output of another note is a 404 here, never a cross-note delete.
690 let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id))
691 .await?
692 .filter(|output| output.get_course_note() == note.get_id())
693 .ok_or(AppError::NotFound)?;
694 service::rag_output::delete(&st.db, output.get_id()).await?;
695 Ok(StatusCode::NO_CONTENT)
696}
697
698/// Re-index a course note now, without waiting for its next write.
699///
700/// Indexing otherwise fires only on a note or file write, so a note saved
701/// while no AI service was connected stays unindexed until something touches
702/// it again — this door re-runs the same dispatch on demand. The `202` says
703/// the re-index was *dispatched*, not that it finished: the bridge round trip
704/// runs off the request path ([`spawn_index`]), and an unreachable service
705/// leaves the stored index as it was. Poll `GET /course-notes/{id}/rag` for
706/// the output once it lands.
707#[utoipa::path(
708 post,
709 path = "/{id}/rag/reindex",
710 tag = "course-notes",
711 security(("session_cookie" = [])),
712 params(("id" = String, Path, description = "Course note id")),
713 responses(
714 (status = 202, description = "Re-index dispatched; poll `GET /course-notes/{id}/rag` for the stored output"),
715 (status = 401, description = "Not authenticated", body = ErrorResponse),
716 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
717 (status = 404, description = "Not found", body = ErrorResponse),
718 (status = 503, description = "No AI service is available — nothing was written, retry later", body = ErrorResponse),
719 ),
720)]
721async fn reindex_rag(
722 State(st): State<AppState>,
723 tenant: ResolvedTenant,
724 RequireTeacher(user): RequireTeacher,
725 Path(id): Path<String>,
726) -> Result<Response, AppError> {
727 let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
728 if !can_manage_course(&course, &user) {
729 return Err(AppError::Forbidden(
730 "only the course creator or a manager/admin can re-index this course note",
731 ));
732 }
733 // The same 503 gate `ai::rag::index_course_note` applies internally, lifted
734 // here so the caller learns why nothing will happen instead of getting a
735 // `202` for a dispatch that would silently no-op. `has_capability` is racy
736 // by design and guards no write — the note is untouched either way.
737 if !tenant.modules.contains(Module::Chatbot) {
738 return Ok(ai_unavailable(
739 "the AI service is not enabled on this deployment",
740 ));
741 }
742 let Some(bridge) = st.ai.as_ref() else {
743 return Ok(ai_unavailable(
744 "the AI service is not enabled on this deployment",
745 ));
746 };
747 if !bridge.has_capability(AI_RAG_INDEX_CAPABILITY) {
748 return Ok(ai_unavailable("no AI service is connected right now"));
749 }
750 // `note` was just read through the shared path, so the dispatched payload
751 // is the note as it stands now.
752 spawn_index(&st, &tenant, note);
753 Ok(StatusCode::ACCEPTED.into_response())
754}
755
756#[cfg(test)]
757mod tests {
758 use super::*;
759
760 /// `course` is required and must be a real key: empty is "must not be
761 /// empty", a non-uuid is "must be a hyphenated uuid" — never the nil id
762 /// silently 404ing as a missing course. A well-formed id passes through,
763 /// and one that names no course stays on the 404 path (the course read
764 /// the handler runs next must miss for the auth check).
765 #[tokio::test]
766 async fn course_key_is_validated_before_the_course_read() {
767 let (db, _leases) = crate::database::init_test_db().await;
768 let filter = |course: &str| CourseFilter {
769 course: course.to_string(),
770 };
771
772 match filter("").resolve() {
773 Err(AppError::Validation(ValidationError::Invalid { field, reason })) => {
774 assert_eq!(field, "course");
775 assert_eq!(reason, "must not be empty");
776 }
777 other => panic!("expected an empty-course error, got {other:?}"),
778 }
779 match filter(" ").resolve() {
780 Err(AppError::Validation(ValidationError::Invalid { field, reason })) => {
781 assert_eq!(field, "course");
782 assert_eq!(reason, "must not be empty");
783 }
784 other => panic!("expected a blank-course error, got {other:?}"),
785 }
786 match filter("not-a-uuid").resolve() {
787 Err(AppError::Validation(ValidationError::Invalid { field, reason })) => {
788 assert_eq!(field, "course");
789 assert_eq!(reason, "must be a hyphenated uuid");
790 }
791 other => panic!("expected a malformed-course error, got {other:?}"),
792 }
793
794 // A well-formed id passes through; if it names no course, the read
795 // the handler does next misses and the route answers 404.
796 let id = filter("019732e3-7b00-7000-8000-00000000dead")
797 .resolve()
798 .unwrap();
799 assert_eq!(
800 id.uuid(),
801 uuid::Uuid::parse_str("019732e3-7b00-7000-8000-00000000dead").unwrap()
802 );
803 assert!(service::course::read(&db, &id).await.unwrap().is_none());
804 }
805}