voirs-sdk 0.1.0-rc.1

Unified SDK and public API for VoiRS speech synthesis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
pub mod distributed;
pub mod storage;
pub mod telemetry;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;

use crate::{Result, VoirsError};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloudConfig {
    pub provider: CloudProvider,
    pub region: String,
    pub credentials: CloudCredentials,
    pub storage_config: StorageConfig,
    pub processing_config: ProcessingConfig,
    pub telemetry_config: TelemetryConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CloudProvider {
    AWS,
    Azure,
    GCP,
    Custom(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloudCredentials {
    pub access_key: String,
    pub secret_key: String,
    pub token: Option<String>,
    pub endpoint: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    pub bucket_name: String,
    pub encryption: bool,
    pub compression: bool,
    pub backup_retention_days: u32,
    pub sync_interval_minutes: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessingConfig {
    pub max_concurrent_jobs: u32,
    pub timeout_seconds: u32,
    pub retry_count: u32,
    pub load_balancing: LoadBalancingStrategy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LoadBalancingStrategy {
    RoundRobin,
    LeastConnections,
    LatencyBased,
    ResourceBased,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TelemetryConfig {
    pub enabled: bool,
    pub sampling_rate: f32,
    pub batch_size: u32,
    pub flush_interval_seconds: u32,
    pub endpoints: Vec<String>,
}

pub struct CloudManager {
    config: Arc<RwLock<CloudConfig>>,
    storage: Arc<dyn CloudStorage>,
    processing: Arc<dyn DistributedProcessing>,
    telemetry: Arc<dyn TelemetryProvider>,
}

#[async_trait::async_trait]
pub trait CloudStorage: Send + Sync {
    async fn upload_model(&self, model_id: &str, data: &[u8]) -> Result<String>;
    async fn download_model(&self, model_id: &str) -> Result<Vec<u8>>;
    async fn list_models(&self) -> Result<Vec<ModelMetadata>>;
    async fn delete_model(&self, model_id: &str) -> Result<()>;
    async fn sync_models(&self) -> Result<SyncReport>;
    async fn create_backup(&self, backup_id: &str) -> Result<BackupInfo>;
    async fn restore_backup(&self, backup_id: &str) -> Result<()>;
}

#[async_trait::async_trait]
pub trait DistributedProcessing: Send + Sync {
    async fn submit_job(&self, job: ProcessingJob) -> Result<JobHandle>;
    async fn get_job_status(&self, job_id: &str) -> Result<JobStatus>;
    async fn cancel_job(&self, job_id: &str) -> Result<()>;
    async fn get_worker_stats(&self) -> Result<Vec<WorkerStats>>;
    async fn scale_workers(&self, target_count: u32) -> Result<()>;
}

#[async_trait::async_trait]
pub trait TelemetryProvider: Send + Sync {
    async fn record_event(&self, event: TelemetryEvent) -> Result<()>;
    async fn record_metric(&self, metric: Metric) -> Result<()>;
    async fn flush(&self) -> Result<()>;
    async fn get_analytics(&self, query: AnalyticsQuery) -> Result<AnalyticsResult>;
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelMetadata {
    pub id: String,
    pub name: String,
    pub version: String,
    pub size_bytes: u64,
    pub checksum: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub tags: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncReport {
    pub models_synced: u32,
    pub models_updated: u32,
    pub models_deleted: u32,
    pub sync_duration: chrono::Duration,
    pub errors: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupInfo {
    pub id: String,
    pub name: String,
    pub size_bytes: u64,
    pub created_at: DateTime<Utc>,
    pub models_count: u32,
    pub checksum: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessingJob {
    pub id: String,
    pub job_type: JobType,
    pub input_data: Vec<u8>,
    pub parameters: HashMap<String, serde_json::Value>,
    pub priority: JobPriority,
    pub requirements: ResourceRequirements,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum JobType {
    Synthesis,
    Training,
    Evaluation,
    Recognition,
    Custom(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum JobPriority {
    Low,
    Normal,
    High,
    Critical,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceRequirements {
    pub cpu_cores: u32,
    pub memory_mb: u32,
    pub gpu_required: bool,
    pub gpu_memory_mb: Option<u32>,
    pub max_execution_time: chrono::Duration,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobHandle {
    pub id: String,
    pub status: JobStatus,
    pub created_at: DateTime<Utc>,
    pub estimated_completion: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum JobStatus {
    Queued,
    Running,
    Completed,
    Failed(String),
    Cancelled,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerStats {
    pub id: String,
    pub status: WorkerStatus,
    pub current_jobs: u32,
    pub completed_jobs: u32,
    pub failed_jobs: u32,
    pub cpu_usage: f32,
    pub memory_usage: f32,
    pub gpu_usage: Option<f32>,
    pub last_heartbeat: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WorkerStatus {
    Idle,
    Busy,
    Offline,
    Provisioning,
    Draining,
    Error(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryEvent {
    pub id: String,
    pub event_type: String,
    pub timestamp: DateTime<Utc>,
    pub user_id: Option<String>,
    pub session_id: Option<String>,
    pub properties: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metric {
    pub name: String,
    pub value: f64,
    pub unit: String,
    pub timestamp: DateTime<Utc>,
    pub tags: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsQuery {
    pub metric_name: String,
    pub start_time: DateTime<Utc>,
    pub end_time: DateTime<Utc>,
    pub aggregation: AggregationType,
    pub filters: HashMap<String, String>,
    pub group_by: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AggregationType {
    Sum,
    Average,
    Count,
    Min,
    Max,
    Percentile(f32),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsResult {
    pub data_points: Vec<DataPoint>,
    pub summary: AnalyticsSummary,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataPoint {
    pub timestamp: DateTime<Utc>,
    pub value: f64,
    pub dimensions: HashMap<String, String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsSummary {
    pub total_points: u32,
    pub min_value: f64,
    pub max_value: f64,
    pub average_value: f64,
    pub sum_value: f64,
}

impl CloudManager {
    pub fn new(
        config: CloudConfig,
        storage: Arc<dyn CloudStorage>,
        processing: Arc<dyn DistributedProcessing>,
        telemetry: Arc<dyn TelemetryProvider>,
    ) -> Self {
        Self {
            config: Arc::new(RwLock::new(config)),
            storage,
            processing,
            telemetry,
        }
    }

    pub async fn get_config(&self) -> CloudConfig {
        self.config.read().await.clone()
    }

    pub async fn update_config(&self, config: CloudConfig) -> Result<()> {
        let mut current_config = self.config.write().await;
        *current_config = config;
        Ok(())
    }

    pub fn storage(&self) -> &Arc<dyn CloudStorage> {
        &self.storage
    }

    pub fn processing(&self) -> &Arc<dyn DistributedProcessing> {
        &self.processing
    }

    pub fn telemetry(&self) -> &Arc<dyn TelemetryProvider> {
        &self.telemetry
    }

    pub async fn health_check(&self) -> Result<CloudHealthStatus> {
        let storage_healthy = self.check_storage_health().await?;
        let processing_healthy = self.check_processing_health().await?;
        let telemetry_healthy = self.check_telemetry_health().await?;

        Ok(CloudHealthStatus {
            overall: storage_healthy && processing_healthy && telemetry_healthy,
            storage: storage_healthy,
            processing: processing_healthy,
            telemetry: telemetry_healthy,
            last_check: Utc::now(),
        })
    }

    async fn check_storage_health(&self) -> Result<bool> {
        // Try to list models to check storage connectivity
        match self.storage.list_models().await {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    async fn check_processing_health(&self) -> Result<bool> {
        // Check worker stats to verify processing cluster health
        match self.processing.get_worker_stats().await {
            Ok(stats) => Ok(!stats.is_empty()),
            Err(_) => Ok(false),
        }
    }

    async fn check_telemetry_health(&self) -> Result<bool> {
        // Try to flush telemetry to check connectivity
        match self.telemetry.flush().await {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloudHealthStatus {
    pub overall: bool,
    pub storage: bool,
    pub processing: bool,
    pub telemetry: bool,
    pub last_check: DateTime<Utc>,
}

impl Default for CloudConfig {
    fn default() -> Self {
        Self {
            provider: CloudProvider::AWS,
            region: "us-east-1".to_string(),
            credentials: CloudCredentials {
                access_key: "".to_string(),
                secret_key: "".to_string(),
                token: None,
                endpoint: None,
            },
            storage_config: StorageConfig {
                bucket_name: "voirs-models".to_string(),
                encryption: true,
                compression: true,
                backup_retention_days: 30,
                sync_interval_minutes: 60,
            },
            processing_config: ProcessingConfig {
                max_concurrent_jobs: 10,
                timeout_seconds: 3600,
                retry_count: 3,
                load_balancing: LoadBalancingStrategy::LeastConnections,
            },
            telemetry_config: TelemetryConfig {
                enabled: true,
                sampling_rate: 1.0,
                batch_size: 100,
                flush_interval_seconds: 60,
                endpoints: vec!["https://api.voirs.dev/telemetry".to_string()],
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cloud_config_default() {
        let config = CloudConfig::default();
        assert!(matches!(config.provider, CloudProvider::AWS));
        assert_eq!(config.region, "us-east-1");
        assert!(config.storage_config.encryption);
        assert!(config.telemetry_config.enabled);
    }

    #[test]
    fn test_cloud_config_serialization() {
        let config = CloudConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: CloudConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config.region, deserialized.region);
    }

    #[test]
    fn test_job_priority_ordering() {
        let priorities = vec![
            JobPriority::Low,
            JobPriority::Normal,
            JobPriority::High,
            JobPriority::Critical,
        ];

        // Test that different priorities exist
        assert_eq!(priorities.len(), 4);
    }

    #[test]
    fn test_load_balancing_strategies() {
        let strategies = vec![
            LoadBalancingStrategy::RoundRobin,
            LoadBalancingStrategy::LeastConnections,
            LoadBalancingStrategy::LatencyBased,
            LoadBalancingStrategy::ResourceBased,
        ];

        // Test that all strategies are available
        assert_eq!(strategies.len(), 4);
    }
}