Spaces:
Runtime error

ai-tester-platform / scripts /preflight.py
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
8.27 kB
"""Pre-deploy preflight checks.
Validates that the environment is ready for a production launch on Render
(or any other host). Runs a series of independent checks and prints a
concise pass/fail summary. Non-zero exit code on any failure so it can be
wired into a CI/CD pipeline or invoked manually before flipping traffic.
Usage::
python -m scripts.preflight # all checks
python -m scripts.preflight --skip aiprov # skip individual check ids
Each check returns one of:
"ok" β€” passed
"warn" β€” non-blocking issue (counts toward exit 0 if --strict not set)
"fail" β€” blocking issue (always non-zero exit)
"skip" β€” explicitly skipped or N/A in this environment
Designed to be safe to run in production: read-only operations only, no DB
writes, no API key rotations.
"""
from __future__ import annotations
import argparse
import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, List, Optional
# Allow `python scripts/preflight.py` (no -m) by ensuring the project root
# is on sys.path before any `from src...` import.
_ROOT = Path(__file__).resolve().parent.parent
if str(_ROOT) not in sys.path:
sys.path.insert(0, str(_ROOT))
@dataclass
class CheckResult:
name: str
status: str # ok | warn | fail | skip
detail: str = ""
def _required_env(*names: str) -> Optional[str]:
"""Return the first missing env var name, or None if all are set."""
for name in names:
if not os.getenv(name, "").strip():
return name
return None
def check_runtime_env() -> CheckResult:
"""Critical env vars required for production startup."""
is_prod = os.getenv("ENV", "").strip().lower() in {"production", "prod"}
if not is_prod:
return CheckResult("env.production", "skip", "ENV is not 'production'")
missing = []
for var in ("DATABASE_URL", "APP_SECRETS_MASTER_KEY"):
if not os.getenv(var, "").strip():
missing.append(var)
if os.getenv("ENFORCE_AUTH", "").strip().lower() in {"1", "true", "yes", "on"}:
for var in ("SUPABASE_URL", "SUPABASE_ANON_KEY"):
if not os.getenv(var, "").strip():
missing.append(var)
if missing:
return CheckResult("env.production", "fail", f"missing: {', '.join(missing)}")
return CheckResult("env.production", "ok")
def check_database() -> CheckResult:
"""Open a session and run SELECT 1."""
try:
from sqlalchemy import text
from src.db import get_db
except Exception as exc:
return CheckResult("db.import", "fail", f"cannot import db layer: {exc}")
try:
db = get_db()
with db.get_session() as session:
session.execute(text("SELECT 1"))
return CheckResult("db.select1", "ok", str(db.engine.url).split("@")[-1])
except Exception as exc:
return CheckResult("db.select1", "fail", str(exc)[:200])
def check_secrets_crypto() -> CheckResult:
"""Round-trip encrypt/decrypt to confirm APP_SECRETS_MASTER_KEY works."""
if not os.getenv("APP_SECRETS_MASTER_KEY", "").strip():
return CheckResult("secrets.crypto", "skip", "APP_SECRETS_MASTER_KEY not set")
try:
from src.security.secrets import decrypt_secret, encrypt_secret
encrypted = encrypt_secret("preflight-canary")
decrypted = decrypt_secret(encrypted)
if decrypted != "preflight-canary":
return CheckResult("secrets.crypto", "fail", "round-trip mismatch")
return CheckResult("secrets.crypto", "ok")
except Exception as exc:
return CheckResult("secrets.crypto", "fail", str(exc)[:200])
def check_ai_provider() -> CheckResult:
"""Confirm at least one AI provider key is set."""
provider = os.getenv("AI_PROVIDER", "openai").strip().lower()
key_var = {
"openai": "OPENAI_API_KEY",
"groq": "GROQ_API_KEY",
"kimi": "KIMI_API_KEY",
"openrouter": "OPENROUTER_API_KEY",
}.get(provider)
if not key_var:
return CheckResult("ai.provider", "warn", f"unknown provider '{provider}'")
if not os.getenv(key_var, "").strip():
return CheckResult("ai.provider", "fail", f"{key_var} not set")
return CheckResult("ai.provider", "ok", f"provider={provider}")
def check_playwright() -> CheckResult:
"""Verify Playwright browsers are installed (server-side test runs)."""
try:
from playwright.sync_api import sync_playwright
except Exception as exc:
return CheckResult("playwright.import", "fail", str(exc)[:200])
try:
with sync_playwright() as p:
# Launch + close quickly. If the browser binary is missing,
# Playwright raises a clear error here.
browser = p.chromium.launch(headless=True)
browser.close()
return CheckResult("playwright.chromium", "ok")
except Exception as exc:
return CheckResult(
"playwright.chromium",
"fail",
f"{str(exc)[:160]} (run: python -m playwright install --with-deps chromium)",
)
def check_supabase() -> CheckResult:
"""Soft check on Supabase connectivity. Skipped if not configured."""
url = os.getenv("SUPABASE_URL", "").strip()
key = os.getenv("SUPABASE_ANON_KEY", "").strip()
if not url or not key:
return CheckResult("supabase.connect", "skip", "SUPABASE_* not configured")
try:
from src.api.supabase_init import check_supabase_connection
return (
CheckResult("supabase.connect", "ok")
if check_supabase_connection()
else CheckResult("supabase.connect", "warn", "client could not connect")
)
except Exception as exc:
return CheckResult("supabase.connect", "warn", str(exc)[:200])
def check_cors_in_prod() -> CheckResult:
is_prod = os.getenv("ENV", "").strip().lower() in {"production", "prod"}
if not is_prod:
return CheckResult("cors.allowlist", "skip", "ENV not production")
raw = os.getenv("ALLOWED_ORIGINS", "").strip()
if not raw and not os.getenv("ALLOWED_ORIGIN_REGEX", "").strip():
return CheckResult(
"cors.allowlist",
"warn",
"no ALLOWED_ORIGINS set; CORS will refuse cross-origin requests",
)
return CheckResult("cors.allowlist", "ok", raw)
CHECKS: List[tuple[str, Callable[[], CheckResult]]] = [
("env", check_runtime_env),
("db", check_database),
("secrets", check_secrets_crypto),
("aiprov", check_ai_provider),
("playwright", check_playwright),
("supabase", check_supabase),
("cors", check_cors_in_prod),
]
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"--skip",
default="",
help="Comma-separated check ids to skip (env,db,secrets,aiprov,playwright,supabase,cors)",
)
parser.add_argument(
"--strict",
action="store_true",
help="Exit non-zero on warnings, not just failures.",
)
args = parser.parse_args()
skipped_ids = {s.strip() for s in args.skip.split(",") if s.strip()}
results: List[CheckResult] = []
for cid, fn in CHECKS:
if cid in skipped_ids:
results.append(CheckResult(cid, "skip", "--skip"))
continue
try:
results.append(fn())
except Exception as exc: # pragma: no cover β€” defensive
results.append(CheckResult(cid, "fail", f"check crashed: {exc}"))
width = max(len(r.name) for r in results)
glyphs = {"ok": "βœ“", "warn": "!", "fail": "βœ—", "skip": "Β·"}
print()
for r in results:
glyph = glyphs.get(r.status, "?")
print(f" {glyph} {r.name:<{width}} [{r.status:>4}] {r.detail}")
print()
has_fail = any(r.status == "fail" for r in results)
has_warn = any(r.status == "warn" for r in results)
if has_fail:
print("preflight: FAILED β€” fix the items above before deploying.")
return 1
if args.strict and has_warn:
print("preflight: warnings present (--strict).")
return 2
print("preflight: OK")
return 0
if __name__ == "__main__":
sys.exit(main())