Worker (Python API)¶
Long-running event consumer that claims rows from worker_events, runs the Orchestrator, and updates entity state. Operational guide: Worker.
Types and entrypoints¶
Worker
¶
Worker(config: WorkerConfig | None = None, guards: GuardRegistry | None = None, actions: ActionRegistry | None = None, *, event_source: EventSource | None = None)
PyStator worker: a long-running event-processing service.
Usage::
from pystator.worker import Worker
worker = Worker()
await worker.start()
await worker.run() # blocks until shutdown signal
With custom guards and actions::
from pystator import GuardRegistry, ActionRegistry
from pystator.worker import Worker
guards = GuardRegistry()
actions = ActionRegistry()
@guards.register("is_full_fill")
def is_full_fill(ctx):
return ctx["fill_qty"] >= ctx["order_qty"]
worker = Worker(guards=guards, actions=actions)
await worker.start()
await worker.run()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
WorkerConfig | None
|
Worker configuration. Defaults to :class: |
None
|
guards
|
GuardRegistry | None
|
Guard registry bound to all loaded machines. |
None
|
actions
|
ActionRegistry | None
|
Action registry bound to all loaded machines. |
None
|
event_source
|
EventSource | None
|
Custom event source. When |
None
|
Source code in src/pystator/worker/runner.py
dlq_store
property
¶
Dead letter store (available after :meth:start when DLQ is enabled).
start
async
¶
Initialise connections, load machines, verify readiness.
Must be called before :meth:run.
Source code in src/pystator/worker/runner.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
run
async
¶
Block and process events until a shutdown signal is received.
Spawns config.concurrency poller tasks. Each poller claims
events, processes them, then sleeps for poll_interval_ms
before the next claim.
Handles SIGTERM and SIGINT for graceful shutdown.
Source code in src/pystator/worker/runner.py
WorkerConfig
dataclass
¶
WorkerConfig(db_url: str | None = None, poll_interval_ms: int = 500, concurrency: int = 5, apply_data_poll_interval_ms: int = 250, apply_data_concurrency: int = 5, drain_timeout_s: int = 30, max_attempts: int = 5, apply_data_max_attempts: int = 5, machine_source: str = 'db', machine_dir: str | None = None, worker_id: str = _default_worker_id(), claim_lease_timeout_s: int = 300, retry_backoff_base_ms: int = 1000, retry_backoff_max_ms: int = 300000, dlq_enabled: bool = True, dlq_database_url: str | None = None, dlq_table_name: str = 'dead_letter_queue')
submit_event
async
¶
submit_event(machine_name: str, entity_id: str, trigger: str, *, context: dict[str, Any] | None = None, fires_at: datetime | None = None, idempotency_key: str | None = None, max_attempts: int = 5, db_url: str | None = None) -> str
Convenience function: submit one event to the worker queue.
Writes directly to the worker_events table. Can be called from
any process that has database access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
machine_name
|
str
|
Target FSM machine name. |
required |
entity_id
|
str
|
Entity identifier (e.g. |
required |
trigger
|
str
|
Event trigger name (e.g. |
required |
context
|
dict[str, Any] | None
|
Optional dict passed to guards and actions. |
None
|
fires_at
|
datetime | None
|
When the event becomes eligible. |
None
|
idempotency_key
|
str | None
|
Optional dedup key. |
None
|
max_attempts
|
int
|
Maximum processing attempts. |
5
|
db_url
|
str | None
|
Database URL. Falls back to the standard pystator config resolution chain. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The |
Source code in src/pystator/worker/__init__.py
submit_event_sync
¶
submit_event_sync(machine_name: str, entity_id: str, trigger: str, *, context: dict[str, Any] | None = None, fires_at: datetime | None = None, idempotency_key: str | None = None, max_attempts: int = 5, db_url: str | None = None) -> str
Synchronous wrapper around :func:submit_event.
Suitable for calling from non-async code (scripts, Django views, Flask routes, etc.).
Source code in src/pystator/worker/__init__.py
Related models¶
WorkerEvent
dataclass
¶
WorkerEvent(machine_name: str, entity_id: str, trigger: str, context: dict[str, Any] | None = None, fires_at: datetime | None = None, idempotency_key: str | None = None, max_attempts: int = 5)
Immutable event envelope submitted by callers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
machine_name
|
str
|
Name of the FSM machine to route to. |
required |
entity_id
|
str
|
Identifier for the entity (e.g. |
required |
trigger
|
str
|
The event trigger name (e.g. |
required |
context
|
dict[str, Any] | None
|
Optional dict passed to guards and actions. |
None
|
fires_at
|
datetime | None
|
When the event becomes eligible for processing.
|
None
|
idempotency_key
|
str | None
|
Optional client-supplied dedup key. If a pending/claimed event with the same key already exists, the submission is silently skipped. |
None
|
max_attempts
|
int
|
Maximum number of processing attempts before the event moves to dead-letter. |
5
|
ClaimedEvent
dataclass
¶
ClaimedEvent(event_id: str, machine_name: str, entity_id: str, trigger: str, context: dict[str, Any], attempt: int, max_attempts: int, fires_at: datetime = (lambda: now(UTC))(), claimed_at: datetime = (lambda: now(UTC))())
An event that has been atomically claimed by a worker.
The :class:EventProcessor receives this after a successful claim
from the event source. event_id is used to complete or fail the
event after processing.
EventStatus
¶
Bases: str, Enum
Lifecycle status of a worker event.
PENDING
class-attribute
instance-attribute
¶
Event is queued and waiting to be claimed.
CLAIMED
class-attribute
instance-attribute
¶
Event has been claimed by a worker and is being processed.
COMPLETED
class-attribute
instance-attribute
¶
Event was processed successfully.
DEAD_LETTER
class-attribute
instance-attribute
¶
Processing failed and max attempts have been exhausted.
Imports¶
Install: pip install pystator[worker] (database URL required at runtime).