it-architecture/backend/app/services/metrics.py

289 lines
12 KiB
Python

"""Flow metrics: deterministic history generation plus live increments.
Each flow row carries a steady-state cadence (interval, batch size, payload). The
hourly history is derived from that cadence with a seeded jitter so the graph has
real numbers to animate against, and re-generating the same day always yields the
same figures. The live tick then adds small increments on top so the picture moves
while somebody is watching it.
"""
from __future__ import annotations
import json
import random
import sqlite3
from datetime import date, datetime, timedelta
from ..db import all_, json_dump, setting, transaction, utcnow
# Weekday shape: the company works during business hours, quieter at night.
NIGHT_FACTOR = 0.06
WEEKEND_FACTOR = 0.18
PEAK_CURVE = {
0: 0.05, 1: 0.04, 2: 0.03, 3: 0.03, 4: 0.03, 5: 0.04,
6: 0.07, 7: 0.12, 8: 0.35, 9: 0.78, 10: 1.00, 11: 0.92,
12: 0.42, 13: 0.55, 14: 0.96, 15: 1.00, 16: 0.94, 17: 0.86,
18: 0.46, 19: 0.30, 20: 0.22, 21: 0.15, 22: 0.10, 23: 0.07,
}
def parse_peak_hours(raw) -> list[int]:
"""Accept either the stored JSON string or an already decoded list."""
if isinstance(raw, str):
try:
raw = json.loads(raw or "[]")
except json.JSONDecodeError:
return []
if not isinstance(raw, (list, tuple, set)):
return []
return {int(v) for v in raw if isinstance(v, (int, float)) and 0 <= int(v) <= 23}
def hour_weight(hour: int, peak_hours, reliability: str) -> float:
"""Relative activity for one hour, blending the global curve with flow peaks."""
peak_hours = parse_peak_hours(peak_hours)
base = PEAK_CURVE.get(hour, 0.1)
if hour in peak_hours:
base = max(base, 0.62 + 0.38 * PEAK_CURVE.get(hour, 0.1))
if reliability == "sync":
# Interactive links track head-office hours closely.
base *= 1.0
else:
# Batch jobs keep a low background trickle outside office hours.
base = max(base, 0.12)
return max(0.02, min(1.4, base))
def expected_batches(flow: dict, hour: int) -> float:
interval = max(30, int(flow["interval_sec"] or 3600))
capacity = 3600.0 / interval
return capacity * hour_weight(hour, flow["peak_hours"], flow["reliability"])
def _rng(seed: str, flow_id: int, day: str, hour: int) -> random.Random:
return random.Random(f"{seed}|{flow_id}|{day}|{hour}")
def day_is_weekend(day: date) -> bool:
return day.weekday() >= 5
def compute_bucket(flow: dict, day: date, hour: int, seed: str) -> dict:
"""Deterministic metric bucket for one flow/hour."""
rng = _rng(seed, flow["id"], day.isoformat(), hour)
weight = hour_weight(hour, flow["peak_hours"], flow["reliability"])
factor = WEEKEND_FACTOR if day_is_weekend(day) else 1.0
expected = expected_batches(flow, hour) * factor
jitter = rng.uniform(0.72, 1.32)
batches = max(0, int(round(expected * jitter)))
if batches == 0 and rng.random() < 0.12 * weight:
batches = 1
per_batch = max(1, int(flow["records_per_batch"]))
records = int(round(batches * per_batch * rng.uniform(0.8, 1.24))) if batches else 0
kb = float(flow["avg_payload_kb"] or 1.0)
payload_bytes = int(round(batches * kb * 1024 * rng.uniform(0.78, 1.3)))
# Occasional degraded window on async links so the health view has variety.
error_rate = 0.004 if flow["reliability"] == "async" else 0.001
errors = int(round(records * error_rate * rng.choice([0, 0, 0, 1, 1, 2, 6])))
latency = int(round(int(flow["latency_ms"]) * rng.uniform(0.82, 1.45)))
return {
"day": day.isoformat(),
"hour": hour,
"batches": batches,
"records": records,
"bytes": payload_bytes,
"errors": errors,
"latency_ms": latency,
}
def upsert_bucket(conn: sqlite3.Connection, flow_id: int, bucket: dict) -> None:
conn.execute(
"""INSERT INTO flow_metrics (flow_id, day, hour, batches, records, bytes, errors, latency_ms)
VALUES (?,?,?,?,?,?,?,?)
ON CONFLICT(flow_id, day, hour) DO UPDATE SET
batches = excluded.batches,
records = excluded.records,
bytes = excluded.bytes,
errors = excluded.errors,
latency_ms = excluded.latency_ms""",
(
flow_id, bucket["day"], bucket["hour"], bucket["batches"],
bucket["records"], bucket["bytes"], bucket["errors"], bucket["latency_ms"],
),
)
def ensure_history(conn: sqlite3.Connection, days: int = 30) -> None:
"""Backfill hourly history for any flow that does not have its own rows yet.
Checked per flow rather than globally so links added after the first run still
get a believable history instead of rendering as dead edges.
"""
flows = all_(
conn,
"""SELECT f.* FROM data_flows f
WHERE NOT EXISTS (SELECT 1 FROM flow_metrics m WHERE m.flow_id = f.id)""",
)
if not flows:
return
seed = str(setting(conn, "metric_seed", "it-panorama-seed-v1"))
today = date.today()
with transaction(conn):
for flow in flows:
for offset in range(days, 0, -1):
day = today - timedelta(days=offset)
for hour in range(24):
upsert_bucket(conn, flow["id"], compute_bucket(flow, day, hour, seed))
# Today only up to the current hour so the graph never claims future traffic.
day = today
for hour in range(datetime.now().hour + 1):
upsert_bucket(conn, flow["id"], compute_bucket(flow, day, hour, seed))
def live_tick(conn: sqlite3.Connection) -> dict:
"""Advance the current hour by one live step. Returns a compact summary."""
seed = str(setting(conn, "metric_seed", "it-panorama-seed-v1"))
now = datetime.now()
today = now.date()
hour = now.hour
rng = random.Random(f"live|{seed}|{today.isoformat()}|{hour}|{int(now.timestamp() // 7)}")
flows = all_(conn, "SELECT * FROM data_flows WHERE enabled = 1")
touched = 0
with transaction(conn):
for flow in flows:
weight = hour_weight(hour, flow["peak_hours"], flow["reliability"])
probability = min(0.95, weight * 0.85)
if rng.random() > probability:
continue
expected = expected_batches(flow, hour) / 24.0
batches = max(1, int(round(expected * rng.uniform(0.6, 2.2))))
conn.execute(
"""INSERT INTO flow_metrics (flow_id, day, hour, batches, records, bytes, errors, latency_ms)
VALUES (?,?,?,?,?,?,?,?)
ON CONFLICT(flow_id, day, hour) DO UPDATE SET
batches = batches + excluded.batches,
records = records + excluded.records,
bytes = bytes + excluded.bytes,
errors = errors + excluded.errors,
latency_ms = (latency_ms * 3 + excluded.latency_ms) / 4""",
(
flow["id"], today.isoformat(), hour, batches,
int(round(batches * flow["records_per_batch"] * rng.uniform(0.85, 1.3))),
int(round(batches * float(flow["avg_payload_kb"]) * 1024 * rng.uniform(0.85, 1.25))),
1 if (flow["reliability"] == "async" and rng.random() < 0.05) else 0,
int(round(int(flow["latency_ms"]) * rng.uniform(0.85, 1.4))),
),
)
touched += 1
conn.execute("INSERT INTO settings (key, value, updated_at) VALUES ('last_live_tick', ?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
(json_dump(now.replace(microsecond=0).isoformat()), utcnow()))
return {"touched": touched, "at": now.replace(microsecond=0).isoformat()}
def totals(conn: sqlite3.Connection, days: int) -> dict:
"""Rolling totals used by the KPI cards."""
start = (date.today() - timedelta(days=days - 1)).isoformat()
row = conn.execute(
"""SELECT COALESCE(SUM(m.batches),0) AS batches, COALESCE(SUM(m.records),0) AS records,
COALESCE(SUM(m.bytes),0) AS bytes, COALESCE(SUM(m.errors),0) AS errors,
AVG(NULLIF(m.latency_ms,0)) AS avg_latency
FROM flow_metrics m JOIN data_flows f ON f.id = m.flow_id
WHERE f.enabled = 1 AND m.day >= ?""",
(start,),
).fetchone()
active = conn.execute(
"""SELECT COUNT(*) AS c FROM flow_metrics m JOIN data_flows f ON f.id = m.flow_id
WHERE f.enabled = 1 AND m.day >= ? AND m.records > 0""",
(start,),
).fetchone()
return {
"batches": int(row["batches"] or 0),
"records": int(row["records"] or 0),
"bytes": int(row["bytes"] or 0),
"errors": int(row["errors"] or 0),
"avg_latency_ms": int(round(row["avg_latency"] or 0)),
"active_buckets": int(active["c"] or 0),
}
def series_for_day(conn: sqlite3.Connection, day: str) -> list[dict]:
return all_(
conn,
"""SELECT flow_id, hour, batches, records, bytes, errors, latency_ms
FROM flow_metrics WHERE day = ? ORDER BY flow_id, hour""",
(day,),
)
def hourly_series(conn: sqlite3.Connection, flow_id: int, days: int) -> list[dict]:
start = (date.today() - timedelta(days=days - 1)).isoformat()
return all_(
conn,
"""SELECT day, hour, batches, records, bytes, errors, latency_ms FROM flow_metrics
WHERE flow_id = ? AND day >= ? ORDER BY day, hour""",
(flow_id, start),
)
def health_label(error_rate: float, latency_ms: int) -> str:
if error_rate >= 0.02:
return "risk"
if error_rate >= 0.005 or latency_ms >= 900:
return "watch"
return "healthy"
def flow_health(conn: sqlite3.Connection, days: int = 7) -> dict[int, dict]:
"""Per-flow aggregate health over the trailing window."""
start = (date.today() - timedelta(days=days - 1)).isoformat()
rows = all_(
conn,
"""SELECT flow_id, SUM(batches) AS batches, SUM(records) AS records, SUM(bytes) AS bytes,
SUM(errors) AS errors, AVG(NULLIF(latency_ms,0)) AS latency,
MAX(records) AS peak_records
FROM flow_metrics WHERE day >= ? GROUP BY flow_id""",
(start,),
)
out: dict[int, dict] = {}
for row in rows:
records = int(row["records"] or 0)
errors = int(row["errors"] or 0)
latency = int(round(row["latency"] or 0))
rate = (errors / records) if records else 0.0
out[int(row["flow_id"])] = {
"batches": int(row["batches"] or 0),
"records": records,
"bytes": int(row["bytes"] or 0),
"errors": errors,
"error_rate": round(rate, 5),
"avg_latency_ms": latency,
"peak_hour_records": int(row["peak_records"] or 0),
"health": health_label(rate, latency),
}
return out
def throughput_rps(flow: dict, health: dict | None) -> float:
"""Records per second used to drive particle density and speed on the client."""
interval = max(30, int(flow["interval_sec"] or 3600))
weight = hour_weight(datetime.now().hour, flow["peak_hours"], flow["reliability"])
factor = WEEKEND_FACTOR if day_is_weekend(date.today()) else 1.0
per_hour = (3600.0 / interval) * weight * factor * int(flow["records_per_batch"])
return round(per_hour / 3600.0, 4)
def payload_rps(flow: dict) -> float:
interval = max(30, int(flow["interval_sec"] or 3600))
weight = hour_weight(datetime.now().hour, flow["peak_hours"], flow["reliability"])
factor = WEEKEND_FACTOR if day_is_weekend(date.today()) else 1.0
return round((3600.0 / interval) * weight * factor * float(flow["avg_payload_kb"]) / 1024.0, 4)
__all__ = [
"compute_bucket", "ensure_history", "live_tick", "totals", "series_for_day",
"hourly_series", "flow_health", "throughput_rps", "payload_rps", "hour_weight", "parse_peak_hours"
]