streams
streams
codex_platform.streams
Redis Streams broker — event sourcing / pub-sub layer.
Separate module from redis_service. Streams are a message broker, not a data structure.
Components:
- StreamProducer — XADD (publish events)
- StreamConsumer — XREADGROUP + XACK (low-level read)
- StreamProcessor — background polling engine (wraps StreamConsumer)
- StreamRouter — groups handlers by event type (per-feature)
- StreamDispatcher — routes messages to handlers (generic, no DI)
Typical setup::
from codex_platform.streams import (
StreamConsumer, StreamProducer,
StreamProcessor, StreamRouter, StreamDispatcher,
)
# Producer
producer = StreamProducer(redis_client, stream_name="events:orders")
# Consumer + Processor
consumer = StreamConsumer(redis_client, "events:orders", "workers", "worker_1")
dispatcher = StreamDispatcher()
@dispatcher.on("order.paid")
async def handle_order(payload: dict) -> None:
...
processor = StreamProcessor(
storage=consumer,
stream_name="events:orders",
consumer_group_name="workers",
consumer_name="worker_1",
)
processor.set_callback(dispatcher.process)
await processor.start()
Classes
StreamConsumer
Reads events from a Redis Stream via a consumer group (XREADGROUP).
Acknowledges processed messages via XACK.
Source code in src/codex_platform/streams/consumer.py
Functions
ensure_group()
async
Create the consumer group if it does not already exist (XGROUP CREATE … MKSTREAM).
Source code in src/codex_platform/streams/consumer.py
read(count=10)
async
Read new events from the stream for the consumer group (XREADGROUP).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Maximum number of messages to fetch per call. Defaults to |
10
|
Returns:
| Type | Description |
|---|---|
list[StreamEvent]
|
List of :class: |
Raises:
| Type | Description |
|---|---|
RedisConnectionError
|
Redis connection failure. |
RedisServiceError
|
Redis operation failure. |
Source code in src/codex_platform/streams/consumer.py
ack(event_id)
async
Acknowledge that an event has been processed (XACK).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_id
|
str
|
Stream entry ID returned by :meth: |
required |
Raises:
| Type | Description |
|---|---|
RedisConnectionError
|
Redis connection failure. |
RedisServiceError
|
Redis operation failure. |
Source code in src/codex_platform/streams/consumer.py
StreamEvent
dataclass
RetrySchedulerProtocol
Bases: Protocol
Protocol for a retry scheduler (ARQ, Celery, etc.).
Pass to StreamDispatcher for automatic rescheduling of failed messages.
Source code in src/codex_platform/streams/dispatcher.py
Functions
schedule_retry(stream_name, payload, delay=60)
async
Schedules message reprocessing after a delay.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream_name
|
str
|
Redis Stream name. |
required |
payload
|
dict[str, Any]
|
Original message data. |
required |
delay
|
int
|
Retry delay in seconds. |
60
|
Source code in src/codex_platform/streams/dispatcher.py
StreamDispatcher
Routes Redis Stream messages to registered handlers by event type.
Handlers are registered via @dispatcher.on(event_type) decorator
or by including StreamRouter instances.
On handler failure: if a retry_scheduler is provided, the message
is scheduled for retry. Otherwise the exception is re-raised (message
stays in PEL, unacknowledged).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
retry_scheduler
|
RetrySchedulerProtocol | None
|
Optional retry scheduler implementing |
None
|
Example::
dispatcher = StreamDispatcher()
@dispatcher.on("user.registered")
async def welcome(payload: dict) -> None:
await send_welcome_email(payload["email"])
processor.set_callback(dispatcher.process)
Source code in src/codex_platform/streams/dispatcher.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 | |
Functions
include_router(router)
Merges handlers from a StreamRouter into this dispatcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
router
|
StreamRouter
|
Router from a feature module. |
required |
Source code in src/codex_platform/streams/dispatcher.py
on(event_type, filter_func=None)
Decorator for registering a handler directly on the dispatcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
str
|
Stream message type (e.g. |
required |
filter_func
|
FilterFunc | None
|
Optional |
None
|
Source code in src/codex_platform/streams/dispatcher.py
process(payload, stream_name='')
async
Dispatches an incoming message to matching handlers.
Called by StreamProcessor on each incoming message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict[str, Any]
|
Message data dict. Must contain |
required |
stream_name
|
str
|
Stream name (used for retry scheduling only). |
''
|
Source code in src/codex_platform/streams/dispatcher.py
StreamProcessor
Async engine for consuming and dispatching Redis Stream events.
Runs a continuous background polling loop. On each iteration reads a batch of messages from the consumer group, dispatches each to the registered callback, and ACKs on success.
If the callback fails — message stays in PEL (unacknowledged) for future recovery. The processor recovers automatically if the consumer group is lost (NOGROUP error).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage
|
StreamStorageProtocol
|
Any object implementing |
required |
stream_name
|
str
|
Redis Stream identifier. |
required |
consumer_group_name
|
str
|
Shared group name (same across all instances = load balancing). |
required |
consumer_name
|
str
|
Unique name for this processor instance. |
required |
batch_count
|
int
|
Max messages per poll cycle. |
10
|
poll_interval
|
float
|
Sleep duration (seconds) when no messages available. |
1.0
|
TODO
PEL recovery on startup — XPENDING/XCLAIM for messages stuck in PEL after a processor crash.
Example::
consumer = StreamConsumer(redis, "events:bot", "bot_group", "worker_1")
processor = StreamProcessor(
storage=consumer,
stream_name="events:bot",
consumer_group_name="bot_group",
consumer_name="worker_1",
)
processor.set_callback(my_async_handler)
await processor.start()
# ... later
await processor.stop()
Source code in src/codex_platform/streams/processor.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
Functions
set_callback(callback)
Registers the message handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
MessageCallback
|
|
required |
start()
async
Starts the background polling loop.
Creates the consumer group (up to 5 attempts with 3s delay),
then spawns _consume_loop as an asyncio Task.
Source code in src/codex_platform/streams/processor.py
stop()
async
Stops the polling loop gracefully.
Source code in src/codex_platform/streams/processor.py
StreamStorageProtocol
Bases: Protocol
Adapter protocol for Redis Stream I/O.
StreamConsumer from streams.consumer implements this protocol.
You can also implement it yourself for testing or alternative backends.
Source code in src/codex_platform/streams/processor.py
Functions
create_group(stream_name, group_name)
async
read_events(stream_name, group_name, consumer_name, count)
async
Reads undelivered messages for the group (XREADGROUP ... >).
Returns:
| Type | Description |
|---|---|
list[tuple[str, dict[str, Any]]]
|
List of (message_id, data_dict). Empty if no messages. |
Source code in src/codex_platform/streams/processor.py
StreamProducer
Writes events to a Redis Stream (XADD).
Automatically sanitizes the payload before writing:
- bool values are converted to "True" / "False"
- None values are filtered out
- all remaining values are coerced to str
Source code in src/codex_platform/streams/producer.py
Functions
add_event(event_type, data)
async
Append an event to the Redis Stream (XADD).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
str
|
Event type label, e.g. |
required |
data
|
dict[str, Any]
|
Event payload. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The ID of the newly added stream entry (e.g. |
Raises:
| Type | Description |
|---|---|
RedisConnectionError
|
Redis connection failure. |
RedisServiceError
|
Redis operation failure. |
Source code in src/codex_platform/streams/producer.py
StreamRouter
Groups Redis Stream event handlers by message type.
After populating, include into a StreamDispatcher via include_router().
Example::
router = StreamRouter()
@router.on("order.paid")
async def on_order_paid(payload: dict) -> None:
...
dispatcher.include_router(router)
Source code in src/codex_platform/streams/router.py
Attributes
handlers
property
Registered handlers (read-only).
Functions
on(event_type, filter_func=None)
Decorator for registering a handler for an event type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
str
|
Stream message type (e.g. |
required |
filter_func
|
FilterFunc | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[HandlerFunc], HandlerFunc]
|
Decorator (returns the original handler unchanged). |