burncloud_database_models/
repository.rs

1use async_trait::async_trait;
2use sqlx::{Database, Pool, Row};
3use uuid::Uuid;
4use chrono::{DateTime, Utc};
5use std::collections::HashMap;
6use burncloud_service_models as service;
7use crate::models::*;
8use crate::converters::*;
9
10/// 数据库仓库特质 - 定义通用的数据库操作接口
11#[async_trait]
12pub trait DatabaseRepository<DB: Database> {
13    type Error: std::error::Error + Send + Sync + 'static;
14
15    async fn pool(&self) -> &Pool<DB>;
16}
17
18/// 模型数据库仓库
19#[async_trait]
20pub trait ModelRepository<DB: Database>: DatabaseRepository<DB> {
21    /// 获取所有模型
22    async fn get_all_models(&self) -> Result<Vec<service::Model>, Self::Error>;
23
24    /// 根据ID获取模型
25    async fn get_model_by_id(&self, id: Uuid) -> Result<Option<service::Model>, Self::Error>;
26
27    /// 根据名称获取模型
28    async fn get_model_by_name(&self, name: &str) -> Result<Option<service::Model>, Self::Error>;
29
30    /// 创建新模型
31    async fn create_model(&self, model: &service::Model) -> Result<(), Self::Error>;
32
33    /// 更新模型
34    async fn update_model(&self, model: &service::Model) -> Result<(), Self::Error>;
35
36    /// 删除模型
37    async fn delete_model(&self, id: Uuid) -> Result<(), Self::Error>;
38
39    /// 搜索模型
40    async fn search_models(&self, query: &str, limit: Option<i64>) -> Result<Vec<service::Model>, Self::Error>;
41
42    /// 按类型获取模型
43    async fn get_models_by_type(&self, model_type: &service::ModelType) -> Result<Vec<service::Model>, Self::Error>;
44
45    /// 按提供商获取模型
46    async fn get_models_by_provider(&self, provider: &str) -> Result<Vec<service::Model>, Self::Error>;
47}
48
49/// 已安装模型数据库仓库
50#[async_trait]
51pub trait InstalledModelRepository<DB: Database>: DatabaseRepository<DB> {
52    /// 获取所有已安装模型
53    async fn get_all_installed_models(&self) -> Result<Vec<service::InstalledModel>, Self::Error>;
54
55    /// 根据模型ID获取已安装模型
56    async fn get_installed_model_by_model_id(&self, model_id: Uuid) -> Result<Option<service::InstalledModel>, Self::Error>;
57
58    /// 安装模型
59    async fn install_model(&self, installed_model: &service::InstalledModel) -> Result<(), Self::Error>;
60
61    /// 更新已安装模型
62    async fn update_installed_model(&self, installed_model: &service::InstalledModel) -> Result<(), Self::Error>;
63
64    /// 卸载模型
65    async fn uninstall_model(&self, model_id: Uuid) -> Result<(), Self::Error>;
66
67    /// 按状态获取已安装模型
68    async fn get_installed_models_by_status(&self, status: &service::ModelStatus) -> Result<Vec<service::InstalledModel>, Self::Error>;
69
70    /// 更新模型使用统计
71    async fn update_model_usage(&self, model_id: Uuid) -> Result<(), Self::Error>;
72}
73
74/// 运行时数据库仓库
75#[async_trait]
76pub trait RuntimeRepository<DB: Database>: DatabaseRepository<DB> {
77    /// 获取所有运行时配置
78    async fn get_all_runtime_configs(&self) -> Result<Vec<service::RuntimeConfig>, Self::Error>;
79
80    /// 创建运行时配置
81    async fn create_runtime_config(&self, config: &service::RuntimeConfig) -> Result<Uuid, Self::Error>;
82
83    /// 获取模型运行时
84    async fn get_model_runtime(&self, model_id: Uuid) -> Result<Option<service::ModelRuntime>, Self::Error>;
85
86    /// 创建模型运行时
87    async fn create_model_runtime(&self, runtime: &service::ModelRuntime) -> Result<(), Self::Error>;
88
89    /// 更新模型运行时
90    async fn update_model_runtime(&self, runtime: &service::ModelRuntime) -> Result<(), Self::Error>;
91
92    /// 删除模型运行时
93    async fn delete_model_runtime(&self, runtime_id: Uuid) -> Result<(), Self::Error>;
94
95    /// 记录运行时指标
96    async fn record_runtime_metrics(&self, metrics: &service::RuntimeMetrics) -> Result<(), Self::Error>;
97
98    /// 获取运行时指标历史
99    async fn get_runtime_metrics_history(
100        &self,
101        runtime_id: Uuid,
102        from: DateTime<Utc>,
103        to: DateTime<Utc>,
104    ) -> Result<Vec<service::RuntimeMetrics>, Self::Error>;
105
106    /// 记录运行时事件
107    async fn record_runtime_event(&self, event: &service::RuntimeEvent) -> Result<(), Self::Error>;
108
109    /// 获取运行时事件
110    async fn get_runtime_events(
111        &self,
112        runtime_id: Uuid,
113        limit: Option<i64>,
114    ) -> Result<Vec<service::RuntimeEvent>, Self::Error>;
115}
116
117/// 仓库管理数据库仓库
118#[async_trait]
119pub trait RepositoryManagementRepository<DB: Database>: DatabaseRepository<DB> {
120    /// 获取所有模型仓库
121    async fn get_all_repositories(&self) -> Result<Vec<service::ModelRepository>, Self::Error>;
122
123    /// 根据ID获取仓库
124    async fn get_repository_by_id(&self, id: Uuid) -> Result<Option<service::ModelRepository>, Self::Error>;
125
126    /// 创建仓库
127    async fn create_repository(&self, repository: &service::ModelRepository) -> Result<(), Self::Error>;
128
129    /// 更新仓库
130    async fn update_repository(&self, repository: &service::ModelRepository) -> Result<(), Self::Error>;
131
132    /// 删除仓库
133    async fn delete_repository(&self, id: Uuid) -> Result<(), Self::Error>;
134
135    /// 记录同步结果
136    async fn record_sync_result(&self, sync_result: &service::SyncResult) -> Result<(), Self::Error>;
137
138    /// 获取同步历史
139    async fn get_sync_history(&self, repository_id: Uuid, limit: Option<i64>) -> Result<Vec<service::SyncResult>, Self::Error>;
140}
141
142/// 监控数据库仓库
143#[async_trait]
144pub trait MonitoringRepository<DB: Database>: DatabaseRepository<DB> {
145    /// 记录系统指标
146    async fn record_system_metrics(&self, metrics: &service::SystemMetrics) -> Result<(), Self::Error>;
147
148    /// 获取系统指标历史
149    async fn get_system_metrics_history(
150        &self,
151        from: DateTime<Utc>,
152        to: DateTime<Utc>,
153    ) -> Result<Vec<service::SystemMetrics>, Self::Error>;
154
155    /// 记录应用指标
156    async fn record_application_metrics(&self, metrics: &service::ApplicationMetrics) -> Result<(), Self::Error>;
157
158    /// 获取应用指标历史
159    async fn get_application_metrics_history(
160        &self,
161        from: DateTime<Utc>,
162        to: DateTime<Utc>,
163    ) -> Result<Vec<service::ApplicationMetrics>, Self::Error>;
164
165    /// 记录模型指标
166    async fn record_model_metrics(&self, metrics: &service::ModelMetrics) -> Result<(), Self::Error>;
167
168    /// 获取模型指标历史
169    async fn get_model_metrics_history(
170        &self,
171        model_id: Uuid,
172        from: DateTime<Utc>,
173        to: DateTime<Utc>,
174    ) -> Result<Vec<service::ModelMetrics>, Self::Error>;
175
176    /// 创建告警事件
177    async fn create_alert_event(&self, alert: &service::AlertEvent) -> Result<(), Self::Error>;
178
179    /// 更新告警事件
180    async fn update_alert_event(&self, alert: &service::AlertEvent) -> Result<(), Self::Error>;
181
182    /// 获取活跃告警
183    async fn get_active_alerts(&self) -> Result<Vec<service::AlertEvent>, Self::Error>;
184
185    /// 获取告警历史
186    async fn get_alert_history(&self, limit: Option<i64>) -> Result<Vec<service::AlertEvent>, Self::Error>;
187}
188
189/// 配置数据库仓库
190#[async_trait]
191pub trait ConfigRepository<DB: Database>: DatabaseRepository<DB> {
192    /// 获取全局配置
193    async fn get_global_config(&self) -> Result<Option<service::GlobalConfig>, Self::Error>;
194
195    /// 保存全局配置
196    async fn save_global_config(&self, config: &service::GlobalConfig) -> Result<(), Self::Error>;
197
198    /// 获取配置历史
199    async fn get_config_history(&self, limit: Option<i64>) -> Result<Vec<service::GlobalConfig>, Self::Error>;
200}
201
202/// 任务管理数据库仓库
203#[async_trait]
204pub trait TaskRepository<DB: Database>: DatabaseRepository<DB> {
205    /// 创建任务
206    async fn create_task(&self, task: &DbTask) -> Result<(), Self::Error>;
207
208    /// 获取待处理任务
209    async fn get_pending_tasks(&self, limit: Option<i64>) -> Result<Vec<DbTask>, Self::Error>;
210
211    /// 更新任务状态
212    async fn update_task_status(&self, task_id: Uuid, status: &str) -> Result<(), Self::Error>;
213
214    /// 完成任务
215    async fn complete_task(&self, task_id: Uuid, result: Option<&str>) -> Result<(), Self::Error>;
216
217    /// 失败任务
218    async fn fail_task(&self, task_id: Uuid, error: &str) -> Result<(), Self::Error>;
219
220    /// 创建下载任务
221    async fn create_download_task(&self, task: &DbDownloadTask) -> Result<(), Self::Error>;
222
223    /// 更新下载进度
224    async fn update_download_progress(
225        &self,
226        task_id: Uuid,
227        downloaded_size: i64,
228        progress_percent: f32,
229        speed_bps: i64,
230    ) -> Result<(), Self::Error>;
231
232    /// 获取下载任务
233    async fn get_download_tasks_by_model(&self, model_id: Uuid) -> Result<Vec<DbDownloadTask>, Self::Error>;
234}
235
236/// 用户会话数据库仓库
237#[async_trait]
238pub trait SessionRepository<DB: Database>: DatabaseRepository<DB> {
239    /// 创建用户会话
240    async fn create_session(&self, session: &DbUserSession) -> Result<(), Self::Error>;
241
242    /// 根据令牌获取会话
243    async fn get_session_by_token(&self, token: &str) -> Result<Option<DbUserSession>, Self::Error>;
244
245    /// 更新会话最后访问时间
246    async fn update_session_last_accessed(&self, session_id: Uuid) -> Result<(), Self::Error>;
247
248    /// 删除会话
249    async fn delete_session(&self, session_id: Uuid) -> Result<(), Self::Error>;
250
251    /// 清理过期会话
252    async fn cleanup_expired_sessions(&self) -> Result<i64, Self::Error>;
253
254    /// 记录API使用
255    async fn record_api_usage(&self, usage: &DbApiUsage) -> Result<(), Self::Error>;
256
257    /// 获取API使用统计
258    async fn get_api_usage_stats(
259        &self,
260        from: DateTime<Utc>,
261        to: DateTime<Utc>,
262    ) -> Result<Vec<DbApiUsage>, Self::Error>;
263}
264
265/// 通用错误类型
266#[derive(Debug, thiserror::Error)]
267pub enum RepositoryError {
268    #[error("Database error: {0}")]
269    Database(#[from] sqlx::Error),
270    #[error("Serialization error: {0}")]
271    Serialization(#[from] serde_json::Error),
272    #[error("Not found")]
273    NotFound,
274    #[error("Validation error: {0}")]
275    Validation(String),
276    #[error("Conflict: {0}")]
277    Conflict(String),
278}
279
280/// 分页参数
281#[derive(Debug, Clone)]
282pub struct Pagination {
283    pub offset: i64,
284    pub limit: i64,
285}
286
287impl Default for Pagination {
288    fn default() -> Self {
289        Self {
290            offset: 0,
291            limit: 20,
292        }
293    }
294}
295
296/// 查询过滤器
297#[derive(Debug, Clone)]
298pub struct QueryFilter {
299    pub search: Option<String>,
300    pub model_type: Option<service::ModelType>,
301    pub provider: Option<String>,
302    pub status: Option<service::ModelStatus>,
303    pub tags: Vec<String>,
304    pub created_after: Option<DateTime<Utc>>,
305    pub created_before: Option<DateTime<Utc>>,
306}
307
308impl Default for QueryFilter {
309    fn default() -> Self {
310        Self {
311            search: None,
312            model_type: None,
313            provider: None,
314            status: None,
315            tags: Vec::new(),
316            created_after: None,
317            created_before: None,
318        }
319    }
320}
321
322/// 排序选项
323#[derive(Debug, Clone)]
324pub enum SortOrder {
325    Asc,
326    Desc,
327}
328
329#[derive(Debug, Clone)]
330pub struct SortBy {
331    pub field: String,
332    pub order: SortOrder,
333}
334
335impl Default for SortBy {
336    fn default() -> Self {
337        Self {
338            field: "created_at".to_string(),
339            order: SortOrder::Desc,
340        }
341    }
342}
343
344/// 查询选项
345#[derive(Debug, Clone, Default)]
346pub struct QueryOptions {
347    pub pagination: Pagination,
348    pub filter: QueryFilter,
349    pub sort_by: SortBy,
350}
351
352/// 查询结果
353#[derive(Debug, Clone)]
354pub struct QueryResult<T> {
355    pub items: Vec<T>,
356    pub total_count: i64,
357    pub has_more: bool,
358}
359
360impl<T> QueryResult<T> {
361    pub fn new(items: Vec<T>, total_count: i64, pagination: &Pagination) -> Self {
362        let has_more = (pagination.offset + pagination.limit) < total_count;
363        Self {
364            items,
365            total_count,
366            has_more,
367        }
368    }
369}