ЛР 5 — БПИ2302 — Щербацевич — на 4

This commit is contained in:
2026-11-20 19:54:38 +03:00
parent 276dbdad8a
commit 1844c21198
88 changed files with 7499 additions and 30 deletions
View File
View File
+40
View File
@@ -0,0 +1,40 @@
import logging
import sys
import uvicorn
from app.config import load_settings
def main() -> None:
settings = load_settings()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
force=True,
)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
logging.getLogger("sqlalchemy.pool").setLevel(logging.WARNING)
logging.getLogger("asyncpg").setLevel(logging.WARNING)
logging.getLogger("app").info(
"starting host=%s port=%s env=%s instance_id=%s",
settings.host,
settings.port,
settings.env,
settings.instance_id,
)
uvicorn.run(
"app.main:app",
host=settings.host,
port=settings.port,
workers=1,
access_log=False,
timeout_keep_alive=5,
timeout_graceful_shutdown=5,
log_config=None,
)
if __name__ == "__main__":
main()
+14
View File
@@ -0,0 +1,14 @@
from fastapi import APIRouter
from app.api.attachments import router as attachments_router
from app.api.auth import router as auth_router
from app.api.chats import router as chats_router
from app.api.messages import router as messages_router
from app.api.users import router as users_router
api_router = APIRouter(prefix="/api/v1")
api_router.include_router(users_router)
api_router.include_router(auth_router)
api_router.include_router(chats_router)
api_router.include_router(messages_router)
api_router.include_router(attachments_router)
+71
View File
@@ -0,0 +1,71 @@
from uuid import UUID
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import Response
from app.crud.attachments import create_attachment, metadata_for_member, open_content
from app.deps import get_current_user
from app.errors import AppError
from app.present import PublicUser
from app.runtime import require_settings, require_store
from app.schemas.attachment import AttachmentOut
router = APIRouter()
async def read_limited_body(request: Request) -> bytes:
limit = require_settings().max_upload_bytes
raw_length = request.headers.get("content-length")
if raw_length is not None:
try:
announced = int(raw_length)
except ValueError:
raise AppError(400, "invalid_request", "Некорректный запрос") from None
if announced > limit:
raise AppError(413, "payload_too_large", "Файл слишком большой")
chunks: list[bytes] = []
total = 0
async for chunk in request.stream():
total += len(chunk)
if total > limit:
raise AppError(413, "payload_too_large", "Файл слишком большой")
if chunk:
chunks.append(chunk)
return b"".join(chunks)
@router.post("/chats/{chat_id}/attachments", status_code=202, response_model=AttachmentOut)
async def upload_attachment(
chat_id: UUID,
request: Request,
filename: str = Query(min_length=1, max_length=255),
user: PublicUser = Depends(get_current_user),
) -> dict:
payload = await read_limited_body(request)
created = await create_attachment(
chat_id,
user.id,
filename,
request.headers.get("content-type"),
payload,
)
return created.to_dict()
@router.get("/attachments/{attachment_id}", response_model=AttachmentOut)
async def get_attachment(
attachment_id: UUID,
user: PublicUser = Depends(get_current_user),
) -> dict:
return (await metadata_for_member(attachment_id, user.id)).to_dict()
@router.get("/attachments/{attachment_id}/content")
async def download_attachment(
attachment_id: UUID,
user: PublicUser = Depends(get_current_user),
variant: str = Query(default="original"),
) -> Response:
key, media_type = await open_content(attachment_id, user.id, variant)
payload = await require_store().get(key)
return Response(content=payload, media_type=media_type)
+37
View File
@@ -0,0 +1,37 @@
from fastapi import APIRouter, Depends, Header
from starlette.responses import Response
from app.crud.users import authenticate
from app.deps import BASIC_CHALLENGE, BEARER_CHALLENGE, require_token, unauthorized
from app.schemas.session import SessionOut
from app.security import parse_basic, verify_password
from app.sessions import create_session, revoke_session
from app.timeutil import format_time
router = APIRouter()
@router.post("/auth/sessions", status_code=201, response_model=SessionOut)
async def create_session_route(authorization: str | None = Header(default=None)) -> dict:
parsed = parse_basic(authorization or "")
if parsed is None:
verify_password("invalid-basic-auth", None)
raise unauthorized(BASIC_CHALLENGE)
username, password = parsed
user = await authenticate(username, password)
if user is None:
raise unauthorized(BASIC_CHALLENGE)
token, expires_at = await create_session(user.id)
return {
"token": token,
"token_type": "Bearer",
"expires_at": format_time(expires_at),
"user": user.to_dict(),
}
@router.delete("/auth/sessions/current", status_code=204)
async def revoke_current_session(token: str = Depends(require_token)) -> Response:
if not await revoke_session(token):
raise unauthorized(BEARER_CHALLENGE)
return Response(status_code=204)
+31
View File
@@ -0,0 +1,31 @@
from uuid import UUID
from fastapi import APIRouter, Depends, Query
from app.crud.chats import chat_for_member, chats_for_user, create_chat as save_chat
from app.deps import get_current_user
from app.present import PublicUser
from app.schemas.chat import ChatOut, ChatPage, CreateChat
router = APIRouter()
@router.post("/chats", status_code=201, response_model=ChatOut)
async def create_chat(body: CreateChat, user: PublicUser = Depends(get_current_user)) -> dict:
chat = await save_chat(user.id, body.title, tuple(body.member_ids))
return chat.to_dict()
@router.get("/chats", response_model=ChatPage)
async def list_chats(
user: PublicUser = Depends(get_current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None, min_length=1),
) -> dict:
return await chats_for_user(user.id, limit, cursor)
@router.get("/chats/{chat_id}", response_model=ChatOut)
async def get_chat(chat_id: UUID, user: PublicUser = Depends(get_current_user)) -> dict:
chat = await chat_for_member(chat_id, user.id)
return chat.to_dict()
+43
View File
@@ -0,0 +1,43 @@
import logging
from fastapi import APIRouter, Request
from pydantic import BaseModel
from sqlalchemy import text
from app.db import is_dependency_error
from app.errors import AppError
router = APIRouter()
logger = logging.getLogger("app.health")
class HealthOut(BaseModel):
status: str
@router.get("/health/live", response_model=HealthOut)
async def live() -> dict:
return {"status": "ok"}
@router.get("/health/ready", response_model=HealthOut)
async def ready(request: Request) -> dict:
if not getattr(request.app.state, "accepting", False):
raise AppError(503, "unavailable", "Сервер не готов")
engine = getattr(request.app.state, "engine", None)
redis = getattr(request.app.state, "redis", None)
store = getattr(request.app.state, "store", None)
if engine is None or redis is None or store is None:
raise AppError(503, "unavailable", "Сервис временно недоступен")
try:
async with engine.connect() as conn:
await conn.execute(text("SELECT 1"))
await redis.ping()
await store.ping()
except AppError:
raise
except Exception as exc:
if not is_dependency_error(exc):
logger.warning("readiness check failed type=%s", type(exc).__name__)
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
return {"status": "ok"}
+43
View File
@@ -0,0 +1,43 @@
import re
from uuid import UUID
from fastapi import APIRouter, Depends, Query, Request
from app.crud.messages import create_message as save_message
from app.crud.messages import messages_for_member
from app.deps import get_current_user
from app.errors import AppError
from app.present import PublicUser
from app.schemas.message import CreateMessage, MessageOut, MessagePage
router = APIRouter()
_IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def require_idempotency_key(request: Request) -> str:
value = request.headers.get("idempotency-key")
if value is None or _IDEMPOTENCY_KEY.fullmatch(value) is None:
raise AppError(400, "invalid_request", "Некорректный Idempotency-Key")
return value
@router.post("/chats/{chat_id}/messages", status_code=201, response_model=MessageOut)
async def create_message(
chat_id: UUID,
body: CreateMessage,
request: Request,
user: PublicUser = Depends(get_current_user),
) -> dict:
key = require_idempotency_key(request)
message = await save_message(chat_id, user.id, body.text, key, body.attachment_ids)
return message.to_dict()
@router.get("/chats/{chat_id}/messages", response_model=MessagePage)
async def list_messages(
chat_id: UUID,
user: PublicUser = Depends(get_current_user),
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None, min_length=1),
) -> dict:
return await messages_for_member(chat_id, user.id, limit, cursor)
+19
View File
@@ -0,0 +1,19 @@
from fastapi import APIRouter, Depends
from app.crud.users import create_user
from app.deps import get_current_user
from app.present import PublicUser
from app.schemas.user import CreateUser, UserOut
router = APIRouter()
@router.post("/users", status_code=201, response_model=UserOut)
async def register(body: CreateUser) -> dict:
user = await create_user(body.username, body.display_name, body.password)
return user.to_dict()
@router.get("/users/me", response_model=UserOut)
async def me(user: PublicUser = Depends(get_current_user)) -> dict:
return user.to_dict()
+43
View File
@@ -0,0 +1,43 @@
import logging
import aio_pika
logger = logging.getLogger("app.broker")
EXCHANGE = "attachments"
WORK_QUEUE = "attachment.jobs"
DLQ = "attachment.jobs.dlq"
WORK_KEY = "attachment.process"
DLQ_KEY = "attachment.failed"
async def connect(url: str) -> aio_pika.abc.AbstractRobustConnection:
return await aio_pika.connect_robust(url, timeout=10)
async def declare(channel: aio_pika.abc.AbstractChannel) -> tuple[aio_pika.abc.AbstractExchange, aio_pika.abc.AbstractQueue]:
exchange = await channel.declare_exchange(EXCHANGE, aio_pika.ExchangeType.TOPIC, durable=True)
work = await channel.declare_queue(
WORK_QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": EXCHANGE,
"x-dead-letter-routing-key": DLQ_KEY,
},
)
await work.bind(exchange, routing_key=WORK_KEY)
dead = await channel.declare_queue(DLQ, durable=True)
await dead.bind(exchange, routing_key=DLQ_KEY)
return exchange, work
def job_message(payload: str) -> aio_pika.Message:
return aio_pika.Message(
body=payload.encode("utf-8"),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
content_type="application/json",
)
async def publish(exchange: aio_pika.abc.AbstractExchange, payload: str, routing_key: str) -> None:
await exchange.publish(job_message(payload), routing_key=routing_key, mandatory=True)
+194
View File
@@ -0,0 +1,194 @@
import os
import socket
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Settings:
host: str
port: int
env: str
app_role: str
instance_id: str
run_migrations: bool
session_ttl_seconds: int
idempotency_ttl_seconds: int
database_url: str
cache_url: str
s3_endpoint: str
s3_region: str
s3_bucket: str
s3_access_key_id: str
s3_secret_access_key: str
max_upload_bytes: int
max_image_pixels: int
attachment_gc_grace_seconds: int
migrations_dir: Path
db_pool_size: int
db_max_overflow: int
db_pool_timeout_seconds: float
db_connect_timeout_seconds: float
db_command_timeout_seconds: float
redis_socket_timeout_seconds: float
redis_max_connections: int
broker_url: str
worker_concurrency: int
job_max_attempts: int
job_timeout_seconds: int
job_lease_seconds: int
job_backoff_base_seconds: float
job_backoff_cap_seconds: float
pipeline_version: int
staging_retention_seconds: int
worker_image_memory_bytes: int
jpeg_quality: int
webp_quality: int
webp_method: int
faults_file: str
def _int(name: str, default: int, low: int, high: int) -> int:
raw = os.environ.get(name, str(default)).strip()
try:
value = int(raw)
except ValueError as exc:
raise SystemExit(f"{name} must be an integer") from exc
if not low <= value <= high:
raise SystemExit(f"{name} is out of range")
return value
def _float(name: str, default: float, low: float, high: float) -> float:
raw = os.environ.get(name, str(default)).strip()
try:
value = float(raw)
except ValueError as exc:
raise SystemExit(f"{name} must be a number") from exc
if not low <= value <= high:
raise SystemExit(f"{name} is out of range")
return value
def _secret(direct_name: str, file_name: str) -> str:
direct = os.environ.get(direct_name, "").strip()
if direct:
return direct
path = os.environ.get(file_name, "").strip()
if not path:
raise SystemExit(f"set {direct_name} or {file_name}")
try:
value = Path(path).read_text(encoding="utf-8").strip()
except OSError as exc:
raise SystemExit(f"cannot read {file_name}") from exc
if not value:
raise SystemExit(f"{file_name} is empty")
return value
def _migrations_dir() -> Path:
configured = os.environ.get("MIGRATIONS_DIR", "").strip()
if configured:
return Path(configured)
return Path(__file__).resolve().parents[2] / "migrations"
def _flag(name: str, default: bool) -> bool:
raw = os.environ.get(name, "1" if default else "0").strip().lower()
if raw in {"1", "true", "yes", "on"}:
return True
if raw in {"0", "false", "no", "off"}:
return False
raise SystemExit(f"{name} must be a boolean")
def _instance_id() -> str:
configured = os.environ.get("INSTANCE_ID", "").strip()
if configured:
return configured
host = os.environ.get("HOSTNAME", "").strip() or socket.gethostname()
if not host:
raise SystemExit("INSTANCE_ID is empty")
return host
def load_settings() -> Settings:
host = os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0"
env_name = os.environ.get("APP_ENV", "lab").strip() or "lab"
role = os.environ.get("APP_ROLE", "api").strip() or "api"
if role not in {"api", "migrate", "gc", "worker", "relay", "replay"}:
raise SystemExit("APP_ROLE must be api, migrate, gc, worker, relay or replay")
port = _int("APP_PORT", 8080, 1, 65535)
database_url = _secret("DATABASE_URL", "DATABASE_URL_FILE")
if not database_url.startswith("postgresql+asyncpg://"):
raise SystemExit("DATABASE_URL must start with postgresql+asyncpg://")
cache_url = ""
s3_endpoint = ""
s3_region = os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1"
s3_bucket = os.environ.get("S3_BUCKET", "messenger-attachments").strip() or "messenger-attachments"
s3_access_key_id = ""
s3_secret_access_key = ""
broker_url = ""
if role == "api":
cache_url = _secret("REDIS_URL", "CACHE_URL_FILE")
if not cache_url.startswith(("redis://", "rediss://")):
raise SystemExit("REDIS_URL must start with redis:// or rediss://")
if role in {"api", "gc", "worker"}:
s3_endpoint = os.environ.get("S3_ENDPOINT", "").strip()
if not s3_endpoint:
raise SystemExit("S3_ENDPOINT is required")
s3_access_key_id = _secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
s3_secret_access_key = _secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
if role in {"worker", "relay"}:
broker_url = _secret("BROKER_URL", "BROKER_URL_FILE")
if not broker_url.startswith(("amqp://", "amqps://")):
raise SystemExit("BROKER_URL must start with amqp:// or amqps://")
timeout_seconds = _int("JOB_TIMEOUT_SECONDS", 45, 1, 600)
lease_seconds = _int("JOB_LEASE_SECONDS", 90, 2, 3600)
if lease_seconds <= timeout_seconds:
raise SystemExit("JOB_LEASE_SECONDS must be greater than JOB_TIMEOUT_SECONDS")
migrations = _migrations_dir()
if not migrations.is_dir():
raise SystemExit("migrations directory is missing")
return Settings(
host=host,
port=port,
env=env_name,
app_role=role,
instance_id=_instance_id(),
run_migrations=_flag("RUN_MIGRATIONS", True),
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600),
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 60, 30 * 24 * 3600),
database_url=database_url,
cache_url=cache_url,
s3_endpoint=s3_endpoint,
s3_region=s3_region,
s3_bucket=s3_bucket,
s3_access_key_id=s3_access_key_id,
s3_secret_access_key=s3_secret_access_key,
max_upload_bytes=_int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024, 1024, 10 * 1024 * 1024),
max_image_pixels=_int("MAX_IMAGE_PIXELS", 40_000_000, 1, 40_000_000),
attachment_gc_grace_seconds=_int("ATTACHMENT_GC_GRACE_SECONDS", 900, 1, 24 * 3600),
migrations_dir=migrations,
db_pool_size=_int("DB_POOL_SIZE", 10, 1, 50),
db_max_overflow=_int("DB_MAX_OVERFLOW", 10, 0, 50),
db_pool_timeout_seconds=_float("DB_POOL_TIMEOUT_SECONDS", 5, 0.1, 30),
db_connect_timeout_seconds=_float("DB_CONNECT_TIMEOUT_SECONDS", 2, 0.1, 30),
db_command_timeout_seconds=_float("DB_COMMAND_TIMEOUT_SECONDS", 5, 0.1, 60),
redis_socket_timeout_seconds=_float("REDIS_SOCKET_TIMEOUT_SECONDS", 1, 0.1, 30),
redis_max_connections=_int("REDIS_MAX_CONNECTIONS", 50, 1, 200),
broker_url=broker_url,
worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 8),
job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 20),
job_timeout_seconds=timeout_seconds,
job_lease_seconds=lease_seconds,
job_backoff_base_seconds=_float("JOB_BACKOFF_BASE_SECONDS", 0.4, 0.05, 60),
job_backoff_cap_seconds=_float("JOB_BACKOFF_CAP_SECONDS", 8, 0.1, 300),
pipeline_version=_int("PIPELINE_VERSION", 1, 1, 1000),
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 30, 30 * 24 * 3600),
worker_image_memory_bytes=_int("WORKER_IMAGE_MEMORY_BYTES", 256 * 1024 * 1024, 8 * 1024 * 1024, 1024 * 1024 * 1024),
jpeg_quality=_int("JPEG_QUALITY", 85, 1, 95),
webp_quality=_int("WEBP_QUALITY", 80, 1, 100),
webp_method=_int("WEBP_METHOD", 6, 0, 6),
faults_file=os.environ.get("FAULTS_FILE", "").strip(),
)
+1
View File
@@ -0,0 +1 @@
"""Чтение и изменение PostgreSQL. Сессии живут в Redis, не в этих таблицах."""
+243
View File
@@ -0,0 +1,243 @@
import asyncio
import hashlib
import logging
from datetime import timedelta
from uuid import UUID, uuid4
from sqlalchemy import and_, or_, select
from sqlalchemy.exc import IntegrityError
from app.db import map_integrity, session_scope
from app.errors import AppError
from app.images import declared_content_type, inspect_image
from app.jobs import job_document
from app.models import Attachment, AttachmentJob, AttachmentVariant, ChatMember, JobOutbox
from app.pipeline import variant_names
from app.present import PublicAttachment
from app.runtime import require_settings, require_store
from app.timeutil import utcnow
logger = logging.getLogger("app.attachments")
_VARIANT_ORDER = {name: index for index, name in enumerate(variant_names())}
def validate_filename(filename: str | None) -> str:
if filename is None or filename.strip() == "":
raise AppError(400, "invalid_request", "Некорректное имя файла")
if len(filename) > 255:
raise AppError(400, "invalid_request", "Некорректное имя файла")
for char in filename:
code = ord(char)
if char in {"/", "\\", "\x00"} or code < 32 or code == 127:
raise AppError(400, "invalid_request", "Некорректное имя файла")
return filename
def _variant_dict(row: AttachmentVariant) -> dict:
return {
"name": row.name,
"content_type": row.content_type,
"size_bytes": row.size_bytes,
"width": row.width,
"height": row.height,
"sha256": row.sha256,
}
def _public(row: Attachment, variants: list[dict] | None = None) -> PublicAttachment:
visible = tuple(variants or ()) if row.status == "ready" else ()
return PublicAttachment(
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=visible,
error_code=row.error_code,
created_at=row.created_at,
updated_at=row.updated_at,
)
async def _require_member(session, chat_id: UUID, user_id: UUID) -> None:
member = await session.scalar(
select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)
)
if member is None:
raise AppError(404, "not_found", "Объект не найден")
async def _variants_for(session, attachment_id: UUID) -> list[dict]:
rows = (
await session.scalars(select(AttachmentVariant).where(AttachmentVariant.attachment_id == attachment_id))
).all()
payload = [_variant_dict(row) for row in rows]
payload.sort(key=lambda item: _VARIANT_ORDER.get(item["name"], 9))
return payload
async def create_attachment(
chat_id: UUID,
owner_id: UUID,
filename: str,
content_type_header: str | None,
payload: bytes,
) -> PublicAttachment:
settings = require_settings()
store = require_store()
filename = validate_filename(filename)
declared = declared_content_type(content_type_header)
if not payload:
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
if len(payload) > settings.max_upload_bytes:
raise AppError(413, "payload_too_large", "Файл слишком большой")
async with session_scope() as session:
async with session.begin():
await _require_member(session, chat_id, owner_id)
await asyncio.to_thread(inspect_image, payload, declared, settings.max_image_pixels)
digest = hashlib.sha256(payload).hexdigest()
attachment_id = uuid4()
job_id = uuid4()
staging_key = "staging/%s" % attachment_id
object_key = "att/%s/original" % attachment_id
created_at = utcnow()
await store.put(staging_key, payload, declared)
try:
async with session_scope() as session:
try:
async with session.begin():
await _require_member(session, chat_id, owner_id)
session.add(
Attachment(
id=attachment_id,
chat_id=chat_id,
owner_id=owner_id,
filename=filename,
content_type=declared,
size_bytes=len(payload),
sha256=digest,
object_key=object_key,
staging_key=staging_key,
status="queued",
error_code=None,
created_at=created_at,
updated_at=created_at,
)
)
await session.flush()
session.add(
AttachmentJob(
job_id=job_id,
attachment_id=attachment_id,
pipeline_version=settings.pipeline_version,
status="queued",
attempt=0,
max_attempts=settings.job_max_attempts,
staging_key=staging_key,
objects_written_at=None,
created_at=created_at,
updated_at=created_at,
)
)
await session.flush()
session.add(
JobOutbox(
id=uuid4(),
job_id=job_id,
payload=job_document(job_id, attachment_id, settings.pipeline_version, 1, created_at),
available_at=created_at,
created_at=created_at,
published_at=None,
publish_attempts=0,
gap_injected=False,
)
)
await session.flush()
except IntegrityError as exc:
raise map_integrity(exc, "Конфликт записи") from None
except Exception:
await store.delete(staging_key)
raise
return PublicAttachment(
id=attachment_id,
chat_id=chat_id,
owner_id=owner_id,
filename=filename,
content_type=declared,
size_bytes=len(payload),
sha256=digest,
status="queued",
variants=(),
error_code=None,
created_at=created_at,
updated_at=created_at,
)
async def metadata_for_member(attachment_id: UUID, user_id: UUID) -> PublicAttachment:
async with session_scope() as session:
async with session.begin():
row = await session.get(Attachment, attachment_id)
if row is None:
raise AppError(404, "not_found", "Объект не найден")
await _require_member(session, row.chat_id, user_id)
variants = await _variants_for(session, row.id) if row.status == "ready" else []
return _public(row, variants)
async def open_content(attachment_id: UUID, user_id: UUID, variant: str) -> tuple[str, str]:
if variant not in {"original", "thumbnail", "crop", "optimized"}:
raise AppError(400, "invalid_request", "Некорректный запрос")
async with session_scope() as session:
async with session.begin():
row = await session.get(Attachment, attachment_id)
if row is None:
raise AppError(404, "not_found", "Объект не найден")
await _require_member(session, row.chat_id, user_id)
if row.status != "ready":
raise AppError(409, "conflict", "Вложение ещё не готово")
if variant == "original":
return row.object_key, row.content_type
found = await session.scalar(
select(AttachmentVariant).where(
AttachmentVariant.attachment_id == row.id,
AttachmentVariant.name == variant,
)
)
if found is None:
raise AppError(404, "not_found", "Объект не найден")
return found.object_key, found.content_type
async def known_object_keys() -> set[str]:
settings = require_settings()
retain_after = utcnow() - timedelta(seconds=settings.staging_retention_seconds)
async with session_scope() as session:
async with session.begin():
keys = set((await session.scalars(select(Attachment.object_key))).all())
keys.update((await session.scalars(select(AttachmentVariant.object_key))).all())
staging_jobs = (
await session.scalars(
select(AttachmentJob.staging_key).where(
or_(
AttachmentJob.status.in_(("queued", "processing")),
and_(AttachmentJob.status == "failed", AttachmentJob.updated_at > retain_after),
)
)
)
).all()
keys.update(staging_jobs)
staging_rows = (
await session.scalars(
select(Attachment.staging_key).where(
Attachment.staging_key.is_not(None),
Attachment.status.in_(("queued", "processing")),
)
)
).all()
keys.update(key for key in staging_rows if key)
return keys
+101
View File
@@ -0,0 +1,101 @@
from uuid import UUID, uuid4
from sqlalchemy import select, tuple_
from sqlalchemy.exc import IntegrityError
from app.db import map_integrity, session_scope
from app.errors import AppError
from app.models import Chat, ChatMember, User
from app.pagination import decode_position, slice_page
from app.present import PublicChat
from app.timeutil import utcnow
def _invalid_members() -> AppError:
return AppError(400, "invalid_request", "Некорректный список участников")
async def create_chat(
owner_id: UUID,
title: str,
member_ids: tuple[UUID, ...],
*,
fail_after_insert: bool = False,
) -> PublicChat:
if (
not member_ids
or len(member_ids) > 100
or len(set(member_ids)) != len(member_ids)
or owner_id not in member_ids
):
raise _invalid_members()
chat_id = uuid4()
created_at = utcnow()
async with session_scope() as session:
try:
async with session.begin():
found = set((await session.scalars(select(User.id).where(User.id.in_(member_ids)))).all())
if found != set(member_ids):
raise _invalid_members()
session.add(Chat(id=chat_id, title=title, created_at=created_at))
await session.flush()
# Точка для проверки отката: строка чата уже вставлена, COMMIT ещё нет.
if fail_after_insert:
raise RuntimeError("rollback-check")
for ordinal, member_id in enumerate(member_ids):
session.add(ChatMember(chat_id=chat_id, user_id=member_id, ordinal=ordinal))
await session.flush()
except IntegrityError as exc:
raise map_integrity(exc, "Конфликт записи") from None
return PublicChat(id=chat_id, title=title, member_ids=tuple(member_ids), created_at=created_at)
async def _member_ids(session, chat_id: UUID) -> tuple[UUID, ...]:
rows = await session.execute(
select(ChatMember.user_id).where(ChatMember.chat_id == chat_id).order_by(ChatMember.ordinal)
)
return tuple(row[0] for row in rows)
async def chat_for_member(chat_id: UUID, user_id: UUID) -> PublicChat:
async with session_scope() as session:
async with session.begin():
member = await session.scalar(
select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)
)
chat = await session.get(Chat, chat_id)
if member is None or chat is None:
raise AppError(404, "not_found", "Объект не найден")
return PublicChat(
id=chat.id,
title=chat.title,
member_ids=await _member_ids(session, chat.id),
created_at=chat.created_at,
)
async def chats_for_user(user_id: UUID, limit: int, cursor: str | None) -> dict:
position = decode_position(cursor, "c", user_id) if cursor else None
async with session_scope() as session:
async with session.begin():
stmt = (
select(Chat)
.join(ChatMember, ChatMember.chat_id == Chat.id)
.where(ChatMember.user_id == user_id)
)
if position is not None:
created_at, cursor_id = position
stmt = stmt.where(tuple_(Chat.created_at, Chat.id) > tuple_(created_at, cursor_id))
stmt = stmt.order_by(Chat.created_at.asc(), Chat.id.asc()).limit(limit + 1)
chats = (await session.scalars(stmt)).unique().all()
public = []
for chat in chats:
public.append(
PublicChat(
id=chat.id,
title=chat.title,
member_ids=await _member_ids(session, chat.id),
created_at=chat.created_at,
)
)
return slice_page(public, limit, "c", user_id)
+196
View File
@@ -0,0 +1,196 @@
import hashlib
import json
from datetime import timedelta
from uuid import UUID, uuid4
from sqlalchemy import delete, select, text, tuple_
from sqlalchemy.exc import IntegrityError
from app.db import map_integrity, session_scope
from app.errors import AppError
from app.models import Attachment, ChatMember, IdempotencyRecord, Message, MessageAttachment
from app.pagination import decode_position, slice_page
from app.present import PublicMessage
from app.runtime import require_settings
from app.timeutil import utcnow
def message_path(chat_id: UUID) -> str:
return "/api/v1/chats/%s/messages" % chat_id
def request_fingerprint(text_value: str, attachment_ids: list[UUID]) -> str:
payload = json.dumps(
{
"attachment_ids": [str(item) for item in attachment_ids],
"text": text_value,
},
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _lock_keys(scope: str) -> tuple[int, int]:
digest = hashlib.sha256(scope.encode("utf-8")).digest()
first = int.from_bytes(digest[:4], "big", signed=True)
second = int.from_bytes(digest[4:8], "big", signed=True)
return first, second
def _public(row: Message, attachment_ids: list[UUID]) -> PublicMessage:
return PublicMessage(
id=row.id,
chat_id=row.chat_id,
sender_id=row.sender_id,
text=row.text,
created_at=row.created_at,
attachment_ids=tuple(attachment_ids),
)
async def _require_member(session, chat_id: UUID, user_id: UUID) -> None:
member = await session.scalar(
select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)
)
if member is None:
raise AppError(404, "not_found", "Объект не найден")
async def _attachment_map(session, message_ids: list[UUID]) -> dict[UUID, list[UUID]]:
grouped: dict[UUID, list[UUID]] = {message_id: [] for message_id in message_ids}
if not message_ids:
return grouped
rows = (
await session.execute(
select(MessageAttachment.message_id, MessageAttachment.attachment_id)
.where(MessageAttachment.message_id.in_(message_ids))
.order_by(MessageAttachment.message_id, MessageAttachment.ordinal)
)
).all()
for message_id, attachment_id in rows:
grouped.setdefault(message_id, []).append(attachment_id)
return grouped
async def create_message(
chat_id: UUID,
sender_id: UUID,
text_value: str,
idempotency_key: str,
attachment_ids: list[UUID] | None = None,
) -> PublicMessage:
settings = require_settings()
files = list(attachment_ids or [])
path = message_path(chat_id)
request_hash = request_fingerprint(text_value, files)
lock_a, lock_b = _lock_keys("POST:%s:%s:%s" % (sender_id, path, idempotency_key))
ttl = timedelta(seconds=settings.idempotency_ttl_seconds)
async with session_scope() as session:
try:
async with session.begin():
await session.execute(
text("SELECT pg_advisory_xact_lock(:a, :b)"),
{"a": lock_a, "b": lock_b},
)
await _require_member(session, chat_id, sender_id)
if files:
found = (
await session.scalars(select(Attachment).where(Attachment.id.in_(files)))
).all()
by_id = {row.id: row for row in found}
if len(by_id) != len(files):
raise AppError(404, "not_found", "Объект не найден")
for item in files:
row = by_id[item]
if row.chat_id != chat_id:
raise AppError(404, "not_found", "Объект не найден")
if row.status == "failed":
raise AppError(409, "conflict", "Вложение недоступно")
existing = await session.scalar(
select(IdempotencyRecord).where(
IdempotencyRecord.user_id == sender_id,
IdempotencyRecord.method == "POST",
IdempotencyRecord.request_path == path,
IdempotencyRecord.idempotency_key == idempotency_key,
)
)
now = utcnow()
if existing is not None and existing.created_at + ttl >= now:
if existing.request_hash != request_hash:
raise AppError(409, "conflict", "Повтор ключа с другим сообщением")
row = await session.get(Message, existing.message_id)
if row is None:
raise AppError(500, "internal_error", "Внутренняя ошибка")
mapping = await _attachment_map(session, [row.id])
return _public(row, mapping.get(row.id, []))
if existing is not None:
await session.execute(
delete(IdempotencyRecord).where(
IdempotencyRecord.user_id == existing.user_id,
IdempotencyRecord.method == existing.method,
IdempotencyRecord.request_path == existing.request_path,
IdempotencyRecord.idempotency_key == existing.idempotency_key,
)
)
await session.flush()
message_id = uuid4()
created_at = now
session.add(
Message(
id=message_id,
chat_id=chat_id,
sender_id=sender_id,
text=text_value,
created_at=created_at,
)
)
await session.flush()
for ordinal, attachment_id in enumerate(files):
session.add(
MessageAttachment(
message_id=message_id,
attachment_id=attachment_id,
ordinal=ordinal,
)
)
session.add(
IdempotencyRecord(
user_id=sender_id,
method="POST",
request_path=path,
idempotency_key=idempotency_key,
request_hash=request_hash,
status_code=201,
message_id=message_id,
created_at=created_at,
)
)
await session.flush()
except IntegrityError as exc:
raise map_integrity(exc, "Конфликт записи") from None
return PublicMessage(
id=message_id,
chat_id=chat_id,
sender_id=sender_id,
text=text_value,
created_at=created_at,
attachment_ids=tuple(files),
)
async def messages_for_member(chat_id: UUID, user_id: UUID, limit: int, cursor: str | None) -> dict:
async with session_scope() as session:
async with session.begin():
await _require_member(session, chat_id, user_id)
position = decode_position(cursor, "m", chat_id) if cursor else None
stmt = select(Message).where(Message.chat_id == chat_id)
if position is not None:
created_at, message_id = position
stmt = stmt.where(tuple_(Message.created_at, Message.id) > tuple_(created_at, message_id))
stmt = stmt.order_by(Message.created_at.asc(), Message.id.asc()).limit(limit + 1)
rows = (await session.scalars(stmt)).all()
mapping = await _attachment_map(session, [row.id for row in rows])
public = [_public(row, mapping.get(row.id, [])) for row in rows]
return slice_page(public, limit, "m", chat_id)
+78
View File
@@ -0,0 +1,78 @@
import re
from uuid import UUID, uuid4
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from app.db import map_integrity, session_scope
from app.models import User
from app.present import PublicUser
from app.security import hash_password, verify_password
from app.timeutil import utcnow
_USERNAME = re.compile(r"^[a-z0-9_]{3,32}$")
async def get_user(user_id: UUID) -> PublicUser | None:
async with session_scope() as session:
async with session.begin():
row = (
await session.execute(
select(User.id, User.username, User.display_name, User.created_at).where(User.id == user_id)
)
).one_or_none()
if row is None:
return None
return PublicUser(id=row.id, username=row.username, display_name=row.display_name, created_at=row.created_at)
async def create_user(username: str, display_name: str, password: str) -> PublicUser:
# Argon2 считается до открытия транзакции, чтобы не держать соединение пула.
password_hash = hash_password(password)
user_id = uuid4()
created_at = utcnow()
async with session_scope() as session:
try:
async with session.begin():
session.add(
User(
id=user_id,
username=username,
display_name=display_name,
password_hash=password_hash,
created_at=created_at,
)
)
await session.flush()
except IntegrityError as exc:
raise map_integrity(exc, "Имя пользователя занято") from None
return PublicUser(id=user_id, username=username, display_name=display_name, created_at=created_at)
async def authenticate(username: str, password: str) -> PublicUser | None:
if _USERNAME.fullmatch(username) is None or not 12 <= len(password) <= 128:
verify_password("rejected-credential", None)
return None
async with session_scope() as session:
async with session.begin():
row = (
await session.execute(
select(User.id, User.username, User.display_name, User.created_at, User.password_hash).where(
User.username == username
)
)
).one_or_none()
if row is None:
stored = None
snapshot = None
else:
stored = row.password_hash
snapshot = PublicUser(
id=row.id,
username=row.username,
display_name=row.display_name,
created_at=row.created_at,
)
if not verify_password(password, stored):
return None
return snapshot
+79
View File
@@ -0,0 +1,79 @@
import logging
from contextlib import asynccontextmanager
from redis.exceptions import RedisError
from sqlalchemy.exc import DBAPIError, IntegrityError, InterfaceError, OperationalError
from sqlalchemy.exc import TimeoutError as SATimeout
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
from app.config import Settings
from app.errors import AppError
logger = logging.getLogger("app.db")
def build_engine(settings: Settings) -> AsyncEngine:
command_ms = str(int(settings.db_command_timeout_seconds * 1000))
lock_ms = str(int(settings.db_pool_timeout_seconds * 1000))
return create_async_engine(
settings.database_url,
pool_size=settings.db_pool_size,
max_overflow=settings.db_max_overflow,
pool_timeout=settings.db_pool_timeout_seconds,
pool_pre_ping=True,
pool_recycle=1800,
echo=False,
connect_args={
"timeout": settings.db_connect_timeout_seconds,
"command_timeout": settings.db_command_timeout_seconds,
"server_settings": {
"statement_timeout": command_ms,
"lock_timeout": lock_ms,
"idle_in_transaction_session_timeout": "10000",
},
},
)
def build_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
return async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
def is_dependency_error(exc: BaseException) -> bool:
if isinstance(exc, (OperationalError, InterfaceError, SATimeout, RedisError, ConnectionError, TimeoutError)):
return True
return isinstance(exc, DBAPIError) and bool(getattr(exc, "connection_invalidated", False))
def map_integrity(exc: IntegrityError, duplicate_message: str) -> AppError:
orig = getattr(exc, "orig", None)
code = getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None)
if code == "23505":
return AppError(409, "conflict", duplicate_message)
if code in {"23503", "23514", "23502"}:
return AppError(400, "invalid_request", "Некорректный запрос")
return AppError(500, "internal_error", "Внутренняя ошибка")
@asynccontextmanager
async def session_scope():
from app.runtime import require_factory
factory = require_factory()
try:
session = factory()
except Exception as exc:
if is_dependency_error(exc):
logger.warning("database unavailable type=%s", type(exc).__name__)
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
raise
try:
async with session:
yield session
except AppError:
raise
except Exception as exc:
if is_dependency_error(exc):
logger.warning("database unavailable type=%s", type(exc).__name__)
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
raise
+50
View File
@@ -0,0 +1,50 @@
from fastapi import Depends, Header, Request
from app.crud.users import get_user
from app.errors import AppError
from app.present import PublicUser
from app.sessions import resolve_session
BEARER_CHALLENGE = 'Bearer realm="messenger"'
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
def unauthorized(challenge: str) -> AppError:
return AppError(
401,
"unauthorized",
"Требуется идентификация",
headers={"WWW-Authenticate": challenge},
)
async def get_current_user(
request: Request,
authorization: str | None = Header(default=None),
) -> PublicUser:
# Нет заголовка — клиент анонимный. Redis для этого не нужен и не делает его доверенным.
if authorization is None:
raise unauthorized(BEARER_CHALLENGE)
scheme, _, token = authorization.partition(" ")
token = token.strip()
if scheme.lower() != "bearer" or not token or len(token) > 512:
raise unauthorized(BEARER_CHALLENGE)
user_id = await resolve_session(token)
if user_id is None:
raise unauthorized(BEARER_CHALLENGE)
user = await get_user(user_id)
if user is None:
raise unauthorized(BEARER_CHALLENGE)
request.state.session_token = token
return user
def current_token(request: Request) -> str:
token = getattr(request.state, "session_token", "")
if not token:
raise unauthorized(BEARER_CHALLENGE)
return token
def require_token(request: Request, user: PublicUser = Depends(get_current_user)) -> str:
del user
return current_token(request)
+54
View File
@@ -0,0 +1,54 @@
import logging
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException
class AppError(Exception):
def __init__(self, status: int, code: str, message: str, headers: dict | None = None) -> None:
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.headers = headers
def request_id_of(request: Request) -> str:
return getattr(request.state, "request_id", "") or "missing"
def error_response(
status: int,
code: str,
message: str,
request_id: str,
headers: dict | None = None,
) -> JSONResponse:
return JSONResponse(
status_code=status,
content={"error": {"code": code, "message": message, "request_id": request_id}},
headers=headers,
)
async def handle_app_error(request: Request, exc: AppError) -> JSONResponse:
return error_response(exc.status, exc.code, exc.message, request_id_of(request), exc.headers)
async def handle_dependency(request: Request, exc: Exception) -> JSONResponse:
# Текст исключения может содержать SQL или параметры. В ответ и лог его не кладём.
logging.getLogger("app").warning("dependency unavailable type=%s", type(exc).__name__)
return error_response(503, "unavailable", "Сервис временно недоступен", request_id_of(request))
async def handle_validation_error(request: Request, _exc: RequestValidationError) -> JSONResponse:
return error_response(400, "invalid_request", "Некорректный запрос", request_id_of(request))
async def handle_http_error(request: Request, exc: HTTPException) -> JSONResponse:
# Тело не в UTF-8 FastAPI превращает в HTTPException 400 с полем detail.
if exc.status_code == 400:
return error_response(400, "invalid_request", "Некорректный запрос", request_id_of(request))
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}, headers=exc.headers)
+45
View File
@@ -0,0 +1,45 @@
import json
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class Faults:
inject_transient: bool = False
crash_after_s3: bool = False
relay_exit_before_publish: bool = False
stall_seconds: float = 0
timeout_seconds: float = 0
def read_faults(path: str) -> Faults:
if not path:
return Faults()
file = Path(path)
if not file.is_file():
return Faults()
try:
raw = json.loads(file.read_text(encoding="utf-8"))
except (OSError, ValueError, UnicodeError):
return Faults()
if not isinstance(raw, dict):
return Faults()
def flag(name: str) -> bool:
return bool(raw.get(name))
def number(name: str) -> float:
value = raw.get(name, 0)
if isinstance(value, bool) or not isinstance(value, (int, float)):
return 0
if value < 0:
return 0
return float(value)
return Faults(
inject_transient=flag("inject_transient"),
crash_after_s3=flag("crash_after_s3"),
relay_exit_before_publish=flag("relay_exit_before_publish"),
stall_seconds=number("stall_seconds"),
timeout_seconds=number("timeout_seconds"),
)
+66
View File
@@ -0,0 +1,66 @@
import asyncio
import logging
import os
import sys
from datetime import timedelta
from app.config import load_settings
from app.crud.attachments import known_object_keys
from app.db import build_engine, build_session_factory
from app.migrate import wait_for_database, wait_for_schema
from app.runtime import configure
from app.s3 import build_store
from app.timeutil import utcnow
logger = logging.getLogger("app.gc")
async def sweep_once() -> int:
settings = load_settings()
store = build_store(settings)
engine = build_engine(settings)
try:
await wait_for_database(engine)
await wait_for_schema(engine, settings.migrations_dir)
configure(build_session_factory(engine), None, settings, store)
cutoff = utcnow() - timedelta(seconds=settings.attachment_gc_grace_seconds)
known = await known_object_keys()
deleted = 0
for key, modified in await store.list_objects():
if key in known or modified > cutoff:
continue
await store.delete(key)
deleted += 1
if deleted:
logger.info("orphan objects deleted count=%s", deleted)
return deleted
finally:
await engine.dispose()
async def run_loop() -> None:
settings = load_settings()
interval = min(60, max(15, settings.attachment_gc_grace_seconds // 6))
while True:
try:
await sweep_once()
except Exception as exc:
logger.warning("gc sweep failed type=%s", type(exc).__name__)
await asyncio.sleep(interval)
def main() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
force=True,
)
if os.environ.get("GC_ONCE", "").strip() in {"1", "true", "yes"}:
asyncio.run(sweep_once())
return
asyncio.run(run_loop())
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
import io
from dataclasses import dataclass
from PIL import Image, ImageFile, UnidentifiedImageError
from app.errors import AppError
ImageFile.LOAD_TRUNCATED_IMAGES = False
_PNG = b"\x89PNG\r\n\x1a\n"
_JPEG = b"\xff\xd8\xff"
@dataclass(frozen=True)
class ImageMeta:
content_type: str
def declared_content_type(header: str | None) -> str:
value = (header or "").split(";", 1)[0].strip().lower()
if value in {"image/png", "image/jpeg"}:
return value
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
def sniff_content_type(data: bytes) -> str | None:
if data.startswith(_PNG):
return "image/png"
if data.startswith(_JPEG):
return "image/jpeg"
return None
def inspect_image(data: bytes, declared: str, max_pixels: int) -> ImageMeta:
sniffed = sniff_content_type(data)
if sniffed is None or sniffed != declared:
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
Image.MAX_IMAGE_PIXELS = max_pixels
try:
with Image.open(io.BytesIO(data)) as image:
width, height = image.size
if width < 1 or height < 1:
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения")
if width * height > max_pixels:
raise AppError(413, "payload_too_large", "Слишком большое изображение")
image.verify()
except AppError:
raise
except Image.DecompressionBombError:
raise AppError(413, "payload_too_large", "Слишком большое изображение") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
raise AppError(415, "unsupported_media_type", "Неподдерживаемый тип изображения") from None
return ImageMeta(content_type=declared)
+417
View File
@@ -0,0 +1,417 @@
import json
import logging
import random
from dataclasses import dataclass
from datetime import datetime, timedelta
from uuid import UUID, uuid4
from sqlalchemy import select
from app.db import session_scope
from app.models import Attachment, AttachmentJob, AttachmentVariant, JobFailure, JobOutbox, JobReplay
from app.pipeline import variant_names
from app.runtime import require_settings
from app.timeutil import format_time, utcnow
logger = logging.getLogger("app.jobs")
REQUIRED_VARIANTS = set(variant_names())
@dataclass(frozen=True)
class AcquireResult:
action: str
job_id: UUID | None = None
attachment_id: UUID | None = None
pipeline_version: int = 1
attempt: int = 0
max_attempts: int = 1
staging_key: str = ""
object_key: str = ""
content_type: str = ""
sha256: str = ""
size_bytes: int = 0
objects_written_at: datetime | None = None
def backoff_seconds(attempt: int, base: float, cap: float) -> float:
delay = base * (2 ** min(max(attempt - 1, 0), 8))
if delay > cap:
delay = cap
total = delay + random.uniform(0, base)
if total > cap:
return cap
return total
def job_document(job_id: UUID, attachment_id: UUID, pipeline_version: int, attempt: int, created_at: datetime) -> str:
body = {
"schema_version": 1,
"job_id": str(job_id),
"type": "attachment.process.v1",
"attachment_id": str(attachment_id),
"pipeline_version": pipeline_version,
"attempt": max(1, attempt),
"created_at": format_time(created_at),
}
return json.dumps(body, separators=(",", ":"), sort_keys=True)
def _outbox(job: AttachmentJob, when: datetime, attempt: int) -> JobOutbox:
return JobOutbox(
id=uuid4(),
job_id=job.job_id,
payload=job_document(job.job_id, job.attachment_id, job.pipeline_version, attempt, job.created_at),
available_at=when,
created_at=when,
published_at=None,
publish_attempts=0,
gap_injected=False,
)
def _failure(job: AttachmentJob, code: str, permanent: bool, when: datetime) -> JobFailure:
return JobFailure(
id=uuid4(),
job_id=job.job_id,
attachment_id=job.attachment_id,
attempt=job.attempt,
error_code=code,
permanent=permanent,
created_at=when,
)
async def _variant_names(session, attachment_id: UUID) -> set[str]:
rows = (
await session.scalars(select(AttachmentVariant.name).where(AttachmentVariant.attachment_id == attachment_id))
).all()
return set(rows)
async def acquire_job(job_id: UUID, owner: str, redelivered: bool) -> AcquireResult:
settings = require_settings()
now = utcnow()
until = now + timedelta(seconds=settings.job_lease_seconds)
async with session_scope() as session:
async with session.begin():
job = await session.get(AttachmentJob, job_id, with_for_update=True)
if job is None:
return AcquireResult(action="missing")
attachment = await session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment is None:
return AcquireResult(action="missing")
if attachment.status == "ready" or job.status == "ready":
job.status = "ready"
job.lease_until = None
job.lease_owner = None
job.error_code = None
job.updated_at = now
if attachment.status != "ready":
attachment.status = "ready"
attachment.error_code = None
attachment.updated_at = now
return AcquireResult(action="ready", job_id=job.job_id, attachment_id=attachment.id)
if job.status == "failed" or attachment.status == "failed":
return AcquireResult(action="failed", job_id=job.job_id, attachment_id=attachment.id)
if job.status == "queued" and job.attempt >= job.max_attempts:
code = "retry_exhausted"
job.status = "failed"
job.error_code = code
job.lease_until = None
job.lease_owner = None
job.updated_at = now
attachment.status = "failed"
attachment.error_code = code
attachment.updated_at = now
session.add(_failure(job, code, True, now))
return AcquireResult(action="failed", job_id=job.job_id, attachment_id=attachment.id)
held = (
job.status == "processing"
and job.lease_owner
and job.lease_owner != owner
and job.lease_until is not None
and job.lease_until > now
and not redelivered
)
if held:
return AcquireResult(action="busy", job_id=job.job_id, attachment_id=attachment.id)
if job.status == "queued":
job.attempt += 1
job.status = "processing"
job.lease_until = until
job.lease_owner = owner
job.updated_at = now
attachment.status = "processing"
attachment.error_code = None
attachment.updated_at = now
return AcquireResult(
action="acquired",
job_id=job.job_id,
attachment_id=attachment.id,
pipeline_version=job.pipeline_version,
attempt=job.attempt,
max_attempts=job.max_attempts,
staging_key=job.staging_key,
object_key=attachment.object_key,
content_type=attachment.content_type,
sha256=attachment.sha256,
size_bytes=attachment.size_bytes,
objects_written_at=job.objects_written_at,
)
async def mark_objects_written(job_id: UUID) -> None:
now = utcnow()
async with session_scope() as session:
async with session.begin():
job = await session.get(AttachmentJob, job_id, with_for_update=True)
if job is None or job.objects_written_at is not None:
return
job.objects_written_at = now
job.updated_at = now
async def fail_or_retry(job_id: UUID, code: str, permanent: bool) -> str:
settings = require_settings()
now = utcnow()
async with session_scope() as session:
async with session.begin():
job = await session.get(AttachmentJob, job_id, with_for_update=True)
if job is None or job.status == "ready":
return "ignored"
attachment = await session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment is None or attachment.status == "ready":
return "ignored"
terminal = permanent or job.attempt >= job.max_attempts
final_code = code if permanent else "retry_exhausted"
session.add(_failure(job, final_code if terminal else code, terminal, now))
job.lease_until = None
job.lease_owner = None
job.updated_at = now
if terminal:
job.status = "failed"
job.error_code = final_code
attachment.status = "failed"
attachment.error_code = final_code
attachment.updated_at = now
payload = job_document(job.job_id, job.attachment_id, job.pipeline_version, max(1, job.attempt), job.created_at)
return "failed:" + payload
delay = backoff_seconds(job.attempt, settings.job_backoff_base_seconds, settings.job_backoff_cap_seconds)
job.status = "queued"
job.error_code = None
job.next_attempt_at = now + timedelta(seconds=delay)
attachment.status = "queued"
attachment.error_code = None
attachment.updated_at = now
session.add(_outbox(job, job.next_attempt_at, job.attempt + 1))
logger.info(
"job retry scheduled job_id=%s attempt=%s backoff_seconds=%.3f",
job.job_id,
job.attempt,
delay,
)
return "retry"
async def finalize_job(job_id: UUID, variants: list[dict]) -> str:
now = utcnow()
async with session_scope() as session:
async with session.begin():
job = await session.get(AttachmentJob, job_id, with_for_update=True)
if job is None:
return "missing"
attachment = await session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment is None:
return "missing"
if job.status == "ready" and attachment.status == "ready":
return "already"
for item in variants:
existing = await session.scalar(
select(AttachmentVariant).where(
AttachmentVariant.attachment_id == attachment.id,
AttachmentVariant.name == item["name"],
)
)
if existing is not None and existing.pipeline_version > job.pipeline_version:
continue
if existing is None:
session.add(
AttachmentVariant(
attachment_id=attachment.id,
name=item["name"],
content_type=item["content_type"],
size_bytes=item["size_bytes"],
width=item["width"],
height=item["height"],
sha256=item["sha256"],
object_key=item["object_key"],
pipeline_version=job.pipeline_version,
)
)
else:
existing.content_type = item["content_type"]
existing.size_bytes = item["size_bytes"]
existing.width = item["width"]
existing.height = item["height"]
existing.sha256 = item["sha256"]
existing.object_key = item["object_key"]
existing.pipeline_version = job.pipeline_version
names = await _variant_names(session, attachment.id)
names.update(item["name"] for item in variants)
if not REQUIRED_VARIANTS <= names:
return "incomplete"
attachment.status = "ready"
attachment.error_code = None
attachment.updated_at = now
job.status = "ready"
job.error_code = None
job.lease_until = None
job.lease_owner = None
job.updated_at = now
return "ready"
async def sweep_expired_leases() -> int:
settings = require_settings()
now = utcnow()
changed = 0
async with session_scope() as session:
async with session.begin():
rows = (
await session.scalars(
select(AttachmentJob)
.where(
AttachmentJob.status == "processing",
AttachmentJob.lease_until.is_not(None),
AttachmentJob.lease_until < now,
)
.with_for_update(skip_locked=True)
)
).all()
for job in rows:
attachment = await session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment is None or attachment.status == "ready" or job.status == "ready":
job.status = "ready"
job.lease_until = None
job.lease_owner = None
job.updated_at = now
continue
job.lease_until = None
job.lease_owner = None
job.updated_at = now
if job.attempt >= job.max_attempts:
job.status = "failed"
job.error_code = "retry_exhausted"
attachment.status = "failed"
attachment.error_code = "retry_exhausted"
attachment.updated_at = now
session.add(_failure(job, "retry_exhausted", True, now))
else:
delay = backoff_seconds(job.attempt, settings.job_backoff_base_seconds, settings.job_backoff_cap_seconds)
when = now + timedelta(seconds=delay)
job.status = "queued"
job.error_code = None
job.next_attempt_at = when
attachment.status = "queued"
attachment.error_code = None
attachment.updated_at = now
session.add(_outbox(job, when, job.attempt + 1))
changed += 1
if changed:
logger.info("expired leases recovered count=%s", changed)
return changed
async def mark_gap_and_list(limit: int, crash_enabled: bool) -> tuple[list[dict], UUID | None]:
now = utcnow()
async with session_scope() as session:
async with session.begin():
rows = (
await session.scalars(
select(JobOutbox)
.where(JobOutbox.published_at.is_(None), JobOutbox.available_at <= now)
.order_by(JobOutbox.created_at.asc(), JobOutbox.id.asc())
.limit(limit)
.with_for_update(skip_locked=True)
)
).all()
crash_id = None
# Один аварийный выход на пачку: если разрыв уже отмечен, публикуем, а не падаем снова.
if crash_enabled and rows and not any(row.gap_injected for row in rows):
rows[0].gap_injected = True
crash_id = rows[0].id
batch = [
{
"id": row.id,
"job_id": row.job_id,
"payload": row.payload,
"gap_injected": row.gap_injected,
}
for row in rows
]
return batch, crash_id
async def mark_published(outbox_id: UUID) -> None:
now = utcnow()
async with session_scope() as session:
async with session.begin():
row = await session.get(JobOutbox, outbox_id, with_for_update=True)
if row is None or row.published_at is not None:
return
row.published_at = now
row.publish_attempts += 1
async def note_publish_attempt(outbox_id: UUID) -> None:
async with session_scope() as session:
async with session.begin():
row = await session.get(JobOutbox, outbox_id)
if row is None:
return
row.publish_attempts += 1
async def replay_job(job_id: UUID) -> dict:
now = utcnow()
async with session_scope() as session:
async with session.begin():
job = await session.get(AttachmentJob, job_id, with_for_update=True)
if job is None:
return {"outcome": "not_found", "job_id": str(job_id)}
attachment = await session.get(Attachment, job.attachment_id, with_for_update=True)
if attachment is None:
return {"outcome": "not_found", "job_id": str(job_id)}
names = await _variant_names(session, attachment.id)
if attachment.status == "ready" and job.status == "ready" and REQUIRED_VARIANTS <= names:
session.add(JobReplay(id=uuid4(), job_id=job.job_id, outcome="already_ready", created_at=now))
return {
"outcome": "already_ready",
"job_id": str(job.job_id),
"attachment_id": str(attachment.id),
}
if job.status in {"queued", "processing"} and attachment.status != "failed":
session.add(JobReplay(id=uuid4(), job_id=job.job_id, outcome="in_progress", created_at=now))
return {
"outcome": "in_progress",
"job_id": str(job.job_id),
"attachment_id": str(attachment.id),
}
job.status = "queued"
job.attempt = 0
job.error_code = None
job.lease_until = None
job.lease_owner = None
job.next_attempt_at = now
job.updated_at = now
attachment.status = "queued"
attachment.error_code = None
attachment.updated_at = now
session.add(_outbox(job, now, 1))
session.add(JobReplay(id=uuid4(), job_id=job.job_id, outcome="enqueued", created_at=now))
return {
"outcome": "enqueued",
"job_id": str(job.job_id),
"attachment_id": str(attachment.id),
}
+114
View File
@@ -0,0 +1,114 @@
import asyncio
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from redis.exceptions import RedisError
from sqlalchemy.exc import InterfaceError, OperationalError, ProgrammingError
from sqlalchemy.exc import TimeoutError as SATimeout
from starlette.exceptions import HTTPException
from app.api import api_router
from app.api.health import router as health_router
from app.config import load_settings
from app.db import build_engine, build_session_factory, is_dependency_error
from app.errors import AppError, handle_app_error, handle_dependency, handle_http_error, handle_validation_error
from app.migrate import apply_migrations, wait_for_database, wait_for_schema
from app.middleware import request_context
from app.runtime import configure
from app.s3 import build_store
from app.security import init_security
from app.sessions import build_redis
logger = logging.getLogger("app")
async def open_stores(engine, redis, store, settings) -> None:
await wait_for_database(engine)
for attempt in range(40):
try:
await redis.ping()
break
except Exception as exc:
if not is_dependency_error(exc):
logger.error("redis probe failed type=%s", type(exc).__name__)
raise SystemExit("redis probe failed") from None
logger.warning("redis not ready type=%s attempt=%s", type(exc).__name__, attempt + 1)
if attempt == 39:
raise SystemExit("redis is not ready") from None
await asyncio.sleep(0.5)
for attempt in range(40):
try:
await store.ping()
break
except AppError:
logger.warning("s3 not ready attempt=%s", attempt + 1)
if attempt == 39:
raise SystemExit("s3 is not ready") from None
await asyncio.sleep(0.5)
except Exception as exc:
logger.warning("s3 probe failed type=%s attempt=%s", type(exc).__name__, attempt + 1)
if attempt == 39:
raise SystemExit("s3 is not ready") from None
await asyncio.sleep(0.5)
if settings.run_migrations:
try:
applied = await apply_migrations(engine, settings.migrations_dir)
logger.info("migrations newly_applied=%s", applied)
except ProgrammingError as exc:
sqlstate = getattr(getattr(exc, "orig", None), "sqlstate", "")
logger.error("migration rejected type=%s sqlstate=%s", type(exc).__name__, sqlstate)
raise SystemExit("migration failed") from None
else:
await wait_for_schema(engine, settings.migrations_dir)
@asynccontextmanager
async def lifespan(app: FastAPI):
settings = load_settings()
init_security()
engine = build_engine(settings)
redis = build_redis(settings)
store = build_store(settings)
app.state.engine = engine
app.state.redis = redis
app.state.store = store
app.state.settings = settings
app.state.instance_id = settings.instance_id
app.state.accepting = False
try:
await open_stores(engine, redis, store, settings)
configure(build_session_factory(engine), redis, settings, store)
app.state.accepting = True
logger.info(
"ready env=%s instance_id=%s session_ttl_seconds=%s db_pool=%s",
settings.env,
settings.instance_id,
settings.session_ttl_seconds,
settings.db_pool_size,
)
yield
finally:
app.state.accepting = False
logger.info("shutdown: new requests are no longer accepted")
await redis.aclose()
await engine.dispose()
def create_app() -> FastAPI:
app = FastAPI(title="MTUSI Messenger", version="1.5.0", lifespan=lifespan)
app.state.instance_id = "starting"
app.state.accepting = False
app.add_exception_handler(AppError, handle_app_error)
app.add_exception_handler(RequestValidationError, handle_validation_error)
app.add_exception_handler(HTTPException, handle_http_error)
for cls in (OperationalError, InterfaceError, SATimeout, RedisError):
app.add_exception_handler(cls, handle_dependency)
app.middleware("http")(request_context)
app.include_router(health_router)
app.include_router(api_router)
return app
app = create_app()
+52
View File
@@ -0,0 +1,52 @@
import logging
import time
from uuid import uuid4
from fastapi import Request
from app.db import is_dependency_error
from app.errors import error_response
logger = logging.getLogger("app.access")
def _instance_id(request: Request) -> str:
settings = getattr(request.app.state, "settings", None)
if settings is not None:
return settings.instance_id
return getattr(request.app.state, "instance_id", "starting")
async def request_context(request: Request, call_next):
request_id = uuid4().hex
request.state.request_id = request_id
started = time.perf_counter()
status = 500
try:
accepting = getattr(request.app.state, "accepting", True)
if not accepting and request.url.path != "/health/live":
response = error_response(503, "unavailable", "Сервер останавливается", request_id)
else:
try:
response = await call_next(request)
except Exception as exc:
if is_dependency_error(exc):
logger.warning("dependency unavailable type=%s", type(exc).__name__)
response = error_response(503, "unavailable", "Сервис временно недоступен", request_id)
else:
logger.error("internal error request_id=%s type=%s", request_id, type(exc).__name__)
response = error_response(500, "internal_error", "Внутренняя ошибка", request_id)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = _instance_id(request)
status = response.status_code
return response
finally:
elapsed_ms = int((time.perf_counter() - started) * 1000)
logger.info(
"request method=%s path=%s status=%s request_id=%s duration_ms=%s",
request.method,
request.url.path,
status,
request_id,
elapsed_ms,
)
+141
View File
@@ -0,0 +1,141 @@
import asyncio
import logging
import sys
from pathlib import Path
from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine
from app.config import load_settings
from app.db import build_engine, is_dependency_error
logger = logging.getLogger("app.migrate")
# Один номер на все процессы, чтобы две миграции не применяли DDL одновременно.
_ADVISORY_LOCK = 842021
def sql_statements(script: str) -> list[str]:
lines = []
for line in script.splitlines():
if line.strip().startswith("--"):
continue
lines.append(line)
statements = []
for part in "\n".join(lines).split(";"):
statement = part.strip()
if statement:
statements.append(statement)
return statements
def expected_versions(directory: Path) -> list[str]:
files = sorted(path for path in directory.glob("*.sql") if path.is_file())
if not files:
raise SystemExit("no SQL migrations found")
return [path.name for path in files]
async def apply_migrations(engine: AsyncEngine, directory: Path) -> int:
files = sorted(path for path in directory.glob("*.sql") if path.is_file())
if not files:
raise SystemExit("no SQL migrations found")
applied = 0
async with engine.begin() as conn:
await conn.execute(text("SELECT pg_advisory_xact_lock(:lock_id)"), {"lock_id": _ADVISORY_LOCK})
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
)
for path in files:
version = path.name
exists = await conn.scalar(
text("SELECT version FROM schema_migrations WHERE version = :version"),
{"version": version},
)
if exists:
continue
for statement in sql_statements(path.read_text(encoding="utf-8")):
await conn.execute(text(statement))
await conn.execute(
text("INSERT INTO schema_migrations (version) VALUES (:version)"),
{"version": version},
)
applied += 1
logger.info("migration applied version=%s", version)
return applied
async def wait_for_database(engine: AsyncEngine) -> None:
for attempt in range(40):
try:
async with engine.connect() as conn:
await conn.execute(text("SELECT 1"))
return
except Exception as exc:
if not is_dependency_error(exc):
logger.error("database probe failed type=%s", type(exc).__name__)
raise SystemExit("database probe failed") from None
logger.warning("database not ready type=%s attempt=%s", type(exc).__name__, attempt + 1)
if attempt == 39:
raise SystemExit("database is not ready") from None
await asyncio.sleep(0.5)
async def wait_for_schema(engine: AsyncEngine, directory: Path) -> None:
needed = set(expected_versions(directory))
for attempt in range(40):
try:
async with engine.connect() as conn:
rows = (await conn.execute(text("SELECT version FROM schema_migrations"))).all()
found = {row[0] for row in rows}
if needed <= found:
logger.info("schema ready versions=%s", ",".join(sorted(found)))
return
logger.warning("schema incomplete attempt=%s", attempt + 1)
except ProgrammingError:
logger.warning("schema_migrations missing attempt=%s", attempt + 1)
except Exception as exc:
if not is_dependency_error(exc):
logger.error("schema probe failed type=%s", type(exc).__name__)
raise SystemExit("schema probe failed") from None
logger.warning("schema probe unavailable type=%s attempt=%s", type(exc).__name__, attempt + 1)
if attempt == 39:
raise SystemExit("schema is not ready")
await asyncio.sleep(0.5)
async def run_job() -> None:
settings = load_settings()
engine = build_engine(settings)
try:
await wait_for_database(engine)
applied = await apply_migrations(engine, settings.migrations_dir)
logger.info("migrations newly_applied=%s", applied)
except ProgrammingError as exc:
sqlstate = getattr(getattr(exc, "orig", None), "sqlstate", "")
logger.error("migration rejected type=%s sqlstate=%s", type(exc).__name__, sqlstate)
raise SystemExit("migration failed") from None
finally:
await engine.dispose()
def main() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
force=True,
)
asyncio.run(run_job())
if __name__ == "__main__":
main()
+300
View File
@@ -0,0 +1,300 @@
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
SmallInteger,
Text,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
__table_args__ = (
UniqueConstraint("username", name="uq_users_username"),
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="ck_users_username_format"),
CheckConstraint(
"char_length(btrim(display_name)) >= 1 AND char_length(display_name) <= 100",
name="ck_users_display_name_len",
),
CheckConstraint("char_length(password_hash) >= 20", name="ck_users_password_hash_len"),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
username: Mapped[str] = mapped_column(Text, nullable=False)
display_name: Mapped[str] = mapped_column(Text, nullable=False)
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class Chat(Base):
__tablename__ = "chats"
__table_args__ = (
CheckConstraint(
"char_length(btrim(title)) >= 1 AND char_length(title) <= 100",
name="ck_chats_title",
),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
title: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class ChatMember(Base):
__tablename__ = "chat_members"
__table_args__ = (
CheckConstraint("ordinal >= 0 AND ordinal < 100", name="ck_chat_members_ordinal"),
Index("ix_chat_members_user", "user_id", "chat_id"),
)
chat_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("chats.id"),
primary_key=True,
)
user_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("users.id"),
primary_key=True,
)
ordinal: Mapped[int] = mapped_column(SmallInteger, nullable=False)
class Message(Base):
__tablename__ = "messages"
__table_args__ = (
CheckConstraint(
"char_length(body) <= 4000",
name="ck_messages_text",
),
# Keyset: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4
Index("ix_messages_history", "chat_id", "created_at", "id"),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id"), nullable=False)
sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
text: Mapped[str] = mapped_column("body", Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class IdempotencyRecord(Base):
__tablename__ = "idempotency_records"
__table_args__ = (
CheckConstraint("method = 'POST'", name="ck_idem_method"),
CheckConstraint("status_code = 201", name="ck_idem_status"),
CheckConstraint("idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$'", name="ck_idem_key"),
CheckConstraint("char_length(request_path) BETWEEN 1 AND 300", name="ck_idem_path"),
CheckConstraint("char_length(request_hash) = 64", name="ck_idem_hash"),
Index("ix_idempotency_message", "message_id"),
Index("ix_idempotency_created", "created_at"),
)
user_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("users.id"),
primary_key=True,
)
method: Mapped[str] = mapped_column(Text, primary_key=True)
request_path: Mapped[str] = mapped_column(Text, primary_key=True)
idempotency_key: Mapped[str] = mapped_column(Text, primary_key=True)
request_hash: Mapped[str] = mapped_column(Text, nullable=False)
status_code: Mapped[int] = mapped_column(SmallInteger, nullable=False)
message_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("messages.id"),
nullable=False,
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class Attachment(Base):
__tablename__ = "attachments"
__table_args__ = (
UniqueConstraint("object_key", name="uq_attachments_object_key"),
CheckConstraint("char_length(filename) BETWEEN 1 AND 255", name="ck_attachments_filename"),
CheckConstraint("content_type IN ('image/png', 'image/jpeg')", name="ck_attachments_content_type"),
CheckConstraint("size_bytes >= 1 AND size_bytes <= 10485760", name="ck_attachments_size"),
CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_attachments_sha256"),
CheckConstraint(
"status IN ('queued', 'processing', 'ready', 'failed')",
name="ck_attachments_status",
),
CheckConstraint(
"(status = 'failed' AND error_code IS NOT NULL) OR (status <> 'failed' AND error_code IS NULL)",
name="ck_attachments_error",
),
CheckConstraint(
"staging_key IS NULL OR char_length(staging_key) BETWEEN 8 AND 300",
name="ck_attachments_staging",
),
Index("ix_attachments_chat", "chat_id", "created_at", "id"),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id"), nullable=False)
owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
filename: Mapped[str] = mapped_column(Text, nullable=False)
content_type: Mapped[str] = mapped_column(Text, nullable=False)
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(Text, nullable=False)
object_key: Mapped[str] = mapped_column(Text, nullable=False)
staging_key: Mapped[str | None] = mapped_column(Text, nullable=True)
status: Mapped[str] = mapped_column(Text, nullable=False)
error_code: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class AttachmentVariant(Base):
__tablename__ = "attachment_variants"
__table_args__ = (
UniqueConstraint("object_key", name="uq_attachment_variants_object_key"),
CheckConstraint("name IN ('thumbnail', 'crop', 'optimized')", name="ck_variants_name"),
CheckConstraint(
"content_type IN ('image/jpeg', 'image/png', 'image/webp')",
name="ck_variants_type",
),
CheckConstraint("size_bytes >= 1", name="ck_variants_size"),
CheckConstraint("width >= 1 AND height >= 1", name="ck_variants_dim"),
CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_variants_sha"),
CheckConstraint("pipeline_version >= 1", name="ck_variants_pipeline"),
)
attachment_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("attachments.id"),
primary_key=True,
)
name: Mapped[str] = mapped_column(Text, primary_key=True)
content_type: Mapped[str] = mapped_column(Text, nullable=False)
size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)
width: Mapped[int] = mapped_column(Integer, nullable=False)
height: Mapped[int] = mapped_column(Integer, nullable=False)
sha256: Mapped[str] = mapped_column(Text, nullable=False)
object_key: Mapped[str] = mapped_column(Text, nullable=False)
pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False)
class AttachmentJob(Base):
__tablename__ = "attachment_jobs"
__table_args__ = (
UniqueConstraint("attachment_id", "pipeline_version", name="uq_attachment_jobs_effect"),
CheckConstraint("status IN ('queued', 'processing', 'ready', 'failed')", name="ck_jobs_status"),
CheckConstraint("attempt >= 0 AND attempt <= max_attempts", name="ck_jobs_attempt"),
CheckConstraint("max_attempts BETWEEN 1 AND 20", name="ck_jobs_max"),
CheckConstraint("pipeline_version >= 1", name="ck_jobs_pipeline"),
Index("ix_jobs_lease", "status", "lease_until"),
)
job_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
attachment_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("attachments.id"),
nullable=False,
)
pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(Text, nullable=False)
attempt: Mapped[int] = mapped_column(Integer, nullable=False)
max_attempts: Mapped[int] = mapped_column(Integer, nullable=False)
lease_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
lease_owner: Mapped[str | None] = mapped_column(Text, nullable=True)
next_attempt_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
error_code: Mapped[str | None] = mapped_column(Text, nullable=True)
staging_key: Mapped[str] = mapped_column(Text, nullable=False)
objects_written_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class JobOutbox(Base):
__tablename__ = "job_outbox"
__table_args__ = (
CheckConstraint("publish_attempts >= 0", name="ck_outbox_attempts"),
Index("ix_outbox_pending", "available_at", "created_at"),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
job_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("attachment_jobs.job_id"),
nullable=False,
)
payload: Mapped[str] = mapped_column(Text, nullable=False)
available_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
publish_attempts: Mapped[int] = mapped_column(Integer, nullable=False)
gap_injected: Mapped[bool] = mapped_column(Boolean, nullable=False)
class JobFailure(Base):
__tablename__ = "job_failures"
__table_args__ = (
CheckConstraint("char_length(error_code) BETWEEN 1 AND 64", name="ck_job_failures_code"),
Index("ix_job_failures_job", "job_id", "created_at"),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
job_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("attachment_jobs.job_id"),
nullable=False,
)
attachment_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
attempt: Mapped[int] = mapped_column(Integer, nullable=False)
error_code: Mapped[str] = mapped_column(Text, nullable=False)
permanent: Mapped[bool] = mapped_column(Boolean, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class JobReplay(Base):
__tablename__ = "job_replays"
__table_args__ = (
CheckConstraint(
"outcome IN ('enqueued', 'already_ready', 'in_progress')",
name="ck_replays_outcome",
),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
job_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("attachment_jobs.job_id"),
nullable=False,
)
outcome: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class MessageAttachment(Base):
__tablename__ = "message_attachments"
__table_args__ = (
CheckConstraint("ordinal >= 0 AND ordinal < 10", name="ck_message_attachments_ordinal"),
Index("ix_message_attachments_attachment", "attachment_id"),
)
message_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("messages.id"),
primary_key=True,
)
attachment_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("attachments.id"),
primary_key=True,
)
ordinal: Mapped[int] = mapped_column(SmallInteger, nullable=False)
+50
View File
@@ -0,0 +1,50 @@
import base64
import json
from datetime import datetime
from uuid import UUID
from app.errors import AppError
from app.timeutil import format_time, parse_time
def encode_cursor(kind: str, resource_id: UUID, created_at: datetime, entity_id: UUID) -> str:
payload = {
"i": str(entity_id),
"k": kind,
"r": str(resource_id),
"t": format_time(created_at),
}
raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("ascii")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_position(token: str, kind: str, resource_id: UUID) -> tuple[datetime, UUID]:
if len(token) > 1024:
raise AppError(400, "invalid_request", "Некорректный cursor")
padding = "=" * (-len(token) % 4)
try:
data = json.loads(base64.urlsafe_b64decode(token + padding))
if (
not isinstance(data, dict)
or data.get("k") != kind
or data.get("r") != str(resource_id)
or not isinstance(data.get("t"), str)
or not isinstance(data.get("i"), str)
):
raise ValueError("cursor")
created_at = parse_time(data["t"])
entity_id = UUID(data["i"])
except (KeyError, TypeError, ValueError, AttributeError, json.JSONDecodeError):
raise AppError(400, "invalid_request", "Некорректный cursor") from None
return created_at, entity_id
def slice_page(rows: list, limit: int, kind: str, resource_id: UUID) -> dict:
# SQL уже вернул не больше limit + 1 строк, отфильтрованных keyset-условием.
has_more = len(rows) > limit
page = rows[:limit]
next_cursor = None
if has_more and page:
last = page[-1]
next_cursor = encode_cursor(kind, resource_id, last.created_at, last.id)
return {"items": [row.to_dict() for row in page], "next_cursor": next_cursor}
+165
View File
@@ -0,0 +1,165 @@
import io
import multiprocessing
import time
from PIL import Image, ImageFile, ImageOps, UnidentifiedImageError
ImageFile.LOAD_TRUNCATED_IMAGES = False
THUMBNAIL_BOX = 256
CROP_SIDE = 128
OPTIMIZED_BOX = 1280
_VARIANT_ORDER = ("thumbnail", "crop", "optimized")
def _without_metadata(image: Image.Image) -> Image.Image:
bare = Image.new("RGB", image.size)
bare.paste(image)
return bare
def _to_rgb(image: Image.Image) -> Image.Image:
oriented = ImageOps.exif_transpose(image)
if oriented.mode == "RGB":
return _without_metadata(oriented)
if oriented.mode in {"RGBA", "LA"} or (oriented.mode == "P" and "transparency" in oriented.info):
rgba = oriented.convert("RGBA")
base = Image.new("RGB", rgba.size, (255, 255, 255))
base.paste(rgba, mask=rgba.getchannel("A"))
return base
return _without_metadata(oriented.convert("RGB"))
def _fit_within(image: Image.Image, box: int) -> Image.Image:
width, height = image.size
scale = min(box / width, box / height, 1.0)
new_width = max(1, int(width * scale))
new_height = max(1, int(height * scale))
if new_width == width and new_height == height:
return image
return image.resize((new_width, new_height), Image.Resampling.LANCZOS)
def _center_square(image: Image.Image, side: int) -> Image.Image:
width, height = image.size
source = min(width, height)
left = (width - source) // 2
top = (height - source) // 2
cropped = image.crop((left, top, left + source, top + source))
if cropped.size != (side, side):
cropped = cropped.resize((side, side), Image.Resampling.LANCZOS)
return cropped
def _jpeg_bytes(image: Image.Image, quality: int) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=quality, optimize=True)
return buffer.getvalue()
def _webp_bytes(image: Image.Image, quality: int, method: int) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format="WEBP", quality=quality, method=method)
return buffer.getvalue()
def _fail(code: str, permanent: bool) -> dict:
return {"ok": False, "code": code, "permanent": permanent}
def render_variants(
data: bytes,
max_pixels: int,
memory_budget: int,
jpeg_quality: int,
webp_quality: int,
webp_method: int,
) -> dict:
Image.MAX_IMAGE_PIXELS = max_pixels
try:
with Image.open(io.BytesIO(data)) as source:
width, height = source.size
if width < 1 or height < 1:
return _fail("invalid_image", True)
if width * height > max_pixels or width * height * 4 > memory_budget:
return _fail("payload_too_large", True)
source.load()
rgb = _to_rgb(source)
thumbnail = _fit_within(rgb, THUMBNAIL_BOX)
crop = _center_square(rgb, CROP_SIDE)
optimized = _fit_within(rgb, OPTIMIZED_BOX)
variants = {
"thumbnail": {
"content_type": "image/jpeg",
"width": thumbnail.size[0],
"height": thumbnail.size[1],
"data": _jpeg_bytes(thumbnail, jpeg_quality),
},
"crop": {
"content_type": "image/jpeg",
"width": crop.size[0],
"height": crop.size[1],
"data": _jpeg_bytes(crop, jpeg_quality),
},
"optimized": {
"content_type": "image/webp",
"width": optimized.size[0],
"height": optimized.size[1],
"data": _webp_bytes(optimized, webp_quality, webp_method),
},
}
return {"ok": True, "variants": variants}
except Image.DecompressionBombError:
return _fail("payload_too_large", True)
except MemoryError:
return _fail("payload_too_large", True)
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
return _fail("invalid_image", True)
def _spawn_render(queue, data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method, stall_seconds) -> None:
if stall_seconds > 0:
time.sleep(stall_seconds)
queue.put(render_variants(data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method))
def render_in_process(
data: bytes,
max_pixels: int,
memory_budget: int,
jpeg_quality: int,
webp_quality: int,
webp_method: int,
timeout_seconds: float,
stall_seconds: float = 0,
) -> dict:
context = multiprocessing.get_context("spawn")
queue = context.Queue(maxsize=1)
process = context.Process(
target=_spawn_render,
args=(queue, data, max_pixels, memory_budget, jpeg_quality, webp_quality, webp_method, stall_seconds),
)
process.start()
process.join(timeout_seconds)
try:
if process.is_alive():
process.terminate()
process.join(5)
if process.is_alive():
process.kill()
process.join(2)
return _fail("processing_failed", False)
if process.exitcode != 0:
return _fail("processing_failed", False)
try:
return queue.get_nowait()
except Exception:
return _fail("processing_failed", False)
finally:
queue.close()
queue.cancel_join_thread()
def variant_names() -> tuple[str, ...]:
return _VARIANT_ORDER
+89
View File
@@ -0,0 +1,89 @@
from dataclasses import dataclass
from datetime import datetime
from uuid import UUID
from app.timeutil import format_time
@dataclass(frozen=True)
class PublicUser:
id: UUID
username: str
display_name: str
created_at: datetime
def to_dict(self) -> dict:
return {
"id": self.id,
"username": self.username,
"display_name": self.display_name,
"created_at": format_time(self.created_at),
}
@dataclass(frozen=True)
class PublicChat:
id: UUID
title: str
member_ids: tuple[UUID, ...]
created_at: datetime
def to_dict(self) -> dict:
return {
"id": self.id,
"title": self.title,
"member_ids": list(self.member_ids),
"created_at": format_time(self.created_at),
}
@dataclass(frozen=True)
class PublicMessage:
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: datetime
attachment_ids: tuple[UUID, ...] = ()
def to_dict(self) -> dict:
return {
"id": self.id,
"chat_id": self.chat_id,
"sender_id": self.sender_id,
"text": self.text,
"created_at": format_time(self.created_at),
"attachment_ids": list(self.attachment_ids),
}
@dataclass(frozen=True)
class PublicAttachment:
id: UUID
chat_id: UUID
owner_id: UUID
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
error_code: str | None
created_at: datetime
updated_at: datetime
variants: tuple = ()
def to_dict(self) -> dict:
return {
"id": self.id,
"chat_id": self.chat_id,
"owner_id": self.owner_id,
"filename": self.filename,
"content_type": self.content_type,
"size_bytes": self.size_bytes,
"sha256": self.sha256,
"status": self.status,
"variants": list(self.variants),
"error_code": self.error_code,
"created_at": format_time(self.created_at),
"updated_at": format_time(self.updated_at),
}
+140
View File
@@ -0,0 +1,140 @@
import asyncio
import logging
import os
import signal
import sys
from pathlib import Path
from app.broker import WORK_KEY, connect, declare, publish
from app.config import load_settings
from app.db import build_engine, build_session_factory
from app.faults import read_faults
from app.jobs import mark_gap_and_list, mark_published, note_publish_attempt
from app.migrate import wait_for_database, wait_for_schema
from app.runtime import configure
logger = logging.getLogger("app.relay")
def configure_logging() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
force=True,
)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
logging.getLogger("aio_pika").setLevel(logging.WARNING)
logging.getLogger("aiormq").setLevel(logging.WARNING)
def flush_logs() -> None:
for handler in logging.getLogger().handlers:
handler.flush()
sys.stdout.flush()
async def beat(path: str, stop: asyncio.Event) -> None:
file = Path(path)
while not stop.is_set():
file.write_text("ok", encoding="utf-8")
try:
await asyncio.wait_for(stop.wait(), timeout=2)
except asyncio.TimeoutError:
continue
async def open_broker(url: str):
for attempt in range(40):
try:
return await connect(url)
except Exception as exc:
logger.warning("broker not ready type=%s attempt=%s", type(exc).__name__, attempt + 1)
await asyncio.sleep(0.5)
raise SystemExit("broker is not ready")
async def publish_loop(stop: asyncio.Event) -> None:
settings = require_settings_later()
while not stop.is_set():
connection = None
try:
connection = await open_broker(settings.broker_url)
channel = await connection.channel(publisher_confirms=True)
exchange, _queue = await declare(channel)
logger.info("relay publishing with confirms")
while not stop.is_set():
faults = read_faults(settings.faults_file)
batch, crash_id = await mark_gap_and_list(10, faults.relay_exit_before_publish)
if crash_id is not None:
logger.error(
"injected exit after outbox commit before broker publish outbox_id=%s",
crash_id,
)
flush_logs()
os._exit(42)
if not batch:
try:
await asyncio.wait_for(stop.wait(), timeout=0.4)
except asyncio.TimeoutError:
continue
break
for item in batch:
try:
await publish(exchange, item["payload"], WORK_KEY)
except Exception as exc:
logger.warning("publish failed type=%s job_id=%s", type(exc).__name__, item["job_id"])
await note_publish_attempt(item["id"])
continue
await mark_published(item["id"])
logger.info("outbox published job_id=%s", item["job_id"])
except Exception as exc:
if stop.is_set():
break
logger.warning("relay interrupted type=%s", type(exc).__name__)
await asyncio.sleep(1)
finally:
if connection is not None:
try:
await connection.close()
except Exception as exc:
logger.warning("broker close failed type=%s", type(exc).__name__)
def require_settings_later():
from app.runtime import require_settings
return require_settings()
async def serve() -> None:
settings = load_settings()
engine = build_engine(settings)
stop = asyncio.Event()
try:
await wait_for_database(engine)
await wait_for_schema(engine, settings.migrations_dir)
configure(build_session_factory(engine), None, settings, None)
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, stop.set)
except NotImplementedError:
pass
heart = asyncio.create_task(beat("/tmp/relay-heartbeat", stop))
try:
await publish_loop(stop)
finally:
stop.set()
heart.cancel()
finally:
await engine.dispose()
def main() -> None:
configure_logging()
asyncio.run(serve())
if __name__ == "__main__":
main()
+43
View File
@@ -0,0 +1,43 @@
import asyncio
import json
import logging
import sys
from uuid import UUID
from app.config import load_settings
from app.db import build_engine, build_session_factory
from app.jobs import replay_job
from app.migrate import wait_for_database
from app.runtime import configure
async def run(job_id: UUID) -> int:
settings = load_settings()
engine = build_engine(settings)
try:
await wait_for_database(engine)
configure(build_session_factory(engine), None, settings, None)
result = await replay_job(job_id)
finally:
await engine.dispose()
print(json.dumps(result, ensure_ascii=False), flush=True)
if result.get("outcome") == "not_found":
return 2
return 0
def main() -> None:
logging.basicConfig(level=logging.WARNING, stream=sys.stderr, force=True)
if len(sys.argv) != 2:
print("usage: python -m app.replay JOB_ID", file=sys.stderr)
raise SystemExit(2)
try:
job_id = UUID(sys.argv[1])
except ValueError:
print("job id must be a uuid", file=sys.stderr)
raise SystemExit(2)
raise SystemExit(asyncio.run(run(job_id)))
if __name__ == "__main__":
main()
+46
View File
@@ -0,0 +1,46 @@
from app.config import Settings
_factory = None
_redis = None
_store = None
_settings: Settings | None = None
def configure(factory, redis, settings: Settings, store=None) -> None:
global _factory, _redis, _store, _settings
_factory = factory
_redis = redis
_store = store
_settings = settings
def require_factory():
if _factory is None:
from app.errors import AppError
raise AppError(503, "unavailable", "Сервис временно недоступен")
return _factory
def require_redis():
if _redis is None:
from app.errors import AppError
raise AppError(503, "unavailable", "Сервис временно недоступен")
return _redis
def require_settings() -> Settings:
if _settings is None:
from app.errors import AppError
raise AppError(503, "unavailable", "Сервис временно недоступен")
return _settings
def require_store():
if _store is None:
from app.errors import AppError
raise AppError(503, "unavailable", "Сервис временно недоступен")
return _store
+102
View File
@@ -0,0 +1,102 @@
import asyncio
import logging
from datetime import datetime, timezone
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError
from app.config import Settings
from app.errors import AppError
logger = logging.getLogger("app.s3")
class ObjectStore:
def __init__(self, settings: Settings) -> None:
self.bucket = settings.s3_bucket
self._client = boto3.client(
"s3",
endpoint_url=settings.s3_endpoint,
aws_access_key_id=settings.s3_access_key_id,
aws_secret_access_key=settings.s3_secret_access_key,
region_name=settings.s3_region,
config=Config(
s3={"addressing_style": "path"},
connect_timeout=2,
read_timeout=30,
retries={"max_attempts": 2, "mode": "standard"},
),
)
def _call(self, fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except EndpointConnectionError:
logger.warning("s3 endpoint unavailable type=%s", "EndpointConnectionError")
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
except ClientError as exc:
code = str(exc.response.get("Error", {}).get("Code", ""))
if code in {"NoSuchKey", "404"}:
raise AppError(404, "not_found", "Объект не найден") from None
logger.warning("s3 client error type=%s code=%s", type(exc).__name__, code or "unknown")
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
except BotoCoreError:
logger.warning("s3 unavailable type=%s", "BotoCoreError")
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
async def ping(self) -> None:
await asyncio.to_thread(self._call, self._client.head_bucket, Bucket=self.bucket)
async def put(self, key: str, data: bytes, content_type: str) -> None:
await asyncio.to_thread(
self._call,
self._client.put_object,
Bucket=self.bucket,
Key=key,
Body=data,
ContentType=content_type,
ContentLength=len(data),
)
async def get(self, key: str) -> bytes:
def _read() -> bytes:
body = self._call(self._client.get_object, Bucket=self.bucket, Key=key)["Body"]
return body.read()
return await asyncio.to_thread(_read)
async def delete(self, key: str) -> None:
try:
await asyncio.to_thread(self._call, self._client.delete_object, Bucket=self.bucket, Key=key)
except AppError:
return
async def list_objects(self) -> list[tuple[str, datetime]]:
def _list() -> list[tuple[str, datetime]]:
items: list[tuple[str, datetime]] = []
for prefix in ("att/", "staging/"):
token = None
while True:
kwargs = {"Bucket": self.bucket, "Prefix": prefix}
if token:
kwargs["ContinuationToken"] = token
page = self._call(self._client.list_objects_v2, **kwargs)
for obj in page.get("Contents") or []:
key = str(obj["Key"])
modified = obj["LastModified"]
if modified.tzinfo is None:
modified = modified.replace(tzinfo=timezone.utc)
items.append((key, modified.astimezone(timezone.utc)))
if not page.get("IsTruncated"):
break
token = page.get("NextContinuationToken")
if not token:
break
return items
return await asyncio.to_thread(_list)
def build_store(settings: Settings) -> ObjectStore:
return ObjectStore(settings)
View File
+27
View File
@@ -0,0 +1,27 @@
from uuid import UUID
from pydantic import BaseModel
class VariantOut(BaseModel):
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
class AttachmentOut(BaseModel):
id: UUID
chat_id: UUID
owner_id: UUID
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
variants: list[VariantOut]
error_code: str | None
created_at: str
updated_at: str
+35
View File
@@ -0,0 +1,35 @@
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
member_ids: list[UUID] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def check_title(cls, value: str) -> str:
if value.strip() == "" or len(value) > 100:
raise ValueError("title")
return value
@field_validator("member_ids")
@classmethod
def unique_members(cls, value: list[UUID]) -> list[UUID]:
if len(set(value)) != len(value):
raise ValueError("duplicate members")
return value
class ChatOut(BaseModel):
id: UUID
title: str
member_ids: list[UUID]
created_at: str
class ChatPage(BaseModel):
items: list[ChatOut]
next_cursor: str | None
+43
View File
@@ -0,0 +1,43 @@
from uuid import UUID
from pydantic import BaseModel, ConfigDict, field_validator, model_validator
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str
attachment_ids: list[UUID] = []
@field_validator("text")
@classmethod
def check_text(cls, value: str) -> str:
if len(value) > 4000:
raise ValueError("text")
return value
@field_validator("attachment_ids")
@classmethod
def check_attachments(cls, value: list[UUID]) -> list[UUID]:
if len(value) > 10 or len(set(value)) != len(value):
raise ValueError("attachment_ids")
return value
@model_validator(mode="after")
def require_payload(self):
if self.text.strip() == "" and not self.attachment_ids:
raise ValueError("text")
return self
class MessageOut(BaseModel):
id: UUID
chat_id: UUID
sender_id: UUID
text: str
created_at: str
attachment_ids: list[UUID]
class MessagePage(BaseModel):
items: list[MessageOut]
next_cursor: str | None
+10
View File
@@ -0,0 +1,10 @@
from pydantic import BaseModel
from app.schemas.user import UserOut
class SessionOut(BaseModel):
token: str
token_type: str
expires_at: str
user: UserOut
+41
View File
@@ -0,0 +1,41 @@
import re
from uuid import UUID
from pydantic import BaseModel, ConfigDict, field_validator
class CreateUser(BaseModel):
model_config = ConfigDict(extra="forbid")
username: str
display_name: str
password: str
@field_validator("username")
@classmethod
def check_username(cls, value: str) -> str:
if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None:
raise ValueError("username")
return value
@field_validator("display_name")
@classmethod
def check_display_name(cls, value: str) -> str:
if value.strip() == "" or len(value) > 100:
raise ValueError("display_name")
return value
@field_validator("password")
@classmethod
def check_password(cls, value: str) -> str:
# Длина в code points. Пароль не обрезается и не нормализуется.
if not 12 <= len(value) <= 128:
raise ValueError("password")
return value
class UserOut(BaseModel):
id: UUID
username: str
display_name: str
created_at: str
+65
View File
@@ -0,0 +1,65 @@
import base64
import binascii
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
from argon2.low_level import Type
# Учебные параметры Argon2id: устойчивее SHA-256, но подъём на ноутбуке
_TIME_COST = 2
_MEMORY_COST = 32768
_PARALLELISM = 1
_hasher: PasswordHasher | None = None
_dummy_hash: str | None = None
def get_hasher() -> PasswordHasher:
global _hasher
if _hasher is None:
_hasher = PasswordHasher(
time_cost=_TIME_COST,
memory_cost=_MEMORY_COST,
parallelism=_PARALLELISM,
hash_len=32,
salt_len=16,
type=Type.ID,
)
return _hasher
def init_security() -> None:
global _dummy_hash
if _dummy_hash is None:
_dummy_hash = get_hasher().hash("messenger-dummy-password-not-used-for-login")
def hash_password(password: str) -> str:
return get_hasher().hash(password)
def verify_password(password: str, password_hash: str | None) -> bool:
init_security()
try:
get_hasher().verify(password_hash or _dummy_hash, password)
matched = True
except (VerifyMismatchError, InvalidHashError):
matched = False
return password_hash is not None and matched
def parse_basic(header: str) -> tuple[str, str] | None:
if not header:
return None
scheme, _, rest = header.partition(" ")
if scheme.lower() != "basic" or not rest.strip():
return None
try:
decoded = base64.b64decode(rest.strip(), validate=True)
text = decoded.decode("utf-8")
except (ValueError, UnicodeError, binascii.Error):
return None
username, separator, password = text.partition(":")
if separator != ":" or len(username) > 256 or len(password) > 1024:
return None
return username, password
+90
View File
@@ -0,0 +1,90 @@
import hashlib
import json
import logging
import secrets
from datetime import timedelta
from uuid import UUID
from redis.asyncio import Redis
from redis.exceptions import RedisError
from app.config import Settings
from app.errors import AppError
from app.runtime import require_redis, require_settings
from app.timeutil import format_time, parse_time, utcnow
logger = logging.getLogger("app.sessions")
def build_redis(settings: Settings) -> Redis:
return Redis.from_url(
settings.cache_url,
decode_responses=True,
socket_timeout=settings.redis_socket_timeout_seconds,
socket_connect_timeout=settings.redis_socket_timeout_seconds,
health_check_interval=30,
max_connections=settings.redis_max_connections,
)
def session_key(token: str) -> str:
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
return "sess:" + digest
async def _call(awaitable):
try:
return await awaitable
except RedisError:
logger.warning("redis unavailable type=%s", "RedisError")
raise AppError(503, "unavailable", "Сервис временно недоступен") from None
def _read_payload(raw: str) -> tuple[UUID, object] | None:
try:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("payload")
return UUID(str(data["user_id"])), parse_time(data["expires_at"])
except (ValueError, KeyError, TypeError):
return None
async def create_session(user_id: UUID) -> tuple[str, object]:
settings = require_settings()
token = secrets.token_urlsafe(32)
expires_at = utcnow() + timedelta(seconds=settings.session_ttl_seconds)
payload = json.dumps(
{"user_id": str(user_id), "expires_at": format_time(expires_at)},
separators=(",", ":"),
)
# PXAT — абсолютное время. Повтор AOF после рестарта не продлевает TTL.
await _call(require_redis().set(session_key(token), payload, pxat=int(expires_at.timestamp() * 1000)))
return token, expires_at
async def resolve_session(token: str) -> UUID | None:
key = session_key(token)
raw = await _call(require_redis().get(key))
if raw is None:
return None
parsed = _read_payload(raw)
if parsed is None:
await _call(require_redis().delete(key))
return None
user_id, expires_at = parsed
if expires_at <= utcnow():
await _call(require_redis().delete(key))
return None
return user_id
async def revoke_session(token: str) -> bool:
raw = await _call(require_redis().getdel(session_key(token)))
if raw is None:
return False
parsed = _read_payload(raw)
if parsed is None:
return False
_, expires_at = parsed
return expires_at > utcnow()
+1
View File
@@ -0,0 +1 @@
"""Состояние лабораторной 2 хранится в PostgreSQL и Redis, не в памяти процесса."""
+5
View File
@@ -0,0 +1,5 @@
"""Память процесса больше не хранит пользователей, чаты и сообщения.
Источник истины для этих данных — PostgreSQL.
Источник истины для сессий — Redis с AOF и абсолютным PXAT.
"""
+20
View File
@@ -0,0 +1,20 @@
from datetime import datetime, timezone
def utcnow() -> datetime:
return datetime.now(timezone.utc)
def format_time(value: datetime) -> str:
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def parse_time(value: str) -> datetime:
if not isinstance(value, str) or not value.endswith("Z"):
raise ValueError("time")
parsed = datetime.fromisoformat(value[:-1] + "+00:00")
if parsed.tzinfo is None:
raise ValueError("time")
return parsed.astimezone(timezone.utc)
+273
View File
@@ -0,0 +1,273 @@
import asyncio
import hashlib
import json
import logging
import os
import signal
import socket
import sys
from pathlib import Path
from uuid import UUID
from app.broker import DLQ_KEY, connect, declare, publish
from app.config import load_settings
from app.db import build_engine, build_session_factory
from app.errors import AppError
from app.faults import read_faults
from app.jobs import acquire_job, fail_or_retry, finalize_job, mark_objects_written, sweep_expired_leases
from app.migrate import wait_for_database, wait_for_schema
from app.pipeline import render_in_process, variant_names
from app.runtime import configure, require_settings, require_store
from app.s3 import build_store
logger = logging.getLogger("app.worker")
class Publisher:
exchange = None
def configure_logging() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
force=True,
)
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
logging.getLogger("aio_pika").setLevel(logging.WARNING)
logging.getLogger("aiormq").setLevel(logging.WARNING)
def flush_logs() -> None:
for handler in logging.getLogger().handlers:
handler.flush()
sys.stdout.flush()
def parse_job_id(body: bytes) -> UUID | None:
try:
payload = json.loads(body.decode("utf-8"))
except (UnicodeError, ValueError):
return None
if not isinstance(payload, dict) or payload.get("type") != "attachment.process.v1":
return None
try:
return UUID(str(payload.get("job_id")))
except (TypeError, ValueError):
return None
async def emit_terminal(result: str) -> None:
if not result.startswith("failed:"):
return
payload = result[len("failed:") :]
exchange = Publisher.exchange
if exchange is None:
logger.warning("dlq skipped because the broker exchange is not ready")
return
try:
await publish(exchange, payload, DLQ_KEY)
logger.info("terminal failure copied to dlq")
except Exception as exc:
logger.warning("dlq publish failed type=%s", type(exc).__name__)
async def handle(message, owner: str) -> None:
job_id = parse_job_id(message.body)
if job_id is None:
logger.warning("discarded job message type=invalid")
return
acquired = await acquire_job(job_id, owner, bool(getattr(message, "redelivered", False)))
if acquired.action != "acquired" or acquired.job_id is None or acquired.attachment_id is None:
return
settings = require_settings()
faults = read_faults(settings.faults_file)
if faults.inject_transient and acquired.objects_written_at is None:
logger.warning("injected transient failure job_id=%s attempt=%s", acquired.job_id, acquired.attempt)
await emit_terminal(await fail_or_retry(acquired.job_id, "processing_failed", False))
return
store = require_store()
try:
data = await store.get(acquired.staging_key)
except AppError as exc:
permanent = exc.status == 404
await emit_terminal(await fail_or_retry(acquired.job_id, "processing_failed", permanent))
return
digest = hashlib.sha256(data).hexdigest()
if digest != acquired.sha256 or len(data) != acquired.size_bytes:
await emit_terminal(await fail_or_retry(acquired.job_id, "processing_failed", True))
return
timeout = faults.timeout_seconds or settings.job_timeout_seconds
rendered = await asyncio.to_thread(
render_in_process,
data,
settings.max_image_pixels,
settings.worker_image_memory_bytes,
settings.jpeg_quality,
settings.webp_quality,
settings.webp_method,
timeout,
faults.stall_seconds,
)
if not rendered.get("ok"):
await emit_terminal(
await fail_or_retry(
acquired.job_id,
str(rendered.get("code") or "processing_failed"),
bool(rendered.get("permanent")),
)
)
return
await store.put(acquired.object_key, data, acquired.content_type)
stored = []
for name in variant_names():
item = rendered["variants"][name]
blob = item["data"]
key = "att/%s/%s" % (acquired.attachment_id, name)
await store.put(key, blob, item["content_type"])
stored.append(
{
"name": name,
"content_type": item["content_type"],
"size_bytes": len(blob),
"width": item["width"],
"height": item["height"],
"sha256": hashlib.sha256(blob).hexdigest(),
"object_key": key,
}
)
await mark_objects_written(acquired.job_id)
if faults.crash_after_s3 and acquired.objects_written_at is None:
logger.error("injected crash after object write before ack job_id=%s", acquired.job_id)
flush_logs()
os._exit(86)
outcome = await finalize_job(acquired.job_id, stored)
if outcome == "incomplete":
await emit_terminal(await fail_or_retry(acquired.job_id, "processing_failed", False))
return
try:
await store.delete(acquired.staging_key)
except AppError:
logger.warning("staging delete failed job_id=%s", acquired.job_id)
logger.info("job ready job_id=%s attachment_id=%s", acquired.job_id, acquired.attachment_id)
async def beat(path: str, stop: asyncio.Event) -> None:
file = Path(path)
while not stop.is_set():
file.write_text("ok", encoding="utf-8")
try:
await asyncio.wait_for(stop.wait(), timeout=2)
except asyncio.TimeoutError:
continue
async def sweep_loop(stop: asyncio.Event) -> None:
while not stop.is_set():
try:
await sweep_expired_leases()
except Exception as exc:
logger.warning("lease sweep failed type=%s", type(exc).__name__)
try:
await asyncio.wait_for(stop.wait(), timeout=2)
except asyncio.TimeoutError:
continue
async def open_broker(url: str):
for attempt in range(40):
try:
return await connect(url)
except Exception as exc:
logger.warning("broker not ready type=%s attempt=%s", type(exc).__name__, attempt + 1)
await asyncio.sleep(0.5)
raise SystemExit("broker is not ready")
async def consume(stop: asyncio.Event) -> None:
settings = require_settings()
owner = "%s:%s" % (socket.gethostname(), os.getpid())
semaphore = asyncio.Semaphore(settings.worker_concurrency)
async def on_message(message) -> None:
async with semaphore:
try:
await handle(message, owner)
await message.ack()
except Exception as exc:
logger.warning("worker message failed type=%s", type(exc).__name__)
try:
await message.nack(requeue=False)
except Exception as nack_error:
logger.warning("nack failed type=%s", type(nack_error).__name__)
while not stop.is_set():
connection = None
try:
connection = await open_broker(settings.broker_url)
channel = await connection.channel()
await channel.set_qos(prefetch_count=settings.worker_concurrency)
publisher = await connection.channel(publisher_confirms=True)
exchange, _queue = await declare(publisher)
_exchange, queue = await declare(channel)
Publisher.exchange = exchange
await queue.consume(on_message)
logger.info("worker consuming prefetch=%s", settings.worker_concurrency)
await stop.wait()
except Exception as exc:
if stop.is_set():
break
logger.warning("worker consume interrupted type=%s", type(exc).__name__)
await asyncio.sleep(1)
finally:
if connection is not None:
try:
await connection.close()
except Exception as exc:
logger.warning("broker close failed type=%s", type(exc).__name__)
async def serve() -> None:
settings = load_settings()
engine = build_engine(settings)
store = build_store(settings)
stop = asyncio.Event()
try:
await wait_for_database(engine)
await wait_for_schema(engine, settings.migrations_dir)
for _attempt in range(40):
try:
await store.ping()
break
except Exception:
logger.warning("s3 not ready")
await asyncio.sleep(0.5)
else:
raise SystemExit("s3 is not ready")
configure(build_session_factory(engine), None, settings, store)
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, stop.set)
except NotImplementedError:
pass
heart = asyncio.create_task(beat("/tmp/worker-heartbeat", stop))
sweeper = asyncio.create_task(sweep_loop(stop))
try:
await consume(stop)
finally:
stop.set()
heart.cancel()
sweeper.cancel()
finally:
await engine.dispose()
def main() -> None:
configure_logging()
asyncio.run(serve())
if __name__ == "__main__":
main()