Core API#
Configuration#
- litestar_queues.config.STALE_REQUEUE_PRIORITY: Literal['preserve'] | int | Callable[[int], int] = 'preserve'#
recovered work keeps the priority it was enqueued with.
- Type:
Default stale-requeue policy
- litestar_queues.config.ExecutionBackendConfig = str | litestar_queues.config.ExecutionBackendConfigProtocol#
Type alias for execution backend selectors.
- class litestar_queues.config.ExecutionBackendConfigProtocol(*args, **kwargs)[source]#
Bases:
ProtocolProtocol for typed execution backend configuration objects.
- __init__(*args, **kwargs)#
- class litestar_queues.config.MigrationConfiguringBackend(*args, **kwargs)[source]#
Bases:
ProtocolBackend config that registers its own migrations during plugin init.
A backend owns whatever application wiring its storage needs.
QueuePluginonly asks whether the configured backend provides this hook, so selecting one backend never imports another backend’s package – or requires its extra to be installed.- configure_migrations(config: QueueConfig) None[source]#
Register backend-owned migrations with the application.
- __init__(*args, **kwargs)#
- litestar_queues.config.QueueBackendConfig = str | litestar_queues.config.QueueBackendConfigProtocol#
Type alias for queue backend selectors.
- class litestar_queues.config.QueueBackendConfigProtocol(*args, **kwargs)[source]#
Bases:
ProtocolProtocol for typed queue backend configuration objects.
- __init__(*args, **kwargs)#
- class litestar_queues.config.QueueConfig(namespace: str = 'litestar_queues', queue_backend: QueueBackendConfig = 'ephemeral', execution_backend: ExecutionBackendConfig = 'local', task_dependency_resolver: TaskDependencyResolver | None = None, task_dependency_provider: TaskDependencyProvider | None = None, error_sanitizer: TaskErrorSanitizer | None = None, worker: WorkerConfig = <factory>, service_dependency_key: str | None = None, events_dependency_key: str | None = None, events: QueueEventsConfig | None = None, observability: ObservabilityConfig | None = None, task_modules: tuple[str, ...] = (), initialize_schedules: bool = True, log_success: bool = False, sync_thread_pool_size: int = <factory>, sync_thread_name_prefix: str | None = None, scheduler_canary_task: str | None = None, maintenance: QueueMaintenanceConfig | None = None, max_argument_identity_bytes: int | None = None, stale_requeue_priority: StaleRequeuePriority = 'preserve')[source]#
Bases:
objectConfiguration for QueuePlugin.
- queue_backend: QueueBackendConfig#
Queue-record persistence backend selector or typed backend configuration.
- execution_backend: ExecutionBackendConfig#
Default placement backend used to execute claimed tasks.
- task_dependency_resolver: TaskDependencyResolver | None#
Per-attempt dependency resolver;
Noneinjects no additional task keyword arguments.
- __init__(namespace: str = 'litestar_queues', queue_backend: QueueBackendConfig = 'ephemeral', execution_backend: ExecutionBackendConfig = 'local', task_dependency_resolver: TaskDependencyResolver | None = None, task_dependency_provider: TaskDependencyProvider | None = None, error_sanitizer: TaskErrorSanitizer | None = None, worker: WorkerConfig = <factory>, service_dependency_key: str | None = None, events_dependency_key: str | None = None, events: QueueEventsConfig | None = None, observability: ObservabilityConfig | None = None, task_modules: tuple[str, ...] = (), initialize_schedules: bool = True, log_success: bool = False, sync_thread_pool_size: int = <factory>, sync_thread_name_prefix: str | None = None, scheduler_canary_task: str | None = None, maintenance: QueueMaintenanceConfig | None = None, max_argument_identity_bytes: int | None = None, stale_requeue_priority: StaleRequeuePriority = 'preserve') None#
- task_dependency_provider: TaskDependencyProvider | None#
Per-attempt dependency scope;
Noneopens no scope around the task body.Mutually exclusive with
task_dependency_resolver. Use the resolver for stateless keyword arguments and the provider when the attempt must own a resource that has to be released on every outcome.
- error_sanitizer: TaskErrorSanitizer | None#
Persisted task-error formatter;
Nonestores the default exception representation.
- worker: WorkerConfig#
Shared configuration for in-app and standalone workers.
- service_dependency_key: str | None#
Litestar dependency key for the injected queue service;
Nonederives it from the namespace.
- events_dependency_key: str | None#
Litestar dependency key for the event producer;
Nonederives it from the namespace.
- events: QueueEventsConfig | None#
Task-event capabilities;
Nonedisables delivery, streams, and history.
- observability: ObservabilityConfig | None#
Package telemetry configuration;
Nonedisables the observability runtime.
- initialize_schedules: bool#
Whether application startup synchronizes registered recurring schedules.
- sync_thread_pool_size: int#
Maximum threads running synchronous tasks concurrently.
Defaults to the cgroup-aware effective CPU count plus four, capped at 32. Threads are created on demand, so this is a ceiling rather than a startup cost.
- sync_thread_name_prefix: str | None#
Thread-name prefix for synchronous tasks;
Nonederives it from the namespace.
- scheduler_canary_task: str | None#
Scheduler-health task name;
Nonederives the package-owned default.
- maintenance: QueueMaintenanceConfig | None#
Automatic maintenance policy;
Nonedisables the maintenance loop.
- max_argument_identity_bytes: int | None#
Maximum canonical argument-identity size in bytes;
Nonedisables the bound.
- stale_requeue_priority: StaleRequeuePriority#
Priority applied to stale-recovered work; see
StaleRequeuePriority.
- names: QueueNamespace#
Validated format-specific runtime-name renderer.
- property signature_namespace: dict[str, Any]#
Names Litestar must resolve that an application cannot supply itself.
This carries only the types named in this package’s own dependency providers.
provide_service_dependencyandprovide_event_producer_dependencyannotate their return types as strings while importing those types underTYPE_CHECKING, so Litestar needs them here to resolve the injectedqueue_serviceandqueue_eventsdependencies.Nothing else belongs here. Config, backend, worker, and event types are named in application setup code, not in handler signatures, and a handler that does annotate one has already imported it. Registering the whole public API instead made
QueuePlugin.on_app_initimport every installed adapter on every application startup, which defeated the package’s lazy-import boundary and charged applications for extras they never selected.
- property observability_runtime_state_key: str#
Litestar state key holding the observability runtime.
- get_service(state: State | None = None) QueueService[source]#
Return a QueueService for this configuration.
- get_queue_backend() BaseQueueBackend[source]#
Return a configured queue backend instance.
- get_execution_backend() BaseExecutionBackend[source]#
Return a configured execution backend instance.
- get_event_publisher(*, channels_backend: ChannelsLike | None = None, manage_channels_lifecycle: bool = False) QueueEventPublisher[source]#
Return a configured queue event publisher.
- Parameters:
channels_backend – Fallback live sink target used only when
QueueEventsConfig.channelsis unset.QueuePluginpasses the app’s registeredChannelsPluginhere so event delivery needs no manual channel wiring.manage_channels_lifecycle – Whether the publisher owns the resolved Channels target lifecycle.
- async provide_service_dependency(state: State) AsyncIterator['QueueService'][source]#
Yield the application-scoped QueueService for Litestar dependency injection.
- async provide_event_producer_dependency(state: State) AsyncIterator[QueueEventProducer][source]#
Yield the application-scoped QueueEventProducer for Litestar dependency injection.
- class litestar_queues.config.QueueNamespace(root: str = 'litestar_queues')[source]#
Bases:
objectValidated root for package-owned runtime identifiers.
- coordination(*parts: str) str[source]#
Render a distributed coordination name with legacy compatibility.
- litestar_queues.config.StaleRequeuePriority#
Priority policy applied to work recovered by the stale sweep.
"preserve"keeps the original priority, anintis a ceiling clamp, and a callable maps the current priority to the recovered one.
- class litestar_queues.config.TaskDependencyProvider(*args, **kwargs)[source]#
Bases:
ProtocolPer-attempt async context manager supplying task keyword arguments.
The queue enters this scope inside the attempt timeout, merges the yielded mapping into the task’s keyword arguments, and awaits
__aexit__exactly once for every attempt outcome: success, retryable failure, terminal failure, timeout, cancellation, claim loss, and shutdown interruption.__aexit__receivesasyncio.CancelledErrorfor timeout, cancellation, claim loss, and shutdown alike, because all four reach the attempt as a coroutine cancellation. Readrecordandcontextto distinguish outcomes; never the exception type. A truthy__aexit__return value is ignored: this is a resource scope, not an exception filter.An implementation that also owns process-level state may expose
open()andclose()(synchronous or asynchronous);QueueServiceincludes them in its own lifecycle and partial-open rollback.- __init__(*args, **kwargs)#
- litestar_queues.config.TaskDependencyResolver#
User-supplied callable that resolves extra kwargs for a task before execution.
- litestar_queues.config.TaskErrorSanitizer#
User-supplied callable that converts task exceptions into persisted error messages.
- class litestar_queues.config.WorkerConfig(placement: ~typing.Literal['server', 'asgi', 'external'] = 'server', id: str | None = None, batch_size: int = 10, poll_interval: float = 0.1, poll_backoff_max: float | None = 30.0, poll_backoff_multiplier: float = 2.0, poll_jitter: float = 0.15, max_concurrency: int = 1, queue_concurrency: ~collections.abc.Mapping[str, int] = <factory>, heartbeat_interval: float = 30, heartbeat_jitter_fraction: float = 0.1, heartbeat_miss_threshold: int = 2, cancel_on_claim_loss: bool = True, cancellation_poll_interval: float = 1.0, reconcile_interval: float = 30, stale_after: float | None = None, stale_check_interval: float = 60.0, expiry_check_interval: float | None = 60.0, graceful_shutdown_timeout: float = 30, final_cancel_timeout: float = 5, hard_exit_timeout: float | None = 10.0, requeue_on_shutdown: bool = False, max_interruptions: int = 3, startup_timeout: float = 30, queues: tuple[str, ...] = ())[source]#
Bases:
objectConfiguration shared by in-app and standalone workers.
- placement: Literal['server', 'asgi', 'external']#
Which process owns this worker; see
WorkerPlacement.
- poll_backoff_max: float | None#
Maximum adaptive polling interval in seconds;
Nonedisables backoff.
- cancel_on_claim_loss: bool#
Whether heartbeat claim loss cancels the locally running coroutine.
Writes are already fenced on the claim, but side effects are not: while a lost claim keeps running, a replacement worker executes the same record. Cancelling closes that duplicate-execution window. Set to
Falseto let a lost attempt run to completion and have its terminal write rejected.
- cancellation_poll_interval: float#
Interval between durable running-cancellation reconciliation passes.
- expiry_check_interval: float | None#
Interval between pending-job expiration passes;
Nonedisables sweeps.
- hard_exit_timeout: float | None#
Wall-clock budget from forced shutdown to process exit;
Nonedisables the watchdog.
- max_interruptions: int#
Shutdown requeues an attempt may absorb before interruptions consume the retry budget.
- __init__(placement: ~typing.Literal['server', 'asgi', 'external'] = 'server', id: str | None = None, batch_size: int = 10, poll_interval: float = 0.1, poll_backoff_max: float | None = 30.0, poll_backoff_multiplier: float = 2.0, poll_jitter: float = 0.15, max_concurrency: int = 1, queue_concurrency: ~collections.abc.Mapping[str, int] = <factory>, heartbeat_interval: float = 30, heartbeat_jitter_fraction: float = 0.1, heartbeat_miss_threshold: int = 2, cancel_on_claim_loss: bool = True, cancellation_poll_interval: float = 1.0, reconcile_interval: float = 30, stale_after: float | None = None, stale_check_interval: float = 60.0, expiry_check_interval: float | None = 60.0, graceful_shutdown_timeout: float = 30, final_cancel_timeout: float = 5, hard_exit_timeout: float | None = 10.0, requeue_on_shutdown: bool = False, max_interruptions: int = 3, startup_timeout: float = 30, queues: tuple[str, ...] = ()) None#
- litestar_queues.config.WorkerPlacement#
Which process owns the queue worker.
serverThe Litestar CLI server lifespan owns exactly one fresh worker process per
litestar runinvocation. This is the default.asgiEach ASGI worker owns one queue worker inside its own application lifespan. Deliberately multiplicative with the web-worker count.
externalNothing is started automatically; a separate process manager runs
litestar queues run, or the caller executes tasks inline.
alias of
Literal[‘server’, ‘asgi’, ‘external’]
- litestar_queues.config.execution_backend_name(backend: str | ExecutionBackendConfigProtocol) str[source]#
Return the registered execution backend name for a selector.
- litestar_queues.config.queue_backend_name(backend: str | QueueBackendConfigProtocol) str[source]#
Return the registered queue backend name for a selector.
Service#
- class litestar_queues.service.QueueService(config: QueueConfig, *, queue_backend: BaseQueueBackend | None = None, execution_backend: BaseExecutionBackend | None = None, event_publisher: QueueEventPublisher | None = None, observability_runtime: QueueObservabilityRuntimeProtocol | None = None)[source]#
Bases:
objectHigh-level facade for queue and execution backends.
- __init__(config: QueueConfig, *, queue_backend: BaseQueueBackend | None = None, execution_backend: BaseExecutionBackend | None = None, event_publisher: QueueEventPublisher | None = None, observability_runtime: QueueObservabilityRuntimeProtocol | None = None) None[source]#
Initialize the queue service.
- property config: QueueConfig#
Queue configuration.
- get_queue_backend() BaseQueueBackend[source]#
Return the configured queue backend.
- get_execution_backend() BaseExecutionBackend[source]#
Return the configured execution backend.
- get_event_publisher() QueueEventPublisher[source]#
Return the configured event publisher.
- get_event_producer() QueueEventProducer[source]#
Return a producer over this service’s event publisher.
- get_event_log() QueueEventLog | None[source]#
Return the backend-owned durable event history, if configured.
History is wired during
open()only whenevents.historyis present; otherwise this returnsNoneand history maintenance is a no-op.
- property observability_runtime: QueueObservabilityRuntimeProtocol#
Return the configured observability runtime.
- async open() Self[source]#
Open queue and execution backends.
If the configured task dependency provider exposes an
open()method, it is called first. If the provider fails to open, it will not be closed.- Returns:
The opened service.
- async enqueue(task: str | Task[Any, Any], *args: Any, scheduled_at: datetime | None = None, run_after: float | timedelta | None = None, expires_in: float | timedelta | None = None, expires_at: datetime | None = None, key: str | None = None, queue: str | None = None, priority: int | None = None, retries: int | None = None, timeout: float | None = None, execution_backend: str | None = None, execution_profile: str | None = None, description: str | None = None, log_level: str | None = None, log_success: bool | None = None, requeue_on_stale: bool | None = None, metadata: dict[str, Any] | None = None, **kwargs: Any) TaskResult[source]#
Enqueue a registered task.
- Returns:
A result handle for the queued record.
- resolve_task(task: str | Task[Any, Any]) Task[Any, Any][source]#
Resolve a task name or wrapper to a registered task.
- Returns:
The registered task wrapper.
- Raises:
KeyError – If a task name is not registered.
- async get_task(task_id: UUID) QueuedTaskRecord | None[source]#
Return a queued task record by ID.
- async get_statistics(*, queue: str | None = None) QueueStatistics[source]#
Return global or queue-scoped task status counts.
- async cancel_task(task_id: UUID, *, include_running: bool = False) bool[source]#
Cancel one queued task and publish its terminal lifecycle event.
- Parameters:
task_id – Identifier of the task to cancel.
include_running – Whether a running task may transition to cancelled.
- Returns:
Trueonly for the caller that wins the durable state transition.
- async interrupt_task(record: QueuedTaskRecord, *, worker_id: str, reason: str = 'shutdown', max_interruptions: int | None = None) QueuedTaskRecord | None[source]#
Requeue one owned running attempt after local execution unwinds.
An attempt that keeps being interrupted would otherwise cycle forever without ever consuming its retry budget, so at
max_interruptionsthe interruption is routed through the ordinary retry policy instead.- Returns:
The requeued or failed record, or
Nonewhen the fence was lost.
- async reset_task_identity(key: str) bool[source]#
Delete a
unique_until="forever"reservation by its exact effective key.This is the only supported way to allow a forever identity to be enqueued again. It never infers or resets an identity from raw arguments; the caller must pass the exact effective key (for example the
lq:u:v1:...value or the configured/explicit key).- Returns:
Truewhen a reservation was removed.
- async get_task_identity(key: str) TaskReservation | None[source]#
Return the forever reservation owning an identity key, if any.
- async execute_record(record: QueuedTaskRecord, *, worker_id: str | None = None) QueuedTaskRecord[source]#
Execute a claimed queue record and persist the lifecycle result.
- Parameters:
record – The claimed queue record to execute.
worker_id – Identity of the worker driving execution, if any. The value is forwarded to
TaskExecutionContext.worker_idso published events carry stable worker provenance. Service-driven executions (no worker) leave this asNone.
- Returns:
The updated queue record.
- Raises:
asyncio.CancelledError – If task execution is cancelled.
- async reconcile_external(limit: int | None = None) int[source]#
Reconcile externally dispatched records against their executor.
A bounded call first asks the configured backend to repair deliveries its transport lost, then spends what is left of the budget on ordinary reconciliation, so one maintenance pass stays finite however the two divide the work. The worker’s unbounded sweep skips repair: it has no ceiling to respect, and repair is a maintenance responsibility.
- Parameters:
limit – When provided, examine at most this many external records across both halves.
Nonereconciles every outstanding external record and repairs nothing.- Returns:
Number of records repaired or brought to a terminal queue status.
- async recover_stale_tasks(*, stale_after: timedelta, worker_id: str | None = None, limit: int | None = None) StaleTaskRecoveryResult[source]#
Recover stale running tasks and publish a worker summary event.
- Parameters:
stale_after – Heartbeat age past which a running task is stale.
worker_id – Identity attached to published recovery events.
limit – When provided, recover at most this many records in one bounded batch.
Nonepreserves the unbounded worker behavior.
- Returns:
Summary of recovered, failed, skipped, and handler-needed tasks.
- async expire_overdue_tasks(*, limit: int | None = None, worker_id: str | None = None) list[QueuedTaskRecord][source]#
Expire overdue pending or scheduled records and publish one event each.
- Returns:
Records transitioned to
expired.
- async claim_tasks(*, limit: int, queues: tuple[str, ...] = (), execution_backend: str | None = None, worker_id: str | None = None, queue_limits: Mapping[str, int] | None = None) list[QueuedTaskRecord][source]#
Claim due tasks and publish events for claim-time expirations.
- Returns:
Records successfully transitioned to
running.
- async claim_task(task_id: UUID, *, worker_id: str | None = None, expected_retry_count: int | None = None, expected_execution_ref: str | None = None) tuple[QueuedTaskRecord | None, QueuedTaskRecord | None][source]#
Claim one task and publish its claim-time expiration event.
- Returns:
The claimed record and the expired record, at most one of which is set.
- async initialize_schedules() list[QueuedTaskRecord][source]#
Create queue records for registered recurring schedules.
- Returns:
The created or reused schedule records.
- async publish_claim_lost(record: QueuedTaskRecord, *, phase: str, task_context: TaskExecutionContext | None = None, worker_id: str | None = None, expected_retry_count: int | None = None) QueuedTaskRecord[source]#
Publish an ownership-loss event and return the current record state.
- Returns:
Current queue task record state.
Maintenance#
Bounded, backend-neutral queue maintenance.
The maintenance service runs a small, predictable amount of repair and retention work under token-fenced distributed coordination and a wall-clock time budget, then returns. It never starts a worker, executes due work, or loops to drain a backlog. Phases always run in the fixed order external-execution reconciliation, stale-running recovery, terminal-task retention, and durable-event retention.
- litestar_queues.maintenance.MaintenancePhase#
One bounded maintenance phase, in fixed execution order.
alias of
Literal[‘external’, ‘stale’, ‘terminal’, ‘events’]
- litestar_queues.maintenance.MaintenancePhaseStatus#
Outcome of a single maintenance phase.
alias of
Literal[‘completed’, ‘skipped’, ‘failed’, ‘partial’]
- class litestar_queues.maintenance.QueueMaintenanceConfig(time_budget: float = 300.0, coordination_timeout: float = 360.0, external_limit: int = 100, stale_after: float | None = None, stale_limit: int = 100, terminal_retention: float | None = None, terminal_limit: int = 1000, event_retention_rules: tuple[QueueEventRetentionRule, ...] = (), event_limit: int = 1000)[source]#
Bases:
objectBounded maintenance thresholds and limits.
Durations and retention values are seconds. Every limit and duration must be positive and
coordination_timeoutmust exceedtime_budgetso ownership outlives the whole run.stale_after,terminal_retention, andevent_retention_rulesdefault toNone(or empty) which disables their phase; there are no destructive defaults.- event_retention_rules: tuple[QueueEventRetentionRule, ...]#
Ordered event-history retention rules; empty disables the events phase.
Rules are evaluated in order and the first rule whose
matchmatches a record decides that record’s retention age. A record matching no rule is never deleted.
- __init__(time_budget: float = 300.0, coordination_timeout: float = 360.0, external_limit: int = 100, stale_after: float | None = None, stale_limit: int = 100, terminal_retention: float | None = None, terminal_limit: int = 1000, event_retention_rules: tuple[QueueEventRetentionRule, ...] = (), event_limit: int = 1000) None#
- class litestar_queues.maintenance.QueueMaintenancePhaseResult(phase: Literal['external', 'stale', 'terminal', 'events'], status: Literal['completed', 'skipped', 'failed', 'partial'], changed: int = 0, duration_ms: float = 0.0, error: str | None = None)[source]#
Bases:
objectResult of one bounded maintenance phase.
- class litestar_queues.maintenance.QueueMaintenanceService(service: QueueService, config: QueueMaintenanceConfig, *, monotonic: Callable[[], float] = <built-in function perf_counter>, utcnow: Callable[[], datetime] = <function _default_utcnow>)[source]#
Bases:
objectRun bounded maintenance phases under token-fenced coordination and a time budget.
- __init__(service: QueueService, config: QueueMaintenanceConfig, *, monotonic: Callable[[], float] = <built-in function perf_counter>, utcnow: Callable[[], datetime] = <function _default_utcnow>) None[source]#
Initialize the maintenance service.
- Parameters:
service – An opened queue service whose backend advertises
supports_maintenance.config – Bounded maintenance thresholds and limits.
monotonic – Injected monotonic clock for budget/duration accounting.
utcnow – Injected UTC clock used to compute stable retention cutoffs.
- async run(phases: Collection[MaintenancePhase] | None = None) QueueMaintenanceSummary[source]#
Claim maintenance ownership and run each selected phase once.
- Parameters:
phases – Optional narrowing of the phases to run. Filtering only narrows configuration; it never enables a disabled retention threshold.
Noneconsiders every phase in the fixed order.- Returns:
A summary whose outcome is
already_runningwhen ownership is denied,failedwhen any phase failed,partialwhen the budget skipped an enabled phase, elsecompleted.- Raises:
QueueConfigurationError – If a requested phase name is unknown or the backend does not support distributed maintenance coordination.
- class litestar_queues.maintenance.QueueMaintenanceSummary(outcome: ~typing.Literal['completed', 'failed', 'partial', 'already_running'], acquired: bool, duration_ms: float, phases: list[~litestar_queues.maintenance.QueueMaintenancePhaseResult] = <factory>)[source]#
Bases:
objectResult of a whole maintenance run.
- phases: list[QueueMaintenancePhaseResult]#
Tasks#
- class litestar_queues.task.RetryBackoff(initial_delay: float, multiplier: float = 1.0, max_delay: float | None = None)[source]#
Bases:
objectDelay policy applied when a task consumes a retry.
- class litestar_queues.task.ScheduleConfig(task_name: str, cron: str | None = None, interval: timedelta | int | float | None = None, timezone: str = 'UTC', initial_delay: timedelta | int | float = 0, jitter: timedelta | int | float = 0)[source]#
Bases:
objectConfiguration for a recurring task schedule.
- interval: timedelta | int | float | None#
Fixed interval as a duration or seconds;
Noneusescronscheduling.
- initial_delay: timedelta | int | float#
Delay before the first interval run as a duration or seconds.
- get_next_run(after: datetime | None = None, *, use_initial_delay: bool = False) datetime[source]#
Calculate the next scheduled run time.
- Returns:
The next run time in UTC.
- Raises:
ValueError – If no interval or cron expression is configured.
- copy_for_task(task_name: str) ScheduleConfig[source]#
Return this normalized schedule for another task name.
- class litestar_queues.task.Task(func: TaskCallable[P, T], *, name: str, queue: str = 'default', priority: int = 0, retries: int = 0, retry_backoff: float | RetryBackoff | None = None, timeout: float | None = None, execution_backend: str | None = None, execution_profile: str | None = None, key: str | None = None, unique_by: TaskUniqueBy | None = None, unique_until: TaskUniqueUntil = 'terminal', run_after: float | timedelta | None = None, expires_in: float | timedelta | None = None, description: str | None = None, log_level: str | None = None, log_success: bool | None = None, requeue_on_stale: bool | None = None, requeue_on_shutdown: bool | None = None, on_stale_failure: StaleFailureHandler | None = None, sync_to_thread: bool | None = None, actor: QueueEventActor | Callable[[], QueueEventActor] | None = None)[source]#
Bases:
Generic[P,T]Registered task wrapper with direct call and enqueue APIs.
- __init__(func: TaskCallable[P, T], *, name: str, queue: str = 'default', priority: int = 0, retries: int = 0, retry_backoff: float | RetryBackoff | None = None, timeout: float | None = None, execution_backend: str | None = None, execution_profile: str | None = None, key: str | None = None, unique_by: TaskUniqueBy | None = None, unique_until: TaskUniqueUntil = 'terminal', run_after: float | timedelta | None = None, expires_in: float | timedelta | None = None, description: str | None = None, log_level: str | None = None, log_success: bool | None = None, requeue_on_stale: bool | None = None, requeue_on_shutdown: bool | None = None, on_stale_failure: StaleFailureHandler | None = None, sync_to_thread: bool | None = None, actor: QueueEventActor | Callable[[], QueueEventActor] | None = None) None[source]#
- property retry_backoff: RetryBackoff | None#
Retry delay policy, if configured.
- property unique_by: Literal['task', 'arguments'] | None#
Identity source when no explicit or configured key is supplied.
- property unique_until: Literal['terminal', 'forever']#
terminal(default) orforever.- Type:
Identity lifetime
- property signature: Signature#
Cached call signature of the wrapped callable, computed once per task.
- property requeue_on_stale: bool#
Whether stale running records should be requeued when retries remain.
- property on_stale_failure: Callable[[QueuedTaskRecord], object | Awaitable[object]] | None#
Callback invoked after this task reaches terminal stale failure.
- property sync_to_thread: bool | None#
Whether a synchronous callable is offloaded to a worker thread.
Nonekeeps the safe default and offloads;Falseopts in to running inline on the event loop.
- property actor: QueueEventActor | Callable[[], QueueEventActor] | None#
Task-specific declared actor or actor resolver.
- async execute_record(record: QueuedTaskRecord, *, task_context: TaskExecutionContext | None = None, extra_kwargs: Mapping[str, object] | None = None, sync_executor: Executor | None = None) T[source]#
Execute this task for a queued record in worker context.
- Returns:
The wrapped callable result.
- metadata(values: dict[str, Any] | None = None) dict[str, Any][source]#
Return enqueue metadata for this task.
- using(*, queue: str | None = None, priority: int | None = None, retries: int | None = None, retry_backoff: float | RetryBackoff | None = None, timeout: float | None = None, execution_backend: str | None = None, execution_profile: str | None = None, key: str | None = None, unique_by: Literal['task', 'arguments'] | None = None, unique_until: Literal['terminal', 'forever'] | None = None, run_after: float | timedelta | None = None, expires_in: float | timedelta | None = None, description: str | None = None, log_level: str | None = None, log_success: bool | None = None, requeue_on_stale: bool | None = None, requeue_on_shutdown: bool | None = None, on_stale_failure: Callable[[QueuedTaskRecord], object | Awaitable[object]] | None = None, sync_to_thread: bool | None = None) Task[P, T][source]#
Return a configured copy with enqueue overrides.
- async enqueue(*args: ~typing.~P, **kwargs: ~typing.~P) TaskResult[source]#
Enqueue this task using the configured default service or fall back to an immediate service.
- Returns:
A result handle for the queued record.
- class litestar_queues.task.TaskResult(task_id: UUID, task_name: str, *, service: QueueService | None = None, record: QueuedTaskRecord | None = None)[source]#
Bases:
objectHandle to a queued task result.
- __init__(task_id: UUID, task_name: str, *, service: QueueService | None = None, record: QueuedTaskRecord | None = None) None[source]#
- property id: UUID#
Queue record ID.
- property record: QueuedTaskRecord | None#
Cached queue record.
- async refresh() Self[source]#
Refresh this handle from its queue service.
- Returns:
The refreshed result handle.
- Raises:
RuntimeError – If the result has no associated service.
- async wait(*, timeout: float | None = None, poll_interval: float = 0.1) Self[source]#
Wait until the task reaches a terminal status.
- Returns:
The completed result handle.
- Raises:
TimeoutError – If the timeout elapses before a terminal status.
RuntimeError – If the task no longer exists in the queue backend.
- litestar_queues.task.TaskUniqueBy#
the registered task name or the normalized call arguments.
- Type:
Identity source for task uniqueness
alias of
Literal[‘task’, ‘arguments’]
- litestar_queues.task.TaskUniqueUntil#
released at terminal (the default) or retained by a reservation.
- Type:
Identity lifetime for task uniqueness
alias of
Literal[‘terminal’, ‘forever’]
- litestar_queues.task.discover_tasks(package: str, subpackage: str = 'jobs', *, force_reload: bool = False) tuple[str, ...][source]#
Walk
packageand import every<package>.<...>.<subpackage>.<...>module.Adopters with
app.domain.<x>.jobs/layouts can call this once at startup so@task-decorated callables register without having to enumerateQueueConfig.task_modulesby hand.- Parameters:
package – Dotted package name to walk (e.g.
"app.domain").subpackage – Path segment that marks task modules. Any module whose dotted path (excluding the root) contains this segment is imported. Defaults to
"jobs".force_reload – Re-import modules already in
sys.modules.
- Returns:
Sorted, deduplicated tuple of task names registered after the walk.
- Raises:
ModuleNotFoundError – If
packagecannot be imported, or if it resolves to a plain module rather than a package.
- litestar_queues.task.get_default_service() QueueService | None[source]#
Return the global default QueueService instance.
- litestar_queues.task.get_scheduled_tasks() dict[str, ScheduleConfig][source]#
Return the global scheduled task registry.
- litestar_queues.task.get_task_registry() dict[str, Task[Any, Any]][source]#
Return the global task registry.
- litestar_queues.task.load_task_modules(modules: tuple[str, ...] | list[str], *, force_reload: bool = False) int[source]#
Import configured task modules so decorators register tasks.
- Returns:
Number of imported modules.
- litestar_queues.task.set_default_service(service: QueueService | None) None[source]#
Set the global default QueueService instance.
- litestar_queues.task.task(func: Callable[[P], Awaitable[T]], /) Task[P, T][source]#
- litestar_queues.task.task(func: Callable[[P], T], /) Task[P, T]
- litestar_queues.task.task(name: str | None = None, /, *, queue: str = 'default', priority: int = 0, retries: int = 0, retry_backoff: float | RetryBackoff | None = None, timeout: float | None = None, execution_backend: str | None = None, execution_profile: str | None = None, key: str | None = None, unique_by: Literal['task', 'arguments'] | None = None, unique_until: Literal['terminal', 'forever'] = 'terminal', run_after: float | timedelta | None = None, expires_in: float | timedelta | None = None, description: str | None = None, log_level: str | None = None, log_success: bool | None = None, requeue_on_stale: bool | None = None, requeue_on_shutdown: bool | None = None, on_stale_failure: Callable[[QueuedTaskRecord], object | Awaitable[object]] | None = None, sync_to_thread: bool | None = None, actor: QueueEventActor | Callable[[], QueueEventActor] | None = None, cron: str | None = None, interval: float | timedelta | None = None, timezone: str = 'UTC', initial_delay: float | timedelta = 0, jitter: float | timedelta = 0) Callable[[Callable[[...], Any]], Task[Any, Any]]
Register a callable as a queue task.
- Returns:
A task wrapper when used bare, otherwise a decorator.
- Raises:
ValueError – If both cron and interval are configured.
Models#
- litestar_queues.models.TERMINAL_STATUSES: frozenset[Literal['pending', 'scheduled', 'running', 'completed', 'failed', 'cancelled', 'expired']] = frozenset({'cancelled', 'completed', 'expired', 'failed'})#
Statuses that represent finished queue records.
- class litestar_queues.models.HeartbeatTouch(task_id: UUID, expected_retry_count: int | None, metadata_patch: dict[str, Any] | None = None)[source]#
Bases:
objectA fenced heartbeat update request for one running task.
- class litestar_queues.models.HeartbeatTouchResult(touched_task_ids: set[~uuid.UUID] = <factory>, missed_task_ids: set[~uuid.UUID] = <factory>)[source]#
Bases:
objectBackend-neutral result for a bulk heartbeat update.
- class litestar_queues.models.QueueBackendCapabilities(supports_worker_wakeups: bool = False, wakeup_backend: str | None = None, wakeups_durable: bool = False, supports_completion_events: bool = False, supports_maintenance: bool = False)[source]#
Bases:
objectBehavior advertised by a queue backend.
- class litestar_queues.models.QueueStatistics(pending: int = 0, scheduled: int = 0, running: int = 0, completed: int = 0, failed: int = 0, cancelled: int = 0, expired: int = 0)[source]#
Bases:
objectOperational status counts for a queue backend.
- class litestar_queues.models.QueuedTaskRecord(task_name: str, id: ~uuid.UUID = <factory>, args: tuple[~typing.Any, ...] = (), kwargs: dict[str, ~typing.Any] = <factory>, queue: str = 'default', execution_backend: str = 'local', execution_profile: str | None = None, execution_ref: str | None = None, worker_id: str | None = None, status: ~typing.Literal['pending', 'scheduled', 'running', 'completed', 'failed', 'cancelled', 'expired'] = 'pending', priority: int = 0, max_retries: int = 0, retry_count: int = 0, scheduled_at: ~datetime.datetime | None = None, expires_at: ~datetime.datetime | None = None, created_at: ~datetime.datetime = <factory>, queued_at: ~datetime.datetime = <factory>, started_at: ~datetime.datetime | None = None, completed_at: ~datetime.datetime | None = None, heartbeat_at: ~datetime.datetime | None = None, result: ~typing.Any | None = None, error: str | None = None, key: str | None = None, metadata: dict[str, ~typing.Any] = <factory>)[source]#
Bases:
objectBackend-neutral representation of a queued task.
- __init__(task_name: str, id: ~uuid.UUID = <factory>, args: tuple[~typing.Any, ...] = (), kwargs: dict[str, ~typing.Any] = <factory>, queue: str = 'default', execution_backend: str = 'local', execution_profile: str | None = None, execution_ref: str | None = None, worker_id: str | None = None, status: ~typing.Literal['pending', 'scheduled', 'running', 'completed', 'failed', 'cancelled', 'expired'] = 'pending', priority: int = 0, max_retries: int = 0, retry_count: int = 0, scheduled_at: ~datetime.datetime | None = None, expires_at: ~datetime.datetime | None = None, created_at: ~datetime.datetime = <factory>, queued_at: ~datetime.datetime = <factory>, started_at: ~datetime.datetime | None = None, completed_at: ~datetime.datetime | None = None, heartbeat_at: ~datetime.datetime | None = None, result: ~typing.Any | None = None, error: str | None = None, key: str | None = None, metadata: dict[str, ~typing.Any] = <factory>) None#
- class litestar_queues.models.StaleTaskRecoveryResult(requeued: int = 0, failed: int = 0, skipped: int = 0, handler_needed: int = 0, failed_task_ids: list[~uuid.UUID] = <factory>, handler_needed_task_ids: list[~uuid.UUID] = <factory>)[source]#
Bases:
objectSummary of stale running task recovery.
- class litestar_queues.models.TaskRequest(task_name: str, args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, queue: str = 'default', priority: int = 0, max_retries: int = 0, scheduled_at: datetime | None = None, expires_at: datetime | None = None, key: str | None = None, execution_backend: str = 'local', execution_profile: str | None = None, metadata: dict[str, Any] | None = None)[source]#
Bases:
objectA task submission for bulk enqueue via
enqueue_many.Carries the task name and enqueue arguments needed to submit one item in a batch. The backend returns the resulting queue records in request order.
- __init__(task_name: str, args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, queue: str = 'default', priority: int = 0, max_retries: int = 0, scheduled_at: datetime | None = None, expires_at: datetime | None = None, key: str | None = None, execution_backend: str = 'local', execution_profile: str | None = None, metadata: dict[str, Any] | None = None) None#
- class litestar_queues.models.TaskReservation(key: str, task_id: UUID, task_name: str, created_at: datetime)[source]#
Bases:
objectA durable
unique_until="forever"identity reservation.Records only the identity key, the originating task id/name, and the reservation time. It never carries args, kwargs, result, or error material. Routine terminal and event maintenance never delete it; an explicit administrative reset is the only removal path.
Worker#
Everything that runs queue work, grouped by who owns the process.
workeris the claim/execute loop itself, the only public name here.runtimeorchestrates one worker start-to-stop without knowing how it was launched. Both the CLI and the server child use it.supervisorowns the fresh worker child that alitestar runinvocation starts, plus that child’s process entry point.invocationpublishes and verifies the marker that tells a process whether its invocation already owns a worker.heartbeatkeeps claims alive while work runs.
Submodules are imported lazily so importing Worker does not pull in
multiprocessing or the Litestar CLI.
- class litestar_queues.worker.Worker(service: QueueService, config: WorkerConfig | None = None)[source]#
Bases:
objectLocal in-process queue worker.
- __init__(service: QueueService, config: WorkerConfig | None = None) None[source]#
Initialize the worker.
- Parameters:
service – Queue service used to reach the configured backends.
config – Worker runtime configuration;
Noneuses defaults.
- async stop(*, force: bool = False) bool[source]#
Stop the worker loop and drain or cancel in-flight work.
- Returns:
True when graceful drain escalated to cancellation.
- async run_once() int[source]#
Process one batch of due tasks.
- Returns:
Number of claimed task records.
- Raises:
QueueConfigurationError – If the execution backend schedules its own delivery, leaving a worker nothing it may safely claim.
- async reconcile_external(*, limit: int | None = None) int[source]#
Reconcile externally dispatched records by delegating to the service.
The reconciliation contract (state transitions, unknown-backend skipping, and metrics) lives on
QueueService.reconcile_external(); the worker keeps only the periodic cadence and fleet lock.- Returns:
Number of records that reached a terminal queue status.
Plugin#
- class litestar_queues.plugin.QueuePlugin(config: QueueConfig | None = None)[source]#
Bases:
InitPlugin,CLIPluginLitestar plugin for queue service dependency registration and lifecycle.
Inheriting the concrete
CLIPluginis what makes Litestar registerserver_lifespan(); satisfyingCLIPluginProtocolstructurally is not enough.- __init__(config: QueueConfig | None = None) None[source]#
Initialize the queue plugin.
- property config: QueueConfig#
Plugin configuration.
- get_service(state: State | None = None) QueueService[source]#
Return a QueueService for this plugin.
- create_worker_service() QueueService[source]#
Create a fresh service that owns its process-local event resources.
- on_app_init(app_config: AppConfig) AppConfig[source]#
Register queue dependencies, signature namespace, state, and the lifespan manager.
- Returns:
The updated application configuration.
- on_cli_init(cli: ClickGroup) None[source]#
Attach the
queuessubcommand group to the Litestar CLI.- Parameters:
cli – The root
click.Groupof the Litestar CLI.
- server_lifespan(app: Litestar) Generator[None][source]#
Own exactly one queue worker for the lifetime of a
litestar runinvocation.Litestar enters this once, around the whole server command, for both its direct Uvicorn call and its multi-worker/reload subprocess path. Any alternative run-command plugin enters the same hook, so there is deliberately no server-specific detection or flag parsing here.
- Yields:
None – with the invocation marker, storage, and worker child active.
Observability#
- litestar_queues.observability.DEFAULT_DURATION_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 600.0, 1800.0)#
Buckets spanning sub-millisecond enqueues through half-hour task executions.
The
prometheus_clientdefault tops out at ten seconds, which sends every real task duration into the+Infbucket.
- class litestar_queues.observability.ObservabilityConfig(enable_otel: bool | None = None, enable_prometheus: bool | None = None, enable_sqlcommenter: bool | None = None, tracer_name: str | None = None, meter_name: str | None = None, tracer_provider: Any | None = None, meter_provider: Any | None = None, prometheus_registry: Any | None = None, metric_prefix: str | None = None, duration_buckets: tuple[float, ...] = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 600.0, 1800.0))[source]#
Bases:
objectConfiguration for optional queue-domain observability.
- enable_prometheus: bool | None#
Prometheus policy;
Nonefollows the app’s Litestar Prometheus middleware.
- prometheus_registry: Any | None#
Explicit Prometheus registry;
Noneuses the client default registry.
- duration_buckets: tuple[float, ...]#
Prometheus histogram buckets, in seconds, for queue duration metrics.
- should_enable_otel(app: Litestar | None = None) bool[source]#
Return whether OpenTelemetry should be enabled.
- Returns:
Whether OpenTelemetry tracing and metrics should be enabled.
- should_enable_prometheus(app: Litestar | None = None) bool[source]#
Return whether Prometheus metrics should be enabled.
- Returns:
Whether Prometheus metrics should be enabled.
- should_enable_sqlcommenter(app: Litestar | None = None) bool[source]#
Return whether SQLCommenter attribution should be enabled.
- Returns:
Whether queue-owned SQLCommenter attribution should be enabled.
- resolve_prometheus_registry() Any[source]#
Return the registry queue collectors are registered with.
- Returns:
The configured registry, or the
prometheus_clientdefault registry, which is what Litestar’sPrometheusControllerscrapes.
- __init__(enable_otel: bool | None = None, enable_prometheus: bool | None = None, enable_sqlcommenter: bool | None = None, tracer_name: str | None = None, meter_name: str | None = None, tracer_provider: Any | None = None, meter_provider: Any | None = None, prometheus_registry: Any | None = None, metric_prefix: str | None = None, duration_buckets: tuple[float, ...] = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 600.0, 1800.0)) None#
- class litestar_queues.observability.QueueObservabilityRuntime(config: ObservabilityConfig | None, *, app: Litestar | None = None, namespace: QueueNamespace | str | None = None)[source]#
Bases:
objectRuntime helper for queue-domain spans and metrics.
- __init__(config: ObservabilityConfig | None, *, app: Litestar | None = None, namespace: QueueNamespace | str | None = None) None[source]#
- enabled#
- property sqlcommenter_enabled: bool#
Whether backends should attach SQLCommenter attribution to statements.
- get_tracer() Any[source]#
Return the configured tracer.
- Returns:
The configured OpenTelemetry tracer.
- start_span(name: str, *, kind: str, attributes: Mapping[str, object], parent: object | None = None) Any | None[source]#
Start a queue span and make it the current span.
The span must be current for two reasons:
inject_trace_contextserialises the current context, and any instrumentation running inside the span – database drivers, HTTP clients, log correlation – resolves its parent from the current context.- Returns:
The started span handle, or
Nonewhen tracing is disabled.
- record_exception(span: Any | None, exc: BaseException) None[source]#
Record an exception on a span and mark the span failed.
- set_status_error(span: Any | None, description: str) None[source]#
Mark a span as failed when no exception reached this frame.
- set_attribute(span: Any | None, key: str, value: object) None[source]#
Set a span attribute if one was created.
- inject_trace_context(metadata: dict[str, Any]) None[source]#
Inject current W3C trace context into queue metadata.
- extract_trace_context(metadata: Mapping[str, Any]) object | None[source]#
Extract a parent trace context from queue metadata.
- Returns:
Extracted trace context, or
Nonewhen unavailable.
- record_counter(name: str, value: int = 1, *, attributes: Mapping[str, str]) None[source]#
Record a counter value for enabled metrics sinks.
- record_gauge_delta(name: str, delta: int = 1, *, attributes: Mapping[str, str]) None[source]#
Record a gauge delta for enabled metrics sinks.
- class litestar_queues.observability.QueueObservabilityRuntimeProtocol(*args, **kwargs)[source]#
Bases:
ProtocolProtocol for queue observability runtimes used by services and workers.
- start_span(name: str, *, kind: str, attributes: Mapping[str, object], parent: object | None = None) Any | None[source]#
Start a queue span and make it the current span.
- Returns:
The started span handle, or
Nonewhen tracing is disabled.
- record_exception(span: Any | None, exc: BaseException) None[source]#
Record an exception on a span and mark it failed.
- set_status_error(span: Any | None, description: str) None[source]#
Mark a span as failed without an exception.
- inject_trace_context(metadata: dict[str, Any]) None[source]#
Inject trace context into queue metadata.
- extract_trace_context(metadata: Mapping[str, Any]) object | None[source]#
Extract trace context from queue metadata.
- Returns:
Extracted trace context, or
Nonewhen unavailable.
- record_counter(name: str, value: int = 1, *, attributes: Mapping[str, str]) None[source]#
Record a counter sample.
- record_gauge_delta(name: str, delta: int = 1, *, attributes: Mapping[str, str]) None[source]#
Record a gauge delta sample.
- record_duration(name: str, seconds: float, *, attributes: Mapping[str, str]) None[source]#
Record a duration sample.
- record_histogram(name: str, value: float, *, unit: str, attributes: Mapping[str, str]) None[source]#
Record a value histogram sample.
- __init__(*args, **kwargs)#
- litestar_queues.observability.bind_correlation_id(metadata: Mapping[str, Any]) tuple[Any, bool][source]#
Rebind the enqueueing request’s correlation ID for task execution.
- Returns:
The previously active correlation ID, and whether it must be restored.
- litestar_queues.observability.capture_correlation_id(metadata: dict[str, Any]) None[source]#
Store the currently active correlation ID on a queued record.
- litestar_queues.observability.create_observability_runtime(config: ObservabilityConfig | None, *, app: Litestar | None = None, namespace: QueueNamespace | str | None = None) QueueObservabilityRuntime[source]#
Create the queue observability runtime for a service.
- Returns:
Queue observability runtime instance.
Typing#
Public typing helpers for optional observability support.
The supported import location for litestar_queues._typing. Each package
publishes its own facade over its own private module – this one does not
re-export a nested package’s types, so event backend protocols live in
litestar_queues.events.typing and adapter protocols beside their
adapter.
- litestar_queues.typing.OtelMeter#
alias of
Meter
- litestar_queues.typing.OtelSpan#
alias of
Span
- litestar_queues.typing.OtelSpanKind#
alias of
SpanKind
- litestar_queues.typing.OtelStatus#
alias of
Status
- litestar_queues.typing.OtelStatusCode#
alias of
StatusCode
- litestar_queues.typing.OtelTracer#
alias of
Tracer
- litestar_queues.typing.PrometheusCounter#
alias of
Counter
- litestar_queues.typing.PrometheusGauge#
alias of
Gauge
- litestar_queues.typing.PrometheusHistogram#
alias of
Histogram
- litestar_queues.typing.prometheus_default_registry() Any[source]#
Return the default Prometheus registry.
- Returns:
The process-wide
prometheus_clientregistry that Litestar’sPrometheusControllerscrapes.
- litestar_queues.typing.sqlspec_correlation_context() Any | None[source]#
Return SQLSpec’s
CorrelationContext.Resolved lazily rather than at import time, because importing SQLSpec is not free and most consumers of this module never need it.
- Returns:
SQLSpec’s
CorrelationContextclass, orNonewhen SQLSpec is absent.
Exceptions#
- exception litestar_queues.exceptions.JobCancelledError[source]#
Bases:
QueueErrorRaised by a task to cooperatively mark itself cancelled.
- exception litestar_queues.exceptions.MissingDependencyError(package: str, install_package: str | None = None)[source]#
Bases:
QueueError,ImportErrorRaised when a required optional dependency is not installed.
- exception litestar_queues.exceptions.NonRetryableError[source]#
Bases:
QueueErrorRaised by a task to mark the current failure as permanent.
- exception litestar_queues.exceptions.QueueConfigurationError[source]#
Bases:
QueueErrorRaised when queue backend configuration is invalid.
- exception litestar_queues.exceptions.QueueDispatchError(message: str, *, task_id: UUID, committed: bool)[source]#
Bases:
QueueErrorRaised when a persisted record could not be handed to its transport.
committedis the part callers act on. A committed record is durable and a repair sweep can retry its dispatch; an uncommitted one never reached storage, so the caller owns retrying the whole enqueue.
- exception litestar_queues.exceptions.QueueError[source]#
Bases:
ExceptionBase exception for litestar-queues errors.
- exception litestar_queues.exceptions.QueueEventBufferFull[source]#
Bases:
QueueErrorRaised when queue event buffering cannot accept another event.
- exception litestar_queues.exceptions.QueueWarning[source]#
Bases:
UserWarningBase class for litestar-queues warnings.
- exception litestar_queues.exceptions.TaskIdentityError[source]#
Bases:
QueueErrorRaised when task uniqueness identity cannot be derived.
Signals that
unique_by="arguments"was requested for a call whose bound arguments cannot be represented by the package’s canonical JSON identity contract (for example non-finite floats or non-JSON objects). Uniqueness identity never falls back to pickle orrepr(); the caller must supply an explicit key or pass identity-friendly arguments instead.
- exception litestar_queues.exceptions.TaskIdentityTooLargeError(*, actual_bytes: int, max_bytes: int)[source]#
Bases:
QueueErrorRaised when a canonical argument-identity payload exceeds the configured limit.
- litestar_queues.exceptions.job_cancelled(message: str = 'Task cancelled') None[source]#
Raise a cooperative task cancellation.
- Raises:
JobCancelledError – Always raised with the provided message.
- litestar_queues.exceptions.non_retryable(message: str) None[source]#
Raise a non-retryable task failure.
- Raises:
NonRetryableError – Always raised with the provided message.