Skip to main content

trustformers_mobile/lifecycle/
config.rs

1//! Lifecycle Configuration Types
2//!
3//! This module contains all configuration types for app lifecycle management,
4//! including resource management, background tasks, notifications, and system responses.
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9/// Lifecycle management configuration
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct LifecycleConfig {
12    /// Enable background execution
13    pub enable_background_execution: bool,
14    /// Background execution time limit (seconds)
15    pub background_execution_limit_seconds: u64,
16    /// Enable state persistence
17    pub enable_state_persistence: bool,
18    /// State save interval (seconds)
19    pub state_save_interval_seconds: u64,
20    /// Resource management settings
21    pub resource_management: ResourceManagementConfig,
22    /// Background task settings
23    pub background_tasks: BackgroundTaskConfig,
24    /// Notification settings
25    pub notifications: NotificationConfig,
26    /// Memory warning handling
27    pub memory_warning_handling: MemoryWarningConfig,
28    /// Thermal warning handling
29    pub thermal_warning_handling: ThermalWarningConfig,
30    /// Network interruption handling
31    pub network_interruption_handling: NetworkInterruptionConfig,
32}
33
34/// Resource management configuration
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct ResourceManagementConfig {
37    /// Enable automatic resource scaling
38    pub enable_auto_scaling: bool,
39    /// Memory pressure response
40    pub memory_pressure_response: MemoryPressureResponse,
41    /// Thermal pressure response
42    pub thermal_pressure_response: ThermalPressureResponse,
43    /// Battery pressure response
44    pub battery_pressure_response: BatteryPressureResponse,
45    /// Background resource limits
46    pub background_limits: BackgroundResourceLimits,
47    /// Foreground resource allocation
48    pub foreground_allocation: ForegroundResourceAllocation,
49}
50
51/// Memory pressure response strategies
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct MemoryPressureResponse {
54    /// Enable memory cleanup on pressure
55    pub enable_cleanup: bool,
56    /// Memory pressure thresholds (%)
57    pub pressure_thresholds: MemoryPressureThresholds,
58    /// Cleanup strategies by pressure level
59    pub cleanup_strategies: HashMap<MemoryPressureLevel, CleanupStrategy>,
60    /// Model eviction policy
61    pub model_eviction_policy: ModelEvictionPolicy,
62}
63
64/// Memory pressure levels and thresholds
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct MemoryPressureThresholds {
67    /// Warning level threshold (%)
68    pub warning_percent: u8,
69    /// Critical level threshold (%)
70    pub critical_percent: u8,
71    /// Emergency level threshold (%)
72    pub emergency_percent: u8,
73}
74
75/// Memory pressure levels
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
77pub enum MemoryPressureLevel {
78    Normal,
79    Warning,
80    Critical,
81    Emergency,
82}
83
84/// Cleanup strategies for memory pressure
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct CleanupStrategy {
87    /// Clear model caches
88    pub clear_model_cache: bool,
89    /// Clear intermediate tensors
90    pub clear_intermediate_tensors: bool,
91    /// Reduce batch sizes
92    pub reduce_batch_sizes: bool,
93    /// Compress models in memory
94    pub compress_models: bool,
95    /// Offload models to disk
96    pub offload_to_disk: bool,
97    /// Priority for cleanup operations
98    pub cleanup_priority: CleanupPriority,
99}
100
101/// Cleanup operation priorities
102#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
103pub enum CleanupPriority {
104    Low,
105    Medium,
106    High,
107    Critical,
108}
109
110/// Model eviction policies
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
112pub enum ModelEvictionPolicy {
113    LeastRecentlyUsed,
114    LeastFrequentlyUsed,
115    SizeBasedEviction,
116    PriorityBasedEviction,
117    AdaptiveEviction,
118}
119
120/// Thermal pressure response strategies
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ThermalPressureResponse {
123    /// Enable thermal response
124    pub enable_response: bool,
125    /// Thermal throttling levels
126    pub throttling_levels: ThermalThrottlingLevels,
127    /// Performance scaling strategy
128    pub performance_scaling: PerformanceScalingStrategy,
129    /// Inference frequency reduction
130    pub frequency_reduction: FrequencyReductionConfig,
131}
132
133/// Thermal throttling levels and responses
134#[derive(Debug, Clone, Serialize, Deserialize)]
135pub struct ThermalThrottlingLevels {
136    /// Light throttling threshold (°C)
137    pub light_throttle_celsius: f32,
138    /// Moderate throttling threshold (°C)
139    pub moderate_throttle_celsius: f32,
140    /// Heavy throttling threshold (°C)
141    pub heavy_throttle_celsius: f32,
142    /// Emergency throttling threshold (°C)
143    pub emergency_throttle_celsius: f32,
144}
145
146/// Performance scaling strategies
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
148pub enum PerformanceScalingStrategy {
149    Linear,
150    Exponential,
151    Adaptive,
152    UserDefined,
153}
154
155/// Inference frequency reduction configuration
156#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct FrequencyReductionConfig {
158    /// Enable frequency reduction
159    pub enable_reduction: bool,
160    /// Reduction factors by thermal level
161    pub reduction_factors: HashMap<ThermalLevel, f32>,
162    /// Minimum inference frequency (Hz)
163    pub min_frequency_hz: f32,
164}
165
166/// Thermal levels for throttling
167#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
168pub enum ThermalLevel {
169    Normal,
170    Light,
171    Moderate,
172    Heavy,
173    Emergency,
174}
175
176/// Battery pressure response strategies
177#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct BatteryPressureResponse {
179    /// Enable battery response
180    pub enable_response: bool,
181    /// Battery level thresholds
182    pub battery_thresholds: BatteryThresholds,
183    /// Power saving strategies
184    pub power_saving_strategies: HashMap<crate::battery::BatteryLevel, PowerSavingStrategy>,
185    /// Background processing limits
186    pub background_processing_limits: BackgroundProcessingLimits,
187}
188
189/// Battery level thresholds for responses
190#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct BatteryThresholds {
192    /// Critical battery level (%)
193    pub critical_percent: u8,
194    /// Low battery level (%)
195    pub low_percent: u8,
196    /// Medium battery level (%)
197    pub medium_percent: u8,
198}
199
200/// Power saving strategies by battery level
201#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct PowerSavingStrategy {
203    /// Reduce inference frequency
204    pub reduce_inference_frequency: bool,
205    /// Lower model precision
206    pub lower_model_precision: bool,
207    /// Disable background updates
208    pub disable_background_updates: bool,
209    /// Use CPU-only inference
210    pub cpu_only_inference: bool,
211    /// Defer non-critical tasks
212    pub defer_non_critical_tasks: bool,
213}
214
215/// Background processing limits based on battery
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct BackgroundProcessingLimits {
218    /// Maximum background time (seconds)
219    pub max_background_time_seconds: u64,
220    /// Maximum CPU usage (%)
221    pub max_cpu_usage_percent: u8,
222    /// Maximum memory usage (MB)
223    pub max_memory_usage_mb: usize,
224    /// Task priority adjustments
225    pub priority_adjustments: HashMap<TaskType, i8>,
226}
227
228/// Background resource limits
229#[derive(Debug, Clone, Serialize, Deserialize)]
230pub struct BackgroundResourceLimits {
231    /// Maximum CPU usage in background (%)
232    pub max_cpu_percent: u8,
233    /// Maximum memory usage in background (MB)
234    pub max_memory_mb: usize,
235    /// Maximum network usage in background (MB/min)
236    pub max_network_mbps: f32,
237    /// Maximum background execution time (seconds)
238    pub max_execution_time_seconds: u64,
239}
240
241/// Foreground resource allocation
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ForegroundResourceAllocation {
244    /// CPU allocation (%)
245    pub cpu_allocation_percent: u8,
246    /// Memory allocation (MB)
247    pub memory_allocation_mb: usize,
248    /// Network allocation (MB/min)
249    pub network_allocation_mbps: f32,
250    /// GPU allocation (%)
251    pub gpu_allocation_percent: Option<u8>,
252}
253
254/// Background task configuration
255#[derive(Debug, Clone, Serialize, Deserialize)]
256pub struct BackgroundTaskConfig {
257    /// Enable background model updates
258    pub enable_model_updates: bool,
259    /// Enable background federated learning
260    pub enable_federated_learning: bool,
261    /// Enable background data processing
262    pub enable_data_processing: bool,
263    /// Background task priorities
264    pub task_priorities: HashMap<TaskType, TaskPriority>,
265    /// Task scheduling strategies
266    pub scheduling_strategies: HashMap<TaskType, SchedulingStrategy>,
267    /// Maximum concurrent background tasks
268    pub max_concurrent_tasks: usize,
269}
270
271/// Types of background tasks
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
273pub enum TaskType {
274    ModelUpdate,
275    FederatedLearning,
276    DataSync,
277    CacheCleanup,
278    Analytics,
279    Backup,
280    Precomputation,
281    HealthCheck,
282}
283
284/// Task priority levels
285#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
286pub enum TaskPriority {
287    Low,
288    Normal,
289    High,
290    Critical,
291    Emergency,
292}
293
294/// Task scheduling strategies
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
296pub enum SchedulingStrategy {
297    Immediate,
298    Deferred,
299    OpportunisticAgg,
300    UserIdle,
301    NetworkOptimal,
302    BatteryOptimal,
303    ThermalOptimal,
304}
305
306/// Notification configuration
307#[derive(Debug, Clone, Serialize, Deserialize)]
308pub struct NotificationConfig {
309    /// Enable push notifications
310    pub enable_push_notifications: bool,
311    /// Enable local notifications
312    pub enable_local_notifications: bool,
313    /// Notification types to enable
314    pub enabled_types: Vec<NotificationType>,
315    /// Background notification handling
316    pub background_handling: BackgroundNotificationHandling,
317    /// Notification throttling
318    pub throttling: NotificationThrottling,
319}
320
321/// Types of notifications
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
323pub enum NotificationType {
324    ModelUpdateAvailable,
325    FederatedLearningTask,
326    SystemAlert,
327    PerformanceWarning,
328    MaintenanceRequired,
329    UserAction,
330}
331
332/// Background notification handling
333#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct BackgroundNotificationHandling {
335    /// Queue notifications when in background
336    pub queue_when_background: bool,
337    /// Maximum queued notifications
338    pub max_queued_notifications: usize,
339    /// Batch notification delivery
340    pub batch_delivery: bool,
341    /// Delivery strategies by type
342    pub delivery_strategies: HashMap<NotificationType, DeliveryStrategy>,
343}
344
345/// Notification delivery strategies
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
347pub enum DeliveryStrategy {
348    Immediate,
349    Batched,
350    Deferred,
351    OnForeground,
352    UserTriggered,
353}
354
355/// Notification throttling configuration
356#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct NotificationThrottling {
358    /// Enable throttling
359    pub enable_throttling: bool,
360    /// Maximum notifications per hour
361    pub max_per_hour: u32,
362    /// Minimum interval between notifications (seconds)
363    pub min_interval_seconds: u64,
364    /// Notification type-based rate limits
365    pub notification_rate_limits: HashMap<NotificationType, u32>,
366}
367
368/// Memory warning configuration
369#[derive(Debug, Clone, Serialize, Deserialize)]
370pub struct MemoryWarningConfig {
371    /// Enable memory warning handling
372    pub enable_handling: bool,
373    /// Automatic cleanup on warning
374    pub automatic_cleanup: bool,
375    /// Warning response strategies
376    pub response_strategies: Vec<MemoryWarningResponse>,
377    /// Grace period before aggressive cleanup (seconds)
378    pub grace_period_seconds: u64,
379}
380
381/// Memory warning response actions
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
383pub enum MemoryWarningResponse {
384    ClearCaches,
385    ReduceBatchSizes,
386    OffloadModels,
387    PauseBackgroundTasks,
388    NotifyUser,
389    ForceGarbageCollection,
390}
391
392/// Thermal warning configuration
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct ThermalWarningConfig {
395    /// Enable thermal warning handling
396    pub enable_handling: bool,
397    /// Automatic throttling on warning
398    pub automatic_throttling: bool,
399    /// Warning response strategies
400    pub response_strategies: Vec<ThermalWarningResponse>,
401    /// Cooldown period (seconds)
402    pub cooldown_period_seconds: u64,
403}
404
405/// Thermal warning response actions
406#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
407pub enum ThermalWarningResponse {
408    ReduceInferenceFrequency,
409    LowerModelPrecision,
410    PauseComputeIntensiveTasks,
411    SwitchToCpuOnly,
412    NotifyUser,
413    EnterCooldownMode,
414}
415
416/// Network interruption handling configuration
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct NetworkInterruptionConfig {
419    /// Enable interruption handling
420    pub enable_handling: bool,
421    /// Automatic reconnection
422    pub automatic_reconnection: bool,
423    /// Maximum reconnection attempts
424    pub max_reconnection_attempts: u32,
425    /// Reconnection backoff strategy
426    pub backoff_strategy: ReconnectionBackoffStrategy,
427    /// Offline mode configuration
428    pub offline_mode: OfflineModeConfig,
429}
430
431/// Reconnection backoff strategies
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
433pub enum ReconnectionBackoffStrategy {
434    Linear,
435    Exponential,
436    Fibonacci,
437    Custom,
438}
439
440/// Offline mode configuration
441#[derive(Debug, Clone, Serialize, Deserialize)]
442pub struct OfflineModeConfig {
443    /// Enable offline mode
444    pub enable_offline_mode: bool,
445    /// Local model fallback
446    pub local_model_fallback: bool,
447    /// Cache inference results
448    pub cache_inference_results: bool,
449    /// Queue sync operations
450    pub queue_sync_operations: bool,
451    /// Maximum offline cache size (MB)
452    pub max_offline_cache_mb: usize,
453}
454
455impl Default for LifecycleConfig {
456    fn default() -> Self {
457        Self {
458            enable_background_execution: true,
459            background_execution_limit_seconds: 30,
460            enable_state_persistence: true,
461            state_save_interval_seconds: 60,
462            resource_management: ResourceManagementConfig::default(),
463            background_tasks: BackgroundTaskConfig::default(),
464            notifications: NotificationConfig::default(),
465            memory_warning_handling: MemoryWarningConfig::default(),
466            thermal_warning_handling: ThermalWarningConfig::default(),
467            network_interruption_handling: NetworkInterruptionConfig::default(),
468        }
469    }
470}
471
472impl Default for ResourceManagementConfig {
473    fn default() -> Self {
474        Self {
475            enable_auto_scaling: true,
476            memory_pressure_response: MemoryPressureResponse::default(),
477            thermal_pressure_response: ThermalPressureResponse::default(),
478            battery_pressure_response: BatteryPressureResponse::default(),
479            background_limits: BackgroundResourceLimits::default(),
480            foreground_allocation: ForegroundResourceAllocation::default(),
481        }
482    }
483}
484
485impl Default for MemoryPressureResponse {
486    fn default() -> Self {
487        let mut cleanup_strategies = HashMap::new();
488        cleanup_strategies.insert(
489            MemoryPressureLevel::Warning,
490            CleanupStrategy {
491                clear_model_cache: true,
492                clear_intermediate_tensors: false,
493                reduce_batch_sizes: false,
494                compress_models: false,
495                offload_to_disk: false,
496                cleanup_priority: CleanupPriority::Low,
497            },
498        );
499        cleanup_strategies.insert(
500            MemoryPressureLevel::Critical,
501            CleanupStrategy {
502                clear_model_cache: true,
503                clear_intermediate_tensors: true,
504                reduce_batch_sizes: true,
505                compress_models: true,
506                offload_to_disk: false,
507                cleanup_priority: CleanupPriority::Medium,
508            },
509        );
510        cleanup_strategies.insert(
511            MemoryPressureLevel::Emergency,
512            CleanupStrategy {
513                clear_model_cache: true,
514                clear_intermediate_tensors: true,
515                reduce_batch_sizes: true,
516                compress_models: true,
517                offload_to_disk: true,
518                cleanup_priority: CleanupPriority::Critical,
519            },
520        );
521
522        Self {
523            enable_cleanup: true,
524            pressure_thresholds: MemoryPressureThresholds {
525                warning_percent: 70,
526                critical_percent: 85,
527                emergency_percent: 95,
528            },
529            cleanup_strategies,
530            model_eviction_policy: ModelEvictionPolicy::LeastRecentlyUsed,
531        }
532    }
533}
534
535impl Default for ThermalPressureResponse {
536    fn default() -> Self {
537        let mut reduction_factors = HashMap::new();
538        reduction_factors.insert(ThermalLevel::Light, 0.9);
539        reduction_factors.insert(ThermalLevel::Moderate, 0.7);
540        reduction_factors.insert(ThermalLevel::Heavy, 0.5);
541        reduction_factors.insert(ThermalLevel::Emergency, 0.3);
542
543        Self {
544            enable_response: true,
545            throttling_levels: ThermalThrottlingLevels {
546                light_throttle_celsius: 40.0,
547                moderate_throttle_celsius: 45.0,
548                heavy_throttle_celsius: 50.0,
549                emergency_throttle_celsius: 55.0,
550            },
551            performance_scaling: PerformanceScalingStrategy::Adaptive,
552            frequency_reduction: FrequencyReductionConfig {
553                enable_reduction: true,
554                reduction_factors,
555                min_frequency_hz: 1.0,
556            },
557        }
558    }
559}
560
561impl Default for BatteryPressureResponse {
562    fn default() -> Self {
563        use crate::battery::BatteryLevel;
564        let mut power_saving_strategies = HashMap::new();
565
566        power_saving_strategies.insert(
567            BatteryLevel::Critical,
568            PowerSavingStrategy {
569                reduce_inference_frequency: true,
570                lower_model_precision: true,
571                disable_background_updates: true,
572                cpu_only_inference: true,
573                defer_non_critical_tasks: true,
574            },
575        );
576
577        power_saving_strategies.insert(
578            BatteryLevel::Low,
579            PowerSavingStrategy {
580                reduce_inference_frequency: true,
581                lower_model_precision: false,
582                disable_background_updates: true,
583                cpu_only_inference: false,
584                defer_non_critical_tasks: true,
585            },
586        );
587
588        let mut priority_adjustments = HashMap::new();
589        priority_adjustments.insert(TaskType::ModelUpdate, -1);
590        priority_adjustments.insert(TaskType::FederatedLearning, -2);
591        priority_adjustments.insert(TaskType::Analytics, -1);
592
593        Self {
594            enable_response: true,
595            battery_thresholds: BatteryThresholds {
596                critical_percent: 15,
597                low_percent: 30,
598                medium_percent: 50,
599            },
600            power_saving_strategies,
601            background_processing_limits: BackgroundProcessingLimits {
602                max_background_time_seconds: 10,
603                max_cpu_usage_percent: 20,
604                max_memory_usage_mb: 100,
605                priority_adjustments,
606            },
607        }
608    }
609}
610
611impl Default for BackgroundResourceLimits {
612    fn default() -> Self {
613        Self {
614            max_cpu_percent: 30,
615            max_memory_mb: 256,
616            max_network_mbps: 1.0,
617            max_execution_time_seconds: 30,
618        }
619    }
620}
621
622impl Default for ForegroundResourceAllocation {
623    fn default() -> Self {
624        Self {
625            cpu_allocation_percent: 80,
626            memory_allocation_mb: 1024,
627            network_allocation_mbps: 10.0,
628            gpu_allocation_percent: Some(70),
629        }
630    }
631}
632
633impl Default for BackgroundTaskConfig {
634    fn default() -> Self {
635        let mut task_priorities = HashMap::new();
636        task_priorities.insert(TaskType::ModelUpdate, TaskPriority::Normal);
637        task_priorities.insert(TaskType::FederatedLearning, TaskPriority::Low);
638        task_priorities.insert(TaskType::DataSync, TaskPriority::Normal);
639        task_priorities.insert(TaskType::CacheCleanup, TaskPriority::Low);
640        task_priorities.insert(TaskType::Analytics, TaskPriority::Low);
641        task_priorities.insert(TaskType::Backup, TaskPriority::Low);
642        task_priorities.insert(TaskType::Precomputation, TaskPriority::Normal);
643        task_priorities.insert(TaskType::HealthCheck, TaskPriority::High);
644
645        let mut scheduling_strategies = HashMap::new();
646        scheduling_strategies.insert(TaskType::ModelUpdate, SchedulingStrategy::NetworkOptimal);
647        scheduling_strategies.insert(
648            TaskType::FederatedLearning,
649            SchedulingStrategy::BatteryOptimal,
650        );
651        scheduling_strategies.insert(TaskType::DataSync, SchedulingStrategy::NetworkOptimal);
652        scheduling_strategies.insert(TaskType::CacheCleanup, SchedulingStrategy::UserIdle);
653        scheduling_strategies.insert(TaskType::Analytics, SchedulingStrategy::UserIdle);
654        scheduling_strategies.insert(TaskType::Backup, SchedulingStrategy::UserIdle);
655        scheduling_strategies.insert(TaskType::Precomputation, SchedulingStrategy::ThermalOptimal);
656        scheduling_strategies.insert(TaskType::HealthCheck, SchedulingStrategy::Immediate);
657
658        Self {
659            enable_model_updates: true,
660            enable_federated_learning: false,
661            enable_data_processing: true,
662            task_priorities,
663            scheduling_strategies,
664            max_concurrent_tasks: 3,
665        }
666    }
667}
668
669impl Default for NotificationConfig {
670    fn default() -> Self {
671        let enabled_types = vec![
672            NotificationType::SystemAlert,
673            NotificationType::PerformanceWarning,
674            NotificationType::MaintenanceRequired,
675        ];
676
677        Self {
678            enable_push_notifications: true,
679            enable_local_notifications: true,
680            enabled_types,
681            background_handling: BackgroundNotificationHandling::default(),
682            throttling: NotificationThrottling::default(),
683        }
684    }
685}
686
687impl Default for BackgroundNotificationHandling {
688    fn default() -> Self {
689        let mut delivery_strategies = HashMap::new();
690        delivery_strategies.insert(
691            NotificationType::ModelUpdateAvailable,
692            DeliveryStrategy::Batched,
693        );
694        delivery_strategies.insert(
695            NotificationType::FederatedLearningTask,
696            DeliveryStrategy::Deferred,
697        );
698        delivery_strategies.insert(NotificationType::SystemAlert, DeliveryStrategy::Immediate);
699        delivery_strategies.insert(
700            NotificationType::PerformanceWarning,
701            DeliveryStrategy::OnForeground,
702        );
703        delivery_strategies.insert(
704            NotificationType::MaintenanceRequired,
705            DeliveryStrategy::Batched,
706        );
707        delivery_strategies.insert(
708            NotificationType::UserAction,
709            DeliveryStrategy::UserTriggered,
710        );
711
712        Self {
713            queue_when_background: true,
714            max_queued_notifications: 10,
715            batch_delivery: true,
716            delivery_strategies,
717        }
718    }
719}
720
721impl Default for NotificationThrottling {
722    fn default() -> Self {
723        let mut notification_rate_limits = HashMap::new();
724        notification_rate_limits.insert(NotificationType::ModelUpdateAvailable, 2);
725        notification_rate_limits.insert(NotificationType::FederatedLearningTask, 5);
726        notification_rate_limits.insert(NotificationType::SystemAlert, 10);
727        notification_rate_limits.insert(NotificationType::PerformanceWarning, 20);
728        notification_rate_limits.insert(NotificationType::MaintenanceRequired, 100);
729
730        Self {
731            enable_throttling: true,
732            max_per_hour: 10,
733            min_interval_seconds: 300, // 5 minutes
734            notification_rate_limits,
735        }
736    }
737}
738
739impl Default for MemoryWarningConfig {
740    fn default() -> Self {
741        Self {
742            enable_handling: true,
743            automatic_cleanup: true,
744            response_strategies: vec![
745                MemoryWarningResponse::ClearCaches,
746                MemoryWarningResponse::ReduceBatchSizes,
747                MemoryWarningResponse::PauseBackgroundTasks,
748            ],
749            grace_period_seconds: 10,
750        }
751    }
752}
753
754impl Default for ThermalWarningConfig {
755    fn default() -> Self {
756        Self {
757            enable_handling: true,
758            automatic_throttling: true,
759            response_strategies: vec![
760                ThermalWarningResponse::ReduceInferenceFrequency,
761                ThermalWarningResponse::PauseComputeIntensiveTasks,
762            ],
763            cooldown_period_seconds: 30,
764        }
765    }
766}
767
768impl Default for NetworkInterruptionConfig {
769    fn default() -> Self {
770        Self {
771            enable_handling: true,
772            automatic_reconnection: true,
773            max_reconnection_attempts: 5,
774            backoff_strategy: ReconnectionBackoffStrategy::Exponential,
775            offline_mode: OfflineModeConfig::default(),
776        }
777    }
778}
779
780impl Default for OfflineModeConfig {
781    fn default() -> Self {
782        Self {
783            enable_offline_mode: true,
784            local_model_fallback: true,
785            cache_inference_results: true,
786            queue_sync_operations: true,
787            max_offline_cache_mb: 100,
788        }
789    }
790}