Добавить наблюдаемость OpenTelemetry и Grafana на оценку 3
This commit is contained in:
+51
-4
@@ -8,6 +8,7 @@ import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from sqlalchemy import text
|
||||
@@ -18,6 +19,9 @@ from app.pipeline import (IMAGE_TIMEOUT, LEASE_SECONDS, TOTAL_TIMEOUT,
|
||||
arm_from_env, broker_channel, crash_if_armed,
|
||||
event, parse_envelope, retry_or_fail)
|
||||
from app.storage import ObjectMissing, storage
|
||||
from app.telemetry import (configure, emit, install_termination_handler, jobs_duration,
|
||||
jobs_processed, shutdown, span)
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
logger = logging.getLogger("messenger.worker")
|
||||
|
||||
@@ -145,20 +149,21 @@ async def finish(row: dict, *, variants=None, code: str | None = None,
|
||||
return True
|
||||
|
||||
|
||||
async def handle(message) -> None:
|
||||
async def _handle(message) -> str:
|
||||
try:
|
||||
job = parse_envelope(message.body)
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
logger.warning("invalid envelope sent to durable DLQ")
|
||||
await message.reject(requeue=False)
|
||||
return
|
||||
return "invalid"
|
||||
row = await claim(job)
|
||||
if row is None:
|
||||
# A ready/failed/stale attempt is a durable no-op. A duplicate of
|
||||
# active processing is covered by the DB lease recovery, so it too
|
||||
# can be acknowledged without running a second concurrent decoder.
|
||||
await message.ack()
|
||||
return
|
||||
return "duplicate"
|
||||
outcome = "error"
|
||||
try:
|
||||
async with asyncio.timeout(TOTAL_TIMEOUT):
|
||||
variants = await build_objects(row)
|
||||
@@ -172,12 +177,50 @@ async def handle(message) -> None:
|
||||
if await finish(row, variants=variants):
|
||||
await crash_if_armed("crash_after_commit_before_ack")
|
||||
logger.info("ready attachment=%s", row["id"])
|
||||
outcome = "success"
|
||||
else:
|
||||
outcome = "duplicate"
|
||||
# If finish failed, the exception propagates and the connection closes:
|
||||
# RabbitMQ redelivers while PG keeps the durable lease/retry intention.
|
||||
await message.ack()
|
||||
return outcome
|
||||
|
||||
|
||||
async def handle(message) -> None:
|
||||
# Technical IDs in logs/spans only; metric dimensions stay low-cardinality.
|
||||
job = {}
|
||||
try:
|
||||
job = parse_envelope(message.body)
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
pass
|
||||
started = time.perf_counter()
|
||||
outcome = "error"
|
||||
with span("attachments process", kind=SpanKind.CONSUMER, attributes={
|
||||
"messaging.system": "rabbitmq", "messaging.destination.name": "attachments",
|
||||
"messaging.operation": "process", "job_type": "attachment.process.v1",
|
||||
}) as active:
|
||||
try:
|
||||
outcome = await _handle(message)
|
||||
finally:
|
||||
duration = time.perf_counter() - started
|
||||
attrs = {"job_type": "attachment.process.v1", "outcome": outcome}
|
||||
jobs_processed.add(1, attrs)
|
||||
if outcome in {"success", "error"}:
|
||||
jobs_duration.record(duration, attrs)
|
||||
active.set_attribute("outcome", outcome)
|
||||
if outcome in {"error", "invalid"}:
|
||||
active.set_status(Status(StatusCode.ERROR))
|
||||
for name in ("job_id", "attachment_id", "attempt"):
|
||||
if name in job:
|
||||
active.set_attribute(name, job[name])
|
||||
emit("job.complete", severity=logging.WARNING if outcome == "error" else logging.INFO,
|
||||
**attrs, job_id=job.get("job_id"), attachment_id=job.get("attachment_id"),
|
||||
attempt=job.get("attempt"), duration_seconds=duration)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
configure("messenger-worker")
|
||||
install_termination_handler()
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
for name in ("aio_pika", "aiormq"):
|
||||
logging.getLogger(name).setLevel(logging.CRITICAL)
|
||||
@@ -204,7 +247,11 @@ async def main() -> None:
|
||||
await connection.close()
|
||||
await storage.close()
|
||||
await engine.dispose()
|
||||
await asyncio.to_thread(shutdown)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except asyncio.CancelledError:
|
||||
pass # SIGTERM has run finally/SDK flush; exit cleanly.
|
||||
|
||||
Reference in New Issue
Block a user