metrics.py 16.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
import logging
import time

from datetime import datetime, timedelta, timezone

import redis.asyncio as redis

from starlette.routing import Match


PREFIX = "metrics:v1"
TTL_SECONDS = 7 * 24 * 60 * 60
STREAM_MAXLEN = 10000
HTTP_BUCKETS_MS = (100, 300, 600, 1000, 2000, 3000)
PRIVATE_API_PREFIXES = ("/_metrics", "/api/_metrics")

redis_client = None
logger = logging.getLogger("api_proy2")


###############################################################################
# middleware
###############################################################################

class MetricsMiddleware:
    def __init__(self, app, routes):
        self.app = app
        self.routes = routes

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        path = scope.get("path", "")
        if path.startswith(PRIVATE_API_PREFIXES):
            await self.app(scope, receive, send)
            return

        started_at = time.perf_counter()
        status_code = 500
        response_headers = []

        async def send_wrapper(message):
            nonlocal status_code, response_headers

            if message["type"] == "http.response.start":
                status_code = message["status"]
                response_headers = message.get("headers", [])

            await send(message)

        try:
            await self.app(scope, receive, send_wrapper)
        finally:
            try:
                await record_http(
                    method=scope.get("method", "GET"),
                    route=find_route_template(self.routes, scope),
                    path=scope.get("path", ""),
                    client_ip=get_client_ip(scope.get("headers", [])),
                    status_code=status_code,
                    duration_ms=(time.perf_counter() - started_at) * 1000,
                    cache_status=get_header_value(response_headers, b"x-cache"),
                )
            except Exception:
                logger.exception("metrics write failed")


def install(app):
    app.add_middleware(MetricsMiddleware, routes=app.router.routes)


###############################################################################
# redis lifecycle
###############################################################################

async def get_redis():
    global redis_client

    if redis_client is not None:
        return redis_client

    with open("./docs/redis") as f:
        redis_url = f.read().strip()

    if "://" not in redis_url:
        redis_url = f"redis://{redis_url}"

    redis_client = redis.from_url(redis_url, decode_responses=True)
    return redis_client


async def close_redis():
    global redis_client

    if redis_client is None:
        return

    await redis_client.aclose()
    redis_client = None


###############################################################################
# write api
###############################################################################

async def record_http(
    method,
    route,
    path,
    client_ip,
    status_code,
    duration_ms,
    cache_status=None
):
    redis_conn = await get_redis()
    minute = get_current_minute()
    http_minute_key = get_http_minute_key(minute)
    ip_minute_key = get_ip_minute_key(minute)
    route_label = join_label(method, route, int(status_code))
    route_key = join_label(method, route)
    pipe = redis_conn.pipeline(transaction=False)

    pipe.hincrby(http_minute_key, f"count|{route_label}", 1)
    pipe.hincrbyfloat(http_minute_key, f"sum_ms|{route_label}", float(duration_ms))
    pipe.hincrby(http_minute_key, f"status|{int(status_code)}", 1)

    if cache_status in {"hit", "miss"}:
        pipe.hincrby(http_minute_key, f"cache_{cache_status}|{route_key}", 1)

    for bucket_ms in HTTP_BUCKETS_MS:
        if duration_ms <= bucket_ms:
            pipe.hincrby(http_minute_key, f"le_{bucket_ms}|{route_label}", 1)

    pipe.hincrby(ip_minute_key, normalize_label_part(client_ip), 1)

    pipe.expire(http_minute_key, TTL_SECONDS)
    pipe.expire(ip_minute_key, TTL_SECONDS)

    # pipe.xadd(
    #     get_requests_stream_key(),
    #     {
    #         "ts": get_now_utc().isoformat(),
    #         "method": str(method),
    #         "route": str(route),
    #         "path": str(path),
    #         "client_ip": str(client_ip or ""),
    #         "status_code": str(int(status_code)),
    #         "duration_ms": str(round(float(duration_ms), 3)),
    #         "cache_status": str(cache_status or ""),
    #     },
    #     maxlen=STREAM_MAXLEN,
    #     approximate=True,
    # )
    await pipe.execute()


###############################################################################
# read api
###############################################################################

async def read_summary(minutes=60, include_ts=False):
    if include_ts:
        return await read_summary_series(minutes)

    return await read_summary_window(minutes)


async def read_routes(minutes=60, include_ts=False):
    if include_ts:
        return await read_route_series(minutes)

    return await read_route_window(minutes)


async def read_ips(minutes=60, include_ts=False):
    if include_ts:
        return await read_ip_series(minutes)

    return await read_ip_window(minutes)


# async def read_requests(limit=100):
#     redis_conn = await get_redis()
#     rows = await redis_conn.xrevrange(get_requests_stream_key(), count=limit)
#     return [{"id": row_id, "fields": payload} for row_id, payload in rows]


async def read_http(minutes):
    return merge_minute_maps(await load_http_minutes(minutes))


###############################################################################
# summary readers
###############################################################################

async def read_summary_window(minutes):
    http_minutes = await load_http_minutes(minutes)
    http_fields = merge_minute_maps(http_minutes)
    total_count = get_total_count(http_fields)
    total_sum_ms = get_total_sum_ms(http_fields)

    return {
        "window_minutes": minutes,
        "generated_at": get_now_utc().isoformat(),
        "http": {
            "count": total_count,
            "sum_ms": total_sum_ms,
            "avg_ms": round(total_sum_ms / total_count, 3) if total_count else 0.0,
            "status": get_status_totals(http_fields),
            "cache": get_cache_totals(http_fields),
            "buckets_ms": get_bucket_totals(http_fields),
        },
    }


async def read_summary_series(minutes):
    http_minutes = await load_http_minutes(minutes)
    http_fields = merge_minute_maps(http_minutes)
    total_count = get_total_count(http_fields)
    total_sum_ms = get_total_sum_ms(http_fields)
    series = []

    for minute, minute_fields in http_minutes:
        minute_count = get_total_count(minute_fields)
        minute_sum_ms = get_total_sum_ms(minute_fields)
        series.append({
            "minute": minute,
            "http": {
                "count": minute_count,
                "sum_ms": minute_sum_ms,
                "avg_ms": round(minute_sum_ms / minute_count, 3) if minute_count else 0.0,
                "status": get_status_totals(minute_fields),
                "cache": get_cache_totals(minute_fields),
                "buckets_ms": get_bucket_totals(minute_fields),
            },
        })

    return {
        "window_minutes": minutes,
        "generated_at": get_now_utc().isoformat(),
        "http": {
            "count": total_count,
            "sum_ms": total_sum_ms,
            "avg_ms": round(total_sum_ms / total_count, 3) if total_count else 0.0,
            "status": get_status_totals(http_fields),
            "cache": get_cache_totals(http_fields),
            "buckets_ms": get_bucket_totals(http_fields),
        },
        "series": series,
    }


###############################################################################
# route readers
###############################################################################

async def read_route_window(minutes):
    return build_route_rows(await read_http(minutes))


async def read_route_series(minutes):
    rows = []

    for minute, minute_fields in await load_http_minutes(minutes):
        rows.extend(build_route_rows(minute_fields, minute=minute))

    rows.sort(key=lambda row: (
        row["minute"], -row["count"], -row["sum_ms"], row["route"]
    ))
    return rows


###############################################################################
# ip readers
###############################################################################

async def read_ip_window(minutes):
    ip_fields = merge_minute_maps(await load_ip_minutes(minutes))
    rows = []

    for ip, count in ip_fields.items():
        rows.append({
            "ip": ip,
            "count": int(count),
        })

    rows.sort(key=lambda row: (-row["count"], row["ip"]))
    return rows


async def read_ip_series(minutes):
    rows = []

    for minute, minute_fields in await load_ip_minutes(minutes):
        for ip, count in minute_fields.items():
            rows.append({
                "minute": minute,
                "ip": ip,
                "count": int(count),
            })

    rows.sort(key=lambda row: (row["minute"], -row["count"], row["ip"]))
    return rows


###############################################################################
# minute loaders
###############################################################################

async def load_http_minutes(minutes):
    minute_keys = get_minute_buckets(minutes)
    if not minute_keys:
        return []

    redis_conn = await get_redis()
    pipe = redis_conn.pipeline(transaction=False)

    for minute in minute_keys:
        pipe.hgetall(get_http_minute_key(minute))

    rows = await pipe.execute()
    return build_minute_maps(minute_keys, rows)


async def load_ip_minutes(minutes):
    minute_keys = get_minute_buckets(minutes)
    if not minute_keys:
        return []

    redis_conn = await get_redis()
    pipe = redis_conn.pipeline(transaction=False)

    for minute in minute_keys:
        pipe.hgetall(get_ip_minute_key(minute))

    rows = await pipe.execute()
    return build_minute_maps(minute_keys, rows)


###############################################################################
# route matching
###############################################################################

def find_route_template(routes, scope):
    route_template = match_route_template(routes, scope)
    if route_template is not None:
        return route_template

    root_path = scope.get("root_path", "")
    path = scope.get("path", "")

    if root_path and path.startswith(root_path):
        stripped_scope = dict(scope)
        stripped_scope["path"] = path[len(root_path):] or "/"
        route_template = match_route_template(routes, stripped_scope)
        if route_template is not None:
            return route_template

    return path


def match_route_template(routes, scope):
    for route in routes:
        match, _ = route.matches(scope)
        if match == Match.FULL:
            return getattr(
                route, "path_format", getattr(route, "path", scope.get("path", ""))
            )

    return None


###############################################################################
# request parsing
###############################################################################

def get_header_value(headers, key):
    for header_key, header_value in headers:
        if header_key.lower() == key:
            return header_value.decode()

    return None


def get_client_ip(headers):
    real_ip = get_header_value(headers, b"x-real-ip")
    if real_ip:
        return real_ip.strip()
    
    forwarded_for = get_header_value(headers, b"x-forwarded-for")
    if forwarded_for:
        return forwarded_for.split(",", 1)[0].strip()

    return None


###############################################################################
# row builders
###############################################################################

def build_route_rows(fields, minute=None):
    routes = {}

    for field, value in fields.items():
        parts = field.split("|")
        if len(parts) < 4:
            continue

        metric_name = parts[0]
        method = parts[1]
        route = parts[2]
        status_code = parts[3]

        if metric_name not in {"count", "sum_ms"} and not metric_name.startswith("le_"):
            continue

        route_key = (method, route, status_code)
        if route_key not in routes:
            routes[route_key] = {
                "method": method,
                "route": route,
                "status_code": int(status_code),
                "count": 0,
                "sum_ms": 0.0,
                "avg_ms": 0.0,
                "buckets_ms": {},
            }

            if minute is not None:
                routes[route_key]["minute"] = minute

        if metric_name == "count":
            routes[route_key]["count"] += int(value)
        elif metric_name == "sum_ms":
            routes[route_key]["sum_ms"] += float(value)
        else:
            bucket_ms = metric_name[3:]
            routes[route_key]["buckets_ms"][bucket_ms] = (
                routes[route_key]["buckets_ms"].get(bucket_ms, 0) + int(value)
            )

    rows = []
    for row in routes.values():
        if row["count"]:
            row["avg_ms"] = round(row["sum_ms"] / row["count"], 3)
        row["sum_ms"] = round(row["sum_ms"], 3)
        rows.append(row)

    rows.sort(key=lambda row: (-row["count"], -row["sum_ms"], row["route"]))
    return rows


def build_minute_maps(minute_keys, rows):
    minute_maps = []

    for minute, row in zip(minute_keys, rows):
        minute_fields = {}
        for field, raw_value in row.items():
            minute_fields[field] = float(raw_value)
        minute_maps.append((minute, minute_fields))

    return minute_maps


###############################################################################
# aggregation helpers
###############################################################################

def merge_minute_maps(minute_maps):
    merged = {}

    for _, minute_fields in minute_maps:
        for field, value in minute_fields.items():
            merged[field] = merged.get(field, 0.0) + float(value)

    return merged


def get_total_count(fields):
    count = 0

    for field, value in fields.items():
        if field.startswith("count|"):
            count += int(value)

    return count


def get_total_sum_ms(fields):
    total = 0.0

    for field, value in fields.items():
        if field.startswith("sum_ms|"):
            total += float(value)

    return round(total, 3)


def get_status_totals(fields):
    totals = {}

    for field, value in fields.items():
        if field.startswith("status|"):
            status_code = field.split("|", 1)[1]
            totals[status_code] = totals.get(status_code, 0) + int(value)

    return totals


def get_cache_totals(fields):
    totals = {"hit": 0, "miss": 0}

    for field, value in fields.items():
        if field.startswith("cache_hit|"):
            totals["hit"] += int(value)
        elif field.startswith("cache_miss|"):
            totals["miss"] += int(value)

    return totals


def get_bucket_totals(fields):
    totals = {}

    for field, value in fields.items():
        if field.startswith("le_"):
            bucket_ms = field.split("|", 1)[0][3:]
            totals[bucket_ms] = totals.get(bucket_ms, 0) + int(value)

    return totals


###############################################################################
# time and key helpers
###############################################################################

def get_now_utc():
    return datetime.now(timezone.utc)


def get_current_minute(now=None):
    now = now or get_now_utc()
    return now.strftime("%Y%m%d%H%M")


def get_minute_buckets(minutes, now=None):
    if minutes <= 0:
        return []

    now = now or get_now_utc()
    base = now.replace(second=0, microsecond=0)
    return [
        (base - timedelta(minutes=offset)).strftime("%Y%m%d%H%M")
        for offset in range(minutes)
    ]


def get_http_minute_key(minute):
    return f"{PREFIX}:http:{minute}"


def get_ip_minute_key(minute):
    return f"{PREFIX}:ip:{minute}"


def get_requests_stream_key():
    return f"{PREFIX}:requests"


###############################################################################
# label helpers
###############################################################################

def join_label(*parts):
    return "|".join(normalize_label_part(part) for part in parts)


def normalize_label_part(value):
    if value is None:
        return "__none__"

    text = str(value).strip()
    if not text:
        return "__empty__"

    return text.replace("|", "_")