Implement bounded OTLP observability across API and asynchronous image pipeline

This commit is contained in:
2026-11-15 22:30:03 +03:00
parent 470d9d6f1e
commit 2701db5106
60 changed files with 6118 additions and 49 deletions
+1
View File
@@ -0,0 +1 @@
"""Учебный REST-мессенджер."""
+12
View File
@@ -0,0 +1,12 @@
import os
import uvicorn
uvicorn.run(
"messenger.app:app",
host=os.getenv("APP_HOST", "0.0.0.0"),
port=int(os.getenv("APP_PORT", "8080")),
workers=1,
access_log=False,
timeout_graceful_shutdown=5,
)
+346
View File
@@ -0,0 +1,346 @@
import base64
import binascii
import json
import logging
import os
import re
import time
from contextlib import asynccontextmanager
from threading import BoundedSemaphore
from uuid import uuid4
from fastapi import Depends, FastAPI, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from opentelemetry import propagate
from opentelemetry.trace import SpanKind, Status, StatusCode
from starlette.exceptions import HTTPException
from . import telemetry
from .attachments import AttachmentService
from .domain import Failure, boundary, identifier, page
from .models import CreateChat, CreateMessage, CreateUser
from .postgres import PostgresStore
from .storage import ObjectStorage
logger = logging.getLogger("messenger")
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"), format="%(message)s")
INSTANCE_ID = str(uuid4())
CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
500: "internal_error",
}
@asynccontextmanager
async def lifespan(app):
app.state.telemetry = telemetry.setup("messenger-api")
app.state.store = PostgresStore()
app.state.telemetry.start_background(app.state.store)
app.state.storage = ObjectStorage()
app.state.attachments = AttachmentService(app.state.store, app.state.storage)
app.state.upload_slots = BoundedSemaphore(1)
logger.info(json.dumps({"event": "started", "storage": "postgres"}))
yield
app.state.storage.close()
app.state.store.close()
logger.info(json.dumps({"event": "stopped"}))
app.state.telemetry.close()
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
def error(request, status, message, headers=None):
return JSONResponse(
{
"error": {
"code": CODES.get(status, "invalid_request"),
"message": message,
"request_id": request.state.request_id,
}
},
status_code=status,
headers=headers,
)
async def invalid_json_encoding(request: Request):
path = request.url.path
if request.method != "POST" or not (
path in {"/api/v1/users", "/api/v1/chats"}
or re.fullmatch(r"/api/v1/chats/[^/]+/messages", path)
):
return False
raw = await request.body()
try:
raw.decode("utf-8")
except UnicodeDecodeError:
return True
# Literal NUL is invalid JSON; it also prevents json.loads(bytes) from
# autodetecting BOM-less UTF-16/32. Escaped JSON \u0000 remains valid.
return b"\x00" in raw
@app.middleware("http")
async def request_log(request: Request, call_next):
request.state.request_id = str(uuid4())
start = time.perf_counter()
observed = not request.url.path.startswith("/health/")
if not observed:
response = await call_next(request)
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
context = propagate.extract(dict(request.headers))
with telemetry.operation("HTTP " + request.method, context=context, kind=SpanKind.SERVER) as span:
try:
if (request.method == "POST" and request.url.path == "/api/v1/auth/sessions"
and await request.body()):
response = error(request, 400, "Вход не принимает тело запроса")
elif await invalid_json_encoding(request):
response = error(request, 400, "JSON должен быть закодирован в UTF-8")
else:
response = await call_next(request)
except Exception:
logger.error(json.dumps({"event": "unexpected_error", "request_id": request.state.request_id}))
response = error(request, 500, "Внутренняя ошибка")
response.headers["X-Request-Id"] = request.state.request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
route = getattr(request.scope.get("route"), "path", "unknown")
elapsed = time.perf_counter() - start
attrs = {"method": request.method, "route": route,
"status_class": str(response.status_code // 100) + "xx"}
span.update_name(request.method + " " + route)
span.set_attributes({"http.request.method": request.method, "http.route": route,
"http.response.status_code": response.status_code})
if response.status_code >= 500:
span.set_status(Status(StatusCode.ERROR, "server_error"))
t = telemetry.current()
if observed and t:
t.requests.add(1, attrs)
t.http_duration.record(elapsed, attrs)
t.sampling.add(1, {"decision": "sampled" if span.is_recording() else "not_sampled"})
logger.info(json.dumps({"event": "request", "request_id": request.state.request_id,
**attrs, "status": response.status_code,
"duration_ms": round(elapsed * 1000, 3)}))
return response
@app.exception_handler(Failure)
async def domain_error(request, exc):
return error(request, exc.status, exc.message, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_error(request, exc):
return error(request, 400, "Неверный JSON или поля запроса")
@app.exception_handler(HTTPException)
async def http_error(request, exc):
return error(request, exc.status_code, "Неверный запрос", exc.headers)
def bearer_failure():
return Failure(
401, "Требуется действующая сессия", {"WWW-Authenticate": 'Bearer realm="messenger"'}
)
def bearer(request):
parts = request.headers.get("Authorization", "").split()
if len(parts) != 2 or parts[0].lower() != "bearer":
raise bearer_failure()
return parts[1]
def actor(request: Request):
user = request.app.state.store.authenticate(bearer(request))
if user is None:
raise bearer_failure()
return user
@app.post("/api/v1/auth/sessions", status_code=201)
def login(request: Request):
headers = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
parts = request.headers.get("Authorization", "").split()
try:
if len(parts) != 2 or parts[0].lower() != "basic" or len(parts[1]) > 2048:
raise ValueError
decoded = base64.b64decode(parts[1], validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
raise ValueError
except (ValueError, UnicodeError, binascii.Error):
raise Failure(401, "Неверные учётные данные", headers) from None
session = request.app.state.store.login(username, password)
if session is None:
raise Failure(401, "Неверные учётные данные", headers)
return session
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(request: Request, user=Depends(actor)):
if not request.app.state.store.logout(bearer(request)):
raise bearer_failure()
return Response(status_code=204)
def pagination(request, scope):
allowed = {"limit", "cursor"}
if any(k not in allowed for k in request.query_params):
raise Failure(400, "Неизвестный параметр запроса")
if any(len(request.query_params.getlist(k)) > 1 for k in allowed):
raise Failure(400, "Повторный параметр запроса")
value = request.query_params.get("limit", "50")
if len(value) > 3 or not re.fullmatch(r"[0-9]+", value) or not 1 <= int(value) <= 100:
raise Failure(400, "limit должен быть целым от 1 до 100")
return int(value), boundary(scope, request.query_params.get("cursor"))
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready(request: Request):
if not request.app.state.store.ready() or not request.app.state.storage.ready():
raise Failure(503, "Хранилище недоступно")
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def register(data: CreateUser, request: Request):
return request.app.state.store.register(data.model_dump(mode="json"))
@app.get("/api/v1/users/me")
def me(user=Depends(actor)):
return user
@app.post("/api/v1/chats", status_code=201)
def create_chat(data: CreateChat, request: Request, user=Depends(actor)):
return request.app.state.store.create_chat(user["id"], data.model_dump(mode="json"))
@app.get("/api/v1/chats")
def chats(request: Request, user=Depends(actor)):
scope = "chats:" + user["id"]
limit, after = pagination(request, scope)
return page(request.app.state.store.list_chats(user["id"], after, limit), limit, scope)
@app.get("/api/v1/chats/{chat_id}")
def chat(chat_id: str, request: Request, user=Depends(actor)):
return request.app.state.store.chat(user["id"], identifier(chat_id))
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def send(chat_id: str, data: CreateMessage, request: Request, user=Depends(actor)):
key = request.headers.get("Idempotency-Key", "")
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
raise Failure(400, "Требуется корректный Idempotency-Key")
return request.app.state.store.send(
user["id"], identifier(chat_id), data.text, key, [str(a) for a in data.attachment_ids]
)
@app.get("/api/v1/chats/{chat_id}/messages")
def history(chat_id: str, request: Request, user=Depends(actor)):
cid = identifier(chat_id)
scope = "messages:" + cid
limit, after = pagination(request, scope)
return page(request.app.state.store.history(user["id"], cid, after, limit), limit, scope)
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(chat_id: str, request: Request, user=Depends(actor)):
import asyncio
import tempfile
from starlette.concurrency import run_in_threadpool
from .attachments import MAX_BYTES, filename_valid
if (
set(request.query_params) != {"filename"}
or len(request.query_params.getlist("filename")) != 1
):
raise Failure(400, "Требуется одно имя файла")
filename = filename_valid(request.query_params["filename"])
cid = identifier(chat_id)
await run_in_threadpool(request.app.state.store.chat, user["id"], cid)
content_type = request.headers.get("content-type", "").lower()
if content_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
if not request.app.state.upload_slots.acquire(blocking=False):
raise Failure(429, "Все места загрузки заняты", {"Retry-After": "1"})
try:
with tempfile.SpooledTemporaryFile(max_size=256 * 1024) as spool:
size = 0
try:
async with asyncio.timeout(15):
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
spool.write(chunk)
except TimeoutError:
raise Failure(400, "Истекло время загрузки") from None
spool.seek(0)
return await run_in_threadpool(
request.app.state.attachments.upload,
user["id"],
cid,
filename,
content_type,
spool,
size,
)
finally:
request.app.state.upload_slots.release()
@app.get("/api/v1/attachments/{attachment_id}")
def attachment_metadata(attachment_id: str, request: Request, user=Depends(actor)):
return request.app.state.attachments.metadata(user["id"], identifier(attachment_id))
@app.get("/api/v1/attachments/{attachment_id}/content")
def attachment_content(attachment_id: str, request: Request, user=Depends(actor)):
from fastapi.responses import StreamingResponse
if (
any(k != "variant" for k in request.query_params)
or len(request.query_params.getlist("variant")) > 1
):
raise Failure(400, "Неверный вариант")
variant = request.query_params.get("variant", "original")
if variant not in {"original", "thumbnail", "crop", "optimized"}:
raise Failure(400, "Неверный вариант")
obj = request.app.state.attachments.content(user["id"], identifier(attachment_id), variant)
def chunks():
try:
while data := obj["Body"].read(64 * 1024):
yield data
finally:
obj["Body"].close()
return StreamingResponse(
chunks(),
media_type=obj["ContentType"],
headers={"Content-Length": str(obj["ContentLength"])},
)
+176
View File
@@ -0,0 +1,176 @@
"""Durable asynchronous intake with full bounded validation before acceptance."""
import hashlib
import json
import os
import signal
import subprocess
import sys
import unicodedata
from pathlib import Path
from uuid import uuid4
from .domain import Failure, timestamp
from .jobs import Jobs, fault
from .postgres import public
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
PUBLIC_FIELDS = (
"id",
"chat_id",
"owner_id",
"filename",
"content_type",
"size_bytes",
"sha256",
"status",
"error_code",
"created_at",
"updated_at",
)
def filename_valid(name):
if not isinstance(name, str) or not 1 <= len(name) <= 255 or not name.strip():
raise Failure(400, "Неверное имя файла")
if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in name):
raise Failure(400, "Неверное имя файла")
return name
def validate_image(fileobj, declared_type):
if declared_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
fileobj.seek(0)
encoded = fileobj.read(MAX_BYTES + 1)
if len(encoded) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
try:
with subprocess.Popen(
[sys.executable, "-m", "messenger.image_validation", declared_type],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=True,
env={
"PATH": os.environ.get("PATH", os.defpath),
"PYTHONPATH": str(Path(__file__).resolve().parents[1]),
"PYTHONDONTWRITEBYTECODE": "1",
"LANG": "C.UTF-8",
},
) as process:
try:
output, _ = process.communicate(input=encoded, timeout=5)
except subprocess.TimeoutExpired:
# The validator can itself run djpeg: kill its whole process group
# before releasing the upload slot, not only the Python parent.
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass # The child may have exited at the timeout boundary.
process.communicate()
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
if process.returncode:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
raise Failure(415, "Изображение не прошло ограниченную проверку")
except OSError:
raise Failure(503, "Проверка изображения временно недоступна") from None
finally:
del encoded
try:
outcome = json.loads(output)
except (ValueError, UnicodeError):
raise Failure(415, "Повреждённое изображение") from None
if not isinstance(outcome, dict):
raise Failure(415, "Изображение не прошло ограниченную проверку")
if "error" in outcome:
status = outcome["error"]
if type(status) is not int or status not in {413, 415}:
status = 415
raise Failure(status, "Изображение не прошло ограниченную проверку")
values = outcome.get("ok")
if not isinstance(values, list) or len(values) != 3:
raise Failure(415, "Изображение не прошло ограниченную проверку")
fileobj.seek(0)
return tuple(values)
def metadata_public(row):
return {**public({k: row[k] for k in PUBLIC_FIELDS}), "variants": row["variants"]}
class AttachmentService:
def __init__(self, store, storage):
self.store = store
self.storage = storage
self.jobs = Jobs(store)
def upload(self, actor, cid, filename, content_type, fileobj, size):
filename_valid(filename)
if not 1 <= size <= MAX_BYTES:
raise Failure(413 if size > MAX_BYTES else 415, "Неверный размер изображения")
validate_image(fileobj, content_type)
digest = hashlib.file_digest(fileobj, "sha256").hexdigest()
aid = str(uuid4())
key = "staging/" + aid
now = timestamp()
with self.store.connection() as conn:
self.store._chat(conn, actor, cid)
conn.execute(
"INSERT INTO upload_intents(id,object_key,created_at) VALUES (%s,%s,%s)",
(aid, key, now),
)
# Keep the intent locked throughout PUT/finalization: reconciler skips live
# uploads even if a slow request crosses the grace boundary.
with self.store.connection() as conn, conn.transaction():
intent = conn.execute(
"SELECT id FROM upload_intents WHERE id=%s FOR UPDATE", (aid,)
).fetchone()
if not intent:
raise Failure(503, "Загрузка больше не активна")
self.storage.put(key, fileobj, size, content_type)
fault(self.store, "after_staging", aid)
row = conn.execute(
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,"
"status,error_code,created_at,updated_at,object_key,stage_key) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,'queued',NULL,%s,%s,%s,%s) RETURNING *",
(aid, cid, actor, filename, content_type, size, digest, now, now, key, key),
).fetchone()
self.jobs.enqueue(conn, aid, key)
conn.execute("DELETE FROM upload_intents WHERE id=%s", (aid,))
# Never delete S3 on an ambiguous COMMIT: the transaction may have committed.
fault(self.store, "after_upload_commit", aid)
return metadata_public(row)
def metadata(self, actor, aid):
with self.store.connection() as conn:
row = conn.execute(
"SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id "
"WHERE a.id=%s AND m.user_id=%s",
(aid, actor),
).fetchone()
if not row:
raise Failure(404, "Объект не найден")
return metadata_public(row)
def content(self, actor, aid, variant="original"):
with self.store.connection() as conn:
row = conn.execute(
"SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id "
"WHERE a.id=%s AND m.user_id=%s",
(aid, actor),
).fetchone()
if not row:
raise Failure(404, "Объект не найден")
if row["status"] != "ready":
raise Failure(409, "Вложение не готово")
key = row["object_key"]
if variant != "original":
if variant not in {v["name"] for v in row["variants"]}:
raise Failure(404, "Вариант не найден")
key = key.rsplit("/", 1)[0] + "/" + variant
return self.storage.get(key)
+10
View File
@@ -0,0 +1,10 @@
import os
from pathlib import Path
def secret(name: str) -> str:
filename = os.environ.get(name + "_FILE")
value = Path(filename).read_text().strip() if filename else os.environ.get(name, "")
if not value:
raise RuntimeError("Отсутствует настройка " + name)
return value
+63
View File
@@ -0,0 +1,63 @@
import base64
import json
import re
from datetime import UTC, datetime
from uuid import UUID
class Failure(Exception):
def __init__(self, status: int, message: str, headers: dict | None = None):
self.status = status
self.message = message
self.headers = headers or {}
def timestamp() -> str:
return datetime.now(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
def identifier(value: str) -> str:
try:
return str(UUID(value))
except (ValueError, TypeError, AttributeError):
raise Failure(400, "Некорректный UUID") from None
def boundary(scope: str, cursor: str | None) -> tuple[str, str] | None:
if cursor is None:
return None
try:
if not cursor or len(cursor) > 1024 or not re.fullmatch(r"[A-Za-z0-9_-]+", cursor):
raise ValueError
data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))
if (
not isinstance(data, list)
or len(data) != 4
or type(data[0]) is not int
or data[0] != 1
or data[1] != scope
):
raise ValueError
date, uid = data[2:]
if not isinstance(date, str) or not re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z",
date,
):
raise ValueError
datetime.fromisoformat(date.replace("Z", "+00:00"))
if not isinstance(uid, str) or str(UUID(uid)) != uid:
raise ValueError
return date, uid
except (ValueError, TypeError, KeyError, UnicodeError):
raise Failure(400, "Некорректный cursor или область запроса") from None
def page(items: list[dict], limit: int, scope: str) -> dict:
more = len(items) > limit
selected = items[:limit]
cursor = None
if more:
last = selected[-1]
payload = json.dumps([1, scope, last["created_at"], last["id"]], separators=(",", ":"))
cursor = base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=")
return {"items": selected, "next_cursor": cursor}
+82
View File
@@ -0,0 +1,82 @@
"""Image transformations, run in a bounded child process by the worker."""
import hashlib
import json
import sys
from pathlib import Path
from PIL import Image, ImageOps
Image.MAX_IMAGE_PIXELS = 40_000_000
def fitted_size(width, height, bound):
"""Fit without upscale; integer arithmetic deliberately rounds down."""
longest = max(width, height)
if longest <= bound:
return width, height
return max(1, width * bound // longest), max(1, height * bound // longest)
def render(source, destination, version=1):
if version not in (1, 2):
raise ValueError("unsupported_pipeline")
destination = Path(destination)
with Image.open(source) as image:
if image.width * image.height > 40_000_000:
raise ValueError("pixel_limit")
image.load()
ImageOps.exif_transpose(image, in_place=True)
if "A" in image.getbands() or (image.mode == "P" and "transparency" in image.info):
rgba = image if image.mode == "RGBA" else image.convert("RGBA")
rgb = Image.new("RGB", rgba.size, "white")
alpha = rgba.getchannel("A")
rgb.paste(rgba, mask=alpha)
alpha.close()
if rgba is not image:
rgba.close()
else:
rgb = image if image.mode == "RGB" else image.convert("RGB")
thumbnail = rgb.resize(fitted_size(*rgb.size, 256), Image.Resampling.LANCZOS)
crop = ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
optimized = rgb.resize(fitted_size(*rgb.size, 1280), Image.Resampling.LANCZOS)
variants = []
for name, variant, kind, mime, options in (
("thumbnail", thumbnail, "JPEG", "image/jpeg", {"quality": 85}),
("crop", crop, "JPEG", "image/jpeg", {"quality": 85}),
(
"optimized",
optimized,
"WEBP",
"image/webp",
{"quality": 80 if version == 1 else 75, "method": 4},
),
):
# No EXIF/ICC arguments: outputs do not propagate source metadata.
path = destination / name
variant.save(path, format=kind, **options)
data = path.read_bytes()
variants.append(
{
"name": name,
"content_type": mime,
"size_bytes": len(data),
"width": variant.width,
"height": variant.height,
"sha256": hashlib.sha256(data).hexdigest(),
}
)
variant.close()
if rgb is not image:
rgb.close()
return variants
if __name__ == "__main__":
import resource
resource.setrlimit(resource.RLIMIT_AS, (700 * 1024**2, 700 * 1024**2))
resource.setrlimit(resource.RLIMIT_CPU, (15, 15))
source, destination, version = sys.argv[1:]
result = render(source, destination, int(version))
(Path(destination) / "variants.json").write_text(json.dumps(result))
+146
View File
@@ -0,0 +1,146 @@
"""Short-lived bounded pixel validation; no DB, credentials or application imports."""
import json
import resource
import subprocess
import sys
from io import BytesIO
from PIL import Image, UnidentifiedImageError
from .domain import Failure
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
def inspect_image(fileobj, declared_type):
if declared_type not in {"image/png", "image/jpeg"}:
raise Failure(415, "Ожидается PNG или JPEG")
try:
fileobj.seek(0)
with Image.open(fileobj) as header:
width, height = header.size
if width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей")
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}.get(header.format)
if actual != declared_type:
raise Failure(415, "Формат изображения не соответствует MIME")
frames = getattr(header, "n_frames", 1)
default_image = bool(getattr(header, "default_image", False))
if width * height * frames > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
header.verify()
# Drop parsed metadata before the separate strict decoder process starts.
del header
if actual == "image/png":
# verify() checks CRC, but does not compare acTL's frame count with
# every fcTL. Do not let a forged count hide a corrupt later frame.
fileobj.seek(8)
controls = frame_controls = 0
declared_frames = None
animation_data = False
while True:
chunk_header = fileobj.read(8)
if len(chunk_header) != 8:
raise ValueError("Truncated PNG chunk")
length = int.from_bytes(chunk_header[:4], "big")
kind = chunk_header[4:]
controls += kind == b"acTL"
frame_controls += kind == b"fcTL"
animation_data |= kind == b"fdAT"
if kind == b"acTL":
if length != 8:
raise ValueError("Invalid acTL length")
declared_frames = int.from_bytes(fileobj.read(4), "big")
fileobj.seek(length, 1) # remaining payload plus CRC
else:
fileobj.seek(length + 4, 1)
if kind == b"IEND":
break
if controls:
if (
controls != 1
or not declared_frames
or frame_controls != declared_frames
or declared_frames + int(default_image) != frames
):
raise ValueError("Invalid APNG frame count")
elif frame_controls or animation_data:
raise ValueError("Animation chunks without acTL")
if actual == "image/jpeg":
# Validate scan warnings before allocating Pillow's decoded canvas.
# 384 MiB covers coefficient arrays for <=40M pixels and <=4 channels;
# keeping both full decoded buffers alive could exceed the API cgroup.
fileobj.seek(0)
# A bounded compressed copy avoids sharing buffered file-descriptor
# offsets with the child, and supports BytesIO callers as well.
encoded = fileobj.read(MAX_BYTES + 1)
if len(encoded) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
try:
decoded = subprocess.run(
["djpeg", "-strict", "-maxmemory", "384m", "-outfile", "/dev/null"],
input=encoded,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=4,
check=False,
)
except subprocess.TimeoutExpired:
raise Failure(415, "Изображение не прошло ограниченную проверку") from None
finally:
del encoded
if decoded.returncode:
raise Failure(415, "Повреждённое изображение")
# djpeg has already decoded every JPEG pixel, streaming output rows.
# A second Pillow load would overlap full progressive coefficient
# arrays with a 160 MiB CMYK canvas and violate the API's 512 MiB cap.
fileobj.seek(0)
return actual, width, height
# Decode one frame at a time. Pillow may retain a previous APNG canvas
# for compositing, but no list/copies of every decoded frame is collected.
fileobj.seek(0)
with Image.open(fileobj) as image:
decoded_pixels = 0
for frame in range(frames):
if decoded_pixels + width * height > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
image.seek(frame)
decoded_pixels += image.size[0] * image.size[1]
if decoded_pixels > MAX_PIXELS:
raise Failure(413, "Слишком много пикселей во всех кадрах")
image.load()
# Image's context manager closes its input handle, not the decoded core.
# Releasing the object frees native canvases before hashing/S3 publication.
del image
fileobj.seek(0)
return actual, width, height
except Image.DecompressionBombError:
raise Failure(413, "Слишком много пикселей") from None
except (UnidentifiedImageError, OSError, ValueError, SyntaxError, EOFError):
raise Failure(415, "Повреждённое изображение") from None
def main():
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resource.setrlimit(resource.RLIMIT_CPU, (4, 5))
if sys.platform == "linux":
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
try:
data = sys.stdin.buffer.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise Failure(413, "Файл больше 10 MiB")
result = inspect_image(BytesIO(data), sys.argv[1])
print(json.dumps({"ok": result}))
except Failure as exc:
print(json.dumps({"error": exc.status}))
except MemoryError:
print(json.dumps({"error": 415}))
except Exception:
print(json.dumps({"error": 415}))
if __name__ == "__main__":
main()
+123
View File
@@ -0,0 +1,123 @@
"""Local operator commands; no public HTTP replay or arbitrary object paths."""
import argparse
import json
from .domain import Failure
from .jobs import Jobs, fault
from .postgres import PostgresStore
from .storage import ObjectStorage
from .worker import cleanup_ready
def cleanup(store, storage, failed_hours=168, intent_seconds=3600):
if failed_hours < 0 or intent_seconds < 0:
raise ValueError("Retention must be nonnegative")
counts = {"ready_staging": 0, "failed_sources": 0, "orphan_intents": 0}
with store.connection() as conn:
ready = conn.execute(
"SELECT id FROM attachments WHERE status='ready' AND stage_key IS NOT NULL"
).fetchall()
for row in ready:
cleanup_ready(store, storage, row["id"])
counts["ready_staging"] += 1
with store.connection() as conn:
candidates = conn.execute(
"SELECT id FROM attachments WHERE status='failed' AND updated_at<now()-(%s * interval '1 hour')",
(failed_hours,),
).fetchall()
for row in candidates:
with store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (row["id"],)
).fetchone()
# Recheck under the same row lock used by replay and publication.
if not a or a["status"] != "failed":
continue
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
(a["id"], a["pipeline_version"]),
).fetchone()
if not current or current["state"] != "failed" or current["source_key"] is None:
continue
old = conn.execute(
"SELECT updated_at<now()-(%s * interval '1 hour') AS old FROM attachments WHERE id=%s",
(failed_hours, a["id"]),
).fetchone()["old"]
if not old:
continue
fault(store, "cleanup_before_delete", a["id"])
# If cleanup commits first, later replay refuses source_missing. If replay
# commits first, status is queued and cleanup skips it. DELETE stays locked.
source = current["source_key"]
storage.delete(source)
prefix = f"attachments/{a['id']}/v{a['pipeline_version']}"
for variant in ("original", "thumbnail", "crop", "optimized"):
storage.delete(prefix + "/" + variant)
conn.execute("UPDATE attachment_jobs SET source_key=NULL WHERE id=%s", (current["id"],))
conn.execute("UPDATE attachments SET stage_key=NULL WHERE id=%s", (a["id"],))
Jobs.audit(conn, current["id"], "source_retention_expired", current["attempt"])
counts["failed_sources"] += 1
with store.connection() as conn:
intents = conn.execute(
"SELECT id FROM upload_intents WHERE created_at<now()-(%s * interval '1 second')",
(intent_seconds,),
).fetchall()
for row in intents:
with store.connection() as conn, conn.transaction():
intent = conn.execute(
"SELECT * FROM upload_intents WHERE id=%s FOR UPDATE SKIP LOCKED", (row["id"],)
).fetchone()
if intent is None:
continue
referenced = conn.execute(
"SELECT 1 FROM attachments WHERE id=%s", (row["id"],)
).fetchone()
if referenced is None:
storage.delete(intent["object_key"])
counts["orphan_intents"] += 1
conn.execute("DELETE FROM upload_intents WHERE id=%s", (row["id"],))
return counts
def main():
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest="command", required=True)
for name in ("replay", "reprocess"):
command = sub.add_parser(name)
command.add_argument("attachment_id")
if name == "reprocess":
command.add_argument("--version", type=int, required=True)
sub.add_parser("failed")
command = sub.add_parser("cleanup")
command.add_argument("--failed-hours", type=float, default=168)
command.add_argument("--intent-seconds", type=float, default=3600)
args = parser.parse_args()
store, storage = PostgresStore(), ObjectStorage()
try:
jobs = Jobs(store)
if args.command == "replay":
result = {"job_id": jobs.replay(args.attachment_id, storage)}
elif args.command == "reprocess":
result = {"job_id": jobs.reprocess(args.attachment_id, args.version, storage)}
elif args.command == "cleanup":
result = cleanup(store, storage, args.failed_hours, args.intent_seconds)
else:
with store.connection() as conn:
result = [
dict(row)
for row in conn.execute(
"SELECT j.id,j.attachment_id,j.attempt,f.error_code,f.replay_count FROM failed_jobs f JOIN attachment_jobs j ON j.id=f.job_id WHERE j.state='failed'"
).fetchall()
]
print(json.dumps(result, default=str))
except Failure as exc:
print(json.dumps({"status": exc.status, "error": exc.message}))
raise SystemExit(1) from None
finally:
storage.close()
store.close()
if __name__ == "__main__":
main()
+330
View File
@@ -0,0 +1,330 @@
"""PostgreSQL owns job state; broker deliveries are repeatable notifications."""
import json
import logging
import os
import random
import time
from datetime import UTC, datetime
from uuid import uuid4
import redis
from opentelemetry import propagate
from opentelemetry.trace import SpanKind
from . import telemetry
from .config import secret
from .domain import Failure
from .postgres import public
logger = logging.getLogger("messenger.jobs")
STREAM = "attachment-jobs:v1"
GROUP = "image-workers"
def broker_client():
return redis.Redis.from_url(
secret("BROKER_URL"),
decode_responses=False,
socket_connect_timeout=2,
socket_timeout=3,
)
def fault(store, point, attachment_id):
"""Only enabled in the explicit fault-test overlay; never accepts HTTP controls."""
if os.getenv("ENABLE_FAULT_INJECTION") != "1":
return
with store.connection() as conn:
row = conn.execute(
"UPDATE test_faults SET reached_at=now() WHERE id=("
"SELECT id FROM test_faults WHERE point=%s AND reached_at IS NULL "
"AND (attachment_id IS NULL OR attachment_id=%s) ORDER BY id LIMIT 1) RETURNING *",
(point, attachment_id),
).fetchone()
if row is None:
return
logger.warning(json.dumps({"event": "fault_reached", "point": point, "fault_id": row["id"]}))
if row["action"] == "crash":
os._exit(86)
if row["action"] == "error":
raise RuntimeError("injected_transient_failure")
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
with store.connection() as conn:
released = conn.execute(
"SELECT released FROM test_faults WHERE id=%s", (row["id"],)
).fetchone()
if released and released["released"]:
return
time.sleep(0.1)
raise RuntimeError("fault_barrier_timeout")
class Jobs:
def __init__(self, store):
self.store = store
self.attempt_limit = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
self.lease_seconds = int(os.getenv("JOB_LEASE_SECONDS", "45"))
if not 1 <= self.attempt_limit <= 20 or not 5 <= self.lease_seconds <= 300:
raise RuntimeError("Invalid job retry/lease configuration")
def enqueue(self, conn, attachment_id, source_key, version=1):
job_id = str(uuid4())
conn.execute(
"INSERT INTO attachment_jobs(id,attachment_id,pipeline_version,source_key,state,attempt_limit,traceparent,tracestate) "
"VALUES (%s,%s,%s,%s,'queued',%s,%s,%s)",
(job_id, attachment_id, version, source_key, self.attempt_limit, telemetry.carrier().get("traceparent"), telemetry.carrier().get("tracestate")),
)
conn.execute("INSERT INTO job_outbox(job_id) VALUES (%s)", (job_id,))
self.audit(conn, job_id, "accepted", 0)
return job_id
@staticmethod
def audit(conn, job_id, event, attempt):
conn.execute(
"INSERT INTO job_audit(job_id,event,attempt) VALUES (%s,%s,%s)",
(job_id, event, attempt),
)
def publish_one(self, broker):
with self.store.connection() as conn, conn.transaction():
job = conn.execute(
"SELECT j.* FROM job_outbox o JOIN attachment_jobs j ON j.id=o.job_id "
"WHERE o.published_at IS NULL AND j.available_at<=now() "
"ORDER BY j.available_at LIMIT 1 FOR UPDATE OF o SKIP LOCKED"
).fetchone()
if job is None:
return False
if job["state"] == "queued":
body = {
"schema_version": 1,
"job_id": str(job["id"]),
"type": "attachment.process.v1",
"attachment_id": str(job["attachment_id"]),
"pipeline_version": job["pipeline_version"],
"attempt": job["attempt"] + 1,
"created_at": public({"v": job["created_at"]})["v"],
}
# XADD response with appendfsync=always is the broker acceptance boundary.
parent = {key: job.get(key) for key in ("traceparent", "tracestate") if job.get(key)}
with telemetry.operation("attachments publish", context=propagate.extract(parent), kind=SpanKind.PRODUCER):
body.update(telemetry.carrier())
broker.xadd(STREAM, {"body": json.dumps(body)})
fault(self.store, "after_publish", job["attachment_id"])
conn.execute("UPDATE job_outbox SET published_at=now() WHERE job_id=%s", (job["id"],))
return True
def claim(self, job_id, attachment_id, version):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if attachment is None:
return None
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job_id,)
).fetchone()
if (
job is None
or str(job["attachment_id"]) != str(attachment_id)
or job["pipeline_version"] != version
):
return None
if attachment["pipeline_version"] != version:
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE id=%s AND state NOT IN ('ready','superseded')",
(job_id,),
)
return None
if job["state"] != "queued":
return None
lease_id = str(uuid4())
job = conn.execute(
"UPDATE attachment_jobs SET state='processing',attempt=attempt+1,lease_id=%s,"
"lease_until=now()+(%s * interval '1 second'),updated_at=now() "
"WHERE id=%s AND available_at<=now() RETURNING *",
(lease_id, self.lease_seconds, job_id),
).fetchone()
if job is None:
return None
conn.execute(
"UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",
(attachment_id,),
)
self.audit(conn, job_id, "claimed", job["attempt"])
job["source_sha256"] = attachment["sha256"]
job["source_size"] = attachment["size_bytes"]
job["source_content_type"] = attachment["content_type"]
return job
def complete(self, job, object_key, variants):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (job["attachment_id"],)
).fetchone()
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job["id"],)
).fetchone()
if (
attachment["pipeline_version"] != job["pipeline_version"]
or current["state"] != "processing"
or current["lease_id"] != job["lease_id"]
):
self.audit(conn, job["id"], "stale_publish_rejected", job["attempt"])
return False
conn.execute(
"UPDATE attachments SET status='ready',error_code=NULL,object_key=%s,variants=%s::jsonb,updated_at=now() WHERE id=%s",
(object_key, json.dumps(variants), job["attachment_id"]),
)
conn.execute(
"UPDATE attachment_jobs SET state='ready',lease_until=NULL,error_code=NULL,updated_at=now() WHERE id=%s",
(job["id"],),
)
self.audit(conn, job["id"], "published", job["attempt"])
t = telemetry.current()
if t:
t.ready_duration.record((datetime.now(UTC) - job["created_at"]).total_seconds(), {"job_type": "attachment.process.v1"})
return True
def fail(self, job, code, permanent=False):
with self.store.connection() as conn, conn.transaction():
attachment = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (job["attachment_id"],)
).fetchone()
current = conn.execute(
"SELECT * FROM attachment_jobs WHERE id=%s FOR UPDATE", (job["id"],)
).fetchone()
if (
attachment["pipeline_version"] != job["pipeline_version"]
or current["lease_id"] != job["lease_id"]
or current["state"] != "processing"
):
return
if permanent or current["attempt"] >= current["attempt_limit"]:
final_code = code if permanent else "retry_exhausted"
self._failed(conn, current, final_code)
else:
delay = min(30, 2 ** (current["attempt"] - 1)) + random.uniform(0, 0.5)
conn.execute(
"UPDATE attachment_jobs SET state='queued',error_code=%s,lease_until=NULL,"
"available_at=now()+(%s * interval '1 second'),updated_at=now() WHERE id=%s",
(code, delay, job["id"]),
)
conn.execute(
"UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],)
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
self.audit(conn, job["id"], "retry_scheduled", job["attempt"])
def _failed(self, conn, job, code):
conn.execute(
"UPDATE attachment_jobs SET state='failed',error_code=%s,lease_until=NULL,updated_at=now() WHERE id=%s",
(code, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s",
(code, job["attachment_id"]),
)
conn.execute(
"INSERT INTO failed_jobs(job_id,error_code) VALUES (%s,%s) "
"ON CONFLICT(job_id) DO UPDATE SET error_code=excluded.error_code,failed_at=now()",
(job["id"], code),
)
self.audit(conn, job["id"], "failed:" + code, job["attempt"])
def recover_one(self):
with self.store.connection() as conn, conn.transaction():
candidate = conn.execute(
"SELECT a.id FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id "
"WHERE j.state='processing' AND j.lease_until<now() LIMIT 1 FOR UPDATE OF a SKIP LOCKED"
).fetchone()
if candidate is None:
return False
job = conn.execute(
"SELECT j.* FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id "
"WHERE j.attachment_id=%s AND j.state='processing' AND j.lease_until<now() "
"AND j.pipeline_version=a.pipeline_version FOR UPDATE OF j",
(candidate["id"],),
).fetchone()
if job is None:
return False
if job["attempt"] >= job["attempt_limit"]:
self._failed(conn, job, "retry_exhausted")
else:
conn.execute(
"UPDATE attachment_jobs SET state='queued',lease_until=NULL,available_at=now(),updated_at=now() WHERE id=%s",
(job["id"],),
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s",
(job["attachment_id"],),
)
conn.execute(
"UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],)
)
self.audit(conn, job["id"], "lease_recovered", job["attempt"])
return True
def replay(self, attachment_id, storage):
with self.store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if not a or a["status"] != "failed":
raise Failure(409, "Повтор разрешён только для failed")
job = conn.execute(
"SELECT * FROM attachment_jobs WHERE attachment_id=%s AND pipeline_version=%s FOR UPDATE",
(attachment_id, a["pipeline_version"]),
).fetchone()
if not job["source_key"] or not storage.exists(job["source_key"]):
raise Failure(409, "Источник больше недоступен")
fault(self.store, "replay_before_commit", attachment_id)
conn.execute(
"UPDATE attachment_jobs SET state='queued',attempt_limit=attempt+%s,available_at=now(),error_code=NULL,updated_at=now() WHERE id=%s",
(self.attempt_limit, job["id"]),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s",
(attachment_id,),
)
conn.execute("UPDATE job_outbox SET published_at=NULL WHERE job_id=%s", (job["id"],))
conn.execute(
"UPDATE failed_jobs SET replay_count=replay_count+1 WHERE job_id=%s", (job["id"],)
)
self.audit(conn, job["id"], "operator_replay", job["attempt"])
return str(job["id"])
def reprocess(self, attachment_id, version, storage):
if version not in (1, 2):
raise Failure(400, "Поддерживаются версии pipeline 1 и 2")
with self.store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if not a:
raise Failure(404, "Вложение отсутствует")
if version <= a["pipeline_version"]:
raise Failure(409, "Нужна более новая версия pipeline")
source = a["object_key"] if a["status"] == "ready" else a["stage_key"]
if not source or not storage.exists(source):
raise Failure(409, "Источник больше недоступен")
if a["status"] == "ready" and a["stage_key"] and a["stage_key"].startswith("staging/"):
# A worker can be paused after publishing ready but before its
# staging cleanup. Do not orphan that key when choosing final v1
# as the new source. Delete stays under the same attachment lock;
# a storage failure leaves the ready version unchanged.
fault(self.store, "reprocess_before_staging_delete", attachment_id)
storage.delete(a["stage_key"])
conn.execute(
"UPDATE attachment_jobs SET state='superseded',updated_at=now() WHERE attachment_id=%s AND state IN ('queued','processing','failed')",
(attachment_id,),
)
conn.execute(
"UPDATE attachments SET pipeline_version=%s,status='queued',variants='[]',error_code=NULL,stage_key=%s,updated_at=now() WHERE id=%s",
(version, source, attachment_id),
)
return self.enqueue(conn, attachment_id, source, version)
+32
View File
@@ -0,0 +1,32 @@
import hashlib
from pathlib import Path
import psycopg
from .config import secret
def migrate():
with psycopg.connect(secret("DATABASE_URL")) as conn:
# Serialize independent migration processes without changing application data.
conn.execute("SELECT pg_advisory_xact_lock(2301002)")
conn.execute(
"CREATE TABLE IF NOT EXISTS schema_migrations "
"(name text PRIMARY KEY, checksum text NOT NULL)"
)
for path in sorted(Path("migrations").glob("*.sql")):
checksum = hashlib.sha256(path.read_bytes()).hexdigest()
old = conn.execute(
"SELECT checksum FROM schema_migrations WHERE name=%s", (path.name,)
).fetchone()
if old:
if old[0] != checksum:
raise RuntimeError("Изменена применённая миграция: " + path.name)
continue
conn.execute(path.read_text())
conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name, checksum))
print("Applied", path.name)
if __name__ == "__main__":
migrate()
+71
View File
@@ -0,0 +1,71 @@
import re
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator, model_validator
class RequestModel(BaseModel):
model_config = ConfigDict(extra="forbid")
@field_validator("*", mode="after")
@classmethod
def nonblank(cls, value):
if isinstance(value, str):
value.encode("utf-8")
if isinstance(value, str) and not value.strip():
raise ValueError("Строка не может состоять из пробелов")
return value
class CreateUser(RequestModel):
username: StrictStr = Field(pattern=r"^[a-z0-9_]{3,32}$")
display_name: StrictStr = Field(min_length=1, max_length=100)
password: StrictStr = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def full_username(cls, value):
if not re.fullmatch(r"[a-z0-9_]{3,32}", value):
raise ValueError("Неверное имя пользователя")
return value
class CreateChat(RequestModel):
title: StrictStr = Field(min_length=1, max_length=100)
member_ids: list[UUID] = Field(min_length=1, max_length=100)
@field_validator("member_ids", mode="before")
@classmethod
def string_ids(cls, value):
if not isinstance(value, list) or any(not isinstance(x, str) for x in value):
raise ValueError("Ожидается массив UUID-строк")
return value
@field_validator("member_ids")
@classmethod
def unique_ids(cls, value):
if len(set(value)) != len(value):
raise ValueError("Участники не должны повторяться")
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: StrictStr = Field(max_length=4000)
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
@field_validator("attachment_ids", mode="before")
@classmethod
def string_ids(cls, value):
if not isinstance(value, list) or any(not isinstance(x, str) for x in value):
raise ValueError("Ожидается массив UUID-строк")
return value
@model_validator(mode="after")
def content(self):
self.text.encode("utf-8")
if len(set(self.attachment_ids)) != len(self.attachment_ids):
raise ValueError("Вложения не должны повторяться")
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Пустое сообщение без вложений")
return self
+334
View File
@@ -0,0 +1,334 @@
import hashlib
import json
import logging
import os
import secrets
from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from threading import BoundedSemaphore
from uuid import UUID, uuid4
import psycopg
import redis
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests
from .config import secret
from .domain import Failure, timestamp
from .telemetry import operation
logger = logging.getLogger("messenger")
KDF_SLOTS = BoundedSemaphore(2)
KDF = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=1)
DUMMY_HASH = KDF.hash("invalid-user-dummy-password")
class DeadlineConnection(psycopg.Connection):
def wait(self, gen, interval=0.1, timeout=None):
try:
return super().wait(gen, interval=interval, timeout=timeout or 3.0)
except psycopg.errors._WaitTimeout:
# A paused server cannot complete cancellation. Discard an uncertain
# connection instead of returning it to the pool or waiting forever.
self.pgconn.finish()
raise
def public(row):
return {
k: (
str(v)
if isinstance(v, UUID)
else v.astimezone(UTC).isoformat(timespec="microseconds").replace("+00:00", "Z")
if isinstance(v, datetime)
else bytes(v).decode("utf-8")
if isinstance(v, (bytes, memoryview))
else v
)
for k, v in row.items()
if k not in {"password_hash", "token_digest"}
}
class PostgresStore:
def __init__(self):
self.pool = ConnectionPool(
secret("DATABASE_URL"),
connection_class=DeadlineConnection,
min_size=1,
max_size=int(os.getenv("POOL_MAX_SIZE", "8")),
timeout=2,
max_waiting=32,
kwargs={
"autocommit": True,
"row_factory": dict_row,
"connect_timeout": 2,
"options": "-c statement_timeout=2500 -c lock_timeout=1500",
},
check=ConnectionPool.check_connection,
)
self.pool.wait(timeout=15)
self.cache = redis.Redis.from_url(
secret("CACHE_URL"),
socket_connect_timeout=0.2,
socket_timeout=0.2,
decode_responses=True,
)
self.ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
if self.ttl < 1:
raise RuntimeError("SESSION_TTL_SECONDS должен быть положительным")
@contextmanager
def connection(self):
try:
with operation("postgres.transaction", {"db.system.name": "postgresql"}):
with self.pool.connection() as conn:
yield conn
except (
psycopg.OperationalError,
psycopg.InterfaceError,
PoolTimeout,
TooManyRequests,
psycopg.errors.QueryCanceled,
psycopg.errors.LockNotAvailable,
):
raise Failure(503, "Хранилище временно недоступно") from None
def close(self):
self.cache.close()
self.pool.close()
def ready(self):
try:
with self.connection() as conn:
conn.execute(
"SELECT u.id,u.password_hash,c.id,m.chat_id,msg.id,s.token_digest,r.key,"
"a.id,a.stage_key,a.pipeline_version,a.variants,ma.attachment_id,ui.object_key,"
"j.id,j.source_key,j.attempt_limit,j.lease_until,o.job_id,o.published_at,"
"audit.job_id,f.error_code FROM users u,chats c,members m,messages msg,"
"sessions s,message_requests r,attachments a,message_attachments ma,"
"upload_intents ui,attachment_jobs j,job_outbox o,job_audit audit,failed_jobs f "
"WHERE false"
)
return True
except (Failure, psycopg.Error):
return False
def _cached_user(self, uid):
key = "user:v1:" + uid
try:
value = self.cache.get(key)
if value:
cached = json.loads(value)
if (
isinstance(cached, dict)
and cached.get("id") == uid
and set(cached) == {"id", "username", "display_name", "created_at"}
):
return cached
except (redis.RedisError, ValueError, TypeError):
logger.warning(json.dumps({"event": "cache_bypass"}))
user = self.user(uid)
if user:
try:
self.cache.setex(key, 60, json.dumps(user))
except redis.RedisError:
logger.warning(json.dumps({"event": "cache_bypass"}))
return user
def user(self, uid):
with self.connection() as conn:
row = conn.execute(
"SELECT id,username,display_name,created_at FROM users WHERE id=%s", (uid,)
).fetchone()
return public(row) if row else None
def register(self, data):
with KDF_SLOTS:
hashed = KDF.hash(data.pop("password"))
uid = str(uuid4())
try:
with self.connection() as conn:
row = conn.execute(
"INSERT INTO users VALUES (%s,%s,%s,%s,%s) "
"RETURNING id,username,display_name,created_at",
(
uid,
data["username"],
data["display_name"].encode("utf-8"),
hashed,
timestamp(),
),
).fetchone()
return public(row)
except psycopg.errors.UniqueViolation:
raise Failure(409, "Имя пользователя занято") from None
def login(self, username, password):
with self.connection() as conn:
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
try:
with KDF_SLOTS:
KDF.verify(row["password_hash"] if row else DUMMY_HASH, password)
except VerificationError:
return None
if row is None:
return None
token = secrets.token_urlsafe(32)
digest = hashlib.sha256(token.encode()).hexdigest()
expires = datetime.now(UTC) + timedelta(seconds=self.ttl)
with self.connection() as conn:
conn.execute("INSERT INTO sessions VALUES (%s,%s,%s)", (digest, row["id"], expires))
return {
"token": token,
"token_type": "Bearer",
"expires_at": public({"v": expires})["v"],
"user": public(row),
}
def authenticate(self, token):
if not token or len(token) > 512:
return None
digest = hashlib.sha256(token.encode()).hexdigest()
# Session validity always comes from PostgreSQL, including on a cache hit.
with self.connection() as conn:
row = conn.execute(
"SELECT s.user_id FROM sessions s WHERE s.token_digest=%s AND s.expires_at>now()",
(digest,),
).fetchone()
return self._cached_user(str(row["user_id"])) if row else None
def logout(self, token):
with self.connection() as conn:
row = conn.execute(
"DELETE FROM sessions WHERE token_digest=%s AND expires_at>now() RETURNING user_id",
(hashlib.sha256(token.encode()).hexdigest(),),
).fetchone()
return row is not None
def create_chat(self, actor, data):
if actor not in data["member_ids"]:
raise Failure(400, "Вызывающий должен входить в чат")
cid = str(uuid4())
try:
with self.connection() as conn, conn.transaction():
row = conn.execute(
"INSERT INTO chats VALUES (%s,%s,%s) RETURNING *",
(cid, data["title"].encode("utf-8"), timestamp()),
).fetchone()
for index, uid in enumerate(data["member_ids"]):
conn.execute("INSERT INTO members VALUES (%s,%s,%s)", (cid, uid, index))
return {**public(row), "member_ids": data["member_ids"]}
except psycopg.errors.ForeignKeyViolation:
raise Failure(400, "Неизвестный участник") from None
@staticmethod
def _chat(conn, actor, cid):
row = conn.execute(
"SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id "
"WHERE c.id=%s AND m.user_id=%s",
(cid, actor),
).fetchone()
if row is None:
raise Failure(404, "Объект не найден")
members = conn.execute(
"SELECT user_id FROM members WHERE chat_id=%s ORDER BY position", (cid,)
).fetchall()
return {**public(row), "member_ids": [str(m["user_id"]) for m in members]}
def chat(self, actor, cid):
with self.connection() as conn:
return self._chat(conn, actor, cid)
def list_chats(self, actor, after, limit):
with self.connection() as conn:
sql = "SELECT c.* FROM chats c JOIN members m ON m.chat_id=c.id WHERE m.user_id=%s"
params = [actor]
if after:
sql += " AND (c.created_at,c.id)>(%s,%s)"
params.extend(after)
sql += " ORDER BY c.created_at,c.id LIMIT %s"
params.append(limit + 1)
rows = conn.execute(sql, params).fetchall()
return [self._chat(conn, actor, str(row["id"])) for row in rows]
def send(self, actor, cid, text, key, attachment_ids=None):
attachment_ids = attachment_ids or []
body_digest = hashlib.sha256(
json.dumps(
{"text": text, "attachment_ids": attachment_ids},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
).encode()
).hexdigest()
with self.connection() as conn, conn.transaction():
self._chat(conn, actor, cid)
# Serializes exactly this semantic key across all API processes. Hash
# collisions can only serialize unrelated requests, never mix results.
scope = json.dumps([actor, "POST", cid, key], separators=(",", ":"))
lock = int.from_bytes(hashlib.sha256(scope.encode()).digest()[:8], "big", signed=True)
conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock,))
old = conn.execute(
"SELECT body_digest,response FROM message_requests "
"WHERE actor_id=%s AND chat_id=%s AND key=%s AND expires_at>now()",
(actor, cid, key),
).fetchone()
if old:
if old["body_digest"] != body_digest:
raise Failure(409, "Ключ уже использован для другого сообщения")
return json.loads(bytes(old["response"]))
conn.execute(
"DELETE FROM message_requests WHERE actor_id=%s AND chat_id=%s AND key=%s",
(actor, cid, key),
)
for aid in attachment_ids:
attachment = conn.execute(
"SELECT id,status FROM attachments WHERE id=%s AND chat_id=%s FOR SHARE",
(aid, cid),
).fetchone()
if not attachment:
raise Failure(404, "Объект не найден")
if attachment["status"] == "failed":
raise Failure(409, "Вложение недоступно")
row = conn.execute(
"INSERT INTO messages VALUES (%s,%s,%s,%s,%s) RETURNING *",
(str(uuid4()), cid, actor, text.encode("utf-8"), timestamp()),
).fetchone()
for position, aid in enumerate(attachment_ids):
conn.execute(
"INSERT INTO message_attachments VALUES (%s,%s,%s)", (row["id"], aid, position)
)
response = {**public(row), "attachment_ids": attachment_ids}
conn.execute(
"INSERT INTO message_requests(actor_id,chat_id,key,body_digest,response,expires_at) "
"VALUES (%s,%s,%s,%s,%s,now()+interval '24 hours')",
(actor, cid, key, body_digest, json.dumps(response).encode("utf-8")),
)
return response
def history(self, actor, cid, after, limit):
with self.connection() as conn:
self._chat(conn, actor, cid)
sql = "SELECT * FROM messages WHERE chat_id=%s"
params = [cid]
if after:
sql += " AND (created_at,id)>(%s,%s)"
params.extend(after)
sql += " ORDER BY created_at,id LIMIT %s"
params.append(limit + 1)
result = []
for row in conn.execute(sql, params).fetchall():
attachments = conn.execute(
"SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position",
(row["id"],),
).fetchall()
result.append(
{
**public(row),
"attachment_ids": [str(a["attachment_id"]) for a in attachments],
}
)
return result
+100
View File
@@ -0,0 +1,100 @@
"""Private S3 access with bounded network waits; never expose storage keys in API."""
import os
from contextlib import contextmanager
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from .config import secret
from .domain import Failure
from .telemetry import operation
class ObjectStorage:
def __init__(self, admin=False):
self.bucket = os.getenv("S3_BUCKET", "messenger")
prefix = "S3_ADMIN" if admin else "S3"
self.client = boto3.client(
"s3",
endpoint_url=os.getenv("S3_ENDPOINT", "http://s3:8333"),
aws_access_key_id=secret(prefix + "_ACCESS_KEY"),
aws_secret_access_key=secret(prefix + "_SECRET_KEY"),
region_name="us-east-1",
config=Config(
connect_timeout=1,
read_timeout=2,
retries={"total_max_attempts": 1},
s3={"addressing_style": "path"},
request_checksum_calculation="when_required",
response_checksum_validation="when_required",
),
)
@contextmanager
def boundary(self):
try:
with operation("s3.request", {"rpc.system": "aws-api", "rpc.service": "S3"}):
yield
except (BotoCoreError, ClientError):
raise Failure(503, "Хранилище файлов временно недоступно") from None
def put(self, key, fileobj, size, content_type):
fileobj.seek(0)
with self.boundary():
self.client.put_object(
Bucket=self.bucket,
Key=key,
Body=fileobj,
ContentLength=size,
ContentType=content_type,
)
def get(self, key):
try:
with operation("s3.get", {"rpc.system": "aws-api", "rpc.service": "S3"}):
return self.client.get_object(Bucket=self.bucket, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404"}:
raise Failure(404, "Объект не найден") from None
raise Failure(503, "Хранилище файлов временно недоступно") from None
except BotoCoreError:
raise Failure(503, "Хранилище файлов временно недоступно") from None
def head(self, key):
try:
with operation("s3.head", {"rpc.system": "aws-api", "rpc.service": "S3"}):
return self.client.head_object(Bucket=self.bucket, Key=key)
except ClientError as exc:
if exc.response.get("Error", {}).get("Code") in {"NoSuchKey", "404", "NotFound"}:
return None
raise Failure(503, "Хранилище файлов временно недоступно") from None
except BotoCoreError:
raise Failure(503, "Хранилище файлов временно недоступно") from None
def exists(self, key):
return self.head(key) is not None
def delete(self, key):
with self.boundary():
self.client.delete_object(Bucket=self.bucket, Key=key)
def objects(self, page_size=100):
with self.boundary():
paginator = self.client.get_paginator("list_objects_v2")
for page in paginator.paginate(
Bucket=self.bucket, PaginationConfig={"PageSize": page_size}
):
yield from page.get("Contents", [])
def ready(self):
try:
with self.boundary():
self.client.head_bucket(Bucket=self.bucket)
return True
except Failure:
return False
def close(self):
self.client.close()
+30
View File
@@ -0,0 +1,30 @@
"""Idempotent private bucket bootstrap; this process alone receives admin keys."""
import time
from botocore.exceptions import BotoCoreError, ClientError
from .storage import ObjectStorage
def main():
storage = ObjectStorage(admin=True)
for attempt in range(30):
try:
try:
storage.client.head_bucket(Bucket=storage.bucket)
except ClientError as exc:
if exc.response["Error"]["Code"] not in {"404", "NoSuchBucket", "NotFound"}:
raise
storage.client.create_bucket(Bucket=storage.bucket)
print("Private bucket ready; anonymous identity is not configured.")
storage.close()
return
except (ClientError, BotoCoreError):
if attempt == 29:
raise RuntimeError("S3 bootstrap timeout") from None
time.sleep(1)
if __name__ == "__main__":
main()
+232
View File
@@ -0,0 +1,232 @@
"""Bounded OTLP telemetry; technical attributes only, no payload/credential capture."""
import json
import logging
import os
import threading
from contextlib import contextmanager
from datetime import UTC, datetime
from uuid import uuid4
import psutil
import requests
from opentelemetry import metrics, propagate, trace
from opentelemetry._logs import set_logger_provider
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.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, SpanExportResult
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
from opentelemetry.trace import SpanKind, Status, StatusCode
HTTP_BUCKETS = (0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
JOB_BUCKETS = (0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 45, 60, 120)
INSTANCE_ID = str(uuid4())
_runtime = None
class CountingSession(requests.Session):
"""Count actual protobuf HTTP sends, including transport retries, without retaining data."""
def __init__(self, stats, signal):
super().__init__()
self.stats, self.signal = stats, signal
def send(self, request, **kwargs):
self.stats[self.signal + "_wire_bytes"] += len(request.body or b"")
self.stats[self.signal + "_http_sends"] += 1
return super().send(request, **kwargs)
class ObservedSpanExporter(OTLPSpanExporter):
def __init__(self, stats, **kwargs):
self.stats = stats
super().__init__(**kwargs)
def export(self, spans):
result = super().export(spans)
key = "spans_exported" if result == SpanExportResult.SUCCESS else "spans_export_failed"
self.stats[key] += len(spans)
return result
class TechnicalLogs(logging.Filter):
def filter(self, record):
return record.name.startswith("messenger")
class JsonFormatter(logging.Formatter):
def format(self, record):
try:
event = json.loads(record.getMessage())
if not isinstance(event, dict):
event = {"event": "application_event"}
except ValueError:
event = {"event": "application_event"}
context = trace.get_current_span().get_span_context()
return json.dumps({
**event,
"timestamp": datetime.now(UTC).isoformat(),
"severity": record.levelname,
"service.name": os.getenv("OTEL_SERVICE_NAME", "messenger-api"),
"trace_id": format(context.trace_id, "032x") if context.is_valid else None,
"span_id": format(context.span_id, "016x") if context.is_valid else None,
})
class Telemetry:
def __init__(self, service):
self.service = service
self.enabled = os.getenv("OTEL_ENABLED", "1") == "1"
self.busy = 0
self.providers = []
self.export_stats = {key: 0 for key in ("spans_exported", "spans_export_failed", "traces_wire_bytes", "traces_http_sends", "metrics_wire_bytes", "metrics_http_sends", "logs_wire_bytes", "logs_http_sends")}
self.stop = threading.Event()
self.thread = None
resource = Resource.create({
"service.name": service,
"service.version": os.getenv("SERVICE_VERSION", "lab6-v1"),
"service.instance.id": INSTANCE_ID,
"deployment.environment.name": "lab",
})
os.environ["OTEL_SERVICE_NAME"] = service
root = logging.getLogger()
root.setLevel(logging.INFO)
for handler in root.handlers:
handler.setFormatter(JsonFormatter())
if not root.handlers:
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
root.addHandler(handler)
if self.enabled:
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4318").rstrip("/")
common = {"timeout": 1.0}
# Standard OTLP environment variables also support HTTPS/mTLS in lab7.
trace_provider = TracerProvider(resource=resource, sampler=ParentBased(
TraceIdRatioBased(float(os.getenv("OTEL_SAMPLE_RATIO", "1")))))
trace_provider.add_span_processor(BatchSpanProcessor(
ObservedSpanExporter(self.export_stats, endpoint=endpoint + "/v1/traces", session=CountingSession(self.export_stats, "traces"), **common),
max_queue_size=256, max_export_batch_size=64,
schedule_delay_millis=500, export_timeout_millis=1500,
))
trace.set_tracer_provider(trace_provider)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=endpoint + "/v1/metrics", session=CountingSession(self.export_stats, "metrics"), **common),
export_interval_millis=int(os.getenv("OTEL_METRIC_INTERVAL_MS", "5000")),
export_timeout_millis=1500,
)
meter_provider = MeterProvider(resource=resource, metric_readers=[reader], views=[
View(instrument_name="messenger.http.duration", aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS)),
View(instrument_name="messenger.job.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
View(instrument_name="messenger.attachment.ready.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
])
metrics.set_meter_provider(meter_provider)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
OTLPLogExporter(endpoint=endpoint + "/v1/logs", session=CountingSession(self.export_stats, "logs"), **common),
max_queue_size=256, max_export_batch_size=64,
schedule_delay_millis=500, export_timeout_millis=1500,
))
set_logger_provider(logger_provider)
otlp_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
otlp_handler.addFilter(TechnicalLogs())
# Keep machine-readable JSON in OTLP log body, preserving request ID.
otlp_handler.setFormatter(JsonFormatter())
root.addHandler(otlp_handler)
self.providers = [trace_provider, meter_provider, logger_provider]
self.tracer = trace.get_tracer("messenger", "1.0")
meter = metrics.get_meter("messenger", "1.0")
self.requests = meter.create_counter("messenger.http.requests", unit="{request}")
self.http_duration = meter.create_histogram("messenger.http.duration", unit="s")
self.sampling = meter.create_counter("messenger.http.trace.decisions", unit="{request}")
self.jobs = meter.create_counter("messenger.jobs", unit="{job}")
self.job_duration = meter.create_histogram("messenger.job.duration", unit="s")
self.ready_duration = meter.create_histogram("messenger.attachment.ready.duration", unit="s")
self.queue_depth = meter.create_gauge("messenger.queue.depth", unit="{job}")
self.oldest_age = meter.create_gauge("messenger.queue.oldest.age", unit="s")
self.pool_used = meter.create_gauge("messenger.db.pool.used", unit="{connection}")
self.pool_waiting = meter.create_gauge("messenger.db.pool.waiting", unit="{request}")
self.worker_busy = meter.create_gauge("messenger.worker.busy", unit="{worker}")
self.worker_capacity = meter.create_gauge("messenger.worker.capacity", unit="{worker}")
self.process_cpu = meter.create_gauge("messenger.process.cpu", unit="%")
self.process_memory = meter.create_gauge("messenger.process.memory", unit="By")
self.export_observation = meter.create_gauge("messenger.telemetry.export", unit="{item}")
def start_background(self, store):
process = psutil.Process()
process.cpu_percent()
def collect():
while not self.stop.wait(2):
for name, value in self.export_stats.items():
self.export_observation.set(value, {"observation": name})
stats = store.pool.get_stats()
self.pool_used.set(max(0, stats.get("pool_size", 0) - stats.get("pool_available", 0)))
self.pool_waiting.set(stats.get("requests_waiting", 0))
self.process_cpu.set(process.cpu_percent())
self.process_memory.set(process.memory_info().rss)
if self.service == "messenger-worker":
self.worker_busy.set(self.busy)
self.worker_capacity.set(1)
if self.service == "messenger-dispatcher":
try:
with store.connection() as conn:
row = conn.execute("SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM now()-min(created_at)),0) AS age FROM attachment_jobs WHERE state IN ('queued','processing')").fetchone()
self.queue_depth.set(row["depth"], {"queue": "attachments"})
self.oldest_age.set(float(row["age"]), {"queue": "attachments"})
except Exception:
logging.getLogger("messenger.telemetry").warning(json.dumps({"event": "queue_observation_unavailable"}))
if self.enabled:
self.thread = threading.Thread(target=collect, name="telemetry-observations", daemon=True)
self.thread.start()
def close(self):
self.stop.set()
if self.thread:
self.thread.join(timeout=4)
# Business shutdown has a fixed budget even if telemetry endpoints are down.
def shutdown_providers():
for provider in self.providers:
provider.shutdown()
shutdown = threading.Thread(target=shutdown_providers, name="telemetry-shutdown", daemon=True)
shutdown.start()
shutdown.join(timeout=2)
def setup(service):
global _runtime
if _runtime is None:
_runtime = Telemetry(service)
return _runtime
def current():
return _runtime
def carrier():
result = {}
propagate.inject(result)
return {key: result[key] for key in ("traceparent", "tracestate") if key in result}
@contextmanager
def operation(name, attributes=None, context=None, kind=SpanKind.CLIENT):
if kind == SpanKind.CLIENT and context is None and not trace.get_current_span().get_span_context().is_valid:
yield trace.get_current_span()
return
tracer = trace.get_tracer("messenger", "1.0")
with tracer.start_as_current_span(name, attributes=attributes or {}, context=context,
kind=kind, record_exception=False,
set_status_on_exception=False) as span:
try:
yield span
except BaseException as exc:
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raise
+286
View File
@@ -0,0 +1,286 @@
"""Separate serial worker (prefetch=1) and transactional-outbox dispatcher."""
import argparse
import hashlib
import json
import logging
import re
import signal
import subprocess
import sys
import tempfile
import time
from datetime import datetime
from pathlib import Path
from uuid import UUID, uuid4
import redis
from opentelemetry import propagate, trace
from opentelemetry.trace import SpanKind, Status, StatusCode
from . import telemetry
from .domain import Failure
from .jobs import GROUP, STREAM, Jobs, broker_client, fault
from .postgres import PostgresStore
from .storage import ObjectStorage
logger = logging.getLogger("messenger.worker")
logging.basicConfig(level=logging.INFO, format="%(message)s")
stopping = False
MAX_JOB_BYTES = 8192
def stop(signum, frame):
global stopping
stopping = True
def process(job, jobs, storage):
fault(jobs.store, "before_effect", job["attachment_id"])
with tempfile.TemporaryDirectory(prefix="image-job-") as directory:
root = Path(directory)
source = root / "source"
response = storage.get(job["source_key"])
try:
if response["ContentLength"] > 10_485_760:
raise ValueError("invalid_image")
with source.open("wb") as target:
while block := response["Body"].read(64 * 1024):
target.write(block)
if target.tell() > 10_485_760:
raise ValueError("invalid_image")
finally:
response["Body"].close()
with source.open("rb") as file:
digest = hashlib.file_digest(file, "sha256").hexdigest()
if digest != job["source_sha256"] or source.stat().st_size != job["source_size"]:
raise ValueError("invalid_image")
# Resize executes outside the API and is bounded in wall time, CPU and address space.
result = subprocess.run(
[
sys.executable,
"-m",
"messenger.image_pipeline",
str(source),
directory,
str(job["pipeline_version"]),
],
timeout=20,
capture_output=True,
check=False,
)
if result.returncode:
raise ValueError("invalid_image")
variants = json.loads((root / "variants.json").read_text())
prefix = f"attachments/{job['attachment_id']}/v{job['pipeline_version']}"
with source.open("rb") as file:
storage.put(
prefix + "/original", file, source.stat().st_size, job["source_content_type"]
)
for variant in variants:
path = root / variant["name"]
with path.open("rb") as file:
storage.put(
prefix + "/" + variant["name"],
file,
variant["size_bytes"],
variant["content_type"],
)
fault(jobs.store, "after_effect", job["attachment_id"])
published = jobs.complete(job, prefix + "/original", variants)
if published:
fault(jobs.store, "after_result_commit", job["attachment_id"])
cleanup_ready(jobs.store, storage, job["attachment_id"])
return published
def cleanup_ready(store, storage, attachment_id):
# Same row lock as reprocess/replay: cannot delete a source chosen by a new job.
with store.connection() as conn, conn.transaction():
a = conn.execute(
"SELECT * FROM attachments WHERE id=%s FOR UPDATE", (attachment_id,)
).fetchone()
if (
a
and a["status"] == "ready"
and a["stage_key"]
and a["stage_key"].startswith("staging/")
):
storage.delete(a["stage_key"])
conn.execute("UPDATE attachments SET stage_key=NULL WHERE id=%s", (attachment_id,))
def validate_delivery(body):
if not isinstance(body, (str, bytes, bytearray)):
raise ValueError("invalid_job")
encoded = body.encode("utf-8") if isinstance(body, str) else body
if len(encoded) > MAX_JOB_BYTES:
raise ValueError("invalid_job")
try:
data = json.loads(encoded)
except RecursionError:
raise ValueError("invalid_job") from None
expected = {
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at",
}
optional = {"traceparent", "tracestate"}
if not isinstance(data, dict) or not expected <= set(data) or set(data) - expected - optional:
raise ValueError("invalid_job")
if (
type(data["schema_version"]) is not int
or data["schema_version"] != 1
or data["type"] != "attachment.process.v1"
):
raise ValueError("invalid_job")
if not isinstance(data["job_id"], str) or not isinstance(data["attachment_id"], str):
raise ValueError("invalid_job")
for field in ("job_id", "attachment_id"):
canonical = str(UUID(data[field]))
if data[field].lower() != canonical:
raise ValueError("invalid_job")
# RFC UUID hex is case-insensitive; PostgreSQL and state comparisons use
# the same canonical spelling, so a valid uppercase delivery is not lost.
data[field] = canonical
if type(data["pipeline_version"]) is not int or data["pipeline_version"] < 1:
raise ValueError("invalid_job")
if type(data["attempt"]) is not int or data["attempt"] < 1:
raise ValueError("invalid_job")
created = data["created_at"]
if (
not isinstance(created, str)
or len(created) > 64
or not re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?Z", created
)
):
raise ValueError("invalid_job")
datetime.fromisoformat(created[:-1] + "+00:00")
if "traceparent" in data and (
not isinstance(data["traceparent"], str)
or not re.fullmatch(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", data["traceparent"])
):
raise ValueError("invalid_job")
if "tracestate" in data and (
not isinstance(data["tracestate"], str) or len(data["tracestate"]) > 512
):
raise ValueError("invalid_job")
return data
def consume_one(store, jobs, storage, broker, entry):
entry_id, fields = entry
try:
body = validate_delivery(fields.get("body", fields.get(b"body")))
except (KeyError, ValueError, TypeError):
logger.error(json.dumps({"event": "invalid_delivery"}))
broker.xack(STREAM, GROUP, entry_id)
broker.xdel(STREAM, entry_id)
return
with telemetry.operation("attachments consume", context=propagate.extract(body), kind=SpanKind.CONSUMER):
consume_job(store, jobs, storage, broker, body)
# Durable state owns recovery even when notification acknowledgements repeat.
broker.xack(STREAM, GROUP, entry_id)
broker.xdel(STREAM, entry_id)
def consume_job(store, jobs, storage, broker, body):
job = jobs.claim(body["job_id"], body["attachment_id"], body["pipeline_version"])
t = telemetry.current()
started = time.perf_counter()
outcome = "duplicate"
if job:
try:
if t:
t.busy = 1
outcome = "success" if process(job, jobs, storage) else "superseded"
except ValueError:
jobs.fail(job, "invalid_image", permanent=True)
outcome = "failed"
except (Failure, subprocess.TimeoutExpired, OSError, RuntimeError) as exc:
logger.warning(
json.dumps(
{"event": "job_retry", "job_id": str(job["id"]), "kind": type(exc).__name__}
)
)
jobs.fail(job, "processing_failed")
outcome = "retry" if job["attempt"] < job["attempt_limit"] else "failed"
finally:
if t:
t.busy = 0
attrs = {"job_type": "attachment.process.v1", "outcome": outcome}
t.jobs.add(1, attrs)
t.job_duration.record(time.perf_counter() - started, attrs)
span = trace.get_current_span()
span.set_attributes({"job.type": "attachment.process.v1", "job.outcome": outcome})
if outcome in {"failed", "retry"}:
span.set_status(Status(StatusCode.ERROR, "processing_failed"))
logger.info(json.dumps({"event": "job_finished", "outcome": outcome}))
else:
trace.get_current_span().set_attributes({"job.type": "attachment.process.v1", "job.outcome": "duplicate"})
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dispatcher", action="store_true")
args = parser.parse_args()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
t = telemetry.setup("messenger-dispatcher" if args.dispatcher else "messenger-worker")
store = PostgresStore()
t.start_background(store)
jobs = Jobs(store)
broker = broker_client()
storage = None if args.dispatcher else ObjectStorage()
consumer = "worker-" + str(uuid4())
last_claim = 0
try:
while not stopping:
try:
if args.dispatcher:
jobs.recover_one()
if not jobs.publish_one(broker):
time.sleep(0.2)
continue
try:
broker.xgroup_create(STREAM, GROUP, id="0", mkstream=True)
except redis.ResponseError as exc:
if "BUSYGROUP" not in str(exc):
raise
entries = []
if time.monotonic() - last_claim >= 5:
claimed = broker.xautoclaim(
STREAM,
GROUP,
consumer,
min_idle_time=jobs.lease_seconds * 1000,
start_id="0-0",
count=1,
)
entries = claimed[1]
last_claim = time.monotonic()
if not entries:
batches = broker.xreadgroup(GROUP, consumer, {STREAM: ">"}, count=1, block=500)
entries = batches[0][1] if batches else []
for entry in entries:
consume_one(store, jobs, storage, broker, entry)
except (redis.RedisError, Failure) as exc:
logger.warning(
json.dumps({"event": "dependency_retry", "kind": type(exc).__name__})
)
time.sleep(0.5)
finally:
broker.close()
if storage is not None:
storage.close()
t.close()
store.close()
if __name__ == "__main__":
main()