use crate::email::EmailSender;
use crate::storage::FileStorage;
use sqlx::PgPool;
use std::sync::Arc;
#[cfg(feature = "redis")]
use deadpool_redis::Pool as RedisPool;
#[derive(Clone)]
pub struct JobContext {
email_sender: Option<Arc<dyn EmailSender>>,
database_pool: Option<Arc<PgPool>>,
file_storage: Option<Arc<dyn FileStorage>>,
#[cfg(feature = "redis")]
redis_pool: Option<RedisPool>,
}
impl JobContext {
#[must_use]
pub fn new() -> Self {
Self {
email_sender: None,
database_pool: None,
file_storage: None,
#[cfg(feature = "redis")]
redis_pool: None,
}
}
#[must_use]
pub fn with_email_sender(mut self, sender: Arc<dyn EmailSender>) -> Self {
self.email_sender = Some(sender);
self
}
#[must_use]
pub fn with_database_pool(mut self, pool: Arc<PgPool>) -> Self {
self.database_pool = Some(pool);
self
}
#[must_use]
pub fn with_file_storage(mut self, storage: Arc<dyn FileStorage>) -> Self {
self.file_storage = Some(storage);
self
}
#[cfg(feature = "redis")]
#[must_use]
pub fn with_redis_pool(mut self, pool: RedisPool) -> Self {
self.redis_pool = Some(pool);
self
}
#[must_use]
pub fn email_sender(&self) -> Option<&Arc<dyn EmailSender>> {
self.email_sender.as_ref()
}
#[must_use]
pub const fn database_pool(&self) -> Option<&Arc<PgPool>> {
self.database_pool.as_ref()
}
#[must_use]
pub fn file_storage(&self) -> Option<&Arc<dyn FileStorage>> {
self.file_storage.as_ref()
}
#[cfg(feature = "redis")]
#[must_use]
pub const fn redis_pool(&self) -> Option<&RedisPool> {
self.redis_pool.as_ref()
}
}
impl Default for JobContext {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for JobContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut debug_struct = f.debug_struct("JobContext");
debug_struct
.field("email_sender", &self.email_sender.is_some())
.field("database_pool", &self.database_pool.is_some())
.field("file_storage", &self.file_storage.is_some());
#[cfg(feature = "redis")]
debug_struct.field("redis_pool", &self.redis_pool.is_some());
debug_struct.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_job_context_new() {
let ctx = JobContext::new();
assert!(ctx.email_sender().is_none());
assert!(ctx.database_pool().is_none());
assert!(ctx.file_storage().is_none());
}
#[test]
fn test_job_context_default() {
let ctx = JobContext::default();
assert!(ctx.email_sender().is_none());
assert!(ctx.database_pool().is_none());
assert!(ctx.file_storage().is_none());
}
#[test]
fn test_job_context_debug() {
let ctx = JobContext::new();
let debug_output = format!("{ctx:?}");
assert!(debug_output.contains("JobContext"));
assert!(debug_output.contains("email_sender"));
}
}