Skip to main content

yang_base/database/
datasource.rs

1//! 具名数据源注册表。
2//!
3//! [`DatasourceRegistry`] 是 `Tools` 的唯一数据库资源容器:一个应用可以持有多个
4//! MySQL / PostgreSQL 连接池,模块通过逻辑数据源名解析自己的库。默认源保留既有
5//! 单库语义,旧调用方无需改动。
6
7use crate::database::AnyDatabase;
8use crate::datasource::DatasourceId;
9use crate::error::BaseError;
10use crate::tools::ResourceHealth;
11use std::collections::BTreeMap;
12use yang_db::{BackendKind, DbError, PoolStatus};
13
14/// 单个具名数据源。
15#[derive(Debug)]
16pub struct Datasource {
17    id: DatasourceId,
18    database: AnyDatabase,
19    required: bool,
20}
21
22impl Datasource {
23    /// 用逻辑名与数据库容器构造数据源;容器内部身份会被覆盖为同一逻辑名。
24    pub fn new(id: DatasourceId, database: AnyDatabase, required: bool) -> Self {
25        Self {
26            database: database.with_id(id.clone()),
27            id,
28            required,
29        }
30    }
31
32    /// 返回逻辑数据源名。
33    pub fn id(&self) -> &DatasourceId {
34        &self.id
35    }
36
37    /// 返回底层数据库容器。
38    pub fn database(&self) -> &AnyDatabase {
39        &self.database
40    }
41
42    /// readiness 是否要求该源健康。
43    pub fn is_required(&self) -> bool {
44        self.required
45    }
46
47    /// 返回连接池状态快照。
48    pub fn pool_status(&self) -> PoolStatus {
49        self.database.pool_status()
50    }
51
52    /// 执行健康检查。
53    pub async fn health_check(&self) -> Result<bool, DbError> {
54        self.database.health_check().await
55    }
56
57    /// 幂等关闭连接池。
58    pub async fn close(&self) {
59        self.database.close().await;
60    }
61}
62
63/// 单个数据源的连接池状态快照。
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct DatasourcePoolStatus {
66    /// 逻辑数据源名。
67    pub datasource: DatasourceId,
68    /// 物理后端。
69    pub backend: BackendKind,
70    /// 连接池状态。
71    pub status: PoolStatus,
72}
73
74/// 单个数据源的健康快照(比 `ToolsHealth` 的扁平资源列表更易按源读取)。
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct DatasourceHealth {
77    /// 逻辑数据源名。
78    pub datasource: DatasourceId,
79    /// 物理后端。
80    pub backend: BackendKind,
81    /// 是否健康。
82    pub healthy: bool,
83    /// 失败原因;健康时为 `None`。
84    pub detail: Option<String>,
85    /// 是否参与 readiness。
86    pub required: bool,
87}
88
89/// 应用持有的全部具名数据源。
90#[derive(Debug)]
91pub struct DatasourceRegistry {
92    default: DatasourceId,
93    order: Vec<DatasourceId>,
94    by_id: BTreeMap<DatasourceId, Datasource>,
95}
96
97impl DatasourceRegistry {
98    /// 构造注册表。
99    ///
100    /// - `default` 为 `None` 时:只有一个源则自动成为默认源,多个源则报错;
101    /// - 重名、默认源不存在均报错。
102    pub fn new(
103        default: Option<DatasourceId>,
104        datasources: Vec<Datasource>,
105    ) -> Result<Self, BaseError> {
106        if datasources.is_empty() {
107            return Err(BaseError::ConfigError("数据源注册表不能为空".to_string()));
108        }
109        let mut order = Vec::with_capacity(datasources.len());
110        let mut by_id = BTreeMap::new();
111        for datasource in datasources {
112            let id = datasource.id().clone();
113            if by_id.insert(id.clone(), datasource).is_some() {
114                return Err(BaseError::ConfigError(format!("数据源重复注册: {id}")));
115            }
116            order.push(id);
117        }
118        let default = match default {
119            Some(default) => {
120                if !by_id.contains_key(&default) {
121                    return Err(BaseError::ConfigError(format!(
122                        "默认数据源未注册: {default}"
123                    )));
124                }
125                default
126            }
127            None if order.len() == 1 => order[0].clone(),
128            None => {
129                return Err(BaseError::ConfigError(
130                    "注册了多个数据源时必须显式指定默认数据源".to_string(),
131                ))
132            }
133        };
134        Ok(Self {
135            default,
136            order,
137            by_id,
138        })
139    }
140
141    /// 返回默认数据源名。
142    pub fn default_id(&self) -> &DatasourceId {
143        &self.default
144    }
145
146    /// 返回默认数据源。
147    pub fn default_datasource(&self) -> &Datasource {
148        // 构造期已保证默认源存在。
149        &self.by_id[&self.default]
150    }
151
152    /// 按逻辑名查找数据源。
153    pub fn get(&self, id: &DatasourceId) -> Option<&Datasource> {
154        self.by_id.get(id)
155    }
156
157    /// 解析可选数据源名:`None` 表示默认源。
158    pub fn resolve(&self, id: Option<&DatasourceId>) -> Result<&Datasource, BaseError> {
159        match id {
160            Some(id) => self.resolve_id(id),
161            None => Ok(self.default_datasource()),
162        }
163    }
164
165    /// 解析数据源名:字面量 `default` 在未注册同名源时回退到注册表的默认源。
166    pub fn resolve_id(&self, id: &DatasourceId) -> Result<&Datasource, BaseError> {
167        if let Some(datasource) = self.get(id) {
168            return Ok(datasource);
169        }
170        if id.is_default() {
171            return Ok(self.default_datasource());
172        }
173        Err(BaseError::ConfigError(format!("数据源未注册: {id}")))
174    }
175
176    /// 是否包含指定数据源。
177    pub fn contains(&self, id: &DatasourceId) -> bool {
178        self.by_id.contains_key(id)
179    }
180
181    /// 数据源数量。
182    pub fn len(&self) -> usize {
183        self.by_id.len()
184    }
185
186    /// 是否为空(构造期已禁止,保留 API 一致性)。
187    pub fn is_empty(&self) -> bool {
188        self.by_id.is_empty()
189    }
190
191    /// 按注册顺序迭代。
192    pub fn iter(&self) -> impl Iterator<Item = &Datasource> {
193        self.order.iter().filter_map(|id| self.by_id.get(id))
194    }
195
196    /// 逐源健康检查;只包含参与 readiness 的 required 源。
197    pub async fn health_check(&self) -> Vec<ResourceHealth> {
198        let mut resources = Vec::with_capacity(self.order.len());
199        for datasource in self.iter().filter(|datasource| datasource.is_required()) {
200            resources.push(resource_health(datasource).await);
201        }
202        resources
203    }
204
205    /// 逐源健康快照(带逻辑名与 required 标记)。
206    pub async fn health(&self) -> Vec<DatasourceHealth> {
207        let mut resources = Vec::with_capacity(self.order.len());
208        for datasource in self.iter() {
209            let result = datasource.health_check().await;
210            resources.push(DatasourceHealth {
211                datasource: datasource.id().clone(),
212                backend: datasource.database().backend(),
213                healthy: matches!(result, Ok(true)),
214                detail: match result {
215                    Ok(true) => None,
216                    Ok(false) => Some("健康检查返回 false".to_string()),
217                    Err(error) => Some(error.to_string()),
218                },
219                required: datasource.is_required(),
220            });
221        }
222        resources
223    }
224
225    /// 逐源连接池状态。
226    pub fn pool_statuses(&self) -> Vec<DatasourcePoolStatus> {
227        self.iter()
228            .map(|datasource| DatasourcePoolStatus {
229                datasource: datasource.id().clone(),
230                backend: datasource.database().backend(),
231                status: datasource.pool_status(),
232            })
233            .collect()
234    }
235
236    /// 按注册逆序关闭所有连接池。
237    pub async fn close(&self) {
238        for id in self.order.iter().rev() {
239            if let Some(datasource) = self.by_id.get(id) {
240                datasource.close().await;
241            }
242        }
243    }
244}
245
246async fn resource_health(datasource: &Datasource) -> ResourceHealth {
247    let resource = match datasource.database().backend() {
248        yang_db::BackendKind::MySql => "mysql",
249        yang_db::BackendKind::PostgreSql => "postgres",
250        _ => "database",
251    };
252    match datasource.health_check().await {
253        Ok(healthy) => ResourceHealth {
254            resource,
255            healthy,
256            detail: if healthy {
257                None
258            } else {
259                Some(format!("数据源 {} 健康检查返回 false", datasource.id()))
260            },
261        },
262        Err(error) => ResourceHealth {
263            resource,
264            healthy: false,
265            detail: Some(format!("数据源 {}: {error}", datasource.id())),
266        },
267    }
268}
269
270#[cfg(all(test, feature = "mysql"))]
271mod tests {
272    use super::*;
273
274    fn lazy_mysql() -> AnyDatabase {
275        let pool = sqlx::mysql::MySqlPoolOptions::new()
276            .connect_lazy("mysql://root:test@127.0.0.1:3306/test")
277            .expect("惰性 MySQL 池应创建成功");
278        AnyDatabase::mysql(
279            yang_db::mysql::Database::from_pool(pool, yang_db::mysql::DatabaseConfig::default())
280                .expect("默认配置应有效"),
281        )
282    }
283
284    fn datasource(name: &str) -> Datasource {
285        Datasource::new(
286            DatasourceId::new(name).expect("测试数据源名应有效"),
287            lazy_mysql(),
288            true,
289        )
290    }
291
292    #[tokio::test]
293    async fn single_source_becomes_default() {
294        let registry = DatasourceRegistry::new(None, vec![datasource("default")])
295            .expect("单源应自动成为默认源");
296        assert!(registry.default_id().is_default());
297        assert_eq!(registry.len(), 1);
298    }
299
300    #[tokio::test]
301    async fn multiple_sources_require_explicit_default() {
302        let error = DatasourceRegistry::new(None, vec![datasource("a"), datasource("b")])
303            .expect_err("多源必须显式默认");
304        assert!(error.to_string().contains("默认数据源"));
305    }
306
307    #[tokio::test]
308    async fn duplicate_names_are_rejected() {
309        let error = DatasourceRegistry::new(
310            Some(DatasourceId::default_source()),
311            vec![datasource("default"), datasource("default")],
312        )
313        .expect_err("重复数据源应被拒绝");
314        assert!(error.to_string().contains("重复注册"));
315    }
316
317    #[tokio::test]
318    async fn resolve_falls_back_to_default_and_reports_unknown() {
319        let registry = DatasourceRegistry::new(
320            Some(DatasourceId::default_source()),
321            vec![datasource("default"), datasource("pg_main")],
322        )
323        .expect("两源应构建成功");
324        assert!(registry.resolve(None).is_ok());
325        let unknown = DatasourceId::new("missing").expect("名称应有效");
326        assert!(registry.resolve(Some(&unknown)).is_err());
327    }
328}