исправления trace и span

This commit is contained in:
2026-12-04 03:12:51 +03:00
parent 0bd1f0f220
commit 3ba5126b78
8 changed files with 245 additions and 143 deletions
+43 -31
View File
@@ -16,9 +16,10 @@ from sqlalchemy import select, update, func
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy.dialects.postgresql import insert as pg_insert
from opentelemetry import trace, propagate
from app.telemetry import setup_telemetry
setup_telemetry()
tracer_provider, meter_provider, logger_provider = setup_telemetry()
from app.models import Attachment, AttachmentJob, AttachmentVariant
from app.broker import (
@@ -47,7 +48,8 @@ engine = create_async_engine(DATABASE_URL, echo=False)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
s3_client = Minio(S3_ENDPOINT, access_key=S3_ACCESS_KEY, secret_key=S3_SECRET_KEY, secure=False)
# === OTel метрики worker ===
tracer = trace.get_tracer("messenger-worker")
from opentelemetry import metrics
_meter = metrics.get_meter("messenger.worker")
_jobs_completed = _meter.create_counter("messenger.worker.jobs.completed", description="Completed jobs")
@@ -55,7 +57,6 @@ _jobs_failed = _meter.create_counter("messenger.worker.jobs.failed", description
_job_duration = _meter.create_histogram("messenger.worker.job.duration", unit="s", description="Job processing duration")
_active_jobs = _meter.create_up_down_counter("messenger.worker.jobs.active", description="In-flight jobs")
# Кэш очереди, обновляется sweeper'ом; observable-gauge читает из него
_queue_state = {"active": 0, "oldest_age": 0.0}
_meter.create_observable_gauge(
"messenger.queue.active_jobs",
@@ -294,6 +295,11 @@ async def schedule_retry(job_id: str, payload: dict) -> int:
async def process_message(message: aio_pika.IncomingMessage):
"""Обработка сообщения с W3C trace propagation."""
# Извлекаем traceparent из заголовков сообщения
headers = message.headers or {}
parent_context = propagate.extract(headers)
try:
data = json.loads(message.body)
job_id, att_id, attempt = data["job_id"], data["attachment_id"], int(data["attempt"])
@@ -303,30 +309,41 @@ async def process_message(message: aio_pika.IncomingMessage):
await message.nack(requeue=False)
return
try:
outcome, code = await handle_job(job_id, att_id, attempt)
except Exception:
logger.exception("Handler crashed for job %s", job_id)
outcome, code = "temporary", "internal_error"
# Создаём CONSUMER span с извлечённым контекстом
with tracer.start_as_current_span(
"attachment.process",
context=parent_context,
kind=trace.SpanKind.CONSUMER,
attributes={
"messaging.system": "rabbitmq",
"messaging.operation": "process",
"messaging.message.id": message.message_id or "",
},
) as span:
try:
outcome, code = await handle_job(job_id, att_id, attempt)
except Exception:
logger.exception("Handler crashed for job %s", job_id)
outcome, code = "temporary", "internal_error"
try:
if outcome in ("done", "noop"):
await message.ack()
return
if outcome == "permanent":
await mark_failed(job_id, code)
await message.nack(requeue=False)
return
tier = await schedule_retry(job_id, data)
if tier < 0:
await mark_failed(job_id, "retry_exhausted")
await message.nack(requeue=False)
else:
logger.info("Job %s temporary error (%s), retry in ~%ss", job_id, code, tier)
await message.ack()
except Exception:
logger.exception("Failed to finalize delivery for job %s -> requeue", job_id)
await message.nack(requeue=True)
try:
if outcome in ("done", "noop"):
await message.ack()
return
if outcome == "permanent":
await mark_failed(job_id, code)
await message.nack(requeue=False)
return
tier = await schedule_retry(job_id, data)
if tier < 0:
await mark_failed(job_id, "retry_exhausted")
await message.nack(requeue=False)
else:
logger.info("Job %s temporary error (%s), retry in ~%ss", job_id, code, tier)
await message.ack()
except Exception:
logger.exception("Failed to finalize delivery for job %s -> requeue", job_id)
await message.nack(requeue=True)
async def sweeper():
@@ -336,15 +353,10 @@ async def sweeper():
await asyncio.sleep(5)
async with AsyncSessionLocal() as db:
now = datetime.now(timezone.utc)
# Обновляем кэш очереди для observable-gauge
cnt = (await db.execute(
select(func.count()).select_from(AttachmentJob)
.where(AttachmentJob.status.in_(["queued", "processing"]))
)).scalar() or 0
oldest = (await db.execute(
select(func.min(AttachmentJob.lease_until)).where(AttachmentJob.status == "queued")
)).scalar()
# возраст = время с создания самой старой незавершённой job
oldest_created = (await db.execute(
select(func.min(Attachment.created_at))
.join(AttachmentJob, AttachmentJob.attachment_id == Attachment.id)