Elffuss BraidHub

kikocis/utopia public

95c87338cdc8 · 29.5 KiBRawPermalink
1//! 来源同步任务:url(网页抓取)/ rss(订阅,pubDate → doc_time)/
2//! github_issues / jira_issues(工单,更新时刻 → doc_time,正文里带状态变更史)/
3//! s3(对象存储,LastModified → doc_time)。
4//! 全部走 sha256 去重(重复内容静默跳过),新文档进标准摄入管道(process_document)。
5//! folder 是纯容器(上传入内),api 是推送型——两者无拉取语义。
6
7use crate::state::AppState;
8use chrono::{DateTime, Utc};
9use sha2::{Digest, Sha256};
10use utopia_core::models::Source;
11use uuid::Uuid;
12
13/// 单次同步的新文档上限(防超长 feed/URL 列表拖垮任务)
14const MAX_NEW_PER_SYNC: usize = 200;
15
16/// 抓取用的 User-Agent。reqwest 默认一个都不发,而维基百科明确拒绝匿名请求
17/// (403),Cloudflare 前置的站点也普遍如此——URL 与 RSS 两类来源因此对一大批
18/// 真实网站直接失效。自报家门也是爬虫礼节:站方能认出我们、能联系到我们。
19const UA: &str = concat!(
20 "Utopia/",
21 env!("CARGO_PKG_VERSION"),
22 " (+https://utopia.bi; self-hosted knowledge platform)"
23);
24
25/// 单次同步的产出统计(Moved/Unchanged 不计)。
26#[derive(Debug, Default, Clone, Copy)]
27pub struct SyncStats {
28 pub created: usize,
29 pub updated: usize,
30}
31
32impl SyncStats {
33 fn absorb(&mut self, action: IngestAction) {
34 match action {
35 IngestAction::Created => self.created += 1,
36 IngestAction::Updated => self.updated += 1,
37 _ => {}
38 }
39 }
40 fn total(&self) -> usize {
41 self.created + self.updated
42 }
43}
44
45pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<()> {
46 let source = utopia_store::sources::get(&state.pool, source_id).await?;
47 utopia_store::sources::mark_running(&state.pool, source_id).await?;
48 let run_id = utopia_store::sources::start_run(&state.pool, source_id).await?;
49 state.emit_source(source.kb_id);
50
51 let outcome = match source.kind.as_str() {
52 "url" => sync_urls(state, &source).await,
53 "rss" => sync_rss(state, &source).await,
54 "custom" => sync_custom(state, &source).await,
55 "github_issues" => sync_github_issues(state, &source).await,
56 "jira_issues" => sync_jira_issues(state, &source).await,
57 "s3" | "azure_blob" | "gcs" => sync_object_storage(state, &source).await,
58 // folder / api 无拉取语义
59 _ => Ok(SyncStats::default()),
60 };
61
62 match outcome {
63 Ok(stats) => {
64 utopia_store::sources::finish_run(
65 &state.pool,
66 run_id,
67 source_id,
68 None,
69 stats.created as i32,
70 stats.updated as i32,
71 )
72 .await?;
73 utopia_store::sources::finish_sync(&state.pool, source_id, None, stats.total() as i32)
74 .await?;
75 state.emit_source(source.kb_id);
76 tracing::info!(%source_id, kind = %source.kind, created = stats.created, updated = stats.updated, "来源同步完成");
77 Ok(())
78 }
79 Err(e) => {
80 utopia_store::sources::finish_run(
81 &state.pool,
82 run_id,
83 source_id,
84 Some(&e.to_string()),
85 0,
86 0,
87 )
88 .await?;
89 utopia_store::sources::finish_sync(&state.pool, source_id, Some(&e.to_string()), 0)
90 .await?;
91 state.emit_source(source.kb_id);
92 Err(e)
93 }
94 }
95}
96
97/// 三路判定的结果。
98#[derive(Debug, Clone, Copy, PartialEq)]
99pub enum IngestAction {
100 Created,
101 Updated,
102 Moved,
103 Unchanged,
104 /// 墓碑:标记"不在来源中"(不删除文档,删不删由用户在 UI 决定)
105 Tombstoned,
106}
107
108async fn write_blob(state: &AppState, sha256: &str, bytes: &[u8]) -> anyhow::Result<()> {
109 state.blob.put(sha256, bytes).await
110}
111
112fn sha_hex(bytes: &[u8]) -> String {
113 Sha256::digest(bytes)
114 .iter()
115 .map(|b| format!("{b:02x}"))
116 .collect()
117}
118
119/// 普通上传语义的推送(KB 级 /ingest → Uploads):无来源、无身份键,
120/// 不做三路判定——KB 内已有同内容时视为无操作,其余一律新建。
121pub async fn ingest_upload(
122 state: &AppState,
123 kb_id: Uuid,
124 filename: &str,
125 mime: &str,
126 bytes: &[u8],
127 doc_time: Option<DateTime<Utc>>,
128) -> anyhow::Result<IngestAction> {
129 if bytes.is_empty() {
130 return Ok(IngestAction::Unchanged);
131 }
132 let sha256 = sha_hex(bytes);
133 write_blob(state, &sha256, bytes).await?;
134 match utopia_store::documents::create(
135 &state.pool,
136 kb_id,
137 filename,
138 mime,
139 bytes.len() as i64,
140 &sha256,
141 None,
142 doc_time,
143 None,
144 )
145 .await
146 {
147 Ok(doc) => {
148 utopia_store::jobs::enqueue(
149 &state.pool,
150 "process_document",
151 serde_json::json!({ "document_id": doc.id }),
152 )
153 .await?;
154 state.emit_document(kb_id, doc.id);
155 Ok(IngestAction::Created)
156 }
157 Err(utopia_core::AppError::Conflict(_)) => Ok(IngestAction::Unchanged),
158 Err(e) => Err(e.into()),
159 }
160}
161
162/// 身份感知摄入:按 (source, external_key) 三路判定——
163/// 新增(建文档)/ 变更(原地替换 + 版本记录 + 重跑管道)/ 未变(跳过);
164/// 同内容换路径识别为移动(只改身份,不重跑)。external_key 为 URI 形态
165/// (file:/// 相对路径、页面 URL、rss guid、api:{id}),出处自描述,
166/// 也为 P5 SPARQL 投影的文档 IRI 提前对齐。
167#[allow(clippy::too_many_arguments)]
168pub async fn ingest_item(
169 state: &AppState,
170 kb_id: Uuid,
171 source_id: Uuid,
172 external_key: &str,
173 filename: &str,
174 mime: &str,
175 bytes: &[u8],
176 doc_time: Option<DateTime<Utc>>,
177) -> anyhow::Result<IngestAction> {
178 if bytes.is_empty() {
179 return Ok(IngestAction::Unchanged);
180 }
181 let sha256 = sha_hex(bytes);
182
183 // 主判定:逻辑身份;兜底:迁移前的历史文档(无 key)按文件名认领并补键
184 let mut existing =
185 utopia_store::documents::find_by_external_key(&state.pool, source_id, external_key).await?;
186 if existing.is_none() {
187 if let Some(legacy) =
188 utopia_store::documents::find_legacy_by_filename(&state.pool, source_id, filename)
189 .await?
190 {
191 utopia_store::documents::adopt_external_key(&state.pool, legacy.id, external_key)
192 .await?;
193 // 认领时把旧内容记为版本 1(此前没有版本记录)
194 utopia_store::documents::record_version(
195 &state.pool,
196 legacy.id,
197 &legacy.sha256,
198 legacy.size_bytes,
199 )
200 .await?;
201 existing = Some(legacy);
202 }
203 }
204
205 if let Some(doc) = existing {
206 if doc.sha256 == sha256 {
207 return Ok(IngestAction::Unchanged);
208 }
209 // 变更:原地替换,旧版本入 document_versions(blob 内容寻址不删,回放有料)
210 write_blob(state, &sha256, bytes).await?;
211 utopia_store::documents::replace_content(
212 &state.pool,
213 doc.id,
214 filename,
215 mime,
216 bytes.len() as i64,
217 &sha256,
218 doc_time,
219 )
220 .await?;
221 utopia_store::documents::record_version(&state.pool, doc.id, &sha256, bytes.len() as i64)
222 .await?;
223 utopia_store::jobs::enqueue(
224 &state.pool,
225 "process_document",
226 serde_json::json!({ "document_id": doc.id }),
227 )
228 .await?;
229 state.emit_document(kb_id, doc.id);
230 return Ok(IngestAction::Updated);
231 }
232
233 // 同内容出现在新路径:识别为移动/改名,不重跑管道
234 if let Some(doc) =
235 utopia_store::documents::find_by_source_sha(&state.pool, source_id, &sha256).await?
236 {
237 utopia_store::documents::update_location(&state.pool, doc.id, filename, external_key)
238 .await?;
239 state.emit_document(kb_id, doc.id);
240 return Ok(IngestAction::Moved);
241 }
242
243 write_blob(state, &sha256, bytes).await?;
244 match utopia_store::documents::create(
245 &state.pool,
246 kb_id,
247 filename,
248 mime,
249 bytes.len() as i64,
250 &sha256,
251 Some(source_id),
252 doc_time,
253 Some(external_key),
254 )
255 .await
256 {
257 Ok(doc) => {
258 utopia_store::documents::record_version(
259 &state.pool,
260 doc.id,
261 &sha256,
262 bytes.len() as i64,
263 )
264 .await?;
265 utopia_store::jobs::enqueue(
266 &state.pool,
267 "process_document",
268 serde_json::json!({ "document_id": doc.id }),
269 )
270 .await?;
271 state.emit_document(kb_id, doc.id);
272 Ok(IngestAction::Created)
273 }
274 // KB 内已有同内容(如手动上传过同一文件):不重复摄入
275 Err(utopia_core::AppError::Conflict(_)) => Ok(IngestAction::Unchanged),
276 Err(e) => Err(e.into()),
277 }
278}
279
280async fn sync_urls(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
281 let urls: Vec<String> = source.config["urls"]
282 .as_array()
283 .map(|a| {
284 a.iter()
285 .filter_map(|v| v.as_str())
286 .map(str::trim)
287 .filter(|s| !s.is_empty())
288 .map(String::from)
289 .collect()
290 })
291 .unwrap_or_default();
292 if urls.is_empty() {
293 anyhow::bail!("url source is missing config.urls (a list of page URLs)");
294 }
295
296 let http = reqwest::Client::builder()
297 .timeout(std::time::Duration::from_secs(30))
298 .user_agent(UA)
299 .build()?;
300 let mut stats = SyncStats::default();
301 let mut last_err: Option<String> = None;
302 for url in urls.iter().take(MAX_NEW_PER_SYNC) {
303 match fetch_page(&http, url).await {
304 Ok((filename, mime, bytes)) => {
305 // 逻辑身份 = URL 本身:页面内容变了就原地替换(历史进版本表)
306 let action = ingest_item(
307 state,
308 source.kb_id,
309 source.id,
310 url,
311 &filename,
312 &mime,
313 &bytes,
314 None,
315 )
316 .await?;
317 stats.absorb(action);
318 }
319 Err(e) => {
320 tracing::warn!(%url, error = %e, "抓取失败");
321 last_err = Some(format!("{url}: {e}"));
322 }
323 }
324 }
325 // 部分失败:有产出则视为成功(错误进日志),全军覆没才报错
326 if stats.total() == 0 {
327 if let Some(err) = last_err {
328 anyhow::bail!("{err}");
329 }
330 }
331 // 配置列表即全集:不在列表里的文档标"不在来源中"(抓取失败不算——它仍被配置着)
332 utopia_store::documents::reconcile_missing(&state.pool, source.id, &urls)
333 .await
334 .map_err(|e| anyhow::anyhow!(e))?;
335 Ok(stats)
336}
337
338async fn fetch_page(
339 http: &reqwest::Client,
340 url: &str,
341) -> anyhow::Result<(String, String, Vec<u8>)> {
342 let resp = http.get(url).send().await?;
343 if !resp.status().is_success() {
344 anyhow::bail!("HTTP {}", resp.status());
345 }
346 let mime = resp
347 .headers()
348 .get(reqwest::header::CONTENT_TYPE)
349 .and_then(|v| v.to_str().ok())
350 .unwrap_or("text/html")
351 .split(';')
352 .next()
353 .unwrap_or("text/html")
354 .to_string();
355 let bytes = resp.bytes().await?.to_vec();
356 let filename = filename_from_url(url, &mime);
357 Ok((filename, mime, bytes))
358}
359
360fn filename_from_url(url: &str, mime: &str) -> String {
361 let stripped = url
362 .trim_start_matches("https://")
363 .trim_start_matches("http://")
364 .trim_end_matches('/');
365 let mut slug: String = stripped
366 .chars()
367 .map(|c| {
368 if c.is_alphanumeric() || c == '.' || c == '-' {
369 c
370 } else {
371 '-'
372 }
373 })
374 .collect();
375 slug.truncate(120);
376 let has_ext = slug
377 .rsplit('.')
378 .next()
379 .map(|e| e.len() <= 5)
380 .unwrap_or(false)
381 && slug.contains('.')
382 && !slug.ends_with('.');
383 if !has_ext || mime.contains("html") {
384 format!("{slug}.html")
385 } else {
386 slug
387 }
388}
389
390async fn sync_rss(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
391 let feed_url = source.config["feed_url"]
392 .as_str()
393 .filter(|s| !s.trim().is_empty())
394 .ok_or_else(|| anyhow::anyhow!("rss source is missing config.feed_url"))?;
395
396 let http = reqwest::Client::builder()
397 .timeout(std::time::Duration::from_secs(30))
398 .user_agent(UA)
399 .build()?;
400 let resp = http.get(feed_url).send().await?;
401 if !resp.status().is_success() {
402 anyhow::bail!("HTTP {} fetching feed", resp.status());
403 }
404 let bytes = resp.bytes().await?;
405 let feed = feed_rs::parser::parse(&bytes[..])
406 .map_err(|e| anyhow::anyhow!("Failed to parse feed: {e}"))?;
407
408 let mut stats = SyncStats::default();
409 for entry in feed.entries.iter().take(MAX_NEW_PER_SYNC) {
410 let title = entry
411 .title
412 .as_ref()
413 .map(|t| t.content.clone())
414 .unwrap_or_else(|| "untitled".into());
415 let link = entry
416 .links
417 .first()
418 .map(|l| l.href.clone())
419 .unwrap_or_default();
420 // 逻辑身份:feed 规范的 guid(通常已是 permalink/urn),缺失时退条目链接
421 let key = if !entry.id.trim().is_empty() {
422 entry.id.trim().to_string()
423 } else if !link.is_empty() {
424 link.clone()
425 } else {
426 format!("entry:{}", sha_hex(title.as_bytes()))
427 };
428 let body = entry
429 .content
430 .as_ref()
431 .and_then(|c| c.body.clone())
432 .or_else(|| entry.summary.as_ref().map(|s| s.content.clone()))
433 .unwrap_or_default();
434 // 条目发布时间 → 文档时间:时态抽取吃到真实时间戳(本平台的差异化正在于此)
435 let doc_time = entry.published.or(entry.updated);
436
437 let html = format!(
438 "<html><head><title>{}</title></head><body><h1>{}</h1>\n<p><a href=\"{}\">{}</a></p>\n{}</body></html>",
439 title, title, link, link, body
440 );
441 let mut slug: String = title
442 .chars()
443 .map(|c| if c.is_alphanumeric() { c } else { '-' })
444 .collect();
445 slug.truncate(80);
446 let filename = format!("{slug}.html");
447
448 let action = ingest_item(
449 state,
450 source.kb_id,
451 source.id,
452 &key,
453 &filename,
454 "text/html",
455 html.as_bytes(),
456 doc_time,
457 )
458 .await?;
459 stats.absorb(action);
460 }
461 Ok(stats)
462}
463
464/// GitHub 工单:一张工单一篇文档,正文里带它的状态变更史。
465///
466/// 工单与评论走**仓库级 + `since`**(一次分页取全),事件走**逐工单**——
467/// 不是不一致,是 `issues/events` 不支持 `since` 且会被 PR 事件淹没,
468/// 拿真实仓库一跑就发现状态变更史悄悄空了。详见 [`crate::github_issues`]。
469///
470/// `doc_time` 取 `updated_at` 而不是 `created_at`:每次同步捕获的是"此刻这张
471/// 工单是什么样",认知时间该说这个状态是何时成立的。新增一条评论会改
472/// `updated_at`,于是内容变了、记一个新版本、`doc_time` 也跟着走。
473async fn sync_github_issues(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
474 let repo = source.config["repo"]
475 .as_str()
476 .map(str::trim)
477 .filter(|s| !s.is_empty())
478 .ok_or_else(|| {
479 anyhow::anyhow!("github_issues source is missing config.repo (owner/name)")
480 })?;
481 if repo.split('/').count() != 2 {
482 anyhow::bail!("config.repo should look like owner/name, got {repo:?}");
483 }
484 let auth = source.config["auth_header"]
485 .as_str()
486 .map(str::trim)
487 .filter(|s| !s.is_empty());
488 // PR 在 GitHub 的模型里也是 issue。默认排除——问"工单系统"要的是工单;
489 // 但有些仓库的决策记录实际写在 PR 描述里,所以留了开关
490 let include_prs = source.config["include_pull_requests"]
491 .as_bool()
492 .unwrap_or(false);
493
494 let http = reqwest::Client::builder()
495 .timeout(std::time::Duration::from_secs(30))
496 .user_agent(UA)
497 .build()?;
498 let base = format!("https://api.github.com/repos/{repo}");
499
500 // 增量:GitHub 的 since 是"这之后更新过的"
501 let mut issue_q: Vec<(&str, String)> = vec![("state", "all".into())];
502 let mut comment_q: Vec<(&str, String)> = Vec::new();
503 if let Some(t) = source.last_sync_at {
504 issue_q.push(("since", t.to_rfc3339()));
505 comment_q.push(("since", t.to_rfc3339()));
506 }
507
508 let issues: Vec<crate::github_issues::Issue> =
509 crate::github_issues::fetch_all(&http, &format!("{base}/issues"), &issue_q, auth).await?;
510 let comments: Vec<crate::github_issues::Comment> = crate::github_issues::fetch_all(
511 &http,
512 &format!("{base}/issues/comments"),
513 &comment_q,
514 auth,
515 )
516 .await?;
517 let mut stats = SyncStats::default();
518 for (issue, cs) in crate::github_issues::group_comments(&issues, &comments)
519 .into_iter()
520 .filter(|(i, _)| include_prs || i.pull_request.is_none())
521 .take(MAX_NEW_PER_SYNC)
522 {
523 // 逐工单取事件。N 只是本轮要写入的工单数——首次同步等于总数,
524 // 之后有 since 兜着通常是个位数
525 let events = crate::github_issues::sort_events(
526 crate::github_issues::fetch_all(
527 &http,
528 &format!("{base}/issues/{}/events", issue.number),
529 &[],
530 auth,
531 )
532 .await?,
533 );
534 let es: Vec<&crate::github_issues::Event> = events.iter().collect();
535 let body = crate::github_issues::render(issue, &cs, &es);
536 // 逻辑身份带上仓库:同一个知识库里接两个仓库时,#18 不会互相覆盖
537 let key = format!("github:{repo}#{}", issue.number);
538 let filename = format!("{}-{}.md", issue.number, slugify(&issue.title));
539 let action = ingest_item(
540 state,
541 source.kb_id,
542 source.id,
543 &key,
544 &filename,
545 "text/markdown",
546 body.as_bytes(),
547 Some(issue.updated_at),
548 )
549 .await?;
550 stats.absorb(action);
551 }
552 Ok(stats)
553}
554
555/// Jira 工单:一张工单一篇文档,正文里带**字段级**的变更史。
556///
557/// 比 GitHub 那条路省:`search?expand=changelog` 一次调用就带回工单本体、
558/// 完整变更史与评论,**没有 N+1**。增量靠 JQL 的 `updated >= …` 表达,
559/// 因为 Jira 没有 `since` 参数。详见 [`crate::jira_issues`]。
560///
561/// `doc_time` 取 `updated`,与 github_issues 同一口径:每次同步捕获的是
562/// "此刻这张工单是什么样",认知时间该说这个状态何时成立。
563async fn sync_jira_issues(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
564 let base_url = source.config["base_url"]
565 .as_str()
566 .map(str::trim)
567 .filter(|s| !s.is_empty())
568 .ok_or_else(|| anyhow::anyhow!("jira_issues source is missing config.base_url"))?;
569 let project = source.config["project"]
570 .as_str()
571 .map(str::trim)
572 .filter(|s| !s.is_empty())
573 .ok_or_else(|| anyhow::anyhow!("jira_issues source is missing config.project"))?;
574 // 项目 key 直接拼进 JQL,所以不能是任意字符串。Jira 的 key 本身就限定
575 // 字母数字加下划线——挡住它顺带挡住了 JQL 注入
576 if !project.chars().all(|c| c.is_alphanumeric() || c == '_') {
577 anyhow::bail!("config.project should be a Jira project key, got {project:?}");
578 }
579 let auth = source.config["auth_header"]
580 .as_str()
581 .map(str::trim)
582 .filter(|s| !s.is_empty());
583
584 let http = reqwest::Client::builder()
585 .timeout(std::time::Duration::from_secs(45))
586 .user_agent(UA)
587 .build()?;
588
589 let jql = crate::jira_issues::jql(project, source.last_sync_at);
590 let (issues, total) = crate::jira_issues::fetch_all(&http, base_url, &jql, auth).await?;
591 // **截断了就说出来。** 一个跑了多年的项目动辄上万张工单,翻页上限意味着
592 // 这一轮只覆盖了一段;不报的话界面上"同步完成"就是一句误导
593 if total > issues.len() as i64 {
594 tracing::warn!(
595 source_id = %source.id,
596 fetched = issues.len(),
597 total,
598 "Jira 结果被翻页上限截断,本轮只覆盖了一部分;下一轮的 JQL 窗口会接上"
599 );
600 }
601
602 let mut stats = SyncStats::default();
603 for issue in issues.iter().take(MAX_NEW_PER_SYNC) {
604 let body = crate::jira_issues::render(issue);
605 // 逻辑身份带上站点:一个知识库接两个 Jira 时,PROJ-1 不会互相覆盖
606 let host = reqwest::Url::parse(base_url)
607 .ok()
608 .and_then(|u| u.host_str().map(str::to_string))
609 .unwrap_or_else(|| "jira".into());
610 let key = format!("jira:{host}/{}", issue.key);
611 let filename = format!(
612 "{}-{}.md",
613 issue.key,
614 slugify(issue.fields.summary.as_deref().unwrap_or(""))
615 );
616 let action = ingest_item(
617 state,
618 source.kb_id,
619 source.id,
620 &key,
621 &filename,
622 "text/markdown",
623 body.as_bytes(),
624 issue.fields.updated.map(|t| t.0),
625 )
626 .await?;
627 stats.absorb(action);
628 }
629 Ok(stats)
630}
631
632/// 标题 → 文件名安全的片段。与 RSS 那条路同一个口径(非字母数字换成 -,截断)。
633fn slugify(title: &str) -> String {
634 let mut s: String = title
635 .chars()
636 .map(|c| if c.is_alphanumeric() { c } else { '-' })
637 .collect();
638 s.truncate(60);
639 s.trim_matches('-').to_string()
640}
641
642/// 自定义拉取器 —— Utopia Ingest Interface:
643/// `GET {endpoint}?since=<上次同步 RFC3339>`(首次同步不带 since;可配 Authorization 头),
644/// 响应 `{"items":[{"id":"稳定唯一ID","title":"文档名","content":"正文(纯文本/Markdown/HTML)",
645/// "doc_time":"RFC3339 可选","mime":"text/markdown 可选"}]}`。
646/// id → external_key(custom:{id}),三路判定生效:同 id 同内容跳过、新内容原地更新。
647async fn sync_custom(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
648 let endpoint = source.config["endpoint"]
649 .as_str()
650 .filter(|s| !s.trim().is_empty())
651 .ok_or_else(|| anyhow::anyhow!("custom source is missing config.endpoint"))?;
652 let mut url =
653 reqwest::Url::parse(endpoint).map_err(|e| anyhow::anyhow!("Invalid endpoint URL: {e}"))?;
654 if let Some(t) = source.last_sync_at {
655 url.query_pairs_mut().append_pair("since", &t.to_rfc3339());
656 }
657
658 // loopback 端点不走系统代理:代理对回环地址只会 502,本机服务必须直连
659 let loopback = url
660 .host_str()
661 .map(|h| {
662 h.eq_ignore_ascii_case("localhost") || h == "127.0.0.1" || h == "::1" || h == "[::1]"
663 })
664 .unwrap_or(false);
665 let mut builder = reqwest::Client::builder()
666 .timeout(std::time::Duration::from_secs(30))
667 .user_agent(UA);
668 if loopback {
669 builder = builder.no_proxy();
670 }
671 let http = builder.build()?;
672 let mut req = http.get(url);
673 if let Some(auth) = source.config["auth_header"]
674 .as_str()
675 .filter(|s| !s.trim().is_empty())
676 {
677 req = req.header(reqwest::header::AUTHORIZATION, auth.trim());
678 }
679 let resp = req.send().await?;
680 if !resp.status().is_success() {
681 anyhow::bail!("HTTP {} from endpoint", resp.status());
682 }
683 let body: serde_json::Value = resp.json().await?;
684 let items = body["items"]
685 .as_array()
686 .ok_or_else(|| anyhow::anyhow!("Response is missing the items[] array"))?;
687
688 let mut stats = SyncStats::default();
689 let mut seen_keys: Vec<String> = Vec::new();
690 for item in items.iter().take(MAX_NEW_PER_SYNC) {
691 let Some(id) = item["id"].as_str().map(str::trim).filter(|s| !s.is_empty()) else {
692 tracing::warn!(source_id = %source.id, "custom item 缺少 id,跳过");
693 continue;
694 };
695 let Some(content) = item["content"].as_str().filter(|s| !s.trim().is_empty()) else {
696 tracing::warn!(source_id = %source.id, %id, "custom item 缺少 content,跳过");
697 continue;
698 };
699 let title = item["title"]
700 .as_str()
701 .map(str::trim)
702 .filter(|s| !s.is_empty())
703 .unwrap_or(id);
704 let mime = item["mime"].as_str().unwrap_or("text/markdown");
705 let doc_time = item["doc_time"]
706 .as_str()
707 .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
708 .map(|t| t.with_timezone(&Utc));
709 let filename = ensure_extension(title, mime);
710 let key = format!("custom:{id}");
711 let action = ingest_item(
712 state,
713 source.kb_id,
714 source.id,
715 &key,
716 &filename,
717 mime,
718 content.as_bytes(),
719 doc_time,
720 )
721 .await?;
722 stats.absorb(action);
723 seen_keys.push(key);
724 }
725 // 增量响应(?since=)里缺席≠删除,不做全集对账;但:
726 // 1) 再次出现的条目摘掉 missing 标记(失而复得)
727 // 2) 显式墓碑 deleted[] 才标"不在来源中"——删不删文档由用户在 UI 决定
728 if !seen_keys.is_empty() {
729 utopia_store::documents::clear_missing_keys(&state.pool, source.id, &seen_keys)
730 .await
731 .map_err(|e| anyhow::anyhow!(e))?;
732 }
733 let tombstones: Vec<String> = body["deleted"]
734 .as_array()
735 .map(|a| {
736 a.iter()
737 .filter_map(|v| v.as_str())
738 .map(|id| format!("custom:{}", id.trim()))
739 .collect()
740 })
741 .unwrap_or_default();
742 if !tombstones.is_empty() {
743 let n = utopia_store::documents::mark_missing_keys(&state.pool, source.id, &tombstones)
744 .await
745 .map_err(|e| anyhow::anyhow!(e))?;
746 tracing::info!(source_id = %source.id, count = n, "custom 墓碑:标记不在来源中");
747 }
748 Ok(stats)
749}
750
751/// 对象存储同步:列前缀下的对象,逐个摄入。
752///
753/// `external_key` 用 `s3://bucket/key`,跟 `file:///` 与页面 URL 同一个约定:
754/// 出处自描述。换了前缀但内容没变时,`ingest_item` 会认成「搬家」而不是新增,
755/// 不会重跑一遍抽取。
756///
757/// **`doc_time` 取 `LastModified`,而它是写入时刻不是文档自身的时间。**
758/// 一份 2019 年的合同今天传上去,时间线上会落在今天。对象存储没有更好的
759/// 来源——除非文件名或正文里带日期,而那是抽取器的活。这一条与 `url` 源
760/// 同病:`0013` 的第一条判据在这里只满足一半。
761async fn sync_object_storage(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
762 let bucket = source.config["bucket"]
763 .as_str()
764 .map(str::trim)
765 .filter(|s| !s.is_empty())
766 .ok_or_else(|| anyhow::anyhow!("{} source is missing config.bucket", source.kind))?;
767 let prefix = source.config["prefix"]
768 .as_str()
769 .map(str::trim)
770 .filter(|s| !s.is_empty());
771
772 let store = crate::object_storage::client(&source.kind, &source.config)?;
773 let (objects, truncated) =
774 crate::object_storage::fetch(&source.kind, store.as_ref(), bucket, prefix).await?;
775
776 // 到顶不是错误,但必须说出来——否则「同步成功」下面藏着没进来的东西,
777 // 而那正是 0005 说的失败无声
778 if truncated {
779 tracing::warn!(
780 %bucket, prefix = prefix.unwrap_or(""),
781 "对象数到达单次上限,其余留给下一次同步"
782 );
783 }
784
785 let mut stats = SyncStats::default();
786 for obj in objects {
787 // **不猜 mime。** `utopia_ingest::parse` 先看魔数、再看扩展名,
788 // 注释写着「扩展名可能撒谎」——在这里按文件名猜一个,只是多一个
789 // 会撒谎的来源,而且要为此多一个依赖。`octet-stream` 是诚实的:
790 // 我们拿到的就是一串字节,没看过里面是什么。
791 let action = ingest_item(
792 state,
793 source.kb_id,
794 source.id,
795 &obj.external_key,
796 &obj.filename,
797 "application/octet-stream",
798 &obj.bytes,
799 obj.last_modified,
800 )
801 .await?;
802 stats.absorb(action);
803 }
804 Ok(stats)
805}
806
807/// 标题无扩展名时按 mime 补一个,接入解析矩阵的分派。
808fn ensure_extension(title: &str, mime: &str) -> String {
809 let has_ext = title
810 .rsplit('.')
811 .next()
812 .map(|e| e.len() <= 5 && e.len() >= 2 && !e.contains(' '))
813 .unwrap_or(false)
814 && title.contains('.');
815 if has_ext {
816 return title.to_string();
817 }
818 let ext = if mime.contains("html") {
819 "html"
820 } else if mime.contains("plain") {
821 "txt"
822 } else {
823 "md"
824 };
825 format!("{title}.{ext}")
826}