Elffuss BraidHub

kikocis/utopia public

b7cca7fa81d9 · 4.2 KiBRawPermalink
1//! 告警的产生侧(0005)。存取在 `utopia_store::alerts`,这里只管**什么时候报**。
2//!
3//! 没有"什么时候消"——一次故障一行,写完不再改。见那个模块的文档。
4
5use utopia_core::models::Role;
6use utopia_store::alerts;
7
8use crate::state::AppState;
9
10/// 告警保留多少天。**纯原子的代价就在这里**:一个坏掉的来源按小时同步,
11/// 一天写 24 行,不清理这张表会长成第二个日志文件。
12///
13/// 30 天够回答"上个月那次是怎么回事",而更久远的事该去翻 `audit_events` 与日志。
14const RETAIN_DAYS: i32 = 30;
15
16/// 任务失败时看一眼是不是模型端点不可用。
17///
18/// **只在任务最终放弃时报**(`attempts >= max_attempts`)。中间那几次重试报了
19/// 就是同一件事发三遍——重试本来就是为了不惊动人,报出去等于把它的意义抵消掉。
20/// 一个任务至多一条告警,不需要任何去重状态。
21///
22/// 判据是错误链里有没有 [`utopia_llm::Unreachable`],**不匹配错误文本**——
23/// 调用链上任何一层加一句 context 都会改文本。
24pub async fn observe_job_failure(
25 state: &AppState,
26 job: &utopia_store::jobs::Job,
27 err: &anyhow::Error,
28) {
29 if job.attempts < job.max_attempts {
30 return;
31 }
32 if !utopia_llm::is_unreachable(err) {
33 return;
34 }
35 // 系统级:哪个库的任务撞上的不重要,端点是整个部署共用的
36 if let Err(e) = alerts::raise(
37 &state.pool,
38 alerts::NewAlert {
39 kb_id: None,
40 severity: "error",
41 kind: alerts::kind::LLM_UNREACHABLE,
42 min_role: Role::Admin,
43 subject_type: Some("system"),
44 subject_id: None,
45 detail: serde_json::json!({ "job": job.kind, "error": err.to_string() }),
46 },
47 )
48 .await
49 {
50 tracing::warn!(error = %e, "上报 llm.unreachable 失败");
51 return;
52 }
53 state.emit_alert();
54}
55
56/// 每天清一次过期告警。
57pub fn spawn_retention_sweep(state: AppState) {
58 tokio::spawn(async move {
59 let mut tick = tokio::time::interval(std::time::Duration::from_secs(24 * 60 * 60));
60 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
61 loop {
62 tick.tick().await;
63 match alerts::purge_older_than(&state.pool, RETAIN_DAYS).await {
64 Ok(n) if n > 0 => {
65 tracing::info!(count = n, days = RETAIN_DAYS, "清理过期告警");
66 state.emit_alert();
67 }
68 Ok(_) => {}
69 Err(e) => tracing::warn!(error = %e, "清理过期告警失败"),
70 }
71 }
72 });
73}
74
75/// 数据源挂上了,库表结构却没摄进来。
76///
77/// **报的不是那次失败,是它留下的状态。** 挂载分两步:写 `kb_data_sources`,
78/// 再把 schema 生成文档摄进库。第一步成了、第二步没成的时候,源是真挂着的——
79/// `query_data` 会入列,而模型检索不到任何表结构,只能瞎猜列名。
80///
81/// 挂载那一刻的报错只有点按钮的人看得见。此后这个库就一直静默地缺着,
82/// 而这正是 0009 说的那件事:真正伤人的不是失败,是失败无声。
83pub async fn observe_schema_sync_failure(
84 state: &AppState,
85 kb_id: uuid::Uuid,
86 source_id: uuid::Uuid,
87 source_name: &str,
88 err: &anyhow::Error,
89) {
90 if let Err(e) = alerts::raise(
91 &state.pool,
92 alerts::NewAlert {
93 kb_id: Some(kb_id),
94 severity: "warning",
95 kind: alerts::kind::SCHEMA_SYNC_FAILED,
96 // 配置类:要修的是连接串或网络,不是内容。找 admin
97 min_role: Role::Admin,
98 subject_type: Some("data_source"),
99 subject_id: Some(source_id),
100 // 名字在这里存一份——源被删掉之后 subject_id 解析不出名字,
101 // 而告警该留得住
102 detail: serde_json::json!({
103 "source": source_name,
104 "error": err.to_string(),
105 }),
106 },
107 )
108 .await
109 {
110 tracing::warn!(error = %e, "上报 data_source.schema_sync_failed 失败");
111 return;
112 }
113 state.emit_alert();
114}