Elffuss BraidHub

kikocis/utopia public

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