Elffuss BraidHub

kikocis/utopia public

2d1966ff85f5 · 16.8 KiBRawPermalink
1//! 来源管理 API + 文本推送摄入(ingest)。
2
3use axum::extract::{Path, State};
4use axum::http::HeaderMap;
5use axum::Json;
6use chrono::{DateTime, Utc};
7use serde::Deserialize;
8use serde_json::json;
9use utopia_core::models::Role;
10use uuid::Uuid;
11
12use super::graph_routes::require_kb;
13use crate::auth::AuthUser;
14use crate::error::ApiResult;
15use crate::state::AppState;
16
17/// 生成 api 来源的推送密钥。
18fn new_ingest_token() -> String {
19 format!("utp_{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
20}
21
22pub async fn list(
23 State(state): State<AppState>,
24 AuthUser(user): AuthUser,
25 Path(kb_id): Path<Uuid>,
26) -> ApiResult<Json<serde_json::Value>> {
27 require_kb(&state, &user, kb_id, Role::Viewer).await?;
28 let sources = utopia_store::sources::list(&state.pool, kb_id).await?;
29 Ok(Json(json!({ "sources": sources })))
30}
31
32#[derive(Deserialize)]
33pub struct CreateBody {
34 pub kind: String,
35 pub name: String,
36 #[serde(default)]
37 pub config: serde_json::Value,
38 #[serde(default)]
39 pub icon: Option<String>,
40 #[serde(default)]
41 pub sync_interval_minutes: Option<i32>,
42 /// 标准 5 段 cron(与 interval 互斥,二者传其一)
43 #[serde(default)]
44 pub sync_cron: Option<String>,
45}
46
47pub async fn create(
48 State(state): State<AppState>,
49 AuthUser(user): AuthUser,
50 Path(kb_id): Path<Uuid>,
51 Json(body): Json<CreateBody>,
52) -> ApiResult<Json<serde_json::Value>> {
53 require_kb(&state, &user, kb_id, Role::Editor).await?;
54 let source = utopia_store::sources::create(
55 &state.pool,
56 kb_id,
57 &body.kind,
58 &body.name,
59 &body.config,
60 body.icon.as_deref(),
61 body.sync_interval_minutes,
62 body.sync_cron.as_deref(),
63 )
64 .await?;
65 // 拉取型来源建好立即同步一次(有配置即产出,无需等下一个调度周期)
66 if matches!(source.kind.as_str(), "url" | "rss" | "custom") {
67 let _ = utopia_store::sources::mark_queued(&state.pool, source.id).await;
68 utopia_store::jobs::enqueue(
69 &state.pool,
70 "sync_source",
71 json!({ "source_id": source.id }),
72 )
73 .await?;
74 }
75 // api 来源:生成专属推送密钥(此后可随时经 get_token 查看)
76 let mut ingest_token: Option<String> = None;
77 if source.kind == "api" {
78 let token = new_ingest_token();
79 utopia_store::sources::set_ingest_token(&state.pool, source.id, &token).await?;
80 ingest_token = Some(token);
81 }
82 state.emit_source(kb_id);
83 let _ = utopia_store::audit::record(
84 &state.pool,
85 Some(kb_id),
86 user.id,
87 "source.created",
88 "source",
89 Some(source.id),
90 json!({ "kind": source.kind, "name": source.name }),
91 )
92 .await;
93 Ok(Json(
94 json!({ "source": mask_secrets(source), "ingest_token": ingest_token }),
95 ))
96}
97
98/// 查看 api 来源的推送密钥(Editor;列表响应从不携带,查看走这里)。
99pub async fn get_token(
100 State(state): State<AppState>,
101 AuthUser(user): AuthUser,
102 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
103) -> ApiResult<Json<serde_json::Value>> {
104 require_kb(&state, &user, kb_id, Role::Editor).await?;
105 let source = utopia_store::sources::get(&state.pool, source_id).await?;
106 if source.kb_id != kb_id || source.kind != "api" {
107 return Err(utopia_core::AppError::NotFound.into());
108 }
109 Ok(Json(json!({ "ingest_token": source.ingest_token })))
110}
111
112/// 轮换 api 来源的推送密钥:旧密钥立即失效。
113pub async fn rotate_token(
114 State(state): State<AppState>,
115 AuthUser(user): AuthUser,
116 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
117) -> ApiResult<Json<serde_json::Value>> {
118 require_kb(&state, &user, kb_id, Role::Editor).await?;
119 let source = utopia_store::sources::get(&state.pool, source_id).await?;
120 if source.kb_id != kb_id || source.kind != "api" {
121 return Err(utopia_core::AppError::NotFound.into());
122 }
123 let token = new_ingest_token();
124 utopia_store::sources::set_ingest_token(&state.pool, source_id, &token).await?;
125 Ok(Json(json!({ "ingest_token": token })))
126}
127
128/// 响应前剔除凭据(auth_header 只进不出)。
129fn mask_secrets(mut source: utopia_core::models::Source) -> utopia_core::models::Source {
130 if let Some(obj) = source.config.as_object_mut() {
131 obj.remove("auth_header");
132 }
133 source
134}
135
136#[derive(Deserialize)]
137pub struct UpdateBody {
138 pub name: Option<String>,
139 pub config: Option<serde_json::Value>,
140 pub icon: Option<String>,
141 /// 出现 schedule 字段即整体覆盖调度(interval 与 cron 互斥;两者皆 null = 关闭定时)
142 #[serde(default)]
143 pub schedule: Option<ScheduleBody>,
144}
145
146#[derive(Deserialize)]
147pub struct ScheduleBody {
148 #[serde(default)]
149 pub sync_interval_minutes: Option<i32>,
150 #[serde(default)]
151 pub sync_cron: Option<String>,
152}
153
154pub async fn update(
155 State(state): State<AppState>,
156 AuthUser(user): AuthUser,
157 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
158 Json(body): Json<UpdateBody>,
159) -> ApiResult<Json<serde_json::Value>> {
160 require_kb(&state, &user, kb_id, Role::Editor).await?;
161 // 凭据只进不出:响应从不回显 auth_header,表单留空 = 保留库里原值
162 let mut config = body.config;
163 if let Some(cfg) = config.as_mut() {
164 let blank = cfg
165 .get("auth_header")
166 .and_then(|v| v.as_str())
167 .map(str::trim)
168 .is_none_or(|s| s.is_empty());
169 if blank {
170 if let Some(obj) = cfg.as_object_mut() {
171 obj.remove("auth_header");
172 let existing = utopia_store::sources::get(&state.pool, source_id).await?;
173 if let Some(prev) = existing.config.get("auth_header").and_then(|v| v.as_str()) {
174 obj.insert("auth_header".into(), json!(prev));
175 }
176 }
177 }
178 }
179 let source = utopia_store::sources::update(
180 &state.pool,
181 source_id,
182 body.name.as_deref(),
183 config.as_ref(),
184 body.icon.as_deref(),
185 body.schedule
186 .map(|s| (s.sync_interval_minutes, s.sync_cron)),
187 )
188 .await?;
189 state.emit_source(kb_id);
190 // 审计不落凭据:config 只记除 auth_header 外的键
191 let _ = utopia_store::audit::record(
192 &state.pool,
193 Some(kb_id),
194 user.id,
195 "source.updated",
196 "source",
197 Some(source_id),
198 json!({ "name": body.name, "config_changed": config.is_some() }),
199 )
200 .await;
201 Ok(Json(json!({ "source": mask_secrets(source) })))
202}
203
204/// 批量删除该来源下所有"不在来源中"的文档(url 对账 / custom 墓碑标出的)。
205pub async fn cleanup_missing(
206 State(state): State<AppState>,
207 AuthUser(user): AuthUser,
208 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
209) -> ApiResult<Json<serde_json::Value>> {
210 require_kb(&state, &user, kb_id, Role::Editor).await?;
211 let ids = utopia_store::documents::list_missing(&state.pool, source_id).await?;
212 for id in &ids {
213 utopia_store::documents::delete(&state.pool, *id).await?;
214 let search = state.search.clone();
215 let did = id.to_string();
216 tokio::task::spawn_blocking(move || search.delete_document(&did))
217 .await
218 .map_err(|e| utopia_core::AppError::Other(e.into()))?
219 .map_err(utopia_core::AppError::Other)?;
220 }
221 state.emit_source(kb_id);
222 Ok(Json(json!({ "deleted": ids.len() })))
223}
224
225pub async fn delete(
226 State(state): State<AppState>,
227 AuthUser(user): AuthUser,
228 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
229) -> ApiResult<Json<serde_json::Value>> {
230 require_kb(&state, &user, kb_id, Role::Editor).await?;
231 // Memory 来源常驻:记忆空间不因来源整理而蒸发(记忆文档本身可在 Library 删除)
232 let source = utopia_store::sources::get(&state.pool, source_id).await?;
233 if source.kind == utopia_store::memory::MEMORY_SOURCE_KIND {
234 return Err(utopia_core::AppError::invalid(
235 "memory_source_permanent",
236 "The Memory source is permanent.",
237 )
238 .into());
239 }
240 utopia_store::sources::delete(&state.pool, source_id).await?;
241 state.emit_source(kb_id);
242 let _ = utopia_store::audit::record(
243 &state.pool,
244 Some(kb_id),
245 user.id,
246 "source.deleted",
247 "source",
248 Some(source_id),
249 json!({}),
250 )
251 .await;
252 Ok(Json(json!({ "ok": true })))
253}
254
255/// 同步运行历史(渠道审计)。
256pub async fn runs(
257 State(state): State<AppState>,
258 AuthUser(user): AuthUser,
259 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
260) -> ApiResult<Json<serde_json::Value>> {
261 require_kb(&state, &user, kb_id, Role::Viewer).await?;
262 let runs = utopia_store::sources::list_runs(&state.pool, source_id, 20).await?;
263 Ok(Json(json!({ "runs": runs })))
264}
265
266pub async fn sync_now(
267 State(state): State<AppState>,
268 AuthUser(user): AuthUser,
269 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
270) -> ApiResult<Json<serde_json::Value>> {
271 require_kb(&state, &user, kb_id, Role::Editor).await?;
272 let queued = utopia_store::sources::mark_queued(&state.pool, source_id).await?;
273 if queued {
274 utopia_store::jobs::enqueue(
275 &state.pool,
276 "sync_source",
277 json!({ "source_id": source_id }),
278 )
279 .await?;
280 state.emit_source(kb_id);
281 }
282 Ok(Json(json!({ "queued": queued })))
283}
284
285#[derive(Deserialize)]
286pub struct IngestBody {
287 pub filename: String,
288 pub content: String,
289 #[serde(default)]
290 pub doc_time: Option<DateTime<Utc>>,
291 /// 调用方的逻辑文档 ID:同 ID 再推 = 更新同一文档(原地替换 + 版本记录)。
292 /// 不传则以 filename 为身份。
293 #[serde(default)]
294 pub external_id: Option<String>,
295 /// 墓碑:true = 按身份标记"不在来源中"(不删除;仅 api 来源推送支持)。
296 /// 此时 content 可省略;再次正常推送同身份会摘掉标记。
297 #[serde(default)]
298 pub deleted: bool,
299}
300
301fn action_str(action: crate::ingest_sources::IngestAction) -> &'static str {
302 match action {
303 crate::ingest_sources::IngestAction::Created => "created",
304 crate::ingest_sources::IngestAction::Updated => "updated",
305 crate::ingest_sources::IngestAction::Moved => "moved",
306 crate::ingest_sources::IngestAction::Unchanged => "unchanged",
307 crate::ingest_sources::IngestAction::Tombstoned => "marked_missing",
308 }
309}
310
311/// KB 级文本推送(会话认证):普通上传语义——落入 Uploads,无身份追踪。
312/// 需要"同 ID 再推 = 更新"语义时,建一个 api 来源用它的密钥推送。
313pub async fn ingest(
314 State(state): State<AppState>,
315 AuthUser(user): AuthUser,
316 Path(kb_id): Path<Uuid>,
317 Json(body): Json<IngestBody>,
318) -> ApiResult<Json<serde_json::Value>> {
319 require_kb(&state, &user, kb_id, Role::Editor).await?;
320 if body.deleted {
321 return Err(utopia_core::AppError::Validation(
322 "tombstones need identity tracking — push to an api source instead".into(),
323 )
324 .into());
325 }
326 if body.filename.trim().is_empty() || body.content.trim().is_empty() {
327 return Err(
328 utopia_core::AppError::Validation("filename and content are required".into()).into(),
329 );
330 }
331 let action = crate::ingest_sources::ingest_upload(
332 &state,
333 kb_id,
334 body.filename.trim(),
335 "text/plain",
336 body.content.as_bytes(),
337 body.doc_time,
338 )
339 .await
340 .map_err(utopia_core::AppError::Other)?;
341 Ok(Json(json!({ "action": action_str(action) })))
342}
343
344/// 认证之后的推送处理:解析 + 校验 + 摄入/墓碑。错误一律返回文字(记进 run)。
345async fn handle_push(
346 state: &AppState,
347 source: &utopia_core::models::Source,
348 bytes: &[u8],
349) -> Result<crate::ingest_sources::IngestAction, String> {
350 let body: IngestBody =
351 serde_json::from_slice(bytes).map_err(|e| format!("Invalid JSON payload: {e}"))?;
352 let identity = body
353 .external_id
354 .as_deref()
355 .map(str::trim)
356 .filter(|s| !s.is_empty())
357 .unwrap_or_else(|| body.filename.trim())
358 .to_string();
359 if identity.is_empty() {
360 return Err("external_id or filename is required".into());
361 }
362 let key = format!("api:{identity}");
363
364 // 墓碑:标记"不在来源中"(与 custom 的 deleted[] 同一条路径),content 可省略
365 if body.deleted {
366 utopia_store::documents::mark_missing_keys(&state.pool, source.id, &[key])
367 .await
368 .map_err(|e| e.to_string())?;
369 return Ok(crate::ingest_sources::IngestAction::Tombstoned);
370 }
371
372 if body.filename.trim().is_empty() || body.content.trim().is_empty() {
373 return Err("filename and content are required".into());
374 }
375 let action = crate::ingest_sources::ingest_item(
376 state,
377 source.kb_id,
378 source.id,
379 &key,
380 body.filename.trim(),
381 "text/plain",
382 body.content.as_bytes(),
383 body.doc_time,
384 )
385 .await
386 .map_err(|e| e.to_string())?;
387 // 失而复得:曾被墓碑标记的身份再次正常推送,摘掉 missing 标记
388 utopia_store::documents::clear_missing_keys(&state.pool, source.id, &[key])
389 .await
390 .map_err(|e| e.to_string())?;
391 Ok(action)
392}
393
394/// api 来源推送(来源专属密钥认证,无会话):三路身份语义——
395/// 新 external_id → 新增;同 ID 同内容 → 无操作;同 ID 新内容 → 原地更新 + 版本记录。
396/// 认证通过后每次推送都记一条 run(含格式错误——集成调试全靠它);
397/// 未认证请求不写任何记录(不给匿名流量制造落库路径)。
398pub async fn push(
399 State(state): State<AppState>,
400 Path(source_id): Path<Uuid>,
401 headers: HeaderMap,
402 bytes: axum::body::Bytes,
403) -> ApiResult<Json<serde_json::Value>> {
404 let source = utopia_store::sources::get(&state.pool, source_id).await?;
405 if source.kind != "api" {
406 return Err(utopia_core::AppError::NotFound.into());
407 }
408 // Bearer 密钥校验
409 let token = headers
410 .get("authorization")
411 .and_then(|v| v.to_str().ok())
412 .and_then(|v| v.strip_prefix("Bearer "))
413 .map(str::trim)
414 .filter(|s| !s.is_empty())
415 .ok_or(utopia_core::AppError::Unauthorized)?;
416 if source.ingest_token.as_deref() != Some(token) {
417 return Err(utopia_core::AppError::Unauthorized.into());
418 }
419
420 let run = utopia_store::sources::start_run(&state.pool, source.id).await?;
421 match handle_push(&state, &source, &bytes).await {
422 Ok(action) => {
423 let (created, updated) = match action {
424 crate::ingest_sources::IngestAction::Created => (1, 0),
425 crate::ingest_sources::IngestAction::Updated
426 | crate::ingest_sources::IngestAction::Moved => (0, 1),
427 crate::ingest_sources::IngestAction::Unchanged
428 | crate::ingest_sources::IngestAction::Tombstoned => (0, 0),
429 };
430 utopia_store::sources::finish_run(&state.pool, run, source.id, None, created, updated)
431 .await?;
432 // 来源行同步反映"上一次推送":操作条/左栏状态点直接可用
433 utopia_store::sources::finish_sync(&state.pool, source.id, None, created).await?;
434 state.emit_source(source.kb_id);
435 Ok(Json(json!({ "action": action_str(action) })))
436 }
437 Err(msg) => {
438 utopia_store::sources::finish_run(&state.pool, run, source.id, Some(&msg), 0, 0)
439 .await?;
440 utopia_store::sources::finish_sync(&state.pool, source.id, Some(&msg), 0).await?;
441 state.emit_source(source.kb_id);
442 Err(utopia_core::AppError::Validation(msg).into())
443 }
444 }
445}
446
447/// 来源级全量重抽(增量语义):该来源下所有 ready 文档重新过一遍抽取。
448/// 走正常管道——实体消解、事实去重、时态冲突照常,既有人工决策全部保留。
449pub async fn re_extract(
450 State(state): State<AppState>,
451 AuthUser(user): AuthUser,
452 Path((kb_id, source_id)): Path<(Uuid, Uuid)>,
453) -> ApiResult<Json<serde_json::Value>> {
454 require_kb(&state, &user, kb_id, Role::Editor).await?;
455 let source = utopia_store::sources::get(&state.pool, source_id).await?;
456 if source.kb_id != kb_id {
457 return Err(utopia_core::AppError::NotFound.into());
458 }
459 // 任务由 queue_extraction 与状态同事务建好,这里只负责推送
460 let ids =
461 utopia_store::documents::queue_extraction(&state.pool, kb_id, Some(source_id)).await?;
462 for id in &ids {
463 state.emit_document(kb_id, *id);
464 }
465 let _ = utopia_store::audit::record(
466 &state.pool,
467 Some(kb_id),
468 user.id,
469 "source.re_extract",
470 "source",
471 Some(source_id),
472 json!({ "name": source.name, "documents": ids.len() }),
473 )
474 .await;
475 Ok(Json(json!({ "queued": ids.len() })))
476}