use larust_core::AppError;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
pub(crate) const INITIAL_POLL_INTERVAL: Duration = Duration::from_millis(250);
pub(crate) const MAX_POLL_INTERVAL: Duration = Duration::from_secs(5);
pub(crate) const JOB_LEASE_TIMEOUT_SECS: i64 = 5 * 60;
pub(crate) const MAX_ATTEMPTS: i64 = 3;
pub(crate) type BoxedHandler =
Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync>;
#[must_use]
pub struct JobRegistry {
pub(crate) handlers: HashMap<String, BoxedHandler>,
}
impl Default for JobRegistry {
fn default() -> Self {
Self::new()
}
}
impl JobRegistry {
pub fn new() -> Self {
Self {
handlers: HashMap::new(),
}
}
pub fn register<J: crate::Job>(mut self) -> Self {
let handler: BoxedHandler = Box::new(|payload: String| {
Box::pin(async move {
let job: J = serde_json::from_str(&payload)
.map_err(|source| AppError::Internal(Box::new(source)))?;
job.handle().await
})
});
let existing = self.handlers.insert(J::JOB_TYPE.to_string(), handler);
assert!(
existing.is_none(),
"duplicate JobRegistry::register for JOB_TYPE {:?} - each job type must be \
registered exactly once",
J::JOB_TYPE,
);
self
}
}
pub async fn work(registry: JobRegistry) -> Result<(), AppError> {
match crate::queue_driver() {
"redis" => crate::redis_worker::work(registry).await,
_ => crate::sql_worker::work(registry).await,
}
}