Skip to main content

apalis_core/worker/
context.rs

1//! Worker context and task tracking.
2//!
3//! [`WorkerContext`] is responsible for managing
4//! the execution lifecycle of a worker, tracking tasks, handling shutdown, and emitting
5//! lifecycle events.
6//!
7//! ## Lifecycle
8//! A `WorkerContext` goes through distinct phases of operation:
9//!
10//! - **Pending**: Created via [`WorkerContext::new`] and must be explicitly started.
11//! - **Running**: Activated by calling [`WorkerContext::start`]. The worker becomes ready to accept and track tasks.
12//! - **Paused**: Temporarily halted via [`WorkerContext::pause`]. New tasks are blocked from execution.
13//! - **Resumed**: Brought back to `Running` using [`WorkerContext::resume`].
14//! - **Stopped**: Finalized via [`WorkerContext::stop`]. The worker shuts down gracefully, allowing tracked tasks to complete.
15//!
16//! The `WorkerContext` itself implements [`Future`], and can be `.await`ed — it resolves
17//! once the worker is shut down and all tasks have completed.
18//!
19//! ## Task Management
20//! Asynchronous tasks can be tracked which ensures:
21//! - Task count is incremented before execution and decremented on completion
22//! - Shutdown is automatically triggered once all tasks are done
23//!
24//! Use [`task_count`](WorkerContext::task_count) and [`has_pending_tasks`](WorkerContext::has_pending_tasks) to inspect
25//! ongoing task state.
26//!
27//! ## Shutdown Semantics
28//! The worker is considered shutting down if:
29//! - `stop()` has been called
30//! - A shutdown signal (if configured) has been triggered
31//!
32//! Once shutdown begins, no new tasks should be accepted. Internally, a stored [`Waker`] is
33//! used to drive progress toward shutdown completion.
34//!
35//! ## Event Handling
36//! Worker lifecycle events (e.g., `Start`, `Stop`) are emitted automatically
37//! and custom ones can be emitted using [`WorkerContext::emit`].
38//!
39//! ## Request Integration
40//! `WorkerContext` implements [`FromRequest`] so it can be extracted automatically in request
41//! handlers when using a compatible framework or service layer.
42//!
43//! ## Types
44//! - [`WorkerContext`] — shared state container for a worker
45use std::{
46    fmt::{self},
47    sync::{
48        Arc, Mutex,
49        atomic::{AtomicBool, AtomicUsize, Ordering},
50    },
51    task::{Context, Waker},
52    time::{Duration, Instant},
53};
54
55#[cfg(feature = "task-context")]
56use crate::task::context::{TaskContext, TaskStateError};
57
58use crate::{
59    error::{WorkerError, WorkerStateError},
60    monitor::shutdown::Shutdown,
61    task::from_request::FromRequest,
62    task::{ExecutionContext, Task, data::MissingDataError},
63    worker::{
64        event::{Event, EventListener, RawEventListener},
65        lifecycle::TaskLifecycleError,
66        state::{InnerWorkerState, WorkerState},
67    },
68};
69
70/// Utility for managing a worker's context
71///
72/// A worker context is created for each worker thread and is responsible for managing
73/// the worker's state, task tracking, and event handling.
74///
75///  **Tip**: All fields are wrapped inside [`Arc`] so it should be cheap to clone
76#[derive(Clone)]
77pub struct WorkerContext {
78    pub(crate) name: Arc<String>,
79    /// The waker used to wake the worker when tasks complete or shutdown is triggered.
80    waker: Arc<Mutex<Option<Waker>>>,
81    state: Arc<WorkerState>,
82    pub(crate) shutdown: Option<Shutdown>,
83    event_handler: EventListener,
84    pub(super) is_ready: Arc<AtomicBool>,
85    service: Arc<String>,
86    #[cfg(feature = "task-context")]
87    tasks: Arc<dashmap::DashSet<TaskContext>>,
88
89    #[cfg(not(feature = "task-context"))]
90    tasks: Arc<AtomicUsize>,
91
92    instant: Instant,
93    restarts: Arc<AtomicUsize>,
94}
95
96impl fmt::Debug for WorkerContext {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.debug_struct("WorkerContext")
99            .field("shutdown", &["Shutdown handle"])
100            .field("task_count", &self.task_count())
101            .field("state", &self.state.load(Ordering::SeqCst))
102            .field("service", &self.service)
103            .field("is_ready", &self.is_ready)
104            .field("tasks", &"[..]")
105            .field("elapsed", &self.instant.elapsed())
106            .field("restarts", &self.restarts)
107            .finish()
108    }
109}
110
111impl WorkerContext {
112    /// Create a new worker context
113    #[must_use]
114    pub fn new(name: &str) -> Self {
115        Self {
116            name: Arc::new(name.to_owned()),
117            service: "Unspecified".to_owned().into(),
118            waker: Default::default(),
119            state: Default::default(),
120            shutdown: Default::default(),
121            event_handler: Arc::new(Box::new(|_, _| {
122                // noop
123            })),
124            is_ready: Default::default(),
125            tasks: Default::default(),
126            instant: Instant::now(),
127            restarts: Default::default(),
128        }
129    }
130
131    /// Get the worker id
132    #[must_use]
133    pub fn name(&self) -> &str {
134        &self.name
135    }
136
137    /// Start running the worker
138    pub fn start(&mut self) -> Result<(), WorkerError> {
139        let current_state = self.state.load(Ordering::SeqCst);
140        if current_state != InnerWorkerState::Pending {
141            return Err(WorkerError::StateError(WorkerStateError::AlreadyStarted));
142        }
143        self.state
144            .store(InnerWorkerState::Running, Ordering::SeqCst);
145        self.is_ready.store(false, Ordering::SeqCst);
146        info!("Worker {} started", self.name());
147        self.wake();
148        Ok(())
149    }
150
151    /// Restart running the worker
152    pub(crate) fn restart(&self) -> Result<(), WorkerError> {
153        self.state
154            .store(InnerWorkerState::Pending, Ordering::SeqCst);
155        self.is_ready.store(false, Ordering::SeqCst);
156        #[cfg(feature = "task-context")]
157        self.cleanup()
158            .map_err(|e| WorkerError::StateError(WorkerStateError::InvalidState(e.to_string())))?;
159        self.restarts.fetch_add(1, Ordering::SeqCst);
160        info!("Worker {} restarted", self.name());
161        self.wake();
162        Ok(())
163    }
164
165    /// Pauses a worker, preventing any new jobs from being polled
166    pub fn pause(&self) -> Result<(), WorkerError> {
167        if !self.is_running() {
168            return Err(WorkerError::StateError(WorkerStateError::NotRunning));
169        }
170        self.state.store(InnerWorkerState::Paused, Ordering::SeqCst);
171        info!("Worker {} paused", self.name());
172        Ok(())
173    }
174
175    /// Resume a worker that is paused
176    pub fn resume(&self) -> Result<(), WorkerError> {
177        if !self.is_paused() {
178            return Err(WorkerError::StateError(WorkerStateError::NotPaused));
179        }
180        if self.is_shutting_down() {
181            return Err(WorkerError::StateError(WorkerStateError::ShuttingDown));
182        }
183        self.state
184            .store(InnerWorkerState::Running, Ordering::SeqCst);
185        self.wake();
186        info!("Worker {} resumed", self.name());
187        Ok(())
188    }
189
190    /// Calling this function triggers shutting down the worker while waiting for any tasks to complete
191    pub fn stop(&self) -> Result<(), WorkerError> {
192        let current_state = self.state.load(Ordering::SeqCst);
193        if current_state == InnerWorkerState::Pending {
194            return Err(WorkerError::StateError(WorkerStateError::NotStarted));
195        }
196        self.state
197            .store(InnerWorkerState::Stopped, Ordering::SeqCst);
198        self.wake();
199        self.emit_ref(&Event::Stop);
200        info!("Worker {} stopped", self.name());
201        Ok(())
202    }
203
204    /// Checks if the worker is ready to consume new tasks
205    #[must_use]
206    pub fn is_ready(&self) -> bool {
207        self.is_running() && !self.is_shutting_down() && self.is_ready.load(Ordering::SeqCst)
208    }
209
210    /// Get the `type_name` of the service used
211    ///
212    /// ## Example
213    /// ```ignore
214    /// async fn send_email(email: Email) {}
215    ///
216    /// // Might be something like:
217    /// TaskFn<send_email, Email, ()>>
218    /// ```
219    #[must_use]
220    pub fn get_service(&self) -> &str {
221        self.service.as_ref()
222    }
223
224    pub(crate) fn bind_service<T>(&mut self) {
225        let service = std::any::type_name::<T>();
226
227        const RULES: &[(&str, &str, &str)] = &[
228            (
229                "Retry<",
230                "Trace<",
231                "`retries()` must be before `enable_tracing()`; traces produced will provide invalid attempt information",
232            ),
233            (
234                "Retry<",
235                "PrometheusService<",
236                "`retries()` must be before `prometheus()`; metrics inside retries will be invalid",
237            ),
238            (
239                "Retry<",
240                "Timeout<",
241                "`retries()` must be before `timeout()`; timeouts will be applied to the total retry process",
242            ),
243            (
244                "Timeout<",
245                "Trace<",
246                "`timeout()` should be before `enable_tracing()`; otherwise timeout failures may not be reflected correctly in traces",
247            ),
248            (
249                "Timeout<",
250                "PrometheusService<",
251                "`timeout()` should be before `prometheus()`; otherwise timeout failures may not be reflected correctly in metrics",
252            ),
253            (
254                "ConcurrencyLimit<",
255                "Retry<",
256                "`concurrency()` should generally be before `retries()`; otherwise each retry may consume a separate concurrency slot",
257            ),
258            (
259                "ConcurrencyLimit<",
260                "Timeout<",
261                "`concurrency()` should generally be before `timeout()`; otherwise queued requests may consume timeout duration",
262            ),
263            (
264                "RateLimit<",
265                "Retry<",
266                "`rate_limit()` should generally be before `retries()`; otherwise retries may consume rate-limit capacity",
267            ),
268            (
269                "LoadShed<",
270                "Retry<",
271                "`load_shed()` should generally be before `retries()`; otherwise retries may repeatedly encounter load-shed failures",
272            ),
273            (
274                "Retry<",
275                "CatchPanicService<",
276                "`catch_panic()` should generally be after `retries()` if panics are intended to participate in retry handling",
277            ),
278        ];
279
280        for &(outer, inner, message) in RULES {
281            if let (Some(a), Some(b)) = (service.find(outer), service.find(inner)) {
282                if a > b {
283                    warn!("{message}");
284                }
285            }
286        }
287
288        *Arc::make_mut(&mut self.service) = service.to_owned();
289    }
290
291    /// Checks whether the worker is running
292    #[must_use]
293    pub fn is_running(&self) -> bool {
294        self.state.load(Ordering::SeqCst) == InnerWorkerState::Running
295    }
296
297    /// Checks whether the worker is pending
298    #[must_use]
299    pub fn is_pending(&self) -> bool {
300        self.state.load(Ordering::SeqCst) == InnerWorkerState::Pending
301    }
302
303    /// Checks whether the worker is paused
304    #[must_use]
305    pub fn is_paused(&self) -> bool {
306        self.state.load(Ordering::SeqCst) == InnerWorkerState::Paused
307    }
308
309    /// Checks whether the worker has been stopped
310    #[must_use]
311    pub fn is_stopped(&self) -> bool {
312        self.state.load(Ordering::SeqCst) == InnerWorkerState::Stopped || self.is_terminated()
313    }
314
315    /// Checks whether the worker is terminated
316    ///
317    #[must_use]
318    pub fn is_terminated(&self) -> bool {
319        self.state.load(Ordering::SeqCst) == InnerWorkerState::Terminated
320    }
321
322    /// Checks the current futures in the worker domain
323    /// This include futures spawned via `worker.track`
324    #[must_use]
325    pub fn task_count(&self) -> usize {
326        #[cfg(feature = "task-context")]
327        {
328            self.tasks.len()
329        }
330
331        #[cfg(not(feature = "task-context"))]
332        self.tasks.load(Ordering::SeqCst)
333    }
334
335    /// Checks whether the worker has pending tasks
336    #[must_use]
337    pub fn has_pending_tasks(&self) -> bool {
338        self.task_count() > 0
339    }
340
341    /// Is the shutdown token called
342    #[must_use]
343    pub fn is_shutting_down(&self) -> bool {
344        self.is_stopped() || self.shutdown.as_ref().is_some_and(|s| s.is_shutting_down())
345    }
346
347    /// Get the current worker state
348    #[must_use]
349    pub fn state(&self) -> &str {
350        self.state.as_str()
351    }
352
353    /// Emits an event to the worker's event handler
354    pub(crate) fn emit_event(&self, event: &Event) {
355        self.emit_ref(event);
356    }
357
358    /// Emits a [`Event::Custom`] to the worker's event handler
359    pub fn emit<T: Send + Sync + 'static>(&self, data: T) {
360        self.emit_ref(&Event::custom(data));
361    }
362
363    fn emit_ref(&self, event: &Event) {
364        let handler = self.event_handler.as_ref();
365        handler(self, event);
366    }
367
368    /// Calls a method to signify a heartbeat with the worker
369    pub fn heartbeat(&self, cx: &mut Context<'_>) {
370        self.register_waker(cx);
371        self.emit_ref(&Event::HeartBeat);
372        // Mark the worker as ready/alive.
373        self.is_ready.store(true, Ordering::SeqCst);
374    }
375
376    /// Wraps the event listener with a new function
377    pub(crate) fn add_listener<F: Fn(&Self, &Event) + Send + Sync + 'static>(&mut self, f: F) {
378        let cur = self.event_handler.clone();
379        let new: RawEventListener = Box::new(move |ctx, ev| {
380            f(ctx, ev);
381            cur(ctx, ev);
382        });
383        self.event_handler = Arc::new(new);
384    }
385
386    /// Register the current waker for the worker
387    ///
388    /// This is used to wake the worker when tasks complete or shutdown is triggered.
389    pub(crate) fn register_waker(&self, cx: &Context<'_>) {
390        if let Ok(mut guard) = self.waker.lock() {
391            if guard
392                .as_ref()
393                .is_none_or(|stored| !stored.will_wake(cx.waker()))
394            {
395                *guard = Some(cx.waker().clone());
396            }
397        }
398    }
399
400    pub(crate) fn wake(&self) {
401        if let Ok(waker) = self.waker.lock() {
402            if let Some(waker) = &*waker {
403                waker.wake_by_ref();
404            }
405        }
406    }
407
408    /// Register the [`ExecutionContext`] to get the [`TaskContext`]
409    #[cfg(feature = "task-context")]
410    pub(super) fn register_task(
411        &self,
412        ctx: &Arc<ExecutionContext>,
413    ) -> Result<TaskContext, TaskLifecycleError> {
414        let tasks = &self.tasks;
415        let task_id = ctx
416            .task_id()
417            .ok_or(TaskLifecycleError::MissingTaskId)?
418            .to_string();
419
420        if tasks.contains(task_id.as_str()) {
421            return Err(TaskLifecycleError::Duplicate);
422        }
423
424        let token = TaskContext::new(ctx);
425        tasks.insert(token.clone());
426        Ok(token)
427    }
428
429    #[cfg(not(feature = "task-context"))]
430    pub(super) fn register_task(
431        &self,
432        _: &Arc<ExecutionContext>,
433    ) -> Result<(), TaskLifecycleError> {
434        self.tasks.fetch_add(1, Ordering::SeqCst);
435        Ok(())
436    }
437
438    /// Cancel a specific task, if it's tracked.
439    #[cfg(feature = "task-context")]
440    pub fn cancel_task(&self, context: &TaskContext) -> Result<(), TaskStateError> {
441        if let Some(token) = &self.tasks.get(context) {
442            token.cancel()
443        } else {
444            Err(TaskStateError::TaskNotFound)
445        }
446    }
447
448    /// Remove the token once the task completes, to avoid unbounded growth.
449    #[cfg(feature = "task-context")]
450    pub(super) fn remove_task(&self, ctx: &TaskContext) -> Result<(), TaskStateError> {
451        let task_id = ctx.task_id();
452        self.tasks
453            .remove(task_id)
454            .ok_or(TaskStateError::TaskNotFound)?;
455        Ok(())
456    }
457
458    /// Remove the token once the task completes, to avoid unbounded growth.
459    #[cfg(not(feature = "task-context"))]
460    #[allow(clippy::trivially_copy_pass_by_ref)]
461    pub(super) fn remove_task(&self, _: &()) -> Result<(), WorkerError> {
462        self.tasks.fetch_sub(1, Ordering::SeqCst);
463        Ok(())
464    }
465
466    /// Extracts the [`TaskContext`] from the [`WorkerContext`]
467    #[cfg(feature = "task-context")]
468    pub(crate) fn get_task_context(
469        &self,
470        ctx: &Arc<ExecutionContext>,
471    ) -> Result<TaskContext, TaskStateError> {
472        self.get_task(ctx.task_id().unwrap().to_string().as_str())
473    }
474
475    /// Get the task context for a task attached to a worker
476    #[cfg(feature = "task-context")]
477    pub fn get_task(&self, task_id: &str) -> Result<TaskContext, TaskStateError> {
478        Ok(self
479            .tasks
480            .get(task_id)
481            .ok_or(TaskStateError::TaskNotFound)?
482            .clone())
483    }
484
485    /// Remove any completed tasks
486    #[cfg(feature = "task-context")]
487    pub fn cleanup(&self) -> Result<(), TaskStateError> {
488        let tasks = &self.tasks;
489        tasks.retain(|token| !(token.is_completed() && token.is_empty()));
490        Ok(())
491    }
492
493    /// Get the context of each running task
494    #[cfg(feature = "task-context")]
495    pub fn tasks(&self) -> Result<Vec<TaskContext>, TaskStateError> {
496        let tasks = &self.tasks;
497        Ok(tasks.iter().map(|s| s.clone()).collect())
498    }
499
500    /// Returns the amount of time elapsed since this worker started.
501    #[must_use]
502    pub fn elapsed(&self) -> Duration {
503        self.instant.elapsed()
504    }
505
506    /// Returns the number of times the worker has been restated:
507    ///
508    /// See also [`Monitor::should_restart`]
509    ///
510    /// [`Monitor::should_restart`]: crate::monitor::Monitor::should_restart
511    #[must_use]
512    pub fn restarts(&self) -> usize {
513        self.restarts.load(Ordering::SeqCst)
514    }
515
516    /// This forces a shutting down worker to exit.
517    pub fn kill(&mut self) -> Result<(), WorkerError> {
518        if !self.is_shutting_down() {
519            return Err(WorkerError::StateError(WorkerStateError::InvalidState(
520                "Worker is not shutting down".to_owned(),
521            )));
522        }
523        #[cfg(feature = "task-context")]
524        if self.task_count() != 0 {
525            self.tasks()
526                .map_err(|e| {
527                    WorkerError::StateError(WorkerStateError::InvalidState(e.to_string()))
528                })?
529                .into_iter()
530                .map(|a| a.cancel())
531                .collect::<Result<Vec<_>, _>>()
532                .map_err(|e| {
533                    WorkerError::StateError(WorkerStateError::InvalidState(e.to_string()))
534                })?;
535        }
536        self.state
537            .store(InnerWorkerState::Terminated, Ordering::SeqCst);
538        self.wake();
539        Ok(())
540    }
541}
542
543impl From<&str> for WorkerContext {
544    fn from(name: &str) -> Self {
545        Self::new(name)
546    }
547}
548
549impl From<String> for WorkerContext {
550    fn from(name: String) -> Self {
551        Self::new(&name)
552    }
553}
554
555impl From<&Self> for WorkerContext {
556    fn from(context: &Self) -> Self {
557        context.clone()
558    }
559}
560
561impl<Args: Sync> FromRequest<Task<Args>> for WorkerContext {
562    type Error = MissingDataError;
563    async fn from_request(task: &Task<Args>) -> Result<Self, Self::Error> {
564        task.data().get_checked().cloned()
565    }
566}
567
568impl Drop for WorkerContext {
569    fn drop(&mut self) {
570        if Arc::strong_count(&self.state) > 1 {
571            // There are still other references to this context, so we shouldn't log a warning.
572            return;
573        }
574        if self.is_running() && self.has_pending_tasks() {
575            error!(
576                "Worker '{}' is being dropped while running with `{}` tasks. Consider calling stop() before dropping.",
577                self.name(),
578                self.task_count()
579            );
580        }
581    }
582}
583
584#[cfg(test)]
585mod tests {
586
587    use futures_util::FutureExt;
588
589    use crate::{
590        backend::memory::MemoryStorage, error::BoxDynError, worker::builder::WorkerBuilder,
591    };
592    use std::time::Duration;
593
594    use super::*;
595
596    #[tokio::test]
597    async fn test_worker_state_transitions() {
598        let backend = MemoryStorage::<u32>::new();
599
600        let ctx = WorkerContext::new("test-worker");
601
602        let worker = WorkerBuilder::new(&ctx)
603            .backend(backend)
604            .build(|_task: u32| async { Ok::<_, BoxDynError>(()) });
605
606        let worker_handle = tokio::spawn(async move { worker.run().boxed().await });
607        tokio::time::sleep(Duration::from_millis(50)).await;
608
609        // Initial state: worker should be running
610        assert!(ctx.is_running());
611        assert!(!ctx.is_shutting_down());
612        assert!(!ctx.is_stopped());
613
614        // Pause the worker
615        ctx.pause().unwrap();
616        assert!(ctx.is_paused());
617        assert!(
618            !ctx.is_shutting_down(),
619            "Paused worker should NOT be considered shutting down"
620        );
621
622        // Resume the worker
623        ctx.resume().unwrap();
624        assert!(ctx.is_running());
625        assert!(!ctx.is_paused());
626
627        // Stop the worker
628        ctx.stop().unwrap();
629        assert!(ctx.is_stopped());
630        assert!(ctx.is_shutting_down());
631
632        // Try to resume a stopped worker (should fail with NotPaused error since state is Stopped)
633        assert!(
634            matches!(
635                ctx.resume(),
636                Err(WorkerError::StateError(WorkerStateError::NotPaused))
637            ),
638            "Resuming a stopped worker should fail with NotPaused error"
639        );
640
641        worker_handle.await.unwrap().unwrap();
642    }
643}