import asyncio, json, time
import aiohttp
class ShipmentNotifier:
def __init__(self, db, consumer):
self.db = db
self.consumer = consumer
self.sent_cache = {} # order_id -> timestamp
async def handle(self, msg):
event = json.loads(msg.value)
order_id = event["order_id"]
# дедупликация
if order_id in self.sent_cache:
return
# обновляем статус
await self.db.execute(
"UPDATE orders SET status='shipped' WHERE id=$1",
order_id,
)
# отправляем email
async with aiohttp.ClientSession() as session:
await session.post(
"http://email-service/send",
json={"to": event["email"], "order_id": order_id},
)
self.sent_cache[order_id] = time.time()
await self.consumer.commit()
async def run(self):
async for msg in self.consumer:
asyncio.create_task(self.handle(msg))