core/services/cache.py

272 lines
9.3 KiB
Python
Raw Normal View History

2024-02-27 12:40:53 +00:00
import asyncio
import json
2024-02-25 13:43:04 +00:00
2024-04-08 07:38:58 +00:00
from sqlalchemy import event, select
2024-02-27 12:40:53 +00:00
from orm.author import Author, AuthorFollower
from orm.reaction import Reaction
2024-04-08 07:38:58 +00:00
from orm.shout import Shout, ShoutAuthor
2024-02-27 12:40:53 +00:00
from orm.topic import Topic, TopicFollower
from resolvers.stat import get_with_stat
2024-03-06 18:57:04 +00:00
from services.encoders import CustomJSONEncoder
2024-02-27 12:40:53 +00:00
from services.logger import root_logger as logger
2024-04-08 07:38:58 +00:00
from services.rediscache import redis
2024-02-25 13:43:04 +00:00
2024-02-27 12:40:53 +00:00
DEFAULT_FOLLOWS = {
2024-03-28 12:56:32 +00:00
'topics': [],
'authors': [],
'communities': [{'id': 1, 'name': 'Дискурс', 'slug': 'discours', 'pic': ''}],
2024-02-27 12:40:53 +00:00
}
2024-02-25 13:43:04 +00:00
2024-03-06 19:05:17 +00:00
async def set_author_cache(author: dict):
2024-03-06 19:00:37 +00:00
payload = json.dumps(author, cls=CustomJSONEncoder)
2024-03-28 12:56:32 +00:00
await redis.execute('SET', f'user:{author.get("user")}', payload)
await redis.execute('SET', f'author:{author.get("id")}', payload)
2024-03-12 12:50:57 +00:00
async def set_topic_cache(topic: dict):
payload = json.dumps(topic, cls=CustomJSONEncoder)
2024-03-28 12:56:32 +00:00
await redis.execute('SET', f'topic:{topic.get("id")}', payload)
2024-02-27 12:40:53 +00:00
2024-03-06 19:05:17 +00:00
async def update_author_followers_cache(author_id: int, followers):
2024-03-12 11:59:36 +00:00
payload = json.dumps(
[f.dict() if isinstance(f, Author) else f for f in followers],
cls=CustomJSONEncoder,
)
2024-03-28 12:56:32 +00:00
await redis.execute('SET', f'author:{author_id}:followers', payload)
2024-02-29 07:23:08 +00:00
2024-03-06 19:05:17 +00:00
async def set_follows_topics_cache(follows, author_id: int):
2024-02-27 12:40:53 +00:00
try:
2024-03-12 11:59:36 +00:00
payload = json.dumps(
[a.dict() if isinstance(a, Author) else a for a in follows],
cls=CustomJSONEncoder,
)
2024-03-28 12:56:32 +00:00
await redis.execute('SET', f'author:{author_id}:follows-topics', payload)
2024-02-27 12:40:53 +00:00
except Exception as exc:
logger.error(exc)
import traceback
exc = traceback.format_exc()
logger.error(exc)
2024-03-06 19:05:17 +00:00
async def set_follows_authors_cache(follows, author_id: int):
2024-02-27 12:40:53 +00:00
try:
2024-03-12 11:59:36 +00:00
payload = json.dumps(
[a.dict() if isinstance(a, Author) else a for a in follows],
cls=CustomJSONEncoder,
)
2024-03-28 12:56:32 +00:00
await redis.execute('SET', f'author:{author_id}:follows-authors', payload)
2024-03-06 19:05:17 +00:00
except Exception as exc:
2024-02-27 12:40:53 +00:00
import traceback
2024-03-06 19:05:17 +00:00
logger.error(exc)
2024-02-27 12:40:53 +00:00
exc = traceback.format_exc()
logger.error(exc)
2024-03-06 09:25:55 +00:00
async def update_follows_for_author(
follower: Author, entity_type: str, entity: dict, is_insert: bool
):
2024-03-11 10:37:35 +00:00
follows = []
2024-03-28 12:56:32 +00:00
redis_key = f'author:{follower.id}:follows-{entity_type}s'
follows_str = await redis.execute('GET', redis_key)
2024-03-11 10:37:35 +00:00
if isinstance(follows_str, str):
follows = json.loads(follows_str)
2024-02-29 21:51:49 +00:00
if is_insert:
follows.append(entity)
else:
2024-03-28 12:56:32 +00:00
entity_id = entity.get('id')
2024-03-11 14:07:37 +00:00
if not entity_id:
2024-03-28 12:56:32 +00:00
raise Exception('wrong entity')
2024-02-29 21:51:49 +00:00
# Remove the entity from follows
2024-03-28 12:56:32 +00:00
follows = [e for e in follows if e['id'] != entity_id]
2024-03-11 14:07:37 +00:00
logger.debug(f'{entity['slug']} removed from what @{follower.slug} follows')
2024-03-28 12:56:32 +00:00
if entity_type == 'topic':
await set_follows_topics_cache(follows, follower.id)
if entity_type == 'author':
await set_follows_authors_cache(follows, follower.id)
2024-02-29 21:51:49 +00:00
return follows
2024-03-06 09:25:55 +00:00
async def update_followers_for_author(
follower: Author, author: Author, is_insert: bool
):
2024-03-28 12:56:32 +00:00
redis_key = f'author:{author.id}:followers'
followers_str = await redis.execute('GET', redis_key)
2024-03-12 05:00:42 +00:00
followers = []
if isinstance(followers_str, str):
followers = json.loads(followers_str)
2024-02-29 21:51:49 +00:00
if is_insert:
followers.append(follower)
else:
# Remove the entity from followers
2024-03-28 12:56:32 +00:00
followers = [e for e in followers if e['id'] != author.id]
await update_author_followers_cache(author.id, followers)
2024-02-29 21:51:49 +00:00
return followers
2024-03-12 11:59:36 +00:00
def after_shout_update(_mapper, _connection, shout: Shout):
2024-02-27 12:40:53 +00:00
# Main query to get authors associated with the shout through ShoutAuthor
authors_query = (
select(Author)
.select_from(ShoutAuthor) # Select from ShoutAuthor
.join(Author, Author.id == ShoutAuthor.author) # Join with Author
.where(ShoutAuthor.shout == shout.id) # Filter by shout.id
)
for author_with_stat in get_with_stat(authors_query):
2024-02-29 21:51:49 +00:00
asyncio.create_task(set_author_cache(author_with_stat.dict()))
2024-02-27 12:40:53 +00:00
2024-03-12 11:59:36 +00:00
def after_reaction_update(mapper, connection, reaction: Reaction):
2024-02-27 12:40:53 +00:00
try:
author_subquery = select(Author).where(Author.id == reaction.created_by)
replied_author_subquery = (
select(Author)
.join(Reaction, Author.id == Reaction.created_by)
.where(Reaction.id == reaction.reply_to)
)
2024-03-06 09:25:55 +00:00
author_query = (
2024-03-12 11:59:36 +00:00
select(author_subquery.subquery())
2024-03-06 09:25:55 +00:00
.select_from(author_subquery.subquery())
.union(
2024-03-28 12:56:32 +00:00
select(replied_author_subquery.subquery()).select_from(
replied_author_subquery.subquery()
)
2024-02-27 12:40:53 +00:00
)
)
for author_with_stat in get_with_stat(author_query):
2024-02-29 21:51:49 +00:00
asyncio.create_task(set_author_cache(author_with_stat.dict()))
2024-02-27 12:40:53 +00:00
2024-03-06 09:25:55 +00:00
shout = connection.execute(
select(Shout).select_from(Shout).where(Shout.id == reaction.shout)
).first()
2024-02-27 12:40:53 +00:00
if shout:
2024-03-12 11:59:36 +00:00
after_shout_update(mapper, connection, shout)
2024-02-27 12:40:53 +00:00
except Exception as exc:
logger.error(exc)
2024-03-11 10:39:12 +00:00
import traceback
2024-03-12 11:59:36 +00:00
2024-03-11 10:39:12 +00:00
traceback.print_exc()
2024-02-27 12:40:53 +00:00
2024-03-12 07:52:32 +00:00
def after_author_update(_mapper, _connection, author: Author):
2024-02-27 12:40:53 +00:00
q = select(Author).where(Author.id == author.id)
2024-03-04 17:34:11 +00:00
result = get_with_stat(q)
if result:
[author_with_stat] = result
asyncio.create_task(set_author_cache(author_with_stat.dict()))
2024-02-27 12:40:53 +00:00
2024-03-12 07:52:32 +00:00
def after_topic_follower_insert(_mapper, _connection, target: TopicFollower):
2024-02-27 12:40:53 +00:00
asyncio.create_task(
2024-03-28 12:56:32 +00:00
handle_topic_follower_change(target.topic, target.follower, True)
2024-02-27 12:40:53 +00:00
)
2024-03-12 07:52:32 +00:00
def after_topic_follower_delete(_mapper, _connection, target: TopicFollower):
2024-02-27 12:40:53 +00:00
asyncio.create_task(
2024-03-28 12:56:32 +00:00
handle_topic_follower_change(target.topic, target.follower, False)
2024-02-27 12:40:53 +00:00
)
2024-03-12 07:52:32 +00:00
def after_author_follower_insert(_mapper, _connection, target: AuthorFollower):
2024-02-27 12:40:53 +00:00
asyncio.create_task(
2024-03-28 12:56:32 +00:00
handle_author_follower_change(target.author, target.follower, True)
2024-02-27 12:40:53 +00:00
)
2024-03-12 07:52:32 +00:00
def after_author_follower_delete(_mapper, _connection, target: AuthorFollower):
2024-02-27 12:40:53 +00:00
asyncio.create_task(
2024-03-28 12:56:32 +00:00
handle_author_follower_change(target.author, target.follower, False)
2024-02-27 12:40:53 +00:00
)
2024-03-12 11:59:36 +00:00
async def handle_author_follower_change(
author_id: int, follower_id: int, is_insert: bool
):
2024-02-27 12:40:53 +00:00
author_query = select(Author).select_from(Author).filter(Author.id == author_id)
[author] = get_with_stat(author_query)
follower_query = select(Author).select_from(Author).filter(Author.id == follower_id)
2024-03-11 09:10:14 +00:00
[follower] = get_with_stat(follower_query)
2024-02-27 12:40:53 +00:00
if follower and author:
2024-02-29 21:51:49 +00:00
_ = asyncio.create_task(set_author_cache(author.dict()))
2024-03-06 09:25:55 +00:00
follows_authors = await redis.execute(
2024-03-28 12:56:32 +00:00
'GET', f'author:{follower_id}:follows-authors'
2024-03-06 09:25:55 +00:00
)
2024-03-28 11:05:06 +00:00
if isinstance(follows_authors, str):
2024-02-27 12:40:53 +00:00
follows_authors = json.loads(follows_authors)
2024-03-28 12:56:32 +00:00
if not any(x.get('id') == author.id for x in follows_authors):
2024-02-27 12:40:53 +00:00
follows_authors.append(author.dict())
2024-02-29 21:51:49 +00:00
_ = asyncio.create_task(set_follows_authors_cache(follows_authors, follower_id))
_ = asyncio.create_task(set_author_cache(follower.dict()))
2024-02-27 12:40:53 +00:00
await update_follows_for_author(
follower,
2024-03-28 12:56:32 +00:00
'author',
2024-02-27 12:40:53 +00:00
{
2024-03-28 12:56:32 +00:00
'id': author.id,
'name': author.name,
'slug': author.slug,
'pic': author.pic,
'bio': author.bio,
'stat': author.stat,
2024-02-27 12:40:53 +00:00
},
is_insert,
)
2024-03-12 11:59:36 +00:00
async def handle_topic_follower_change(
topic_id: int, follower_id: int, is_insert: bool
):
2024-03-11 09:10:14 +00:00
topic_query = select(Topic).filter(Topic.id == topic_id)
[topic] = get_with_stat(topic_query)
2024-02-27 12:40:53 +00:00
follower_query = select(Author).filter(Author.id == follower_id)
2024-03-11 09:10:14 +00:00
[follower] = get_with_stat(follower_query)
2024-02-27 12:40:53 +00:00
if follower and topic:
2024-02-29 21:51:49 +00:00
_ = asyncio.create_task(set_author_cache(follower.dict()))
2024-03-06 09:25:55 +00:00
follows_topics = await redis.execute(
2024-03-28 12:56:32 +00:00
'GET', f'author:{follower_id}:follows-topics'
2024-03-06 09:25:55 +00:00
)
2024-03-28 11:05:06 +00:00
if isinstance(follows_topics, str):
2024-02-27 12:40:53 +00:00
follows_topics = json.loads(follows_topics)
2024-03-28 12:56:32 +00:00
if not any(x.get('id') == topic.id for x in follows_topics):
2024-02-27 12:40:53 +00:00
follows_topics.append(topic)
2024-02-29 21:51:49 +00:00
_ = asyncio.create_task(set_follows_topics_cache(follows_topics, follower_id))
2024-02-27 12:40:53 +00:00
await update_follows_for_author(
follower,
2024-03-28 12:56:32 +00:00
'topic',
2024-02-27 12:40:53 +00:00
{
2024-03-28 12:56:32 +00:00
'id': topic.id,
'title': topic.title,
'slug': topic.slug,
'body': topic.body,
'stat': topic.stat,
2024-02-27 12:40:53 +00:00
},
is_insert,
)
2024-03-12 11:59:36 +00:00
def events_register():
2024-03-28 12:56:32 +00:00
event.listen(Shout, 'after_insert', after_shout_update)
event.listen(Shout, 'after_update', after_shout_update)
2024-03-12 11:59:36 +00:00
2024-03-28 12:56:32 +00:00
event.listen(Reaction, 'after_insert', after_reaction_update)
event.listen(Reaction, 'after_update', after_reaction_update)
2024-03-12 11:59:36 +00:00
2024-03-28 12:56:32 +00:00
event.listen(Author, 'after_insert', after_author_update)
event.listen(Author, 'after_update', after_author_update)
2024-03-12 11:59:36 +00:00
2024-03-28 12:56:32 +00:00
event.listen(AuthorFollower, 'after_insert', after_author_follower_insert)
event.listen(AuthorFollower, 'after_delete', after_author_follower_delete)
2024-03-12 11:59:36 +00:00
2024-03-28 12:56:32 +00:00
event.listen(TopicFollower, 'after_insert', after_topic_follower_insert)
event.listen(TopicFollower, 'after_delete', after_topic_follower_delete)
2024-03-12 11:59:36 +00:00
logger.info('cache events were registered!')