Skip to main content

larust_queue/
worker.rs

1//! `JobRegistry` (shared, driver-agnostic) plus `work()`'s runtime driver
2//! dispatch - mirrors `dispatch.rs`'s own shape (see that module's doc
3//! comment for the underlying precedent).
4
5use larust_core::AppError;
6use std::collections::HashMap;
7use std::future::Future;
8use std::pin::Pin;
9use std::time::Duration;
10
11/// How often a worker checks for new work again after finding none. Not
12/// configurable in v1 - a fixed, reasonable default, same "hardcoded, not
13/// a toggle, until real pressure justifies one" shape as
14/// `larust_http::session::EXPIRED_SESSION_CLEANUP_INTERVAL`. Shared by
15/// both drivers' own `work()` loop.
16pub(crate) const INITIAL_POLL_INTERVAL: Duration = Duration::from_millis(250);
17pub(crate) const MAX_POLL_INTERVAL: Duration = Duration::from_secs(5);
18/// How long a claimed-but-unfinished job's lease is honored before another
19/// worker is allowed to reclaim it (a crashed worker's own leftover claim).
20pub(crate) const JOB_LEASE_TIMEOUT_SECS: i64 = 5 * 60;
21pub(crate) const MAX_ATTEMPTS: i64 = 3;
22
23pub(crate) type BoxedHandler =
24    Box<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync>;
25
26/// Maps a `Job::JOB_TYPE` tag back to the concrete type that can
27/// deserialize and run it - built fresh by whatever calls `work()`
28/// (typically the generated app's own `queue:work` branch in `main.rs`),
29/// not a process-wide static: only one `work()` loop reads it, in the one
30/// process running it, so there's no cross-request sharing need the way
31/// `larust-events`' listener registry or `larust_http::route`'s
32/// named-route registry have.
33#[must_use]
34pub struct JobRegistry {
35    pub(crate) handlers: HashMap<String, BoxedHandler>,
36}
37
38impl Default for JobRegistry {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl JobRegistry {
45    pub fn new() -> Self {
46        Self {
47            handlers: HashMap::new(),
48        }
49    }
50
51    /// Registers `J` so `work()` can run it. Panics on a duplicate
52    /// `J::JOB_TYPE` - a startup-time registration collision is a real
53    /// programmer bug (the shadowed job type would silently never run its
54    /// own handler again); failing loudly and immediately here beats
55    /// surfacing it later as "jobs of type X mysteriously stopped
56    /// deserializing correctly."
57    pub fn register<J: crate::Job>(mut self) -> Self {
58        let handler: BoxedHandler = Box::new(|payload: String| {
59            Box::pin(async move {
60                let job: J = serde_json::from_str(&payload)
61                    .map_err(|source| AppError::Internal(Box::new(source)))?;
62                job.handle().await
63            })
64        });
65        let existing = self.handlers.insert(J::JOB_TYPE.to_string(), handler);
66        assert!(
67            existing.is_none(),
68            "duplicate JobRegistry::register for JOB_TYPE {:?} - each job type must be \
69             registered exactly once",
70            J::JOB_TYPE,
71        );
72        self
73    }
74}
75
76/// Runs forever, claiming and executing jobs one at a time until the
77/// process is stopped (Ctrl+C / killed - no signal handling here, same as
78/// Laravel's own `queue:work` without `--stop-when-empty`). A job whose
79/// handler fails, or whose `job_type` has no registered handler, is
80/// recorded as a failure rather than retried forever or silently dropped.
81pub async fn work(registry: JobRegistry) -> Result<(), AppError> {
82    match crate::queue_driver() {
83        "redis" => crate::redis_worker::work(registry).await,
84        _ => crate::sql_worker::work(registry).await,
85    }
86}