Files
mtusi2026lab4/messenger/service.py
T
nothingredmouth 4b23b44eb8 Перенести приложение мессенджера с сессиями и идемпотентностью в PostgreSQL
Пользователи, аутентификация Argon2id, Bearer-сессии с TTL и отзывом,
транзакционный репозиторий, keyset-пагинация, идемпотентные отправки
(advisory lock + message_requests), версияемые миграции 001/002.
2026-11-17 03:37:07 +00:00

69 lines
3.3 KiB
Python

"""Use cases; independent of Flask and the concrete storage adapter."""
import re
from .domain import fields, string, uuid_value, invalid, ApiError
from .repository import Repository
from .pagination import Pagination
from .security import Authentication
class Messenger:
def __init__(self, repository: Repository, session_ttl=3600, idempotency_ttl=86400):
self.repository = repository
self.idempotency_ttl = idempotency_ttl
self.pagination = Pagination(repository.cursor_key())
self.auth = Authentication(repository, session_ttl)
def register(self, body):
fields(body, ('username', 'display_name', 'password'))
username = string(body['username'], 32)
if not re.fullmatch(r'[a-z0-9_]{3,32}', username):
invalid('Invalid username')
display_name = string(body['display_name'], 100)
password = self.auth.password(body['password'])
return self.repository.create_user(username, display_name, self.auth.hasher.hash(password))
def create_chat(self, actor, body):
fields(body, ('title', 'member_ids'))
title = string(body['title'], 100)
members = body['member_ids']
if not isinstance(members, list) or not 1 <= len(members) <= 100:
invalid('Invalid member list')
members = [uuid_value(m) for m in members]
if len(set(members)) != len(members):
invalid('Duplicate members')
return self.repository.create_chat(actor, title, members)
def chat(self, actor, chat_id):
return self.repository.chat(actor, uuid_value(chat_id))
def send(self, actor, chat_id, body, key):
self.chat(actor, chat_id)
if not isinstance(key, str) or not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key):
invalid('Valid Idempotency-Key required')
if not isinstance(body, dict) or set(body) not in ({'text'}, {'text', 'attachment_ids'}):
invalid('Invalid message fields')
if not isinstance(body['text'], str) or len(body['text']) > 4000 or '\x00' in body['text']:
invalid('Invalid message text')
attachments = body.get('attachment_ids', [])
if not isinstance(attachments, list) or len(attachments) > 10:
invalid('Invalid attachment IDs')
attachments = [uuid_value(item) for item in attachments]
if len(attachments) != len(set(attachments)):
invalid('Duplicate attachment IDs')
if not body['text'].strip() and not attachments:
invalid('Message needs text or attachments')
return self.repository.create_message(actor, uuid_value(chat_id), body['text'],
attachments, key, self.idempotency_ttl)
def chats(self, actor, limit, cursor):
scope = 'chats:' + actor
limit, after = self.pagination.decode(scope, limit, cursor)
return self.pagination.page(self.repository.chats(actor, limit + 1, after), scope, limit)
def history(self, actor, chat_id, limit, cursor):
chat_id = uuid_value(chat_id)
self.repository.chat(actor, chat_id)
scope = 'messages:' + chat_id
limit, after = self.pagination.decode(scope, limit, cursor)
return self.pagination.page(self.repository.messages(actor, chat_id, limit + 1, after), scope, limit)