| 1 | //! 来源管理 API + 文本推送摄入(ingest)。 |
| 2 | |
| 3 | use axum::extract::{Path, State}; |
| 4 | use axum::http::HeaderMap; |
| 5 | use axum::Json; |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use serde::Deserialize; |
| 8 | use serde_json::json; |
| 9 | use utopia_core::models::{Role, SOURCE_SECRET_KEYS}; |
| 10 | use uuid::Uuid; |
| 11 | |
| 12 | use super::graph_routes::require_kb; |
| 13 | use crate::auth::AuthUser; |
| 14 | use crate::error::ApiResult; |
| 15 | use crate::state::AppState; |
| 16 | |
| 17 | /// 生成 api 来源的推送密钥。 |
| 18 | fn new_ingest_token() -> String { |
| 19 | format!("utp_{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple()) |
| 20 | } |
| 21 | |
| 22 | /// 取一条来源,并确认它属于路径上的这个库。 |
| 23 | /// |
| 24 | /// `require_kb` 只查人对库的权限;来源 id 是另一个维度——不比对的话,A 库的 |
| 25 | /// Editor 拿着 B 库来源的 id 就能同步、清理、删除它。不属于就当不存在(404), |
| 26 | /// 与 `get_token` 一直以来的做法一致 |
| 27 | async fn source_in_kb( |
| 28 | state: &AppState, |
| 29 | kb_id: Uuid, |
| 30 | source_id: Uuid, |
| 31 | ) -> ApiResult<utopia_core::models::Source> { |
| 32 | let source = utopia_store::sources::get(&state.pool, source_id).await?; |
| 33 | if source.kb_id != kb_id { |
| 34 | return Err(utopia_core::AppError::NotFound.into()); |
| 35 | } |
| 36 | Ok(source) |
| 37 | } |
| 38 | |
| 39 | pub async fn list( |
| 40 | State(state): State<AppState>, |
| 41 | AuthUser(user): AuthUser, |
| 42 | Path(kb_id): Path<Uuid>, |
| 43 | ) -> ApiResult<Json<serde_json::Value>> { |
| 44 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 45 | let sources = utopia_store::sources::list(&state.pool, kb_id).await?; |
| 46 | Ok(Json(json!({ "sources": sources }))) |
| 47 | } |
| 48 | |
| 49 | #[derive(Deserialize)] |
| 50 | pub struct CreateBody { |
| 51 | pub kind: String, |
| 52 | pub name: String, |
| 53 | #[serde(default)] |
| 54 | pub config: serde_json::Value, |
| 55 | #[serde(default)] |
| 56 | pub icon: Option<String>, |
| 57 | #[serde(default)] |
| 58 | pub sync_interval_minutes: Option<i32>, |
| 59 | /// 标准 5 段 cron(与 interval 互斥,二者传其一) |
| 60 | #[serde(default)] |
| 61 | pub sync_cron: Option<String>, |
| 62 | } |
| 63 | |
| 64 | pub async fn create( |
| 65 | State(state): State<AppState>, |
| 66 | AuthUser(user): AuthUser, |
| 67 | Path(kb_id): Path<Uuid>, |
| 68 | Json(body): Json<CreateBody>, |
| 69 | ) -> ApiResult<Json<serde_json::Value>> { |
| 70 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 71 | let source = utopia_store::sources::create( |
| 72 | &state.pool, |
| 73 | kb_id, |
| 74 | &body.kind, |
| 75 | &body.name, |
| 76 | &body.config, |
| 77 | body.icon.as_deref(), |
| 78 | body.sync_interval_minutes, |
| 79 | body.sync_cron.as_deref(), |
| 80 | ) |
| 81 | .await?; |
| 82 | // 拉取型来源建好立即同步一次(有配置即产出,无需等下一个调度周期) |
| 83 | if matches!(source.kind.as_str(), "url" | "rss" | "custom") { |
| 84 | let _ = utopia_store::sources::mark_queued(&state.pool, source.id).await; |
| 85 | utopia_store::jobs::enqueue( |
| 86 | &state.pool, |
| 87 | "sync_source", |
| 88 | json!({ "source_id": source.id }), |
| 89 | ) |
| 90 | .await?; |
| 91 | } |
| 92 | // api 来源:生成专属推送密钥(此后可随时经 get_token 查看) |
| 93 | let mut ingest_token: Option<String> = None; |
| 94 | if source.kind == "api" { |
| 95 | let token = new_ingest_token(); |
| 96 | utopia_store::sources::set_ingest_token(&state.pool, source.id, &token).await?; |
| 97 | ingest_token = Some(token); |
| 98 | } |
| 99 | state.emit_source(kb_id); |
| 100 | let _ = utopia_store::audit::record( |
| 101 | &state.pool, |
| 102 | Some(kb_id), |
| 103 | user.id, |
| 104 | "source.created", |
| 105 | "source", |
| 106 | Some(source.id), |
| 107 | json!({ "kind": source.kind, "name": source.name }), |
| 108 | ) |
| 109 | .await; |
| 110 | Ok(Json( |
| 111 | json!({ "source": mask_secrets(source), "ingest_token": ingest_token }), |
| 112 | )) |
| 113 | } |
| 114 | |
| 115 | /// 查看 api 来源的推送密钥(Editor;列表响应从不携带,查看走这里)。 |
| 116 | pub async fn get_token( |
| 117 | State(state): State<AppState>, |
| 118 | AuthUser(user): AuthUser, |
| 119 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 120 | ) -> ApiResult<Json<serde_json::Value>> { |
| 121 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 122 | let source = source_in_kb(&state, kb_id, source_id).await?; |
| 123 | if source.kind != "api" { |
| 124 | return Err(utopia_core::AppError::NotFound.into()); |
| 125 | } |
| 126 | Ok(Json(json!({ "ingest_token": source.ingest_token }))) |
| 127 | } |
| 128 | |
| 129 | /// 轮换 api 来源的推送密钥:旧密钥立即失效。 |
| 130 | pub async fn rotate_token( |
| 131 | State(state): State<AppState>, |
| 132 | AuthUser(user): AuthUser, |
| 133 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 134 | ) -> ApiResult<Json<serde_json::Value>> { |
| 135 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 136 | let source = source_in_kb(&state, kb_id, source_id).await?; |
| 137 | if source.kind != "api" { |
| 138 | return Err(utopia_core::AppError::NotFound.into()); |
| 139 | } |
| 140 | let token = new_ingest_token(); |
| 141 | utopia_store::sources::set_ingest_token(&state.pool, source_id, &token).await?; |
| 142 | Ok(Json(json!({ "ingest_token": token }))) |
| 143 | } |
| 144 | |
| 145 | /// 响应前剔除凭据(只进不出;键见 `SOURCE_SECRET_KEYS`)。 |
| 146 | fn mask_secrets(source: utopia_core::models::Source) -> utopia_core::models::Source { |
| 147 | source.without_secrets() |
| 148 | } |
| 149 | |
| 150 | /// 更新时凭据的合并规则,每个 `SOURCE_SECRET_KEYS` 里的键一样:新配置里**没有**这个键 |
| 151 | /// 或值是空串 → 保留库里的原值(表单留空就是「别动」);显式 `null` → 删掉; |
| 152 | /// 其余照新值。响应从不回显,所以客户端没有办法把旧值原样送回来,规则只能长在这里 |
| 153 | fn keep_secrets(next: &mut serde_json::Value, existing: &serde_json::Value) { |
| 154 | let Some(obj) = next.as_object_mut() else { |
| 155 | return; |
| 156 | }; |
| 157 | for key in SOURCE_SECRET_KEYS { |
| 158 | let keep = match obj.get(*key) { |
| 159 | None => true, |
| 160 | Some(serde_json::Value::Null) => { |
| 161 | obj.remove(*key); |
| 162 | false |
| 163 | } |
| 164 | Some(v) => v.as_str().is_some_and(|s| s.trim().is_empty()), |
| 165 | }; |
| 166 | if keep { |
| 167 | obj.remove(*key); |
| 168 | if let Some(prev) = existing.get(*key) { |
| 169 | obj.insert((*key).to_string(), prev.clone()); |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | #[derive(Deserialize)] |
| 176 | pub struct UpdateBody { |
| 177 | pub name: Option<String>, |
| 178 | pub config: Option<serde_json::Value>, |
| 179 | pub icon: Option<String>, |
| 180 | /// 出现 schedule 字段即整体覆盖调度(interval 与 cron 互斥;两者皆 null = 关闭定时) |
| 181 | #[serde(default)] |
| 182 | pub schedule: Option<ScheduleBody>, |
| 183 | } |
| 184 | |
| 185 | #[derive(Deserialize)] |
| 186 | pub struct ScheduleBody { |
| 187 | #[serde(default)] |
| 188 | pub sync_interval_minutes: Option<i32>, |
| 189 | #[serde(default)] |
| 190 | pub sync_cron: Option<String>, |
| 191 | } |
| 192 | |
| 193 | pub async fn update( |
| 194 | State(state): State<AppState>, |
| 195 | AuthUser(user): AuthUser, |
| 196 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 197 | Json(body): Json<UpdateBody>, |
| 198 | ) -> ApiResult<Json<serde_json::Value>> { |
| 199 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 200 | let existing = source_in_kb(&state, kb_id, source_id).await?; |
| 201 | // 凭据只进不出:响应从不回显,表单留空 / 没传 = 保留库里原值 |
| 202 | let mut config = body.config; |
| 203 | if let Some(cfg) = config.as_mut() { |
| 204 | keep_secrets(cfg, &existing.config); |
| 205 | } |
| 206 | let source = utopia_store::sources::update( |
| 207 | &state.pool, |
| 208 | source_id, |
| 209 | body.name.as_deref(), |
| 210 | config.as_ref(), |
| 211 | body.icon.as_deref(), |
| 212 | body.schedule |
| 213 | .map(|s| (s.sync_interval_minutes, s.sync_cron)), |
| 214 | ) |
| 215 | .await?; |
| 216 | state.emit_source(kb_id); |
| 217 | // 审计不落凭据:config 只记「改没改」 |
| 218 | let _ = utopia_store::audit::record( |
| 219 | &state.pool, |
| 220 | Some(kb_id), |
| 221 | user.id, |
| 222 | "source.updated", |
| 223 | "source", |
| 224 | Some(source_id), |
| 225 | json!({ "name": body.name, "config_changed": config.is_some() }), |
| 226 | ) |
| 227 | .await; |
| 228 | Ok(Json(json!({ "source": mask_secrets(source) }))) |
| 229 | } |
| 230 | |
| 231 | /// 批量删除该来源下所有"不在来源中"的文档(url 对账 / custom 墓碑标出的)。 |
| 232 | pub async fn cleanup_missing( |
| 233 | State(state): State<AppState>, |
| 234 | AuthUser(user): AuthUser, |
| 235 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 236 | ) -> ApiResult<Json<serde_json::Value>> { |
| 237 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 238 | source_in_kb(&state, kb_id, source_id).await?; |
| 239 | let ids = utopia_store::documents::list_missing(&state.pool, source_id).await?; |
| 240 | for id in &ids { |
| 241 | utopia_store::documents::delete(&state.pool, *id).await?; |
| 242 | let search = state.search.clone(); |
| 243 | let did = id.to_string(); |
| 244 | tokio::task::spawn_blocking(move || search.delete_document(&did)) |
| 245 | .await |
| 246 | .map_err(|e| utopia_core::AppError::Other(e.into()))? |
| 247 | .map_err(utopia_core::AppError::Other)?; |
| 248 | } |
| 249 | state.emit_source(kb_id); |
| 250 | Ok(Json(json!({ "deleted": ids.len() }))) |
| 251 | } |
| 252 | |
| 253 | pub async fn delete( |
| 254 | State(state): State<AppState>, |
| 255 | AuthUser(user): AuthUser, |
| 256 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 257 | ) -> ApiResult<Json<serde_json::Value>> { |
| 258 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 259 | // Memory 来源常驻:记忆空间不因来源整理而蒸发(记忆文档本身可在 Library 删除) |
| 260 | let source = source_in_kb(&state, kb_id, source_id).await?; |
| 261 | if source.kind == utopia_store::memory::MEMORY_SOURCE_KIND { |
| 262 | return Err(utopia_core::AppError::invalid( |
| 263 | "memory_source_permanent", |
| 264 | "The Memory source is permanent.", |
| 265 | ) |
| 266 | .into()); |
| 267 | } |
| 268 | utopia_store::sources::delete(&state.pool, source_id).await?; |
| 269 | state.emit_source(kb_id); |
| 270 | let _ = utopia_store::audit::record( |
| 271 | &state.pool, |
| 272 | Some(kb_id), |
| 273 | user.id, |
| 274 | "source.deleted", |
| 275 | "source", |
| 276 | Some(source_id), |
| 277 | json!({}), |
| 278 | ) |
| 279 | .await; |
| 280 | Ok(Json(json!({ "ok": true }))) |
| 281 | } |
| 282 | |
| 283 | /// 同步运行历史(渠道审计)。 |
| 284 | pub async fn runs( |
| 285 | State(state): State<AppState>, |
| 286 | AuthUser(user): AuthUser, |
| 287 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 288 | ) -> ApiResult<Json<serde_json::Value>> { |
| 289 | require_kb(&state, &user, kb_id, Role::Viewer).await?; |
| 290 | source_in_kb(&state, kb_id, source_id).await?; |
| 291 | let runs = utopia_store::sources::list_runs(&state.pool, source_id, 20).await?; |
| 292 | Ok(Json(json!({ "runs": runs }))) |
| 293 | } |
| 294 | |
| 295 | pub async fn sync_now( |
| 296 | State(state): State<AppState>, |
| 297 | AuthUser(user): AuthUser, |
| 298 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 299 | ) -> ApiResult<Json<serde_json::Value>> { |
| 300 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 301 | source_in_kb(&state, kb_id, source_id).await?; |
| 302 | let queued = utopia_store::sources::mark_queued(&state.pool, source_id).await?; |
| 303 | if queued { |
| 304 | utopia_store::jobs::enqueue( |
| 305 | &state.pool, |
| 306 | "sync_source", |
| 307 | json!({ "source_id": source_id }), |
| 308 | ) |
| 309 | .await?; |
| 310 | state.emit_source(kb_id); |
| 311 | } |
| 312 | Ok(Json(json!({ "queued": queued }))) |
| 313 | } |
| 314 | |
| 315 | #[derive(Deserialize)] |
| 316 | pub struct IngestBody { |
| 317 | pub filename: String, |
| 318 | /// 墓碑推送(`deleted: true`)可以不带 content——指南一直这么写,而字段 |
| 319 | /// 从前是必填,缺了就在反序列化那一步被拒。其余情况仍然必填:空串在 |
| 320 | /// 下面的校验里挡 |
| 321 | #[serde(default)] |
| 322 | pub content: String, |
| 323 | #[serde(default)] |
| 324 | pub doc_time: Option<DateTime<Utc>>, |
| 325 | /// 调用方的逻辑文档 ID:同 ID 再推 = 更新同一文档(原地替换 + 版本记录)。 |
| 326 | /// 不传则以 filename 为身份。 |
| 327 | #[serde(default)] |
| 328 | pub external_id: Option<String>, |
| 329 | /// 墓碑:true = 按身份标记"不在来源中"(不删除;仅 api 来源推送支持)。 |
| 330 | /// 此时 content 可省略;再次正常推送同身份会摘掉标记。 |
| 331 | #[serde(default)] |
| 332 | pub deleted: bool, |
| 333 | } |
| 334 | |
| 335 | fn action_str(action: crate::ingest_sources::IngestAction) -> &'static str { |
| 336 | match action { |
| 337 | crate::ingest_sources::IngestAction::Created => "created", |
| 338 | crate::ingest_sources::IngestAction::Updated => "updated", |
| 339 | crate::ingest_sources::IngestAction::Moved => "moved", |
| 340 | crate::ingest_sources::IngestAction::Unchanged => "unchanged", |
| 341 | crate::ingest_sources::IngestAction::Tombstoned => "marked_missing", |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | /// KB 级文本推送(会话认证):普通上传语义——落入 Uploads,无身份追踪。 |
| 346 | /// 需要"同 ID 再推 = 更新"语义时,建一个 api 来源用它的密钥推送。 |
| 347 | pub async fn ingest( |
| 348 | State(state): State<AppState>, |
| 349 | AuthUser(user): AuthUser, |
| 350 | Path(kb_id): Path<Uuid>, |
| 351 | Json(body): Json<IngestBody>, |
| 352 | ) -> ApiResult<Json<serde_json::Value>> { |
| 353 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 354 | if body.deleted { |
| 355 | return Err(utopia_core::AppError::Validation( |
| 356 | "tombstones need identity tracking — push to an api source instead".into(), |
| 357 | ) |
| 358 | .into()); |
| 359 | } |
| 360 | if body.filename.trim().is_empty() || body.content.trim().is_empty() { |
| 361 | return Err( |
| 362 | utopia_core::AppError::Validation("filename and content are required".into()).into(), |
| 363 | ); |
| 364 | } |
| 365 | let action = crate::ingest_sources::ingest_upload( |
| 366 | &state, |
| 367 | kb_id, |
| 368 | body.filename.trim(), |
| 369 | "text/plain", |
| 370 | body.content.as_bytes(), |
| 371 | body.doc_time, |
| 372 | ) |
| 373 | .await |
| 374 | .map_err(utopia_core::AppError::Other)?; |
| 375 | Ok(Json(json!({ "action": action_str(action) }))) |
| 376 | } |
| 377 | |
| 378 | /// 推送失败的两种性质。**调用方发错了**和**我们这边没接住**得分开:前者记进 |
| 379 | /// run 供集成调试,但不算来源同步失败——来源没坏,是那一次请求不合格; |
| 380 | /// 后者才该把来源标成 failed 并进告警中心。从前两者都走 `finish_sync(error)`, |
| 381 | /// 一次格式错误就让铃铛说"来源同步失败,没有新内容进来" |
| 382 | enum PushError { |
| 383 | /// 4xx:负载不合格(JSON 解析、缺字段) |
| 384 | Rejected(String), |
| 385 | /// 摄入本身失败 |
| 386 | Failed(String), |
| 387 | } |
| 388 | |
| 389 | impl PushError { |
| 390 | fn message(&self) -> &str { |
| 391 | match self { |
| 392 | PushError::Rejected(m) | PushError::Failed(m) => m, |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// 认证之后的推送处理:解析 + 校验 + 摄入/墓碑。错误一律返回文字(记进 run)。 |
| 398 | async fn handle_push( |
| 399 | state: &AppState, |
| 400 | source: &utopia_core::models::Source, |
| 401 | bytes: &[u8], |
| 402 | ) -> Result<crate::ingest_sources::IngestAction, PushError> { |
| 403 | let body: IngestBody = serde_json::from_slice(bytes) |
| 404 | .map_err(|e| PushError::Rejected(format!("Invalid JSON payload: {e}")))?; |
| 405 | let identity = body |
| 406 | .external_id |
| 407 | .as_deref() |
| 408 | .map(str::trim) |
| 409 | .filter(|s| !s.is_empty()) |
| 410 | .unwrap_or_else(|| body.filename.trim()) |
| 411 | .to_string(); |
| 412 | if identity.is_empty() { |
| 413 | return Err(PushError::Rejected( |
| 414 | "external_id or filename is required".into(), |
| 415 | )); |
| 416 | } |
| 417 | let key = format!("api:{identity}"); |
| 418 | |
| 419 | // 墓碑:标记"不在来源中"(与 custom 的 deleted[] 同一条路径),content 可省略 |
| 420 | if body.deleted { |
| 421 | utopia_store::documents::mark_missing_keys(&state.pool, source.id, &[key]) |
| 422 | .await |
| 423 | .map_err(|e| PushError::Failed(e.to_string()))?; |
| 424 | return Ok(crate::ingest_sources::IngestAction::Tombstoned); |
| 425 | } |
| 426 | |
| 427 | if body.filename.trim().is_empty() || body.content.trim().is_empty() { |
| 428 | return Err(PushError::Rejected( |
| 429 | "filename and content are required".into(), |
| 430 | )); |
| 431 | } |
| 432 | let action = crate::ingest_sources::ingest_item( |
| 433 | state, |
| 434 | source.kb_id, |
| 435 | source.id, |
| 436 | &key, |
| 437 | body.filename.trim(), |
| 438 | "text/plain", |
| 439 | body.content.as_bytes(), |
| 440 | body.doc_time, |
| 441 | ) |
| 442 | .await |
| 443 | .map_err(|e| PushError::Failed(e.to_string()))?; |
| 444 | // 失而复得:曾被墓碑标记的身份再次正常推送,摘掉 missing 标记 |
| 445 | utopia_store::documents::clear_missing_keys(&state.pool, source.id, &[key]) |
| 446 | .await |
| 447 | .map_err(|e| PushError::Failed(e.to_string()))?; |
| 448 | Ok(action) |
| 449 | } |
| 450 | |
| 451 | /// api 来源推送(来源专属密钥认证,无会话):三路身份语义—— |
| 452 | /// 新 external_id → 新增;同 ID 同内容 → 无操作;同 ID 新内容 → 原地更新 + 版本记录。 |
| 453 | /// 认证通过后每次推送都记一条 run(含格式错误——集成调试全靠它); |
| 454 | /// 未认证请求不写任何记录(不给匿名流量制造落库路径)。 |
| 455 | pub async fn push( |
| 456 | State(state): State<AppState>, |
| 457 | Path(source_id): Path<Uuid>, |
| 458 | headers: HeaderMap, |
| 459 | bytes: axum::body::Bytes, |
| 460 | ) -> ApiResult<Json<serde_json::Value>> { |
| 461 | let source = utopia_store::sources::get(&state.pool, source_id).await?; |
| 462 | if source.kind != "api" { |
| 463 | return Err(utopia_core::AppError::NotFound.into()); |
| 464 | } |
| 465 | // Bearer 密钥校验 |
| 466 | let token = headers |
| 467 | .get("authorization") |
| 468 | .and_then(|v| v.to_str().ok()) |
| 469 | .and_then(|v| v.strip_prefix("Bearer ")) |
| 470 | .map(str::trim) |
| 471 | .filter(|s| !s.is_empty()) |
| 472 | .ok_or(utopia_core::AppError::Unauthorized)?; |
| 473 | if source.ingest_token.as_deref() != Some(token) { |
| 474 | return Err(utopia_core::AppError::Unauthorized.into()); |
| 475 | } |
| 476 | |
| 477 | let run = utopia_store::sources::start_run(&state.pool, source.id).await?; |
| 478 | match handle_push(&state, &source, &bytes).await { |
| 479 | Ok(action) => { |
| 480 | let (created, updated) = match action { |
| 481 | crate::ingest_sources::IngestAction::Created => (1, 0), |
| 482 | crate::ingest_sources::IngestAction::Updated |
| 483 | | crate::ingest_sources::IngestAction::Moved => (0, 1), |
| 484 | crate::ingest_sources::IngestAction::Unchanged |
| 485 | | crate::ingest_sources::IngestAction::Tombstoned => (0, 0), |
| 486 | }; |
| 487 | utopia_store::sources::finish_run(&state.pool, run, source.id, None, created, updated) |
| 488 | .await?; |
| 489 | // 来源行同步反映"上一次推送":操作条/左栏状态点直接可用 |
| 490 | utopia_store::sources::finish_sync(&state.pool, source.id, None, created).await?; |
| 491 | state.emit_source(source.kb_id); |
| 492 | Ok(Json(json!({ "action": action_str(action) }))) |
| 493 | } |
| 494 | Err(err) => { |
| 495 | let msg = err.message().to_string(); |
| 496 | utopia_store::sources::finish_run(&state.pool, run, source.id, Some(&msg), 0, 0) |
| 497 | .await?; |
| 498 | // 只有我们这边没接住才算来源失败;调用方发错了留在 run 历史里就够 |
| 499 | if let PushError::Failed(_) = err { |
| 500 | utopia_store::sources::finish_sync(&state.pool, source.id, Some(&msg), 0).await?; |
| 501 | } |
| 502 | state.emit_source(source.kb_id); |
| 503 | Err(utopia_core::AppError::Validation(msg).into()) |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// 来源级全量重抽(增量语义):该来源下所有 ready 文档重新过一遍抽取。 |
| 509 | /// 走正常管道——实体消解、事实去重、时态冲突照常,既有人工决策全部保留。 |
| 510 | pub async fn re_extract( |
| 511 | State(state): State<AppState>, |
| 512 | AuthUser(user): AuthUser, |
| 513 | Path((kb_id, source_id)): Path<(Uuid, Uuid)>, |
| 514 | ) -> ApiResult<Json<serde_json::Value>> { |
| 515 | require_kb(&state, &user, kb_id, Role::Editor).await?; |
| 516 | let source = utopia_store::sources::get(&state.pool, source_id).await?; |
| 517 | if source.kb_id != kb_id { |
| 518 | return Err(utopia_core::AppError::NotFound.into()); |
| 519 | } |
| 520 | // 任务由 queue_extraction 与状态同事务建好,这里只负责推送 |
| 521 | let ids = |
| 522 | utopia_store::documents::queue_extraction(&state.pool, kb_id, Some(source_id)).await?; |
| 523 | for id in &ids { |
| 524 | state.emit_document(kb_id, *id); |
| 525 | } |
| 526 | let _ = utopia_store::audit::record( |
| 527 | &state.pool, |
| 528 | Some(kb_id), |
| 529 | user.id, |
| 530 | "source.re_extract", |
| 531 | "source", |
| 532 | Some(source_id), |
| 533 | json!({ "name": source.name, "documents": ids.len() }), |
| 534 | ) |
| 535 | .await; |
| 536 | Ok(Json(json!({ "queued": ids.len() }))) |
| 537 | } |
| 538 | |
| 539 | #[cfg(test)] |
| 540 | mod tests { |
| 541 | use super::keep_secrets; |
| 542 | use serde_json::json; |
| 543 | |
| 544 | #[test] |
| 545 | fn a_blank_or_missing_secret_keeps_the_stored_one() { |
| 546 | let existing = json!({ "bucket": "old", "secret_access_key": "s", "password": "p" }); |
| 547 | // 没传 → 留;空串 → 留;有值 → 换;null → 删 |
| 548 | let mut next = json!({ "bucket": "new", "password": " ", "token": null }); |
| 549 | keep_secrets(&mut next, &existing); |
| 550 | assert_eq!(next["bucket"], "new"); |
| 551 | assert_eq!( |
| 552 | next["secret_access_key"], "s", |
| 553 | "missing keeps the stored value" |
| 554 | ); |
| 555 | assert_eq!(next["password"], "p", "blank keeps the stored value"); |
| 556 | assert!(next.get("token").is_none(), "an explicit null removes it"); |
| 557 | let mut next = json!({ "secret_access_key": "fresh" }); |
| 558 | keep_secrets(&mut next, &existing); |
| 559 | assert_eq!(next["secret_access_key"], "fresh"); |
| 560 | assert_eq!(next["password"], "p"); |
| 561 | } |
| 562 | |
| 563 | #[test] |
| 564 | fn no_secret_reaches_a_response() { |
| 565 | let source = utopia_core::models::Source { |
| 566 | id: uuid::Uuid::nil(), |
| 567 | kb_id: uuid::Uuid::nil(), |
| 568 | kind: "s3".into(), |
| 569 | name: "s".into(), |
| 570 | config: json!({ "bucket": "b", "access_key_id": "AKIA", "secret_access_key": "x", |
| 571 | "account_key": "y", "service_account_key": "z", "password": "w", |
| 572 | "token": "t", "auth_header": "h" }), |
| 573 | icon: None, |
| 574 | sync_interval_minutes: None, |
| 575 | sync_cron: None, |
| 576 | last_sync_at: None, |
| 577 | last_sync_status: "never".into(), |
| 578 | last_sync_error: None, |
| 579 | last_sync_added: 0, |
| 580 | ingest_token: Some("utp_x".into()), |
| 581 | created_at: chrono::Utc::now(), |
| 582 | }; |
| 583 | let masked = super::mask_secrets(source); |
| 584 | let obj = masked.config.as_object().unwrap(); |
| 585 | for key in utopia_core::models::SOURCE_SECRET_KEYS { |
| 586 | assert!(!obj.contains_key(*key), "{key} leaked"); |
| 587 | } |
| 588 | assert_eq!(obj["bucket"], "b"); |
| 589 | assert_eq!( |
| 590 | obj["access_key_id"], "AKIA", |
| 591 | "an identifier is not a secret" |
| 592 | ); |
| 593 | } |
| 594 | } |