forked from mtusi2026/mtusi2026lab6
Реализовать наблюдаемость мессенджера и проверить её под нагрузкой
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""One-process implementation of the lab 1 messenger contract."""
|
||||
@@ -0,0 +1,27 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
from messenger import telemetry
|
||||
|
||||
|
||||
def main():
|
||||
level = os.getenv("APP_LOG_LEVEL", "INFO").upper()
|
||||
logging.basicConfig(level=level, format="%(message)s")
|
||||
with telemetry.active("api"):
|
||||
uvicorn.run(
|
||||
"messenger.app:create_app",
|
||||
factory=True,
|
||||
host=os.getenv("APP_HOST", "0.0.0.0"),
|
||||
port=int(os.getenv("APP_PORT", "8080")),
|
||||
workers=1,
|
||||
access_log=False,
|
||||
log_level=level.lower(),
|
||||
timeout_keep_alive=2,
|
||||
timeout_graceful_shutdown=5,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,350 @@
|
||||
"""HTTP adapter. The instructor's OpenAPI, not FastAPI defaults, defines errors."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from contextlib import asynccontextmanager
|
||||
from time import perf_counter
|
||||
from typing import Annotated
|
||||
from urllib.parse import quote
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||||
from opentelemetry.context import Context
|
||||
from opentelemetry.trace import INVALID_SPAN, SpanKind
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from messenger import telemetry
|
||||
from messenger.attachments import Attachments
|
||||
from messenger.auth import AuthService, Identity, basic_credentials, bearer_digest, unauthorized
|
||||
from messenger.cache import SessionCache
|
||||
from messenger.domain import DomainError, User, invalid, not_found
|
||||
from messenger.repository import PostgresRepository
|
||||
from messenger.schemas import (
|
||||
AttachmentView,
|
||||
ChatPage,
|
||||
ChatView,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
MessagePage,
|
||||
MessageView,
|
||||
SessionView,
|
||||
UserView,
|
||||
canonical_uuid,
|
||||
)
|
||||
from messenger.service import Messenger
|
||||
from messenger.settings import Settings
|
||||
from messenger.storage import ObjectStore
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
|
||||
class RequestContext:
|
||||
def __init__(self, app: ASGIApp, instance_id: str):
|
||||
self.app = app
|
||||
self.instance_id = instance_id
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
if scope.get("path") in {"/health/live", "/health/ready"}:
|
||||
await self.request(scope, receive, send, INVALID_SPAN)
|
||||
return
|
||||
with telemetry.span("http.request", context=Context(), kind=SpanKind.SERVER) as span:
|
||||
await self.request(scope, receive, send, span)
|
||||
|
||||
async def request(self, scope, receive, send, span):
|
||||
request_id = str(uuid4())
|
||||
scope.setdefault("state", {})["request_id"] = request_id
|
||||
start, status, response_started = perf_counter(), 500, False
|
||||
|
||||
async def with_id(message: Message):
|
||||
nonlocal status, response_started
|
||||
if message["type"] == "http.response.start":
|
||||
response_started = True
|
||||
status = message["status"]
|
||||
message["headers"] = [
|
||||
pair
|
||||
for pair in message.get("headers", [])
|
||||
if pair[0].lower() not in (b"x-request-id", b"x-instance-id")
|
||||
] + [
|
||||
(b"x-request-id", request_id.encode()),
|
||||
(b"x-instance-id", self.instance_id.encode()),
|
||||
]
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, with_id)
|
||||
except Exception as exc:
|
||||
# Do not let Uvicorn print exception values that could contain user data.
|
||||
if response_started:
|
||||
raise
|
||||
logger.error(json.dumps({"event": "internal_error", "type": type(exc).__name__}))
|
||||
response = error_response(
|
||||
Request(scope), 500, "internal_error", "Внутренняя ошибка сервера"
|
||||
)
|
||||
await response(scope, receive, with_id)
|
||||
finally:
|
||||
route = getattr(scope.get("route"), "path", "unmatched")
|
||||
if route not in {"/health/live", "/health/ready"}:
|
||||
telemetry.http(
|
||||
span, scope["method"], route, status, perf_counter() - start, request_id
|
||||
)
|
||||
|
||||
|
||||
def error_response(
|
||||
request: Request, status: int, code: str, message: str, headers: dict | None = None
|
||||
) -> JSONResponse:
|
||||
identity = getattr(request.state, "request_id", str(uuid4()))
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": identity}},
|
||||
headers={"X-Request-Id": identity, **(headers or {})},
|
||||
)
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
settings = settings or Settings.from_env()
|
||||
repository = PostgresRepository(
|
||||
settings.database_url,
|
||||
settings.pool_size,
|
||||
settings.idempotency_ttl,
|
||||
settings.read_autocommit,
|
||||
)
|
||||
cache = SessionCache(settings.cache_url)
|
||||
store = ObjectStore(settings)
|
||||
authentication = AuthService(repository, cache, settings.session_ttl)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
repository.open()
|
||||
app.state.ready = True
|
||||
logger.info(json.dumps({"event": "started", "environment": os.getenv("APP_ENV", "lab")}))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
app.state.ready = False
|
||||
repository.close()
|
||||
cache.close()
|
||||
store.close()
|
||||
logger.info(json.dumps({"event": "stopped"}))
|
||||
|
||||
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
app.state.instance_id = uuid4().hex
|
||||
app.add_middleware(RequestContext, instance_id=app.state.instance_id)
|
||||
app.state.messenger = Messenger(repository)
|
||||
app.state.attachments = Attachments(repository, app.state.messenger, store, settings)
|
||||
app.state.repository = repository
|
||||
app.state.authentication = authentication
|
||||
app.state.cache = cache
|
||||
app.state.ready = False
|
||||
|
||||
@app.exception_handler(DomainError)
|
||||
async def domain_error(request: Request, exc: DomainError):
|
||||
return error_response(request, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Некорректные поля или JSON")
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request: Request, exc: HTTPException):
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
return error_response(request, exc.status_code, code, "Некорректный HTTP-запрос")
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_error(request: Request, exc: Exception):
|
||||
logger.error(json.dumps({"event": "internal_error", "type": type(exc).__name__}))
|
||||
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
|
||||
def service(request: Request) -> Messenger:
|
||||
return request.app.state.messenger
|
||||
|
||||
def token_digest(request: Request) -> bytes:
|
||||
if len(request.headers.getlist("authorization")) != 1:
|
||||
raise unauthorized()
|
||||
return bearer_digest(request.headers.get("authorization"))
|
||||
|
||||
def identity(
|
||||
digest: Annotated[bytes, Depends(token_digest)],
|
||||
) -> Identity:
|
||||
return authentication.identify(digest)
|
||||
|
||||
def actor(current: Annotated[Identity, Depends(identity)]) -> User:
|
||||
return current.user
|
||||
|
||||
async def credentials(request: Request) -> tuple[str, str]:
|
||||
if len(request.headers.getlist("authorization")) != 1:
|
||||
raise unauthorized("Basic")
|
||||
result = basic_credentials(request.headers.get("authorization"))
|
||||
if await request.body():
|
||||
raise invalid("Вход не принимает тело запроса")
|
||||
return result
|
||||
|
||||
def resource_id(chat_id: str) -> str:
|
||||
try:
|
||||
return canonical_uuid(chat_id)
|
||||
except ValueError:
|
||||
raise invalid("Некорректный UUID чата") from None
|
||||
|
||||
def pagination(request: Request) -> tuple[int, str | None]:
|
||||
for key in ("limit", "cursor"):
|
||||
if len(request.query_params.getlist(key)) > 1:
|
||||
raise invalid("Параметр пагинации указан несколько раз")
|
||||
raw = request.query_params.get("limit", "50")
|
||||
try:
|
||||
if not re.fullmatch(r"[0-9]+", raw):
|
||||
raise ValueError
|
||||
limit = int(raw)
|
||||
if not 1 <= limit <= 100:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise invalid("limit должен быть целым от 1 до 100") from None
|
||||
return limit, request.query_params.get("cursor")
|
||||
|
||||
def json_input(request: Request):
|
||||
media = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if media != "application/json":
|
||||
raise DomainError(415, "unsupported_media_type", "Требуется application/json")
|
||||
|
||||
def message_key(request: Request) -> str:
|
||||
values = request.headers.getlist("idempotency-key")
|
||||
if len(values) != 1 or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", values[0]):
|
||||
raise invalid("Требуется корректный Idempotency-Key")
|
||||
return values[0]
|
||||
|
||||
CurrentUser = Annotated[User, Depends(actor)]
|
||||
Service = Annotated[Messenger, Depends(service)]
|
||||
ChatId = Annotated[str, Depends(resource_id)]
|
||||
Pagination = Annotated[tuple[int, str | None], Depends(pagination)]
|
||||
|
||||
@app.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
def ready(request: Request):
|
||||
if not request.app.state.ready:
|
||||
raise DomainError(503, "unavailable", "Приложение не готово")
|
||||
repository.ready()
|
||||
store.ready()
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post(
|
||||
"/api/v1/users",
|
||||
status_code=201,
|
||||
response_model=UserView,
|
||||
dependencies=[Depends(json_input)],
|
||||
)
|
||||
def register(body: CreateUser):
|
||||
return authentication.register(body.username, body.display_name, body.password)
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201, response_model=SessionView)
|
||||
def login(value: Annotated[tuple[str, str], Depends(credentials)]):
|
||||
return authentication.login(*value)
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(current: Annotated[Identity, Depends(identity)]):
|
||||
authentication.logout(current)
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=UserView)
|
||||
def me(current: CurrentUser):
|
||||
return current
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats",
|
||||
status_code=201,
|
||||
response_model=ChatView,
|
||||
dependencies=[Depends(json_input)],
|
||||
)
|
||||
def create_chat(body: CreateChat, current: CurrentUser, messenger: Service):
|
||||
return messenger.create_chat(current, body.title, body.member_ids)
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def chats(current: CurrentUser, messenger: Service, page: Pagination):
|
||||
return messenger.chats(current, *page)
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=ChatView)
|
||||
def chat(current: CurrentUser, chat: ChatId, messenger: Service):
|
||||
return messenger.chat(current, chat)
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
status_code=201,
|
||||
response_model=MessageView,
|
||||
dependencies=[Depends(json_input)],
|
||||
)
|
||||
def send_message(
|
||||
body: CreateMessage,
|
||||
current: CurrentUser,
|
||||
chat: ChatId,
|
||||
messenger: Service,
|
||||
key: Annotated[str, Depends(message_key)],
|
||||
):
|
||||
return messenger.send(current, chat, body.text, key, tuple(body.attachment_ids))
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def messages(current: CurrentUser, chat: ChatId, messenger: Service, page: Pagination):
|
||||
return messenger.messages(current, chat, *page)
|
||||
|
||||
def attachment_id(attachment_id: str) -> str:
|
||||
try:
|
||||
return canonical_uuid(attachment_id)
|
||||
except ValueError:
|
||||
raise invalid("Некорректный UUID вложения") from None
|
||||
|
||||
AttachmentId = Annotated[str, Depends(attachment_id)]
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202, response_model=AttachmentView)
|
||||
async def upload(request: Request, current: CurrentUser, chat: ChatId):
|
||||
return await app.state.attachments.upload(request, current, chat)
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}", response_model=AttachmentView)
|
||||
def attachment(current: CurrentUser, id: AttachmentId):
|
||||
return app.state.attachments.metadata(current, id)
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
def content(request: Request, current: CurrentUser, id: AttachmentId):
|
||||
row = app.state.attachments.record(current, id)
|
||||
if row["storage_state"] != "ready":
|
||||
raise DomainError(409, "conflict", "Вложение пока недоступно")
|
||||
values = request.query_params.getlist("variant")
|
||||
if (
|
||||
len(values) > 1
|
||||
or values
|
||||
and values[0] not in ("original", "thumbnail", "crop", "optimized")
|
||||
):
|
||||
raise invalid("Некорректный вариант вложения")
|
||||
if values and values[0] != "original":
|
||||
row = next((v for v in row["variants"] if v["name"] == values[0]), None)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
row = {**row, "filename": values[0]}
|
||||
body = store.download(row)
|
||||
|
||||
def chunks():
|
||||
try:
|
||||
while data := body.read(65536):
|
||||
yield data
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
return StreamingResponse(
|
||||
chunks(),
|
||||
media_type=row["content_type"],
|
||||
headers={
|
||||
"Content-Length": str(row["size_bytes"]),
|
||||
"Content-Disposition": "attachment; filename*=UTF-8''"
|
||||
+ quote(row["filename"], safe=""),
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Bounded upload: verified staging and transactional job intent precede HTTP 202."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import tempfile
|
||||
import unicodedata
|
||||
import warnings
|
||||
|
||||
from anyio import to_thread
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from messenger.domain import DomainError, invalid, new_id, not_found
|
||||
from messenger.pipeline import Pipeline
|
||||
from messenger.repository import attachment_value
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.filterwarnings("error", category=Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def filename(value):
|
||||
if (
|
||||
not value
|
||||
or not value.strip()
|
||||
or len(value) > 255
|
||||
or any(c in "/\\" or unicodedata.category(c).startswith("C") for c in value)
|
||||
):
|
||||
raise invalid("Некорректное имя файла")
|
||||
return value
|
||||
|
||||
|
||||
def image_type(file, maximum):
|
||||
try:
|
||||
file.seek(0)
|
||||
with Image.open(file) as image:
|
||||
if image.width * image.height > maximum:
|
||||
raise DomainError(413, "payload_too_large", "Слишком много пикселей")
|
||||
if image.format not in ("PNG", "JPEG"):
|
||||
raise ValueError
|
||||
media = "image/png" if image.format == "PNG" else "image/jpeg"
|
||||
image.verify()
|
||||
file.seek(0)
|
||||
with Image.open(file) as image:
|
||||
image.load() # Reject truncated pixel streams, not just an intact header.
|
||||
file.seek(0)
|
||||
return media
|
||||
except Image.DecompressionBombError, Image.DecompressionBombWarning:
|
||||
raise DomainError(413, "payload_too_large", "Слишком много пикселей") from None
|
||||
except UnidentifiedImageError, OSError, ValueError, SyntaxError:
|
||||
raise DomainError(415, "unsupported_media_type", "Повреждённое изображение") from None
|
||||
|
||||
|
||||
class Attachments:
|
||||
def __init__(self, repository, messenger, store, settings):
|
||||
self.repository, self.messenger, self.store = repository, messenger, store
|
||||
self.settings = settings
|
||||
self.slots = asyncio.Semaphore(settings.upload_slots)
|
||||
|
||||
async def upload(self, request, actor, chat_id):
|
||||
await to_thread.run_sync(self.messenger.chat, actor, chat_id)
|
||||
values = request.query_params.getlist("filename")
|
||||
if len(values) != 1:
|
||||
raise invalid("Требуется одно имя файла")
|
||||
name = filename(values[0])
|
||||
media = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if media not in ("image/png", "image/jpeg"):
|
||||
raise DomainError(415, "unsupported_media_type", "Требуется PNG или JPEG")
|
||||
length = request.headers.get("content-length")
|
||||
if length is not None:
|
||||
if not length.isascii() or not length.isdecimal():
|
||||
raise invalid("Некорректный Content-Length")
|
||||
if int(length) > self.settings.max_upload_bytes:
|
||||
raise DomainError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
try:
|
||||
await asyncio.wait_for(self.slots.acquire(), timeout=5)
|
||||
except TimeoutError:
|
||||
raise DomainError(429, "rate_limited", "Слишком много загрузок") from None
|
||||
try:
|
||||
with tempfile.TemporaryFile() as file:
|
||||
size, digest = 0, hashlib.sha256()
|
||||
try:
|
||||
async with asyncio.timeout(15):
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > self.settings.max_upload_bytes:
|
||||
raise DomainError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
digest.update(chunk)
|
||||
await to_thread.run_sync(file.write, chunk)
|
||||
except TimeoutError:
|
||||
raise DomainError(400, "invalid_request", "Время загрузки истекло") from None
|
||||
except ClientDisconnect:
|
||||
raise invalid("Загрузка прервана") from None
|
||||
actual = await to_thread.run_sync(image_type, file, self.settings.max_image_pixels)
|
||||
if actual != media:
|
||||
raise DomainError(415, "unsupported_media_type", "MIME не совпадает с файлом")
|
||||
id = new_id()
|
||||
key = "staging/" + id
|
||||
await to_thread.run_sync(Pipeline(self.repository, self.settings).reserve, id, key)
|
||||
await to_thread.run_sync(
|
||||
self.store.put, key, file, size, actual, digest.hexdigest()
|
||||
)
|
||||
# A failure before this COMMIT leaves only an unaccepted staging orphan.
|
||||
# The same transaction creates attachment, job and outbox intent.
|
||||
row = await to_thread.run_sync(
|
||||
Pipeline(self.repository, self.settings).accept,
|
||||
id,
|
||||
chat_id,
|
||||
actor.id,
|
||||
name,
|
||||
actual,
|
||||
size,
|
||||
digest.hexdigest(),
|
||||
key,
|
||||
)
|
||||
return attachment_value(row)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
def record(self, actor, id):
|
||||
row = self.repository.attachment(id)
|
||||
if row is None:
|
||||
raise not_found()
|
||||
self.messenger.chat(actor, str(row["chat_id"]))
|
||||
return row
|
||||
|
||||
def metadata(self, actor, id):
|
||||
return attachment_value(self.record(actor, id))
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Argon2id passwords and opaque sessions. Cache hits never authorize a request."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from threading import BoundedSemaphore
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
from argon2.profiles import RFC_9106_LOW_MEMORY
|
||||
|
||||
from messenger.cache import SessionCache
|
||||
from messenger.domain import DomainError, User
|
||||
from messenger.repository import PostgresRepository
|
||||
|
||||
|
||||
def unauthorized(scheme: str = "Bearer") -> DomainError:
|
||||
challenge = scheme + ' realm="messenger"'
|
||||
if scheme == "Basic":
|
||||
challenge += ', charset="UTF-8"'
|
||||
return DomainError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Требуется действительная идентификация",
|
||||
{"WWW-Authenticate": challenge},
|
||||
)
|
||||
|
||||
|
||||
def basic_credentials(header: str | None) -> tuple[str, str]:
|
||||
try:
|
||||
if header is None or len(header) > 2048:
|
||||
raise ValueError
|
||||
scheme, encoded = header.split(" ", 1)
|
||||
if scheme.lower() != "basic":
|
||||
raise ValueError
|
||||
raw = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
username, password = raw.split(":", 1)
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||
raise ValueError
|
||||
if not 12 <= len(password) <= 128 or not password.strip():
|
||||
raise ValueError
|
||||
return username, password
|
||||
except ValueError, UnicodeError, binascii.Error:
|
||||
raise unauthorized("Basic") from None
|
||||
|
||||
|
||||
def bearer_digest(header: str | None) -> bytes:
|
||||
if header:
|
||||
parts = header.split(" ")
|
||||
if len(parts) == 2 and parts[0].lower() == "bearer":
|
||||
if re.fullmatch(r"[A-Za-z0-9_-]{43}", parts[1]):
|
||||
return hashlib.sha256(parts[1].encode()).digest()
|
||||
raise unauthorized()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Identity:
|
||||
user: User
|
||||
token_hash: bytes
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Session:
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, repository: PostgresRepository, cache: SessionCache, ttl: int):
|
||||
self.repository, self.cache, self.ttl = repository, cache, ttl
|
||||
self.hasher = PasswordHasher.from_parameters(RFC_9106_LOW_MEMORY)
|
||||
self.kdf_slots = BoundedSemaphore(2)
|
||||
self.dummy_hash = self.hasher.hash(secrets.token_urlsafe(32))
|
||||
|
||||
@contextmanager
|
||||
def kdf(self):
|
||||
if not self.kdf_slots.acquire(timeout=0.5):
|
||||
raise DomainError(503, "unavailable", "Обработка пароля временно занята")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.kdf_slots.release()
|
||||
|
||||
def register(self, username: str, display_name: str, password: str) -> User:
|
||||
with self.kdf():
|
||||
encoded = self.hasher.hash(password)
|
||||
return self.repository.add_user(username, display_name, encoded)
|
||||
|
||||
def login(self, username: str, password: str) -> Session:
|
||||
credentials = self.repository.credentials(username)
|
||||
encoded = credentials[1] if credentials else self.dummy_hash
|
||||
try:
|
||||
with self.kdf():
|
||||
self.hasher.verify(encoded, password)
|
||||
except VerificationError, InvalidHashError:
|
||||
raise unauthorized("Basic") from None
|
||||
if credentials is None:
|
||||
raise unauthorized("Basic")
|
||||
token = secrets.token_urlsafe(32)
|
||||
digest = hashlib.sha256(token.encode()).digest()
|
||||
user = credentials[0]
|
||||
expires = self.repository.create_session(digest, user.id, self.ttl)
|
||||
return Session(token, "Bearer", expires, user)
|
||||
|
||||
def identify(self, digest: bytes) -> Identity:
|
||||
session = self.repository.active_session(digest)
|
||||
if session is None:
|
||||
raise unauthorized()
|
||||
user_id = str(session["user_id"])
|
||||
user = self.cache.get(digest, user_id)
|
||||
if user is None:
|
||||
user = self.repository.get_user(user_id)
|
||||
if user is None:
|
||||
raise unauthorized()
|
||||
ttl = int((session["expires_at"] - session["checked_at"]).total_seconds())
|
||||
self.cache.put(digest, user, ttl)
|
||||
return Identity(user, digest)
|
||||
|
||||
def logout(self, identity: Identity):
|
||||
self.repository.revoke_session(identity.token_hash)
|
||||
self.cache.delete(identity.token_hash)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Dedicated durable Valkey Stream, one consumer group; never evict/trim pending work."""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
import redis
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
STREAM = "attachment-jobs"
|
||||
GROUP = "image-workers-v1"
|
||||
DLQ = "invalid-jobs"
|
||||
|
||||
|
||||
class Job(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
schema_version: Literal[1]
|
||||
job_id: str
|
||||
type: Literal["attachment.process.v1"]
|
||||
attachment_id: str
|
||||
pipeline_version: int = Field(ge=1)
|
||||
attempt: int = Field(ge=1)
|
||||
created_at: str
|
||||
traceparent: str | None = Field(
|
||||
default=None, pattern=r"^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"
|
||||
)
|
||||
tracestate: str | None = Field(default=None, max_length=512)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def strict_carrier(cls, value):
|
||||
if isinstance(value, dict):
|
||||
if type(value.get("schema_version")) is not int:
|
||||
raise ValueError("Integer schema version required")
|
||||
if any(k in value and value[k] is None for k in ("traceparent", "tracestate")):
|
||||
raise ValueError("Optional carrier fields must be strings when provided")
|
||||
return value
|
||||
|
||||
@field_validator("job_id", "attachment_id")
|
||||
@classmethod
|
||||
def uuid(cls, value):
|
||||
if str(UUID(value)) != value:
|
||||
raise ValueError("Canonical UUID required")
|
||||
return value
|
||||
|
||||
@field_validator("created_at")
|
||||
@classmethod
|
||||
def timestamp(cls, value):
|
||||
if not re.fullmatch(r"\d{4}-\d\d-\d\dT.+(?:Z|[+-]\d\d:\d\d)", value):
|
||||
raise ValueError("RFC3339 required")
|
||||
datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return value
|
||||
|
||||
|
||||
class Broker:
|
||||
def __init__(self, settings):
|
||||
self.client = redis.Redis.from_url(
|
||||
settings.broker_url,
|
||||
decode_responses=True,
|
||||
socket_timeout=2,
|
||||
socket_connect_timeout=1,
|
||||
retry_on_timeout=False,
|
||||
)
|
||||
|
||||
def group(self):
|
||||
try:
|
||||
self.client.xgroup_create(STREAM, GROUP, id="0", mkstream=True)
|
||||
except redis.ResponseError as exc:
|
||||
if "BUSYGROUP" not in str(exc):
|
||||
raise
|
||||
|
||||
def publish(self, job):
|
||||
# XADD reply is the publisher boundary; appendfsync=always precedes that reply.
|
||||
return self.client.xadd(STREAM, {"job": job.model_dump_json(exclude_none=True)})
|
||||
|
||||
def ack(self, id):
|
||||
# A single consumer group only. Atomically remove completed entries, never MAXLEN.
|
||||
self.client.eval(
|
||||
"redis.call('XACK',KEYS[1],ARGV[1],ARGV[2]); return redis.call('XDEL',KEYS[1],ARGV[2])",
|
||||
1,
|
||||
STREAM,
|
||||
GROUP,
|
||||
id,
|
||||
)
|
||||
|
||||
def quarantine(self, id, reason):
|
||||
# Never copy arbitrary attacker-supplied fields into DLQ/logs.
|
||||
with self.client.pipeline(transaction=True) as tx:
|
||||
tx.xadd(DLQ, {"stream_id": id, "reason": reason}, maxlen=1000)
|
||||
tx.xack(STREAM, GROUP, id)
|
||||
tx.xdel(STREAM, id)
|
||||
tx.execute()
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Disposable session-user cache; PostgreSQL always decides token validity."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import asdict
|
||||
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
|
||||
from messenger.domain import User
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url: str):
|
||||
self.client = Redis.from_url(
|
||||
url,
|
||||
socket_connect_timeout=0.2,
|
||||
socket_timeout=0.2,
|
||||
max_connections=8,
|
||||
decode_responses=True,
|
||||
retry_on_timeout=False,
|
||||
retry=Retry(NoBackoff(), 0),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def key(digest: bytes) -> str:
|
||||
return "session-user:" + digest.hex()
|
||||
|
||||
def get(self, digest: bytes, user_id: str) -> User | None:
|
||||
try:
|
||||
raw = self.client.get(self.key(digest))
|
||||
if raw:
|
||||
value = User(**json.loads(raw))
|
||||
if value.id == user_id:
|
||||
return value
|
||||
except RedisError, ValueError, TypeError:
|
||||
logger.warning('{"event":"session_cache_unavailable","operation":"get"}')
|
||||
return None
|
||||
|
||||
def put(self, digest: bytes, user: User, ttl: int):
|
||||
try:
|
||||
self.client.set(self.key(digest), json.dumps(asdict(user)), ex=max(1, ttl))
|
||||
except RedisError:
|
||||
logger.warning('{"event":"session_cache_unavailable","operation":"set"}')
|
||||
|
||||
def delete(self, digest: bytes):
|
||||
try:
|
||||
self.client.delete(self.key(digest))
|
||||
except RedisError:
|
||||
logger.warning('{"event":"session_cache_unavailable","operation":"delete"}')
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Dry-run by default. Retention GC protects all active jobs and every published object."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.pipeline import event
|
||||
from messenger.repository import PostgresRepository
|
||||
from messenger.settings import Settings
|
||||
from messenger.storage import ObjectStore
|
||||
|
||||
|
||||
def collect(db, store, retention, apply=False):
|
||||
if retention < 300:
|
||||
raise ValueError("Retention must be at least 300 seconds")
|
||||
counts = {"scanned": 0, "eligible": 0, "deleted": 0, "protected": 0}
|
||||
# Serialize collectors; API handoff is bounded < retention and all owned keys have UUID prefix.
|
||||
with db.connection() as lock:
|
||||
if not lock.execute("SELECT pg_try_advisory_lock(2301005) AS ok").fetchone()["ok"]:
|
||||
return {**counts, "busy": True}
|
||||
try:
|
||||
for page in store.client.get_paginator("list_objects_v2").paginate(Bucket=store.bucket):
|
||||
for obj in page.get("Contents", []):
|
||||
counts["scanned"] += 1
|
||||
key = obj["Key"]
|
||||
parts = key.split("/")
|
||||
try:
|
||||
if (
|
||||
parts[0] not in ("staging", "objects")
|
||||
or str(UUID(parts[1])) != parts[1]
|
||||
):
|
||||
continue
|
||||
except ValueError, IndexError:
|
||||
continue
|
||||
if (datetime.now(UTC) - obj["LastModified"]).total_seconds() < retention:
|
||||
continue
|
||||
with db.connection(write=True) as conn:
|
||||
reservation = conn.execute(
|
||||
"SELECT * FROM upload_reservations WHERE id=%s FOR UPDATE", (parts[1],)
|
||||
).fetchone()
|
||||
if (
|
||||
reservation
|
||||
and reservation["state"] == "uploading"
|
||||
and reservation["expires_at"] > datetime.now(UTC)
|
||||
):
|
||||
counts["protected"] += 1
|
||||
continue
|
||||
# This row lock serializes replay/new-version with deletion eligibility.
|
||||
a = conn.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (parts[1],)
|
||||
).fetchone()
|
||||
active = conn.execute(
|
||||
"SELECT 1 FROM attachment_jobs WHERE attachment_id=%s AND "
|
||||
"state IN ('queued','processing') LIMIT 1",
|
||||
(parts[1],),
|
||||
).fetchone()
|
||||
published = (
|
||||
a
|
||||
and a["storage_state"] == "ready"
|
||||
and (
|
||||
key == a["object_key"]
|
||||
or any(v["object_key"] == key for v in a["variants"])
|
||||
)
|
||||
)
|
||||
recent_failed = conn.execute(
|
||||
"SELECT 1 FROM attachment_jobs WHERE attachment_id=%s AND "
|
||||
"state='failed' "
|
||||
"AND updated_at>clock_timestamp()-(%s*interval '1 second') LIMIT 1",
|
||||
(parts[1], retention),
|
||||
).fetchone()
|
||||
if active or published or recent_failed:
|
||||
counts["protected"] += 1
|
||||
continue
|
||||
head = store.head(key)
|
||||
if (
|
||||
not head
|
||||
or head["ETag"] != obj["ETag"]
|
||||
or head["ContentLength"] != obj["Size"]
|
||||
or (datetime.now(UTC) - head["LastModified"]).total_seconds()
|
||||
< retention
|
||||
):
|
||||
continue
|
||||
counts["eligible"] += 1
|
||||
if apply:
|
||||
if reservation and reservation["state"] == "uploading":
|
||||
conn.execute(
|
||||
"UPDATE upload_reservations SET state='abandoned' WHERE id=%s",
|
||||
(parts[1],),
|
||||
)
|
||||
store.client.delete_object(Bucket=store.bucket, Key=key)
|
||||
counts["deleted"] += 1
|
||||
rows = conn.execute(
|
||||
"UPDATE attachment_jobs SET source_expired=true WHERE "
|
||||
"source_key=%s "
|
||||
"AND state='failed' RETURNING job_id",
|
||||
(key,),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
event(conn, row["job_id"], "source_expired")
|
||||
finally:
|
||||
lock.execute("SELECT pg_advisory_unlock(2301005)")
|
||||
return counts
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--apply", action="store_true")
|
||||
args = parser.parse_args()
|
||||
settings = Settings.from_env()
|
||||
db = PostgresRepository(settings.database_url, pool_size=2)
|
||||
db.open()
|
||||
store = ObjectStore(settings)
|
||||
try:
|
||||
print(json.dumps(collect(db, store, settings.staging_retention, args.apply)))
|
||||
finally:
|
||||
store.close()
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Versioned keyset position, bound to a list and its resource, never an offset."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from uuid import UUID
|
||||
|
||||
from messenger.domain import HistoryKey, invalid
|
||||
|
||||
|
||||
def encode_cursor(scope: str, position: HistoryKey) -> str:
|
||||
value = {"v": 1, "scope": scope, "created_at": position[0], "id": position[1]}
|
||||
return (
|
||||
base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode())
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
|
||||
|
||||
def decode_cursor(value: str | None, scope: str) -> HistoryKey | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if not value or len(value) > 1024:
|
||||
raise ValueError
|
||||
raw = base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True)
|
||||
data = json.loads(raw)
|
||||
if not isinstance(data, dict) or set(data) != {"v", "scope", "created_at", "id"}:
|
||||
raise ValueError
|
||||
if type(data["v"]) is not int or data["v"] != 1 or data["scope"] != scope:
|
||||
raise ValueError
|
||||
if not isinstance(data["created_at"], str) or not data["created_at"].endswith("Z"):
|
||||
raise ValueError
|
||||
stamp = datetime.fromisoformat(data["created_at"])
|
||||
if stamp.tzinfo != UTC or not isinstance(data["id"], str):
|
||||
raise ValueError
|
||||
identity = str(UUID(data["id"]))
|
||||
return stamp.isoformat(timespec="microseconds").replace("+00:00", "Z"), identity
|
||||
except ValueError, TypeError, KeyError, UnicodeError, binascii.Error:
|
||||
raise invalid("Некорректный cursor или другая область пагинации") from None
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Immutable domain values; no dependency on HTTP or a storage technology."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return str(uuid4())
|
||||
|
||||
|
||||
class DomainError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, headers: dict | None = None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid(message: str = "Некорректный запрос") -> DomainError:
|
||||
return DomainError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def not_found() -> DomainError:
|
||||
return DomainError(404, "not_found", "Объект не найден")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class User:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Chat:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: tuple[str, ...]
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Message:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Attachment:
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
created_at: str
|
||||
updated_at: str
|
||||
status: str = "ready"
|
||||
variants: tuple = ()
|
||||
error_code: str | None = None
|
||||
|
||||
|
||||
type HistoryKey = tuple[str, str]
|
||||
|
||||
|
||||
def history_key(item: Chat | Message) -> HistoryKey:
|
||||
return item.created_at, item.id
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Operator-only, single-use fault barriers. Disabled in the normal Compose stack."""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from messenger.domain import DomainError
|
||||
from messenger.pipeline import event
|
||||
|
||||
|
||||
class PermanentFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def checkpoint(db, settings, job, phase):
|
||||
if not settings.fault_injection:
|
||||
return
|
||||
with db.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"UPDATE pipeline_faults SET remaining=remaining-1 WHERE job_id=%s AND phase=%s "
|
||||
"AND remaining>0 RETURNING action",
|
||||
(job, phase),
|
||||
).fetchone()
|
||||
if row:
|
||||
event(conn, job, "fault_injected", phase=phase, action=row["action"], pid=os.getpid())
|
||||
if not row:
|
||||
return
|
||||
match row["action"]:
|
||||
case "crash":
|
||||
os._exit(87)
|
||||
case "hang":
|
||||
time.sleep(settings.job_timeout * 3)
|
||||
case "transient":
|
||||
raise DomainError(503, "unavailable", "Synthetic transient failure")
|
||||
case "permanent":
|
||||
raise PermanentFailure
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Pure, versioned image transforms. No network, filenames, or EXIF in output."""
|
||||
|
||||
import io
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
|
||||
def fit(image, maximum):
|
||||
scale = max(image.size)
|
||||
if scale <= maximum:
|
||||
return image.copy()
|
||||
size = tuple(max(1, n * maximum // scale) for n in image.size)
|
||||
return image.resize(size, Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def variants(source, version):
|
||||
if version not in (1, 2):
|
||||
raise ValueError("Unsupported pipeline version")
|
||||
with Image.open(source) as raw:
|
||||
oriented = ImageOps.exif_transpose(raw)
|
||||
rgba = oriented.convert("RGBA")
|
||||
image = Image.new("RGB", rgba.size, "white")
|
||||
image.paste(rgba, mask=rgba.getchannel("A"))
|
||||
rgba.close()
|
||||
oriented.close()
|
||||
try:
|
||||
for name, output, format, options in (
|
||||
("thumbnail", fit(image, 256), "JPEG", {"quality": 85, "subsampling": 0}),
|
||||
(
|
||||
"crop",
|
||||
ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS),
|
||||
"JPEG",
|
||||
{"quality": 85, "subsampling": 0},
|
||||
),
|
||||
(
|
||||
"optimized",
|
||||
fit(image, 1280),
|
||||
"WEBP",
|
||||
{"quality": 82 if version == 1 else 76, "method": 4},
|
||||
),
|
||||
):
|
||||
with output, io.BytesIO() as buffer:
|
||||
output.save(buffer, format=format, exif=b"", **options)
|
||||
yield (
|
||||
name,
|
||||
buffer.getvalue(),
|
||||
output.size,
|
||||
"image/webp" if format == "WEBP" else "image/jpeg",
|
||||
)
|
||||
finally:
|
||||
image.close()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Transactional, checksummed migrations, serialized across concurrent starts."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from messenger.settings import secret
|
||||
|
||||
|
||||
def migrate(conninfo: str, directory: Path):
|
||||
with psycopg.connect(conninfo, connect_timeout=5) as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(2301002)")
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
"version text PRIMARY KEY, checksum text NOT NULL, "
|
||||
"applied_at timestamptz NOT NULL DEFAULT clock_timestamp())"
|
||||
)
|
||||
for path in sorted(directory.glob("*.sql")):
|
||||
content = path.read_text()
|
||||
checksum = hashlib.sha256(content.encode()).hexdigest()
|
||||
current = conn.execute(
|
||||
"SELECT checksum FROM schema_migrations WHERE version=%s", (path.stem,)
|
||||
).fetchone()
|
||||
if current:
|
||||
if current[0] != checksum:
|
||||
raise RuntimeError("Applied migration checksum changed: " + path.stem)
|
||||
continue
|
||||
conn.execute(content)
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version,checksum) VALUES (%s,%s)",
|
||||
(path.stem, checksum),
|
||||
)
|
||||
print("Applied migration " + path.stem)
|
||||
|
||||
|
||||
def main():
|
||||
migrate(
|
||||
secret("DATABASE_URL_FILE", "/run/secrets/database_url"),
|
||||
Path(os.getenv("MIGRATIONS_DIR", "/app/migrations")),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Explicit local operator actions, never exposed as a public HTTP endpoint."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
|
||||
from messenger.pipeline import Pipeline
|
||||
from messenger.repository import PostgresRepository
|
||||
from messenger.settings import Settings
|
||||
from messenger.storage import ObjectStore
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("failed", "replay", "new-version"))
|
||||
parser.add_argument("attachment_id", nargs="?")
|
||||
args = parser.parse_args()
|
||||
settings = Settings.from_env()
|
||||
db = PostgresRepository(settings.database_url, pool_size=2)
|
||||
db.open()
|
||||
try:
|
||||
if args.action == "failed":
|
||||
with db.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT job_id,attachment_id,pipeline_version,attempt,error_code,"
|
||||
"source_expired FROM attachment_jobs WHERE state='failed' "
|
||||
"ORDER BY updated_at LIMIT 100"
|
||||
).fetchall()
|
||||
print(json.dumps(rows, default=str))
|
||||
else:
|
||||
if not args.attachment_id:
|
||||
parser.error("attachment_id is required")
|
||||
with db.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT j.source_key,a.object_key,a.storage_state FROM attachment_jobs j "
|
||||
"JOIN attachments a ON a.id=j.attachment_id AND "
|
||||
"a.pipeline_version=j.pipeline_version "
|
||||
"WHERE a.id=%s",
|
||||
(args.attachment_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
parser.error("Unknown attachment")
|
||||
store = ObjectStore(settings)
|
||||
try:
|
||||
key = row["object_key"] if row["storage_state"] == "ready" else row["source_key"]
|
||||
if not store.head(key):
|
||||
parser.error("Source is no longer retained")
|
||||
finally:
|
||||
store.close()
|
||||
job = Pipeline(db, settings).replay(
|
||||
args.attachment_id, new_version=args.action == "new-version"
|
||||
)
|
||||
print(json.dumps({"job_id": job, "action": args.action}))
|
||||
except ValueError as exc:
|
||||
parser.error(str(exc))
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Job state machine. PostgreSQL fences publication; the stream is at least once."""
|
||||
|
||||
import os
|
||||
import random
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from messenger import telemetry
|
||||
from messenger.domain import DomainError, new_id
|
||||
|
||||
|
||||
def event(conn, job_id, name, **details):
|
||||
conn.execute(
|
||||
"INSERT INTO pipeline_audit(job_id,event,details) VALUES (%s,%s,%s)",
|
||||
(job_id, name, Jsonb(details)),
|
||||
)
|
||||
|
||||
|
||||
def intent(conn, job_id, when=None):
|
||||
conn.execute(
|
||||
"INSERT INTO job_outbox(job_id,due_at) VALUES (%s,coalesce(%s,clock_timestamp())) "
|
||||
"ON CONFLICT(job_id) DO UPDATE SET due_at=EXCLUDED.due_at,published_at=NULL,stream_id=NULL",
|
||||
(job_id, when),
|
||||
)
|
||||
|
||||
|
||||
class Pipeline:
|
||||
def __init__(self, repository, settings):
|
||||
self.db, self.settings = repository, settings
|
||||
|
||||
def reserve(self, id, key):
|
||||
with self.db.connection(write=True) as conn:
|
||||
conn.execute("INSERT INTO upload_reservations(id,object_key) VALUES (%s,%s)", (id, key))
|
||||
|
||||
def accept(self, id, chat, owner, name, media, size, digest, key):
|
||||
with self.db.connection(write=True) as conn:
|
||||
reservation = conn.execute(
|
||||
"SELECT * FROM upload_reservations WHERE id=%s FOR UPDATE", (id,)
|
||||
).fetchone()
|
||||
if (
|
||||
not reservation
|
||||
or reservation["state"] != "uploading"
|
||||
or reservation["object_key"] != key
|
||||
or reservation["expires_at"] <= datetime.now(UTC)
|
||||
):
|
||||
raise DomainError(503, "unavailable", "Срок приёма файла истёк")
|
||||
conn.execute("UPDATE upload_reservations SET state='accepted' WHERE id=%s", (id,))
|
||||
row = conn.execute(
|
||||
"INSERT INTO attachments "
|
||||
"(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,"
|
||||
"object_key,storage_state) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *",
|
||||
(id, chat, owner, name, media, size, digest, key),
|
||||
).fetchone()
|
||||
job = new_id()
|
||||
trace = telemetry.carrier()
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,source_key,"
|
||||
"traceparent,tracestate) VALUES (%s,%s,1,%s,%s,%s)",
|
||||
(job, id, key, trace.get("traceparent"), trace.get("tracestate")),
|
||||
)
|
||||
intent(conn, job)
|
||||
event(conn, job, "accepted")
|
||||
return row
|
||||
|
||||
def claim(self, envelope):
|
||||
with self.db.connection(write=True) as conn:
|
||||
# All writers lock attachment before job, including publication and operator replay.
|
||||
a = conn.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (envelope.attachment_id,)
|
||||
).fetchone()
|
||||
if not a:
|
||||
return "unknown", None
|
||||
j = conn.execute(
|
||||
"SELECT * FROM attachment_jobs WHERE job_id=%s FOR NO KEY UPDATE",
|
||||
(envelope.job_id,),
|
||||
).fetchone()
|
||||
if (
|
||||
not j
|
||||
or j["attachment_id"] != a["id"]
|
||||
or j["pipeline_version"] != envelope.pipeline_version
|
||||
):
|
||||
return "unknown", None
|
||||
if a["pipeline_version"] != j["pipeline_version"] or j["state"] == "superseded":
|
||||
event(conn, j["job_id"], "stale_delivery")
|
||||
return "stale", None
|
||||
if j["state"] == "ready":
|
||||
event(conn, j["job_id"], "duplicate_ready")
|
||||
return "ready", a
|
||||
if j["state"] == "failed":
|
||||
return "failed", None
|
||||
now = datetime.now(UTC)
|
||||
if j["state"] == "processing" or j["next_attempt_at"] > now:
|
||||
return "busy", None
|
||||
if envelope.attempt != j["attempt"] + 1:
|
||||
# An older envelope cannot steal a scheduled retry or an explicit replay.
|
||||
return "obsolete_attempt", None
|
||||
fence = new_id()
|
||||
conn.execute(
|
||||
"UPDATE attachment_jobs SET state='processing',attempt=attempt+1,fence=%s,"
|
||||
"lease_until=clock_timestamp()+(%s*interval '1 "
|
||||
"second'),updated_at=clock_timestamp() "
|
||||
"WHERE job_id=%s",
|
||||
(fence, self.settings.lease_seconds, j["job_id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachments SET storage_state='processing',"
|
||||
"updated_at=clock_timestamp() WHERE id=%s",
|
||||
(a["id"],),
|
||||
)
|
||||
event(
|
||||
conn, j["job_id"], "claimed", attempt=j["attempt"] + 1, fence=fence, pid=os.getpid()
|
||||
)
|
||||
return "claimed", {
|
||||
**a,
|
||||
"job_id": str(j["job_id"]),
|
||||
"source_key": j["source_key"],
|
||||
"fence": fence,
|
||||
"attempt": j["attempt"] + 1,
|
||||
"accepted_at": j["created_at"],
|
||||
}
|
||||
|
||||
def publish(self, row, original_key, variants):
|
||||
with self.db.connection(write=True) as conn:
|
||||
a = conn.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (row["id"],)
|
||||
).fetchone()
|
||||
j = conn.execute(
|
||||
"SELECT * FROM attachment_jobs WHERE job_id=%s FOR NO KEY UPDATE", (row["job_id"],)
|
||||
).fetchone()
|
||||
if not self.owns(a, j, row):
|
||||
event(conn, row["job_id"], "publication_fenced")
|
||||
return False
|
||||
conn.execute(
|
||||
"UPDATE attachments SET storage_state='ready',object_key=%s,variants=%s,"
|
||||
"error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",
|
||||
(original_key, Jsonb(variants), row["id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachment_jobs SET state='ready',lease_until=NULL,error_code=NULL,"
|
||||
"updated_at=clock_timestamp() WHERE job_id=%s",
|
||||
(row["job_id"],),
|
||||
)
|
||||
event(conn, row["job_id"], "result_committed", version=row["pipeline_version"])
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def owns(a, j, row):
|
||||
return (
|
||||
a
|
||||
and j
|
||||
and a["pipeline_version"] == row["pipeline_version"]
|
||||
and j["state"] == "processing"
|
||||
and str(j["fence"]) == row["fence"]
|
||||
and j["lease_until"] > datetime.now(UTC)
|
||||
)
|
||||
|
||||
def failure(self, row, code, permanent=False):
|
||||
with self.db.connection(write=True) as conn:
|
||||
a = conn.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (row["id"],)
|
||||
).fetchone()
|
||||
j = conn.execute(
|
||||
"SELECT * FROM attachment_jobs WHERE job_id=%s FOR NO KEY UPDATE", (row["job_id"],)
|
||||
).fetchone()
|
||||
if self.owns(a, j, row):
|
||||
return self._retry(conn, j, code, permanent)
|
||||
return "fenced"
|
||||
|
||||
def _retry(self, conn, j, code, permanent=False):
|
||||
failed = permanent or j["attempt"] >= self.settings.job_max_attempts
|
||||
state = "failed" if failed else "queued"
|
||||
if failed and not permanent:
|
||||
code = "retry_exhausted"
|
||||
# Full jitter; durable absolute time survives worker/relay restarts.
|
||||
delay = random.uniform(0.25, min(30, 2 ** min(j["attempt"], 5)))
|
||||
due = datetime.now(UTC) + timedelta(seconds=delay)
|
||||
conn.execute(
|
||||
"UPDATE attachment_jobs SET state=%s,error_code=%s,next_attempt_at=%s,lease_until=NULL,"
|
||||
"updated_at=clock_timestamp() WHERE job_id=%s",
|
||||
(state, code, due, j["job_id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachments SET storage_state=%s,error_code=%s,updated_at=clock_timestamp() "
|
||||
"WHERE id=%s",
|
||||
(state, code if failed else None, j["attachment_id"]),
|
||||
)
|
||||
event(conn, j["job_id"], state, reason=code, attempt=j["attempt"], delay_seconds=delay)
|
||||
if not failed:
|
||||
intent(conn, j["job_id"], due)
|
||||
return "failed" if failed else "retry"
|
||||
|
||||
def recover(self):
|
||||
# Bounded SKIP LOCKED batch; multiple relays. No transaction held during Pillow.
|
||||
with self.db.connection(write=True) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id "
|
||||
"AND j.pipeline_version=a.pipeline_version WHERE j.state='processing' "
|
||||
"AND j.lease_until<clock_timestamp() ORDER BY a.id LIMIT 32 "
|
||||
"FOR UPDATE OF a SKIP LOCKED"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
j = conn.execute(
|
||||
"SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
|
||||
"AND a.pipeline_version=j.pipeline_version WHERE a.id=%s FOR NO KEY "
|
||||
"UPDATE OF j",
|
||||
(row["id"],),
|
||||
).fetchone()
|
||||
if j["state"] == "processing" and j["lease_until"] < datetime.now(UTC):
|
||||
event(conn, j["job_id"], "lease_expired")
|
||||
self._retry(conn, j, "worker_timeout")
|
||||
|
||||
def replay(self, attachment, *, new_version=False):
|
||||
with self.db.connection(write=True) as conn:
|
||||
a = conn.execute(
|
||||
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment,)
|
||||
).fetchone()
|
||||
if not a:
|
||||
raise ValueError("Unknown attachment")
|
||||
j = conn.execute(
|
||||
"SELECT * FROM attachment_jobs WHERE attachment_id=%s "
|
||||
"AND pipeline_version=%s FOR UPDATE",
|
||||
(attachment, a["pipeline_version"]),
|
||||
).fetchone()
|
||||
if new_version:
|
||||
if a["pipeline_version"] != 1:
|
||||
raise ValueError("Only pipeline v1 -> v2 is implemented")
|
||||
conn.execute(
|
||||
"UPDATE attachment_jobs SET state='superseded' WHERE job_id=%s "
|
||||
"AND state IN ('queued','processing','failed')",
|
||||
(j["job_id"],),
|
||||
)
|
||||
key = a["object_key"] if a["storage_state"] == "ready" else j["source_key"]
|
||||
job = new_id()
|
||||
conn.execute(
|
||||
"INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,source_key) "
|
||||
"VALUES (%s,%s,2,%s)",
|
||||
(job, attachment, key),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachments SET "
|
||||
"pipeline_version=2,storage_state='queued',variants='[]',"
|
||||
"error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",
|
||||
(attachment,),
|
||||
)
|
||||
event(conn, job, "new_version", previous_job=str(j["job_id"]))
|
||||
else:
|
||||
if j["state"] != "failed" or j["source_expired"]:
|
||||
raise ValueError("Replay requires failed job with retained source")
|
||||
job = str(j["job_id"])
|
||||
conn.execute(
|
||||
"UPDATE attachment_jobs SET "
|
||||
"state='queued',attempt=0,fence=NULL,error_code=NULL,"
|
||||
"next_attempt_at=clock_timestamp(),updated_at=clock_timestamp() WHERE "
|
||||
"job_id=%s",
|
||||
(job,),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachments SET storage_state='queued',error_code=NULL,"
|
||||
"updated_at=clock_timestamp() WHERE id=%s",
|
||||
(attachment,),
|
||||
)
|
||||
event(conn, job, "operator_replay")
|
||||
intent(conn, job)
|
||||
return job
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Transactional outbox publisher and expired-lease watchdog, independently restartable."""
|
||||
|
||||
import signal
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import redis
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from messenger import telemetry
|
||||
from messenger.broker import Broker, Job
|
||||
from messenger.domain import DomainError
|
||||
from messenger.faults import checkpoint
|
||||
from messenger.pipeline import Pipeline, event
|
||||
from messenger.repository import PostgresRepository, stamp
|
||||
from messenger.settings import Settings
|
||||
|
||||
|
||||
def publish_one(db, broker, settings):
|
||||
with db.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"SELECT o.job_id,j.attachment_id,j.pipeline_version,j.attempt,j.created_at,"
|
||||
"j.traceparent,j.tracestate "
|
||||
"FROM job_outbox o JOIN attachment_jobs j USING(job_id) "
|
||||
"WHERE o.published_at IS NULL AND o.due_at<=clock_timestamp() AND j.state='queued' "
|
||||
"ORDER BY o.due_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED"
|
||||
).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
with telemetry.span("jobs.publish", context=telemetry.context(row), kind=SpanKind.PRODUCER):
|
||||
job = Job(
|
||||
schema_version=1,
|
||||
type=telemetry.JOB_TYPE,
|
||||
job_id=str(row["job_id"]),
|
||||
attachment_id=str(row["attachment_id"]),
|
||||
pipeline_version=row["pipeline_version"],
|
||||
attempt=row["attempt"] + 1,
|
||||
created_at=stamp(row["created_at"]),
|
||||
**telemetry.carrier(),
|
||||
)
|
||||
stream_id = broker.publish(job)
|
||||
telemetry.event("job_published", job_id=job.job_id, attempt=job.attempt)
|
||||
# Commit-on-return may be lost here; repeat sends the same logical job_id.
|
||||
checkpoint(db, settings, row["job_id"], "after_publish")
|
||||
conn.execute(
|
||||
"UPDATE job_outbox SET published_at=clock_timestamp(),stream_id=%s WHERE job_id=%s",
|
||||
(stream_id, row["job_id"]),
|
||||
)
|
||||
event(conn, row["job_id"], "published", stream_id=stream_id, attempt=job.attempt)
|
||||
return True
|
||||
|
||||
|
||||
def sample_backlog(db):
|
||||
with db.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT count(*) AS depth, "
|
||||
"coalesce(extract(epoch FROM clock_timestamp()-min(created_at)),0) AS age "
|
||||
"FROM attachment_jobs WHERE state IN ('queued','processing')"
|
||||
).fetchone()
|
||||
telemetry.gauge("messenger.queue.depth", row["depth"], queue="attachment-jobs")
|
||||
telemetry.gauge(
|
||||
"messenger.queue.oldest", max(0, float(row["age"])), unit="s", queue="attachment-jobs"
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
with telemetry.active("relay"):
|
||||
run()
|
||||
|
||||
|
||||
def run():
|
||||
settings = Settings.from_env()
|
||||
db = PostgresRepository(settings.database_url, pool_size=4)
|
||||
db.open()
|
||||
broker = Broker(settings)
|
||||
pipeline = Pipeline(db, settings)
|
||||
running = True
|
||||
next_sample = 0.0
|
||||
|
||||
def stop(*_):
|
||||
nonlocal running
|
||||
running = False
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
while running:
|
||||
try:
|
||||
if telemetry.runtime is not None and time.monotonic() >= next_sample:
|
||||
sample_backlog(db)
|
||||
next_sample = time.monotonic() + 2
|
||||
pipeline.recover()
|
||||
sent = publish_one(db, broker, settings)
|
||||
Path("/tmp/relay-heartbeat").touch()
|
||||
if not sent:
|
||||
time.sleep(0.2)
|
||||
except redis.RedisError, DomainError:
|
||||
# Keep the transaction uncommitted and retry. No credentials/SQL in logs.
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
broker.close()
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,351 @@
|
||||
"""PostgreSQL adapter: bounded connections, parameterized SQL, commit before return."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests
|
||||
|
||||
from messenger import telemetry
|
||||
from messenger.domain import (
|
||||
Attachment,
|
||||
Chat,
|
||||
DomainError,
|
||||
HistoryKey,
|
||||
Message,
|
||||
User,
|
||||
invalid,
|
||||
new_id,
|
||||
)
|
||||
|
||||
|
||||
def stamp(value: datetime) -> str:
|
||||
return value.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_value(row) -> User:
|
||||
return User(str(row["id"]), row["username"], row["display_name"], stamp(row["created_at"]))
|
||||
|
||||
|
||||
def chat_value(row) -> Chat:
|
||||
return Chat(
|
||||
str(row["id"]),
|
||||
row["title"],
|
||||
tuple(str(x) for x in row["member_ids"]),
|
||||
stamp(row["created_at"]),
|
||||
)
|
||||
|
||||
|
||||
def message_value(row) -> Message:
|
||||
return Message(
|
||||
str(row["id"]),
|
||||
str(row["chat_id"]),
|
||||
str(row["sender_id"]),
|
||||
row["text"],
|
||||
stamp(row["created_at"]),
|
||||
tuple(str(x) for x in row.get("attachment_ids", ())),
|
||||
)
|
||||
|
||||
|
||||
def attachment_value(row) -> Attachment:
|
||||
return Attachment(
|
||||
*(str(row[k]) for k in ("id", "chat_id", "owner_id")),
|
||||
row["filename"],
|
||||
row["content_type"],
|
||||
row["size_bytes"],
|
||||
row["sha256"],
|
||||
stamp(row["created_at"]),
|
||||
stamp(row["updated_at"]),
|
||||
row["storage_state"],
|
||||
tuple(
|
||||
{k: v for k, v in item.items() if k != "object_key"} for item in row.get("variants", [])
|
||||
),
|
||||
row.get("error_code"),
|
||||
)
|
||||
|
||||
|
||||
class Repository(Protocol):
|
||||
def get_user(self, user_id: str) -> User | None: ...
|
||||
def add_chat(self, title: str, member_ids: tuple[str, ...]) -> Chat: ...
|
||||
def get_chat(self, chat_id: str) -> Chat | None: ...
|
||||
def page_chats(self, user_id: str, after: HistoryKey | None, limit: int) -> list[Chat]: ...
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> Message: ...
|
||||
def idempotent_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
sender_id: str,
|
||||
text: str,
|
||||
key: str,
|
||||
attachment_ids: tuple[str, ...] = (),
|
||||
) -> Message: ...
|
||||
def page_messages(
|
||||
self, chat_id: str, after: HistoryKey | None, limit: int
|
||||
) -> list[Message]: ...
|
||||
|
||||
|
||||
CHAT_COLUMNS = """c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY position) AS member_ids"""
|
||||
|
||||
|
||||
MESSAGE_COLUMNS = """m.*, ARRAY(SELECT attachment_id FROM message_attachments
|
||||
WHERE message_id=m.id ORDER BY position) AS attachment_ids"""
|
||||
|
||||
|
||||
class PostgresRepository:
|
||||
def __init__(
|
||||
self,
|
||||
conninfo: str,
|
||||
pool_size: int = 8,
|
||||
idempotency_ttl: int = 86400,
|
||||
read_autocommit: bool = True,
|
||||
):
|
||||
self.read_autocommit = read_autocommit
|
||||
self.idempotency_ttl = idempotency_ttl
|
||||
self.pool = ConnectionPool(
|
||||
conninfo,
|
||||
min_size=1,
|
||||
max_size=pool_size,
|
||||
timeout=1,
|
||||
max_waiting=32,
|
||||
open=False,
|
||||
check=ConnectionPool.check_connection,
|
||||
kwargs={
|
||||
"row_factory": dict_row,
|
||||
"autocommit": True,
|
||||
"connect_timeout": 2,
|
||||
"options": "-c statement_timeout=2500 -c lock_timeout=1000 "
|
||||
"-c idle_in_transaction_session_timeout=5000 -c timezone=UTC",
|
||||
},
|
||||
)
|
||||
|
||||
def open(self):
|
||||
self.pool.open(wait=True, timeout=15)
|
||||
|
||||
def close(self):
|
||||
self.pool.close(timeout=5)
|
||||
|
||||
@contextmanager
|
||||
def connection(self, *, write: bool = False):
|
||||
with telemetry.span(
|
||||
"db.transaction" if write else "db.read", **{"db.system.name": "postgresql"}
|
||||
):
|
||||
with self._connection(write=write) as conn:
|
||||
yield conn
|
||||
|
||||
@contextmanager
|
||||
def _connection(self, *, write):
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
transaction = (
|
||||
conn.transaction() if write or not self.read_autocommit else nullcontext()
|
||||
)
|
||||
with transaction:
|
||||
telemetry.pool(self.pool)
|
||||
yield conn
|
||||
except (
|
||||
psycopg.OperationalError,
|
||||
psycopg.InterfaceError,
|
||||
PoolTimeout,
|
||||
TooManyRequests,
|
||||
errors.QueryCanceled,
|
||||
errors.LockNotAvailable,
|
||||
):
|
||||
telemetry.pool(self.pool)
|
||||
telemetry.record("messenger.db.errors", 1)
|
||||
raise DomainError(503, "unavailable", "Хранилище временно недоступно") from None
|
||||
|
||||
def ready(self):
|
||||
with self.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT count(*) AS n FROM schema_migrations "
|
||||
"WHERE version IN "
|
||||
"('001_initial','002_idempotency','003_attachments',"
|
||||
"'004_pipeline','005_upload_handoff','006_trace_context')"
|
||||
).fetchone()
|
||||
if row["n"] != 6:
|
||||
raise DomainError(503, "unavailable", "Схема ещё не готова")
|
||||
|
||||
def add_user(self, username: str, display_name: str, password_hash: str) -> User:
|
||||
try:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO users (id,username,display_name,password_hash) "
|
||||
"VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(new_id(), username, display_name, password_hash),
|
||||
).fetchone()
|
||||
return user_value(row)
|
||||
except errors.UniqueViolation:
|
||||
raise DomainError(409, "conflict", "Имя пользователя уже занято") from None
|
||||
|
||||
def credentials(self, username: str):
|
||||
with self.connection() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
||||
return (user_value(row), row["password_hash"]) if row else None
|
||||
|
||||
def get_user(self, user_id: str) -> User | None:
|
||||
with self.connection() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE id=%s", (user_id,)).fetchone()
|
||||
return user_value(row) if row else None
|
||||
|
||||
def add_chat(self, title: str, member_ids: tuple[str, ...]) -> Chat:
|
||||
try:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO chats (id,title) VALUES (%s,%s) RETURNING *", (new_id(), title)
|
||||
).fetchone()
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id,user_id,position) VALUES (%s,%s,%s)",
|
||||
[(row["id"], member, i) for i, member in enumerate(member_ids)],
|
||||
)
|
||||
return Chat(str(row["id"]), title, member_ids, stamp(row["created_at"]))
|
||||
except errors.ForeignKeyViolation:
|
||||
raise invalid("Указан неизвестный участник") from None
|
||||
|
||||
def get_chat(self, chat_id: str) -> Chat | None:
|
||||
with self.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id=%s", (chat_id,)
|
||||
).fetchone()
|
||||
return chat_value(row) if row else None
|
||||
|
||||
def page_chats(self, user_id: str, after: HistoryKey | None, limit: int) -> list[Chat]:
|
||||
condition = " AND (c.created_at,c.id) > (%s::timestamptz,%s::uuid)" if after else ""
|
||||
params = (user_id, *after, limit) if after else (user_id, limit)
|
||||
with self.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + " FROM chats c WHERE EXISTS "
|
||||
"(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)"
|
||||
+ condition
|
||||
+ " ORDER BY c.created_at,c.id LIMIT %s",
|
||||
params,
|
||||
).fetchall()
|
||||
return [chat_value(row) for row in rows]
|
||||
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> Message:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(new_id(), chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
return message_value(row)
|
||||
|
||||
def page_messages(self, chat_id: str, after: HistoryKey | None, limit: int) -> list[Message]:
|
||||
condition = " AND (m.created_at,m.id) > (%s::timestamptz,%s::uuid)" if after else ""
|
||||
params = (chat_id, *after, limit) if after else (chat_id, limit)
|
||||
with self.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT "
|
||||
+ MESSAGE_COLUMNS
|
||||
+ " FROM messages m WHERE m.chat_id=%s"
|
||||
+ condition
|
||||
+ " ORDER BY m.created_at,m.id LIMIT %s",
|
||||
params,
|
||||
).fetchall()
|
||||
return [message_value(row) for row in rows]
|
||||
|
||||
def idempotent_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
sender_id: str,
|
||||
text: str,
|
||||
key: str,
|
||||
attachment_ids: tuple[str, ...] = (),
|
||||
) -> Message:
|
||||
scope = json.dumps([sender_id, "POST", chat_id, key], separators=(",", ":"))
|
||||
lock = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], "big", signed=True)
|
||||
payload = json.dumps(
|
||||
{"text": text, "attachment_ids": list(attachment_ids)},
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
digest = hashlib.sha256(payload.encode()).digest()
|
||||
with self.connection(write=True) as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock,))
|
||||
previous = conn.execute(
|
||||
"SELECT r.payload_hash," + MESSAGE_COLUMNS + " FROM message_requests r "
|
||||
"JOIN messages m ON m.id=r.response_message_id "
|
||||
"WHERE r.user_id=%s AND r.http_method='POST' AND r.chat_id=%s "
|
||||
"AND r.idempotency_key=%s AND r.expires_at > clock_timestamp()",
|
||||
(sender_id, chat_id, key),
|
||||
).fetchone()
|
||||
if previous:
|
||||
if previous["payload_hash"] != digest:
|
||||
raise DomainError(409, "conflict", "Ключ уже использован с другим сообщением")
|
||||
return message_value(previous)
|
||||
conn.execute(
|
||||
"DELETE FROM message_requests WHERE user_id=%s AND http_method='POST' "
|
||||
"AND chat_id=%s AND idempotency_key=%s",
|
||||
(sender_id, chat_id, key),
|
||||
)
|
||||
if attachment_ids:
|
||||
rows = conn.execute(
|
||||
"SELECT id,storage_state FROM attachments WHERE chat_id=%s "
|
||||
"AND id=ANY(%s::uuid[]) ORDER BY id FOR UPDATE",
|
||||
(chat_id, list(attachment_ids)),
|
||||
).fetchall()
|
||||
if len(rows) != len(attachment_ids):
|
||||
raise DomainError(404, "not_found", "Объект не найден")
|
||||
if any(row["storage_state"] == "failed" for row in rows):
|
||||
raise DomainError(409, "conflict", "Вложение пока недоступно")
|
||||
message = message_value(
|
||||
conn.execute(
|
||||
"INSERT INTO messages (id,chat_id,sender_id,text) "
|
||||
"VALUES (%s,%s,%s,%s) RETURNING *",
|
||||
(new_id(), chat_id, sender_id, text),
|
||||
).fetchone()
|
||||
)
|
||||
for position, attachment in enumerate(attachment_ids):
|
||||
conn.execute(
|
||||
"INSERT INTO message_attachments VALUES (%s,%s,%s,%s)",
|
||||
(message.id, chat_id, attachment, position),
|
||||
)
|
||||
message = Message(
|
||||
message.id,
|
||||
message.chat_id,
|
||||
message.sender_id,
|
||||
message.text,
|
||||
message.created_at,
|
||||
attachment_ids,
|
||||
)
|
||||
self._save_request(conn, sender_id, chat_id, key, digest, message.id)
|
||||
return message
|
||||
|
||||
def _save_request(self, conn, user_id, chat_id, key, digest, message_id):
|
||||
conn.execute(
|
||||
"INSERT INTO message_requests "
|
||||
"(user_id,chat_id,idempotency_key,payload_hash,response_message_id,expires_at) "
|
||||
"VALUES (%s,%s,%s,%s,%s,clock_timestamp()+make_interval(secs => %s))",
|
||||
(user_id, chat_id, key, digest, message_id, self.idempotency_ttl),
|
||||
)
|
||||
|
||||
def create_session(self, token_hash: bytes, user_id: str, ttl: int) -> str:
|
||||
with self.connection(write=True) as conn:
|
||||
row = conn.execute(
|
||||
"INSERT INTO sessions (token_hash,user_id,expires_at) "
|
||||
"VALUES (%s,%s,clock_timestamp() + make_interval(secs => %s)) RETURNING expires_at",
|
||||
(token_hash, user_id, ttl),
|
||||
).fetchone()
|
||||
return stamp(row["expires_at"])
|
||||
|
||||
def active_session(self, token_hash: bytes):
|
||||
with self.connection() as conn:
|
||||
return conn.execute(
|
||||
"SELECT user_id,expires_at,clock_timestamp() AS checked_at FROM sessions "
|
||||
"WHERE token_hash=%s AND expires_at > clock_timestamp()",
|
||||
(token_hash,),
|
||||
).fetchone()
|
||||
|
||||
def revoke_session(self, token_hash: bytes):
|
||||
with self.connection(write=True) as conn:
|
||||
conn.execute("DELETE FROM sessions WHERE token_hash=%s", (token_hash,))
|
||||
|
||||
def attachment(self, id):
|
||||
with self.connection() as conn:
|
||||
return conn.execute("SELECT * FROM attachments WHERE id=%s", (id,)).fetchone()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Strict lab 5 wire types; password never belongs to a response User."""
|
||||
|
||||
import re
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
def canonical_uuid(value: str) -> str:
|
||||
if not re.fullmatch(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", value):
|
||||
raise ValueError("Ожидается UUID")
|
||||
return str(UUID(value))
|
||||
|
||||
|
||||
def nonblank(value: str) -> str:
|
||||
if not value.strip() or any(0xD800 <= ord(char) <= 0xDFFF for char in value):
|
||||
raise ValueError("Ожидается непустая строка Unicode")
|
||||
return value
|
||||
|
||||
|
||||
type Identifier = Annotated[str, AfterValidator(canonical_uuid)]
|
||||
type ShortText = Annotated[str, Field(min_length=1, max_length=100), AfterValidator(nonblank)]
|
||||
|
||||
|
||||
class Input(BaseModel):
|
||||
model_config = ConfigDict(strict=True, extra="forbid")
|
||||
|
||||
|
||||
class CreateUser(Input):
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: ShortText
|
||||
password: Annotated[str, Field(min_length=12, max_length=128), AfterValidator(nonblank)]
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def valid_username(cls, value: str) -> str:
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", value):
|
||||
raise ValueError("Недопустимое имя пользователя")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(Input):
|
||||
title: ShortText
|
||||
member_ids: list[Identifier] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class CreateMessage(Input):
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[Identifier] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_content(self):
|
||||
if (
|
||||
not self.text.strip()
|
||||
and not self.attachment_ids
|
||||
or any(0xD800 <= ord(c) <= 0xDFFF for c in self.text)
|
||||
or len(set(self.attachment_ids)) != len(self.attachment_ids)
|
||||
):
|
||||
raise ValueError("Некорректное содержимое сообщения")
|
||||
return self
|
||||
|
||||
|
||||
class View(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True, extra="forbid")
|
||||
|
||||
|
||||
class UserView(View):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class SessionView(View):
|
||||
token: str
|
||||
token_type: str
|
||||
expires_at: str
|
||||
user: UserView
|
||||
|
||||
|
||||
class ChatView(View):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: list[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class MessageView(View):
|
||||
attachment_ids: list[str]
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(View):
|
||||
items: list[ChatView]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class MessagePage(View):
|
||||
items: list[MessageView]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class AttachmentView(View):
|
||||
id: str
|
||||
chat_id: str
|
||||
owner_id: str
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: list
|
||||
error_code: str | None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Use cases shared by HTTP and tests. Authorization precedes resource access."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from messenger.cursor import decode_cursor, encode_cursor
|
||||
from messenger.domain import Chat, Message, User, history_key, invalid, not_found
|
||||
from messenger.repository import Repository
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Page[T]:
|
||||
items: list[T]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class Messenger:
|
||||
def __init__(self, repository: Repository):
|
||||
self.repository = repository
|
||||
|
||||
def create_chat(self, actor: User, title: str, member_ids: list[str]) -> Chat:
|
||||
if len(member_ids) != len(set(member_ids)) or actor.id not in member_ids:
|
||||
raise invalid("Участники не должны повторяться; вызывающий должен входить в чат")
|
||||
return self.repository.add_chat(title, tuple(member_ids))
|
||||
|
||||
def chat(self, actor: User, chat_id: str) -> Chat:
|
||||
chat = self.repository.get_chat(chat_id)
|
||||
if chat is None or actor.id not in chat.member_ids:
|
||||
raise not_found()
|
||||
return chat
|
||||
|
||||
def chats(self, actor: User, limit: int, cursor: str | None) -> Page[Chat]:
|
||||
scope = "chats:" + actor.id
|
||||
after = decode_cursor(cursor, scope)
|
||||
return self._page(self.repository.page_chats(actor.id, after, limit + 1), limit, scope)
|
||||
|
||||
def send(
|
||||
self, actor: User, chat_id: str, text: str, key: str, attachments: tuple[str, ...] = ()
|
||||
) -> Message:
|
||||
self.chat(actor, chat_id)
|
||||
return self.repository.idempotent_message(chat_id, actor.id, text, key, attachments)
|
||||
|
||||
def messages(self, actor: User, chat_id: str, limit: int, cursor: str | None) -> Page[Message]:
|
||||
self.chat(actor, chat_id)
|
||||
scope = "messages:" + chat_id
|
||||
after = decode_cursor(cursor, scope)
|
||||
return self._page(self.repository.page_messages(chat_id, after, limit + 1), limit, scope)
|
||||
|
||||
@staticmethod
|
||||
def _page[T: Chat | Message](items: list[T], limit: int, scope: str) -> Page[T]:
|
||||
visible = items[:limit]
|
||||
cursor = encode_cursor(scope, history_key(visible[-1])) if len(items) > limit else None
|
||||
return Page(visible, cursor)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Explicit configuration; credentials are read from untracked secret files."""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def secret(name: str, default: str, optional=False) -> str:
|
||||
path = Path(os.getenv(name, default))
|
||||
return path.read_text().strip() if path.exists() or not optional else ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
database_url: str = field(repr=False)
|
||||
cache_url: str = field(repr=False)
|
||||
session_ttl: int = 3600
|
||||
pool_size: int = 8
|
||||
idempotency_ttl: int = 86400
|
||||
read_autocommit: bool = True
|
||||
|
||||
s3_endpoint: str = "http://127.0.0.1:59006"
|
||||
s3_region: str = "us-east-1"
|
||||
s3_bucket: str = "messenger-attachments"
|
||||
s3_access_key: str = field(default="", repr=False)
|
||||
s3_secret_key: str = field(default="", repr=False)
|
||||
max_upload_bytes: int = 10485760
|
||||
max_image_pixels: int = 40000000
|
||||
upload_slots: int = 1
|
||||
|
||||
broker_url: str = field(default="redis://broker:6379/0", repr=False)
|
||||
worker_concurrency: int = 2
|
||||
job_max_attempts: int = 5
|
||||
job_timeout: int = 20
|
||||
staging_retention: int = 86400
|
||||
fault_injection: bool = False
|
||||
|
||||
@property
|
||||
def lease_seconds(self):
|
||||
return self.job_timeout + 3
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
size = int(os.getenv("DATABASE_POOL_SIZE", "8"))
|
||||
idempotency_ttl = int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if idempotency_ttl < 86400:
|
||||
raise ValueError("Idempotency retention must be at least 24 hours")
|
||||
if not 1 <= ttl <= 2_592_000 or not 1 <= size <= 32:
|
||||
raise ValueError("Invalid session lifetime or connection pool size")
|
||||
maximum = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||
pixels = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||
if not 1 <= maximum <= 10485760 or not 1 <= pixels <= 40000000:
|
||||
raise ValueError("Invalid upload limits")
|
||||
concurrency = int(os.getenv("WORKER_CONCURRENCY", "2"))
|
||||
attempts = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||
timeout = int(os.getenv("JOB_TIMEOUT_SECONDS", "20"))
|
||||
retention = int(os.getenv("STAGING_RETENTION_SECONDS", "86400"))
|
||||
if not 1 <= concurrency <= 4 or not 1 <= attempts <= 10 or not 2 <= timeout <= 120:
|
||||
raise ValueError("Invalid worker limits")
|
||||
if retention < 300:
|
||||
raise ValueError("Staging retention must be at least 300 seconds")
|
||||
return cls(
|
||||
secret("DATABASE_URL_FILE", "/run/secrets/database_url"),
|
||||
secret("CACHE_URL_FILE", "/run/secrets/cache_url"),
|
||||
ttl,
|
||||
size,
|
||||
idempotency_ttl,
|
||||
os.getenv("DATABASE_READ_AUTOCOMMIT", "1") == "1",
|
||||
os.getenv("S3_ENDPOINT", "http://s3:9000"),
|
||||
os.getenv("S3_REGION", "us-east-1"),
|
||||
os.getenv("S3_BUCKET", "messenger-attachments"),
|
||||
secret("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_access_key_id", optional=True),
|
||||
secret("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_secret_access_key", optional=True),
|
||||
maximum,
|
||||
pixels,
|
||||
broker_url=secret("BROKER_URL_FILE", "/run/secrets/broker_url")
|
||||
if os.path.exists(os.getenv("BROKER_URL_FILE", "/run/secrets/broker_url"))
|
||||
else "redis://broker:6379/0",
|
||||
worker_concurrency=concurrency,
|
||||
job_max_attempts=attempts,
|
||||
job_timeout=timeout,
|
||||
staging_retention=retention,
|
||||
fault_injection=os.getenv("ENABLE_FAULT_INJECTION", "0") == "1",
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""S3 adapter: bounded sockets, least-privilege credentials, no automatic PUT retries."""
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from messenger import telemetry
|
||||
from messenger.domain import DomainError
|
||||
|
||||
|
||||
def unavailable():
|
||||
return DomainError(503, "unavailable", "Файловое хранилище временно недоступно")
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self, settings):
|
||||
self.bucket = settings.s3_bucket
|
||||
self.client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
region_name=settings.s3_region,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
config=Config(
|
||||
connect_timeout=0.5,
|
||||
read_timeout=2,
|
||||
max_pool_connections=8,
|
||||
retries={"total_max_attempts": 1},
|
||||
s3={"addressing_style": "path"},
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
),
|
||||
)
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
self.client.head_bucket(Bucket=self.bucket)
|
||||
except BotoCoreError, ClientError:
|
||||
raise unavailable() from None
|
||||
|
||||
def put(self, key, file, size, media, digest):
|
||||
with telemetry.span("s3.put"):
|
||||
try:
|
||||
self.client.put_object(
|
||||
Bucket=self.bucket,
|
||||
Key=key,
|
||||
Body=file,
|
||||
ContentLength=size,
|
||||
ContentType=media,
|
||||
Metadata={"sha256": digest},
|
||||
)
|
||||
except BotoCoreError, ClientError:
|
||||
raise unavailable() from None
|
||||
|
||||
def head(self, key):
|
||||
with telemetry.span("s3.head"):
|
||||
try:
|
||||
return self.client.head_object(Bucket=self.bucket, Key=key)
|
||||
except ClientError as exc:
|
||||
if str(exc.response.get("Error", {}).get("Code")) in (
|
||||
"404",
|
||||
"NoSuchKey",
|
||||
"NotFound",
|
||||
):
|
||||
return None
|
||||
raise unavailable() from None
|
||||
except BotoCoreError:
|
||||
raise unavailable() from None
|
||||
|
||||
def download(self, row):
|
||||
with telemetry.span("s3.download"):
|
||||
try:
|
||||
response = self.client.get_object(Bucket=self.bucket, Key=row["object_key"])
|
||||
if response["ContentLength"] != row["size_bytes"]:
|
||||
response["Body"].close()
|
||||
raise unavailable()
|
||||
return response["Body"]
|
||||
except BotoCoreError, ClientError:
|
||||
raise unavailable() from None
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Application telemetry with bounded export and an explicit attribute allowlist."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from importlib.metadata import version
|
||||
from uuid import uuid4
|
||||
|
||||
from opentelemetry import trace
|
||||
from opentelemetry._logs import LogRecord, SeverityNumber
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.metrics import Observation
|
||||
from opentelemetry.sdk._logs import LoggerProvider
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
PROPAGATOR = TraceContextTextMapPropagator()
|
||||
BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120)
|
||||
HTTP_METHODS = frozenset(("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"))
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
runtime = None
|
||||
|
||||
|
||||
class Telemetry:
|
||||
def __init__(self, role, instance, metrics):
|
||||
resource_attrs = Resource(
|
||||
{
|
||||
"service.name": f"messenger-{role}",
|
||||
"service.version": version("mtusi-messenger"),
|
||||
"service.instance.id": instance,
|
||||
"deployment.environment.name": "lab",
|
||||
}
|
||||
)
|
||||
ratio = float(os.getenv("OTEL_SAMPLE_RATIO", "1"))
|
||||
self.traces = TracerProvider(
|
||||
resource=resource_attrs, sampler=ParentBased(TraceIdRatioBased(ratio))
|
||||
)
|
||||
self.traces.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
OTLPSpanExporter(timeout=1),
|
||||
max_queue_size=512,
|
||||
max_export_batch_size=64,
|
||||
schedule_delay_millis=500,
|
||||
)
|
||||
)
|
||||
self.tracer = self.traces.get_tracer("messenger")
|
||||
self.logs = LoggerProvider(resource=resource_attrs)
|
||||
self.logs.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(timeout=1),
|
||||
max_queue_size=512,
|
||||
max_export_batch_size=64,
|
||||
schedule_delay_millis=500,
|
||||
)
|
||||
)
|
||||
self.log = self.logs.get_logger("messenger")
|
||||
self.meters = None
|
||||
self.instruments = {}
|
||||
if metrics:
|
||||
self.meters = MeterProvider(
|
||||
resource=resource_attrs,
|
||||
metric_readers=[
|
||||
PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(timeout=1),
|
||||
export_interval_millis=2000,
|
||||
export_timeout_millis=1000,
|
||||
)
|
||||
],
|
||||
views=[
|
||||
View(
|
||||
instrument_name="messenger.*.duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(BUCKETS),
|
||||
)
|
||||
],
|
||||
)
|
||||
self.meter = self.meters.get_meter("messenger")
|
||||
self.meter.create_observable_counter(
|
||||
"messenger.process.cpu", unit="s", callbacks=[self.cpu_seconds]
|
||||
)
|
||||
self.meter.create_observable_gauge(
|
||||
"messenger.process.rss", unit="By", callbacks=[self.rss_bytes]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def cpu_seconds(_):
|
||||
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
yield Observation(time.process_time() + usage.ru_utime + usage.ru_stime)
|
||||
|
||||
@staticmethod
|
||||
def rss_bytes(_):
|
||||
try:
|
||||
with open("/proc/self/statm", encoding="ascii") as stats:
|
||||
yield Observation(int(stats.read().split()[1]) * os.sysconf("SC_PAGE_SIZE"))
|
||||
except OSError:
|
||||
return
|
||||
|
||||
def shutdown(self):
|
||||
if self.meters:
|
||||
self.meters.shutdown(timeout_millis=1500)
|
||||
self.logs.shutdown()
|
||||
self.traces.shutdown()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def active(role, instance=None, *, metrics=True):
|
||||
global runtime
|
||||
if os.getenv("TELEMETRY_ENABLED", "0") != "1":
|
||||
yield
|
||||
return
|
||||
runtime = Telemetry(role, instance or uuid4().hex, metrics)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
state, runtime = runtime, None
|
||||
state.shutdown()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def span(name, *, context=None, kind=SpanKind.INTERNAL, **attrs):
|
||||
if runtime is None:
|
||||
yield trace.INVALID_SPAN
|
||||
return
|
||||
with runtime.tracer.start_as_current_span(
|
||||
name,
|
||||
context=context,
|
||||
kind=kind,
|
||||
attributes=attrs,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as current:
|
||||
try:
|
||||
yield current
|
||||
except Exception as exc:
|
||||
current.set_attribute("error.type", type(exc).__name__)
|
||||
current.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
|
||||
def carrier():
|
||||
result = {}
|
||||
if runtime is not None:
|
||||
PROPAGATOR.inject(result)
|
||||
return result
|
||||
|
||||
|
||||
def context(headers):
|
||||
return PROPAGATOR.extract(
|
||||
{k: headers[k] for k in ("traceparent", "tracestate") if headers.get(k)}
|
||||
)
|
||||
|
||||
|
||||
def record(name, value, *, kind="counter", unit="1", **attrs):
|
||||
if runtime is None or runtime.meters is None:
|
||||
return
|
||||
instrument = runtime.instruments.get(name)
|
||||
if instrument is None:
|
||||
create = {
|
||||
"counter": runtime.meter.create_counter,
|
||||
"histogram": runtime.meter.create_histogram,
|
||||
"gauge": runtime.meter.create_gauge,
|
||||
}[kind]
|
||||
instrument = runtime.instruments.setdefault(name, create(name, unit=unit))
|
||||
if kind == "counter":
|
||||
instrument.add(value, attrs)
|
||||
elif kind == "histogram":
|
||||
instrument.record(value, attrs)
|
||||
else:
|
||||
instrument.set(value, attrs)
|
||||
|
||||
|
||||
def duration(name, seconds, **attrs):
|
||||
record(name, seconds, kind="histogram", unit="s", **attrs)
|
||||
|
||||
|
||||
def gauge(name, value, *, unit="", **attrs):
|
||||
record(name, value, kind="gauge", unit=unit, **attrs)
|
||||
|
||||
|
||||
def pool(pool):
|
||||
if runtime is not None and runtime.meters is not None:
|
||||
stats = pool.get_stats()
|
||||
gauge(
|
||||
"messenger.db.pool.used",
|
||||
max(0, stats["pool_size"] - stats["pool_available"]),
|
||||
)
|
||||
gauge("messenger.db.pool.waiting", stats["requests_waiting"])
|
||||
|
||||
|
||||
def event(event_name, *, error=False, **attrs):
|
||||
fields = {"event": event_name, **attrs}
|
||||
current = trace.get_current_span().get_span_context()
|
||||
if current.is_valid:
|
||||
fields["trace_id"] = format(current.trace_id, "032x")
|
||||
fields["span_id"] = format(current.span_id, "016x")
|
||||
logger.log(logging.ERROR if error else logging.INFO, json.dumps(fields))
|
||||
if runtime is not None:
|
||||
runtime.log.emit(
|
||||
LogRecord(
|
||||
timestamp=time.time_ns(),
|
||||
observed_timestamp=time.time_ns(),
|
||||
severity_text="ERROR" if error else "INFO",
|
||||
severity_number=SeverityNumber.ERROR if error else SeverityNumber.INFO,
|
||||
body=event_name,
|
||||
attributes=fields,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def http(current, method, route, status, elapsed, request_id):
|
||||
method = method if method in HTTP_METHODS else "_OTHER"
|
||||
attrs = {"method": method, "route": route, "status_class": f"{status // 100}xx"}
|
||||
current.update_name(f"{method} {route}")
|
||||
current.set_attributes(
|
||||
{"http.request.method": method, "http.route": route, "http.response.status_code": status}
|
||||
)
|
||||
if status >= 500:
|
||||
current.set_status(Status(StatusCode.ERROR))
|
||||
record("messenger.http.requests", 1, **attrs)
|
||||
duration("messenger.http.duration", elapsed, **attrs)
|
||||
event(
|
||||
"http_request",
|
||||
error=status >= 500,
|
||||
request_id=request_id,
|
||||
status=status,
|
||||
duration_ms=round(elapsed * 1000, 3),
|
||||
**attrs,
|
||||
)
|
||||
@@ -0,0 +1,270 @@
|
||||
"""Bounded supervisor: one disposable OS process per job, hard wall-clock and RAM limits."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import multiprocessing
|
||||
import resource
|
||||
import signal
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import redis
|
||||
from opentelemetry.trace import SpanKind
|
||||
from pydantic import ValidationError
|
||||
|
||||
from messenger import telemetry
|
||||
from messenger.attachments import image_type
|
||||
from messenger.broker import GROUP, STREAM, Broker, Job
|
||||
from messenger.domain import DomainError
|
||||
from messenger.faults import PermanentFailure, checkpoint
|
||||
from messenger.images import variants
|
||||
from messenger.pipeline import Pipeline, event
|
||||
from messenger.repository import PostgresRepository
|
||||
from messenger.settings import Settings
|
||||
from messenger.storage import ObjectStore
|
||||
|
||||
|
||||
def verify_effect(store, row):
|
||||
records = [row, *row["variants"]]
|
||||
if len(records) != 4 or {v["name"] for v in row["variants"]} != {
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized",
|
||||
}:
|
||||
raise DomainError(503, "unavailable", "Incomplete result")
|
||||
for item in records:
|
||||
head = store.head(item["object_key"])
|
||||
if (
|
||||
not head
|
||||
or head["ContentLength"] != item["size_bytes"]
|
||||
or head["Metadata"].get("sha256") != item["sha256"]
|
||||
):
|
||||
raise DomainError(503, "unavailable", "Incomplete result")
|
||||
|
||||
|
||||
def handle(db, broker, store, settings, id, payload):
|
||||
try:
|
||||
job = Job.model_validate_json(payload)
|
||||
except ValidationError:
|
||||
broker.quarantine(id, "invalid_envelope")
|
||||
return "invalid", None
|
||||
context = telemetry.context(job.model_dump(include={"traceparent", "tracestate"}))
|
||||
with telemetry.span(
|
||||
"jobs.consume",
|
||||
context=context,
|
||||
kind=SpanKind.CONSUMER,
|
||||
**{"messaging.destination.name": STREAM},
|
||||
) as span:
|
||||
outcome, age = process_job(db, broker, store, settings, id, job)
|
||||
span.set_attribute("job.outcome", outcome)
|
||||
telemetry.event(
|
||||
"job_processed",
|
||||
job_id=job.job_id,
|
||||
attempt=job.attempt,
|
||||
outcome=outcome,
|
||||
error=outcome in {"retry", "failed"},
|
||||
)
|
||||
return outcome, age
|
||||
|
||||
|
||||
def process_job(db, broker, store, settings, id, job):
|
||||
pipeline = Pipeline(db, settings)
|
||||
outcome, row = pipeline.claim(job)
|
||||
if outcome == "busy":
|
||||
return "busy", None # Watchdog recovers the lease.
|
||||
if outcome == "unknown":
|
||||
broker.quarantine(id, "unknown_job")
|
||||
return "unknown", None
|
||||
if outcome == "ready":
|
||||
verify_effect(store, row)
|
||||
broker.ack(id)
|
||||
return "duplicate", None
|
||||
if outcome != "claimed":
|
||||
broker.ack(id) # Failed registry / obsolete version / durable retry owns this work.
|
||||
return outcome, None
|
||||
try:
|
||||
checkpoint(db, settings, job.job_id, "before_effect")
|
||||
with tempfile.TemporaryFile() as original:
|
||||
body = store.download({**row, "object_key": row["source_key"]})
|
||||
size, digest = 0, hashlib.sha256()
|
||||
try:
|
||||
while chunk := body.read(65536):
|
||||
size += len(chunk)
|
||||
if size > settings.max_upload_bytes:
|
||||
raise PermanentFailure
|
||||
digest.update(chunk)
|
||||
original.write(chunk)
|
||||
finally:
|
||||
body.close()
|
||||
if size != row["size_bytes"] or digest.hexdigest() != row["sha256"]:
|
||||
raise PermanentFailure
|
||||
image_type(original, settings.max_image_pixels)
|
||||
prefix = f"objects/{row['id']}/v{row['pipeline_version']}/"
|
||||
original_key = prefix + "original"
|
||||
store.put(original_key, original, size, row["content_type"], digest.hexdigest())
|
||||
checkpoint(db, settings, job.job_id, "after_effect")
|
||||
records = []
|
||||
for name, data, (width, height), media in variants(original, row["pipeline_version"]):
|
||||
checksum = hashlib.sha256(data).hexdigest()
|
||||
key = prefix + name
|
||||
store.put(key, io.BytesIO(data), len(data), media, checksum)
|
||||
records.append(
|
||||
{
|
||||
"name": name,
|
||||
"content_type": media,
|
||||
"size_bytes": len(data),
|
||||
"sha256": checksum,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"object_key": key,
|
||||
}
|
||||
)
|
||||
with db.connection(write=True) as conn:
|
||||
event(conn, job.job_id, "objects_written", version=row["pipeline_version"])
|
||||
committed = pipeline.publish(row, original_key, records)
|
||||
age = max(0.0, (datetime.now(UTC) - row["accepted_at"]).total_seconds())
|
||||
if committed:
|
||||
checkpoint(db, settings, job.job_id, "after_commit")
|
||||
broker.ack(id)
|
||||
return ("ready", age) if committed else ("fenced", None)
|
||||
except PermanentFailure:
|
||||
outcome = pipeline.failure(row, "invalid_image", permanent=True)
|
||||
broker.ack(id)
|
||||
return outcome, None
|
||||
except MemoryError:
|
||||
outcome = pipeline.failure(row, "resource_limit", permanent=True)
|
||||
broker.ack(id)
|
||||
return outcome, None
|
||||
except DomainError as exc:
|
||||
outcome = pipeline.failure(
|
||||
row,
|
||||
"invalid_image" if exc.status in (413, 415) else "storage_unavailable",
|
||||
permanent=exc.status in (413, 415),
|
||||
)
|
||||
broker.ack(id)
|
||||
return outcome, None
|
||||
except redis.RedisError:
|
||||
# Result may already be committed; retain the pending entry for a verified no-op.
|
||||
raise
|
||||
except Exception:
|
||||
outcome = pipeline.failure(row, "processing_failed")
|
||||
broker.ack(id)
|
||||
return outcome, None
|
||||
|
||||
|
||||
def child(settings, id, payload, result, instance):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with telemetry.active("worker", instance, metrics=False):
|
||||
outcome, age = run_child(settings, id, payload)
|
||||
result.send((outcome, age, time.monotonic() - start))
|
||||
finally:
|
||||
result.close()
|
||||
|
||||
|
||||
def run_child(settings, id, payload):
|
||||
# Linux hard limit includes Pillow buffers and native allocations. Supervisor kills hangs.
|
||||
resource.setrlimit(resource.RLIMIT_AS, (768 * 1024**2, 768 * 1024**2))
|
||||
db = PostgresRepository(settings.database_url, pool_size=2)
|
||||
db.open()
|
||||
broker, store = Broker(settings), ObjectStore(settings)
|
||||
try:
|
||||
return handle(db, broker, store, settings, id, payload)
|
||||
except redis.RedisError, DomainError:
|
||||
return "dependency_error", None # Leave pending; omit driver details.
|
||||
finally:
|
||||
store.close()
|
||||
broker.close()
|
||||
db.close()
|
||||
|
||||
|
||||
def observe(result, elapsed, timed_out):
|
||||
try:
|
||||
outcome, age, duration = result.recv() if result.poll() else ("crashed", None, elapsed)
|
||||
except EOFError:
|
||||
outcome, age, duration = "crashed", None, elapsed
|
||||
finally:
|
||||
result.close()
|
||||
if timed_out:
|
||||
outcome = "timeout"
|
||||
attrs = {"job_type": telemetry.JOB_TYPE, "outcome": outcome}
|
||||
telemetry.record("messenger.jobs.processed", 1, **attrs)
|
||||
telemetry.duration("messenger.jobs.duration", duration, **attrs)
|
||||
if age is not None:
|
||||
telemetry.duration("messenger.ready.duration", age, job_type=telemetry.JOB_TYPE)
|
||||
|
||||
|
||||
def main():
|
||||
instance = uuid4().hex
|
||||
with telemetry.active("worker", instance):
|
||||
run(instance)
|
||||
|
||||
|
||||
def run(instance):
|
||||
settings = Settings.from_env()
|
||||
broker = Broker(settings)
|
||||
consumer, cursor = uuid4().hex, "0-0"
|
||||
context = multiprocessing.get_context("spawn")
|
||||
active, running = [], True
|
||||
|
||||
def stop(*_):
|
||||
nonlocal running
|
||||
running = False
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
while running:
|
||||
for task in active[:]:
|
||||
process, result, started = task
|
||||
elapsed = time.monotonic() - started
|
||||
alive = process.is_alive()
|
||||
if not alive or elapsed > settings.job_timeout:
|
||||
if alive:
|
||||
process.kill()
|
||||
process.join()
|
||||
observe(result, elapsed, alive)
|
||||
active.remove(task)
|
||||
process.close()
|
||||
telemetry.gauge("messenger.worker.busy", len(active))
|
||||
telemetry.gauge("messenger.worker.capacity", settings.worker_concurrency)
|
||||
Path("/tmp/worker-heartbeat").touch()
|
||||
if len(active) >= settings.worker_concurrency:
|
||||
time.sleep(0.05)
|
||||
continue
|
||||
try:
|
||||
broker.group()
|
||||
reclaimed = broker.client.xautoclaim(
|
||||
STREAM, GROUP, consumer, settings.lease_seconds * 1000, cursor, count=1
|
||||
)
|
||||
cursor, entries = reclaimed[0], reclaimed[1]
|
||||
if not entries:
|
||||
result = broker.client.xreadgroup(
|
||||
GROUP, consumer, {STREAM: ">"}, count=1, block=200
|
||||
)
|
||||
entries = result[0][1] if result else []
|
||||
if entries:
|
||||
id, fields = entries[0]
|
||||
result, sender = context.Pipe(duplex=False)
|
||||
process = context.Process(
|
||||
target=child, args=(settings, id, fields.get("job", ""), sender, instance)
|
||||
)
|
||||
process.start()
|
||||
sender.close()
|
||||
active.append((process, result, time.monotonic()))
|
||||
except redis.RedisError:
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
for process, result, _ in active:
|
||||
result.close()
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join()
|
||||
broker.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user