Files
mtusi2026lab6/src/infra/telemetry/metrics.py
T

205 lines
7.0 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.
"""Наблюдаемые метрики уровня 4: пул PostgreSQL, насыщение worker, очередь.
Design change `job-trace-propagation`, решения 9–11, 13. Значения читает
callback сбора метрик в потоке экспорта, пишет цикл событий: гонка безвредна
(целые, на сбор ± 1). Телеметрия выключена — регистрации нет.
"""
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from datetime import timedelta
from typing import Any
from opentelemetry.metrics import CallbackOptions, Observation
from src.infra.telemetry import core
from src.schemas.dataclasses import QueueSnapshotDTO
from src.utils.constants import (
ATTR_DB_CONNECTION_STATE,
ATTR_DB_POOL_NAME,
ATTR_MESSAGING_DESTINATION,
ATTR_QUEUE_STAGE,
DB_CONNECTION_STATE_IDLE,
DB_CONNECTION_STATE_USED,
METRIC_DB_CONNECTION_COUNT,
METRIC_DB_CONNECTION_MAX,
METRIC_DB_CONNECTION_PENDING,
METRIC_DB_CONNECTION_TIMEOUTS,
METRIC_QUEUE_DEPTH,
METRIC_QUEUE_OLDEST_AGE,
METRIC_WORKER_BUSY,
METRIC_WORKER_CAPACITY,
METRIC_WORKER_WAITING,
QUEUE_SNAPSHOT_STALE_SECONDS,
QUEUE_STAGE_OUTBOX,
QUEUE_STAGE_PROCESSING,
QUEUE_STAGE_PUBLISHED,
QUEUE_STAGE_SCHEDULED,
)
from src.utils.utc import utcnow
def pool_name(engine_url: Any) -> str:
"""Имя пула по semantic conventions: `server.address:server.port/
db.namespace`."""
port = "" if engine_url.port is None else f":{engine_url.port}"
return f"{engine_url.host or ''}{port}/{engine_url.database or ''}"
def observe_pool(engine: Any, *, max_overflow: int) -> None:
"""`db.client.connection.*` пула engine (решение 10): каждый сбор читает
текущий `engine.sync_engine.pool` — `dispose()` создаёт новый пул того же
класса. Ожидающие и отказы по сроку — у `CountingQueuePool`."""
meter = core.meter()
if meter is None:
return
sync_engine = engine.sync_engine
attributes = {ATTR_DB_POOL_NAME: pool_name(sync_engine.url)}
def counts(_options: CallbackOptions) -> Iterable[Observation]:
pool = sync_engine.pool
return [
Observation(
pool.checkedout(),
{
**attributes,
ATTR_DB_CONNECTION_STATE: DB_CONNECTION_STATE_USED,
},
),
Observation(
pool.checkedin(),
{
**attributes,
ATTR_DB_CONNECTION_STATE: DB_CONNECTION_STATE_IDLE,
},
),
]
def limit(_options: CallbackOptions) -> Iterable[Observation]:
return [
Observation(sync_engine.pool.size() + max_overflow, attributes),
]
def pending(_options: CallbackOptions) -> Iterable[Observation]:
read = getattr(sync_engine.pool, "pending", None)
return [] if read is None else [Observation(read(), attributes)]
def timeouts(_options: CallbackOptions) -> Iterable[Observation]:
read = getattr(sync_engine.pool, "timeouts", None)
return [] if read is None else [Observation(read(), attributes)]
meter.create_observable_up_down_counter(
METRIC_DB_CONNECTION_COUNT,
callbacks=[counts],
unit="{connection}",
description="Connections of the pool by state",
)
meter.create_observable_up_down_counter(
METRIC_DB_CONNECTION_MAX,
callbacks=[limit],
unit="{connection}",
description="Maximum connections of the pool",
)
meter.create_observable_up_down_counter(
METRIC_DB_CONNECTION_PENDING,
callbacks=[pending],
unit="{request}",
description="Requests waiting for a pool connection",
)
meter.create_observable_counter(
METRIC_DB_CONNECTION_TIMEOUTS,
callbacks=[timeouts],
unit="{timeout}",
description="Pool checkouts that timed out",
)
@dataclass(slots=True)
class WorkerLoad:
"""Счётчики мест конкуренции worker (решение 11): `waiting` — доставки до
входа в место, `busy` — внутри. Пишет `_handle` worker."""
busy: int = 0
waiting: int = 0
def observe_worker(*, capacity: int, load: WorkerLoad) -> None:
meter = core.meter()
if meter is None:
return
meter.create_observable_up_down_counter(
METRIC_WORKER_BUSY,
callbacks=[lambda _options: [Observation(load.busy)]],
unit="{delivery}",
description="Deliveries occupying a concurrency slot",
)
meter.create_observable_up_down_counter(
METRIC_WORKER_CAPACITY,
callbacks=[lambda _options: [Observation(capacity)]],
unit="{delivery}",
description="Concurrency slots of the worker",
)
meter.create_observable_up_down_counter(
METRIC_WORKER_WAITING,
callbacks=[lambda _options: [Observation(load.waiting)]],
unit="{delivery}",
description="Received deliveries waiting for a slot",
)
def queue_observations(
snapshot: QueueSnapshotDTO | None,
*,
queue: str,
) -> tuple[list[Observation], list[Observation]]:
"""Глубина по стадиям и возраст старейшего из последнего снимка; снимок
старше `QUEUE_SNAPSHOT_STALE_SECONDS` или его нет — ничего (решение 9)."""
if snapshot is None or utcnow() - snapshot.taken_at > timedelta(
seconds=QUEUE_SNAPSHOT_STALE_SECONDS,
):
return [], []
base = {ATTR_MESSAGING_DESTINATION: queue}
depth = [
Observation(value, {**base, ATTR_QUEUE_STAGE: stage})
for stage, value in (
(QUEUE_STAGE_SCHEDULED, snapshot.scheduled),
(QUEUE_STAGE_OUTBOX, snapshot.outbox),
(QUEUE_STAGE_PUBLISHED, snapshot.published),
(QUEUE_STAGE_PROCESSING, snapshot.processing),
)
]
age = 0.0
if snapshot.oldest_created_at is not None:
age = max(
0.0,
(snapshot.taken_at - snapshot.oldest_created_at).total_seconds(),
)
return depth, [Observation(age, base)]
def observe_queue(
*,
queue: str,
latest: Callable[[], QueueSnapshotDTO | None],
) -> None:
"""Gauge глубины и возраста очереди relay по последнему снимку."""
meter = core.meter()
if meter is None:
return
meter.create_observable_gauge(
METRIC_QUEUE_DEPTH,
callbacks=[
lambda _options: queue_observations(latest(), queue=queue)[0],
],
unit="{job}",
description="Unfinished jobs by stage",
)
meter.create_observable_gauge(
METRIC_QUEUE_OLDEST_AGE,
callbacks=[
lambda _options: queue_observations(latest(), queue=queue)[1],
],
unit="s",
description="Age of the oldest unfinished job since it was accepted",
)