Elffuss BraidHub

kikocis/utopia public

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