Elffuss BraidHub

kikocis/utopia public

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