cloud_disk_sync/core/
traits.rs

1use crate::config::{AccountConfig, EncryptionConfig, SyncTask};
2use crate::core::audit::{AuditFilter, AuditOperation};
3use crate::core::health::{ConnectivityStatus, HealthStatus, StorageHealth};
4use crate::core::resources::{DiskHandle, MemoryHandle, ResourceLimits, ResourceUsage};
5use crate::core::scheduler::ScheduledTask;
6use crate::error::{Result, SyncError};
7use crate::plugins::hooks::PluginHook;
8use crate::report::SyncReport;
9use async_trait::async_trait;
10use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13/// 状态管理 trait
14pub trait StateManager: Send + Sync {
15    fn save_state(&self, key: &str, value: &[u8]) -> Result<()>;
16    fn load_state(&self, key: &str) -> Result<Option<Vec<u8>>>;
17    fn delete_state(&self, key: &str) -> Result<()>;
18    fn list_states(&self, prefix: &str) -> Result<Vec<String>>;
19}
20
21/// 进度报告 trait
22pub trait ProgressReporter: Send + Sync {
23    fn report_start(&self, total_size: u64, total_files: usize);
24    fn report_progress(&self, current_size: u64, current_file: &str);
25    fn report_file_complete(&self, file: &str, size: u64, duration: Duration);
26    fn report_error(&self, file: &str, error: &SyncError);
27    fn report_complete(&self, stats: &TransferStats);
28}
29
30/// 重试策略 trait
31pub trait RetryStrategy: Send + Sync {
32    fn should_retry(&self, attempt: u32, error: &SyncError) -> bool;
33    fn delay_before_retry(&self, attempt: u32) -> Duration;
34    fn max_attempts(&self) -> u32;
35}
36
37/// 流控策略 trait
38#[async_trait]
39pub trait RateLimiter: Send + Sync {
40    async fn acquire<'a>(&'a self) -> Result<()>
41    where
42        Self: 'a;
43
44    fn current_rate(&self) -> f64; // 请求/秒
45    fn set_rate(&mut self, requests_per_second: f64);
46    fn try_acquire(&self) -> bool;
47}
48
49/// 校验和计算 trait
50pub trait ChecksumCalculator: Send + Sync {
51    fn calculate_file_checksum(&self, path: &Path) -> Result<String>;
52    fn calculate_data_checksum(&self, data: &[u8]) -> String;
53    fn verify_checksum(&self, path: &Path, expected: &str) -> Result<bool>;
54}
55
56/// 文件差异检测 trait
57pub trait DiffDetector: Send + Sync {
58    fn detect_changes(
59        &self,
60        source_files: &[FileMetadata],
61        target_files: &[FileMetadata],
62        options: &DiffOptions,
63    ) -> Result<Vec<FileChange>>;
64
65    fn calculate_diff_size(&self, changes: &[FileChange]) -> u64;
66}
67
68/// 文件过滤器 trait
69pub trait FileFilter: Send + Sync {
70    fn should_include(&self, file: &FileMetadata) -> bool;
71    fn filter_files(&self, files: &[FileMetadata]) -> Vec<FileMetadata>;
72}
73
74/// 任务调度器 trait
75#[async_trait]
76pub trait TaskScheduler: Send + Sync {
77    async fn schedule(&self, task: ScheduledTask) -> Result<String>;
78    async fn cancel(&self, task_id: &str) -> Result<()>;
79    async fn list_scheduled(&self) -> Result<Vec<ScheduledTask>>;
80    async fn trigger_now(&self, task_id: &str) -> Result<()>;
81}
82
83/// 通知器 trait
84pub trait Notifier: Send + Sync {
85    fn notify_success(&self, report: &SyncReport);
86    fn notify_error(&self, error: &SyncError);
87    fn notify_warning(&self, warning: &str);
88    fn notify_progress(&self, progress: &ProgressUpdate);
89}
90
91/// 审计记录器 trait
92pub trait AuditLogger: Send + Sync {
93    fn log_operation(&self, operation: AuditOperation);
94    fn query_operations(
95        &self,
96        filter: AuditFilter,
97        limit: Option<usize>,
98    ) -> Result<Vec<AuditOperation>>;
99}
100
101/// 配置验证器 trait
102pub trait ConfigValidator: Send + Sync {
103    fn validate_account(&self, account: &AccountConfig) -> Result<()>;
104    fn validate_task(&self, task: &SyncTask) -> Result<()>;
105    fn validate_encryption(&self, config: &EncryptionConfig) -> Result<()>;
106}
107
108/// 健康检查 trait
109#[async_trait]
110pub trait HealthChecker: Send + Sync {
111    async fn check_provider_health(&self, provider_id: &str) -> Result<HealthStatus>;
112    async fn check_storage_health(&self) -> Result<StorageHealth>;
113    async fn check_connectivity(&self) -> Result<ConnectivityStatus>;
114}
115
116/// 资源管理 trait
117pub trait ResourceManager: Send + Sync {
118    fn allocate_memory(&self, size: usize) -> Result<MemoryHandle>;
119    fn allocate_disk(&self, size: u64) -> Result<DiskHandle>;
120    fn current_usage(&self) -> ResourceUsage;
121    fn set_limits(&self, limits: ResourceLimits);
122}
123
124/// 插件系统 trait
125#[async_trait]
126pub trait Plugin: Send + Sync {
127    fn name(&self) -> &str;
128    fn version(&self) -> &str;
129    fn description(&self) -> &str;
130
131    async fn initialize(&self) -> Result<()>;
132    async fn shutdown(&self) -> Result<()>;
133
134    fn hooks(&self) -> Vec<PluginHook>;
135}
136
137/// 钩子处理器 trait
138#[async_trait]
139pub trait HookHandler: Send + Sync {
140    async fn on_before_sync(&self, task: &SyncTask) -> Result<()>;
141    async fn on_after_sync(&self, task: &SyncTask, report: &SyncReport) -> Result<()>;
142    async fn on_file_uploading(&self, file: &FileMetadata) -> Result<()>;
143    async fn on_file_uploaded(&self, file: &FileMetadata) -> Result<()>;
144    async fn on_error(&self, error: &SyncError) -> Result<()>;
145}
146
147// 数据传输统计
148#[derive(Debug, Clone)]
149pub struct TransferStats {
150    pub total_files: usize,
151    pub successful_files: usize,
152    pub failed_files: usize,
153    pub skipped_files: usize,
154    pub total_bytes: u64,
155    pub transferred_bytes: u64,
156    pub average_speed: f64, // bytes/second
157    pub total_duration: Duration,
158    pub start_time: chrono::DateTime<chrono::Utc>,
159    pub end_time: chrono::DateTime<chrono::Utc>,
160}
161
162// 文件元数据
163#[derive(Debug, Clone)]
164pub struct FileMetadata {
165    pub path: PathBuf,
166    pub size: u64,
167    pub modified: i64,
168    pub created: i64,
169    pub accessed: i64,
170    pub checksum: Option<String>,
171    pub permissions: u32,
172    pub is_dir: bool,
173    pub is_symlink: bool,
174}
175
176// 文件变化
177#[derive(Debug, Clone)]
178pub enum FileChange {
179    Added(FileMetadata),
180    Modified {
181        old: FileMetadata,
182        new: FileMetadata,
183    },
184    Deleted(FileMetadata),
185    Moved {
186        from: FileMetadata,
187        to: FileMetadata,
188    },
189    Unchanged(FileMetadata),
190}
191
192// 差异检测选项
193#[derive(Debug, Clone)]
194pub struct DiffOptions {
195    pub compare_size: bool,
196    pub compare_mtime: bool,
197    pub compare_checksum: bool,
198    pub ignore_patterns: Vec<String>,
199    pub max_depth: Option<usize>,
200    pub follow_symlinks: bool,
201}
202
203// 进度更新
204#[derive(Debug, Clone)]
205pub struct ProgressUpdate {
206    pub current_file: String,
207    pub current_size: u64,
208    pub total_size: u64,
209    pub current_file_index: usize,
210    pub total_files: usize,
211    pub speed: f64, // bytes/second
212    pub elapsed: Duration,
213    pub estimated_remaining: Duration,
214}