Module context

Module context 

Source
Expand description

Worker context and task tracking.

WorkerContext is responsible for managing the execution lifecycle of a worker, tracking tasks, handling shutdown, and emitting lifecycle events. It also provides Tracked for wrapping and monitoring asynchronous tasks within the worker domain.

§Lifecycle

A WorkerContext goes through distinct phases of operation:

The WorkerContext itself implements Future, and can be .awaited — it resolves once the worker is shut down and all tasks have completed.

§Task Management

Asynchronous tasks can be tracked using WorkerContext::track, which wraps a future in a Tracked type. This ensures:

  • Task count is incremented before execution and decremented on completion
  • Shutdown is automatically triggered once all tasks are done

Use task_count and has_pending_tasks to inspect ongoing task state.

§Shutdown Semantics

The worker is considered shutting down if:

  • stop() has been called
  • A shutdown signal (if configured) has been triggered

Once shutdown begins, no new tasks should be accepted. Internally, a stored Waker is used to drive progress toward shutdown completion.

§Event Handling

Worker lifecycle events (e.g., Start, Stop) can be emitted using WorkerContext::emit. Custom handlers can be registered via WorkerContext::wrap_listener to hook into these transitions.

§Request Integration

WorkerContext implements FromRequest so it can be extracted automatically in request handlers when using a compatible framework or service layer.

§Types

  • WorkerContext — shared state container for a worker
  • Tracked — future wrapper for task lifecycle tracking

Structs§

Tracked
A future tracked by the worker
WorkerContext
Utility for managing a worker’s context