wip refactoring: reactions, storages isolated
This commit is contained in:
62
storages/gittask.py
Normal file
62
storages/gittask.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import asyncio
|
||||
from settings import SHOUTS_REPO
|
||||
|
||||
class GitTask:
|
||||
''' every shout update use a new task '''
|
||||
queue = asyncio.Queue()
|
||||
|
||||
def __init__(self, input, username, user_email, comment):
|
||||
self.slug = input["slug"]
|
||||
self.shout_body = input["body"]
|
||||
self.username = username
|
||||
self.user_email = user_email
|
||||
self.comment = comment
|
||||
|
||||
GitTask.queue.put_nowait(self)
|
||||
|
||||
def init_repo(self):
|
||||
repo_path = "%s" % (SHOUTS_REPO)
|
||||
|
||||
Path(repo_path).mkdir()
|
||||
|
||||
cmd = "cd %s && git init && " \
|
||||
"git config user.name 'discours' && " \
|
||||
"git config user.email 'discours@discours.io' && " \
|
||||
"touch initial && git add initial && " \
|
||||
"git commit -m 'init repo'" \
|
||||
% (repo_path)
|
||||
output = subprocess.check_output(cmd, shell=True)
|
||||
print(output)
|
||||
|
||||
def execute(self):
|
||||
repo_path = "%s" % (SHOUTS_REPO)
|
||||
|
||||
if not Path(repo_path).exists():
|
||||
self.init_repo()
|
||||
|
||||
#cmd = "cd %s && git checkout master" % (repo_path)
|
||||
#output = subprocess.check_output(cmd, shell=True)
|
||||
#print(output)
|
||||
|
||||
shout_filename = "%s.mdx" % (self.slug)
|
||||
shout_full_filename = "%s/%s" % (repo_path, shout_filename)
|
||||
with open(shout_full_filename, mode='w', encoding='utf-8') as shout_file:
|
||||
shout_file.write(bytes(self.shout_body,'utf-8').decode('utf-8','ignore'))
|
||||
|
||||
author = "%s <%s>" % (self.username, self.user_email)
|
||||
cmd = "cd %s && git add %s && git commit -m '%s' --author='%s'" % \
|
||||
(repo_path, shout_filename, self.comment, author)
|
||||
output = subprocess.check_output(cmd, shell=True)
|
||||
print(output)
|
||||
|
||||
@staticmethod
|
||||
async def git_task_worker():
|
||||
print("[resolvers.git] worker start")
|
||||
while True:
|
||||
task = await GitTask.queue.get()
|
||||
try:
|
||||
task.execute()
|
||||
except Exception as err:
|
||||
print("[resolvers.git] worker error: %s" % (err))
|
152
storages/reactions.py
Normal file
152
storages/reactions.py
Normal file
@@ -0,0 +1,152 @@
|
||||
import asyncio
|
||||
from sqlalchemy import and_, desc, func
|
||||
from orm.base import local_session
|
||||
from orm.reaction import Reaction, ReactionKind
|
||||
from orm.topic import ShoutTopic
|
||||
|
||||
|
||||
def kind_to_rate(kind) -> int:
|
||||
if kind in [
|
||||
ReactionKind.AGREE,
|
||||
ReactionKind.LIKE,
|
||||
ReactionKind.PROOF,
|
||||
ReactionKind.ACCEPT
|
||||
]: return 1
|
||||
elif kind in [
|
||||
ReactionKind.DISAGREE,
|
||||
ReactionKind.DISLIKE,
|
||||
ReactionKind.DISPROOF,
|
||||
ReactionKind.REJECT
|
||||
]: return -1
|
||||
else: return 0
|
||||
|
||||
class ReactionsStorage:
|
||||
limit = 200
|
||||
reactions = []
|
||||
rating_by_shout = {}
|
||||
reactions_by_shout = {}
|
||||
reactions_by_topic = {} # TODO: get sum reactions for all shouts in topic
|
||||
reactions_by_author = {}
|
||||
lock = asyncio.Lock()
|
||||
period = 3*60 # 3 mins
|
||||
|
||||
@staticmethod
|
||||
async def prepare_all(session):
|
||||
# FIXME
|
||||
stmt = session.query(Reaction).\
|
||||
filter(Reaction.deletedAt == None).\
|
||||
order_by(desc("createdAt")).\
|
||||
limit(ReactionsStorage.limit)
|
||||
reactions = []
|
||||
for row in session.execute(stmt):
|
||||
reaction = row.Reaction
|
||||
reactions.append(reaction)
|
||||
async with ReactionsStorage.lock:
|
||||
print("[storage.reactions] %d recently published reactions " % len(reactions))
|
||||
ReactionsStorage.reactions = reactions
|
||||
|
||||
@staticmethod
|
||||
async def prepare_by_author(session):
|
||||
try:
|
||||
# FIXME
|
||||
by_authors = session.query(Reaction.createdBy, func.count('*').label("count")).\
|
||||
where(and_(Reaction.deletedAt == None)).\
|
||||
group_by(Reaction.createdBy).all()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
by_authors = {}
|
||||
async with ReactionsStorage.lock:
|
||||
ReactionsStorage.reactions_by_author = dict([stat for stat in by_authors])
|
||||
print("[storage.reactions] %d recently reacted users" % len(by_authors))
|
||||
|
||||
@staticmethod
|
||||
async def prepare_by_shout(session):
|
||||
try:
|
||||
# FIXME
|
||||
by_shouts = session.query(Reaction.shout, func.count('*').label("count")).\
|
||||
where(and_(Reaction.deletedAt == None)).\
|
||||
group_by(Reaction.shout).all()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
by_shouts = {}
|
||||
async with ReactionsStorage.lock:
|
||||
ReactionsStorage.reactions_by_shout = dict([stat for stat in by_shouts])
|
||||
print("[storage.reactions] %d recently reacted shouts" % len(by_shouts))
|
||||
|
||||
@staticmethod
|
||||
async def calc_ratings(session):
|
||||
rating_by_shout = {}
|
||||
for shout in ReactionsStorage.reactions_by_shout.keys():
|
||||
rating_by_shout[shout] = 0
|
||||
shout_reactions_by_kinds = session.query(Reaction).\
|
||||
where(and_(Reaction.deletedAt == None, Reaction.shout == shout)).\
|
||||
group_by(Reaction.kind)
|
||||
for kind, reactions in shout_reactions_by_kinds:
|
||||
rating_by_shout[shout] += len(reactions) * kind_to_rate(kind)
|
||||
async with ReactionsStorage.lock:
|
||||
ReactionsStorage.rating_by_shout = rating_by_shout
|
||||
|
||||
@staticmethod
|
||||
async def prepare_by_topic(session):
|
||||
by_topics = session.query(Reaction.shout, func.count('*').label("count")).\
|
||||
filter(Reaction.deletedAt == None).\
|
||||
join(ShoutTopic, ShoutTopic.shout == Reaction.shout).\
|
||||
order_by(desc("count")).\
|
||||
group_by(ShoutTopic.topic).all()
|
||||
reactions_by_topic = {}
|
||||
for stat in by_topics:
|
||||
if not reactions_by_topic.get(stat.topic):
|
||||
reactions_by_topic[stat.shout] = 0
|
||||
reactions_by_topic[stat.shout] += stat.count
|
||||
async with ReactionsStorage.lock:
|
||||
ReactionsStorage.reactions_by_topic = reactions_by_topic
|
||||
|
||||
@staticmethod
|
||||
async def recent() -> list[Reaction]:
|
||||
async with ReactionsStorage.lock:
|
||||
return ReactionsStorage.reactions.sort(key=lambda x: x.createdAt, reverse=True)
|
||||
|
||||
@staticmethod
|
||||
async def total() -> int:
|
||||
async with ReactionsStorage.lock:
|
||||
return len(ReactionsStorage.reactions)
|
||||
|
||||
@staticmethod
|
||||
async def by_shout(shout) -> int:
|
||||
async with ReactionsStorage.lock:
|
||||
stat = ReactionsStorage.reactions_by_shout.get(shout)
|
||||
stat = stat if stat else 0
|
||||
return stat
|
||||
|
||||
@staticmethod
|
||||
async def shout_rating(shout):
|
||||
async with ReactionsStorage.lock:
|
||||
return ReactionsStorage.rating_by_shout.get(shout)
|
||||
|
||||
@staticmethod
|
||||
async def by_author(slug) -> int:
|
||||
async with ReactionsStorage.lock:
|
||||
stat = ReactionsStorage.reactions_by_author.get(slug)
|
||||
stat = stat if stat else 0
|
||||
return stat
|
||||
|
||||
@staticmethod
|
||||
async def by_topic(topic) -> int:
|
||||
async with ReactionsStorage.lock:
|
||||
stat = ReactionsStorage.reactions_by_topic.get(topic)
|
||||
stat = stat if stat else 0
|
||||
return stat
|
||||
|
||||
@staticmethod
|
||||
async def worker():
|
||||
while True:
|
||||
try:
|
||||
with local_session() as session:
|
||||
await ReactionsStorage.prepare_all(session)
|
||||
await ReactionsStorage.prepare_by_shout(session)
|
||||
await ReactionsStorage.calc_ratings(session)
|
||||
await ReactionsStorage.prepare_by_topic(session)
|
||||
print("[storage.reactions] updated")
|
||||
except Exception as err:
|
||||
print("[storage.reactions] errror: %s" % (err))
|
||||
await asyncio.sleep(ReactionsStorage.period)
|
36
storages/roles.py
Normal file
36
storages/roles.py
Normal file
@@ -0,0 +1,36 @@
|
||||
|
||||
import asyncio
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from orm.rbac import Role
|
||||
|
||||
class RoleStorage:
|
||||
roles = {}
|
||||
lock = asyncio.Lock()
|
||||
|
||||
@staticmethod
|
||||
def init(session):
|
||||
self = RoleStorage
|
||||
roles = session.query(Role).\
|
||||
options(selectinload(Role.permissions)).all()
|
||||
self.roles = dict([(role.id, role) for role in roles])
|
||||
print('[storage.roles] %d ' % len(roles))
|
||||
|
||||
|
||||
@staticmethod
|
||||
async def get_role(id):
|
||||
self = RoleStorage
|
||||
async with self.lock:
|
||||
return self.roles.get(id)
|
||||
|
||||
@staticmethod
|
||||
async def add_role(role):
|
||||
self = RoleStorage
|
||||
async with self.lock:
|
||||
self.roles[id] = role
|
||||
|
||||
@staticmethod
|
||||
async def del_role(id):
|
||||
self = RoleStorage
|
||||
async with self.lock:
|
||||
del self.roles[id]
|
42
storages/shoutauthor.py
Normal file
42
storages/shoutauthor.py
Normal file
@@ -0,0 +1,42 @@
|
||||
|
||||
import asyncio
|
||||
from orm.base import local_session
|
||||
from orm.shout import ShoutAuthor
|
||||
|
||||
|
||||
class ShoutAuthorStorage:
|
||||
authors_by_shout = {}
|
||||
lock = asyncio.Lock()
|
||||
period = 30*60 #sec
|
||||
|
||||
@staticmethod
|
||||
async def load(session):
|
||||
self = ShoutAuthorStorage
|
||||
authors = session.query(ShoutAuthor)
|
||||
for author in authors:
|
||||
user = author.user
|
||||
shout = author.shout
|
||||
if shout in self.authors_by_shout:
|
||||
self.authors_by_shout[shout].append(user)
|
||||
else:
|
||||
self.authors_by_shout[shout] = [user]
|
||||
print('[storage.shoutauthor] %d shouts ' % len(self.authors_by_shout))
|
||||
|
||||
@staticmethod
|
||||
async def get_authors(shout):
|
||||
self = ShoutAuthorStorage
|
||||
async with self.lock:
|
||||
return self.authors_by_shout.get(shout, [])
|
||||
|
||||
@staticmethod
|
||||
async def worker():
|
||||
self = ShoutAuthorStorage
|
||||
while True:
|
||||
try:
|
||||
with local_session() as session:
|
||||
async with self.lock:
|
||||
await self.load(session)
|
||||
print("[storage.shoutauthor] updated")
|
||||
except Exception as err:
|
||||
print("[storage.shoutauthor] errror: %s" % (err))
|
||||
await asyncio.sleep(self.period)
|
150
storages/shoutscache.py
Normal file
150
storages/shoutscache.py
Normal file
@@ -0,0 +1,150 @@
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from sqlalchemy import and_, desc, func, select
|
||||
from sqlalchemy.orm import selectinload
|
||||
from orm.base import local_session
|
||||
from orm.reaction import Reaction
|
||||
from orm.shout import Shout
|
||||
from storages.reactions import ReactionsStorage
|
||||
from storages.viewed import ViewedByDay
|
||||
|
||||
|
||||
class ShoutsCache:
|
||||
limit = 200
|
||||
period = 60*60 #1 hour
|
||||
lock = asyncio.Lock()
|
||||
|
||||
@staticmethod
|
||||
async def prepare_recent_published():
|
||||
with local_session() as session:
|
||||
stmt = select(Shout).\
|
||||
options(selectinload(Shout.authors), selectinload(Shout.topics)).\
|
||||
where(Shout.publishedAt != None).\
|
||||
order_by(desc("publishedAt")).\
|
||||
limit(ShoutsCache.limit)
|
||||
shouts = []
|
||||
for row in session.execute(stmt):
|
||||
shout = row.Shout
|
||||
shout.rating = await ReactionsStorage.shout_rating(shout.slug) or 0
|
||||
shouts.append(shout)
|
||||
async with ShoutsCache.lock:
|
||||
ShoutsCache.recent_published = shouts
|
||||
print("[storage.shoutscache] %d recently published shouts " % len(shouts))
|
||||
|
||||
@staticmethod
|
||||
async def prepare_recent_all():
|
||||
with local_session() as session:
|
||||
stmt = select(Shout).\
|
||||
options(selectinload(Shout.authors), selectinload(Shout.topics)).\
|
||||
order_by(desc("createdAt")).\
|
||||
limit(ShoutsCache.limit)
|
||||
shouts = []
|
||||
for row in session.execute(stmt):
|
||||
shout = row.Shout
|
||||
shout.rating = await ReactionsStorage.shout_rating(shout.slug) or 0
|
||||
shouts.append(shout)
|
||||
async with ShoutsCache.lock:
|
||||
ShoutsCache.recent_all = shouts
|
||||
print("[storage.shoutscache] %d recently created shouts " % len(shouts))
|
||||
|
||||
@staticmethod
|
||||
async def prepare_recent_reacted():
|
||||
with local_session() as session:
|
||||
stmt = select(Shout, func.max(Reaction.createdAt).label("reactionCreatedAt")).\
|
||||
options(selectinload(Shout.authors), selectinload(Shout.topics)).\
|
||||
join(Reaction).\
|
||||
where(and_(Shout.publishedAt != None, Reaction.deletedAt == None)).\
|
||||
group_by(Shout.slug).\
|
||||
order_by(desc("reactionCreatedAt")).\
|
||||
limit(ShoutsCache.limit)
|
||||
shouts = []
|
||||
for row in session.execute(stmt):
|
||||
shout = row.Shout
|
||||
shout.rating = await ReactionsStorage.shout_rating(shout.slug) or 0
|
||||
shouts.append(shout)
|
||||
async with ShoutsCache.lock:
|
||||
ShoutsCache.recent_reacted = shouts
|
||||
print("[storage.shoutscache] %d recently reacted shouts " % len(shouts))
|
||||
|
||||
|
||||
@staticmethod
|
||||
async def prepare_top_overall():
|
||||
with local_session() as session:
|
||||
# with reacted times counter
|
||||
stmt = select(Shout,
|
||||
func.count(Reaction.id).label("reacted")).\
|
||||
options(selectinload(Shout.authors), selectinload(Shout.topics), selectinload(Shout.reactions)).\
|
||||
join(Reaction).\
|
||||
where(and_(Shout.publishedAt != None, Reaction.deletedAt == None)).\
|
||||
group_by(Shout.slug).\
|
||||
order_by(desc("reacted")).\
|
||||
limit(ShoutsCache.limit)
|
||||
shouts = []
|
||||
# with rating synthetic counter
|
||||
for row in session.execute(stmt):
|
||||
shout = row.Shout
|
||||
shout.rating = await ReactionsStorage.shout_rating(shout.slug) or 0
|
||||
shouts.append(shout)
|
||||
shouts.sort(key = lambda shout: shout.rating, reverse = True)
|
||||
async with ShoutsCache.lock:
|
||||
print("[storage.shoutscache] %d top shouts " % len(shouts))
|
||||
ShoutsCache.top_overall = shouts
|
||||
|
||||
@staticmethod
|
||||
async def prepare_top_month():
|
||||
month_ago = datetime.now() - timedelta(days = 30)
|
||||
with local_session() as session:
|
||||
stmt = select(Shout, func.count(Reaction.id).label("reacted")).\
|
||||
options(selectinload(Shout.authors), selectinload(Shout.topics)).\
|
||||
join(Reaction).\
|
||||
where(and_(Shout.createdAt > month_ago, Shout.publishedAt != None)).\
|
||||
group_by(Shout.slug).\
|
||||
order_by(desc("reacted")).\
|
||||
limit(ShoutsCache.limit)
|
||||
shouts = []
|
||||
for row in session.execute(stmt):
|
||||
shout = row.Shout
|
||||
shout.rating = await ReactionsStorage.shout_rating(shout.slug) or 0
|
||||
shouts.append(shout)
|
||||
shouts.sort(key = lambda shout: shout.rating, reverse = True)
|
||||
async with ShoutsCache.lock:
|
||||
print("[storage.shoutscache] %d top month shouts " % len(shouts))
|
||||
ShoutsCache.top_month = shouts
|
||||
|
||||
@staticmethod
|
||||
async def prepare_top_viewed():
|
||||
month_ago = datetime.now() - timedelta(days = 30)
|
||||
with local_session() as session:
|
||||
stmt = select(Shout, func.sum(ViewedByDay.value).label("viewed")).\
|
||||
options(selectinload(Shout.authors), selectinload(Shout.topics)).\
|
||||
join(ViewedByDay).\
|
||||
where(and_(ViewedByDay.day > month_ago, Shout.publishedAt != None)).\
|
||||
group_by(Shout.slug).\
|
||||
order_by(desc("viewed")).\
|
||||
limit(ShoutsCache.limit)
|
||||
shouts = []
|
||||
for row in session.execute(stmt):
|
||||
shout = row.Shout
|
||||
shout.rating = await ReactionsStorage.shout_rating(shout.slug) or 0
|
||||
shouts.append(shout)
|
||||
# shouts.sort(key = lambda shout: shout.viewed, reverse = True)
|
||||
async with ShoutsCache.lock:
|
||||
print("[storage.shoutscache] %d top viewed shouts " % len(shouts))
|
||||
ShoutsCache.top_viewed = shouts
|
||||
|
||||
@staticmethod
|
||||
async def worker():
|
||||
while True:
|
||||
try:
|
||||
await ShoutsCache.prepare_top_month()
|
||||
await ShoutsCache.prepare_top_overall()
|
||||
await ShoutsCache.prepare_top_viewed()
|
||||
await ShoutsCache.prepare_recent_published()
|
||||
await ShoutsCache.prepare_recent_all()
|
||||
await ShoutsCache.prepare_recent_reacted()
|
||||
print("[storage.shoutscache] updated")
|
||||
except Exception as err:
|
||||
print("[storage.shoutscache] error: %s" % (err))
|
||||
raise err
|
||||
await asyncio.sleep(ShoutsCache.period)
|
57
storages/topics.py
Normal file
57
storages/topics.py
Normal file
@@ -0,0 +1,57 @@
|
||||
|
||||
import asyncio
|
||||
from orm.topic import Topic
|
||||
|
||||
|
||||
class TopicStorage:
|
||||
topics = {}
|
||||
lock = asyncio.Lock()
|
||||
|
||||
@staticmethod
|
||||
def init(session):
|
||||
self = TopicStorage
|
||||
topics = session.query(Topic)
|
||||
self.topics = dict([(topic.slug, topic) for topic in topics])
|
||||
for topic in self.topics.values():
|
||||
self.load_parents(topic) # TODO: test
|
||||
|
||||
print('[storage.topics] %d ' % len(self.topics.keys()))
|
||||
|
||||
@staticmethod
|
||||
def load_parents(topic):
|
||||
self = TopicStorage
|
||||
parents = []
|
||||
for parent in self.topics.values():
|
||||
if topic.slug in parent.children:
|
||||
parents.append(parent.slug)
|
||||
topic.parents = parents
|
||||
return topic
|
||||
|
||||
@staticmethod
|
||||
async def get_topics_all():
|
||||
self = TopicStorage
|
||||
async with self.lock:
|
||||
return self.topics.values()
|
||||
|
||||
@staticmethod
|
||||
async def get_topics_by_slugs(slugs):
|
||||
self = TopicStorage
|
||||
async with self.lock:
|
||||
if not slugs:
|
||||
return self.topics.values()
|
||||
topics = filter(lambda topic: topic.slug in slugs, self.topics.values())
|
||||
return list(topics)
|
||||
|
||||
@staticmethod
|
||||
async def get_topics_by_community(community):
|
||||
self = TopicStorage
|
||||
async with self.lock:
|
||||
topics = filter(lambda topic: topic.community == community, self.topics.values())
|
||||
return list(topics)
|
||||
|
||||
@staticmethod
|
||||
async def add_topic(topic):
|
||||
self = TopicStorage
|
||||
async with self.lock:
|
||||
self.topics[topic.slug] = topic
|
||||
self.load_parents(topic)
|
85
storages/topicstat.py
Normal file
85
storages/topicstat.py
Normal file
@@ -0,0 +1,85 @@
|
||||
|
||||
|
||||
import asyncio
|
||||
from orm.base import local_session
|
||||
from storages.shoutauthor import ShoutAuthorStorage
|
||||
from orm.topic import ShoutTopic, TopicFollower
|
||||
|
||||
|
||||
class TopicStat:
|
||||
shouts_by_topic = {}
|
||||
authors_by_topic = {}
|
||||
followers_by_topic = {}
|
||||
reactions_by_topic = {}
|
||||
lock = asyncio.Lock()
|
||||
period = 30*60 #sec
|
||||
|
||||
@staticmethod
|
||||
async def load_stat(session):
|
||||
self = TopicStat
|
||||
self.shouts_by_topic = {}
|
||||
self.authors_by_topic = {}
|
||||
shout_topics = session.query(ShoutTopic)
|
||||
for shout_topic in shout_topics:
|
||||
topic = shout_topic.topic
|
||||
shout = shout_topic.shout
|
||||
if topic in self.shouts_by_topic:
|
||||
self.shouts_by_topic[topic].append(shout)
|
||||
else:
|
||||
self.shouts_by_topic[topic] = [shout]
|
||||
|
||||
authors = await ShoutAuthorStorage.get_authors(shout)
|
||||
if topic in self.authors_by_topic:
|
||||
self.authors_by_topic[topic].update(authors)
|
||||
else:
|
||||
self.authors_by_topic[topic] = set(authors)
|
||||
|
||||
print('[storage.topicstat] authors sorted')
|
||||
print('[storage.topicstat] shouts sorted')
|
||||
|
||||
self.followers_by_topic = {}
|
||||
followings = session.query(TopicFollower)
|
||||
for flw in followings:
|
||||
topic = flw.topic
|
||||
user = flw.follower
|
||||
if topic in self.followers_by_topic:
|
||||
self.followers_by_topic[topic].append(user)
|
||||
else:
|
||||
self.followers_by_topic[topic] = [user]
|
||||
print('[storage.topicstat] followers sorted')
|
||||
|
||||
@staticmethod
|
||||
async def get_shouts(topic):
|
||||
self = TopicStat
|
||||
async with self.lock:
|
||||
return self.shouts_by_topic.get(topic, [])
|
||||
|
||||
@staticmethod
|
||||
async def get_stat(topic) -> dict:
|
||||
self = TopicStat
|
||||
async with self.lock:
|
||||
shouts = self.shouts_by_topic.get(topic, [])
|
||||
followers = self.followers_by_topic.get(topic, [])
|
||||
authors = self.authors_by_topic.get(topic, [])
|
||||
reactions = self.reactions_by_topic.get(topic, [])
|
||||
|
||||
return {
|
||||
"shouts" : len(shouts),
|
||||
"authors" : len(authors),
|
||||
"followers" : len(followers),
|
||||
"reactions" : len(reactions)
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
async def worker():
|
||||
self = TopicStat
|
||||
while True:
|
||||
try:
|
||||
with local_session() as session:
|
||||
async with self.lock:
|
||||
await self.load_stat(session)
|
||||
print("[storage.topicstat] updated")
|
||||
except Exception as err:
|
||||
print("[storage.topicstat] errror: %s" % (err))
|
||||
await asyncio.sleep(self.period)
|
||||
|
43
storages/users.py
Normal file
43
storages/users.py
Normal file
@@ -0,0 +1,43 @@
|
||||
|
||||
import asyncio
|
||||
from sqlalchemy.orm import selectinload
|
||||
from orm.user import User
|
||||
|
||||
|
||||
class UserStorage:
|
||||
users = {}
|
||||
lock = asyncio.Lock()
|
||||
|
||||
@staticmethod
|
||||
def init(session):
|
||||
self = UserStorage
|
||||
users = session.query(User).\
|
||||
options(selectinload(User.roles)).all()
|
||||
self.users = dict([(user.id, user) for user in users])
|
||||
print('[storage.users] %d ' % len(self.users))
|
||||
|
||||
@staticmethod
|
||||
async def get_user(id):
|
||||
self = UserStorage
|
||||
async with self.lock:
|
||||
return self.users.get(id)
|
||||
|
||||
@staticmethod
|
||||
async def get_user_by_slug(slug):
|
||||
self = UserStorage
|
||||
async with self.lock:
|
||||
for user in self.users.values():
|
||||
if user.slug == slug:
|
||||
return user
|
||||
|
||||
@staticmethod
|
||||
async def add_user(user):
|
||||
self = UserStorage
|
||||
async with self.lock:
|
||||
self.users[user.id] = user
|
||||
|
||||
@staticmethod
|
||||
async def del_user(id):
|
||||
self = UserStorage
|
||||
async with self.lock:
|
||||
del self.users[id]
|
122
storages/viewed.py
Normal file
122
storages/viewed.py
Normal file
@@ -0,0 +1,122 @@
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, DateTime, ForeignKey, Integer
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
from orm.base import Base, local_session
|
||||
|
||||
|
||||
class ViewedByDay(Base):
|
||||
__tablename__ = "viewed_by_day"
|
||||
|
||||
id = None
|
||||
shout = Column(ForeignKey('shout.slug'), primary_key=True)
|
||||
day = Column(DateTime, primary_key=True, default=datetime.now)
|
||||
value = Column(Integer)
|
||||
|
||||
|
||||
class ViewedStorage:
|
||||
viewed = {
|
||||
'shouts': {},
|
||||
# TODO: ? 'reactions': {},
|
||||
'topics': {} # TODO: get sum views for all shouts in topic
|
||||
}
|
||||
this_day_views = {}
|
||||
to_flush = []
|
||||
period = 30*60 # sec
|
||||
lock = asyncio.Lock()
|
||||
|
||||
@staticmethod
|
||||
def init(session):
|
||||
self = ViewedStorage
|
||||
views = session.query(ViewedByDay).all()
|
||||
|
||||
for view in views:
|
||||
shout = view.shout
|
||||
value = view.value
|
||||
if shout:
|
||||
old_value = self.viewed['shouts'].get(shout, 0)
|
||||
self.viewed['shouts'][shout] = old_value + value
|
||||
if not shout in self.this_day_views:
|
||||
self.this_day_views[shout] = view
|
||||
this_day_view = self.this_day_views[shout]
|
||||
if this_day_view.day < view.day:
|
||||
self.this_day_views[shout] = view
|
||||
|
||||
print('[storage.viewed] watching %d shouts' % len(views))
|
||||
# TODO: add reactions ?
|
||||
|
||||
@staticmethod
|
||||
async def get_shout(shout_slug):
|
||||
self = ViewedStorage
|
||||
async with self.lock:
|
||||
return self.viewed['shouts'].get(shout_slug, 0)
|
||||
|
||||
# NOTE: this method is never called
|
||||
@staticmethod
|
||||
async def get_reaction(reaction_id):
|
||||
self = ViewedStorage
|
||||
async with self.lock:
|
||||
return self.viewed['reactions'].get(reaction_id, 0)
|
||||
|
||||
@staticmethod
|
||||
async def inc_shout(shout_slug):
|
||||
self = ViewedStorage
|
||||
async with self.lock:
|
||||
this_day_view = self.this_day_views.get(shout_slug)
|
||||
day_start = datetime.now().replace(hour=0, minute=0, second=0)
|
||||
if not this_day_view or this_day_view.day < day_start:
|
||||
if this_day_view and getattr(this_day_view, "modified", False):
|
||||
self.to_flush.append(this_day_view)
|
||||
this_day_view = ViewedByDay.create(shout=shout_slug, value=1)
|
||||
self.this_day_views[shout_slug] = this_day_view
|
||||
else:
|
||||
this_day_view.value = this_day_view.value + 1
|
||||
this_day_view.modified = True
|
||||
old_value = self.viewed['shouts'].get(shout_slug, 0)
|
||||
self.viewed['shotus'][shout_slug] = old_value + 1
|
||||
|
||||
@staticmethod
|
||||
async def inc_reaction(shout_slug, reaction_id):
|
||||
self = ViewedStorage
|
||||
async with self.lock:
|
||||
this_day_view = self.this_day_views.get(reaction_id)
|
||||
day_start = datetime.now().replace(hour=0, minute=0, second=0)
|
||||
if not this_day_view or this_day_view.day < day_start:
|
||||
if this_day_view and getattr(this_day_view, "modified", False):
|
||||
self.to_flush.append(this_day_view)
|
||||
this_day_view = ViewedByDay.create(
|
||||
shout=shout_slug, reaction=reaction_id, value=1)
|
||||
self.this_day_views[shout_slug] = this_day_view
|
||||
else:
|
||||
this_day_view.value = this_day_view.value + 1
|
||||
this_day_view.modified = True
|
||||
old_value = self.viewed['shouts'].get(shout_slug, 0)
|
||||
self.viewed['shouts'][shout_slug] = old_value + 1
|
||||
old_value = self.viewed['reactions'].get(shout_slug, 0)
|
||||
self.viewed['reaction'][reaction_id] = old_value + 1
|
||||
|
||||
@staticmethod
|
||||
async def flush_changes(session):
|
||||
self = ViewedStorage
|
||||
async with self.lock:
|
||||
for view in self.this_day_views.values():
|
||||
if getattr(view, "modified", False):
|
||||
session.add(view)
|
||||
flag_modified(view, "value")
|
||||
view.modified = False
|
||||
for view in self.to_flush:
|
||||
session.add(view)
|
||||
self.to_flush.clear()
|
||||
session.commit()
|
||||
|
||||
@staticmethod
|
||||
async def worker():
|
||||
while True:
|
||||
try:
|
||||
with local_session() as session:
|
||||
await ViewedStorage.flush_changes(session)
|
||||
print("[storage.viewed] storage flushed changes")
|
||||
except Exception as err:
|
||||
print("[storage.viewed] errror: %s" % (err))
|
||||
await asyncio.sleep(ViewedStorage.period)
|
Reference in New Issue
Block a user