Files
mtusi2026lab7/src/infra/telemetry/db.py
T
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

131 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Span запросов PostgreSQL — слушатели событий engine (решения 4 и 12).
`instrumentation-sqlalchemy` 0.66b2 требует `sqlalchemy<2.1`, а у нас 2.1:
поэтому свои слушатели `before_cursor_execute`, `after_cursor_execute` и
`handle_error`. Их ставит точка входа процесса (`instrument_engine`), фабрика
engine о телеметрии не знает. Запрос асинхронной сессии выполняется в
greenlet с контекстом задачи: родитель — span запроса или задания, без него
span нет (правило корня). Фиксацию (`COMMIT` asyncpg идёт мимо событий
курсора) пишет `SqlAlchemyUnitOfWork._commit`.
"""
from typing import Any
from opentelemetry import trace
from opentelemetry.trace import SpanKind
from sqlalchemy import event
from sqlalchemy.engine import ExceptionContext
from sqlalchemy.ext.asyncio import AsyncEngine
from src.config import settings
from src.infra.telemetry import core, metrics
DB_SYSTEM = "postgresql"
# атрибут контекста выполнения со span запроса
_SPAN_ATTR = "_messenger_span"
def db_attributes(engine_url: Any) -> dict[str, Any]:
attributes: dict[str, Any] = {
"db.system.name": DB_SYSTEM,
"db.namespace": engine_url.database or "",
"server.address": engine_url.host or "",
}
if engine_url.port is not None:
attributes["server.port"] = engine_url.port
return attributes
def operation_name(statement: str) -> str:
"""Первое слово запроса: `SELECT`, `INSERT`, `WITH`…"""
words = statement.split(None, 1)
return words[0].upper() if words else "QUERY"
def instrument_engine(
engine: AsyncEngine,
*,
max_overflow: int | None = None,
) -> None:
"""Слушатели span и метрики пула (`db.client.connection.*`, design change
`job-trace-propagation`, решение 10) на engine процесса; предел пула —
его размер и `max_overflow` (по умолчанию `[database]`). Телеметрия
выключена — ничего."""
if not core.is_enabled():
return
metrics.observe_pool(
engine,
max_overflow=(
settings.database.max_overflow
if max_overflow is None
else max_overflow
),
)
sync_engine = engine.sync_engine
base = db_attributes(sync_engine.url)
def before(
_conn: Any,
_cursor: Any,
statement: str,
_parameters: Any,
context: Any,
_executemany: bool,
) -> None:
tracer = core.tracer()
if (
tracer is None
or context is None
or not trace.get_current_span().is_recording()
):
return
operation = operation_name(statement)
span = tracer.start_span(
operation,
kind=SpanKind.CLIENT,
attributes={
**base,
"db.operation.name": operation,
# параметризованный SQL: значения — плейсхолдеры
"db.query.text": statement,
},
)
setattr(context, _SPAN_ATTR, span)
def after(
_conn: Any,
_cursor: Any,
_statement: str,
_parameters: Any,
context: Any,
_executemany: bool,
) -> None:
span = getattr(context, _SPAN_ATTR, None)
if span is not None:
setattr(context, _SPAN_ATTR, None)
span.end()
def on_error(exception_context: ExceptionContext) -> None:
context = exception_context.execution_context
span = getattr(context, _SPAN_ATTR, None)
if span is None:
return
setattr(context, _SPAN_ATTR, None)
core.mark_error(span, exception_context.original_exception)
span.end()
event.listen(sync_engine, "before_cursor_execute", before)
event.listen(sync_engine, "after_cursor_execute", after)
event.listen(sync_engine, "handle_error", on_error)
def commit_span() -> Any:
"""Span фиксации транзакции единицы работы."""
return core.child_span(
"COMMIT",
attributes={
"db.system.name": DB_SYSTEM,
"db.operation.name": "COMMIT",
},
)