feat: ЛР6 - наблюдаемость OpenTelemetry, Grafana и исследование цены наблюдаемости

This commit is contained in:
Ильяс
2026-11-27 20:09:36 +03:00
parent 38a00e1930
commit c549409d7b
25 changed files with 2599 additions and 187 deletions
+11
View File
@@ -91,6 +91,17 @@ class BrokerPublisher:
self._channel = None
return False
async def get_queue_message_count(self) -> int:
try:
if self._channel is None or self._channel.is_closed:
await self.get_exchange()
if self._channel and not self._channel.is_closed:
q = await self._channel.get_queue(QUEUE_NAME)
return q.declaration_result.message_count
except Exception:
pass
return 0
async def close(self) -> None:
try:
if self._channel and not self._channel.is_closed:
+3
View File
@@ -9,6 +9,7 @@ from fastapi import FastAPI
from app.config import APP_HOST, APP_PORT, LOG_LEVEL
from app.errors import register_error_handlers
from app.middleware import RequestIdAndLoggingMiddleware
from app.telemetry import init_telemetry
from app.routes.attachments import router as attachments_router
from app.routes.auth import router as auth_router
from app.routes.chats import router as chats_router
@@ -37,6 +38,8 @@ async def lifespan(app: FastAPI):
await storage.disconnect()
init_telemetry("messenger-api")
app = FastAPI(
title="highload-messenger",
version="1.6.0",
+75 -35
View File
@@ -1,41 +1,62 @@
from __future__ import annotations
import logging
import sys
import re
import time
import uuid
from opentelemetry.trace import SpanKind
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from app.config import INSTANCE_ID
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
stream=sys.stdout,
from app.telemetry import (
get_tracer,
record_http_request,
)
logger = logging.getLogger("app.access")
ROUTE_CHATS_MESSAGES = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+/messages$")
ROUTE_CHATS_ATTACHMENTS = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+/attachments$")
ROUTE_CHATS_ID = re.compile(r"^/api/v1/chats/[0-9a-fA-F-]+$")
ROUTE_ATTACHMENTS_CONTENT = re.compile(r"^/api/v1/attachments/[0-9a-fA-F-]+/content$")
ROUTE_ATTACHMENTS_ID = re.compile(r"^/api/v1/attachments/[0-9a-fA-F-]+$")
def get_route_template(path: str) -> str:
if ROUTE_CHATS_MESSAGES.match(path):
return "/api/v1/chats/{chat_id}/messages"
if ROUTE_CHATS_ATTACHMENTS.match(path):
return "/api/v1/chats/{chat_id}/attachments"
if ROUTE_CHATS_ID.match(path):
return "/api/v1/chats/{chat_id}"
if ROUTE_ATTACHMENTS_CONTENT.match(path):
return "/api/v1/attachments/{attachment_id}/content"
if ROUTE_ATTACHMENTS_ID.match(path):
return "/api/v1/attachments/{attachment_id}"
return path
class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
# Получаем X-Request-Id или генерируем новый
request_id = request.headers.get("X-Request-Id")
if not request_id or not request_id.strip():
request_id = str(uuid.uuid4())
request.state.request_id = request_id
start_time = time.monotonic()
path = request.url.path
route_template = get_route_template(path)
if request.method in ("POST", "PUT", "PATCH") and request.url.path != "/api/v1/auth/sessions":
if request.method in ("POST", "PUT", "PATCH") and path != "/api/v1/auth/sessions":
is_attachment_upload = (
request.method == "POST"
and "/attachments" in request.url.path
and request.url.path.startswith("/api/v1/chats/")
and "/attachments" in path
and path.startswith("/api/v1/chats/")
)
ct = request.headers.get("content-type")
ct_clean = ct.split(";")[0].strip().lower() if ct else ""
@@ -62,32 +83,51 @@ class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
request_id,
)
try:
response = await call_next(request)
except Exception:
# Исключение перехватится exception_handler
duration_ms = (time.monotonic() - start_time) * 1000
logger.error(
"%s %s -> 500 error | duration=%.2fms | request_id=%s",
tracer = get_tracer()
with tracer.start_as_current_span(
f"{request.method} {route_template}",
kind=SpanKind.SERVER,
) as span:
span.set_attribute("http.method", request.method)
span.set_attribute("http.route", route_template)
span.set_attribute("http.target", path)
span.set_attribute("request.id", request_id)
try:
response = await call_next(request)
except Exception:
duration_sec = time.monotonic() - start_time
span.set_attribute("http.status_code", 500)
span.record_exception(Exception("Unhandled server error"))
record_http_request(request.method, route_template, "500", duration_sec)
logger.error(
"%s %s -> 500 error | duration=%.2fms | request_id=%s",
request.method,
path,
duration_sec * 1000,
request_id,
)
raise
duration_sec = time.monotonic() - start_time
span.set_attribute("http.status_code", response.status_code)
record_http_request(request.method, route_template, str(response.status_code), duration_sec)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
ctx = span.get_span_context()
if ctx.is_valid:
response.headers["X-Trace-Id"] = format(ctx.trace_id, "032x")
logger.info(
"%s %s -> %d | duration=%.2fms | request_id=%s",
request.method,
request.url.path,
duration_ms,
path,
response.status_code,
duration_sec * 1000,
request_id,
)
raise
duration_ms = (time.monotonic() - start_time) * 1000
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
# лог без логирования тела запросов и текстов сообщений
logger.info(
"%s %s -> %d | duration=%.2fms | request_id=%s",
request.method,
request.url.path,
response.status_code,
duration_ms,
request_id,
)
return response
return response
+12 -1
View File
@@ -8,6 +8,7 @@ from typing import Any
import asyncpg
from app.broker import publisher
from app.telemetry import set_oldest_job_age, set_queue_depth
logger = logging.getLogger("messenger.outbox")
@@ -90,7 +91,17 @@ class OutboxRelay:
while self._running:
try:
dispatched = await self.process_pending(pool)
# Если были отправлены задачи, проверяем сразу следующую порцию
count = await publisher.get_queue_message_count()
set_queue_depth(count)
async with pool.acquire() as conn:
age = await conn.fetchval(
"""
SELECT COALESCE(EXTRACT(EPOCH FROM (NOW() - MIN(created_at))), 0.0)
FROM outbox_jobs
WHERE status = 'pending'
"""
)
set_oldest_job_age(float(age or 0.0))
if dispatched > 0:
continue
except asyncio.CancelledError:
+26 -4
View File
@@ -17,6 +17,7 @@ import botocore.exceptions
from PIL import Image
from app.auth import generate_session_token, hash_password, verify_password
from app.telemetry import inject_trace_context, set_db_pool_active
from app.config import (
CACHE_URL,
DATABASE_URL,
@@ -98,9 +99,24 @@ class PostgresStorage:
async def acquire_conn(self, timeout: float = 2.0):
if self.pg_pool is None:
raise asyncpg.InterfaceError("Пул подключений к PostgreSQL не инициализирован")
async with asyncio.timeout(3.0):
async with self.pg_pool.acquire(timeout=timeout) as conn:
yield conn
try:
holders = getattr(self.pg_pool, "_holders", [])
free = getattr(self.pg_pool, "_free", [])
set_db_pool_active(len(holders) - len(free) + 1)
except Exception:
pass
try:
async with asyncio.timeout(3.0):
async with self.pg_pool.acquire(timeout=timeout) as conn:
yield conn
finally:
if self.pg_pool is not None:
try:
holders = getattr(self.pg_pool, "_holders", [])
free = getattr(self.pg_pool, "_free", [])
set_db_pool_active(len(holders) - len(free))
except Exception:
pass
async def connect(self) -> None:
logger.info("Подключение к PostgreSQL: %s", DATABASE_URL.split("@")[-1])
@@ -809,7 +825,9 @@ class PostgresStorage:
await asyncio.to_thread(_put_to_s3)
# 9. Атомарное сохранение в PostgreSQL: attachments + outbox_jobs
carrier: dict[str, str] = {}
inject_trace_context(carrier)
job_payload = {
"schema_version": 1,
"job_id": str(job_id),
@@ -819,6 +837,10 @@ class PostgresStorage:
"attempt": 1,
"created_at": now_iso,
}
if "traceparent" in carrier:
job_payload["traceparent"] = carrier["traceparent"]
if "tracestate" in carrier:
job_payload["tracestate"] = carrier["tracestate"]
try:
async with self.acquire_conn() as conn:
+283
View File
@@ -0,0 +1,283 @@
from __future__ import annotations
import datetime as dt
import json
import logging
import os
import sys
from typing import Any
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.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.sampling import (
ALWAYS_OFF,
ALWAYS_ON,
ParentBased,
TraceIdRatioBased,
)
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
_initialized = False
_tracer: trace.Tracer | None = None
_meter: metrics.Meter | None = None
http_requests_total: Any = None
http_request_duration_seconds: Any = None
jobs_processed_total: Any = None
jobs_failed_total: Any = None
job_processing_duration_seconds: Any = None
attachment_time_to_ready_seconds: Any = None
queue_depth_gauge: Any = None
queue_oldest_job_age_gauge: Any = None
db_pool_active_gauge: Any = None
_current_queue_depth: int = 0
_current_oldest_job_age: float = 0.0
_current_db_pool_active: int = 0
class JsonLogFormatter(logging.Formatter):
def __init__(self, service_name: str) -> None:
super().__init__()
self.service_name = service_name
def format(self, record: logging.LogRecord) -> str:
trace_id = ""
span_id = ""
span = trace.get_current_span()
if span.is_recording():
ctx = span.get_span_context()
if ctx.is_valid:
trace_id = format(ctx.trace_id, "032x")
span_id = format(ctx.span_id, "016x")
payload: dict[str, Any] = {
"timestamp": dt.datetime.now(dt.timezone.utc).isoformat(),
"severity": record.levelname,
"service.name": self.service_name,
"event": record.getMessage(),
}
if trace_id:
payload["trace_id"] = trace_id
payload["span_id"] = span_id
if record.exc_info and record.exc_text:
payload["exception"] = record.exc_text
return json.dumps(payload, ensure_ascii=False)
def _observable_queue_depth(options: Any) -> list[metrics.Observation]:
return [metrics.Observation(_current_queue_depth)]
def _observable_oldest_job_age(options: Any) -> list[metrics.Observation]:
return [metrics.Observation(_current_oldest_job_age)]
def _observable_db_pool(options: Any) -> list[metrics.Observation]:
return [metrics.Observation(_current_db_pool_active)]
def set_queue_depth(depth: int) -> None:
global _current_queue_depth
_current_queue_depth = max(0, depth)
def set_oldest_job_age(age_seconds: float) -> None:
global _current_oldest_job_age
_current_oldest_job_age = max(0.0, float(age_seconds))
def set_db_pool_active(count: int) -> None:
global _current_db_pool_active
_current_db_pool_active = max(0, count)
def init_telemetry(service_name: str) -> None:
global _initialized, _tracer, _meter
global http_requests_total, http_request_duration_seconds
global jobs_processed_total, jobs_failed_total, job_processing_duration_seconds
global queue_depth_gauge, db_pool_active_gauge
if _initialized:
return
_initialized = True
root_logger = logging.getLogger()
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(JsonLogFormatter(service_name))
root_logger.addHandler(stdout_handler)
root_logger.setLevel(logging.INFO)
if os.getenv("OTEL_SDK_DISABLED", "false").lower() == "true":
_tracer = trace.get_tracer(service_name)
_meter = metrics.get_meter(service_name)
return
instance_id = os.getenv("INSTANCE_ID", service_name)
resource = Resource.create(
{
"service.name": service_name,
"service.version": "1.6.0",
"deployment.environment.name": os.getenv("APP_ENV", "lab"),
"service.instance.id": instance_id,
}
)
sampler_mode = os.getenv("OTEL_TRACES_SAMPLER", "always_on").lower()
sampler_arg = float(os.getenv("OTEL_TRACES_SAMPLER_ARG", "1.0"))
if sampler_mode == "always_off":
sampler = ALWAYS_OFF
elif sampler_mode in ("traceidratio", "ratio"):
sampler = TraceIdRatioBased(sampler_arg)
elif sampler_mode in ("parentbased_traceidratio", "parentbased_ratio"):
sampler = ParentBased(root=TraceIdRatioBased(sampler_arg))
else:
sampler = ALWAYS_ON
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
span_exporter = OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces", timeout=3)
span_processor = BatchSpanProcessor(span_exporter, max_queue_size=2048, schedule_delay_millis=500)
tracer_provider = TracerProvider(resource=resource, sampler=sampler)
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)
_tracer = trace.get_tracer(service_name)
metric_exporter = OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics", timeout=3)
metric_reader = PeriodicExportingMetricReader(metric_exporter, export_interval_millis=2000)
http_boundaries = [
0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0
]
job_boundaries = [
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0
]
views = [
View(
instrument_name="http_request_duration_seconds",
aggregation=ExplicitBucketHistogramAggregation(boundaries=http_boundaries),
),
View(
instrument_name="job_processing_duration_seconds",
aggregation=ExplicitBucketHistogramAggregation(boundaries=job_boundaries),
),
View(
instrument_name="attachment_time_to_ready_seconds",
aggregation=ExplicitBucketHistogramAggregation(boundaries=job_boundaries),
),
]
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader], views=views)
metrics.set_meter_provider(meter_provider)
_meter = metrics.get_meter(service_name)
http_requests_total = _meter.create_counter(
name="http_requests_total",
unit="",
description="Total count of processed HTTP requests",
)
http_request_duration_seconds = _meter.create_histogram(
name="http_request_duration_seconds",
unit="s",
description="HTTP request duration in seconds",
)
jobs_processed_total = _meter.create_counter(
name="jobs_processed_total",
unit="",
description="Total count of successfully processed worker jobs",
)
jobs_failed_total = _meter.create_counter(
name="jobs_failed_total",
unit="",
description="Total count of failed worker jobs",
)
job_processing_duration_seconds = _meter.create_histogram(
name="job_processing_duration_seconds",
unit="s",
description="Job processing duration in seconds",
)
attachment_time_to_ready_seconds = _meter.create_histogram(
name="attachment_time_to_ready_seconds",
unit="s",
description="End-to-end time from upload to ready in seconds",
)
queue_depth_gauge = _meter.create_observable_gauge(
name="queue_depth",
unit="",
description="Current depth of pending jobs in queue",
callbacks=[_observable_queue_depth],
)
queue_oldest_job_age_gauge = _meter.create_observable_gauge(
name="queue_oldest_job_age_seconds",
unit="s",
description="Age of oldest job waiting in queue in seconds",
callbacks=[_observable_oldest_job_age],
)
db_pool_active_gauge = _meter.create_observable_gauge(
name="db_pool_connections",
unit="",
description="Active PostgreSQL pool connections",
callbacks=[_observable_db_pool],
)
log_exporter = OTLPLogExporter(endpoint=f"{endpoint}/v1/logs", timeout=3)
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(log_exporter, schedule_delay_millis=500)
)
set_logger_provider(logger_provider)
otel_log_handler = LoggingHandler(logger_provider=logger_provider)
otel_log_handler.setFormatter(JsonLogFormatter(service_name))
root_logger.addHandler(otel_log_handler)
def record_time_to_ready(duration_sec: float) -> None:
if attachment_time_to_ready_seconds is not None:
attachment_time_to_ready_seconds.record(duration_sec, {"status": "ready"})
def record_http_request(method: str, route: str, status: int | str, duration_sec: float) -> None:
if http_requests_total is not None:
http_requests_total.add(1, {"method": method, "route": route, "status": str(status)})
if http_request_duration_seconds is not None:
http_request_duration_seconds.record(duration_sec, {"method": method, "route": route, "status": str(status)})
def record_job_processed(job_type: str, outcome: str, duration_sec: float) -> None:
if jobs_processed_total is not None:
jobs_processed_total.add(1, {"job_type": job_type, "outcome": outcome})
if job_processing_duration_seconds is not None:
job_processing_duration_seconds.record(duration_sec, {"job_type": job_type, "outcome": outcome})
def record_job_failed(job_type: str, outcome: str, error_code: str) -> None:
if jobs_failed_total is not None:
jobs_failed_total.add(1, {"job_type": job_type, "outcome": outcome, "error_code": error_code})
def get_tracer() -> trace.Tracer:
global _tracer
if _tracer is None:
_tracer = trace.get_tracer("messenger")
return _tracer
def inject_trace_context(carrier: dict[str, str]) -> None:
TraceContextTextMapPropagator().inject(carrier)
def extract_trace_context(carrier: dict[str, str]) -> Any:
return TraceContextTextMapPropagator().extract(carrier)
+171 -122
View File
@@ -1,11 +1,13 @@
from __future__ import annotations
import asyncio
import datetime as dt
import io
import json
import logging
import random
import signal
import time
import uuid
from typing import Any
@@ -14,6 +16,18 @@ import asyncpg
import boto3
from botocore.config import Config
from PIL import UnidentifiedImageError
from opentelemetry.trace import SpanKind, StatusCode
from app.telemetry import (
extract_trace_context,
get_tracer,
init_telemetry,
record_job_failed,
record_job_processed,
record_time_to_ready,
set_db_pool_active,
set_queue_depth,
)
from app.broker import (
DL_ROUTING_KEY,
@@ -123,6 +137,20 @@ class AttachmentWorker:
await exchange.publish(msg, routing_key=ROUTING_KEY)
except Exception as pub_err:
logger.error("Failed republish on lease expiration for %s: %s", r["id"], pub_err)
if self._channel and not self._channel.is_closed:
try:
q = await self._channel.get_queue(QUEUE_NAME)
set_queue_depth(q.declaration_result.message_count)
except Exception:
pass
if self.pool:
try:
holders = getattr(self.pool, "_holders", [])
free = getattr(self.pool, "_free", [])
set_db_pool_active(len(holders) - len(free))
except Exception:
pass
except asyncio.CancelledError:
break
except Exception as exc:
@@ -154,141 +182,161 @@ class AttachmentWorker:
logger.error("DB pool not initialized")
return
async with self.pool.acquire() as conn:
row = await conn.fetchrow(
"""
UPDATE attachments
SET status = 'processing',
processing_started_at = NOW(),
processing_worker_id = $1,
updated_at = NOW()
WHERE id = $2 AND status IN ('queued', 'failed')
RETURNING id, chat_id, filename, content_type, size_bytes, sha256, s3_key, status
""",
self.worker_id,
att_id,
)
if not row:
current_status = await conn.fetchval(
"SELECT status FROM attachments WHERE id = $1", att_id
)
logger.info(
"Attachment %s is in state '%s', skipping processing (idempotent no-op).",
parent_ctx = extract_trace_context(payload)
tracer = get_tracer()
t0 = time.monotonic()
with tracer.start_as_current_span(
"attachment.process",
context=parent_ctx,
kind=SpanKind.CONSUMER,
attributes={"job.type": "attachment.process.v1"},
) as span:
async with self.pool.acquire() as conn:
row = await conn.fetchrow(
"""
UPDATE attachments
SET status = 'processing',
processing_started_at = NOW(),
processing_worker_id = $1,
updated_at = NOW()
WHERE id = $2 AND status IN ('queued', 'failed')
RETURNING id, chat_id, filename, content_type, size_bytes, sha256, s3_key, status, created_at
""",
self.worker_id,
att_id,
current_status,
)
return
try:
async with asyncio.timeout(30.0):
staging_key = row["s3_key"]
try:
s3_resp = await asyncio.to_thread(
self.s3_client.get_object,
Bucket=S3_BUCKET,
Key=staging_key,
if not row:
current_status = await conn.fetchval(
"SELECT status FROM attachments WHERE id = $1", att_id
)
raw_bytes = s3_resp["Body"].read()
except Exception as s3_err:
logger.error("Failed to read staging S3 key %s: %s", staging_key, s3_err)
await self._handle_retryable_error(payload, attempt, str(s3_err))
return
# 3. Генерируем варианты через Pillow
try:
variants = await asyncio.to_thread(process_image_variants, raw_bytes)
except (UnidentifiedImageError, ValueError) as img_err:
logger.warning(
"Permanent image processing error for %s: %s", att_id, img_err
)
await self._fail_attachment(att_id, "invalid_image")
await self._send_to_dlq(payload, f"permanent_image_error: {img_err}")
return
except Exception as unk_err:
logger.error(
"Unexpected processing error for %s: %s", att_id, unk_err
)
await self._handle_retryable_error(payload, attempt, str(unk_err))
return
# 4. Сохраняем оригинал и варианты в постоянные S3-ключи
chat_id = str(row["chat_id"])
final_original_key = f"chats/{chat_id}/{att_id}/original"
try:
# Оригинал
await asyncio.to_thread(
self.s3_client.put_object,
Bucket=S3_BUCKET,
Key=final_original_key,
Body=raw_bytes,
ContentType=row["content_type"],
)
# Варианты
for var in variants:
var_key = f"chats/{chat_id}/{att_id}/{var['name']}"
await asyncio.to_thread(
self.s3_client.put_object,
Bucket=S3_BUCKET,
Key=var_key,
Body=var["data"],
ContentType=var["content_type"],
)
except Exception as upload_err:
logger.error("Failed uploading variants to S3 for %s: %s", att_id, upload_err)
await self._handle_retryable_error(payload, attempt, str(upload_err))
return
# 5. Атомарно обновляем PostgreSQL в 'ready'
variants_metadata = [
{
"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
]
async with self.pool.acquire() as conn:
await conn.execute(
"""
UPDATE attachments
SET status = 'ready',
s3_key = $1,
variants = $2::jsonb,
error_code = NULL,
processing_started_at = NULL,
processing_worker_id = NULL,
updated_at = NOW()
WHERE id = $3
""",
final_original_key,
json.dumps(variants_metadata),
logger.info(
"Attachment %s is in state '%s', skipping processing (idempotent no-op).",
att_id,
current_status,
)
return
# 6. Очистка staging-файла в MinIO
if staging_key != final_original_key:
try:
async with asyncio.timeout(30.0):
staging_key = row["s3_key"]
try:
await asyncio.to_thread(
self.s3_client.delete_object,
s3_resp = await asyncio.to_thread(
self.s3_client.get_object,
Bucket=S3_BUCKET,
Key=staging_key,
)
except Exception as del_err:
logger.warning("Failed to delete staging key %s: %s", staging_key, del_err)
raw_bytes = s3_resp["Body"].read()
except Exception as s3_err:
logger.error("Failed to read staging S3 key %s: %s", staging_key, s3_err)
span.set_status(StatusCode.ERROR, str(s3_err))
span.record_exception(s3_err)
await self._handle_retryable_error(payload, attempt, str(s3_err))
return
logger.info("Attachment %s successfully processed into ready with 3 variants.", att_id)
except TimeoutError:
logger.error("Job processing timed out (>30s) for %s. Aborting hung worker task.", att_id)
await self._handle_retryable_error(payload, attempt, "job_deadline_exceeded_30s")
return
try:
variants = await asyncio.to_thread(process_image_variants, raw_bytes)
except (UnidentifiedImageError, ValueError) as img_err:
logger.warning(
"Permanent image processing error for %s: %s", att_id, img_err
)
span.set_status(StatusCode.ERROR, str(img_err))
span.record_exception(img_err)
await self._fail_attachment(att_id, "invalid_image")
await self._send_to_dlq(payload, f"permanent_image_error: {img_err}")
return
except Exception as unk_err:
logger.error(
"Unexpected processing error for %s: %s", att_id, unk_err
)
span.set_status(StatusCode.ERROR, str(unk_err))
span.record_exception(unk_err)
await self._handle_retryable_error(payload, attempt, str(unk_err))
return
chat_id = str(row["chat_id"])
final_original_key = f"chats/{chat_id}/{att_id}/original"
try:
await asyncio.to_thread(
self.s3_client.put_object,
Bucket=S3_BUCKET,
Key=final_original_key,
Body=raw_bytes,
ContentType=row["content_type"],
)
for var in variants:
var_key = f"chats/{chat_id}/{att_id}/{var['name']}"
await asyncio.to_thread(
self.s3_client.put_object,
Bucket=S3_BUCKET,
Key=var_key,
Body=var["data"],
ContentType=var["content_type"],
)
except Exception as upload_err:
logger.error("Failed uploading variants to S3 for %s: %s", att_id, upload_err)
span.set_status(StatusCode.ERROR, str(upload_err))
span.record_exception(upload_err)
await self._handle_retryable_error(payload, attempt, str(upload_err))
return
variants_metadata = [
{
"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
]
async with self.pool.acquire() as conn:
await conn.execute(
"""
UPDATE attachments
SET status = 'ready',
s3_key = $1,
variants = $2::jsonb,
error_code = NULL,
processing_started_at = NULL,
processing_worker_id = NULL,
updated_at = NOW()
WHERE id = $3
""",
final_original_key,
json.dumps(variants_metadata),
att_id,
)
if staging_key != final_original_key:
try:
await asyncio.to_thread(
self.s3_client.delete_object,
Bucket=S3_BUCKET,
Key=staging_key,
)
except Exception as del_err:
logger.warning("Failed to delete staging key %s: %s", staging_key, del_err)
dur = time.monotonic() - t0
record_job_processed("attachment.process.v1", "success", dur)
if "created_at" in row and row["created_at"]:
e2e_dur = (dt.datetime.now(dt.timezone.utc) - row["created_at"]).total_seconds()
record_time_to_ready(max(0.0, e2e_dur))
logger.info("Attachment %s successfully processed into ready with 3 variants.", att_id)
except TimeoutError as to_err:
span.set_status(StatusCode.ERROR, "job_deadline_exceeded_30s")
span.record_exception(to_err)
logger.error("Job processing timed out (>30s) for %s. Aborting hung worker task.", att_id)
await self._handle_retryable_error(payload, attempt, "job_deadline_exceeded_30s")
return
async def _fail_attachment(self, att_id: uuid.UUID, error_code: str) -> None:
"""Переводит вложение в статус failed с безопасным машинным кодом."""
record_job_failed("attachment.process.v1", "error", error_code)
if not self.pool:
return
async with self.pool.acquire() as conn:
@@ -370,6 +418,7 @@ class AttachmentWorker:
await self._send_to_dlq(payload, f"retry_exhausted: {reason}")
async def start(self) -> None:
init_telemetry("messenger-worker")
self._running = True
await self.init_resources()