Elffuss BraidHub

kikocis/utopia public

de93f0eb4620 · 12.7 KiBRawPermalink
1//! 问数数据源:系统层注册(admin,凭据只进不出)+ 知识库层挂载(库 admin)。
2//! 挂载/手动刷新时把目标库的 schema 生成 markdown 摄入 KB(同 key 原地更新),
3//! Chat 写 SQL 前可检索到表结构。查询执行的安全闸在刀 2(query_data 工具)。
4
5use axum::extract::{Path, State};
6use axum::Json;
7use serde::Deserialize;
8use serde_json::json;
9use utopia_core::models::Role;
10use utopia_core::AppError;
11use uuid::Uuid;
12
13use super::graph_routes::require_kb;
14use crate::auth::AuthUser;
15use crate::error::ApiResult;
16use crate::state::AppState;
17
18fn require_admin(user: &utopia_core::models::User) -> Result<(), AppError> {
19 if user.is_admin {
20 Ok(())
21 } else {
22 Err(AppError::Forbidden)
23 }
24}
25
26// ---------------------------------------------------------------------------
27// 系统层:注册/测试/删除
28// ---------------------------------------------------------------------------
29
30pub async fn list(
31 State(state): State<AppState>,
32 AuthUser(user): AuthUser,
33) -> ApiResult<Json<serde_json::Value>> {
34 require_admin(&user)?;
35 let sources = utopia_store::datasources::list(&state.pool).await?;
36 Ok(Json(json!({ "data_sources": sources })))
37}
38
39#[derive(Deserialize)]
40pub struct CreateBody {
41 pub name: String,
42 #[serde(default = "default_engine")]
43 pub engine: String,
44 pub conn_string: String,
45}
46fn default_engine() -> String {
47 "postgres".into()
48}
49
50pub async fn create(
51 State(state): State<AppState>,
52 AuthUser(user): AuthUser,
53 Json(body): Json<CreateBody>,
54) -> ApiResult<Json<serde_json::Value>> {
55 require_admin(&user)?;
56 let id = utopia_store::datasources::create(
57 &state.pool,
58 &body.name,
59 &body.engine,
60 &body.conn_string,
61 user.id,
62 )
63 .await?;
64 Ok(Json(json!({ "id": id })))
65}
66
67pub async fn delete(
68 State(state): State<AppState>,
69 AuthUser(user): AuthUser,
70 Path(id): Path<Uuid>,
71) -> ApiResult<Json<serde_json::Value>> {
72 require_admin(&user)?;
73 utopia_store::datasources::delete(&state.pool, id).await?;
74 Ok(Json(json!({ "ok": true })))
75}
76
77pub async fn test(
78 State(state): State<AppState>,
79 AuthUser(user): AuthUser,
80 Path(id): Path<Uuid>,
81) -> ApiResult<Json<serde_json::Value>> {
82 require_admin(&user)?;
83 let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, id).await?;
84 let ok = match crate::query_engine::engine_for(&engine, &conn) {
85 Ok(eng) => eng.test().await.is_ok(),
86 Err(_) => false,
87 };
88 utopia_store::datasources::record_test(&state.pool, id, ok).await?;
89 Ok(Json(json!({ "ok": ok })))
90}
91
92// ---------------------------------------------------------------------------
93// 知识库层:挂载/卸载/schema 刷新
94// ---------------------------------------------------------------------------
95
96pub async fn mounted(
97 State(state): State<AppState>,
98 AuthUser(user): AuthUser,
99 Path(kb_id): Path<Uuid>,
100) -> ApiResult<Json<serde_json::Value>> {
101 require_kb(&state, &user, kb_id, Role::Viewer).await?;
102 let mounted = utopia_store::datasources::mounted(&state.pool, kb_id).await?;
103 Ok(Json(json!({ "data_sources": mounted })))
104}
105
106/// 库 admin 能挂哪些(列表给 name/summary,不含凭据)。
107///
108/// **只列授权给本工作区的(0014)。** 从前这里返回 `datasources::list`——
109/// 全部署每一个源,于是任何库的管理员都看得见并挂得上任意生产库。
110pub async fn mountable(
111 State(state): State<AppState>,
112 AuthUser(user): AuthUser,
113 Path(kb_id): Path<Uuid>,
114) -> ApiResult<Json<serde_json::Value>> {
115 let kb = require_kb(&state, &user, kb_id, Role::Admin).await?;
116 let granted =
117 utopia_store::datasources::granted_to_workspace(&state.pool, kb.workspace_id).await?;
118 Ok(Json(json!({ "data_sources": granted })))
119}
120
121pub async fn mount(
122 State(state): State<AppState>,
123 AuthUser(user): AuthUser,
124 Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
125) -> ApiResult<Json<serde_json::Value>> {
126 require_kb(&state, &user, kb_id, Role::Admin).await?;
127 // **列表过滤不是守卫。** 那只挡「看得见」,而这个端点是照着 id 调的——
128 // 谁都能自己拼一个 uuid 打过来。授权在这里再查一次
129 if !utopia_store::datasources::is_granted(&state.pool, kb_id, ds_id).await? {
130 return Err(AppError::invalid(
131 "source_not_granted",
132 "This data source is not available to this workspace",
133 )
134 .into());
135 }
136 utopia_store::datasources::mount(&state.pool, kb_id, ds_id).await?;
137 // 挂载即摄取 schema:Chat 写 SQL 前能检索到表结构
138 //
139 // **这一步失败不能回报成挂载失败。** 上面那行已经写进 kb_data_sources 了,
140 // 源是真挂着的;从前这里 `?` 出去回 500,人以为没挂上,实际挂上了——
141 // 而问数看不见它有哪些表。改成:照实说挂载成了,schema 没成,并且
142 // 报进告警中心,因为那之后就是一个静默的缺失状态(0009)
143 match sync_schema_doc(&state, kb_id, ds_id).await {
144 Ok(synced) => Ok(Json(json!({ "ok": true, "schema_tables": synced }))),
145 Err(e) => {
146 let name = source_name(&state, ds_id).await;
147 crate::alerting::observe_schema_sync_failure(&state, kb_id, ds_id, &name, &e).await;
148 Ok(Json(json!({
149 "ok": true,
150 "schema_tables": 0,
151 "schema_error": e.to_string(),
152 })))
153 }
154 }
155}
156
157/// 告警要留住名字:源被删之后 `subject_id` 就解析不出名字了。查不到时给占位符
158/// 而不是让告警本身失败——**报警路径上的失败不该淹掉它要报的那件事**。
159async fn source_name(state: &AppState, ds_id: Uuid) -> String {
160 utopia_store::datasources::list(&state.pool)
161 .await
162 .ok()
163 .and_then(|all| all.into_iter().find(|d| d.id == ds_id).map(|d| d.name))
164 .unwrap_or_else(|| ds_id.to_string())
165}
166
167pub async fn unmount(
168 State(state): State<AppState>,
169 AuthUser(user): AuthUser,
170 Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
171) -> ApiResult<Json<serde_json::Value>> {
172 require_kb(&state, &user, kb_id, Role::Admin).await?;
173 utopia_store::datasources::unmount(&state.pool, kb_id, ds_id).await?;
174 Ok(Json(json!({ "ok": true })))
175}
176
177/// 手动刷新结构。
178///
179/// **这里照旧把错误回给调用方**——点按钮的人正看着,而且什么都没半途发生。
180/// 但同样报一条告警:留下的后果与挂载失败时一模一样(源挂着、表结构是旧的
181/// 或空的),而点按钮的人未必是需要知道这件事的人。
182pub async fn sync_schema(
183 State(state): State<AppState>,
184 AuthUser(user): AuthUser,
185 Path((kb_id, ds_id)): Path<(Uuid, Uuid)>,
186) -> ApiResult<Json<serde_json::Value>> {
187 require_kb(&state, &user, kb_id, Role::Admin).await?;
188 match sync_schema_doc(&state, kb_id, ds_id).await {
189 Ok(synced) => Ok(Json(json!({ "ok": true, "schema_tables": synced }))),
190 Err(e) => {
191 let name = source_name(&state, ds_id).await;
192 crate::alerting::observe_schema_sync_failure(&state, kb_id, ds_id, &name, &e).await;
193 Err(AppError::Other(e).into())
194 }
195 }
196}
197
198/// Agentic 探索:后台任务读挂载源 schema,提议 指标/维度→字段 映射(低置信入 Review)。
199pub async fn explore(
200 State(state): State<AppState>,
201 AuthUser(user): AuthUser,
202 Path(kb_id): Path<Uuid>,
203) -> ApiResult<Json<serde_json::Value>> {
204 require_kb(&state, &user, kb_id, Role::Admin).await?;
205 if utopia_store::datasources::mounted(&state.pool, kb_id)
206 .await?
207 .is_empty()
208 {
209 return Err(AppError::invalid("no_data_sources", "No data sources mounted").into());
210 }
211 utopia_store::jobs::enqueue(&state.pool, "explore_mappings", json!({ "kb_id": kb_id })).await?;
212 Ok(Json(json!({ "ok": true })))
213}
214
215/// 拉 information_schema 生成 markdown,走三路判定摄入(同 key 原地更新)。
216/// 文档挂在 per-KB 的 "Data schemas" folder 来源下。
217async fn sync_schema_doc(state: &AppState, kb_id: Uuid, ds_id: Uuid) -> anyhow::Result<usize> {
218 const MAX_TABLES: usize = 200;
219 let name = utopia_store::datasources::list(&state.pool)
220 .await?
221 .into_iter()
222 .find(|d| d.id == ds_id)
223 .map(|d| d.name)
224 .ok_or_else(|| anyhow::anyhow!("Data source not found"))?;
225 let (engine, conn) = utopia_store::datasources::engine_and_conn(&state.pool, ds_id).await?;
226 let cols = crate::query_engine::engine_for(&engine, &conn)?
227 .fetch_schema()
228 .await?;
229
230 let mut md = format!(
231 "# Data source: {name}\n\nTables and columns available for SQL queries against this source.\n"
232 );
233 let mut current = String::new();
234 let mut tables = 0usize;
235 for c in &cols {
236 let key = format!("{}.{}", c.schema, c.table);
237 if key != current {
238 if tables >= MAX_TABLES {
239 md.push_str("\n(further tables omitted)\n");
240 break;
241 }
242 current = key.clone();
243 tables += 1;
244 md.push_str(&format!("\n## {key}\n"));
245 }
246 md.push_str(&format!(
247 "- {} ({}){}\n",
248 c.column,
249 c.data_type,
250 c.comment
251 .as_deref()
252 .map(|x| format!(" — {x}"))
253 .unwrap_or_default()
254 ));
255 }
256
257 // per-KB "Data schemas" 容器来源(folder:纯容器语义)
258 let folder = match sqlx::query_as::<_, (Uuid,)>(
259 "SELECT id FROM sources WHERE kb_id = $1 AND kind = 'folder' AND name = 'Data schemas'",
260 )
261 .bind(kb_id)
262 .fetch_optional(&state.pool)
263 .await?
264 {
265 Some((id,)) => id,
266 None => {
267 utopia_store::sources::create(
268 &state.pool,
269 kb_id,
270 "folder",
271 "Data schemas",
272 &serde_json::json!({}),
273 Some("database"),
274 None,
275 None,
276 )
277 .await?
278 .id
279 }
280 };
281 crate::ingest_sources::ingest_item(
282 state,
283 kb_id,
284 folder,
285 &format!("datasource:{ds_id}:schema"),
286 &format!("{name}-schema.md"),
287 "text/markdown",
288 md.as_bytes(),
289 None,
290 )
291 .await?;
292 state.emit_source(kb_id);
293 Ok(tables)
294}
295
296// ---------------------------------------------------------------------------
297// 系统层:授权(0014)
298//
299// 授权与挂载是两层,各有各的主人:
300// 授权 = 系统管理员说「这个源可以给哪些工作区用」 ← 这里
301// 挂载 = KB 管理员说「我这个库挂哪几个」 ← 上面那组
302// 两层都是多对多。挂载只能在授权过的集合里挑。
303// ---------------------------------------------------------------------------
304
305/// 这个源授权给了哪些工作区。
306pub async fn grants(
307 State(state): State<AppState>,
308 AuthUser(user): AuthUser,
309 Path(id): Path<Uuid>,
310) -> ApiResult<Json<serde_json::Value>> {
311 require_admin(&user)?;
312 let rows = utopia_store::datasources::grants_for_source(&state.pool, id).await?;
313 let workspaces: Vec<serde_json::Value> = rows
314 .into_iter()
315 .map(|(id, name)| json!({ "id": id, "name": name }))
316 .collect();
317 Ok(Json(json!({ "workspaces": workspaces })))
318}
319
320pub async fn grant(
321 State(state): State<AppState>,
322 AuthUser(user): AuthUser,
323 Path((id, workspace_id)): Path<(Uuid, Uuid)>,
324) -> ApiResult<Json<serde_json::Value>> {
325 require_admin(&user)?;
326 utopia_store::datasources::grant(&state.pool, id, workspace_id, user.id).await?;
327 let _ = utopia_store::audit::record(
328 &state.pool,
329 None,
330 user.id,
331 "data_source.granted",
332 "data_source",
333 Some(id),
334 json!({ "workspace_id": workspace_id }),
335 )
336 .await;
337 Ok(Json(json!({ "ok": true })))
338}
339
340/// 收回授权。**连同该工作区里已挂上的一起卸掉**——只删授权行的话,
341/// 问数读的还是 `kb_data_sources`,撤销就不生效。返回卸掉了几个,
342/// 好让界面说得出「顺带卸了 3 个库」而不是悄悄断人家的连接。
343pub async fn revoke(
344 State(state): State<AppState>,
345 AuthUser(user): AuthUser,
346 Path((id, workspace_id)): Path<(Uuid, Uuid)>,
347) -> ApiResult<Json<serde_json::Value>> {
348 require_admin(&user)?;
349 let unmounted = utopia_store::datasources::revoke(&state.pool, id, workspace_id).await?;
350 let _ = utopia_store::audit::record(
351 &state.pool,
352 None,
353 user.id,
354 "data_source.revoked",
355 "data_source",
356 Some(id),
357 json!({ "workspace_id": workspace_id, "unmounted": unmounted }),
358 )
359 .await;
360 Ok(Json(json!({ "ok": true, "unmounted": unmounted })))
361}