diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9c07226 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.11.9-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + PYTHONPATH=/app + +WORKDIR /app + +COPY requirements.txt . +RUN pip install -r requirements.txt + +COPY main.py . +COPY app ./app +COPY scripts ./scripts + +RUN useradd --system --uid 10001 --no-create-home --shell /usr/sbin/nologin appuser +USER 10001 + +# 8443 — mTLS-вход от LB (relay), 8081 — внутренний health-listener, +# 8080 — uvicorn только на loopback (не покидает контейнер). +EXPOSE 8443 + +CMD ["python", "-m", "app.server"] diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/attachments.py b/app/attachments.py new file mode 100644 index 0000000..19aa466 --- /dev/null +++ b/app/attachments.py @@ -0,0 +1,139 @@ +"""lab5: API только принимает staging + пишет job. Ресайз ушёл в worker.""" +import hashlib +import io +import logging +import uuid + +from PIL import Image, UnidentifiedImageError + +from . import config, db, jobs, repo, s3 +from .errors import ApiError, bad_request, not_found + +log = logging.getLogger("attachments") + +ALLOWED_FORMATS = {"PNG": "image/png", "JPEG": "image/jpeg"} +Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS + + +def validate_filename(filename): + if not isinstance(filename, str) or not (1 <= len(filename) <= 255): + raise bad_request("Некорректное имя файла") + for c in filename: + if c in ("/", "\\", "\x00") or ord(c) < 0x20 or ord(c) == 0x7F: + raise bad_request("Недопустимое имя файла") + return filename + + +def inspect_image_header(fileobj, total_bytes): + """Только заголовок: формат и размеры. Полное декодирование — в worker. + + load() в API не вызываем — дорого и не нужно для 202. + """ + if total_bytes == 0: + raise bad_request("Пустой файл") + if total_bytes > config.MAX_UPLOAD_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + fileobj.seek(0) + try: + with Image.open(fileobj) as img: + fmt = img.format + width, height = img.size + except UnidentifiedImageError: + raise ApiError(415, "unsupported_media_type", "Неизвестный формат изображения") + except Image.DecompressionBombError: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + finally: + fileobj.seek(0) + + if fmt not in ALLOWED_FORMATS: + raise ApiError(415, "unsupported_media_type", "Ожидается PNG или JPEG") + if width <= 0 or height <= 0: + raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") + if width * height > config.MAX_IMAGE_PIXELS: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + return ALLOWED_FORMATS[fmt] + + +def upload_to_staging(chat_id, owner_id, filename, fileobj, total_bytes, digest, content_type): + """POST /attachments: staging в S3 → INSERT attachments(queued) + job + outbox → 202.""" + validate_filename(filename) + staging_key = "staging/%s/%s" % (chat_id, uuid.uuid4().hex) + + with db.connection() as conn: + if not repo.is_member(conn, chat_id, owner_id): + raise not_found() + + # 1. staging в S3 — до INSERT, чтобы не было queued без байтов. + try: + fileobj.seek(0) + s3.put_object(staging_key, fileobj, content_type, content_length=total_bytes) + except Exception as exc: + log.warning("staging PUT failed: %s", type(exc).__name__) + raise ApiError(503, "unavailable", "Хранилище временно недоступно") + + # 2. Одна транзакция: attachments + job + outbox. + try: + with db.connection() as conn: + row = repo.insert_attachment_queued( + conn, chat_id, owner_id, filename, content_type, + total_bytes, digest, staging_key) + jobs.create_job_for_attachment(conn, row["id"], config.PIPELINE_VERSION) + except Exception: + # Компенсация: удалить staging, чтобы не оставить orphan. + s3.delete_object(staging_key) + raise + + # 3. Публикуем outbox сразу — если брокер жив, latency короче. + # Если упадёт — worker или API-поток подхватит на следующей итерации. + try: + with db.connection() as conn: + jobs.publish_pending_outbox(conn, _broker_publish) + except Exception: + log.warning("inline outbox publish failed, будет повторено") + + return row + + +def _broker_publish(payload, headers=None): + from . import broker + broker.publish(payload, headers) + + +def download_original(attachment_id, user_id): + with db.connection() as conn: + row = repo.get_attachment_for_member(conn, attachment_id, user_id) + if row is None: + raise not_found() + if row["status"] in ("queued", "processing"): + raise ApiError(409, "conflict", "Вложение ещё не готово") + if row["status"] == "failed": + raise ApiError(409, "conflict", "Вложение недоступно") + if not row["object_key"]: + raise ApiError(409, "conflict", "Вложение ещё не готово") + try: + body = s3.get_object(row["object_key"]) + except Exception as exc: + log.warning("S3 GET original failed: %s", type(exc).__name__) + raise ApiError(503, "unavailable", "Хранилище временно недоступно") + return row, body + + +def download_variant(attachment_id, user_id, variant_name): + with db.connection() as conn: + row = repo.get_attachment_for_member(conn, attachment_id, user_id) + if row is None: + raise not_found() + if row["status"] in ("queued", "processing"): + raise ApiError(409, "conflict", "Вложение ещё не готово") + if row["status"] == "failed": + raise ApiError(409, "conflict", "Вложение недоступно") + with db.connection() as conn: + v = repo.get_variant(conn, attachment_id, variant_name) + if v is None: + raise not_found() + try: + body = s3.get_object(v["object_key"]) + except Exception as exc: + log.warning("S3 GET variant failed: %s", type(exc).__name__) + raise ApiError(503, "unavailable", "Хранилище временно недоступно") + return v, body \ No newline at end of file diff --git a/app/broker.py b/app/broker.py new file mode 100644 index 0000000..43f3389 --- /dev/null +++ b/app/broker.py @@ -0,0 +1,124 @@ +"""RabbitMQ: обязательный TLS + EXTERNAL-аутентификация по клиентскому сертификату. + +Identity = CN сертификата (messenger-api / messenger-worker). Права выданы +раздельно и ограничены topology лаборатории (см. infra/rabbitmq/init.sh). + +Topology: + exchange: lab5 (direct, durable) + routing_key: attachment.process.v1 → queue attachment.process.v1 (durable) + DLX: lab5.dlx (direct) + routing_key: attachment.failed → queue attachment.failed (durable) +""" +import json +import logging +import ssl +import threading + +import pika + +from . import config + +log = logging.getLogger("broker") + +EXCHANGE = "lab5" +DLX = "lab5.dlx" +QUEUE = "attachment.process.v1" +FAILED_QUEUE = "attachment.failed" + +_lock = threading.Lock() +_channel = None + + +def _ssl_context(): + ctx = ssl.create_default_context(cafile=config.BROKER_CA) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.load_cert_chain(config.BROKER_CERT, config.BROKER_KEY) + return ctx + + +def _connect(): + # Внешний механизм EXTERNAL: пароля нет, identity берётся из сертификата. + # server_hostname включает проверку имени (SAN/CN) сервера. + return pika.BlockingConnection(pika.ConnectionParameters( + host=config.BROKER_HOST, + port=config.BROKER_PORT, + virtual_host=config.BROKER_VHOST, + credentials=pika.ExternalCredentials(), + ssl_options=pika.SSLOptions(_ssl_context(), server_hostname=config.BROKER_HOST), + heartbeat=30, + blocked_connection_timeout=30, + connection_attempts=1, + socket_timeout=5, + )) + + +def get_channel(): + """Один канал на процесс; worker также использует для consume.""" + global _channel + if _channel is None or _channel.is_closed: + with _lock: + if _channel is None or _channel.is_closed: + ch = _connect().channel() + ch.exchange_declare(EXCHANGE, exchange_type="direct", durable=True) + ch.exchange_declare(DLX, exchange_type="direct", durable=True) + ch.queue_declare( + QUEUE, durable=True, + arguments={"x-dead-letter-exchange": DLX, + "x-dead-letter-routing-key": "attachment.failed"}) + ch.queue_declare(FAILED_QUEUE, durable=True) + ch.queue_bind(QUEUE, EXCHANGE, routing_key=QUEUE) + ch.queue_bind(FAILED_QUEUE, DLX, routing_key="attachment.failed") + _channel = ch + return _channel + + +def publish(job_payload, headers=None): + """Publish с publisher confirm. + + headers — сохранённый в outbox W3C-контекст создания задачи; если не задан, + инжектится контекст текущего span. Так API → broker → worker остаются в + одной трассе даже когда публикация происходит в фоновом outbox-цикле. + """ + from . import telemetry # noqa: PLC0415 - избегаем цикла импортов + ch = get_channel() + ch.confirm_delivery() + body = json.dumps(job_payload, separators=(",", ":")).encode("utf-8") + carrier = dict(headers or {}) + if not carrier: + telemetry.inject_headers(carrier) + ch.basic_publish( + exchange=EXCHANGE, + routing_key=QUEUE, + body=body, + properties=pika.BasicProperties( + content_type="application/json", + delivery_mode=2, + message_id=job_payload["job_id"], + headers=carrier or None, + ), + mandatory=True, + ) + + +def declare_only(): + get_channel() + + +def wait_ready(timeout=30): + import time + + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + try: + conn = _connect() + try: + conn.channel().queue_declare(QUEUE, passive=True) + return True + finally: + conn.close() + except Exception as exc: # noqa: BLE001 - readiness probe + last = exc + time.sleep(0.5) + log.warning("broker not ready: %s", type(last).__name__ if last else "timeout") + return False diff --git a/app/cache.py b/app/cache.py new file mode 100644 index 0000000..eff9b5f --- /dev/null +++ b/app/cache.py @@ -0,0 +1,52 @@ +"""Тонкая обёртка над Redis/Valkey.""" +import logging +import threading +import time + +import redis + +from . import config + +log = logging.getLogger("cache") +_client = None +_down_until = 0.0 +_lock = threading.Lock() + + +def _get_client(): + global _client + if not config.CACHE_URL: + return None + if _client is None: + with _lock: + if _client is None: + _client = redis.Redis.from_url( + config.CACHE_URL, socket_timeout=config.CACHE_TIMEOUT, + socket_connect_timeout=config.CACHE_TIMEOUT, max_connections=20, + decode_responses=True, retry_on_timeout=False) + return _client + + +def _call(fn): + global _down_until + client = _get_client() + if client is None or time.monotonic() < _down_until: + return None + try: + return fn(client) + except redis.RedisError as exc: + _down_until = time.monotonic() + config.CACHE_BACKOFF + log.warning("cache unavailable (%s); bypassing for %.0fs", type(exc).__name__, config.CACHE_BACKOFF) + return None + + +def get(key): + return _call(lambda c: c.get(key)) + + +def set_if_absent(key, value, ttl_ms): + return _call(lambda c: c.set(key, value, nx=True, px=ttl_ms)) + + +def set_always(key, value, ttl_ms): + return _call(lambda c: c.set(key, value, px=ttl_ms)) \ No newline at end of file diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..70b1b93 --- /dev/null +++ b/app/config.py @@ -0,0 +1,130 @@ +"""Конфигурация lab7. + +Не-секретные значения берутся из окружения. Секреты (DATABASE_URL, ключи S3) +приложение получает из OpenBao через AppRole в app/secrets.py — в образе и в Git +их нет. Одноразовые сервисы (migrate, db-init) читают URL через *_FILE. +""" +import os +import socket +from pathlib import Path + + +def _read(name): + path = os.environ.get(name + "_FILE") + if path: + try: + return Path(path).read_text(encoding="utf-8").strip() + except OSError: + return None + return os.environ.get(name) or None + + +def _int(name, default, low, high): + value = int(os.environ.get(name, default)) + if not low <= value <= high: + raise ValueError("%s must be in %d..%d" % (name, low, high)) + return value + + +def _float(name, default): + return float(os.environ.get(name, default)) + + +def _bool(name, default="false"): + return os.environ.get(name, default).lower() == "true" + + +SERVICE = os.environ.get("APP_SERVICE", "messenger-api") +APP_HOST = "127.0.0.1" # uvicorn: только loopback +APP_PORT = _int("APP_PORT", 8080, 1, 65535) # loopback, за mTLS-relay +PUBLIC_PORT = _int("PUBLIC_PORT", 8443, 1, 65535) # mTLS-relay, доступен LB +HEALTH_PORT = _int("HEALTH_PORT", 8081, 1, 65535) # внутренний health, loopback +APP_ENV = os.environ.get("APP_ENV", "lab") +INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname() + +# ---------- TLS-материал (docker secrets, read-only) ---------- +SECRETS_DIR = os.environ.get("SECRETS_DIR", "/run/secrets") +TLS_CA_SERVERS = os.environ.get("TLS_CA_SERVERS", SECRETS_DIR + "/ca_servers") +TLS_CA_CLIENTS = os.environ.get("TLS_CA_CLIENTS", SECRETS_DIR + "/ca_clients") +API_TLS_CERT = os.environ.get("API_TLS_CERT", SECRETS_DIR + "/api_server_crt") +API_TLS_KEY = os.environ.get("API_TLS_KEY", SECRETS_DIR + "/api_server_key") +API_IDENTITIES_FILE = os.environ.get("API_IDENTITIES_FILE", SECRETS_DIR + "/identity_allowlist") +OTEL_CA = os.environ.get("OTEL_CLIENT_CA", TLS_CA_SERVERS) +OTEL_CLIENT_CERT = os.environ.get("OTEL_CLIENT_CERT", SECRETS_DIR + "/api_client_crt") +OTEL_CLIENT_KEY = os.environ.get("OTEL_CLIENT_KEY", SECRETS_DIR + "/api_client_key") + +# ---------- сессии ---------- +SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600, 300, 30 * 24 * 3600) + +# ---------- PostgreSQL ---------- +# Значение приходит из OpenBao (app/secrets.py) для api/worker. +# Для одноразовых сервисов — DATABASE_URL_FILE. +DATABASE_URL = _read("DATABASE_URL") +DB_POOL_MIN = _int("DB_POOL_MIN", 1, 0, 50) +DB_POOL_MAX = _int("DB_POOL_MAX", 16, 1, 50) +DB_POOL_TIMEOUT = _float("DB_POOL_TIMEOUT", 3.0) +DB_STATEMENT_TIMEOUT_MS = _int("DB_STATEMENT_TIMEOUT_MS", 5000, 100, 60000) + +# ---------- Argon2id ---------- +# OWASP: m>=19 MiB, t>=2, p>=1. Значения и замер — в REPORT.md. +ARGON2_MEMORY_KIB = _int("ARGON2_MEMORY_KIB", 19456, 8192, 1048576) +ARGON2_TIME_COST = _int("ARGON2_TIME_COST", 2, 1, 10) +ARGON2_PARALLELISM = _int("ARGON2_PARALLELISM", 1, 1, 4) +HASH_CONCURRENCY = _int("HASH_CONCURRENCY", 4, 1, 32) +HASH_SLOT_TIMEOUT = _float("HASH_SLOT_TIMEOUT", 5.0) + +# ---------- Ограничение частоты входа (общее для реплик: состояние в PostgreSQL) ---------- +LOGIN_RATE_WINDOW_SECONDS = _int("LOGIN_RATE_WINDOW_SECONDS", 60, 10, 3600) +LOGIN_RATE_IP_PER_WINDOW = _int("LOGIN_RATE_IP_PER_WINDOW", 20, 1, 10000) +LOGIN_RATE_USER_PER_WINDOW = _int("LOGIN_RATE_USER_PER_WINDOW", 30, 1, 10000) + +# ---------- лимиты запросов ---------- +MAX_BODY_BYTES = 64 * 1024 +MAX_UPLOAD_BYTES = _int("MAX_UPLOAD_BYTES", 10485760, 1, 10485760) +MAX_IMAGE_PIXELS = _int("MAX_IMAGE_PIXELS", 40000000, 1, 40000000) +THREAD_LIMIT = _int("THREAD_LIMIT", 24, 1, 200) +IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400, 60, 86400 * 7) + +# ---------- S3 (ключи приходят из OpenBao) ---------- +S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "https://minio:9000") +S3_REGION = os.environ.get("S3_REGION", "us-east-1") +S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments") +S3_VERIFY = os.environ.get("S3_VERIFY", TLS_CA_SERVERS) +S3_ACCESS_KEY_ID = None +S3_SECRET_ACCESS_KEY = None +S3_CONNECT_TIMEOUT = _float("S3_CONNECT_TIMEOUT", 3.0) +S3_READ_TIMEOUT = _float("S3_READ_TIMEOUT", 30.0) +S3_ORPHAN_GRACE_SECONDS = _int("S3_ORPHAN_GRACE_SECONDS", 3600, 60, 7 * 24 * 3600) + +# ---------- брокер: TLS + EXTERNAL (сертификат = identity) ---------- +BROKER_HOST = os.environ.get("BROKER_HOST", "rabbitmq") +BROKER_PORT = _int("BROKER_PORT", 5671, 1, 65535) +BROKER_VHOST = os.environ.get("BROKER_VHOST", "/") +BROKER_CA = os.environ.get("BROKER_CA", TLS_CA_SERVERS) +BROKER_CERT = os.environ.get("BROKER_CLIENT_CERT", SECRETS_DIR + "/api_client_crt") +BROKER_KEY = os.environ.get("BROKER_CLIENT_KEY", SECRETS_DIR + "/api_client_key") + +# ---------- фоновая обработка ---------- +WORKER_CONCURRENCY = _int("WORKER_CONCURRENCY", 2, 1, 32) +JOB_MAX_ATTEMPTS = _int("JOB_MAX_ATTEMPTS", 5, 1, 100) +JOB_TIMEOUT_SECONDS = _int("JOB_TIMEOUT_SECONDS", 60, 10, 3600) +STAGING_RETENTION_SECONDS = _int("STAGING_RETENTION_SECONDS", 86400, 60, 30 * 24 * 3600) +PIPELINE_VERSION = _int("PIPELINE_VERSION", 1, 1, 100) + +# ---------- OpenBao ---------- +OPENBAO_ADDR = os.environ.get("OPENBAO_ADDR", "https://openbao:8200") +OPENBAO_CA = os.environ.get("OPENBAO_CA", TLS_CA_SERVERS) +OPENBAO_ROLE = os.environ.get("OPENBAO_ROLE", "api") +OPENBAO_ROLE_ID_FILE = os.environ.get( + "OPENBAO_ROLE_ID_FILE", SECRETS_DIR + "/openbao_role_id_" + OPENBAO_ROLE) +OPENBAO_SECRET_ID_FILE = os.environ.get( + "OPENBAO_SECRET_ID_FILE", SECRETS_DIR + "/openbao_secret_id_" + OPENBAO_ROLE) +OPENBAO_KV_PATH = os.environ.get("OPENBAO_KV_PATH", "secret/data/messenger/" + OPENBAO_ROLE) +OPENBAO_WAIT_SECONDS = _int("OPENBAO_WAIT_SECONDS", 300, 1, 3600) +OPENBAO_TIMEOUT = _float("OPENBAO_TIMEOUT", 5.0) +OPENBAO_RENEW_INTERVAL_SECONDS = _int("OPENBAO_RENEW_INTERVAL_SECONDS", 300, 30, 3600) + +# ---------- OTel ---------- +OTEL_ENABLED = not _bool("OTEL_SDK_DISABLED") +OTEL_ENDPOINT = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "https://ingress:4318") +OTEL_SERVICE_VERSION = os.environ.get("OTEL_SERVICE_VERSION", "1.7.0") diff --git a/app/cursor.py b/app/cursor.py new file mode 100644 index 0000000..9fa0f16 --- /dev/null +++ b/app/cursor.py @@ -0,0 +1,27 @@ +"""Непрозрачный keyset-курсор (created_at, id).""" +import base64 +import json +import uuid +from datetime import datetime, timezone + +from .errors import bad_request + + +def encode(kind, scope, created_at, row_id): + payload = {"k": kind, "s": str(scope), "t": created_at.astimezone(timezone.utc).isoformat(), "i": str(row_id)} + return base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).rstrip(b"=").decode() + + +def decode(value, kind, scope): + if not value: + raise bad_request("Некорректный cursor") + try: + raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + payload = json.loads(raw.decode("utf-8")) + created_at = datetime.fromisoformat(payload["t"]) + row_id = uuid.UUID(payload["i"]) + if payload["k"] != kind or payload["s"] != str(scope) or created_at.tzinfo is None: + raise ValueError("scope mismatch") + return created_at, row_id + except (ValueError, KeyError, TypeError, UnicodeDecodeError): + raise bad_request("Некорректный cursor") \ No newline at end of file diff --git a/app/db.py b/app/db.py new file mode 100644 index 0000000..b3349cd --- /dev/null +++ b/app/db.py @@ -0,0 +1,53 @@ +"""Пул соединений PostgreSQL.""" +import threading + +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool, PoolClosed, PoolTimeout + +from . import config + +TRANSIENT = (psycopg.OperationalError, PoolTimeout, PoolClosed, psycopg.errors.QueryCanceled, + psycopg.errors.LockNotAvailable) + +_pool = None +_lock = threading.Lock() + + +def get_pool(): + global _pool + if _pool is None: + with _lock: + if _pool is None: + if not config.DATABASE_URL: + raise RuntimeError("DATABASE_URL(_FILE) is not configured") + options = ("-c statement_timeout=%d -c lock_timeout=3000 " + "-c idle_in_transaction_session_timeout=10000" % config.DB_STATEMENT_TIMEOUT_MS) + pool = ConnectionPool( + config.DATABASE_URL, + min_size=config.DB_POOL_MIN, max_size=config.DB_POOL_MAX, + timeout=config.DB_POOL_TIMEOUT, max_lifetime=1800, max_idle=300, + reconnect_timeout=5, + check=ConnectionPool.check_connection, + kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": options, + "application_name": "messenger-api"}, + open=False) + pool.open(wait=False) + _pool = pool + return _pool + + +def connection(timeout=None): + return get_pool().connection(timeout=timeout) + + +def ping(): + with connection(timeout=1.5) as conn: + conn.execute("SELECT 1") + + +def close(): + global _pool + if _pool is not None: + _pool.close(timeout=5) + _pool = None \ No newline at end of file diff --git a/app/errors.py b/app/errors.py new file mode 100644 index 0000000..29f9526 --- /dev/null +++ b/app/errors.py @@ -0,0 +1,20 @@ +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + super().__init__(message) + self.status, self.code, self.message, self.headers = status, code, message, headers or {} + + +BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} +BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'} + + +def bad_request(message="Некорректный запрос"): + return ApiError(400, "invalid_request", message) + + +def unauthorized(challenge): + return ApiError(401, "unauthorized", "Требуется аутентификация", challenge) + + +def not_found(): + return ApiError(404, "not_found", "Объект не найден") \ No newline at end of file diff --git a/app/health.py b/app/health.py new file mode 100644 index 0000000..1a50c43 --- /dev/null +++ b/app/health.py @@ -0,0 +1,72 @@ +"""Внутренний health-listener на loopback (порт 8081). + +Он изолирован: не публикуется, не проксируется LB и не даёт доступа к бизнес-API. +Нужен docker healthcheck и сценарию `stop-one`, чтобы не открывать health-путь +через mTLS-вход. +""" +import json +import logging +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from . import broker, config, db, s3 + +log = logging.getLogger("health") + + +def _readiness(): + checks = {} + try: + db.ping() + checks["database"] = True + except Exception as exc: # noqa: BLE001 - health must not raise + checks["database"] = False + log.warning("readiness: database %s", type(exc).__name__) + try: + s3.ping() + checks["s3"] = True + except Exception as exc: # noqa: BLE001 + checks["s3"] = False + log.warning("readiness: s3 %s", type(exc).__name__) + try: + checks["broker"] = bool(broker.wait_ready(timeout=1)) + except Exception as exc: # noqa: BLE001 + checks["broker"] = False + log.warning("readiness: broker %s", type(exc).__name__) + return all(checks.values()), checks + + +class Handler(BaseHTTPRequestHandler): + server_version = "messenger-health" + sys_version = "" + + def do_GET(self): # noqa: N802 - BaseHTTPRequestHandler API + if self.path.startswith("/health/live"): + self._send(200, {"status": "ok"}) + elif self.path.startswith("/health/ready"): + ready, checks = _readiness() + self._send(200 if ready else 503, {"status": "ok" if ready else "unavailable", "checks": checks}) + else: + self._send(404, {"error": "not_found"}) + + def _send(self, status, payload): + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def log_message(self, fmt, *args): # noqa: A003 - silence per-request noise + return + + +def start(): + """Поднимает health-listener в фоновом потоке (не блокирует uvicorn).""" + server = ThreadingHTTPServer(("127.0.0.1", config.HEALTH_PORT), Handler) + server.daemon_threads = True + log.info("health listener on 127.0.0.1:%d", config.HEALTH_PORT) + thread = threading.Thread(target=server.serve_forever, name="health", daemon=True) + thread.start() + return thread diff --git a/app/idempotency.py b/app/idempotency.py new file mode 100644 index 0000000..20bc7da --- /dev/null +++ b/app/idempotency.py @@ -0,0 +1,66 @@ +"""Логика идемпотентности для POST запросов.""" +import hashlib +import json +import re + +from .errors import ApiError, bad_request + +# Контракт: ASCII [A-Za-z0-9._:-]{1,128} +_IDEM_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}") + + +def get_request_hash(data: dict) -> str: + """Хеш тела, независимый от порядка ключей. + + Отсутствующий attachment_ids семантически равен [] — нормализуем, + иначе {"text":"x"} и {"text":"x","attachment_ids":[]} дают разные хеши. + """ + normalized = dict(data) + normalized.setdefault("attachment_ids", []) + return hashlib.sha256(json.dumps(normalized, sort_keys=True).encode("utf-8")).hexdigest() + + +def check_and_lock(conn, user_id: str, method: str, path: str, key: str, req_hash: str): + if not key: + raise bad_request("Missing Idempotency-Key") + if not _IDEM_KEY_RE.fullmatch(key): + raise bad_request("Invalid Idempotency-Key format") + + lock_id = f"{user_id}:{method}:{path}:{key}" + conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (lock_id,)) + + row = conn.execute(""" + SELECT request_hash, status_code, response_body + FROM idempotency_keys + WHERE user_id = %s AND method = %s AND path = %s AND key = %s + """, (user_id, method, path, key)).fetchone() + + if row: + if row["request_hash"] != req_hash: + raise ApiError(409, "conflict", "Idempotency-Key conflict: body differs") + if row["status_code"] is not None and row["response_body"] is not None: + return False, json.loads(row["response_body"]) + return True, None + + return True, None + + +def save_result(conn, user_id, method, path, key, req_hash, status_code, response_body): + conn.execute(""" + INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response_body) + VALUES (%s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (user_id, method, path, key) DO UPDATE + SET status_code = EXCLUDED.status_code, response_body = EXCLUDED.response_body + """, (user_id, method, path, key, req_hash, status_code, json.dumps(response_body))) + + +def cleanup(conn, ttl_seconds: int): + conn.execute(""" + DELETE FROM idempotency_keys + WHERE (user_id, method, path, key) IN ( + SELECT user_id, method, path, key + FROM idempotency_keys + WHERE created_at < now() - make_interval(secs => %s) + LIMIT 100 + ) + """, (ttl_seconds,)) \ No newline at end of file diff --git a/app/jobs.py b/app/jobs.py new file mode 100644 index 0000000..3ea33ab --- /dev/null +++ b/app/jobs.py @@ -0,0 +1,180 @@ +"""Репозиторий jobs и outbox + реестр failed + replay. + +lab7: pending-outbox публикация, retry и операторский replay сохраняют +W3C trace context в outbox.headers, поэтому цепочка upload → publish → consume +не рвётся при фоновой публикации и повторе. +""" +import json +import logging +import uuid +from datetime import datetime, timezone + +from . import config, telemetry + +log = logging.getLogger("jobs") + +JOB_TYPE = "attachment.process.v1" + + +def _payload(job_row): + return { + "schema_version": 1, + "job_id": str(job_row["job_id"]), + "type": job_row["type"], + "attachment_id": str(job_row["attachment_id"]), + "pipeline_version": job_row["pipeline_version"], + "attempt": max(1, int(job_row.get("attempt") or 0)), + "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), + } + + +def _insert_outbox(conn, topic, payload, carrier=None): + conn.execute( + """INSERT INTO outbox (topic, payload, headers) VALUES (%s, %s::jsonb, %s::jsonb)""", + (topic, json.dumps(payload), json.dumps(carrier or {}))) + + +# --- создание задания (API) ---------------------------------------------- + +def create_job_for_attachment(conn, attachment_id, pipeline_version=1): + """INSERT job + INSERT outbox в одной транзакции. + + trace context текущего запроса сохраняется вместе с outbox-строкой: + публикация может произойти позже, в фоновом цикле без активного span. + """ + carrier = telemetry.inject_headers({}) + job = conn.execute( + """INSERT INTO jobs (job_id, attachment_id, pipeline_version, status, max_attempts) + VALUES (%s, %s, %s, 'queued', %s) + ON CONFLICT (attachment_id, pipeline_version) DO NOTHING + RETURNING job_id, attachment_id, pipeline_version, attempt, type""", + (uuid.uuid4(), attachment_id, pipeline_version, config.JOB_MAX_ATTEMPTS)).fetchone() + if job is None: + return None + payload = _payload(job) + _insert_outbox(conn, job["type"], payload, carrier) + return payload + + +# --- outbox publisher ----------------------------------------------------- + +def publish_pending_outbox(conn, publish_fn): + """Публикует неопубликованные outbox-записи. Возвращает число опубликованных.""" + rows = conn.execute( + """SELECT id, topic, payload, headers FROM outbox + WHERE published_at IS NULL AND attempts < 20 + ORDER BY id LIMIT 50 FOR UPDATE SKIP LOCKED""").fetchall() + published = 0 + for row in rows: + payload = row["payload"] if isinstance(row["payload"], dict) else json.loads(row["payload"]) + headers = row["headers"] if isinstance(row["headers"], dict) else json.loads(row["headers"] or "{}") + try: + publish_fn(payload, headers) + except Exception as exc: # noqa: BLE001 - цикл не должен падать + conn.execute( + """UPDATE outbox SET attempts = attempts + 1, last_error = %s WHERE id = %s""", + (type(exc).__name__, row["id"])) + log.warning("outbox %s publish failed: %s", row["id"], type(exc).__name__) + break # брокер, возможно, недоступен + conn.execute( + """UPDATE outbox SET published_at = clock_timestamp() WHERE id = %s""", + (row["id"],)) + published += 1 + return published + + +# --- worker: claim, processing, retry, failed ---------------------------- + +def claim_job(conn, job_id): + """Атомарно переводит queued → processing, выдаёт lease.""" + return conn.execute( + """UPDATE jobs + SET status = 'processing', + attempt = attempt + 1, + lease_until = clock_timestamp() + make_interval(secs => %s), + updated_at = clock_timestamp() + WHERE job_id = %s + AND status = 'queued' + AND (next_attempt_at IS NULL OR next_attempt_at <= clock_timestamp()) + RETURNING job_id, attachment_id, pipeline_version, attempt, max_attempts, type""", + (config.JOB_TIMEOUT_SECONDS, job_id)).fetchone() + + +def mark_ready(conn, job_id): + conn.execute( + """UPDATE jobs SET status = 'ready', error_code = NULL, lease_until = NULL, + updated_at = clock_timestamp() + WHERE job_id = %s""", (job_id,)) + + +def mark_retry(conn, job_id, error_code, backoff_seconds, carrier=None): + """queued с backoff + НОВАЯ outbox-строка. + + Без повторной публикации задача с next_attempt_at не была бы доставлена: + брокер уже получил ack. Поэтому retry = UPDATE jobs + INSERT outbox в одной + транзакции; контекст текущей попытки сохраняется в headers. + """ + row = conn.execute( + """UPDATE jobs + SET status = 'queued', + lease_until = NULL, + next_attempt_at = clock_timestamp() + make_interval(secs => %s), + error_code = %s, + updated_at = clock_timestamp() + WHERE job_id = %s + RETURNING job_id, attachment_id, pipeline_version, attempt, type""", + (backoff_seconds, error_code, job_id)).fetchone() + if row is not None: + _insert_outbox(conn, row["type"], _payload(row), carrier) + return row + + +def mark_failed(conn, job_id, error_code): + conn.execute( + """UPDATE jobs SET status = 'failed', error_code = %s, lease_until = NULL, + updated_at = clock_timestamp() + WHERE job_id = %s""", (error_code, job_id)) + + +def find_expired_leases(conn, limit=50): + return conn.execute( + """SELECT job_id, attachment_id, attempt, max_attempts + FROM jobs + WHERE status = 'processing' AND lease_until < clock_timestamp() + ORDER BY lease_until LIMIT %s + FOR UPDATE SKIP LOCKED""", (limit,)).fetchall() + + +def requeue_expired(conn, row): + if row["attempt"] >= row["max_attempts"]: + mark_failed(conn, row["job_id"], "worker_timeout") + return "failed" + backoff = min(60.0, 2.0 ** row["attempt"]) * (0.5 + 0.5 * (uuid.uuid4().int & 0xFFFF) / 0xFFFF) + mark_retry(conn, row["job_id"], "worker_timeout", backoff) + return "queued" + + +# --- operator replay ------------------------------------------------------ + +def replay_failed(conn, job_id): + """Операторский replay: failed → queued, attempt=0, INSERT outbox.""" + row = conn.execute( + """UPDATE jobs + SET status = 'queued', attempt = 0, error_code = NULL, + lease_until = NULL, next_attempt_at = NULL, updated_at = clock_timestamp() + WHERE job_id = %s AND status = 'failed' + RETURNING job_id, attachment_id, pipeline_version, type""", + (job_id,)).fetchone() + if row is None: + return None + payload = { + "schema_version": 1, + "job_id": str(row["job_id"]), + "type": row["type"], + "attachment_id": str(row["attachment_id"]), + "pipeline_version": row["pipeline_version"], + "attempt": 1, + "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"), + } + _insert_outbox(conn, row["type"], payload) + return payload diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 0000000..18e3575 --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,61 @@ +"""Версионируемые миграции.""" +import hashlib +import logging +import sys +import time +from pathlib import Path + +import psycopg + +from . import config + +LOCK_ID = 727_002_001 +log = logging.getLogger("migrate") + + +def migration_files(): + return sorted((Path(__file__).parent / "migrations").glob("[0-9][0-9][0-9][0-9]_*.sql")) + + +def apply_all(conninfo): + files = migration_files() + with psycopg.connect(conninfo, connect_timeout=3) as conn: + conn.execute("SELECT pg_advisory_xact_lock(%s)", (LOCK_ID,)) + 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()) + done = [] + for path in files: + sql = path.read_text(encoding="utf-8") + checksum = hashlib.sha256(sql.encode()).hexdigest() + if path.stem in applied: + if applied[path.stem] != checksum: + raise RuntimeError("migration %s was modified after being applied" % path.stem) + continue + conn.execute(sql) + conn.execute("INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", (path.stem, checksum)) + done.append(path.stem) + return done + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s") + if not config.DATABASE_URL: + sys.exit("DATABASE_URL(_FILE) is not configured") + deadline = time.monotonic() + 60 + while True: + try: + done = apply_all(config.DATABASE_URL) + break + except psycopg.OperationalError as exc: + if time.monotonic() > deadline: + raise + log.info("database not ready (%s), retrying", type(exc).__name__) + time.sleep(1) + log.info("applied: %s", ", ".join(done) if done else "nothing to do (schema is up to date)") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/app/migrations/0001_core.sql b/app/migrations/0001_core.sql new file mode 100644 index 0000000..10147f3 --- /dev/null +++ b/app/migrations/0001_core.sql @@ -0,0 +1,39 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_by uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100) +); +CREATE INDEX chats_created_at_id_idx ON chats (created_at, id); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + added_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000), + CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id) +); +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); \ No newline at end of file diff --git a/app/migrations/0002_sessions.sql b/app/migrations/0002_sessions.sql new file mode 100644 index 0000000..d34c43d --- /dev/null +++ b/app/migrations/0002_sessions.sql @@ -0,0 +1,10 @@ +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + CONSTRAINT sessions_hash_length CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at) +); +CREATE INDEX sessions_expires_at_idx ON sessions (expires_at); +CREATE INDEX sessions_user_idx ON sessions (user_id); \ No newline at end of file diff --git a/app/migrations/0003_idempotency.sql b/app/migrations/0003_idempotency.sql new file mode 100644 index 0000000..33b2433 --- /dev/null +++ b/app/migrations/0003_idempotency.sql @@ -0,0 +1,13 @@ +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users(id), + method text NOT NULL, + path text NOT NULL, + key text NOT NULL, + request_hash text NOT NULL, + status_code int, + response_body text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (user_id, method, path, key) +); + +CREATE INDEX idempotency_keys_created_at_idx ON idempotency_keys (created_at); \ No newline at end of file diff --git a/app/migrations/0004_attachments.sql b/app/migrations/0004_attachments.sql new file mode 100644 index 0000000..cf74bc5 --- /dev/null +++ b/app/migrations/0004_attachments.sql @@ -0,0 +1,36 @@ +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users (id), + filename text NOT NULL, + content_type text NOT NULL, + size_bytes bigint NOT NULL, + sha256 char(64) NOT NULL, + object_key text NOT NULL, + status text NOT NULL, + error_code text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size_positive CHECK (size_bytes > 0 AND size_bytes <= 10485760), + CONSTRAINT attachments_sha256_format CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_object_key_unique UNIQUE (object_key), + CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready', 'failed')), + CONSTRAINT attachments_error_code CHECK ( + (status = 'ready' AND error_code IS NULL) OR + (status = 'failed' AND error_code IS NOT NULL) OR + (status = 'pending') + ) +); +CREATE INDEX attachments_chat_created_idx ON attachments (chat_id, created_at); +CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending'; + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT, + position int NOT NULL, + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_position CHECK (position >= 0) +); +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); \ No newline at end of file diff --git a/app/migrations/0005_messages_text_allow_empty.sql b/app/migrations/0005_messages_text_allow_empty.sql new file mode 100644 index 0000000..9631602 --- /dev/null +++ b/app/migrations/0005_messages_text_allow_empty.sql @@ -0,0 +1,5 @@ +-- lab4: разрешаем пустой text, если есть вложения. Проверка «text или вложения» +-- делается в приложении, а БД гарантирует только верхнюю границу. +ALTER TABLE messages DROP CONSTRAINT messages_text_length; +ALTER TABLE messages ADD CONSTRAINT messages_text_length + CHECK (char_length(text) BETWEEN 0 AND 4000); \ No newline at end of file diff --git a/app/migrations/0006_jobs_outbox_variants.sql b/app/migrations/0006_jobs_outbox_variants.sql new file mode 100644 index 0000000..b0c5dfa --- /dev/null +++ b/app/migrations/0006_jobs_outbox_variants.sql @@ -0,0 +1,75 @@ +-- lab5: статусы queued/processing, variants, jobs, outbox, staging_key. + +-- 1. Расширяем статусы attachment (было pending/ready/failed). +ALTER TABLE attachments DROP CONSTRAINT attachments_status; +ALTER TABLE attachments ADD CONSTRAINT attachments_status + CHECK (status IN ('queued', 'processing', 'ready', 'failed')); + +-- 2. Существующие pending → queued (совместимость с lab4). +UPDATE attachments SET status = 'queued' WHERE status = 'pending'; + +-- 3. Разделяем staging и финальный объект. +-- object_key = финальный путь (ставит worker после копирования). +-- staging_key = куда API положил байты при upload. +ALTER TABLE attachments ADD COLUMN staging_key text; +ALTER TABLE attachments ALTER COLUMN object_key DROP NOT NULL; +ALTER TABLE attachments ADD CONSTRAINT attachments_ready_has_object + CHECK (status <> 'ready' OR object_key IS NOT NULL); + +-- 4. Варианты (thumbnail, crop, optimized). +CREATE TABLE attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + name text NOT NULL, + object_key text NOT NULL, + content_type text NOT NULL, + size_bytes bigint NOT NULL, + width int NOT NULL, + height int NOT NULL, + sha256 char(64) NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (attachment_id, name), + CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT attachment_variants_size CHECK (size_bytes > 0), + CONSTRAINT attachment_variants_dims CHECK (width > 0 AND height > 0), + CONSTRAINT attachment_variants_sha CHECK (sha256 ~ '^[a-f0-9]{64}$') +); + +-- 5. Jobs: одна логическая работа на (attachment_id, pipeline_version). +-- job_id — стабильный идентификатор; attempt растёт при retry. +-- lease_until защищает от двух воркеров на одной задаче. +CREATE TABLE jobs ( + job_id uuid PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE, + pipeline_version int NOT NULL DEFAULT 1, + type text NOT NULL DEFAULT 'attachment.process.v1', + status text NOT NULL DEFAULT 'queued', + attempt int NOT NULL DEFAULT 0, + max_attempts int NOT NULL DEFAULT 5, + lease_until timestamptz, + next_attempt_at timestamptz, + error_code text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')), + CONSTRAINT jobs_type CHECK (type = 'attachment.process.v1'), + CONSTRAINT jobs_attempt CHECK (attempt >= 0), + CONSTRAINT jobs_max_att CHECK (max_attempts BETWEEN 1 AND 100), + CONSTRAINT jobs_pipeline CHECK (pipeline_version >= 1), + UNIQUE (attachment_id, pipeline_version) +); +CREATE INDEX jobs_claim_idx ON jobs (status, next_attempt_at) WHERE status = 'queued'; +CREATE INDEX jobs_lease_idx ON jobs (lease_until) WHERE status = 'processing'; + +-- 6. Transactional outbox: INSERT в той же транзакции, что и jobs. +-- Отдельный publisher читает непубликованные и подтверждает. +CREATE TABLE outbox ( + id bigserial PRIMARY KEY, + topic text NOT NULL, + payload jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + attempts int NOT NULL DEFAULT 0, + last_error text +); +CREATE INDEX outbox_pending_idx ON outbox (id) WHERE published_at IS NULL; \ No newline at end of file diff --git a/app/migrations/0007_attachments_error_code_fix.sql b/app/migrations/0007_attachments_error_code_fix.sql new file mode 100644 index 0000000..6a6e4bb --- /dev/null +++ b/app/migrations/0007_attachments_error_code_fix.sql @@ -0,0 +1,6 @@ +-- lab5: constraint attachments_error_code должен знать про queued/processing. +-- Идемпотентно: DROP IF EXISTS — можно применять повторно. +ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_error_code; +ALTER TABLE attachments ADD CONSTRAINT attachments_error_code CHECK ( + (status = 'failed') = (error_code IS NOT NULL) +); \ No newline at end of file diff --git a/app/migrations/0008_login_attempts.sql b/app/migrations/0008_login_attempts.sql new file mode 100644 index 0000000..45a9256 --- /dev/null +++ b/app/migrations/0008_login_attempts.sql @@ -0,0 +1,9 @@ +-- lab7: общий для реплик rate limit входа (состояние в PostgreSQL). +CREATE TABLE login_attempts ( + bucket text NOT NULL, + window_start timestamptz NOT NULL, + attempts int NOT NULL, + PRIMARY KEY (bucket, window_start), + CONSTRAINT login_attempts_attempts_positive CHECK (attempts > 0) +); +CREATE INDEX login_attempts_window_idx ON login_attempts (window_start); diff --git a/app/migrations/0009_outbox_headers.sql b/app/migrations/0009_outbox_headers.sql new file mode 100644 index 0000000..aae7d4a --- /dev/null +++ b/app/migrations/0009_outbox_headers.sql @@ -0,0 +1,2 @@ +-- lab7: W3C trace context, сохранённый вместе с outbox-записью. +ALTER TABLE outbox ADD COLUMN IF NOT EXISTS headers jsonb NOT NULL DEFAULT '{}'::jsonb; diff --git a/app/pipeline.py b/app/pipeline.py new file mode 100644 index 0000000..f8cfeaf --- /dev/null +++ b/app/pipeline.py @@ -0,0 +1,99 @@ +"""Обработка изображений: thumbnail 256×256, crop 128×128, optimized WebP.""" +import hashlib +import io +import logging + +from PIL import Image, ImageOps + +from . import config + +log = logging.getLogger("pipeline") + +PIPELINE_VERSION = 1 +Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS + +THUMB_MAX = (256, 256) +CROP_SIDE = 128 +OPT_MAX = (1280, 1280) +OPT_QUALITY = 82 +JPEG_QUALITY = 85 + + +def _open_normalized(data: bytes) -> Image.Image: + """Открывает, применяет EXIF orientation, приводит к RGB с белым фоном для alpha.""" + img = Image.open(io.BytesIO(data)) + img = ImageOps.exif_transpose(img) + if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info): + background = Image.new("RGB", img.size, (255, 255, 255)) + img_rgba = img.convert("RGBA") + background.paste(img_rgba, mask=img_rgba.split()[-1]) + img = background + elif img.mode != "RGB": + img = img.convert("RGB") + img.load() + return img + + +def _encode_jpeg(img: Image.Image) -> bytes: + buf = io.BytesIO() + img.save(buf, format="JPEG", quality=JPEG_QUALITY, optimize=True, progressive=True) + return buf.getvalue() + + +def _encode_webp(img: Image.Image) -> bytes: + buf = io.BytesIO() + img.save(buf, format="WEBP", quality=OPT_QUALITY, method=4) + return buf.getvalue() + + +def _make_thumbnail(img: Image.Image): + thumb = img.copy() + thumb.thumbnail(THUMB_MAX, Image.Resampling.LANCZOS) + if thumb.width < 1 or thumb.height < 1: + raise ValueError("thumbnail degenerate") + return _encode_jpeg(thumb), thumb.width, thumb.height + + +def _make_crop(img: Image.Image): + side = CROP_SIDE + # ImageOps.fit центрирует и ресайзит; для маленьких исходников увеличивает — разрешено. + crop = ImageOps.fit(img, (side, side), Image.Resampling.LANCZOS) + return _encode_jpeg(crop), side, side + + +def _make_optimized(img: Image.Image): + opt = img.copy() + opt.thumbnail(OPT_MAX, Image.Resampling.LANCZOS) + return _encode_webp(opt), opt.width, opt.height + + +def process(data: bytes): + """Возвращает список вариантов: [{name, content_type, bytes, width, height, sha256, size_bytes}].""" + img = _open_normalized(data) + if img.width * img.height > config.MAX_IMAGE_PIXELS: + raise ValueError("too many pixels") + + results = [] + + thumb_bytes, tw, th = _make_thumbnail(img) + results.append({ + "name": "thumbnail", "content_type": "image/jpeg", + "bytes": thumb_bytes, "width": tw, "height": th, + "sha256": hashlib.sha256(thumb_bytes).hexdigest(), "size_bytes": len(thumb_bytes), + }) + + crop_bytes, cw, ch = _make_crop(img) + results.append({ + "name": "crop", "content_type": "image/jpeg", + "bytes": crop_bytes, "width": cw, "height": ch, + "sha256": hashlib.sha256(crop_bytes).hexdigest(), "size_bytes": len(crop_bytes), + }) + + opt_bytes, ow, oh = _make_optimized(img) + results.append({ + "name": "optimized", "content_type": "image/webp", + "bytes": opt_bytes, "width": ow, "height": oh, + "sha256": hashlib.sha256(opt_bytes).hexdigest(), "size_bytes": len(opt_bytes), + }) + + return results \ No newline at end of file diff --git a/app/ratelimit.py b/app/ratelimit.py new file mode 100644 index 0000000..1a18ec3 --- /dev/null +++ b/app/ratelimit.py @@ -0,0 +1,34 @@ +"""Ограничение частоты входа, общее для всех API-реплик. + +Состояние — в PostgreSQL (fixed window), поэтому лимит не обходится +переключением между репликами за LB. Счётчики ведутся и для несуществующих +username, чтобы разница в ответах не выдавала наличие пользователя. +""" +from . import config + +_CLEANUP_SQL = ("DELETE FROM login_attempts WHERE bucket IN (" + " SELECT bucket FROM login_attempts" + " WHERE window_start < now() - interval '10 minutes' LIMIT 100)") + + +def hit(conn, bucket, limit, window=None): + """Увеличивает счётчик bucket за текущее окно. + + Возвращает (allowed, retry_after_seconds). + """ + window = window or config.LOGIN_RATE_WINDOW_SECONDS + row = conn.execute( + """INSERT INTO login_attempts (bucket, window_start, attempts) + VALUES (%s, to_timestamp(floor(extract(epoch FROM now()) / %s) * %s), 1) + ON CONFLICT (bucket, window_start) + DO UPDATE SET attempts = login_attempts.attempts + 1 + RETURNING attempts, + ceil(extract(epoch FROM + window_start + make_interval(secs => %s) - clock_timestamp())) AS retry_after""", + (bucket, window, window, window)).fetchone() + retry_after = int(row["retry_after"] or 1) + return row["attempts"] <= limit, max(1, retry_after) + + +def cleanup(conn): + conn.execute(_CLEANUP_SQL) diff --git a/app/relay.py b/app/relay.py new file mode 100644 index 0000000..495a35f --- /dev/null +++ b/app/relay.py @@ -0,0 +1,200 @@ +"""mTLS-вход каждой API-реплики. + +uvicorn 0.30 не передаёт клиентский сертификат в ASGI-scope, поэтому mTLS +терминируется собственным relay перед uvicorn: + + LB --TLS (client cert CN=lb)--▶ relay :8443 --plain loopback--▶ uvicorn :8080 + +Relay проверяет: + * цепочку клиентского сертификата до ca-clients; + * разрешённую identity: CN + серийный номер из identities.json; + * scope identity (prefix пути) — health-сертификат не получает бизнес-API. + +Порт 8080 слушает только 127.0.0.1 и не покидает контейнер. Обновление +identities.json подхватывается по mtime без рестарта: отзыв старой identity +действует на новые подключения. +""" +import json +import logging +import os +import socket +import ssl +import threading + +from . import config + +log = logging.getLogger("mtls") +_HEAD_LIMIT = 16384 + + +class IdentityStore: + def __init__(self, path): + self.path = path + self._mtime = 0.0 + self._allowed = {} + self._lock = threading.Lock() + + def _reload(self): + try: + mtime = os.stat(self.path).st_mtime + except OSError: + return + if mtime == self._mtime: + return + with self._lock: + if mtime == self._mtime: + return + try: + with open(self.path, encoding="utf-8") as fh: + raw = json.load(fh) + except (OSError, ValueError) as exc: + log.error("identity allowlist unreadable (%s); keeping previous set", type(exc).__name__) + return + allowed = {} + for entry in raw.values(): + serials = {str(x).upper() for x in entry.get("serials", [])} + allowed[entry.get("cn", "")] = {"serials": serials, "scope": entry.get("scope", "/")} + self._allowed = allowed + self._mtime = mtime + log.info("identity allowlist loaded: %s", ", ".join(sorted(allowed))) + + def allows(self, cn, serial, path): + self._reload() + entry = self._allowed.get(cn) + if entry is None: + return False + if str(serial).upper() not in entry["serials"]: + return False + return path.startswith(entry["scope"]) + + +_store = None + + +def _get_store(): + global _store + if _store is None: + _store = IdentityStore(config.API_IDENTITIES_FILE) + return _store + + +def _tls_context(): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 + ctx.load_cert_chain(config.API_TLS_CERT, config.API_TLS_KEY) + ctx.verify_mode = ssl.CERT_REQUIRED + ctx.load_verify_locations(cafile=config.TLS_CA_CLIENTS) + return ctx + + +def _read_head(sock): + data = b"" + while b"\r\n\r\n" not in data: + chunk = sock.recv(4096) + if not chunk: + return data + data += chunk + if len(data) > _HEAD_LIMIT: + return data + return data + + +def _request_path(head): + try: + line = head.split(b"\r\n", 1)[0].decode("latin-1") + parts = line.split(" ") + return parts[1] if len(parts) >= 2 else "" + except (UnicodeDecodeError, IndexError): + return "" + + +def _deny(sock, status="403 Forbidden", reason=b""): + body = b"" + head = ("HTTP/1.1 %s\r\nContent-Length: 0\r\nConnection: close\r\nX-Mtls-Reject: identity\r\n\r\n" + % status).encode("ascii") + try: + sock.sendall(head + body) + except OSError: + pass + finally: + try: + sock.close() + except OSError: + pass + + +def _pump(src, dst): + try: + while True: + chunk = src.recv(65536) + if not chunk: + break + dst.sendall(chunk) + except OSError: + pass + finally: + try: + dst.shutdown(socket.SHUT_WR) + except OSError: + pass + + +def _handle(ctx, conn, peer): + tls = None + upstream = None + try: + conn.settimeout(10) + try: + tls = ctx.wrap_socket(conn, server_side=True) + except (ssl.SSLError, OSError) as exc: + log.warning("mtls handshake failed from %s (%s)", peer[0], type(exc).__name__) + return + cert = tls.getpeercert() or {} + cn = dict(x[0] for x in cert.get("subject", ())).get("commonName", "") + serial = cert.get("serialNumber", "") + head = _read_head(tls) + path = _request_path(head) + if not head or not _get_store().allows(cn, serial, path): + log.warning("mtls denied peer=%s cn=%r serial=%r path=%r", peer[0], cn, serial, path) + _deny(tls) + tls = None + return + tls.settimeout(None) + upstream = socket.create_connection((config.APP_HOST, config.APP_PORT), timeout=10) + upstream.settimeout(None) + upstream.sendall(head) + back = threading.Thread(target=_pump, args=(upstream, tls), daemon=True) + back.start() + _pump(tls, upstream) + back.join(timeout=30) + except (OSError, ssl.SSLError) as exc: + log.warning("mtls relay error from %s (%s)", peer[0], type(exc).__name__) + finally: + for sock in (tls, upstream): + if sock is not None: + try: + sock.close() + except OSError: + pass + + +def _serve(): + ctx = _tls_context() + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("0.0.0.0", config.PUBLIC_PORT)) + srv.listen(128) + log.info("mtls relay listening on :%d -> %s:%d (client CA %s)", + config.PUBLIC_PORT, config.APP_HOST, config.APP_PORT, config.TLS_CA_CLIENTS) + while True: + try: + conn, peer = srv.accept() + except OSError: + return + threading.Thread(target=_handle, args=(ctx, conn, peer), daemon=True).start() + + +def start(): + thread = threading.Thread(target=_serve, name="mtls-relay", daemon=True) + thread.start() + return thread diff --git a/app/repo.py b/app/repo.py new file mode 100644 index 0000000..1cbfe4f --- /dev/null +++ b/app/repo.py @@ -0,0 +1,205 @@ +"""Доступ к данным. Добавлены queued-статусы, variants, json с variants.""" +import uuid + +from . import cursor +from .errors import bad_request, not_found +from .sessions import fmt_ts + + +# ---------- пользователи / чаты (без изменений) ---------- + +def username_exists(conn, username): + return conn.execute("SELECT 1 FROM users WHERE username = %s", (username,)).fetchone() is not None + + +def insert_user(conn, username, display_name, password_hash): + return 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, display_name, password_hash)).fetchone() + + +def user_for_login(conn, username): + return conn.execute( + "SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s", + (username,)).fetchone() + + +def update_password_hash(conn, user_id, new_hash): + conn.execute("UPDATE users SET password_hash = %s WHERE id = %s", (new_hash, user_id)) + + +def chat_json(row): + return {"id": str(row["id"]), "title": row["title"], + "member_ids": [str(x) for x in row["member_ids"]], + "created_at": fmt_ts(row["created_at"])} + + +def create_chat(conn, creator_id, title, member_ids, check_members=True): + if check_members: + found = conn.execute("SELECT count(*) AS n FROM users WHERE id = ANY(%s)", + (member_ids,)).fetchone()["n"] + if found != len(member_ids): + raise bad_request("Неизвестный участник чата") + chat = conn.execute( + "INSERT INTO chats (id, title, created_by) VALUES (%s, %s, %s) RETURNING id, title, created_at", + (uuid.uuid4(), title, creator_id)).fetchone() + conn.execute("INSERT INTO chat_members (chat_id, user_id) SELECT %s, unnest(%s::uuid[])", + (chat["id"], member_ids)) + chat["member_ids"] = sorted(member_ids) + return chat + + +def get_chat(conn, chat_id, user_id): + return conn.execute( + """SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) AS member_ids + FROM chats c + WHERE c.id = %s AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = %s)""", + (chat_id, user_id)).fetchone() + + +def is_member(conn, chat_id, user_id): + return conn.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, user_id)).fetchone() is not None + + +def list_chats(conn, user_id, after, limit): + base = """SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) AS member_ids + FROM chat_members me JOIN chats c ON c.id = me.chat_id + WHERE me.user_id = %s""" + params = [user_id] + if after: + base += " AND (c.created_at, c.id) > (%s, %s)" + params += list(after) + rows = conn.execute(base + " ORDER BY c.created_at, c.id LIMIT %s", params + [limit + 1]).fetchall() + page, more = rows[:limit], len(rows) > limit + nxt = cursor.encode("chats", user_id, page[-1]["created_at"], page[-1]["id"]) if more else None + return [chat_json(r) for r in page], nxt + + +# ---------- сообщения (без изменений логики) ---------- + +def _message_json(row): + return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), + "text": row["text"], "created_at": fmt_ts(row["created_at"]), + "attachment_ids": [str(x) for x in (row.get("attachment_ids") or [])]} + + +def message_json(row): + return _message_json(row) + + +def insert_message(conn, chat_id, sender_id, text, attachment_ids=None): + attachment_ids = attachment_ids or [] + if attachment_ids: + rows = conn.execute( + """SELECT id, status FROM attachments WHERE id = ANY(%s) AND chat_id = %s""", + (attachment_ids, chat_id)).fetchall() + by_id = {r["id"]: r for r in rows} + if len(by_id) != len(attachment_ids): + raise not_found() + for att_id in attachment_ids: + if by_id[att_id]["status"] == "failed": + raise bad_request("Нельзя прикрепить failed-вложение") + # queued/processing разрешены с lab5 — можно ссылаться до готовности. + row = conn.execute( + """INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) + RETURNING id, chat_id, sender_id, text, created_at""", + (uuid.uuid4(), chat_id, sender_id, text)).fetchone() + if attachment_ids: + conn.execute( + """INSERT INTO message_attachments (message_id, attachment_id, position) + SELECT %s, unnest(%s::uuid[]), generate_subscripts(%s::uuid[], 1) - 1""", + (row["id"], attachment_ids, attachment_ids)) + row["attachment_ids"] = attachment_ids + return row + + +def list_messages(conn, chat_id, after, limit): + sql = """SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, + ARRAY(SELECT ma.attachment_id FROM message_attachments ma + WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids + FROM messages m WHERE m.chat_id = %s""" + params = [chat_id] + if after: + sql += " AND (m.created_at, m.id) > (%s, %s)" + params += list(after) + rows = conn.execute(sql + " ORDER BY m.created_at, m.id LIMIT %s", params + [limit + 1]).fetchall() + page, more = rows[:limit], len(rows) > limit + nxt = cursor.encode("messages", chat_id, page[-1]["created_at"], page[-1]["id"]) if more else None + return [_message_json(r) for r in page], nxt + + +# ---------- вложения lab5 ---------- + +def insert_attachment_queued(conn, chat_id, owner_id, filename, content_type, + size_bytes, sha256, staging_key): + return conn.execute( + """INSERT INTO attachments + (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, + staging_key, status) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'queued') + RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, + status, error_code, created_at, updated_at""", + (uuid.uuid4(), chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key) + ).fetchone() + + +def mark_attachment_failed(conn, attachment_id, error_code): + conn.execute( + """UPDATE attachments + SET status='failed', error_code=%s, updated_at=clock_timestamp() + WHERE id=%s AND status IN ('queued','processing')""", + (error_code, attachment_id)) + + +def get_attachment_for_member(conn, attachment_id, user_id): + return conn.execute( + """SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, + a.object_key, a.staging_key, a.status, a.error_code, a.created_at, a.updated_at + FROM attachments a + WHERE a.id = %s + AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = %s)""", + (attachment_id, user_id)).fetchone() + + +def get_variant(conn, attachment_id, variant_name): + return conn.execute( + """SELECT attachment_id, name, object_key, content_type, size_bytes, width, height, sha256 + FROM attachment_variants WHERE attachment_id = %s AND name = %s""", + (attachment_id, variant_name)).fetchone() + + +def list_variants(conn, attachment_id): + return conn.execute( + """SELECT name, content_type, size_bytes, width, height, sha256 + FROM attachment_variants WHERE attachment_id = %s ORDER BY name""", + (attachment_id,)).fetchall() + + +def attachment_json(row, variants=None): + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "owner_id": str(row["owner_id"]), + "filename": row["filename"], + "content_type": row["content_type"], + "size_bytes": row["size_bytes"], + "sha256": row["sha256"], + "status": row["status"], + "variants": [ + { + "name": v["name"], + "content_type": v["content_type"], + "size_bytes": v["size_bytes"], + "width": v["width"], + "height": v["height"], + "sha256": v["sha256"], + } for v in (variants or []) + ], + "error_code": row["error_code"], + "created_at": fmt_ts(row["created_at"]), + "updated_at": fmt_ts(row["updated_at"]), + } \ No newline at end of file diff --git a/app/s3.py b/app/s3.py new file mode 100644 index 0000000..a763885 --- /dev/null +++ b/app/s3.py @@ -0,0 +1,75 @@ +"""S3-совместимое хранилище (Silo/MinIO): потоковые put/get, копирование, удаление.""" +import logging +import threading + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError + +from . import config + +log = logging.getLogger("s3") +_client = None +_lock = threading.Lock() + + +def _get_client(): + global _client + if _client is None: + with _lock: + if _client is None: + _client = boto3.client( + "s3", + endpoint_url=config.S3_ENDPOINT, + aws_access_key_id=config.S3_ACCESS_KEY_ID, + aws_secret_access_key=config.S3_SECRET_ACCESS_KEY, + region_name=config.S3_REGION, + verify=config.S3_VERIFY, # TLS с проверкой сервера (lab7) + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + retries={"max_attempts": 3, "mode": "standard"}, + connect_timeout=config.S3_CONNECT_TIMEOUT, + read_timeout=config.S3_READ_TIMEOUT, + ), + ) + return _client + + +def ensure_bucket(): + client = _get_client() + try: + client.head_bucket(Bucket=config.S3_BUCKET) + except ClientError as exc: + if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchBucket"): + client.create_bucket(Bucket=config.S3_BUCKET) + else: + raise + + +def put_object(key: str, body, content_type: str, content_length: int): + client = _get_client() + client.put_object( + Bucket=config.S3_BUCKET, Key=key, Body=body, + ContentType=content_type, ContentLength=content_length, + ) + + +def get_object(key: str): + """Возвращает StreamingBody.""" + client = _get_client() + resp = client.get_object(Bucket=config.S3_BUCKET, Key=key) + return resp["Body"] + + +def delete_object(key: str): + client = _get_client() + try: + client.delete_object(Bucket=config.S3_BUCKET, Key=key) + except (ClientError, BotoCoreError): + log.warning("failed to delete object %s", key) + + +def ping(): + client = _get_client() + client.head_bucket(Bucket=config.S3_BUCKET) \ No newline at end of file diff --git a/app/secrets.py b/app/secrets.py new file mode 100644 index 0000000..7ba4454 --- /dev/null +++ b/app/secrets.py @@ -0,0 +1,159 @@ +"""Получение секретов из OpenBao по AppRole. + +Модель: + * в приложении нет root token и unseal-ключей; есть только role_id и + короткоживущий secret_id, выданные оператором в bootstrap/ (файлы, не Git); + * по ним приложение логинится, получает token с TTL и читает один KV-путь + secret/data/messenger/ по scoped policy; + * token продлевается в фоне; при недоступном/sealed OpenBao приложение + продолжает работать на уже загруженных в память секретах (это ограниченное, + а не бесконечное поведение: новые секреты не появятся, при рестарте без + OpenBao приложение не стартует). +""" +import json +import logging +import ssl +import threading +import time +import urllib.error +import urllib.request + +from . import config + +log = logging.getLogger("secrets") + +STATE = {"loaded": False, "token_ok": False, "last_error": None} + + +class OpenBaoError(RuntimeError): + pass + + +def _ssl_context(): + return ssl.create_default_context(cafile=config.OPENBAO_CA) + + +def _request(method, path, body=None, token=None, timeout=None): + url = config.OPENBAO_ADDR.rstrip("/") + path + data = json.dumps(body).encode("utf-8") if body is not None else None + req = urllib.request.Request(url, data=data, method=method) + req.add_header("Content-Type", "application/json") + if token: + req.add_header("X-Vault-Token", token) + try: + with urllib.request.urlopen(req, timeout=timeout or config.OPENBAO_TIMEOUT, + context=_ssl_context()) as resp: + raw = resp.read() + return json.loads(raw) if raw else {} + except urllib.error.HTTPError as exc: + # Тело ошибки OpenBao полезно для диагностики, но не должно содержать секретов. + raise OpenBaoError("%s %s -> HTTP %s" % (method, path, exc.code)) from None + except (urllib.error.URLError, OSError) as exc: + raise OpenBaoError("%s %s -> %s" % (method, path, type(exc).__name__)) from None + + +def _read_file(path, what): + try: + with open(path, encoding="utf-8") as fh: + value = fh.read().strip() + except OSError: + raise OpenBaoError("%s not available (%s)" % (what, path)) from None + if not value: + raise OpenBaoError("%s is empty (%s)" % (what, path)) + return value + + +def login(): + role_id = _read_file(config.OPENBAO_ROLE_ID_FILE, "role_id") + secret_id = _read_file(config.OPENBAO_SECRET_ID_FILE, "secret_id") + payload = _request("POST", "/v1/auth/approle/login", + {"role_id": role_id, "secret_id": secret_id}) + auth = payload.get("auth") or {} + token = auth.get("client_token") + if not token: + raise OpenBaoError("approle login returned no token") + return token, float(auth.get("lease_duration") or 0) + + +def read_kv(token, role): + payload = _request("GET", "/v1/" + config.OPENBAO_KV_PATH, token=token) + data = (payload.get("data") or {}).get("data") + if not isinstance(data, dict): + raise OpenBaoError("KV payload for role %s is not a mapping" % role) + return data + + +def _renew_loop(state, lease, stop): + """Продление token с re-auth при истечении/отзыве (например, после unseal). + + При недоступном OpenBao секреты остаются в памяти, приложение продолжает + обслуживать запросы; как только OpenBao вернулся — выполняется новый login. + """ + interval = config.OPENBAO_RENEW_INTERVAL_SECONDS + if lease > interval: + interval = max(30, int(lease * 0.6)) + while not stop.wait(interval): + try: + payload = _request("POST", "/v1/auth/token/renew-self", {}, + token=state["token"]) + auth = payload.get("auth") or {} + lease = float(auth.get("lease_duration") or lease) + STATE["token_ok"] = True + STATE["last_error"] = None + log.info("openbao token renewed, lease=%.0fs", lease) + except OpenBaoError as exc: + STATE["token_ok"] = False + STATE["last_error"] = str(exc) + log.warning("openbao token renew failed (%s); re-authenticating", exc) + try: + state["token"], lease = login() + STATE["token_ok"] = True + STATE["last_error"] = None + log.info("openbao token re-acquired via AppRole") + except OpenBaoError as reauth_exc: + STATE["last_error"] = str(reauth_exc) + log.warning("openbao re-auth failed (%s); serving with cached secrets", reauth_exc) + interval = 30 + continue + interval = config.OPENBAO_RENEW_INTERVAL_SECONDS + if lease > interval: + interval = max(30, int(lease * 0.6)) + + +def load(role=None): + """Загружает секреты роли и применяет их к config. Ждёт OpenBao ограниченное время.""" + role = role or config.OPENBAO_ROLE + deadline = time.monotonic() + config.OPENBAO_WAIT_SECONDS + attempt = 0 + while True: + attempt += 1 + try: + token, lease = login() + data = read_kv(token, role) + apply(data) + STATE.update({"loaded": True, "token_ok": True, "last_error": None}) + stop = threading.Event() + threading.Thread(target=_renew_loop, args=({"token": token}, lease, stop), + daemon=True).start() + log.info("openbao secrets loaded for role=%s path=%s", role, config.OPENBAO_KV_PATH) + return data + except OpenBaoError as exc: + STATE["last_error"] = str(exc) + if time.monotonic() >= deadline: + raise + if attempt == 1 or attempt % 10 == 0: + log.warning("openbao not ready (%s); retrying", exc) + time.sleep(2) + + +def apply(data): + """Переносит значения из KV в config. Ничего не логирует.""" + required = ("database_url", "s3_access_key_id", "s3_secret_access_key") + missing = [key for key in required if not data.get(key)] + if missing: + raise OpenBaoError("KV payload misses required keys: %s" % ", ".join(missing)) + config.DATABASE_URL = str(data["database_url"]) + config.S3_ACCESS_KEY_ID = str(data["s3_access_key_id"]) + config.S3_SECRET_ACCESS_KEY = str(data["s3_secret_access_key"]) + if data.get("s3_bucket"): + config.S3_BUCKET = str(data["s3_bucket"]) diff --git a/app/security.py b/app/security.py new file mode 100644 index 0000000..670375c --- /dev/null +++ b/app/security.py @@ -0,0 +1,94 @@ +"""Пароли (Argon2id), токены, разбор заголовка Authorization. + +Argon2id: m=19456 KiB (19 MiB), t=2, p=1 по умолчанию (OWASP minimum). +При успешном входе hash с устаревшими параметрами пересчитывается (rehash). +Число одновременных хеширований ограничено семафором с таймаутом: поток +дешёвых login-запросов получает 503 + Retry-After, а не съедает CPU. +""" +import base64 +import binascii +import hashlib +import re +import secrets +import threading +from contextlib import contextmanager + +from argon2 import PasswordHasher, Type +from argon2.exceptions import InvalidHashError, VerificationError + +from . import config +from .errors import ApiError + +_hasher = PasswordHasher(time_cost=config.ARGON2_TIME_COST, + memory_cost=config.ARGON2_MEMORY_KIB, + parallelism=config.ARGON2_PARALLELISM, + hash_len=32, salt_len=16, type=Type.ID) +_DUMMY_HASH = _hasher.hash("dummy-password-for-constant-time") +_hash_slots = threading.BoundedSemaphore(config.HASH_CONCURRENCY) +_TOKEN_RE = re.compile(r"[A-Za-z0-9._~+/=-]{16,512}") + + +@contextmanager +def _slot(): + if not _hash_slots.acquire(timeout=config.HASH_SLOT_TIMEOUT): + raise ApiError(503, "unavailable", "Сервис временно перегружен", {"Retry-After": "1"}) + try: + yield + finally: + _hash_slots.release() + + +def hash_password(password): + with _slot(): + return _hasher.hash(password) + + +def verify_password(stored_hash, password): + """Возвращает (ok, new_hash). new_hash не None, если нужен rehash.""" + with _slot(): + try: + _hasher.verify(stored_hash, password) + except (VerificationError, InvalidHashError): + return False, None + return True, (_hasher.hash(password) if _hasher.check_needs_rehash(stored_hash) else None) + + +def burn_verify(password): + """Тратит такое же время, как настоящая проверка (защита от user enumeration).""" + with _slot(): + try: + _hasher.verify(_DUMMY_HASH, password) + except VerificationError: + pass + + +def new_token(): + return secrets.token_urlsafe(32) + + +def token_hash(token): + return hashlib.sha256(token.encode("ascii")).digest() + + +def parse_basic(header): + if not header: + return None + scheme, _, rest = header.partition(" ") + if scheme.lower() != "basic": + return None + try: + text = base64.b64decode(rest.strip(), validate=True).decode("utf-8") + except (binascii.Error, UnicodeDecodeError, ValueError): + return None + username, sep, password = text.partition(":") + return (username, password) if sep else None + + +def parse_bearer(header): + if not header: + return None + scheme, _, rest = header.partition(" ") + token = rest.strip() + if scheme.lower() != "bearer" or not _TOKEN_RE.fullmatch(token): + return None + return token diff --git a/app/server.py b/app/server.py new file mode 100644 index 0000000..33cfef1 --- /dev/null +++ b/app/server.py @@ -0,0 +1,32 @@ +"""Точка входа API: секреты из OpenBao -> mTLS relay -> uvicorn на loopback.""" +import logging +import os + +import uvicorn + +from . import secrets + +log = logging.getLogger("server") + + +def main(): + # Секреты должны быть применены до первого обращения к БД/S3. + secrets.load("api") + + from main import app # noqa: PLC0415 - импорт после инициализации секретов + + from . import health, relay # noqa: PLC0415 + + os.environ.setdefault("APP_SERVICE", "messenger-api") + relay.start() + health.start() + + log.info("starting uvicorn on loopback %s:%d behind mTLS relay on :%d", + "127.0.0.1", 8080, 8443) + uvicorn.run(app, host="127.0.0.1", port=8080, log_level="warning", + access_log=False, server_header=False, date_header=False) + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + main() diff --git a/app/sessions.py b/app/sessions.py new file mode 100644 index 0000000..b8cf8c0 --- /dev/null +++ b/app/sessions.py @@ -0,0 +1,48 @@ +"""Сессии: единственный источник истины — PostgreSQL (TLS, отдельная DB-роль). + +От кэша Valkey/Redis в lab7 отказались: это лишняя trust-граница без выигрыша +для учебного стенда (см. REPORT.md, строка N/A в trust-matrix). +""" +import time +from datetime import timezone + +from . import config, db, security + + +def fmt_ts(value): + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def user_json(row): + return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], + "created_at": fmt_ts(row["created_at"])} + + +def create(conn, user_row): + token = security.new_token() + row = conn.execute( + """INSERT INTO sessions (token_hash, user_id, expires_at) + VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s)) + RETURNING expires_at""", + (security.token_hash(token), user_row["id"], config.SESSION_TTL_SECONDS)).fetchone() + conn.execute("""DELETE FROM sessions WHERE token_hash IN ( + SELECT token_hash FROM sessions WHERE expires_at < now() - interval '1 hour' LIMIT 100)""") + return token, row["expires_at"] + + +def lookup(token): + digest = security.token_hash(token) + with db.connection() as conn: + row = conn.execute( + """SELECT u.id, u.username, u.display_name, u.created_at, + extract(epoch FROM s.expires_at) AS exp + FROM sessions s JOIN users u ON u.id = s.user_id + WHERE s.token_hash = %s AND s.expires_at > clock_timestamp()""", (digest,)).fetchone() + if row is None: + return None + return {"user": user_json(row), "digest": digest} + + +def revoke(digest): + with db.connection() as conn: + conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,)) diff --git a/app/telemetry.py b/app/telemetry.py new file mode 100644 index 0000000..a217673 --- /dev/null +++ b/app/telemetry.py @@ -0,0 +1,149 @@ +"""lab7: OTel SDK с mTLS к Collector и структурные JSON-логи. + +Каждый процесс вызывает init(service_name=...) один раз. Экспорт идёт на +OTLP-HTTP вход LB (nginx :4318), который требует клиентский сертификат и +проверяет identity (CN=messenger-api|messenger-worker); дальше Collector +пишет сигналы в Prometheus/Loki/Tempo по TLS. + +Логи — JSON в теле записи: trace_id/span_id попадают в саму строку Loki, +поэтому переход «лог → трасса» в Grafana работает без хрупкого regexp +по чужому формату. +""" +import json +import logging +import os +from datetime import datetime, timezone + +from opentelemetry import metrics, trace +from opentelemetry._logs import set_logger_provider +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.propagate import extract as _extract +from opentelemetry.propagate import inject as _inject +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.resources import SERVICE_NAME, SERVICE_VERSION, Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +from . import config + +log = logging.getLogger("telemetry") +_initialized = False +_service_name = "unknown" + + +class JsonFormatter(logging.Formatter): + """Структурный лог: тело строки — JSON с коррелирующими полями.""" + + def format(self, record): + span = trace.get_current_span() + ctx = span.get_span_context() if span is not None else None + payload = { + "ts": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"), + "severity": record.levelname, + "service.name": _service_name, + "event": record.getMessage(), + "logger": record.name, + "trace_id": format(ctx.trace_id, "032x") if ctx is not None and ctx.is_valid else "", + "span_id": format(ctx.span_id, "016x") if ctx is not None and ctx.is_valid else "", + "instance": os.environ.get("HOSTNAME", ""), + } + if record.exc_info: + payload["exception"] = self.formatException(record.exc_info) + # Компактный JSON: Grafana derived field ищет `"trace_id":"..."` без пробела. + return json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + + +class JsonLoggingHandler(LoggingHandler): + """LoggingHandler, который кладёт в тело OTLP-записи наш JSON. + + SDK 1.27 формирует body как `record.msg % args` и игнорирует formatter, + из-за чего строка в Loki не содержала бы trace_id. Переопределяем + `_translate`, чтобы тело было тем же JSON, что и в stdout. + """ + + def _translate(self, record): + translated = super()._translate(record) + translated.body = self.format(record) + return translated + + +def _install_formatter(): + formatter = JsonFormatter() + root = logging.getLogger() + for handler in root.handlers: + handler.setFormatter(formatter) + for handler in list(root.handlers): + if isinstance(handler, LoggingHandler): + handler.setFormatter(formatter) + + +def init(service_name): + """Идемпотентная инициализация. OTEL_SDK_DISABLED=true → только JSON-логи.""" + global _initialized, _service_name + if _initialized: + return + _service_name = service_name + + if not config.OTEL_ENABLED: + _install_formatter() + log.info("OTel disabled by OTEL_SDK_DISABLED; structured logs only") + _initialized = True + return + + tls = { + "certificate_file": config.OTEL_CA, + "client_certificate_file": config.OTEL_CLIENT_CERT, + "client_key_file": config.OTEL_CLIENT_KEY, + } + endpoint = config.OTEL_ENDPOINT.rstrip("/") + resource = Resource.create({ + SERVICE_NAME: service_name, + SERVICE_VERSION: config.OTEL_SERVICE_VERSION, + "deployment.environment.name": "lab", + "service.instance.id": config.INSTANCE_ID, + }) + + tracer_provider = TracerProvider(resource=resource) + tracer_provider.add_span_processor( + BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint + "/v1/traces", **tls))) + trace.set_tracer_provider(tracer_provider) + + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=endpoint + "/v1/metrics", **tls), + export_interval_millis=10_000) + metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader])) + + logger_provider = LoggerProvider(resource=resource) + logger_provider.add_log_record_processor( + BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint + "/v1/logs", **tls))) + set_logger_provider(logger_provider) + + root = logging.getLogger() + root.addHandler(JsonLoggingHandler(level=logging.INFO, logger_provider=logger_provider)) + _install_formatter() + + _initialized = True + log.info("OTel initialized: service=%s endpoint=%s", service_name, endpoint) + + +def get_tracer(name=None): + return trace.get_tracer(name or "messenger") + + +def get_meter(name=None): + return metrics.get_meter(name or "messenger") + + +def inject_headers(carrier): + """W3C traceparent/tracestate → headers брокера.""" + _inject(carrier) + return carrier + + +def extract_context(carrier): + return _extract(carrier or {}) diff --git a/app/validation.py b/app/validation.py new file mode 100644 index 0000000..4088efe --- /dev/null +++ b/app/validation.py @@ -0,0 +1,83 @@ +"""Строгая валидация входа.""" +import json +import re +import uuid + +from .errors import ApiError, bad_request + +_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}") +_USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}") +_INT_RE = re.compile(r"[0-9]{1,6}") + + +def parse_uuid(value): + if isinstance(value, str) and _UUID_RE.fullmatch(value): + return uuid.UUID(value) + return None + + +def require_uuid(value, name="id"): + parsed = parse_uuid(value) + if parsed is None: + raise bad_request("Некорректный %s" % name) + return parsed + + +def _reject_constant(name): + raise ValueError("non-finite number") + + +def _no_duplicates(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate key") + result[key] = value + return result + + +def json_body(content_type, raw, allowed, required): + if content_type.split(";")[0].strip().lower() != "application/json": + raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: application/json") + try: + data = json.loads(raw.decode("utf-8"), parse_constant=_reject_constant, object_pairs_hook=_no_duplicates) + except (ValueError, UnicodeDecodeError, RecursionError): + raise bad_request("Некорректный JSON") + if not isinstance(data, dict) or set(data) - set(allowed) or not set(required) <= set(data): + raise bad_request("Некорректный набор полей") + return data + + +def text_field(value, name, low, high, allow_blank=False): + if not isinstance(value, str): + raise bad_request("Поле %s должно быть строкой" % name) + if "\x00" in value or not _encodable(value): + raise bad_request("Поле %s содержит недопустимые символы" % name) + if not low <= len(value) <= high: + raise bad_request("Поле %s: длина должна быть %d–%d" % (name, low, high)) + if not allow_blank and not value.strip(): + raise bad_request("Поле %s не должно состоять только из пробелов" % name) + return value + + +def _encodable(value): + try: + value.encode("utf-8") + return True + except UnicodeEncodeError: + return False + + +def username_field(value): + if not isinstance(value, str) or not _USERNAME_RE.fullmatch(value): + raise bad_request("username должен соответствовать [a-z0-9_]{3,32}") + return value + + +def limit_param(params): + raw = params.get("limit") + if raw is None: + return 50 + if not _INT_RE.fullmatch(raw) or not 1 <= int(raw) <= 100: + raise bad_request("limit должен быть целым числом 1–100") + return int(raw) \ No newline at end of file diff --git a/app/worker.py b/app/worker.py new file mode 100644 index 0000000..2be6bc1 --- /dev/null +++ b/app/worker.py @@ -0,0 +1,379 @@ +"""Worker lab6: consume из RabbitMQ, обработка изображения, OTel-инструментация.""" +import hashlib +import json +import logging +import signal +import sys +import threading +import time +import uuid + +import pika +from opentelemetry import trace +from opentelemetry.instrumentation.botocore import BotocoreInstrumentor +from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor +from opentelemetry.trace import SpanKind + +from . import broker, config, db, jobs, pipeline, repo, s3, secrets, telemetry + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") +logging.getLogger("pika").setLevel(logging.WARNING) +logging.getLogger("opentelemetry").setLevel(logging.WARNING) +log = logging.getLogger("worker") + +_stop = threading.Event() + +# OTel-хендлы и метрики инициализируются один раз в main(). +_tracer = None +_m_jobs = None +_m_duration = None +_m_time_to_ready = None +_m_busy = None + + +def _init_metrics(): + global _tracer, _m_jobs, _m_duration, _m_time_to_ready, _m_busy + if _tracer is not None: + return + _tracer = telemetry.get_tracer("messenger-worker") + meter = telemetry.get_meter("messenger-worker") + _m_jobs = meter.create_counter( + "messenger_jobs_processed_total", + description="Jobs processed, by outcome") + _m_duration = meter.create_histogram( + "messenger_job_processing_duration_seconds", + description="Job processing duration", + unit="s") + _m_time_to_ready = meter.create_histogram( + "messenger_time_to_ready_seconds", + description="Upload accepted -> status ready", + unit="s") + _m_busy = meter.create_up_down_counter( + "messenger_worker_busy", + description="Worker slots in use") + + +def _on_sigterm(signum, frame): + log.info("SIGTERM received, stopping after current message") + _stop.set() + + +def _backoff(attempt: int) -> float: + """Экспоненциальный backoff с jitter: 2^attempt секунд ± 50%.""" + base = min(60.0, 2.0 ** min(attempt, 6)) + jitter = 0.5 + 0.5 * (uuid.uuid4().int & 0xFFFF) / 0xFFFF + return base * jitter + + +def _is_permanent(exc: Exception) -> bool: + if isinstance(exc, ValueError): + return True + return False + + +def _load_attachment(conn, attachment_id: uuid.UUID): + return conn.execute( + """SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, + object_key, staging_key, status + FROM attachments WHERE id = %s""", (attachment_id,)).fetchone() + + +def _already_ready(conn, attachment_id: uuid.UUID) -> bool: + """Идемпотентность: если ready и есть все три варианта — no-op.""" + row = conn.execute( + """SELECT a.status, + (SELECT count(*) FROM attachment_variants v WHERE v.attachment_id = a.id) AS n + FROM attachments a WHERE a.id = %s""", (attachment_id,)).fetchone() + if row is None: + return False + return row["status"] == "ready" and row["n"] >= 3 + + +def _process_one(conn, job_row) -> None: + """Один job: скачать staging, обработать, залить финал+варианты, транзакционно записать.""" + attachment_id = job_row["attachment_id"] + job_id = job_row["job_id"] + + if _already_ready(conn, attachment_id): + jobs.mark_ready(conn, job_id) + log.info("job %s: already ready, ack", job_id) + return + + att = _load_attachment(conn, attachment_id) + if att is None: + jobs.mark_failed(conn, job_id, "attachment_missing") + return + if not att["staging_key"]: + jobs.mark_failed(conn, job_id, "staging_missing") + return + + # 1. Прочитать staging из S3. BotocoreInstrumentor создаст client span. + body = s3.get_object(att["staging_key"]) + try: + data = body.read() + finally: + body.close() + + if hashlib.sha256(data).hexdigest() != att["sha256"]: + raise RuntimeError("staging checksum mismatch") + + # 2. Обработать (thumbnail, crop, optimized). Не инструментируется отдельно — + # CPU-bound, метрика duration уже покрывает всё. + variants = pipeline.process(data) + + # 3. Финализировать: original + варианты в S3. + final_key = "originals/%s/%s" % (att["chat_id"], uuid.uuid4().hex) + s3.put_object(final_key, data, att["content_type"], content_length=len(data)) + for v in variants: + v_key = "variants/%s/%s" % (attachment_id, v["name"]) + s3.put_object(v_key, v["bytes"], v["content_type"], content_length=len(v["bytes"])) + v["object_key"] = v_key + + # 4. Зафиксировать в БД атомарно. + with db.connection() as txn: + check = txn.execute( + """SELECT status FROM attachments WHERE id = %s FOR UPDATE""", + (attachment_id,)).fetchone() + if check["status"] == "ready": + jobs.mark_ready(txn, job_id) + return + for v in variants: + txn.execute( + """INSERT INTO attachment_variants + (attachment_id, name, object_key, content_type, size_bytes, width, height, sha256) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (attachment_id, name) DO UPDATE + SET object_key = EXCLUDED.object_key, + content_type = EXCLUDED.content_type, + size_bytes = EXCLUDED.size_bytes, + width = EXCLUDED.width, + height = EXCLUDED.height, + sha256 = EXCLUDED.sha256""", + (attachment_id, v["name"], v["object_key"], v["content_type"], + v["size_bytes"], v["width"], v["height"], v["sha256"])) + txn.execute( + """UPDATE attachments + SET status = 'ready', object_key = %s, error_code = NULL, + staging_key = NULL, updated_at = clock_timestamp() + WHERE id = %s""", + (final_key, attachment_id)) + jobs.mark_ready(txn, job_id) + + # 5. После COMMIT — удалить staging (best-effort). + try: + s3.delete_object(att["staging_key"]) + except Exception: + log.warning("staging delete failed for %s", att["staging_key"]) + + +def _record_time_to_ready(attachment_id: uuid.UUID) -> None: + """histogram: from attachments.created_at (upload accepted) to now (ready).""" + try: + with db.connection() as conn: + row = conn.execute( + """SELECT EXTRACT(EPOCH FROM now() - created_at)::float AS delta + FROM attachments WHERE id = %s""", + (attachment_id,)).fetchone() + if row and row["delta"] is not None: + _m_time_to_ready.record(float(row["delta"]), + {"pipeline.version": "1"}) + except Exception: + pass + + +def _handle_message(ch, method, properties, body): + """Consumer: span + W3C trace context + ack только после COMMIT.""" + _init_metrics() + + # W3C trace context из headers. Pika хранит значения как bytes — декодируем. + raw_headers = (properties.headers or {}) if properties else {} + headers = {} + for k, v in raw_headers.items(): + if isinstance(v, bytes): + headers[k] = v.decode("utf-8", errors="replace") + else: + headers[k] = v + ctx = telemetry.extract_context(headers) + + try: + payload = json.loads(body) + job_id = uuid.UUID(payload["job_id"]) + except Exception: + log.error("malformed job payload, drop") + ch.basic_nack(method.delivery_tag, requeue=False) + return + + with _tracer.start_as_current_span( + "attachment.process", + context=ctx, + kind=SpanKind.CONSUMER, + attributes={ + "messaging.system": "rabbitmq", + "messaging.destination.name": broker.QUEUE, + "messaging.message.id": str(job_id), + "messaging.operation": "process", + "job.id": str(job_id), + "attachment.id": payload.get("attachment_id", ""), + "service.instance.id": config.INSTANCE_ID, + }) as span: + t0 = time.monotonic() + _m_busy.add(1, {"worker": config.INSTANCE_ID}) + try: + with db.connection() as conn: + job_row = jobs.claim_job(conn, job_id) + if job_row is None: + span.set_attribute("job.skip", "not_claimable") + ch.basic_ack(method.delivery_tag) + return + + if job_row["attempt"] > job_row["max_attempts"]: + with db.connection() as conn: + jobs.mark_failed(conn, job_id, "retry_exhausted") + _m_jobs.add(1, {"outcome": "failed", "job.type": "attachment.process.v1"}) + span.set_attribute("job.outcome", "failed") + span.set_attribute("job.error_code", "retry_exhausted") + ch.basic_ack(method.delivery_tag) + return + + with db.connection() as conn: + _process_one(conn, job_row) + + duration = time.monotonic() - t0 + _m_duration.record(duration, + {"outcome": "ready", "job.type": "attachment.process.v1"}) + _m_jobs.add(1, {"outcome": "ready", "job.type": "attachment.process.v1"}) + _record_time_to_ready(job_row["attachment_id"]) + + span.set_attribute("job.outcome", "ready") + span.set_attribute("job.attempt", job_row["attempt"]) + span.set_attribute("job.duration_seconds", round(duration, 3)) + ch.basic_ack(method.delivery_tag) + log.info("job %s: done (attempt %d, %.2fs)", job_id, job_row["attempt"], duration) + + except Exception as exc: + span.set_attribute("job.outcome", "error") + span.record_exception(exc) + log.warning("job %s: error %s", job_id, type(exc).__name__) + permanent = _is_permanent(exc) + attempt = 1 + max_attempts = config.JOB_MAX_ATTEMPTS + try: + with db.connection() as conn: + row = conn.execute( + "SELECT attempt, max_attempts FROM jobs WHERE job_id = %s", + (job_id,)).fetchone() + if row: + attempt = row["attempt"] + max_attempts = row["max_attempts"] + if permanent or attempt >= max_attempts: + jobs.mark_failed(conn, job_id, + "invalid_image" if permanent else "retry_exhausted") + _m_jobs.add(1, {"outcome": "failed", "job.type": "attachment.process.v1"}) + span.set_attribute("job.error_code", + "invalid_image" if permanent else "retry_exhausted") + else: + # retry = re-publish через outbox с контекстом текущей попытки + carrier = telemetry.inject_headers({}) + jobs.mark_retry(conn, job_id, "processing_failed", + _backoff(attempt), carrier) + _m_jobs.add(1, {"outcome": "retry", "job.type": "attachment.process.v1"}) + span.set_attribute("job.error_code", "processing_failed") + span.set_attribute("job.retry_after", round(_backoff(attempt), 1)) + finally: + ch.basic_ack(method.delivery_tag) + finally: + _m_busy.add(-1, {"worker": config.INSTANCE_ID}) + + +def _reaper_loop(): + """Возвращает в queued задачи с истёкшим lease.""" + while not _stop.wait(30): + try: + with db.connection() as conn: + rows = jobs.find_expired_leases(conn) + for row in rows: + outcome = jobs.requeue_expired(conn, row) + log.info("lease reaper: job %s -> %s", row["job_id"], outcome) + except Exception as exc: + log.warning("reaper error: %s", type(exc).__name__) + + +def _outbox_loop(): + """Публикует outbox — на случай, если API упал между COMMIT и publish.""" + while not _stop.wait(3): + try: + with db.connection() as conn: + jobs.publish_pending_outbox(conn, broker.publish) + except Exception as exc: + log.warning("outbox error: %s", type(exc).__name__) + + +def main(): + signal.signal(signal.SIGTERM, _on_sigterm) + signal.signal(signal.SIGINT, _on_sigterm) + + # lab7: scoped secrets из OpenBao (свой DB role и свои S3-ключи). + secrets.load("worker") + + # lab6: OTel. service.name=messenger-worker (отличается от API). + telemetry.init("messenger-worker") + PsycopgInstrumentor().instrument() + BotocoreInstrumentor().instrument() + _init_metrics() + + # Ждём broker до 120 секунд — на случай рестарта RabbitMQ. + ready = False + for attempt in range(60): + if _stop.is_set(): + return + try: + broker.declare_only() + ready = True + break + except Exception as exc: + log.warning("broker not ready (attempt %d): %s", + attempt + 1, type(exc).__name__) + if _stop.wait(2): + return + if not ready: + log.error("broker unavailable after 120s, exiting") + sys.exit(1) + + log.info("worker started, queue=%s concurrency=%d", + broker.QUEUE, config.WORKER_CONCURRENCY) + + threading.Thread(target=_reaper_loop, daemon=True).start() + threading.Thread(target=_outbox_loop, daemon=True).start() + + # Consume с ручным ack и ограниченным prefetch. + conn = pika.BlockingConnection(pika.URLParameters(config.BROKER_URL)) + ch = conn.channel() + ch.basic_qos(prefetch_count=config.WORKER_CONCURRENCY) + ch.basic_consume(queue=broker.QUEUE, on_message_callback=_handle_message, auto_ack=False) + + while not _stop.is_set(): + try: + conn.process_data_events(time_limit=1) + except pika.exceptions.AMQPConnectionError: + log.warning("broker connection lost, reconnecting in 2s") + time.sleep(2) + try: + conn = pika.BlockingConnection(pika.URLParameters(config.BROKER_URL)) + ch = conn.channel() + ch.basic_qos(prefetch_count=config.WORKER_CONCURRENCY) + ch.basic_consume(queue=broker.QUEUE, on_message_callback=_handle_message, + auto_ack=False) + except Exception as exc: + log.warning("reconnect failed: %s", type(exc).__name__) + + try: + ch.stop_consuming() + conn.close() + except Exception: + pass + db.close() + log.info("worker stopped") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/infra/alert-rules.yml b/infra/alert-rules.yml new file mode 100644 index 0000000..83ffd25 --- /dev/null +++ b/infra/alert-rules.yml @@ -0,0 +1,44 @@ +groups: + - name: messenger-api + interval: 15s + rules: + # Доля 5xx среди бизнес-запросов (health исключён) > 5% за 2 минуты. + - alert: ApiHighErrorRate + expr: | + ( + sum(rate(http_server_duration_milliseconds_count{ + http_status_code=~"5..", + http_target!~"/health/.*" + }[2m])) + / + sum(rate(http_server_duration_milliseconds_count{ + http_target!~"/health/.*" + }[2m])) + ) > 0.05 + for: 2m + labels: + severity: warning + annotations: + summary: "API error rate > 5% за 2 минуты" + description: "5xx доля бизнес-запросов превысила 5% в течение 2 минут." + runbook: "Проверить /api/v1 logs в Loki по trace_id из ошибки; проверить health БД/S3/broker." + + - alert: QueueLagHigh + expr: messenger_queue_oldest_job_age_seconds > 60 + for: 2m + labels: + severity: warning + annotations: + summary: "Очередь обработки отстаёт > 60s" + description: "Самая старая задача в queued старше 60 секунд." + runbook: "Проверить worker (docker compose ps worker, logs worker); проверить RabbitMQ; проверить S3/DB latency." + + - alert: QueueLagCritical + expr: messenger_queue_oldest_job_age_seconds > 300 + for: 1m + labels: + severity: critical + annotations: + summary: "Очередь обработки отстаёт > 5 минут" + description: "Обработка не продвигается; возможен отказ worker." + runbook: "Остановить worker → проверить логи; проверить RabbitMQ; replay failed." \ No newline at end of file diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..800fc54 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,431 @@ +{ + "annotations": { + "list": [] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "links": [], + "panels": [ + { + "type": "row", + "title": "API HTTP", + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 0 + }, + "collapsed": false, + "panels": [] + }, + { + "type": "timeseries", + "title": "RPS по route template", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 1 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "sum by (http_target) (rate(http_server_duration_milliseconds_count{http_target!~\"/health/.*\"}[1m]))", + "legendFormat": "{{http_target}}" + } + ] + }, + { + "type": "timeseries", + "title": "Error ratio (5xx / всё, health исключён)", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 1 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "(sum(rate(http_server_duration_milliseconds_count{http_status_code=~\"5..\",http_target!~\"/health/.*\"}[2m])) or vector(0)) / sum(rate(http_server_duration_milliseconds_count{http_target!~\"/health/.*\"}[2m]))", + "legendFormat": "5xx ratio" + } + ] + }, + { + "type": "timeseries", + "title": "Latency p50/p95/p99 (API, ms)", + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 9 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "ms", + "custom": { + "drawStyle": "line", + "fillOpacity": 0 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))", + "legendFormat": "p50" + }, + { + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))", + "legendFormat": "p95" + }, + { + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))", + "legendFormat": "p99" + } + ] + }, + { + "type": "row", + "title": "Worker / Queue", + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 17 + }, + "collapsed": false, + "panels": [] + }, + { + "type": "timeseries", + "title": "Jobs по outcome (rate, 1m)", + "gridPos": { + "h": 8, + "w": 12, + "x": 0, + "y": 18 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))", + "legendFormat": "{{outcome}}" + } + ] + }, + { + "type": "timeseries", + "title": "Job processing duration p50/p95/p99 (s)", + "gridPos": { + "h": 8, + "w": 12, + "x": 12, + "y": 18 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "drawStyle": "line", + "fillOpacity": 0 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))", + "legendFormat": "p50" + }, + { + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))", + "legendFormat": "p95" + }, + { + "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))", + "legendFormat": "p99" + } + ] + }, + { + "type": "timeseries", + "title": "Queue depth (queued)", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 26 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "sum(messenger_queue_depth)", + "legendFormat": "depth" + } + ] + }, + { + "type": "timeseries", + "title": "Oldest job age (s)", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 26 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "yellow", + "value": 60 + }, + { + "color": "red", + "value": 300 + } + ] + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "max(messenger_queue_oldest_job_age_seconds)", + "legendFormat": "oldest age" + } + ] + }, + { + "type": "timeseries", + "title": "Time to ready p50/p95 (s)", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 26 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "drawStyle": "line", + "fillOpacity": 0 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))", + "legendFormat": "p50" + }, + { + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))", + "legendFormat": "p95" + } + ] + }, + { + "type": "row", + "title": "Saturation", + "gridPos": { + "h": 1, + "w": 24, + "x": 0, + "y": 34 + }, + "collapsed": false, + "panels": [] + }, + { + "type": "timeseries", + "title": "Worker busy slots (capacity 2)", + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 35 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + }, + "max": 2 + }, + "overrides": [] + }, + "targets": [ + { + "expr": "sum(messenger_worker_busy)", + "legendFormat": "busy" + } + ] + }, + { + "type": "timeseries", + "title": "DB pool (available / waiting)", + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 35 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "sum by (state) (messenger_db_pool)", + "legendFormat": "{{state}}" + } + ] + }, + { + "type": "timeseries", + "title": "Active HTTP requests", + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 35 + }, + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "drawStyle": "line", + "fillOpacity": 10 + } + }, + "overrides": [] + }, + "targets": [ + { + "expr": "sum(http_server_active_requests)", + "legendFormat": "active" + } + ] + } + ], + "refresh": "10s", + "schemaVersion": 39, + "tags": [ + "messenger", + "lab7" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-15m", + "to": "now" + }, + "timezone": "browser", + "title": "Messenger — lab7", + "uid": "messenger-lab7" +} diff --git a/infra/grafana/provisioning/dashboards.yaml b/infra/grafana/provisioning/dashboards.yaml new file mode 100644 index 0000000..b9d923f --- /dev/null +++ b/infra/grafana/provisioning/dashboards.yaml @@ -0,0 +1,12 @@ +apiVersion: 1 + +providers: + - name: messenger + orgId: 1 + folder: Messenger + type: file + disableDeletion: false + updateIntervalSeconds: 30 + options: + path: /var/lib/grafana/dashboards + foldersFromFilesStructure: false \ No newline at end of file diff --git a/infra/grafana/provisioning/datasources.yaml b/infra/grafana/provisioning/datasources.yaml new file mode 100644 index 0000000..d2d0b32 --- /dev/null +++ b/infra/grafana/provisioning/datasources.yaml @@ -0,0 +1,38 @@ +apiVersion: 1 + +# Все источники — по HTTPS с проверкой сервера. CA стенда добавлен в trust +# через SSL_CERT_FILE (см. compose.yaml, сервис grafana). +# uid закреплены явно: dashboard не должен зависеть от случайного uid Grafana. +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:9090 + isDefault: true + jsonData: + timeInterval: 10s + tlsSkipVerify: false + - name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:3100 + jsonData: + derivedFields: + # Логи — JSON: trace_id лежит в теле строки. + - datasourceUid: tempo + matcherRegex: '"trace_id":\s*"([0-9a-f]{16,32})"' + name: TraceID + url: "$${__value.raw}" + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:3200 + jsonData: + tracesToLogsV2: + datasourceUid: loki + filterByTraceID: true + serviceMap: + datasourceUid: prometheus diff --git a/infra/loki.yaml b/infra/loki.yaml new file mode 100644 index 0000000..e7b1e7b --- /dev/null +++ b/infra/loki.yaml @@ -0,0 +1,57 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + log_level: warn + http_tls_config: + cert_file: /run/secrets/loki_crt + key_file: /run/secrets/loki_key + min_version: TLS12 + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + instance_addr: 127.0.0.1 + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + retention_period: 24h + reject_old_samples: false + # Явная карта OTLP resource attributes → labels/structured metadata. + # service.name становится индексной меткой service_name (используется в + # Grafana и в student-tests). + otlp_config: + resource_attributes: + attributes_config: + - action: index_label + attributes: + - service.name + - action: structured_metadata + attributes: + - service.namespace + - service.version + - service.instance.id + - deployment.environment.name + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem diff --git a/infra/otel-collector.yaml b/infra/otel-collector.yaml new file mode 100644 index 0000000..4779258 --- /dev/null +++ b/infra/otel-collector.yaml @@ -0,0 +1,70 @@ +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 + # TLS обязателен: даже внутри стенда OTLP не принимается plaintext. + # Identity клиента (CN=messenger-api|messenger-worker) проверяет OTLP-ingress + # (nginx :4318) — Collector доступен только из этой сети. + tls: + cert_file: /run/secrets/collector_crt + key_file: /run/secrets/collector_key + grpc: + endpoint: 0.0.0.0:4317 + tls: + cert_file: /run/secrets/collector_crt + key_file: /run/secrets/collector_key + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 200 + spike_limit_mib: 50 + batch: + timeout: 5s + send_batch_size: 1024 + attributes/scrub: + actions: + - key: http.request.header.authorization + action: delete + - key: http.request.header.cookie + action: delete + - key: http.request.header.x-api-key + action: delete + - key: db.connection_string + action: delete + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + tls: + cert_file: /run/secrets/collector_crt + key_file: /run/secrets/collector_key + resource_to_telemetry_conversion: + enabled: true + otlphttp/loki: + endpoint: https://loki:3100/otlp + tls: + ca_file: /run/secrets/ca_servers + otlp/tempo: + endpoint: tempo:4317 + tls: + ca_file: /run/secrets/ca_servers + +service: + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch, attributes/scrub] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch, attributes/scrub] + exporters: [otlphttp/loki] + telemetry: + logs: + level: info diff --git a/infra/prometheus-web.yml b/infra/prometheus-web.yml new file mode 100644 index 0000000..799f64a --- /dev/null +++ b/infra/prometheus-web.yml @@ -0,0 +1,4 @@ +tls_server_config: + cert_file: /run/secrets/prometheus_crt + key_file: /run/secrets/prometheus_key + min_version: TLS12 diff --git a/infra/prometheus.yaml b/infra/prometheus.yaml new file mode 100644 index 0000000..087fea1 --- /dev/null +++ b/infra/prometheus.yaml @@ -0,0 +1,21 @@ +global: + scrape_interval: 10s + evaluation_interval: 10s + +rule_files: + - /etc/prometheus/alert-rules.yml + +scrape_configs: + # Метрики от OTel Collector (TLS-экспортёр :8889, сервер проверяется по CA). + - job_name: otel-collector + scheme: https + tls_config: + ca_file: /etc/prometheus/ca.crt + static_configs: + - targets: ['otel-collector:8889'] + - job_name: prometheus + scheme: https + tls_config: + ca_file: /etc/prometheus/ca.crt + static_configs: + - targets: ['prometheus:9090'] diff --git a/infra/tempo.yaml b/infra/tempo.yaml new file mode 100644 index 0000000..0ae810c --- /dev/null +++ b/infra/tempo.yaml @@ -0,0 +1,38 @@ +server: + http_listen_port: 3200 + grpc_listen_port: 9095 + log_level: warn + tls: + cert_file: /run/secrets/tempo_crt + key_file: /run/secrets/tempo_key + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +ingester: + max_block_duration: 5m + +compactor: + compaction: + block_retention: 24h + +storage: + trace: + backend: local + local: + path: /var/tempo/traces + wal: + path: /var/tempo/wal + +metrics_generator: + registry: + external_labels: + source: tempo + storage: + path: /var/tempo/generator/wal diff --git a/main.py b/main.py new file mode 100644 index 0000000..a080c64 --- /dev/null +++ b/main.py @@ -0,0 +1,509 @@ +"""Мессенджер, лабораторная 7: транспорт HTTPS, mTLS LB→API, секреты из OpenBao. + +Бизнес-API не менялся относительно lab6; изменения касаются границ доверия: + * uvicorn слушает loopback за mTLS-relay (app/relay.py, :8443); + * секреты БД/S3 приходят из OpenBao по AppRole (app/secrets.py); + * вход ограничен rate limit'ом, общим для реплик (PostgreSQL); + * Argon2id + rehash; Kafka/broker и S3 — только TLS. +""" +import hashlib +import logging +import re +import tempfile +import threading +import uuid +from contextlib import asynccontextmanager +from typing import NamedTuple +from urllib.parse import quote + +import anyio.to_thread +import psycopg +from fastapi import Depends, FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from opentelemetry import metrics as metrics_module +from opentelemetry.instrumentation.botocore import BotocoreInstrumentor +from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor +from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor +from starlette.exceptions import HTTPException as StarletteHTTPException + +from app import (attachments, broker, config, cursor, db, idempotency, jobs, + ratelimit, repo, security, sessions, s3, telemetry, validation) +from app.errors import (BASIC_CHALLENGE, BEARER_CHALLENGE, ApiError, + bad_request, not_found, unauthorized) + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") +for _noisy in ("pika", "aiohttp", "urllib3", "botocore", "opentelemetry"): + _l = logging.getLogger(_noisy) + _l.setLevel(logging.WARNING) + _l.propagate = False +log = logging.getLogger("api") + +_REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") +INSTANCE_ID = config.INSTANCE_ID +_stop = threading.Event() + + +def _outbox_loop(): + """API тоже публикует outbox — снижает latency до broker.""" + while not _stop.wait(2): + try: + with db.connection() as conn: + jobs.publish_pending_outbox(conn, broker.publish) + except Exception: + pass + + +def _register_metrics(): + """Observable gauges: SDK сам вызывает callbacks при каждом экспорте. + + Никакого отдельного потока не нужно — MeterProvider с PeriodicExportingMetricReader + сам опрашивает при экспорте. + """ + meter = telemetry.get_meter("messenger-api") + + def _queue_depth(_options): + try: + with db.connection() as conn: + row = conn.execute( + "SELECT count(*) AS c FROM jobs WHERE status='queued'").fetchone() + yield metrics_module.Observation( + int(row["c"] or 0), {"queue.name": broker.QUEUE}) + except Exception: + return + + def _queue_age(_options): + try: + with db.connection() as conn: + row = conn.execute( + """SELECT EXTRACT(EPOCH FROM + COALESCE(now() - min(created_at), '0'::interval))::float AS age + FROM jobs WHERE status='queued'""").fetchone() + yield metrics_module.Observation( + float(row["age"] or 0.0), {"queue.name": broker.QUEUE}) + except Exception: + return + + def _db_pool(_options): + try: + stats = db.get_pool().get_stats() + yield metrics_module.Observation( + int(stats.get("pool_available", 0)), {"state": "available"}) + yield metrics_module.Observation( + int(stats.get("requests_waiting", 0)), {"state": "waiting"}) + except Exception: + return + + meter.create_observable_gauge( + "messenger_queue_depth", callbacks=[_queue_depth], + description="Jobs in queued status") + meter.create_observable_gauge( + "messenger_queue_oldest_job_age_seconds", callbacks=[_queue_age], + description="Age of oldest queued job (seconds)") + meter.create_observable_gauge( + "messenger_db_pool", callbacks=[_db_pool], + description="DB pool state (available/waiting)") + + +@asynccontextmanager +async def lifespan(_app): + anyio.to_thread.current_default_thread_limiter().total_tokens = config.THREAD_LIMIT + + # Psycopg/Botocore можно инструментировать и здесь — они не привязаны к ASGI-приложению. + PsycopgInstrumentor().instrument() + BotocoreInstrumentor().instrument() + _register_metrics() + + threading.Thread(target=_outbox_loop, daemon=True).start() + + try: + broker.declare_only() + except Exception as exc: + log.warning("broker topology init failed: %s", type(exc).__name__) + + yield + _stop.set() + db.close() + + +app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) +# lab6: OTel инициализируется до старта приложения. +# FastAPIInstrumentor.instrument_app() обязан вызываться ДО первого запроса, +# иначе Starlette не даёт добавить middleware. +telemetry.init("messenger-api") +FastAPIInstrumentor.instrument_app(app, excluded_urls="health") + + +def make_error(code, message, request_id): + return {"error": {"code": code, "message": message, "request_id": request_id}} + + +def _rid(request): + return getattr(request.state, "request_id", None) or uuid.uuid4().hex + + +def error_response(request, status, code, message, headers=None): + rid = _rid(request) + out = {"X-Request-Id": rid, "X-Instance-Id": INSTANCE_ID, "Cache-Control": "no-store"} + out.update(headers or {}) + return JSONResponse(status_code=status, content=make_error(code, message, rid), headers=out) + + +@app.middleware("http") +async def add_request_id(request: Request, call_next): + incoming = request.headers.get("X-Request-Id", "") + rid = incoming if _REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex + request.state.request_id = rid + response = await call_next(request) + response.headers["X-Request-Id"] = rid + response.headers["X-Instance-Id"] = INSTANCE_ID + response.headers["Cache-Control"] = "no-store" + return response + + +@app.exception_handler(ApiError) +async def api_error_handler(request: Request, exc: ApiError): + return error_response(request, exc.status, exc.code, exc.message, exc.headers) + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc): + return error_response(request, 400, "invalid_request", "Некорректный запрос") + + +@app.exception_handler(StarletteHTTPException) +async def http_exc_handler(request: Request, exc: StarletteHTTPException): + mapping = {404: ("not_found", "Объект не найден"), 405: ("invalid_request", "Метод не поддерживается")} + code, message = mapping.get(exc.status_code, ("invalid_request", "Ошибка запроса")) + return error_response(request, exc.status_code, code, message) + + +@app.exception_handler(Exception) +async def generic_handler(request: Request, exc: Exception): + if isinstance(exc, db.TRANSIENT): + log.warning("dependency unavailable [%s]: %s", _rid(request), type(exc).__name__) + return error_response(request, 503, "unavailable", "Сервис временно недоступен") + log.error("unhandled error [%s]", _rid(request), exc_info=exc) + return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") + + +class Auth(NamedTuple): + user: dict + user_id: uuid.UUID + digest: bytes + + +def authenticated(request: Request) -> Auth: + token = security.parse_bearer(request.headers.get("Authorization")) + if token is None: + raise unauthorized(BEARER_CHALLENGE) + found = sessions.lookup(token) + if found is None: + raise unauthorized(BEARER_CHALLENGE) + return Auth(found["user"], uuid.UUID(found["user"]["id"]), found["digest"]) + + +class RawBody(NamedTuple): + content_type: str + data: bytes + + +async def raw_body(request: Request) -> RawBody: + declared = request.headers.get("content-length") + if declared is not None and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + chunks, size = [], 0 + async for chunk in request.stream(): + size += len(chunk) + if size > config.MAX_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + chunks.append(chunk) + return RawBody(request.headers.get("content-type", ""), b"".join(chunks)) + + +@app.get("/health/live") +def live(): + return {"status": "ok"} + + +@app.get("/health/ready") +def ready(): + try: + db.ping() + except Exception: + raise ApiError(503, "unavailable", "PostgreSQL недоступен") + try: + s3.ping() + except Exception: + raise ApiError(503, "unavailable", "S3 недоступен") + try: + if not broker.wait_ready(timeout=2): + raise ApiError(503, "unavailable", "Broker недоступен") + except ApiError: + raise + except Exception: + raise ApiError(503, "unavailable", "Broker недоступен") + return {"status": "ok"} + + +# ---------- пользователи / сессии / чаты ---------- + +@app.post("/api/v1/users", status_code=201) +def create_user(body: RawBody = Depends(raw_body)): + data = validation.json_body(body.content_type, body.data, + {"username", "display_name", "password"}, + {"username", "display_name", "password"}) + username = validation.username_field(data["username"]) + display_name = validation.text_field(data["display_name"], "display_name", 1, 100) + password = validation.text_field(data["password"], "password", 12, 128) + with db.connection() as conn: + if repo.username_exists(conn, username): + raise ApiError(409, "conflict", "Имя пользователя занято") + password_hash = security.hash_password(password) + try: + with db.connection() as conn: + row = repo.insert_user(conn, username, display_name, password_hash) + except psycopg.errors.UniqueViolation: + raise ApiError(409, "conflict", "Имя пользователя занято") + return sessions.user_json(row) + + +@app.get("/api/v1/users/me") +def get_me(auth: Auth = Depends(authenticated)): + return auth.user + + +def _client_ip(request): + """LB (nginx) ставит X-Real-IP; других путей к бизнес-API нет — mTLS relay.""" + forwarded = (request.headers.get("X-Real-IP") or "").strip() + if forwarded: + return forwarded[:64] + return request.client.host if request.client else "unknown" + + +@app.post("/api/v1/auth/sessions", status_code=201) +def login(request: Request): + creds = security.parse_basic(request.headers.get("Authorization")) + if creds is None: + raise unauthorized(BASIC_CHALLENGE) + username, password = creds + + # Rate limit общий для реплик (PostgreSQL) и стоит ДО Argon2: он ограничивает + # бюджет дорогого хеширования, а не только число ответов. + ip = _client_ip(request) + user_bucket = "user:" + (username.strip().lower()[:64] or "-") + with db.connection() as conn: + ratelimit.cleanup(conn) + ip_ok, ip_retry = ratelimit.hit(conn, "ip:" + ip, config.LOGIN_RATE_IP_PER_WINDOW) + user_ok, user_retry = ratelimit.hit(conn, user_bucket, config.LOGIN_RATE_USER_PER_WINDOW) + if not (ip_ok and user_ok): + retry_after = str(max(ip_retry, user_retry)) + raise ApiError(429, "rate_limited", "Слишком много попыток входа", + {"Retry-After": retry_after}) + + with db.connection() as conn: + user = repo.user_for_login(conn, username) if validation._USERNAME_RE.fullmatch(username) else None + if user is None: + security.burn_verify(password) + raise unauthorized(BASIC_CHALLENGE) + ok, new_hash = security.verify_password(user["password_hash"], password) + if not ok: + raise unauthorized(BASIC_CHALLENGE) + with db.connection() as conn: + if new_hash: + repo.update_password_hash(conn, user["id"], new_hash) + token, expires_at = sessions.create(conn, user) + return {"token": token, "token_type": "Bearer", + "expires_at": sessions.fmt_ts(expires_at), "user": sessions.user_json(user)} + + +@app.delete("/api/v1/auth/sessions/current") +def logout(auth: Auth = Depends(authenticated)): + sessions.revoke(auth.digest) + return Response(status_code=204) + + +@app.post("/api/v1/chats", status_code=201) +def create_chat(auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)): + data = validation.json_body(body.content_type, body.data, + {"title", "member_ids"}, {"title", "member_ids"}) + title = validation.text_field(data["title"], "title", 1, 100) + raw = data["member_ids"] + if not isinstance(raw, list) or not 1 <= len(raw) <= 100: + raise bad_request("member_ids: от 1 до 100 элементов") + members = [validation.require_uuid(x, "member_id") for x in raw] + if len(set(members)) != len(members) or auth.user_id not in members: + raise bad_request("member_ids должны быть уникальны и включать вызывающего") + with db.connection() as conn: + chat = repo.create_chat(conn, auth.user_id, title, members) + return repo.chat_json(chat) + + +@app.get("/api/v1/chats") +def list_chats(request: Request, auth: Auth = Depends(authenticated)): + limit = validation.limit_param(request.query_params) + raw = request.query_params.get("cursor") + after = cursor.decode(raw, "chats", auth.user_id) if raw is not None else None + with db.connection() as conn: + items, nxt = repo.list_chats(conn, auth.user_id, after, limit) + return {"items": items, "next_cursor": nxt} + + +@app.get("/api/v1/chats/{chat_id}") +def get_chat(chat_id: str, auth: Auth = Depends(authenticated)): + cid = validation.require_uuid(chat_id, "chat_id") + with db.connection() as conn: + chat = repo.get_chat(conn, cid, auth.user_id) + if chat is None: + raise not_found() + return repo.chat_json(chat) + + +# ---------- сообщения ---------- + +def _parse_attachment_ids(data): + raw = data.get("attachment_ids", []) + if not isinstance(raw, list) or len(raw) > 10: + raise bad_request("attachment_ids: до 10 элементов") + ids = [validation.require_uuid(x, "attachment_id") for x in raw] + if len(set(ids)) != len(ids): + raise bad_request("attachment_ids должны быть уникальны") + return ids + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +def create_message(chat_id: str, request: Request, auth: Auth = Depends(authenticated), + body: RawBody = Depends(raw_body)): + cid = validation.require_uuid(chat_id, "chat_id") + with db.connection() as conn: + if not repo.is_member(conn, cid, auth.user_id): + raise not_found() + + data = validation.json_body(body.content_type, body.data, + {"text", "attachment_ids"}, {"text"}) + text = validation.text_field(data["text"], "text", 0, 4000, allow_blank=True) + attachment_ids = _parse_attachment_ids(data) + if not text.strip() and not attachment_ids: + raise bad_request("Пустое сообщение без вложений") + + idem_key = request.headers.get("Idempotency-Key") + path = "/api/v1/chats/%s/messages" % chat_id + req_hash = idempotency.get_request_hash(data) + + with db.connection() as conn: + idempotency.cleanup(conn, config.IDEMPOTENCY_TTL_SECONDS) + need_exec, cached = idempotency.check_and_lock( + conn, str(auth.user_id), "POST", path, idem_key, req_hash) + if not need_exec: + return JSONResponse(status_code=201, content=cached) + msg = repo.insert_message(conn, cid, auth.user_id, text, attachment_ids) + msg_json = repo.message_json(msg) + idempotency.save_result(conn, str(auth.user_id), "POST", path, idem_key, + req_hash, 201, msg_json) + return msg_json + + +@app.get("/api/v1/chats/{chat_id}/messages") +def list_messages(chat_id: str, request: Request, auth: Auth = Depends(authenticated)): + cid = validation.require_uuid(chat_id, "chat_id") + limit = validation.limit_param(request.query_params) + raw = request.query_params.get("cursor") + after = cursor.decode(raw, "messages", cid) if raw is not None else None + with db.connection() as conn: + if not repo.is_member(conn, cid, auth.user_id): + raise not_found() + items, nxt = repo.list_messages(conn, cid, after, limit) + return {"items": items, "next_cursor": nxt} + + +# ---------- вложения (lab5: 202 queued) ---------- + +@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202) +async def upload_attachment(chat_id: str, request: Request, auth: Auth = Depends(authenticated)): + cid = validation.require_uuid(chat_id, "chat_id") + filename = request.query_params.get("filename") + if filename is None: + raise bad_request("filename обязателен") + + declared = request.headers.get("content-type", "").split(";")[0].strip().lower() + if declared not in ("image/png", "image/jpeg"): + raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg") + + def _check_member(): + with db.connection() as conn: + return repo.is_member(conn, cid, auth.user_id) + + if not await anyio.to_thread.run_sync(_check_member): + raise not_found() + + declared_len = request.headers.get("content-length") + if declared_len is not None and declared_len.isdigit() and int(declared_len) > config.MAX_UPLOAD_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + + spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024) + hasher = hashlib.sha256() + total = 0 + try: + async for chunk in request.stream(): + total += len(chunk) + if total > config.MAX_UPLOAD_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + hasher.update(chunk) + spool.write(chunk) + if total == 0: + raise bad_request("Пустой файл") + spool.seek(0) + digest = hasher.hexdigest() + + def _process(): + actual = attachments.inspect_image_header(spool, total) + if actual != declared: + raise ApiError(415, "unsupported_media_type", "MIME не соответствует содержимому") + return attachments.upload_to_staging( + cid, auth.user_id, filename, spool, total, digest, actual) + + row = await anyio.to_thread.run_sync(_process) + return repo.attachment_json(row) + finally: + spool.close() + + +@app.get("/api/v1/attachments/{attachment_id}") +def get_attachment(attachment_id: str, auth: Auth = Depends(authenticated)): + aid = validation.require_uuid(attachment_id, "attachment_id") + with db.connection() as conn: + row = repo.get_attachment_for_member(conn, aid, auth.user_id) + if row is None: + raise not_found() + variants = repo.list_variants(conn, aid) + return repo.attachment_json(row, variants) + + +@app.get("/api/v1/attachments/{attachment_id}/content") +async def download_attachment(attachment_id: str, request: Request, + auth: Auth = Depends(authenticated)): + aid = validation.require_uuid(attachment_id, "attachment_id") + variant_name = request.query_params.get("variant", "original") + if variant_name not in ("original", "thumbnail", "crop", "optimized"): + raise bad_request("variant: original|thumbnail|crop|optimized") + + def _read_all(): + if variant_name == "original": + row, body = attachments.download_original(aid, auth.user_id) + try: + data = body.read() + finally: + body.close() + return row, data + v, body = attachments.download_variant(aid, auth.user_id, variant_name) + try: + data = body.read() + finally: + body.close() + return v, data + + row, data = await anyio.to_thread.run_sync(_read_all) + if variant_name == "original": + headers = {"Content-Disposition": "attachment; filename*=UTF-8''%s" % quote(row["filename"], safe="")} + return Response(content=data, media_type=row["content_type"], headers=headers) + return Response(content=data, media_type=row["content_type"]) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2871689 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,36 @@ +boto3==1.43.107 +Pillow==12.3.0 +annotated-types==0.8.0 +anyio==4.15.1 +argon2-cffi==25.1.0 +argon2-cffi-bindings==26.1.0 +cffi==2.1.1 +click==8.5.0 +fastapi==0.115.0 +h11==0.16.0 +httptools==0.9.0 +idna==3.20 +psycopg==3.2.9 +psycopg-binary==3.2.9 +psycopg-pool==3.2.6 +pycparser==3.11 +pydantic==2.14.1 +pydantic_core==2.50.1 +python-dotenv==1.2.4 +PyYAML==6.0.3 +starlette==0.38.6 +typing-inspection==0.4.4 +typing_extensions==4.16.0 +uvicorn==0.30.6 +uvloop==0.23.0 +watchfiles==1.3.0 +websockets==17.2 +pika==1.3.2 +opentelemetry-api==1.27.0 +opentelemetry-sdk==1.27.0 +opentelemetry-exporter-otlp-proto-http==1.27.0 +opentelemetry-instrumentation-fastapi==0.48b0 +opentelemetry-instrumentation-psycopg==0.48b0 +opentelemetry-instrumentation-botocore==0.48b0 +opentelemetry-instrumentation-pika==0.48b0 +opentelemetry-instrumentation-logging==0.48b0