Реализовать уровень 4: сквозные трассы, SLO, отказы и отчёт
This commit is contained in:
+32
-10
@@ -15,6 +15,10 @@ from sqlalchemy import text
|
||||
|
||||
from app.config import read_value
|
||||
from app.db import SessionLocal
|
||||
from app import advanced
|
||||
from app.telemetry import emit, span
|
||||
from app.trace_context import carrier, parent_context
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
logger = logging.getLogger("messenger.pipeline")
|
||||
QUEUE = "attachments"
|
||||
@@ -56,13 +60,15 @@ async def broker_channel():
|
||||
|
||||
|
||||
def envelope(row) -> dict:
|
||||
return {
|
||||
job = {
|
||||
"schema_version": 1, "job_id": str(row["job_id"]),
|
||||
"type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]),
|
||||
"pipeline_version": int(row.get("pipeline_version", 1)),
|
||||
"attempt": int(row["attempt"]),
|
||||
"created_at": row["created_at"].isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
job.update({name: row[name] for name in ("traceparent", "tracestate") if row.get(name)})
|
||||
return job
|
||||
|
||||
|
||||
def parse_envelope(raw: bytes) -> dict:
|
||||
@@ -94,12 +100,20 @@ def parse_envelope(raw: bytes) -> dict:
|
||||
|
||||
|
||||
async def publish(channel, job: dict) -> None:
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(json.dumps(job).encode("utf-8"), content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=job["job_id"]),
|
||||
routing_key=QUEUE, mandatory=True, timeout=5,
|
||||
)
|
||||
with span("attachments publish", kind=SpanKind.PRODUCER, parent=parent_context(job), attributes={
|
||||
"messaging.system": "rabbitmq", "messaging.destination.name": QUEUE,
|
||||
"messaging.operation": "publish", "job_id": job["job_id"], "attempt": job["attempt"],
|
||||
}):
|
||||
# The confirmed envelope names this producer span as the consumer's
|
||||
# parent. Durable outbox remains unchanged if confirmation is lost.
|
||||
outgoing = {**job, **carrier()}
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(json.dumps(outgoing).encode("utf-8"), content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=job["job_id"]),
|
||||
routing_key=QUEUE, mandatory=True, timeout=5,
|
||||
)
|
||||
emit("job.published", job_id=job["job_id"], attempt=job["attempt"], queue=QUEUE)
|
||||
|
||||
|
||||
async def event(db, row, name: str, detail: str = "") -> None:
|
||||
@@ -146,15 +160,23 @@ async def retry_or_fail(db, row, code: str, *, permanent: bool = False) -> None:
|
||||
logger.warning("failed attachment=%s code=%s", row["id"], final_code)
|
||||
return
|
||||
delay = retry_delay(row["attempts_run"])
|
||||
# A consumer retry continues from its active span. Lease recovery may have
|
||||
# no active span, so retain the context durably recorded by the old claim.
|
||||
context = carrier() or {name: row.get(name) for name in ("traceparent", "tracestate")}
|
||||
await db.execute(text("""
|
||||
UPDATE attachments SET status='queued',error_code=NULL,attempt=attempt+1,
|
||||
lease_token=NULL,lease_until=NULL,
|
||||
traceparent=:traceparent,tracestate=:tracestate,
|
||||
next_attempt_at=now()+make_interval(secs => CAST(:delay AS double precision)),
|
||||
updated_at=now() WHERE id=:id
|
||||
"""), {"id": row["id"], "delay": delay})
|
||||
"""), {"id": row["id"], "delay": delay,
|
||||
"traceparent": context.get("traceparent"), "tracestate": context.get("tracestate")})
|
||||
await db.execute(text("""
|
||||
INSERT INTO outbox(job_id,attachment_id,attempt,available_at)
|
||||
SELECT job_id,id,attempt,next_attempt_at FROM attachments WHERE id=:id
|
||||
INSERT INTO outbox(job_id,attachment_id,attempt,available_at,traceparent,tracestate)
|
||||
SELECT job_id,id,attempt,next_attempt_at,traceparent,tracestate FROM attachments WHERE id=:id
|
||||
"""), {"id": row["id"]})
|
||||
await event(db, row, "retry", f"{code}; delay={delay:.3f}s")
|
||||
logger.info("retry attachment=%s after=%.3fs", row["id"], delay)
|
||||
advanced.retries.add(1, {"job_type": "attachment.process.v1"})
|
||||
emit("job.retry", job_id=str(row["job_id"]), attachment_id=str(row["id"]),
|
||||
attempt=row["attempt"] + 1, outcome="retry", queue=QUEUE)
|
||||
|
||||
Reference in New Issue
Block a user