actr-cli 0.1.15

Command line tool for Actor-RTC framework projects
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
//! Unified Error Handling
//!
//! Defines unified error types and handling strategies for the CLI tool

use thiserror::Error;

/// CLI Unified Error Type
#[derive(Debug, Error)]
pub enum ActrCliError {
    #[error("Config error: {message}")]
    Config { message: String },

    #[error("Invalid project: {message}")]
    InvalidProject { message: String },

    #[error("Invalid argument: {message}")]
    InvalidArgument { message: String },

    #[error("Network error: {message}")]
    Network { message: String },

    #[error("Dependency error: {message}")]
    Dependency { message: String },

    #[error("Dependency conflict: {message}")]
    DependencyConflict { message: String },

    #[error("Service not found: {name}")]
    ServiceNotFound { name: String },

    #[error("Service discovery error: {message}")]
    ServiceDiscovery { message: String },

    #[error("Fingerprint validation error: {message}")]
    FingerprintValidation { message: String },

    #[error("Fingerprint mismatch: expected {expected}, got {actual}")]
    FingerprintMismatch { expected: String, actual: String },

    #[error("Compatibility conflict: {message}")]
    CompatibilityConflict { message: String },

    #[error("Code generation error: {message}")]
    CodeGeneration { message: String },

    #[error("Cache error: {message}")]
    Cache { message: String },

    #[error("User interface error: {message}")]
    UserInterface { message: String },

    #[error("Command execution error: {message}")]
    Command { message: String },

    #[error("Validation failed: {details}")]
    ValidationFailed { details: String },

    #[error("Install failed: {reason}")]
    InstallFailed { reason: String },

    #[error("Component not registered: {component}")]
    ComponentNotRegistered { component: String },

    #[error("Operation cancelled")]
    OperationCancelled,

    #[error("IO error")]
    Io(#[from] std::io::Error),

    #[error("Serialization error")]
    Serialization(#[from] toml::de::Error),

    #[error("HTTP error")]
    Http(#[from] reqwest::Error),

    #[error("Other error: {0}")]
    Other(#[from] anyhow::Error),
}

/// Install Error
#[derive(Debug, Error)]
pub enum InstallError {
    #[error("Dependency resolution failed: {dependency}")]
    DependencyResolutionFailed { dependency: String },

    #[error("Service unavailable: {service}")]
    ServiceUnavailable { service: String },

    #[error("Network connection failed")]
    NetworkConnectionFailed,

    #[error("Fingerprint mismatch: {service} - expected: {expected}, actual: {actual}")]
    FingerprintMismatch {
        service: String,
        expected: String,
        actual: String,
    },

    #[error("Version conflict: {details}")]
    VersionConflict { details: String },

    #[error("Cache operation failed: {operation}")]
    CacheOperationFailed { operation: String },

    #[error("Config update failed: {reason}")]
    ConfigUpdateFailed { reason: String },

    #[error("Pre-check failed: {failures:?}")]
    PreCheckFailed { failures: Vec<String> },
}

/// Validation Error
#[derive(Debug, Error)]
pub enum ValidationError {
    #[error("Config file syntax error: {file}")]
    ConfigSyntaxError { file: String },

    #[error("Dependency not found: {dependency}")]
    DependencyNotFound { dependency: String },

    #[error("Network unreachable")]
    NetworkUnreachable,

    #[error("Fingerprint mismatch: {service}")]
    FingerprintMismatch { service: String },

    #[error("Circular dependency: {cycle}")]
    CircularDependency { cycle: String },

    #[error("Insufficient permissions: {resource}")]
    InsufficientPermissions { resource: String },
}

/// User-friendly Error Display
impl ActrCliError {
    /// Get user-friendly error message
    pub fn user_message(&self) -> String {
        match self {
            ActrCliError::Config { message } => {
                format!(
                    "⚠️  Config file error: {message}\n💡 Hint: Check Actr.toml syntax and content"
                )
            }
            ActrCliError::Network { message } => {
                format!(
                    "🌐 Network connection error: {message}\n💡 Hint: Check network connection and service address"
                )
            }
            ActrCliError::Dependency { message } => {
                format!(
                    "📦 Dependency error: {message}\n💡 Hint: Run 'actr check' to check dependencies"
                )
            }
            ActrCliError::ValidationFailed { details } => {
                format!(
                    "❌ Validation failed: {details}\n💡 Hint: Fix the issues above and try again"
                )
            }
            ActrCliError::InstallFailed { reason } => {
                format!(
                    "📥 Install failed: {reason}\n💡 Hint: Run 'actr check' to check environment"
                )
            }
            _ => self.to_string(),
        }
    }

    /// Get possible solutions
    pub fn suggested_actions(&self) -> Vec<String> {
        match self {
            ActrCliError::Config { .. } => vec![
                "Check Actr.toml file syntax".to_string(),
                "Run 'actr config test' to validate config".to_string(),
                "Refer to config examples in documentation".to_string(),
            ],
            ActrCliError::Network { .. } => vec![
                "Check network connection".to_string(),
                "Verify service address is correct".to_string(),
                "Check firewall settings".to_string(),
                "Run 'actr check --verbose' for details".to_string(),
            ],
            ActrCliError::Dependency { .. } => vec![
                "Run 'actr check' to check dependency status".to_string(),
                "Run 'actr install' to install missing dependencies".to_string(),
                "Run 'actr discovery' to find available services".to_string(),
            ],
            ActrCliError::ValidationFailed { .. } => vec![
                "Check and fix reported issues".to_string(),
                "Run 'actr check --verbose' for detailed diagnostics".to_string(),
                "Ensure all dependency services are available".to_string(),
            ],
            ActrCliError::InstallFailed { .. } => vec![
                "Check disk space".to_string(),
                "Check network connection".to_string(),
                "Run 'actr check' to validate environment".to_string(),
                "Try clearing cache and retry".to_string(),
            ],
            _ => vec!["View detailed error information".to_string()],
        }
    }

    /// Get related documentation links
    pub fn documentation_links(&self) -> Vec<(&str, &str)> {
        match self {
            ActrCliError::Config { .. } => vec![
                ("Config Docs", "https://docs.actor-rtc.com/config"),
                (
                    "Actr.toml Reference",
                    "https://docs.actor-rtc.com/actr-toml",
                ),
            ],
            ActrCliError::Dependency { .. } => vec![
                (
                    "Dependency Management",
                    "https://docs.actor-rtc.com/dependencies",
                ),
                (
                    "Troubleshooting",
                    "https://docs.actor-rtc.com/troubleshooting",
                ),
            ],
            _ => vec![("User Guide", "https://docs.actor-rtc.com/guide")],
        }
    }
}

/// Convert validation report to error
impl From<super::components::ValidationReport> for ActrCliError {
    fn from(report: super::components::ValidationReport) -> Self {
        let mut details = Vec::new();

        if !report.config_validation.is_valid {
            details.extend(
                report
                    .config_validation
                    .errors
                    .iter()
                    .map(|e| format!("Config error: {e}")),
            );
        }

        for dep in &report.dependency_validation {
            if !dep.is_available {
                details.push(format!(
                    "Dependency unavailable: {} - {}",
                    dep.dependency,
                    dep.error.as_deref().unwrap_or("unknown error")
                ));
            }
        }

        for net in &report.network_validation {
            if !net.is_reachable {
                details.push(format!(
                    "Network unreachable: {}",
                    net.error.as_deref().unwrap_or("connection failed")
                ));
            }
        }

        for fp in &report.fingerprint_validation {
            if !fp.is_valid {
                details.push(format!(
                    "Fingerprint validation failed: {} - {}",
                    fp.dependency,
                    fp.error.as_deref().unwrap_or("fingerprint mismatch")
                ));
            }
        }

        for conflict in &report.conflicts {
            details.push(format!("Dependency conflict: {}", conflict.description));
        }

        ActrCliError::ValidationFailed {
            details: details.join("; "),
        }
    }
}

/// Error Report Formatter
pub struct ErrorReporter;

impl ErrorReporter {
    /// Format error report
    pub fn format_error(error: &ActrCliError) -> String {
        let mut output = Vec::new();

        // Main error message
        output.push(error.user_message());
        output.push(String::new());

        // Suggested solutions
        let actions = error.suggested_actions();
        if !actions.is_empty() {
            output.push("🔧 Suggested solutions:".to_string());
            for (i, action) in actions.iter().enumerate() {
                output.push(format!("   {}. {}", i + 1, action));
            }
            output.push(String::new());
        }

        // Documentation links
        let docs = error.documentation_links();
        if !docs.is_empty() {
            output.push("📚 Related documentation:".to_string());
            for (title, url) in docs {
                output.push(format!("{title}: {url}"));
            }
            output.push(String::new());
        }

        output.join("\n")
    }

    /// Format validation report
    pub fn format_validation_report(report: &super::components::ValidationReport) -> String {
        let mut output = vec![
            "🔍 Dependency Validation Report".to_string(),
            "=".repeat(50),
            String::new(),
            "📋 Config file validation:".to_string(),
        ];

        // Config validation
        if report.config_validation.is_valid {
            output.push("   ✅ Passed".to_string());
        } else {
            output.push("   ❌ Failed".to_string());
            for error in &report.config_validation.errors {
                output.push(format!("{error}"));
            }
        }
        output.push(String::new());

        // Dependency validation
        output.push("📦 Dependency availability:".to_string());
        for dep in &report.dependency_validation {
            if dep.is_available {
                output.push(format!("{} - available", dep.dependency));
            } else {
                output.push(format!(
                    "{} - {}",
                    dep.dependency,
                    dep.error.as_deref().unwrap_or("unavailable")
                ));
            }
        }
        output.push(String::new());

        // Network validation
        output.push("🌐 Network connectivity:".to_string());
        for net in &report.network_validation {
            if net.is_reachable {
                let latency = net
                    .latency_ms
                    .map(|ms| format!(" ({ms}ms)"))
                    .unwrap_or_default();
                output.push(format!("   ✅ Connected{}", latency));
            } else {
                output.push(format!(
                    "   ❌ Connection failed - {}",
                    net.error.as_deref().unwrap_or("unreachable")
                ));
            }
        }
        output.push(String::new());

        // Fingerprint validation
        if !report.fingerprint_validation.is_empty() {
            output.push("🔐 Fingerprint validation:".to_string());
            for fp in &report.fingerprint_validation {
                if fp.is_valid {
                    output.push(format!("{} - passed", fp.dependency));
                } else {
                    output.push(format!(
                        "{} - {}",
                        fp.dependency,
                        fp.error.as_deref().unwrap_or("validation failed")
                    ));
                }
            }
            output.push(String::new());
        }

        // Conflict report
        if !report.conflicts.is_empty() {
            output.push("⚠️ Dependency conflicts:".to_string());
            for conflict in &report.conflicts {
                output.push(format!(
                    "{} vs {}: {}",
                    conflict.dependency_a, conflict.dependency_b, conflict.description
                ));
            }
            output.push(String::new());
        }

        // Summary
        if report.is_success() {
            output.push("✨ Overall: All validations passed".to_string());
        } else {
            output.push("❌ Overall: Issues need to be resolved".to_string());
        }

        output.join("\n")
    }
}