Elffuss BraidHub

kikocis/utopia public

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