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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! Enhanced error system for VoiRS SDK.
//!
//! This module provides a comprehensive error management system with:
//! - Detailed error types with contextual information
//! - Automatic error recovery strategies
//! - Error reporting and diagnostics
//! - Performance impact analysis
//!
//! # Architecture
//!
//! The error system is organized into three main components:
//!
//! - [`types`] - Core error types and definitions
//! - [`recovery`] - Error recovery strategies and circuit breakers
//! - [`reporting`] - Error logging, metrics, and diagnostics
//!
//! # Quick Start
//!
//! ```no_run
//! use voirs_sdk::error::{VoirsError, ErrorReporter, ErrorRecoveryManager};
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create error recovery manager
//! let mut recovery_manager = ErrorRecoveryManager::default();
//!
//! // Create error reporter
//! let mut reporter = ErrorReporter::default();
//!
//! // Report an error
//! let error = VoirsError::SynthesisFailed {
//!     text: "Hello world".to_string(),
//!     text_length: 11,
//!     stage: voirs_sdk::error::SynthesisStage::TextPreprocessing,
//!     cause: Box::new(std::io::Error::new(std::io::ErrorKind::Other, "test")),
//! };
//! reporter.report_error(&error, Some("synthesis"));
//!
//! // Execute operation with recovery
//! let result = recovery_manager.execute_with_recovery("synthesis", || {
//!     Box::pin(async {
//!         // Your operation here
//!         Ok(())
//!     })
//! }).await;
//! # Ok(())
//! # }
//! ```
//!
//! # Error Context
//!
//! Errors can be enhanced with additional context:
//!
//! ```no_run
//! use voirs_sdk::error::{VoirsError, ErrorWithContext};
//!
//! let error = VoirsError::device_error("cuda", "Out of memory");
//! let error_with_context = error.with_context("synthesis", "generate_audio");
//! ```
//!
//! # Recovery Strategies
//!
//! Different recovery strategies can be configured for different components:
//!
//! ```no_run
//! use voirs_sdk::error::{ErrorRecoveryManager, RecoveryStrategy};
//! use std::time::Duration;
//!
//! let mut manager = ErrorRecoveryManager::new();
//!
//! // Configure exponential backoff for network operations
//! manager.register_strategy("network", RecoveryStrategy::RetryExponential {
//!     max_attempts: 5,
//!     initial_delay: Duration::from_millis(100),
//!     max_delay: Duration::from_secs(10),
//!     multiplier: 2.0,
//! });
//!
//! // Configure circuit breaker for device operations
//! manager.register_circuit_breaker("device", Default::default());
//! ```
//!
//! # Error Reporting
//!
//! Comprehensive error reporting with diagnostics:
//!
//! ```no_run
//! use voirs_sdk::error::{ErrorReporter, ErrorReporterConfig, ConsoleErrorListener};
//!
//! let config = ErrorReporterConfig {
//!     collect_stack_traces: true,
//!     collect_system_context: true,
//!     auto_report_critical: true,
//!     ..Default::default()
//! };
//!
//! let mut reporter = ErrorReporter::new(config);
//! reporter.add_listener(ConsoleErrorListener);
//!
//! // Generate diagnostic report
//! let diagnostic = reporter.generate_diagnostic_report();
//! println!("System health score: {:.2}", diagnostic.system_health.overall_score);
//! ```

pub mod recovery;
pub mod reporting;
pub mod types;

// Re-export main types for convenience
pub use types::{
    AudioBufferErrorType, AudioBufferInfo, ContextResult, ErrorContext, ErrorSeverity,
    ErrorWithContext, IoOperation, ModelType, QualityMetrics, Result, SynthesisStage, VoirsError,
};

pub use recovery::{
    CircuitBreaker, CircuitBreakerConfig, CircuitBreakerError, CircuitState, ErrorRecoveryManager,
    RecoveryContext, RecoveryStrategy,
};

pub use reporting::{
    ConsoleErrorListener, DiagnosticReport, ErrorCategory, ErrorListener, ErrorReport,
    ErrorReporter, ErrorReporterConfig, ErrorStatistics, FileErrorListener, PerformanceImpact,
    RuntimeInfo, SystemContext, SystemHealth,
};

/// Global error reporter instance
static GLOBAL_ERROR_REPORTER: std::sync::OnceLock<ErrorReporter> = std::sync::OnceLock::new();

/// Initialize global error reporter
pub fn init_global_error_reporter(config: ErrorReporterConfig) {
    let _ = GLOBAL_ERROR_REPORTER.set(ErrorReporter::new(config));
}

/// Get global error reporter
pub fn get_global_error_reporter() -> Option<&'static ErrorReporter> {
    GLOBAL_ERROR_REPORTER.get()
}

/// Report error using global reporter
pub fn report_global_error(error: &VoirsError, context: Option<&str>) {
    if let Some(reporter) = get_global_error_reporter() {
        reporter.report_error(error, context);
    }
}

/// Convenience macro for creating VoirsError instances
#[macro_export]
macro_rules! voirs_error {
    // Synthesis error
    (synthesis_failed: $text:expr, $cause:expr) => {
        $crate::error::VoirsError::synthesis_failed($text, $cause)
    };

    // Device error
    (device_error: $device:expr, $message:expr) => {
        $crate::error::VoirsError::device_error($device, $message)
    };

    // Config error
    (config_error: $message:expr) => {
        $crate::error::VoirsError::config_error($message)
    };

    // Model error
    (model_error: $message:expr) => {
        $crate::error::VoirsError::model_error($message)
    };

    // Audio error
    (audio_error: $message:expr) => {
        $crate::error::VoirsError::audio_error($message)
    };

    // G2P error
    (g2p_error: $message:expr) => {
        $crate::error::VoirsError::g2p_error($message)
    };

    // Timeout error
    (timeout: $message:expr) => {
        $crate::error::VoirsError::timeout($message)
    };

    // Internal error
    (internal: $component:expr, $message:expr) => {
        $crate::error::VoirsError::InternalError {
            component: $component.to_string(),
            message: $message.to_string(),
        }
    };
}

/// Convenience macro for error recovery
#[macro_export]
macro_rules! with_recovery {
    ($manager:expr, $component:expr, $operation:expr) => {
        $manager
            .execute_with_recovery($component, || Box::pin(async move { $operation }))
            .await
    };
}

/// Convenience macro for error reporting
#[macro_export]
macro_rules! report_error {
    ($error:expr) => {
        $crate::error::report_global_error(&$error, None);
    };
    ($error:expr, $context:expr) => {
        $crate::error::report_global_error(&$error, Some($context));
    };
}

/// Extension trait for Result types to add error reporting
pub trait ResultExt<T> {
    /// Report error if Result is Err, then return the Result unchanged
    fn report_on_error(self, context: Option<&str>) -> Self;

    /// Report error and convert to a different error type
    fn report_and_convert<E, F>(self, context: Option<&str>, f: F) -> std::result::Result<T, E>
    where
        F: FnOnce(VoirsError) -> E;

    /// Add error context
    #[allow(clippy::result_large_err)]
    fn with_error_context(
        self,
        component: impl Into<String>,
        operation: impl Into<String>,
    ) -> ContextResult<T>;
}

impl<T> ResultExt<T> for Result<T> {
    fn report_on_error(self, context: Option<&str>) -> Self {
        if let Err(ref error) = self {
            report_global_error(error, context);
        }
        self
    }

    fn report_and_convert<E, F>(self, context: Option<&str>, f: F) -> std::result::Result<T, E>
    where
        F: FnOnce(VoirsError) -> E,
    {
        match self {
            Ok(value) => Ok(value),
            Err(error) => {
                report_global_error(&error, context);
                Err(f(error))
            }
        }
    }

    fn with_error_context(
        self,
        component: impl Into<String>,
        operation: impl Into<String>,
    ) -> ContextResult<T> {
        match self {
            Ok(value) => Ok(value),
            Err(error) => Err(error.with_context(component, operation)),
        }
    }
}

/// Extension trait for VoirsError to add common helper methods
pub trait VoirsErrorExt {
    /// Check if error indicates a permanent failure
    fn is_permanent(&self) -> bool;

    /// Check if error indicates a temporary failure
    fn is_temporary(&self) -> bool;

    /// Check if error is related to user input
    fn is_user_error(&self) -> bool;

    /// Check if error is related to system resources
    fn is_resource_error(&self) -> bool;

    /// Get recommended wait time before retry
    fn recommended_retry_delay(&self) -> Option<std::time::Duration>;
}

impl VoirsErrorExt for VoirsError {
    fn is_permanent(&self) -> bool {
        matches!(
            self,
            VoirsError::UnsupportedDevice { .. }
                | VoirsError::ModelNotFound { .. }
                | VoirsError::FileCorrupted { .. }
                | VoirsError::LanguageNotSupported { .. }
                | VoirsError::NotImplemented { .. }
        )
    }

    fn is_temporary(&self) -> bool {
        !self.is_permanent() && self.is_recoverable()
    }

    fn is_user_error(&self) -> bool {
        matches!(
            self,
            VoirsError::VoiceNotFound { .. }
                | VoirsError::InvalidConfiguration { .. }
                | VoirsError::ConfigError { .. }
        )
    }

    fn is_resource_error(&self) -> bool {
        matches!(
            self,
            VoirsError::OutOfMemory { .. }
                | VoirsError::GpuOutOfMemory { .. }
                | VoirsError::ResourceExhausted { .. }
        )
    }

    fn recommended_retry_delay(&self) -> Option<std::time::Duration> {
        use std::time::Duration;

        if !self.is_recoverable() {
            return None;
        }

        Some(match self {
            VoirsError::NetworkError { .. } => Duration::from_secs(1),
            VoirsError::TimeoutError { .. } => Duration::from_millis(500),
            VoirsError::DeviceError { .. } => Duration::from_millis(100),
            VoirsError::ModelError { .. } => Duration::from_secs(2),
            VoirsError::OutOfMemory { .. } => Duration::from_secs(5),
            _ => Duration::from_millis(200),
        })
    }
}

/// Implement From traits for common error conversions
impl From<std::io::Error> for VoirsError {
    fn from(err: std::io::Error) -> Self {
        Self::IoError {
            path: std::path::PathBuf::from("unknown"),
            operation: IoOperation::Read,
            source: err,
        }
    }
}

/// Legacy constructor helper - allows old code to work unchanged
impl VoirsError {
    /// Legacy InvalidConfiguration constructor
    pub fn invalid_configuration_legacy(field: String, value: String, reason: String) -> Self {
        Self::InvalidConfiguration {
            field,
            value,
            reason,
            valid_values: None,
        }
    }

    /// Legacy DeviceNotAvailable constructor
    pub fn device_not_available_legacy(device: String) -> Self {
        Self::DeviceNotAvailable {
            device,
            alternatives: Vec::new(),
        }
    }

    /// Legacy VoiceNotFound constructor
    pub fn voice_not_found_legacy(voice: String, available: Vec<String>) -> Self {
        Self::VoiceNotFound {
            voice,
            available: available.clone(),
            suggestions: available.into_iter().take(3).collect(),
        }
    }
}

impl From<serde_json::Error> for VoirsError {
    fn from(err: serde_json::Error) -> Self {
        Self::SerializationError {
            format: "JSON".to_string(),
            message: err.to_string(),
        }
    }
}

impl From<toml::de::Error> for VoirsError {
    fn from(err: toml::de::Error) -> Self {
        Self::SerializationError {
            format: "TOML".to_string(),
            message: err.to_string(),
        }
    }
}

impl From<toml::ser::Error> for VoirsError {
    fn from(err: toml::ser::Error) -> Self {
        Self::SerializationError {
            format: "TOML".to_string(),
            message: err.to_string(),
        }
    }
}

impl From<hf_hub::api::sync::ApiError> for VoirsError {
    fn from(err: hf_hub::api::sync::ApiError) -> Self {
        Self::NetworkError {
            message: format!("HuggingFace Hub API error: {err}"),
            retry_count: 0,
            max_retries: 3,
            source: Some(Box::new(err)),
        }
    }
}

impl From<voirs_acoustic::AcousticError> for VoirsError {
    fn from(err: voirs_acoustic::AcousticError) -> Self {
        Self::SynthesisFailed {
            text: "unknown".to_string(),
            text_length: 0,
            stage: SynthesisStage::AcousticModeling,
            cause: Box::new(err),
        }
    }
}

impl From<voirs_vocoder::VocoderError> for VoirsError {
    fn from(err: voirs_vocoder::VocoderError) -> Self {
        Self::SynthesisFailed {
            text: "unknown".to_string(),
            text_length: 0,
            stage: SynthesisStage::Vocoding,
            cause: Box::new(err),
        }
    }
}

impl From<voirs_g2p::G2pError> for VoirsError {
    fn from(err: voirs_g2p::G2pError) -> Self {
        Self::SynthesisFailed {
            text: "unknown".to_string(),
            text_length: 0,
            stage: SynthesisStage::G2pConversion,
            cause: Box::new(err),
        }
    }
}

/// Compatibility wrapper to maintain backward compatibility with old error type
impl VoirsError {
    /// Create a new synthesis error (legacy API)
    pub fn synthesis_failed(
        text: impl Into<String>,
        cause: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        let text = text.into();
        Self::SynthesisFailed {
            text_length: text.len(),
            text,
            stage: SynthesisStage::TextPreprocessing,
            cause: Box::new(cause),
        }
    }

    /// Create a new device error (legacy API)
    pub fn device_error(device: impl Into<String>, message: impl Into<String>) -> Self {
        Self::DeviceError {
            device: device.into(),
            message: message.into(),
            recovery_hint: None,
        }
    }

    /// Create a new configuration error (legacy API)
    pub fn config_error(message: impl Into<String>) -> Self {
        Self::ConfigError {
            field: "unknown".to_string(),
            message: message.into(),
        }
    }

    /// Create a new model error (legacy API)
    pub fn model_error(message: impl Into<String>) -> Self {
        Self::ModelError {
            model_type: ModelType::Acoustic,
            message: message.into(),
            source: None,
        }
    }

    /// Create a new audio error (legacy API)
    pub fn audio_error(message: impl Into<String>) -> Self {
        Self::AudioError {
            message: message.into(),
            buffer_info: None,
        }
    }

    /// Create a new plugin error (legacy API)
    pub fn plugin_error(message: impl Into<String>) -> Self {
        Self::ConfigError {
            field: "plugin".to_string(),
            message: message.into(),
        }
    }

    /// Create a new G2P error (legacy API)
    pub fn g2p_error(message: impl Into<String>) -> Self {
        Self::G2pError {
            text: "unknown".to_string(),
            message: message.into(),
            language: None,
        }
    }

    /// Create a new cache error (legacy API)
    pub fn cache_error(message: impl Into<String>) -> Self {
        Self::ConfigError {
            field: "cache".to_string(),
            message: message.into(),
        }
    }

    /// Create a new timeout error (legacy API)
    pub fn timeout(_message: impl Into<String>) -> Self {
        Self::TimeoutError {
            operation: "unknown".to_string(),
            duration: std::time::Duration::from_secs(30),
            expected_duration: None,
        }
    }

    /// Create voice not found error with automatic suggestions
    pub fn voice_not_found(voice: impl Into<String>, available: Vec<String>) -> Self {
        let voice_str = voice.into();
        let suggestions = available
            .iter()
            .filter(|v| v.contains(&voice_str) || voice_str.contains(*v))
            .take(3)
            .cloned()
            .collect();

        Self::VoiceNotFound {
            voice: voice_str,
            available,
            suggestions,
        }
    }

    /// Create invalid configuration error
    pub fn invalid_config(
        field: impl Into<String>,
        value: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self::InvalidConfiguration {
            field: field.into(),
            value: value.into(),
            reason: reason.into(),
            valid_values: None,
        }
    }

    /// Create invalid configuration error with valid values
    pub fn invalid_config_with_values(
        field: impl Into<String>,
        value: impl Into<String>,
        reason: impl Into<String>,
        valid_values: Vec<String>,
    ) -> Self {
        Self::InvalidConfiguration {
            field: field.into(),
            value: value.into(),
            reason: reason.into(),
            valid_values: Some(valid_values),
        }
    }

    /// Create internal error
    pub fn internal(component: impl Into<String>, message: impl Into<String>) -> Self {
        Self::InternalError {
            component: component.into(),
            message: message.into(),
        }
    }

    /// Create serialization error
    pub fn serialization(format: impl Into<String>, message: impl Into<String>) -> Self {
        Self::SerializationError {
            format: format.into(),
            message: message.into(),
        }
    }

    /// Create I/O error
    pub fn io_error(
        path: impl Into<std::path::PathBuf>,
        operation: IoOperation,
        source: std::io::Error,
    ) -> Self {
        Self::IoError {
            path: path.into(),
            operation,
            source,
        }
    }

    /// Create model error with type
    pub fn model_error_typed(model_type: ModelType, message: impl Into<String>) -> Self {
        Self::ModelError {
            model_type,
            message: message.into(),
            source: None,
        }
    }

    /// Create invalid argument error (alias for config error)
    pub fn invalid_argument(message: impl Into<String>) -> Self {
        Self::config_error(message)
    }

    /// Create cancellation error
    pub fn cancelled(message: impl Into<String>) -> Self {
        Self::config_error(format!("Operation cancelled: {}", message.into()))
    }
}

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

    #[test]
    fn test_error_macros() {
        let error = voirs_error!(config_error: "Test error");
        assert!(matches!(error, VoirsError::ConfigError { .. }));

        let error = voirs_error!(internal: "test_component", "Test message");
        assert!(matches!(error, VoirsError::InternalError { .. }));
    }

    #[test]
    fn test_error_extensions() {
        let error = VoirsError::NetworkError {
            message: "Connection failed".to_string(),
            retry_count: 1,
            max_retries: 3,
            source: None,
        };

        assert!(error.is_temporary());
        assert!(!error.is_permanent());
        assert!(!error.is_user_error());
        assert!(error.recommended_retry_delay().is_some());
    }

    #[test]
    fn test_result_extensions() {
        let result: Result<i32> = Err(VoirsError::InternalError {
            component: "test".to_string(),
            message: "test error".to_string(),
        });

        let context_result = result.with_error_context("test_component", "test_operation");
        assert!(context_result.is_err());

        if let Err(error_with_context) = context_result {
            assert_eq!(error_with_context.context.component, "test_component");
            assert_eq!(error_with_context.context.operation, "test_operation");
        }
    }

    #[tokio::test]
    async fn test_integration() {
        // Initialize global error reporter
        init_global_error_reporter(ErrorReporterConfig::default());

        // Create recovery manager
        let manager = ErrorRecoveryManager::default();

        // Test operation with recovery
        let result: Result<()> = manager
            .execute_with_recovery(
                "test",
                || -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
                    Box::pin(async {
                        Err(VoirsError::InternalError {
                            component: "test".to_string(),
                            message: "test error".to_string(),
                        })
                    })
                },
            )
            .await;

        assert!(result.is_err());

        // Check that error was reported
        if let Some(reporter) = get_global_error_reporter() {
            let _stats = reporter.get_statistics();
            // Note: The error might not be reported due to severity filtering
        }
    }
}