From 8eab283f6f4d711c53f052894a6406c95a4afad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B0=D0=BC=D0=BE=D1=85=D0=B2=D0=B0=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=90=D0=BD=D0=B4=D1=80=D0=B5=D0=B9=20=D0=A0=D0=B5?= =?UTF-8?q?=D0=BC=D0=BE=D0=B2=D0=B8=D1=87?= Date: Fri, 2 Oct 2026 15:09:55 +0300 Subject: [PATCH] feat: Instrument durable API-to-worker telemetry (U2) --- .gitignore | 1 + compose.telemetry.yaml | 7 ++- compose.yaml | 8 ++- migrations/008_trace_context.sql | 7 +++ requirements.txt | 4 ++ scripts/setup-local-secrets.py | 2 + src/attachments.py | 25 +++++--- src/main.py | 40 +++++++++++- src/pipeline_jobs.py | 16 +++-- src/publisher.py | 42 +++++++++---- src/telemetry.py | 86 +++++++++++++++++++++++++ src/worker.py | 53 +++++++++++++--- student-tests/test_outbox_payload.py | 6 +- student-tests/test_telemetry.py | 94 ++++++++++++++++++++++++++++ 14 files changed, 355 insertions(+), 36 deletions(-) create mode 100644 migrations/008_trace_context.sql create mode 100644 src/telemetry.py create mode 100644 student-tests/test_telemetry.py diff --git a/.gitignore b/.gitignore index f101a4f..860fedd 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ .env .env.* !.env.example +compose.local.yaml secrets/ certs/private/ *.key diff --git a/compose.telemetry.yaml b/compose.telemetry.yaml index 8201791..02f35c4 100644 --- a/compose.telemetry.yaml +++ b/compose.telemetry.yaml @@ -41,7 +41,8 @@ services: ports: - "127.0.0.1:${GRAFANA_PORT:-3000}:3000" environment: - GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in local .env} + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + secrets: [grafana_admin_password] volumes: - grafana_data:/var/lib/grafana - ./infra/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro @@ -57,3 +58,7 @@ volumes: loki_data: tempo_data: grafana_data: + +secrets: + grafana_admin_password: + file: ./secrets/grafana_admin_password diff --git a/compose.yaml b/compose.yaml index 8bdc432..345da2d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,4 +1,4 @@ -name: mtusi2026lab5 +name: mtusi2026lab6 services: postgres: @@ -112,6 +112,8 @@ services: S3_BUCKET: messenger-attachments S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 + APP_VERSION: lab6 secrets: [database_url, s3_access_key_id, s3_secret_access_key] depends_on: migrate: @@ -135,6 +137,8 @@ services: DATABASE_URL_FILE: /run/secrets/database_url BROKER_URL_FILE: /run/secrets/broker_url BROKER_QUEUE: attachments.process + OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 + APP_VERSION: lab6 secrets: [database_url, broker_url] depends_on: migrate: @@ -175,6 +179,8 @@ services: WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1} JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 + APP_VERSION: lab6 secrets: [database_url, broker_url, s3_access_key_id, s3_secret_access_key] depends_on: migrate: diff --git a/migrations/008_trace_context.sql b/migrations/008_trace_context.sql new file mode 100644 index 0000000..f992f9a --- /dev/null +++ b/migrations/008_trace_context.sql @@ -0,0 +1,7 @@ +-- Preserve the upload span context across the durable outbox and every retry. +-- Version 007 is reserved for the lab5 replay/audit migration. +ALTER TABLE attachment_jobs + ADD COLUMN traceparent text + CHECK (traceparent IS NULL OR traceparent ~ '^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$'), + ADD COLUMN tracestate text + CHECK (tracestate IS NULL OR length(tracestate) <= 512); diff --git a/requirements.txt b/requirements.txt index a9a509e..2655fc2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,3 +8,7 @@ minio==7.2.20 Pillow==11.3.0 urllib3==2.8.0 pika==1.4.4 +opentelemetry-api==1.45.0 +opentelemetry-sdk==1.45.0 +opentelemetry-semantic-conventions==0.66b0 +opentelemetry-exporter-otlp-proto-http==1.45.0 diff --git a/scripts/setup-local-secrets.py b/scripts/setup-local-secrets.py index 168168d..6fbac6d 100644 --- a/scripts/setup-local-secrets.py +++ b/scripts/setup-local-secrets.py @@ -36,6 +36,8 @@ def main() -> None: write("s3_secret_access_key", secrets.token_urlsafe(32)) write("s3_maintenance_key_id", secrets.token_hex(10)) write("s3_maintenance_secret_key", secrets.token_urlsafe(32)) + if not (ROOT / "grafana_admin_password").exists(): + write("grafana_admin_password", secrets.token_urlsafe(32)) if __name__ == "__main__": diff --git a/src/attachments.py b/src/attachments.py index 818c5a5..13cb080 100644 --- a/src/attachments.py +++ b/src/attachments.py @@ -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: diff --git a/src/main.py b/src/main.py index 26dea4b..d8a500c 100644 --- a/src/main.py +++ b/src/main.py @@ -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(";") diff --git a/src/pipeline_jobs.py b/src/pipeline_jobs.py index 5fa477f..47b2342 100644 --- a/src/pipeline_jobs.py +++ b/src/pipeline_jobs.py @@ -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 diff --git a/src/publisher.py b/src/publisher.py index 53fdfb8..209d24b 100644 --- a/src/publisher.py +++ b/src/publisher.py @@ -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() diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 0000000..9d6408c --- /dev/null +++ b/src/telemetry.py @@ -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"), + ) diff --git a/src/worker.py b/src/worker.py index b0c2f7f..364b58b 100644 --- a/src/worker.py +++ b/src/worker.py @@ -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) diff --git a/student-tests/test_outbox_payload.py b/student-tests/test_outbox_payload.py index 0fe6b3f..b1c37de 100644 --- a/student-tests/test_outbox_payload.py +++ b/student-tests/test_outbox_payload.py @@ -23,10 +23,14 @@ class OutboxPayloadTest(unittest.TestCase): "job_id": uuid4(), "attachment_id": uuid4(), "pipeline_version": 2, "attempt": 3, "created_at": datetime.now(timezone.utc), "object_key": "staging/must-not-leak", "bytes": b"must-not-leak", + "traceparent": "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01", + "tracestate": "lab=upload", } message = job_payload(row) validate(message, schema) - self.assertEqual(set(message), set(schema["required"])) + self.assertEqual(set(message), set(schema["required"]) | {"traceparent", "tracestate"}) + self.assertEqual(message["traceparent"], row["traceparent"]) + self.assertEqual(message["tracestate"], row["tracestate"]) self.assertNotIn("staging", json.dumps(message)) self.assertNotIn("bytes", json.dumps(message)) diff --git a/student-tests/test_telemetry.py b/student-tests/test_telemetry.py new file mode 100644 index 0000000..d5b8837 --- /dev/null +++ b/student-tests/test_telemetry.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""The durable job carrier preserves one trace across broker boundaries.""" + +import json +import sys +import unittest +from datetime import datetime, timezone +from pathlib import Path +from unittest.mock import Mock, patch +from uuid import uuid4 + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from opentelemetry import trace # noqa: E402 +from opentelemetry.sdk.trace import TracerProvider # noqa: E402 +from opentelemetry.sdk.trace.export import SimpleSpanProcessor # noqa: E402 +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter # noqa: E402 +from opentelemetry.trace import SpanKind # noqa: E402 +from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator # noqa: E402 + + +exporter = InMemorySpanExporter() +provider = TracerProvider() +provider.add_span_processor(SimpleSpanProcessor(exporter)) +trace.set_tracer_provider(provider) + +from src.pipeline_jobs import job_payload # noqa: E402 +from src import worker # noqa: E402 + + +class TelemetryTest(unittest.TestCase): + def setUp(self): + exporter.clear() + + def test_failed_job_has_low_cardinality_metric_and_error_span(self): + item = { + "job_id": str(uuid4()), "attachment_id": str(uuid4()), + "type": "attachment.process.v1", "attempt": 1, + } + counter, duration = Mock(), Mock() + with patch.object(worker, "process_message", return_value="failed"), \ + patch.object(worker, "job_instruments", return_value=(counter, duration)): + self.assertEqual(worker.traced_process_message(item), "failed") + labels = {"job_type": "attachment.process.v1", "outcome": "failed"} + counter.add.assert_called_once_with(1, labels) + self.assertEqual(duration.record.call_args.args[1], labels) + self.assertEqual(exporter.get_finished_spans()[-1].status.status_code.name, "ERROR") + + def test_upload_publish_consume_and_retry_share_causal_trace(self): + propagator = TraceContextTextMapPropagator() + tracer = trace.get_tracer(__name__) + row = { + "job_id": uuid4(), "attachment_id": uuid4(), "pipeline_version": 1, + "attempt": 1, "created_at": datetime.now(timezone.utc), + } + + with tracer.start_as_current_span("upload") as upload: + upload_carrier = {} + propagator.inject(upload_carrier) + row.update(upload_carrier) + + producer_parent = propagator.extract(upload_carrier) + with tracer.start_as_current_span("publish", context=producer_parent, kind=SpanKind.PRODUCER) as producer: + producer_carrier = {} + propagator.inject(producer_carrier) + message = {**job_payload(row), **producer_carrier} + + with patch.object(worker, "process_message", return_value="queued"): + self.assertEqual(worker.traced_process_message(worker.parse_message(json.dumps(message).encode())), "queued") + # A managed retry uses the same durable upload parent but a new + # publisher attempt; both worker attempts remain in one trace. + row["attempt"] = 2 + retry_parent = propagator.extract(upload_carrier) + with tracer.start_as_current_span("retry_publish", context=retry_parent, + kind=SpanKind.PRODUCER) as retry_producer: + retry_carrier = {} + propagator.inject(retry_carrier) + retry_message = {**job_payload(row), **retry_carrier} + self.assertEqual(worker.traced_process_message(worker.parse_message(json.dumps(retry_message).encode())), "queued") + + spans = exporter.get_finished_spans() + consumers = [span for span in spans if span.name == "attachments.process"] + self.assertEqual(len(consumers), 2) + self.assertEqual(consumers[0].parent.span_id, producer.get_span_context().span_id) + self.assertEqual(consumers[1].parent.span_id, retry_producer.get_span_context().span_id) + self.assertEqual(producer.parent.span_id, upload.get_span_context().span_id) + self.assertEqual(retry_producer.parent.span_id, upload.get_span_context().span_id) + self.assertEqual({span.context.trace_id for span in spans}, {upload.get_span_context().trace_id}) + + +if __name__ == "__main__": + unittest.main()