feat: Instrument durable API-to-worker telemetry (U2)

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 15:09:55 +03:00
parent 26f091c9b4
commit 8eab283f6f
14 changed files with 355 additions and 36 deletions
+18 -7
View File
@@ -13,6 +13,8 @@ from uuid import UUID, uuid4
from fastapi import HTTPException, Request
from minio import Minio
from minio.error import S3Error
from opentelemetry import trace
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from PIL import Image, UnidentifiedImageError
from urllib3 import PoolManager, Retry, Timeout
@@ -25,6 +27,8 @@ MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
logger = logging.getLogger(__name__)
tracer = trace.get_tracer(__name__)
trace_context = TraceContextTextMapPropagator()
def secret(name: str) -> str:
@@ -120,17 +124,24 @@ def persist_attachment(chat_id: str, actor_id: str, filename: str, content_type:
try:
stream.seek(0)
client = storage()
client.put_object(BUCKET, staging_key, stream, size, content_type=content_type)
with tracer.start_as_current_span("s3.stage_upload", record_exception=False, set_status_on_exception=False):
client.put_object(BUCKET, staging_key, stream, size, content_type=content_type)
with connection() as conn:
if not renew_upload(conn, attachment_id):
raise HTTPException(503)
verify_staging(client, staging_key, size, sha256, content_type)
with tracer.start_as_current_span("s3.verify_staging", record_exception=False, set_status_on_exception=False):
verify_staging(client, staging_key, size, sha256, content_type)
carrier = {}
trace_context.inject(carrier)
with connection() as conn:
row, _job_id = queue_attachment(
conn, attachment_id=attachment_id, chat_id=UUID(chat_id), owner_id=UUID(actor_id),
filename=filename, staging_key=staging_key, object_key=object_key,
content_type=content_type, size_bytes=size, sha256=sha256,
)
with tracer.start_as_current_span("db.queue_attachment", record_exception=False,
set_status_on_exception=False):
row, _job_id = queue_attachment(
conn, attachment_id=attachment_id, chat_id=UUID(chat_id), owner_id=UUID(actor_id),
filename=filename, staging_key=staging_key, object_key=object_key,
content_type=content_type, size_bytes=size, sha256=sha256,
traceparent=carrier.get("traceparent"), tracestate=carrier.get("tracestate"),
)
except HTTPException:
raise
except Exception as exc:
+39 -1
View File
@@ -1,16 +1,27 @@
"""FastAPI entry point and contract-wide response handling."""
"""FastAPI entry point, contract responses, and safe HTTP telemetry."""
import logging
from time import monotonic
from uuid import uuid4
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from .api import router
from . import telemetry
app = FastAPI()
app.include_router(router)
INSTANCE_ID = uuid4().hex
telemetry.configure("messenger-api")
HTTP_REQUESTS, HTTP_DURATION = telemetry.http_instruments()
TRACER = trace.get_tracer(__name__)
TRACE_CONTEXT = TraceContextTextMapPropagator()
logger = logging.getLogger(__name__)
ERRORS = {
400: ("invalid_request", "Неверный запрос"),
@@ -37,6 +48,33 @@ def error_response(request: Request, status: int, extra_headers: dict | None = N
@app.middleware("http")
async def request_contract(request: Request, call_next):
request.state.request_id = str(uuid4())
started = monotonic()
status = 500
context = TRACE_CONTEXT.extract(request.headers)
with TRACER.start_as_current_span("HTTP request", context=context, kind=SpanKind.SERVER,
record_exception=False, set_status_on_exception=False) as span:
try:
response = await _contract_response(request, call_next)
status = response.status_code
return response
finally:
route = getattr(request.scope.get("route"), "path", "unmatched")
status_class = f"{status // 100}xx"
attributes = {"method": request.method, "route": route, "status_class": status_class}
HTTP_REQUESTS.add(1, attributes)
HTTP_DURATION.record(monotonic() - started, attributes)
span.update_name(f"{request.method} {route}")
span.set_attribute("http.request.method", request.method)
span.set_attribute("http.route", route)
span.set_attribute("http.response.status_code", status)
span.set_attribute("request.id", request.state.request_id)
if status >= 500:
span.set_status(Status(StatusCode.ERROR))
logger.info("http_request", extra={"event": "http_request", "request_id": request.state.request_id,
"method": request.method, "route": route, "status_class": status_class})
async def _contract_response(request: Request, call_next):
is_upload = request.url.path.startswith("/api/v1/chats/") and request.url.path.endswith("/attachments")
if request.method == "POST" and request.url.path.startswith("/api/v1/") and request.url.path != "/api/v1/auth/sessions" and not is_upload:
media_type, _, charset = request.headers.get("content-type", "").lower().partition(";")
+11 -5
View File
@@ -13,7 +13,7 @@ REQUIRED_VARIANTS = {"original", "thumbnail", "crop", "optimized"}
def job_payload(row):
"""Broker message per jobs.schema.json: identifiers only, never file bytes."""
return {
payload = {
"schema_version": 1,
"job_id": str(row["job_id"]),
"type": "attachment.process.v1",
@@ -22,6 +22,10 @@ def job_payload(row):
"attempt": row["attempt"],
"created_at": row["created_at"].astimezone(timezone.utc).isoformat().replace("+00:00", "Z"),
}
for key in ("traceparent", "tracestate"):
if row.get(key):
payload[key] = row[key]
return payload
def reserve_upload(conn, attachment_id, staging_key, lease_seconds=300):
@@ -50,7 +54,7 @@ def renew_upload(conn, attachment_id, lease_seconds=300):
def queue_attachment(conn, *, attachment_id, chat_id, owner_id, filename,
staging_key, object_key, content_type, size_bytes, sha256,
pipeline_version=1):
pipeline_version=1, traceparent=None, tracestate=None):
"""Commit attachment, job, and outbox after the full S3 staging PUT."""
job_id = uuid4()
with conn.transaction():
@@ -70,8 +74,9 @@ def queue_attachment(conn, *, attachment_id, chat_id, owner_id, filename,
content_type, size_bytes, sha256, pipeline_version),
).fetchone()
conn.execute(
"INSERT INTO attachment_jobs (id,attachment_id,pipeline_version) VALUES (%s,%s,%s)",
(job_id, attachment_id, pipeline_version),
"INSERT INTO attachment_jobs (id,attachment_id,pipeline_version,traceparent,tracestate) "
"VALUES (%s,%s,%s,%s,%s)",
(job_id, attachment_id, pipeline_version, traceparent, tracestate),
)
conn.execute(
"INSERT INTO attachment_outbox (job_id,attempt) VALUES (%s,1)",
@@ -97,7 +102,8 @@ def claim_outbox(conn, limit=10, lease_seconds=30):
" SET claim_token=%s,claim_expires_at=clock_timestamp()+make_interval(secs => %s)"
" FROM due,attachment_jobs j"
" WHERE o.id=due.id AND j.id=o.job_id"
" RETURNING o.id,o.job_id,o.attempt,j.attachment_id,j.pipeline_version,j.created_at",
" RETURNING o.id,o.job_id,o.attempt,j.attachment_id,j.pipeline_version,j.created_at,"
"j.traceparent,j.tracestate",
(limit, token, lease_seconds),
).fetchall()
return token, rows
+29 -13
View File
@@ -8,36 +8,52 @@ from pathlib import Path
import pika
import psycopg
from opentelemetry import trace
from opentelemetry.trace import SpanKind
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from psycopg_pool import PoolTimeout
from .db import pool
from .pipeline_jobs import claim_outbox, confirm_outbox, job_payload
from .telemetry import configure
logger = logging.getLogger(__name__)
logger = logging.getLogger("src.publisher")
QUEUE = os.environ.get("BROKER_QUEUE", "attachments.process")
tracer = trace.get_tracer(__name__)
trace_context = TraceContextTextMapPropagator()
def publish_batch(channel):
with pool().connection() as conn:
token, rows = claim_outbox(conn, limit=10, lease_seconds=30)
for row in rows:
body = json.dumps(job_payload(row), separators=(",", ":")).encode("utf-8")
channel.basic_publish(
exchange="", routing_key=QUEUE, body=body, mandatory=True,
properties=pika.BasicProperties(
content_type="application/json", delivery_mode=2,
message_id=str(row["job_id"]), type="attachment.process.v1",
),
)
# basic_publish returns only after a broker confirm in confirm mode.
with pool().connection() as conn:
if not confirm_outbox(conn, row["id"], token):
logger.warning("Outbox claim expired before confirm for row %s", row["id"])
parent = trace_context.extract({key: row[key] for key in ("traceparent", "tracestate") if row.get(key)})
with tracer.start_as_current_span("attachments.publish", context=parent, kind=SpanKind.PRODUCER,
record_exception=False, set_status_on_exception=False) as span:
span.set_attribute("messaging.destination.name", QUEUE)
span.set_attribute("messaging.message.attempt", row["attempt"])
carrier = {}
trace_context.inject(carrier)
body = json.dumps({**job_payload(row), **carrier}, separators=(",", ":")).encode("utf-8")
channel.basic_publish(
exchange="", routing_key=QUEUE, body=body, mandatory=True,
properties=pika.BasicProperties(
content_type="application/json", delivery_mode=2,
message_id=str(row["job_id"]), type="attachment.process.v1",
),
)
# basic_publish returns only after a broker confirm in confirm mode.
with pool().connection() as conn:
if not confirm_outbox(conn, row["id"], token):
logger.warning("Outbox claim expired before confirm for row %s", row["id"])
logger.info("job_published", extra={"event": "job_published", "job_type": "attachment.process.v1",
"attempt": row["attempt"]})
return len(rows)
def main():
configure("messenger-publisher")
logging.basicConfig(level=logging.INFO)
logging.getLogger("pika").setLevel(logging.ERROR)
url = Path(os.environ["BROKER_URL_FILE"]).read_text(encoding="utf-8").strip()
+86
View File
@@ -0,0 +1,86 @@
"""Bounded, process-local OTLP setup and low-cardinality instruments."""
import logging
import os
from functools import lru_cache
from uuid import uuid4
from opentelemetry import metrics, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
HTTP_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10)
JOB_BUCKETS = (0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60, 120)
@lru_cache(maxsize=1)
def configure(service_name: str) -> bool:
"""Export asynchronously when Compose supplies a Collector endpoint."""
endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "").rstrip("/")
if not endpoint:
return False
resource = Resource.create({
"service.name": service_name,
"service.version": os.environ.get("APP_VERSION", "lab6"),
"service.instance.id": uuid4().hex,
"deployment.environment.name": "lab",
})
traces = TracerProvider(resource=resource)
traces.add_span_processor(BatchSpanProcessor(
OTLPSpanExporter(endpoint=f"{endpoint}/v1/traces", timeout=2),
max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=1000,
))
trace.set_tracer_provider(traces)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=f"{endpoint}/v1/metrics", timeout=2),
export_interval_millis=5000, export_timeout_millis=2000,
)
metrics.set_meter_provider(MeterProvider(
resource=resource, metric_readers=[reader],
views=[
View(instrument_name="messenger.http.duration", aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS)),
View(instrument_name="messenger.jobs.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
],
))
logs = LoggerProvider(resource=resource)
logs.add_log_record_processor(BatchLogRecordProcessor(
OTLPLogExporter(endpoint=f"{endpoint}/v1/logs", timeout=2),
max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=1000,
))
set_logger_provider(logs)
app_logger = logging.getLogger("src")
app_logger.setLevel(logging.INFO)
app_logger.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logs))
return True
@lru_cache(maxsize=1)
def http_instruments():
meter = metrics.get_meter("messenger.http")
return (
meter.create_counter("messenger.http.requests", unit="1"),
meter.create_histogram("messenger.http.duration", unit="s"),
)
@lru_cache(maxsize=1)
def job_instruments():
meter = metrics.get_meter("messenger.jobs")
return (
meter.create_counter("messenger.jobs.processed", unit="1"),
meter.create_histogram("messenger.jobs.duration", unit="s"),
)
+46 -7
View File
@@ -17,18 +17,24 @@ from uuid import UUID
import pika
import psycopg
from minio.error import S3Error
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from psycopg_pool import PoolTimeout
from .attachments import BUCKET, storage
from .db import pool
from .image_variants import InvalidImage, MAX_BYTES, render
from .pipeline_jobs import claim_job, complete_job, finish_attempt, recover_expired
from .telemetry import configure, job_instruments
logger = logging.getLogger(__name__)
logger = logging.getLogger("src.worker")
QUEUE = os.environ.get("BROKER_QUEUE", "attachments.process")
MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))
LEASE_SECONDS = int(os.environ.get("JOB_TIMEOUT_SECONDS", "60"))
tracer = trace.get_tracer(__name__)
trace_context = TraceContextTextMapPropagator()
def parse_message(body: bytes) -> dict:
@@ -126,11 +132,15 @@ def process_message(item: dict) -> str:
token = job["lease_token"]
try:
with _deadline(LEASE_SECONDS):
data = _source_bytes(job)
variants = render(data, job["content_type"])
stored = _write_variants(job, variants)
with tracer.start_as_current_span("s3.read_source", record_exception=False, set_status_on_exception=False):
data = _source_bytes(job)
with tracer.start_as_current_span("image.render", record_exception=False, set_status_on_exception=False):
variants = render(data, job["content_type"])
with tracer.start_as_current_span("s3.write_variants", record_exception=False, set_status_on_exception=False):
stored = _write_variants(job, variants)
with pool().connection() as conn:
current = complete_job(conn, job["id"], token, stored)
with tracer.start_as_current_span("db.complete_job", record_exception=False, set_status_on_exception=False):
current = complete_job(conn, job["id"], token, stored)
if current and job["staging_key"]:
try:
storage().remove_object(BUCKET, job["staging_key"])
@@ -152,6 +162,7 @@ def process_message(item: dict) -> str:
else:
code, permanent = "processing_failed", False
logger.warning("Job %s attempt %s: %s", job["id"], job["attempt"], code)
trace.get_current_span().add_event("job_retry_or_failure", {"error.code": code})
with pool().connection() as conn:
try:
return finish_attempt(
@@ -164,7 +175,36 @@ def process_message(item: dict) -> str:
return "stale_lease"
def traced_process_message(item: dict) -> str:
parent = trace_context.extract({key: item[key] for key in ("traceparent", "tracestate") if key in item})
with tracer.start_as_current_span("attachments.process", context=parent, kind=SpanKind.CONSUMER,
record_exception=False, set_status_on_exception=False) as span:
span.set_attribute("messaging.destination.name", QUEUE)
span.set_attribute("messaging.message.attempt", item["attempt"])
span.set_attribute("job.id", item["job_id"])
span.set_attribute("attachment.id", item["attachment_id"])
started = time.monotonic()
outcome = "error"
try:
outcome = process_message(item)
return outcome
except (psycopg.Error, PoolTimeout, OSError):
outcome = "database_unavailable"
raise
finally:
attributes = {"job_type": item["type"], "outcome": outcome}
processed, duration = job_instruments()
processed.add(1, attributes)
duration.record(time.monotonic() - started, attributes)
span.set_attribute("job.outcome", outcome)
if outcome in {"failed", "database_unavailable", "error"}:
span.set_status(Status(StatusCode.ERROR))
logger.info("job_processed", extra={"event": "job_processed", "job_type": item["type"],
"outcome": outcome, "attempt": item["attempt"]})
def main() -> None:
configure("messenger-worker")
logging.basicConfig(level=logging.INFO)
if MAX_ATTEMPTS < 1 or LEASE_SECONDS < 1:
raise SystemExit("invalid worker retry settings")
@@ -197,9 +237,8 @@ def main() -> None:
channel.basic_reject(method.delivery_tag, requeue=False)
continue
try:
result = process_message(item)
traced_process_message(item)
channel.basic_ack(method.delivery_tag)
logger.info("Job %s: %s", item["job_id"], result)
except (psycopg.Error, PoolTimeout, OSError) as exc:
logger.warning("Job %s database unavailable (%s)", item["job_id"], type(exc).__name__)
channel.basic_nack(method.delivery_tag, requeue=True)