core/services/stat/topicstat.py

70 lines
2.5 KiB
Python
Raw Normal View History

import asyncio
import time
2022-08-11 05:53:14 +00:00
from base.orm import local_session
from orm.shout import Shout, ShoutTopic, ShoutAuthor
2022-09-19 13:50:43 +00:00
from orm.topic import TopicFollower
# from sqlalchemy.sql.expression import select
2022-09-07 19:36:40 +00:00
class TopicStat:
2022-10-03 21:45:26 +00:00
# by slugs
2022-09-19 13:50:43 +00:00
shouts_by_topic = {} # Shout object stored
authors_by_topic = {} # User
followers_by_topic = {} # User
2022-10-03 21:45:26 +00:00
#
2022-09-03 10:50:14 +00:00
lock = asyncio.Lock()
period = 30 * 60 # sec
2022-09-03 10:50:14 +00:00
@staticmethod
async def load_stat(session):
self = TopicStat
shout_topics = session.query(ShoutTopic, Shout).join(Shout).all()
2022-11-17 06:25:26 +00:00
print("[stat.topics] %d links for shouts" % len(shout_topics))
for [shout_topic, shout] in shout_topics:
2022-09-19 13:50:43 +00:00
tpc = shout_topic.topic
2022-10-03 21:45:26 +00:00
self.shouts_by_topic[tpc] = self.shouts_by_topic.get(tpc, dict())
self.shouts_by_topic[tpc][shout.slug] = shout
self.authors_by_topic[tpc] = self.authors_by_topic.get(tpc, dict())
authors = session.query(
ShoutAuthor.user, ShoutAuthor.caption
).filter(
ShoutAuthor.shout == shout.slug
).all()
for a in authors:
self.authors_by_topic[tpc][a[0]] = a[1]
2022-09-14 13:02:05 +00:00
2022-09-03 10:50:14 +00:00
self.followers_by_topic = {}
2022-09-19 13:50:43 +00:00
followings = session.query(TopicFollower).all()
2022-11-17 06:25:26 +00:00
print("[stat.topics] %d followings by users" % len(followings))
2022-09-03 10:50:14 +00:00
for flw in followings:
topic = flw.topic
2022-10-03 21:45:26 +00:00
userslug = flw.follower
self.followers_by_topic[topic] = self.followers_by_topic.get(topic, dict())
self.followers_by_topic[topic][userslug] = userslug
2022-09-03 10:50:14 +00:00
@staticmethod
async def get_shouts(topic):
self = TopicStat
async with self.lock:
2022-10-03 21:45:26 +00:00
return self.shouts_by_topic.get(topic, dict())
2022-09-03 10:50:14 +00:00
@staticmethod
async def worker():
self = TopicStat
first_run = True
2022-09-03 10:50:14 +00:00
while True:
try:
with local_session() as session:
2022-11-26 07:46:06 +00:00
ts = time.time()
2022-09-03 10:50:14 +00:00
async with self.lock:
await self.load_stat(session)
2022-11-26 07:46:06 +00:00
print("[stat.topicstat] load_stat took %fs " % (time.time() - ts))
2022-09-03 10:50:14 +00:00
except Exception as err:
2022-09-19 13:50:43 +00:00
raise Exception(err)
if first_run:
# sleep for period + 1 min after first run
# to distribute load on server by workers with the same period
await asyncio.sleep(60)
first_run = False
2022-09-03 10:50:14 +00:00
await asyncio.sleep(self.period)