Elffuss BraidHub

kikocis/utopia public

ffe9e37e55e3 · 14.6 KiBRawPermalink
1//! 摄入来源仓储:"来源即文件夹"——source 是容器,挂着它摄入的文档,可定时同步。
2
3use chrono::{DateTime, Utc};
4use sqlx::PgPool;
5use utopia_core::models::{Role, Source, SourceView, SyncRun, SOURCE_SECRET_KEYS};
6use utopia_core::{AppError, AppResult};
7use uuid::Uuid;
8
9/// folder = 纯容器(上传/拖拽入内,无同步语义);url/rss = 拉取型;api = 推送型。
10/// 本机目录监听(watch_folder)已否决——自部署用户看不到服务器磁盘;
11/// 未来的 watch 形态是对象存储/网盘(P5 连接器,与 BlobStore 接缝配套)。
12/// custom = 自定义拉取器:任何实现 Utopia ingest 接口的 URL(返回 items JSON)即可定时摄取。
13/// github_issues / jira_issues = 工单:一张工单连同它的状态变更史成为一篇文档。
14///
15/// **改这里就得改前端那份清单**(`Library.tsx` 的建来源对话框与 `api.ts` 的
16/// `SourceView["kind"]`)。两处对不上时的症状是:界面上选得到、建的时候报
17/// 「kind must be one of…」——单元测试与 tsc 都看不见,只有端到端会撞上。
18pub const KINDS: &[&str] = &[
19 "folder",
20 "url",
21 "rss",
22 "api",
23 "custom",
24 "github_issues",
25 "jira_issues",
26];
27
28/// 校验并规范化标准 5 段 cron 表达式(内部用 cron crate 的 6 段:补秒位)。
29pub fn validate_cron(expr: &str) -> AppResult<String> {
30 let normalized = expr.split_whitespace().collect::<Vec<_>>().join(" ");
31 let fields = normalized.split(' ').count();
32 if fields != 5 {
33 return Err(AppError::invalid_detail(
34 "bad_cron_fields",
35 "Cron expression must have 5 fields (minute hour day month weekday)",
36 format!("got {fields}"),
37 ));
38 }
39 use std::str::FromStr;
40 cron::Schedule::from_str(&format!("0 {normalized}")).map_err(|e| {
41 AppError::invalid_detail("bad_cron", "Invalid cron expression", e.to_string())
42 })?;
43 Ok(normalized)
44}
45
46/// cron 的下一次触发时刻(服务器本地时区)。
47fn cron_next_after(expr: &str, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
48 use std::str::FromStr;
49 let schedule = cron::Schedule::from_str(&format!("0 {expr}")).ok()?;
50 let local_after = after.with_timezone(&chrono::Local);
51 schedule
52 .after(&local_after)
53 .next()
54 .map(|t| t.with_timezone(&Utc))
55}
56
57pub async fn list(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<SourceView>> {
58 // config 剔掉凭据:列表给 Viewer 看,哪一种连接器的密钥都不下发。
59 // 键在 `SOURCE_SECRET_KEYS` 一张表上——从前这里只减 `auth_header`,五种连接器
60 // 的密钥就这么漏出去的(#246)
61 let rows: Vec<SourceView> = sqlx::query_as(
62 "SELECT s.id, s.kind, s.name, s.config - $2::text[] AS config, s.icon,
63 s.sync_interval_minutes, s.sync_cron,
64 s.last_sync_at, s.last_sync_status, s.last_sync_error, s.last_sync_added,
65 (SELECT count(*) FROM documents d WHERE d.source_id = s.id) AS doc_count,
66 (SELECT count(*) FROM documents d
67 WHERE d.source_id = s.id AND d.missing_since IS NOT NULL) AS missing_count
68 FROM sources s WHERE s.kb_id = $1 ORDER BY s.created_at",
69 )
70 .bind(kb_id)
71 .bind(SOURCE_SECRET_KEYS)
72 .fetch_all(pool)
73 .await?;
74 Ok(rows)
75}
76
77pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Source> {
78 sqlx::query_as("SELECT * FROM sources WHERE id = $1")
79 .bind(id)
80 .fetch_optional(pool)
81 .await?
82 .ok_or(AppError::NotFound)
83}
84
85#[allow(clippy::too_many_arguments)]
86pub async fn create(
87 pool: &PgPool,
88 kb_id: Uuid,
89 kind: &str,
90 name: &str,
91 config: &serde_json::Value,
92 icon: Option<&str>,
93 sync_interval_minutes: Option<i32>,
94 sync_cron: Option<&str>,
95) -> AppResult<Source> {
96 if !KINDS.contains(&kind) {
97 return Err(AppError::Validation(format!(
98 "kind must be one of: {}",
99 KINDS.join(", ")
100 )));
101 }
102 if name.trim().is_empty() {
103 return Err(AppError::invalid(
104 "source_name_required",
105 "Source name is required",
106 ));
107 }
108 // 互斥:cron 优先(UI 只会传其一)
109 let cron_norm = sync_cron.map(validate_cron).transpose()?;
110 let interval = if cron_norm.is_some() {
111 None
112 } else {
113 sync_interval_minutes
114 };
115 // serde 缺省的 Value::Null 会以 jsonb null 落库,前端读 config.x 直接炸——规范化为空对象
116 let config = if config.is_null() {
117 serde_json::json!({})
118 } else {
119 config.clone()
120 };
121 let source = sqlx::query_as(
122 "INSERT INTO sources (id, kb_id, kind, name, config, icon, sync_interval_minutes, sync_cron)
123 VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *",
124 )
125 .bind(Uuid::now_v7())
126 .bind(kb_id)
127 .bind(kind)
128 .bind(name.trim())
129 .bind(config)
130 .bind(icon)
131 .bind(interval)
132 .bind(cron_norm)
133 .fetch_one(pool)
134 .await?;
135 Ok(source)
136}
137
138/// 设置 api 来源的推送密钥(创建 / 轮换时)。
139pub async fn set_ingest_token(pool: &PgPool, source_id: Uuid, token: &str) -> AppResult<()> {
140 let res = sqlx::query("UPDATE sources SET ingest_token = $2 WHERE id = $1")
141 .bind(source_id)
142 .bind(token)
143 .execute(pool)
144 .await?;
145 if res.rows_affected() == 0 {
146 return Err(AppError::NotFound);
147 }
148 Ok(())
149}
150
151/// 更新调度:interval 与 cron 互斥,任一被显式设置时都会覆盖两者。
152#[allow(clippy::too_many_arguments)]
153pub async fn update(
154 pool: &PgPool,
155 id: Uuid,
156 name: Option<&str>,
157 config: Option<&serde_json::Value>,
158 icon: Option<&str>,
159 schedule: Option<(Option<i32>, Option<String>)>,
160) -> AppResult<Source> {
161 let schedule = match schedule {
162 Some((interval, cron)) => {
163 let cron_norm = cron.as_deref().map(validate_cron).transpose()?;
164 let interval = if cron_norm.is_some() { None } else { interval };
165 Some((interval, cron_norm))
166 }
167 None => None,
168 };
169 let source = sqlx::query_as(
170 "UPDATE sources SET
171 name = COALESCE($2, name),
172 config = COALESCE($3, config),
173 icon = COALESCE($4, icon),
174 sync_interval_minutes = CASE WHEN $5 THEN $6 ELSE sync_interval_minutes END,
175 sync_cron = CASE WHEN $5 THEN $7 ELSE sync_cron END
176 WHERE id = $1 RETURNING *",
177 )
178 .bind(id)
179 .bind(name)
180 .bind(config)
181 .bind(icon)
182 .bind(schedule.is_some())
183 .bind(schedule.as_ref().and_then(|(i, _)| *i))
184 .bind(schedule.as_ref().and_then(|(_, c)| c.clone()))
185 .fetch_optional(pool)
186 .await?
187 .ok_or(AppError::NotFound)?;
188 Ok(source)
189}
190
191/// 删除来源;其文档保留(source_id 置 NULL,落回 Uploads 组)。
192pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
193 let res = sqlx::query("DELETE FROM sources WHERE id = $1")
194 .bind(id)
195 .execute(pool)
196 .await?;
197 if res.rows_affected() == 0 {
198 return Err(AppError::NotFound);
199 }
200 Ok(())
201}
202
203/// 到期待同步的来源(调度器每分钟扫)。
204/// interval 型在 SQL 里判定;cron 型取回 Rust 侧求下一次触发时刻再过滤。
205pub async fn due_sources(pool: &PgPool) -> AppResult<Vec<Source>> {
206 let rows: Vec<Source> = sqlx::query_as(
207 "SELECT * FROM sources
208 WHERE last_sync_status NOT IN ('queued', 'running')
209 AND ((sync_interval_minutes IS NOT NULL
210 AND (last_sync_at IS NULL
211 OR last_sync_at + make_interval(mins => sync_interval_minutes) <= now()))
212 OR sync_cron IS NOT NULL)",
213 )
214 .fetch_all(pool)
215 .await?;
216
217 let now = chrono::Utc::now();
218 Ok(rows
219 .into_iter()
220 .filter(|s| match &s.sync_cron {
221 None => true, // interval 型已在 SQL 判定
222 Some(expr) => {
223 // 基准取上次同步时刻(没同步过取创建时刻):错过的触发点在下一轮扫描补上
224 let anchor = s.last_sync_at.unwrap_or(s.created_at);
225 cron_next_after(expr, anchor).is_some_and(|next| next <= now)
226 }
227 })
228 .collect())
229}
230
231/// 标记入队(幂等:已在队列/运行中则返回 false,避免重复入队)。
232pub async fn mark_queued(pool: &PgPool, id: Uuid) -> AppResult<bool> {
233 let res = sqlx::query(
234 "UPDATE sources SET last_sync_status = 'queued'
235 WHERE id = $1 AND last_sync_status NOT IN ('queued', 'running')",
236 )
237 .bind(id)
238 .execute(pool)
239 .await?;
240 Ok(res.rows_affected() > 0)
241}
242
243pub async fn mark_running(pool: &PgPool, id: Uuid) -> AppResult<()> {
244 sqlx::query("UPDATE sources SET last_sync_status = 'running' WHERE id = $1")
245 .bind(id)
246 .execute(pool)
247 .await?;
248 Ok(())
249}
250
251/// 一次同步收尾。失败时记一条告警,成功时什么都不做——
252/// **"现在好了没有"不是告警中心该回答的问题**,来源页面上就写着。
253///
254/// 返回值是"记了没有",调用方据此决定要不要推事件。
255pub async fn finish_sync(
256 pool: &PgPool,
257 id: Uuid,
258 error: Option<&str>,
259 added: i32,
260) -> AppResult<bool> {
261 let row: Option<(Uuid, String)> = sqlx::query_as(
262 "UPDATE sources SET last_sync_status = $2, last_sync_error = $3,
263 last_sync_added = $4, last_sync_at = now()
264 WHERE id = $1
265 RETURNING kb_id, name",
266 )
267 .bind(id)
268 .bind(if error.is_some() { "failed" } else { "ok" })
269 .bind(error)
270 .bind(added)
271 .fetch_optional(pool)
272 .await?;
273 let Some((kb_id, name)) = row else {
274 return Ok(false);
275 };
276 let Some(msg) = error else {
277 return Ok(false);
278 };
279 crate::alerts::raise(
280 pool,
281 crate::alerts::NewAlert {
282 kb_id: Some(kb_id),
283 severity: "error",
284 kind: crate::alerts::kind::SOURCE_SYNC_FAILED,
285 // 内容类给 editor,不只给 admin:管理员需要知道该修连接了,
286 // 但**配这个源的人**更需要知道你的东西没进来
287 min_role: Role::Editor,
288 subject_type: Some("source"),
289 subject_id: Some(id),
290 // 名字存一份:源被删之后 subject_id 解析不出名字,而告警该留得住
291 detail: serde_json::json!({ "name": name, "error": msg }),
292 },
293 )
294 .await?;
295 Ok(true)
296}
297
298/// 文档打标签(整组替换)。
299///
300/// **零调用,故意留着**:没有路由,界面上也没有入口。标签会是文档上唯一
301/// 「人自己贴的」维度——来源是它从哪来的,名字与状态是系统给的,三者都表达
302/// 不了「这批要脱敏」这种横跨来源、只有人知道的分组。要不要有这个维度,
303/// 悬而未决——完整的两面之辞写在 `migrations/0002_ingest.sql` 的 `tags` 列上,
304/// 别当死代码删掉。
305pub async fn set_document_tags(
306 pool: &PgPool,
307 kb_id: Uuid,
308 document_id: Uuid,
309 tags: &[String],
310) -> AppResult<()> {
311 let cleaned: Vec<String> = tags
312 .iter()
313 .map(|t| t.trim().to_string())
314 .filter(|t| !t.is_empty())
315 .collect();
316 let res = sqlx::query(
317 "UPDATE documents SET tags = $3, updated_at = now() WHERE id = $1 AND kb_id = $2",
318 )
319 .bind(document_id)
320 .bind(kb_id)
321 .bind(&cleaned)
322 .execute(pool)
323 .await?;
324 if res.rows_affected() == 0 {
325 return Err(AppError::NotFound);
326 }
327 Ok(())
328}
329
330/// 同步用去重:该 KB 是否已有同内容文档。
331pub async fn document_exists_by_sha(pool: &PgPool, kb_id: Uuid, sha256: &str) -> AppResult<bool> {
332 let row: Option<(Uuid,)> =
333 sqlx::query_as("SELECT id FROM documents WHERE kb_id = $1 AND sha256 = $2 LIMIT 1")
334 .bind(kb_id)
335 .bind(sha256)
336 .fetch_optional(pool)
337 .await?;
338 Ok(row.is_some())
339}
340
341/// 记录同步时刻(避免调度器在长同步过程中重复触发后又立刻到期)。
342pub async fn touch_sync_time(pool: &PgPool, id: Uuid, at: DateTime<Utc>) -> AppResult<()> {
343 sqlx::query("UPDATE sources SET last_sync_at = $2 WHERE id = $1")
344 .bind(id)
345 .bind(at)
346 .execute(pool)
347 .await?;
348 Ok(())
349}
350
351// ---------------------------------------------------------------------------
352// 同步运行记录(渠道审计历史)
353// ---------------------------------------------------------------------------
354
355pub async fn start_run(pool: &PgPool, source_id: Uuid) -> AppResult<Uuid> {
356 let id = Uuid::now_v7();
357 sqlx::query("INSERT INTO source_sync_runs (id, source_id) VALUES ($1, $2)")
358 .bind(id)
359 .bind(source_id)
360 .execute(pool)
361 .await?;
362 Ok(id)
363}
364
365pub async fn finish_run(
366 pool: &PgPool,
367 run_id: Uuid,
368 source_id: Uuid,
369 error: Option<&str>,
370 created_docs: i32,
371 updated_docs: i32,
372) -> AppResult<()> {
373 sqlx::query(
374 "UPDATE source_sync_runs SET finished_at = now(), status = $2, error = $3,
375 created_docs = $4, updated_docs = $5
376 WHERE id = $1",
377 )
378 .bind(run_id)
379 .bind(if error.is_some() { "failed" } else { "ok" })
380 .bind(error)
381 .bind(created_docs)
382 .bind(updated_docs)
383 .execute(pool)
384 .await?;
385 // 每来源只留最近 50 条
386 sqlx::query(
387 "DELETE FROM source_sync_runs WHERE source_id = $1 AND id NOT IN
388 (SELECT id FROM source_sync_runs WHERE source_id = $1
389 ORDER BY started_at DESC LIMIT 50)",
390 )
391 .bind(source_id)
392 .execute(pool)
393 .await?;
394 Ok(())
395}
396
397pub async fn list_runs(pool: &PgPool, source_id: Uuid, limit: i64) -> AppResult<Vec<SyncRun>> {
398 let rows: Vec<SyncRun> = sqlx::query_as(
399 "SELECT id, started_at, finished_at, status, created_docs, updated_docs, error
400 FROM source_sync_runs WHERE source_id = $1
401 ORDER BY started_at DESC LIMIT $2",
402 )
403 .bind(source_id)
404 .bind(limit)
405 .fetch_all(pool)
406 .await?;
407 Ok(rows)
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 #[test]
415 fn cron_validation() {
416 assert_eq!(validate_cron("30 9 * * *").unwrap(), "30 9 * * *");
417 assert_eq!(
418 validate_cron(" 0 9 * * Mon,Thu ").unwrap(),
419 "0 9 * * Mon,Thu"
420 );
421 assert!(validate_cron("9 * * *").is_err()); // 4 段
422 assert!(validate_cron("99 9 * * *").is_err()); // 分钟越界
423 assert!(validate_cron("0 0 0 0 0 0").is_err()); // 6 段
424 }
425
426 #[test]
427 fn cron_next_computes() {
428 let after = chrono::Utc::now();
429 let next = cron_next_after("*/5 * * * *", after).unwrap();
430 assert!(next > after);
431 assert!((next - after).num_minutes() <= 5);
432 }
433}