use crate::storage::RedisClient;
use crate::progress::ProgressContext;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[derive(Clone)]
pub struct HandlerContext {
task_id: String,
redis: RedisClient,
progress: Option<ProgressContext>,
cancelled: Arc<AtomicBool>,
}
impl HandlerContext {
pub fn new(
task_id: String,
redis: RedisClient,
progress: Option<ProgressContext>,
cancelled: Arc<AtomicBool>,
) -> Self {
Self {
task_id,
redis,
progress,
cancelled,
}
}
pub fn task_id(&self) -> &str {
&self.task_id
}
pub fn redis(&self) -> &RedisClient {
&self.redis
}
pub fn progress(&self) -> Option<&ProgressContext> {
self.progress.as_ref()
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Relaxed)
}
pub async fn report_progress(&self, percentage: u8) -> crate::Result<()> {
if let Some(progress) = &self.progress {
progress.report(percentage as u32).await?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
#[ignore = "Requires Redis server"]
async fn test_handler_context_creation() {
let redis = crate::storage::RedisClient::from_url("redis://localhost:6379")
.await
.unwrap();
let ctx = HandlerContext::new(
"test-task-id".to_string(),
redis,
None,
Arc::new(AtomicBool::new(false)),
);
assert_eq!(ctx.task_id(), "test-task-id");
assert!(!ctx.is_cancelled());
}
#[test]
fn test_cancellation_flag() {
let cancelled = Arc::new(AtomicBool::new(false));
assert!(!cancelled.load(Ordering::Relaxed));
cancelled.store(true, Ordering::Relaxed);
assert!(cancelled.load(Ordering::Relaxed));
}
}