Merge branch 'feature/core' of https://dev.discours.io/discours.io/core into feature/core
This commit is contained in:
commit
8a0da7381b
|
@ -9,5 +9,7 @@ RUN apt-get update && apt-get install -y git gcc curl postgresql && \
|
||||||
poetry config virtualenvs.create false && \
|
poetry config virtualenvs.create false && \
|
||||||
poetry install --no-dev
|
poetry install --no-dev
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
# Run server when the container launches
|
# Run server when the container launches
|
||||||
CMD granian --no-ws --host 0.0.0.0 --port 8080 --interface asgi main:app
|
CMD python server.py
|
||||||
|
|
16
README.md
16
README.md
|
@ -29,32 +29,32 @@ mkdir .venv
|
||||||
python3.12 -m venv .venv
|
python3.12 -m venv .venv
|
||||||
poetry env use .venv/bin/python3.12
|
poetry env use .venv/bin/python3.12
|
||||||
poetry update
|
poetry update
|
||||||
poetry granian --no-ws --host 0.0.0.0 --port 8080 --interface asgi main:app
|
poetry run main.py
|
||||||
```
|
```
|
||||||
## Подключенные сервисы
|
## Подключенные сервисы
|
||||||
|
|
||||||
Для межсерверной коммуникации используется разны механики, похожим образом это устроено в других сервисах нашей инфраструктуры.
|
Для межсерверной коммуникации используются отдельные логики, папка `services/*` содержит адаптеры для использования базы данных, `redis`, кеширование и клиенты для запросов GraphQL.
|
||||||
|
|
||||||
### auth.py
|
### auth.py
|
||||||
|
|
||||||
Настройте переменную окружения WEBHOOK_SECRET и настройте webhook-полезную нагрузку на /new-author. Он ожидается при создании нового пользователя. На фронтенде включите заголовок Authorization с токеном из запроса signIn или мутации registerUser.
|
Задайте переменную окружения `WEBHOOK_SECRET` чтобы принимать запросы по адресу `/new-author` от [сервера авторизации](https://dev.discours.io/devstack/authorizer). Событие ожидается при создании нового пользователя. Для авторизованных запросов и мутаций фронтенд добавляет к запросу токен авторизации в заголовок `Authorization`.
|
||||||
|
|
||||||
### viewed.py
|
### viewed.py
|
||||||
|
|
||||||
Для статистики просмотров установите переменные окружения GOOGLE_ANALYTICS_TOKEN и GOOGLE_GA_VIEW_ID для сбора данных из Google Analytics.
|
Задайте переменные окружения `GOOGLE_ANALYTICS_TOKEN` и `GOOGLE_GA_VIEW_ID` для сбора данных из [Google Analytics](https://developers.google.com/analytics?hl=ru).
|
||||||
|
|
||||||
### search.py
|
### search.py
|
||||||
|
|
||||||
Результаты ElasticSearch с оценкой `score`, объединенные с запросами к базе данных, запрашиваем через GraphQL API `load_shouts_search`.
|
Позволяет получать результаты пользовательских поисковых запросов в кешируемом виде от [нашего сервера](https://search.discours.io) ElasticSearch с оценкой `score`, объединенные с запросами к базе данных, запрашиваем через GraphQL API `load_shouts_search`.
|
||||||
|
|
||||||
### notify.py
|
### notify.py
|
||||||
|
|
||||||
Отправка уведомлений по Redis PubSub каналам
|
Отправка уведомлений по Redis PubSub каналам, согласно структуре данных, за которую отвечает [сервис уведомлений](https://dev.discours.io/discours.io/notifier)
|
||||||
|
|
||||||
### unread.py
|
### unread.py
|
||||||
|
|
||||||
Счетчик непрочитанных сообщений получается через Redis-запрос к данным сервиса сообщений.
|
Счетчик непрочитанных сообщений получается через Redis-запрос к данным [сервиса сообщений](https://dev.discours.io/discours.io/inbox).
|
||||||
|
|
||||||
### following.py
|
### following.py
|
||||||
|
|
||||||
Внутренний сервис, обеспечивающий асинхронный доступ к оперативному хранилищу подписчиков на комментарии, топики и авторы.
|
Внутренний сервис, обеспечивающий асинхронный доступ к хранилищу подписчиков на комментарии, топики и авторы в оперативной памяти.
|
||||||
|
|
|
@ -77,9 +77,7 @@ async def get_shout(_, _info, slug=None, shout_id=None):
|
||||||
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||||
}
|
}
|
||||||
|
|
||||||
for author_caption in (
|
for author_caption in session.query(ShoutAuthor).join(Shout).where(Shout.slug == slug):
|
||||||
session.query(ShoutAuthor).join(Shout).where(Shout.slug == slug)
|
|
||||||
):
|
|
||||||
for author in shout.authors:
|
for author in shout.authors:
|
||||||
if author.id == author_caption.author:
|
if author.id == author_caption.author:
|
||||||
author.caption = author_caption.caption
|
author.caption = author_caption.caption
|
||||||
|
@ -100,9 +98,7 @@ async def get_shout(_, _info, slug=None, shout_id=None):
|
||||||
shout.main_topic = main_topic[0]
|
shout.main_topic = main_topic[0]
|
||||||
return shout
|
return shout
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(
|
raise HTTPException(status_code=404, detail=f'shout {slug or shout_id} not found')
|
||||||
status_code=404, detail=f'shout {slug or shout_id} not found'
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@query.field('load_shouts_by')
|
@query.field('load_shouts_by')
|
||||||
|
@ -148,9 +144,7 @@ async def load_shouts_by(_, _info, options):
|
||||||
|
|
||||||
# order
|
# order
|
||||||
order_by = options.get('order_by', Shout.published_at)
|
order_by = options.get('order_by', Shout.published_at)
|
||||||
query_order_by = (
|
query_order_by = desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
||||||
desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
|
||||||
)
|
|
||||||
q = q.order_by(nulls_last(query_order_by))
|
q = q.order_by(nulls_last(query_order_by))
|
||||||
|
|
||||||
# limit offset
|
# limit offset
|
||||||
|
@ -243,20 +237,15 @@ async def load_shouts_feed(_, info, options):
|
||||||
with local_session() as session:
|
with local_session() as session:
|
||||||
reader = session.query(Author).filter(Author.user == user_id).first()
|
reader = session.query(Author).filter(Author.user == user_id).first()
|
||||||
if reader:
|
if reader:
|
||||||
reader_followed_authors = select(AuthorFollower.author).where(
|
reader_followed_authors = select(AuthorFollower.author).where(AuthorFollower.follower == reader.id)
|
||||||
AuthorFollower.follower == reader.id
|
reader_followed_topics = select(TopicFollower.topic).where(TopicFollower.follower == reader.id)
|
||||||
)
|
|
||||||
reader_followed_topics = select(TopicFollower.topic).where(
|
|
||||||
TopicFollower.follower == reader.id
|
|
||||||
)
|
|
||||||
|
|
||||||
subquery = (
|
subquery = (
|
||||||
select(Shout.id)
|
select(Shout.id)
|
||||||
.where(Shout.id == ShoutAuthor.shout)
|
.where(Shout.id == ShoutAuthor.shout)
|
||||||
.where(Shout.id == ShoutTopic.shout)
|
.where(Shout.id == ShoutTopic.shout)
|
||||||
.where(
|
.where(
|
||||||
(ShoutAuthor.author.in_(reader_followed_authors))
|
(ShoutAuthor.author.in_(reader_followed_authors)) | (ShoutTopic.topic.in_(reader_followed_topics))
|
||||||
| (ShoutTopic.topic.in_(reader_followed_topics))
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -281,24 +270,15 @@ async def load_shouts_feed(_, info, options):
|
||||||
|
|
||||||
order_by = options.get('order_by', Shout.published_at)
|
order_by = options.get('order_by', Shout.published_at)
|
||||||
|
|
||||||
query_order_by = (
|
query_order_by = desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
||||||
desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
|
||||||
)
|
|
||||||
offset = options.get('offset', 0)
|
offset = options.get('offset', 0)
|
||||||
limit = options.get('limit', 10)
|
limit = options.get('limit', 10)
|
||||||
|
|
||||||
q = (
|
q = q.group_by(Shout.id).order_by(nulls_last(query_order_by)).limit(limit).offset(offset)
|
||||||
q.group_by(Shout.id)
|
|
||||||
.order_by(nulls_last(query_order_by))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset)
|
|
||||||
)
|
|
||||||
|
|
||||||
# print(q.compile(compile_kwargs={"literal_binds": True}))
|
# print(q.compile(compile_kwargs={"literal_binds": True}))
|
||||||
|
|
||||||
for [shout, reacted_stat, commented_stat, _last_comment] in session.execute(
|
for [shout, reacted_stat, commented_stat, _last_comment] in session.execute(q).unique():
|
||||||
q
|
|
||||||
).unique():
|
|
||||||
main_topic = (
|
main_topic = (
|
||||||
session.query(Topic.slug)
|
session.query(Topic.slug)
|
||||||
.join(
|
.join(
|
||||||
|
@ -342,9 +322,7 @@ async def load_shouts_search(_, _info, text, limit=50, offset=0):
|
||||||
.join(Author, Shout.authors) # Ensure this join is not duplicated
|
.join(Author, Shout.authors) # Ensure this join is not duplicated
|
||||||
.join(Topic, Shout.topics) # Ensure this join is not duplicated
|
.join(Topic, Shout.topics) # Ensure this join is not duplicated
|
||||||
.join(Community, Shout.communities) # Ensure this join is not duplicated
|
.join(Community, Shout.communities) # Ensure this join is not duplicated
|
||||||
.where(
|
.where(and_(Shout.deleted_at.is_(None), Shout.slug.in_(results_dict.keys())))
|
||||||
and_(Shout.deleted_at.is_(None), Shout.slug.in_(results_dict.keys()))
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
shouts_data = []
|
shouts_data = []
|
||||||
|
@ -406,9 +384,7 @@ async def load_shouts_unrated(_, info, limit: int = 50, offset: int = 0):
|
||||||
and_(
|
and_(
|
||||||
Reaction.shout == Shout.id,
|
Reaction.shout == Shout.id,
|
||||||
Reaction.replyTo.is_(None),
|
Reaction.replyTo.is_(None),
|
||||||
Reaction.kind.in_(
|
Reaction.kind.in_([ReactionKind.LIKE.value, ReactionKind.DISLIKE.value]),
|
||||||
[ReactionKind.LIKE.value, ReactionKind.DISLIKE.value]
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.outerjoin(Author, Author.user == bindparam('user_id'))
|
.outerjoin(Author, Author.user == bindparam('user_id'))
|
||||||
|
@ -477,9 +453,7 @@ async def load_shouts_random_top(_, _info, options):
|
||||||
|
|
||||||
aliased_reaction = aliased(Reaction)
|
aliased_reaction = aliased(Reaction)
|
||||||
|
|
||||||
subquery = (
|
subquery = select(Shout.id).outerjoin(aliased_reaction).where(Shout.deleted_at.is_(None))
|
||||||
select(Shout.id).outerjoin(aliased_reaction).where(Shout.deleted_at.is_(None))
|
|
||||||
)
|
|
||||||
|
|
||||||
subquery = apply_filters(subquery, options.get('filters', {}))
|
subquery = apply_filters(subquery, options.get('filters', {}))
|
||||||
subquery = subquery.group_by(Shout.id).order_by(
|
subquery = subquery.group_by(Shout.id).order_by(
|
||||||
|
|
17
server.py
Normal file
17
server.py
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
from granian.constants import Interfaces
|
||||||
|
from granian.server import Granian
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print('[server] started')
|
||||||
|
|
||||||
|
granian_instance = Granian(
|
||||||
|
'main:app',
|
||||||
|
address='0.0.0.0', # noqa S104
|
||||||
|
port=8000,
|
||||||
|
workers=2,
|
||||||
|
threads=2,
|
||||||
|
websockets=False,
|
||||||
|
interface=Interfaces.ASGI
|
||||||
|
)
|
||||||
|
granian_instance.serve()
|
Loading…
Reference in New Issue
Block a user