use once_cell::sync::OnceCell; use parking_lot::RwLock; use serde::Serialize; use smartstring::alias::String as SmartString; use std::collections::VecDeque; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::{Mutex, Notify}; pub(super) const SWITCH_JOB_TIMEOUT: Duration = Duration::from_secs(30); pub(super) const SWITCH_CLEANUP_TIMEOUT: Duration = Duration::from_secs(5); static SWITCH_MANAGER: OnceCell = OnceCell::new(); pub(super) fn manager() -> &'static SwitchManager { SWITCH_MANAGER.get_or_init(SwitchManager::default) } #[derive(Debug)] // Central coordination point shared between the driver and workflow state machine. pub(super) struct SwitchManager { core_mutex: Mutex<()>, request_sequence: AtomicU64, switching: AtomicBool, task_sequence: AtomicU64, status: RwLock, event_sequence: AtomicU64, recent_events: RwLock>, } impl Default for SwitchManager { fn default() -> Self { Self { core_mutex: Mutex::new(()), request_sequence: AtomicU64::new(0), switching: AtomicBool::new(false), task_sequence: AtomicU64::new(0), status: RwLock::new(ProfileSwitchStatus::default()), event_sequence: AtomicU64::new(0), recent_events: RwLock::new(VecDeque::with_capacity(32)), } } } impl SwitchManager { pub(super) fn core_mutex(&self) -> &Mutex<()> { &self.core_mutex } // Monotonic identifiers so logs can correlate enqueue/finish pairs. pub(super) fn next_task_id(&self) -> u64 { self.task_sequence.fetch_add(1, Ordering::SeqCst) + 1 } /// Sequence id assigned to each enqueue request so we can spot stale work. pub(super) fn next_request_sequence(&self) -> u64 { self.request_sequence.fetch_add(1, Ordering::SeqCst) + 1 } pub(super) fn latest_request_sequence(&self) -> u64 { self.request_sequence.load(Ordering::SeqCst) } pub(super) fn begin_switch(&'static self) -> SwitchScope<'static> { self.switching.store(true, Ordering::SeqCst); SwitchScope { manager: self } } pub(super) fn is_switching(&self) -> bool { self.switching.load(Ordering::SeqCst) } pub(super) fn set_status(&self, status: ProfileSwitchStatus) { *self.status.write() = status; } pub(super) fn status_snapshot(&self) -> ProfileSwitchStatus { self.status.read().clone() } pub(super) fn push_event(&self, result: SwitchResultStatus) { const MAX_EVENTS: usize = 64; let sequence = self.event_sequence.fetch_add(1, Ordering::SeqCst) + 1; let mut guard = self.recent_events.write(); if guard.len() == MAX_EVENTS { guard.pop_front(); } guard.push_back(SwitchResultEvent { sequence, result }); } pub(super) fn events_after(&self, sequence: u64) -> Vec { self.recent_events .read() .iter() .filter(|event| event.sequence > sequence) .cloned() .collect() } } pub(super) struct SwitchScope<'a> { manager: &'a SwitchManager, } impl Drop for SwitchScope<'_> { fn drop(&mut self) { self.manager.switching.store(false, Ordering::SeqCst); } } #[derive(Debug, Clone)] pub(super) struct SwitchCancellation { flag: Arc, notify: Arc, } impl SwitchCancellation { pub(super) fn new() -> Self { Self { flag: Arc::new(AtomicBool::new(false)), notify: Arc::new(Notify::new()), } } pub(super) fn cancel(&self) { self.flag.store(true, Ordering::SeqCst); self.notify.notify_waiters(); } /// True if another request already cancelled this job. pub(super) fn is_cancelled(&self) -> bool { self.flag.load(Ordering::SeqCst) } pub(super) fn same_token(&self, other: &SwitchCancellation) -> bool { Arc::ptr_eq(&self.flag, &other.flag) } pub(super) async fn cancelled_future(&self) { // Used by async blocks that want to pause until a newer request pre-empts them. if self.is_cancelled() { return; } self.notify.notified().await; } } #[derive(Debug, Clone)] pub(super) struct SwitchRequest { task_id: u64, profile_id: SmartString, notify: bool, cancel_token: SwitchCancellation, heartbeat: SwitchHeartbeat, } impl SwitchRequest { pub(super) fn new(task_id: u64, profile_id: SmartString, notify: bool) -> Self { Self { task_id, profile_id, notify, cancel_token: SwitchCancellation::new(), heartbeat: SwitchHeartbeat::new(), } } pub(super) fn task_id(&self) -> u64 { self.task_id } pub(super) fn profile_id(&self) -> &SmartString { &self.profile_id } pub(super) fn notify(&self) -> bool { self.notify } pub(super) fn merge_notify(&mut self, notify: bool) { // When a new request wants a toast, remember it even if an older request did not. if notify { self.notify = true; } } pub(super) fn cancel_token(&self) -> &SwitchCancellation { &self.cancel_token } pub(super) fn heartbeat(&self) -> &SwitchHeartbeat { &self.heartbeat } } #[derive(Debug, Clone)] pub(super) struct SwitchHeartbeat { last_tick_millis: Arc, stage_code: Arc, } fn now_millis() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or(Duration::ZERO) .as_millis() as u64 } #[derive(Debug, Clone, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct ProfileSwitchStatus { pub is_switching: bool, pub active: Option, pub queue: Vec, pub cleanup_profiles: Vec, pub last_result: Option, pub last_updated: u64, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct SwitchTaskStatus { pub task_id: u64, pub profile_id: String, pub notify: bool, pub stage: Option, pub queued: bool, } impl SwitchTaskStatus { pub(super) fn from_request(request: &SwitchRequest, queued: bool) -> Self { Self { task_id: request.task_id(), profile_id: request.profile_id().to_string(), notify: request.notify(), stage: if queued { None } else { Some(request.heartbeat().stage_code()) }, queued, } } } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct SwitchResultStatus { pub task_id: u64, pub profile_id: String, pub success: bool, pub cancelled: bool, pub finished_at: u64, pub error_stage: Option, pub error_detail: Option, } impl SwitchResultStatus { pub(super) fn success(task_id: u64, profile_id: &SmartString) -> Self { Self { task_id, profile_id: profile_id.to_string(), success: true, cancelled: false, finished_at: now_millis(), error_stage: None, error_detail: None, } } pub(super) fn failed( task_id: u64, profile_id: &SmartString, stage: Option, detail: Option, ) -> Self { Self { task_id, profile_id: profile_id.to_string(), success: false, cancelled: false, finished_at: now_millis(), error_stage: stage, error_detail: detail, } } pub(super) fn cancelled( task_id: u64, profile_id: &SmartString, detail: Option, ) -> Self { Self { task_id, profile_id: profile_id.to_string(), success: false, cancelled: true, finished_at: now_millis(), error_stage: Some("cancelled".to_string()), error_detail: detail, } } } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct SwitchResultEvent { pub sequence: u64, pub result: SwitchResultStatus, } pub(super) fn current_millis() -> u64 { now_millis() } impl SwitchHeartbeat { fn now_millis() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or(Duration::ZERO) .as_millis() as u64 } pub(super) fn new() -> Self { let heartbeat = Self { last_tick_millis: Arc::new(AtomicU64::new(Self::now_millis())), stage_code: Arc::new(AtomicU32::new(0)), }; heartbeat.touch(); heartbeat } pub(super) fn touch(&self) { self.last_tick_millis .store(Self::now_millis(), Ordering::SeqCst); } /// Update the internal timer to reflect the amount of time since the last heartbeat. pub(super) fn elapsed(&self) -> Duration { let last = self.last_tick_millis.load(Ordering::SeqCst); let now = Self::now_millis(); Duration::from_millis(now.saturating_sub(last)) } pub(super) fn set_stage(&self, stage: u32) { self.stage_code.store(stage, Ordering::SeqCst); self.touch(); } pub(super) fn stage_code(&self) -> u32 { self.stage_code.load(Ordering::SeqCst) } }