Создала общий модуль OTel для API и worker
This commit is contained in:
+153
-35
@@ -1,9 +1,14 @@
|
||||
x-lab-number: 4
|
||||
x-lab-number: 6
|
||||
x-required-roles:
|
||||
- api
|
||||
- postgres
|
||||
- load_balancer
|
||||
- s3
|
||||
- broker
|
||||
- worker
|
||||
- otel_collector
|
||||
- telemetry_storage
|
||||
- grafana
|
||||
|
||||
services:
|
||||
postgres:
|
||||
@@ -70,8 +75,6 @@ services:
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
# Консоль администратора НЕ публикуется наружу; доступ только из сети compose.
|
||||
# Порт 9000 (S3 API) тоже внутренний — публичного доступа нет.
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -92,12 +95,8 @@ services:
|
||||
- |
|
||||
set -eu
|
||||
mc alias set local http://minio:9000 "$${MINIO_ROOT_USER}" "$${MINIO_ROOT_PASSWORD}"
|
||||
# Приватный bucket; idempotent.
|
||||
mc mb --ignore-existing local/"$${S3_BUCKET}"
|
||||
# Политика: bucket не публичный. Явно none.
|
||||
mc anonymous set none local/"$${S3_BUCKET}" || true
|
||||
# Прикладные S3-credentials с ограниченными правами на префикс приложения.
|
||||
# Политика выдаётся через `mc admin policy`; создаём отдельного пользователя.
|
||||
if ! mc admin user info local "$${S3_APP_KEY_ID}" >/dev/null 2>&1; then
|
||||
mc admin user add local "$${S3_APP_KEY_ID}" "$${S3_APP_SECRET_KEY}"
|
||||
fi
|
||||
@@ -105,28 +104,15 @@ services:
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::${S3_BUCKET}"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject", "s3:PutObject", "s3:DeleteObject",
|
||||
"s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"
|
||||
],
|
||||
"Resource": ["arn:aws:s3:::${S3_BUCKET}/*"]
|
||||
}
|
||||
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"], "Resource": ["arn:aws:s3:::${S3_BUCKET}"]},
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"], "Resource": ["arn:aws:s3:::${S3_BUCKET}/*"]}
|
||||
]
|
||||
}
|
||||
POLICY
|
||||
# Подставляем имя bucket в политику
|
||||
sed -i "s/\$${S3_BUCKET}/$${S3_BUCKET}/g" /tmp/app-policy.json || true
|
||||
mc admin policy create local messenger-app /tmp/app-policy.json 2>/dev/null || true
|
||||
mc admin policy attach local messenger-app --user "$${S3_APP_KEY_ID}" || true
|
||||
echo "minio-init done"
|
||||
# Административные credentials нужны только здесь и в minio.
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin}
|
||||
@@ -142,9 +128,8 @@ services:
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.storage.db"]
|
||||
# Явный whitelist переменных: без MINIO_ROOT_USER/PASSWORD.
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
@@ -191,7 +176,7 @@ services:
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.worker"]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
@@ -202,6 +187,10 @@ services:
|
||||
S3_APP_KEY_ID: ${S3_APP_KEY_ID}
|
||||
S3_APP_SECRET_KEY: ${S3_APP_SECRET_KEY}
|
||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
@@ -209,6 +198,8 @@ services:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
@@ -221,17 +212,23 @@ services:
|
||||
|
||||
outbox:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.outbox_worker"]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||
OTEL_SERVICE_NAME: messenger-outbox
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
@@ -241,10 +238,7 @@ services:
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
# Явный whitelist переменных: приложение не получает административные
|
||||
# credentials MinIO (MINIO_ROOT_USER/PASSWORD). Для S3 — только
|
||||
# прикладные S3_APP_KEY_ID/S3_APP_SECRET_KEY с ограниченной политикой.
|
||||
image: mtuci-messenger:lab6
|
||||
environment:
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
@@ -263,6 +257,10 @@ services:
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-300}
|
||||
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-3600}
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
@@ -272,6 +270,8 @@ services:
|
||||
condition: service_healthy
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready').read()"]
|
||||
interval: 5s
|
||||
@@ -289,13 +289,10 @@ services:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
# Уровень 4: фоновая сверка S3↔БД (orphan-объекты и missing).
|
||||
# Запускается как долгоживущий сервис, спит CLEANUP_INTERVAL_SECONDS.
|
||||
s3_cleanup:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.storage.s3_cleanup"]
|
||||
# Явный whitelist переменных: без административных кредов MinIO.
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
@@ -341,6 +338,119 @@ services:
|
||||
cpus: "0.1"
|
||||
memory: 32M
|
||||
|
||||
# ---------- Observability: lab6 ----------
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.108.0
|
||||
container_name: mtuci-otel-collector
|
||||
command: ["--config=/etc/otel/collector.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
|
||||
depends_on:
|
||||
- tempo
|
||||
- loki
|
||||
- prometheus
|
||||
# Порты OTLP наружу не публикуем: API/worker/outbox в той же сети.
|
||||
# health-порт тоже внутри compose-сети.
|
||||
healthcheck:
|
||||
test: ["CMD", "/otelcol-contrib", "--version"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 256M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 64M
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.54.1
|
||||
container_name: mtuci-prometheus
|
||||
command:
|
||||
- "--config.file=/etc/prometheus/prometheus.yaml"
|
||||
- "--storage.tsdb.path=/prometheus"
|
||||
- "--storage.tsdb.retention.time=15d"
|
||||
- "--web.listen-address=0.0.0.0:9090"
|
||||
volumes:
|
||||
- ./infra/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- ./infra/prometheus/rules:/etc/prometheus/rules:ro
|
||||
- prometheus-data:/prometheus
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.1.1
|
||||
container_name: mtuci-loki
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
volumes:
|
||||
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- loki-data:/loki
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.5.0
|
||||
container_name: mtuci-tempo
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
volumes:
|
||||
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempo-data:/var/tempo
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.2.0
|
||||
container_name: mtuci-grafana
|
||||
environment:
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "true"
|
||||
GF_AUTH_ANONYMOUS_ORG_ROLE: "Admin"
|
||||
GF_AUTH_DISABLE_LOGIN_FORM: "true"
|
||||
GF_FEATURE_TOGGLES_ENABLE: "traceqlEditor"
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin}
|
||||
volumes:
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- grafana-data:/var/lib/grafana
|
||||
ports:
|
||||
- "127.0.0.1:3000:3000"
|
||||
depends_on:
|
||||
- prometheus
|
||||
- loki
|
||||
- tempo
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.3"
|
||||
memory: 256M
|
||||
reservations:
|
||||
cpus: "0.05"
|
||||
memory: 64M
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
name: mtuci2026lab5_postgres-data
|
||||
@@ -350,7 +460,15 @@ volumes:
|
||||
name: mtuci2026lab5_minio-data
|
||||
rabbitmq-data:
|
||||
name: mtuci2026lab5_rabbitmq-data
|
||||
prometheus-data:
|
||||
name: mtuci2026lab6_prometheus-data
|
||||
loki-data:
|
||||
name: mtuci2026lab6_loki-data
|
||||
tempo-data:
|
||||
name: mtuci2026lab6_tempo-data
|
||||
grafana-data:
|
||||
name: mtuci2026lab6_grafana-data
|
||||
|
||||
networks:
|
||||
default:
|
||||
name: mtuci2026lab5_default
|
||||
name: mtuci2026lab6_default
|
||||
@@ -0,0 +1,60 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
|
||||
processors:
|
||||
# Level-4: ограничение RAM и batch, чтобы не расти бесконечно при
|
||||
# недоступном backend и уменьшить объём записи.
|
||||
memory_limiter:
|
||||
check_interval: 2s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 64
|
||||
batch:
|
||||
timeout: 5s
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
resource:
|
||||
attributes:
|
||||
- key: deployment.environment.name
|
||||
value: lab
|
||||
action: upsert
|
||||
|
||||
exporters:
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
tls:
|
||||
insecure: true
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
tls:
|
||||
insecure: true
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
send_timestamps: true
|
||||
metric_expiration: 5m
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: warn
|
||||
metrics:
|
||||
address: 0.0.0.0:8888
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,12 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yaml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
scrape_interval: 5s
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
+6
-2
@@ -3,7 +3,11 @@ uvicorn[standard]==0.32.0
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg_pool==3.2.3
|
||||
redis==5.2.0
|
||||
openapi-spec-validator==0.7.2
|
||||
boto3==1.35.74
|
||||
Pillow==11.0.0
|
||||
pika==1.3.2
|
||||
pika==1.3.2
|
||||
opentelemetry-api==1.28.2
|
||||
opentelemetry-sdk==1.28.2
|
||||
opentelemetry-exporter-otlp-proto-http==1.28.2
|
||||
opentelemetry-instrumentation-fastapi==0.49b2
|
||||
opentelemetry-instrumentation-requests==0.49b2
|
||||
+53
-21
@@ -12,11 +12,13 @@ from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from .api import attachments, auth, chats, health, messages, users
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
# --- Логирование: структурный stdout, без содержимого сообщений ---
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
@@ -24,14 +26,10 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
# X-Instance-Id: стабильный в пределах жизни процесса. Значение приходит
|
||||
# из env INSTANCE_ID (задаётся Dockerfile/Compose) либо генерируется один раз.
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами
|
||||
init_pool()
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
@@ -44,12 +42,37 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab5",
|
||||
version="1.5.0",
|
||||
title="MTUCI Messenger — lab6",
|
||||
version="1.6.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
# OTel инициализация и FastAPI auto-instrumentation.
|
||||
init_telemetry("messenger-api", "1.6.0")
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
|
||||
# --- Метрики HTTP из контракта observability.md ---
|
||||
_http_counter = meter("messenger").create_counter(
|
||||
"http_requests_total",
|
||||
description="HTTP requests count",
|
||||
unit="1",
|
||||
)
|
||||
_http_hist = meter("messenger").create_histogram(
|
||||
"http_request_duration_seconds",
|
||||
description="HTTP request duration",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
# Хелпер: убираем реальные UUID из маршрута → route template.
|
||||
import re as _re
|
||||
_ROUTE_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}")
|
||||
|
||||
|
||||
def _route_template(path: str) -> str:
|
||||
return _ROUTE_UUID_RE.sub("{id}", path)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
@@ -64,15 +87,31 @@ app.openapi = custom_openapi
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог."""
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог + метрики."""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
path = request.url.path
|
||||
route = _route_template(path)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
|
||||
# Только low-cardinality labels: method, route template, status class.
|
||||
_http_counter.add(
|
||||
1,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
_http_hist.record(
|
||||
duration_s,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
||||
request.method, path, response.status_code,
|
||||
@@ -81,7 +120,7 @@ async def observability_middleware(request: Request, call_next):
|
||||
return response
|
||||
|
||||
|
||||
# Словарь HTTP-кодов → кодов ошибок из контракта
|
||||
# --- Обработчики ошибок (без изменений с lab5) ---
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
@@ -96,22 +135,17 @@ _ERROR_CODES = {
|
||||
|
||||
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
"""Basic — только для POST /api/v1/auth/sessions; остальное — Bearer."""
|
||||
if path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def _error_response(
|
||||
status_code: int, message: str, request_id: str, path: str = ""
|
||||
) -> JSONResponse:
|
||||
def _error_response(status_code: int, message: str, request_id: str,
|
||||
path: str = "") -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
# Контракт: X-Request-Id и X-Instance-Id обязательны во ВСЕХ ответах,
|
||||
# включая 500, которые формируются в обход middleware (exception handlers
|
||||
# срабатывают ПОСЛЕ call_next). Проставляем их здесь явно.
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return JSONResponse(
|
||||
@@ -136,7 +170,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
@@ -179,12 +212,11 @@ if __name__ == "__main__":
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info"
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn."""
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
"""Outbox worker lab5 level 4: publish неопубликованных job в RabbitMQ.
|
||||
|
||||
Закрывает разрыв COMMIT → publish: если API упал после COMMIT, outbox
|
||||
осталась в БД; этот процесс опубликует её после рестарта. Publisher
|
||||
confirm гарантирует приём брокером перед mark published.
|
||||
"""
|
||||
"""Outbox worker lab5/lab6: publish неопубликованных job в RabbitMQ с трейсингом."""
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .storage.postgres import storage
|
||||
from .storage.rabbit import publish_job
|
||||
from .storage.rabbit import EXCHANGE, QUEUE, publish_job
|
||||
from .telemetry import init_telemetry
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -22,6 +23,10 @@ logging.basicConfig(
|
||||
log = logging.getLogger("outbox")
|
||||
|
||||
_stop = False
|
||||
_tracer = trace.get_tracer("outbox")
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
init_telemetry("messenger-outbox", "1.6.0")
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
@@ -30,6 +35,28 @@ def _handle_sigterm(signum, frame):
|
||||
_stop = True
|
||||
|
||||
|
||||
def _publish_with_trace(payload: dict) -> None:
|
||||
"""Публикует payload с traceparent, чтобы consumer дал child span.
|
||||
|
||||
При ошибке пусть летит наверх — outbox ретраит сам.
|
||||
"""
|
||||
carrier: dict[str, str] = {}
|
||||
with _tracer.start_as_current_span(
|
||||
"job.publish", kind=SpanKind.PRODUCER,
|
||||
attributes={"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE,
|
||||
"job.id": str(payload.get("job_id", ""))},
|
||||
) as span:
|
||||
try:
|
||||
_propagator.inject(carrier)
|
||||
publish_job(payload, extra_headers=carrier)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception as exc:
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
raise
|
||||
|
||||
|
||||
def main() -> None:
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
init_pool()
|
||||
@@ -48,7 +75,7 @@ def main() -> None:
|
||||
if _stop:
|
||||
break
|
||||
try:
|
||||
publish_job(payload)
|
||||
_publish_with_trace(payload)
|
||||
storage.mark_outbox_published(outbox_id)
|
||||
log.info("event=outbox_published id=%s job_id=%s",
|
||||
outbox_id, payload.get("job_id"))
|
||||
@@ -57,7 +84,6 @@ def main() -> None:
|
||||
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
||||
outbox_id, type(exc).__name__, str(exc)[:300],
|
||||
)
|
||||
# не выходим, попробуем в следующем цикле
|
||||
time.sleep(2)
|
||||
break
|
||||
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||
- DLQ: финальные ошибки и исчерпанные retry.
|
||||
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||
|
||||
ВАЖНО: setup_topology вызывается в worker при старте и в outbox
|
||||
однократно при первом publish. Не декларируем топологию на каждый
|
||||
publish — иначе гонка с параллельными декларациями.
|
||||
- lab6: extra_headers для traceparent/tracestate.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
@@ -88,14 +85,15 @@ def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> N
|
||||
_topology_ready = True
|
||||
|
||||
|
||||
def publish_job(payload: dict) -> None:
|
||||
"""Публикация job с publisher confirm. Бросает при неудаче."""
|
||||
def publish_job(payload: dict, extra_headers: Optional[dict] = None) -> None:
|
||||
"""Публикация job с publisher confirm. extra_headers — traceparent."""
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
headers = dict(extra_headers or {})
|
||||
ch.basic_publish(
|
||||
exchange=EXCHANGE,
|
||||
routing_key=QUEUE,
|
||||
@@ -103,6 +101,7 @@ def publish_job(payload: dict) -> None:
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
headers=headers or None,
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Единая точка инициализации OpenTelemetry для API и worker.
|
||||
|
||||
- Отдаём OTLP/HTTP в Collector (otel-collector:4318).
|
||||
- resource attributes: service.name / service.version / service.instance.id /
|
||||
deployment.environment.name=lab.
|
||||
- Без сетевых зависимостей в момент старта: экспортёр сам буферизует и
|
||||
ретраит. При недоступности Collector приложение продолжает работать
|
||||
(см. README уровня 4).
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import uuid
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
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 Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
|
||||
|
||||
_INITIALIZED = False
|
||||
|
||||
# Instance id: стабильный в пределах процесса. Отличается у каждой реплики.
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
# OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||
return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||
|
||||
|
||||
def _resource(service_name: str, service_version: str) -> Resource:
|
||||
return Resource.create(
|
||||
{
|
||||
"service.name": service_name,
|
||||
"service.version": service_version,
|
||||
"service.instance.id": INSTANCE_ID,
|
||||
"deployment.environment.name": os.environ.get("APP_ENV", "lab"),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _build_trace_provider(resource: Resource) -> TracerProvider:
|
||||
provider = TracerProvider(resource=resource)
|
||||
exporter = OTLPSpanExporter(
|
||||
endpoint=_endpoint() + "/v1/traces",
|
||||
timeout=5,
|
||||
)
|
||||
provider.add_span_processor(BatchSpanProcessor(exporter, max_queue_size=2048,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=2000))
|
||||
return provider
|
||||
|
||||
|
||||
def _build_meter_provider(resource: Resource) -> MeterProvider:
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=_endpoint() + "/v1/metrics", timeout=5),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
return MeterProvider(resource=resource, metric_readers=[reader])
|
||||
|
||||
|
||||
def _build_logger_provider(resource: Resource) -> LoggerProvider:
|
||||
provider = LoggerProvider(resource=resource)
|
||||
provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=_endpoint() + "/v1/logs", timeout=5),
|
||||
max_queue_size=2048,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=2000,
|
||||
)
|
||||
)
|
||||
return provider
|
||||
|
||||
|
||||
def init_telemetry(service_name: str, service_version: str = "1.6.0") -> None:
|
||||
"""Инициализация OTel. Идемпотентна в пределах процесса."""
|
||||
global _INITIALIZED
|
||||
if _INITIALIZED:
|
||||
return
|
||||
|
||||
resource = _resource(service_name, service_version)
|
||||
trace.set_tracer_provider(_build_trace_provider(resource))
|
||||
metrics.set_meter_provider(_build_meter_provider(resource))
|
||||
logger_provider = _build_logger_provider(resource)
|
||||
set_logger_provider(logger_provider)
|
||||
|
||||
# Прокидываем OTel лог-хендлер в корневой logger, чтобы все `logging.info`
|
||||
# шли и в stdout (basicConfig ниже), и в OTLP/Loki через Collector.
|
||||
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
root = logging.getLogger()
|
||||
root.addHandler(handler)
|
||||
|
||||
_INITIALIZED = True
|
||||
logging.getLogger("telemetry").info(
|
||||
"event=otel_init service=%s instance_id=%s endpoint=%s",
|
||||
service_name, INSTANCE_ID, _endpoint(),
|
||||
)
|
||||
|
||||
|
||||
def tracer(name: str = "app"):
|
||||
return trace.get_tracer(name)
|
||||
|
||||
|
||||
def meter(name: str = "app"):
|
||||
return metrics.get_meter(name)
|
||||
+108
-80
@@ -1,10 +1,9 @@
|
||||
"""Worker lab5: обработка вложений из RabbitMQ.
|
||||
"""Worker lab5/lab6: обработка вложений из RabbitMQ с трейсингом.
|
||||
|
||||
- at-least-once: manual ack после durable эффекта.
|
||||
- идемпотентность: ключ (attachment_id, pipeline_version, variant).
|
||||
- retry с backoff через TTL retry-очереди, затем DLQ.
|
||||
- lease: processing_until, зависшие возвращаются в queued.
|
||||
- thumbnail 256×256 (JPEG), crop 128×128 (JPEG), optimized WebP 1280×1280.
|
||||
- at-least-once, идемпотентно, retry через TTL-очереди, DLQ.
|
||||
- OTel: consumer span на каждый job, извлечение trace context из заголовков
|
||||
сообщения (W3C traceparent/tracestate).
|
||||
- Метрики: jobs_processed_total{outcome}, job_processing_duration_seconds.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
@@ -13,10 +12,14 @@ import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import pika
|
||||
from PIL import Image, ImageOps
|
||||
from opentelemetry import context as otel_context, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from .storage import s3
|
||||
from .storage.db import init_pool, close_pool
|
||||
@@ -25,6 +28,7 @@ from .storage.rabbit import (
|
||||
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
||||
publish_retry, publish_dlq,
|
||||
)
|
||||
from .telemetry import init_telemetry, meter
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -41,6 +45,23 @@ OPT_SIZE = (1280, 1280)
|
||||
OPT_QUALITY = 82
|
||||
|
||||
_stop = False
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
# OTel инициализация — до первого сообщения.
|
||||
init_telemetry("messenger-worker", "1.6.0")
|
||||
_tracer = trace.get_tracer("worker")
|
||||
_meter = meter("messenger-worker")
|
||||
_jobs_counter = _meter.create_counter(
|
||||
"jobs_processed_total",
|
||||
description="Jobs processed by outcome",
|
||||
unit="1",
|
||||
)
|
||||
_jobs_hist = _meter.create_histogram(
|
||||
"job_processing_duration_seconds",
|
||||
description="Job processing duration",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
@@ -54,7 +75,6 @@ def _now_iso() -> str:
|
||||
|
||||
|
||||
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||
"""Alpha компонуется на белый; EXIF orientation применяется."""
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGBA")
|
||||
@@ -67,7 +87,6 @@ def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||
|
||||
|
||||
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""Вписать в 256×256 без увеличения. Округление вниз, минимум 1 px."""
|
||||
w, h = img.size
|
||||
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
@@ -79,7 +98,6 @@ def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
|
||||
|
||||
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""Центрированный квадрат 128×128 (маленькие допускают увеличение)."""
|
||||
w, h = img.size
|
||||
side = min(w, h)
|
||||
left = (w - side) // 2
|
||||
@@ -92,7 +110,6 @@ def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
|
||||
|
||||
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""WebP, вписан в 1280×1280 без увеличения, EXIF удалён."""
|
||||
w, h = img.size
|
||||
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
@@ -109,7 +126,7 @@ def _sha256(data: bytes) -> str:
|
||||
|
||||
|
||||
def process_job(payload: dict) -> None:
|
||||
"""Обработка одного job. Идемпотентна: finalize_ready использует ON CONFLICT."""
|
||||
"""Обработка одного job. Идемпотентна через finalize_ready."""
|
||||
attachment_id = payload["attachment_id"]
|
||||
pipeline_version = payload.get("pipeline_version", 1)
|
||||
job_id = payload["job_id"]
|
||||
@@ -117,12 +134,10 @@ def process_job(payload: dict) -> None:
|
||||
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
||||
job_id, attachment_id, payload.get("attempt", 1))
|
||||
|
||||
# 1) Захватить lease. Если уже ready/failed — no-op (дубль).
|
||||
if not storage.claim_processing(attachment_id, LEASE_SECONDS):
|
||||
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
# 2) Получить staging key и метаданные.
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
||||
@@ -132,14 +147,11 @@ def process_job(payload: dict) -> None:
|
||||
log.info("event=already_ready attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
# 3) Скачать staging из S3.
|
||||
try:
|
||||
raw, ctype = s3.get_object(staging_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Временная ошибка S3 — retry.
|
||||
raise RuntimeError("staging_unavailable") from exc
|
||||
|
||||
# 4) Проверить, что файл всё ещё валиден (worker defense-in-depth).
|
||||
try:
|
||||
img = Image.open(io.BytesIO(raw))
|
||||
img.load()
|
||||
@@ -150,8 +162,6 @@ def process_job(payload: dict) -> None:
|
||||
return
|
||||
|
||||
img_rgb = _to_rgb_white(img)
|
||||
|
||||
# 5) Записать финальный оригинал.
|
||||
final_key = s3.original_key(att.chat_id, att.id)
|
||||
s3.put_bytes(final_key, raw, att.content_type)
|
||||
|
||||
@@ -165,55 +175,38 @@ def process_job(payload: dict) -> None:
|
||||
"sha256": _sha256(raw),
|
||||
}]
|
||||
|
||||
# 6) Thumbnail (обязателен).
|
||||
_, thumb_bytes = _make_thumbnail(img_rgb)
|
||||
thumb_key = s3.variant_key(att.chat_id, att.id, "thumbnail")
|
||||
s3.put_bytes(thumb_key, thumb_bytes, "image/jpeg")
|
||||
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
||||
variants.append({
|
||||
"name": "thumbnail",
|
||||
"object_key": thumb_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(thumb_bytes),
|
||||
"width": tw,
|
||||
"height": th,
|
||||
"sha256": _sha256(thumb_bytes),
|
||||
"name": "thumbnail", "object_key": thumb_key,
|
||||
"content_type": "image/jpeg", "size_bytes": len(thumb_bytes),
|
||||
"width": tw, "height": th, "sha256": _sha256(thumb_bytes),
|
||||
})
|
||||
|
||||
# 7) Crop (level 4).
|
||||
_, crop_bytes = _make_crop(img_rgb)
|
||||
crop_key = s3.variant_key(att.chat_id, att.id, "crop")
|
||||
s3.put_bytes(crop_key, crop_bytes, "image/jpeg")
|
||||
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
||||
variants.append({
|
||||
"name": "crop",
|
||||
"object_key": crop_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(crop_bytes),
|
||||
"width": cw,
|
||||
"height": ch,
|
||||
"sha256": _sha256(crop_bytes),
|
||||
"name": "crop", "object_key": crop_key,
|
||||
"content_type": "image/jpeg", "size_bytes": len(crop_bytes),
|
||||
"width": cw, "height": ch, "sha256": _sha256(crop_bytes),
|
||||
})
|
||||
|
||||
# 8) Optimized WebP (level 4).
|
||||
_, opt_bytes = _make_optimized(img_rgb)
|
||||
opt_key = s3.variant_key(att.chat_id, att.id, "optimized")
|
||||
s3.put_bytes(opt_key, opt_bytes, "image/webp")
|
||||
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
||||
variants.append({
|
||||
"name": "optimized",
|
||||
"object_key": opt_key,
|
||||
"content_type": "image/webp",
|
||||
"size_bytes": len(opt_bytes),
|
||||
"width": ow,
|
||||
"height": oh,
|
||||
"sha256": _sha256(opt_bytes),
|
||||
"name": "optimized", "object_key": opt_key,
|
||||
"content_type": "image/webp", "size_bytes": len(opt_bytes),
|
||||
"width": ow, "height": oh, "sha256": _sha256(opt_bytes),
|
||||
})
|
||||
|
||||
# 9) Атомарно: variants + status=ready.
|
||||
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
||||
|
||||
# 10) Удалить staging после безопасной фиксации.
|
||||
try:
|
||||
s3.delete_object(staging_key)
|
||||
except Exception:
|
||||
@@ -223,46 +216,81 @@ def process_job(payload: dict) -> None:
|
||||
attachment_id, job_id, len(variants))
|
||||
|
||||
|
||||
def _on_message(ch, method, properties, body):
|
||||
"""Callback consumer. ack/nack — явно."""
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except Exception:
|
||||
# Битый JSON — постоянная ошибка.
|
||||
log.error("event=invalid_job_json")
|
||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
def _extract_trace_context(properties) -> otel_context.Context:
|
||||
"""Достаём W3C traceparent/tracestate из headers сообщения.
|
||||
|
||||
Трейс API-upload → outbox publish → worker consume получает одну общую
|
||||
цепочку. При отсутствии headers возвращаем пустой контекст.
|
||||
"""
|
||||
headers = dict(properties.headers or {})
|
||||
retry_count = int(headers.get("x-retry-count", 0))
|
||||
payload["attempt"] = retry_count + 1
|
||||
payload["_headers"] = headers
|
||||
if "traceparent" not in headers and "tracestate" not in headers:
|
||||
return otel_context.Context()
|
||||
carrier = {
|
||||
k.lower(): str(v)
|
||||
for k, v in headers.items()
|
||||
if k.lower() in ("traceparent", "tracestate")
|
||||
}
|
||||
return _propagator.extract(carrier=carrier)
|
||||
|
||||
try:
|
||||
process_job(payload)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||
# Исчерпаны попытки — failed + DLQ.
|
||||
try:
|
||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||
except Exception:
|
||||
pass
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return
|
||||
# Retry через TTL-очередь, затем ack текущей.
|
||||
|
||||
def _on_message(ch, method, properties, body):
|
||||
"""Callback consumer. ack/nack — явно. Обёрнуто в consumer span."""
|
||||
parent_ctx = _extract_trace_context(properties)
|
||||
started = time.monotonic()
|
||||
with _tracer.start_as_current_span(
|
||||
"job.consume", context=parent_ctx, kind=SpanKind.CONSUMER,
|
||||
attributes={"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE},
|
||||
) as span:
|
||||
try:
|
||||
publish_retry(payload, retry_count + 1)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
payload = json.loads(body)
|
||||
except Exception:
|
||||
# Не смогли опубликовать retry — вернуть в очередь.
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
log.error("event=invalid_job_json")
|
||||
_jobs_counter.add(1, {"job.type": "unknown", "outcome": "invalid"})
|
||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
headers = dict(properties.headers or {})
|
||||
retry_count = int(headers.get("x-retry-count", 0))
|
||||
payload["attempt"] = retry_count + 1
|
||||
payload["_headers"] = headers
|
||||
span.set_attribute("job.id", str(payload.get("job_id", "")))
|
||||
span.set_attribute("job.type", str(payload.get("type", "unknown")))
|
||||
span.set_attribute("job.attempt", retry_count + 1)
|
||||
|
||||
try:
|
||||
process_job(payload)
|
||||
duration = time.monotonic() - started
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
duration = time.monotonic() - started
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||
try:
|
||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||
except Exception:
|
||||
pass
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||
try:
|
||||
publish_retry(payload, retry_count + 1)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception:
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
Reference in New Issue
Block a user