Создала общий модуль OTel для API и worker
This commit is contained in:
+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