| 1 | use axum::extract::{Multipart, Path, Query, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use sha2::{Digest, Sha256}; |
| 6 | use utopia_core::models::{Document, Role}; |
| 7 | use utopia_core::AppError; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | use crate::auth::AuthUser; |
| 11 | use crate::error::ApiResult; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | #[derive(Deserialize)] |
| 15 | pub struct UploadQuery { |
| 16 | /// 目标 folder 来源:上传直接归入该文件夹(仅 kind=folder 接受上传) |
| 17 | #[serde(default)] |
| 18 | pub source: Option<Uuid>, |
| 19 | } |
| 20 | |
| 21 | /// 批量上传(multipart,可多文件)。重复内容(同 KB 同 sha256)跳过。 |
| 22 | pub async fn upload( |
| 23 | State(state): State<AppState>, |
| 24 | AuthUser(user): AuthUser, |
| 25 | Path(kb_id): Path<Uuid>, |
| 26 | Query(q): Query<UploadQuery>, |
| 27 | mut multipart: Multipart, |
| 28 | ) -> ApiResult<Json<serde_json::Value>> { |
| 29 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?; |
| 30 | let target_source = match q.source { |
| 31 | Some(sid) => { |
| 32 | let src = utopia_store::sources::get(&state.pool, sid).await?; |
| 33 | if src.kb_id != kb_id || src.kind != "folder" { |
| 34 | return Err(AppError::invalid( |
| 35 | "upload_needs_folder", |
| 36 | "Uploads can only target a folder source in this knowledge base", |
| 37 | ) |
| 38 | .into()); |
| 39 | } |
| 40 | Some(sid) |
| 41 | } |
| 42 | None => None, |
| 43 | }; |
| 44 | |
| 45 | let mut created: Vec<Document> = Vec::new(); |
| 46 | let mut skipped: Vec<serde_json::Value> = Vec::new(); |
| 47 | |
| 48 | while let Some(field) = multipart |
| 49 | .next_field() |
| 50 | .await |
| 51 | .map_err(|e| AppError::invalid_detail("bad_upload", "Malformed upload", e.to_string()))? |
| 52 | { |
| 53 | let Some(filename) = field.file_name().map(String::from) else { |
| 54 | continue; |
| 55 | }; |
| 56 | let mime = field |
| 57 | .content_type() |
| 58 | .unwrap_or("application/octet-stream") |
| 59 | .to_string(); |
| 60 | let bytes = field.bytes().await.map_err(|e| { |
| 61 | AppError::invalid_detail("upload_read_failed", "Failed to read upload", e.to_string()) |
| 62 | })?; |
| 63 | if bytes.is_empty() { |
| 64 | skipped.push(json!({ "filename": filename, "reason": "empty file" })); |
| 65 | continue; |
| 66 | } |
| 67 | |
| 68 | let sha256 = hex(&Sha256::digest(&bytes)); |
| 69 | state |
| 70 | .blob |
| 71 | .put(&sha256, &bytes) |
| 72 | .await |
| 73 | .map_err(AppError::Other)?; |
| 74 | |
| 75 | match utopia_store::documents::create( |
| 76 | &state.pool, |
| 77 | kb_id, |
| 78 | &filename, |
| 79 | &mime, |
| 80 | bytes.len() as i64, |
| 81 | &sha256, |
| 82 | target_source, |
| 83 | None, |
| 84 | None, |
| 85 | ) |
| 86 | .await |
| 87 | { |
| 88 | Ok(doc) => { |
| 89 | utopia_store::jobs::enqueue( |
| 90 | &state.pool, |
| 91 | "process_document", |
| 92 | json!({ "document_id": doc.id }), |
| 93 | ) |
| 94 | .await?; |
| 95 | created.push(doc); |
| 96 | } |
| 97 | Err(AppError::Conflict(_)) => { |
| 98 | skipped.push(json!({ "filename": filename, "reason": "duplicate content" })); |
| 99 | } |
| 100 | Err(e) => return Err(e.into()), |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | if created.is_empty() && skipped.is_empty() { |
| 105 | return Err(AppError::invalid("no_files", "No files received").into()); |
| 106 | } |
| 107 | Ok(Json(json!({ "created": created, "skipped": skipped }))) |
| 108 | } |
| 109 | |
| 110 | #[derive(serde::Deserialize)] |
| 111 | pub struct DocsQuery { |
| 112 | /// 来源作用域:缺省 = 全部;`none` = 没有来源的;否则一个来源 id |
| 113 | #[serde(default)] |
| 114 | pub source: Option<String>, |
| 115 | /// 文件名包含 |
| 116 | #[serde(default)] |
| 117 | pub q: Option<String>, |
| 118 | /// 抽取状态:none | queued | extracting | done | failed |
| 119 | #[serde(default)] |
| 120 | pub graph: Option<String>, |
| 121 | #[serde(default)] |
| 122 | pub limit: Option<i64>, |
| 123 | #[serde(default)] |
| 124 | pub offset: Option<i64>, |
| 125 | } |
| 126 | |
| 127 | /// 文库一页。 |
| 128 | /// |
| 129 | /// **改成服务端筛选与分页**:从前一次取回整库、前端切片。27 篇没事,两万篇会把 |
| 130 | /// 整张表打进浏览器;而客户端筛选还有个更隐蔽的毛病——它只筛得到已经拿下来的那些。 |
| 131 | pub async fn list( |
| 132 | State(state): State<AppState>, |
| 133 | AuthUser(user): AuthUser, |
| 134 | Path(kb_id): Path<Uuid>, |
| 135 | Query(q): Query<DocsQuery>, |
| 136 | ) -> ApiResult<Json<utopia_core::models::DocumentPage>> { |
| 137 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 138 | let page = utopia_store::documents::page( |
| 139 | &state.pool, |
| 140 | kb_id, |
| 141 | parse_scope(q.source.as_deref()), |
| 142 | q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()), |
| 143 | q.graph.as_deref().filter(|s| !s.is_empty()), |
| 144 | q.limit.unwrap_or(15).clamp(1, 200), |
| 145 | q.offset.unwrap_or(0).max(0), |
| 146 | ) |
| 147 | .await?; |
| 148 | Ok(Json(page)) |
| 149 | } |
| 150 | |
| 151 | /// `None` = 全部,`Some(None)` = 没有来源的,`Some(Some(id))` = 某个来源。 |
| 152 | /// |
| 153 | /// 认不出的字符串当成「全部」而不是报错:这个参数来自界面上的一次点击, |
| 154 | /// 而一次点击不该把整页变成一条错误。 |
| 155 | fn parse_scope(raw: Option<&str>) -> Option<Option<Uuid>> { |
| 156 | match raw { |
| 157 | None | Some("") => None, |
| 158 | Some("none") => Some(None), |
| 159 | Some(s) => s.parse().ok().map(Some), |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// 一键重试这个作用域里全部抽取失败的文档。 |
| 164 | /// |
| 165 | /// **存在的理由是一条条点太慢**:一个来源里五篇失败就是点五次,而失败往往是 |
| 166 | /// 成批的(模型端点断了一阵,那段时间进来的全挂)。 |
| 167 | pub async fn retry_failed( |
| 168 | State(state): State<AppState>, |
| 169 | AuthUser(user): AuthUser, |
| 170 | Path(kb_id): Path<Uuid>, |
| 171 | Query(q): Query<DocsQuery>, |
| 172 | ) -> ApiResult<Json<serde_json::Value>> { |
| 173 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?; |
| 174 | let ids = |
| 175 | utopia_store::documents::failed_ids(&state.pool, kb_id, parse_scope(q.source.as_deref())) |
| 176 | .await?; |
| 177 | // 逐个入队而不是一条 SQL 批量改状态:排队本身有别的动作(解雇在跑的任务、 |
| 178 | // 清增量标记),那些在 `queue_extraction_one` 里,绕过它会留下半截状态 |
| 179 | let mut queued = 0usize; |
| 180 | for id in &ids { |
| 181 | if utopia_store::documents::queue_extraction_one(&state.pool, *id) |
| 182 | .await |
| 183 | .is_ok() |
| 184 | { |
| 185 | queued += 1; |
| 186 | } |
| 187 | } |
| 188 | if queued > 0 { |
| 189 | state.emit_document(kb_id, ids[0]); |
| 190 | } |
| 191 | Ok(Json(json!({ "queued": queued, "found": ids.len() }))) |
| 192 | } |
| 193 | |
| 194 | /// 文档详情 + 全部分块(文档查看器用)。 |
| 195 | pub async fn detail( |
| 196 | State(state): State<AppState>, |
| 197 | AuthUser(user): AuthUser, |
| 198 | Path(id): Path<Uuid>, |
| 199 | ) -> ApiResult<Json<serde_json::Value>> { |
| 200 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 201 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Viewer).await?; |
| 202 | let chunks = utopia_store::documents::chunks_full(&state.pool, id).await?; |
| 203 | Ok(Json(json!({ "document": doc, "chunks": chunks }))) |
| 204 | } |
| 205 | |
| 206 | /// 反向证据链:文档各分块抽出的事实(文档查看器右栏)。 |
| 207 | pub async fn extractions( |
| 208 | State(state): State<AppState>, |
| 209 | AuthUser(user): AuthUser, |
| 210 | Path(id): Path<Uuid>, |
| 211 | ) -> ApiResult<Json<serde_json::Value>> { |
| 212 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 213 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Viewer).await?; |
| 214 | let facts = utopia_store::graph::document_extractions(&state.pool, id).await?; |
| 215 | Ok(Json(json!({ "facts": facts }))) |
| 216 | } |
| 217 | |
| 218 | pub async fn delete( |
| 219 | State(state): State<AppState>, |
| 220 | AuthUser(user): AuthUser, |
| 221 | Path(id): Path<Uuid>, |
| 222 | ) -> ApiResult<Json<serde_json::Value>> { |
| 223 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 224 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?; |
| 225 | |
| 226 | utopia_store::documents::delete(&state.pool, id).await?; |
| 227 | let search = state.search.clone(); |
| 228 | let did = id.to_string(); |
| 229 | tokio::task::spawn_blocking(move || search.delete_document(&did)) |
| 230 | .await |
| 231 | .map_err(|e| AppError::Other(e.into()))? |
| 232 | .map_err(AppError::Other)?; |
| 233 | let _ = utopia_store::audit::record( |
| 234 | &state.pool, |
| 235 | Some(doc.kb_id), |
| 236 | user.id, |
| 237 | "document.deleted", |
| 238 | "document", |
| 239 | Some(id), |
| 240 | json!({ "filename": doc.filename }), |
| 241 | ) |
| 242 | .await; |
| 243 | Ok(Json(json!({ "ok": true }))) |
| 244 | } |
| 245 | |
| 246 | /// 重新处理(解析器升级/失败重试)。 |
| 247 | pub async fn reprocess( |
| 248 | State(state): State<AppState>, |
| 249 | AuthUser(user): AuthUser, |
| 250 | Path(id): Path<Uuid>, |
| 251 | ) -> ApiResult<Json<serde_json::Value>> { |
| 252 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 253 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?; |
| 254 | utopia_store::documents::set_status(&state.pool, id, "pending").await?; |
| 255 | let job_id = utopia_store::jobs::enqueue( |
| 256 | &state.pool, |
| 257 | "process_document", |
| 258 | json!({ "document_id": id }), |
| 259 | ) |
| 260 | .await?; |
| 261 | Ok(Json(json!({ "job_id": job_id }))) |
| 262 | } |
| 263 | |
| 264 | fn hex(bytes: &[u8]) -> String { |
| 265 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 266 | } |
| 267 | |
| 268 | /// 抽取丢弃信号:哪些事实抽出来了却没能落地。整库一次取回——按 |
| 269 | /// (文档 × 原因 × 具体对象) 聚合后行数很小,Library 既算总数又展开详情, |
| 270 | /// 不必逐行发请求。 |
| 271 | pub async fn extraction_drops( |
| 272 | State(state): State<AppState>, |
| 273 | AuthUser(user): AuthUser, |
| 274 | Path(kb_id): Path<Uuid>, |
| 275 | ) -> ApiResult<Json<serde_json::Value>> { |
| 276 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 277 | let drops = utopia_store::extraction_drops::for_kb(&state.pool, kb_id).await?; |
| 278 | Ok(Json(json!({ "drops": drops }))) |
| 279 | } |