notifier/resolvers/listener.py

42 lines
1.5 KiB
Python
Raw Normal View History

2023-11-26 10:18:57 +00:00
from orm.notification import Notification
2023-12-22 09:09:03 +00:00
from resolvers.model import NotificationReaction, NotificationAuthor, NotificationShout
2023-11-26 10:18:57 +00:00
from services.db import local_session
from services.rediscache import redis
2023-12-22 09:09:03 +00:00
import asyncio
2023-11-26 10:18:57 +00:00
2023-12-22 09:09:03 +00:00
class ServiceMessage:
action: str
entity: str
payload: NotificationReaction | NotificationAuthor | NotificationShout
async def handle_notification(n: ServiceMessage, channel: str):
2023-11-26 10:18:57 +00:00
"""создаеёт новое хранимое уведомление"""
2023-11-26 12:37:22 +00:00
with local_session() as session:
try:
2023-12-22 09:09:03 +00:00
if channel.startswith("follower:"):
author_id = int(channel.split(":")[1])
if isinstance(n.payload, NotificationAuthor):
n.payload.following_id = author_id
n = Notification(action=n.action, entity=n.entity, payload=n.payload)
2023-11-26 10:18:57 +00:00
session.add(n)
2023-11-26 18:33:51 +00:00
session.commit()
2023-11-26 12:37:22 +00:00
except Exception as e:
session.rollback()
print(f"[listener.handle_reaction] error: {str(e)}")
2023-11-26 10:18:57 +00:00
2023-12-22 09:09:03 +00:00
async def listen_task(pattern):
async for message_data, channel in redis.listen(pattern):
try:
notification_message = ServiceMessage(**message_data)
await handle_notification(notification_message, str(channel))
except Exception as e:
print(f"[listener.listen_task] Error processing notification: {str(e)}")
async def notifications_worker():
# Use asyncio.gather to run tasks concurrently
await asyncio.gather(listen_task("follower:*"), listen_task("reaction"), listen_task("shout"))