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#[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#[async_trait]
20pub trait ModelRepository<DB: Database>: DatabaseRepository<DB> {
21 async fn get_all_models(&self) -> Result<Vec<service::Model>, Self::Error>;
23
24 async fn get_model_by_id(&self, id: Uuid) -> Result<Option<service::Model>, Self::Error>;
26
27 async fn get_model_by_name(&self, name: &str) -> Result<Option<service::Model>, Self::Error>;
29
30 async fn create_model(&self, model: &service::Model) -> Result<(), Self::Error>;
32
33 async fn update_model(&self, model: &service::Model) -> Result<(), Self::Error>;
35
36 async fn delete_model(&self, id: Uuid) -> Result<(), Self::Error>;
38
39 async fn search_models(&self, query: &str, limit: Option<i64>) -> Result<Vec<service::Model>, Self::Error>;
41
42 async fn get_models_by_type(&self, model_type: &service::ModelType) -> Result<Vec<service::Model>, Self::Error>;
44
45 async fn get_models_by_provider(&self, provider: &str) -> Result<Vec<service::Model>, Self::Error>;
47}
48
49#[async_trait]
51pub trait InstalledModelRepository<DB: Database>: DatabaseRepository<DB> {
52 async fn get_all_installed_models(&self) -> Result<Vec<service::InstalledModel>, Self::Error>;
54
55 async fn get_installed_model_by_model_id(&self, model_id: Uuid) -> Result<Option<service::InstalledModel>, Self::Error>;
57
58 async fn install_model(&self, installed_model: &service::InstalledModel) -> Result<(), Self::Error>;
60
61 async fn update_installed_model(&self, installed_model: &service::InstalledModel) -> Result<(), Self::Error>;
63
64 async fn uninstall_model(&self, model_id: Uuid) -> Result<(), Self::Error>;
66
67 async fn get_installed_models_by_status(&self, status: &service::ModelStatus) -> Result<Vec<service::InstalledModel>, Self::Error>;
69
70 async fn update_model_usage(&self, model_id: Uuid) -> Result<(), Self::Error>;
72}
73
74#[async_trait]
76pub trait RuntimeRepository<DB: Database>: DatabaseRepository<DB> {
77 async fn get_all_runtime_configs(&self) -> Result<Vec<service::RuntimeConfig>, Self::Error>;
79
80 async fn create_runtime_config(&self, config: &service::RuntimeConfig) -> Result<Uuid, Self::Error>;
82
83 async fn get_model_runtime(&self, model_id: Uuid) -> Result<Option<service::ModelRuntime>, Self::Error>;
85
86 async fn create_model_runtime(&self, runtime: &service::ModelRuntime) -> Result<(), Self::Error>;
88
89 async fn update_model_runtime(&self, runtime: &service::ModelRuntime) -> Result<(), Self::Error>;
91
92 async fn delete_model_runtime(&self, runtime_id: Uuid) -> Result<(), Self::Error>;
94
95 async fn record_runtime_metrics(&self, metrics: &service::RuntimeMetrics) -> Result<(), Self::Error>;
97
98 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 async fn record_runtime_event(&self, event: &service::RuntimeEvent) -> Result<(), Self::Error>;
108
109 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#[async_trait]
119pub trait RepositoryManagementRepository<DB: Database>: DatabaseRepository<DB> {
120 async fn get_all_repositories(&self) -> Result<Vec<service::ModelRepository>, Self::Error>;
122
123 async fn get_repository_by_id(&self, id: Uuid) -> Result<Option<service::ModelRepository>, Self::Error>;
125
126 async fn create_repository(&self, repository: &service::ModelRepository) -> Result<(), Self::Error>;
128
129 async fn update_repository(&self, repository: &service::ModelRepository) -> Result<(), Self::Error>;
131
132 async fn delete_repository(&self, id: Uuid) -> Result<(), Self::Error>;
134
135 async fn record_sync_result(&self, sync_result: &service::SyncResult) -> Result<(), Self::Error>;
137
138 async fn get_sync_history(&self, repository_id: Uuid, limit: Option<i64>) -> Result<Vec<service::SyncResult>, Self::Error>;
140}
141
142#[async_trait]
144pub trait MonitoringRepository<DB: Database>: DatabaseRepository<DB> {
145 async fn record_system_metrics(&self, metrics: &service::SystemMetrics) -> Result<(), Self::Error>;
147
148 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 async fn record_application_metrics(&self, metrics: &service::ApplicationMetrics) -> Result<(), Self::Error>;
157
158 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 async fn record_model_metrics(&self, metrics: &service::ModelMetrics) -> Result<(), Self::Error>;
167
168 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 async fn create_alert_event(&self, alert: &service::AlertEvent) -> Result<(), Self::Error>;
178
179 async fn update_alert_event(&self, alert: &service::AlertEvent) -> Result<(), Self::Error>;
181
182 async fn get_active_alerts(&self) -> Result<Vec<service::AlertEvent>, Self::Error>;
184
185 async fn get_alert_history(&self, limit: Option<i64>) -> Result<Vec<service::AlertEvent>, Self::Error>;
187}
188
189#[async_trait]
191pub trait ConfigRepository<DB: Database>: DatabaseRepository<DB> {
192 async fn get_global_config(&self) -> Result<Option<service::GlobalConfig>, Self::Error>;
194
195 async fn save_global_config(&self, config: &service::GlobalConfig) -> Result<(), Self::Error>;
197
198 async fn get_config_history(&self, limit: Option<i64>) -> Result<Vec<service::GlobalConfig>, Self::Error>;
200}
201
202#[async_trait]
204pub trait TaskRepository<DB: Database>: DatabaseRepository<DB> {
205 async fn create_task(&self, task: &DbTask) -> Result<(), Self::Error>;
207
208 async fn get_pending_tasks(&self, limit: Option<i64>) -> Result<Vec<DbTask>, Self::Error>;
210
211 async fn update_task_status(&self, task_id: Uuid, status: &str) -> Result<(), Self::Error>;
213
214 async fn complete_task(&self, task_id: Uuid, result: Option<&str>) -> Result<(), Self::Error>;
216
217 async fn fail_task(&self, task_id: Uuid, error: &str) -> Result<(), Self::Error>;
219
220 async fn create_download_task(&self, task: &DbDownloadTask) -> Result<(), Self::Error>;
222
223 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 async fn get_download_tasks_by_model(&self, model_id: Uuid) -> Result<Vec<DbDownloadTask>, Self::Error>;
234}
235
236#[async_trait]
238pub trait SessionRepository<DB: Database>: DatabaseRepository<DB> {
239 async fn create_session(&self, session: &DbUserSession) -> Result<(), Self::Error>;
241
242 async fn get_session_by_token(&self, token: &str) -> Result<Option<DbUserSession>, Self::Error>;
244
245 async fn update_session_last_accessed(&self, session_id: Uuid) -> Result<(), Self::Error>;
247
248 async fn delete_session(&self, session_id: Uuid) -> Result<(), Self::Error>;
250
251 async fn cleanup_expired_sessions(&self) -> Result<i64, Self::Error>;
253
254 async fn record_api_usage(&self, usage: &DbApiUsage) -> Result<(), Self::Error>;
256
257 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#[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#[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#[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#[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#[derive(Debug, Clone, Default)]
346pub struct QueryOptions {
347 pub pagination: Pagination,
348 pub filter: QueryFilter,
349 pub sort_by: SortBy,
350}
351
352#[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}