Skip to main content

trustformers_mobile/lifecycle/
state.rs

1//! App State Management Types
2//!
3//! This module contains types for managing app lifecycle states, transitions,
4//! and related context information.
5
6use serde::{Deserialize, Serialize};
7use std::collections::{HashMap, VecDeque};
8use std::time::Instant;
9
10/// App states
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12pub enum AppState {
13    /// App is starting up
14    Launching,
15    /// App is active and in foreground
16    Active,
17    /// App is in background but still executing
18    Background,
19    /// App is inactive (transitioning)
20    Inactive,
21    /// App is suspended (not executing)
22    Suspended,
23    /// App is terminating
24    Terminating,
25    /// Unknown state
26    Unknown,
27}
28
29/// State transitions
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
31pub enum StateTransition {
32    LaunchToActive,
33    ActiveToBackground,
34    BackgroundToActive,
35    ActiveToInactive,
36    InactiveToActive,
37    BackgroundToSuspended,
38    SuspendedToBackground,
39    AnyToTerminating,
40}
41
42/// State transition event
43#[derive(Debug, Clone)]
44pub struct StateTransitionEvent {
45    pub from_state: AppState,
46    pub to_state: AppState,
47    pub transition: StateTransition,
48    pub timestamp: Instant,
49    pub reason: TransitionReason,
50    pub context: TransitionContext,
51}
52
53/// Reasons for state transitions
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub enum TransitionReason {
56    UserAction,
57    SystemRequest,
58    LowMemory,
59    LowBattery,
60    ThermalPressure,
61    NetworkInterruption,
62    Timeout,
63    Error,
64    SystemSuspend,
65    SystemResume,
66}
67
68/// Context information for state transitions
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct TransitionContext {
71    /// Available memory (MB)
72    pub available_memory_mb: usize,
73    /// Battery level (%)
74    pub battery_level_percent: u8,
75    /// CPU temperature (°C)
76    pub cpu_temperature_celsius: f32,
77    /// Network connectivity status
78    pub network_connected: bool,
79    /// Active background tasks count
80    pub active_background_tasks: usize,
81    /// Time since last user interaction (seconds)
82    pub time_since_user_interaction_seconds: u64,
83    /// Foreground app duration (seconds)
84    pub foreground_duration_seconds: u64,
85    /// Background app duration (seconds)
86    pub background_duration_seconds: u64,
87    /// System pressure indicators
88    pub system_pressure: SystemPressureIndicators,
89    /// Resource usage at transition
90    pub resource_usage: ResourceUsageSnapshot,
91}
92
93/// System pressure indicators
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct SystemPressureIndicators {
96    /// Memory pressure level
97    pub memory_pressure: crate::lifecycle::config::MemoryPressureLevel,
98    /// Thermal state
99    pub thermal_state: crate::lifecycle::config::ThermalLevel,
100    /// Battery state
101    pub battery_state: crate::battery::BatteryLevel,
102    /// Network quality
103    pub network_quality: NetworkQuality,
104}
105
106/// Network quality levels
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
108pub enum NetworkQuality {
109    Excellent,
110    Good,
111    Fair,
112    Poor,
113    Disconnected,
114}
115
116/// Resource usage snapshot
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct ResourceUsageSnapshot {
119    /// CPU usage percentage (0-100)
120    pub cpu_usage_percent: f32,
121    /// Memory usage in MB
122    pub memory_usage_mb: usize,
123    /// GPU usage percentage (0-100)
124    pub gpu_usage_percent: Option<f32>,
125    /// Network usage in MB/s
126    pub network_usage_mbps: f32,
127    /// Storage I/O in MB/s
128    pub storage_io_mbps: f32,
129    /// Active model count
130    pub active_models: usize,
131    /// Inference queue size
132    pub inference_queue_size: usize,
133}
134
135/// App checkpoint for state persistence
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct AppCheckpoint {
138    /// App state at checkpoint
139    pub app_state: AppState,
140    /// Timestamp of checkpoint
141    pub timestamp: u64, // Using u64 for serialization
142    /// Model states
143    pub model_states: Vec<ModelState>,
144    /// Cache states
145    pub cache_states: HashMap<String, CacheState>,
146    /// User session state
147    pub user_session: UserSessionState,
148}
149
150/// Model state information
151#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct ModelState {
153    /// Model identifier
154    pub model_id: String,
155    /// Model load state
156    pub load_state: ModelLoadState,
157    /// Model configuration
158    pub configuration: ModelConfiguration,
159    /// Performance metrics
160    pub performance_metrics: ModelPerformanceMetrics,
161    /// Last access timestamp
162    pub last_access_timestamp: u64,
163    /// Usage count
164    pub usage_count: usize,
165}
166
167/// Model load states
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
169pub enum ModelLoadState {
170    Unloaded,
171    Loading,
172    Loaded,
173    Error,
174    Cached,
175    Compressed,
176    Offloaded,
177}
178
179/// Cache state information
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct CacheState {
182    /// Cache size in bytes
183    pub size_bytes: usize,
184    /// Number of cached items
185    pub item_count: usize,
186    /// Last access timestamp
187    pub last_access_timestamp: u64,
188    /// Hit rate percentage
189    pub hit_rate_percent: f32,
190}
191
192/// Model configuration
193#[derive(Debug, Clone, Serialize, Deserialize)]
194pub struct ModelConfiguration {
195    /// Model precision
196    pub precision: ModelPrecision,
197    /// Optimization level
198    pub optimization_level: OptimizationLevel,
199    /// Backend in use
200    pub backend: ModelBackend,
201}
202
203/// Model precision levels
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205pub enum ModelPrecision {
206    FP32,
207    FP16,
208    INT8,
209    INT4,
210    Dynamic,
211}
212
213/// Model optimization levels
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215pub enum OptimizationLevel {
216    None,
217    Basic,
218    Aggressive,
219    UltraLowMemory,
220}
221
222/// Model backend types
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
224pub enum ModelBackend {
225    CPU,
226    CoreML,
227    NNAPI,
228    Metal,
229    Vulkan,
230    Custom,
231}
232
233/// Model performance metrics
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct ModelPerformanceMetrics {
236    /// Average inference time (ms)
237    pub avg_inference_time_ms: f32,
238    /// Memory usage (MB)
239    pub memory_usage_mb: usize,
240    /// Throughput (inferences/second)
241    pub throughput_per_second: f32,
242    /// Error rate percentage
243    pub error_rate_percent: f32,
244}
245
246/// Task state information
247#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct TaskState {
249    /// Task identifier
250    pub task_id: String,
251    /// Task type
252    pub task_type: crate::lifecycle::config::TaskType,
253    /// Current status
254    pub status: LifecycleTaskStatus,
255    /// Priority level
256    pub priority: crate::lifecycle::config::TaskPriority,
257    /// Progress percentage (0-100)
258    pub progress_percent: u8,
259    /// Estimated completion time (seconds)
260    pub estimated_completion_seconds: Option<u64>,
261}
262
263/// Task execution status
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
265pub enum LifecycleTaskStatus {
266    Pending,
267    Running,
268    Paused,
269    Completed,
270    Failed,
271    Cancelled,
272}
273
274/// User session state
275#[derive(Debug, Clone, Serialize, Deserialize)]
276pub struct UserSessionState {
277    /// Session start timestamp
278    pub session_start_timestamp: u64,
279    /// Total interaction time (seconds)
280    pub total_interaction_time_seconds: u64,
281    /// Recent user interactions
282    pub recent_interactions: Vec<UserInteraction>,
283    /// Session statistics
284    pub session_stats: SessionStatistics,
285}
286
287/// User interaction record
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct UserInteraction {
290    /// Interaction timestamp
291    pub timestamp: u64,
292    /// Type of interaction
293    pub interaction_type: InteractionType,
294    /// Interaction outcome
295    pub outcome: InteractionOutcome,
296    /// Duration of interaction (ms)
297    pub duration_ms: u64,
298}
299
300/// Types of user interactions
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
302pub enum InteractionType {
303    Touch,
304    Voice,
305    Gesture,
306    TextInput,
307    ModelInference,
308    Navigation,
309    Settings,
310}
311
312/// Interaction outcomes
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
314pub enum InteractionOutcome {
315    Success,
316    Failure,
317    Cancelled,
318    Timeout,
319    Error,
320}
321
322/// Session statistics
323#[derive(Debug, Clone, Serialize, Deserialize)]
324pub struct SessionStatistics {
325    /// Total inferences performed
326    pub total_inferences: usize,
327    /// Total models loaded
328    pub total_models_loaded: usize,
329    /// Total background tasks executed
330    pub total_background_tasks: usize,
331    /// Average response time (ms)
332    pub avg_response_time_ms: f32,
333    /// Error count
334    pub error_count: usize,
335}
336
337/// System context information
338#[derive(Debug, Clone, Serialize, Deserialize)]
339pub struct SystemContext {
340    /// Current timestamp
341    pub timestamp: u64,
342    /// Device information
343    pub device_info: SystemDeviceInfo,
344    /// Resource availability
345    pub resource_availability: ResourceAvailability,
346    /// Network status
347    pub network_status: NetworkStatus,
348    /// Power status
349    pub power_status: PowerStatus,
350    /// Thermal status
351    pub thermal_status: ThermalStatus,
352    /// Active processes
353    pub active_processes: ProcessInfo,
354    /// System load
355    pub system_load: SystemLoad,
356}
357
358/// System device information
359#[derive(Debug, Clone, Serialize, Deserialize)]
360pub struct SystemDeviceInfo {
361    /// Device model
362    pub device_model: String,
363    /// OS version
364    pub os_version: String,
365    /// Available cores
366    pub cpu_cores: usize,
367    /// Total RAM (MB)
368    pub total_ram_mb: usize,
369    /// Available storage (MB)
370    pub available_storage_mb: usize,
371}
372
373/// Resource availability information
374#[derive(Debug, Clone, Serialize, Deserialize)]
375pub struct ResourceAvailability {
376    /// Available CPU percentage
377    pub available_cpu_percent: f32,
378    /// Available memory (MB)
379    pub available_memory_mb: usize,
380    /// Available GPU percentage
381    pub available_gpu_percent: Option<f32>,
382    /// Available network bandwidth (Mbps)
383    pub available_network_mbps: f32,
384}
385
386/// Network status information
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct NetworkStatus {
389    /// Network connectivity
390    pub connected: bool,
391    /// Connection type
392    pub connection_type: NetworkConnectionType,
393    /// Signal strength (0-100)
394    pub signal_strength_percent: u8,
395    /// Network quality
396    pub quality: NetworkQuality,
397    /// Data usage (MB)
398    pub data_usage_mb: f32,
399}
400
401/// Network connection types
402#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
403pub enum NetworkConnectionType {
404    WiFi,
405    Cellular,
406    Ethernet,
407    Bluetooth,
408    Unknown,
409}
410
411/// Power status information
412#[derive(Debug, Clone, Serialize, Deserialize)]
413pub struct PowerStatus {
414    /// Battery level (%)
415    pub battery_level_percent: u8,
416    /// Charging status
417    pub charging_status: ChargingStatus,
418    /// Power save mode enabled
419    pub power_save_mode: bool,
420    /// Estimated battery life (minutes)
421    pub estimated_battery_life_minutes: Option<u32>,
422}
423
424/// Charging status
425#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
426pub enum ChargingStatus {
427    Charging,
428    Discharging,
429    Full,
430    NotCharging,
431    Unknown,
432}
433
434/// Thermal status information
435#[derive(Debug, Clone, Serialize, Deserialize)]
436pub struct ThermalStatus {
437    /// CPU temperature (°C)
438    pub cpu_temperature_celsius: f32,
439    /// GPU temperature (°C)
440    pub gpu_temperature_celsius: Option<f32>,
441    /// Thermal state
442    pub thermal_state: crate::lifecycle::config::ThermalLevel,
443    /// Throttling active
444    pub throttling_active: bool,
445}
446
447/// Process information
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct ProcessInfo {
450    /// Total processes
451    pub total_processes: usize,
452    /// Active processes
453    pub active_processes: usize,
454    /// Background processes
455    pub background_processes: usize,
456    /// Memory usage by processes (MB)
457    pub process_memory_usage_mb: usize,
458}
459
460/// System load information
461#[derive(Debug, Clone, Serialize, Deserialize)]
462pub struct SystemLoad {
463    /// 1-minute load average
464    pub load_1min: f32,
465    /// 5-minute load average
466    pub load_5min: f32,
467    /// 15-minute load average
468    pub load_15min: f32,
469    /// CPU utilization (%)
470    pub cpu_utilization_percent: f32,
471    /// Memory utilization (%)
472    pub memory_utilization_percent: f32,
473}
474
475/// App state manager for lifecycle transitions
476pub struct AppStateManager {
477    current_state: AppState,
478    previous_state: AppState,
479    state_history: VecDeque<StateTransition>,
480    state_listeners: Vec<Box<dyn StateListener>>,
481    transition_handlers: HashMap<StateTransition, Box<dyn TransitionHandler>>,
482}
483
484/// Trait for state change listeners
485pub trait StateListener: Send + Sync {
486    fn on_state_change(&self, event: &StateTransitionEvent);
487}
488
489/// Trait for state transition handlers
490pub trait TransitionHandler: Send + Sync {
491    fn handle_transition(
492        &self,
493        event: &StateTransitionEvent,
494    ) -> Result<(), Box<dyn std::error::Error>>;
495}
496
497impl AppStateManager {
498    /// Create new state manager
499    pub fn new() -> Self {
500        Self {
501            current_state: AppState::Unknown,
502            previous_state: AppState::Unknown,
503            state_history: VecDeque::new(),
504            state_listeners: Vec::new(),
505            transition_handlers: HashMap::new(),
506        }
507    }
508
509    /// Get current app state
510    pub fn current_state(&self) -> AppState {
511        self.current_state
512    }
513
514    /// Get previous app state
515    pub fn previous_state(&self) -> AppState {
516        self.previous_state
517    }
518
519    /// Transition to new state
520    pub fn transition_to_state(
521        &mut self,
522        new_state: AppState,
523        reason: TransitionReason,
524        context: TransitionContext,
525    ) -> Result<(), Box<dyn std::error::Error>> {
526        let transition = self.determine_transition(self.current_state, new_state)?;
527
528        let event = StateTransitionEvent {
529            from_state: self.current_state,
530            to_state: new_state,
531            transition,
532            timestamp: Instant::now(),
533            reason,
534            context,
535        };
536
537        // Execute transition handler if registered
538        if let Some(handler) = self.transition_handlers.get(&transition) {
539            handler.handle_transition(&event)?;
540        }
541
542        // Update state
543        self.previous_state = self.current_state;
544        self.current_state = new_state;
545        self.state_history.push_back(transition);
546
547        // Keep history bounded
548        if self.state_history.len() > 100 {
549            self.state_history.pop_front();
550        }
551
552        // Notify listeners
553        for listener in &self.state_listeners {
554            listener.on_state_change(&event);
555        }
556
557        Ok(())
558    }
559
560    /// Register state change listener
561    pub fn add_state_listener(&mut self, listener: Box<dyn StateListener>) {
562        self.state_listeners.push(listener);
563    }
564
565    /// Register transition handler
566    pub fn add_transition_handler(
567        &mut self,
568        transition: StateTransition,
569        handler: Box<dyn TransitionHandler>,
570    ) {
571        self.transition_handlers.insert(transition, handler);
572    }
573
574    /// Get state transition history
575    pub fn get_state_history(&self) -> &VecDeque<StateTransition> {
576        &self.state_history
577    }
578
579    /// Determine transition type between states
580    fn determine_transition(
581        &self,
582        from: AppState,
583        to: AppState,
584    ) -> Result<StateTransition, Box<dyn std::error::Error>> {
585        match (from, to) {
586            (AppState::Launching, AppState::Active) => Ok(StateTransition::LaunchToActive),
587            (AppState::Active, AppState::Background) => Ok(StateTransition::ActiveToBackground),
588            (AppState::Background, AppState::Active) => Ok(StateTransition::BackgroundToActive),
589            (AppState::Active, AppState::Inactive) => Ok(StateTransition::ActiveToInactive),
590            (AppState::Inactive, AppState::Active) => Ok(StateTransition::InactiveToActive),
591            (AppState::Background, AppState::Suspended) => {
592                Ok(StateTransition::BackgroundToSuspended)
593            },
594            (AppState::Suspended, AppState::Background) => {
595                Ok(StateTransition::SuspendedToBackground)
596            },
597            (_, AppState::Terminating) => Ok(StateTransition::AnyToTerminating),
598            _ => Err(format!("Invalid state transition from {:?} to {:?}", from, to).into()),
599        }
600    }
601}
602
603impl Default for AppStateManager {
604    fn default() -> Self {
605        Self::new()
606    }
607}