briga-core-api / scripts /monitoring /integration_health_check.py
yabeskn's picture
fix: change EXPOSE and uvicorn port from 8080 to 7860 in Dockerfile
b613c13
Raw History Blame Contribute Delete
4.85 kB
import os
import time
import requests
import asyncio
import httpx
from loguru import logger
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine
# --- Configuration ---
API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:8000")
DATABASE_URL = os.getenv("DATABASE_URL")
AI_ENDPOINT = f"{API_BASE_URL}/api/v1/agents/execute" # New Antigravity Endpoint
# --- Monitoring Targets ---
CHECKS = {
"backend_api": True,
"database_connectivity": True,
"ai_gateway_latency": True,
"audit_ledger_integrity": True,
"token_quota_status": True
}
async def check_backend():
"""Check if the FastAPI backend is responding."""
try:
async with httpx.AsyncClient() as client:
start_time = time.time()
response = await client.get(f"{API_BASE_URL}/health")
latency = (time.time() - start_time) * 1000
if response.status_code == 200:
logger.success(f"[BACKEND] Status: OK | Latency: {latency:.2f}ms")
return True
else:
logger.error(f"[BACKEND] Status: {response.status_code}")
except Exception as e:
logger.critical(f"[BACKEND] Connection Failed: {e}")
return False
async def check_database():
"""Check Supabase connectivity and query latency."""
if not DATABASE_URL:
logger.warning("[DATABASE] Skip: DATABASE_URL not set")
return False
try:
engine = create_async_engine(DATABASE_URL)
start_time = time.time()
async with engine.connect() as conn:
await conn.execute(text("SELECT 1"))
latency = (time.time() - start_time) * 1000
logger.success(f"[DATABASE] Status: Connected | Query Latency: {latency:.2f}ms")
await engine.dispose()
return True
except Exception as e:
logger.error(f"[DATABASE] Connectivity Error: {e}")
return False
async def check_audit_integrity():
"""Verify if the cryptographic hash chain is intact."""
if not DATABASE_URL: return False
integrity_query = """
WITH verified_trail AS (
SELECT
id, current_hash, previous_hash,
LAG(current_hash, 1, '0000000000000000000000000000000000000000000000000000000000000000')
OVER (ORDER BY id ASC) AS expected_prev_hash
FROM audit.audit_trail
)
SELECT COUNT(*) FROM verified_trail WHERE previous_hash != expected_prev_hash;
"""
try:
engine = create_async_engine(DATABASE_URL)
async with engine.connect() as conn:
result = await conn.execute(text(integrity_query))
failed_count = result.scalar()
if failed_count == 0:
logger.success("[AUDIT] Integrity Status: VERIFIED (0 breaks)")
else:
logger.warning(f"[AUDIT] Integrity Compromised: {failed_count} hash breaks detected!")
await engine.dispose()
return True
except Exception as e:
logger.debug(f"[AUDIT] Skip: Schema not yet deployed or {e}")
return False
async def check_stats():
"""Fetch high-level platform stats for the dashboard."""
if not DATABASE_URL: return False
stats_query = """
SELECT
(SELECT COUNT(*) FROM talents) as total_talents,
(SELECT COUNT(*) FROM job_postings WHERE status = 'posted') as active_jobs,
(SELECT COUNT(*) FROM agent_queues WHERE status = 'QUEUED') as queued_tasks
"""
try:
engine = create_async_engine(DATABASE_URL)
async with engine.connect() as conn:
result = await conn.execute(text(stats_query))
row = result.fetchone()
if row:
logger.info(f"[STATS] Talents: {row[0]} | Active Jobs: {row[1]} | Queue: {row[2]}")
await engine.dispose()
return True
except Exception as e:
logger.debug(f"[STATS] Unavailable: {e}")
return False
async def run_suite():
"""Run all health checks in a loop with a Dashboard Summary."""
print("\n" + "="*60)
print(" BRIGAWAN.ID — FOUNDER'S INTEGRATION DASHBOARD")
print("="*60)
while True:
print(f"\n[Cycle: {time.strftime('%H:%M:%S')}]")
tasks = []
if CHECKS["backend_api"]: tasks.append(check_backend())
if CHECKS["database_connectivity"]: tasks.append(check_database())
if CHECKS["audit_ledger_integrity"]: tasks.append(check_audit_integrity())
tasks.append(check_stats())
await asyncio.gather(*tasks)
print("-" * 30)
print("SYSTEM STATUS: 🟢 ALL CLEAR (15 RPM Safe)")
print("-" * 30)
await asyncio.sleep(15)
if __name__ == "__main__":
try:
asyncio.run(run_suite())
except KeyboardInterrupt:
logger.info("Monitoring terminated by user.")