core/services/triggers.py

168 lines
6.2 KiB
Python
Raw Normal View History

2024-04-09 08:17:32 +00:00
import asyncio
2024-05-18 14:31:45 +00:00
from sqlalchemy import event, select
2024-04-09 08:17:32 +00:00
from orm.author import Author, AuthorFollower
from orm.reaction import Reaction
from orm.shout import Shout, ShoutAuthor
2024-04-19 15:22:07 +00:00
from orm.topic import Topic, TopicFollower
2024-04-09 08:17:32 +00:00
from resolvers.stat import get_with_stat
2024-05-20 22:40:57 +00:00
from services.cache import cache_author, cache_follows, cache_topic
2024-04-09 08:17:32 +00:00
from services.logger import root_logger as logger
DEFAULT_FOLLOWS = {
2024-04-17 15:32:23 +00:00
"topics": [],
"authors": [],
"communities": [{"id": 1, "name": "Дискурс", "slug": "discours", "pic": ""}],
2024-04-09 08:17:32 +00:00
}
2024-08-06 15:53:25 +00:00
def run_background_task(coro):
"""Запускает асинхронную задачу в фоне и обрабатывает исключения."""
task = asyncio.create_task(coro)
task.add_done_callback(handle_task_result)
def handle_task_result(task):
"""Обработка результата завершенной задачи."""
try:
task.result()
except Exception as e:
logger.error(f"Error in background task: {e}")
async def handle_author_follower_change(author_id: int, follower_id: int, is_insert: bool):
logger.info(
f"Handling author follower change: author_id={author_id}, follower_id={follower_id}, is_insert={is_insert}"
)
author_query = select(Author).filter(Author.id == author_id)
author_result = await get_with_stat(author_query)
follower_query = select(Author).filter(Author.id == follower_id)
follower_result = await get_with_stat(follower_query)
2024-06-11 19:46:35 +00:00
if follower_result and author_result:
author_with_stat = author_result[0]
follower = follower_result[0]
if author_with_stat:
author_dict = author_with_stat.dict()
2024-08-06 15:53:25 +00:00
run_background_task(cache_author(author_dict))
run_background_task(cache_follows(follower.id, "author", author_with_stat.id, is_insert))
2024-04-09 13:59:41 +00:00
2024-05-30 04:12:00 +00:00
async def handle_topic_follower_change(topic_id: int, follower_id: int, is_insert: bool):
2024-08-06 15:53:25 +00:00
logger.info(
f"Handling topic follower change: topic_id={topic_id}, follower_id={follower_id}, is_insert={is_insert}"
)
2024-04-09 13:59:41 +00:00
topic_query = select(Topic).filter(Topic.id == topic_id)
2024-08-06 15:53:25 +00:00
topic = await get_with_stat(topic_query)
2024-04-09 13:59:41 +00:00
follower_query = select(Author).filter(Author.id == follower_id)
2024-08-06 15:53:25 +00:00
follower = await get_with_stat(follower_query)
2024-06-11 11:46:10 +00:00
if isinstance(follower[0], Author) and isinstance(topic[0], Topic):
2024-06-09 12:49:37 +00:00
topic = topic[0]
follower = follower[0]
2024-08-06 15:53:25 +00:00
run_background_task(cache_topic(topic.dict()))
run_background_task(cache_author(follower.dict()))
run_background_task(cache_follows(follower.id, "topic", topic.id, is_insert))
2024-04-09 13:59:41 +00:00
2024-08-06 15:53:25 +00:00
async def after_shout_update(_mapper, _connection, shout: Shout):
2024-04-17 15:32:23 +00:00
logger.info("after shout update")
2024-08-06 15:53:25 +00:00
2024-04-09 08:17:32 +00:00
authors_query = (
select(Author)
2024-08-06 15:53:25 +00:00
.join(ShoutAuthor, ShoutAuthor.author == Author.id) # Use join directly with Author
.filter(ShoutAuthor.shout == shout.id)
2024-04-09 08:17:32 +00:00
)
2024-08-06 15:53:25 +00:00
authors_updated = await get_with_stat(authors_query)
2024-05-18 14:41:04 +00:00
for author_with_stat in authors_updated:
2024-08-06 15:53:25 +00:00
run_background_task(cache_author(author_with_stat.dict()))
2024-04-09 08:17:32 +00:00
2024-08-06 15:53:25 +00:00
async def after_reaction_update(mapper, connection, reaction: Reaction):
2024-04-17 15:32:23 +00:00
logger.info("after reaction update")
2024-04-09 08:17:32 +00:00
try:
2024-05-18 14:31:45 +00:00
# reaction author
2024-04-09 08:17:32 +00:00
author_subquery = select(Author).where(Author.id == reaction.created_by)
2024-06-11 14:51:34 +00:00
2024-08-06 15:53:25 +00:00
result = await get_with_stat(author_subquery)
2024-06-11 19:46:35 +00:00
if result:
2024-06-11 14:51:34 +00:00
author_with_stat = result[0]
if isinstance(author_with_stat, Author):
author_dict = author_with_stat.dict()
2024-08-06 15:53:25 +00:00
run_background_task(cache_author(author_dict))
2024-05-18 14:31:45 +00:00
# reaction repliers
2024-04-09 08:17:32 +00:00
replied_author_subquery = (
2024-05-30 04:12:00 +00:00
select(Author).join(Reaction, Author.id == Reaction.created_by).where(Reaction.id == reaction.reply_to)
2024-04-09 08:17:32 +00:00
)
2024-08-06 15:53:25 +00:00
authors_with_stat = await get_with_stat(replied_author_subquery)
2024-05-18 13:16:09 +00:00
for author_with_stat in authors_with_stat:
2024-08-06 15:53:25 +00:00
run_background_task(cache_author(author_with_stat.dict()))
2024-04-09 08:17:32 +00:00
2024-08-06 15:53:25 +00:00
shout_query = select(Shout).where(Shout.id == reaction.shout)
shout_result = await connection.execute(shout_query)
shout = shout_result.scalar_one_or_none()
2024-04-09 08:17:32 +00:00
if shout:
2024-08-06 15:53:25 +00:00
await after_shout_update(mapper, connection, shout)
2024-04-09 08:17:32 +00:00
except Exception as exc:
logger.error(exc)
import traceback
traceback.print_exc()
2024-08-06 15:53:25 +00:00
async def after_author_update(_mapper, _connection, author: Author):
2024-04-17 15:32:23 +00:00
logger.info("after author update")
2024-05-18 11:15:05 +00:00
author_query = select(Author).where(Author.id == author.id)
2024-08-06 15:53:25 +00:00
result = await get_with_stat(author_query)
2024-04-09 08:17:32 +00:00
if result:
2024-06-11 19:46:35 +00:00
author_with_stat = result[0]
author_dict = author_with_stat.dict()
2024-08-06 15:53:25 +00:00
run_background_task(cache_author(author_dict))
2024-04-09 08:17:32 +00:00
2024-08-06 15:53:25 +00:00
async def after_topic_follower_insert(_mapper, _connection, target: TopicFollower):
2024-04-09 08:17:32 +00:00
logger.info(target)
2024-08-06 15:53:25 +00:00
run_background_task(handle_topic_follower_change(target.topic, target.follower, True))
2024-04-09 08:17:32 +00:00
2024-08-06 15:53:25 +00:00
async def after_topic_follower_delete(_mapper, _connection, target: TopicFollower):
2024-04-09 08:17:32 +00:00
logger.info(target)
2024-08-06 15:53:25 +00:00
run_background_task(handle_topic_follower_change(target.topic, target.follower, False))
2024-04-09 08:17:32 +00:00
2024-08-06 15:53:25 +00:00
async def after_author_follower_insert(_mapper, _connection, target: AuthorFollower):
2024-04-09 08:17:32 +00:00
logger.info(target)
2024-08-06 15:53:25 +00:00
run_background_task(handle_author_follower_change(target.author, target.follower, True))
2024-04-09 08:17:32 +00:00
2024-08-06 15:53:25 +00:00
async def after_author_follower_delete(_mapper, _connection, target: AuthorFollower):
2024-04-09 08:17:32 +00:00
logger.info(target)
2024-08-06 15:53:25 +00:00
run_background_task(handle_author_follower_change(target.author, target.follower, False))
2024-04-09 08:17:32 +00:00
def events_register():
2024-04-17 15:32:23 +00:00
event.listen(Shout, "after_insert", after_shout_update)
event.listen(Shout, "after_update", after_shout_update)
2024-04-09 08:17:32 +00:00
2024-04-17 15:32:23 +00:00
event.listen(Reaction, "after_insert", after_reaction_update)
event.listen(Reaction, "after_update", after_reaction_update)
2024-04-09 08:17:32 +00:00
2024-04-17 15:32:23 +00:00
event.listen(Author, "after_insert", after_author_update)
event.listen(Author, "after_update", after_author_update)
2024-04-09 08:17:32 +00:00
2024-04-17 15:32:23 +00:00
event.listen(AuthorFollower, "after_insert", after_author_follower_insert)
event.listen(AuthorFollower, "after_delete", after_author_follower_delete)
2024-04-09 08:17:32 +00:00
2024-04-17 15:32:23 +00:00
event.listen(TopicFollower, "after_insert", after_topic_follower_insert)
event.listen(TopicFollower, "after_delete", after_topic_follower_delete)
2024-04-09 08:17:32 +00:00
2024-04-17 15:32:23 +00:00
logger.info("cache events were registered!")