| 1 | mod adjudication; |
| 2 | mod alerting; |
| 3 | mod api; |
| 4 | mod auth; |
| 5 | mod blob; |
| 6 | mod bootstrap_ontology; |
| 7 | mod client_ctx; |
| 8 | mod docs_corpus; |
| 9 | mod error; |
| 10 | mod extraction; |
| 11 | mod github_issues; |
| 12 | mod ingest_sources; |
| 13 | mod jira_issues; |
| 14 | mod live; |
| 15 | mod llm_util; |
| 16 | mod mappings; |
| 17 | mod notion; |
| 18 | mod object_storage; |
| 19 | mod ontology_index; |
| 20 | mod ontology_packs; |
| 21 | mod owl_import; |
| 22 | mod pack_alignment; |
| 23 | mod pipeline; |
| 24 | mod predicate_match; |
| 25 | mod query_engine; |
| 26 | mod retrieval; |
| 27 | mod state; |
| 28 | mod type_resolution; |
| 29 | mod webdav; |
| 30 | |
| 31 | use state::AppState; |
| 32 | use std::sync::Arc; |
| 33 | use tracing_subscriber::EnvFilter; |
| 34 | use utopia_core::config::AppConfig; |
| 35 | use utopia_search::SearchIndex; |
| 36 | use uuid::Uuid; |
| 37 | |
| 38 | /// 记忆那条路带着「谁说的」(0015);别的任务没有这个字段,读到 None 本就该如此 |
| 39 | fn payload_proposed_by(payload: &serde_json::Value) -> Option<Uuid> { |
| 40 | payload |
| 41 | .get("proposed_by") |
| 42 | .and_then(|v| v.as_str()) |
| 43 | .and_then(|s| s.parse().ok()) |
| 44 | } |
| 45 | |
| 46 | fn payload_document_id(payload: &serde_json::Value) -> anyhow::Result<Uuid> { |
| 47 | payload |
| 48 | .get("document_id") |
| 49 | .and_then(|v| v.as_str()) |
| 50 | .and_then(|s| s.parse().ok()) |
| 51 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 document_id")) |
| 52 | } |
| 53 | |
| 54 | #[tokio::main] |
| 55 | async fn main() -> anyhow::Result<()> { |
| 56 | dotenvy::dotenv().ok(); |
| 57 | tracing_subscriber::fmt() |
| 58 | .with_env_filter( |
| 59 | EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,utopia=debug".into()), |
| 60 | ) |
| 61 | .init(); |
| 62 | |
| 63 | let cfg = AppConfig::load()?; |
| 64 | |
| 65 | // 迁移要建表建触发器,运行时不需要那些权限。两者分开,应用才能用一个 |
| 66 | // 只读写业务表、对台账只增不改的受限角色连库。迁移池用完立即释放, |
| 67 | // 那个高权限连接不在运行期常驻。 |
| 68 | let migration_url = cfg.migration_url().to_string(); |
| 69 | let separate_migration_role = cfg.migration_url.is_some(); |
| 70 | { |
| 71 | let mig_pool = utopia_store::db::connect(&migration_url, Some(2)).await?; |
| 72 | utopia_store::db::migrate(&mig_pool).await?; |
| 73 | mig_pool.close().await; |
| 74 | } |
| 75 | if separate_migration_role { |
| 76 | tracing::info!("数据库迁移完成(迁移身份与运行身份分离)"); |
| 77 | } else { |
| 78 | tracing::info!("数据库迁移完成"); |
| 79 | } |
| 80 | |
| 81 | let pool = utopia_store::db::connect(&cfg.database_url, cfg.db_max_connections).await?; |
| 82 | |
| 83 | let index_dir = std::path::Path::new(&cfg.data_dir).join("index"); |
| 84 | let search = Arc::new(SearchIndex::open(&index_dir)?); |
| 85 | tracing::info!("全文索引就绪: {}", index_dir.display()); |
| 86 | |
| 87 | // **索引落空就自己重建,不给按钮。** |
| 88 | // |
| 89 | // 索引是独立于数据库的一份文件:换机器、卷没挂上、目录损坏,任何一样都会让它 |
| 90 | // 落空。而落空之后检索只会静默回零——界面上看不出任何异样,用户会以为是 |
| 91 | // 「确实没有匹配」。这种失败不该靠人先意识到再去点一个按钮。 |
| 92 | // |
| 93 | // 判据是「库里有分块而索引空着」,不是「数目对不对得上」:后者在正常运行中 |
| 94 | // 也会短暂不等(一篇文档正在索引),拿它当判据会让每次启动都重建一遍。 |
| 95 | reindex_if_empty(&pool, &search).await; |
| 96 | |
| 97 | // JWT 密钥:环境变量优先(轮换、多实例显式对齐走这条),否则用库里那条; |
| 98 | // 库里也没有就现生成一条存进去。生成放在这里而不是 store 里,是因为 |
| 99 | // OsRng 已经随 argon2 在 server 的依赖里,store 不必为此多一个依赖。 |
| 100 | // 空串按未设置处理:compose 里写 ${UTOPIA_JWT_SECRET:-} 时环境变量是存在但为空的, |
| 101 | // 照字面读会得到 Some("")——一个所有部署都相同的空密钥,比默认值更糟。 |
| 102 | let jwt_secret = match cfg.jwt_secret.clone().filter(|s| !s.trim().is_empty()) { |
| 103 | Some(s) => s, |
| 104 | None => { |
| 105 | let secret = |
| 106 | utopia_store::access::ensure_jwt_secret(&pool, &auth::generate_jwt_secret()) |
| 107 | .await?; |
| 108 | tracing::info!("JWT 密钥取自部署设置(未显式配置 UTOPIA_JWT_SECRET)"); |
| 109 | secret |
| 110 | } |
| 111 | }; |
| 112 | |
| 113 | let state = AppState::new(pool.clone(), &cfg, search, jwt_secret); |
| 114 | |
| 115 | // worker 并发数:系统设置持久化,启动时装载;运行中经同一 AtomicUsize 热调 |
| 116 | let n = utopia_store::access::worker_concurrency(&pool) |
| 117 | .await |
| 118 | .unwrap_or(32); |
| 119 | state.worker_concurrency.store( |
| 120 | n.clamp(1, 256) as usize, |
| 121 | std::sync::atomic::Ordering::Relaxed, |
| 122 | ); |
| 123 | |
| 124 | // 任务分发:新任务类型在这里注册 |
| 125 | let worker_state = state.clone(); |
| 126 | tokio::spawn(utopia_store::jobs::run_worker( |
| 127 | pool, |
| 128 | state.worker_concurrency.clone(), |
| 129 | move |job| { |
| 130 | let st = worker_state.clone(); |
| 131 | async move { |
| 132 | // 任务失败时看一眼是不是模型端点连不上——那是系统级故障, |
| 133 | // 而现在它只会留在 jobs.last_error 里,没有任何界面看得到 |
| 134 | // |
| 135 | // 没救的失败在这里挂上标记,队列据此不再退避重试(#195): |
| 136 | // 判据在这一侧,因为 `utopia-store` 看不见 LLM 的错误类型 |
| 137 | let result = dispatch(&st, &job) |
| 138 | .await |
| 139 | .map_err(|e| match alerting::hopeless(&e) { |
| 140 | true => e.context(utopia_core::Terminal), |
| 141 | false => e, |
| 142 | }); |
| 143 | if let Err(e) = &result { |
| 144 | alerting::observe_job_failure(&st, &job, e).await; |
| 145 | } |
| 146 | result |
| 147 | } |
| 148 | }, |
| 149 | )); |
| 150 | |
| 151 | alerting::spawn_retention_sweep(state.clone()); |
| 152 | |
| 153 | // 定时摄入调度器:每分钟扫一次到期来源,入队同步任务 |
| 154 | let sched_state = state.clone(); |
| 155 | tokio::spawn(async move { |
| 156 | let mut tick = tokio::time::interval(std::time::Duration::from_secs(60)); |
| 157 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 158 | loop { |
| 159 | tick.tick().await; |
| 160 | match utopia_store::sources::due_sources(&sched_state.pool).await { |
| 161 | Ok(due) => { |
| 162 | for s in due { |
| 163 | match utopia_store::sources::mark_queued(&sched_state.pool, s.id).await { |
| 164 | Ok(true) => { |
| 165 | if let Err(e) = utopia_store::jobs::enqueue( |
| 166 | &sched_state.pool, |
| 167 | "sync_source", |
| 168 | serde_json::json!({ "source_id": s.id }), |
| 169 | ) |
| 170 | .await |
| 171 | { |
| 172 | tracing::warn!(source_id = %s.id, error = %e, "同步任务入队失败"); |
| 173 | } |
| 174 | } |
| 175 | Ok(false) => {} |
| 176 | Err(e) => tracing::warn!(source_id = %s.id, error = %e, "标记入队失败"), |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | Err(e) => tracing::warn!(error = %e, "扫描到期来源失败"), |
| 181 | } |
| 182 | } |
| 183 | }); |
| 184 | |
| 185 | // 定时推理调度器(0002 R1)。 |
| 186 | // |
| 187 | // **必须定时,不能只靠手点**:事实是持续变的——每篇文档抽取都在加边——而 |
| 188 | // 派生只在跑的那一刻算。不定时的话,下一篇文档进来之后图上的派生就是缺的, |
| 189 | // 而这种缺失界面上看不出来(不是错,是新链没推)。 |
| 190 | // |
| 191 | // 与来源同步共用一个节拍:每分钟扫一遍,到期的入队。真正的推导在任务里跑, |
| 192 | // 不在这个循环里——一个大库全量重推可能要几秒,卡在调度循环里会拖住别的库 |
| 193 | let infer_state = state.clone(); |
| 194 | tokio::spawn(async move { |
| 195 | let mut tick = tokio::time::interval(std::time::Duration::from_secs(60)); |
| 196 | tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 197 | loop { |
| 198 | tick.tick().await; |
| 199 | match utopia_store::reasoning::due_for_inference(&infer_state.pool).await { |
| 200 | Ok(due) => { |
| 201 | for kb_id in due { |
| 202 | if let Err(e) = utopia_store::jobs::enqueue( |
| 203 | &infer_state.pool, |
| 204 | "materialize_inferences", |
| 205 | serde_json::json!({ "kb_id": kb_id }), |
| 206 | ) |
| 207 | .await |
| 208 | { |
| 209 | tracing::warn!(kb_id = %kb_id, error = %e, "推理任务入队失败"); |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | Err(e) => tracing::warn!(error = %e, "扫描到期推理失败"), |
| 214 | } |
| 215 | } |
| 216 | }); |
| 217 | |
| 218 | let app = api::router(state, &cfg); |
| 219 | let listener = tokio::net::TcpListener::bind(&cfg.bind_addr).await?; |
| 220 | tracing::info!("Utopia 服务启动于 http://{}", cfg.bind_addr); |
| 221 | |
| 222 | // 浏览器可能把 localhost 解析为 ::1(IPv6)——配置为 IPv4 地址时补一个同端口的 |
| 223 | // IPv6 回环监听,避免「找不到 localhost」。绑定失败(端口被占/无 IPv6)仅告警。 |
| 224 | if let Ok(addr) = cfg.bind_addr.parse::<std::net::SocketAddrV4>() { |
| 225 | let v6_addr = format!("[::1]:{}", addr.port()); |
| 226 | match tokio::net::TcpListener::bind(&v6_addr).await { |
| 227 | Ok(v6_listener) => { |
| 228 | tracing::info!("同时监听 http://{v6_addr}"); |
| 229 | let app_v6 = app.clone(); |
| 230 | tokio::spawn(async move { |
| 231 | let svc = app_v6.into_make_service_with_connect_info::<std::net::SocketAddr>(); |
| 232 | if let Err(e) = axum::serve(v6_listener, svc).await { |
| 233 | tracing::warn!(error = %e, "IPv6 监听退出"); |
| 234 | } |
| 235 | }); |
| 236 | } |
| 237 | Err(e) => tracing::warn!(error = %e, "IPv6 回环绑定失败(不影响 IPv4)"), |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | // with_connect_info:审计需要真实的 TCP 对端地址。直连部署时它是唯一真值—— |
| 242 | // X-Forwarded-For 那些头此时并不存在,且本就不可轻信。 |
| 243 | let svc = app.into_make_service_with_connect_info::<std::net::SocketAddr>(); |
| 244 | axum::serve(listener, svc).await?; |
| 245 | Ok(()) |
| 246 | } |
| 247 | |
| 248 | /// 索引空着而库里有东西 → 从库里重建一遍。 |
| 249 | /// |
| 250 | /// 失败只告警不阻断启动:检索退化成「暂时搜不到」,而整个服务起不来是更坏的 |
| 251 | /// 结果。日志里那一行说清了发生什么,下次重启还会再试。 |
| 252 | async fn reindex_if_empty(pool: &sqlx::PgPool, search: &SearchIndex) { |
| 253 | if !search.is_empty() { |
| 254 | return; |
| 255 | } |
| 256 | let total = match utopia_store::documents::live_chunk_count(pool).await { |
| 257 | Ok(n) => n, |
| 258 | Err(e) => { |
| 259 | tracing::warn!(error = %e, "数不出分块数,跳过索引重建"); |
| 260 | return; |
| 261 | } |
| 262 | }; |
| 263 | if total == 0 { |
| 264 | return; |
| 265 | } |
| 266 | tracing::info!(chunks = total, "全文索引是空的,从库里重建"); |
| 267 | let rows = match utopia_store::documents::all_chunks_for_index(pool).await { |
| 268 | Ok(r) => r, |
| 269 | Err(e) => { |
| 270 | tracing::warn!(error = %e, "读分块失败,索引未重建"); |
| 271 | return; |
| 272 | } |
| 273 | }; |
| 274 | // 按文档攒批再写:`reindex_document` 一次替换一篇文档的全部分块, |
| 275 | // 逐条调会把前一条刚写的删掉 |
| 276 | let mut current: Option<(uuid::Uuid, uuid::Uuid)> = None; |
| 277 | let mut batch: Vec<(String, String)> = Vec::new(); |
| 278 | let mut done = 0usize; |
| 279 | let flush = |key: Option<(uuid::Uuid, uuid::Uuid)>, batch: &mut Vec<(String, String)>| { |
| 280 | if let Some((kb, doc)) = key { |
| 281 | if let Err(e) = search.reindex_document(&kb.to_string(), &doc.to_string(), batch) { |
| 282 | tracing::warn!(error = %e, document = %doc, "重建索引时有一篇没写进去"); |
| 283 | } |
| 284 | } |
| 285 | batch.clear(); |
| 286 | }; |
| 287 | for (kb_id, doc_id, chunk_id, text) in rows { |
| 288 | if current != Some((kb_id, doc_id)) { |
| 289 | flush(current, &mut batch); |
| 290 | current = Some((kb_id, doc_id)); |
| 291 | } |
| 292 | batch.push((chunk_id.to_string(), text)); |
| 293 | done += 1; |
| 294 | } |
| 295 | // `reindex_document` 自己 commit,所以这里不必再提交一次 |
| 296 | flush(current, &mut batch); |
| 297 | tracing::info!(chunks = done, "全文索引重建完成"); |
| 298 | } |
| 299 | /// |
| 300 | /// 任务分发:新任务类型在这里注册。 |
| 301 | /// |
| 302 | /// 单拎成函数而不是内联在闭包里,是为了让失败**有一个统一的出口**—— |
| 303 | /// 上面那层要在每次失败时看一眼错误链,内联的话每个分支都得自己记得。 |
| 304 | async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow::Result<()> { |
| 305 | match job.kind.as_str() { |
| 306 | "noop" => { |
| 307 | tracing::info!(job_id = job.id, "noop 任务执行成功"); |
| 308 | Ok(()) |
| 309 | } |
| 310 | "process_document" => { |
| 311 | let id = payload_document_id(&job.payload)?; |
| 312 | pipeline::process_document(st, id).await |
| 313 | } |
| 314 | "memory_ingest" => { |
| 315 | let id = payload_document_id(&job.payload)?; |
| 316 | pipeline::memory_ingest(st, id, payload_proposed_by(&job.payload)).await |
| 317 | } |
| 318 | "explore_mappings" => { |
| 319 | let kb_id: Uuid = job |
| 320 | .payload |
| 321 | .get("kb_id") |
| 322 | .and_then(|v| v.as_str()) |
| 323 | .and_then(|s| s.parse().ok()) |
| 324 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?; |
| 325 | mappings::explore_mappings(st, kb_id).await |
| 326 | } |
| 327 | // 定时重推(0002 R1)。**先记时间再推**——推导抛错时也不该让这个库 |
| 328 | // 在下一分钟被重新扫起来,那会变成一个每分钟失败一次的循环 |
| 329 | "materialize_inferences" => { |
| 330 | let kb_id: Uuid = job |
| 331 | .payload |
| 332 | .get("kb_id") |
| 333 | .and_then(|v| v.as_str()) |
| 334 | .and_then(|s| s.parse().ok()) |
| 335 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?; |
| 336 | utopia_store::reasoning::mark_inference_ran(&st.pool, kb_id).await?; |
| 337 | let report = utopia_store::reasoning::materialize(&st.pool, kb_id).await?; |
| 338 | // **到点对比**:`materialize` 本来就在拿这一轮算出来的对上库里现有的, |
| 339 | // 所以「对比」不是新机制。这里只把那次对比的结果留下来给人看—— |
| 340 | // 没有变化时不写,免得台账被每小时一条「什么都没变」淹掉 |
| 341 | if report.inserted > 0 || report.invalidated > 0 { |
| 342 | let _ = utopia_store::audit::record( |
| 343 | &st.pool, |
| 344 | Some(kb_id), |
| 345 | Uuid::nil(), |
| 346 | "inference.materialized", |
| 347 | "knowledge_base", |
| 348 | Some(kb_id), |
| 349 | serde_json::json!({ |
| 350 | "scheduled": true, |
| 351 | "inserted": report.inserted, |
| 352 | "invalidated": report.invalidated, |
| 353 | "rules": report.rules, |
| 354 | }), |
| 355 | ) |
| 356 | .await; |
| 357 | st.emit_graph(kb_id); |
| 358 | } |
| 359 | Ok(()) |
| 360 | } |
| 361 | "extract_document" => { |
| 362 | let id = payload_document_id(&job.payload)?; |
| 363 | extraction::extract_document(st, id, payload_proposed_by(&job.payload)).await |
| 364 | } |
| 365 | "bootstrap_ontology" => { |
| 366 | let kb_id: Uuid = job |
| 367 | .payload |
| 368 | .get("kb_id") |
| 369 | .and_then(|v| v.as_str()) |
| 370 | .and_then(|s| s.parse().ok()) |
| 371 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?; |
| 372 | bootstrap_ontology::bootstrap_ontology(st, kb_id).await |
| 373 | } |
| 374 | // 本体向量索引:**后台建,不卡请求**。 |
| 375 | // 一份 965 类的本体首次要嵌 2600 行,六到八分钟;放在 |
| 376 | // 交互请求里就是导入完之后第一个用到检索的人干等 |
| 377 | "embed_ontology" => { |
| 378 | let kb_id: Uuid = job |
| 379 | .payload |
| 380 | .get("kb_id") |
| 381 | .and_then(|v| v.as_str()) |
| 382 | .and_then(|s| s.parse().ok()) |
| 383 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?; |
| 384 | ontology_index::refresh(st, kb_id).await.map(|_| ()) |
| 385 | } |
| 386 | "adjudicate_entities" => { |
| 387 | let kb_id: Uuid = job |
| 388 | .payload |
| 389 | .get("kb_id") |
| 390 | .and_then(|v| v.as_str()) |
| 391 | .and_then(|s| s.parse().ok()) |
| 392 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 kb_id"))?; |
| 393 | adjudication::adjudicate_entities(st, kb_id).await |
| 394 | } |
| 395 | "sync_source" => { |
| 396 | let source_id: Uuid = job |
| 397 | .payload |
| 398 | .get("source_id") |
| 399 | .and_then(|v| v.as_str()) |
| 400 | .and_then(|s| s.parse().ok()) |
| 401 | .ok_or_else(|| anyhow::anyhow!("payload 缺少 source_id"))?; |
| 402 | ingest_sources::sync_source(st, source_id).await |
| 403 | } |
| 404 | other => anyhow::bail!("未知任务类型: {other}"), |
| 405 | } |
| 406 | } |