1use 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#[derive(Debug)]
16pub struct Datasource {
17 id: DatasourceId,
18 database: AnyDatabase,
19 required: bool,
20}
21
22impl Datasource {
23 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 pub fn id(&self) -> &DatasourceId {
34 &self.id
35 }
36
37 pub fn database(&self) -> &AnyDatabase {
39 &self.database
40 }
41
42 pub fn is_required(&self) -> bool {
44 self.required
45 }
46
47 pub fn pool_status(&self) -> PoolStatus {
49 self.database.pool_status()
50 }
51
52 pub async fn health_check(&self) -> Result<bool, DbError> {
54 self.database.health_check().await
55 }
56
57 pub async fn close(&self) {
59 self.database.close().await;
60 }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct DatasourcePoolStatus {
66 pub datasource: DatasourceId,
68 pub backend: BackendKind,
70 pub status: PoolStatus,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct DatasourceHealth {
77 pub datasource: DatasourceId,
79 pub backend: BackendKind,
81 pub healthy: bool,
83 pub detail: Option<String>,
85 pub required: bool,
87}
88
89#[derive(Debug)]
91pub struct DatasourceRegistry {
92 default: DatasourceId,
93 order: Vec<DatasourceId>,
94 by_id: BTreeMap<DatasourceId, Datasource>,
95}
96
97impl DatasourceRegistry {
98 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 pub fn default_id(&self) -> &DatasourceId {
143 &self.default
144 }
145
146 pub fn default_datasource(&self) -> &Datasource {
148 &self.by_id[&self.default]
150 }
151
152 pub fn get(&self, id: &DatasourceId) -> Option<&Datasource> {
154 self.by_id.get(id)
155 }
156
157 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 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 pub fn contains(&self, id: &DatasourceId) -> bool {
178 self.by_id.contains_key(id)
179 }
180
181 pub fn len(&self) -> usize {
183 self.by_id.len()
184 }
185
186 pub fn is_empty(&self) -> bool {
188 self.by_id.is_empty()
189 }
190
191 pub fn iter(&self) -> impl Iterator<Item = &Datasource> {
193 self.order.iter().filter_map(|id| self.by_id.get(id))
194 }
195
196 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 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 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 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}