This commit is contained in:
Матвей
2026-11-07 13:15:01 +03:00
parent 20afc2c790
commit eafb825657
93 changed files with 7549 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
+141
View File
@@ -0,0 +1,141 @@
import asyncio
from hashlib import sha256
import os
from tempfile import TemporaryFile
import unicodedata
from uuid import UUID, uuid4
import warnings
from fastapi import APIRouter, Depends, Query, Request, Response
from PIL import Image, UnidentifiedImageError
from starlette.concurrency import run_in_threadpool
from starlette.requests import ClientDisconnect
from .errors import ApiError
from .models import Attachment
from .routes import get_current_user, get_store
from .storage.postgres import PostgresStore
router = APIRouter()
Image.MAX_IMAGE_PIXELS = 40000000
warnings.filterwarnings("error", category=Image.DecompressionBombWarning)
def inspect_image(file, content_type, max_pixels):
try:
file.seek(0)
with Image.open(file, formats=("PNG", "JPEG")) as image:
if image.width * image.height > max_pixels:
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format]
if actual != content_type or getattr(image, "n_frames", 1) != 1:
raise ApiError(415, "unsupported_media_type", "Нужен обычный PNG или JPEG")
image.verify()
# verify checks PNG CRC; load also catches truncated pixel streams/JPEGs.
file.seek(0)
with Image.open(file, formats=("PNG", "JPEG")) as image:
image.load()
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as error:
raise ApiError(413, "payload_too_large", "Слишком много пикселей") from error
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as error:
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from error
file.seek(0)
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=202)
async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
await store.get_chat_for_member(chat_id, user["id"])
if (not 1 <= len(filename) <= 255 or not filename.strip() or
any(c in "/\\" or unicodedata.category(c) in {"Cc", "Cs"} for c in filename)):
raise ApiError(400, "invalid_request", "Некорректное имя файла")
content_type = request.headers.get("content-type", "").lower()
if content_type not in {"image/png", "image/jpeg"}:
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
s3 = request.app.state.s3
limit = s3.settings.max_bytes
if "content-length" in request.headers:
try:
length = int(request.headers["content-length"])
if length < 0:
raise ValueError()
except ValueError:
raise ApiError(400, "invalid_request", "Некорректная длина") from None
if length > limit:
raise ApiError(413, "payload_too_large", "Файл больше лимита")
try:
timeout = int(os.environ.get("UPLOAD_TIMEOUT_SECONDS", "30"))
if not 1 <= timeout <= 120:
raise ApiError(503, "unavailable", "Некорректный лимит времени загрузки")
async with asyncio.timeout(timeout):
async with request.app.state.upload_slot:
# Temporary scratch space only; deleted on every exit, never used for downloads.
with TemporaryFile() as file:
size = 0
digest = sha256()
async for chunk in request.stream():
size += len(chunk)
if size > limit:
raise ApiError(413, "payload_too_large", "Файл больше лимита")
digest.update(chunk)
await run_in_threadpool(file.write, chunk)
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
attachment_id, job_id = uuid4(), uuid4()
key = f"staging/{attachment_id}/original"
async with store.attachment_transaction() as connection:
try:
max_pending = int(os.environ.get("MAX_PENDING_JOBS", "100"))
except ValueError as error:
raise ApiError(503, "unavailable", "Некорректный лимит очереди") from error
if max_pending < 1:
raise ApiError(503, "unavailable", "Некорректный лимит очереди")
await store.ensure_attachment_queue_capacity(connection, max_pending)
await s3.put(key, file, size, content_type)
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
attachment = await store.create_attachment(
attachment_id, chat_id, user["id"], filename, content_type,
size, digest.hexdigest(), key, job_id, connection=connection,
)
# Fault-injection for level-4 proof: durable outbox must recover this commit.
if os.environ.get("OUTBOX_FAULT_AFTER_COMMIT") == "1":
os._exit(70)
attachment["variants"] = []
return attachment
except ClientDisconnect:
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
except TimeoutError:
raise ApiError(503, "unavailable", "Время загрузки истекло") from None
@router.get("/api/v1/attachments/{attachment_id}", response_model=Attachment)
async def metadata(attachment_id: UUID, user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store)):
return await store.attachment_for_member(attachment_id, user["id"])
@router.get("/api/v1/attachments/{attachment_id}/content")
async def download(attachment_id: UUID, request: Request,
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
attachment = await store.attachment_for_member(attachment_id, user["id"])
if attachment["status"] != "ready":
raise ApiError(409, "conflict", "Вложение ещё не готово")
if variant == "original":
data = await request.app.state.s3.download(attachment)
content_type = attachment["content_type"]
else:
matching = [item for item in attachment["variants"] if item["name"] == variant]
if not matching:
raise ApiError(404, "not_found", "Вариант не найден")
item = matching[0]
object_key = await store.pool.fetchval(
'SELECT object_key FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$2 AND name=$3',
attachment_id, attachment['pipeline_version'], variant,
)
data = await request.app.state.s3.download_key(
object_key, item["size_bytes"], item["sha256"]
)
content_type = item["content_type"]
return Response(data, media_type=content_type,
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})
+51
View File
@@ -0,0 +1,51 @@
"""Idempotent private bucket bootstrap; executed with separate admin credentials."""
import time
from uuid import uuid4
from botocore.exceptions import BotoCoreError, ClientError
from .storage.s3 import S3Settings, S3Store
def main():
store = S3Store(S3Settings.load())
try:
for attempt in range(60):
try:
store.client.list_buckets()
break
except (BotoCoreError, ClientError):
if attempt == 59:
raise RuntimeError("S3 startup timed out") from None
time.sleep(1)
bucket = store.settings.bucket
try:
store.client.head_bucket(Bucket=bucket)
except ClientError as error:
if str(error.response["Error"]["Code"]) not in {"404", "NoSuchBucket", "NotFound"}:
raise
store.client.create_bucket(Bucket=bucket)
# No anonymous identity; revoke any previously configured public grants/policy.
store.client.put_bucket_acl(Bucket=bucket, ACL="private")
try:
store.client.delete_bucket_policy(Bucket=bucket)
except ClientError as error:
if error.response["Error"]["Code"] != "NoSuchBucketPolicy":
raise
# The master health endpoint can become available before a volume accepts
# writes after a restart. Verify the actual data path before APIs start.
probe_key = f"_bootstrap/write-probe-{uuid4()}"
for attempt in range(30):
try:
store.client.put_object(Bucket=bucket, Key=probe_key, Body=b"ready")
store.client.delete_object(Bucket=bucket, Key=probe_key)
break
except (BotoCoreError, ClientError):
if attempt == 29:
raise RuntimeError("S3 write path startup timed out") from None
time.sleep(1)
print("PASS: private S3 bucket ready")
finally:
store.client.close()
if __name__ == "__main__":
main()
+90
View File
@@ -0,0 +1,90 @@
"""Small durable RabbitMQ adapter; broker messages contain no attachment bytes."""
import json
import os
from pathlib import Path
import pika
from starlette.concurrency import run_in_threadpool
from .errors import ApiError
from . import telemetry as tel
QUEUE = "attachment.process.v1"
DLQ = "attachment.process.v1.dlq"
def broker_url() -> str:
path = os.environ.get("BROKER_URL_FILE")
value = Path(path).read_text(encoding="utf-8").strip() if path else os.environ.get("BROKER_URL", "")
if not value.startswith(("amqp://", "amqps://")):
raise ValueError("BROKER_URL или BROKER_URL_FILE должен содержать AMQP URL")
return value
def _connection() -> pika.BlockingConnection:
connection = pika.BlockingConnection(pika.URLParameters(broker_url()))
channel = connection.channel()
channel.queue_declare(queue=QUEUE, durable=True)
channel.queue_declare(queue=DLQ, durable=True)
return connection
def _publish(payload: dict, headers: dict | None = None) -> None:
connection = _connection()
try:
channel = connection.channel()
channel.confirm_delivery()
channel.basic_publish(
exchange="", routing_key=QUEUE,
body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json", headers=headers),
mandatory=True,
)
finally:
connection.close()
async def publish(payload: dict, context=None) -> None:
try:
with tel.tracer.start_as_current_span("attachment.publish", context=tel.extract(context), kind=tel.SpanKind.PRODUCER, record_exception=False, set_status_on_exception=False) as span:
span.set_attribute("messaging.retry.attempt", int(payload.get("attempt", 1)))
try:
await run_in_threadpool(_publish, payload, tel.carrier())
except Exception:
span.set_status(tel.Status(tel.StatusCode.ERROR))
raise
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
raise ApiError(503, "unavailable", "Брокер недоступен") from error
async def publish_dlq(payload: dict) -> None:
payload = {**payload, "failure": payload.get('failure', 'retry_exhausted')}
try:
await run_in_threadpool(_publish_to, DLQ, payload)
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
raise RuntimeError("DLQ is unavailable") from error
def _publish_to(queue: str, payload: dict) -> None:
connection = _connection()
try:
channel = connection.channel()
channel.confirm_delivery()
channel.basic_publish(
exchange="", routing_key=queue, body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json"),
mandatory=True,
)
finally:
connection.close()
async def ready() -> None:
connection = None
try:
connection = await run_in_threadpool(_connection)
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
raise ApiError(503, "unavailable", "Брокер недоступен") from error
finally:
if connection is not None:
await run_in_threadpool(connection.close)
+125
View File
@@ -0,0 +1,125 @@
from dataclasses import dataclass
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
_CONFIGURATION_KEYS = {
"APP_HOST",
"APP_PORT",
"APP_ENV",
"DATABASE_URL",
"DATABASE_URL_FILE",
"SESSION_TTL_SECONDS",
"IDEMPOTENCY_TTL_SECONDS",
"INSTANCE_ID",
"CURSOR_SECRET",
"CURSOR_SECRET_FILE",
"S3_ENDPOINT", "S3_REGION", "S3_BUCKET",
"S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE",
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE",
"BROKER_URL", "BROKER_URL_FILE",
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
"WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS", "STAGING_RETENTION_SECONDS",
"WORKER_PREFETCH", "MAX_PENDING_JOBS", "RENDER_MEMORY_MB",
}
@dataclass(frozen=True, slots=True)
class Settings:
"""Проверенная конфигурация запуска HTTP-сервера."""
host: str
port: int
environment: str
database_url: str
session_ttl_seconds: int
idempotency_ttl_seconds: int
instance_id: str
cursor_secret: bytes
def load_settings(env_file: Path = ROOT / ".env") -> Settings:
"""Читает разрешённые ключи .env, не заменяя явно переданное окружение."""
if env_file.is_file():
for raw_line in env_file.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
key, separator, value = line.partition("=")
if not separator or key not in _CONFIGURATION_KEYS:
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
value = value[1:-1]
os.environ.setdefault(key, value)
def value(name: str, default: str = "") -> str:
return os.environ.get(name, default).strip()
def number(name: str, default: int) -> int:
try:
result = int(value(name, str(default)))
except ValueError as error:
raise ValueError(f"{name} должен быть целым числом") from error
if result < 1:
raise ValueError(f"{name} должен быть положительным")
return result
def url(name: str, file_name: str, prefixes: tuple[str, ...]) -> str:
result = value(name)
path = value(file_name)
if path:
try:
result = Path(path).read_text(encoding="utf-8").strip()
except OSError as error:
raise ValueError(f"{file_name} недоступен") from error
if result and not result.startswith(prefixes):
raise ValueError(f"{name} содержит неверный URL")
return result
def secret(name: str, file_name: str) -> bytes:
result = value(name)
path = value(file_name)
if path:
try:
result = Path(path).read_text(encoding="utf-8").strip()
except OSError as error:
raise ValueError(f"{file_name} недоступен") from error
encoded = result.encode("utf-8")
if len(encoded) < 32:
raise ValueError(f"{name} должен содержать не менее 32 байт")
return encoded
host = value("APP_HOST", "0.0.0.0")
environment = value("APP_ENV", "lab")
if not host:
raise ValueError("APP_HOST не может быть пустым")
if not environment:
raise ValueError("APP_ENV не может быть пустым")
port = number("APP_PORT", 8080)
if port > 65535:
raise ValueError("APP_PORT должен находиться в диапазоне 1..65535")
database_url = url(
"DATABASE_URL", "DATABASE_URL_FILE", ("postgresql://", "postgres://")
)
if not database_url:
raise ValueError("Нужен PostgreSQL DATABASE_URL или DATABASE_URL_FILE")
instance_id = value("INSTANCE_ID") or os.uname().nodename
if not instance_id:
raise ValueError("INSTANCE_ID не может быть пустым")
idempotency_ttl_seconds = number("IDEMPOTENCY_TTL_SECONDS", 86400)
if idempotency_ttl_seconds < 86400:
raise ValueError("IDEMPOTENCY_TTL_SECONDS должен быть не менее 86400")
return Settings(
host=host,
port=port,
environment=environment,
database_url=database_url,
session_ttl_seconds=number("SESSION_TTL_SECONDS", 3600),
idempotency_ttl_seconds=idempotency_ttl_seconds,
instance_id=instance_id,
cursor_secret=secret("CURSOR_SECRET", "CURSOR_SECRET_FILE"),
)
+81
View File
@@ -0,0 +1,81 @@
import base64
from datetime import UTC, datetime
import hashlib
import hmac
import json
from uuid import UUID
_secret: bytes | None = None
class CursorError(ValueError):
"""Недопустимый, повреждённый или применённый не к тому ресурсу курсор."""
def configure_secret(secret: bytes) -> None:
"""Устанавливает общий для всех реплик ключ подписи курсоров."""
global _secret
if len(secret) < 32:
raise ValueError("cursor secret must contain at least 32 bytes")
_secret = secret
def signing_secret() -> bytes:
if _secret is None:
raise RuntimeError("cursor secret has not been configured")
return _secret
def _encode_bytes(value: bytes) -> str:
return base64.urlsafe_b64encode(value).decode().rstrip("=")
def _decode_bytes(value: str) -> bytes:
try:
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
except (ValueError, UnicodeEncodeError) as error:
raise CursorError from error
def encode_cursor(scope: str, created_at: datetime, item_id: str) -> str:
payload = json.dumps(
{
"scope": scope,
"created_at": created_at.astimezone(UTC)
.isoformat()
.replace("+00:00", "Z"),
"id": item_id,
},
separators=(",", ":"),
sort_keys=True,
).encode()
signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
return _encode_bytes(payload) + "." + _encode_bytes(signature)
def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, str]:
try:
encoded_payload, encoded_signature = cursor.split(".")
payload = _decode_bytes(encoded_payload)
signature = _decode_bytes(encoded_signature)
except ValueError as error:
raise CursorError from error
expected_signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
if not hmac.compare_digest(signature, expected_signature):
raise CursorError
try:
data = json.loads(payload)
if set(data) != {"scope", "created_at", "id"}:
raise CursorError
if data["scope"] != expected_scope:
raise CursorError
item_id = str(UUID(data["id"]))
created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
if created_at.tzinfo is None:
raise CursorError
return created_at.astimezone(UTC), item_id
except (TypeError, ValueError, KeyError) as error:
raise CursorError from error
+12
View File
@@ -0,0 +1,12 @@
"""Ошибки, которые преобразуются в контрактные HTTP-ответы."""
class ApiError(Exception):
def __init__(
self, status_code: int, code: str, message: str, headers: dict[str, str] | None = None
) -> None:
self.status_code = status_code
self.code = code
self.message = message
self.headers = headers or {}
+189
View File
@@ -0,0 +1,189 @@
import asyncio
import logging
import os
import sys
import time
from contextlib import asynccontextmanager
from uuid import uuid4
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
import uvicorn
from starlette.responses import JSONResponse, Response
from starlette.exceptions import HTTPException
from .errors import ApiError
from .cursor import configure_secret
from .models import ErrorDetails, ErrorResponse
from .config import load_settings
from .routes import router
from .attachments import router as attachment_router
from .storage.s3 import S3Settings, S3Store
from .storage.postgres import PostgresStore
from . import telemetry as tel
tel.setup("messenger-api")
def logger(name: str) -> logging.Logger:
result = logging.getLogger(name)
if result.handlers:
return result
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
result.addHandler(handler)
result.setLevel(logging.INFO)
result.propagate = False
return result
access_logger = logger("messenger.access")
@asynccontextmanager
async def lifespan(application: FastAPI):
settings = load_settings()
configure_secret(settings.cursor_secret)
store = PostgresStore(settings.database_url)
await store.connect()
application.state.store = store
application.state.settings = settings
application.state.s3 = S3Store(S3Settings.load())
concurrency = int(os.environ.get("UPLOAD_CONCURRENCY", "1"))
if not 1 <= concurrency <= 8:
raise ValueError("UPLOAD_CONCURRENCY must be 1..8")
application.state.upload_slot = asyncio.Semaphore(concurrency)
application.state.accepting_requests = True
async def sample_pool():
while True:
pool = store.pool
tel.state.update(pool_used=pool.get_size()-pool.get_idle_size(), pool_capacity=pool.get_max_size(), pool_waiting=len(pool._queue._getters))
await asyncio.sleep(1)
sampler = asyncio.create_task(sample_pool())
try:
yield
finally:
sampler.cancel()
try:
await sampler
except asyncio.CancelledError:
pass
application.state.accepting_requests = False
application.state.s3.client.close()
await store.close()
app = FastAPI(
title="MTUSI Messenger",
version="1.6.0",
redoc_url=None,
lifespan=lifespan,
)
@app.middleware("http")
async def add_request_id(request: Request, call_next) -> Response:
"""Добавляет ID запроса и пишет безопасную строку access-лога."""
request.state.request_id = str(uuid4())
started_at = time.monotonic()
status_code = 500
with tel.tracer.start_as_current_span("HTTP request", context=tel.extract(dict(request.headers)), kind=tel.SpanKind.SERVER, record_exception=False, set_status_on_exception=False) as span:
try:
response = await call_next(request)
status_code = response.status_code
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = request.app.state.settings.instance_id
return response
finally:
route = getattr(request.scope.get("route"), "path", "unmatched")
method = tel.http_method(request.method)
attrs = {"method": method, "route": route, "status_class": f"{status_code // 100}xx"}
span.update_name(f"{method} {route}")
span.set_attributes({"http.request.method": method, "http.route": route, "http.response.status_code": status_code})
if status_code >= 500:
span.set_status(tel.Status(tel.StatusCode.ERROR))
tel.http_requests.add(1, attrs)
tel.http_duration.record(time.monotonic() - started_at, attrs)
tel.log.info("http.request", extra={"request_id": request.state.request_id, "method": method, "route": route, "status": status_code})
def error_response(
request: Request, status_code: int, code: str, message: str, headers: dict[str, str] | None = None
) -> JSONResponse:
request_id = request.state.request_id
body = ErrorResponse(
error=ErrorDetails(code=code, message=message, request_id=request_id)
)
# Неожиданная ошибка обрабатывается за пределами HTTP-middleware.
# Поэтому её ответ тоже должен сам получить заголовок из контракта.
return JSONResponse(
status_code=status_code,
content=body.model_dump(),
headers={
"X-Request-Id": request_id,
"X-Instance-Id": request.app.state.settings.instance_id,
**(headers or {}),
},
)
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, error: ApiError) -> JSONResponse:
"""Преобразует контролируемую ошибку API в стандартный JSON-ответ."""
return error_response(request, error.status_code, error.code, error.message, error.headers)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(
request: Request, error: RequestValidationError
) -> JSONResponse:
"""Преобразует ошибки JSON и Pydantic в обязательный ответ 400."""
return error_response(request, 400, "invalid_request", "Некорректный запрос")
@app.exception_handler(HTTPException)
async def handle_http_error(request: Request, error: HTTPException) -> JSONResponse:
"""Включает ошибки декодирования тела, возникающие до Pydantic."""
codes = {
400: "invalid_request",
401: "unauthorized",
403: "forbidden",
404: "not_found",
405: "method_not_allowed",
503: "unavailable",
}
code = codes.get(error.status_code, "internal_error")
return error_response(
request, error.status_code, code,
"Некорректный запрос" if error.status_code < 500 else "Ошибка сервера",
error.headers,
)
@app.exception_handler(Exception)
async def handle_unexpected_error(request: Request, error: Exception) -> JSONResponse:
"""Не раскрывает внутренние детали при непредвиденной ошибке приложения."""
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
app.include_router(router)
app.include_router(attachment_router)
def main() -> None:
settings = load_settings()
uvicorn.run(
app,
host=settings.host,
port=settings.port,
access_log=False,
timeout_graceful_shutdown=8,
)
if __name__ == "__main__":
main()
+18
View File
@@ -0,0 +1,18 @@
import asyncio
from .config import load_settings
from .storage.postgres import PostgresStore
async def run() -> None:
settings = load_settings()
store = PostgresStore(settings.database_url)
await store.connect()
try:
await store.migrate()
finally:
await store.close()
if __name__ == "__main__":
asyncio.run(run())
+151
View File
@@ -0,0 +1,151 @@
from datetime import datetime
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
class CreateUserRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
username: str = Field(min_length=3, max_length=32, pattern=r"^[a-z0-9_]{3,32}$")
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("display_name")
@classmethod
def display_name_must_not_be_whitespace(cls, value: str) -> str:
"""Не допускает обязательное имя, состоящее только из пробелов."""
if not value.strip():
raise ValueError("display_name не может состоять только из пробелов")
return value
class CreateChatRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: list[UUID] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def title_must_not_be_whitespace(cls, value: str) -> str:
"""Не допускает обязательное название, состоящее только из пробелов."""
if not value.strip():
raise ValueError("title не может состоять только из пробелов")
return value
class ChatPageResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
items: list["Chat"]
next_cursor: str | None
class CreateMessageRequest(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
text: str = Field(max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids")
@classmethod
def valid_ids(cls, values: list[str]) -> list[str]:
normalized = [str(UUID(value)) for value in values]
if len(normalized) != len(set(normalized)):
raise ValueError("Повторяющиеся attachment_ids")
return normalized
@model_validator(mode="after")
def has_content(self):
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Сообщение без содержимого")
return self
class MessagePageResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
items: list["Message"]
next_cursor: str | None
class ErrorDetails(BaseModel):
model_config = ConfigDict(extra="forbid")
code: str
message: str
request_id: str
class ErrorResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
error: ErrorDetails
class User(BaseModel):
model_config = ConfigDict(extra="forbid")
id: UUID
username: str
display_name: str
created_at: datetime
class Chat(BaseModel):
model_config = ConfigDict(extra="forbid")
id: UUID
title: str
member_ids: list[UUID]
created_at: datetime
class Message(BaseModel):
model_config = ConfigDict(extra="forbid")
id: UUID
chat_id: UUID
sender_id: UUID
text: str
attachment_ids: list[UUID] = Field(default_factory=list)
created_at: datetime
class Session(BaseModel):
model_config = ConfigDict(extra="forbid")
token: str = Field(min_length=32)
token_type: str = "Bearer"
expires_at: datetime
user: User
class Attachment(BaseModel):
model_config = ConfigDict(extra="ignore")
id: UUID
chat_id: UUID
owner_id: UUID
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
variants: list["Variant"] = Field(default_factory=list)
error_code: str | None = None
created_at: datetime
updated_at: datetime
class Variant(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str
content_type: str
size_bytes: int
width: int
height: int
sha256: str
+46
View File
@@ -0,0 +1,46 @@
"""Transactional-outbox dispatcher; safe to run as one or more replicas."""
import asyncio
import logging
import os
import json
import time
from .broker import publish
from .config import load_settings
from .storage.postgres import PostgresStore
from . import telemetry as tel
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s outbox %(message)s")
async def run() -> None:
tel.setup("messenger-outbox")
settings = load_settings()
store = PostgresStore(settings.database_url)
await store.connect()
interval = max(0.1, float(os.environ.get("OUTBOX_DISPATCH_INTERVAL_SECONDS", "1")))
try:
while True:
try:
await store.schedule_due_jobs(int(os.environ.get('JOB_MAX_ATTEMPTS', '5')))
for event in await store.due_outbox_events():
context = event['trace_context']
await publish(event["payload"], json.loads(context) if isinstance(context, str) else context)
await store.mark_outbox_published(event["id"])
except Exception:
logging.exception("outbox dispatch failed; durable event remains pending")
try:
queue = await store.pool.fetchrow("SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM now()-min(created_at)), 0)::float8 AS age FROM attachment_jobs WHERE status='queued'")
slo = await store.sample_ready_slo()
tel.state.update(queue_depth=queue['depth'], queue_age=queue['age'],
slo_ready_eligible=slo['eligible'], slo_ready_bad=slo['bad'],
slo_unknown=slo['unknown'], queue_sample_time=time.time())
except Exception:
logging.warning("queue telemetry unavailable")
await asyncio.sleep(interval)
finally:
await store.close()
if __name__ == "__main__":
asyncio.run(run())
+37
View File
@@ -0,0 +1,37 @@
"""Operator-only metrics for one synthetic chat; never exposes credentials."""
import asyncio
import json
import os
from pathlib import Path
import sys
from uuid import UUID
from .config import load_settings
from .storage.postgres import PostgresStore
async def main(chat):
store = PostgresStore(load_settings().database_url)
await store.connect()
try:
rows = await store.pool.fetch('SELECT a.id, a.status, extract(epoch from (j.first_started_at-j.created_at))::float8 AS queue_wait_seconds FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.chat_id=$1', chat)
jobs = [dict(row, id=str(row['id'])) for row in rows]
pending = await store.pool.fetchval("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')")
finally:
await store.close()
rss = 0
for path in Path('/proc').glob('[0-9]*/status'):
try:
if int(path.parent.name) == os.getpid():
continue
for line in path.read_text().splitlines():
if line.startswith('VmRSS:'):
rss += int(line.split()[1]) * 1024
except (OSError, ValueError):
pass
print(json.dumps({'jobs': jobs, 'pending': pending, 'rss_bytes': rss,
'concurrency': int(os.environ['WORKER_CONCURRENCY']),
'prefetch': int(os.environ['WORKER_PREFETCH'])}))
if __name__ == '__main__':
asyncio.run(main(UUID(sys.argv[1])))
+104
View File
@@ -0,0 +1,104 @@
"""Safely reconcile attachment metadata and original S3 objects.
The command is dry-run by default. It only deletes unreferenced objects older
than a configured grace period; missing objects are reported and never cause a
metadata delete. That keeps a delayed PostgreSQL commit and active attachment
records safe from a maintenance run.
"""
import argparse
import asyncio
from datetime import datetime, timedelta, timezone
import json
import os
from time import perf_counter
from .config import load_settings
from .storage.postgres import PostgresStore
from .storage.s3 import S3Settings, S3Store
async def run(args) -> dict:
settings = load_settings()
db = PostgresStore(settings.database_url)
s3 = S3Store(S3Settings.load())
try:
await db.connect()
async with db.attachment_transaction(maintenance=True):
return await scan(args, db, s3)
finally:
s3.client.close()
await db.close()
async def scan(args, db, s3) -> dict:
# Age is measured at scan start, not after a potentially slow inventory.
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
started = perf_counter()
objects, s3_pages = {}, 0
for prefix in ('staging/', 'originals/', 'variants/'):
entries, pages = await s3.list_with_pages(prefix)
objects.update(entries)
s3_pages += pages
listed_at = perf_counter()
metadata = await db.attachment_keys()
metadata_at = perf_counter()
orphan = sorted(key for key, modified in objects.items()
if key not in metadata and modified <= cutoff)
fresh = sorted(key for key, modified in objects.items()
if key not in metadata and modified > cutoff)
missing = sorted({str(attachment_id): key for key, attachment_id in metadata.items()
if key not in objects}.items())
deleted = []
selected = set(args.object_key) if args.object_key else None
if args.apply:
for key in orphan:
if selected is not None and key not in selected:
continue
await s3.delete(key)
deleted.append(key)
finished = perf_counter()
return {
"mode": "apply" if args.apply else "dry-run",
"grace_seconds": args.grace_seconds,
"s3_objects": len(objects),
"metadata_rows": len(metadata),
"orphan_candidates": orphan,
"fresh_unreferenced": fresh,
"missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing],
"deleted": deleted,
"selected_keys": sorted(selected) if selected is not None else None,
"scan_metrics": {
"s3_list_pages": s3_pages,
"s3_list_seconds": round(listed_at - started, 6),
"postgres_metadata_seconds": round(metadata_at - listed_at, 6),
"total_seconds": round(finished - started, 6),
},
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
parser.add_argument("--grace-seconds", type=int, default=int(os.environ.get('STAGING_RETENTION_SECONDS', '86400')))
parser.add_argument('--loop', action='store_true')
parser.add_argument("--object-key", action="append", default=[],
help="restrict apply to these exact keys; repeatable, inventory stays complete")
args = parser.parse_args()
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
parser.error("--grace-seconds must be 0..604800")
if any(not key.startswith(('originals/', 'staging/', 'variants/')) for key in args.object_key):
parser.error('unsupported object prefix')
if args.loop:
import time
while True:
try:
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
except Exception:
print('cleanup deferred: dependency unavailable', flush=True)
time.sleep(60)
else:
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
if __name__ == "__main__":
main()
+27
View File
@@ -0,0 +1,27 @@
"""Isolated image renderer. Parent enforces wall time and kills this process."""
import os
import pickle
import sys
def main():
if sys.platform == 'linux':
import resource
limit = int(os.environ.get('RENDER_MEMORY_MB', '768')) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
from .worker import variants
from PIL import UnidentifiedImageError, Image
try:
data = sys.stdin.buffer.read(10485761)
if len(data) > 10485760:
raise ValueError('bytes limit')
result = variants(data, int(os.environ.get('MAX_IMAGE_PIXELS', '40000000')))
pickle.dump(result, sys.stdout.buffer)
except MemoryError:
sys.exit(21)
except (ValueError, OSError, SyntaxError, UnidentifiedImageError, Image.DecompressionBombError):
sys.exit(20)
if __name__ == '__main__':
main()
+24
View File
@@ -0,0 +1,24 @@
"""Operator-only safe replay for a failed attachment job."""
import argparse
import asyncio
from uuid import UUID
from .config import load_settings
from .storage.postgres import PostgresStore
async def run(attachment_id: UUID) -> None:
store = PostgresStore(load_settings().database_url)
await store.connect()
try:
if not await store.replay_failed_attachment(attachment_id):
raise SystemExit("attachment is not in failed state")
finally:
await store.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("attachment_id", type=UUID)
args = parser.parse_args()
asyncio.run(run(args.attachment_id))
+185
View File
@@ -0,0 +1,185 @@
import base64
import re
from datetime import datetime
from uuid import UUID
from fastapi import APIRouter, Depends, Header, Query, Request, Response
from .cursor import CursorError, decode_cursor, encode_cursor
from .errors import ApiError
from .storage.postgres import PostgresStore
from .broker import ready as broker_ready
from .models import (
Chat,
ChatPageResponse,
CreateChatRequest,
CreateMessageRequest,
CreateUserRequest,
Message,
MessagePageResponse,
Session,
User,
)
router = APIRouter()
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def get_store(request: Request) -> PostgresStore:
return request.app.state.store
async def get_current_user(
authorization: str | None = Header(default=None),
store: PostgresStore = Depends(get_store),
) -> dict:
if authorization is None or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия", BEARER_CHALLENGE)
token = authorization[7:]
if not token or not token.isascii() or token.strip() != token:
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия", BEARER_CHALLENGE)
user = await store.user_for_token(token)
if user is None:
raise ApiError(401, "unauthorized", "Недействительная сессия", BEARER_CHALLENGE)
return user
def parse_basic(authorization: str | None) -> tuple[str, str]:
if authorization is None or not authorization.startswith("Basic "):
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE)
try:
decoded = base64.b64decode(authorization[6:], validate=True)
username_bytes, password_bytes = decoded.split(b":", 1)
username = username_bytes.decode("ascii")
password = password_bytes.decode("utf-8")
except (UnicodeDecodeError, ValueError) as error:
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE) from error
if not username or not (12 <= len(password) <= 128):
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE)
return username, password
def cursor_position(cursor: str | None, scope: str) -> tuple[datetime, UUID] | None:
if cursor is None:
return None
try:
created_at, item_id = decode_cursor(cursor, scope)
return created_at, UUID(item_id)
except (CursorError, ValueError) as error:
raise ApiError(400, "invalid_request", "Некорректный cursor") from error
def next_page_cursor(rows: list[dict], limit: int, scope: str) -> str | None:
if len(rows) <= limit:
return None
last = rows[limit - 1]
return encode_cursor(scope, last["created_at"], str(last["id"]))
@router.get("/health/live")
async def liveness() -> dict[str, str]:
return {"status": "ok"}
@router.get("/health/ready")
async def readiness(request: Request, store: PostgresStore = Depends(get_store)) -> dict[str, str]:
if not request.app.state.accepting_requests:
raise ApiError(503, "unavailable", "API завершает работу")
await store.ready()
await request.app.state.s3.ready()
await broker_ready()
return {"status": "ok"}
@router.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(
payload: CreateUserRequest, store: PostgresStore = Depends(get_store)
) -> dict:
return await store.create_user(payload.username, payload.display_name, payload.password)
@router.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
async def create_session(
request: Request,
authorization: str | None = Header(default=None),
store: PostgresStore = Depends(get_store),
) -> dict:
if await request.body():
raise ApiError(400, "invalid_request", "Тело запроса не требуется")
username, password = parse_basic(authorization)
user = await store.authenticate(username, password)
if user is None:
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE)
return await store.create_session(user, request.app.state.settings.session_ttl_seconds)
@router.delete("/api/v1/auth/sessions/current", status_code=204)
async def revoke_session(
authorization: str | None = Header(default=None),
store: PostgresStore = Depends(get_store),
user: dict = Depends(get_current_user),
) -> Response:
del user
await store.revoke_session(authorization[7:])
return Response(status_code=204)
@router.get("/api/v1/users/me", response_model=User)
async def current_user(user: dict = Depends(get_current_user)) -> dict:
return user
@router.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(
payload: CreateChatRequest,
user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store),
) -> dict:
return await store.create_chat(user["id"], payload.title, payload.member_ids)
@router.get("/api/v1/chats", response_model=ChatPageResponse)
async def list_chats(
user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store),
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None, min_length=1),
) -> ChatPageResponse:
scope = "chats:" + str(user["id"])
rows = await store.list_chats_for_member(user["id"], cursor_position(cursor, scope), limit)
page = rows[:limit]
return ChatPageResponse(items=page, next_cursor=next_page_cursor(rows, limit, scope))
@router.get("/api/v1/chats/{chat_id}", response_model=Chat)
async def get_chat(
chat_id: UUID,
user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store),
) -> dict:
return await store.get_chat_for_member(chat_id, user["id"])
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(
chat_id: UUID,
payload: CreateMessageRequest,
request: Request,
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store),
) -> dict:
if idempotency_key is None or IDEMPOTENCY_KEY.fullmatch(idempotency_key) is None:
raise ApiError(400, "invalid_request", "Некорректный Idempotency-Key")
return await store.create_message_idempotent(
chat_id,
user["id"],
payload.text,
idempotency_key,
request.app.state.settings.idempotency_ttl_seconds,
[UUID(value) for value in payload.attachment_ids],
)
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePageResponse)
async def list_messages(
chat_id: UUID,
user: dict = Depends(get_current_user),
store: PostgresStore = Depends(get_store),
limit: int = Query(default=50, ge=1, le=100),
cursor: str | None = Query(default=None, min_length=1),
) -> MessagePageResponse:
scope = "messages:" + str(chat_id)
after = cursor_position(cursor, scope)
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
page = rows[:limit]
return MessagePageResponse(items=page, next_cursor=next_page_cursor(rows, limit, scope))
+2
View File
@@ -0,0 +1,2 @@
"""Слой in-memory хранения для приложения первой лабораторной работы."""
"""Persistent storage adapters."""
+594
View File
@@ -0,0 +1,594 @@
from datetime import datetime, timedelta, timezone
from contextlib import asynccontextmanager
from hashlib import sha256
import json
from pathlib import Path
from secrets import token_urlsafe
from uuid import UUID, uuid4
import asyncpg
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from ..errors import ApiError
from .. import telemetry as tel
ROOT = Path(__file__).resolve().parents[2]
MIGRATIONS = ROOT / "migrations"
PASSWORD_HASHER = PasswordHasher()
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, TimeoutError)
class PostgresStore:
def __init__(self, database_url: str) -> None:
self._database_url = database_url
self._pool: asyncpg.Pool | None = None
async def connect(self) -> None:
try:
self._pool = await asyncpg.create_pool(
self._database_url, min_size=1, max_size=10, command_timeout=5
)
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def close(self) -> None:
if self._pool is not None:
await self._pool.close()
@property
def pool(self) -> asyncpg.Pool:
if self._pool is None:
raise RuntimeError("PostgreSQL pool has not been initialized")
return self._pool
async def migrate(self) -> None:
async with self.pool.acquire() as connection:
await connection.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
)
for migration in sorted(MIGRATIONS.glob("*.sql")):
applied = await connection.fetchval(
"SELECT 1 FROM schema_migrations WHERE version = $1", migration.name
)
if applied:
continue
async with connection.transaction():
await connection.execute(migration.read_text(encoding="utf-8"))
await connection.execute(
"INSERT INTO schema_migrations (version) VALUES ($1)", migration.name
)
@staticmethod
def _user(row: asyncpg.Record) -> dict:
return {
"id": row["id"],
"username": row["username"],
"display_name": row["display_name"],
"created_at": row["created_at"],
}
@staticmethod
def _chat(row: asyncpg.Record) -> dict:
return {
"id": row["id"],
"title": row["title"],
"member_ids": row["member_ids"],
"created_at": row["created_at"],
}
@staticmethod
def _message(row: asyncpg.Record) -> dict:
return {
"id": row["id"],
"chat_id": row["chat_id"],
"sender_id": row["sender_id"],
"text": row["text"],
"attachment_ids": row["attachment_ids"],
"created_at": row["created_at"],
}
async def ready(self) -> None:
try:
await self.pool.fetchval("SELECT 1")
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_user(self, username: str, display_name: str, password: str) -> dict:
try:
row = await self.pool.fetchrow(
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) RETURNING id, username, display_name, created_at",
uuid4(),
username,
display_name,
PASSWORD_HASHER.hash(password),
)
except asyncpg.UniqueViolationError as error:
raise ApiError(409, "conflict", "Username уже занят") from error
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return self._user(row)
async def authenticate(self, username: str, password: str) -> dict | None:
try:
row = await self.pool.fetchrow(
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
username,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
return None
try:
valid = PASSWORD_HASHER.verify(row["password_hash"], password)
except (InvalidHashError, VerificationError):
valid = False
return self._user(row) if valid else None
async def create_session(self, user: dict, ttl_seconds: int) -> dict:
token = token_urlsafe(32)
token_hash = sha256(token.encode("ascii")).hexdigest()
try:
row = await self.pool.fetchrow(
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, now() + $3 * interval '1 second') RETURNING expires_at",
token_hash,
user["id"],
ttl_seconds,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user}
async def user_for_token(self, token: str) -> dict | None:
if not token.isascii():
return None
token_hash = sha256(token.encode("ascii")).hexdigest()
try:
row = await self.pool.fetchrow(
"SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()",
token_hash,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return self._user(row) if row else None
async def revoke_session(self, token: str) -> None:
try:
await self.pool.execute(
"DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest()
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_chat(self, creator_id: UUID, title: str, member_ids: list[UUID]) -> dict:
if len(member_ids) != len(set(member_ids)) or creator_id not in member_ids:
raise ApiError(400, "invalid_request", "Некорректный список участников")
try:
async with self.pool.acquire() as connection, connection.transaction():
existing = await connection.fetchval(
"SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_ids
)
if existing != len(member_ids):
raise ApiError(400, "invalid_request", "Один или несколько участников не существуют")
row = await connection.fetchrow(
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
uuid4(),
title,
)
await connection.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
[(row["id"], member_id) for member_id in member_ids],
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return {
"id": row["id"],
"title": row["title"],
"member_ids": member_ids,
"created_at": row["created_at"],
}
async def get_chat_for_member(self, chat_id: UUID, user_id: UUID) -> dict:
try:
row = await self.pool.fetchrow(
"SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $2 JOIN chat_members cm_all ON cm_all.chat_id = c.id WHERE c.id = $1 GROUP BY c.id",
chat_id,
user_id,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
raise ApiError(404, "not_found", "Чат не найден")
return self._chat(row)
async def list_chats_for_member(
self, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
) -> list[dict]:
query = "SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1 JOIN chat_members cm_all ON cm_all.chat_id = c.id"
args: list = [user_id]
if after is not None:
query += " WHERE (c.created_at, c.id) > ($2, $3)"
args.extend(after)
query += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $" + str(len(args) + 1)
args.append(limit + 1)
try:
rows = await self.pool.fetch(query, *args)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return [self._chat(row) for row in rows]
async def create_message_idempotent(
self, chat_id: UUID, sender_id: UUID, text: str, idempotency_key: str, ttl_seconds: int, attachment_ids: list[UUID] | None = None
) -> dict:
"""Создаёт сообщение и фиксирует результат retry в одной транзакции."""
path = f"/api/v1/chats/{chat_id}/messages"
attachment_ids = attachment_ids or []
# Preserve hashes of text-only requests already accepted by lab3.
canonical = {"text": text}
if attachment_ids:
canonical["attachment_ids"] = [str(value) for value in attachment_ids]
request_hash = sha256(
json.dumps(canonical, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
).hexdigest()
try:
async with self.pool.acquire() as connection, connection.transaction():
member = await connection.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_id, sender_id
)
if member is None:
raise ApiError(404, "not_found", "Чат не найден")
await connection.execute(
"DELETE FROM idempotency_records WHERE created_at <= now() - $1 * interval '1 second'", ttl_seconds
)
if attachment_ids:
count = await connection.fetchval(
"SELECT count(*) FROM attachments WHERE chat_id = $1 AND id = ANY($2::uuid[])",
chat_id, attachment_ids,
)
if count != len(attachment_ids):
raise ApiError(404, "not_found", "Вложение не найдено")
failed = await connection.fetchval(
"SELECT 1 FROM attachments WHERE id=ANY($1::uuid[]) AND status='failed' LIMIT 1", attachment_ids
)
if failed:
raise ApiError(409, 'conflict', 'Вложение завершилось ошибкой')
claimed = await connection.fetchrow(
"INSERT INTO idempotency_records (user_id, method, path, idempotency_key, request_hash) "
"VALUES ($1, 'POST', $2, $3, $4) ON CONFLICT DO NOTHING RETURNING message_id",
sender_id, path, idempotency_key, request_hash,
)
if claimed is None:
recorded = await connection.fetchrow(
"SELECT request_hash, message_id FROM idempotency_records "
"WHERE user_id = $1 AND method = 'POST' AND path = $2 AND idempotency_key = $3 FOR UPDATE",
sender_id, path, idempotency_key,
)
if recorded is None:
raise ApiError(503, "unavailable", "Не удалось получить результат идемпотентного запроса")
if recorded["request_hash"] != request_hash:
raise ApiError(409, "conflict", "Idempotency-Key использован с другим телом")
if recorded["message_id"] is None:
raise ApiError(503, "unavailable", "Не удалось получить результат идемпотентного запроса")
row = await connection.fetchrow(
"SELECT id, chat_id, sender_id, text, attachment_ids, created_at FROM messages WHERE id = $1", recorded["message_id"]
)
if row is None:
raise ApiError(503, "unavailable", "Не удалось получить сохранённое сообщение")
return self._message(row)
row = await connection.fetchrow(
"INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids) VALUES ($1, $2, $3, $4, $5) "
"RETURNING id, chat_id, sender_id, text, attachment_ids, created_at",
uuid4(), chat_id, sender_id, text, attachment_ids,
)
await connection.execute(
"UPDATE idempotency_records SET message_id = $1 WHERE user_id = $2 AND method = 'POST' "
"AND path = $3 AND idempotency_key = $4",
row["id"], sender_id, path, idempotency_key,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return self._message(row)
async def list_messages_for_member(
self, chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
) -> list[dict]:
await self.get_chat_for_member(chat_id, user_id)
query = "SELECT id, chat_id, sender_id, text, attachment_ids, created_at FROM messages WHERE chat_id = $1"
args: list = [chat_id]
if after is not None:
query += " AND (created_at, id) > ($2, $3)"
args.extend(after)
query += " ORDER BY created_at, id LIMIT $" + str(len(args) + 1)
args.append(limit + 1)
try:
rows = await self.pool.fetch(query, *args)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return [self._message(row) for row in rows]
@asynccontextmanager
async def attachment_transaction(self, *, maintenance=False):
"""Shared writer / exclusive reconciler lock across all API replicas.
Writers hold the transaction from before PUT through metadata COMMIT.
Maintenance holds the exclusive lock through inventory and deletion.
All attachment writers must participate in this protocol.
"""
try:
with tel.tracer.start_as_current_span("postgres.attachment_transaction", kind=tel.SpanKind.CLIENT, record_exception=False, set_status_on_exception=False) as span:
try:
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute("SET LOCAL lock_timeout = '5s'")
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
await connection.execute(f"SELECT {lock}(41004, 1)")
yield connection
except Exception:
span.set_status(tel.Status(tel.StatusCode.ERROR))
raise
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
content_type, size_bytes, digest, staging_key, job_id, *, connection=None) -> dict:
try:
row = await (connection or self.pool).fetchrow(
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key) "
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, staging_key,
)
await (connection or self.pool).execute(
"INSERT INTO attachment_jobs (job_id, attachment_id, trace_context) VALUES ($1, $2, $3::jsonb)", job_id, attachment_id, json.dumps(tel.carrier())
)
await (connection or self.pool).execute(
"INSERT INTO attachment_slo (attachment_id) VALUES ($1)", attachment_id
)
payload = {
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
"attachment_id": str(attachment_id), "pipeline_version": 1, "attempt": 1,
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
}
await (connection or self.pool).execute(
"INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)",
uuid4(), job_id, json.dumps(payload, separators=(",", ":")),
)
await (connection or self.pool).execute(
"UPDATE attachment_jobs SET next_attempt_at = 'infinity' WHERE job_id = $1", job_id
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
return dict(row)
async def ensure_attachment_queue_capacity(self, connection: asyncpg.Connection, maximum: int) -> None:
"""Globally serialize admission so replicas cannot over-accept queued work."""
try:
await connection.execute("SELECT pg_advisory_xact_lock(41005, 1)")
pending = await connection.fetchval(
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued', 'processing')"
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if pending >= maximum:
raise ApiError(429, "rate_limited", "Очередь обработки заполнена")
async def attachment_for_member(self, attachment_id: UUID, user_id: UUID) -> dict:
try:
row = await self.pool.fetchrow(
"SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id "
"WHERE a.id = $1 AND m.user_id = $2", attachment_id, user_id,
)
except DB_ERRORS as error:
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
if row is None:
raise ApiError(404, "not_found", "Вложение не найдено")
return await self._attachment_with_variants(row)
async def _attachment_with_variants(self, row: asyncpg.Record | dict) -> dict:
result = dict(row)
variants = await self.pool.fetch(
"SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants "
"WHERE attachment_id = $1 AND pipeline_version = $2 ORDER BY name",
result["id"], result["pipeline_version"],
)
result["variants"] = [dict(item) for item in variants]
return result
async def claim_attachment_job(self, attachment_id: UUID, lease_seconds: int) -> dict | None:
try:
async with self.pool.acquire() as connection, connection.transaction():
row = await connection.fetchrow(
"SELECT a.*, j.job_id, j.attempt, j.lease_until, "
"(j.next_attempt_at <> 'infinity'::timestamptz AND j.next_attempt_at > now()) AS retry_waiting "
"FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
"WHERE a.id = $1 FOR UPDATE", attachment_id
)
# Only the dispatcher recovers an expired lease and increments
# its attempt. Redelivery must not renew it or bypass backoff.
if row is None or row["status"] != "queued" or row["retry_waiting"]:
return None
await connection.execute(
"UPDATE attachments SET status = 'processing', processing_started_at = now(), updated_at = now() WHERE id = $1",
attachment_id,
)
await connection.execute(
"UPDATE attachment_jobs SET status = 'processing', first_started_at=COALESCE(first_started_at, now()), lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
attachment_id, lease_seconds,
)
result = dict(row)
result['claim_time'] = await connection.fetchval('SELECT processing_started_at FROM attachments WHERE id=$1', attachment_id)
return result
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict], claim_time) -> bool:
try:
async with self.pool.acquire() as connection, connection.transaction():
valid = await connection.fetchval(
"SELECT 1 FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 AND j.lease_until > now() FOR UPDATE", attachment_id, claim_time
)
if not valid:
return False
for variant in variants:
await connection.execute(
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
"VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8) "
"ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256",
attachment_id, variant["name"], variant["object_key"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"],
)
await connection.execute(
"UPDATE attachments SET status = 'ready', original_key = $2, error_code = NULL, updated_at = now() WHERE id = $1",
attachment_id, original_key,
)
await connection.execute("UPDATE attachment_jobs SET status = 'ready', lease_until = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id)
await connection.execute(
"UPDATE attachment_slo SET ready_xid=pg_current_xact_id()::xid "
"WHERE attachment_id=$1 AND ready_xid IS NULL", attachment_id
)
return True
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def ready_seconds(self, attachment_id: UUID):
# Both ends are DB commit timestamps, not transaction start or a worker's clock.
return await self.pool.fetchval("""
SELECT EXTRACT(EPOCH FROM (
COALESCE(ready_at, pg_xact_commit_timestamp(ready_xid)) -
COALESCE(accepted_at, pg_xact_commit_timestamp(accepted_xid))))::float8
FROM attachment_slo WHERE attachment_id=$1
""", attachment_id)
async def sample_ready_slo(self):
# Materialize promptly: PostgreSQL does not retain commit timestamps forever.
async with self.pool.acquire() as connection, connection.transaction():
await connection.execute("""
UPDATE attachment_slo SET
accepted_at=COALESCE(accepted_at, pg_xact_commit_timestamp(accepted_xid)),
ready_at=COALESCE(ready_at, pg_xact_commit_timestamp(ready_xid))
WHERE accepted_at IS NULL OR (ready_xid IS NOT NULL AND ready_at IS NULL)
""")
await connection.execute("""
UPDATE attachment_slo SET bad=(ready_at IS NULL OR ready_at>accepted_at+interval '30 seconds')
WHERE bad IS NULL AND accepted_at<=now()-interval '30 seconds'
AND (ready_xid IS NULL OR ready_at IS NOT NULL)
""")
return await connection.fetchrow("""
SELECT count(bad) AS eligible, count(*) FILTER (WHERE bad) AS bad,
count(*) FILTER (WHERE accepted_at IS NULL OR
(ready_xid IS NOT NULL AND ready_at IS NULL)) AS unknown
FROM attachment_slo
""")
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float, claim_time, permanent_code=None) -> bool:
"""Return true only when a bounded at-least-once retry was recorded."""
try:
async with self.pool.acquire() as connection, connection.transaction():
job = await connection.fetchrow(
"SELECT j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 FOR UPDATE", attachment_id, claim_time
)
if job is None:
return False
if permanent_code is None and job["attempt"] < max_attempts:
await connection.execute(
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', lease_until = NULL, next_attempt_at = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
attachment_id, delay_seconds,
)
await connection.execute(
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
)
return True
code = permanent_code or 'retry_exhausted'
await connection.execute("UPDATE attachments SET status='failed', error_code=$2, updated_at=now() WHERE id=$1", attachment_id, code)
await connection.execute("UPDATE attachment_jobs SET status='failed', last_error=$2, lease_until=NULL, updated_at=now() WHERE attachment_id=$1", attachment_id, code)
return False
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def due_outbox_events(self, limit: int = 20) -> list[dict]:
try:
return [{**dict(row), 'payload': json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload']} for row in await self.pool.fetch(
"SELECT o.id, o.payload, j.trace_context FROM attachment_outbox o JOIN attachment_jobs j ON j.job_id=o.job_id WHERE o.published_at IS NULL ORDER BY o.created_at LIMIT $1", limit
)]
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def mark_outbox_published(self, event_id: UUID) -> None:
await self.pool.execute("UPDATE attachment_outbox SET published_at = now(), attempts = attempts + 1 WHERE id = $1", event_id)
async def schedule_due_jobs(self, max_attempts: int = 5) -> None:
"""Outbox dispatcher also restores expired leases and scheduled retries."""
try:
async with self.pool.acquire() as connection, connection.transaction():
rows = await connection.fetch(
"SELECT job_id, attachment_id, pipeline_version, attempt, status FROM attachment_jobs "
"WHERE (status = 'queued' AND (next_attempt_at <= now() OR "
"(next_attempt_at = 'infinity'::timestamptz AND updated_at < now() - interval '60 seconds'))) "
"OR (status = 'processing' AND lease_until < now()) "
"FOR UPDATE SKIP LOCKED"
)
for row in rows:
row = dict(row)
if row["status"] == "processing":
if row['attempt'] >= max_attempts:
await connection.execute("UPDATE attachment_jobs SET status='failed', lease_until=NULL, last_error='retry_exhausted', updated_at=now() WHERE job_id=$1", row['job_id'])
await connection.execute("UPDATE attachments SET status='failed', error_code='retry_exhausted', updated_at=now() WHERE id=$1", row['attachment_id'])
continue
row['attempt'] += 1
await connection.execute(
"UPDATE attachment_jobs SET status = 'queued', attempt=$2, lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"], row['attempt']
)
await connection.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", row["attachment_id"])
payload = {"schema_version": 1, "job_id": str(row["job_id"]), "type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"], "attempt": row["attempt"], "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
await connection.execute("INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)", uuid4(), row["job_id"], json.dumps(payload, separators=(",", ":")))
# Refresh the watchdog on publication intent, not on claim.
# Unclaimed jobs are republished after 60s. At-least-once
# duplicates are safe, and a published-but-lost delivery
# can no longer strand durable accepted work forever.
await connection.execute("UPDATE attachment_jobs SET next_attempt_at = 'infinity', updated_at=now() WHERE job_id = $1", row["job_id"])
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def replay_failed_attachment(self, attachment_id: UUID) -> bool:
"""Explicit operator-only replay; never requeues an already successful job."""
try:
async with self.pool.acquire() as connection, connection.transaction():
job = await connection.fetchrow(
"SELECT job_id, status FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
)
if job is None or job["status"] != "failed":
return False
await connection.execute(
"UPDATE attachment_jobs SET status = 'queued', attempt = 1, next_attempt_at = now(), lease_until = NULL, replayed_at = now(), last_error = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id
)
await connection.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1", attachment_id)
return True
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
async def attachment_keys(self) -> dict[str, UUID]:
"""Inventory used only by the maintenance reconciler."""
try:
rows = await self.pool.fetch("SELECT staging_key AS object_key, id FROM attachments WHERE status <> 'ready' UNION ALL SELECT original_key, id FROM attachments WHERE original_key IS NOT NULL UNION ALL SELECT object_key, attachment_id AS id FROM attachment_variants")
except DB_ERRORS as error:
raise RuntimeError("PostgreSQL is unavailable") from error
return {row["object_key"]: row["id"] for row in rows}
# Span names describe operations only; never export SQL, parameters, credentials or IDs.
def _trace_db(method):
from functools import wraps
@wraps(method)
async def wrapped(*args, **kwargs):
with tel.tracer.start_as_current_span('postgres.' + method.__name__, kind=tel.SpanKind.CLIENT,
record_exception=False, set_status_on_exception=False) as span:
try:
return await method(*args, **kwargs)
except Exception:
span.set_status(tel.Status(tel.StatusCode.ERROR))
raise
return wrapped
for _name in ('ready', 'create_user', 'authenticate', 'create_session', 'user_for_token', 'revoke_session',
'create_chat', 'get_chat_for_member', 'list_chats_for_member', 'create_message_idempotent',
'list_messages_for_member', 'create_attachment', 'attachment_for_member', 'claim_attachment_job',
'complete_attachment_job', 'retry_attachment_job'):
setattr(PostgresStore, _name, _trace_db(getattr(PostgresStore, _name)))
+123
View File
@@ -0,0 +1,123 @@
"""Bounded S3 operations; synchronous SDK calls run outside the event loop."""
from dataclasses import dataclass
from hashlib import sha256
import os
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from starlette.concurrency import run_in_threadpool
from ..errors import ApiError
from .. import telemetry as tel
@dataclass(frozen=True)
class S3Settings:
endpoint: str
region: str
bucket: str
access_key: str
secret_key: str
max_bytes: int
max_pixels: int
@classmethod
def load(cls):
def secret(name):
path = os.environ.get(name + "_FILE")
result = Path(path).read_text().strip() if path else os.environ.get(name, "")
if not result:
raise ValueError(f"Missing {name}")
return result
max_bytes = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
max_pixels = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
if not 1 <= max_bytes <= 10485760 or not 1 <= max_pixels <= 40000000:
raise ValueError("Image limits exceed contract")
return cls(os.environ.get("S3_ENDPOINT", "http://s3:8333"),
os.environ.get("S3_REGION", "us-east-1"),
os.environ.get("S3_BUCKET", "messenger-attachments"),
secret("S3_ACCESS_KEY_ID"), secret("S3_SECRET_ACCESS_KEY"),
max_bytes, max_pixels)
class S3Store:
def __init__(self, settings):
self.settings = settings
self.client = boto3.client(
"s3", endpoint_url=settings.endpoint, region_name=settings.region,
aws_access_key_id=settings.access_key, aws_secret_access_key=settings.secret_key,
config=Config(signature_version="s3v4", connect_timeout=2, read_timeout=5,
retries={"total_max_attempts": 1},
s3={"addressing_style": "path"},
request_checksum_calculation="when_required",
response_checksum_validation="when_required"),
)
async def call(self, method, **kwargs):
with tel.tracer.start_as_current_span("s3." + method, kind=tel.SpanKind.CLIENT, record_exception=False, set_status_on_exception=False) as span:
try:
return await run_in_threadpool(getattr(self.client, method), **kwargs)
except (BotoCoreError, ClientError, OSError) as error:
span.set_status(tel.Status(tel.StatusCode.ERROR))
raise ApiError(503, "unavailable", "S3 недоступно") from error
async def ready(self):
await self.call("head_bucket", Bucket=self.settings.bucket)
async def put(self, key, file, size, content_type):
file.seek(0)
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
Body=file, ContentLength=size, ContentType=content_type)
async def copy(self, source_key: str, destination_key: str, content_type: str) -> None:
await self.call(
"copy_object", Bucket=self.settings.bucket, Key=destination_key,
CopySource={"Bucket": self.settings.bucket, "Key": source_key},
ContentType=content_type, MetadataDirective="REPLACE",
)
async def list(self, prefix: str) -> dict[str, object]:
"""Return every object under a controlled prefix, handling S3 pagination."""
objects, _ = await self.list_with_pages(prefix)
return objects
async def list_with_pages(self, prefix: str) -> tuple[dict[str, object], int]:
"""Return inventory and number of S3 ListObjectsV2 pages consumed."""
result: dict[str, object] = {}
token = None
pages = 0
while True:
args = {"Bucket": self.settings.bucket, "Prefix": prefix}
if token:
args["ContinuationToken"] = token
page = await self.call("list_objects_v2", **args)
pages += 1
for item in page.get("Contents", []):
result[item["Key"]] = item["LastModified"]
if not page.get("IsTruncated"):
return result, pages
token = page["NextContinuationToken"]
async def delete(self, key: str) -> None:
await self.call("delete_object", Bucket=self.settings.bucket, Key=key)
async def download(self, attachment):
return await self.download_key(attachment["original_key"], attachment["size_bytes"], attachment["sha256"])
async def download_key(self, key: str, expected_size: int | None = None,
expected_sha256: str | None = None) -> bytes:
response = await self.call("get_object", Bucket=self.settings.bucket, Key=key)
body = response["Body"]
try:
data = await run_in_threadpool(body.read, self.settings.max_bytes + 1)
except (BotoCoreError, OSError) as error:
raise ApiError(503, "unavailable", "S3 недоступно") from error
finally:
body.close()
if ((expected_size is not None and len(data) != expected_size) or
(expected_sha256 is not None and sha256(data).hexdigest() != expected_sha256)):
raise ApiError(503, "unavailable", "Оригинал недоступен")
return data
+118
View File
@@ -0,0 +1,118 @@
"""Bounded OTLP telemetry; only explicitly selected, non-sensitive fields leave the process."""
import json
import logging
import os
import socket
import time
import resource
from datetime import datetime, timezone
from opentelemetry import metrics, trace
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("messenger")
meter = metrics.get_meter("messenger")
trace_context = TraceContextTextMapPropagator()
http_requests = meter.create_counter("messenger.http.requests", unit="{request}")
http_duration = meter.create_histogram("messenger.http.duration", unit="s")
jobs = meter.create_counter("messenger.jobs", unit="{job}")
job_duration = meter.create_histogram("messenger.job.duration", unit="s")
ready_duration = meter.create_histogram("messenger.job.ready.duration", unit="s")
busy = meter.create_up_down_counter("messenger.worker.busy", unit="{worker}")
capacity = meter.create_up_down_counter("messenger.worker.capacity", unit="{worker}")
state = {"queue_depth": 0, "queue_age": 0, "pool_used": 0, "pool_capacity": 0, "pool_waiting": 0,
"slo_ready_eligible": 0, "slo_ready_bad": 0, "slo_unknown": 0, "queue_sample_time": 0}
for name, unit in (("queue_sample_time", "s"), ("slo_unknown", "{job}"), ("queue_depth", "{job}"), ("queue_age", "s"), ("pool_used", "{connection}"), ("pool_capacity", "{connection}"), ("pool_waiting", "{request}")):
meter.create_observable_gauge("messenger." + name, callbacks=[lambda options, key=name: [metrics.Observation(state[key], {"queue": "attachment.process.v1"} if key.startswith("queue_") else {})]], unit=unit)
for name in ("slo_ready_eligible", "slo_ready_bad"):
meter.create_observable_counter("messenger." + name, callbacks=[lambda options, key=name: [metrics.Observation(state[key])]], unit="{job}")
def process_cpu(options):
usage = resource.getrusage(resource.RUSAGE_SELF)
return [metrics.Observation(usage.ru_utime + usage.ru_stime)]
def process_rss(options):
try:
with open('/proc/self/statm', encoding='ascii') as stream:
return [metrics.Observation(int(stream.read().split()[1]) * os.sysconf('SC_PAGE_SIZE'))]
except (OSError, ValueError, IndexError):
return []
meter.create_observable_counter("messenger.process.cpu", callbacks=[process_cpu], unit="s")
meter.create_observable_gauge("messenger.process.memory", callbacks=[process_rss], unit="By")
log = logging.getLogger("messenger.telemetry")
log.setLevel(logging.INFO)
log.propagate = False
LOG_FIELDS = ("request_id", "method", "route", "status", "outcome")
LOG_EVENTS = {"http.request", "job.processed", "telemetry.unavailable"}
STANDARD_LOG_FIELDS = frozenset(logging.makeLogRecord({}).__dict__)
def http_method(value):
return value if value in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "CONNECT", "TRACE"} else "_OTHER"
class SafeLogFilter(logging.Filter):
"""Sanitize the shared record BEFORE both stdout and OTLP handlers."""
def filter(self, record):
for key in list(record.__dict__):
if key not in STANDARD_LOG_FIELDS and key not in LOG_FIELDS:
del record.__dict__[key]
record.msg = record.msg if isinstance(record.msg, str) and record.msg in LOG_EVENTS else "telemetry.unavailable"
record.args = ()
record.exc_info = record.exc_text = record.stack_info = None
return True
log.addFilter(SafeLogFilter())
class JsonFormatter(logging.Formatter):
def format(self, record):
ctx = trace.get_current_span().get_span_context()
obj = {"timestamp": datetime.now(timezone.utc).isoformat(), "severity": record.levelname,
"service.name": os.environ.get("OTEL_SERVICE_NAME", "messenger"), "event": record.getMessage()}
if ctx.is_valid:
obj.update(trace_id=f"{ctx.trace_id:032x}", span_id=f"{ctx.span_id:016x}")
for field in LOG_FIELDS:
if hasattr(record, field): obj[field] = getattr(record, field)
return json.dumps(obj, ensure_ascii=False)
def setup(service):
if os.environ.get("OTEL_ENABLED", "0") != "1":
return
os.environ["OTEL_SERVICE_NAME"] = service
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
resource = Resource.create({"service.name": service, "service.version": "1.6.0", "service.instance.id": socket.gethostname(), "deployment.environment.name": "lab"})
provider = TracerProvider(resource=resource)
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(timeout=2), max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000))
trace.set_tracer_provider(provider)
buckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600]
views = [View(instrument_name=name, aggregation=ExplicitBucketHistogramAggregation(boundaries=buckets)) for name in ("messenger.http.duration", "messenger.job.duration", "messenger.job.ready.duration")]
metrics.set_meter_provider(MeterProvider(resource=resource, views=views, metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter(timeout=2), export_interval_millis=5000)]))
logs = LoggerProvider(resource=resource)
logs.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(timeout=2), max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000))
log.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logs))
stream = logging.StreamHandler()
stream.setFormatter(JsonFormatter())
log.addHandler(stream)
def carrier():
result = {}
trace_context.inject(result)
return result
def extract(value):
return trace_context.extract(value or {})
+265
View File
@@ -0,0 +1,265 @@
"""RabbitMQ consumer for the version-1 attachment pipeline."""
import asyncio
from hashlib import sha256
from io import BytesIO
import json
import logging
import os
import random
import pickle
import subprocess
import sys
import time
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
from uuid import UUID, uuid4
from PIL import Image, ImageOps
from .broker import QUEUE, _connection, publish_dlq
from .config import load_settings
from .storage.postgres import PostgresStore
from .storage.s3 import S3Settings, S3Store
from . import telemetry as tel
from datetime import datetime, timezone
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
class PermanentFailure(Exception):
pass
def fit(image, bound):
longest = max(image.size)
if longest <= bound:
return image.copy()
return image.resize((max(1, image.width * bound // longest),
max(1, image.height * bound // longest)), Image.Resampling.LANCZOS)
def render_isolated(data, timeout):
try:
result = subprocess.run([sys.executable, '-m', 'src.render'], input=data,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
except subprocess.TimeoutExpired as error:
raise TimeoutError('render deadline exceeded') from error
if result.returncode in (20, 21):
raise PermanentFailure('invalid_image' if result.returncode == 20 else 'image_resource_limit')
if result.returncode:
raise RuntimeError('renderer exited')
# Only our own child process produces this payload; no external pickle input.
return pickle.loads(result.stdout)
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
image = ImageOps.exif_transpose(source)
if image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info):
background = Image.new("RGBA", image.size, "white")
background.alpha_composite(image.convert("RGBA"))
image = background.convert("RGB")
else:
image = image.convert("RGB")
image = fit(image, 256)
output = BytesIO()
image.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue(), image.width, image.height
def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes, str, int, int]]:
"""Render required variants without preserving EXIF or other input metadata."""
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
if source.width * source.height > max_pixels:
raise ValueError("image exceeds configured pixel limit")
image = ImageOps.exif_transpose(source).convert("RGBA")
white = Image.new("RGBA", image.size, "white")
white.alpha_composite(image)
rgb = white.convert("RGB")
thumb = fit(rgb, 256)
thumbnail_out = BytesIO(); thumb.save(thumbnail_out, "JPEG", quality=85, optimize=True)
side = min(rgb.width, rgb.height)
left, top = (rgb.width - side) // 2, (rgb.height - side) // 2
crop = rgb.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
crop_out = BytesIO(); crop.save(crop_out, "JPEG", quality=85, optimize=True)
optimized = fit(rgb, 1280)
optimized_out = BytesIO(); optimized.save(optimized_out, "WEBP", quality=80, method=4)
return [
("thumbnail", thumbnail_out.getvalue(), "image/jpeg", thumb.width, thumb.height),
("crop", crop_out.getvalue(), "image/jpeg", 128, 128),
("optimized", optimized_out.getvalue(), "image/webp", optimized.width, optimized.height),
]
async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> str:
# Excludes cleanup for the whole lifetime of S3 effects, including stale attempts.
async with store.attachment_transaction():
return await process_locked(store, s3, payload, lease_seconds)
async def process_locked(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> str:
attachment_id = UUID(payload["attachment_id"])
attachment = await store.claim_attachment_job(attachment_id, lease_seconds)
if attachment is None:
return "skipped"
payload['_claim_time'] = attachment['claim_time']
payload['attempt'] = attachment.get('attempt', payload.get('attempt', 1))
attempt_key = uuid4().hex
original_key = f"originals/{attachment_id}/{attempt_key}"
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
rendered = await asyncio.to_thread(render_isolated, original, lease_seconds)
metadata = []
for name, content, content_type, width, height in rendered:
extension = "webp" if name == "optimized" else "jpg"
object_key = f"variants/{attachment_id}/{attempt_key}/{name}.{extension}"
await s3.put(object_key, BytesIO(content), len(content), content_type)
metadata.append({"name": name, "object_key": object_key, "content_type": content_type,
"size_bytes": len(content), "width": width, "height": height,
"sha256": sha256(content).hexdigest()})
# Explicit, opt-in integration fault. Marker survives container restart,
# so one crash exercises lease recovery without a permanent crash loop.
if os.environ.get('WORKER_FAULT_AFTER_S3_PUT') == '1':
marker = Path('/tmp/worker-fault-after-s3')
try:
with marker.open('x') as stream:
stream.write(str(attachment_id))
except FileExistsError:
pass
else:
os._exit(70)
committed = await store.complete_attachment_job(attachment_id, original_key, metadata, attachment['claim_time'])
if committed:
try:
duration = await store.ready_seconds(attachment_id)
if duration is not None:
tel.ready_duration.record(duration, {"job_type": "attachment"})
except Exception:
tel.log.warning("telemetry.unavailable")
try:
await s3.delete(attachment["staging_key"])
except Exception:
logging.warning('staging cleanup deferred attachment_id=%s', attachment_id)
return "success" if committed else "skipped"
def settle_delivery(channel, delivery_tag, future):
"""Only a successful durable disposition permits acknowledgement."""
try:
success = future.result() is True
except Exception:
success = False
if channel.is_open:
if success:
channel.basic_ack(delivery_tag)
else:
channel.basic_nack(delivery_tag, requeue=True)
def main() -> None:
tel.setup("messenger-worker")
settings = load_settings()
connection = _connection()
channel = connection.channel()
workers = max(1, int(os.environ.get("WORKER_CONCURRENCY", "2")))
tel.capacity.add(workers)
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_PREFETCH", str(workers)))))
async def handle_async(payload):
"""Each executor thread owns its event loop and its DB/S3 clients."""
store = PostgresStore(settings.database_url)
s3 = S3Store(S3Settings.load())
await store.connect()
try:
return await process(store, s3, payload, max(1, int(os.environ.get("JOB_TIMEOUT_SECONDS", "60"))))
finally:
s3.client.close()
await store.close()
async def schedule_retry(attachment_id, delay, claim_time, permanent_code=None):
retry_store = PostgresStore(settings.database_url)
await retry_store.connect()
try:
return await retry_store.retry_attachment_job(
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay, claim_time, permanent_code
)
finally:
await retry_store.close()
def handle_job(body):
payload = None
try:
payload = json.loads(body)
if not isinstance(payload, dict):
raise ValueError('job must be an object')
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
raise ValueError("unexpected broker payload")
UUID(payload['attachment_id'])
UUID(payload['job_id'])
tel.trace.get_current_span().set_attribute("messaging.retry.attempt", int(payload.get('attempt', 1)))
except (ValueError, KeyError, TypeError):
try:
asyncio.run(publish_dlq({'failure': 'invalid_job'}))
return True, "failed"
except Exception:
return False, "failed"
try:
outcome = asyncio.run(handle_async(payload))
except Exception as error:
logging.warning("job failed attachment_id=%s", payload['attachment_id'])
if '_claim_time' not in payload:
return False, "failed"
try:
attachment_id = UUID(payload["attachment_id"])
attempt = int(payload.get("attempt", 1))
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
asyncio.run(schedule_retry(attachment_id, delay, payload['_claim_time'],
str(error) if isinstance(error, PermanentFailure) else None))
except Exception:
return False, "failed"
return True, "failed"
return True, outcome
def handle(body, headers):
started = time.monotonic()
tel.busy.add(1)
with tel.tracer.start_as_current_span("attachment.consume", context=tel.extract(headers), kind=tel.SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False) as span:
try:
acknowledged, outcome = handle_job(body)
return acknowledged
except Exception:
outcome = "failed"
raise
finally:
if 'outcome' not in locals(): outcome = "failed"
if outcome == "failed": span.set_status(tel.Status(tel.StatusCode.ERROR))
attrs = {"job_type": "attachment", "outcome": outcome}
tel.jobs.add(1, attrs)
tel.job_duration.record(time.monotonic() - started, attrs)
tel.log.info("job.processed", extra={"outcome": outcome})
tel.busy.add(-1)
def consume(ch, method, properties, body):
future = executor.submit(handle, body, properties.headers or {})
def acknowledged(_future):
if connection.is_open:
connection.add_callback_threadsafe(lambda: settle_delivery(ch, method.delivery_tag, _future))
future.add_done_callback(acknowledged)
try:
def heartbeat():
Path('/tmp/worker-heartbeat').write_text(str(time.time()))
connection.call_later(2, heartbeat)
heartbeat()
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="attachment-worker") as executor:
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
channel.start_consuming()
finally:
connection.close()
if __name__ == "__main__":
main()