forked from mtusi2026/mtusi2026lab7
Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""Messenger for the MTUSI course «Высоконагруженные приложения» (lab 6: observability)."""
|
||||
|
||||
__version__ = "1.6.0"
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Entry point: `python -m messenger`. The HTTP server is the main process (PID 1 in Docker).
|
||||
|
||||
Shutdown sequence on SIGTERM/SIGINT (lab 3: the replica stands behind HAProxy):
|
||||
1. readiness flips to 503 (`app.state.draining = True`), requests are still served;
|
||||
2. after DRAIN_SECONDS (compose: 3 s > HAProxy detection 2 x 1 s) the load balancer has
|
||||
marked this replica DOWN and sends nothing new here;
|
||||
3. uvicorn closes the listening socket; in-flight requests get up to
|
||||
SHUTDOWN_TIMEOUT_SECONDS (compose: 8 s) to finish;
|
||||
4. the lifespan closes the DB pool and the Valkey client; the process exits with code 0.
|
||||
DRAIN + SHUTDOWN (11 s) < compose stop_grace_period (15 s), so Docker never needs SIGKILL.
|
||||
A second signal during the drain skips the rest of it. Data stays in PostgreSQL and Valkey.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from types import FrameType
|
||||
|
||||
import uvicorn
|
||||
|
||||
from . import __version__, logging_setup, telemetry
|
||||
from .app import create_app
|
||||
from .config import ConfigError, Settings
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
|
||||
class GracefulServer(uvicorn.Server):
|
||||
"""uvicorn.Server that drains (readiness 503, still serving) before the normal graceful stop."""
|
||||
|
||||
def __init__(self, config: uvicorn.Config, drain_seconds: float):
|
||||
super().__init__(config)
|
||||
self.drain_seconds = drain_seconds
|
||||
self.drain_timer: threading.Timer | None = None
|
||||
|
||||
def handle_exit(self, sig: int, frame: FrameType | None) -> None:
|
||||
self.config.app.state.draining = True # config.app is our Starlette instance
|
||||
if self.drain_timer is None and self.drain_seconds > 0 and not self.should_exit:
|
||||
log.info("drain_started", extra={"fields": {"signal": sig, "drain_s": self.drain_seconds,
|
||||
"timeout_s": self.config.timeout_graceful_shutdown}})
|
||||
# uvicorn polls should_exit in its main loop, so setting it from a timer thread is safe.
|
||||
self.drain_timer = threading.Timer(self.drain_seconds, self._stop, args=(sig, frame))
|
||||
self.drain_timer.daemon = True
|
||||
self.drain_timer.start()
|
||||
return
|
||||
if self.drain_timer is not None:
|
||||
self.drain_timer.cancel() # second signal: stop draining now
|
||||
self._stop(sig, frame)
|
||||
|
||||
def _stop(self, sig: int, frame: FrameType | None) -> None:
|
||||
if not self.should_exit:
|
||||
log.info("shutdown_requested", extra={"fields": {"signal": sig}})
|
||||
super().handle_exit(sig, frame)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
settings = Settings.from_env()
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
logging_setup.configure(settings.log_level)
|
||||
telemetry.setup("messenger-api", settings.instance_id, __version__)
|
||||
app = create_app(settings)
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
log_config=None,
|
||||
access_log=False,
|
||||
server_header=False,
|
||||
proxy_headers=False,
|
||||
lifespan="on",
|
||||
timeout_graceful_shutdown=settings.shutdown_timeout,
|
||||
)
|
||||
server = GracefulServer(config, settings.drain_seconds)
|
||||
log.info("starting", extra={"fields": {
|
||||
"version": __version__, "revision": os.environ.get("APP_REVISION", "dev"), "env": settings.env, "host": settings.host, "port": settings.port,
|
||||
"python": sys.version.split()[0], "storage": "postgresql", "instance_id": settings.instance_id,
|
||||
}})
|
||||
try:
|
||||
server.run()
|
||||
finally:
|
||||
log.info("stopped")
|
||||
telemetry.shutdown() # flush buffered spans/logs/metrics, bounded by the exporter timeouts
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,682 @@
|
||||
"""HTTP layer: Starlette routes, request-id/logging middleware and error mapping."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from starlette.applications import Starlette
|
||||
from starlette.exceptions import HTTPException
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse, Response, StreamingResponse
|
||||
from starlette.routing import Route
|
||||
from starlette.types import ASGIApp, Message as AsgiMessage, Receive, Scope, Send
|
||||
|
||||
from opentelemetry import context as otel_context
|
||||
from opentelemetry import trace
|
||||
|
||||
from . import attachments, authhdr, cursor, docs, passwords, repo, telemetry, validation
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import BASIC_CHALLENGE, ApiError, Conflict, InvalidRequest, NotFound, PayloadTooLarge, Unauthorized, Unavailable
|
||||
from .sessions import SessionStore, build_store
|
||||
from .storage import ObjectMissing, Storage
|
||||
from .timefmt import rfc3339
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
access_log = logging.getLogger("messenger.access")
|
||||
|
||||
REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Responses
|
||||
# --------------------------------------------------------------------------
|
||||
def error_response(request_id: str, status: int, code: str, message: str, headers: dict[str, str] | None = None) -> JSONResponse:
|
||||
body = {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
return JSONResponse(body, status_code=status, headers={"X-Request-Id": request_id, **(headers or {})})
|
||||
|
||||
|
||||
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
assert isinstance(exc, ApiError)
|
||||
return error_response(request.state.request_id, exc.status, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
"""Unknown routes and wrong methods also answer in the contract error format."""
|
||||
assert isinstance(exc, HTTPException)
|
||||
if exc.status_code == 404:
|
||||
return error_response(request.state.request_id, 404, "not_found", "Объект не найден")
|
||||
if exc.status_code == 405:
|
||||
return error_response(request.state.request_id, 405, "invalid_request", "Метод не поддерживается", exc.headers)
|
||||
return error_response(request.state.request_id, exc.status_code, "invalid_request", "Неверный запрос")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Middleware (pure ASGI, so it also covers 404/405 and unexpected exceptions)
|
||||
# --------------------------------------------------------------------------
|
||||
class RequestContextMiddleware:
|
||||
"""Adds X-Request-Id and X-Instance-Id to EVERY response (errors, health and crash 500/503
|
||||
included), writes one access-log line, turns crashes into 500.
|
||||
|
||||
Lab 6: this outermost middleware is also the HTTP SERVER span and the HTTP metrics. The span
|
||||
continues the caller's W3C `traceparent` (extracted from the headers BEFORE the span starts,
|
||||
so a client-supplied trace is continued, not replaced by a new root). The route TEMPLATE
|
||||
(`/api/v1/chats/{chat_id}/messages`) is taken from the Starlette route that served the request,
|
||||
never the raw path: it names the span and labels the metrics. /health/* gets metrics but no
|
||||
span (HAProxy and Docker poll it every second; those traces would only bury the real ones).
|
||||
Response header X-Trace-Id = the trace of this request (to find it in Grafana/Tempo)."""
|
||||
|
||||
def __init__(self, app: ASGIApp, instance_id: str):
|
||||
self.app = app
|
||||
self.instance_id = instance_id.encode("ascii")
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
raw_headers = scope["headers"]
|
||||
incoming = dict(raw_headers).get(b"x-request-id", b"").decode("latin-1")
|
||||
request_id = incoming if REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex
|
||||
scope.setdefault("state", {})["request_id"] = request_id
|
||||
method = scope["method"] if scope["method"] in KNOWN_METHODS else "_OTHER"
|
||||
traced = not scope["path"].startswith("/health/")
|
||||
span = (telemetry.TRACER.start_span(f"{method}", kind=telemetry.SpanKind.SERVER,
|
||||
context=telemetry.extract_headers(raw_headers),
|
||||
attributes={"http.request.method": method, "url.scheme": "http",
|
||||
"messenger.request_id": request_id,
|
||||
"service.instance.id": self.instance_id.decode("ascii")})
|
||||
if traced else None)
|
||||
token = otel_context.attach(trace.set_span_in_context(span)) if span is not None else None
|
||||
trace_header = None
|
||||
if span is not None and span.get_span_context().is_valid:
|
||||
trace_header = format(span.get_span_context().trace_id, "032x").encode("ascii")
|
||||
status = 500
|
||||
started = False
|
||||
begin = time.perf_counter()
|
||||
telemetry.http_active.add(1, {"http.request.method": method})
|
||||
|
||||
async def send_with_id(message: AsgiMessage) -> None:
|
||||
nonlocal status, started
|
||||
if message["type"] == "http.response.start":
|
||||
started = True
|
||||
status = message["status"]
|
||||
headers = [(k, v) for k, v in message.get("headers", [])
|
||||
if k.lower() not in (b"x-request-id", b"x-instance-id", b"x-trace-id")]
|
||||
headers.append((b"x-request-id", request_id.encode("latin-1")))
|
||||
headers.append((b"x-instance-id", self.instance_id))
|
||||
if trace_header is not None:
|
||||
headers.append((b"x-trace-id", trace_header))
|
||||
message = {**message, "headers": headers}
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_with_id)
|
||||
except asyncio.CancelledError:
|
||||
# uvicorn cancels requests still running when SHUTDOWN_TIMEOUT_SECONDS expires:
|
||||
# answer 503 (retryable) instead of a generic 500, then let the cancellation proceed.
|
||||
if not started:
|
||||
status = 503
|
||||
response = error_response(request_id, 503, "unavailable", "Сервер завершает работу")
|
||||
await response(scope, receive, send_with_id)
|
||||
raise
|
||||
except Exception as exc:
|
||||
log.exception("unhandled_error", extra={"fields": {"request_id": request_id}})
|
||||
if span is not None:
|
||||
span.record_exception(exc) # type + stack (code lines only), never request data
|
||||
if not started:
|
||||
status = 500
|
||||
response = error_response(request_id, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
await response(scope, receive, send_with_id)
|
||||
finally:
|
||||
elapsed = time.perf_counter() - begin
|
||||
route = route_template(scope)
|
||||
attributes = {"http.request.method": method, "http.route": route,
|
||||
"http.response.status_code": status, "http.response.status_class": f"{status // 100}xx"}
|
||||
telemetry.http_duration.record(elapsed, attributes)
|
||||
telemetry.http_active.add(-1, {"http.request.method": method})
|
||||
access_log.info("request", extra={"fields": {
|
||||
"request_id": request_id,
|
||||
"method": scope["method"],
|
||||
"path": scope["path"], # ids only; query (cursor) and bodies are never logged
|
||||
"route": route,
|
||||
"status": status,
|
||||
"instance_id": self.instance_id.decode("ascii"),
|
||||
"duration_ms": round(elapsed * 1000, 3),
|
||||
}})
|
||||
if span is not None:
|
||||
span.update_name(f"{method} {route}")
|
||||
span.set_attribute("http.route", route)
|
||||
span.set_attribute("http.response.status_code", status)
|
||||
if status >= 500:
|
||||
telemetry.mark_error(span, str(status)) # 4xx is the client's problem: not an error of the server span
|
||||
span.end()
|
||||
otel_context.detach(token)
|
||||
|
||||
|
||||
KNOWN_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
|
||||
|
||||
|
||||
def route_template(scope: Scope) -> str:
|
||||
"""Template of the route that matched (set by the Starlette router), e.g.
|
||||
/api/v1/chats/{chat_id}/messages. Unknown paths share ONE label value, so a scanner hitting
|
||||
random URLs cannot create new metric series."""
|
||||
route = scope.get("route")
|
||||
path = getattr(route, "path", None)
|
||||
return path if isinstance(path, str) else "UNMATCHED"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Request helpers
|
||||
# --------------------------------------------------------------------------
|
||||
def db_of(request: Request) -> Database:
|
||||
return request.app.state.db
|
||||
|
||||
|
||||
def sessions_of(request: Request) -> SessionStore:
|
||||
return request.app.state.sessions
|
||||
|
||||
|
||||
def storage_of(request: Request) -> Storage:
|
||||
return request.app.state.storage
|
||||
|
||||
|
||||
def staging_of(request: Request) -> Storage:
|
||||
return request.app.state.staging
|
||||
|
||||
|
||||
async def authenticate(request: Request) -> str:
|
||||
"""User id of a valid Bearer session, otherwise 401. X-User-Id is ignored since lab 2.
|
||||
|
||||
Store failures are 503 (Unavailable), never 401 and never anonymous access.
|
||||
"""
|
||||
token = authhdr.parse_bearer(request.headers.get("authorization"))
|
||||
user_id = await sessions_of(request).user_id_for(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
return user_id
|
||||
|
||||
|
||||
def path_uuid(request: Request, name: str) -> str:
|
||||
return validation.parse_uuid(request.path_params[name], name)
|
||||
|
||||
|
||||
async def read_json(request: Request) -> dict[str, Any]:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
media_type, _, params = content_type.partition(";")
|
||||
if media_type.strip().lower() != "application/json":
|
||||
raise InvalidRequest("Content-Type должен быть application/json")
|
||||
charset = params.strip().lower()
|
||||
if charset and charset.replace(" ", "") not in {"charset=utf-8", "charset=\"utf-8\""}:
|
||||
raise InvalidRequest("Поддерживается только кодировка UTF-8")
|
||||
limit: int = request.app.state.settings.max_body_bytes
|
||||
declared = request.headers.get("content-length")
|
||||
if declared is not None and declared.isdigit() and int(declared) > limit:
|
||||
raise PayloadTooLarge()
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise PayloadTooLarge()
|
||||
chunks.append(chunk)
|
||||
return validation.parse_json_object(b"".join(chunks))
|
||||
|
||||
|
||||
def page_params(request: Request) -> tuple[int, str | None]:
|
||||
query = request.query_params.multi_items()
|
||||
limit = validation.parse_limit(validation.single_query_param(query, "limit"))
|
||||
raw_cursor = validation.single_query_param(query, "cursor")
|
||||
if raw_cursor is not None and raw_cursor == "":
|
||||
raise InvalidRequest("cursor не может быть пустым")
|
||||
return limit, raw_cursor
|
||||
|
||||
|
||||
async def reject_body(request: Request) -> None:
|
||||
"""POST /auth/sessions takes credentials only from the Basic header; any body is 400."""
|
||||
if request.headers.get("transfer-encoding") or request.headers.get("content-length", "0") != "0":
|
||||
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
|
||||
async for chunk in request.stream():
|
||||
if chunk:
|
||||
raise InvalidRequest("Вход принимает только заголовок Authorization: Basic, без тела")
|
||||
|
||||
|
||||
def idempotency_key(request: Request) -> str:
|
||||
values = request.headers.getlist("idempotency-key")
|
||||
return validation.idempotency_key(values[0] if len(values) == 1 else None)
|
||||
|
||||
|
||||
def request_fingerprint(text: str, attachment_ids: list[str]) -> bytes:
|
||||
"""SHA-256 of the canonical body: key order and an absent attachment_ids vs [] do not matter."""
|
||||
canonical = json.dumps({"attachment_ids": attachment_ids, "text": text},
|
||||
ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(canonical.encode("utf-8")).digest()
|
||||
|
||||
|
||||
def ok(body: Any, status: int = 200) -> JSONResponse:
|
||||
return JSONResponse(body, status_code=status)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Handlers
|
||||
# --------------------------------------------------------------------------
|
||||
async def live(request: Request) -> JSONResponse:
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def ready(request: Request) -> JSONResponse:
|
||||
"""200 only if the WHOLE mandatory synchronous path can be served: PostgreSQL, Valkey
|
||||
(SESSION_STORE=valkey) and, since lab 4, the S3 bucket (upload/download of attachments)
|
||||
answer. 503 while draining after SIGTERM. HAProxy routes to such replicas first."""
|
||||
if request.app.state.draining:
|
||||
raise Unavailable("Сервер завершает работу")
|
||||
db_ok, store_ok, s3_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping(),
|
||||
storage_of(request).ping())
|
||||
if not db_ok:
|
||||
raise Unavailable("PostgreSQL недоступен")
|
||||
if not store_ok:
|
||||
raise Unavailable("Хранилище сессий недоступно")
|
||||
if not s3_ok:
|
||||
raise Unavailable("Хранилище файлов (S3) недоступно")
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def ready_core(request: Request) -> JSONResponse:
|
||||
"""Not in the contract: readiness WITHOUT S3, for the load balancer's degraded mode only.
|
||||
If S3 is down for every replica, /health/ready is 503 everywhere; HAProxy then routes to
|
||||
replicas that are at least core-ready, so chats and messages keep working while every
|
||||
attachment request answers 503 itself (see infra/haproxy/haproxy.cfg)."""
|
||||
if request.app.state.draining:
|
||||
raise Unavailable("Сервер завершает работу")
|
||||
db_ok, store_ok = await asyncio.gather(db_of(request).ping(), sessions_of(request).ping())
|
||||
if not (db_ok and store_ok):
|
||||
raise Unavailable("PostgreSQL или хранилище сессий недоступно")
|
||||
return ok({"status": "ok"})
|
||||
|
||||
|
||||
async def register_user(request: Request) -> JSONResponse:
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"username", "display_name", "password"})
|
||||
username = validation.username_field(data)
|
||||
display_name = validation.text_field(data, "display_name", 100)
|
||||
password = validation.password_field(data)
|
||||
password_hash = await passwords.hash_password(password)
|
||||
user = await repo.create_user(db_of(request), username, display_name, password_hash)
|
||||
log.info("user_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
|
||||
return ok(user.to_json(), 201)
|
||||
|
||||
|
||||
async def create_session(request: Request) -> JSONResponse:
|
||||
"""Login: only `Authorization: Basic`; wrong user and wrong password give the same 401."""
|
||||
username, password = authhdr.parse_basic(request.headers.get("authorization"))
|
||||
await reject_body(request)
|
||||
found = await repo.get_credentials(db_of(request), username)
|
||||
user, stored_hash = found if found else (None, None)
|
||||
if not await passwords.verify_password(stored_hash, password) or user is None:
|
||||
log.info("login_failed", extra={"fields": {"request_id": request.state.request_id}})
|
||||
raise Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE)
|
||||
ttl = request.app.state.settings.session_ttl_seconds
|
||||
token, expires_at = await sessions_of(request).create(user.id, ttl)
|
||||
log.info("session_created", extra={"fields": {"request_id": request.state.request_id, "user_id": user.id}})
|
||||
return ok({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires_at), "user": user.to_json()}, 201)
|
||||
|
||||
|
||||
async def revoke_session(request: Request) -> Response:
|
||||
token = authhdr.parse_bearer(request.headers.get("authorization"))
|
||||
if not await sessions_of(request).revoke(token):
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
log.info("session_revoked", extra={"fields": {"request_id": request.state.request_id}})
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
async def me(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
user = await repo.get_user(db_of(request), user_id)
|
||||
if user is None:
|
||||
raise Unauthorized("Сессия недействительна, истекла или отозвана")
|
||||
return ok(user.to_json())
|
||||
|
||||
|
||||
async def create_chat(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
data = await read_json(request)
|
||||
validation.check_fields(data, {"title", "member_ids"})
|
||||
title = validation.text_field(data, "title", 100)
|
||||
member_ids = validation.member_ids_field(data)
|
||||
chat = await repo.create_chat(db_of(request), user_id, title, member_ids)
|
||||
log.info("chat_created", extra={"fields": {"request_id": request.state.request_id, "chat_id": chat.id, "members": len(member_ids)}})
|
||||
return ok(chat.to_json(), 201)
|
||||
|
||||
|
||||
async def list_chats(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
limit, raw_cursor = page_params(request)
|
||||
after = cursor.decode(raw_cursor, cursor.CHATS, user_id) if raw_cursor else None
|
||||
items, has_more = await repo.list_chats(db_of(request), user_id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.CHATS, user_id, items[-1].key) if has_more else None
|
||||
return ok({"items": [c.to_json() for c in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
async def get_chat(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
return ok((await repo.get_chat(db_of(request), user_id, chat_id)).to_json())
|
||||
|
||||
|
||||
def parse_message(data: dict[str, Any]) -> tuple[str, list[str]]:
|
||||
"""`text` is required and a string (also with attachments); `attachment_ids`, if present, an
|
||||
array of 0-10 unique UUIDs. "" or whitespace-only text is allowed only with attachments."""
|
||||
validation.check_fields(data, {"text"}, frozenset({"attachment_ids"}))
|
||||
attachment_ids = validation.attachment_ids_field(data)
|
||||
text = validation.text_field(data, "text", 4000, min_len=0 if attachment_ids else 1,
|
||||
allow_blank=bool(attachment_ids))
|
||||
return text, attachment_ids
|
||||
|
||||
|
||||
async def create_message(request: Request) -> JSONResponse:
|
||||
"""Order of answers for both write paths: 401 -> 400 bad chat id -> 404 outsider -> 400 key/body
|
||||
-> 409 other body with the same key -> 201 (new or replayed). sender_id comes from the session."""
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
settings = request.app.state.settings
|
||||
await message_faults(request)
|
||||
if settings.message_write_path == "multi":
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders get 404 before key/body are looked at
|
||||
key = idempotency_key(request)
|
||||
text, attachment_ids = parse_message(await read_json(request))
|
||||
result = await repo.post_message(db, user_id, chat_id, key, request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds, attachment_ids)
|
||||
else:
|
||||
try:
|
||||
key = idempotency_key(request)
|
||||
text, attachment_ids = parse_message(await read_json(request))
|
||||
except ApiError:
|
||||
# Rare error path only: an outsider must still get 404, not a hint about the body.
|
||||
await repo.ensure_member(db, user_id, chat_id)
|
||||
raise
|
||||
# Membership check, key claim, chat clock and message: one SQL call, one transaction.
|
||||
result = await repo.post_message_single_call(db, user_id, chat_id, key,
|
||||
request_fingerprint(text, attachment_ids), text,
|
||||
settings.idempotency_ttl_seconds, attachment_ids)
|
||||
if result.replayed:
|
||||
log.info("idempotent_replay", extra={"fields": {"request_id": request.state.request_id,
|
||||
"message_id": result.message.id}})
|
||||
return ok(result.message.to_json(), 201)
|
||||
|
||||
|
||||
async def list_messages(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # 404 for outsiders before cursor details leak
|
||||
limit, raw_cursor = page_params(request)
|
||||
after = cursor.decode(raw_cursor, cursor.MESSAGES, chat_id) if raw_cursor else None
|
||||
items, has_more = await repo.list_messages(db, chat_id, after, limit)
|
||||
next_cursor = cursor.encode(cursor.MESSAGES, chat_id, items[-1].key) if has_more else None
|
||||
return ok({"items": [m.to_json() for m in items], "next_cursor": next_cursor})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ attachments (lab 4, lab 5)
|
||||
async def message_faults(request: Request) -> None:
|
||||
"""Lab 6 experiments (API_FAULT_POINTS slow_handler / random_5xx / random_slow); no-op normally."""
|
||||
settings: Settings = request.app.state.settings
|
||||
points = settings.fault_points
|
||||
if not points:
|
||||
return
|
||||
if "random_5xx" in points and random.random() * 1000 < settings.fault_value("random_5xx", 10):
|
||||
log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": "random_5xx"}})
|
||||
raise Unavailable("Внедрённый отказ: random_5xx")
|
||||
if "random_slow" in points and random.random() * 1000 < settings.fault_value("random_slow", 10):
|
||||
await asyncio.sleep(0.5)
|
||||
if "slow_handler" in points:
|
||||
await asyncio.sleep(settings.fault_value("slow_handler", 300) / 1000)
|
||||
|
||||
|
||||
def fault(request: Request, point: str) -> None:
|
||||
"""Failure injection for the experiments (FAULT_POINTS of the api service, compose variable
|
||||
API_FAULT_POINTS; empty in normal runs)."""
|
||||
if point in request.app.state.settings.fault_points:
|
||||
log.warning("fault_injected", extra={"fields": {"request_id": request.state.request_id, "point": point}})
|
||||
raise Unavailable("Внедрённый отказ: " + point)
|
||||
|
||||
|
||||
async def upload_attachment(request: Request) -> JSONResponse:
|
||||
"""POST /chats/{chat_id}/attachments?filename=...: raw PNG/JPEG -> 202 queued (attachments.py)."""
|
||||
settings: Settings = request.app.state.settings
|
||||
reader = attachments.BodyReader(request)
|
||||
slots: asyncio.Semaphore = request.app.state.upload_slots
|
||||
acquired = False
|
||||
try:
|
||||
try:
|
||||
user_id = await authenticate(request)
|
||||
chat_id = path_uuid(request, "chat_id")
|
||||
db = db_of(request)
|
||||
await repo.ensure_member(db, user_id, chat_id) # outsiders: 404 before anything about the body
|
||||
filename = validation.filename_param(validation.query_items(request.scope["query_string"]))
|
||||
declared = attachments.declared_type(request)
|
||||
length = attachments.declared_length(request, settings.max_upload_bytes)
|
||||
try:
|
||||
await asyncio.wait_for(slots.acquire(), settings.upload_queue_timeout_seconds)
|
||||
except asyncio.TimeoutError:
|
||||
raise attachments.Busy("Слишком много одновременных загрузок, повторите позже") from None
|
||||
acquired = True
|
||||
upload = await attachments.read_image(reader, settings, declared, request.app.state.verify_slots, length)
|
||||
except ApiError:
|
||||
# Early rejection: drop (not store) a bounded rest of the body so the client reads our error.
|
||||
await reader.discard(settings.max_upload_bytes + (1 << 20), timeout=5.0)
|
||||
raise
|
||||
# The slot is held until the buffer is no longer needed (after the S3 PUT), so at most
|
||||
# UPLOAD_CONCURRENCY bodies of this replica exist in memory at any moment.
|
||||
return await store_upload(request, db, chat_id, user_id, filename, upload)
|
||||
finally:
|
||||
if acquired:
|
||||
slots.release()
|
||||
|
||||
|
||||
async def store_upload(request: Request, db: Database, chat_id: str, user_id: str, filename: str,
|
||||
upload: attachments.Upload) -> JSONResponse:
|
||||
"""intent (pending) -> staging PUT -> queued + job + outbox -> 202 (docs/PIPELINE.md).
|
||||
No resize here: the worker does it; a stopped worker only delays `ready`."""
|
||||
settings: Settings = request.app.state.settings
|
||||
attachment_id = uuid.uuid4()
|
||||
staging_key = attachments.new_staging_key()
|
||||
await attachments.create_intent(db, attachment_id, chat_id, user_id, filename, upload.info, len(upload.data),
|
||||
upload.sha256, staging_key)
|
||||
await staging_of(request).put(staging_key, upload.data, upload.info.content_type,
|
||||
{"attachment-id": str(attachment_id), "sha256": upload.sha256.hex()})
|
||||
fault(request, "after_s3_put")
|
||||
attachment = await attachments.enqueue(db, attachment_id, settings)
|
||||
if attachment is None:
|
||||
raise Unavailable("Загрузка не завершена, повторите запрос")
|
||||
fault(request, "after_enqueue_commit")
|
||||
log.info("attachment_queued", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id, "chat_id": chat_id,
|
||||
"size": attachment.size_bytes, "type": attachment.content_type,
|
||||
"pipeline_version": settings.pipeline_version}})
|
||||
return ok(attachment.to_json(), 202)
|
||||
|
||||
|
||||
async def get_attachment(request: Request) -> JSONResponse:
|
||||
user_id = await authenticate(request)
|
||||
attachment_id = path_uuid(request, "attachment_id")
|
||||
return ok((await attachments.get_visible(db_of(request), user_id, attachment_id)).to_json())
|
||||
|
||||
|
||||
def content_disposition(filename: str) -> str:
|
||||
"""RFC 6266/5987: ASCII fallback + UTF-8 name; the stored name itself is never interpreted."""
|
||||
from urllib.parse import quote
|
||||
fallback = "".join(c if 32 <= ord(c) < 127 and c not in '"\\%;' else "_" for c in filename)
|
||||
return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(filename, safe='')}"
|
||||
|
||||
|
||||
async def download_attachment(request: Request) -> Response:
|
||||
"""Original or variant bytes through the authorized API: no redirect, no public S3 URL.
|
||||
queued/processing/failed -> 409 (not ready); a variant a ready attachment lacks -> 404.
|
||||
Streamed from S3 in 64 KiB chunks (memory per download does not depend on the file size)."""
|
||||
user_id = await authenticate(request)
|
||||
attachment_id = path_uuid(request, "attachment_id")
|
||||
query = validation.query_items(request.scope["query_string"])
|
||||
try:
|
||||
variant = validation.variant_param(query)
|
||||
except ApiError:
|
||||
await attachments.get_visible(db_of(request), user_id, attachment_id) # 404 for outsiders first
|
||||
raise
|
||||
attachment = await attachments.get_visible(db_of(request), user_id, attachment_id)
|
||||
if attachment.status != "ready":
|
||||
raise Conflict("Обработка вложения не удалась" if attachment.status == "failed" else "Вложение ещё не готово")
|
||||
if attachment.lost:
|
||||
raise NotFound("Оригинал вложения утрачен")
|
||||
if variant == "original":
|
||||
key, size_expected, media_type, etag = (attachment.object_key, attachment.size_bytes,
|
||||
attachment.content_type, attachment.sha256)
|
||||
name = attachment.filename
|
||||
else:
|
||||
found = attachment.variant(variant)
|
||||
if found is None:
|
||||
raise NotFound("Такого варианта у вложения нет")
|
||||
key, size_expected, media_type, etag = found.object_key, found.size_bytes, found.content_type, found.sha256
|
||||
stem = attachment.filename.rsplit(".", 1)[0] or "image"
|
||||
name = stem + "-" + variant + (".webp" if media_type == "image/webp" else ".jpg")
|
||||
try:
|
||||
size, chunks = await storage_of(request).open_stream(key)
|
||||
except ObjectMissing:
|
||||
log.error("attachment_object_missing", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id, "variant": variant}})
|
||||
raise Unavailable("Файл вложения временно недоступен") from None
|
||||
if size != size_expected:
|
||||
log.error("attachment_size_mismatch", extra={"fields": {"request_id": request.state.request_id,
|
||||
"attachment_id": attachment.id, "variant": variant}})
|
||||
await chunks.aclose()
|
||||
raise Unavailable("Файл вложения временно недоступен")
|
||||
headers = {
|
||||
"Content-Length": str(size),
|
||||
"Content-Disposition": content_disposition(name),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
"ETag": '"' + etag + '"',
|
||||
}
|
||||
return StreamingResponse(chunks, media_type=media_type, headers=headers)
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None) -> Starlette:
|
||||
settings = settings or Settings.from_env()
|
||||
db = Database(settings)
|
||||
sessions = build_store(settings, db)
|
||||
storage = Storage(settings) # final bucket: Read
|
||||
staging = Storage(settings, bucket=settings.s3_staging_bucket) # staging bucket: Write (+ janitor DELETE)
|
||||
|
||||
async def purge_loop() -> None:
|
||||
"""Housekeeping: expired Idempotency-Key rows (older than IDEMPOTENCY_TTL_SECONDS)."""
|
||||
while True:
|
||||
await asyncio.sleep(600)
|
||||
try:
|
||||
deleted = await repo.purge_idempotency_keys(db, settings.idempotency_ttl_seconds)
|
||||
if deleted:
|
||||
log.info("idempotency_keys_purged", extra={"fields": {"deleted": deleted}})
|
||||
except ApiError:
|
||||
pass # database unavailable right now; next round
|
||||
|
||||
async def janitor_loop(every: float) -> None:
|
||||
"""Cleanup of intents of failed uploads older than PENDING_GRACE_SECONDS (attachments.py).
|
||||
Every replica runs it; the advisory lock lets one round run at a time."""
|
||||
while True:
|
||||
await asyncio.sleep(every * (0.5 + random.random()))
|
||||
try:
|
||||
removed = await attachments.clean_stale_pending(db, staging, settings.pending_grace_seconds)
|
||||
if removed:
|
||||
log.info("stale_uploads_removed", extra={"fields": {"count": removed}})
|
||||
except ApiError:
|
||||
pass # PostgreSQL or S3 unavailable right now; the rows stay pending for the next round
|
||||
|
||||
stats_log = logging.getLogger("messenger.stats")
|
||||
|
||||
async def stats_loop(every: float) -> None:
|
||||
"""Experiments only: DB pool saturation (waiting requests, wait time) and process CPU."""
|
||||
cpu = time.process_time()
|
||||
db.pool.pop_stats()
|
||||
while True:
|
||||
await asyncio.sleep(every)
|
||||
stats = db.pool.pop_stats()
|
||||
now_cpu = time.process_time()
|
||||
stats_log.info("pool_stats", extra={"fields": {
|
||||
"interval_s": every, "cpu_s": round(now_cpu - cpu, 4),
|
||||
**{k: stats.get(k, 0) for k in ("pool_size", "pool_available", "requests_waiting", "requests_num",
|
||||
"requests_queued", "requests_wait_ms", "usage_ms", "requests_errors")}}})
|
||||
cpu = now_cpu
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(app: Starlette):
|
||||
passwords.configure(settings.hash_concurrency)
|
||||
telemetry.observe_pool(db.pool, db.name)
|
||||
await db.open()
|
||||
await storage.open()
|
||||
await staging.open()
|
||||
log.info("dependencies_configured", extra={"fields": {
|
||||
"session_store": sessions.name, "session_ttl_s": settings.session_ttl_seconds,
|
||||
"db_pool_max": settings.db_pool_max, "db_timeout_s": settings.db_timeout_seconds,
|
||||
"instance_id": settings.instance_id, "drain_s": settings.drain_seconds,
|
||||
"message_write_path": settings.message_write_path, "s3_bucket": settings.s3_bucket,
|
||||
"s3_staging_bucket": settings.s3_staging_bucket, "pipeline_version": settings.pipeline_version,
|
||||
"upload_concurrency": settings.upload_concurrency, "verify_concurrency": settings.image_verify_concurrency,
|
||||
"pending_grace_s": settings.pending_grace_seconds,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
tasks = [asyncio.create_task(purge_loop())]
|
||||
if settings.janitor_interval_seconds > 0:
|
||||
tasks.append(asyncio.create_task(janitor_loop(settings.janitor_interval_seconds)))
|
||||
if settings.stats_log_seconds > 0:
|
||||
tasks.append(asyncio.create_task(stats_loop(settings.stats_log_seconds)))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await sessions.close()
|
||||
await staging.close()
|
||||
await storage.close()
|
||||
await db.close()
|
||||
|
||||
routes = [
|
||||
Route("/health/live", live, methods=["GET"]),
|
||||
Route("/health/ready", ready, methods=["GET"]),
|
||||
Route("/health/ready/core", ready_core, methods=["GET"]),
|
||||
Route("/api/v1/users", register_user, methods=["POST"]),
|
||||
Route("/api/v1/users/me", me, methods=["GET"]),
|
||||
Route("/api/v1/auth/sessions", create_session, methods=["POST"]),
|
||||
Route("/api/v1/auth/sessions/current", revoke_session, methods=["DELETE"]),
|
||||
Route("/api/v1/chats", create_chat, methods=["POST"]),
|
||||
Route("/api/v1/chats", list_chats, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
|
||||
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
|
||||
Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]),
|
||||
Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]),
|
||||
Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]),
|
||||
]
|
||||
if settings.docs_enabled: # Swagger UI for manual experiments, not part of the contract
|
||||
routes += [
|
||||
Route("/docs", docs.swagger_page, methods=["GET"]),
|
||||
Route("/openapi.json", docs.openapi_json, methods=["GET"]),
|
||||
]
|
||||
app = Starlette(
|
||||
routes=routes,
|
||||
exception_handlers={ApiError: api_error_handler, HTTPException: http_exception_handler},
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.add_middleware(RequestContextMiddleware, instance_id=settings.instance_id)
|
||||
app.state.settings = settings
|
||||
app.state.db = db
|
||||
app.state.sessions = sessions
|
||||
app.state.storage = storage
|
||||
app.state.staging = staging
|
||||
app.state.upload_slots = asyncio.Semaphore(settings.upload_concurrency)
|
||||
app.state.verify_slots = asyncio.Semaphore(settings.image_verify_concurrency)
|
||||
app.state.draining = False
|
||||
return app
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Attachments: metadata in PostgreSQL, bytes in private S3 buckets (lab 4), processed
|
||||
asynchronously by the worker (lab 5, docs/PIPELINE.md).
|
||||
|
||||
Upload (POST /chats/{id}/attachments, raw PNG/JPEG body), in this order:
|
||||
|
||||
auth -> membership (404) -> filename / Content-Type / Content-Length (400/415/413)
|
||||
-> upload slot (at most UPLOAD_CONCURRENCY bodies per replica, else 503 + Retry-After)
|
||||
-> body in chunks: size limit, read deadline, format + pixel count from the first bytes
|
||||
-> full integrity check (images.verify) -> SHA-256 / size known (415 is decided HERE)
|
||||
-> INSERT row status='pending' with a fresh random staging key, COMMIT (intent)
|
||||
-> PUT the original into the STAGING bucket (Content-MD5)
|
||||
-> ONE transaction: status 'pending' -> 'queued' + jobs row + outbox row, COMMIT
|
||||
-> 202 queued.
|
||||
|
||||
What is durable at 202: the complete, verified original in the staging bucket (S3 confirmed the
|
||||
PUT and its MD5), the metadata row, the job and the outbox row that makes the relay publish it.
|
||||
A crash of the API after the answer loses nothing; a broker that is down only delays the publish.
|
||||
|
||||
Failures between the steps (docs/PIPELINE.md, failure windows):
|
||||
* before the intent COMMIT: nothing was written;
|
||||
* after the intent, before/while PUT, or between PUT and the job COMMIT (FAULT_POINTS=after_s3_put):
|
||||
a 'pending' row (+ maybe the staging object), invisible to everybody (404). The client got 503
|
||||
and may retry (a new attachment). The janitor deletes the staging object - idempotent - and then
|
||||
the row once it is older than PENDING_GRACE_SECONDS, deciding under the row lock;
|
||||
* after the job COMMIT, answer lost (FAULT_POINTS=after_enqueue_commit): a correct queued
|
||||
attachment the client does not know; the worker processes it as usual.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import logging
|
||||
import secrets
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
from starlette.requests import Request
|
||||
|
||||
from . import images, jobs
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import ApiError, InvalidRequest, NotFound, PayloadTooLarge, Unavailable, UnsupportedMediaType
|
||||
from .storage import STAGING_PREFIX, Storage
|
||||
from .timefmt import rfc3339
|
||||
|
||||
log = logging.getLogger("messenger.attachments")
|
||||
|
||||
JANITOR_LOCK_ID = 2026_04 # advisory lock: one janitor round at a time across all replicas
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Variant:
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
object_key: str
|
||||
|
||||
def to_json(self) -> dict:
|
||||
return {"name": self.name, "content_type": self.content_type, "size_bytes": self.size_bytes,
|
||||
"width": self.width, "height": self.height, "sha256": self.sha256}
|
||||
|
||||
|
||||
@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
|
||||
object_key: str | None # published original in the final bucket (None until the worker publishes it)
|
||||
status: str
|
||||
created_at: dt.datetime
|
||||
updated_at: dt.datetime
|
||||
lost: bool = False
|
||||
error_code: str | None = None
|
||||
published_version: int | None = None
|
||||
variants: tuple[Variant, ...] = ()
|
||||
|
||||
def to_json(self) -> dict:
|
||||
"""Public representation: no object keys, no buckets, no job internals."""
|
||||
return {"id": self.id, "chat_id": self.chat_id, "owner_id": self.owner_id, "filename": self.filename,
|
||||
"content_type": self.content_type, "size_bytes": self.size_bytes, "sha256": self.sha256,
|
||||
"status": self.status, "variants": [v.to_json() for v in self.variants] if self.status == "ready" else [],
|
||||
"error_code": self.error_code if self.status == "failed" else None,
|
||||
"created_at": rfc3339(self.created_at), "updated_at": rfc3339(self.updated_at)}
|
||||
|
||||
def variant(self, name: str) -> Variant | None:
|
||||
return next((v for v in self.variants if v.name == name), None)
|
||||
|
||||
|
||||
COLUMNS = ("a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.object_key, "
|
||||
"a.status, a.created_at, a.updated_at, a.lost_at IS NOT NULL, a.error_code, a.published_version")
|
||||
|
||||
|
||||
def _attachment(row, variants: tuple[Variant, ...] = ()) -> Attachment:
|
||||
return Attachment(str(row[0]), str(row[1]), str(row[2]), row[3], row[4], row[5], bytes(row[6]).hex(), row[7],
|
||||
row[8], row[9], row[10], row[11], row[12], row[13], variants)
|
||||
|
||||
|
||||
def new_staging_key() -> str:
|
||||
"""Server-generated, 128 random bits, unrelated to the attachment id and the filename."""
|
||||
return STAGING_PREFIX + secrets.token_hex(16)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ SQL
|
||||
async def create_intent(db: Database, attachment_id: uuid.UUID, chat_id: str, owner_id: str, filename: str,
|
||||
info: images.ImageInfo, size: int, sha256: bytes, staging_key: str) -> None:
|
||||
async def work(conn: psycopg.AsyncConnection) -> None:
|
||||
await conn.execute(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, "
|
||||
"width, height, staging_key, staging_state, status) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'present', 'pending')",
|
||||
(attachment_id, chat_id, owner_id, filename, info.content_type, size, sha256, info.width, info.height,
|
||||
staging_key))
|
||||
try:
|
||||
await db.run(work, transaction=False)
|
||||
except pg_errors.ForeignKeyViolation:
|
||||
raise NotFound("Чат не найден") from None
|
||||
|
||||
|
||||
async def enqueue(db: Database, attachment_id: uuid.UUID, settings: Settings) -> Attachment | None:
|
||||
"""pending -> queued + job + outbox row in ONE transaction (the durable handoff before 202).
|
||||
None if the row is no longer pending (the janitor removed a stale intent)."""
|
||||
async def work(conn: psycopg.AsyncConnection) -> Attachment | None:
|
||||
cur = await conn.execute(
|
||||
"UPDATE attachments a SET status = 'queued', updated_at = clock_timestamp() "
|
||||
f"WHERE a.id = %s AND a.status = 'pending' RETURNING {COLUMNS}", (attachment_id,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
await jobs.create_job(conn, attachment_id, settings.pipeline_version, "upload", settings.job_max_attempts,
|
||||
"api:" + settings.instance_id)
|
||||
return _attachment(row)
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
async def get_visible(db: Database, user_id: str, attachment_id: str) -> Attachment:
|
||||
"""An attachment of a chat the user is a member of, in any state but the invisible intent
|
||||
'pending'; anything else is 404 (unknown, foreign chat, unfinished upload) - existence of
|
||||
foreign objects is never revealed. A ready attachment comes with its published variants."""
|
||||
async def work(conn: psycopg.AsyncConnection) -> Attachment:
|
||||
cur = await conn.execute(
|
||||
f"SELECT {COLUMNS} FROM attachments a "
|
||||
"JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = %s "
|
||||
"WHERE a.id = %s AND a.status <> 'pending'", (user_id, attachment_id))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise NotFound("Вложение не найдено")
|
||||
variants: tuple[Variant, ...] = ()
|
||||
if row[8] == "ready":
|
||||
cur = await conn.execute(
|
||||
"SELECT name, content_type, size_bytes, width, height, sha256, object_key FROM attachment_variants "
|
||||
"WHERE attachment_id = %s AND pipeline_version = %s "
|
||||
"ORDER BY array_position(ARRAY['thumbnail', 'crop', 'optimized'], name)", (row[0], row[13]))
|
||||
variants = tuple(Variant(r[0], r[1], r[2], r[3], r[4], bytes(r[5]).hex(), r[6]) for r in await cur.fetchall())
|
||||
return _attachment(row, variants)
|
||||
# REPEATABLE READ is not needed: the variant rows of a published version never change.
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
async def clean_stale_pending(db: Database, staging: Storage, grace_seconds: int, batch: int = 20) -> int:
|
||||
"""Janitor round: remove intents of uploads that never got their job (no 202 was sent).
|
||||
|
||||
Under FOR UPDATE: an upload that is (impossibly) still running would block on the row in
|
||||
enqueue() and then find it gone (-> 503). Order: staging object first (idempotent), row second;
|
||||
a crash in between leaves the pending row and the next round repeats. Only status='pending'
|
||||
rows older than the grace period are touched: queued/processing/ready/failed never.
|
||||
"""
|
||||
async def work(conn: psycopg.AsyncConnection) -> int:
|
||||
cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (JANITOR_LOCK_ID,))
|
||||
if not (await cur.fetchone())[0]:
|
||||
return 0
|
||||
cur = await conn.execute(
|
||||
"SELECT id, staging_key FROM attachments WHERE status = 'pending' "
|
||||
"AND created_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"ORDER BY created_at LIMIT %s FOR UPDATE SKIP LOCKED", (grace_seconds, batch))
|
||||
rows = await cur.fetchall()
|
||||
if not rows:
|
||||
return 0
|
||||
await asyncio.gather(*(staging.delete(key) for _, key in rows))
|
||||
await conn.execute("DELETE FROM attachments WHERE id = ANY(%s) AND status = 'pending'",
|
||||
([r[0] for r in rows],))
|
||||
return len(rows)
|
||||
return await db.run(work, deadline=staging.timeout + 5)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ request body
|
||||
class Busy(Unavailable):
|
||||
"""All upload slots of this replica are taken: retry shortly (no body was read)."""
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
return {"Retry-After": "1"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Upload:
|
||||
data: bytearray
|
||||
info: images.ImageInfo
|
||||
sha256: bytes
|
||||
|
||||
|
||||
class BodyReader:
|
||||
"""Reads the raw ASGI body ourselves (not request.stream()), so we always know how much of it
|
||||
is consumed and can discard the rest after an early rejection."""
|
||||
|
||||
def __init__(self, request: Request):
|
||||
self.receive = request.receive
|
||||
self.done = False
|
||||
|
||||
async def chunk(self, timeout: float) -> bytes | None:
|
||||
if self.done:
|
||||
return None
|
||||
message = await asyncio.wait_for(self.receive(), timeout)
|
||||
if message["type"] == "http.disconnect":
|
||||
self.done = True
|
||||
raise InvalidRequest("Клиент прервал загрузку")
|
||||
if not message.get("more_body", False):
|
||||
self.done = True
|
||||
return message.get("body", b"")
|
||||
|
||||
async def discard(self, limit: int, timeout: float) -> None:
|
||||
"""After an early 4xx: read and DROP up to `limit` more bytes, so an ordinary client that
|
||||
writes the whole body before reading the answer still gets our JSON error instead of a
|
||||
connection reset. Nothing is kept in memory; beyond the limit the connection is dropped."""
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout
|
||||
seen = 0
|
||||
try:
|
||||
while not self.done and seen <= limit:
|
||||
remaining = deadline - loop.time()
|
||||
if remaining <= 0:
|
||||
return
|
||||
seen += len(await self.chunk(remaining) or b"")
|
||||
except (ApiError, asyncio.TimeoutError):
|
||||
return
|
||||
|
||||
|
||||
def declared_type(request: Request) -> str:
|
||||
"""Content-Type of the upload must be image/png or image/jpeg (parameters ignored)."""
|
||||
media_type = request.headers.get("content-type", "").partition(";")[0].strip().lower()
|
||||
if media_type not in (images.PNG, images.JPEG):
|
||||
raise UnsupportedMediaType("Content-Type должен быть image/png или image/jpeg")
|
||||
return media_type
|
||||
|
||||
|
||||
def declared_length(request: Request, limit: int) -> int | None:
|
||||
raw = request.headers.get("content-length")
|
||||
if raw is None:
|
||||
return None # chunked transfer: the limit is enforced while reading
|
||||
if not raw.isdigit():
|
||||
raise InvalidRequest("Неверный Content-Length")
|
||||
length = int(raw)
|
||||
if length > limit:
|
||||
raise PayloadTooLarge(f"Файл больше {limit} байт")
|
||||
if length == 0:
|
||||
raise InvalidRequest("Тело запроса пустое: нужны байты изображения")
|
||||
return length
|
||||
|
||||
|
||||
async def read_image(reader: BodyReader, settings: Settings, declared: str, verify_slots: asyncio.Semaphore,
|
||||
length: int | None) -> Upload:
|
||||
"""Body -> verified image. Memory: ONE buffer of at most MAX_UPLOAD_BYTES per upload - exactly
|
||||
Content-Length bytes allocated once when the length is declared (no growth, no final copy);
|
||||
it is passed as is to the checks and to the S3 PUT. The format and the pixel count are known
|
||||
after the first bytes, so a picture that is too big or not a PNG/JPEG is rejected without
|
||||
reading/decoding the rest."""
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + settings.upload_read_timeout_seconds
|
||||
limit = settings.max_upload_bytes
|
||||
buffer = bytearray(length) if length else bytearray()
|
||||
view = memoryview(buffer) if length else None
|
||||
filled = 0
|
||||
digest = hashlib.sha256()
|
||||
info: images.ImageInfo | None = None
|
||||
while True:
|
||||
remaining = deadline - loop.time()
|
||||
if remaining <= 0:
|
||||
raise InvalidRequest("Тело запроса не получено вовремя")
|
||||
try:
|
||||
chunk = await reader.chunk(remaining)
|
||||
except asyncio.TimeoutError:
|
||||
raise InvalidRequest("Тело запроса не получено вовремя") from None
|
||||
if chunk is None:
|
||||
break
|
||||
if filled + len(chunk) > (length or limit):
|
||||
raise PayloadTooLarge(f"Файл больше {limit} байт")
|
||||
if view is not None:
|
||||
view[filled:filled + len(chunk)] = chunk
|
||||
else:
|
||||
buffer += chunk
|
||||
filled += len(chunk)
|
||||
digest.update(chunk)
|
||||
if info is None and filled:
|
||||
info = _sniff(view[:filled] if view is not None else buffer, settings, declared)
|
||||
if view is not None:
|
||||
view.release()
|
||||
if not filled:
|
||||
raise InvalidRequest("Тело запроса пустое: нужны байты изображения")
|
||||
if length and filled != length:
|
||||
raise InvalidRequest("Тело запроса короче Content-Length")
|
||||
if info is None:
|
||||
raise UnsupportedMediaType("Файл не является корректным изображением PNG или JPEG")
|
||||
try:
|
||||
async with verify_slots:
|
||||
await images.verify(buffer, info, timeout=settings.image_verify_timeout_seconds,
|
||||
jpeg_max_memory_mb=settings.jpeg_max_memory_mb)
|
||||
except images.ImageError as exc:
|
||||
raise _image_error(exc) from None
|
||||
except asyncio.TimeoutError:
|
||||
raise UnsupportedMediaType("Изображение не удалось проверить за отведённое время") from None
|
||||
except (images.VerifierUnavailable, MemoryError):
|
||||
log.warning("image_verifier_unavailable", extra={"fields": {"type": info.content_type, "size": filled}})
|
||||
raise Busy("Не хватило ресурсов для проверки изображения, повторите позже") from None
|
||||
return Upload(buffer, info, digest.digest())
|
||||
|
||||
|
||||
def _sniff(buffer: bytearray, settings: Settings, declared: str) -> images.ImageInfo | None:
|
||||
try:
|
||||
info = images.sniff(buffer, settings.max_image_pixels)
|
||||
except images.ImageError as exc:
|
||||
raise _image_error(exc) from None
|
||||
if info is not None and info.content_type != declared:
|
||||
# "MIME spoofing": the header says PNG, the bytes are JPEG (or vice versa).
|
||||
raise UnsupportedMediaType("Содержимое не совпадает с Content-Type")
|
||||
return info
|
||||
|
||||
|
||||
def _image_error(exc: images.ImageError) -> ApiError:
|
||||
return PayloadTooLarge(exc.message) if exc.status == 413 else UnsupportedMediaType(exc.message)
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Track 2: read-only checker of the pipeline invariants: `python -m messenger.audit`
|
||||
(compose service `auditor`, profile tools; `make audit`).
|
||||
|
||||
Read-only by construction: every database transaction is `READ ONLY` (PostgreSQL refuses any
|
||||
write), and the S3 key pair of the auditor has Read + List only. Output: one JSON report; exit 1
|
||||
if any invariant is violated.
|
||||
|
||||
Invariants (docs/PIPELINE.md):
|
||||
I1 no lost work - a queued/processing attachment has an active job; an active job has an
|
||||
outbox row (published or due) - nothing waits for a message that nobody sends.
|
||||
I2 one effect - per (attachment, pipeline_version) either no variant rows or exactly the
|
||||
three variants, all written by ONE successful attempt of a job of that version.
|
||||
I3 published data - every published object (original, variants) exists with the stored size
|
||||
(--verify-checksums: and the stored SHA-256).
|
||||
I4 monotonic - published_version = the highest version with a succeeded job; a ready
|
||||
attachment is never queued/processing again (published_version stays set).
|
||||
I5 source kept - an active job whose original is not published still has its staging copy
|
||||
(state present AND the object exists in the staging bucket).
|
||||
I6 no stray data - every object in the buckets is referenced: published, staging of a live row,
|
||||
or planned by an attempt whose objects were not cleaned yet. An object of an
|
||||
already cleaned attempt is reported as `leaked_object` (written by a stalled
|
||||
attempt after its cleanup: garbage, never a loss).
|
||||
I7 attempts - a succeeded job has exactly one succeeded attempt; at most one running attempt
|
||||
per job, and it is the lease holder.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .pipeline import VARIANT_NAMES
|
||||
from .storage import ObjectMissing, SENTINEL_KEY, Storage
|
||||
|
||||
|
||||
async def rows(db: Database, sql: str, params=()) -> list[tuple]:
|
||||
async def work(conn):
|
||||
await conn.execute("SET TRANSACTION READ ONLY")
|
||||
cur = await conn.execute(sql, params)
|
||||
return await cur.fetchall()
|
||||
return await db.run(work, deadline=db.deadline)
|
||||
|
||||
|
||||
async def list_all(storage: Storage, prefix: str) -> dict[str, int]:
|
||||
found, after = {}, None
|
||||
while True:
|
||||
page, more = await storage.list_page(prefix, after, 1000)
|
||||
for item in page:
|
||||
found[item.key] = item.size
|
||||
if not more or not page:
|
||||
return found
|
||||
after = page[-1].key
|
||||
|
||||
|
||||
async def audit(settings: Settings, verify: bool) -> dict:
|
||||
db = Database(settings, name="messenger-audit")
|
||||
final = Storage(settings)
|
||||
staging = Storage(settings, bucket=settings.s3_staging_bucket)
|
||||
await db.open()
|
||||
await final.open()
|
||||
await staging.open()
|
||||
violations: list[dict] = []
|
||||
notes: list[dict] = []
|
||||
|
||||
def bad(kind: str, **detail) -> None:
|
||||
violations.append({"invariant": kind, **{k: str(v) for k, v in detail.items()}})
|
||||
|
||||
try:
|
||||
# I1: queued/processing attachment without an active job; active job without outbox row.
|
||||
for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') "
|
||||
"AND NOT EXISTS (SELECT 1 FROM jobs j WHERE j.attachment_id = a.id "
|
||||
"AND j.state IN ('queued', 'processing'))"):
|
||||
bad("I1_no_active_job", attachment_id=aid)
|
||||
for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'queued' AND NOT EXISTS "
|
||||
"(SELECT 1 FROM outbox o WHERE o.job_id = j.id)"):
|
||||
bad("I1_queued_without_outbox", job_id=jid)
|
||||
|
||||
# I2: exactly three variants per published version, one successful attempt of that version.
|
||||
for aid, version, names, tokens in await rows(
|
||||
db, "SELECT attachment_id, pipeline_version, array_agg(name ORDER BY name), "
|
||||
"array_agg(DISTINCT attempt_token) FROM attachment_variants GROUP BY 1, 2"):
|
||||
if sorted(names) != sorted(VARIANT_NAMES):
|
||||
bad("I2_variant_set", attachment_id=aid, version=version, names=names)
|
||||
if len(tokens) != 1:
|
||||
bad("I2_mixed_attempts", attachment_id=aid, version=version, attempts=len(tokens))
|
||||
for aid, version, outcome, jversion in await rows(
|
||||
db, "SELECT v.attachment_id, v.pipeline_version, ja.outcome, j.pipeline_version "
|
||||
"FROM attachment_variants v JOIN job_attempts ja ON ja.token = v.attempt_token "
|
||||
"JOIN jobs j ON j.id = ja.job_id WHERE ja.outcome <> 'succeeded' OR j.pipeline_version "
|
||||
"<> v.pipeline_version OR j.attachment_id <> v.attachment_id"):
|
||||
bad("I2_variant_from_unsuccessful_attempt", attachment_id=aid, version=version, outcome=outcome)
|
||||
|
||||
# I4: published_version = highest succeeded version; ready <=> published.
|
||||
for aid, status, published, best in await rows(
|
||||
db, "SELECT a.id, a.status, a.published_version, (SELECT max(j.pipeline_version) FROM jobs j "
|
||||
"WHERE j.attachment_id = a.id AND j.state = 'succeeded') FROM attachments a "
|
||||
"WHERE a.published_version IS DISTINCT FROM (SELECT max(j.pipeline_version) FROM jobs j "
|
||||
"WHERE j.attachment_id = a.id AND j.state = 'succeeded') "
|
||||
"OR (a.published_version IS NOT NULL AND a.status <> 'ready')"):
|
||||
bad("I4_published_version", attachment_id=aid, status=status, published=published, best_succeeded=best)
|
||||
|
||||
# I7: attempts.
|
||||
for (jid,) in await rows(db, "SELECT j.id FROM jobs j WHERE j.state = 'succeeded' AND (SELECT count(*) "
|
||||
"FROM job_attempts a WHERE a.job_id = j.id AND a.outcome = 'succeeded') <> 1"):
|
||||
bad("I7_succeeded_attempts", job_id=jid)
|
||||
for jid, token in await rows(db, "SELECT a.job_id, a.token FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
|
||||
"WHERE a.outcome = 'running' AND j.lease_token IS DISTINCT FROM a.token"):
|
||||
bad("I7_running_not_holder", job_id=jid, token=token)
|
||||
|
||||
# I3 + I5 + I6: storage.
|
||||
published = {k: (s, h) for k, s, h in await rows(
|
||||
db, "SELECT object_key, size_bytes, sha256 FROM attachment_variants UNION ALL "
|
||||
"SELECT object_key, size_bytes, sha256 FROM attachments WHERE object_key IS NOT NULL")}
|
||||
staging_live = {k: (s, st, status) for k, s, st, status in await rows(
|
||||
db, "SELECT staging_key, size_bytes, staging_state, status FROM attachments WHERE staging_key IS NOT NULL")}
|
||||
planned_open, planned_cleaned = set(), set()
|
||||
for keys, cleaned in await rows(db, "SELECT planned_keys, objects_cleaned_at IS NOT NULL FROM job_attempts"):
|
||||
(planned_cleaned if cleaned else planned_open).update(keys)
|
||||
final_objects = await list_all(final, "")
|
||||
staging_objects = await list_all(staging, "")
|
||||
for key, (size, sha) in published.items():
|
||||
if key not in final_objects:
|
||||
bad("I3_published_missing", key=key)
|
||||
elif final_objects[key] != size:
|
||||
bad("I3_published_size", key=key, stored=size, actual=final_objects[key])
|
||||
elif verify:
|
||||
data = await final.read_all(key, limit=settings.max_upload_bytes)
|
||||
if hashlib.sha256(data).digest() != bytes(sha):
|
||||
bad("I3_published_checksum", key=key)
|
||||
for key, (size, state, status) in staging_live.items():
|
||||
# 'pending' may lack its object (the PUT failed: the janitor removes the row); accepted
|
||||
# work (queued/processing) must have it.
|
||||
active = status in ("queued", "processing")
|
||||
if state == "present" and key not in staging_objects and active:
|
||||
bad("I5_staging_missing", key=key, status=status)
|
||||
for (aid,) in await rows(db, "SELECT a.id FROM attachments a WHERE a.status IN ('queued', 'processing') "
|
||||
"AND a.object_key IS NULL AND a.staging_state <> 'present'"):
|
||||
bad("I5_active_without_source", attachment_id=aid)
|
||||
for key in final_objects:
|
||||
if key == SENTINEL_KEY or key in published or key in planned_open:
|
||||
continue
|
||||
if key in planned_cleaned:
|
||||
notes.append({"kind": "leaked_object", "key": key})
|
||||
else:
|
||||
bad("I6_unknown_final_object", key=key)
|
||||
for key in staging_objects:
|
||||
if key == SENTINEL_KEY:
|
||||
continue
|
||||
row = staging_live.get(key)
|
||||
if row is None:
|
||||
bad("I6_unknown_staging_object", key=key)
|
||||
elif row[1] == "deleted":
|
||||
notes.append({"kind": "staging_marked_deleted_still_present", "key": key})
|
||||
counts = dict(await rows(db, "SELECT status, count(*) FROM attachments GROUP BY status"))
|
||||
jobs = dict(await rows(db, "SELECT state, count(*) FROM jobs GROUP BY state"))
|
||||
return {"ok": not violations, "violations": violations, "notes": notes,
|
||||
"attachments": counts, "jobs": jobs,
|
||||
"objects": {"final": len(final_objects), "staging": len(staging_objects),
|
||||
"published": len(published), "checksums_verified": verify}}
|
||||
finally:
|
||||
await staging.close()
|
||||
await final.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(prog="audit", description="Read-only check of the pipeline invariants")
|
||||
p.add_argument("--verify-checksums", action="store_true", help="read every published object and compare SHA-256")
|
||||
args = p.parse_args(argv)
|
||||
try:
|
||||
settings = Settings.from_env()
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
try:
|
||||
report = asyncio.run(audit(settings, args.verify_checksums))
|
||||
except (Unavailable, ObjectMissing) as exc:
|
||||
print(json.dumps({"ok": False, "error": "store_unavailable", "detail": type(exc).__name__}))
|
||||
return 1
|
||||
print(json.dumps(report, ensure_ascii=False, indent=1, default=str))
|
||||
return 0 if report["ok"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Parsing of the Authorization header. Any malformed value is 401, never 500.
|
||||
|
||||
Basic (RFC 7617) is accepted only by POST /auth/sessions; everything else needs
|
||||
Bearer. Basic is an encoding, not encryption: plain HTTP is acceptable only for the
|
||||
local synthetic lab stand (lab 7 adds TLS).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
|
||||
from .errors import BASIC_CHALLENGE, BEARER_CHALLENGE, Unauthorized
|
||||
from .validation import USERNAME_RE
|
||||
|
||||
B64_RE = re.compile(r"[A-Za-z0-9+/]+={0,2}")
|
||||
TOKEN_RE = re.compile(r"[A-Za-z0-9_-]{32,128}") # token_urlsafe(32) gives 43 characters
|
||||
|
||||
|
||||
def _split(header: str | None) -> tuple[str, str]:
|
||||
if not header:
|
||||
return "", ""
|
||||
scheme, _, value = header.strip().partition(" ")
|
||||
return scheme.lower(), value.strip()
|
||||
|
||||
|
||||
def parse_basic(header: str | None) -> tuple[str, str]:
|
||||
"""(username, password) from `Basic base64(username:password)`; the password may contain ':'."""
|
||||
invalid = Unauthorized("Неверное имя пользователя или пароль", challenge=BASIC_CHALLENGE)
|
||||
scheme, value = _split(header)
|
||||
if scheme != "basic" or B64_RE.fullmatch(value) is None or len(value) > 1024:
|
||||
raise invalid
|
||||
try:
|
||||
decoded = base64.b64decode(value, validate=True).decode("utf-8")
|
||||
except (binascii.Error, ValueError, UnicodeDecodeError):
|
||||
raise invalid from None
|
||||
username, sep, password = decoded.partition(":") # split at the FIRST colon
|
||||
if not sep or USERNAME_RE.fullmatch(username) is None or not password:
|
||||
raise invalid
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(header: str | None) -> str:
|
||||
scheme, value = _split(header)
|
||||
if scheme != "bearer" or TOKEN_RE.fullmatch(value) is None:
|
||||
# Missing header, Basic on a business endpoint, garbage token: one answer.
|
||||
raise Unauthorized("Требуется действительная Bearer-сессия", challenge=BEARER_CHALLENGE)
|
||||
return value
|
||||
@@ -0,0 +1,93 @@
|
||||
"""RabbitMQ (AMQP 0-9-1) for the attachment jobs: topology names and the message format.
|
||||
|
||||
Topology (declared by the broker itself from its definitions file at boot, infra/rabbitmq and
|
||||
scripts/init_secrets.py; the relay and the worker have NO configure permission and declare nothing):
|
||||
|
||||
exchange messenger.jobs direct, durable
|
||||
queue messenger.attachment-jobs quorum (Raft log on disk), bound with routing key
|
||||
attachment.process.v1; x-delivery-limit and dead-lettering to
|
||||
exchange messenger.jobs.dlx fanout -> queue messenger.attachment-jobs.dlq (quorum)
|
||||
|
||||
Publisher side (relay): persistent message, `mandatory` (an unroutable message is returned, not
|
||||
silently dropped), channel in confirm mode - `publish()` returns only after the broker has
|
||||
written the message to the quorum log (publisher confirm). Consumer side (worker): manual ack
|
||||
after the durable effect, prefetch = WORKER_CONCURRENCY.
|
||||
|
||||
The message carries IDs and service fields only (contracts/jobs.schema.json): no bytes, no URL,
|
||||
no S3 key, no filename, no credentials. The worker takes every trusted detail from PostgreSQL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
|
||||
EXCHANGE = "messenger.jobs"
|
||||
QUEUE = "messenger.attachment-jobs"
|
||||
DLX = "messenger.jobs.dlx"
|
||||
DLQ = "messenger.attachment-jobs.dlq"
|
||||
ROUTING_KEY = "attachment.process.v1"
|
||||
JOB_TYPE = "attachment.process.v1"
|
||||
MAX_MESSAGE_BYTES = 4096
|
||||
|
||||
REQUIRED = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
|
||||
OPTIONAL = {"traceparent", "tracestate"}
|
||||
TRACEPARENT_RE = re.compile(r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}")
|
||||
DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z")
|
||||
|
||||
|
||||
class BadMessage(ValueError):
|
||||
"""Not a valid job message (schema v1): dead-lettered, never processed."""
|
||||
|
||||
|
||||
def rfc3339(value: dt.datetime) -> str:
|
||||
return value.astimezone(dt.timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def encode(job_id: str, attachment_id: str, pipeline_version: int, attempt: int, created_at: dt.datetime,
|
||||
trace_context: dict[str, str] | None = None) -> bytes:
|
||||
"""Lab 6: `trace_context` = {"traceparent", "tracestate"} of the relay's PRODUCER span (the same
|
||||
values also go into the AMQP headers; the worker reads the body fields, the schema's carrier)."""
|
||||
body = {"schema_version": 1, "job_id": job_id, "type": JOB_TYPE, "attachment_id": attachment_id,
|
||||
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": rfc3339(created_at)}
|
||||
for key in ("traceparent", "tracestate"):
|
||||
value = (trace_context or {}).get(key)
|
||||
if value:
|
||||
body[key] = value
|
||||
return json.dumps(body, separators=(",", ":")).encode()
|
||||
|
||||
|
||||
def decode(raw: bytes) -> dict:
|
||||
"""Strict check against contracts/jobs.schema.json (additionalProperties: false)."""
|
||||
if len(raw) > MAX_MESSAGE_BYTES:
|
||||
raise BadMessage("too large")
|
||||
try:
|
||||
body = json.loads(raw)
|
||||
except (ValueError, UnicodeError):
|
||||
raise BadMessage("not JSON") from None
|
||||
if not isinstance(body, dict):
|
||||
raise BadMessage("not an object")
|
||||
keys = set(body)
|
||||
if not REQUIRED <= keys or keys - REQUIRED - OPTIONAL:
|
||||
raise BadMessage("wrong fields")
|
||||
if body["schema_version"] != 1 or isinstance(body["schema_version"], bool) or body["type"] != JOB_TYPE:
|
||||
raise BadMessage("unsupported schema/type")
|
||||
for name in ("job_id", "attachment_id"):
|
||||
if not isinstance(body[name], str):
|
||||
raise BadMessage(name)
|
||||
try:
|
||||
uuid.UUID(body[name])
|
||||
except ValueError:
|
||||
raise BadMessage(name) from None
|
||||
for name in ("pipeline_version", "attempt"):
|
||||
value = body[name]
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 1:
|
||||
raise BadMessage(name)
|
||||
if not isinstance(body["created_at"], str) or not DATETIME_RE.fullmatch(body["created_at"]):
|
||||
raise BadMessage("created_at")
|
||||
if "traceparent" in body and not (isinstance(body["traceparent"], str) and TRACEPARENT_RE.fullmatch(body["traceparent"])):
|
||||
raise BadMessage("traceparent")
|
||||
if "tracestate" in body and not (isinstance(body["tracestate"], str) and len(body["tracestate"]) <= 512):
|
||||
raise BadMessage("tracestate")
|
||||
return body
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Runtime configuration read from environment variables (12-factor style).
|
||||
|
||||
Non-secret settings have safe defaults. Connection strings with passwords are
|
||||
read from files (`DATABASE_URL_FILE`, `CACHE_URL_FILE` → Docker secrets in
|
||||
/run/secrets), so they never appear in `docker inspect`, compose files or logs.
|
||||
Invalid values stop the process at startup with a clear message.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class ConfigError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
INSTANCE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
|
||||
|
||||
|
||||
def _instance_id() -> str:
|
||||
"""X-Instance-Id of this process: INSTANCE_ID or the container hostname.
|
||||
|
||||
Docker sets the hostname of a container to its short container ID, so the value
|
||||
is unique per replica, stable for the life of the process and maps 1:1 to a real
|
||||
container (`docker inspect`), which scripts/stop-one.sh relies on.
|
||||
"""
|
||||
value = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname()
|
||||
if INSTANCE_ID_RE.fullmatch(value) is None:
|
||||
raise ConfigError("INSTANCE_ID must match [A-Za-z0-9._-]{1,64}")
|
||||
return value
|
||||
|
||||
|
||||
def _int(name: str, default: int, low: int, high: int) -> int:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
return default
|
||||
try:
|
||||
value = int(raw.strip())
|
||||
except ValueError:
|
||||
raise ConfigError(f"{name} must be an integer, got {raw!r}") from None
|
||||
if not low <= value <= high:
|
||||
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
|
||||
return value
|
||||
|
||||
|
||||
def _float(name: str, default: float, low: float, high: float) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None or raw.strip() == "":
|
||||
return default
|
||||
try:
|
||||
value = float(raw.strip())
|
||||
except ValueError:
|
||||
raise ConfigError(f"{name} must be a number, got {raw!r}") from None
|
||||
if not low <= value <= high:
|
||||
raise ConfigError(f"{name} must be in [{low}, {high}], got {value}")
|
||||
return value
|
||||
|
||||
|
||||
def _bool(name: str, default: bool) -> bool:
|
||||
raw = os.environ.get(name, "").strip().lower()
|
||||
if raw == "":
|
||||
return default
|
||||
if raw not in {"true", "false", "1", "0"}:
|
||||
raise ConfigError(f"{name} must be true/false, got {raw!r}")
|
||||
return raw in {"true", "1"}
|
||||
|
||||
|
||||
def _choice(name: str, default: str, allowed: set[str]) -> str:
|
||||
value = os.environ.get(name, "").strip().lower() or default
|
||||
if value not in allowed:
|
||||
raise ConfigError(f"{name} must be one of {sorted(allowed)}, got {value!r}")
|
||||
return value
|
||||
|
||||
|
||||
def _secret(name: str, required: bool) -> str:
|
||||
"""Value of <NAME>_FILE (preferred, Docker secret) or <NAME> (local runs/tests)."""
|
||||
path = os.environ.get(f"{name}_FILE", "").strip()
|
||||
if path:
|
||||
try:
|
||||
value = Path(path).read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
# The message names the file, never its content.
|
||||
raise ConfigError(f"{name}_FILE={path} cannot be read: {exc.strerror}") from None
|
||||
else:
|
||||
value = os.environ.get(name, "").strip()
|
||||
if required and not value:
|
||||
raise ConfigError(f"{name}_FILE (or {name}) must be set")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
host: str
|
||||
port: int
|
||||
env: str
|
||||
log_level: str
|
||||
shutdown_timeout: float
|
||||
max_body_bytes: int
|
||||
docs_enabled: bool = True
|
||||
database_url: str = ""
|
||||
session_store: str = "postgres"
|
||||
cache_url: str = ""
|
||||
session_ttl_seconds: int = 3600
|
||||
db_pool_min: int = 1
|
||||
db_pool_max: int = 10
|
||||
db_timeout_seconds: float = 3.0
|
||||
cache_timeout_seconds: float = 0.5
|
||||
hash_concurrency: int = 2
|
||||
instance_id: str = "local"
|
||||
drain_seconds: float = 0.0
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
stats_log_seconds: float = 0.0
|
||||
message_write_path: str = "function"
|
||||
# Lab 4: private S3 bucket and attachment limits (see storage.py, attachments.py).
|
||||
s3_endpoint: str = "http://s3:8333"
|
||||
s3_region: str = "us-east-1"
|
||||
s3_bucket: str = "messenger-attachments"
|
||||
s3_access_key_id: str = ""
|
||||
s3_secret_access_key: str = ""
|
||||
s3_timeout_seconds: float = 3.0
|
||||
s3_connect_timeout_seconds: float = 1.0
|
||||
s3_max_connections: int = 20
|
||||
max_upload_bytes: int = 10 * 1024 * 1024
|
||||
max_image_pixels: int = 40_000_000
|
||||
upload_concurrency: int = 4
|
||||
upload_queue_timeout_seconds: float = 5.0
|
||||
upload_read_timeout_seconds: float = 30.0
|
||||
image_verify_timeout_seconds: float = 10.0
|
||||
image_verify_concurrency: int = 1
|
||||
jpeg_max_memory_mb: int = 256
|
||||
pending_grace_seconds: int = 900
|
||||
janitor_interval_seconds: float = 60.0
|
||||
# Lab 5: staging bucket (API writes, worker reads) and the asynchronous pipeline (jobs_settings()).
|
||||
s3_staging_bucket: str = "messenger-staging"
|
||||
broker_url: str = ""
|
||||
pipeline_version: int = 1
|
||||
job_max_attempts: int = 5
|
||||
job_timeout_seconds: float = 60.0
|
||||
job_lease_seconds: float = 30.0
|
||||
job_retry_base_seconds: float = 2.0
|
||||
job_retry_max_seconds: float = 60.0
|
||||
worker_concurrency: int = 2
|
||||
worker_shutdown_seconds: float = 20.0
|
||||
image_max_memory_mb: int = 768
|
||||
staging_retention_seconds: int = 86400
|
||||
orphan_grace_seconds: int = 600
|
||||
cleanup_interval_seconds: float = 30.0
|
||||
relay_poll_seconds: float = 0.5
|
||||
relay_batch: int = 50
|
||||
queued_republish_seconds: float = 300.0
|
||||
fault_points: frozenset[str] = frozenset()
|
||||
fault_values: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
def fault_value(self, point: str, default: int = 0) -> int:
|
||||
return self.fault_values.get(point, default)
|
||||
|
||||
@property
|
||||
def db_statement_timeout_ms(self) -> int:
|
||||
# The server stops a statement a bit before the client-side deadline fires.
|
||||
return max(100, int(self.db_timeout_seconds * 1000) - 500)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, *, s3_credentials: bool = True) -> "Settings":
|
||||
"""s3_credentials=False: processes without S3 access (relay, jobctl)."""
|
||||
log_level = os.environ.get("LOG_LEVEL", "info").strip().lower() or "info"
|
||||
if log_level not in {"debug", "info", "warning", "error"}:
|
||||
raise ConfigError(f"LOG_LEVEL must be debug/info/warning/error, got {log_level!r}")
|
||||
session_store = os.environ.get("SESSION_STORE", "postgres").strip().lower() or "postgres"
|
||||
if session_store == "redis":
|
||||
session_store = "valkey" # same protocol; the course allows Redis OR Valkey
|
||||
if session_store not in {"postgres", "valkey"}:
|
||||
raise ConfigError(f"SESSION_STORE must be postgres or valkey, got {session_store!r}")
|
||||
db_pool_min = _int("DB_POOL_MIN", 1, 0, 50)
|
||||
db_pool_max = _int("DB_POOL_MAX", 10, 1, 100)
|
||||
if db_pool_min > db_pool_max:
|
||||
raise ConfigError("DB_POOL_MIN must not exceed DB_POOL_MAX")
|
||||
return cls(
|
||||
host=os.environ.get("APP_HOST", "0.0.0.0").strip() or "0.0.0.0",
|
||||
port=_int("APP_PORT", 8080, 1, 65535),
|
||||
env=os.environ.get("APP_ENV", "lab").strip() or "lab",
|
||||
log_level=log_level,
|
||||
# DRAIN_SECONDS + SHUTDOWN_TIMEOUT_SECONDS must stay below compose stop_grace_period.
|
||||
shutdown_timeout=_float("SHUTDOWN_TIMEOUT_SECONDS", 8.0, 0.0, 30.0),
|
||||
max_body_bytes=_int("MAX_BODY_BYTES", 64 * 1024, 1024, 1024 * 1024),
|
||||
docs_enabled=_bool("DOCS_ENABLED", True),
|
||||
database_url=_secret("DATABASE_URL", required=True),
|
||||
session_store=session_store,
|
||||
cache_url=_secret("CACHE_URL", required=session_store == "valkey"),
|
||||
# Contract name. Minimum 1 s so the expiry test can use 2 s.
|
||||
session_ttl_seconds=_int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600),
|
||||
db_pool_min=db_pool_min,
|
||||
db_pool_max=db_pool_max,
|
||||
db_timeout_seconds=_float("DB_TIMEOUT_SECONDS", 3.0, 0.5, 30.0),
|
||||
cache_timeout_seconds=_float("CACHE_TIMEOUT_SECONDS", 0.5, 0.05, 10.0),
|
||||
hash_concurrency=_int("PASSWORD_HASH_CONCURRENCY", 2, 1, 16),
|
||||
instance_id=_instance_id(),
|
||||
# After SIGTERM: readiness is 503 but requests are still served for this long,
|
||||
# so the load balancer stops routing here before the listener closes.
|
||||
drain_seconds=_float("DRAIN_SECONDS", 0.0, 0.0, 10.0),
|
||||
# Contract: a replay within 24 h returns the original result.
|
||||
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600),
|
||||
# Experiments (bench/track1): log DB pool counters and process CPU every N s; 0 = off.
|
||||
stats_log_seconds=_float("STATS_LOG_SECONDS", 0.0, 0.0, 60.0),
|
||||
# Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous
|
||||
# multi-statement transaction; both have identical semantics (A/B on one image).
|
||||
message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}),
|
||||
**s3_settings(credentials_required=s3_credentials),
|
||||
**jobs_settings(broker_required=False),
|
||||
)
|
||||
|
||||
|
||||
# Contract limits (contracts/README.md): configurable DOWN for experiments, never above them.
|
||||
CONTRACT_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
CONTRACT_MAX_IMAGE_PIXELS = 40_000_000
|
||||
# Failure points for the experiments only (FAULT_POINTS of ONE service, compose variables
|
||||
# API_/RELAY_/WORKER_FAULT_POINTS); empty in normal runs. `name` or `name=<integer>`.
|
||||
FAULT_POINTS = {
|
||||
# API, upload: between the staging PUT and the job COMMIT / after the job COMMIT, before 202.
|
||||
"after_s3_put", "after_enqueue_commit",
|
||||
# Relay: crash after the broker confirmed a publish but before outbox.published_at is
|
||||
# committed; publish every message twice; publish a batch in reverse order.
|
||||
"crash_after_publish", "duplicate_publish", "reverse_order",
|
||||
# Worker: crash after the claim (before any side effect), after the S3 writes (before the
|
||||
# result COMMIT), after the result COMMIT (before the ack); transient failure of the first N
|
||||
# attempts; permanent failure; slow processing (N s, lease kept alive) of every job or only of
|
||||
# pipeline version `slow_pipeline`; hang: stop the heartbeat and sleep N s inside processing.
|
||||
"crash_after_claim", "crash_after_s3_write", "crash_after_commit", "transient_error", "permanent_error",
|
||||
"slow", "slow_pipeline", "hang",
|
||||
# Worker cleanup: pause N s after reading the candidates, before locking/deleting them.
|
||||
"pause_cleanup",
|
||||
# Lab 6 (API, POST /chats/{chat_id}/messages only): slow handler code (N ms of work outside the
|
||||
# database: the trace shows a long server span WITHOUT a long child span - incident 2 contrast);
|
||||
# rare server errors (N per mille answered 503) and rare slow requests (N per mille + 500 ms)
|
||||
# for track 1 (what sampling keeps of rare events).
|
||||
"slow_handler", "random_5xx", "random_slow",
|
||||
}
|
||||
|
||||
|
||||
def _faults() -> tuple[frozenset[str], dict[str, int]]:
|
||||
names, values = set(), {}
|
||||
for item in os.environ.get("FAULT_POINTS", "").split(","):
|
||||
name, _, raw = item.strip().partition("=")
|
||||
if not name:
|
||||
continue
|
||||
if name not in FAULT_POINTS:
|
||||
raise ConfigError(f"FAULT_POINTS may contain only {sorted(FAULT_POINTS)}")
|
||||
if raw:
|
||||
if not raw.isdigit():
|
||||
raise ConfigError(f"FAULT_POINTS value of {name} must be an integer")
|
||||
values[name] = int(raw)
|
||||
names.add(name)
|
||||
return frozenset(names), values
|
||||
|
||||
|
||||
def _bucket(name: str, default: str) -> str:
|
||||
bucket = os.environ.get(name, default).strip() or default
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
|
||||
raise ConfigError(f"{name} is not a valid bucket name: {bucket!r}")
|
||||
return bucket
|
||||
|
||||
|
||||
def s3_settings(*, credentials_required: bool = True) -> dict:
|
||||
"""S3 part of Settings; also used by the bootstrap CLI with its own keys."""
|
||||
faults, fault_values = _faults()
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").strip() or "http://s3:8333"
|
||||
if not re.fullmatch(r"https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?/?", endpoint):
|
||||
raise ConfigError(f"S3_ENDPOINT must be http(s)://host[:port], got {endpoint!r}")
|
||||
bucket = _bucket("S3_BUCKET", "messenger-attachments")
|
||||
staging = _bucket("S3_STAGING_BUCKET", "messenger-staging")
|
||||
if staging == bucket:
|
||||
raise ConfigError("S3_STAGING_BUCKET must differ from S3_BUCKET")
|
||||
return dict(
|
||||
s3_endpoint=endpoint,
|
||||
s3_region=os.environ.get("S3_REGION", "us-east-1").strip() or "us-east-1",
|
||||
s3_bucket=bucket,
|
||||
s3_staging_bucket=staging,
|
||||
s3_access_key_id=_secret("S3_ACCESS_KEY_ID", required=credentials_required),
|
||||
s3_secret_access_key=_secret("S3_SECRET_ACCESS_KEY", required=credentials_required),
|
||||
s3_timeout_seconds=_float("S3_TIMEOUT_SECONDS", 3.0, 0.2, 30.0),
|
||||
s3_connect_timeout_seconds=_float("S3_CONNECT_TIMEOUT_SECONDS", 1.0, 0.1, 10.0),
|
||||
s3_max_connections=_int("S3_MAX_CONNECTIONS", 20, 1, 200),
|
||||
max_upload_bytes=_int("MAX_UPLOAD_BYTES", CONTRACT_MAX_UPLOAD_BYTES, 1024, CONTRACT_MAX_UPLOAD_BYTES),
|
||||
max_image_pixels=_int("MAX_IMAGE_PIXELS", CONTRACT_MAX_IMAGE_PIXELS, 1, CONTRACT_MAX_IMAGE_PIXELS),
|
||||
# At most this many request bodies of one replica are buffered/checked at once (RAM bound:
|
||||
# UPLOAD_CONCURRENCY x MAX_UPLOAD_BYTES); further uploads wait, then get 503.
|
||||
upload_concurrency=_int("UPLOAD_CONCURRENCY", 4, 1, 64),
|
||||
upload_queue_timeout_seconds=_float("UPLOAD_QUEUE_TIMEOUT_SECONDS", 5.0, 0.0, 60.0),
|
||||
upload_read_timeout_seconds=_float("UPLOAD_READ_TIMEOUT_SECONDS", 30.0, 1.0, 300.0),
|
||||
image_verify_timeout_seconds=_float("IMAGE_VERIFY_TIMEOUT_SECONDS", 10.0, 1.0, 120.0),
|
||||
# Full checks running at once per replica: a strict JPEG decode of a 40 Mpx progressive
|
||||
# file needs up to ~120-240 MB of coefficient buffers (capped by JPEG_MAX_MEMORY_MB).
|
||||
image_verify_concurrency=_int("IMAGE_VERIFY_CONCURRENCY", 1, 1, 16),
|
||||
jpeg_max_memory_mb=_int("JPEG_MAX_MEMORY_MB", 256, 16, 2048),
|
||||
# An intent row still `pending` after this long belongs to a failed upload: the janitor
|
||||
# deletes its object and the row. Far above the longest possible upload (~45 s).
|
||||
pending_grace_seconds=_int("PENDING_GRACE_SECONDS", 900, 1, 7 * 24 * 3600),
|
||||
janitor_interval_seconds=_float("JANITOR_INTERVAL_SECONDS", 60.0, 0.0, 3600.0),
|
||||
fault_points=faults,
|
||||
fault_values=fault_values,
|
||||
)
|
||||
|
||||
|
||||
def jobs_settings(*, broker_required: bool) -> dict:
|
||||
"""Lab 5 pipeline: retries, lease, worker limits, cleanup, relay (docs/PIPELINE.md)."""
|
||||
from .pipeline import PIPELINES # local import: pipeline.py imports nothing from here
|
||||
timeout = _float("JOB_TIMEOUT_SECONDS", 60.0, 1.0, 600.0)
|
||||
lease = _float("JOB_LEASE_SECONDS", 30.0, 2.0, 600.0)
|
||||
base = _float("JOB_RETRY_BASE_SECONDS", 2.0, 0.0, 600.0)
|
||||
cap = _float("JOB_RETRY_MAX_SECONDS", 60.0, 0.0, 3600.0)
|
||||
if base > cap:
|
||||
raise ConfigError("JOB_RETRY_BASE_SECONDS must not exceed JOB_RETRY_MAX_SECONDS")
|
||||
orphan_grace = _int("ORPHAN_GRACE_SECONDS", 600, 1, 7 * 24 * 3600)
|
||||
version = _int("PIPELINE_VERSION", 1, 1, 1000)
|
||||
if version not in PIPELINES:
|
||||
raise ConfigError(f"PIPELINE_VERSION must be one of {sorted(PIPELINES)}")
|
||||
return dict(
|
||||
broker_url=_secret("BROKER_URL", required=broker_required),
|
||||
# Pipeline version of the jobs created by new uploads (track 2: versioned pipeline).
|
||||
pipeline_version=version,
|
||||
# Managed attempts (claims) per job before failed/retry_exhausted.
|
||||
job_max_attempts=_int("JOB_MAX_ATTEMPTS", 5, 1, 100),
|
||||
# Hard limit of ONE attempt: the image child process is killed, the lease is no longer renewed.
|
||||
job_timeout_seconds=timeout,
|
||||
# Lease of a claimed job, renewed by the heartbeat every lease/3 while the attempt runs.
|
||||
job_lease_seconds=lease,
|
||||
# Backoff of transient failures: full jitter, uniform(0, min(max, base * 2^(attempt-1))).
|
||||
job_retry_base_seconds=base,
|
||||
job_retry_max_seconds=cap,
|
||||
# Jobs processed at once by ONE worker process = RabbitMQ prefetch (basic.qos).
|
||||
worker_concurrency=_int("WORKER_CONCURRENCY", 2, 1, 32),
|
||||
worker_shutdown_seconds=_float("WORKER_SHUTDOWN_SECONDS", 20.0, 0.0, 120.0),
|
||||
# Address-space limit (RLIMIT_AS) of the child process that decodes/encodes ONE image.
|
||||
image_max_memory_mb=_int("IMAGE_MAX_MEMORY_MB", 768, 128, 8192),
|
||||
# Staging copy of a FAILED attachment is kept this long for a replay, then deleted.
|
||||
staging_retention_seconds=_int("STAGING_RETENTION_SECONDS", 86400, 0, 30 * 24 * 3600),
|
||||
# Objects of attempts that did not publish are deleted once the attempt ended this long ago.
|
||||
orphan_grace_seconds=orphan_grace,
|
||||
cleanup_interval_seconds=_float("CLEANUP_INTERVAL_SECONDS", 30.0, 0.0, 3600.0),
|
||||
relay_poll_seconds=_float("RELAY_POLL_SECONDS", 0.5, 0.05, 60.0),
|
||||
relay_batch=_int("RELAY_BATCH", 50, 1, 1000),
|
||||
# A queued job whose message has not led to a claim for this long is published again
|
||||
# (message lost in the broker, dead-lettered, purged): no accepted job waits forever.
|
||||
queued_republish_seconds=_float("QUEUED_REPUBLISH_SECONDS", 300.0, 5.0, 86400.0),
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Opaque keyset cursors.
|
||||
|
||||
A cursor encodes the sort key `(created_at, id)` of the last item on the page
|
||||
plus the resource it belongs to, e.g. `v1|m|<chat_id>|<ts_us>|<message_id>`,
|
||||
packed in URL-safe base64. The client treats it as an opaque string; the server
|
||||
rejects cursors of another chat/user (400) and any non-canonical encoding.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
|
||||
from .errors import InvalidRequest
|
||||
from .validation import UUID_RE
|
||||
|
||||
B64_RE = re.compile(r"[A-Za-z0-9_-]{1,512}")
|
||||
TS_RE = re.compile(r"[0-9]{1,19}")
|
||||
|
||||
# Latest instant both Python datetime and PostgreSQL accept: 9999-12-31T23:59:59.999999Z.
|
||||
MAX_TS_US = 253402300799999999
|
||||
|
||||
MESSAGES = "m"
|
||||
CHATS = "c"
|
||||
|
||||
SortKey = tuple[int, str]
|
||||
|
||||
|
||||
def encode(scope: str, owner_id: str, key: SortKey) -> str:
|
||||
ts, item_id = key
|
||||
raw = f"v1|{scope}|{owner_id}|{ts}|{item_id}".encode("ascii")
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
||||
|
||||
|
||||
def decode(cursor: str, scope: str, owner_id: str) -> SortKey:
|
||||
"""Return the sort key stored in the cursor or raise InvalidRequest."""
|
||||
bad = InvalidRequest("Неверный cursor")
|
||||
if B64_RE.fullmatch(cursor) is None:
|
||||
raise bad
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("ascii")
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise bad from None
|
||||
parts = raw.split("|")
|
||||
if len(parts) != 5 or parts[0] != "v1":
|
||||
raise bad
|
||||
_, got_scope, got_owner, ts, item_id = parts
|
||||
if TS_RE.fullmatch(ts) is None or UUID_RE.fullmatch(item_id) is None or item_id != item_id.lower():
|
||||
raise bad
|
||||
key = (int(ts), item_id)
|
||||
if key[0] > MAX_TS_US:
|
||||
raise bad # out-of-range time must be 400, not an overflow (500) in datetime/SQL
|
||||
if encode(got_scope, got_owner, key) != cursor:
|
||||
raise bad # only the canonical form produced by the server is accepted
|
||||
if got_scope != scope or got_owner != owner_id:
|
||||
raise InvalidRequest("cursor относится к другому ресурсу")
|
||||
return key
|
||||
@@ -0,0 +1,171 @@
|
||||
"""PostgreSQL access: a bounded connection pool and a hard deadline for every unit of work.
|
||||
|
||||
Three independent limits keep a request from hanging when the database misbehaves:
|
||||
|
||||
* pool `timeout` — waiting for a free connection (pool exhausted);
|
||||
* server `statement_timeout` / `lock_timeout` — PostgreSQL itself cancels a slow
|
||||
statement or a statement stuck behind a lock;
|
||||
* client deadline — covers what the server cannot report, e.g. a
|
||||
paused/frozen PostgreSQL container or a dead network.
|
||||
|
||||
The client deadline needs care. Every unit of work runs as its own task; at the deadline
|
||||
the REQUEST stops waiting and gets 503 at once, but the task is NOT cancelled: cancelling a
|
||||
psycopg query makes psycopg send a cancel request, and libpq starts that connection
|
||||
(PQcancelStart) synchronously in the event-loop thread, resolving the host name first.
|
||||
When the API has lost its network to PostgreSQL (lab 3 review scenario: `docker network
|
||||
disconnect`), that blocked the WHOLE replica, /health/live included, for ~1 minute.
|
||||
The abandoned task instead ends by itself, bounded by:
|
||||
|
||||
* TCP keepalives + `tcp_user_timeout` (= the deadline): a dead peer or a vanished network
|
||||
breaks the socket within seconds, the connection is discarded by the pool;
|
||||
* `statement_timeout` / `lock_timeout` on a live but slow server;
|
||||
* a frozen (paused) server keeps the connection until it resumes; meanwhile new work waits
|
||||
at most the pool timeout and gets 503.
|
||||
|
||||
Any failure becomes 503 `unavailable` — never 401, never a hang.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import TypeVar
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import AsyncConnectionPool, PoolTimeout
|
||||
|
||||
from . import telemetry
|
||||
from .config import Settings
|
||||
from .errors import Unavailable
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
T = TypeVar("T")
|
||||
Work = Callable[[psycopg.AsyncConnection], Awaitable[T]]
|
||||
|
||||
# Errors that mean "the database is unavailable right now", not "the request is wrong".
|
||||
# QueryCanceled (statement_timeout), LockNotAvailable (lock_timeout) and AdminShutdown
|
||||
# (server restart) are subclasses of OperationalError.
|
||||
UNAVAILABLE_ERRORS = (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TimeoutError)
|
||||
|
||||
|
||||
def _forget(task: asyncio.Task) -> None:
|
||||
"""Done-callback for abandoned tasks: retrieve the result so nothing is logged as 'never retrieved'."""
|
||||
if not task.cancelled():
|
||||
task.exception()
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, settings: Settings, name: str = "messenger-api"):
|
||||
self.name = name
|
||||
self.deadline = settings.db_timeout_seconds
|
||||
options = (
|
||||
f"-c statement_timeout={settings.db_statement_timeout_ms} "
|
||||
f"-c lock_timeout={max(100, settings.db_statement_timeout_ms // 2)} "
|
||||
"-c idle_in_transaction_session_timeout=10000"
|
||||
)
|
||||
self.pool = AsyncConnectionPool(
|
||||
conninfo=settings.database_url,
|
||||
min_size=settings.db_pool_min,
|
||||
max_size=settings.db_pool_max,
|
||||
timeout=settings.db_timeout_seconds, # max wait for a free connection
|
||||
open=False,
|
||||
name=name,
|
||||
check=AsyncConnectionPool.check_connection, # drop connections broken by a DB restart
|
||||
kwargs={
|
||||
"options": options,
|
||||
"connect_timeout": max(1, int(settings.db_timeout_seconds)),
|
||||
"application_name": name, # visible in pg_stat_activity: api / relay / worker
|
||||
# Autocommit connections: a single statement (post_message function, ping) is its
|
||||
# own transaction with ONE round trip; multi-statement work uses an explicit
|
||||
# conn.transaction() (BEGIN ... COMMIT), see run().
|
||||
"autocommit": True,
|
||||
# Detect a dead peer / lost network without any cancel request (see module doc).
|
||||
"keepalives": 1,
|
||||
"keepalives_idle": 5,
|
||||
"keepalives_interval": 1,
|
||||
"keepalives_count": 3,
|
||||
"tcp_user_timeout": int(settings.db_timeout_seconds * 1000),
|
||||
},
|
||||
)
|
||||
|
||||
async def open(self) -> None:
|
||||
# wait=False: the API starts (liveness 200) even if PostgreSQL is not up yet;
|
||||
# readiness stays 503 until the database answers.
|
||||
await self.pool.open(wait=False)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.pool.close(timeout=2)
|
||||
|
||||
async def run(self, work: Work[T], deadline: float | None = None, *, transaction: bool = True,
|
||||
op: str | None = None) -> T:
|
||||
"""Run `work(conn)` in one transaction (COMMIT on success, ROLLBACK on any exception).
|
||||
transaction=False: `work` issues exactly ONE statement, which autocommit makes atomic.
|
||||
|
||||
Domain errors raised by `work` (NotFound, Conflict, ...) propagate unchanged;
|
||||
database unavailability and the deadline become Unavailable (503).
|
||||
|
||||
Lab 6: one CLIENT span `db <op>` per unit of work (only inside a traced request/job: no
|
||||
root spans from background loops) with the pool wait as attribute
|
||||
`db.client.connection.wait_time_ms`, plus the metrics db.client.operation.duration and
|
||||
db.client.connection.wait_time. `op` defaults to the calling function's name (a fixed
|
||||
set of code names, low cardinality); SQL text and parameters are never recorded.
|
||||
"""
|
||||
op = op or sys._getframe(1).f_code.co_name
|
||||
parent_recording = telemetry.trace.get_current_span().is_recording()
|
||||
|
||||
async def unit() -> T:
|
||||
begin = time.perf_counter()
|
||||
span = (telemetry.TRACER.start_span(f"db {op}", kind=telemetry.SpanKind.CLIENT, attributes={
|
||||
"db.system.name": "postgresql", "db.operation.name": op, "db.client.connection.pool.name": self.name})
|
||||
if parent_recording else None)
|
||||
outcome = "error"
|
||||
try:
|
||||
async with self.pool.connection() as conn:
|
||||
waited = time.perf_counter() - begin
|
||||
telemetry.db_wait.record(waited, {"db.client.connection.pool.name": self.name})
|
||||
if span is not None:
|
||||
span.set_attribute("db.client.connection.wait_time_ms", round(waited * 1000, 3))
|
||||
if not transaction:
|
||||
result = await work(conn)
|
||||
else:
|
||||
async with conn.transaction():
|
||||
result = await work(conn)
|
||||
outcome = "ok"
|
||||
return result
|
||||
except UNAVAILABLE_ERRORS as exc:
|
||||
if span is not None:
|
||||
telemetry.mark_error(span, type(exc).__name__)
|
||||
raise
|
||||
except Exception:
|
||||
outcome = "domain" # NotFound/Conflict...: an answer, not a database failure
|
||||
raise
|
||||
finally:
|
||||
telemetry.db_duration.record(time.perf_counter() - begin, {
|
||||
"db.system.name": "postgresql", "db.operation.name": op, "outcome": outcome,
|
||||
"db.client.connection.pool.name": self.name})
|
||||
if span is not None:
|
||||
span.end()
|
||||
|
||||
task = asyncio.ensure_future(unit()) # copies the context: the span's parent is the caller's span
|
||||
try:
|
||||
return await asyncio.wait_for(asyncio.shield(task), deadline or self.deadline)
|
||||
except UNAVAILABLE_ERRORS as exc:
|
||||
log.warning("database_unavailable", extra={"fields": {"error": type(exc).__name__, "op": op}})
|
||||
raise Unavailable("База данных временно недоступна") from None
|
||||
finally:
|
||||
if not task.done():
|
||||
# Deadline or cancelled request: stop waiting now. The task is left to finish
|
||||
# on its own (no task.cancel(): that would trigger psycopg's blocking cancel).
|
||||
task.add_done_callback(_forget)
|
||||
|
||||
async def ping(self, timeout: float = 1.0) -> bool:
|
||||
async def select_one(conn: psycopg.AsyncConnection) -> None:
|
||||
await conn.execute("SELECT 1")
|
||||
try:
|
||||
await self.run(select_one, deadline=timeout, transaction=False, op="ping")
|
||||
return True
|
||||
except Unavailable:
|
||||
return False
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Swagger UI for manual experiments: http://127.0.0.1:8080/docs
|
||||
|
||||
The page shows the course contract contracts/openapi.json as is (it is not
|
||||
generated from our code). Only `servers` is replaced with "/" so that the
|
||||
"Try it out" requests go to the same host the page was opened from.
|
||||
Swagger UI itself (JS/CSS) is loaded by the browser from the jsDelivr CDN.
|
||||
Disable with DOCS_ENABLED=false.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import HTMLResponse, JSONResponse
|
||||
|
||||
SPEC_PATH = Path(__file__).resolve().parents[2] / "contracts" / "openapi.json"
|
||||
SWAGGER_UI = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.33.0"
|
||||
|
||||
PAGE = f"""<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Messenger lab1 — Swagger UI</title>
|
||||
<link rel="stylesheet" href="{SWAGGER_UI}/swagger-ui.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="{SWAGGER_UI}/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
window.ui = SwaggerUIBundle({{
|
||||
url: "/openapi.json",
|
||||
dom_id: "#swagger-ui",
|
||||
tryItOutEnabled: true, // fields are editable right away
|
||||
persistAuthorization: true, // X-User-Id from "Authorize" survives page reload
|
||||
displayRequestDuration: true,
|
||||
}});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _spec() -> dict:
|
||||
spec = json.loads(SPEC_PATH.read_text(encoding="utf-8"))
|
||||
spec["servers"] = [{"url": "/", "description": "этот сервер"}]
|
||||
return spec
|
||||
|
||||
|
||||
async def swagger_page(request: Request) -> HTMLResponse:
|
||||
return HTMLResponse(PAGE)
|
||||
|
||||
|
||||
async def openapi_json(request: Request) -> JSONResponse:
|
||||
return JSONResponse(_spec())
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Domain errors mapped 1:1 to the contract error codes (contracts/README.md)."""
|
||||
from __future__ import annotations
|
||||
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
status = 500
|
||||
code = "internal_error"
|
||||
default_message = "Внутренняя ошибка сервера"
|
||||
|
||||
def __init__(self, message: str | None = None):
|
||||
self.message = message or self.default_message
|
||||
super().__init__(self.message)
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
return {}
|
||||
|
||||
|
||||
class InvalidRequest(ApiError):
|
||||
status = 400
|
||||
code = "invalid_request"
|
||||
default_message = "Неверный запрос"
|
||||
|
||||
|
||||
class Unauthorized(ApiError):
|
||||
"""401 with the challenge of the scheme the endpoint expects (RFC 7235)."""
|
||||
|
||||
status = 401
|
||||
code = "unauthorized"
|
||||
default_message = "Требуется действительная сессия"
|
||||
|
||||
def __init__(self, message: str | None = None, challenge: str = BEARER_CHALLENGE):
|
||||
super().__init__(message)
|
||||
self.challenge = challenge
|
||||
|
||||
@property
|
||||
def headers(self) -> dict[str, str]:
|
||||
return {"WWW-Authenticate": self.challenge}
|
||||
|
||||
|
||||
class NotFound(ApiError):
|
||||
status = 404
|
||||
code = "not_found"
|
||||
default_message = "Объект не найден"
|
||||
|
||||
|
||||
class Conflict(ApiError):
|
||||
status = 409
|
||||
code = "conflict"
|
||||
default_message = "Конфликт"
|
||||
|
||||
|
||||
class PayloadTooLarge(ApiError):
|
||||
status = 413
|
||||
code = "payload_too_large"
|
||||
default_message = "Тело запроса слишком большое"
|
||||
|
||||
|
||||
class UnsupportedMediaType(ApiError):
|
||||
status = 415
|
||||
code = "unsupported_media_type"
|
||||
default_message = "Неподдерживаемый тип содержимого"
|
||||
|
||||
|
||||
class Unavailable(ApiError):
|
||||
status = 503
|
||||
code = "unavailable"
|
||||
default_message = "Сервис временно недоступен"
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Docker HEALTHCHECK probe without curl/wget in the image: `python -m messenger.healthcheck`.
|
||||
|
||||
(no arguments) API: GET /health/ready on the local port
|
||||
--file /tmp/heartbeat --max-age 30 relay/worker: the main loop wrote its heartbeat recently
|
||||
(it writes it only while its database/broker work)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if len(argv) == 4 and argv[0] == "--file" and argv[2] == "--max-age":
|
||||
try:
|
||||
with open(argv[1], encoding="ascii") as f:
|
||||
return 0 if time.time() - float(f.read().strip()) <= float(argv[3]) else 1
|
||||
except (OSError, ValueError):
|
||||
return 1
|
||||
port = os.environ.get("APP_PORT", "8080").strip() or "8080"
|
||||
try:
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/ready", timeout=2) as response:
|
||||
return 0 if response.status == 200 else 1
|
||||
except Exception:
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,328 @@
|
||||
"""Content checks of uploaded images (lab 4): what the bytes ARE, not what the client says.
|
||||
|
||||
Two stages, both with bounded memory and both BEFORE anything is stored:
|
||||
|
||||
1. `sniff(head)` — runs on the first bytes while the body is still arriving. Recognises
|
||||
PNG/JPEG by the signature and reads the dimensions from the header (PNG IHDR, JPEG SOFn).
|
||||
A foreign format is rejected (415) and a picture with more than MAX_IMAGE_PIXELS pixels
|
||||
(413) before the rest of the body is read and long before any pixel is decoded.
|
||||
2. `verify(data, info)` — full integrity check of the complete file, run in a worker thread:
|
||||
* PNG: our own streaming validator. Every chunk CRC is checked, the IDAT zlib stream is
|
||||
inflated in 1 MiB steps and DISCARDED (no raster in memory), its size must be exactly
|
||||
height x (1 + row bytes) (Adam7 per pass), every row filter byte must be 0..4, IEND
|
||||
must close the file. A truncated file, a broken IDAT or extra/missing pixel data fail.
|
||||
Pillow is not used for PNG: it would allocate the whole raster (40 Mpx RGBA = 160 MB).
|
||||
* JPEG: libjpeg-turbo `djpeg -strict` decodes the whole entropy-coded data at 1/8 scale
|
||||
(DCT scaling: the output raster is 64 times smaller) in a child process; any decoder
|
||||
warning is fatal, so a truncated file or a file without scan data after SOS fails.
|
||||
|
||||
Every problem of the CONTENT is an ImageError carrying the HTTP status (415 or 413);
|
||||
nothing here may turn user input into a 500.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_SOI = b"\xff\xd8\xff"
|
||||
|
||||
PNG = "image/png"
|
||||
JPEG = "image/jpeg"
|
||||
|
||||
# Bits per pixel channel count by PNG colour type, and the bit depths allowed for it.
|
||||
PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}}
|
||||
# Adam7 passes: (x start, y start, x step, y step).
|
||||
ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
# JPEG start-of-frame markers that carry the frame size (not DHT C4, JPG C8, DAC CC).
|
||||
JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
# Standalone markers without a length field.
|
||||
JPEG_STANDALONE = {0x01, *range(0xD0, 0xD8)}
|
||||
|
||||
DJPEG = shutil.which("djpeg") or "djpeg" # libjpeg-turbo-progs, installed in the Dockerfile
|
||||
INPUT_STEP = 1 << 16 # compressed bytes handed to zlib at once
|
||||
INFLATE_STEP = 1 << 20 # bytes of raw PNG data produced per zlib call
|
||||
MAX_DIMENSION = 2**31 - 1
|
||||
|
||||
|
||||
class ImageError(Exception):
|
||||
"""The uploaded bytes are not an acceptable image. `status`: 415 (format/corrupt) or 413."""
|
||||
|
||||
def __init__(self, status: int, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
class VerifierUnavailable(Exception):
|
||||
"""The checker itself could not run to the end (resources): the API answers 503, retryable."""
|
||||
|
||||
|
||||
def unsupported(message: str ="Файл не является корректным изображением PNG или JPEG") -> ImageError:
|
||||
return ImageError(415, message)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImageInfo:
|
||||
content_type: str
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
def detect(head: bytes) -> str | None:
|
||||
"""Format by signature; None while fewer bytes than a signature have arrived."""
|
||||
if head[:8] == PNG_SIGNATURE:
|
||||
return PNG
|
||||
if head[:3] == JPEG_SOI:
|
||||
return JPEG
|
||||
probe = min(len(head), 8)
|
||||
if PNG_SIGNATURE.startswith(head[:probe]) or JPEG_SOI.startswith(head[:min(probe, 3)]):
|
||||
return None
|
||||
raise unsupported()
|
||||
|
||||
|
||||
def sniff(head: bytes, max_pixels: int) -> ImageInfo | None:
|
||||
"""Format and size from the beginning of the file, or None if more bytes are needed.
|
||||
|
||||
Raises ImageError: 415 for a foreign/broken header, 413 for too many pixels."""
|
||||
kind = detect(head)
|
||||
if kind is None:
|
||||
return None
|
||||
info = _png_header(head) if kind == PNG else _jpeg_header(head)
|
||||
if info is None:
|
||||
return None
|
||||
if info.width * info.height > max_pixels:
|
||||
raise ImageError(413, f"Изображение больше {max_pixels} пикселей")
|
||||
return info
|
||||
|
||||
|
||||
def _png_header(head: bytes) -> ImageInfo | None:
|
||||
if len(head) < 33:
|
||||
return None
|
||||
length, ctype = struct.unpack(">I4s", head[8:16])
|
||||
if ctype != b"IHDR" or length != 13:
|
||||
raise unsupported()
|
||||
if zlib.crc32(head[12:29]) != struct.unpack(">I", head[29:33])[0]:
|
||||
raise unsupported()
|
||||
width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", head[16:29])
|
||||
if not (1 <= width <= MAX_DIMENSION and 1 <= height <= MAX_DIMENSION):
|
||||
raise unsupported()
|
||||
if color not in PNG_DEPTHS or depth not in PNG_DEPTHS[color] or compression or filtering or interlace > 1:
|
||||
raise unsupported()
|
||||
return ImageInfo(PNG, width, height)
|
||||
|
||||
|
||||
def _jpeg_header(head: bytes) -> ImageInfo | None:
|
||||
"""Walk the marker segments up to the first SOFn. None = the SOF has not arrived yet."""
|
||||
i = 2
|
||||
n = len(head)
|
||||
while True:
|
||||
if i >= n:
|
||||
return None
|
||||
if head[i] != 0xFF:
|
||||
raise unsupported()
|
||||
while i < n and head[i] == 0xFF: # fill bytes
|
||||
i += 1
|
||||
if i >= n:
|
||||
return None
|
||||
marker = head[i]
|
||||
i += 1
|
||||
if marker in JPEG_STANDALONE:
|
||||
continue
|
||||
if marker in (0xD8, 0xD9, 0xDA, 0x00):
|
||||
# Second SOI, EOI or scan data before any frame header: not a usable JPEG.
|
||||
raise unsupported()
|
||||
if i + 2 > n:
|
||||
return None
|
||||
length = struct.unpack(">H", head[i:i + 2])[0]
|
||||
if length < 2:
|
||||
raise unsupported()
|
||||
if marker in JPEG_SOF:
|
||||
if i + 7 > n:
|
||||
return None
|
||||
if length < 8:
|
||||
raise unsupported()
|
||||
height, width = struct.unpack(">HH", head[i + 3:i + 7])
|
||||
if width == 0 or height == 0: # height 0 = DNL-defined height: not supported
|
||||
raise unsupported()
|
||||
return ImageInfo(JPEG, width, height)
|
||||
i += length
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ full verification
|
||||
async def verify(data: bytes | bytearray | memoryview, info: ImageInfo, *, timeout: float = 10.0,
|
||||
jpeg_max_memory_mb: int = 256) -> None:
|
||||
"""Complete integrity check of the whole file. PNG: our validator in a worker thread (zlib
|
||||
releases the GIL); JPEG: a strict libjpeg decoder in a child process."""
|
||||
if info.content_type == PNG:
|
||||
await asyncio.wait_for(asyncio.to_thread(verify_png, data), timeout)
|
||||
else:
|
||||
await verify_jpeg(data, timeout, jpeg_max_memory_mb)
|
||||
|
||||
|
||||
def _png_segments(width: int, height: int, depth: int, color: int, interlace: int) -> list[tuple[int, int]]:
|
||||
"""(byte count, row stride) of every pass of the raw (filtered) image data."""
|
||||
bpp = PNG_CHANNELS[color] * depth
|
||||
passes = ADAM7 if interlace else ((0, 0, 1, 1),)
|
||||
segments = []
|
||||
for xs, ys, dx, dy in passes:
|
||||
pw = (width - xs + dx - 1) // dx if width > xs else 0
|
||||
ph = (height - ys + dy - 1) // dy if height > ys else 0
|
||||
if pw and ph:
|
||||
stride = 1 + (pw * bpp + 7) // 8
|
||||
segments.append((ph * stride, stride))
|
||||
return segments
|
||||
|
||||
|
||||
class _RawChecker:
|
||||
"""Counts inflated bytes against the expected size and checks the filter byte of every row
|
||||
using C-speed slicing (`piece[first::stride]`), so even 40 000 000 one-pixel rows are fast."""
|
||||
|
||||
VALID_FILTERS = bytes(range(5))
|
||||
|
||||
def __init__(self, segments: list[tuple[int, int]]):
|
||||
self.segments = segments
|
||||
self.index = 0 # current pass
|
||||
self.offset = 0 # bytes already seen inside the current pass
|
||||
self.expected = sum(size for size, _ in segments)
|
||||
self.total = 0
|
||||
|
||||
def feed(self, piece: bytes) -> None:
|
||||
self.total += len(piece)
|
||||
if self.total > self.expected:
|
||||
raise unsupported()
|
||||
pos = 0
|
||||
while pos < len(piece):
|
||||
size, stride = self.segments[self.index]
|
||||
take = min(size - self.offset, len(piece) - pos)
|
||||
part = piece[pos:pos + take]
|
||||
first = (-self.offset) % stride
|
||||
if part[first::stride].translate(None, self.VALID_FILTERS):
|
||||
raise unsupported()
|
||||
self.offset += take
|
||||
pos += take
|
||||
if self.offset == size:
|
||||
self.index += 1
|
||||
self.offset = 0
|
||||
|
||||
|
||||
def verify_png(data: bytes | bytearray | memoryview) -> None:
|
||||
view = memoryview(data)
|
||||
if bytes(view[:8]) != PNG_SIGNATURE:
|
||||
raise unsupported()
|
||||
pos = 8
|
||||
n = len(view)
|
||||
checker: _RawChecker | None = None
|
||||
inflater = zlib.decompressobj()
|
||||
color = None
|
||||
seen_plte = seen_idat = idat_done = False
|
||||
first = True
|
||||
while True:
|
||||
if pos + 12 > n:
|
||||
raise unsupported() # truncated: no room for another chunk header + CRC
|
||||
length, ctype = struct.unpack(">I4s", view[pos:pos + 8])
|
||||
if length > n - pos - 12:
|
||||
raise unsupported()
|
||||
body = view[pos + 8:pos + 8 + length]
|
||||
crc = struct.unpack(">I", view[pos + 8 + length:pos + 12 + length])[0]
|
||||
if zlib.crc32(body, zlib.crc32(ctype)) != crc:
|
||||
raise unsupported()
|
||||
pos += 12 + length
|
||||
if not all(65 <= c <= 90 or 97 <= c <= 122 for c in ctype):
|
||||
raise unsupported()
|
||||
if first:
|
||||
if ctype != b"IHDR" or length != 13:
|
||||
raise unsupported()
|
||||
width, height, depth, color, compression, filtering, interlace = struct.unpack(">IIBBBBB", body)
|
||||
if (not (1 <= width <= MAX_DIMENSION and 1 <= height <= MAX_DIMENSION) or color not in PNG_DEPTHS
|
||||
or depth not in PNG_DEPTHS[color] or compression or filtering or interlace > 1):
|
||||
raise unsupported()
|
||||
checker = _RawChecker(_png_segments(width, height, depth, color, interlace))
|
||||
first = False
|
||||
continue
|
||||
assert checker is not None
|
||||
if ctype == b"IHDR":
|
||||
raise unsupported()
|
||||
if ctype == b"PLTE":
|
||||
if seen_plte or seen_idat or color in (0, 4) or length % 3 or not 3 <= length <= 768:
|
||||
raise unsupported()
|
||||
seen_plte = True
|
||||
elif ctype == b"IDAT":
|
||||
if idat_done:
|
||||
raise unsupported() # IDAT chunks must be consecutive
|
||||
if color == 3 and not seen_plte:
|
||||
raise unsupported()
|
||||
seen_idat = True
|
||||
_inflate(inflater, body, checker)
|
||||
elif ctype == b"IEND":
|
||||
if length != 0 or not seen_idat:
|
||||
raise unsupported()
|
||||
if pos != n:
|
||||
raise unsupported() # bytes after IEND (polyglot files) are not accepted
|
||||
break
|
||||
elif not 97 <= ctype[0] <= 122:
|
||||
raise unsupported() # unknown CRITICAL chunk: a decoder could not show the image
|
||||
if ctype != b"IDAT" and seen_idat:
|
||||
idat_done = True
|
||||
# The zlib stream must end exactly with the last pixel row, without trailing data.
|
||||
if not inflater.eof or inflater.unused_data or checker.total != checker.expected:
|
||||
raise unsupported()
|
||||
|
||||
|
||||
def _inflate(inflater, body: memoryview, checker: _RawChecker) -> None:
|
||||
if inflater.eof:
|
||||
if len(body):
|
||||
raise unsupported() # data after the end of the zlib stream
|
||||
return
|
||||
# Input is fed in small slices: zlib's `unconsumed_tail` is a COPY of the unread input, so
|
||||
# feeding the whole 10 MiB IDAT at once would copy the rest of it after every output step.
|
||||
try:
|
||||
for start in range(0, len(body), INPUT_STEP):
|
||||
pending: bytes | memoryview = body[start:start + INPUT_STEP]
|
||||
while pending:
|
||||
if inflater.eof:
|
||||
raise unsupported() # data after the end of the zlib stream
|
||||
checker.feed(inflater.decompress(pending, INFLATE_STEP))
|
||||
pending = inflater.unconsumed_tail
|
||||
if inflater.eof and inflater.unused_data:
|
||||
raise unsupported()
|
||||
except zlib.error:
|
||||
raise unsupported() from None
|
||||
|
||||
|
||||
async def verify_jpeg(data: bytes | bytearray | memoryview, timeout: float, max_memory_mb: int) -> None:
|
||||
"""Decode the WHOLE file with the reference decoder (libjpeg-turbo `djpeg`) in strict mode.
|
||||
|
||||
`-strict` turns every libjpeg warning into a failure: "premature end of data segment"
|
||||
(scan data missing or cut before EOI), "premature end of JPEG file", corrupt Huffman data.
|
||||
Pillow cannot be used for this: it ignores libjpeg warnings and returns a grey picture for
|
||||
a JPEG whose scan data is missing. `-scale 1/8` decodes every block but writes a 64x
|
||||
smaller raster to /dev/null; `-maxmemory` caps libjpeg's working memory (coefficient
|
||||
buffers of progressive files); the separate process is killed at the deadline.
|
||||
"""
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
DJPEG, "-strict", "-scale", "1/8", "-maxmemory", str(max_memory_mb * 1024), "-outfile", os.devnull,
|
||||
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE)
|
||||
stderr = b""
|
||||
try:
|
||||
_, stderr = await asyncio.wait_for(process.communicate(data), timeout)
|
||||
except (asyncio.TimeoutError, asyncio.CancelledError):
|
||||
process.kill()
|
||||
await process.wait()
|
||||
raise
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
await process.wait() # djpeg stopped reading: the file is already known to be broken
|
||||
if process.returncode is not None and process.returncode < 0:
|
||||
# Killed by a signal (the cgroup OOM killer under memory pressure): a problem of the
|
||||
# SERVER, not of the file - never report it as 415.
|
||||
raise VerifierUnavailable()
|
||||
if process.returncode != 0:
|
||||
if b"Insufficient memory" in (stderr or b""):
|
||||
# A valid but extremely memory-hungry file (progressive, 4:4:4, ~40 Mpx): a limit, not corruption.
|
||||
raise ImageError(413, "Изображение слишком велико для обработки")
|
||||
raise unsupported()
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Variants of ONE image, built in a separate child process with hard limits (lab 5 worker).
|
||||
|
||||
parent (worker): await render(data, content_type, version, ...) -> list[Rendered]
|
||||
child: python -m messenger.imaging --type image/png --pipeline 1 ...
|
||||
stdin: original bytes; stdout: one JSON header line + variant bytes
|
||||
|
||||
Why a child process per image:
|
||||
* memory: RLIMIT_AS (IMAGE_MAX_MEMORY_MB) caps the address space of the decoder; a picture that
|
||||
needs more fails with MemoryError -> `image_too_large` (permanent), the worker keeps running;
|
||||
* time: the parent kills the child at JOB_TIMEOUT_SECONDS (C code of Pillow cannot be
|
||||
interrupted inside a thread) -> `processing_timeout` (transient, bounded by JOB_MAX_ATTEMPTS);
|
||||
* pixels: the size is read from the header and checked against MAX_IMAGE_PIXELS BEFORE the
|
||||
pixels are decoded (`Image.open` is lazy).
|
||||
A crash of the decoder (signal) is a transient `processing_killed`: the next attempt may run
|
||||
with less memory pressure; JOB_MAX_ATTEMPTS bounds it.
|
||||
|
||||
Geometry and encoder settings: pipeline.py. Alpha is handled in premultiplied form (RGBa) while
|
||||
resizing, so transparent pixels do not bleed their colour into the edges; for JPEG the result is
|
||||
then composited onto white.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .pipeline import CONTENT_TYPES, CROP_SIDE, OPTIMIZED_BOX, PIPELINES, THUMBNAIL_BOX, center_square, fit
|
||||
|
||||
EXIT_INVALID = 3 # the bytes are not a decodable PNG/JPEG
|
||||
EXIT_TOO_LARGE = 4 # pixel limit or memory limit
|
||||
HEADER_LIMIT = 4096
|
||||
|
||||
|
||||
class ProcessingError(Exception):
|
||||
"""Outcome of an attempt that did not produce variants. `permanent`: another attempt with the
|
||||
same input cannot succeed (job -> failed at once); otherwise retry with backoff."""
|
||||
|
||||
def __init__(self, code: str, permanent: bool):
|
||||
super().__init__(code)
|
||||
self.code = code
|
||||
self.permanent = permanent
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Rendered:
|
||||
name: str
|
||||
content_type: str
|
||||
width: int
|
||||
height: int
|
||||
data: bytes
|
||||
|
||||
@property
|
||||
def sha256(self) -> bytes:
|
||||
return hashlib.sha256(self.data).digest()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ parent side
|
||||
async def render(data: bytes, content_type: str, pipeline_version: int, *, max_pixels: int, timeout: float,
|
||||
memory_mb: int) -> list[Rendered]:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-m", "messenger.imaging", "--type", content_type, "--pipeline", str(pipeline_version),
|
||||
"--max-pixels", str(max_pixels), "--memory-mb", str(memory_mb),
|
||||
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
||||
try:
|
||||
out, _ = await asyncio.wait_for(process.communicate(data), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
raise ProcessingError("processing_timeout", permanent=False) from None
|
||||
except asyncio.CancelledError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
raise
|
||||
code = process.returncode
|
||||
if code == EXIT_INVALID:
|
||||
raise ProcessingError("invalid_image", permanent=True)
|
||||
if code == EXIT_TOO_LARGE:
|
||||
raise ProcessingError("image_too_large", permanent=True)
|
||||
if code is None or code < 0:
|
||||
raise ProcessingError("processing_killed", permanent=False) # OOM killer or another signal
|
||||
if code != 0:
|
||||
raise ProcessingError("processing_failed", permanent=False)
|
||||
return parse_output(out)
|
||||
|
||||
|
||||
def parse_output(out: bytes) -> list[Rendered]:
|
||||
newline = out.find(b"\n", 0, HEADER_LIMIT)
|
||||
if newline < 0:
|
||||
raise ProcessingError("processing_failed", permanent=False)
|
||||
header = json.loads(out[:newline])
|
||||
pos = newline + 1
|
||||
result = []
|
||||
for item in header["variants"]:
|
||||
size = int(item["size"])
|
||||
result.append(Rendered(item["name"], item["content_type"], int(item["width"]), int(item["height"]),
|
||||
out[pos:pos + size]))
|
||||
pos += size
|
||||
if pos != len(out) or [r.name for r in result] != list(CONTENT_TYPES):
|
||||
raise ProcessingError("processing_failed", permanent=False)
|
||||
return result
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ child side
|
||||
def build(data: bytes, content_type: str, pipeline_version: int, max_pixels: int) -> list[Rendered]:
|
||||
"""Decode once, build every variant. Raises the Pillow/OS errors of a bad file."""
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
pipeline = PIPELINES[pipeline_version]
|
||||
warnings.simplefilter("ignore", Image.DecompressionBombWarning) # our own pixel limit below
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
expected = {"image/png": "PNG", "image/jpeg": "JPEG"}[content_type]
|
||||
img = Image.open(io.BytesIO(data), formats=[expected]) # header only: nothing decoded yet
|
||||
width, height = img.size
|
||||
if width * height > max_pixels:
|
||||
raise TooLarge()
|
||||
if expected == "JPEG":
|
||||
# DCT scaling: decode a big JPEG directly at 1/2..1/8 of its size, never below what the
|
||||
# largest variant needs (the box stays square, so EXIF rotation does not matter).
|
||||
img.draft("RGB", (OPTIMIZED_BOX, OPTIMIZED_BOX))
|
||||
img.load()
|
||||
img = ImageOps.exif_transpose(img) # orientation goes into the pixels, the tag is dropped
|
||||
img = _normalize(img)
|
||||
alpha = img.mode == "RGBA"
|
||||
base = img.convert("RGBa") if alpha else img # premultiplied alpha for resampling
|
||||
del img
|
||||
|
||||
def finish(im, *, flatten: bool):
|
||||
if alpha:
|
||||
im = im.convert("RGBA")
|
||||
if flatten:
|
||||
white = Image.new("RGB", im.size, (255, 255, 255))
|
||||
white.paste(im, mask=im.getchannel("A"))
|
||||
im = white
|
||||
im.info = {} # no EXIF/XMP/ICC/comments of the source in a variant
|
||||
return im
|
||||
|
||||
def resized(im, size):
|
||||
return im if im.size == size else im.resize(size, Image.Resampling.LANCZOS, reducing_gap=3.0)
|
||||
|
||||
thumbnail = finish(resized(base, fit(*base.size, THUMBNAIL_BOX)), flatten=True)
|
||||
crop = finish(resized(base.crop(center_square(*base.size)), (CROP_SIDE, CROP_SIDE)), flatten=True)
|
||||
optimized = finish(resized(base, fit(*base.size, OPTIMIZED_BOX)), flatten=False)
|
||||
out = []
|
||||
for name, im in (("thumbnail", thumbnail), ("crop", crop), ("optimized", optimized)):
|
||||
buf = io.BytesIO()
|
||||
if CONTENT_TYPES[name] == "image/jpeg":
|
||||
im.save(buf, "JPEG", quality=pipeline.jpeg_quality, optimize=True, subsampling=2, progressive=False)
|
||||
else:
|
||||
im.save(buf, "WEBP", quality=pipeline.webp_quality, method=pipeline.webp_method, exif=b"",
|
||||
icc_profile="", xmp=b"")
|
||||
out.append(Rendered(name, CONTENT_TYPES[name], im.width, im.height, buf.getvalue()))
|
||||
return out
|
||||
|
||||
|
||||
class TooLarge(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _normalize(img):
|
||||
"""Any PNG/JPEG mode -> RGB, or RGBA when the image has transparency."""
|
||||
if img.mode.startswith("I;16") or img.mode == "I":
|
||||
# 16-bit grey: scale 0..65535 to 0..255 (a plain convert("L") would clip to white).
|
||||
img = img.convert("I").point(lambda v: v * (1 / 257)).convert("L")
|
||||
has_alpha = img.mode in ("RGBA", "LA", "PA", "La", "RGBa") or "transparency" in img.info
|
||||
return img.convert("RGBA" if has_alpha else "RGB") if img.mode != ("RGBA" if has_alpha else "RGB") else img
|
||||
|
||||
|
||||
def child_main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--type", required=True, choices=["image/png", "image/jpeg"])
|
||||
parser.add_argument("--pipeline", type=int, required=True, choices=sorted(PIPELINES))
|
||||
parser.add_argument("--max-pixels", type=int, required=True)
|
||||
parser.add_argument("--memory-mb", type=int, required=True)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
import resource
|
||||
limit = args.memory_mb * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
except (ImportError, ValueError, OSError):
|
||||
pass # not Linux (unit tests on Windows): the container memory limit still applies
|
||||
data = sys.stdin.buffer.read()
|
||||
try:
|
||||
variants = build(data, args.type, args.pipeline, args.max_pixels)
|
||||
except (TooLarge, MemoryError):
|
||||
return EXIT_TOO_LARGE
|
||||
except Exception as exc: # noqa: BLE001 - every decoder error of the CONTENT is "invalid image"
|
||||
from PIL import Image
|
||||
if isinstance(exc, Image.DecompressionBombError):
|
||||
return EXIT_TOO_LARGE
|
||||
if isinstance(exc, (OSError, SyntaxError, ValueError, EOFError, KeyError, IndexError, TypeError)):
|
||||
return EXIT_INVALID
|
||||
raise
|
||||
header = {"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width, "height": v.height,
|
||||
"size": len(v.data)} for v in variants]}
|
||||
sys.stdout.buffer.write(json.dumps(header).encode() + b"\n")
|
||||
for v in variants:
|
||||
sys.stdout.buffer.write(v.data)
|
||||
sys.stdout.buffer.flush()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(child_main())
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Operator CLI for attachment jobs: `python -m messenger.jobctl ...` (compose service `jobctl`).
|
||||
|
||||
list-failed [--limit N] failed registry (view failed_jobs), newest first
|
||||
show <attachment_id> attachment state, its jobs, attempts and audit events
|
||||
stats jobs by state, outbox backlog
|
||||
replay <attachment_id> --operator NAME --reason TEXT
|
||||
failed -> queued: a NEW job (kind=replay, replay_of = the failed job) with a fresh attempt
|
||||
budget. Refused (exit 3, nothing changed) unless the attachment is failed AND its source
|
||||
still exists (staging copy present or original published). "Repeat" never means
|
||||
"run a finished job again": a ready attachment is refused (already_ready).
|
||||
reprocess <attachment_id> --pipeline N --operator NAME --reason TEXT
|
||||
Track 2: build a NEWER pipeline version of a READY attachment from its published original.
|
||||
Refused unless ready, N known, N > published version and no job of version >= N active.
|
||||
A not-yet-ready upload is refused: its only source is the staging copy that belongs to the
|
||||
running job, and its result would race with the first publication.
|
||||
|
||||
Every decision is taken under the attachments row lock, the same lock the cleanup takes before it
|
||||
marks a staging copy `deleting`: either the replay sees the copy and the cleanup then skips the
|
||||
row (no longer failed), or the cleanup marked it first and the replay refuses (source_missing).
|
||||
Output: one JSON document on stdout, without secrets or file names.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from . import jobs
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .pipeline import PIPELINES
|
||||
|
||||
OPERATOR_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
|
||||
EXIT_REFUSED = 3
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def operator(value: str) -> str:
|
||||
if not OPERATOR_RE.fullmatch(value):
|
||||
raise argparse.ArgumentTypeError("operator must match [A-Za-z0-9._-]{1,64}")
|
||||
return value
|
||||
|
||||
|
||||
def reason(value: str) -> str:
|
||||
value = value.strip()
|
||||
if not 1 <= len(value) <= 200 or any(ord(ch) < 32 for ch in value):
|
||||
raise argparse.ArgumentTypeError("reason: 1-200 printable characters")
|
||||
return value
|
||||
|
||||
|
||||
def attachment_id(value: str) -> str:
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError("not a UUID") from None
|
||||
|
||||
|
||||
async def lock_attachment(conn, attachment: str):
|
||||
cur = await conn.execute(
|
||||
"SELECT status, staging_state, object_key IS NOT NULL, published_version FROM attachments "
|
||||
"WHERE id = %s FOR UPDATE", (attachment,))
|
||||
row = await cur.fetchone()
|
||||
if row is None or row[0] == "pending":
|
||||
raise Refused("not_found")
|
||||
return row
|
||||
|
||||
|
||||
async def replay(conn, args, settings: Settings) -> dict:
|
||||
status, staging_state, has_original, _ = await lock_attachment(conn, args.attachment_id)
|
||||
if status == "ready":
|
||||
raise Refused("already_ready")
|
||||
if status != "failed":
|
||||
raise Refused("not_failed:" + status)
|
||||
if not has_original and staging_state != "present":
|
||||
raise Refused("source_missing") # staging removed by the retention cleanup
|
||||
cur = await conn.execute(
|
||||
"SELECT id, pipeline_version FROM jobs WHERE attachment_id = %s AND state = 'failed' "
|
||||
"ORDER BY finished_at DESC LIMIT 1", (args.attachment_id,))
|
||||
last = await cur.fetchone()
|
||||
if last is None:
|
||||
raise Refused("no_failed_job")
|
||||
cur = await conn.execute("SELECT 1 FROM jobs WHERE attachment_id = %s AND state IN ('queued', 'processing')",
|
||||
(args.attachment_id,))
|
||||
if await cur.fetchone():
|
||||
raise Refused("active_job")
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', error_code = NULL, failed_at = NULL, updated_at = clock_timestamp() "
|
||||
"WHERE id = %s", (args.attachment_id,))
|
||||
actor = "jobctl:" + args.operator
|
||||
await jobs.event(conn, last[0], "replay_requested", actor, reason=args.reason)
|
||||
job_id = await jobs.create_job(conn, args.attachment_id, last[1], "replay", settings.job_max_attempts, actor,
|
||||
replay_of=last[0], reason=args.reason)
|
||||
return {"result": "queued", "job_id": str(job_id), "replay_of": str(last[0]), "pipeline_version": last[1]}
|
||||
|
||||
|
||||
async def reprocess(conn, args, settings: Settings) -> dict:
|
||||
status, _, _, published = await lock_attachment(conn, args.attachment_id)
|
||||
if args.pipeline not in PIPELINES:
|
||||
raise Refused("unknown_pipeline")
|
||||
if status != "ready":
|
||||
raise Refused("not_ready:" + status)
|
||||
if args.pipeline <= published:
|
||||
raise Refused("not_newer")
|
||||
cur = await conn.execute(
|
||||
"SELECT max(pipeline_version) FROM jobs WHERE attachment_id = %s AND state IN ('queued', 'processing')",
|
||||
(args.attachment_id,))
|
||||
(active,) = await cur.fetchone()
|
||||
if active is not None and active >= args.pipeline:
|
||||
raise Refused("newer_or_same_active")
|
||||
job_id = await jobs.create_job(conn, args.attachment_id, args.pipeline, "reprocess", settings.job_max_attempts,
|
||||
"jobctl:" + args.operator, reason=args.reason)
|
||||
return {"result": "queued", "job_id": str(job_id), "pipeline_version": args.pipeline,
|
||||
"published_version": published}
|
||||
|
||||
|
||||
async def list_failed(conn, args, settings: Settings) -> dict:
|
||||
cur = await conn.execute(
|
||||
"SELECT job_id, attachment_id, pipeline_version, kind, attempt, max_attempts, error_code, finished_at, "
|
||||
"attachment_status, staging_state FROM failed_jobs ORDER BY finished_at DESC LIMIT %s", (args.limit,))
|
||||
cols = [d.name for d in cur.description]
|
||||
return {"failed": [dict(zip(cols, r)) for r in await cur.fetchall()]}
|
||||
|
||||
|
||||
async def show(conn, args, settings: Settings) -> dict:
|
||||
cur = await conn.execute(
|
||||
"SELECT status, error_code, published_version, staging_state, object_key IS NOT NULL AS original_published, "
|
||||
"updated_at FROM attachments WHERE id = %s", (args.attachment_id,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise Refused("not_found")
|
||||
attachment = dict(zip([d.name for d in cur.description], row))
|
||||
|
||||
async def rows(sql: str) -> list[dict]:
|
||||
c = await conn.execute(sql, (args.attachment_id,))
|
||||
names = [d.name for d in c.description]
|
||||
return [dict(zip(names, r)) for r in await c.fetchall()]
|
||||
|
||||
return {
|
||||
"attachment": attachment,
|
||||
"jobs": await rows("SELECT id, pipeline_version, kind, state, attempt, max_attempts, error_code, replay_of, "
|
||||
"created_at, finished_at FROM jobs WHERE attachment_id = %s ORDER BY created_at"),
|
||||
"attempts": await rows("SELECT a.job_id, a.attempt, a.token, a.worker, a.source, a.outcome, a.error_code, "
|
||||
"a.started_at, a.finished_at, a.objects_cleaned_at FROM job_attempts a "
|
||||
"JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = %s ORDER BY a.started_at"),
|
||||
"variants": await rows("SELECT pipeline_version, name, content_type, size_bytes, width, height, "
|
||||
"encode(sha256, 'hex') AS sha256 FROM attachment_variants WHERE attachment_id = %s "
|
||||
"ORDER BY pipeline_version, name"),
|
||||
"events": await rows("SELECT e.job_id, e.at, e.event, e.attempt, e.actor, e.error_code, e.detail "
|
||||
"FROM job_events e JOIN jobs j ON j.id = e.job_id WHERE j.attachment_id = %s "
|
||||
"ORDER BY e.id"),
|
||||
}
|
||||
|
||||
|
||||
async def stats(conn, args, settings: Settings) -> dict:
|
||||
cur = await conn.execute("SELECT state, count(*) FROM jobs GROUP BY state ORDER BY state")
|
||||
by_state = {r[0]: r[1] for r in await cur.fetchall()}
|
||||
cur = await conn.execute("SELECT count(*), count(*) FILTER (WHERE available_at <= clock_timestamp()) "
|
||||
"FROM outbox WHERE published_at IS NULL")
|
||||
pending, due = await cur.fetchone()
|
||||
return {"jobs": by_state, "outbox_unpublished": pending, "outbox_due": due}
|
||||
|
||||
|
||||
COMMANDS = {"replay": replay, "reprocess": reprocess, "list-failed": list_failed, "show": show, "stats": stats}
|
||||
|
||||
|
||||
def arguments(argv: list[str] | None) -> argparse.Namespace:
|
||||
p = argparse.ArgumentParser(prog="jobctl", description="Attachment jobs: failed registry, replay, reprocess")
|
||||
sub = p.add_subparsers(dest="command", required=True)
|
||||
for name in ("replay", "reprocess"):
|
||||
s = sub.add_parser(name)
|
||||
s.add_argument("attachment_id", type=attachment_id)
|
||||
if name == "reprocess":
|
||||
s.add_argument("--pipeline", type=int, required=True)
|
||||
s.add_argument("--operator", type=operator, required=True)
|
||||
s.add_argument("--reason", type=reason, required=True)
|
||||
s = sub.add_parser("list-failed")
|
||||
s.add_argument("--limit", type=int, default=50)
|
||||
s = sub.add_parser("show")
|
||||
s.add_argument("attachment_id", type=attachment_id)
|
||||
sub.add_parser("stats")
|
||||
return p.parse_args(argv)
|
||||
|
||||
|
||||
async def run(args: argparse.Namespace) -> int:
|
||||
settings = Settings.from_env(s3_credentials=False)
|
||||
db = Database(settings, name="messenger-jobctl")
|
||||
await db.open()
|
||||
try:
|
||||
writes = args.command in ("replay", "reprocess")
|
||||
result = await db.run(lambda c: COMMANDS[args.command](c, args, settings), deadline=10)
|
||||
print(json.dumps(result, ensure_ascii=False, indent=1, default=str))
|
||||
return 0 if not writes or result.get("result") == "queued" else 1
|
||||
except Refused as exc:
|
||||
print(json.dumps({"result": "refused", "reason": str(exc)}))
|
||||
return EXIT_REFUSED
|
||||
except Unavailable:
|
||||
print(json.dumps({"result": "error", "reason": "database_unavailable"}))
|
||||
return 1
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = arguments(argv)
|
||||
try:
|
||||
return asyncio.run(run(args))
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,428 @@
|
||||
"""State machine of attachment jobs in PostgreSQL (lab 5). Every transition is ONE transaction.
|
||||
|
||||
Lock order, everywhere both rows are locked: the jobs row FIRST, then the attachments row
|
||||
(claim, complete, retry, lease expiry). Replay/reprocess/cleanup lock only the attachments row
|
||||
and insert NEW job rows. So two transitions never wait on each other in opposite order.
|
||||
|
||||
Fencing: a claim gives the attempt a fresh random `lease_token`. Every later write of that attempt
|
||||
(heartbeat, result, retry) is conditional on `jobs.lease_token = <its token>` under the jobs row
|
||||
lock. When the lease expires, the reaper clears the token; from then on the old attempt - even if
|
||||
its process is still alive (paused, slow) - can neither publish nor schedule anything, and the
|
||||
objects it wrote under its own keys are garbage for the cleanup.
|
||||
|
||||
Monotonic publication: a result of pipeline version V is published only if V is greater than the
|
||||
published version of the attachment; otherwise the job ends as `superseded` and nothing visible
|
||||
changes. `ready` never goes back to queued/processing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import random
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
|
||||
import psycopg
|
||||
|
||||
from . import telemetry
|
||||
from .pipeline import VARIANT_NAMES
|
||||
from .storage import attempt_key
|
||||
|
||||
ACTIVE = ("queued", "processing")
|
||||
|
||||
|
||||
def backoff_delay(attempt: int, base: float, cap: float, rnd=random.random) -> float:
|
||||
"""Full jitter (AWS Architecture Blog, "Exponential Backoff And Jitter"): uniform in
|
||||
[0, min(cap, base * 2^(attempt-1))]. Spreads the retries of many jobs that failed together."""
|
||||
return rnd() * min(cap, base * (2 ** max(0, attempt - 1)))
|
||||
|
||||
|
||||
async def event(conn: psycopg.AsyncConnection, job_id, name: str, actor: str, *, attempt: int | None = None,
|
||||
error_code: str | None = None, **detail) -> None:
|
||||
await conn.execute(
|
||||
"INSERT INTO job_events (job_id, event, attempt, actor, error_code, detail) VALUES (%s, %s, %s, %s, %s, %s)",
|
||||
(job_id, name, attempt, actor, error_code, json.dumps(detail, default=str)))
|
||||
|
||||
|
||||
async def create_job(conn: psycopg.AsyncConnection, attachment_id, pipeline_version: int, kind: str,
|
||||
max_attempts: int, actor: str, *, replay_of=None, **detail) -> uuid.UUID:
|
||||
"""jobs row + its first outbox row + audit, in the CALLER's transaction.
|
||||
Lab 6: the current W3C trace context (the upload request) is stored with the job: every
|
||||
message of this job is published as a child of it (migrations/0006_observability.sql)."""
|
||||
job_id = uuid.uuid4()
|
||||
carrier = telemetry.inject()
|
||||
await conn.execute(
|
||||
"INSERT INTO jobs (id, attachment_id, pipeline_version, kind, replay_of, max_attempts, traceparent, tracestate) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(job_id, attachment_id, pipeline_version, kind, replay_of, max_attempts,
|
||||
carrier.get("traceparent"), carrier.get("tracestate")))
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, 1)", (job_id,))
|
||||
await event(conn, job_id, "created", actor, kind=kind, pipeline_version=pipeline_version,
|
||||
replay_of=str(replay_of) if replay_of else None, **detail)
|
||||
return job_id
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ relay
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Due:
|
||||
outbox_id: int
|
||||
job_id: str
|
||||
attachment_id: str
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
created_at: dt.datetime
|
||||
job_state: str
|
||||
traceparent: str | None = None
|
||||
tracestate: str | None = None
|
||||
kind: str = "upload"
|
||||
|
||||
|
||||
async def due_outbox(conn: psycopg.AsyncConnection, batch: int) -> list[Due]:
|
||||
"""Due, unpublished outbox rows, locked for this relay pass (SKIP LOCKED: several relays
|
||||
never publish the same row at the same time - a crash may still publish it twice)."""
|
||||
cur = await conn.execute(
|
||||
"SELECT o.id, o.job_id, j.attachment_id, j.pipeline_version, o.attempt, j.created_at, j.state, "
|
||||
"j.traceparent, j.tracestate, j.kind "
|
||||
"FROM outbox o JOIN jobs j ON j.id = o.job_id "
|
||||
"WHERE o.published_at IS NULL AND o.available_at <= clock_timestamp() "
|
||||
"ORDER BY o.available_at, o.id LIMIT %s FOR UPDATE OF o SKIP LOCKED", (batch,))
|
||||
return [Due(r[0], str(r[1]), str(r[2]), r[3], r[4], r[5], r[6], r[7], r[8], r[9]) for r in await cur.fetchall()]
|
||||
|
||||
|
||||
async def mark_published(conn: psycopg.AsyncConnection, ids: list[int]) -> None:
|
||||
if ids:
|
||||
await conn.execute("UPDATE outbox SET published_at = clock_timestamp() WHERE id = ANY(%s)", (ids,))
|
||||
|
||||
|
||||
async def count_publish_failure(conn: psycopg.AsyncConnection, ids: list[int]) -> None:
|
||||
if ids:
|
||||
await conn.execute("UPDATE outbox SET publish_failures = publish_failures + 1 WHERE id = ANY(%s)", (ids,))
|
||||
|
||||
|
||||
async def expire_leases(conn: psycopg.AsyncConnection, actor: str, limit: int = 50) -> int:
|
||||
"""Reaper: processing jobs whose lease ran out (the worker died, hung or lost its database).
|
||||
The attempt is abandoned; the job goes back to queued with a new outbox row, or to failed
|
||||
`retry_exhausted` when it used all its attempts."""
|
||||
cur = await conn.execute(
|
||||
"SELECT id, attempt, max_attempts, lease_token, attachment_id FROM jobs "
|
||||
"WHERE state = 'processing' AND lease_until < clock_timestamp() "
|
||||
"ORDER BY lease_until LIMIT %s FOR UPDATE SKIP LOCKED", (limit,))
|
||||
rows = await cur.fetchall()
|
||||
for job_id, attempt, max_attempts, token, attachment_id in rows:
|
||||
await conn.execute(
|
||||
"UPDATE job_attempts SET outcome = 'abandoned', error_code = 'lease_expired', finished_at = clock_timestamp() "
|
||||
"WHERE token = %s AND outcome = 'running'", (token,))
|
||||
if attempt >= max_attempts:
|
||||
await _fail(conn, job_id, attachment_id, "retry_exhausted", actor, attempt, cause="lease_expired")
|
||||
else:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
|
||||
"available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (job_id,))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() "
|
||||
"WHERE id = %s AND status = 'processing'", (attachment_id,))
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1))
|
||||
await event(conn, job_id, "lease_expired", actor, attempt=attempt)
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def republish_stale(conn: psycopg.AsyncConnection, older_than: float, actor: str, limit: int = 50) -> int:
|
||||
"""Lost-message guard: a queued, due job that has had no unpublished outbox row and no
|
||||
publish for `older_than` seconds gets a new outbox row (its message was lost by the broker,
|
||||
dead-lettered after too many redeliveries, or the queue was purged)."""
|
||||
cur = await conn.execute(
|
||||
"SELECT j.id, j.attempt FROM jobs j "
|
||||
"WHERE j.state = 'queued' AND j.available_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"AND j.updated_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.job_id = j.id AND (o.published_at IS NULL "
|
||||
" OR o.published_at > clock_timestamp() - make_interval(secs => %s))) "
|
||||
"ORDER BY j.updated_at LIMIT %s FOR UPDATE OF j SKIP LOCKED", (older_than, older_than, older_than, limit))
|
||||
rows = await cur.fetchall()
|
||||
for job_id, attempt in rows:
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (job_id, attempt + 1))
|
||||
await event(conn, job_id, "republished", actor, attempt=attempt)
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def queue_stats(conn: psycopg.AsyncConnection) -> dict:
|
||||
"""Backlog for the gauges (relay, every few seconds): two aggregates over partial indexes."""
|
||||
cur = await conn.execute(
|
||||
"SELECT count(*) FILTER (WHERE state = 'queued'), count(*) FILTER (WHERE state = 'processing'), "
|
||||
"COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(created_at)), 0)::float8 "
|
||||
"FROM jobs WHERE state IN ('queued', 'processing')")
|
||||
queued, processing, oldest = await cur.fetchone()
|
||||
cur = await conn.execute(
|
||||
"SELECT count(*) FILTER (WHERE available_at <= clock_timestamp()), "
|
||||
"count(*) FILTER (WHERE available_at > clock_timestamp()), "
|
||||
"COALESCE(EXTRACT(EPOCH FROM clock_timestamp() - min(available_at) "
|
||||
" FILTER (WHERE available_at <= clock_timestamp())), 0)::float8 "
|
||||
"FROM outbox WHERE published_at IS NULL")
|
||||
due, delayed, outbox_age = await cur.fetchone()
|
||||
return {"queued": queued, "processing": processing, "oldest_age": float(oldest),
|
||||
"outbox_due": due, "outbox_delayed": delayed, "outbox_oldest_due_age": float(outbox_age)}
|
||||
|
||||
|
||||
async def purge_outbox(conn: psycopg.AsyncConnection, keep_seconds: int = 7 * 86400) -> int:
|
||||
cur = await conn.execute(
|
||||
"DELETE FROM outbox WHERE id IN (SELECT id FROM outbox WHERE published_at < clock_timestamp() "
|
||||
"- make_interval(secs => %s) LIMIT 1000)", (keep_seconds,))
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ worker
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Claim:
|
||||
job_id: str
|
||||
attachment_id: str
|
||||
pipeline_version: int
|
||||
attempt: int
|
||||
max_attempts: int
|
||||
token: str
|
||||
source: str # staging | original
|
||||
source_key: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: bytes
|
||||
write_original: bool # the original is not published yet: this attempt publishes it too
|
||||
kind: str = "upload" # upload | replay | reprocess | migrate
|
||||
accepted_at: dt.datetime | None = None # jobs.created_at = the durable acceptance (202) of an upload
|
||||
|
||||
def key(self, name: str) -> str:
|
||||
return attempt_key(self.attachment_id, self.token, name)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Noop:
|
||||
reason: str # finished | leased | not_due | superseded | unknown_job
|
||||
|
||||
|
||||
async def claim(conn: psycopg.AsyncConnection, job_id: str, worker: str, lease_seconds: float) -> Claim | Noop:
|
||||
cur = await conn.execute(
|
||||
"SELECT state, attempt, max_attempts, available_at > clock_timestamp(), attachment_id, pipeline_version, "
|
||||
"kind, created_at FROM jobs WHERE id = %s FOR UPDATE", (job_id,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return Noop("unknown_job")
|
||||
state, attempt, max_attempts, not_due, attachment_id, version, kind, accepted_at = row
|
||||
if state not in ACTIVE:
|
||||
return Noop("finished") # duplicate/redelivery of a finished job: ack, nothing else
|
||||
if state == "processing":
|
||||
return Noop("leased") # another attempt holds the lease; the reaper handles its death
|
||||
if not_due:
|
||||
return Noop("not_due") # backoff not over: the outbox publishes it at available_at
|
||||
cur = await conn.execute(
|
||||
"SELECT status, published_version, object_key, staging_key, staging_state, content_type, size_bytes, sha256 "
|
||||
"FROM attachments WHERE id = %s FOR UPDATE", (attachment_id,))
|
||||
status, published, object_key, staging_key, staging_state, content_type, size, sha = await cur.fetchone()
|
||||
actor = "worker:" + worker
|
||||
if published is not None and published >= version:
|
||||
# A newer (or the same) version is already published: this job can only be stale.
|
||||
await _finish(conn, job_id, "superseded", None)
|
||||
await event(conn, job_id, "superseded", actor, attempt=attempt, published_version=published)
|
||||
return Noop("superseded")
|
||||
if object_key is not None:
|
||||
source, source_key = "original", object_key
|
||||
elif staging_state == "present":
|
||||
source, source_key = "staging", staging_key
|
||||
else:
|
||||
# Cannot happen while the CHECK attachments_active_has_source holds; fail visibly anyway.
|
||||
await _fail(conn, job_id, attachment_id, "source_missing", actor, attempt)
|
||||
return Noop("finished")
|
||||
token = uuid.uuid4().hex
|
||||
attempt += 1
|
||||
write_original = object_key is None
|
||||
names = (("original",) if write_original else ()) + VARIANT_NAMES
|
||||
planned = [attempt_key(str(attachment_id), token, n) for n in names]
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'processing', attempt = %s, lease_token = %s, lease_owner = %s, "
|
||||
"lease_until = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s",
|
||||
(attempt, token, worker, lease_seconds, job_id))
|
||||
await conn.execute(
|
||||
"INSERT INTO job_attempts (token, job_id, attempt, worker, source, planned_keys) VALUES (%s, %s, %s, %s, %s, %s)",
|
||||
(token, job_id, attempt, worker, source, planned))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = clock_timestamp() WHERE id = %s AND status = 'queued'",
|
||||
(attachment_id,))
|
||||
await event(conn, job_id, "claimed", actor, attempt=attempt, source=source, token=token)
|
||||
return Claim(str(job_id), str(attachment_id), version, attempt, max_attempts, token, source, source_key,
|
||||
content_type, size, bytes(sha), write_original, kind, accepted_at)
|
||||
|
||||
|
||||
async def heartbeat(conn: psycopg.AsyncConnection, claim: Claim, lease_seconds: float) -> bool:
|
||||
"""Extend the lease; False = the lease was lost (expired and taken over): stop the attempt."""
|
||||
cur = await conn.execute(
|
||||
"UPDATE jobs SET lease_until = clock_timestamp() + make_interval(secs => %s) "
|
||||
"WHERE id = %s AND state = 'processing' AND lease_token = %s", (lease_seconds, claim.job_id, claim.token))
|
||||
return cur.rowcount == 1
|
||||
|
||||
|
||||
async def _holds_lease(conn: psycopg.AsyncConnection, claim: Claim) -> bool:
|
||||
cur = await conn.execute("SELECT state = 'processing' AND lease_token = %s FROM jobs WHERE id = %s FOR UPDATE",
|
||||
(claim.token, claim.job_id))
|
||||
row = await cur.fetchone()
|
||||
return bool(row and row[0])
|
||||
|
||||
|
||||
async def complete(conn: psycopg.AsyncConnection, claim: Claim, variants, worker: str) -> str:
|
||||
"""Publish the result of an attempt atomically: variant rows + attachment ready + job succeeded.
|
||||
Returns succeeded | superseded | fenced (this attempt lost its lease: nothing written)."""
|
||||
actor = "worker:" + worker
|
||||
if not await _holds_lease(conn, claim):
|
||||
return "fenced"
|
||||
cur = await conn.execute("SELECT published_version FROM attachments WHERE id = %s FOR UPDATE", (claim.attachment_id,))
|
||||
(published,) = await cur.fetchone()
|
||||
if published is not None and published >= claim.pipeline_version:
|
||||
await _end_attempt(conn, claim, "superseded", None)
|
||||
await _finish(conn, claim.job_id, "superseded", None)
|
||||
await event(conn, claim.job_id, "superseded", actor, attempt=claim.attempt, published_version=published)
|
||||
return "superseded"
|
||||
for v in variants:
|
||||
await conn.execute(
|
||||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, "
|
||||
"size_bytes, width, height, sha256, attempt_token) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
(claim.attachment_id, claim.pipeline_version, v.name, claim.key(v.name), v.content_type, len(v.data),
|
||||
v.width, v.height, v.sha256, claim.token))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'ready', published_version = %s, error_code = NULL, failed_at = NULL, "
|
||||
"object_key = COALESCE(object_key, %s), updated_at = clock_timestamp() WHERE id = %s",
|
||||
(claim.pipeline_version, claim.key("original") if claim.write_original else None, claim.attachment_id))
|
||||
await _end_attempt(conn, claim, "succeeded", None)
|
||||
await _finish(conn, claim.job_id, "succeeded", None)
|
||||
await event(conn, claim.job_id, "succeeded", actor, attempt=claim.attempt, pipeline_version=claim.pipeline_version)
|
||||
return "succeeded"
|
||||
|
||||
|
||||
async def retry_or_fail(conn: psycopg.AsyncConnection, claim: Claim, code: str, permanent: bool, worker: str,
|
||||
base: float, cap: float) -> tuple[str, float]:
|
||||
"""After a failed attempt: permanent error or no attempts left -> failed (failed registry);
|
||||
otherwise queued again after a jittered backoff. Returns (outcome, delay seconds)."""
|
||||
actor = "worker:" + worker
|
||||
if not await _holds_lease(conn, claim):
|
||||
return "fenced", 0.0
|
||||
if permanent or claim.attempt >= claim.max_attempts:
|
||||
final = code if permanent else "retry_exhausted"
|
||||
await _end_attempt(conn, claim, "failed", code)
|
||||
await _fail(conn, claim.job_id, claim.attachment_id, final, actor, claim.attempt, cause=code)
|
||||
return "failed", 0.0
|
||||
delay = backoff_delay(claim.attempt, base, cap)
|
||||
await _end_attempt(conn, claim, "retry", code)
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, error_code = %s, "
|
||||
"available_at = clock_timestamp() + make_interval(secs => %s), updated_at = clock_timestamp() WHERE id = %s",
|
||||
(code, delay, claim.job_id))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'",
|
||||
(claim.attachment_id,))
|
||||
await conn.execute(
|
||||
"INSERT INTO outbox (job_id, attempt, available_at) "
|
||||
"VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s))", (claim.job_id, claim.attempt + 1, delay))
|
||||
await event(conn, claim.job_id, "retry_scheduled", actor, attempt=claim.attempt, error_code=code,
|
||||
delay_s=round(delay, 3))
|
||||
return "retry", delay
|
||||
|
||||
|
||||
async def release(conn: psycopg.AsyncConnection, claim: Claim, worker: str) -> str:
|
||||
"""Graceful stop of a worker with an attempt still running: give the job back at once
|
||||
(without waiting for the lease to expire). The claim already counted as an attempt."""
|
||||
if not await _holds_lease(conn, claim):
|
||||
return "fenced"
|
||||
await _end_attempt(conn, claim, "abandoned", "worker_shutdown")
|
||||
if claim.attempt >= claim.max_attempts:
|
||||
await _fail(conn, claim.job_id, claim.attachment_id, "retry_exhausted", "worker:" + worker, claim.attempt,
|
||||
cause="worker_shutdown")
|
||||
return "failed"
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = 'queued', lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
|
||||
"available_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (claim.job_id,))
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = clock_timestamp() WHERE id = %s AND status = 'processing'",
|
||||
(claim.attachment_id,))
|
||||
await conn.execute("INSERT INTO outbox (job_id, attempt) VALUES (%s, %s)", (claim.job_id, claim.attempt + 1))
|
||||
await event(conn, claim.job_id, "released", "worker:" + worker, attempt=claim.attempt)
|
||||
return "released"
|
||||
|
||||
|
||||
async def _end_attempt(conn: psycopg.AsyncConnection, claim: Claim, outcome: str, code: str | None) -> None:
|
||||
await conn.execute(
|
||||
"UPDATE job_attempts SET outcome = %s, error_code = %s, finished_at = clock_timestamp() "
|
||||
"WHERE token = %s AND outcome = 'running'", (outcome, code, claim.token))
|
||||
|
||||
|
||||
async def _finish(conn: psycopg.AsyncConnection, job_id, state: str, code: str | None) -> None:
|
||||
await conn.execute(
|
||||
"UPDATE jobs SET state = %s, error_code = %s, lease_token = NULL, lease_owner = NULL, lease_until = NULL, "
|
||||
"finished_at = clock_timestamp(), updated_at = clock_timestamp() WHERE id = %s", (state, code, job_id))
|
||||
|
||||
|
||||
async def _fail(conn: psycopg.AsyncConnection, job_id, attachment_id, code: str, actor: str, attempt: int,
|
||||
**detail) -> None:
|
||||
"""Job -> failed (registry). The attachment becomes failed only if it is not ready: a failed
|
||||
reprocess of a newer version leaves the published result in place."""
|
||||
await _finish(conn, job_id, "failed", code)
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = %s, failed_at = clock_timestamp(), "
|
||||
"updated_at = clock_timestamp() WHERE id = %s AND status IN ('queued', 'processing')", (code, attachment_id))
|
||||
await event(conn, job_id, "failed", actor, attempt=attempt, error_code=code, **detail)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ cleanup (worker)
|
||||
async def staging_to_delete(conn: psycopg.AsyncConnection, retention_seconds: int, limit: int = 50) -> list[str]:
|
||||
"""Candidates only (no lock): ready attachments (staging no longer needed) and failed ones
|
||||
older than the retention. The decision is re-checked under the row lock in mark_staging_deleting."""
|
||||
cur = await conn.execute(
|
||||
"SELECT id FROM attachments WHERE staging_state IN ('present', 'deleting') AND (status = 'ready' OR "
|
||||
"(status = 'failed' AND failed_at < clock_timestamp() - make_interval(secs => %s))) "
|
||||
"ORDER BY updated_at LIMIT %s", (retention_seconds, limit))
|
||||
return [str(r[0]) for r in await cur.fetchall()]
|
||||
|
||||
|
||||
async def mark_staging_deleting(conn: psycopg.AsyncConnection, attachment_id: str, retention_seconds: int) -> str | None:
|
||||
"""Under the attachment row lock, decide AGAIN from the committed state and mark the staging copy
|
||||
`deleting` BEFORE the S3 DELETE. A replay that committed in between made the row queued, so it
|
||||
no longer matches; a replay that comes later sees `deleting` and refuses. Queued/processing
|
||||
rows never match (and the CHECK attachments_active_has_source forbids it anyway)."""
|
||||
cur = await conn.execute(
|
||||
"UPDATE attachments SET staging_state = 'deleting' " # internal state: updated_at stays (public field)
|
||||
"WHERE id = %s AND staging_state IN ('present', 'deleting') AND (status = 'ready' OR (status = 'failed' "
|
||||
"AND failed_at < clock_timestamp() - make_interval(secs => %s) AND NOT EXISTS (SELECT 1 FROM jobs j "
|
||||
"WHERE j.attachment_id = attachments.id AND j.state IN ('queued', 'processing')))) RETURNING staging_key",
|
||||
(attachment_id, retention_seconds))
|
||||
row = await cur.fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
async def mark_staging_deleted(conn: psycopg.AsyncConnection, attachment_id: str) -> None:
|
||||
await conn.execute(
|
||||
"UPDATE attachments SET staging_state = 'deleted' WHERE id = %s AND staging_state = 'deleting'", (attachment_id,))
|
||||
|
||||
|
||||
async def attempts_to_clean(conn: psycopg.AsyncConnection, grace_seconds: int, limit: int = 50) -> list[str]:
|
||||
cur = await conn.execute(
|
||||
"SELECT token FROM job_attempts WHERE outcome IN ('retry', 'failed', 'abandoned', 'superseded') "
|
||||
"AND objects_cleaned_at IS NULL AND finished_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"ORDER BY finished_at LIMIT %s", (grace_seconds, limit))
|
||||
return [r[0].hex for r in await cur.fetchall()]
|
||||
|
||||
|
||||
async def lock_attempt_for_cleanup(conn: psycopg.AsyncConnection, token: str) -> list[str] | None:
|
||||
"""Keys of an attempt that can never publish: it ended without success, it is not the lease
|
||||
holder of its job (tokens are never reused) and nothing published references its keys."""
|
||||
cur = await conn.execute(
|
||||
"SELECT ja.planned_keys FROM job_attempts ja JOIN jobs j ON j.id = ja.job_id "
|
||||
"WHERE ja.token = %s AND ja.objects_cleaned_at IS NULL "
|
||||
"AND ja.outcome IN ('retry', 'failed', 'abandoned', 'superseded') "
|
||||
"AND j.lease_token IS DISTINCT FROM ja.token FOR UPDATE OF ja", (token,))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
keys = list(row[0])
|
||||
cur = await conn.execute(
|
||||
"SELECT EXISTS (SELECT 1 FROM attachment_variants WHERE object_key = ANY(%s)) "
|
||||
"OR EXISTS (SELECT 1 FROM attachments WHERE object_key = ANY(%s))", (keys, keys))
|
||||
if (await cur.fetchone())[0]:
|
||||
return None # published: never delete (would be a bug elsewhere; logged by the caller)
|
||||
return keys
|
||||
|
||||
|
||||
async def mark_attempt_cleaned(conn: psycopg.AsyncConnection, token: str) -> None:
|
||||
await conn.execute("UPDATE job_attempts SET objects_cleaned_at = clock_timestamp() WHERE token = %s", (token,))
|
||||
@@ -0,0 +1,44 @@
|
||||
"""JSON-lines logging to stdout. Logs never contain message texts or request bodies.
|
||||
|
||||
Lab 6: every line written inside an active span carries its trace_id/span_id (the same ids the
|
||||
OTLP copy of the record has in Loki), so `docker compose logs` can be joined with Tempo too."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from . import telemetry
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
entry = {
|
||||
"ts": dt.datetime.fromtimestamp(record.created, dt.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||
"level": record.levelname.lower(),
|
||||
"logger": record.name,
|
||||
"event": record.getMessage(),
|
||||
}
|
||||
ids = telemetry.current_ids()
|
||||
if ids:
|
||||
entry["trace_id"], entry["span_id"] = ids
|
||||
fields = getattr(record, "fields", None)
|
||||
if fields:
|
||||
entry.update(fields)
|
||||
if record.exc_info:
|
||||
# Stack traces go only to the server log, never to the HTTP client.
|
||||
entry["exception"] = self.formatException(record.exc_info)
|
||||
return json.dumps(entry, ensure_ascii=False)
|
||||
|
||||
|
||||
def configure(level: str) -> None:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
root = logging.getLogger()
|
||||
root.handlers[:] = [handler]
|
||||
root.setLevel(level.upper())
|
||||
# uvicorn's own access log is disabled; our middleware writes one line per request.
|
||||
for name in ("uvicorn", "uvicorn.error"):
|
||||
logging.getLogger(name).handlers[:] = []
|
||||
logging.getLogger(name).propagate = True
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Versioned SQL migrations: `python -m messenger.migrate` (compose service `migrate`).
|
||||
|
||||
* Files `migrations/NNNN_name.sql` are applied in name order, each in its own
|
||||
transaction together with its row in `schema_migrations` (DDL is transactional
|
||||
in PostgreSQL, so a failed migration leaves nothing behind).
|
||||
* Re-running is safe: applied versions are skipped, so data is never duplicated.
|
||||
* The SHA-256 of every applied file is stored; if an applied file was edited later,
|
||||
the run stops instead of silently diverging from the real schema.
|
||||
* `pg_advisory_lock` serialises concurrent runs (two API replicas starting at once).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from .config import ConfigError, _secret
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations"
|
||||
LOCK_ID = 2026_02 # arbitrary application-wide advisory lock id
|
||||
|
||||
|
||||
def say(text: str) -> None:
|
||||
print(f"migrate: {text}", flush=True)
|
||||
|
||||
|
||||
def connect(url: str, wait_seconds: float = 60) -> psycopg.Connection:
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
while True:
|
||||
try:
|
||||
return psycopg.connect(url, autocommit=True, connect_timeout=3, application_name="messenger-migrate")
|
||||
except psycopg.OperationalError as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise SystemExit(f"migrate: database is not reachable: {type(exc).__name__}") from None
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
url = _secret("DATABASE_URL", required=True)
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
files = sorted(MIGRATIONS_DIR.glob("*.sql"))
|
||||
with connect(url) as conn:
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (LOCK_ID,))
|
||||
try:
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
" version text PRIMARY KEY, checksum text NOT NULL,"
|
||||
" applied_at timestamptz NOT NULL DEFAULT now())")
|
||||
applied = dict(conn.execute("SELECT version, checksum FROM schema_migrations").fetchall())
|
||||
for path in files:
|
||||
version, sql = path.stem, path.read_bytes()
|
||||
checksum = hashlib.sha256(sql).hexdigest()
|
||||
if version in applied:
|
||||
if applied[version] != checksum:
|
||||
say(f"{version}: file changed after it was applied; create a new migration instead")
|
||||
return 1
|
||||
say(f"{version}: already applied, skipped")
|
||||
continue
|
||||
with conn.transaction():
|
||||
conn.execute(sql.decode("utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", (version, checksum))
|
||||
say(f"{version}: applied")
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (LOCK_ID,))
|
||||
say(f"done, {len(files)} migration file(s) checked")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Password hashing with Argon2id (memory-hard password KDF; also mandatory in lab 7).
|
||||
|
||||
* Parameters follow the OWASP minimum for Argon2id: m=19 MiB, t=2, p=1. Unlike bcrypt
|
||||
there is no 72-byte limit, so any 12-128 code point UTF-8 password is hashed whole.
|
||||
* Hashing takes tens of milliseconds of CPU and 19 MiB of RAM. It runs in a worker
|
||||
thread (argon2-cffi releases the GIL), so the event loop keeps serving other
|
||||
requests, and a semaphore caps parallel hashes (memory/CPU DoS protection).
|
||||
* An unknown username is checked against a dummy hash, so "no such user" and
|
||||
"wrong password" take the same time and return the same 401.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
|
||||
_hasher = PasswordHasher(time_cost=2, memory_cost=19 * 1024, parallelism=1, hash_len=32, salt_len=16)
|
||||
_semaphore: asyncio.Semaphore | None = None
|
||||
_dummy_hash: str | None = None
|
||||
|
||||
|
||||
def configure(concurrency: int) -> None:
|
||||
global _semaphore
|
||||
_semaphore = asyncio.Semaphore(concurrency)
|
||||
|
||||
|
||||
async def _run(func, *args):
|
||||
if _semaphore is None:
|
||||
configure(2)
|
||||
async with _semaphore:
|
||||
return await asyncio.to_thread(func, *args)
|
||||
|
||||
|
||||
async def hash_password(password: str) -> str:
|
||||
return await _run(_hasher.hash, password)
|
||||
|
||||
|
||||
def _verify(stored_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return _hasher.verify(stored_hash, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
async def verify_password(stored_hash: str | None, password: str) -> bool:
|
||||
global _dummy_hash
|
||||
if stored_hash is None:
|
||||
if _dummy_hash is None:
|
||||
_dummy_hash = await hash_password("dummy-password-for-timing")
|
||||
await _run(_verify, _dummy_hash, password)
|
||||
return False
|
||||
return await _run(_verify, stored_hash, password)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Versioned image pipeline (lab 5): WHAT the worker builds for one attachment. Pure definitions,
|
||||
no I/O; the pixels are produced by imaging.py in a child process.
|
||||
|
||||
Every pipeline version builds the same three variants with the geometry of the contract; versions
|
||||
differ only in encoder parameters, so the published version is visible in the bytes (sha256):
|
||||
|
||||
thumbnail JPEG, fits into 256x256, keeps the aspect ratio, never upscales, floor rounding
|
||||
(minimum 1 px), EXIF orientation applied, alpha composited onto white;
|
||||
crop JPEG, centred square 128x128 (small images ARE upscaled, the contract allows it);
|
||||
optimized WebP, fits into 1280x1280, never upscales, alpha kept.
|
||||
|
||||
Metadata: nothing of the source is copied into a variant - no EXIF (orientation is applied to
|
||||
the pixels instead), no XMP, no ICC profile, no comments (the pixels are treated as sRGB).
|
||||
The original is published byte for byte and keeps everything.
|
||||
|
||||
Track 2: the version of a job is fixed when the job is created (PIPELINE_VERSION for uploads,
|
||||
`jobctl reprocess --pipeline N` later). A result is published only if its version is greater
|
||||
than the published one, so an old job can never overwrite a newer result.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
THUMBNAIL_BOX = 256
|
||||
CROP_SIDE = 128
|
||||
OPTIMIZED_BOX = 1280
|
||||
VARIANT_NAMES = ("thumbnail", "crop", "optimized")
|
||||
CONTENT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Pipeline:
|
||||
version: int
|
||||
jpeg_quality: int # thumbnail and crop: baseline JPEG, 4:2:0, optimized Huffman tables
|
||||
webp_quality: int # optimized: lossy WebP
|
||||
webp_method: int # 0 (fast) .. 6 (slow, smaller)
|
||||
|
||||
|
||||
PIPELINES = {
|
||||
1: Pipeline(1, jpeg_quality=85, webp_quality=80, webp_method=4),
|
||||
# Versions 2 and 3 exist for the track 2 experiments (reprocess, reorder, stale jobs):
|
||||
# different encoder settings -> different bytes, identical geometry.
|
||||
2: Pipeline(2, jpeg_quality=80, webp_quality=75, webp_method=4),
|
||||
3: Pipeline(3, jpeg_quality=90, webp_quality=85, webp_method=5),
|
||||
}
|
||||
|
||||
|
||||
def fit(width: int, height: int, box: int) -> tuple[int, int]:
|
||||
"""Size inside box x box keeping the aspect ratio, never upscaling, rounded DOWN, >= 1 px.
|
||||
Integer arithmetic: 320x200 -> 256x160 exactly, 1x1000 -> 1x256 (0.256 -> 1 px minimum)."""
|
||||
if width <= box and height <= box:
|
||||
return width, height
|
||||
if width >= height:
|
||||
return box, max(1, height * box // width)
|
||||
return max(1, width * box // height), box
|
||||
|
||||
|
||||
def center_square(width: int, height: int) -> tuple[int, int, int, int]:
|
||||
"""Crop box (left, top, right, bottom) of the centred square with side min(width, height)."""
|
||||
side = min(width, height)
|
||||
left = (width - side) // 2
|
||||
top = (height - side) // 2
|
||||
return left, top, left + side, top + side
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Outbox relay: `python -m messenger.relay` (compose service `relay`, one process).
|
||||
|
||||
loop: SELECT due outbox rows FOR UPDATE SKIP LOCKED
|
||||
-> publish each job message to RabbitMQ, wait for the publisher CONFIRM
|
||||
-> UPDATE outbox SET published_at -> COMMIT
|
||||
every few seconds: reaper (expired leases -> queued/failed), lost-message guard.
|
||||
|
||||
Why an outbox: the API commits the job and the outbox row in ONE PostgreSQL transaction and never
|
||||
talks to the broker. A crash between COMMIT and publish leaves the row unpublished; the relay
|
||||
publishes it when it (or the broker) is back - nobody re-creates a job by hand. While the broker
|
||||
is down, uploads still get 202 and the rows wait in the outbox.
|
||||
|
||||
A crash after the confirm but before the COMMIT of published_at publishes the row once more after
|
||||
the restart: the queue then holds a duplicate. That is at-least-once delivery; the worker turns
|
||||
the duplicate into a no-op (jobs.claim). The relay never deletes or rewrites jobs.
|
||||
|
||||
Lab 6: every publish is a PRODUCER span `messenger.jobs publish` (publish + wait for the confirm),
|
||||
child of the trace context stored with the job (the upload request). The producer's context goes
|
||||
into the message body (`traceparent`/`tracestate`, contracts/jobs.schema.json) and the AMQP
|
||||
headers. The relay is also the source of the queue gauges: every MAINTENANCE_SECONDS it counts
|
||||
unfinished jobs and due outbox rows in PostgreSQL (the source of truth of the backlog, including
|
||||
jobs waiting for a retry, which the broker queue does not hold).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractExchange
|
||||
|
||||
from . import __version__, broker, jobs, logging_setup, service, telemetry
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
|
||||
log = logging.getLogger("messenger.relay")
|
||||
ACTOR = "relay"
|
||||
MAINTENANCE_SECONDS = 5.0
|
||||
PURGE_SECONDS = 600.0
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.db = Database(settings, name="messenger-relay")
|
||||
self.connection: AbstractConnection | None = None
|
||||
self.channel: AbstractChannel | None = None
|
||||
self.exchange: AbstractExchange | None = None
|
||||
self.lost: asyncio.Event | None = None
|
||||
self.queue_stats: dict | None = None # last jobs.queue_stats (None: unknown -> no data points)
|
||||
|
||||
def connected(self) -> bool:
|
||||
return (self.connection is not None and self.lost is not None and not self.lost.is_set()
|
||||
and self.channel is not None and not self.channel.is_closed)
|
||||
|
||||
async def connect(self) -> None:
|
||||
self.connection = await aio_pika.connect(
|
||||
self.settings.broker_url, timeout=5,
|
||||
client_properties={"connection_name": "relay@" + self.settings.instance_id})
|
||||
self.lost = service.watch_connection(self.connection)
|
||||
# Confirm mode: every publish() waits for basic.ack of the broker (message in the quorum log).
|
||||
self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True)
|
||||
# No declare: the topology belongs to the broker definitions; the relay may only write.
|
||||
self.exchange = await self.channel.get_exchange(broker.EXCHANGE, ensure=False)
|
||||
log.info("broker_connected", extra={"fields": {"exchange": broker.EXCHANGE}})
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self.connection is not None:
|
||||
try:
|
||||
await self.connection.close()
|
||||
except Exception: # noqa: BLE001 - already broken
|
||||
pass
|
||||
self.connection = self.channel = self.exchange = self.lost = None
|
||||
|
||||
async def publish_due(self) -> int:
|
||||
settings = self.settings
|
||||
exchange = self.exchange
|
||||
|
||||
async def work(conn) -> list[jobs.Due]:
|
||||
rows = await jobs.due_outbox(conn, settings.relay_batch)
|
||||
if "reverse_order" in settings.fault_points:
|
||||
rows.reverse()
|
||||
# Rows of jobs that are no longer queued (finished meanwhile) need no message.
|
||||
sendable = [r for r in rows if r.job_state == "queued"]
|
||||
copies = 2 if "duplicate_publish" in settings.fault_points else 1
|
||||
for row in sendable:
|
||||
with telemetry.TRACER.start_as_current_span(
|
||||
f"{broker.EXCHANGE} publish", kind=telemetry.SpanKind.PRODUCER,
|
||||
context=telemetry.extract(row.traceparent, row.tracestate),
|
||||
record_exception=False, set_status_on_exception=False,
|
||||
attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "send",
|
||||
"messaging.operation.name": "publish",
|
||||
"messaging.destination.name": broker.EXCHANGE,
|
||||
"messaging.rabbitmq.destination.routing_key": broker.ROUTING_KEY,
|
||||
"messaging.message.id": f"{row.job_id}:{row.outbox_id}",
|
||||
"messenger.job.id": row.job_id, "messenger.job.attempt": row.attempt,
|
||||
"messenger.job.kind": row.kind}) as span:
|
||||
carrier = telemetry.inject() # = this producer span
|
||||
message = aio_pika.Message(
|
||||
broker.encode(row.job_id, row.attachment_id, row.pipeline_version, row.attempt,
|
||||
row.created_at, carrier),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT, content_type="application/json",
|
||||
message_id=f"{row.job_id}:{row.outbox_id}", type=broker.JOB_TYPE, headers=dict(carrier))
|
||||
try:
|
||||
for _ in range(copies):
|
||||
await exchange.publish(message, routing_key=broker.ROUTING_KEY, mandatory=True, timeout=5)
|
||||
except BaseException as exc:
|
||||
telemetry.mark_error(span, type(exc).__name__)
|
||||
raise
|
||||
for row in sendable:
|
||||
# Confirmed by the broker, outbox not marked yet: the window "after publish, before
|
||||
# the confirm is recorded". The crash rolls this transaction back.
|
||||
await service.crash_once(settings, self.db, "crash_after_publish", row.job_id, ACTOR,
|
||||
outbox_id=row.outbox_id)
|
||||
await jobs.mark_published(conn, [r.outbox_id for r in rows])
|
||||
return sendable
|
||||
|
||||
sent = await self.db.run(work, deadline=10 + 5 * settings.relay_batch)
|
||||
for row in sent:
|
||||
log.info("job_published", extra={"fields": {"job_id": row.job_id, "attempt": row.attempt,
|
||||
"outbox_id": row.outbox_id}})
|
||||
return len(sent)
|
||||
|
||||
async def maintenance(self) -> None:
|
||||
try:
|
||||
self.queue_stats = await self.db.run(jobs.queue_stats, op="queue_stats")
|
||||
except Unavailable:
|
||||
self.queue_stats = None # unknown backlog: the gauges report nothing (not a stale value)
|
||||
raise
|
||||
expired = await self.db.run(lambda c: jobs.expire_leases(c, ACTOR))
|
||||
republished = await self.db.run(lambda c: jobs.republish_stale(c, self.settings.queued_republish_seconds, ACTOR))
|
||||
if expired or republished:
|
||||
log.info("maintenance", extra={"fields": {"leases_expired": expired, "republished": republished}})
|
||||
|
||||
def register_metrics(self) -> None:
|
||||
queue = {"messaging.destination.name": broker.QUEUE}
|
||||
|
||||
def depth():
|
||||
st = self.queue_stats
|
||||
return [] if st is None else [(st["queued"], {**queue, "state": "queued"}),
|
||||
(st["processing"], {**queue, "state": "processing"})]
|
||||
|
||||
def oldest():
|
||||
st = self.queue_stats
|
||||
return [] if st is None else [(st["oldest_age"], queue)]
|
||||
|
||||
def outbox():
|
||||
st = self.queue_stats
|
||||
return [] if st is None else [(st["outbox_due"], {"state": "due"}),
|
||||
(st["outbox_delayed"], {"state": "delayed"})]
|
||||
|
||||
def outbox_age():
|
||||
st = self.queue_stats
|
||||
return [] if st is None else [(st["outbox_oldest_due_age"], {})]
|
||||
|
||||
telemetry.observe("messenger.queue.depth", "{job}",
|
||||
"Unfinished jobs (PostgreSQL) by state: queued (incl. waiting for a retry) / processing", depth)
|
||||
telemetry.observe("messenger.queue.oldest_age", "s",
|
||||
"Age of the oldest unfinished job: now - its durable acceptance (jobs.created_at)", oldest)
|
||||
telemetry.observe("messenger.outbox.pending", "{message}",
|
||||
"Unpublished outbox rows: due now / delayed (retry backoff)", outbox)
|
||||
telemetry.observe("messenger.outbox.oldest_age", "s",
|
||||
"How long the oldest DUE outbox row waits for its publish (broker down -> grows)", outbox_age)
|
||||
telemetry.observe_pool(self.db.pool, self.db.name)
|
||||
|
||||
async def run(self) -> int:
|
||||
stop = service.stop_event()
|
||||
self.register_metrics()
|
||||
await self.db.open()
|
||||
next_maintenance = next_purge = 0.0
|
||||
failures = 0
|
||||
try:
|
||||
while not stop.is_set():
|
||||
healthy = True
|
||||
now = time.monotonic()
|
||||
try:
|
||||
if now >= next_maintenance:
|
||||
await self.maintenance()
|
||||
next_maintenance = now + MAINTENANCE_SECONDS
|
||||
if now >= next_purge:
|
||||
purged = await self.db.run(jobs.purge_outbox)
|
||||
next_purge = now + PURGE_SECONDS
|
||||
if purged:
|
||||
log.info("outbox_purged", extra={"fields": {"rows": purged}})
|
||||
except Unavailable:
|
||||
healthy = False
|
||||
try:
|
||||
if not self.connected():
|
||||
await self.disconnect()
|
||||
await self.connect()
|
||||
sent = await self.publish_due()
|
||||
failures = 0
|
||||
except Unavailable:
|
||||
healthy, sent = False, 0
|
||||
except Exception as exc: # noqa: BLE001 - every broker/channel error, never a crash
|
||||
# Broker down/unreachable, channel closed, message returned/nacked: nothing marked,
|
||||
# the rows stay in the outbox (transaction rolled back) and are published later.
|
||||
failures += 1
|
||||
healthy, sent = False, 0
|
||||
log.warning("publish_failed", extra={"fields": {"error": type(exc).__name__, "failures": failures}})
|
||||
await self.disconnect()
|
||||
if healthy:
|
||||
service.beat()
|
||||
if not sent:
|
||||
await service.sleep_or_stop(stop, min(5.0, self.settings.relay_poll_seconds * (2 ** min(failures, 3))))
|
||||
finally:
|
||||
await self.disconnect()
|
||||
await self.db.close()
|
||||
log.info("relay_stopped")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
settings = Settings.from_env(s3_credentials=False)
|
||||
if not settings.broker_url:
|
||||
raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set")
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
logging_setup.configure(settings.log_level)
|
||||
telemetry.setup("messenger-relay", settings.instance_id, __version__)
|
||||
log.info("relay_starting", extra={"fields": {"instance_id": settings.instance_id,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
try:
|
||||
return asyncio.run(Relay(settings).run())
|
||||
finally:
|
||||
telemetry.shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,373 @@
|
||||
"""SQL for users, chats and messages. All statements are parameterised (%s placeholders):
|
||||
values travel separately from the SQL text, so input can never change the query.
|
||||
|
||||
Free text is stored as UTF-8 BYTEA (PostgreSQL TEXT cannot hold U+0000), so it is
|
||||
encoded on the way in and decoded on the way out. See docs/DATA_MODEL.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
|
||||
from .cursor import SortKey
|
||||
from .db import Database
|
||||
from .errors import Conflict, InvalidRequest, NotFound, Unavailable
|
||||
from .timefmt import from_us, rfc3339, to_us
|
||||
|
||||
|
||||
def _b(text: str) -> bytes:
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
def _s(raw: bytes | memoryview) -> str:
|
||||
return bytes(raw).decode("utf-8")
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class User:
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: dt.datetime
|
||||
|
||||
def to_json(self) -> dict:
|
||||
return {"id": self.id, "username": self.username, "display_name": self.display_name,
|
||||
"created_at": rfc3339(self.created_at)}
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class Chat:
|
||||
id: str
|
||||
title: str
|
||||
member_ids: tuple[str, ...]
|
||||
created_at: dt.datetime
|
||||
|
||||
@property
|
||||
def key(self) -> SortKey:
|
||||
return (to_us(self.created_at), self.id)
|
||||
|
||||
def to_json(self) -> dict:
|
||||
return {"id": self.id, "title": self.title, "member_ids": list(self.member_ids),
|
||||
"created_at": rfc3339(self.created_at)}
|
||||
|
||||
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class Message:
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: dt.datetime
|
||||
attachment_ids: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def key(self) -> SortKey:
|
||||
return (to_us(self.created_at), self.id)
|
||||
|
||||
def to_json(self) -> dict:
|
||||
return {"id": self.id, "chat_id": self.chat_id, "sender_id": self.sender_id, "text": self.text,
|
||||
"created_at": rfc3339(self.created_at), "attachment_ids": list(self.attachment_ids)}
|
||||
|
||||
|
||||
def _user(row) -> User:
|
||||
return User(str(row[0]), row[1], _s(row[2]), row[3])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ users
|
||||
async def create_user(db: Database, username: str, display_name: str, password_hash: str) -> User:
|
||||
async def work(conn: psycopg.AsyncConnection) -> User:
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) "
|
||||
"RETURNING id, username, display_name, created_at",
|
||||
(uuid.uuid4(), username, _b(display_name), password_hash))
|
||||
return _user(await cur.fetchone())
|
||||
try:
|
||||
return await db.run(work)
|
||||
except pg_errors.UniqueViolation:
|
||||
# Two concurrent registrations: the unique index lets exactly one INSERT commit.
|
||||
raise Conflict("Имя пользователя уже занято") from None
|
||||
|
||||
|
||||
async def get_user(db: Database, user_id: str) -> User | None:
|
||||
async def work(conn: psycopg.AsyncConnection) -> User | None:
|
||||
cur = await conn.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s", (user_id,))
|
||||
row = await cur.fetchone()
|
||||
return _user(row) if row else None
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
async def get_credentials(db: Database, username: str) -> tuple[User, str] | None:
|
||||
async def work(conn: psycopg.AsyncConnection) -> tuple[User, str] | None:
|
||||
cur = await conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,))
|
||||
row = await cur.fetchone()
|
||||
return (_user(row), row[4]) if row else None
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ chats
|
||||
async def create_chat(db: Database, creator_id: str, title: str, member_ids: list[str]) -> Chat:
|
||||
"""Atomic: the chat row and all memberships commit together or not at all.
|
||||
|
||||
The chat is inserted FIRST; an unknown member then fails the membership INSERT
|
||||
with a foreign-key violation and the whole transaction (chat row included) is
|
||||
rolled back. student-tests check that nothing is left behind.
|
||||
"""
|
||||
if creator_id not in member_ids:
|
||||
raise InvalidRequest("member_ids должен включать текущего пользователя")
|
||||
chat_id = uuid.uuid4()
|
||||
|
||||
async def work(conn: psycopg.AsyncConnection) -> dt.datetime:
|
||||
cur = await conn.execute(
|
||||
"INSERT INTO chats (id, title, created_by) VALUES (%s, %s, %s) RETURNING created_at",
|
||||
(chat_id, _b(title), creator_id))
|
||||
(created_at,) = await cur.fetchone()
|
||||
await conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) "
|
||||
"SELECT %s, m.user_id, m.ord - 1, %s "
|
||||
"FROM unnest(%s::uuid[]) WITH ORDINALITY AS m(user_id, ord)",
|
||||
(chat_id, created_at, member_ids))
|
||||
return created_at
|
||||
try:
|
||||
created_at = await db.run(work)
|
||||
except pg_errors.ForeignKeyViolation:
|
||||
raise InvalidRequest("member_ids содержит несуществующих пользователей") from None
|
||||
return Chat(str(chat_id), title, tuple(member_ids), created_at)
|
||||
|
||||
|
||||
async def _load_chats(conn: psycopg.AsyncConnection, rows) -> list[Chat]:
|
||||
if not rows:
|
||||
return []
|
||||
ids = [r[0] for r in rows]
|
||||
cur = await conn.execute(
|
||||
"SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY(%s) ORDER BY chat_id, position", (ids,))
|
||||
members: dict[uuid.UUID, list[str]] = {i: [] for i in ids}
|
||||
for chat_id, user_id in await cur.fetchall():
|
||||
members[chat_id].append(str(user_id))
|
||||
return [Chat(str(r[0]), _s(r[1]), tuple(members[r[0]]), r[2]) for r in rows]
|
||||
|
||||
|
||||
async def get_chat(db: Database, user_id: str, chat_id: str) -> Chat:
|
||||
"""The chat if the user is a member; a missing chat and a foreign chat are both 404."""
|
||||
async def work(conn: psycopg.AsyncConnection) -> Chat:
|
||||
cur = await conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c "
|
||||
"JOIN chat_members m ON m.chat_id = c.id AND m.user_id = %s WHERE c.id = %s",
|
||||
(user_id, chat_id))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise NotFound("Чат не найден")
|
||||
return (await _load_chats(conn, [row]))[0]
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
async def _check_member(conn: psycopg.AsyncConnection, user_id: str, chat_id: str) -> None:
|
||||
cur = await conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user_id))
|
||||
if await cur.fetchone() is None:
|
||||
raise NotFound("Чат не найден")
|
||||
|
||||
|
||||
async def ensure_member(db: Database, user_id: str, chat_id: str) -> None:
|
||||
async def work(conn: psycopg.AsyncConnection) -> None:
|
||||
await _check_member(conn, user_id, chat_id)
|
||||
await db.run(work)
|
||||
|
||||
|
||||
async def list_chats(db: Database, user_id: str, after: SortKey | None, limit: int) -> tuple[list[Chat], bool]:
|
||||
async def work(conn: psycopg.AsyncConnection) -> tuple[list[Chat], bool]:
|
||||
if after is None:
|
||||
cur = await conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chat_members m JOIN chats c ON c.id = m.chat_id "
|
||||
"WHERE m.user_id = %s ORDER BY m.chat_created_at, m.chat_id LIMIT %s",
|
||||
(user_id, limit + 1))
|
||||
else:
|
||||
cur = await conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at FROM chat_members m JOIN chats c ON c.id = m.chat_id "
|
||||
"WHERE m.user_id = %s AND (m.chat_created_at, m.chat_id) > (%s, %s) "
|
||||
"ORDER BY m.chat_created_at, m.chat_id LIMIT %s",
|
||||
(user_id, from_us(after[0]), after[1], limit + 1))
|
||||
rows = await cur.fetchall()
|
||||
return await _load_chats(conn, rows[:limit]), len(rows) > limit
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ messages
|
||||
@dataclass(slots=True, frozen=True)
|
||||
class PostResult:
|
||||
message: Message
|
||||
replayed: bool # True: the key was already used with this body, nothing new was written
|
||||
|
||||
|
||||
async def _insert_message(conn: psycopg.AsyncConnection, message_id: uuid.UUID, user_id: str, chat_id: str,
|
||||
text: str, attachment_ids: list[str]) -> dt.datetime:
|
||||
"""Insert with a per-chat strictly increasing timestamp.
|
||||
|
||||
`UPDATE chats ... RETURNING` locks the chat row until COMMIT, so writers of one
|
||||
chat are serialised: a message with a smaller created_at can never commit after
|
||||
a message with a bigger one, and a reader paging by cursor cannot skip it.
|
||||
"""
|
||||
cur = await conn.execute(
|
||||
"UPDATE chats SET last_message_at = greatest(clock_timestamp(), "
|
||||
"last_message_at + interval '1 microsecond') WHERE id = %s RETURNING last_message_at",
|
||||
(chat_id,))
|
||||
(created_at,) = await cur.fetchone()
|
||||
await conn.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at, attachment_ids) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s::uuid[])",
|
||||
(message_id, chat_id, user_id, _b(text), created_at, attachment_ids))
|
||||
if attachment_ids:
|
||||
await conn.execute(
|
||||
"INSERT INTO message_attachments (message_id, position, attachment_id) "
|
||||
"SELECT %s, a.ord - 1, a.id FROM unnest(%s::uuid[]) WITH ORDINALITY AS a(id, ord)",
|
||||
(message_id, attachment_ids))
|
||||
return created_at
|
||||
|
||||
|
||||
# Attachments a message may reference (lab 5): of THIS chat and not the invisible 'pending' intent
|
||||
# (else 404); queued/processing/ready are usable, failed or quarantined -> 409.
|
||||
# FOR SHARE keeps a concurrent transition to failed from slipping in before COMMIT.
|
||||
CHECK_ATTACHMENTS = (
|
||||
"SELECT count(*), count(*) FILTER (WHERE a.lost_at IS NULL AND a.status <> 'failed') FROM ("
|
||||
"SELECT lost_at, status FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status <> 'pending' "
|
||||
"FOR SHARE) a")
|
||||
|
||||
|
||||
async def _check_attachments(conn: psycopg.AsyncConnection, chat_id: str, attachment_ids: list[str]) -> str:
|
||||
if not attachment_ids:
|
||||
return "ok"
|
||||
cur = await conn.execute(CHECK_ATTACHMENTS, (attachment_ids, chat_id))
|
||||
found, usable = await cur.fetchone()
|
||||
if found != len(attachment_ids):
|
||||
return "attachment_not_found"
|
||||
return "ok" if usable == found else "attachment_conflict"
|
||||
|
||||
|
||||
def _attachment_error(status: str) -> None:
|
||||
if status == "attachment_not_found":
|
||||
raise NotFound("Вложение не найдено")
|
||||
if status == "attachment_conflict":
|
||||
raise Conflict("Вложение недоступно и не может быть прикреплено")
|
||||
|
||||
|
||||
# Claim the key. A row of a concurrent transaction that is not committed yet makes this
|
||||
# INSERT wait on the unique index until that transaction ends: after COMMIT it is a conflict
|
||||
# (the key is taken), after ROLLBACK the INSERT goes through. A key older than the TTL is
|
||||
# re-used as if it were new (ON CONFLICT ... DO UPDATE ... WHERE expired).
|
||||
CLAIM_KEY = (
|
||||
"INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id) "
|
||||
"VALUES (%s, %s, %s, %s, %s) "
|
||||
"ON CONFLICT (user_id, chat_id, key) DO UPDATE SET "
|
||||
"request_hash = EXCLUDED.request_hash, message_id = EXCLUDED.message_id, created_at = clock_timestamp() "
|
||||
"WHERE idempotency_keys.created_at < clock_timestamp() - make_interval(secs => %s) "
|
||||
"RETURNING 1")
|
||||
STORED_RESULT = (
|
||||
"SELECT k.request_hash, m.id, m.text, m.created_at, m.attachment_ids FROM idempotency_keys k "
|
||||
"JOIN messages m ON m.id = k.message_id "
|
||||
"WHERE k.user_id = %s AND k.chat_id = %s AND k.key = %s")
|
||||
|
||||
|
||||
async def post_message(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes, text: str,
|
||||
ttl_seconds: int, attachment_ids: list[str] = ()) -> PostResult:
|
||||
"""Idempotent send: the key, the message and the stored result commit in ONE transaction.
|
||||
|
||||
* first request -> key row + message + chat clock, all or nothing (no "pending" key is
|
||||
ever left behind: a crash or 5xx rolls everything back and the client may retry);
|
||||
* same key, same body (any replica, also concurrently) -> the stored Message, 201, replayed;
|
||||
* same key, other body -> 409; the membership check comes first, so outsiders always get 404;
|
||||
* attachments (lab 4) are checked before the key is claimed (same order as post_message_v3).
|
||||
"""
|
||||
message_id = uuid.uuid4()
|
||||
attachment_ids = list(attachment_ids)
|
||||
|
||||
async def work(conn: psycopg.AsyncConnection) -> PostResult:
|
||||
await _check_member(conn, user_id, chat_id)
|
||||
check = await _check_attachments(conn, chat_id, attachment_ids)
|
||||
if check == "ok":
|
||||
cur = await conn.execute(CLAIM_KEY, (user_id, chat_id, key, request_hash, message_id, ttl_seconds))
|
||||
if await cur.fetchone() is not None:
|
||||
created_at = await _insert_message(conn, message_id, user_id, chat_id, text, attachment_ids)
|
||||
return PostResult(Message(str(message_id), chat_id, user_id, text, created_at,
|
||||
tuple(attachment_ids)), False)
|
||||
cur = await conn.execute(STORED_RESULT, (user_id, chat_id, key))
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
_attachment_error(check)
|
||||
# The key row vanished between the two statements (expired-key cleanup): retryable.
|
||||
raise Unavailable("Повторите запрос с тем же Idempotency-Key")
|
||||
if bytes(row[0]) != request_hash:
|
||||
raise Conflict("Idempotency-Key уже использован с другим сообщением")
|
||||
return PostResult(Message(str(row[1]), chat_id, user_id, _s(row[2]), row[3],
|
||||
tuple(str(a) for a in row[4])), True)
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
POST_MESSAGE_CALL = ("SELECT o_status, o_id, o_text, o_created_at, o_attachments "
|
||||
"FROM post_message_v3(%s, %s, %s, %s, %s, %s, %s, %s::uuid[])")
|
||||
|
||||
|
||||
async def post_message_single_call(db: Database, user_id: str, chat_id: str, key: str, request_hash: bytes,
|
||||
text: str, ttl_seconds: int, attachment_ids: list[str] = ()) -> PostResult:
|
||||
"""Same contract as post_message, ONE round trip: SQL function post_message_v3 (migration 0005 =
|
||||
0003 + attachment_ids) in autocommit mode, i.e. the call is the whole transaction."""
|
||||
message_id = uuid.uuid4()
|
||||
|
||||
async def work(conn: psycopg.AsyncConnection) -> tuple:
|
||||
cur = await conn.execute(POST_MESSAGE_CALL, (user_id, chat_id, key, request_hash, message_id, _b(text),
|
||||
ttl_seconds, list(attachment_ids)))
|
||||
return await cur.fetchone()
|
||||
status, stored_id, stored_text, created_at, stored_attachments = await db.run(work, transaction=False)
|
||||
if status == "not_found":
|
||||
raise NotFound("Чат не найден")
|
||||
_attachment_error(status)
|
||||
if status == "conflict":
|
||||
raise Conflict("Idempotency-Key уже использован с другим сообщением")
|
||||
if status == "retry":
|
||||
raise Unavailable("Повторите запрос с тем же Idempotency-Key")
|
||||
return PostResult(Message(str(stored_id), chat_id, user_id, _s(stored_text), created_at,
|
||||
tuple(str(a) for a in stored_attachments)), status == "replayed")
|
||||
|
||||
|
||||
async def purge_idempotency_keys(db: Database, ttl_seconds: int, batch: int = 5000) -> int:
|
||||
"""Delete expired keys in bounded batches; one replica at a time (advisory xact lock)."""
|
||||
async def work(conn: psycopg.AsyncConnection) -> int:
|
||||
cur = await conn.execute("SELECT pg_try_advisory_xact_lock(%s)", (2026_03,))
|
||||
if not (await cur.fetchone())[0]:
|
||||
return 0
|
||||
cur = await conn.execute(
|
||||
"DELETE FROM idempotency_keys WHERE ctid = ANY(ARRAY("
|
||||
"SELECT ctid FROM idempotency_keys "
|
||||
"WHERE created_at < clock_timestamp() - make_interval(secs => %s) LIMIT %s))",
|
||||
(ttl_seconds, batch))
|
||||
return cur.rowcount
|
||||
return await db.run(work)
|
||||
|
||||
|
||||
# Two statements instead of one with "(%s IS NULL OR ...)": with a generic plan the OR
|
||||
# would push the cursor into a Filter and late pages would scan the whole prefix.
|
||||
# attachment_ids is a column of the message row (migration 0004): still one index range scan.
|
||||
HISTORY_FIRST = (
|
||||
"SELECT id, sender_id, text, created_at, attachment_ids FROM messages "
|
||||
"WHERE chat_id = %s ORDER BY created_at, id LIMIT %s")
|
||||
HISTORY_AFTER = (
|
||||
"SELECT id, sender_id, text, created_at, attachment_ids FROM messages "
|
||||
"WHERE chat_id = %s AND (created_at, id) > (%s, %s) ORDER BY created_at, id LIMIT %s")
|
||||
|
||||
|
||||
async def list_messages(db: Database, chat_id: str, after: SortKey | None, limit: int) -> tuple[list[Message], bool]:
|
||||
async def work(conn: psycopg.AsyncConnection) -> list:
|
||||
if after is None:
|
||||
cur = await conn.execute(HISTORY_FIRST, (chat_id, limit + 1))
|
||||
else:
|
||||
cur = await conn.execute(HISTORY_AFTER, (chat_id, from_us(after[0]), after[1], limit + 1))
|
||||
return await cur.fetchall()
|
||||
rows = await db.run(work)
|
||||
items = [Message(str(r[0]), chat_id, str(r[1]), _s(r[2]), r[3], tuple(str(a) for a in r[4]))
|
||||
for r in rows[:limit]]
|
||||
return items, len(rows) > limit
|
||||
@@ -0,0 +1,182 @@
|
||||
"""One-shot S3 bootstrap: `python -m messenger.s3_bootstrap` (compose service `s3-init`).
|
||||
|
||||
Idempotent, safe to run on every `docker compose up`:
|
||||
|
||||
1. waits until the S3 endpoint answers;
|
||||
2. creates the final bucket (S3_BUCKET) and the staging bucket (S3_STAGING_BUCKET) with the ADMIN
|
||||
key pair if they do not exist yet (existing buckets and their objects are left untouched);
|
||||
3. writes the sentinel object `health/sentinel` into the final bucket (the API readiness HEADs it);
|
||||
4. proves the access model and FAILS the stand (exit 1) if it is wrong:
|
||||
* anonymous (unsigned) GET of an object and anonymous LIST are refused on both buckets;
|
||||
* api: writes staging, reads final; cannot read staging, write final, list or create buckets,
|
||||
nor read another bucket (a canary bucket created here for this check);
|
||||
* worker: reads and writes both buckets; cannot list or create buckets;
|
||||
* auditor: reads and lists both buckets; cannot write.
|
||||
Only file names and verdicts are printed, never key values.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from .config import ConfigError, Settings, _secret, s3_settings
|
||||
from .errors import Unavailable
|
||||
from .storage import SENTINEL_KEY, Storage
|
||||
|
||||
|
||||
def say(text: str) -> None:
|
||||
print(f"s3-bootstrap: {text}", flush=True)
|
||||
|
||||
|
||||
def anonymous_status(url: str) -> int:
|
||||
"""HTTP status of an UNSIGNED request (what anyone on the network could do)."""
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=3) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
async def error_code(coro) -> str:
|
||||
"""S3 error code of a call that is expected to be refused ('' if it succeeded)."""
|
||||
try:
|
||||
await coro
|
||||
return ""
|
||||
except ClientError as exc:
|
||||
return str(exc.response.get("Error", {}).get("Code", "error"))
|
||||
|
||||
|
||||
def settings_with(keys: tuple[str, str]) -> Settings:
|
||||
base = s3_settings(credentials_required=False)
|
||||
base.update(s3_access_key_id=keys[0], s3_secret_access_key=keys[1])
|
||||
return Settings(host="", port=0, env="lab", log_level="info", shutdown_timeout=0, max_body_bytes=1024, **base)
|
||||
|
||||
|
||||
def pair(prefix: str) -> tuple[str, str]:
|
||||
return _secret(f"{prefix}ACCESS_KEY_ID", True), _secret(f"{prefix}SECRET_ACCESS_KEY", True)
|
||||
|
||||
|
||||
async def ensure_bucket(admin_s3: Storage, bucket: str) -> bool:
|
||||
code = await error_code(admin_s3.client.head_bucket(Bucket=bucket))
|
||||
if code == "":
|
||||
say(f"bucket {bucket}: exists, kept as is")
|
||||
return True
|
||||
if code in ("404", "NoSuchBucket", "NotFound"):
|
||||
code = await error_code(admin_s3.client.create_bucket(Bucket=bucket))
|
||||
if code not in ("", "BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
say(f"bucket {bucket}: create failed ({code})")
|
||||
return False
|
||||
say(f"bucket {bucket}: created")
|
||||
return True
|
||||
say(f"bucket {bucket}: head failed ({code})")
|
||||
return False
|
||||
|
||||
|
||||
async def run() -> int:
|
||||
settings = settings_with(pair("S3_ADMIN_"))
|
||||
final, staging = settings.s3_bucket, settings.s3_staging_bucket
|
||||
admin_s3 = Storage(settings)
|
||||
clients = {"api": Storage(settings_with(pair("S3_"))), "worker": Storage(settings_with(pair("S3_WORKER_"))),
|
||||
"auditor": Storage(settings_with(pair("S3_AUDITOR_")))}
|
||||
for s in (admin_s3, *clients.values()):
|
||||
await s.open()
|
||||
try:
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
await admin_s3._call("list_buckets", admin_s3.client.list_buckets())
|
||||
break
|
||||
except Unavailable:
|
||||
if time.monotonic() > deadline:
|
||||
say("S3 endpoint does not answer within 60 s")
|
||||
return 1
|
||||
await asyncio.sleep(1)
|
||||
for bucket in (final, staging):
|
||||
if not await ensure_bucket(admin_s3, bucket):
|
||||
return 1
|
||||
await admin_s3.put(SENTINEL_KEY, b"ok\n", "text/plain", {})
|
||||
await admin_s3.client.put_object(Bucket=staging, Key=SENTINEL_KEY, Body=b"ok\n")
|
||||
say(f"sentinel {SENTINEL_KEY}: written")
|
||||
canary = final + "-canary"
|
||||
if await error_code(admin_s3.client.head_bucket(Bucket=canary)):
|
||||
await admin_s3.client.create_bucket(Bucket=canary)
|
||||
await admin_s3.client.put_object(Bucket=canary, Key="canary", Body=b"secret of another bucket")
|
||||
|
||||
failures = []
|
||||
base = settings.s3_endpoint.rstrip("/")
|
||||
for bucket in (final, staging):
|
||||
for what, url in ((f"anonymous GET object of {bucket}", f"{base}/{bucket}/{SENTINEL_KEY}"),
|
||||
(f"anonymous LIST of {bucket}", f"{base}/{bucket}?list-type=2")):
|
||||
status = anonymous_status(url)
|
||||
verdict = "refused" if status in (401, 403) else "ALLOWED"
|
||||
say(f"{what}: HTTP {status} -> {verdict}")
|
||||
if verdict != "refused":
|
||||
failures.append(what)
|
||||
|
||||
probe = "health/bootstrap-probe"
|
||||
|
||||
def c(who: str):
|
||||
return clients[who].client
|
||||
|
||||
# (what, coroutine, allowed?) - every refusal must be a real AccessDenied, not an outage.
|
||||
checks = [
|
||||
("api: write staging", c("api").put_object(Bucket=staging, Key=probe, Body=b"p"), True),
|
||||
("api: delete staging (janitor)", c("api").delete_object(Bucket=staging, Key=probe), True),
|
||||
("api: read staging", c("api").head_object(Bucket=staging, Key=SENTINEL_KEY), False),
|
||||
("api: read final", c("api").head_object(Bucket=final, Key=SENTINEL_KEY), True),
|
||||
("api: write final", c("api").put_object(Bucket=final, Key=probe, Body=b"p"), False),
|
||||
("api: list final", c("api").list_objects_v2(Bucket=final, MaxKeys=1), False),
|
||||
("api: list staging", c("api").list_objects_v2(Bucket=staging, MaxKeys=1), False),
|
||||
("api: create bucket", c("api").create_bucket(Bucket=final + "-x"), False),
|
||||
("api: read another bucket", c("api").head_object(Bucket=canary, Key="canary"), False),
|
||||
("worker: read staging", c("worker").head_object(Bucket=staging, Key=SENTINEL_KEY), True),
|
||||
("worker: write final", c("worker").put_object(Bucket=final, Key=probe, Body=b"p"), True),
|
||||
("worker: delete final", c("worker").delete_object(Bucket=final, Key=probe), True),
|
||||
("worker: write staging", c("worker").put_object(Bucket=staging, Key=probe, Body=b"p"), True),
|
||||
("worker: delete staging", c("worker").delete_object(Bucket=staging, Key=probe), True),
|
||||
("worker: list final", c("worker").list_objects_v2(Bucket=final, MaxKeys=1), False),
|
||||
("worker: create bucket", c("worker").create_bucket(Bucket=final + "-x"), False),
|
||||
("worker: read another bucket", c("worker").head_object(Bucket=canary, Key="canary"), False),
|
||||
("auditor: list final", c("auditor").list_objects_v2(Bucket=final, MaxKeys=1), True),
|
||||
("auditor: list staging", c("auditor").list_objects_v2(Bucket=staging, MaxKeys=1), True),
|
||||
("auditor: read final", c("auditor").head_object(Bucket=final, Key=SENTINEL_KEY), True),
|
||||
("auditor: write final", c("auditor").put_object(Bucket=final, Key=probe, Body=b"p"), False),
|
||||
("auditor: delete staging", c("auditor").delete_object(Bucket=staging, Key=SENTINEL_KEY), False),
|
||||
]
|
||||
for what, coro, allowed in checks:
|
||||
code = await error_code(coro)
|
||||
ok = (code == "") == allowed and code in ("", "AccessDenied", "403")
|
||||
say(f"{what}: {'allowed' if code == '' else 'refused (' + code + ')'} -> {'OK' if ok else 'WRONG'}")
|
||||
if not ok:
|
||||
failures.append(what)
|
||||
visible = [b["Name"] for b in (await c("api").list_buckets()).get("Buckets", [])]
|
||||
say(f"api: buckets visible in ListBuckets: {visible} -> {'OK' if canary not in visible else 'WRONG'}")
|
||||
if canary in visible:
|
||||
failures.append("api sees another bucket")
|
||||
if failures:
|
||||
say("access model is WRONG: " + ", ".join(failures))
|
||||
return 1
|
||||
say("done: private buckets, least-privilege keys verified")
|
||||
return 0
|
||||
finally:
|
||||
for s in (admin_s3, *clients.values()):
|
||||
await s.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
return asyncio.run(run())
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ.setdefault("PYTHONUNBUFFERED", "1")
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Common runtime of the background processes (relay, worker): signals, heartbeat file for the
|
||||
Docker healthcheck, failure injection that fires once per job and leaves an audit row."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from . import jobs
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
|
||||
log = logging.getLogger("messenger.service")
|
||||
|
||||
HEARTBEAT_FILE = Path(os.environ.get("HEARTBEAT_FILE", "/tmp/heartbeat"))
|
||||
CRASH_EXIT_CODE = 70 # os._exit: no cleanup, no ack, no COMMIT - like SIGKILL in the middle of work
|
||||
|
||||
|
||||
def beat() -> None:
|
||||
"""Healthcheck input: `python -m messenger.healthcheck --file /tmp/heartbeat --max-age 30`."""
|
||||
try:
|
||||
HEARTBEAT_FILE.write_text(str(time.time()), encoding="ascii")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def watch_connection(connection) -> asyncio.Event:
|
||||
"""Event set when an AMQP connection is closed by ANY side. aio-pika's `is_closed` does not turn
|
||||
True when the broker drops the connection (found by the broker-restart test: the worker kept
|
||||
"running" without a consumer), so the close callback is the signal to reconnect."""
|
||||
lost = asyncio.Event()
|
||||
connection.close_callbacks.add(lambda *_: lost.set())
|
||||
return lost
|
||||
|
||||
|
||||
def stop_event() -> asyncio.Event:
|
||||
stop = asyncio.Event()
|
||||
loop = asyncio.get_running_loop()
|
||||
for sig in (signal.SIGTERM, signal.SIGINT):
|
||||
try:
|
||||
loop.add_signal_handler(sig, stop.set)
|
||||
except (NotImplementedError, RuntimeError):
|
||||
pass # Windows unit tests: no signal handlers
|
||||
return stop
|
||||
|
||||
|
||||
async def sleep_or_stop(stop: asyncio.Event, seconds: float) -> None:
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), seconds)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
|
||||
async def crash_once(settings: Settings, db: Database, point: str, job_id: str, actor: str, **detail) -> None:
|
||||
"""Experiments only (FAULT_POINTS): kill THIS process at `point`, once per job (and per `detail`),
|
||||
across restarts and replicas. The decision is an audit row committed before the crash, so the
|
||||
restarted process (or another replica) continues normally and the evidence stays in job_events."""
|
||||
if point not in settings.fault_points:
|
||||
return
|
||||
|
||||
async def record(conn) -> bool:
|
||||
cur = await conn.execute(
|
||||
"SELECT 1 FROM job_events WHERE job_id = %s AND event = 'fault_injected' AND detail->>'point' = %s "
|
||||
"AND detail @> %s::jsonb", (job_id, point, jobs.json.dumps({k: str(v) for k, v in detail.items()})))
|
||||
if await cur.fetchone():
|
||||
return False
|
||||
await jobs.event(conn, job_id, "fault_injected", actor, point=point, **{k: str(v) for k, v in detail.items()})
|
||||
return True
|
||||
|
||||
if await db.run(record):
|
||||
log.warning("fault_injected_crash", extra={"fields": {"point": point, "job_id": job_id, **detail}})
|
||||
logging.shutdown()
|
||||
os._exit(CRASH_EXIT_CODE)
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Server-side sessions behind an opaque Bearer token.
|
||||
|
||||
* Token: `secrets.token_urlsafe(32)` = 256 random bits. Only SHA-256(token) is
|
||||
stored, so a leaked database/AOF does not contain usable tokens. A fast hash is
|
||||
enough for a 256-bit random value; passwords need a slow KDF (passwords.py).
|
||||
* Expiry is absolute: `expires_at = login time + SESSION_TTL_SECONDS`. Every lookup
|
||||
compares it with the current time, and a restart never extends it.
|
||||
|
||||
Two interchangeable stores (SESSION_STORE):
|
||||
|
||||
* `valkey` (compose default): the ONLY copy of a session is a Valkey key with
|
||||
`PXAT expires_at`, persisted by AOF with `appendfsync always`. There is no second
|
||||
copy (no cache over PostgreSQL), so a logout cannot be "forgotten" and a revoked
|
||||
token cannot come back after Valkey fails and recovers. If Valkey is unreachable
|
||||
a session cannot be checked: protected requests and logout get 503, never access.
|
||||
* `postgres`: table `sessions` (migrations/0001_init.sql).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from typing import Protocol
|
||||
|
||||
from redis import exceptions as redis_errors
|
||||
from redis.asyncio import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.retry import Retry
|
||||
|
||||
from .config import Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .timefmt import UTC, from_us, to_us
|
||||
|
||||
log = logging.getLogger("messenger.sessions")
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token: str) -> bytes:
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def now() -> dt.datetime:
|
||||
return dt.datetime.now(UTC)
|
||||
|
||||
|
||||
class SessionStore(Protocol):
|
||||
name: str
|
||||
|
||||
async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]: ...
|
||||
async def user_id_for(self, token: str) -> str | None: ...
|
||||
async def revoke(self, token: str) -> bool: ...
|
||||
async def ping(self) -> bool: ...
|
||||
async def close(self) -> None: ...
|
||||
|
||||
|
||||
class PostgresSessionStore:
|
||||
name = "postgres"
|
||||
|
||||
def __init__(self, db: Database):
|
||||
self.db = db
|
||||
|
||||
async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]:
|
||||
token = new_token()
|
||||
expires_at = now() + dt.timedelta(seconds=ttl_seconds)
|
||||
|
||||
async def work(conn) -> None:
|
||||
await conn.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(token_hash(token), user_id, expires_at))
|
||||
# Housekeeping: drop this user's expired sessions (bounded by the user's own rows).
|
||||
await conn.execute("DELETE FROM sessions WHERE user_id = %s AND expires_at <= %s", (user_id, now()))
|
||||
await self.db.run(work)
|
||||
return token, expires_at
|
||||
|
||||
async def user_id_for(self, token: str) -> str | None:
|
||||
async def work(conn):
|
||||
cur = await conn.execute(
|
||||
"SELECT user_id FROM sessions WHERE token_hash = %s AND expires_at > %s", (token_hash(token), now()))
|
||||
return await cur.fetchone()
|
||||
row = await self.db.run(work)
|
||||
return str(row[0]) if row else None
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
async def work(conn) -> bool:
|
||||
cur = await conn.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = %s AND expires_at > %s", (token_hash(token), now()))
|
||||
return cur.rowcount == 1
|
||||
return await self.db.run(work)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
return True # covered by the database readiness check
|
||||
|
||||
async def close(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class ValkeySessionStore:
|
||||
name = "valkey"
|
||||
PREFIX = "session:"
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.timeout = settings.cache_timeout_seconds
|
||||
self.client = Redis.from_url(
|
||||
settings.cache_url,
|
||||
socket_timeout=self.timeout,
|
||||
socket_connect_timeout=self.timeout,
|
||||
retry=Retry(NoBackoff(), 0), # no hidden retries: a failure is reported at once
|
||||
decode_responses=False,
|
||||
)
|
||||
|
||||
def _key(self, token: str) -> str:
|
||||
return self.PREFIX + token_hash(token).hex()
|
||||
|
||||
async def _call(self, coro):
|
||||
try:
|
||||
async with asyncio.timeout(self.timeout * 2):
|
||||
return await coro
|
||||
except (redis_errors.ConnectionError, redis_errors.TimeoutError, TimeoutError, OSError) as exc:
|
||||
log.warning("session_store_unavailable", extra={"fields": {"error": type(exc).__name__}})
|
||||
raise Unavailable("Хранилище сессий временно недоступно") from None
|
||||
|
||||
async def create(self, user_id: str, ttl_seconds: int) -> tuple[str, dt.datetime]:
|
||||
token = new_token()
|
||||
expires_at = now() + dt.timedelta(seconds=ttl_seconds)
|
||||
value = json.dumps({"user_id": user_id, "expires_at_us": to_us(expires_at)}).encode()
|
||||
# PXAT = absolute expiry time: survives restarts (AOF) without being extended.
|
||||
await self._call(self.client.set(self._key(token), value, pxat=to_us(expires_at) // 1000))
|
||||
return token, expires_at
|
||||
|
||||
async def user_id_for(self, token: str) -> str | None:
|
||||
raw = await self._call(self.client.get(self._key(token)))
|
||||
if raw is None:
|
||||
return None
|
||||
data = json.loads(raw)
|
||||
if from_us(data["expires_at_us"]) <= now():
|
||||
return None # do not rely only on Valkey's lazy expiry
|
||||
return data["user_id"]
|
||||
|
||||
async def revoke(self, token: str) -> bool:
|
||||
return await self._call(self.client.delete(self._key(token))) == 1
|
||||
|
||||
async def ping(self) -> bool:
|
||||
try:
|
||||
return bool(await self._call(self.client.ping()))
|
||||
except Unavailable:
|
||||
return False
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.client.aclose()
|
||||
|
||||
|
||||
def build_store(settings: Settings, db: Database) -> SessionStore:
|
||||
return ValkeySessionStore(settings) if settings.session_store == "valkey" else PostgresSessionStore(db)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Private S3 bucket (SeaweedFS in compose) through aiobotocore, with a hard deadline per call.
|
||||
|
||||
* Credentials: the API's OWN key pair (S3_ACCESS_KEY_ID_FILE / S3_SECRET_ACCESS_KEY_FILE ->
|
||||
Docker secrets). SeaweedFS grants it only Read + Write on this one bucket: no List, no
|
||||
Admin (cannot create/delete buckets or read other buckets). The admin pair is given only
|
||||
to the S3 server and the one-shot bootstrap (infra/seaweedfs, messenger.s3_bootstrap).
|
||||
* Deadlines: botocore connect/read timeouts AND an asyncio deadline around every call, so a
|
||||
paused or unreachable S3 costs at most S3_TIMEOUT_SECONDS, then 503 `unavailable`. Unlike a
|
||||
libpq query (db.py), an aiohttp request can be cancelled safely, so the call is cancelled.
|
||||
* ONE retry inside botocore (total_max_attempts=2), within the same asyncio deadline: after S3
|
||||
restarts, pooled keep-alive connections to the old process are dead and the first request on
|
||||
such a connection fails although S3 is up again (found by test_s3_outage_..._stop on a clean
|
||||
clone). Every call here is idempotent PER KEY (PUT of the same bytes to the same server-chosen
|
||||
key, GET, HEAD, DELETE), so repeating it cannot create a second attachment.
|
||||
* Checksums: Content-MD5 is sent with every PUT, so S3 rejects bytes damaged on the way.
|
||||
botocore's newer default (aws-chunked CRC32 trailers) is switched off ("when_required"):
|
||||
plain, widely supported S3 requests.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import contextlib
|
||||
import hashlib
|
||||
import logging
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
|
||||
from aiobotocore.config import AioConfig
|
||||
from aiobotocore.session import get_session
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from . import telemetry
|
||||
from .config import Settings
|
||||
from .errors import Unavailable
|
||||
|
||||
log = logging.getLogger("messenger.storage")
|
||||
|
||||
MISSING_CODES = {"NoSuchKey", "404", "NotFound"}
|
||||
|
||||
|
||||
class ObjectMissing(Exception):
|
||||
"""The key does not exist in the bucket (definitive answer of S3, not an outage)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ObjectHead:
|
||||
size: int
|
||||
content_type: str
|
||||
metadata: dict[str, str]
|
||||
last_modified_ts: float # POSIX seconds
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ListedObject:
|
||||
key: str
|
||||
size: int
|
||||
last_modified_ts: float # POSIX seconds
|
||||
|
||||
|
||||
class Storage:
|
||||
def __init__(self, settings: Settings, *, access_key: str | None = None, secret_key: str | None = None,
|
||||
bucket: str | None = None):
|
||||
# Lab 5: one client per bucket - the final bucket (S3_BUCKET) or the staging bucket.
|
||||
self.bucket = bucket or settings.s3_bucket
|
||||
self.timeout = settings.s3_timeout_seconds
|
||||
self._endpoint = settings.s3_endpoint
|
||||
self._region = settings.s3_region
|
||||
self._access_key = access_key or settings.s3_access_key_id
|
||||
self._secret_key = secret_key or settings.s3_secret_access_key
|
||||
self._config = AioConfig(
|
||||
connect_timeout=settings.s3_connect_timeout_seconds,
|
||||
read_timeout=settings.s3_timeout_seconds,
|
||||
retries={"total_max_attempts": 2, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
signature_version="s3v4",
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
max_pool_connections=settings.s3_max_connections,
|
||||
)
|
||||
self._stack: contextlib.AsyncExitStack | None = None
|
||||
self._client = None
|
||||
|
||||
async def open(self) -> None:
|
||||
self._stack = contextlib.AsyncExitStack()
|
||||
session = get_session()
|
||||
self._client = await self._stack.enter_async_context(session.create_client(
|
||||
"s3", endpoint_url=self._endpoint, region_name=self._region,
|
||||
aws_access_key_id=self._access_key, aws_secret_access_key=self._secret_key, config=self._config))
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._stack is not None:
|
||||
await self._stack.aclose()
|
||||
self._stack = None
|
||||
|
||||
@property
|
||||
def client(self):
|
||||
assert self._client is not None, "Storage.open() was not called"
|
||||
return self._client
|
||||
|
||||
async def _call(self, what: str, coro, deadline: float | None = None):
|
||||
"""Await one S3 call under the deadline; outages become Unavailable (503).
|
||||
|
||||
Lab 6: a CLIENT span `s3 <op>` (bucket name only - never the object key, which would let a
|
||||
reader of the traces fetch objects, and never a signed URL) inside a traced request/job.
|
||||
Body chunks of a download (`get_body`) get no span of their own: they belong to `s3 get`
|
||||
timing-wise, and a 10 MiB file would otherwise produce 160 spans."""
|
||||
span = None
|
||||
if what not in ("get_body", "ping") and telemetry.trace.get_current_span().is_recording():
|
||||
span = telemetry.TRACER.start_span(f"s3 {what}", kind=telemetry.SpanKind.CLIENT, attributes={
|
||||
"rpc.system": "aws-api", "rpc.service": "S3", "rpc.method": what, "aws.s3.bucket": self.bucket})
|
||||
try:
|
||||
return await asyncio.wait_for(coro, deadline or self.timeout)
|
||||
except ClientError as exc:
|
||||
code = str(exc.response.get("Error", {}).get("Code", ""))
|
||||
if code in MISSING_CODES:
|
||||
if span is not None:
|
||||
span.set_attribute("messenger.s3.result", "missing")
|
||||
raise ObjectMissing() from None
|
||||
log.warning("s3_error", extra={"fields": {"op": what, "code": code}})
|
||||
if span is not None:
|
||||
telemetry.mark_error(span, code or "ClientError")
|
||||
raise Unavailable("Хранилище файлов временно недоступно") from None
|
||||
except (asyncio.TimeoutError, BotoCoreError, OSError) as exc:
|
||||
log.warning("s3_unavailable", extra={"fields": {"op": what, "error": type(exc).__name__}})
|
||||
if span is not None:
|
||||
telemetry.mark_error(span, type(exc).__name__)
|
||||
raise Unavailable("Хранилище файлов временно недоступно") from None
|
||||
finally:
|
||||
if span is not None:
|
||||
span.end()
|
||||
|
||||
async def put(self, key: str, data: bytes | bytearray, content_type: str, metadata: dict[str, str]) -> None:
|
||||
md5 = base64.b64encode(hashlib.md5(data, usedforsecurity=False).digest()).decode("ascii")
|
||||
# Time budget grows with the size: 10 MiB over a local network takes well under a second.
|
||||
deadline = self.timeout + len(data) / (8 * 1024 * 1024)
|
||||
await self._call("put", self.client.put_object(
|
||||
Bucket=self.bucket, Key=key, Body=data, ContentType=content_type, ContentLength=len(data),
|
||||
ContentMD5=md5, Metadata=metadata), deadline)
|
||||
|
||||
async def head(self, key: str) -> ObjectHead:
|
||||
response = await self._call("head", self.client.head_object(Bucket=self.bucket, Key=key))
|
||||
return ObjectHead(int(response["ContentLength"]), response.get("ContentType", ""),
|
||||
dict(response.get("Metadata", {})), response["LastModified"].timestamp())
|
||||
|
||||
async def open_stream(self, key: str) -> tuple[int, AsyncIterator[bytes]]:
|
||||
"""Start a GET: (Content-Length, async iterator of chunks). The headers arrive under the
|
||||
deadline; every chunk read afterwards has its own deadline (a stalled S3 aborts the
|
||||
download instead of hanging the connection)."""
|
||||
response = await self._call("get", self.client.get_object(Bucket=self.bucket, Key=key))
|
||||
body = response["Body"]
|
||||
size = int(response["ContentLength"])
|
||||
|
||||
async def chunks() -> AsyncIterator[bytes]:
|
||||
try:
|
||||
while True:
|
||||
chunk = await self._call("get_body", body.read(64 * 1024))
|
||||
if not chunk:
|
||||
return
|
||||
yield chunk
|
||||
finally:
|
||||
body.close()
|
||||
return size, chunks()
|
||||
|
||||
async def read_all(self, key: str, limit: int) -> bytes:
|
||||
"""Whole object (worker source, audit checksums); refuses objects above `limit`.
|
||||
Lab 6: span `s3 download` covers headers AND body (the `s3 get` child: headers only)."""
|
||||
with telemetry.child_span("s3 download", {"aws.s3.bucket": self.bucket}) as span:
|
||||
size, chunks = await self.open_stream(key)
|
||||
if size > limit:
|
||||
raise Unavailable("Объект больше допустимого размера")
|
||||
parts = [chunk async for chunk in chunks]
|
||||
if span is not None:
|
||||
span.set_attribute("messenger.s3.size_bytes", size)
|
||||
return b"".join(parts)
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
"""Idempotent: deleting a missing key is a success in S3."""
|
||||
await self._call("delete", self.client.delete_object(Bucket=self.bucket, Key=key))
|
||||
|
||||
async def list_page(self, prefix: str, start_after: str | None, page_size: int) -> tuple[list[ListedObject], bool]:
|
||||
"""One ListObjectsV2 page in key order (needs the List permission: reconciler only)."""
|
||||
params = {"Bucket": self.bucket, "Prefix": prefix, "MaxKeys": page_size}
|
||||
if start_after:
|
||||
params["StartAfter"] = start_after
|
||||
response = await self._call("list", self.client.list_objects_v2(**params))
|
||||
items = [ListedObject(o["Key"], int(o["Size"]), o["LastModified"].timestamp())
|
||||
for o in response.get("Contents", [])]
|
||||
return items, bool(response.get("IsTruncated"))
|
||||
|
||||
async def ping(self, timeout: float = 1.0) -> bool:
|
||||
"""Readiness: HEAD of the sentinel object written by the bootstrap. Proves that S3
|
||||
answers, the bucket exists and the API credentials are accepted (Read permission)."""
|
||||
try:
|
||||
await self._call("ping", self.client.head_object(Bucket=self.bucket, Key=SENTINEL_KEY), timeout)
|
||||
return True
|
||||
except (Unavailable, ObjectMissing):
|
||||
return False
|
||||
|
||||
|
||||
SENTINEL_KEY = "health/sentinel"
|
||||
# Lab 4 originals: o/<random 128-bit hex> in the final bucket (still readable).
|
||||
OBJECT_PREFIX = "o/"
|
||||
# Lab 5: s/<random 128-bit hex> in the STAGING bucket (written by the API before 202) and
|
||||
# a/<attachment id>/<attempt token>/<original|thumbnail|crop|optimized> in the final bucket
|
||||
# (written by the worker; the token makes every attempt write its own keys).
|
||||
STAGING_PREFIX = "s/"
|
||||
|
||||
|
||||
def attempt_key(attachment_id: str, token: str, name: str) -> str:
|
||||
return f"a/{attachment_id}/{token}/{name}"
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Lab 6: OpenTelemetry for the API, the relay and the worker (one module, three processes).
|
||||
|
||||
process --OTLP/HTTP protobuf--> otel-collector --> Prometheus (metrics) / Loki (logs) / Tempo (traces)
|
||||
|
||||
What is set up here (docs/OBSERVABILITY.md has the full signal map):
|
||||
|
||||
* Resource: service.name (messenger-api / messenger-relay / messenger-worker), service.version,
|
||||
service.instance.id (= X-Instance-Id / container hostname), deployment.environment.name=lab
|
||||
(from OTEL_RESOURCE_ATTRIBUTES).
|
||||
* Traces: TracerProvider + BatchSpanProcessor (bounded in-memory queue, OTEL_BSP_* variables)
|
||||
+ OTLP exporter. The sampler comes from OTEL_TRACES_SAMPLER / OTEL_TRACES_SAMPLER_ARG
|
||||
(default parentbased_always_on). Propagation: W3C traceparent/tracestate.
|
||||
* Metrics: MeterProvider + PeriodicExportingMetricReader (OTEL_METRIC_EXPORT_INTERVAL, ms).
|
||||
Histogram bucket boundaries are set per instrument (explicit_bucket_boundaries_advisory):
|
||||
the default OTel boundaries (0, 5, 10, 25 ... 10000) were made for milliseconds and would
|
||||
put every request of a few ms into one bucket when the unit is seconds.
|
||||
* Logs: our own small logging.Handler on the `messenger` logger tree -> LoggerProvider +
|
||||
BatchLogRecordProcessor + OTLP exporter. Each record carries the active trace_id/span_id.
|
||||
Only the `messenger.*` loggers are exported: the SDK's own warnings ("failed to export")
|
||||
go to stdout only, so an unavailable Collector cannot cause a feedback loop.
|
||||
|
||||
OTEL_SDK_DISABLED=true (track 1 "telemetry off") installs nothing: the API calls below become
|
||||
no-ops (non-recording spans, no-op instruments) and only the stdout JSON log remains.
|
||||
|
||||
Nothing exported here may contain secrets or user content: no Authorization header, session
|
||||
token, password, message text, image bytes, S3 key, signed URL or query string (cursor,
|
||||
filename). Metric attributes are low-cardinality only (method, route TEMPLATE, status code,
|
||||
operation, outcome) - never user_id/chat_id/message_id/attachment_id/request_id.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Iterable, Sequence
|
||||
|
||||
from opentelemetry import context as otel_context
|
||||
from opentelemetry import metrics, propagate, trace
|
||||
from opentelemetry.metrics import CallbackOptions, Observation
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
log = logging.getLogger("messenger.telemetry")
|
||||
|
||||
TRACER = trace.get_tracer("messenger")
|
||||
METER = metrics.get_meter("messenger")
|
||||
|
||||
# Bucket boundaries, seconds. Dense where our latencies are (1 ms .. 1 s), still covering the
|
||||
# timeouts (DB 3 s, S3 3 s, job 60 s) so a p99 near a limit is not clamped to the last bucket.
|
||||
HTTP_BUCKETS = (0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.5,
|
||||
0.75, 1.0, 1.5, 2.5, 5.0, 10.0)
|
||||
DB_BUCKETS = (0.0005, 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0)
|
||||
JOB_BUCKETS = (0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, 20.0, 30.0, 60.0)
|
||||
READY_BUCKETS = (0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, 20.0, 30.0, 60.0, 120.0, 300.0, 600.0)
|
||||
|
||||
_state = {"enabled": False, "providers": []}
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return _state["enabled"]
|
||||
|
||||
|
||||
def sdk_disabled() -> bool:
|
||||
return os.environ.get("OTEL_SDK_DISABLED", "false").strip().lower() == "true"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- setup
|
||||
def setup(service_name: str, instance_id: str, version: str) -> None:
|
||||
"""Install the SDK providers for this process (once, before the work starts)."""
|
||||
if sdk_disabled():
|
||||
log.info("telemetry_disabled", extra={"fields": {"reason": "OTEL_SDK_DISABLED"}})
|
||||
return
|
||||
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
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
# Explicit attributes win over OTEL_RESOURCE_ATTRIBUTES / OTEL_SERVICE_NAME.
|
||||
resource = Resource.create({"service.name": service_name, "service.version": version,
|
||||
"service.instance.id": instance_id})
|
||||
tracer_provider = TracerProvider(resource=resource) # sampler from OTEL_TRACES_SAMPLER
|
||||
tracer_provider.add_span_processor(SpanCounter())
|
||||
tracer_provider.add_span_processor(BatchSpanProcessor(CountingSpanExporter(OTLPSpanExporter())))
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
reader = PeriodicExportingMetricReader(OTLPMetricExporter()) # interval from OTEL_METRIC_EXPORT_INTERVAL
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter()))
|
||||
set_logger_provider(logger_provider)
|
||||
logging.getLogger("messenger").addHandler(OtlpLogHandler(logger_provider))
|
||||
|
||||
_state["enabled"] = True
|
||||
_state["providers"] = [tracer_provider, meter_provider, logger_provider]
|
||||
_register_process_metrics()
|
||||
log.info("telemetry_enabled", extra={"fields": {
|
||||
"service": service_name, "endpoint": os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", ""),
|
||||
"sampler": os.environ.get("OTEL_TRACES_SAMPLER", "parentbased_always_on"),
|
||||
"sampler_arg": os.environ.get("OTEL_TRACES_SAMPLER_ARG", "")}})
|
||||
|
||||
|
||||
def shutdown() -> None:
|
||||
"""Flush what is buffered (bounded by the exporters' timeouts) at process exit."""
|
||||
for provider in _state["providers"]:
|
||||
try:
|
||||
provider.shutdown()
|
||||
except Exception: # noqa: BLE001 - the Collector may be gone; never block the exit on it
|
||||
pass
|
||||
_state["providers"] = []
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- logs
|
||||
_SEVERITY = ((logging.CRITICAL, 21), (logging.ERROR, 17), (logging.WARNING, 13), (logging.INFO, 9), (logging.DEBUG, 5))
|
||||
|
||||
|
||||
def _attr(value):
|
||||
if value is None or isinstance(value, (str, bool, int, float)):
|
||||
return value
|
||||
if isinstance(value, (list, tuple, set, frozenset)):
|
||||
return [str(v) for v in value]
|
||||
return str(value)
|
||||
|
||||
|
||||
def is_probe_noise(record: logging.LogRecord, fields: dict) -> bool:
|
||||
"""A SUCCESSFUL /health/* access line is not exported (HAProxy and Docker probe every replica
|
||||
every 1-2 s: ~3 lines/s of noise per replica in Loki). It stays in stdout; a failed probe
|
||||
(503: dependency down, draining) is exported like any other line."""
|
||||
route = fields.get("route")
|
||||
return (record.name == "messenger.access" and isinstance(route, str) and route.startswith("/health/")
|
||||
and isinstance(fields.get("status"), int) and fields["status"] < 400)
|
||||
|
||||
|
||||
class OtlpLogHandler(logging.Handler):
|
||||
"""logging -> OTLP log records. Body and attribute `event` = the event name (our log message is
|
||||
always a short event id such as `request` or `job_done`); the structured `fields` become
|
||||
attributes. trace_id/span_id come from the current context (the active span)."""
|
||||
|
||||
def __init__(self, provider) -> None:
|
||||
super().__init__()
|
||||
self._logger = provider.get_logger("messenger")
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
try:
|
||||
from opentelemetry._logs import SeverityNumber
|
||||
fields = getattr(record, "fields", None) or {}
|
||||
if is_probe_noise(record, fields):
|
||||
return
|
||||
event = record.getMessage()
|
||||
attributes = {"event": event, "logger.name": record.name}
|
||||
for key, value in fields.items():
|
||||
value = _attr(value)
|
||||
if value is not None:
|
||||
attributes[key] = value
|
||||
if record.exc_info and record.exc_info[0] is not None:
|
||||
attributes["exception.type"] = record.exc_info[0].__name__
|
||||
number = next(n for level, n in _SEVERITY if record.levelno >= level) if record.levelno >= logging.DEBUG else 1
|
||||
self._logger.emit(timestamp=int(record.created * 1e9), context=otel_context.get_current(),
|
||||
severity_number=SeverityNumber(number), severity_text=record.levelname,
|
||||
body=event, attributes=attributes, event_name=event)
|
||||
except Exception: # noqa: BLE001
|
||||
self.handleError(record)
|
||||
|
||||
|
||||
def current_ids() -> tuple[str, str] | None:
|
||||
"""(trace_id, span_id) of the active span as hex, for the stdout JSON log."""
|
||||
ctx = trace.get_current_span().get_span_context()
|
||||
if not ctx.is_valid:
|
||||
return None
|
||||
return format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- context
|
||||
def inject() -> dict[str, str]:
|
||||
"""W3C carrier of the CURRENT context: {"traceparent": ..., "tracestate": ...} (may be empty)."""
|
||||
carrier: dict[str, str] = {}
|
||||
propagate.inject(carrier)
|
||||
return {k: v for k, v in carrier.items() if k in ("traceparent", "tracestate")}
|
||||
|
||||
|
||||
def extract(traceparent: str | None, tracestate: str | None = None):
|
||||
carrier = {}
|
||||
if traceparent:
|
||||
carrier["traceparent"] = traceparent
|
||||
if tracestate:
|
||||
carrier["tracestate"] = tracestate
|
||||
return propagate.extract(carrier)
|
||||
|
||||
|
||||
def extract_headers(headers: Iterable[tuple[bytes, bytes]]):
|
||||
"""Context from the raw ASGI headers (only traceparent/tracestate are read)."""
|
||||
carrier = {}
|
||||
for key, value in headers:
|
||||
name = key.decode("latin-1").lower()
|
||||
if name in ("traceparent", "tracestate"):
|
||||
carrier[name] = value.decode("latin-1")
|
||||
return propagate.extract(carrier)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def child_span(name: str, attributes: dict | None = None, kind: SpanKind = SpanKind.INTERNAL):
|
||||
"""Current span for the block - only inside an already traced request/job (else yields None).
|
||||
An exception leaving the block marks the span as error (type only)."""
|
||||
if not trace.get_current_span().is_recording():
|
||||
yield None
|
||||
return
|
||||
with TRACER.start_as_current_span(name, kind=kind, attributes=attributes or {},
|
||||
record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
yield span
|
||||
except BaseException as exc:
|
||||
if not isinstance(exc, (GeneratorExit,)):
|
||||
mark_error(span, type(exc).__name__)
|
||||
raise
|
||||
|
||||
|
||||
def mark_error(span, code: str) -> None:
|
||||
span.set_status(Status(StatusCode.ERROR, code))
|
||||
span.set_attribute("error.type", code)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- instruments
|
||||
http_duration = METER.create_histogram(
|
||||
"http.server.request.duration", unit="s",
|
||||
description="Duration of HTTP server requests (whole ASGI call, until the last body byte)",
|
||||
explicit_bucket_boundaries_advisory=HTTP_BUCKETS)
|
||||
http_active = METER.create_up_down_counter(
|
||||
"http.server.active_requests", unit="{request}", description="HTTP requests being served now")
|
||||
db_duration = METER.create_histogram(
|
||||
"db.client.operation.duration", unit="s",
|
||||
description="One unit of database work (pool wait + statements + COMMIT)",
|
||||
explicit_bucket_boundaries_advisory=DB_BUCKETS)
|
||||
db_wait = METER.create_histogram(
|
||||
"db.client.connection.wait_time", unit="s", description="Time waiting for a free pool connection",
|
||||
explicit_bucket_boundaries_advisory=DB_BUCKETS)
|
||||
jobs_processed = METER.create_counter(
|
||||
"messenger.jobs.processed", unit="{job}",
|
||||
description="Job deliveries handled by the worker, by outcome (succeeded, retry, failed, noop_*, ...)")
|
||||
job_duration = METER.create_histogram(
|
||||
"messenger.job.duration", unit="s", description="Handling of one job delivery by the worker",
|
||||
explicit_bucket_boundaries_advisory=JOB_BUCKETS)
|
||||
time_to_ready = METER.create_histogram(
|
||||
"messenger.attachment.time_to_ready", unit="s",
|
||||
description="From the durable acceptance (202, job COMMIT) to the COMMIT of status ready",
|
||||
explicit_bucket_boundaries_advisory=READY_BUCKETS)
|
||||
worker_busy = METER.create_up_down_counter(
|
||||
"messenger.worker.busy", unit="{job}", description="Job attempts being processed now")
|
||||
spans_ended = METER.create_counter(
|
||||
"messenger.telemetry.spans.ended", unit="{span}", description="Recorded (sampled) spans finished in this process")
|
||||
spans_exported = METER.create_counter(
|
||||
"messenger.telemetry.spans.exported", unit="{span}",
|
||||
description="Spans handed to the OTLP exporter, by result (success / failure)")
|
||||
|
||||
|
||||
def observe(name: str, unit: str, description: str, callback) -> None:
|
||||
"""Asynchronous gauge; `callback()` returns [(value, attributes), ...]. Callbacks run in the
|
||||
metric reader thread, so they only read values the process already has in memory."""
|
||||
def wrapped(options: CallbackOptions) -> Iterable[Observation]:
|
||||
try:
|
||||
return [Observation(v, a) for v, a in callback()]
|
||||
except Exception: # noqa: BLE001 - a broken gauge must not break the export of the others
|
||||
return []
|
||||
METER.create_observable_gauge(name, callbacks=[wrapped], unit=unit, description=description)
|
||||
|
||||
|
||||
def observe_pool(pool, pool_name: str) -> None:
|
||||
"""db.client.connection.* (semantic conventions) from psycopg_pool's counters."""
|
||||
def connections():
|
||||
stats = pool.get_stats()
|
||||
size, idle = stats.get("pool_size", 0), stats.get("pool_available", 0)
|
||||
return [(idle, {"db.client.connection.pool.name": pool_name, "db.client.connection.state": "idle"}),
|
||||
(max(0, size - idle), {"db.client.connection.pool.name": pool_name, "db.client.connection.state": "used"})]
|
||||
observe("db.client.connection.count", "{connection}", "Open pool connections by state", connections)
|
||||
observe("db.client.connection.max", "{connection}", "Pool max_size",
|
||||
lambda: [(pool.max_size, {"db.client.connection.pool.name": pool_name})])
|
||||
observe("db.client.connection.pending_requests", "{request}", "Requests waiting for a pool connection",
|
||||
lambda: [(pool.get_stats().get("requests_waiting", 0), {"db.client.connection.pool.name": pool_name})])
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- spans accounting
|
||||
try:
|
||||
from opentelemetry.sdk.trace import SpanProcessor as _SpanProcessor
|
||||
except ImportError: # pragma: no cover - the SDK is a locked dependency
|
||||
_SpanProcessor = object
|
||||
|
||||
|
||||
class SpanCounter(_SpanProcessor):
|
||||
"""SpanProcessor counting the spans this process records (track 1: losses on the way)."""
|
||||
|
||||
def on_end(self, span) -> None:
|
||||
spans_ended.add(1)
|
||||
|
||||
|
||||
class CountingSpanExporter:
|
||||
"""Wraps the OTLP span exporter: counts spans exported / failed (Collector unreachable)."""
|
||||
|
||||
def __init__(self, inner) -> None:
|
||||
self.inner = inner
|
||||
|
||||
def export(self, spans: Sequence):
|
||||
from opentelemetry.sdk.trace.export import SpanExportResult
|
||||
result = self.inner.export(spans)
|
||||
spans_exported.add(len(spans), {"result": "success" if result == SpanExportResult.SUCCESS else "failure"})
|
||||
return result
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.inner.shutdown()
|
||||
|
||||
def force_flush(self, timeout_millis: int = 30000) -> bool:
|
||||
return self.inner.force_flush(timeout_millis)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- CPU / RAM
|
||||
def _read(path: str) -> str | None:
|
||||
try:
|
||||
with open(path, encoding="ascii") as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _register_process_metrics() -> None:
|
||||
"""Container (cgroup v2) and process CPU/RAM. The container values include the worker's image
|
||||
child processes; Docker's own `docker stats` reads the same cgroup files."""
|
||||
def container_cpu():
|
||||
stat = _read("/sys/fs/cgroup/cpu.stat")
|
||||
if not stat:
|
||||
return []
|
||||
for line in stat.splitlines():
|
||||
if line.startswith("usage_usec "):
|
||||
return [(int(line.split()[1]) / 1e6, {})]
|
||||
return []
|
||||
|
||||
def container_memory():
|
||||
value = _read("/sys/fs/cgroup/memory.current")
|
||||
return [(int(value), {})] if value else []
|
||||
|
||||
def container_memory_limit():
|
||||
value = _read("/sys/fs/cgroup/memory.max")
|
||||
return [(int(value), {})] if value and value.strip().isdigit() else []
|
||||
|
||||
def process_memory():
|
||||
statm = _read("/proc/self/statm")
|
||||
return [(int(statm.split()[1]) * os.sysconf("SC_PAGE_SIZE"), {})] if statm else []
|
||||
|
||||
def cpu_counter(options: CallbackOptions):
|
||||
return [Observation(v, a) for v, a in container_cpu()]
|
||||
|
||||
METER.create_observable_counter("container.cpu.time", callbacks=[cpu_counter], unit="s",
|
||||
description="CPU time of the whole container (cgroup cpu.stat usage_usec)")
|
||||
observe("container.memory.usage", "By", "Memory of the container (cgroup memory.current)", container_memory)
|
||||
observe("container.memory.limit", "By", "Memory limit of the container (cgroup memory.max)", container_memory_limit)
|
||||
observe("process.memory.usage", "By", "Resident memory of the main process", process_memory)
|
||||
|
||||
|
||||
__all__ = ["TRACER", "SpanKind", "StatusCode", "setup", "shutdown", "enabled", "inject", "extract",
|
||||
"extract_headers", "current_ids", "mark_error", "child_span", "observe", "observe_pool"]
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Conversions between PostgreSQL timestamptz values, cursor integers and RFC 3339 strings."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
|
||||
UTC = dt.timezone.utc
|
||||
_EPOCH = dt.datetime(1970, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
def to_us(value: dt.datetime) -> int:
|
||||
"""Microseconds since the Unix epoch (exact: timestamptz has microsecond precision)."""
|
||||
delta = value - _EPOCH
|
||||
return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds
|
||||
|
||||
|
||||
def from_us(us: int) -> dt.datetime:
|
||||
return _EPOCH + dt.timedelta(microseconds=us)
|
||||
|
||||
|
||||
def rfc3339(value: dt.datetime) -> str:
|
||||
"""RFC 3339 UTC with fixed microsecond precision, e.g. 2026-10-12T12:00:00.000001Z."""
|
||||
return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Strict request validation according to contracts/openapi.json + contracts/README.md.
|
||||
|
||||
Written by hand instead of a schema library so that every rule is visible:
|
||||
extra fields, wrong JSON types, whitespace-only strings and lengths counted in
|
||||
Unicode code points all produce 400 invalid_request.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qsl
|
||||
|
||||
from .errors import InvalidRequest
|
||||
|
||||
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
|
||||
# Canonical textual UUID (8-4-4-4-12 hex). Case-insensitive, normalised to lower case.
|
||||
UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
LIMIT_RE = re.compile(r"[0-9]{1,3}")
|
||||
# Idempotency-Key (contract, lab 3): ASCII [A-Za-z0-9._:-]{1,128}.
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
SURROGATES_RE = re.compile("[\ud800-\udfff]")
|
||||
|
||||
DEFAULT_LIMIT = 50
|
||||
MAX_LIMIT = 100
|
||||
|
||||
|
||||
def _reject_constant(name: str) -> Any:
|
||||
# Python's json accepts NaN/Infinity, which are not valid JSON.
|
||||
raise ValueError(f"invalid JSON constant {name}")
|
||||
|
||||
|
||||
def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
# {"text":"a","text":"b"} is ambiguous (which one is meant?) -> 400, not "last one wins".
|
||||
result = dict(pairs)
|
||||
if len(result) != len(pairs):
|
||||
raise ValueError("duplicate key in JSON object")
|
||||
return result
|
||||
|
||||
|
||||
def parse_json_object(body: bytes) -> dict[str, Any]:
|
||||
"""Decode a UTF-8 JSON object or raise InvalidRequest (malformed JSON -> 400)."""
|
||||
try:
|
||||
text = body.decode("utf-8")
|
||||
value = json.loads(text, parse_constant=_reject_constant, object_pairs_hook=_unique_keys)
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise InvalidRequest("Тело запроса должно быть корректным JSON в UTF-8") from None
|
||||
if not isinstance(value, dict):
|
||||
raise InvalidRequest("Тело запроса должно быть JSON-объектом")
|
||||
return value
|
||||
|
||||
|
||||
def check_fields(data: dict[str, Any], required: set[str], optional: frozenset[str] = frozenset()) -> None:
|
||||
extra = set(data) - required - optional
|
||||
if extra:
|
||||
raise InvalidRequest("Неизвестные поля: " + ", ".join(sorted(extra)))
|
||||
missing = required - set(data)
|
||||
if missing:
|
||||
raise InvalidRequest("Отсутствуют обязательные поля: " + ", ".join(sorted(missing)))
|
||||
|
||||
|
||||
def text_field(data: dict[str, Any], name: str, max_len: int, *, min_len: int = 1, allow_blank: bool = False) -> str:
|
||||
value = data[name]
|
||||
if not isinstance(value, str):
|
||||
raise InvalidRequest(f"Поле {name} должно быть строкой")
|
||||
if SURROGATES_RE.search(value):
|
||||
# "\ud800" escapes decode to lone surrogates that cannot be encoded as UTF-8.
|
||||
raise InvalidRequest(f"Поле {name} содержит недопустимые символы")
|
||||
# len() of a Python str is the number of Unicode code points, as the contract requires.
|
||||
if not min_len <= len(value) <= max_len:
|
||||
raise InvalidRequest(f"Длина поля {name} должна быть от {min_len} до {max_len} символов")
|
||||
if value.strip() == "" and not allow_blank:
|
||||
raise InvalidRequest(f"Поле {name} не может состоять только из пробелов")
|
||||
return value
|
||||
|
||||
|
||||
def username_field(data: dict[str, Any]) -> str:
|
||||
value = data["username"]
|
||||
if not isinstance(value, str) or USERNAME_RE.fullmatch(value) is None:
|
||||
raise InvalidRequest("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
return value
|
||||
|
||||
|
||||
def password_field(data: dict[str, Any]) -> str:
|
||||
"""12-128 Unicode code points, not whitespace-only; any other character (':' too) is allowed."""
|
||||
value = data["password"]
|
||||
if not isinstance(value, str):
|
||||
raise InvalidRequest("Поле password должно быть строкой")
|
||||
if SURROGATES_RE.search(value):
|
||||
raise InvalidRequest("Поле password содержит недопустимые символы")
|
||||
if not 12 <= len(value) <= 128:
|
||||
raise InvalidRequest("Длина пароля должна быть от 12 до 128 символов")
|
||||
if value.strip() == "":
|
||||
raise InvalidRequest("Пароль не может состоять только из пробелов")
|
||||
return value
|
||||
|
||||
|
||||
def parse_uuid(value: Any, what: str = "UUID") -> str:
|
||||
if not isinstance(value, str) or UUID_RE.fullmatch(value) is None:
|
||||
raise InvalidRequest(f"Неверный {what}")
|
||||
return value.lower()
|
||||
|
||||
|
||||
def member_ids_field(data: dict[str, Any]) -> list[str]:
|
||||
value = data["member_ids"]
|
||||
if not isinstance(value, list):
|
||||
raise InvalidRequest("member_ids должен быть массивом")
|
||||
if not 1 <= len(value) <= 100:
|
||||
raise InvalidRequest("member_ids должен содержать от 1 до 100 элементов")
|
||||
ids = [parse_uuid(item, "UUID участника") for item in value]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise InvalidRequest("member_ids содержит дубликаты")
|
||||
return ids
|
||||
|
||||
|
||||
def attachment_ids_field(data: dict[str, Any]) -> list[str]:
|
||||
"""Optional `attachment_ids` (lab 4+): absent and [] are the same message (contracts/README.md);
|
||||
null or any other non-array type is 400."""
|
||||
value = data.get("attachment_ids", [])
|
||||
if not isinstance(value, list):
|
||||
raise InvalidRequest("attachment_ids должен быть массивом")
|
||||
if len(value) > 10:
|
||||
raise InvalidRequest("attachment_ids содержит больше 10 элементов")
|
||||
ids = [parse_uuid(item, "UUID вложения") for item in value]
|
||||
if len(set(ids)) != len(ids):
|
||||
raise InvalidRequest("attachment_ids содержит дубликаты")
|
||||
return ids
|
||||
|
||||
|
||||
def idempotency_key(raw: str | None) -> str:
|
||||
if raw is None or IDEMPOTENCY_KEY_RE.fullmatch(raw) is None:
|
||||
raise InvalidRequest("Заголовок Idempotency-Key обязателен: [A-Za-z0-9._:-]{1,128}")
|
||||
return raw
|
||||
|
||||
|
||||
def single_query_param(query: list[tuple[str, str]], name: str) -> str | None:
|
||||
values = [v for k, v in query if k == name]
|
||||
if len(values) > 1:
|
||||
raise InvalidRequest(f"Параметр {name} указан несколько раз")
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
def parse_limit(raw: str | None) -> int:
|
||||
if raw is None:
|
||||
return DEFAULT_LIMIT
|
||||
if LIMIT_RE.fullmatch(raw) is None or not 1 <= int(raw) <= MAX_LIMIT:
|
||||
raise InvalidRequest(f"limit должен быть целым числом от 1 до {MAX_LIMIT}")
|
||||
return int(raw)
|
||||
|
||||
|
||||
# Lab 4: the display name of an attachment. Never used as a path or an S3 key, but it is shown
|
||||
# to other users, so characters that change how a name LOOKS are refused: control characters
|
||||
# (C0, DEL, C1 such as U+0085), line/paragraph separators, unpaired surrogates and bidi controls
|
||||
# ("photo<U+202E>gnp.exe" would display as "photoexe.png").
|
||||
BIDI_CONTROLS = frozenset("\u061c\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069")
|
||||
FORBIDDEN_CATEGORIES = frozenset({"Cc", "Cs", "Zl", "Zp"})
|
||||
|
||||
|
||||
def query_items(raw: bytes) -> list[tuple[str, str]]:
|
||||
"""Strict query parsing: percent-encoded UTF-8 only (Starlette would replace bad bytes by U+FFFD)."""
|
||||
try:
|
||||
return parse_qsl(raw.decode("ascii"), keep_blank_values=True, encoding="utf-8", errors="strict")
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise InvalidRequest("Параметры запроса должны быть в UTF-8 с percent-encoding") from None
|
||||
|
||||
|
||||
def filename_param(query: list[tuple[str, str]]) -> str:
|
||||
value = single_query_param(query, "filename")
|
||||
if value is None:
|
||||
raise InvalidRequest("Параметр filename обязателен")
|
||||
if not 1 <= len(value) <= 255:
|
||||
raise InvalidRequest("Длина filename должна быть от 1 до 255 символов")
|
||||
if value.strip() == "" or value in {".", ".."}:
|
||||
raise InvalidRequest("filename не может состоять только из пробелов или точек")
|
||||
if "/" in value or "\\" in value:
|
||||
raise InvalidRequest("filename не может содержать / или \\")
|
||||
for char in value:
|
||||
if unicodedata.category(char) in FORBIDDEN_CATEGORIES or char in BIDI_CONTROLS:
|
||||
raise InvalidRequest("filename содержит управляющие символы")
|
||||
return value
|
||||
|
||||
|
||||
ATTACHMENT_VARIANTS = ("original", "thumbnail", "crop", "optimized")
|
||||
|
||||
|
||||
def variant_param(query: list[tuple[str, str]]) -> str:
|
||||
"""`variant` of GET /attachments/{id}/content: original (default) or a lab 5 variant name.
|
||||
Any other value is 400; a known name that a ready attachment lacks is 404 (handler)."""
|
||||
value = single_query_param(query, "variant")
|
||||
if value is None:
|
||||
return "original"
|
||||
if value in ATTACHMENT_VARIANTS:
|
||||
return value
|
||||
raise InvalidRequest("variant должен быть original, thumbnail, crop или optimized")
|
||||
@@ -0,0 +1,403 @@
|
||||
"""Image worker: `python -m messenger.worker` (compose service `worker`, separate from the API).
|
||||
|
||||
One delivery of a job message:
|
||||
|
||||
decode + validate (schema v1; invalid -> reject -> dead-letter queue)
|
||||
-> CLAIM in PostgreSQL (jobs.claim): finished/leased/not due/stale -> no-op, ack
|
||||
-> lease heartbeat every JOB_LEASE_SECONDS/3 while the attempt runs
|
||||
-> read the source (staging copy or published original), check size + SHA-256 against the DB
|
||||
-> variants in a child process (imaging.py: pixel, memory and time limits)
|
||||
-> PUT the original (first publication) and the variants under keys of THIS attempt
|
||||
-> ONE transaction: variants + attachment ready, fenced by the lease token (jobs.complete)
|
||||
-> ack -> delete the staging copy (marked in the DB first, then S3).
|
||||
|
||||
The ack comes only after the durable effect (the COMMIT). A crash anywhere before it makes
|
||||
RabbitMQ deliver the message again; the job row then says what is left to do. Failures: a
|
||||
permanent one (invalid_image, image_too_large, source_missing/corrupt) fails the job at once, a
|
||||
transient one (S3 down, timeout, killed decoder) is retried with backoff via the outbox, at most
|
||||
JOB_MAX_ATTEMPTS claims in total.
|
||||
|
||||
Concurrency: RabbitMQ prefetch = WORKER_CONCURRENCY unacked messages per worker, and at most
|
||||
WORKER_CONCURRENCY image child processes. Graceful stop (SIGTERM): stop consuming, let running
|
||||
attempts finish for WORKER_SHUTDOWN_SECONDS, give the rest back (jobs.release).
|
||||
|
||||
The worker also runs the cleanup of the pipeline objects (staging copies that are no longer
|
||||
needed, objects of attempts that never published) - always decided under a row lock.
|
||||
|
||||
Lab 6: one delivery = one CONSUMER span `messenger.attachment-jobs process`, child of the relay's
|
||||
PRODUCER span (context from the message's `traceparent`), so the upload, its publish, every
|
||||
attempt and its DB/S3 steps are one trace. Metrics: messenger.jobs.processed (by outcome),
|
||||
messenger.job.duration, messenger.attachment.time_to_ready (uploads: 202 -> ready COMMIT),
|
||||
messenger.worker.busy / messenger.worker.capacity, db.client.connection.* of the worker pool.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractChannel, AbstractConnection, AbstractIncomingMessage, AbstractQueue
|
||||
|
||||
from . import __version__, broker, imaging, jobs, logging_setup, service, telemetry
|
||||
from .config import ConfigError, Settings
|
||||
from .db import Database
|
||||
from .errors import Unavailable
|
||||
from .imaging import ProcessingError
|
||||
from .storage import ObjectMissing, Storage
|
||||
|
||||
log = logging.getLogger("messenger.worker")
|
||||
|
||||
|
||||
class Worker:
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
self.name = settings.instance_id
|
||||
self.actor = "worker:" + self.name
|
||||
self.db = Database(settings, name="messenger-worker")
|
||||
self.staging = Storage(settings, bucket=settings.s3_staging_bucket)
|
||||
self.final = Storage(settings)
|
||||
self.slots = asyncio.Semaphore(settings.worker_concurrency)
|
||||
self.tasks: set[asyncio.Task] = set()
|
||||
self.connection: AbstractConnection | None = None
|
||||
self.channel: AbstractChannel | None = None
|
||||
self.queue: AbstractQueue | None = None
|
||||
self.consumer_tag: str | None = None
|
||||
self.lost: asyncio.Event | None = None
|
||||
|
||||
def connected(self) -> bool:
|
||||
return (self.connection is not None and self.lost is not None and not self.lost.is_set()
|
||||
and self.channel is not None and not self.channel.is_closed)
|
||||
|
||||
# ---------------------------------------------------------------- broker
|
||||
async def connect(self) -> None:
|
||||
self.connection = await aio_pika.connect(
|
||||
self.settings.broker_url, timeout=5,
|
||||
client_properties={"connection_name": "worker@" + self.name})
|
||||
self.lost = service.watch_connection(self.connection)
|
||||
self.channel = await self.connection.channel()
|
||||
# Prefetch: the broker keeps at most this many unacked messages in flight to this worker.
|
||||
await self.channel.set_qos(prefetch_count=self.settings.worker_concurrency)
|
||||
self.queue = await self.channel.get_queue(broker.QUEUE, ensure=False)
|
||||
self.consumer_tag = await self.queue.consume(self.on_message, no_ack=False)
|
||||
log.info("consuming", extra={"fields": {"queue": broker.QUEUE, "prefetch": self.settings.worker_concurrency}})
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self.connection is not None:
|
||||
try:
|
||||
await self.connection.close()
|
||||
except Exception: # noqa: BLE001 - already broken
|
||||
pass
|
||||
self.connection = self.channel = self.queue = self.lost = None
|
||||
self.consumer_tag = None
|
||||
|
||||
async def on_message(self, message: AbstractIncomingMessage) -> None:
|
||||
task = asyncio.create_task(self.deliver(message))
|
||||
self.tasks.add(task)
|
||||
task.add_done_callback(self.tasks.discard)
|
||||
|
||||
@staticmethod
|
||||
async def settle(action) -> None:
|
||||
"""ack/nack/reject; the channel may be gone (broker restart): then the broker requeues the
|
||||
message by itself and the redelivery is a no-op."""
|
||||
try:
|
||||
await action
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("settle_failed", extra={"fields": {"error": type(exc).__name__}})
|
||||
|
||||
async def deliver(self, message: AbstractIncomingMessage) -> None:
|
||||
begin = time.perf_counter()
|
||||
try:
|
||||
body = broker.decode(message.body)
|
||||
except broker.BadMessage as exc:
|
||||
log.error("bad_message", extra={"fields": {"reason": str(exc), "message_id": message.message_id}})
|
||||
self.count("rejected", begin)
|
||||
await self.settle(message.reject(requeue=False)) # -> messenger.attachment-jobs.dlq
|
||||
return
|
||||
with telemetry.TRACER.start_as_current_span(
|
||||
f"{broker.QUEUE} process", kind=telemetry.SpanKind.CONSUMER,
|
||||
context=telemetry.extract(body.get("traceparent"), body.get("tracestate")),
|
||||
record_exception=False, set_status_on_exception=False,
|
||||
attributes={"messaging.system": "rabbitmq", "messaging.operation.type": "process",
|
||||
"messaging.destination.name": broker.QUEUE,
|
||||
"messaging.message.id": message.message_id or "",
|
||||
"messaging.rabbitmq.message.redelivered": bool(message.redelivered),
|
||||
"messenger.job.id": body["job_id"], "messenger.job.message_attempt": body["attempt"],
|
||||
"messenger.attachment.id": body["attachment_id"],
|
||||
"messenger.pipeline.version": body["pipeline_version"],
|
||||
"service.instance.id": self.name}) as span:
|
||||
try:
|
||||
async with self.slots:
|
||||
telemetry.worker_busy.add(1)
|
||||
try:
|
||||
outcome = await self.process(body["job_id"])
|
||||
finally:
|
||||
telemetry.worker_busy.add(-1)
|
||||
except Unavailable:
|
||||
# PostgreSQL (or S3 during a DB step) unavailable: nothing decided. Back to the queue
|
||||
# after a pause; a claim that did happen is protected by its lease.
|
||||
log.warning("job_deferred", extra={"fields": {"job_id": body["job_id"]}})
|
||||
telemetry.mark_error(span, "deferred")
|
||||
span.set_attribute("messenger.job.outcome", "deferred")
|
||||
self.count("deferred", begin)
|
||||
await asyncio.sleep(2)
|
||||
await self.settle(message.nack(requeue=True))
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
# Shutdown: back to the queue. If the job was claimed it has been released (new outbox
|
||||
# row), and one of the two deliveries becomes a no-op.
|
||||
span.set_attribute("messenger.job.outcome", "cancelled")
|
||||
self.count("cancelled", begin)
|
||||
await self.settle(asyncio.shield(message.nack(requeue=True)))
|
||||
raise
|
||||
span.set_attribute("messenger.job.outcome", outcome)
|
||||
if outcome in ("failed", "retry", "fenced"):
|
||||
telemetry.mark_error(span, outcome)
|
||||
self.count(outcome, begin)
|
||||
log.info("job_done", extra={"fields": {"job_id": body["job_id"], "outcome": outcome,
|
||||
"message_attempt": body["attempt"],
|
||||
"redelivered": message.redelivered}})
|
||||
await self.settle(message.ack())
|
||||
|
||||
@staticmethod
|
||||
def count(outcome: str, begin: float) -> None:
|
||||
"""messenger.jobs.processed + messenger.job.duration of one delivery (outcome: a fixed set:
|
||||
succeeded, retry, failed, fenced, superseded, released, deferred, cancelled, rejected, noop_*)."""
|
||||
attributes = {"messenger.job.type": broker.JOB_TYPE, "outcome": outcome}
|
||||
telemetry.jobs_processed.add(1, attributes)
|
||||
telemetry.job_duration.record(time.perf_counter() - begin, attributes)
|
||||
|
||||
# ---------------------------------------------------------------- one attempt
|
||||
async def process(self, job_id: str) -> str:
|
||||
settings = self.settings
|
||||
claim = await self.db.run(lambda c: jobs.claim(c, job_id, self.name, settings.job_lease_seconds),
|
||||
op="jobs.claim")
|
||||
if isinstance(claim, jobs.Noop):
|
||||
return "noop_" + claim.reason
|
||||
span = telemetry.trace.get_current_span()
|
||||
span.set_attribute("messenger.job.attempt", claim.attempt)
|
||||
span.set_attribute("messenger.job.kind", claim.kind)
|
||||
span.set_attribute("messenger.job.source", claim.source)
|
||||
await service.crash_once(settings, self.db, "crash_after_claim", job_id, self.actor)
|
||||
lost = asyncio.Event()
|
||||
work = asyncio.create_task(self.attempt(claim))
|
||||
beat = asyncio.create_task(self.heartbeat(claim, work, lost))
|
||||
try:
|
||||
variants = await work
|
||||
except asyncio.CancelledError:
|
||||
if lost.is_set() and not asyncio.current_task().cancelling():
|
||||
return "fenced" # lease taken over: this attempt may write nothing more
|
||||
outcome = await asyncio.shield(self.db.run(lambda c: jobs.release(c, claim, self.name), op="jobs.release"))
|
||||
log.info("job_released", extra={"fields": {"job_id": job_id, "outcome": outcome}})
|
||||
raise
|
||||
except ProcessingError as exc:
|
||||
return await self.failed(claim, exc.code, exc.permanent)
|
||||
except Unavailable:
|
||||
return await self.failed(claim, "storage_unavailable", False)
|
||||
finally:
|
||||
beat.cancel()
|
||||
await service.crash_once(settings, self.db, "crash_after_s3_write", job_id, self.actor)
|
||||
outcome = await self.db.run(lambda c: jobs.complete(c, claim, variants, self.name), op="jobs.complete")
|
||||
if outcome == "succeeded" and claim.kind == "upload" and claim.accepted_at is not None:
|
||||
# Lab 6 SLI "time to ready": durable acceptance (job COMMIT before the 202) -> ready COMMIT.
|
||||
telemetry.time_to_ready.record(max(0.0, time.time() - claim.accepted_at.timestamp()),
|
||||
{"messenger.job.kind": claim.kind})
|
||||
await service.crash_once(settings, self.db, "crash_after_commit", job_id, self.actor)
|
||||
if outcome == "succeeded":
|
||||
await self.delete_staging(claim.attachment_id)
|
||||
return outcome
|
||||
|
||||
async def failed(self, claim: jobs.Claim, code: str, permanent: bool) -> str:
|
||||
s = self.settings
|
||||
outcome, delay = await self.db.run(
|
||||
lambda c: jobs.retry_or_fail(c, claim, code, permanent, self.name, s.job_retry_base_seconds,
|
||||
s.job_retry_max_seconds), op="jobs.retry_or_fail")
|
||||
telemetry.trace.get_current_span().set_attribute("messenger.job.error_code", code)
|
||||
log.info("attempt_failed", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt, "code": code,
|
||||
"permanent": permanent, "outcome": outcome,
|
||||
"delay_s": round(delay, 3)}})
|
||||
return outcome
|
||||
|
||||
async def heartbeat(self, claim: jobs.Claim, work: asyncio.Task, lost: asyncio.Event) -> None:
|
||||
"""Renew the lease while the attempt is alive and within JOB_TIMEOUT_SECONDS. A hung attempt
|
||||
stops being renewed, so the reaper can hand the job to another worker; if the lease turns out
|
||||
to be lost, the attempt is cancelled (its result would be fenced anyway)."""
|
||||
s = self.settings
|
||||
if "hang" in s.fault_points:
|
||||
return # experiment: a hung worker that no longer heartbeats
|
||||
started = time.monotonic()
|
||||
while True:
|
||||
await asyncio.sleep(s.job_lease_seconds / 3)
|
||||
if time.monotonic() - started > s.job_timeout_seconds:
|
||||
return
|
||||
try:
|
||||
alive = await self.db.run(lambda c: jobs.heartbeat(c, claim, s.job_lease_seconds), op="jobs.heartbeat")
|
||||
except Unavailable:
|
||||
continue # the lease may expire meanwhile; the fence protects the result
|
||||
if not alive:
|
||||
log.warning("lease_lost", extra={"fields": {"job_id": claim.job_id, "attempt": claim.attempt}})
|
||||
lost.set()
|
||||
work.cancel()
|
||||
return
|
||||
|
||||
async def attempt(self, claim: jobs.Claim) -> list[imaging.Rendered]:
|
||||
s = self.settings
|
||||
if "hang" in s.fault_points:
|
||||
await asyncio.sleep(s.fault_value("hang", 3600)) # stuck outside of the time limit
|
||||
try:
|
||||
return await asyncio.wait_for(self.build(claim), s.job_timeout_seconds)
|
||||
except asyncio.TimeoutError:
|
||||
raise ProcessingError("processing_timeout", permanent=False) from None
|
||||
|
||||
async def build(self, claim: jobs.Claim) -> list[imaging.Rendered]:
|
||||
s = self.settings
|
||||
started = time.monotonic()
|
||||
if claim.size_bytes > s.max_upload_bytes:
|
||||
raise ProcessingError("image_too_large", permanent=True)
|
||||
source = self.staging if claim.source == "staging" else self.final
|
||||
try:
|
||||
data = await source.read_all(claim.source_key, limit=s.max_upload_bytes)
|
||||
except ObjectMissing:
|
||||
raise ProcessingError("source_missing", permanent=True) from None
|
||||
if len(data) != claim.size_bytes or hashlib.sha256(data).digest() != claim.sha256:
|
||||
raise ProcessingError("source_corrupt", permanent=True)
|
||||
self.injected(claim)
|
||||
if "slow" in s.fault_points and s.fault_value("slow_pipeline", claim.pipeline_version) == claim.pipeline_version:
|
||||
await asyncio.sleep(s.fault_value("slow", 10))
|
||||
remaining = max(1.0, s.job_timeout_seconds - (time.monotonic() - started))
|
||||
with telemetry.child_span("image render", {"messenger.image.content_type": claim.content_type,
|
||||
"messenger.image.size_bytes": claim.size_bytes}) as span:
|
||||
variants = await imaging.render(data, claim.content_type, claim.pipeline_version,
|
||||
max_pixels=s.max_image_pixels, timeout=remaining,
|
||||
memory_mb=s.image_max_memory_mb)
|
||||
if span is not None:
|
||||
span.set_attribute("messenger.image.variants", [v.name for v in variants])
|
||||
meta = {"attachment-id": claim.attachment_id, "pipeline-version": str(claim.pipeline_version)}
|
||||
puts = [self.final.put(claim.key(v.name), v.data, v.content_type, meta) for v in variants]
|
||||
if claim.write_original:
|
||||
puts.append(self.final.put(claim.key("original"), data, claim.content_type,
|
||||
{**meta, "sha256": claim.sha256.hex()}))
|
||||
await asyncio.gather(*puts)
|
||||
return variants
|
||||
|
||||
def injected(self, claim: jobs.Claim) -> None:
|
||||
s = self.settings
|
||||
if "permanent_error" in s.fault_points:
|
||||
raise ProcessingError("invalid_image", permanent=True)
|
||||
if "transient_error" in s.fault_points and claim.attempt <= s.fault_value("transient_error", 1000):
|
||||
raise ProcessingError("injected_transient", permanent=False)
|
||||
|
||||
# ---------------------------------------------------------------- cleanup
|
||||
async def delete_staging(self, attachment_id: str) -> None:
|
||||
"""Mark `deleting` under the row lock (re-checked there), then S3 DELETE, then `deleted`."""
|
||||
try:
|
||||
key = await self.db.run(
|
||||
lambda c: jobs.mark_staging_deleting(c, attachment_id, self.settings.staging_retention_seconds))
|
||||
if key is None:
|
||||
return
|
||||
await self.staging.delete(key)
|
||||
await self.db.run(lambda c: jobs.mark_staging_deleted(c, attachment_id))
|
||||
log.info("staging_deleted", extra={"fields": {"attachment_id": attachment_id}})
|
||||
except Unavailable:
|
||||
pass # stays present/deleting; the next cleanup pass repeats (DELETE is idempotent)
|
||||
|
||||
async def cleanup(self) -> None:
|
||||
s = self.settings
|
||||
ids = await self.db.run(lambda c: jobs.staging_to_delete(c, s.staging_retention_seconds))
|
||||
tokens = await self.db.run(lambda c: jobs.attempts_to_clean(c, s.orphan_grace_seconds))
|
||||
if "pause_cleanup" in s.fault_points and (ids or tokens):
|
||||
# Experiment: the race "cleanup read its candidates -> replay commits -> cleanup goes on".
|
||||
log.warning("cleanup_paused", extra={"fields": {"attachments": ids, "attempts": tokens}})
|
||||
await asyncio.sleep(s.fault_value("pause_cleanup", 10))
|
||||
for attachment_id in ids:
|
||||
await self.delete_staging(attachment_id)
|
||||
for token in tokens:
|
||||
keys = await self.db.run(lambda c: jobs.lock_attempt_for_cleanup(c, token))
|
||||
if keys is None:
|
||||
continue
|
||||
await asyncio.gather(*(self.final.delete(k) for k in keys))
|
||||
await self.db.run(lambda c: jobs.mark_attempt_cleaned(c, token))
|
||||
log.info("attempt_objects_deleted", extra={"fields": {"token": token, "objects": len(keys)}})
|
||||
|
||||
async def cleanup_loop(self, stop: asyncio.Event) -> None:
|
||||
while not stop.is_set() and self.settings.cleanup_interval_seconds > 0:
|
||||
await service.sleep_or_stop(stop, self.settings.cleanup_interval_seconds)
|
||||
try:
|
||||
await self.cleanup()
|
||||
except Unavailable:
|
||||
pass
|
||||
|
||||
# ---------------------------------------------------------------- lifecycle
|
||||
async def run(self) -> int:
|
||||
stop = service.stop_event()
|
||||
telemetry.observe("messenger.worker.capacity", "{job}", "WORKER_CONCURRENCY: attempts one worker runs at once",
|
||||
lambda: [(self.settings.worker_concurrency, {})])
|
||||
telemetry.observe_pool(self.db.pool, self.db.name)
|
||||
await self.db.open()
|
||||
await self.staging.open()
|
||||
await self.final.open()
|
||||
cleaner = asyncio.create_task(self.cleanup_loop(stop))
|
||||
try:
|
||||
while not stop.is_set():
|
||||
if not self.connected():
|
||||
await self.disconnect()
|
||||
try:
|
||||
await self.connect()
|
||||
except Exception as exc: # noqa: BLE001 - broker down: retry in 2 s, never crash
|
||||
log.warning("broker_unavailable", extra={"fields": {"error": type(exc).__name__}})
|
||||
await self.disconnect()
|
||||
if self.connected():
|
||||
service.beat() # healthy only while a consumer is really attached
|
||||
await service.sleep_or_stop(stop, 2.0)
|
||||
await self.shutdown()
|
||||
finally:
|
||||
cleaner.cancel()
|
||||
await self.disconnect()
|
||||
await self.final.close()
|
||||
await self.staging.close()
|
||||
await self.db.close()
|
||||
log.info("worker_stopped")
|
||||
return 0
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
"""Stop consuming; running attempts get WORKER_SHUTDOWN_SECONDS, the rest is released."""
|
||||
if self.queue is not None and self.consumer_tag is not None:
|
||||
try:
|
||||
await self.queue.cancel(self.consumer_tag)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
pending = set(self.tasks)
|
||||
log.info("worker_draining", extra={"fields": {"in_flight": len(pending)}})
|
||||
if pending:
|
||||
_, pending = await asyncio.wait(pending, timeout=self.settings.worker_shutdown_seconds)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
if pending:
|
||||
await asyncio.wait(pending, timeout=10)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
settings = Settings.from_env()
|
||||
if not settings.broker_url:
|
||||
raise ConfigError("BROKER_URL_FILE (or BROKER_URL) must be set")
|
||||
except ConfigError as exc:
|
||||
print(f"configuration error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
logging_setup.configure(settings.log_level)
|
||||
telemetry.setup("messenger-worker", settings.instance_id, __version__)
|
||||
log.info("worker_starting", extra={"fields": {
|
||||
"instance_id": settings.instance_id, "concurrency": settings.worker_concurrency,
|
||||
"max_attempts": settings.job_max_attempts, "timeout_s": settings.job_timeout_seconds,
|
||||
"lease_s": settings.job_lease_seconds, "memory_mb": settings.image_max_memory_mb,
|
||||
"fault_points": sorted(settings.fault_points)}})
|
||||
try:
|
||||
return asyncio.run(Worker(settings).run())
|
||||
finally:
|
||||
telemetry.shutdown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user