1use scirs2_core::metrics::{Counter, Gauge, Histogram, MetricsRegistry, Timer};
6use scirs2_core::profiling::Profiler;
7use serde::{Deserialize, Serialize};
8use std::collections::{HashMap, VecDeque};
9use std::sync::Arc;
10use std::time::{Instant, SystemTime, UNIX_EPOCH};
11use tokio::sync::RwLock;
12use tracing::{error, info, warn};
13
14use super::functions::CloudStorageProvider;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18pub enum StorageTier {
19 Hot,
21 Warm,
23 Cold,
25 Archive,
27}
28#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct ElasticScalingConfig {
31 pub min_nodes: u32,
33 pub max_nodes: u32,
35 pub target_cpu_utilization: f64,
37 pub target_memory_utilization: f64,
39 pub scale_up_threshold: f64,
41 pub scale_down_threshold: f64,
43 pub cooldown_seconds: u32,
45 pub use_spot_instances: bool,
47 pub max_spot_ratio: f64,
49 pub instance_types: Vec<InstanceType>,
51 pub provider: CloudProvider,
53}
54#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct CostPrediction {
57 pub predicted_hourly_cost: f64,
59 pub confidence: f64,
61 pub recommended_instance_type: String,
63 pub recommended_spot_ratio: f64,
65 pub estimated_monthly_savings: f64,
67 pub timestamp: u64,
69}
70pub(super) struct GCSClient {
72 #[allow(dead_code)]
73 project: String,
74 #[allow(dead_code)]
75 bucket: String,
76 pub(super) objects: HashMap<String, Vec<u8>>,
77 pub(super) metadata: HashMap<String, ObjectMetadata>,
78}
79#[derive(Debug, Clone, thiserror::Error)]
81pub enum CloudError {
82 #[error("Authentication failed: {0}")]
83 AuthenticationError(String),
84 #[error("Bucket not found: {0}")]
85 BucketNotFound(String),
86 #[error("Object not found: {0}")]
87 ObjectNotFound(String),
88 #[error("Permission denied: {0}")]
89 PermissionDenied(String),
90 #[error("Network error: {0}")]
91 NetworkError(String),
92 #[error("Timeout: {0}")]
93 Timeout(String),
94 #[error("Provider error: {0}")]
95 ProviderError(String),
96 #[error("Configuration error: {0}")]
97 ConfigurationError(String),
98 #[error("Rate limited: {0}")]
99 RateLimited(String),
100}
101pub struct CloudOperationProfiler {
103 #[allow(dead_code)]
104 profiler: Profiler,
105 operation_metrics: Arc<RwLock<HashMap<String, OperationMetrics>>>,
106 #[allow(dead_code)]
107 metric_registry: Arc<MetricsRegistry>,
108}
109impl CloudOperationProfiler {
110 pub fn new() -> Self {
112 Self {
113 profiler: Profiler::new(),
114 operation_metrics: Arc::new(RwLock::new(HashMap::new())),
115 metric_registry: Arc::new(MetricsRegistry::new()),
116 }
117 }
118 pub fn start_operation(&self, _operation: &str) {}
120 pub fn stop_operation(&self, _operation: &str, _bytes: u64, _success: bool) {}
122 pub async fn get_metrics(&self, operation: &str) -> Option<OperationMetrics> {
124 let metrics = self.operation_metrics.read().await;
125 metrics.get(operation).cloned()
126 }
127 pub fn export_prometheus(&self) -> String {
129 "# Cloud operations metrics\n# Registry active".to_string()
130 }
131}
132pub(super) struct GCSMetrics {
134 pub(super) uploads: Counter,
135 pub(super) downloads: Counter,
136 pub(super) errors: Counter,
137}
138#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct StorageOperationResult {
141 pub success: bool,
143 pub duration_ms: u64,
145 pub bytes_transferred: u64,
147 pub error: Option<String>,
149 pub etag: Option<String>,
151}
152#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct S3MetricsSummary {
155 pub total_uploads: u64,
156 pub total_downloads: u64,
157 pub total_upload_bytes: u64,
158 pub total_download_bytes: u64,
159 pub total_errors: u64,
160 pub avg_latency_ms: f64,
161 pub compression_ratio: f64,
162 pub gpu_operations: u64,
163}
164pub struct DisasterRecoveryManager {
166 config: DisasterRecoveryConfig,
167 providers: HashMap<CloudProvider, Arc<dyn CloudStorageProvider>>,
168 current_primary: Arc<RwLock<CloudProvider>>,
169 failure_counts: Arc<RwLock<HashMap<CloudProvider, u32>>>,
170 event_history: Arc<RwLock<VecDeque<(u64, DREvent)>>>,
171 replication_lag: Arc<RwLock<HashMap<CloudProvider, u64>>>,
172}
173impl DisasterRecoveryManager {
174 pub fn new(config: DisasterRecoveryConfig) -> Self {
176 let mut failure_counts = HashMap::new();
177 failure_counts.insert(config.primary_provider, 0);
178 for provider in &config.secondary_providers {
179 failure_counts.insert(*provider, 0);
180 }
181 Self {
182 config: config.clone(),
183 providers: HashMap::new(),
184 current_primary: Arc::new(RwLock::new(config.primary_provider)),
185 failure_counts: Arc::new(RwLock::new(failure_counts)),
186 event_history: Arc::new(RwLock::new(VecDeque::new())),
187 replication_lag: Arc::new(RwLock::new(HashMap::new())),
188 }
189 }
190 pub fn register_provider(
192 &mut self,
193 provider: CloudProvider,
194 backend: Arc<dyn CloudStorageProvider>,
195 ) {
196 self.providers.insert(provider, backend);
197 }
198 pub async fn get_primary(&self) -> CloudProvider {
200 *self.current_primary.read().await
201 }
202 pub async fn health_check_all(&self) -> HashMap<CloudProvider, HealthStatus> {
204 let mut results = HashMap::new();
205 for (provider, backend) in &self.providers {
206 match backend.health_check().await {
207 Ok(status) => {
208 self.record_event(DREvent::HealthCheck {
209 provider: *provider,
210 healthy: status.healthy,
211 latency_ms: status.latency_ms,
212 })
213 .await;
214 let mut counts = self.failure_counts.write().await;
215 if status.healthy {
216 counts.insert(*provider, 0);
217 } else {
218 let count = counts.entry(*provider).or_insert(0);
219 *count += 1;
220 }
221 results.insert(*provider, status);
222 }
223 Err(e) => {
224 let mut counts = self.failure_counts.write().await;
225 let count = counts.entry(*provider).or_insert(0);
226 *count += 1;
227 results.insert(
228 *provider,
229 HealthStatus {
230 healthy: false,
231 latency_ms: 0,
232 error_rate: 1.0,
233 last_check: SystemTime::now()
234 .duration_since(UNIX_EPOCH)
235 .expect("system time should be after UNIX_EPOCH")
236 .as_secs(),
237 message: e.to_string(),
238 },
239 );
240 }
241 }
242 }
243 if self.config.auto_failover_enabled {
244 self.check_and_perform_failover().await;
245 }
246 results
247 }
248 async fn check_and_perform_failover(&self) {
250 let current_primary = *self.current_primary.read().await;
251 let counts = self.failure_counts.read().await;
252 if let Some(&failure_count) = counts.get(¤t_primary) {
253 if failure_count >= self.config.failover_threshold {
254 let mut best_secondary = None;
255 let mut lowest_failures = u32::MAX;
256 for provider in &self.config.secondary_providers {
257 if let Some(&count) = counts.get(provider) {
258 if count < lowest_failures {
259 lowest_failures = count;
260 best_secondary = Some(*provider);
261 }
262 }
263 }
264 if let Some(new_primary) = best_secondary {
265 drop(counts);
266 if let Err(e) = self.perform_failover(new_primary).await {
267 error!("Failover failed: {}", e);
268 }
269 }
270 }
271 }
272 }
273 pub async fn perform_failover(&self, new_primary: CloudProvider) -> Result<(), CloudError> {
275 let old_primary = *self.current_primary.read().await;
276 let start = Instant::now();
277 info!(
278 "Initiating failover from {:?} to {:?}",
279 old_primary, new_primary
280 );
281 self.record_event(DREvent::FailoverInitiated {
282 from: old_primary,
283 to: new_primary,
284 reason: "Primary provider failure threshold exceeded".to_string(),
285 })
286 .await;
287 *self.current_primary.write().await = new_primary;
288 self.failure_counts.write().await.insert(new_primary, 0);
289 let duration = start.elapsed().as_millis() as u64;
290 self.record_event(DREvent::FailoverCompleted {
291 from: old_primary,
292 to: new_primary,
293 duration_ms: duration,
294 })
295 .await;
296 info!(
297 "Failover completed in {}ms. New primary: {:?}",
298 duration, new_primary
299 );
300 Ok(())
301 }
302 pub async fn replicate_to_secondaries(&self, key: &str, data: &[u8]) -> Result<(), CloudError> {
304 let _primary = *self.current_primary.read().await;
305 for provider in &self.config.secondary_providers {
306 if let Some(backend) = self.providers.get(provider) {
307 match backend.upload(key, data, StorageTier::Hot).await {
308 Ok(_) => {
309 info!("Replicated {} to {:?}", key, provider);
310 }
311 Err(e) => {
312 warn!("Failed to replicate {} to {:?}: {}", key, provider, e);
313 }
314 }
315 }
316 }
317 Ok(())
318 }
319 pub async fn get_status(&self) -> DisasterRecoveryStatus {
321 let current_primary = *self.current_primary.read().await;
322 let failure_counts = self.failure_counts.read().await.clone();
323 let replication_lag = self.replication_lag.read().await.clone();
324 let mut provider_status = HashMap::new();
325 for (provider, backend) in &self.providers {
326 if let Ok(health) = backend.health_check().await {
327 provider_status.insert(
328 *provider,
329 ProviderStatus {
330 healthy: health.healthy,
331 latency_ms: health.latency_ms,
332 failure_count: *failure_counts.get(provider).unwrap_or(&0),
333 replication_lag_ms: *replication_lag.get(provider).unwrap_or(&0),
334 },
335 );
336 }
337 }
338 let event_history = self.event_history.read().await;
339 let recent_events: Vec<DREvent> = event_history
340 .iter()
341 .rev()
342 .take(10)
343 .map(|(_, e)| e.clone())
344 .collect();
345 DisasterRecoveryStatus {
346 current_primary,
347 provider_status,
348 rto_seconds: self.config.rto_seconds,
349 rpo_seconds: self.config.rpo_seconds,
350 auto_failover_enabled: self.config.auto_failover_enabled,
351 recent_events,
352 }
353 }
354 async fn record_event(&self, event: DREvent) {
356 let timestamp = SystemTime::now()
357 .duration_since(UNIX_EPOCH)
358 .expect("system time should be after UNIX_EPOCH")
359 .as_secs();
360 let mut history = self.event_history.write().await;
361 history.push_back((timestamp, event));
362 while history.len() > 1000 {
363 history.pop_front();
364 }
365 }
366}
367#[derive(Debug, Clone, Serialize, Deserialize)]
369pub struct ScalingPrediction {
370 pub timestamp: u64,
372 pub horizon_minutes: u32,
374 pub predicted_cpu: f64,
376 pub predicted_memory: f64,
378 pub predicted_nodes_needed: u32,
380 pub confidence: f64,
382 pub trend: Trend,
384}
385#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
387pub enum Trend {
388 Increasing,
389 Decreasing,
390 Stable,
391}
392#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct MLCostRecommendation {
395 pub action: String,
397 pub predicted_savings: f64,
399 pub confidence: f64,
401 pub impact: String,
403 pub ml_based: bool,
405 pub description: String,
407}
408#[derive(Debug, Clone, Serialize, Deserialize)]
410pub struct DisasterRecoveryStatus {
411 pub current_primary: CloudProvider,
413 pub provider_status: HashMap<CloudProvider, ProviderStatus>,
415 pub rto_seconds: u32,
417 pub rpo_seconds: u32,
419 pub auto_failover_enabled: bool,
421 pub recent_events: Vec<DREvent>,
423}
424#[derive(Debug, Clone, Serialize, Deserialize)]
426pub struct ObjectMetadata {
427 pub key: String,
429 pub size: u64,
431 pub last_modified: u64,
433 pub content_type: String,
435 pub storage_tier: StorageTier,
437 pub etag: String,
439 pub custom_metadata: HashMap<String, String>,
441}
442pub struct GCSBackend {
444 #[allow(dead_code)]
445 config: CloudStorageConfig,
446 pub(super) client: Arc<RwLock<GCSClient>>,
447 pub(super) metrics: Arc<GCSMetrics>,
448}
449impl GCSBackend {
450 pub fn new(config: CloudStorageConfig) -> Self {
452 let client = GCSClient {
453 project: config.access_key.clone(),
454 bucket: config.bucket.clone(),
455 objects: HashMap::new(),
456 metadata: HashMap::new(),
457 };
458 let metrics = GCSMetrics {
459 uploads: Counter::new("gcs_uploads_total".to_string()),
460 downloads: Counter::new("gcs_downloads_total".to_string()),
461 errors: Counter::new("gcs_errors_total".to_string()),
462 };
463 Self {
464 config,
465 client: Arc::new(RwLock::new(client)),
466 metrics: Arc::new(metrics),
467 }
468 }
469}
470#[derive(Debug, Clone, Serialize, Deserialize)]
472pub struct DisasterRecoveryConfig {
473 pub primary_provider: CloudProvider,
475 pub secondary_providers: Vec<CloudProvider>,
477 pub rto_seconds: u32,
479 pub rpo_seconds: u32,
481 pub auto_failover_enabled: bool,
483 pub health_check_interval_secs: u32,
485 pub failover_threshold: u32,
487 pub continuous_replication: bool,
489 pub replication_batch_size: usize,
491}
492pub struct AzureBlobBackend {
494 #[allow(dead_code)]
495 config: CloudStorageConfig,
496 pub(super) client: Arc<RwLock<AzureClient>>,
497 pub(super) metrics: Arc<AzureMetrics>,
498}
499impl AzureBlobBackend {
500 pub fn new(config: CloudStorageConfig) -> Self {
502 let client = AzureClient {
503 account: config.access_key.clone(),
504 container: config.bucket.clone(),
505 objects: HashMap::new(),
506 metadata: HashMap::new(),
507 };
508 let metrics = AzureMetrics {
509 uploads: Counter::new("azure_uploads_total".to_string()),
510 downloads: Counter::new("azure_downloads_total".to_string()),
511 errors: Counter::new("azure_errors_total".to_string()),
512 };
513 Self {
514 config,
515 client: Arc::new(RwLock::new(client)),
516 metrics: Arc::new(metrics),
517 }
518 }
519}
520#[derive(Debug, Clone, Serialize, Deserialize)]
522pub struct ProviderStatus {
523 pub healthy: bool,
525 pub latency_ms: u64,
527 pub failure_count: u32,
529 pub replication_lag_ms: u64,
531}
532#[derive(Debug, Clone, Serialize, Deserialize)]
534pub struct LifecycleRule {
535 pub id: String,
537 pub prefix: Option<String>,
539 pub transition_days: u32,
541 pub target_tier: StorageTier,
543 pub expiration_days: u32,
545}
546pub struct S3Metrics {
548 pub uploads: Counter,
549 pub downloads: Counter,
550 pub upload_bytes: Counter,
551 pub download_bytes: Counter,
552 pub errors: Counter,
553 pub latency_sum: Gauge,
554 #[allow(dead_code)]
555 latency_histogram: Histogram,
556 #[allow(dead_code)]
557 operation_timer: Timer,
558 pub compression_ratio: Gauge,
559 pub gpu_acceleration_count: Counter,
560}
561#[derive(Debug, Clone)]
563pub struct OperationMetrics {
564 pub operation_name: String,
565 pub total_count: u64,
566 pub success_count: u64,
567 pub failure_count: u64,
568 pub total_bytes: u64,
569 pub total_duration_ms: u64,
570 pub avg_latency_ms: f64,
571 pub p95_latency_ms: f64,
572 pub p99_latency_ms: f64,
573 pub compression_ratio: f64,
574 pub gpu_accelerated: bool,
575}
576#[derive(Debug, Clone, Serialize, Deserialize)]
578pub enum ScalingDecision {
579 ScaleUp {
581 count: u32,
582 instance_type: String,
583 use_spot: bool,
584 reason: String,
585 },
586 ScaleDown {
588 count: u32,
589 instance_ids: Vec<String>,
590 reason: String,
591 },
592 NoAction { reason: String },
594}
595#[derive(Debug, Clone, Serialize, Deserialize)]
597pub struct ClusterMetrics {
598 pub timestamp: u64,
600 pub avg_cpu_utilization: f64,
602 pub avg_memory_utilization: f64,
604 pub queries_per_second: f64,
606 pub node_count: u32,
608 pub error_rate: f64,
610}
611#[derive(Debug, Clone, Serialize, Deserialize)]
613pub struct CostOptimization {
614 pub current_hourly_cost: f64,
616 pub current_monthly_cost: f64,
618 pub on_demand_count: u32,
620 pub spot_count: u32,
622 pub potential_monthly_savings: f64,
624 pub recommendations: Vec<CostRecommendation>,
626}
627#[derive(Debug, Clone, Serialize, Deserialize)]
629pub struct ElasticScalingStatus {
630 pub current_node_count: u32,
632 pub min_nodes: u32,
634 pub max_nodes: u32,
636 pub spot_count: u32,
638 pub on_demand_count: u32,
640 pub target_cpu: f64,
642 pub target_memory: f64,
644 pub cooldown_seconds: u32,
646 pub recent_events: Vec<ScalingEvent>,
648}
649pub struct MLCostOptimizer {
652 training_data: Arc<RwLock<Vec<CostTrainingData>>>,
653}
654impl MLCostOptimizer {
655 pub fn new() -> Self {
657 Self {
658 training_data: Arc::new(RwLock::new(Vec::new())),
659 }
660 }
661 pub async fn add_training_data(&self, data: CostTrainingData) {
663 let mut training = self.training_data.write().await;
664 training.push(data);
665 if training.len() > 10000 {
666 training.drain(0..1000);
667 }
668 }
669 pub async fn train_model(&mut self) -> Result<(), CloudError> {
671 let training_data = self.training_data.read().await;
672 if training_data.len() < 100 {
673 return Err(CloudError::ConfigurationError(
674 "Insufficient training data".to_string(),
675 ));
676 }
677 info!(
678 "Training ML cost model with {} samples",
679 training_data.len()
680 );
681 Ok(())
682 }
683 pub async fn predict_cost(
685 &self,
686 current_metrics: &ClusterMetrics,
687 current_config: &ElasticScalingConfig,
688 ) -> CostPrediction {
689 let training_data = self.training_data.read().await;
690 let similar_points: Vec<&CostTrainingData> = training_data
691 .iter()
692 .filter(|d| {
693 (d.cpu_utilization - current_metrics.avg_cpu_utilization).abs() < 0.2
694 && (d.memory_utilization - current_metrics.avg_memory_utilization).abs() < 0.2
695 })
696 .collect();
697 let (predicted_cost, confidence) = if !similar_points.is_empty() {
698 let avg_cost = similar_points.iter().map(|p| p.actual_cost).sum::<f64>()
699 / similar_points.len() as f64;
700 let variance = similar_points
701 .iter()
702 .map(|p| (p.actual_cost - avg_cost).powi(2))
703 .sum::<f64>()
704 / similar_points.len() as f64;
705 let confidence = (1.0 - variance.sqrt() / avg_cost).max(0.0).min(1.0);
706 (avg_cost, confidence)
707 } else {
708 (0.10, 0.3)
709 };
710 let recommended_instance_type = if current_metrics.avg_cpu_utilization > 0.7 {
711 "large".to_string()
712 } else if current_metrics.avg_cpu_utilization > 0.4 {
713 "medium".to_string()
714 } else {
715 "small".to_string()
716 };
717 let recommended_spot_ratio = if confidence > 0.7 {
718 current_config.max_spot_ratio
719 } else {
720 current_config.max_spot_ratio * 0.7
721 };
722 let current_cost = predicted_cost * current_metrics.node_count as f64;
723 let spot_savings = current_cost * recommended_spot_ratio * 0.7;
724 let estimated_monthly_savings = spot_savings * 24.0 * 30.0;
725 CostPrediction {
726 predicted_hourly_cost: predicted_cost,
727 confidence,
728 recommended_instance_type,
729 recommended_spot_ratio,
730 estimated_monthly_savings,
731 timestamp: SystemTime::now()
732 .duration_since(UNIX_EPOCH)
733 .expect("system time should be after UNIX_EPOCH")
734 .as_secs(),
735 }
736 }
737 pub async fn get_recommendations(
739 &self,
740 current_status: &ElasticScalingStatus,
741 cost_optimization: &CostOptimization,
742 ) -> Vec<MLCostRecommendation> {
743 let mut recommendations = Vec::new();
744 if current_status.spot_count < current_status.current_node_count / 2 {
745 recommendations.push(MLCostRecommendation {
746 action: "Increase spot instance usage".to_string(),
747 predicted_savings: cost_optimization.potential_monthly_savings * 0.6,
748 confidence: 0.85,
749 impact: "Medium".to_string(),
750 ml_based: true,
751 description: "ML model predicts stable workload suitable for spot instances"
752 .to_string(),
753 });
754 }
755 let training_data = self.training_data.read().await;
756 if !training_data.is_empty() {
757 let recent_avg_cpu = training_data
758 .iter()
759 .rev()
760 .take(100)
761 .map(|d| d.cpu_utilization)
762 .sum::<f64>()
763 / 100.0;
764 if recent_avg_cpu < 0.3 {
765 recommendations.push(MLCostRecommendation {
766 action: "Downsize instance types".to_string(),
767 predicted_savings: cost_optimization.current_monthly_cost * 0.3,
768 confidence: 0.90,
769 impact: "High".to_string(),
770 ml_based: true,
771 description: "ML analysis shows consistent low utilization".to_string(),
772 });
773 }
774 }
775 if training_data.len() > 1000 {
776 recommendations.push(MLCostRecommendation {
777 action: "Implement time-based scaling".to_string(),
778 predicted_savings: cost_optimization.current_monthly_cost * 0.15,
779 confidence: 0.75,
780 impact: "Medium".to_string(),
781 ml_based: true,
782 description: "ML detected workload patterns suitable for scheduled scaling"
783 .to_string(),
784 });
785 }
786 recommendations
787 }
788}
789#[derive(Debug, Clone, Serialize, Deserialize)]
791pub struct NodeInstance {
792 pub instance_id: String,
794 pub node_id: u64,
796 pub instance_type: String,
798 pub is_spot: bool,
800 pub launch_time: u64,
802 pub cpu_utilization: f64,
804 pub memory_utilization: f64,
806 pub provider: CloudProvider,
808 pub region: String,
810}
811pub struct GpuCompressor {
813 enabled: bool,
814}
815impl GpuCompressor {
816 pub fn new() -> Self {
818 Self { enabled: false }
819 }
820 pub async fn compress(&mut self, data: &[u8]) -> Result<Vec<u8>, CloudError> {
822 self.cpu_compress(data)
823 }
824 pub async fn decompress(&mut self, data: &[u8]) -> Result<Vec<u8>, CloudError> {
826 self.cpu_decompress(data)
827 }
828 fn cpu_compress(&self, data: &[u8]) -> Result<Vec<u8>, CloudError> {
830 oxiarc_zstd::encode_all(data, 3)
831 .map_err(|e| CloudError::ProviderError(format!("Compression failed: {}", e)))
832 }
833 fn cpu_decompress(&self, data: &[u8]) -> Result<Vec<u8>, CloudError> {
835 oxiarc_zstd::decode_all(data)
836 .map_err(|e| CloudError::ProviderError(format!("Decompression failed: {}", e)))
837 }
838 pub fn is_gpu_enabled(&self) -> bool {
840 self.enabled
841 }
842}
843pub(super) struct AzureMetrics {
845 pub(super) uploads: Counter,
846 pub(super) downloads: Counter,
847 pub(super) errors: Counter,
848}
849#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
851pub enum CloudProvider {
852 AWS,
854 GCP,
856 Azure,
858 OnPremises,
860}
861#[derive(Debug, Clone, Serialize, Deserialize)]
863pub struct HealthStatus {
864 pub healthy: bool,
866 pub latency_ms: u64,
868 pub error_rate: f64,
870 pub last_check: u64,
872 pub message: String,
874}
875#[derive(Debug, Clone, Serialize, Deserialize)]
877pub struct CostRecommendation {
878 pub action: String,
880 pub estimated_savings: f64,
882 pub risk_level: String,
884 pub description: String,
886}
887#[derive(Debug, Clone, Serialize, Deserialize)]
889pub enum DREvent {
890 HealthCheck {
892 provider: CloudProvider,
893 healthy: bool,
894 latency_ms: u64,
895 },
896 FailoverInitiated {
898 from: CloudProvider,
899 to: CloudProvider,
900 reason: String,
901 },
902 FailoverCompleted {
904 from: CloudProvider,
905 to: CloudProvider,
906 duration_ms: u64,
907 },
908 ReplicationCompleted {
910 source: CloudProvider,
911 target: CloudProvider,
912 objects: usize,
913 bytes: u64,
914 },
915 RecoveryStarted { provider: CloudProvider },
917 RecoveryCompleted {
919 provider: CloudProvider,
920 duration_ms: u64,
921 },
922}
923pub struct S3Backend {
925 #[allow(dead_code)]
926 config: CloudStorageConfig,
927 pub(super) client: Arc<RwLock<S3Client>>,
928 pub(super) metrics: Arc<S3Metrics>,
929}
930impl S3Backend {
931 pub fn new(config: CloudStorageConfig) -> Self {
933 let client = S3Client {
934 endpoint: config
935 .endpoint
936 .clone()
937 .unwrap_or_else(|| format!("https://s3.{}.amazonaws.com", config.region)),
938 region: config.region.clone(),
939 bucket: config.bucket.clone(),
940 objects: HashMap::new(),
941 metadata: HashMap::new(),
942 };
943 let metrics = S3Metrics {
944 uploads: Counter::new("s3_uploads_total".to_string()),
945 downloads: Counter::new("s3_downloads_total".to_string()),
946 upload_bytes: Counter::new("s3_upload_bytes_total".to_string()),
947 download_bytes: Counter::new("s3_download_bytes_total".to_string()),
948 errors: Counter::new("s3_errors_total".to_string()),
949 latency_sum: Gauge::new("s3_latency_sum_ms".to_string()),
950 latency_histogram: Histogram::new("s3_latency_ms".to_string()),
951 operation_timer: Timer::new("s3_operations".to_string()),
952 compression_ratio: Gauge::new("s3_compression_ratio".to_string()),
953 gpu_acceleration_count: Counter::new("s3_gpu_operations_total".to_string()),
954 };
955 Self {
956 config,
957 client: Arc::new(RwLock::new(client)),
958 metrics: Arc::new(metrics),
959 }
960 }
961 pub fn get_metrics(&self) -> &S3Metrics {
963 &self.metrics
964 }
965 pub fn get_metrics_summary(&self) -> S3MetricsSummary {
967 S3MetricsSummary {
968 total_uploads: self.metrics.uploads.get(),
969 total_downloads: self.metrics.downloads.get(),
970 total_upload_bytes: self.metrics.upload_bytes.get(),
971 total_download_bytes: self.metrics.download_bytes.get(),
972 total_errors: self.metrics.errors.get(),
973 avg_latency_ms: self.metrics.latency_sum.get(),
974 compression_ratio: self.metrics.compression_ratio.get(),
975 gpu_operations: self.metrics.gpu_acceleration_count.get(),
976 }
977 }
978}
979pub(super) struct AzureClient {
981 #[allow(dead_code)]
982 account: String,
983 #[allow(dead_code)]
984 container: String,
985 pub(super) objects: HashMap<String, Vec<u8>>,
986 pub(super) metadata: HashMap<String, ObjectMetadata>,
987}
988#[derive(Debug, Clone, Serialize, Deserialize)]
990pub struct ScalingEvent {
991 pub timestamp: u64,
993 pub decision: ScalingDecision,
995 pub success: bool,
997 pub duration_ms: u64,
999 pub error: Option<String>,
1001}
1002pub(super) struct S3Client {
1004 #[allow(dead_code)]
1005 endpoint: String,
1006 #[allow(dead_code)]
1007 region: String,
1008 #[allow(dead_code)]
1009 bucket: String,
1010 pub(super) objects: HashMap<String, Vec<u8>>,
1011 pub(super) metadata: HashMap<String, ObjectMetadata>,
1012}
1013#[derive(Debug, Clone, Serialize, Deserialize)]
1015pub struct CloudStorageConfig {
1016 pub provider: CloudProvider,
1018 pub region: String,
1020 pub bucket: String,
1022 pub access_key: String,
1024 pub secret_key: String,
1026 pub endpoint: Option<String>,
1028 pub default_tier: StorageTier,
1030 pub encryption_enabled: bool,
1032 pub versioning_enabled: bool,
1034 pub lifecycle_rules: Vec<LifecycleRule>,
1036}
1037#[derive(Debug, Clone, Serialize, Deserialize)]
1039pub struct InstanceType {
1040 pub name: String,
1042 pub vcpus: u32,
1044 pub memory_gb: u32,
1046 pub hourly_cost: f64,
1048 pub spot_hourly_cost: f64,
1050}
1051#[derive(Debug, Clone, Serialize, Deserialize)]
1053pub struct CostTrainingData {
1054 pub instance_type: String,
1056 pub cpu_utilization: f64,
1058 pub memory_utilization: f64,
1060 pub queries_per_second: f64,
1062 pub actual_cost: f64,
1064 pub is_spot: bool,
1066 pub timestamp: u64,
1068}