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
+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()