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