2024-02-16 23:56:15 +00:00
|
|
|
import asyncio
|
|
|
|
import logging
|
|
|
|
|
2024-02-04 04:58:44 +00:00
|
|
|
from orm.notification import Notification
|
2024-02-16 23:56:15 +00:00
|
|
|
from resolvers.model import NotificationAuthor, NotificationReaction, NotificationShout
|
2023-11-26 10:18:57 +00:00
|
|
|
from services.db import local_session
|
|
|
|
from services.rediscache import redis
|
2024-01-23 08:44:37 +00:00
|
|
|
|
2024-02-16 23:56:15 +00:00
|
|
|
|
|
|
|
logger = logging.getLogger('[listener.listen_task] ')
|
2024-01-23 08:44:37 +00:00
|
|
|
logger.setLevel(logging.DEBUG)
|
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:
|
2024-02-16 23:56:15 +00:00
|
|
|
if channel.startswith('follower:'):
|
|
|
|
author_id = int(channel.split(':')[1])
|
2023-12-22 09:09:03 +00:00
|
|
|
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()
|
2024-02-16 23:56:15 +00:00
|
|
|
logger.error(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:
|
2024-01-23 08:44:37 +00:00
|
|
|
if message_data:
|
|
|
|
notification_message = ServiceMessage(**message_data)
|
|
|
|
await handle_notification(notification_message, str(channel))
|
2023-12-22 09:09:03 +00:00
|
|
|
except Exception as e:
|
2024-02-16 23:56:15 +00:00
|
|
|
logger.error(f'Error processing notification: {str(e)}')
|
2023-12-22 09:09:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def notifications_worker():
|
|
|
|
# Use asyncio.gather to run tasks concurrently
|
2024-02-16 23:56:15 +00:00
|
|
|
await asyncio.gather(listen_task('follower:*'), listen_task('reaction'), listen_task('shout'))
|