Download src/services/infrastructure_monitor.py from arimatch1/crewhub: direct link, hf CLI and curl.
- Browser
- Download file 19.7 kB
-
https://huggingface.co/spaces/arimatch1/crewhub/resolve/main/src/services/infrastructure_monitor.py
- Command line
-
hf download hf://spaces/arimatch1/crewhub/src/services/infrastructure_monitor.py
-
curl -L -o infrastructure_monitor.py https://huggingface.co/spaces/arimatch1/crewhub/resolve/main/src/services/infrastructure_monitor.py
19.7 kB
| # 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) | |