use crate::account::disable::DisableRepository;
use crate::error::{GarrisonError, GarrisonResult};
use crate::stp::GarrisonLogicDefault;
use crate::strategy::Strategy;
use arc_swap::ArcSwapOption;
use parking_lot::RwLock;
use std::sync::Arc;
use super::{GarrisonManager, GARRISON_MANAGER};
impl GarrisonManager {
pub(super) fn new() -> Self {
Self {
logic: ArcSwapOption::empty(),
strategy: ArcSwapOption::empty(),
cleanup_task_handle: RwLock::new(None),
#[cfg(feature = "anomalous-detector-dual")]
anomalous_analyzer_handle: RwLock::new(None),
#[cfg(feature = "anomalous-detector-dual")]
anomalous_analyzer_shutdown_tx: RwLock::new(None),
}
}
pub fn logic() -> GarrisonResult<Arc<GarrisonLogicDefault>> {
GARRISON_MANAGER
.logic
.load_full()
.ok_or_else(|| GarrisonError::Session("manager-not-init".to_string()))
}
pub fn strategy() -> GarrisonResult<Arc<RwLock<Strategy>>> {
GARRISON_MANAGER
.strategy
.load_full()
.ok_or_else(|| GarrisonError::Session("manager-not-init".to_string()))
}
pub fn disable_repository() -> Option<Arc<dyn DisableRepository>> {
Self::logic()
.ok()
.map(|logic| logic.disable_repository.clone())
}
pub fn with_strategy(strategy: Arc<RwLock<Strategy>>) -> GarrisonResult<()> {
GARRISON_MANAGER.strategy.store(Some(strategy));
Ok(())
}
pub fn is_initialized() -> bool {
GARRISON_MANAGER.logic.load().is_some() && GARRISON_MANAGER.strategy.load().is_some()
}
#[cfg(any(test, feature = "testing"))]
pub fn reset_for_test() {
if let Some(handle) = GARRISON_MANAGER.cleanup_task_handle.write().take() {
handle.abort();
}
#[cfg(feature = "anomalous-detector-dual")]
{
if let Some(handle) = GARRISON_MANAGER.anomalous_analyzer_handle.write().take() {
handle.abort();
}
GARRISON_MANAGER
.anomalous_analyzer_shutdown_tx
.write()
.take();
}
GARRISON_MANAGER.logic.store(None);
GARRISON_MANAGER.strategy.store(None);
}
}
impl Drop for GarrisonManager {
fn drop(&mut self) {
if let Some(handle) = self.cleanup_task_handle.write().take() {
handle.abort();
}
#[cfg(feature = "anomalous-detector-dual")]
{
if let Some(handle) = self.anomalous_analyzer_handle.write().take() {
handle.abort();
}
self.anomalous_analyzer_shutdown_tx.write().take();
}
}
}