forked from mtusi2026/mtusi2026lab7
Добавил TLS и защиту мессенджера для лабораторной 7
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
from fastapi import Request
|
||||
|
||||
from app.core.errors import ApiError
|
||||
from app.repositories.memory import SessionRow, UserRow
|
||||
|
||||
import uuid as _uuid
|
||||
|
||||
BEARER_CHALLENGE = {'WWW-Authenticate': 'Bearer realm="messenger"'}
|
||||
|
||||
|
||||
def storage_of(request: Request):
|
||||
return request.app.state.storage
|
||||
|
||||
|
||||
async def current_session(request: Request) -> SessionRow:
|
||||
header = request.headers.get('authorization', '')
|
||||
token = header[7:].strip() if header[:7].lower() == 'bearer ' else ''
|
||||
if not token:
|
||||
raise ApiError(401, 'Bearer session required', headers=BEARER_CHALLENGE)
|
||||
row = await storage_of(request).session(token)
|
||||
if row is None:
|
||||
raise ApiError(401, 'Session is missing, expired or revoked', headers=BEARER_CHALLENGE)
|
||||
return row
|
||||
|
||||
|
||||
async def current_user(request: Request) -> UserRow:
|
||||
session = await current_session(request)
|
||||
user = await storage_of(request).user(session.user_id)
|
||||
if user is None:
|
||||
raise ApiError(401, 'Session user no longer exists', headers=BEARER_CHALLENGE)
|
||||
return user
|
||||
|
||||
|
||||
async def require_chat_member(request: Request, chat_id: str, user: UserRow):
|
||||
try:
|
||||
_uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, 'chat_id must be a UUID')
|
||||
row = await storage_of(request).chat(chat_id)
|
||||
if row is None or user.id not in row.member_ids:
|
||||
raise ApiError(404, 'Chat is not available for this user')
|
||||
return row
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import hashlib
|
||||
import io
|
||||
import unicodedata
|
||||
import uuid
|
||||
import warnings
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from app.api.deps import current_user, require_chat_member
|
||||
from app.core.config import settings
|
||||
from app.core.errors import ApiError
|
||||
|
||||
router = APIRouter()
|
||||
MIME_BY_FORMAT = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}
|
||||
|
||||
|
||||
def _validate_filename(filename: str) -> None:
|
||||
if not filename or len(filename) > 255 or not filename.strip():
|
||||
raise ApiError(400, 'Invalid filename')
|
||||
if any(ch in filename for ch in ('/', chr(92))):
|
||||
raise ApiError(400, 'Invalid filename')
|
||||
if any(ord(ch) == 0 or unicodedata.category(ch).startswith('C') for ch in filename):
|
||||
raise ApiError(400, 'Invalid filename')
|
||||
|
||||
|
||||
async def _read_bounded_body(request: Request) -> bytes:
|
||||
length = request.headers.get('content-length')
|
||||
if length:
|
||||
try:
|
||||
size = int(length)
|
||||
except ValueError:
|
||||
raise ApiError(400, 'Invalid Content-Length') from None
|
||||
if size < 0:
|
||||
raise ApiError(400, 'Invalid Content-Length')
|
||||
if size > settings.max_upload_bytes:
|
||||
raise ApiError(413, 'Image exceeds the maximum size')
|
||||
chunks = []
|
||||
total = 0
|
||||
async for chunk in request.stream():
|
||||
total += len(chunk)
|
||||
if total > settings.max_upload_bytes:
|
||||
raise ApiError(413, 'Image exceeds the maximum size')
|
||||
chunks.append(chunk)
|
||||
if total == 0:
|
||||
raise ApiError(415, 'Empty or invalid image')
|
||||
return b''.join(chunks)
|
||||
|
||||
|
||||
def _validate_image(data: bytes, declared_type: str) -> None:
|
||||
if declared_type not in {'image/png', 'image/jpeg'}:
|
||||
raise ApiError(415, 'Only PNG and JPEG images are accepted')
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
actual_type = MIME_BY_FORMAT.get(image.format)
|
||||
width, height = image.size
|
||||
if actual_type is None or actual_type != declared_type:
|
||||
raise ApiError(415, 'Image content does not match Content-Type')
|
||||
if width < 1 or height < 1:
|
||||
raise ApiError(415, 'Invalid image dimensions')
|
||||
if width * height > settings.max_image_pixels:
|
||||
raise ApiError(413, 'Image exceeds the maximum pixel count')
|
||||
image.verify()
|
||||
except ApiError:
|
||||
raise
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError,
|
||||
Image.DecompressionBombWarning, OSError, SyntaxError, ValueError):
|
||||
raise ApiError(415, 'Image content is invalid or unsupported') from None
|
||||
|
||||
|
||||
def attachment_out(row) -> dict:
|
||||
return {
|
||||
'id': row.id,
|
||||
'chat_id': row.chat_id,
|
||||
'owner_id': row.owner_id,
|
||||
'filename': row.filename,
|
||||
'content_type': row.content_type,
|
||||
'size_bytes': row.size_bytes,
|
||||
'sha256': row.sha256,
|
||||
'status': row.status,
|
||||
'variants': row.variants,
|
||||
'error_code': row.error_code,
|
||||
'created_at': row.created_at,
|
||||
'updated_at': row.updated_at,
|
||||
}
|
||||
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/attachments', status_code=202)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
filename: str = Query(min_length=1, max_length=255),
|
||||
):
|
||||
user = await current_user(request)
|
||||
chat = await require_chat_member(request, chat_id, user)
|
||||
_validate_filename(filename)
|
||||
content_type = request.headers.get('content-type', '').split(';', 1)[0].strip().lower()
|
||||
if content_type not in {'image/png', 'image/jpeg'}:
|
||||
raise ApiError(415, 'Only PNG and JPEG images are accepted')
|
||||
data = await _read_bounded_body(request)
|
||||
_validate_image(data, content_type)
|
||||
|
||||
attachment_id = str(uuid.uuid4())
|
||||
job_id = str(uuid.uuid4())
|
||||
staging_key = f'staging/{attachment_id}'
|
||||
object_key = f'original/{attachment_id}'
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
object_store = request.app.state.object_store
|
||||
# Ответ 202 появится только после долговременной записи исходника и задания.
|
||||
await object_store.put(staging_key, data, content_type)
|
||||
try:
|
||||
row = await request.app.state.storage.create_attachment(
|
||||
attachment_id=attachment_id,
|
||||
job_id=job_id,
|
||||
chat_id=chat.id,
|
||||
owner_id=user.id,
|
||||
object_key=object_key,
|
||||
staging_key=staging_key,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
size_bytes=len(data),
|
||||
sha256=digest,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await object_store.delete(staging_key)
|
||||
except ApiError:
|
||||
pass
|
||||
raise
|
||||
return JSONResponse(status_code=202, content=attachment_out(row))
|
||||
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}')
|
||||
async def get_attachment(attachment_id: str, request: Request):
|
||||
user = await current_user(request)
|
||||
row = await request.app.state.storage.attachment_for_member(attachment_id, user.id)
|
||||
if row is None:
|
||||
raise ApiError(404, 'Attachment is not available for this user')
|
||||
return attachment_out(row)
|
||||
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}/content')
|
||||
async def download_attachment(
|
||||
attachment_id: str,
|
||||
request: Request,
|
||||
variant: str = Query(default='original', min_length=1, max_length=32),
|
||||
):
|
||||
user = await current_user(request)
|
||||
row = await request.app.state.storage.attachment_for_member(attachment_id, user.id)
|
||||
if row is None:
|
||||
raise ApiError(404, 'Attachment is not available for this user')
|
||||
if row.status in {'queued', 'processing', 'failed'}:
|
||||
raise ApiError(409, 'Attachment content is not ready')
|
||||
|
||||
if variant == 'original':
|
||||
object_key, content_type = row.object_key, row.content_type
|
||||
else:
|
||||
metadata = next((item for item in row.variants if item.get('name') == variant), None)
|
||||
if metadata is None:
|
||||
raise ApiError(404, 'Attachment variant does not exist')
|
||||
object_key = f"variants/{row.id}/v1/{variant}.jpg"
|
||||
content_type = metadata['content_type']
|
||||
data = await request.app.state.object_store.get(object_key)
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=content_type,
|
||||
headers={'Cache-Control': 'private, no-store'},
|
||||
)
|
||||
@@ -0,0 +1,49 @@
|
||||
import hashlib
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import Response
|
||||
|
||||
from app.api.deps import current_session
|
||||
from app.api.serialize import user_out
|
||||
from app.core.config import settings
|
||||
from app.core.errors import ApiError
|
||||
from app.core.security import parse_basic, verify_password
|
||||
from app.repositories.memory import iso_z
|
||||
|
||||
router = APIRouter()
|
||||
BASIC_CHALLENGE = {'WWW-Authenticate': 'Basic realm="messenger", charset="UTF-8"'}
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions', status_code=201)
|
||||
async def login(request: Request):
|
||||
# Общий фиксированный интервал защищает все API-реплики от перебора пароля.
|
||||
creds = parse_basic(request.headers.get('authorization', ''))
|
||||
remote = request.client.host if request.client else 'unknown'
|
||||
identity = creds[0] if creds else 'malformed'
|
||||
account_hash = hashlib.sha256(identity.casefold().encode('utf-8')).hexdigest()
|
||||
key = 'login-rate:' + hashlib.sha256(remote.encode('utf-8')).hexdigest() + ':' + account_hash
|
||||
try:
|
||||
count = await request.app.state.redis.incr(key)
|
||||
if count == 1:
|
||||
await request.app.state.redis.expire(key, 60)
|
||||
if count > 10:
|
||||
ttl = max(1, int(await request.app.state.redis.ttl(key)))
|
||||
raise ApiError(429, 'Too many login attempts', headers={'Retry-After': str(ttl)})
|
||||
except ApiError:
|
||||
raise
|
||||
except Exception:
|
||||
raise ApiError(503, 'Login rate limiter is unavailable') from None
|
||||
storage = request.app.state.storage
|
||||
row = await storage.user_by_username(creds[0]) if creds else None
|
||||
if creds is None or row is None or not verify_password(row.password_hash, creds[1]):
|
||||
raise ApiError(401, 'Invalid credentials', headers=BASIC_CHALLENGE)
|
||||
session = await storage.create_session(row.id, settings.session_ttl_seconds)
|
||||
return {'token': session.token, 'token_type': 'Bearer',
|
||||
'expires_at': iso_z(session.expires_at), 'user': user_out(row)}
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current', status_code=204)
|
||||
async def logout(request: Request):
|
||||
session = await current_session(request)
|
||||
await request.app.state.storage.revoke(session.token)
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,33 @@
|
||||
from fastapi import APIRouter, Query, Request
|
||||
|
||||
from app.api.deps import current_user, require_chat_member
|
||||
from app.api.serialize import chat_out
|
||||
from app.core.cursors import decode_cursor, paginate
|
||||
from app.schemas import CreateChat
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post('/api/v1/chats', status_code=201)
|
||||
async def create_chat(body: CreateChat, request: Request):
|
||||
user = await current_user(request)
|
||||
member_ids = [str(mid) for mid in body.member_ids]
|
||||
row = await request.app.state.storage.create_chat(body.title, member_ids, user.id)
|
||||
return chat_out(row)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats')
|
||||
async def list_chats(request: Request, limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None, min_length=1)):
|
||||
user = await current_user(request)
|
||||
resource = 'chats:' + user.id
|
||||
key = decode_cursor(cursor, resource) if cursor else None
|
||||
rows = await request.app.state.storage.chats_of(user.id)
|
||||
page, next_cursor = paginate(rows, key, limit, resource)
|
||||
return {'items': [chat_out(r) for r in page], 'next_cursor': next_cursor}
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}')
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user = await current_user(request)
|
||||
return chat_out(await require_chat_member(request, chat_id, user))
|
||||
@@ -0,0 +1,17 @@
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.core.errors import ApiError
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get('/health/live')
|
||||
async def live():
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
@router.get('/health/ready')
|
||||
async def ready(request: Request):
|
||||
if not await request.app.state.storage.ready():
|
||||
raise ApiError(503, 'Storage is unavailable')
|
||||
return {'status': 'ok'}
|
||||
@@ -0,0 +1,11 @@
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.api.deps import current_user
|
||||
from app.api.serialize import user_out
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me')
|
||||
async def me(request: Request):
|
||||
return user_out(await current_user(request))
|
||||
@@ -0,0 +1,52 @@
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Header, Query, Request
|
||||
|
||||
from app.api.deps import current_user, require_chat_member
|
||||
from app.api.serialize import message_out
|
||||
from app.core.cursors import decode_cursor, encode_cursor
|
||||
from app.core.errors import ApiError
|
||||
from app.schemas import CreateMessage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/messages', status_code=201)
|
||||
async def create_message(
|
||||
body: CreateMessage,
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(
|
||||
default=None, alias='Idempotency-Key', min_length=1, max_length=128,
|
||||
pattern=r'^[A-Za-z0-9._:-]{1,128}$',
|
||||
),
|
||||
):
|
||||
if idempotency_key is None:
|
||||
raise ApiError(400, 'Idempotency-Key is required')
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
raise ApiError(400, 'Message must contain text or at least one attachment')
|
||||
user = await current_user(request)
|
||||
chat = await require_chat_member(request, chat_id, user)
|
||||
normalized_body = json.dumps(
|
||||
body.model_dump(mode='json'), ensure_ascii=False, sort_keys=True, separators=(',', ':')
|
||||
).encode('utf-8')
|
||||
body_hash = hashlib.sha256(normalized_body).digest()
|
||||
row = await request.app.state.storage.add_idempotent_message(
|
||||
chat.id, user.id, body.text, [str(value) for value in body.attachment_ids],
|
||||
idempotency_key, body_hash,
|
||||
)
|
||||
return message_out(row)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}/messages')
|
||||
async def list_messages(request: Request, chat_id: str,
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None, min_length=1)):
|
||||
user = await current_user(request)
|
||||
chat = await require_chat_member(request, chat_id, user)
|
||||
resource = 'messages:' + chat.id
|
||||
key = decode_cursor(cursor, resource) if cursor else None
|
||||
rows, has_more = await request.app.state.storage.messages_page(chat.id, key, limit)
|
||||
next_cursor = encode_cursor(resource, rows[-1].created_at, rows[-1].id) if has_more else None
|
||||
return {'items': [message_out(row) for row in rows], 'next_cursor': next_cursor}
|
||||
@@ -0,0 +1,14 @@
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.api.serialize import user_out
|
||||
from app.core.security import hash_password
|
||||
from app.schemas import CreateUser
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post('/api/v1/users', status_code=201)
|
||||
async def register(body: CreateUser, request: Request):
|
||||
row = await request.app.state.storage.create_user(
|
||||
body.username, body.display_name, hash_password(body.password))
|
||||
return user_out(row)
|
||||
@@ -0,0 +1,17 @@
|
||||
from app.repositories.memory import UserRow
|
||||
|
||||
|
||||
def user_out(row: UserRow) -> dict:
|
||||
return {'id': row.id, 'username': row.username,
|
||||
'display_name': row.display_name, 'created_at': row.created_at}
|
||||
|
||||
|
||||
def chat_out(row) -> dict:
|
||||
return {'id': row.id, 'title': row.title,
|
||||
'member_ids': list(row.member_ids), 'created_at': row.created_at}
|
||||
|
||||
|
||||
def message_out(row) -> dict:
|
||||
return {'id': row.id, 'chat_id': row.chat_id, 'sender_id': row.sender_id,
|
||||
'text': row.text, 'created_at': row.created_at,
|
||||
'attachment_ids': list(row.attachment_ids)}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore')
|
||||
|
||||
app_host: str = '0.0.0.0'
|
||||
app_port: int = 8080
|
||||
session_ttl_seconds: int = 3600
|
||||
database_url: str = ''
|
||||
database_url_file: str | None = None
|
||||
redis_url: str = 'redis://localhost:6379/0'
|
||||
redis_url_file: str | None = None
|
||||
db_pool_min_size: int = 1
|
||||
db_pool_max_size: int = 10
|
||||
db_pool_acquire_timeout_seconds: float = 3.0
|
||||
db_command_timeout_seconds: float = 5.0
|
||||
redis_timeout_seconds: float = 2.0
|
||||
s3_endpoint_url: str = 'http://localhost:9000'
|
||||
s3_region: str = 'us-east-1'
|
||||
s3_bucket: str = 'messenger-attachments'
|
||||
s3_access_key_id: str = ''
|
||||
s3_access_key_id_file: str | None = None
|
||||
s3_secret_access_key: str = ''
|
||||
s3_secret_access_key_file: str | None = None
|
||||
s3_connect_timeout_seconds: float = 3.0
|
||||
s3_read_timeout_seconds: float = 10.0
|
||||
max_upload_bytes: int = Field(default=10_485_760, ge=1, le=10_485_760)
|
||||
max_image_pixels: int = Field(default=40_000_000, ge=1, le=40_000_000)
|
||||
tls_ca_file: str = '/run/secrets/ca.crt'
|
||||
bao_addr: str = 'https://openbao:8200'
|
||||
bao_cacert: str = '/run/secrets/ca.crt'
|
||||
bao_role_id_file: str = '/run/secrets/bao_role_id'
|
||||
bao_secret_id_file: str = '/run/secrets/bao_secret_id'
|
||||
bao_secret_path: str = 'messenger/api'
|
||||
|
||||
def resolved_database_url(self) -> str:
|
||||
if self.database_url_file:
|
||||
return Path(self.database_url_file).read_text(encoding='utf-8').strip()
|
||||
return self.database_url
|
||||
|
||||
def resolved_redis_url(self) -> str:
|
||||
if self.redis_url_file:
|
||||
return Path(self.redis_url_file).read_text(encoding='utf-8').strip()
|
||||
return self.redis_url
|
||||
|
||||
def resolved_s3_access_key_id(self) -> str:
|
||||
if self.s3_access_key_id_file:
|
||||
return Path(self.s3_access_key_id_file).read_text(encoding='utf-8').strip()
|
||||
return self.s3_access_key_id
|
||||
|
||||
def resolved_s3_secret_access_key(self) -> str:
|
||||
if self.s3_secret_access_key_file:
|
||||
return Path(self.s3_secret_access_key_file).read_text(encoding='utf-8').strip()
|
||||
return self.s3_secret_access_key
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,37 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app.core.errors import ApiError
|
||||
from app.repositories.memory import order_key
|
||||
|
||||
|
||||
def encode_cursor(resource: str, created_at: str, row_id: str) -> str:
|
||||
payload = json.dumps({'r': resource, 't': created_at, 'i': row_id}, separators=(',', ':'))
|
||||
return base64.urlsafe_b64encode(payload.encode()).decode()
|
||||
|
||||
|
||||
def decode_cursor(value: str, resource: str) -> tuple[datetime, int]:
|
||||
"""Курсор от другого ресурса или битый -> 400 invalid_request."""
|
||||
try:
|
||||
payload = json.loads(base64.urlsafe_b64decode(value.encode()))
|
||||
if payload['r'] != resource:
|
||||
raise ValueError('cursor belongs to another resource')
|
||||
moment = datetime.fromisoformat(payload['t'].replace('Z', '+00:00'))
|
||||
return moment, uuid.UUID(payload['i']).int
|
||||
except (ValueError, KeyError, TypeError, binascii.Error):
|
||||
raise ApiError(400, 'Invalid cursor')
|
||||
|
||||
|
||||
def paginate(rows: list, cursor_key, limit: int, resource: str):
|
||||
"""Keyset: берём строки строго после (created_at, id) курсора, без offset-скана."""
|
||||
if cursor_key is not None:
|
||||
rows = [r for r in rows if order_key(r.created_dt, r.id) > cursor_key]
|
||||
page = rows[:limit]
|
||||
next_cursor = None
|
||||
if len(rows) > limit: # следующая запись есть на момент чтения
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(resource, last.created_at, last.id)
|
||||
return page, next_cursor
|
||||
@@ -0,0 +1,72 @@
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
CODES = {400: 'invalid_request', 401: 'unauthorized', 404: 'not_found', 409: 'conflict',
|
||||
413: 'payload_too_large', 415: 'unsupported_media_type', 429: 'rate_limited',
|
||||
503: 'unavailable', 500: 'internal_error'}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
"""Бизнес-ошибка: HTTP-статус + код контракта + безопасное сообщение."""
|
||||
|
||||
def __init__(self, status_code: int, message: str, code: str | None = None,
|
||||
headers: dict | None = None):
|
||||
self.status_code = status_code
|
||||
self.code = code or CODES.get(status_code, 'internal_error')
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
"""Каждый ответ, включая 204 и ошибки, несёт непустой X-Request-Id."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
response = await call_next(request)
|
||||
response.headers['X-Request-Id'] = request.state.request_id
|
||||
response.headers['X-Instance-Id'] = os.environ.get('INSTANCE_ID') or socket.gethostname()
|
||||
return response
|
||||
|
||||
|
||||
def _body(request: Request, status_code: int, code: str, message: str,
|
||||
headers: dict | None = None) -> JSONResponse:
|
||||
rid = getattr(request.state, 'request_id', str(uuid.uuid4()))
|
||||
return JSONResponse(status_code=status_code, headers=headers,
|
||||
content={'error': {'code': code, 'message': message, 'request_id': rid}})
|
||||
|
||||
|
||||
def register_error_handlers(app: FastAPI) -> None:
|
||||
@app.exception_handler(ApiError)
|
||||
async def on_api_error(request: Request, exc: ApiError):
|
||||
return _body(request, exc.status_code, exc.code, exc.message, exc.headers)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def on_validation(request: Request, exc: RequestValidationError):
|
||||
return _body(request, 400, 'invalid_request', 'Request validation failed')
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def on_http(request: Request, exc: StarletteHTTPException):
|
||||
code = CODES.get(exc.status_code, 'invalid_request')
|
||||
return _body(request, exc.status_code, code, 'Route or method not found')
|
||||
|
||||
async def on_dependency_failure(request: Request, exc: Exception):
|
||||
return _body(request, 503, 'unavailable', 'A required service is unavailable')
|
||||
|
||||
app.add_exception_handler(asyncpg.PostgresError, on_dependency_failure)
|
||||
app.add_exception_handler(RedisError, on_dependency_failure)
|
||||
app.add_exception_handler(OSError, on_dependency_failure)
|
||||
app.add_exception_handler(TimeoutError, on_dependency_failure)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def on_unexpected(request: Request, exc: Exception):
|
||||
return _body(request, 500, 'internal_error', 'Internal error')
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Клиент OpenBao AppRole; токены и тела ответов намеренно не попадают в журнал."""
|
||||
import json
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
class SecretBootstrapError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _post(path: str, payload: dict, token: str | None = None) -> dict:
|
||||
body = json.dumps(payload).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
settings.bao_addr.rstrip('/') + '/v1/' + path.lstrip('/'),
|
||||
data=body,
|
||||
headers={'Content-Type': 'application/json', **({'X-Vault-Token': token} if token else {})},
|
||||
method='POST',
|
||||
)
|
||||
context = ssl.create_default_context(cafile=settings.bao_cacert)
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=context, timeout=4) as response:
|
||||
return json.loads(response.read())
|
||||
except (OSError, urllib.error.URLError, ValueError):
|
||||
raise SecretBootstrapError('OpenBao authentication or secret read failed') from None
|
||||
|
||||
|
||||
def load_service_secrets() -> dict[str, str]:
|
||||
"""Войти по AppRole текущего сервиса и прочитать только назначенный ему KV-путь."""
|
||||
try:
|
||||
role_id = Path(settings.bao_role_id_file).read_text(encoding='utf-8').strip()
|
||||
secret_id = Path(settings.bao_secret_id_file).read_text(encoding='utf-8').strip()
|
||||
if not role_id or not secret_id:
|
||||
raise ValueError('empty AppRole credentials')
|
||||
except OSError:
|
||||
raise SecretBootstrapError('OpenBao AppRole files are unavailable') from None
|
||||
login = _post('auth/approle/login', {'role_id': role_id, 'secret_id': secret_id})
|
||||
token = login.get('auth', {}).get('client_token')
|
||||
if not token:
|
||||
raise SecretBootstrapError('OpenBao AppRole login returned no token')
|
||||
try:
|
||||
request = urllib.request.Request(
|
||||
settings.bao_addr.rstrip('/') + '/v1/secret/data/' + settings.bao_secret_path.lstrip('/'),
|
||||
headers={'X-Vault-Token': token}, method='GET')
|
||||
context = ssl.create_default_context(cafile=settings.bao_cacert)
|
||||
with urllib.request.urlopen(request, context=context, timeout=4) as response:
|
||||
result = json.loads(response.read())
|
||||
data = result['data']['data']
|
||||
if not isinstance(data, dict) or not data:
|
||||
raise ValueError('empty KV data')
|
||||
return {str(key): str(value) for key, value in data.items()}
|
||||
except (OSError, urllib.error.URLError, ValueError, KeyError, TypeError):
|
||||
raise SecretBootstrapError('OpenBao scoped secret read failed') from None
|
||||
@@ -0,0 +1,45 @@
|
||||
import base64
|
||||
import binascii
|
||||
import secrets
|
||||
|
||||
import os
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import Argon2Error
|
||||
|
||||
_ph = PasswordHasher(
|
||||
type=Type.ID,
|
||||
time_cost=int(os.getenv("ARGON2_ITERATIONS", "2")),
|
||||
memory_cost=int(os.getenv("ARGON2_MEMORY_KIB", "19456")),
|
||||
parallelism=int(os.getenv("ARGON2_PARALLELISM", "1")),
|
||||
) # Минимальные параметры Argon2id по OWASP: 19 МиБ, 2 прохода, 1 поток.
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(digest: str, password: str) -> bool:
|
||||
try:
|
||||
return _ph.verify(digest, password)
|
||||
except (Argon2Error, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_hex(32) # 32 байта = 256 бит энтропии
|
||||
|
||||
|
||||
def parse_basic(header: str) -> tuple[str, str] | None:
|
||||
"""Преобразовать 'Basic base64(username:password)' в пару (username, password) или вернуть None."""
|
||||
parts = header.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'basic':
|
||||
return None
|
||||
try:
|
||||
raw = base64.b64decode(parts[1].strip(), validate=True)
|
||||
text = raw.decode('utf-8')
|
||||
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||
return None
|
||||
if ':' not in text:
|
||||
return None
|
||||
username, password = text.split(':', 1) # двоеточие в пароле допустимо
|
||||
return username, password
|
||||
@@ -0,0 +1 @@
|
||||
"""Настройка базы данных и миграции схемы."""
|
||||
@@ -0,0 +1,62 @@
|
||||
from pathlib import Path
|
||||
|
||||
import asyncpg
|
||||
import asyncio
|
||||
import ssl
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / 'migrations'
|
||||
|
||||
|
||||
async def apply_migrations(pool: asyncpg.Pool) -> None:
|
||||
"""Применить каждую нумерованную SQL-миграцию один раз в транзакции под advisory lock."""
|
||||
async with pool.acquire() as connection:
|
||||
await connection.execute('SELECT pg_advisory_lock($1)', 762019002)
|
||||
try:
|
||||
await connection.execute(
|
||||
'CREATE TABLE IF NOT EXISTS schema_migrations ('
|
||||
' version integer PRIMARY KEY,'
|
||||
' applied_at timestamptz NOT NULL DEFAULT now())'
|
||||
)
|
||||
applied = {
|
||||
row['version']
|
||||
for row in await connection.fetch('SELECT version FROM schema_migrations')
|
||||
}
|
||||
for path in sorted(MIGRATIONS_DIR.glob('[0-9]*_*.sql')):
|
||||
version = int(path.name.split('_', 1)[0])
|
||||
if version in applied:
|
||||
continue
|
||||
async with connection.transaction():
|
||||
await connection.execute(path.read_text(encoding='utf-8'))
|
||||
await connection.execute(
|
||||
'INSERT INTO schema_migrations (version) VALUES ($1)', version
|
||||
)
|
||||
finally:
|
||||
await connection.execute('SELECT pg_advisory_unlock($1)', 762019002)
|
||||
|
||||
async def _main() -> None:
|
||||
from app.core.config import settings
|
||||
from app.core.openbao import load_service_secrets
|
||||
|
||||
secrets = await asyncio.to_thread(load_service_secrets)
|
||||
settings.database_url = secrets['database_url']
|
||||
dsn = settings.resolved_database_url()
|
||||
if not dsn:
|
||||
raise RuntimeError('Set DATABASE_URL or DATABASE_URL_FILE before running migrations')
|
||||
tls = ssl.create_default_context(cafile=settings.tls_ca_file)
|
||||
pool = await asyncpg.create_pool(
|
||||
dsn,
|
||||
ssl=tls,
|
||||
min_size=settings.db_pool_min_size,
|
||||
max_size=settings.db_pool_max_size,
|
||||
timeout=settings.db_pool_acquire_timeout_seconds,
|
||||
command_timeout=settings.db_command_timeout_seconds,
|
||||
)
|
||||
try:
|
||||
await apply_migrations(pool)
|
||||
finally:
|
||||
await pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import asyncio
|
||||
asyncio.run(_main())
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Повторяемая настройка bucket и IAM-политик RustFS через проверенный TLS."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import ssl
|
||||
import time
|
||||
from botocore.exceptions import ClientError
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
import boto3
|
||||
from botocore.auth import S3SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
|
||||
ENDPOINT = os.environ["S3_ENDPOINT_URL"]
|
||||
REGION = os.getenv("S3_REGION", "us-east-1")
|
||||
BUCKET = os.environ["S3_BUCKET"]
|
||||
CA_FILE = os.environ["TLS_CA_FILE"]
|
||||
ROOT_KEY = os.environ["S3_ROOT_ACCESS_KEY"]
|
||||
ROOT_SECRET = os.environ["S3_ROOT_SECRET_KEY"]
|
||||
|
||||
|
||||
def admin(method, path, payload):
|
||||
url = ENDPOINT + "/rustfs/admin/v3/" + path
|
||||
body = json.dumps(payload, separators=(",", ":")).encode()
|
||||
request = AWSRequest(method=method, url=url, data=body,
|
||||
headers={"Content-Type": "application/json"})
|
||||
S3SigV4Auth(Credentials(ROOT_KEY, ROOT_SECRET), "s3", REGION).add_auth(request)
|
||||
signed = urllib.request.Request(url, data=body,
|
||||
headers=dict(request.headers), method=method)
|
||||
context = ssl.create_default_context(cafile=CA_FILE)
|
||||
try:
|
||||
with urllib.request.urlopen(signed, context=context, timeout=5) as response:
|
||||
response.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
# Из тела ответа печатается только короткий код ошибки, не произвольные данные сервера.
|
||||
if exc.code not in (409, 501):
|
||||
raw = exc.read(4096).decode("utf-8", "replace")
|
||||
match = re.search(r"<Code>([A-Za-z0-9_]+)</Code>", raw)
|
||||
safe_code = match.group(1) if match else "unknown"
|
||||
message_match = re.search(r"<Message>([^<]{0,300})</Message>", raw)
|
||||
safe_message = message_match.group(1) if message_match else "unavailable"
|
||||
safe_message = re.sub(r"[0-9a-fA-F]{32,}", "[redacted]", safe_message)
|
||||
safe_message = safe_message.replace(ROOT_KEY, "[redacted]").replace(ROOT_SECRET, "[redacted]")
|
||||
raise RuntimeError(f"RustFS IAM bootstrap failed with HTTP {exc.code} ({safe_code}): {safe_message}") from None
|
||||
|
||||
|
||||
def main():
|
||||
root = boto3.client("s3", endpoint_url=ENDPOINT, region_name=REGION,
|
||||
aws_access_key_id=ROOT_KEY, aws_secret_access_key=ROOT_SECRET,
|
||||
verify=CA_FILE)
|
||||
for attempt in range(30):
|
||||
try:
|
||||
root.list_buckets()
|
||||
break
|
||||
except Exception:
|
||||
if attempt == 29:
|
||||
raise RuntimeError("RustFS did not become ready") from None
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError("RustFS did not become ready")
|
||||
try:
|
||||
root.head_bucket(Bucket=BUCKET)
|
||||
except ClientError as exc:
|
||||
code = str(exc.response.get("Error", {}).get("Code", ""))
|
||||
if code not in ("404", "NoSuchBucket", "NotFound"):
|
||||
raise RuntimeError("RustFS bucket check failed") from None
|
||||
root.create_bucket(Bucket=BUCKET)
|
||||
|
||||
bucket_arn = f"arn:aws:s3:::{BUCKET}"
|
||||
api_policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": [bucket_arn]},
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": [bucket_arn + "/staging/*", bucket_arn + "/original/*", bucket_arn + "/variants/*"]},
|
||||
],
|
||||
}
|
||||
worker_policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"],
|
||||
"Resource": [bucket_arn + "/staging/*"]},
|
||||
{"Effect": "Allow", "Action": ["s3:PutObject"],
|
||||
"Resource": [bucket_arn + "/original/*", bucket_arn + "/variants/*"]},
|
||||
],
|
||||
}
|
||||
for name, policy in (("messenger-api", api_policy), ("messenger-worker", worker_policy)):
|
||||
admin("PUT", "add-canned-policy?" + urllib.parse.urlencode({"name": name}), policy)
|
||||
for name in ("api", "worker"):
|
||||
access = open(f"/run/identity/s3_{name}_access_key", encoding="utf-8").read().strip()
|
||||
secret = open(f"/run/identity/s3_{name}_secret_key", encoding="utf-8").read().strip()
|
||||
policy = "messenger-api" if name == "api" else "messenger-worker"
|
||||
admin("PUT", "add-user?" + urllib.parse.urlencode({"accessKey": access}),
|
||||
{"secretKey": secret, "status": "enabled"})
|
||||
query = urllib.parse.urlencode({"policyName": policy, "userOrGroup": access, "isGroup": "false"})
|
||||
admin("PUT", "set-user-or-group-policy?" + query, {})
|
||||
print("RustFS bucket and scoped API/worker identities are ready.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import asyncio
|
||||
|
||||
import asyncpg
|
||||
import ssl
|
||||
from fastapi import FastAPI
|
||||
from redis.asyncio import Redis
|
||||
|
||||
from app.api.routes import attachments, auth, health, me, users, chats, messages
|
||||
from app.core.config import settings
|
||||
from app.core.openbao import load_service_secrets
|
||||
from app.core.errors import RequestIdMiddleware, register_error_handlers
|
||||
from app.repositories.object_store import S3ObjectStore
|
||||
from app.repositories.postgres import PgStorage
|
||||
from app.repositories.redis_sessions import RedisSessionStore
|
||||
from app.telemetry import HttpTelemetryMiddleware, configure_telemetry
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
tracer_provider, meter = configure_telemetry("messenger-api")
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
service_secrets = await asyncio.to_thread(load_service_secrets)
|
||||
settings.database_url = service_secrets['database_url']
|
||||
settings.redis_url = service_secrets['redis_url']
|
||||
settings.s3_access_key_id = service_secrets['s3_access_key_id']
|
||||
settings.s3_secret_access_key = service_secrets['s3_secret_access_key']
|
||||
dsn = settings.resolved_database_url()
|
||||
if not dsn:
|
||||
raise RuntimeError('Set DATABASE_URL or DATABASE_URL_FILE before starting the API')
|
||||
tls = ssl.create_default_context(cafile=settings.tls_ca_file)
|
||||
pool = await asyncpg.create_pool(
|
||||
dsn,
|
||||
ssl=tls,
|
||||
min_size=settings.db_pool_min_size,
|
||||
max_size=settings.db_pool_max_size,
|
||||
timeout=settings.db_pool_acquire_timeout_seconds,
|
||||
command_timeout=settings.db_command_timeout_seconds,
|
||||
)
|
||||
redis_args = dict(decode_responses=True,
|
||||
socket_connect_timeout=settings.redis_timeout_seconds,
|
||||
socket_timeout=settings.redis_timeout_seconds)
|
||||
if settings.resolved_redis_url().startswith('rediss://'):
|
||||
redis_args['ssl_ca_certs'] = settings.tls_ca_file
|
||||
redis_args['ssl_check_hostname'] = True
|
||||
redis_client = Redis.from_url(settings.resolved_redis_url(), **redis_args)
|
||||
object_store = S3ObjectStore()
|
||||
try:
|
||||
await object_store.ensure_bucket()
|
||||
app.state.object_store = object_store
|
||||
app.state.redis = redis_client
|
||||
app.state.storage = PgStorage(pool, RedisSessionStore(redis_client), object_store)
|
||||
yield
|
||||
finally:
|
||||
await redis_client.aclose()
|
||||
await pool.close()
|
||||
|
||||
app = FastAPI(title='MTUSI Messenger lab7', docs_url=None, redoc_url=None, lifespan=lifespan)
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
app.add_middleware(HttpTelemetryMiddleware, meter=meter)
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
FastAPIInstrumentor.instrument_app(app, tracer_provider=tracer_provider)
|
||||
register_error_handlers(app)
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(me.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import threading
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from app.core.errors import ApiError
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def iso_z(moment: datetime) -> str:
|
||||
"""RFC 3339 UTC с Z и микросекундами: порядок (created_at, id) не теряет точность."""
|
||||
return moment.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
|
||||
|
||||
|
||||
def order_key(created_dt: datetime, row_id: str):
|
||||
"""Контракт: порядок по (created_at, id), id сравнивается как значение UUID."""
|
||||
return (created_dt, uuid.UUID(row_id).int)
|
||||
|
||||
|
||||
@dataclass
|
||||
class UserRow:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
password_hash: str
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChatRow:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list
|
||||
created_dt: datetime
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class MessageRow:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_dt: datetime
|
||||
created_at: str
|
||||
attachment_ids: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AttachmentRow:
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
object_key: str
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: list
|
||||
error_code: str | None
|
||||
staging_key: str | None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class SessionRow:
|
||||
token: str
|
||||
user_id: str
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Хранилище в памяти из скелета lab1. В lab2 его заменяет PgStorage."""
|
||||
|
||||
def __init__(self):
|
||||
self._lock = threading.RLock()
|
||||
self._users: dict[str, UserRow] = {}
|
||||
self._by_username: dict[str, str] = {}
|
||||
self._chats: dict[str, ChatRow] = {}
|
||||
self._messages: dict[str, list[MessageRow]] = {}
|
||||
self._sessions: dict[str, SessionRow] = {}
|
||||
|
||||
def ready(self) -> bool:
|
||||
return True
|
||||
|
||||
def create_user(self, username: str, display_name: str, password_hash: str) -> UserRow:
|
||||
with self._lock:
|
||||
if username in self._by_username:
|
||||
raise ApiError(409, 'Username is already taken')
|
||||
row = UserRow(str(uuid.uuid4()), username, display_name, password_hash,
|
||||
iso_z(now_utc()))
|
||||
self._users[row.id] = row
|
||||
self._by_username[username] = row.id
|
||||
return row
|
||||
|
||||
def user_by_username(self, username: str) -> UserRow | None:
|
||||
with self._lock:
|
||||
uid = self._by_username.get(username)
|
||||
return self._users.get(uid) if uid else None
|
||||
|
||||
def user(self, user_id: str) -> UserRow | None:
|
||||
with self._lock:
|
||||
return self._users.get(user_id)
|
||||
|
||||
def create_session(self, user_id: str, ttl_seconds: int) -> SessionRow:
|
||||
from app.core.security import new_token
|
||||
with self._lock:
|
||||
row = SessionRow(new_token(), user_id, now_utc() + timedelta(seconds=ttl_seconds))
|
||||
self._sessions[row.token] = row
|
||||
return row
|
||||
|
||||
def session(self, token: str) -> SessionRow | None:
|
||||
with self._lock:
|
||||
row = self._sessions.get(token)
|
||||
if row is None:
|
||||
return None
|
||||
if now_utc() >= row.expires_at:
|
||||
del self._sessions[token]
|
||||
return None
|
||||
return row
|
||||
|
||||
def revoke(self, token: str) -> bool:
|
||||
with self._lock:
|
||||
return self._sessions.pop(token, None) is not None
|
||||
|
||||
def create_chat(self, title: str, member_ids: list, caller_id: str) -> ChatRow:
|
||||
with self._lock:
|
||||
if caller_id not in member_ids:
|
||||
raise ApiError(400, 'Creator must be included in member_ids')
|
||||
for mid in member_ids:
|
||||
if mid not in self._users:
|
||||
raise ApiError(400, 'Unknown member id')
|
||||
moment = now_utc()
|
||||
row = ChatRow(str(uuid.uuid4()), title, list(member_ids), moment, iso_z(moment))
|
||||
self._chats[row.id] = row
|
||||
self._messages[row.id] = []
|
||||
return row
|
||||
|
||||
def chat(self, chat_id: str) -> ChatRow | None:
|
||||
with self._lock:
|
||||
return self._chats.get(chat_id)
|
||||
|
||||
def chats_of(self, user_id: str) -> list[ChatRow]:
|
||||
with self._lock:
|
||||
rows = [c for c in self._chats.values() if user_id in c.member_ids]
|
||||
return sorted(rows, key=lambda c: order_key(c.created_dt, c.id))
|
||||
@@ -0,0 +1,110 @@
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.errors import ApiError
|
||||
|
||||
|
||||
class S3ObjectStore:
|
||||
"""Хранит байты в приватном S3 bucket, не в процессе API."""
|
||||
|
||||
def __init__(self):
|
||||
self.bucket = settings.s3_bucket
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint_url,
|
||||
region_name=settings.s3_region,
|
||||
aws_access_key_id=settings.resolved_s3_access_key_id(),
|
||||
aws_secret_access_key=settings.resolved_s3_secret_access_key(),
|
||||
config=Config(
|
||||
connect_timeout=settings.s3_connect_timeout_seconds,
|
||||
read_timeout=settings.s3_read_timeout_seconds,
|
||||
max_pool_connections=16,
|
||||
retries={"max_attempts": 2, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
verify=settings.tls_ca_file if settings.s3_endpoint_url.startswith('https://') else True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _unavailable():
|
||||
return ApiError(503, "Object storage is unavailable")
|
||||
|
||||
def _ensure_bucket(self):
|
||||
for attempt in range(30):
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
return
|
||||
except ClientError as exc:
|
||||
code = str(exc.response.get("Error", {}).get("Code", ""))
|
||||
if code not in {"404", "NoSuchBucket", "NotFound"}:
|
||||
if code in {"403", "AccessDenied"} or attempt == 29:
|
||||
raise self._unavailable() from None
|
||||
else:
|
||||
try:
|
||||
self.client.create_bucket(Bucket=self.bucket)
|
||||
except ClientError as create_exc:
|
||||
create_code = str(create_exc.response.get("Error", {}).get("Code", ""))
|
||||
if create_code not in {"BucketAlreadyOwnedByYou", "BucketAlreadyExists"}:
|
||||
if attempt == 29:
|
||||
raise self._unavailable() from None
|
||||
else:
|
||||
return
|
||||
except (BotoCoreError, OSError, TimeoutError):
|
||||
if attempt == 29:
|
||||
raise self._unavailable() from None
|
||||
time.sleep(0.5)
|
||||
raise self._unavailable()
|
||||
|
||||
async def ensure_bucket(self):
|
||||
await asyncio.to_thread(self._ensure_bucket)
|
||||
|
||||
def _head_bucket(self):
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
|
||||
async def ready(self) -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(self._head_bucket)
|
||||
return True
|
||||
except (ClientError, BotoCoreError, OSError, TimeoutError):
|
||||
return False
|
||||
|
||||
def _put(self, key: str, data: bytes, content_type: str):
|
||||
self.client.put_object(Bucket=self.bucket, Key=key, Body=data, ContentType=content_type)
|
||||
|
||||
async def put(self, key: str, data: bytes, content_type: str):
|
||||
try:
|
||||
await asyncio.to_thread(self._put, key, data, content_type)
|
||||
except (ClientError, BotoCoreError, OSError, TimeoutError):
|
||||
raise self._unavailable() from None
|
||||
|
||||
def _get(self, key: str) -> bytes:
|
||||
result = self.client.get_object(Bucket=self.bucket, Key=key)
|
||||
try:
|
||||
return result["Body"].read(settings.max_upload_bytes + 1)
|
||||
finally:
|
||||
result["Body"].close()
|
||||
|
||||
async def get(self, key: str) -> bytes:
|
||||
try:
|
||||
data = await asyncio.to_thread(self._get, key)
|
||||
if len(data) > settings.max_upload_bytes:
|
||||
raise self._unavailable()
|
||||
return data
|
||||
except ApiError:
|
||||
raise
|
||||
except (ClientError, BotoCoreError, OSError, TimeoutError):
|
||||
raise self._unavailable() from None
|
||||
|
||||
def _delete(self, key: str):
|
||||
self.client.delete_object(Bucket=self.bucket, Key=key)
|
||||
|
||||
async def delete(self, key: str):
|
||||
try:
|
||||
await asyncio.to_thread(self._delete, key)
|
||||
except (ClientError, BotoCoreError, OSError, TimeoutError):
|
||||
raise self._unavailable() from None
|
||||
@@ -0,0 +1,288 @@
|
||||
import json
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
|
||||
from app.core.errors import ApiError
|
||||
from app.repositories.memory import (
|
||||
AttachmentRow, ChatRow, MessageRow, UserRow, iso_z,
|
||||
)
|
||||
|
||||
|
||||
def _user(row: asyncpg.Record | None) -> UserRow | None:
|
||||
if row is None:
|
||||
return None
|
||||
return UserRow(
|
||||
id=str(row['id']), username=row['username'], display_name=row['display_name'],
|
||||
password_hash=row['password_hash'], created_at=iso_z(row['created_at']),
|
||||
)
|
||||
|
||||
|
||||
def _chat(row: asyncpg.Record) -> ChatRow:
|
||||
moment = row['created_at']
|
||||
return ChatRow(
|
||||
id=str(row['id']), title=row['title'], member_ids=[str(x) for x in row['member_ids']],
|
||||
created_dt=moment, created_at=iso_z(moment),
|
||||
)
|
||||
|
||||
|
||||
def _message(row: asyncpg.Record) -> MessageRow:
|
||||
moment = row['created_at']
|
||||
attachment_ids = row['attachment_ids'] if 'attachment_ids' in row else []
|
||||
return MessageRow(
|
||||
id=str(row['id']), chat_id=str(row['chat_id']), sender_id=str(row['sender_id']),
|
||||
text=row['text'], created_dt=moment, created_at=iso_z(moment),
|
||||
attachment_ids=[str(value) for value in (attachment_ids or [])],
|
||||
)
|
||||
|
||||
|
||||
def _attachment(row: asyncpg.Record) -> AttachmentRow:
|
||||
return AttachmentRow(
|
||||
id=str(row['id']), chat_id=str(row['chat_id']), owner_id=str(row['owner_id']),
|
||||
object_key=row['object_key'], filename=row['filename'],
|
||||
content_type=row['content_type'], size_bytes=row['size_bytes'],
|
||||
sha256=row['sha256'], status=row['status'],
|
||||
variants=(json.loads(row['variants']) if isinstance(row['variants'], str) else row['variants']),
|
||||
error_code=row['error_code'], staging_key=row['staging_key'],
|
||||
created_at=iso_z(row['created_at']), updated_at=iso_z(row['updated_at']),
|
||||
)
|
||||
|
||||
|
||||
_MESSAGE_SELECT = (
|
||||
'SELECT m.*, COALESCE(array_agg(ma.attachment_id ORDER BY ma.position) '
|
||||
"FILTER (WHERE ma.attachment_id IS NOT NULL), ARRAY[]::uuid[]) AS attachment_ids "
|
||||
'FROM messages m LEFT JOIN message_attachments ma ON ma.message_id = m.id '
|
||||
)
|
||||
|
||||
|
||||
class PgStorage:
|
||||
"""PostgreSQL — источник истины для метаданных; S3 хранит только байты."""
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool, session_store, object_store):
|
||||
self.pool = pool
|
||||
self.session_store = session_store
|
||||
self.object_store = object_store
|
||||
|
||||
async def ready(self) -> bool:
|
||||
try:
|
||||
async with self.pool.acquire() as connection:
|
||||
database_ready = await connection.fetchval('SELECT 1') == 1
|
||||
return (
|
||||
database_ready
|
||||
and await self.session_store.ready()
|
||||
and await self.object_store.ready()
|
||||
)
|
||||
except (asyncpg.PostgresError, OSError, TimeoutError):
|
||||
return False
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password_hash: str) -> UserRow:
|
||||
try:
|
||||
async with self.pool.acquire() as connection:
|
||||
row = await connection.fetchrow(
|
||||
'INSERT INTO users (id, username, display_name, password_hash) '
|
||||
'VALUES ($1, $2, $3, $4) RETURNING *',
|
||||
uuid.uuid4(), username, display_name, password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError as exc:
|
||||
if exc.constraint_name == 'users_username_key':
|
||||
raise ApiError(409, 'Username is already taken') from None
|
||||
raise
|
||||
return _user(row)
|
||||
|
||||
async def user_by_username(self, username: str) -> UserRow | None:
|
||||
async with self.pool.acquire() as connection:
|
||||
return _user(await connection.fetchrow(
|
||||
'SELECT * FROM users WHERE username = $1', username
|
||||
))
|
||||
|
||||
async def user(self, user_id: str) -> UserRow | None:
|
||||
async with self.pool.acquire() as connection:
|
||||
return _user(await connection.fetchrow(
|
||||
'SELECT * FROM users WHERE id = $1', uuid.UUID(user_id)
|
||||
))
|
||||
|
||||
async def create_session(self, user_id: str, ttl_seconds: int):
|
||||
return await self.session_store.create_session(user_id, ttl_seconds)
|
||||
|
||||
async def session(self, token: str):
|
||||
return await self.session_store.session(token)
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
return await self.session_store.revoke(token)
|
||||
|
||||
async def create_chat(self, title: str, member_ids: list[str], caller_id: str) -> ChatRow:
|
||||
if caller_id not in member_ids:
|
||||
raise ApiError(400, 'Creator must be included in member_ids')
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
created_at = await connection.fetchval(
|
||||
'INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING created_at',
|
||||
chat_id, title,
|
||||
)
|
||||
await connection.executemany(
|
||||
'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)',
|
||||
[(chat_id, uuid.UUID(member_id)) for member_id in member_ids],
|
||||
)
|
||||
except asyncpg.ForeignKeyViolationError:
|
||||
raise ApiError(400, 'Unknown member id') from None
|
||||
return ChatRow(
|
||||
id=str(chat_id), title=title, member_ids=list(member_ids),
|
||||
created_dt=created_at, created_at=iso_z(created_at),
|
||||
)
|
||||
|
||||
async def chat(self, chat_id: str) -> ChatRow | None:
|
||||
async with self.pool.acquire() as connection:
|
||||
row = await connection.fetchrow(
|
||||
'SELECT c.id, c.title, c.created_at, '
|
||||
'array_agg(cm.user_id ORDER BY cm.user_id) AS member_ids '
|
||||
'FROM chats c JOIN chat_members cm ON cm.chat_id = c.id '
|
||||
'WHERE c.id = $1 GROUP BY c.id', uuid.UUID(chat_id),
|
||||
)
|
||||
return _chat(row) if row else None
|
||||
|
||||
async def chats_of(self, user_id: str) -> list[ChatRow]:
|
||||
async with self.pool.acquire() as connection:
|
||||
rows = await connection.fetch(
|
||||
'SELECT c.id, c.title, c.created_at, '
|
||||
'array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids '
|
||||
'FROM chats c '
|
||||
'JOIN chat_members mine ON mine.chat_id = c.id '
|
||||
'JOIN chat_members cm_all ON cm_all.chat_id = c.id '
|
||||
'WHERE mine.user_id = $1 '
|
||||
'GROUP BY c.id ORDER BY c.created_at, c.id', uuid.UUID(user_id),
|
||||
)
|
||||
return [_chat(row) for row in rows]
|
||||
|
||||
async def create_attachment(
|
||||
self, attachment_id: str, job_id: str, chat_id: str, owner_id: str,
|
||||
object_key: str, staging_key: str, filename: str, content_type: str,
|
||||
size_bytes: int, sha256: str,
|
||||
) -> AttachmentRow:
|
||||
"""Сохранить метаданные и задание одной транзакцией после записи staging."""
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
row = await connection.fetchrow(
|
||||
'INSERT INTO attachments '
|
||||
'(id, chat_id, owner_id, object_key, staging_key, filename, content_type, size_bytes, sha256, status) '
|
||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'queued') RETURNING *",
|
||||
uuid.UUID(attachment_id), uuid.UUID(chat_id), uuid.UUID(owner_id),
|
||||
object_key, staging_key, filename, content_type, size_bytes, sha256,
|
||||
)
|
||||
await connection.execute(
|
||||
'INSERT INTO attachment_jobs (id, attachment_id) VALUES ($1, $2)',
|
||||
uuid.UUID(job_id), uuid.UUID(attachment_id),
|
||||
)
|
||||
return _attachment(row)
|
||||
async def attachment_for_member(self, attachment_id: str, user_id: str) -> AttachmentRow | None:
|
||||
try:
|
||||
attachment_uuid = uuid.UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, 'attachment_id must be a UUID') from None
|
||||
async with self.pool.acquire() as connection:
|
||||
row = await connection.fetchrow(
|
||||
'SELECT a.* FROM attachments a '
|
||||
'JOIN chat_members cm ON cm.chat_id = a.chat_id '
|
||||
'WHERE a.id = $1 AND cm.user_id = $2',
|
||||
attachment_uuid, uuid.UUID(user_id),
|
||||
)
|
||||
return _attachment(row) if row else None
|
||||
|
||||
async def add_idempotent_message(
|
||||
self, chat_id: str, sender_id: str, text: str, attachment_ids: list[str],
|
||||
idempotency_key: str, request_hash: bytes,
|
||||
) -> MessageRow:
|
||||
"""Создать сообщение, его вложения и ключ повтора одной транзакцией."""
|
||||
chat_uuid = uuid.UUID(chat_id)
|
||||
sender_uuid = uuid.UUID(sender_id)
|
||||
attachment_uuids = [uuid.UUID(value) for value in attachment_ids]
|
||||
lock_scope = f'{sender_uuid}:POST:/api/v1/chats/{chat_uuid}/messages:{idempotency_key}'
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
await connection.fetchval(
|
||||
'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', lock_scope,
|
||||
)
|
||||
existing = await connection.fetchrow(
|
||||
'SELECT k.request_hash, m.id FROM message_idempotency k '
|
||||
'JOIN messages m ON m.id = k.message_id '
|
||||
'WHERE k.user_id = $1 AND k.chat_id = $2 AND k.idempotency_key = $3 '
|
||||
"AND k.created_at > now() - interval '24 hours'",
|
||||
sender_uuid, chat_uuid, idempotency_key,
|
||||
)
|
||||
if existing is not None:
|
||||
if bytes(existing['request_hash']) != request_hash:
|
||||
raise ApiError(409, 'Idempotency-Key was already used with another request')
|
||||
row = await connection.fetchrow(
|
||||
_MESSAGE_SELECT + 'WHERE m.id = $1 GROUP BY m.id', existing['id'],
|
||||
)
|
||||
return _message(row)
|
||||
|
||||
if attachment_uuids:
|
||||
available = await connection.fetch(
|
||||
'SELECT id, status FROM attachments WHERE chat_id = $1 '
|
||||
'AND id = ANY($2::uuid[]) FOR SHARE', chat_uuid, attachment_uuids,
|
||||
)
|
||||
if len(available) != len(attachment_uuids):
|
||||
raise ApiError(404, 'Attachment is not available in this chat')
|
||||
if any(row['status'] == 'failed' for row in available):
|
||||
raise ApiError(409, 'Failed attachments cannot be added to a message')
|
||||
|
||||
await connection.execute(
|
||||
'DELETE FROM message_idempotency '
|
||||
'WHERE user_id = $1 AND chat_id = $2 AND idempotency_key = $3',
|
||||
sender_uuid, chat_uuid, idempotency_key,
|
||||
)
|
||||
await connection.execute(
|
||||
"DELETE FROM message_idempotency WHERE ctid IN ("
|
||||
'SELECT ctid FROM message_idempotency '
|
||||
"WHERE created_at <= now() - interval '24 hours' "
|
||||
'ORDER BY created_at LIMIT 100)'
|
||||
)
|
||||
message_id = uuid.uuid4()
|
||||
await connection.execute(
|
||||
'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4)',
|
||||
message_id, chat_uuid, sender_uuid, text,
|
||||
)
|
||||
if attachment_uuids:
|
||||
await connection.executemany(
|
||||
'INSERT INTO message_attachments '
|
||||
'(message_id, attachment_id, chat_id, position) VALUES ($1, $2, $3, $4)',
|
||||
[(message_id, attachment_id, chat_uuid, index)
|
||||
for index, attachment_id in enumerate(attachment_uuids)],
|
||||
)
|
||||
row = await connection.fetchrow(
|
||||
_MESSAGE_SELECT + 'WHERE m.id = $1 GROUP BY m.id', message_id,
|
||||
)
|
||||
await connection.execute(
|
||||
'INSERT INTO message_idempotency '
|
||||
'(user_id, chat_id, idempotency_key, request_hash, message_id) '
|
||||
'VALUES ($1, $2, $3, $4, $5)',
|
||||
sender_uuid, chat_uuid, idempotency_key, request_hash, message_id,
|
||||
)
|
||||
return _message(row)
|
||||
|
||||
async def messages_page(self, chat_id: str, cursor_key, limit: int):
|
||||
"""Прочитать ограниченную keyset-страницу вместе с ID прикреплённых файлов."""
|
||||
chat_uuid = uuid.UUID(chat_id)
|
||||
base = (
|
||||
'SELECT m.*, COALESCE(array_agg(ma.attachment_id ORDER BY ma.position) '
|
||||
"FILTER (WHERE ma.attachment_id IS NOT NULL), ARRAY[]::uuid[]) AS attachment_ids "
|
||||
'FROM messages m LEFT JOIN message_attachments ma ON ma.message_id = m.id '
|
||||
'WHERE m.chat_id = $1 '
|
||||
)
|
||||
async with self.pool.acquire() as connection:
|
||||
if cursor_key is None:
|
||||
rows = await connection.fetch(
|
||||
base + 'GROUP BY m.id ORDER BY m.created_at, m.id LIMIT $2',
|
||||
chat_uuid, limit + 1,
|
||||
)
|
||||
else:
|
||||
created_at, id_value = cursor_key
|
||||
rows = await connection.fetch(
|
||||
base + 'AND (m.created_at, m.id) > ($2, $3) '
|
||||
'GROUP BY m.id ORDER BY m.created_at, m.id LIMIT $4',
|
||||
chat_uuid, created_at, uuid.UUID(int=id_value), limit + 1,
|
||||
)
|
||||
has_more = len(rows) > limit
|
||||
return [_message(row) for row in rows[:limit]], has_more
|
||||
@@ -0,0 +1,66 @@
|
||||
import hashlib
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from app.core.errors import ApiError
|
||||
from app.core.security import new_token
|
||||
from app.repositories.memory import SessionRow, now_utc
|
||||
|
||||
|
||||
class RedisSessionStore:
|
||||
"""Redis — источник истины для сессий; PXAT сохраняет исходный срок истечения после перезапуска."""
|
||||
|
||||
def __init__(self, client: Redis):
|
||||
self.client = client
|
||||
|
||||
@staticmethod
|
||||
def _key(token: str) -> str:
|
||||
digest = hashlib.sha256(token.encode('utf-8')).hexdigest()
|
||||
return 'session:' + digest
|
||||
|
||||
async def ready(self) -> bool:
|
||||
try:
|
||||
return bool(await self.client.ping())
|
||||
except (RedisError, OSError, TimeoutError):
|
||||
return False
|
||||
|
||||
async def create_session(self, user_id: str, ttl_seconds: int) -> SessionRow:
|
||||
token = new_token()
|
||||
current = now_utc()
|
||||
expires_at = current.replace(microsecond=(current.microsecond // 1000) * 1000) + timedelta(seconds=ttl_seconds)
|
||||
expires_ms = int(expires_at.timestamp() * 1000)
|
||||
try:
|
||||
await self.client.set(
|
||||
self._key(token), f'{user_id}|{expires_ms}', pxat=expires_ms
|
||||
)
|
||||
except RedisError:
|
||||
raise ApiError(503, 'Session storage is unavailable') from None
|
||||
return SessionRow(token=token, user_id=user_id, expires_at=expires_at)
|
||||
|
||||
async def session(self, token: str) -> SessionRow | None:
|
||||
try:
|
||||
value = await self.client.get(self._key(token))
|
||||
except RedisError:
|
||||
raise ApiError(503, 'Session storage is unavailable') from None
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
user_id, expires_ms_text = value.split('|', 1)
|
||||
expires_ms = int(expires_ms_text)
|
||||
if expires_ms <= int(time.time() * 1000):
|
||||
await self.client.delete(self._key(token))
|
||||
return None
|
||||
expires_at = datetime.fromtimestamp(expires_ms / 1000, timezone.utc)
|
||||
return SessionRow(token=token, user_id=user_id, expires_at=expires_at)
|
||||
except (ValueError, OverflowError):
|
||||
await self.client.delete(self._key(token))
|
||||
return None
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
try:
|
||||
return bool(await self.client.delete(self._key(token)))
|
||||
except RedisError:
|
||||
raise ApiError(503, 'Session storage is unavailable') from None
|
||||
@@ -0,0 +1,85 @@
|
||||
import uuid as _uuid
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
STRICT = ConfigDict(extra='forbid')
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = STRICT
|
||||
username: str = Field(pattern=r'^[a-z0-9_]{3,32}$')
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator('display_name', 'password')
|
||||
@classmethod
|
||||
def _not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError('string must not consist of whitespace only')
|
||||
return value
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = STRICT
|
||||
id: _uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
model_config = STRICT
|
||||
token: str
|
||||
token_type: Literal['Bearer']
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = STRICT
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[_uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator('title')
|
||||
@classmethod
|
||||
def _title_not_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError('string must not consist of whitespace only')
|
||||
return value
|
||||
|
||||
@field_validator('member_ids')
|
||||
@classmethod
|
||||
def _unique_members(cls, value):
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError('duplicate member ids')
|
||||
return value
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = STRICT
|
||||
text: str = Field(min_length=0, max_length=4000)
|
||||
attachment_ids: list[_uuid.UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator('attachment_ids')
|
||||
@classmethod
|
||||
def _unique_attachments(cls, value):
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError('duplicate attachment ids')
|
||||
return value
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
model_config = STRICT
|
||||
id: _uuid.UUID
|
||||
chat_id: _uuid.UUID
|
||||
owner_id: _uuid.UUID
|
||||
filename: str = Field(min_length=1, max_length=255)
|
||||
content_type: Literal['image/png', 'image/jpeg']
|
||||
size_bytes: int = Field(ge=1, le=10_485_760)
|
||||
sha256: str = Field(pattern=r'^[a-f0-9]{64}$')
|
||||
status: Literal['queued', 'processing', 'ready', 'failed']
|
||||
variants: list = Field(default_factory=list)
|
||||
error_code: str | None = None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
@@ -0,0 +1,89 @@
|
||||
"""OpenTelemetry setup shared by the API and attachment worker."""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.instrumentation.logging import LoggingInstrumentor
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
_ENDPOINT = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||
|
||||
|
||||
def configure_telemetry(service_name: str):
|
||||
"""Настраивает OTLP exporters для сигналов данного процесса."""
|
||||
resource = Resource.create({
|
||||
"service.name": service_name,
|
||||
"service.version": os.getenv("SERVICE_VERSION", "6.0.0"),
|
||||
"service.instance.id": os.getenv("INSTANCE_ID") or socket.gethostname(),
|
||||
"deployment.environment.name": os.getenv("DEPLOYMENT_ENVIRONMENT", "lab"),
|
||||
})
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(BatchSpanProcessor(
|
||||
OTLPSpanExporter(endpoint=_ENDPOINT + "/v1/traces", timeout=3)))
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=_ENDPOINT + "/v1/metrics", timeout=3),
|
||||
export_interval_millis=5000)
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=_ENDPOINT + "/v1/logs", timeout=3)))
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
set_logger_provider(logger_provider)
|
||||
root = logging.getLogger()
|
||||
root.setLevel(os.getenv("LOG_LEVEL", "INFO"))
|
||||
if not any(getattr(handler, "_otel_handler", False) for handler in root.handlers):
|
||||
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
handler._otel_handler = True
|
||||
root.addHandler(handler)
|
||||
LoggingInstrumentor().instrument(set_logging_format=False)
|
||||
return tracer_provider, metrics.get_meter(service_name)
|
||||
|
||||
|
||||
class HttpTelemetryMiddleware:
|
||||
"""Считает HTTP ответы по шаблону маршрута без динамических URL в метках."""
|
||||
def __init__(self, app, meter):
|
||||
self.app = app
|
||||
self.requests = meter.create_counter("messenger_http_requests_total", unit="{request}")
|
||||
self.duration = meter.create_histogram("messenger_http_request_duration_seconds", unit="s")
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
started, status = time.perf_counter(), 500
|
||||
|
||||
async def wrapped_send(message):
|
||||
nonlocal status
|
||||
if message["type"] == "http.response.start":
|
||||
status = int(message["status"])
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, wrapped_send)
|
||||
finally:
|
||||
route = scope.get("route")
|
||||
template = getattr(route, "path", "/unmatched")
|
||||
attrs = {"http.request.method": scope.get("method", "UNKNOWN"),
|
||||
"http.route": template,
|
||||
"http.response.status_class": str(status // 100) + "xx"}
|
||||
elapsed = time.perf_counter() - started
|
||||
self.requests.add(1, attrs)
|
||||
self.duration.record(elapsed, attrs)
|
||||
logging.getLogger("messenger.http").info(
|
||||
"http_request_completed",
|
||||
extra={"event.name": "http.request.completed",
|
||||
"http.request.method": attrs["http.request.method"],
|
||||
"http.route": template, "http.response.status_code": status,
|
||||
"duration_seconds": elapsed,
|
||||
"request_id": scope.get("state", {}).get("request_id")})
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
import warnings
|
||||
import time
|
||||
from datetime import timezone
|
||||
|
||||
import asyncpg
|
||||
import ssl
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from redis.asyncio import Redis
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.openbao import load_service_secrets
|
||||
from app.repositories.object_store import S3ObjectStore
|
||||
from app.telemetry import configure_telemetry
|
||||
from opentelemetry import trace
|
||||
|
||||
LOG = logging.getLogger('attachment-worker')
|
||||
STREAM = 'messenger:attachment-jobs'
|
||||
GROUP = 'attachment-workers-v1'
|
||||
MAX_ATTEMPTS = int(os.getenv('JOB_MAX_ATTEMPTS', '5'))
|
||||
POLL_SECONDS = 0.5
|
||||
RECLAIM_IDLE_MS = 3000
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _make_thumbnail(data: bytes) -> tuple[bytes, int, int]:
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
if source.width * source.height > settings.max_image_pixels:
|
||||
raise InvalidImage()
|
||||
image = ImageOps.exif_transpose(source)
|
||||
if image.mode in ('RGBA', 'LA') or 'transparency' in image.info:
|
||||
rgba = image.convert('RGBA')
|
||||
rgb = Image.new('RGB', rgba.size, 'white')
|
||||
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
||||
else:
|
||||
rgb = image.convert('RGB')
|
||||
rgb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
if rgb.width < 1 or rgb.height < 1:
|
||||
raise InvalidImage()
|
||||
output = io.BytesIO()
|
||||
rgb.save(output, format='JPEG', quality=85, optimize=True)
|
||||
return output.getvalue(), rgb.width, rgb.height
|
||||
except InvalidImage:
|
||||
raise
|
||||
except (UnidentifiedImageError, Image.DecompressionBombError,
|
||||
Image.DecompressionBombWarning, OSError, SyntaxError, ValueError):
|
||||
raise InvalidImage() from None
|
||||
|
||||
|
||||
class AttachmentWorker:
|
||||
def __init__(self, pool: asyncpg.Pool, redis: Redis, store: S3ObjectStore, meter):
|
||||
self.pool = pool
|
||||
self.redis = redis
|
||||
self.store = store
|
||||
self.consumer = 'worker-' + socket.gethostname()
|
||||
self.tracer = trace.get_tracer('attachment-worker')
|
||||
self.job_counter = meter.create_counter('messenger_jobs_total', unit='{job}')
|
||||
self.job_duration = meter.create_histogram('messenger_job_duration_seconds', unit='s')
|
||||
|
||||
async def ensure_group(self) -> None:
|
||||
try:
|
||||
await self.redis.xgroup_create(STREAM, GROUP, id='0-0', mkstream=True)
|
||||
except Exception as exc:
|
||||
if 'BUSYGROUP' not in str(exc):
|
||||
raise
|
||||
|
||||
async def dispatch_outbox(self) -> None:
|
||||
"""Публикует задания из PostgreSQL; повтор после сбоя даёт безопасный дубль."""
|
||||
while True:
|
||||
try:
|
||||
async with self.pool.acquire() as connection:
|
||||
jobs = await connection.fetch(
|
||||
"SELECT j.id, j.attachment_id, j.pipeline_version, j.attempt, j.created_at "
|
||||
"FROM attachment_jobs j WHERE j.state = 'queued' "
|
||||
'AND j.published_at IS NULL AND j.available_at <= now() '
|
||||
'ORDER BY j.available_at, j.created_at LIMIT 20'
|
||||
)
|
||||
for job in jobs:
|
||||
payload = {
|
||||
'schema_version': 1,
|
||||
'job_id': str(job['id']),
|
||||
'type': 'attachment.process.v1',
|
||||
'attachment_id': str(job['attachment_id']),
|
||||
'pipeline_version': job['pipeline_version'],
|
||||
'attempt': job['attempt'],
|
||||
'created_at': job['created_at'].astimezone(timezone.utc).isoformat().replace('+00:00', 'Z'),
|
||||
}
|
||||
# XADD завершился успешно — Redis Streams хранит запись на persistent volume.
|
||||
await self.redis.xadd(STREAM, {'payload': json.dumps(payload, separators=(',', ':'))})
|
||||
await self.pool.execute(
|
||||
"UPDATE attachment_jobs SET published_at = now(), updated_at = now() "
|
||||
"WHERE id = $1 AND state = 'queued' AND attempt = $2 AND published_at IS NULL",
|
||||
job['id'], job['attempt'],
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
LOG.warning('outbox_dispatch_failed')
|
||||
await asyncio.sleep(POLL_SECONDS)
|
||||
|
||||
async def _load_job(self, payload: dict):
|
||||
job_id = uuid.UUID(payload['job_id'])
|
||||
attachment_id = uuid.UUID(payload['attachment_id'])
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
job = await connection.fetchrow(
|
||||
'SELECT * FROM attachment_jobs WHERE id = $1 AND attachment_id = $2 FOR UPDATE',
|
||||
job_id, attachment_id,
|
||||
)
|
||||
if job is None or job['state'] in ('ready', 'failed'):
|
||||
return None, None, None
|
||||
attachment = await connection.fetchrow(
|
||||
'SELECT * FROM attachments WHERE id = $1 FOR UPDATE', attachment_id
|
||||
)
|
||||
if attachment is None:
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET state = 'failed', error_code = 'processing_failed', updated_at = now() WHERE id = $1",
|
||||
job_id,
|
||||
)
|
||||
return None, None, None
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET state = 'processing', updated_at = now() WHERE id = $1",
|
||||
job_id,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = $1 AND status <> 'ready'",
|
||||
attachment_id,
|
||||
)
|
||||
return job, attachment, str(attachment_id)
|
||||
|
||||
async def _finish_ready(self, job_id, attachment_id, variants: list) -> None:
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'ready', variants = $2::jsonb, error_code = NULL, updated_at = now() WHERE id = $1",
|
||||
attachment_id, json.dumps(variants, separators=(',', ':')),
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET state = 'ready', error_code = NULL, updated_at = now() WHERE id = $1",
|
||||
job_id,
|
||||
)
|
||||
|
||||
async def _fail_or_retry(self, job_id, attachment_id, permanent: bool, permanent_code: str = 'invalid_image') -> bool:
|
||||
"""Сохраняет retry/terminal failure; возвращает True, если попытки исчерпаны."""
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
row = await connection.fetchrow(
|
||||
'SELECT attempt, state FROM attachment_jobs WHERE id = $1 FOR UPDATE', job_id
|
||||
)
|
||||
if row is None or row['state'] in ('ready', 'failed'):
|
||||
return True
|
||||
attempt = row['attempt']
|
||||
if permanent or attempt >= MAX_ATTEMPTS:
|
||||
code = permanent_code if permanent else 'retry_exhausted'
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET state = 'failed', error_code = $2, updated_at = now() WHERE id = $1",
|
||||
job_id, code,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1",
|
||||
attachment_id, code,
|
||||
)
|
||||
return True
|
||||
delay = min(2 ** (attempt - 1), 30)
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET state = 'queued', attempt = attempt + 1, "
|
||||
"available_at = now() + ($2 * interval '1 second'), published_at = NULL, "
|
||||
"error_code = 'processing_retry', updated_at = now() WHERE id = $1",
|
||||
job_id, delay,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
return False
|
||||
|
||||
async def process(self, payload: dict) -> None:
|
||||
started = time.perf_counter()
|
||||
outcome = 'success'
|
||||
job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
with self.tracer.start_as_current_span('attachment.process') as span:
|
||||
span.set_attribute('job.type', 'attachment.process.v1')
|
||||
if isinstance(job_id, str):
|
||||
span.set_attribute('job.id', job_id)
|
||||
try:
|
||||
await self._process_job(payload)
|
||||
if isinstance(job_id, str):
|
||||
try:
|
||||
state = await self.pool.fetchval('SELECT state FROM attachment_jobs WHERE id = $1', uuid.UUID(job_id))
|
||||
outcome = {'ready': 'success', 'failed': 'error', 'queued': 'retry', 'processing': 'success'}.get(state, 'skipped')
|
||||
except Exception:
|
||||
outcome = 'error'
|
||||
except Exception as exc:
|
||||
outcome = 'error'
|
||||
span.record_exception(exc)
|
||||
raise
|
||||
finally:
|
||||
elapsed = time.perf_counter() - started
|
||||
attrs = {'job.type': 'attachment.process.v1', 'outcome': outcome}
|
||||
self.job_counter.add(1, attrs)
|
||||
self.job_duration.record(elapsed, attrs)
|
||||
LOG.info('attachment_job_completed', extra={'event.name': 'attachment.job.completed', 'job.type': 'attachment.process.v1', 'job.outcome': outcome})
|
||||
|
||||
async def _process_job(self, payload: dict) -> None:
|
||||
try:
|
||||
if payload.get('schema_version') != 1 or payload.get('type') != 'attachment.process.v1':
|
||||
return
|
||||
job_id = uuid.UUID(payload['job_id'])
|
||||
attachment_id = uuid.UUID(payload['attachment_id'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return
|
||||
|
||||
job, attachment, attachment_id_text = await self._load_job(payload)
|
||||
if job is None or attachment is None:
|
||||
return
|
||||
stage_key = attachment['staging_key']
|
||||
if not stage_key:
|
||||
await self._fail_or_retry(job_id, attachment_id, permanent=True, permanent_code='processing_failed')
|
||||
return
|
||||
|
||||
try:
|
||||
original = await self.store.get(stage_key)
|
||||
thumb_bytes, width, height = await asyncio.to_thread(_make_thumbnail, original)
|
||||
original_key = f'original/{attachment_id_text}'
|
||||
thumbnail_key = f'variants/{attachment_id_text}/v1/thumbnail.jpg'
|
||||
await self.store.put(original_key, original, attachment['content_type'])
|
||||
await self.store.put(thumbnail_key, thumb_bytes, 'image/jpeg')
|
||||
variants = [{
|
||||
'name': 'thumbnail',
|
||||
'content_type': 'image/jpeg',
|
||||
'size_bytes': len(thumb_bytes),
|
||||
'sha256': hashlib.sha256(thumb_bytes).hexdigest(),
|
||||
'width': width,
|
||||
'height': height,
|
||||
}]
|
||||
await self._finish_ready(job_id, attachment_id, variants)
|
||||
try:
|
||||
await self.store.delete(stage_key)
|
||||
except Exception:
|
||||
LOG.warning('staging_cleanup_failed attachment_id=%s', attachment_id_text)
|
||||
except InvalidImage:
|
||||
terminal = await self._fail_or_retry(job_id, attachment_id, permanent=True)
|
||||
if terminal:
|
||||
try:
|
||||
await self.store.delete(stage_key)
|
||||
except Exception:
|
||||
LOG.warning('staging_cleanup_failed attachment_id=%s', attachment_id_text)
|
||||
except Exception:
|
||||
terminal = await self._fail_or_retry(job_id, attachment_id, permanent=False)
|
||||
if terminal:
|
||||
try:
|
||||
await self.store.delete(stage_key)
|
||||
except Exception:
|
||||
LOG.warning('staging_cleanup_failed attachment_id=%s', attachment_id_text)
|
||||
else:
|
||||
LOG.warning('attachment_retry_scheduled attachment_id=%s', attachment_id_text)
|
||||
|
||||
async def _ack(self, message_id: str) -> None:
|
||||
await self.redis.xack(STREAM, GROUP, message_id)
|
||||
|
||||
async def consume(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
claimed = await self.redis.xautoclaim(
|
||||
STREAM, GROUP, self.consumer, RECLAIM_IDLE_MS, start_id='0-0', count=5
|
||||
)
|
||||
messages = claimed[1] if claimed and len(claimed) > 1 else []
|
||||
if not messages:
|
||||
rows = await self.redis.xreadgroup(
|
||||
GROUP, self.consumer, {STREAM: '>'}, count=1, block=1000
|
||||
)
|
||||
messages = rows[0][1] if rows else []
|
||||
for message_id, fields in messages:
|
||||
payload_raw = fields.get('payload', '{}')
|
||||
try:
|
||||
payload = json.loads(payload_raw)
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
payload = {}
|
||||
try:
|
||||
await self.process(payload)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
LOG.warning('attachment_job_processing_interrupted')
|
||||
continue
|
||||
await self._ack(message_id)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
LOG.warning('stream_consumer_unavailable')
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
_, meter = configure_telemetry('messenger-worker')
|
||||
service_secrets = await asyncio.to_thread(load_service_secrets)
|
||||
settings.database_url = service_secrets['database_url']
|
||||
settings.redis_url = service_secrets['redis_url']
|
||||
settings.s3_access_key_id = service_secrets['s3_access_key_id']
|
||||
settings.s3_secret_access_key = service_secrets['s3_secret_access_key']
|
||||
dsn = settings.resolved_database_url()
|
||||
if not dsn:
|
||||
raise RuntimeError('Set DATABASE_URL before starting the worker')
|
||||
tls = ssl.create_default_context(cafile=settings.tls_ca_file)
|
||||
pool = await asyncpg.create_pool(
|
||||
dsn,
|
||||
ssl=tls,
|
||||
min_size=1,
|
||||
max_size=int(os.getenv('WORKER_DB_POOL_MAX_SIZE', '4')),
|
||||
timeout=settings.db_pool_acquire_timeout_seconds,
|
||||
command_timeout=settings.db_command_timeout_seconds,
|
||||
)
|
||||
redis_args = dict(decode_responses=True,
|
||||
socket_connect_timeout=settings.redis_timeout_seconds,
|
||||
socket_timeout=settings.redis_timeout_seconds)
|
||||
if settings.resolved_redis_url().startswith('rediss://'):
|
||||
redis_args['ssl_ca_certs'] = settings.tls_ca_file
|
||||
redis_args['ssl_check_hostname'] = True
|
||||
redis = Redis.from_url(settings.resolved_redis_url(), **redis_args)
|
||||
store = S3ObjectStore()
|
||||
worker = AttachmentWorker(pool, redis, store, meter)
|
||||
try:
|
||||
await worker.ensure_group()
|
||||
dispatcher = asyncio.create_task(worker.dispatch_outbox())
|
||||
consumer = asyncio.create_task(worker.consume())
|
||||
try:
|
||||
await asyncio.gather(dispatcher, consumer)
|
||||
finally:
|
||||
dispatcher.cancel()
|
||||
consumer.cancel()
|
||||
await asyncio.gather(dispatcher, consumer, return_exceptions=True)
|
||||
finally:
|
||||
await redis.aclose()
|
||||
await pool.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
logging.basicConfig(level=os.getenv('LOG_LEVEL', 'INFO'))
|
||||
asyncio.run(run())
|
||||
Reference in New Issue
Block a user