Skip to main content

trustformers_mobile/network_adaptation/
config.rs

1//! Configuration management for network adaptation parameters.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// Network adaptation configuration
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct NetworkAdaptationConfig {
9    /// Enable network condition monitoring
10    pub enable_monitoring: bool,
11    /// Network monitoring interval (ms)
12    pub monitoring_interval_ms: u64,
13    /// Enable adaptive scheduling
14    pub enable_adaptive_scheduling: bool,
15    /// Enable bandwidth optimization
16    pub enable_bandwidth_optimization: bool,
17    /// Network quality thresholds
18    pub quality_thresholds: NetworkQualityThresholds,
19    /// Communication strategy settings
20    pub communication_strategy: CommunicationStrategy,
21    /// Data usage limits
22    pub data_usage_limits: DataUsageLimits,
23    /// Sync frequency settings
24    pub sync_frequency: SyncFrequencyConfig,
25    /// Failure recovery settings
26    pub failure_recovery: FailureRecoveryConfig,
27    /// Network prediction settings
28    pub prediction_config: NetworkPredictionConfig,
29}
30
31/// Network quality thresholds for different actions
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct NetworkQualityThresholds {
34    /// Minimum bandwidth for full sync (Mbps)
35    pub min_bandwidth_full_sync_mbps: f32,
36    /// Minimum bandwidth for incremental sync (Mbps)
37    pub min_bandwidth_incremental_sync_mbps: f32,
38    /// Maximum latency for real-time updates (ms)
39    pub max_latency_realtime_ms: f32,
40    /// Maximum packet loss for reliable sync (%)
41    pub max_packet_loss_percent: f32,
42    /// Signal strength threshold (dBm)
43    pub min_signal_strength_dbm: i32,
44    /// Jitter tolerance (ms)
45    pub max_jitter_ms: f32,
46}
47
48/// Communication strategy for different network conditions
49#[derive(Debug, Clone, Serialize, Deserialize, Default)]
50pub struct CommunicationStrategy {
51    /// Strategy for WiFi networks
52    pub wifi_strategy: WiFiStrategy,
53    /// Strategy for cellular networks
54    pub cellular_strategy: CellularStrategy,
55    /// Strategy for poor network conditions
56    pub poor_network_strategy: PoorNetworkStrategy,
57    /// Compression settings
58    pub compression_config: NetworkCompressionConfig,
59    /// Retry settings
60    pub retry_config: RetryConfig,
61}
62
63/// WiFi-specific communication strategy
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct WiFiStrategy {
66    /// Enable high-frequency updates
67    pub enable_high_frequency_updates: bool,
68    /// Maximum model size for full sync (MB)
69    pub max_full_sync_size_mb: usize,
70    /// Preferred sync window (hours)
71    pub preferred_sync_window_hours: Vec<u8>,
72    /// Enable background sync
73    pub enable_background_sync: bool,
74    /// Concurrent connection limit
75    pub max_concurrent_connections: usize,
76}
77
78/// Cellular-specific communication strategy
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct CellularStrategy {
81    /// Enable cellular sync
82    pub enable_cellular_sync: bool,
83    /// 5G-specific settings
84    pub g5_config: CellularConfig,
85    /// 4G-specific settings
86    pub g4_config: CellularConfig,
87    /// Data usage awareness
88    pub data_usage_awareness: DataUsageAwareness,
89    /// Time-based scheduling
90    pub time_based_scheduling: TimeBasedScheduling,
91}
92
93/// Cellular network configuration
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct CellularConfig {
96    /// Maximum sync size (MB)
97    pub max_sync_size_mb: usize,
98    /// Sync frequency (hours)
99    pub sync_frequency_hours: u32,
100    /// Enable compression
101    pub enable_compression: bool,
102    /// Compression ratio target
103    pub compression_ratio_target: f32,
104    /// Enable delta sync only
105    pub delta_sync_only: bool,
106}
107
108/// Data usage awareness settings
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct DataUsageAwareness {
111    /// Track daily data usage
112    pub track_daily_usage: bool,
113    /// Daily data limit (MB)
114    pub daily_limit_mb: usize,
115    /// Monthly data limit (MB)
116    pub monthly_limit_mb: usize,
117    /// Warning threshold (%)
118    pub warning_threshold_percent: u8,
119    /// Adaptive quality based on usage
120    pub adaptive_quality: bool,
121}
122
123/// Time-based scheduling for cellular networks
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct TimeBasedScheduling {
126    /// Preferred hours for sync (0-23)
127    pub preferred_hours: Vec<u8>,
128    /// Avoid peak hours
129    pub avoid_peak_hours: bool,
130    /// Peak hours definition (0-23)
131    pub peak_hours: Vec<u8>,
132    /// Off-peak bonus multiplier
133    pub off_peak_multiplier: f32,
134}
135
136/// Poor network condition strategy
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct PoorNetworkStrategy {
139    /// Enable degraded mode
140    pub enable_degraded_mode: bool,
141    /// Minimum viable update size (KB)
142    pub min_update_size_kb: usize,
143    /// Extended retry intervals
144    pub extended_retry_intervals: Vec<u64>,
145    /// Enable store-and-forward
146    pub enable_store_and_forward: bool,
147    /// Maximum queue size (MB)
148    pub max_queue_size_mb: usize,
149    /// Fallback to local training only
150    pub fallback_local_only: bool,
151}
152
153/// Network compression configuration
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct NetworkCompressionConfig {
156    /// Enable gradient compression
157    pub enable_gradient_compression: bool,
158    /// Gradient compression algorithm
159    pub gradient_compression_algo: GradientCompressionAlgorithm,
160    /// Model compression for sync
161    pub model_compression_ratio: f32,
162    /// Enable differential compression
163    pub enable_differential_compression: bool,
164    /// Quantization settings for network transfer
165    pub network_quantization: NetworkQuantizationConfig,
166}
167
168/// Gradient compression algorithms
169#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
170pub enum GradientCompressionAlgorithm {
171    /// No compression
172    None,
173    /// Top-K compression
174    TopK { k: usize },
175    /// Random sparsification
176    RandomSparsification { ratio: f32 },
177    /// Quantized compression
178    Quantized { bits: u8 },
179    /// Adaptive compression
180    Adaptive,
181}
182
183/// Network quantization configuration
184#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct NetworkQuantizationConfig {
186    /// Enable quantization for network transfer
187    pub enabled: bool,
188    /// Bits per parameter
189    pub bits_per_parameter: u8,
190    /// Dynamic range scaling
191    pub dynamic_range_scaling: bool,
192    /// Quantization scheme
193    pub scheme: QuantizationScheme,
194}
195
196/// Quantization schemes
197#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
198pub enum QuantizationScheme {
199    Uniform,
200    NonUniform,
201    Logarithmic,
202    Adaptive,
203}
204
205/// Retry configuration for network operations
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct RetryConfig {
208    /// Maximum retry attempts
209    pub max_attempts: usize,
210    /// Base retry interval (ms)
211    pub base_interval_ms: u64,
212    /// Exponential backoff multiplier
213    pub backoff_multiplier: f32,
214    /// Maximum retry interval (ms)
215    pub max_interval_ms: u64,
216    /// Jitter percentage (0.0-1.0)
217    pub jitter_percent: f32,
218}
219
220/// Data usage limits configuration
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct DataUsageLimits {
223    /// Daily data usage limit (MB)
224    pub daily_limit_mb: usize,
225    /// Monthly data usage limit (MB)
226    pub monthly_limit_mb: usize,
227    /// Per-session limit (MB)
228    pub session_limit_mb: usize,
229    /// Warning thresholds (%)
230    pub warning_thresholds: Vec<u8>,
231    /// Emergency stop threshold (%)
232    pub emergency_stop_threshold: u8,
233}
234
235/// Sync frequency configuration
236#[derive(Debug, Clone, Serialize, Deserialize)]
237pub struct SyncFrequencyConfig {
238    /// Base frequency (minutes)
239    pub base_frequency_minutes: u32,
240    /// Adaptive frequency enabled
241    pub adaptive_frequency: bool,
242    /// Minimum frequency (minutes)
243    pub min_frequency_minutes: u32,
244    /// Maximum frequency (minutes)
245    pub max_frequency_minutes: u32,
246    /// Conditions for frequency adjustment
247    pub frequency_conditions: HashMap<String, f32>,
248}
249
250/// Failure recovery configuration
251#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct FailureRecoveryConfig {
253    /// Enable automatic recovery
254    pub enable_auto_recovery: bool,
255    /// Recovery timeout (ms)
256    pub recovery_timeout_ms: u64,
257    /// Maximum recovery attempts
258    pub max_recovery_attempts: usize,
259    /// Recovery strategies
260    pub recovery_strategies: Vec<RecoveryStrategy>,
261    /// Fallback to offline mode
262    pub fallback_offline: bool,
263}
264
265/// Recovery strategies for network failures
266#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
267pub enum RecoveryStrategy {
268    Retry,
269    Reconnect,
270    Degrade,
271    Queue,
272    Offline,
273}
274
275/// Network prediction configuration
276#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct NetworkPredictionConfig {
278    /// Enable prediction
279    pub enabled: bool,
280    /// Prediction window (minutes)
281    pub prediction_window_minutes: u32,
282    /// Historical data window (hours)
283    pub history_window_hours: u32,
284    /// Prediction accuracy threshold
285    pub accuracy_threshold: f32,
286    /// Model update frequency (hours)
287    pub model_update_frequency_hours: u32,
288}
289
290// Default implementations
291impl Default for NetworkAdaptationConfig {
292    fn default() -> Self {
293        Self {
294            enable_monitoring: true,
295            monitoring_interval_ms: 10000, // 10 seconds
296            enable_adaptive_scheduling: true,
297            enable_bandwidth_optimization: true,
298            quality_thresholds: NetworkQualityThresholds::default(),
299            communication_strategy: CommunicationStrategy::default(),
300            data_usage_limits: DataUsageLimits::default(),
301            sync_frequency: SyncFrequencyConfig::default(),
302            failure_recovery: FailureRecoveryConfig::default(),
303            prediction_config: NetworkPredictionConfig::default(),
304        }
305    }
306}
307
308impl Default for NetworkQualityThresholds {
309    fn default() -> Self {
310        Self {
311            min_bandwidth_full_sync_mbps: 5.0,
312            min_bandwidth_incremental_sync_mbps: 1.0,
313            max_latency_realtime_ms: 100.0,
314            max_packet_loss_percent: 2.0,
315            min_signal_strength_dbm: -70,
316            max_jitter_ms: 50.0,
317        }
318    }
319}
320
321impl Default for WiFiStrategy {
322    fn default() -> Self {
323        Self {
324            enable_high_frequency_updates: true,
325            max_full_sync_size_mb: 100,
326            preferred_sync_window_hours: vec![2, 3, 4, 5], // 2-5 AM
327            enable_background_sync: true,
328            max_concurrent_connections: 3,
329        }
330    }
331}
332
333impl Default for CellularStrategy {
334    fn default() -> Self {
335        Self {
336            enable_cellular_sync: true,
337            g5_config: CellularConfig {
338                max_sync_size_mb: 50,
339                sync_frequency_hours: 6,
340                enable_compression: true,
341                compression_ratio_target: 0.7,
342                delta_sync_only: false,
343            },
344            g4_config: CellularConfig {
345                max_sync_size_mb: 20,
346                sync_frequency_hours: 12,
347                enable_compression: true,
348                compression_ratio_target: 0.5,
349                delta_sync_only: true,
350            },
351            data_usage_awareness: DataUsageAwareness::default(),
352            time_based_scheduling: TimeBasedScheduling::default(),
353        }
354    }
355}
356
357impl Default for DataUsageAwareness {
358    fn default() -> Self {
359        Self {
360            track_daily_usage: true,
361            daily_limit_mb: 100,
362            monthly_limit_mb: 2000,
363            warning_threshold_percent: 80,
364            adaptive_quality: true,
365        }
366    }
367}
368
369impl Default for TimeBasedScheduling {
370    fn default() -> Self {
371        Self {
372            preferred_hours: vec![2, 3, 4, 5, 6],
373            avoid_peak_hours: true,
374            peak_hours: vec![8, 9, 10, 17, 18, 19, 20],
375            off_peak_multiplier: 1.5,
376        }
377    }
378}
379
380impl Default for PoorNetworkStrategy {
381    fn default() -> Self {
382        Self {
383            enable_degraded_mode: true,
384            min_update_size_kb: 10,
385            extended_retry_intervals: vec![5000, 10000, 20000, 40000],
386            enable_store_and_forward: true,
387            max_queue_size_mb: 50,
388            fallback_local_only: true,
389        }
390    }
391}
392
393impl Default for NetworkCompressionConfig {
394    fn default() -> Self {
395        Self {
396            enable_gradient_compression: true,
397            gradient_compression_algo: GradientCompressionAlgorithm::Adaptive,
398            model_compression_ratio: 0.8,
399            enable_differential_compression: true,
400            network_quantization: NetworkQuantizationConfig::default(),
401        }
402    }
403}
404
405impl Default for NetworkQuantizationConfig {
406    fn default() -> Self {
407        Self {
408            enabled: true,
409            bits_per_parameter: 16,
410            dynamic_range_scaling: true,
411            scheme: QuantizationScheme::Adaptive,
412        }
413    }
414}
415
416impl Default for RetryConfig {
417    fn default() -> Self {
418        Self {
419            max_attempts: 3,
420            base_interval_ms: 1000,
421            backoff_multiplier: 2.0,
422            max_interval_ms: 10000,
423            jitter_percent: 0.1,
424        }
425    }
426}
427
428impl Default for DataUsageLimits {
429    fn default() -> Self {
430        Self {
431            daily_limit_mb: 100,
432            monthly_limit_mb: 2000,
433            session_limit_mb: 50,
434            warning_thresholds: vec![50, 75, 90],
435            emergency_stop_threshold: 95,
436        }
437    }
438}
439
440impl Default for SyncFrequencyConfig {
441    fn default() -> Self {
442        Self {
443            base_frequency_minutes: 60,
444            adaptive_frequency: true,
445            min_frequency_minutes: 15,
446            max_frequency_minutes: 240,
447            frequency_conditions: HashMap::new(),
448        }
449    }
450}
451
452impl Default for FailureRecoveryConfig {
453    fn default() -> Self {
454        Self {
455            enable_auto_recovery: true,
456            recovery_timeout_ms: 30000,
457            max_recovery_attempts: 3,
458            recovery_strategies: vec![
459                RecoveryStrategy::Retry,
460                RecoveryStrategy::Reconnect,
461                RecoveryStrategy::Degrade,
462            ],
463            fallback_offline: true,
464        }
465    }
466}
467
468impl Default for NetworkPredictionConfig {
469    fn default() -> Self {
470        Self {
471            enabled: true,
472            prediction_window_minutes: 30,
473            history_window_hours: 24,
474            accuracy_threshold: 0.8,
475            model_update_frequency_hours: 6,
476        }
477    }
478}