notifier/resolvers/listener.py
Untone e22d5468ab
All checks were successful
deploy / deploy (push) Successful in 1m11s
0.1.0-fixes
2023-12-22 12:09:03 +03:00

42 lines
1.5 KiB
Python

from orm.notification import Notification
from resolvers.model import NotificationReaction, NotificationAuthor, NotificationShout
from services.db import local_session
from services.rediscache import redis
import asyncio
class ServiceMessage:
action: str
entity: str
payload: NotificationReaction | NotificationAuthor | NotificationShout
async def handle_notification(n: ServiceMessage, channel: str):
"""создаеёт новое хранимое уведомление"""
with local_session() as session:
try:
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)
session.add(n)
session.commit()
except Exception as e:
session.rollback()
print(f"[listener.handle_reaction] error: {str(e)}")
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"))