irmy-messaging 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- irmy_messaging-1.0.0/LICENSE +21 -0
- irmy_messaging-1.0.0/PKG-INFO +255 -0
- irmy_messaging-1.0.0/README.md +223 -0
- irmy_messaging-1.0.0/irmy_messaging/__init__.py +4 -0
- irmy_messaging-1.0.0/irmy_messaging/exceptions.py +10 -0
- irmy_messaging-1.0.0/irmy_messaging/message_router.py +78 -0
- irmy_messaging-1.0.0/irmy_messaging/metrics.py +45 -0
- irmy_messaging-1.0.0/irmy_messaging/model.py +62 -0
- irmy_messaging-1.0.0/irmy_messaging/py.typed +0 -0
- irmy_messaging-1.0.0/irmy_messaging/rabbitmq_client.py +554 -0
- irmy_messaging-1.0.0/irmy_messaging.egg-info/PKG-INFO +255 -0
- irmy_messaging-1.0.0/irmy_messaging.egg-info/SOURCES.txt +20 -0
- irmy_messaging-1.0.0/irmy_messaging.egg-info/dependency_links.txt +1 -0
- irmy_messaging-1.0.0/irmy_messaging.egg-info/requires.txt +7 -0
- irmy_messaging-1.0.0/irmy_messaging.egg-info/top_level.txt +1 -0
- irmy_messaging-1.0.0/pyproject.toml +53 -0
- irmy_messaging-1.0.0/setup.cfg +4 -0
- irmy_messaging-1.0.0/tests/test_dead_letters.py +139 -0
- irmy_messaging-1.0.0/tests/test_event_age.py +156 -0
- irmy_messaging-1.0.0/tests/test_failed_handler.py +28 -0
- irmy_messaging-1.0.0/tests/test_require_route.py +94 -0
- irmy_messaging-1.0.0/tests/test_routing_keys.py +68 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bendyna V. S.R.L.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: irmy-messaging
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Asynchronous RabbitMQ messaging for IRMy services: HMAC-signed events over quorum queues
|
|
5
|
+
Author-email: "Bendyna V. S.R.L." <info@irmy.tech>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://irmy.tech
|
|
8
|
+
Project-URL: Documentation, https://irmy.tech/docs/
|
|
9
|
+
Project-URL: Source, https://github.com/IRMy-tech/irmy-messaging
|
|
10
|
+
Project-URL: Issues, https://github.com/IRMy-tech/irmy-messaging/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/IRMy-tech/irmy-messaging/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: irmy,rabbitmq,amqp,aio-pika,messaging,events
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: System :: Networking
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: aio-pika<10,>=9.6.2
|
|
26
|
+
Requires-Dist: pydantic<3,>=2.13.5
|
|
27
|
+
Requires-Dist: prometheus-client<1,>=0.26.0
|
|
28
|
+
Provides-Extra: test
|
|
29
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == "test"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# irmy-messaging
|
|
34
|
+
|
|
35
|
+
Asynchronous RabbitMQ client used by IRMy services (RabbitMQ 4.x / Quorum Queues).
|
|
36
|
+
|
|
37
|
+
An asynchronous wrapper around `aio-pika` for working with RabbitMQ (version 4+).
|
|
38
|
+
This module implements the Publisher/Subscriber pattern with a strong focus on reliability (Quorum Queues) and security (HMAC message signing).
|
|
39
|
+
|
|
40
|
+
## Features
|
|
41
|
+
|
|
42
|
+
- **Quorum Queues**: Utilizes modern Quorum queues by default for data safety.
|
|
43
|
+
- **Reliability**: Automatic reconnection, Publisher Confirms, and Native Retry strategies (using `x-delivery-limit`).
|
|
44
|
+
- **Dead letters**: One shared dead-letter queue per exchange instead of one per service.
|
|
45
|
+
- **Security**: Data integrity validation via HMAC-SHA256 (signs both Timestamp and Body).
|
|
46
|
+
- **Validation**: Strict header typing and validation using Pydantic.
|
|
47
|
+
- **Non-blocking**: The Consumer operates in the background without blocking the main Event Loop.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install irmy-messaging
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Requires Python 3.12+. The import package is `irmy_messaging`.
|
|
56
|
+
|
|
57
|
+
## Usage
|
|
58
|
+
### Message Router
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import logging
|
|
62
|
+
from pydantic import BaseModel
|
|
63
|
+
from irmy_messaging import RabbitMessageRouter
|
|
64
|
+
from irmy_messaging.model import MessageHeaders
|
|
65
|
+
|
|
66
|
+
logger = logging.getLogger()
|
|
67
|
+
|
|
68
|
+
class OrderProcessingModel(BaseModel):
|
|
69
|
+
...
|
|
70
|
+
|
|
71
|
+
class PaymentProcessingModel(BaseModel):
|
|
72
|
+
...
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def _process_order(body: OrderProcessingModel, headers: MessageHeaders):
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
async def _process_payment(body: PaymentProcessingModel, headers: MessageHeaders):
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
message_router = RabbitMessageRouter(logger=logger)
|
|
84
|
+
message_router.register("event.order.create", _process_order)
|
|
85
|
+
message_router.register("event.payment.receive", _process_payment)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`register()` takes the payload model from the handler's annotation. Pass `model=` to
|
|
89
|
+
share one handler across routing keys with different payload models:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
async def _store(body: BaseModel, headers: MessageHeaders):
|
|
93
|
+
pass
|
|
94
|
+
|
|
95
|
+
message_router.register("event.order.create", _store, model=OrderProcessingModel)
|
|
96
|
+
message_router.register("event.payment.receive", _store, model=PaymentProcessingModel)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Producer
|
|
100
|
+
```python
|
|
101
|
+
import asyncio
|
|
102
|
+
import logging
|
|
103
|
+
from irmy_messaging import RabbitProducer
|
|
104
|
+
from irmy_messaging.exceptions import RabbitException
|
|
105
|
+
|
|
106
|
+
async def main():
|
|
107
|
+
logger = logging.getLogger("Producer")
|
|
108
|
+
|
|
109
|
+
producer = RabbitProducer(
|
|
110
|
+
connection_url="amqp://guest:guest@localhost:5672/",
|
|
111
|
+
logger=logger,
|
|
112
|
+
exchange_name="my_exchange",
|
|
113
|
+
hmac_secret="my_super_secret",
|
|
114
|
+
producer_name="payment_service",
|
|
115
|
+
producer_id="550e8400-e29b-41d4-a716-446655440000",
|
|
116
|
+
retries=3
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
await producer.connect()
|
|
121
|
+
|
|
122
|
+
# tracing_id is optional (a new UUID will be generated if not provided)
|
|
123
|
+
await producer.publish(
|
|
124
|
+
message={"order_id": 123, "status": "paid"},
|
|
125
|
+
routing_key="order.paid"
|
|
126
|
+
)
|
|
127
|
+
except RabbitException as e:
|
|
128
|
+
logger.error(f"Failed to send: {e}")
|
|
129
|
+
finally:
|
|
130
|
+
await producer.disconnect()
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
asyncio.run(main())
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
#### Messages that must reach a queue
|
|
137
|
+
By default RabbitMQ silently drops a message that no queue is bound for -- for example
|
|
138
|
+
when its consumer has not started yet. Pass `require_route=True` when the message must
|
|
139
|
+
not be lost that way: the broker then returns it and `UnroutableMessageError` is raised
|
|
140
|
+
(it is not retried; publish again later).
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from irmy_messaging import UnroutableMessageError
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
await producer.publish(message=request, routing_key="scheduler.request", require_route=True)
|
|
147
|
+
except UnroutableMessageError:
|
|
148
|
+
... # nobody listens yet -- try again in a while
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
`publish_until_routed()` does that retrying for you (backing off from 5 s to 60 s) and
|
|
152
|
+
returns once a queue took the message; run it in a background task and cancel the task to stop:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
task = asyncio.create_task(producer.publish_until_routed(request, "scheduler.request"))
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Consumer
|
|
159
|
+
```python
|
|
160
|
+
import asyncio
|
|
161
|
+
import logging
|
|
162
|
+
from irmy_messaging import RabbitConsumer, RabbitMessageRouter
|
|
163
|
+
from irmy_messaging.model import MessageHeaders
|
|
164
|
+
|
|
165
|
+
logger = logging.getLogger("Consumer")
|
|
166
|
+
|
|
167
|
+
message_router = RabbitMessageRouter(logger=logger)
|
|
168
|
+
message_router.register(...)
|
|
169
|
+
message_router.register(...)
|
|
170
|
+
|
|
171
|
+
async def main():
|
|
172
|
+
# Topology configuration
|
|
173
|
+
bindings = {
|
|
174
|
+
"my_queue": message_router.get_routing_keys()
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
consumer = RabbitConsumer(
|
|
178
|
+
connection_url="amqp://guest:guest@localhost:5672/",
|
|
179
|
+
logger=logger,
|
|
180
|
+
hmac_secret="my_super_secret",
|
|
181
|
+
bindings=bindings,
|
|
182
|
+
exchange_name="irmy",
|
|
183
|
+
prefetch_count=10,
|
|
184
|
+
requeue_limit=3,
|
|
185
|
+
max_event_age_seconds=None, # optional; None = default 24 hours
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
# Non-blocking call
|
|
189
|
+
await consumer.consume(message_router)
|
|
190
|
+
|
|
191
|
+
# Prevent script termination
|
|
192
|
+
await asyncio.Future()
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__":
|
|
195
|
+
asyncio.run(main())
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Dead-letter queue
|
|
199
|
+
Durable consumer queues (`QueueType.DURABLE`, the default) are quorum queues with
|
|
200
|
+
`x-delivery-limit` (`requeue_limit`, default 3). A message whose handler keeps failing is
|
|
201
|
+
dead-lettered to `<exchange>_dlx`, which routes everything (`#`) to **one shared queue,
|
|
202
|
+
`<exchange>_dlq`**, for all services — there is no per-service DLQ. Messages are kept
|
|
203
|
+
there for 14 days (`x-message-ttl`).
|
|
204
|
+
|
|
205
|
+
Which service rejected a message, and why, is in the standard RabbitMQ `x-death` header
|
|
206
|
+
the broker adds when dead-lettering: `queue` (the consumer queue, i.e. the service),
|
|
207
|
+
`reason`, `count`, `time`, `exchange` and `routing-keys`.
|
|
208
|
+
|
|
209
|
+
To replay a dead letter, publish it to the queue named in `x-death[0].queue` (default
|
|
210
|
+
exchange, routing key = queue name). Re-publishing it to the main exchange with its
|
|
211
|
+
original routing key would deliver it again to every service bound to that key.
|
|
212
|
+
|
|
213
|
+
Messages that can never succeed are not retried:
|
|
214
|
+
* a body that fails validation against the handler's model (`RabbitMessageRouter`) is
|
|
215
|
+
logged and dropped;
|
|
216
|
+
* a message with missing or invalid security headers or signature is logged and dropped.
|
|
217
|
+
|
|
218
|
+
`QueueType.TEMPORARY` queues have no dead-lettering: a failed message is dropped.
|
|
219
|
+
|
|
220
|
+
## Message headers
|
|
221
|
+
Every published message carries these headers (names are case-sensitive):
|
|
222
|
+
|
|
223
|
+
* `eventVersion`: event message version (integer, currently `1`).
|
|
224
|
+
* `eventTimestamp`: Unix epoch timestamp (UTC) of event creation.
|
|
225
|
+
* `tracingId`: UUID used to trace the event across consumers.
|
|
226
|
+
* `producerName`: name of the producing microservice.
|
|
227
|
+
* `producerId`: UUID of the producing microservice instance.
|
|
228
|
+
* `x-signature`: HMAC signature, described below.
|
|
229
|
+
|
|
230
|
+
## Security (HMAC Signature)
|
|
231
|
+
Every message is automatically signed to ensure integrity and authenticity.
|
|
232
|
+
|
|
233
|
+
### Signature Format:
|
|
234
|
+
`HMAC_SHA256(secret, payload)`
|
|
235
|
+
|
|
236
|
+
### Payload Format:
|
|
237
|
+
The payload to be signed is constructed as follows:
|
|
238
|
+
|
|
239
|
+
`<eventTimestamp>.<SortedJSONBodyBytes>`
|
|
240
|
+
|
|
241
|
+
* `<eventTimestamp>`: Unix epoch timestamp (integer).
|
|
242
|
+
* `.`: Dot separator.
|
|
243
|
+
* `<SortedJSONBodyBytes>`: JSON body with keys sorted alphabetically.
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
### Consumer Validation Logic:
|
|
247
|
+
The Consumer automatically performs the following checks:
|
|
248
|
+
|
|
249
|
+
1. Existence: Checks for the presence of the signature header.
|
|
250
|
+
2. Integrity: Validates the signature (protects against tampering with the body or the timestamp).
|
|
251
|
+
3. Freshness: Checks eventTimestamp. A message older than 24 hours (or the consumer's `max_event_age_seconds`) is **dead-lettered** to `<exchange>_dlq` (rejected without requeue) and a warning is logged — usually it is the backlog of a consumer that was down, so it is kept rather than lost. On a temporary queue (no DLX) it is discarded.
|
|
252
|
+
4. Schema: Validates the structure and types of all required headers.
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
If any other check fails, the message is dropped (ACKed) immediately without being passed to the handler, and a security alert is logged.
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
# irmy-messaging
|
|
2
|
+
|
|
3
|
+
Asynchronous RabbitMQ client used by IRMy services (RabbitMQ 4.x / Quorum Queues).
|
|
4
|
+
|
|
5
|
+
An asynchronous wrapper around `aio-pika` for working with RabbitMQ (version 4+).
|
|
6
|
+
This module implements the Publisher/Subscriber pattern with a strong focus on reliability (Quorum Queues) and security (HMAC message signing).
|
|
7
|
+
|
|
8
|
+
## Features
|
|
9
|
+
|
|
10
|
+
- **Quorum Queues**: Utilizes modern Quorum queues by default for data safety.
|
|
11
|
+
- **Reliability**: Automatic reconnection, Publisher Confirms, and Native Retry strategies (using `x-delivery-limit`).
|
|
12
|
+
- **Dead letters**: One shared dead-letter queue per exchange instead of one per service.
|
|
13
|
+
- **Security**: Data integrity validation via HMAC-SHA256 (signs both Timestamp and Body).
|
|
14
|
+
- **Validation**: Strict header typing and validation using Pydantic.
|
|
15
|
+
- **Non-blocking**: The Consumer operates in the background without blocking the main Event Loop.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install irmy-messaging
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Requires Python 3.12+. The import package is `irmy_messaging`.
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
### Message Router
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import logging
|
|
30
|
+
from pydantic import BaseModel
|
|
31
|
+
from irmy_messaging import RabbitMessageRouter
|
|
32
|
+
from irmy_messaging.model import MessageHeaders
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger()
|
|
35
|
+
|
|
36
|
+
class OrderProcessingModel(BaseModel):
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
class PaymentProcessingModel(BaseModel):
|
|
40
|
+
...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def _process_order(body: OrderProcessingModel, headers: MessageHeaders):
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
async def _process_payment(body: PaymentProcessingModel, headers: MessageHeaders):
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
message_router = RabbitMessageRouter(logger=logger)
|
|
52
|
+
message_router.register("event.order.create", _process_order)
|
|
53
|
+
message_router.register("event.payment.receive", _process_payment)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`register()` takes the payload model from the handler's annotation. Pass `model=` to
|
|
57
|
+
share one handler across routing keys with different payload models:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
async def _store(body: BaseModel, headers: MessageHeaders):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
message_router.register("event.order.create", _store, model=OrderProcessingModel)
|
|
64
|
+
message_router.register("event.payment.receive", _store, model=PaymentProcessingModel)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Producer
|
|
68
|
+
```python
|
|
69
|
+
import asyncio
|
|
70
|
+
import logging
|
|
71
|
+
from irmy_messaging import RabbitProducer
|
|
72
|
+
from irmy_messaging.exceptions import RabbitException
|
|
73
|
+
|
|
74
|
+
async def main():
|
|
75
|
+
logger = logging.getLogger("Producer")
|
|
76
|
+
|
|
77
|
+
producer = RabbitProducer(
|
|
78
|
+
connection_url="amqp://guest:guest@localhost:5672/",
|
|
79
|
+
logger=logger,
|
|
80
|
+
exchange_name="my_exchange",
|
|
81
|
+
hmac_secret="my_super_secret",
|
|
82
|
+
producer_name="payment_service",
|
|
83
|
+
producer_id="550e8400-e29b-41d4-a716-446655440000",
|
|
84
|
+
retries=3
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
await producer.connect()
|
|
89
|
+
|
|
90
|
+
# tracing_id is optional (a new UUID will be generated if not provided)
|
|
91
|
+
await producer.publish(
|
|
92
|
+
message={"order_id": 123, "status": "paid"},
|
|
93
|
+
routing_key="order.paid"
|
|
94
|
+
)
|
|
95
|
+
except RabbitException as e:
|
|
96
|
+
logger.error(f"Failed to send: {e}")
|
|
97
|
+
finally:
|
|
98
|
+
await producer.disconnect()
|
|
99
|
+
|
|
100
|
+
if __name__ == "__main__":
|
|
101
|
+
asyncio.run(main())
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### Messages that must reach a queue
|
|
105
|
+
By default RabbitMQ silently drops a message that no queue is bound for -- for example
|
|
106
|
+
when its consumer has not started yet. Pass `require_route=True` when the message must
|
|
107
|
+
not be lost that way: the broker then returns it and `UnroutableMessageError` is raised
|
|
108
|
+
(it is not retried; publish again later).
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from irmy_messaging import UnroutableMessageError
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
await producer.publish(message=request, routing_key="scheduler.request", require_route=True)
|
|
115
|
+
except UnroutableMessageError:
|
|
116
|
+
... # nobody listens yet -- try again in a while
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`publish_until_routed()` does that retrying for you (backing off from 5 s to 60 s) and
|
|
120
|
+
returns once a queue took the message; run it in a background task and cancel the task to stop:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
task = asyncio.create_task(producer.publish_until_routed(request, "scheduler.request"))
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### Consumer
|
|
127
|
+
```python
|
|
128
|
+
import asyncio
|
|
129
|
+
import logging
|
|
130
|
+
from irmy_messaging import RabbitConsumer, RabbitMessageRouter
|
|
131
|
+
from irmy_messaging.model import MessageHeaders
|
|
132
|
+
|
|
133
|
+
logger = logging.getLogger("Consumer")
|
|
134
|
+
|
|
135
|
+
message_router = RabbitMessageRouter(logger=logger)
|
|
136
|
+
message_router.register(...)
|
|
137
|
+
message_router.register(...)
|
|
138
|
+
|
|
139
|
+
async def main():
|
|
140
|
+
# Topology configuration
|
|
141
|
+
bindings = {
|
|
142
|
+
"my_queue": message_router.get_routing_keys()
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
consumer = RabbitConsumer(
|
|
146
|
+
connection_url="amqp://guest:guest@localhost:5672/",
|
|
147
|
+
logger=logger,
|
|
148
|
+
hmac_secret="my_super_secret",
|
|
149
|
+
bindings=bindings,
|
|
150
|
+
exchange_name="irmy",
|
|
151
|
+
prefetch_count=10,
|
|
152
|
+
requeue_limit=3,
|
|
153
|
+
max_event_age_seconds=None, # optional; None = default 24 hours
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# Non-blocking call
|
|
157
|
+
await consumer.consume(message_router)
|
|
158
|
+
|
|
159
|
+
# Prevent script termination
|
|
160
|
+
await asyncio.Future()
|
|
161
|
+
|
|
162
|
+
if __name__ == "__main__":
|
|
163
|
+
asyncio.run(main())
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## Dead-letter queue
|
|
167
|
+
Durable consumer queues (`QueueType.DURABLE`, the default) are quorum queues with
|
|
168
|
+
`x-delivery-limit` (`requeue_limit`, default 3). A message whose handler keeps failing is
|
|
169
|
+
dead-lettered to `<exchange>_dlx`, which routes everything (`#`) to **one shared queue,
|
|
170
|
+
`<exchange>_dlq`**, for all services — there is no per-service DLQ. Messages are kept
|
|
171
|
+
there for 14 days (`x-message-ttl`).
|
|
172
|
+
|
|
173
|
+
Which service rejected a message, and why, is in the standard RabbitMQ `x-death` header
|
|
174
|
+
the broker adds when dead-lettering: `queue` (the consumer queue, i.e. the service),
|
|
175
|
+
`reason`, `count`, `time`, `exchange` and `routing-keys`.
|
|
176
|
+
|
|
177
|
+
To replay a dead letter, publish it to the queue named in `x-death[0].queue` (default
|
|
178
|
+
exchange, routing key = queue name). Re-publishing it to the main exchange with its
|
|
179
|
+
original routing key would deliver it again to every service bound to that key.
|
|
180
|
+
|
|
181
|
+
Messages that can never succeed are not retried:
|
|
182
|
+
* a body that fails validation against the handler's model (`RabbitMessageRouter`) is
|
|
183
|
+
logged and dropped;
|
|
184
|
+
* a message with missing or invalid security headers or signature is logged and dropped.
|
|
185
|
+
|
|
186
|
+
`QueueType.TEMPORARY` queues have no dead-lettering: a failed message is dropped.
|
|
187
|
+
|
|
188
|
+
## Message headers
|
|
189
|
+
Every published message carries these headers (names are case-sensitive):
|
|
190
|
+
|
|
191
|
+
* `eventVersion`: event message version (integer, currently `1`).
|
|
192
|
+
* `eventTimestamp`: Unix epoch timestamp (UTC) of event creation.
|
|
193
|
+
* `tracingId`: UUID used to trace the event across consumers.
|
|
194
|
+
* `producerName`: name of the producing microservice.
|
|
195
|
+
* `producerId`: UUID of the producing microservice instance.
|
|
196
|
+
* `x-signature`: HMAC signature, described below.
|
|
197
|
+
|
|
198
|
+
## Security (HMAC Signature)
|
|
199
|
+
Every message is automatically signed to ensure integrity and authenticity.
|
|
200
|
+
|
|
201
|
+
### Signature Format:
|
|
202
|
+
`HMAC_SHA256(secret, payload)`
|
|
203
|
+
|
|
204
|
+
### Payload Format:
|
|
205
|
+
The payload to be signed is constructed as follows:
|
|
206
|
+
|
|
207
|
+
`<eventTimestamp>.<SortedJSONBodyBytes>`
|
|
208
|
+
|
|
209
|
+
* `<eventTimestamp>`: Unix epoch timestamp (integer).
|
|
210
|
+
* `.`: Dot separator.
|
|
211
|
+
* `<SortedJSONBodyBytes>`: JSON body with keys sorted alphabetically.
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
### Consumer Validation Logic:
|
|
215
|
+
The Consumer automatically performs the following checks:
|
|
216
|
+
|
|
217
|
+
1. Existence: Checks for the presence of the signature header.
|
|
218
|
+
2. Integrity: Validates the signature (protects against tampering with the body or the timestamp).
|
|
219
|
+
3. Freshness: Checks eventTimestamp. A message older than 24 hours (or the consumer's `max_event_age_seconds`) is **dead-lettered** to `<exchange>_dlq` (rejected without requeue) and a warning is logged — usually it is the backlog of a consumer that was down, so it is kept rather than lost. On a temporary queue (no DLX) it is discarded.
|
|
220
|
+
4. Schema: Validates the structure and types of all required headers.
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
If any other check fails, the message is dropped (ACKed) immediately without being passed to the handler, and a security alert is logged.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
class RabbitException(Exception):
|
|
2
|
+
def __init__(self, message: str):
|
|
3
|
+
self.message = message
|
|
4
|
+
super().__init__(message)
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class UnroutableMessageError(RabbitException):
|
|
8
|
+
"""``publish(..., require_route=True)``: the broker returned the message because no
|
|
9
|
+
queue is bound for its routing key (for example, the consumer has not started yet
|
|
10
|
+
and has not declared its queue). Nothing was delivered; publish again later."""
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import typing
|
|
3
|
+
from logging import Logger
|
|
4
|
+
from typing import Any, Callable, Optional
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
from .model import MessageHeaders
|
|
8
|
+
from .rabbitmq_client import routing_key_str
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RabbitMessageRouter:
|
|
12
|
+
def __init__(self, logger: Logger) -> None:
|
|
13
|
+
# rk -> (ModelClass, handler)
|
|
14
|
+
self._routes: dict[str, tuple[type[BaseModel], Callable]] = {}
|
|
15
|
+
self._logger = logger
|
|
16
|
+
|
|
17
|
+
def register(self, routing_key: str, handler: Callable,
|
|
18
|
+
model: Optional[type[BaseModel]] = None) -> None:
|
|
19
|
+
"""Route ``routing_key`` to ``handler``. The body is validated against
|
|
20
|
+
``model`` when given, otherwise against the handler's single Pydantic
|
|
21
|
+
parameter annotation — pass ``model`` to share one handler across keys
|
|
22
|
+
with different payload models."""
|
|
23
|
+
routing_key = routing_key_str(routing_key)
|
|
24
|
+
if model is not None and not (isinstance(model, type) and issubclass(model, BaseModel)):
|
|
25
|
+
raise ValueError(f"model for routing key '{routing_key}' must be a Pydantic model class")
|
|
26
|
+
model_cls = model or self._extract_model(handler)
|
|
27
|
+
self._routes[routing_key] = (model_cls, handler)
|
|
28
|
+
self._logger.debug("Registered handler '%s' for routing key '%s'", handler.__qualname__, routing_key)
|
|
29
|
+
|
|
30
|
+
def get_routing_keys(self) -> list[str]:
|
|
31
|
+
return list(self._routes.keys())
|
|
32
|
+
|
|
33
|
+
async def __call__(self, routing_key: str, body: dict, headers: MessageHeaders) -> None:
|
|
34
|
+
if routing_key not in self._routes:
|
|
35
|
+
self._logger.warning("No handler for routing key '%s', dropping message", routing_key)
|
|
36
|
+
return
|
|
37
|
+
|
|
38
|
+
model_cls, handler = self._routes[routing_key]
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
event = model_cls.model_validate(body)
|
|
42
|
+
except Exception:
|
|
43
|
+
# A payload that does not match its model never will: drop it (the
|
|
44
|
+
# consumer acks) instead of retrying it into the dead-letter queue.
|
|
45
|
+
self._logger.exception(
|
|
46
|
+
"Failed to deserialize body for routing key '%s' (tracing id %s), dropping message",
|
|
47
|
+
routing_key, headers.tracing_id,
|
|
48
|
+
)
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
await handler(event, headers)
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def _extract_model(handler: Callable) -> type[BaseModel]:
|
|
55
|
+
hints = _get_hints_without_self(handler)
|
|
56
|
+
|
|
57
|
+
models = [
|
|
58
|
+
v for v in hints.values()
|
|
59
|
+
if isinstance(v, type) and issubclass(v, BaseModel) and v is not MessageHeaders
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
if not models:
|
|
63
|
+
raise ValueError(f"Handler '{handler.__qualname__}' has no Pydantic model parameter")
|
|
64
|
+
if len(models) > 1:
|
|
65
|
+
raise ValueError(f"Handler '{handler.__qualname__}' has multiple Pydantic model parameters")
|
|
66
|
+
|
|
67
|
+
return models[0]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _get_hints_without_self(handler: Callable) -> dict[str, Any]:
|
|
71
|
+
sig = inspect.signature(handler)
|
|
72
|
+
type_hints = typing.get_type_hints(handler)
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
name: type_hints[name]
|
|
76
|
+
for name in sig.parameters
|
|
77
|
+
if name not in ("self", "return") and name in type_hints
|
|
78
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from prometheus_client import Counter, Histogram
|
|
2
|
+
|
|
3
|
+
# Producer metrics
|
|
4
|
+
messages_published_total = Counter(
|
|
5
|
+
"messages_published_total",
|
|
6
|
+
"Number of published messages",
|
|
7
|
+
["routing_key"]
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
messages_publish_duration_seconds = Histogram(
|
|
11
|
+
"messages_publish_duration_seconds",
|
|
12
|
+
"Histogram for counting how much time took to produce event",
|
|
13
|
+
["status", "routing_key"]
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
messages_publish_errors_total = Counter(
|
|
17
|
+
"messages_publish_errors_total",
|
|
18
|
+
"Number of messages failed to publish",
|
|
19
|
+
["routing_key"]
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# Consumer metrics
|
|
23
|
+
messages_consumed_total = Counter(
|
|
24
|
+
"messages_consumed_total",
|
|
25
|
+
"Number of consumed messages",
|
|
26
|
+
["status", "queue"]
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
messages_processing_duration_seconds = Histogram(
|
|
30
|
+
"messages_processing_duration_seconds",
|
|
31
|
+
"Message processing time",
|
|
32
|
+
["status", "queue"]
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
messages_requeued_total = Counter(
|
|
36
|
+
"messages_requeued_total",
|
|
37
|
+
"Messages that were requeued",
|
|
38
|
+
["queue"]
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
messages_rejected_total = Counter(
|
|
42
|
+
"messages_rejected_total",
|
|
43
|
+
"Number of messages rejected to process",
|
|
44
|
+
["queue"]
|
|
45
|
+
)
|