forked from mtusi2026/mtusi2026lab6
Подключить OpenTelemetry, Collector и Grafana для оценки 5.
API и worker отдают метрики, логи и трассы. Правила SLO записаны, прогон инцидентов ещё впереди.
This commit is contained in:
+50
-18
@@ -7,10 +7,11 @@ import hashlib
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app import broker, config, db, pipeline, s3
|
||||
from app import broker, config, db, pipeline, s3, telemetry
|
||||
from app.errors import AppError
|
||||
from app.pipeline import PermanentJobError, TransientJobError
|
||||
from app.store import format_ts
|
||||
@@ -37,19 +38,27 @@ def backoff_seconds(attempt: int) -> float:
|
||||
return base * random.uniform(0.5, 1.5)
|
||||
|
||||
|
||||
def _trace_columns() -> tuple[str | None, str | None]:
|
||||
carrier = telemetry.current_carrier()
|
||||
return carrier.get("traceparent") or None, carrier.get("tracestate") or None
|
||||
|
||||
|
||||
async def insert_job(conn, attachment_id: UUID, created: datetime) -> UUID:
|
||||
job_id = uuid4()
|
||||
traceparent, tracestate = _trace_columns()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, pipeline_version, attempt, status,
|
||||
next_attempt_at, created_at, updated_at
|
||||
next_attempt_at, created_at, updated_at, traceparent, tracestate
|
||||
)
|
||||
VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3)
|
||||
VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3, $4, $5)
|
||||
""",
|
||||
job_id,
|
||||
attachment_id,
|
||||
created,
|
||||
traceparent,
|
||||
tracestate,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -78,7 +87,8 @@ async def publish_pending(limit: int = 20) -> int:
|
||||
async with conn.transaction():
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at,
|
||||
traceparent, tracestate
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
@@ -90,7 +100,11 @@ async def publish_pending(limit: int = 20) -> int:
|
||||
limit,
|
||||
)
|
||||
for row in rows:
|
||||
await broker.publish_job(message_of(row))
|
||||
await broker.publish_job(
|
||||
message_of(row),
|
||||
traceparent=row["traceparent"],
|
||||
tracestate=row["tracestate"],
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE attachment_jobs SET published_at = now() WHERE job_id = $1",
|
||||
row["job_id"],
|
||||
@@ -445,6 +459,7 @@ async def load_attachment(attachment_id: UUID):
|
||||
|
||||
|
||||
async def process(job_id: UUID, pipeline_version: int) -> str:
|
||||
started = time.perf_counter()
|
||||
state, row = await claim(job_id, pipeline_version)
|
||||
if state != "claimed":
|
||||
return state
|
||||
@@ -452,15 +467,23 @@ async def process(job_id: UUID, pipeline_version: int) -> str:
|
||||
lease = row["lease_token"]
|
||||
try:
|
||||
await asyncio.wait_for(_effect(row, lease), config.JOB_TIMEOUT_SECONDS)
|
||||
outcome = "ready"
|
||||
except PermanentJobError as exc:
|
||||
await fail_job(job_id, lease, exc.code)
|
||||
return "failed"
|
||||
outcome = "failed"
|
||||
except (TransientJobError, asyncio.TimeoutError, AppError):
|
||||
return await schedule_retry(job_id, lease, "processing_failed")
|
||||
outcome = await schedule_retry(job_id, lease, "processing_failed")
|
||||
except Exception:
|
||||
logger.warning("job processing failed job_id=%s", job_id)
|
||||
return await schedule_retry(job_id, lease, "processing_failed")
|
||||
return "ready"
|
||||
outcome = await schedule_retry(job_id, lease, "processing_failed")
|
||||
elapsed = time.perf_counter() - started
|
||||
if outcome in ("ready", "failed", "retry", "lost"):
|
||||
telemetry.record_job(outcome, elapsed)
|
||||
if outcome == "ready":
|
||||
created = _aware(row["created_at"])
|
||||
if created is not None:
|
||||
telemetry.record_time_to_ready((datetime.now(timezone.utc) - created).total_seconds())
|
||||
return outcome
|
||||
|
||||
|
||||
async def _effect(row, lease: UUID) -> None:
|
||||
@@ -479,20 +502,24 @@ async def _effect(row, lease: UUID) -> None:
|
||||
os._exit(1)
|
||||
if fault == "fail_once":
|
||||
raise PermanentJobError("processing_failed")
|
||||
data = await s3.get_bytes(attachment["object_key"])
|
||||
with telemetry.span("s3.get", kind="client", attributes={"s3.operation": "get"}):
|
||||
data = await s3.get_bytes(attachment["object_key"])
|
||||
if len(data) != attachment["size_bytes"] or hashlib.sha256(data).hexdigest() != attachment["sha256"]:
|
||||
raise PermanentJobError("invalid_image")
|
||||
final_key = f"originals/{attachment['id']}"
|
||||
if attachment["object_key"] != final_key:
|
||||
await _intent(final_key)
|
||||
await s3.put_bytes(final_key, data, attachment["content_type"])
|
||||
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
|
||||
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": "original"}):
|
||||
await s3.put_bytes(final_key, data, attachment["content_type"])
|
||||
with telemetry.span("image.render"):
|
||||
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
|
||||
stored = []
|
||||
for name, (payload, content_type, width, height) in rendered.items():
|
||||
suffix = "webp" if content_type == "image/webp" else "jpg"
|
||||
key = f"variants/{attachment['id']}/v{version}/{name}.{suffix}"
|
||||
await _intent(key)
|
||||
await s3.put_bytes(key, payload, content_type)
|
||||
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": name}):
|
||||
await s3.put_bytes(key, payload, content_type)
|
||||
stored.append(
|
||||
{
|
||||
"name": name,
|
||||
@@ -511,7 +538,8 @@ async def _effect(row, lease: UUID) -> None:
|
||||
if fresh is not None and int(fresh["applied_pipeline_version"]) > version:
|
||||
stored = []
|
||||
final_key = ""
|
||||
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
|
||||
with telemetry.span("db.complete", kind="client"):
|
||||
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
|
||||
if not committed:
|
||||
raise TransientJobError("processing_failed")
|
||||
if stored and attachment["object_key"] != final_key and final_key:
|
||||
@@ -571,18 +599,21 @@ async def bump_pipeline(attachment_id: UUID) -> dict:
|
||||
return {"result": "missing"}
|
||||
version = int(current) + 1
|
||||
job_id = uuid4()
|
||||
traceparent, tracestate = _trace_columns()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, pipeline_version, attempt, status,
|
||||
next_attempt_at, created_at, updated_at
|
||||
next_attempt_at, created_at, updated_at, traceparent, tracestate
|
||||
)
|
||||
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4)
|
||||
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4, $5, $6)
|
||||
""",
|
||||
job_id,
|
||||
attachment_id,
|
||||
version,
|
||||
created,
|
||||
traceparent,
|
||||
tracestate,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -600,7 +631,8 @@ async def redeliver(job_id: UUID) -> dict:
|
||||
async with db.require().acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status,
|
||||
traceparent, tracestate
|
||||
FROM attachment_jobs
|
||||
WHERE job_id = $1
|
||||
""",
|
||||
@@ -608,7 +640,7 @@ async def redeliver(job_id: UUID) -> dict:
|
||||
)
|
||||
if row is None:
|
||||
return {"result": "missing"}
|
||||
await broker.publish_job(message_of(row))
|
||||
await broker.publish_job(message_of(row), traceparent=row["traceparent"], tracestate=row["tracestate"])
|
||||
return {
|
||||
"result": "published",
|
||||
"job_id": str(row["job_id"]),
|
||||
|
||||
Reference in New Issue
Block a user