File size: 19,663 Bytes
04bb755 | 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 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Collect infrastructure usage metrics and send Discord reports."""
import logging
import os
from datetime import datetime, timezone, timedelta
import httpx
from sqlalchemy import func, select, text
from sqlalchemy.ext.asyncio import AsyncSession
from src.models.infrastructure_metric import InfrastructureMetric
from src.models.user import User
from src.models.task import Task
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Metric definitions
# ---------------------------------------------------------------------------
METRIC_DEFINITIONS = [
{
"key": "db_storage_bytes",
"label": "Database Storage",
"limit": 524_288_000,
"upgrade_trigger": "Supabase Pro ($25/mo)",
"upgrade_url": "https://supabase.com/dashboard",
"format": "bytes",
},
{
"key": "db_connections",
"label": "DB Connections",
"limit": 200,
"upgrade_trigger": "Reduce pool_size or upgrade Supabase",
"upgrade_url": None,
"format": "number",
},
{
"key": "db_table_rows",
"label": "Table Row Counts",
"limit": None,
"upgrade_trigger": None,
"upgrade_url": None,
"format": "number",
},
{
"key": "cf_requests_day",
"label": "CF Worker Requests/Day",
"limit": 100_000,
"upgrade_trigger": "CF Workers paid ($5/mo)",
"upgrade_url": "https://dash.cloudflare.com",
"format": "number",
},
{
"key": "redis_commands_month",
"label": "Redis Commands/Month",
"limit": 500_000,
"upgrade_trigger": "Upstash Pro ($10/mo)",
"upgrade_url": "https://console.upstash.com",
"format": "number",
},
{
"key": "hf_spaces_status",
"label": "HF Spaces",
"limit": None,
"upgrade_trigger": "HF CPU Upgrade ($22/mo)",
"upgrade_url": "https://huggingface.co/spaces",
"format": "status",
},
{
"key": "total_users",
"label": "Registered Users",
"limit": None,
"upgrade_trigger": None,
"upgrade_url": None,
"format": "number",
},
{
"key": "daily_active_users",
"label": "Daily Active Users",
"limit": None,
"upgrade_trigger": None,
"upgrade_url": None,
"format": "number",
},
{
"key": "tasks_created_day",
"label": "Tasks Created/Day",
"limit": None,
"upgrade_trigger": None,
"upgrade_url": None,
"format": "number",
},
]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def compute_status(value: float, limit: float | None) -> str:
if limit is None or limit == 0:
return "green"
pct = (value / limit) * 100
if pct >= 90:
return "red"
if pct >= 70:
return "yellow"
return "green"
def compute_projection(points: list[dict], limit: float | None) -> dict:
"""Linear regression on points to estimate days until limit."""
if limit is None or len(points) < 2:
return {"days_until_limit": None, "estimated_date": None}
n = len(points)
x_vals = list(range(n))
y_vals = [p["value"] for p in points]
x_mean = sum(x_vals) / n
y_mean = sum(y_vals) / n
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_vals, y_vals))
denominator = sum((x - x_mean) ** 2 for x in x_vals)
if denominator == 0:
return {"days_until_limit": None, "estimated_date": None}
slope = numerator / denominator
if slope <= 0:
return {"days_until_limit": None, "estimated_date": None}
current = y_vals[-1]
remaining = limit - current
if remaining <= 0:
return {"days_until_limit": 0, "estimated_date": None}
days = int(remaining / slope)
est_date = datetime.now(timezone.utc) + timedelta(days=days)
return {
"days_until_limit": days,
"estimated_date": est_date.strftime("%Y-%m-%d"),
}
def format_bytes(b: float) -> str:
if b >= 1_073_741_824:
return f"{b / 1_073_741_824:.1f} GB"
if b >= 1_048_576:
return f"{int(b / 1_048_576)} MB"
if b >= 1024:
return f"{b / 1024:.1f} KB"
return f"{int(b)} B"
def format_number(n: float) -> str:
if n >= 1_000_000:
return f"{n / 1_000_000:.1f}M"
if n >= 1_000:
return f"{int(n / 1_000)}K"
return str(int(n))
def _display_value(value: float, fmt: str) -> str:
if fmt == "bytes":
return format_bytes(value)
return format_number(value)
# ---------------------------------------------------------------------------
# Service
# ---------------------------------------------------------------------------
class InfrastructureMonitorService:
def __init__(self, db: AsyncSession):
self.db = db
# -- Collectors --
async def _collect_db_storage(self) -> tuple[float, dict | None]:
result = await self.db.execute(text("SELECT pg_database_size(current_database())"))
size = float(result.scalar_one())
return size, None
async def _collect_db_connections(self) -> tuple[float, dict | None]:
result = await self.db.execute(text("SELECT count(*) FROM pg_stat_activity"))
count = float(result.scalar_one())
return count, None
async def _collect_db_table_rows(self) -> tuple[float, dict | None]:
result = await self.db.execute(text(
"SELECT relname, n_live_tup FROM pg_stat_user_tables "
"ORDER BY n_live_tup DESC LIMIT 10"
))
rows = [{"table": r[0], "rows": int(r[1])} for r in result.fetchall()]
total = sum(r["rows"] for r in rows)
return float(total), {"tables": rows}
async def _collect_cf_requests(self) -> tuple[float, dict | None] | None:
account_id = os.environ.get("CF_ACCOUNT_ID")
api_token = os.environ.get("CF_ANALYTICS_API_TOKEN")
if not account_id or not api_token:
logger.info("CF analytics env vars not set — skipping cf_requests_day")
return None
try:
async with httpx.AsyncClient(timeout=15) as client:
resp = await client.get(
f"https://api.cloudflare.com/client/v4/accounts/{account_id}/analytics/dashboard",
params={"since": "-1440", "continuous": "true"},
headers={"Authorization": f"Bearer {api_token}"},
)
data = resp.json()
if data.get("success"):
totals = data.get("result", {}).get("totals", {})
requests = totals.get("requests", {}).get("all", 0)
return float(requests), None
except Exception:
logger.exception("Failed to collect CF analytics")
return None
async def _collect_redis_commands(self) -> tuple[float, dict | None] | None:
redis_url = os.environ.get("REDIS_URL")
if not redis_url:
logger.info("REDIS_URL not set — skipping redis_commands_month")
return None
try:
import redis as redis_lib
r = redis_lib.from_url(redis_url, decode_responses=True)
info = r.info("stats")
total = float(info.get("total_commands_processed", 0))
now = datetime.now(timezone.utc)
first_of_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
result = await self.db.execute(
select(InfrastructureMetric.metric_value)
.where(
InfrastructureMetric.metric_name == "redis_commands_month",
InfrastructureMetric.collected_at >= first_of_month,
)
.order_by(InfrastructureMetric.collected_at.asc())
.limit(1)
)
baseline = result.scalar_one_or_none()
if baseline is not None:
monthly = total - baseline
else:
monthly = total
r.close()
return monthly, {"total_commands": total}
except Exception:
logger.exception("Failed to collect Redis stats")
return None
async def _collect_hf_spaces(self) -> tuple[float, dict | None]:
spaces = [
"arimatch1/crewhub",
"arimatch1/crewhub-staging",
]
statuses = []
running = 0
async with httpx.AsyncClient(timeout=15) as client:
for space in spaces:
try:
resp = await client.get(
f"https://huggingface.co/api/spaces/{space}",
headers={"Authorization": f"Bearer {os.environ.get('HF_TOKEN', '')}"},
)
data = resp.json()
stage = data.get("runtime", {}).get("stage", "unknown")
statuses.append({"space": space, "status": stage})
if stage == "RUNNING":
running += 1
except Exception:
statuses.append({"space": space, "status": "error"})
return float(running), {"spaces": statuses, "total": len(spaces)}
async def _collect_total_users(self) -> tuple[float, dict | None]:
result = await self.db.execute(select(func.count()).select_from(User))
return float(result.scalar_one()), None
async def _collect_dau(self) -> tuple[float, dict | None]:
cutoff = datetime.now(timezone.utc) - timedelta(hours=24)
result = await self.db.execute(
select(func.count(func.distinct(Task.creator_user_id)))
.where(Task.created_at >= cutoff)
)
return float(result.scalar_one()), None
async def _collect_tasks_day(self) -> tuple[float, dict | None]:
cutoff = datetime.now(timezone.utc) - timedelta(hours=24)
result = await self.db.execute(
select(func.count()).select_from(Task).where(Task.created_at >= cutoff)
)
return float(result.scalar_one()), None
# -- Main collect --
async def collect_all(self) -> list[dict]:
collectors = {
"db_storage_bytes": self._collect_db_storage,
"db_connections": self._collect_db_connections,
"db_table_rows": self._collect_db_table_rows,
"cf_requests_day": self._collect_cf_requests,
"redis_commands_month": self._collect_redis_commands,
"hf_spaces_status": self._collect_hf_spaces,
"total_users": self._collect_total_users,
"daily_active_users": self._collect_dau,
"tasks_created_day": self._collect_tasks_day,
}
now = datetime.now(timezone.utc)
results = []
defn_map = {d["key"]: d for d in METRIC_DEFINITIONS}
for key, collector in collectors.items():
try:
result = await collector()
if result is None:
continue
value, metadata = result
defn = defn_map[key]
limit = defn["limit"]
metric = InfrastructureMetric(
collected_at=now,
metric_name=key,
metric_value=value,
metric_limit=limit,
metadata_json=metadata,
)
self.db.add(metric)
results.append({
"name": key,
"label": defn["label"],
"value": value,
"limit": limit,
"status": compute_status(value, limit),
"display_value": _display_value(value, defn["format"]),
"metadata": metadata,
})
except Exception:
logger.exception("Failed to collect metric %s", key)
await self.db.commit()
return results
# -- Query --
async def get_current(self) -> dict:
subq = (
select(
InfrastructureMetric.metric_name,
func.max(InfrastructureMetric.collected_at).label("max_at"),
)
.group_by(InfrastructureMetric.metric_name)
.subquery()
)
result = await self.db.execute(
select(InfrastructureMetric)
.join(
subq,
(InfrastructureMetric.metric_name == subq.c.metric_name)
& (InfrastructureMetric.collected_at == subq.c.max_at),
)
)
rows = result.scalars().all()
defn_map = {d["key"]: d for d in METRIC_DEFINITIONS}
metrics = []
collected_at = None
for row in rows:
defn = defn_map.get(row.metric_name)
if not defn:
continue
if collected_at is None or row.collected_at > collected_at:
collected_at = row.collected_at
pct = (row.metric_value / row.metric_limit * 100) if row.metric_limit else None
metrics.append({
"name": row.metric_name,
"label": defn["label"],
"value": row.metric_value,
"limit": row.metric_limit,
"percent": round(pct, 1) if pct is not None else None,
"status": compute_status(row.metric_value, row.metric_limit),
"display_value": _display_value(row.metric_value, defn["format"]),
"display_limit": _display_value(row.metric_limit, defn["format"]) if row.metric_limit else None,
"upgrade_trigger": defn["upgrade_trigger"],
"upgrade_url": defn["upgrade_url"],
"metadata": row.metadata_json,
})
return {"collected_at": collected_at, "metrics": metrics}
async def get_history(self, metric_name: str, days: int = 30) -> dict:
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
result = await self.db.execute(
select(InfrastructureMetric)
.where(
InfrastructureMetric.metric_name == metric_name,
InfrastructureMetric.collected_at >= cutoff,
)
.order_by(InfrastructureMetric.collected_at.asc())
)
rows = result.scalars().all()
defn_map = {d["key"]: d for d in METRIC_DEFINITIONS}
defn = defn_map.get(metric_name)
limit = defn["limit"] if defn else None
points = [
{"date": r.collected_at.strftime("%Y-%m-%d"), "value": r.metric_value}
for r in rows
]
projection = compute_projection(points, limit)
return {
"metric": metric_name,
"limit": limit,
"points": points,
"projection": projection,
}
# -- Discord report --
async def send_daily_report(self, results: list[dict]) -> None:
webhook_url = os.environ.get("DISCORD_HEALTHCHECK_WEBHOOK")
if not webhook_url:
logger.info("DISCORD_HEALTHCHECK_WEBHOOK not set — skipping report")
return
today = datetime.now(timezone.utc).strftime("%b %d, %Y")
status_emoji = {"green": "\u2705", "yellow": "\u26a0\ufe0f", "red": "\ud83d\udea8"}
lines = [f"**CrewHub Infrastructure \u2014 Daily Report ({today})**\n"]
threshold_alerts = []
for m in results:
emoji = status_emoji.get(m["status"], "\u2754")
limit_str = ""
if m["limit"]:
pct = m["value"] / m["limit"] * 100
limit_str = f" / {_display_value(m['limit'], 'number')} ({pct:.0f}%)"
lines.append(f"{emoji} **{m['label']}** {m['display_value']}{limit_str}")
if m["status"] in ("yellow", "red") and m.get("limit"):
threshold_alerts.append(m)
user_m = next((m for m in results if m["name"] == "total_users"), None)
dau_m = next((m for m in results if m["name"] == "daily_active_users"), None)
tasks_m = next((m for m in results if m["name"] == "tasks_created_day"), None)
lines.append("\n**Growth**")
if user_m:
lines.append(f" Users: {int(user_m['value'])}")
if dau_m:
lines.append(f" DAU: {int(dau_m['value'])}")
if tasks_m:
lines.append(f" Tasks today: {int(tasks_m['value'])}")
if threshold_alerts:
worst = max(threshold_alerts, key=lambda m: m["value"] / m["limit"])
defn_map = {d["key"]: d for d in METRIC_DEFINITIONS}
defn = defn_map.get(worst["name"], {})
trigger = defn.get("upgrade_trigger", "")
lines.append(f"\n\ud83d\udca1 **Next upgrade:** {trigger}")
body = "\n".join(lines)
try:
async with httpx.AsyncClient(timeout=10) as client:
await client.post(webhook_url, json={"content": body})
except Exception:
logger.exception("Failed to send Discord daily report")
async def send_threshold_alert(self, metric: dict) -> None:
webhook_url = os.environ.get("DISCORD_HEALTHCHECK_WEBHOOK")
if not webhook_url:
return
defn_map = {d["key"]: d for d in METRIC_DEFINITIONS}
defn = defn_map.get(metric["name"], {})
trigger = defn.get("upgrade_trigger", "Unknown")
pct = metric["value"] / metric["limit"] * 100 if metric["limit"] else 0
level = "CRITICAL" if pct >= 90 else "WARNING"
emoji = "\ud83d\udea8" if level == "CRITICAL" else "\u26a0\ufe0f"
body = (
f"{emoji} **{level}: {metric['label']} at {pct:.0f}%** "
f"({metric['display_value']} / {_display_value(metric['limit'], 'number')})\n"
f"**Action:** Upgrade to {trigger}\n"
f"**Dashboard:** https://crewhubai.com/admin/infrastructure"
)
try:
async with httpx.AsyncClient(timeout=10) as client:
await client.post(webhook_url, json={"content": body})
except Exception:
logger.exception("Failed to send threshold alert")
async def check_threshold_crossings(self, results: list[dict]) -> None:
for m in results:
if not m.get("limit"):
continue
current_status = m["status"]
if current_status == "green":
continue
prev = await self.db.execute(
select(InfrastructureMetric)
.where(
InfrastructureMetric.metric_name == m["name"],
InfrastructureMetric.collected_at < datetime.now(timezone.utc) - timedelta(hours=12),
)
.order_by(InfrastructureMetric.collected_at.desc())
.limit(1)
)
prev_row = prev.scalar_one_or_none()
if prev_row:
prev_status = compute_status(prev_row.metric_value, prev_row.metric_limit)
if current_status != prev_status and (
(prev_status == "green" and current_status in ("yellow", "red"))
or (prev_status == "yellow" and current_status == "red")
):
await self.send_threshold_alert(m)
else:
await self.send_threshold_alert(m)
|