From f5403d14959aeaec5644a65c214600839c4f309f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 17 Sep 2026 05:23:46 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20add=20a=20manual=20course-n?= =?UTF-8?q?ote=20RAG=20reindex=20door?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/web/chatbot.rs | 18 ++-------- src/web/course_notes.rs | 66 ++++++++++++++++++++++++++++++++-- src/web/mod.rs | 14 ++++++++ tests/integration.rs | 78 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 157 insertions(+), 19 deletions(-) diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index ee00e78..5213fff 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -53,7 +53,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; use crate::state::{AppState, scoped_key}; -use super::{CurrentUser, Page, PageParams}; +use super::{CurrentUser, Page, PageParams, ai_unavailable}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -406,12 +406,12 @@ async fn send_message( // documented racy — that is fine here: it never guards a write, it only // spares the user a thread full of rows nothing could ever answer. let Some(bridge) = st.ai.clone() else { - return Ok(unavailable( + return Ok(ai_unavailable( "the AI service is not enabled on this deployment", )); }; if !bridge.has_capability(AI_CHAT_CAPABILITY) { - return Ok(unavailable("no AI service is connected right now")); + return Ok(ai_unavailable("no AI service is connected right now")); } // Each create rides the thread's own row — it moves `updated_at` (the @@ -475,18 +475,6 @@ fn content_cap(settings: &Settings) -> usize { (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN) } -/// The AI-unavailable `503`. Built here rather than as an `AppError` variant: -/// this is the only route that can produce it, and `AppError`'s 503s all mean -/// "the database is reconnecting", which this is not. No `Retry-After` — when -/// a service will dial back in is unknowable. -fn unavailable(message: &str) -> Response { - ( - StatusCode::SERVICE_UNAVAILABLE, - Json(json!({ "error": message })), - ) - .into_response() -} - /// Fetch one turn's answer and settle its row. Runs detached from the request. /// /// Every path settles: a row left `pending` would show as a spinner forever. diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 84a7be7..c8ba677 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -19,7 +19,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::ai::rag::spawn_index; -use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::constant::{AI_RAG_INDEX_CAPABILITY, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::course::{Course, CourseId}; use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle}; @@ -28,14 +28,15 @@ use crate::domain::course_note_file::{ }; use crate::domain::rag_output::{RagOutput, RagOutputId}; use crate::error::{AppError, ErrorResponse}; +use crate::module::Module; use crate::service; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; use super::notes::content_disposition; use super::{ - CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, read_upload, - remove_blob, + CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, ai_unavailable, blob_path, + read_upload, remove_blob, }; pub fn routes() -> OpenApiRouter { @@ -52,6 +53,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(create, list)) .routes(routes!(get_one, update, delete_one)) .routes(routes!(list_rag)) + .routes(routes!(reindex_rag)) .routes(routes!(delete_rag)) .merge(files) } @@ -660,3 +662,61 @@ async fn delete_rag( service::rag_output::delete(&st.db, output.get_id()).await?; Ok(StatusCode::NO_CONTENT) } + +/// Re-index a course note now, without waiting for its next write. +/// +/// Indexing otherwise fires only on a note or file write, so a note saved +/// while no AI service was connected stays unindexed until something touches +/// it again — this door re-runs the same dispatch on demand. The `202` says +/// the re-index was *dispatched*, not that it finished: the bridge round trip +/// runs off the request path ([`spawn_index`]), and an unreachable service +/// leaves the stored index as it was. Poll `GET /course-notes/{id}/rag` for +/// the output once it lands. +#[utoipa::path( + post, + path = "/{id}/rag/reindex", + tag = "course-notes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course note id")), + responses( + (status = 202, description = "Re-index dispatched; poll `GET /course-notes/{id}/rag` for the stored output"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 503, description = "No AI service is available — nothing was written, retry later", body = ErrorResponse), + ), +)] +async fn reindex_rag( + State(st): State, + tenant: ResolvedTenant, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let (note, course) = note_with_course(id.clone(), st.db.clone()).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can re-index this course note", + )); + } + // The same 503 gate `ai::rag::index_course_note` applies internally, lifted + // here so the caller learns why nothing will happen instead of getting a + // `202` for a dispatch that would silently no-op. `has_capability` is racy + // by design and guards no write — the note is untouched either way. + if !tenant.modules.contains(Module::Chatbot) { + return Ok(ai_unavailable( + "the AI service is not enabled on this deployment", + )); + } + let Some(bridge) = st.ai.as_ref() else { + return Ok(ai_unavailable( + "the AI service is not enabled on this deployment", + )); + }; + if !bridge.has_capability(AI_RAG_INDEX_CAPABILITY) { + return Ok(ai_unavailable("no AI service is connected right now")); + } + // `note` was just read through the shared path, so the dispatched payload + // is the note as it stands now. + spawn_index(&st, &tenant, note); + Ok(StatusCode::ACCEPTED.into_response()) +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 5793924..7b92d63 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -62,12 +62,14 @@ pub use page::{Page, PageParams, Scheduled, WindowParams, paginate}; use std::path::{Path as FsPath, PathBuf}; +use axum::Json; use axum::extract::Multipart; use axum::extract::multipart::MultipartError; use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS}; use axum::http::{HeaderValue, StatusCode}; use axum::response::{IntoResponse, Response}; use serde::{Deserialize, Deserializer}; +use serde_json::json; use utoipa::ToSchema; use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS}; @@ -363,6 +365,18 @@ where Option::::deserialize(de).map(Some) } +/// The AI-unavailable `503`. Shared by every route that can refuse because no +/// AI service is reachable: built here rather than as an `AppError` variant — +/// `AppError`'s 503s all mean "the database is reconnecting", which this is +/// not. No `Retry-After` — when a service will dial back in is unknowable. +pub(crate) fn ai_unavailable(message: &str) -> Response { + ( + StatusCode::SERVICE_UNAVAILABLE, + Json(json!({ "error": message })), + ) + .into_response() +} + #[cfg(test)] mod tests { use super::*; diff --git a/tests/integration.rs b/tests/integration.rs index 568a929..52f5c3f 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -433,7 +433,7 @@ async fn protected_routes_require_session() { /// Floor on the number of protected operations swept. It only ever goes /// up: raise it when routes are added. Without it, deleting a route family /// would delete its own coverage and still pass. - const MIN_PROTECTED: usize = 268; + const MIN_PROTECTED: usize = 269; let app = mem_app().await; let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) @@ -27847,6 +27847,82 @@ async fn course_note_rag_outputs_read_and_delete() { assert_eq!(common::total(&list.body), 0, "{}", list.body); } +/// The manual reindex door is a note write like any other: teacher+, and +/// management rights over the parent course. A foreign teacher, a student, and +/// an unknown note are all refused — and none of them writes a row. +#[tokio::test] +async fn course_note_rag_reindex_denies_foreign_teacher_student_and_unknown_note() { + let (app, db) = app_and_db().await; + let creator = login_as(&app, &db, "reindex_teacher", "teacher").await; + let outsider = login_as(&app, &db, "reindex_other_teacher", "teacher").await; + let student = login_as(&app, &db, "reindex_student", "student").await; + + let course = create_course(&app, &creator, "reindex").await; + let note = create_course_note(&app, &creator, &course, "to reindex").await; + let uri = format!("/course-notes/{note}/rag/reindex"); + + // A teacher who does not manage the course: 403, like every other write. + let res = send(&app, "POST", &uri, Some(&outsider), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // A student fails the teacher+ wall before any rights check. + let res = send(&app, "POST", &uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // An unknown note is a 404, never a silent 202. + let res = send( + &app, + "POST", + "/course-notes/01NOTANOTE/rag/reindex", + Some(&creator), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + + let (rows, total) = + hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(¬e), None, 0) + .await + .unwrap(); + assert!(rows.is_empty() && total == 0, "a refusal wrote a row"); +} + +/// With no AI service connected the door answers `503` and dispatches nothing: +/// a `202` here would promise a reindex nothing could ever run. +#[tokio::test] +async fn course_note_rag_reindex_reports_503_and_writes_nothing_without_a_service() { + // `app_and_db` wires no AI bridge in — the same "no service connected" + // state a school is in before its AI features are provisioned. + let (app, db) = app_and_db().await; + let creator = login_as(&app, &db, "reindex_off_teacher", "teacher").await; + let course = create_course(&app, &creator, "reindex_off").await; + let note = create_course_note(&app, &creator, &course, "unindexed").await; + + let res = send( + &app, + "POST", + &format!("/course-notes/{note}/rag/reindex"), + Some(&creator), + None, + ) + .await; + assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body); + assert!( + res.body["error"].as_str().is_some_and(|e| !e.is_empty()), + "{}", + res.body + ); + + let (rows, total) = + hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(¬e), None, 0) + .await + .unwrap(); + assert!( + rows.is_empty() && total == 0, + "reindex dispatched while no service was connected" + ); +} + // ========================================================================= // Multi-school isolation probes (REFUTE lane B). Two schools, same usernames. // =========================================================================