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
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
//! 核心复用组件定义
//!
//! 定义了8个核心组件的trait接口,支持依赖注入和组合使用

pub mod cache_manager;
pub mod config_manager;
pub mod dependency_resolver;
pub mod fingerprint_validator;
pub mod network_validator;
pub mod proto_processor;
pub mod service_discovery;
pub mod user_interface;
use actr_protocol::{ActrType, discovery_response::TypeEntry};
pub use cache_manager::DefaultCacheManager;
pub use config_manager::TomlConfigManager;
pub use dependency_resolver::DefaultDependencyResolver;
pub use fingerprint_validator::DefaultFingerprintValidator;
pub use network_validator::DefaultNetworkValidator;
pub use proto_processor::DefaultProtoProcessor;
pub use service_discovery::NetworkServiceDiscovery;
pub use user_interface::ConsoleUI;

use actr_config::Config;
use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;

// ============================================================================
// 核心数据类型
// ============================================================================

/// 依赖规范
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DependencySpec {
    pub alias: String,
    pub name: String,
    pub actr_type: Option<ActrType>,
    pub fingerprint: Option<String>,
}

/// 解析后的依赖信息
#[derive(Debug, Clone)]
pub struct ResolvedDependency {
    pub spec: DependencySpec,
    pub fingerprint: String,
    pub proto_files: Vec<ProtoFile>,
}

/// Proto文件信息
#[derive(Debug, Clone)]
pub struct ProtoFile {
    pub name: String,
    pub path: PathBuf,
    pub content: String,
    pub services: Vec<ServiceDefinition>,
}

/// 服务定义
#[derive(Debug, Clone)]
pub struct ServiceDefinition {
    pub name: String,
    pub methods: Vec<MethodDefinition>,
}

/// 方法定义
#[derive(Debug, Clone)]
pub struct MethodDefinition {
    pub name: String,
    pub input_type: String,
    pub output_type: String,
}

/// 服务信息
#[derive(Debug, Clone)]
pub struct ServiceInfo {
    /// Service name (package name)
    pub name: String,
    pub tags: Vec<String>,
    pub fingerprint: String,
    pub actr_type: ActrType,
    pub published_at: Option<i64>,
    pub description: Option<String>,
    pub methods: Vec<MethodDefinition>,
}

/// 服务详情
#[derive(Debug, Clone)]
pub struct ServiceDetails {
    pub info: ServiceInfo,
    pub proto_files: Vec<ProtoFile>,
    pub dependencies: Vec<String>,
}

/// 指纹信息
#[derive(Debug, Clone, PartialEq)]
pub struct Fingerprint {
    pub algorithm: String,
    pub value: String,
}

/// 验证报告
#[derive(Debug, Clone)]
pub struct ValidationReport {
    pub is_valid: bool,
    pub config_validation: ConfigValidation,
    pub dependency_validation: Vec<DependencyValidation>,
    pub network_validation: Vec<NetworkValidation>,
    pub fingerprint_validation: Vec<FingerprintValidation>,
    pub conflicts: Vec<ConflictReport>,
}

#[derive(Debug, Clone)]
pub struct ConfigValidation {
    pub is_valid: bool,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct DependencyValidation {
    pub dependency: String,
    pub is_available: bool,
    pub error: Option<String>,
}

#[derive(Debug, Clone)]
pub struct NetworkValidation {
    pub is_reachable: bool,
    pub health: HealthStatus,
    pub latency_ms: Option<u64>,
    pub error: Option<String>,
    pub is_applicable: bool,
}

#[derive(Debug, Clone)]
pub struct FingerprintValidation {
    pub dependency: String,
    pub expected: Fingerprint,
    pub actual: Option<Fingerprint>,
    pub is_valid: bool,
    pub error: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ConflictReport {
    pub dependency_a: String,
    pub dependency_b: String,
    pub conflict_type: ConflictType,
    pub description: String,
}

#[derive(Debug, Clone)]
pub enum ConflictType {
    VersionConflict,
    FingerprintMismatch,
    CircularDependency,
}

impl ValidationReport {
    pub fn is_success(&self) -> bool {
        self.is_valid
            && self.config_validation.is_valid
            && self.dependency_validation.iter().all(|d| d.is_available)
            && self
                .network_validation
                .iter()
                .all(|n| !n.is_applicable || n.is_reachable)
            && self.fingerprint_validation.iter().all(|f| f.is_valid)
            && self.conflicts.is_empty()
    }
}

// ============================================================================
// 1. 配置管理组件 (ConfigManager)
// ============================================================================

/// 统一的配置管理接口
#[async_trait]
pub trait ConfigManager: Send + Sync {
    /// 加载配置文件
    async fn load_config(&self, path: &Path) -> Result<Config>;

    /// 保存配置文件
    async fn save_config(&self, config: &Config, path: &Path) -> Result<()>;

    /// 更新依赖配置
    async fn update_dependency(&self, spec: &DependencySpec) -> Result<()>;

    /// 验证配置文件
    async fn validate_config(&self) -> Result<ConfigValidation>;

    /// 获取项目根目录
    fn get_project_root(&self) -> &Path;

    /// 备份当前配置
    async fn backup_config(&self) -> Result<ConfigBackup>;

    /// 恢复配置备份
    async fn restore_backup(&self, backup: ConfigBackup) -> Result<()>;

    /// 删除配置备份
    async fn remove_backup(&self, backup: ConfigBackup) -> Result<()>;
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageConfig {
    pub name: String,
    pub version: String,
    #[serde(rename = "type")]
    pub package_type: Option<String>,
}

/// 配置备份
#[derive(Debug, Clone)]
pub struct ConfigBackup {
    pub original_path: PathBuf,
    pub backup_path: PathBuf,
    pub timestamp: std::time::SystemTime,
}

// ============================================================================
// 2. 依赖解析组件 (DependencyResolver)
// ============================================================================

/// 依赖解析和冲突检测
#[async_trait]
pub trait DependencyResolver: Send + Sync {
    /// Parse dependencies from config
    async fn resolve_spec(&self, config: &Config) -> Result<Vec<DependencySpec>>;

    /// 解析依赖并获取 proto 文件
    async fn resolve_dependencies(
        &self,
        specs: &[DependencySpec],
        service_details: &[ServiceDetails],
    ) -> Result<Vec<ResolvedDependency>>;

    /// 检查依赖冲突
    async fn check_conflicts(&self, deps: &[ResolvedDependency]) -> Result<Vec<ConflictReport>>;

    /// 构建依赖图
    async fn build_dependency_graph(&self, deps: &[ResolvedDependency]) -> Result<DependencyGraph>;
}

#[derive(Debug, Clone)]
pub struct DependencyGraph {
    pub nodes: Vec<String>,
    pub edges: Vec<(String, String)>,
    pub has_cycles: bool,
}

// ============================================================================
// 3. 服务发现组件 (ServiceDiscovery)
// ============================================================================

/// 服务发现和网络交互
#[async_trait]
pub trait ServiceDiscovery: Send + Sync {
    /// 发现网络中的服务
    async fn discover_services(&self, filter: Option<&ServiceFilter>) -> Result<Vec<ServiceInfo>>;

    /// 获取服务详细信息
    async fn get_service_details(&self, name: &str) -> Result<ServiceDetails>;

    /// 检查服务可用性
    async fn check_service_availability(&self, name: &str) -> Result<AvailabilityStatus>;

    /// 获取服务Proto文件
    async fn get_service_proto(&self, name: &str) -> Result<Vec<ProtoFile>>;
}

#[derive(Debug, Clone)]
pub struct ServiceFilter {
    pub name_pattern: Option<String>,
    pub version_range: Option<String>,
    pub tags: Option<Vec<String>>,
}

#[derive(Debug, Clone)]
pub struct AvailabilityStatus {
    pub is_available: bool,
    pub last_seen: Option<std::time::SystemTime>,
    pub health: HealthStatus,
}

#[derive(Debug, Clone)]
pub enum HealthStatus {
    Healthy,
    Degraded,
    Unhealthy,
    Unknown,
}

// ============================================================================
// 4. 网络验证组件 (NetworkValidator)
// ============================================================================

/// 网络连通性验证
#[async_trait]
pub trait NetworkValidator: Send + Sync {
    /// 检查连通性
    async fn check_connectivity(
        &self,
        service_name: &str,
        options: &NetworkCheckOptions,
    ) -> Result<ConnectivityStatus>;

    /// 验证服务健康状态
    async fn verify_service_health(
        &self,
        service_name: &str,
        options: &NetworkCheckOptions,
    ) -> Result<HealthStatus>;

    /// 测试延迟
    async fn test_latency(
        &self,
        service_name: &str,
        options: &NetworkCheckOptions,
    ) -> Result<LatencyInfo>;

    /// 批量检查
    async fn batch_check(
        &self,
        service_names: &[String],
        options: &NetworkCheckOptions,
    ) -> Result<Vec<NetworkCheckResult>>;
}

#[derive(Debug, Clone)]
pub struct ConnectivityStatus {
    pub is_reachable: bool,
    pub response_time_ms: Option<u64>,
    pub error: Option<String>,
}

#[derive(Debug, Clone)]
pub struct LatencyInfo {
    pub min_ms: u64,
    pub max_ms: u64,
    pub avg_ms: u64,
    pub samples: u32,
}

#[derive(Debug, Clone)]
pub struct NetworkCheckResult {
    pub connectivity: ConnectivityStatus,
    pub health: HealthStatus,
    pub latency: Option<LatencyInfo>,
}

/// Options for network checks.
#[derive(Debug, Clone)]
pub struct NetworkCheckOptions {
    pub timeout: Duration,
}

impl NetworkCheckOptions {
    pub fn with_timeout(timeout: Duration) -> Self {
        Self { timeout }
    }

    pub fn with_timeout_secs(timeout_secs: u64) -> Self {
        Self::with_timeout(Duration::from_secs(timeout_secs))
    }
}

impl Default for NetworkCheckOptions {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(5),
        }
    }
}

// ============================================================================
// 5. 指纹验证组件 (FingerprintValidator)
// ============================================================================

/// 指纹计算和验证
#[async_trait]
pub trait FingerprintValidator: Send + Sync {
    /// 计算服务指纹
    async fn compute_service_fingerprint(&self, service: &ServiceInfo) -> Result<Fingerprint>;

    /// 验证指纹匹配
    async fn verify_fingerprint(
        &self,
        expected: &Fingerprint,
        actual: &Fingerprint,
    ) -> Result<bool>;

    /// 计算项目指纹
    async fn compute_project_fingerprint(&self, project_path: &Path) -> Result<Fingerprint>;

    /// 生成锁文件指纹
    async fn generate_lock_fingerprint(&self, deps: &[ResolvedDependency]) -> Result<Fingerprint>;
}

// ============================================================================
// 6. Proto处理组件 (ProtoProcessor)
// ============================================================================

/// Protocol Buffers 文件处理
#[async_trait]
pub trait ProtoProcessor: Send + Sync {
    /// 发现Proto文件
    async fn discover_proto_files(&self, path: &Path) -> Result<Vec<ProtoFile>>;

    /// 解析Proto服务
    async fn parse_proto_services(&self, files: &[ProtoFile]) -> Result<Vec<ServiceDefinition>>;

    /// 生成代码
    async fn generate_code(&self, input: &Path, output: &Path) -> Result<GenerationResult>;

    /// 验证Proto语法
    async fn validate_proto_syntax(&self, files: &[ProtoFile]) -> Result<ValidationReport>;
}

#[derive(Debug, Clone)]
pub struct GenerationResult {
    pub generated_files: Vec<PathBuf>,
    pub warnings: Vec<String>,
    pub errors: Vec<String>,
}

// ============================================================================
// 7. 缓存管理组件 (CacheManager)
// ============================================================================

/// 依赖缓存管理
#[async_trait]
pub trait CacheManager: Send + Sync {
    /// 获取缓存的Proto
    async fn get_cached_proto(&self, service_name: &str) -> Result<Option<CachedProto>>;

    /// 缓存Proto文件
    async fn cache_proto(&self, service_name: &str, proto: &[ProtoFile]) -> Result<()>;

    /// 失效缓存
    async fn invalidate_cache(&self, service_name: &str) -> Result<()>;

    /// 清理缓存
    async fn clear_cache(&self) -> Result<()>;

    /// 获取缓存统计
    async fn get_cache_stats(&self) -> Result<CacheStats>;
}

#[derive(Debug, Clone)]
pub struct CachedProto {
    pub files: Vec<ProtoFile>,
    pub fingerprint: Fingerprint,
    pub cached_at: std::time::SystemTime,
    pub expires_at: Option<std::time::SystemTime>,
}

#[derive(Debug, Clone)]
pub struct CacheStats {
    pub total_entries: usize,
    pub total_size_bytes: u64,
    pub hit_rate: f64,
    pub miss_rate: f64,
}

// ============================================================================
// 8. 用户交互组件 (UserInterface)
// ============================================================================

/// 用户交互界面
#[async_trait]
pub trait UserInterface: Send + Sync {
    /// 提示输入
    async fn prompt_input(&self, prompt: &str) -> Result<String>;

    /// 确认操作
    async fn confirm(&self, message: &str) -> Result<bool>;

    /// 从列表中选择一项
    async fn select_from_list(&self, items: &[String], prompt: &str) -> Result<usize>;

    /// 显示服务表格
    async fn display_service_table(
        &self,
        items: &[ServiceInfo],
        headers: &[&str],
        formatter: fn(&ServiceInfo) -> Vec<String>,
    );

    /// 显示进度条
    async fn show_progress(&self, message: &str) -> Result<Box<dyn ProgressBar>>;
}

/// 进度条接口
pub trait ProgressBar: Send + Sync {
    fn update(&self, progress: f64);
    fn set_message(&self, message: &str);
    fn finish(&self);
}

impl From<TypeEntry> for ServiceInfo {
    fn from(entry: TypeEntry) -> Self {
        let name = entry.name.clone();
        let tags = entry.tags.clone();
        let actr_type = entry.actr_type.clone();

        Self {
            name,
            actr_type,
            tags,
            published_at: entry.published_at,
            fingerprint: entry.service_fingerprint,
            description: entry.description,
            methods: Vec::new(),
        }
    }
}