Spaces:
Runtime error
Runtime error
Download scripts/deploy.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 7.92 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/scripts/deploy.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/scripts/deploy.py
-
curl -L -o deploy.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/scripts/deploy.py
7.92 kB
| """End-to-end deploy orchestrator for AI Tester Platform. | |
| Wraps the per-step scripts so a single command can: | |
| 1. Generate missing secrets in .env.production.local | |
| 2. Apply Supabase SQL schema | |
| 3. Push env vars to Render | |
| 4. Verify the live deployment via /health | |
| By default, every step is **opt-in via flag** to prevent accidental | |
| production changes — pass ``--all`` to run the full chain in dry-run mode | |
| first, then ``--all --execute`` to commit. | |
| Designed to be safe to invoke repeatedly: every underlying script is | |
| idempotent. | |
| Usage:: | |
| # Dry-run everything (no DB writes, no Render API calls): | |
| python scripts/deploy.py --all | |
| # Execute the full chain after dry-run looks clean: | |
| python scripts/deploy.py --all --execute | |
| # Run individual steps: | |
| python scripts/deploy.py --secrets --execute | |
| python scripts/deploy.py --schema --execute | |
| python scripts/deploy.py --env --execute | |
| python scripts/deploy.py --smoke | |
| Environment variables consumed: | |
| APP_SECRETS_MASTER_KEY (when applying schema needing the app) | |
| SUPABASE_DB_URL postgres URL for --schema | |
| DATABASE_URL fallback for --schema if SUPABASE_DB_URL unset | |
| RENDER_API_KEY for --env | |
| RENDER_SERVICE_ID for --env | |
| RENDER_PUBLIC_URL for --smoke (default https://your-app.onrender.com) | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import shlex | |
| import subprocess | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from pathlib import Path | |
| from typing import List | |
| ROOT = Path(__file__).resolve().parent.parent | |
| def _load_env_file() -> Path | None: | |
| """Auto-load `.env.production.local` (or `.env.production`) if present. | |
| We use python-dotenv when available; fall back to a hand-rolled parser | |
| so the script works even if dependencies aren't installed locally yet. | |
| Subprocesses inherit the environment, so loading once here is enough. | |
| """ | |
| for candidate in (".env.production.local", ".env.production"): | |
| path = ROOT / candidate | |
| if not path.exists(): | |
| continue | |
| try: | |
| from dotenv import load_dotenv # type: ignore[import-not-found] | |
| load_dotenv(path, override=False) | |
| except ImportError: | |
| for line in path.read_text(encoding="utf-8").splitlines(): | |
| stripped = line.strip() | |
| if not stripped or stripped.startswith("#") or "=" not in stripped: | |
| continue | |
| key, _, value = stripped.partition("=") | |
| key = key.strip() | |
| value = value.strip().strip("'\"") | |
| os.environ.setdefault(key, value) | |
| return path | |
| return None | |
| _LOADED_ENV = _load_env_file() | |
| def _run(cmd: List[str], dry_run: bool) -> int: | |
| pretty = " ".join(shlex.quote(p) for p in cmd) | |
| if dry_run: | |
| print(f" [dry] {pretty}") | |
| return 0 | |
| print(f" $ {pretty}", flush=True) | |
| return subprocess.call(cmd, cwd=ROOT) | |
| def step_secrets(args: argparse.Namespace) -> int: | |
| print("\n[1/4] generate_secrets") | |
| cmd = [sys.executable, "scripts/generate_secrets.py"] | |
| if args.include_admin_password: | |
| cmd.append("--include-superadmin-password") | |
| return _run(cmd, dry_run=not args.execute) | |
| def step_schema(args: argparse.Namespace) -> int: | |
| print("\n[2/4] apply_supabase_schema") | |
| cmd = [sys.executable, "scripts/apply_supabase_schema.py"] | |
| if not args.execute: | |
| cmd.append("--dry-run") | |
| return _run(cmd, dry_run=False) # the script handles its own dry-run flag | |
| def step_env(args: argparse.Namespace) -> int: | |
| print("\n[3/4] push_env_to_render") | |
| cmd = [sys.executable, "scripts/push_env_to_render.py"] | |
| if not args.execute: | |
| cmd.append("--dry-run") | |
| if args.env_include: | |
| cmd.extend(["--include", args.env_include]) | |
| return _run(cmd, dry_run=False) | |
| def step_smoke(args: argparse.Namespace) -> int: | |
| """Hit /health on the live deployment until it returns 200, with timeout.""" | |
| print("\n[4/4] smoke_health_check") | |
| base = ( | |
| args.public_url | |
| or os.getenv("RENDER_PUBLIC_URL", "").strip() | |
| or "https://your-app.onrender.com" | |
| ) | |
| if base.endswith("/"): | |
| base = base[:-1] | |
| url = f"{base}/health" | |
| print(f" GET {url}") | |
| if not args.execute: | |
| print(" [dry] would poll until 200 OK") | |
| return 0 | |
| deadline = time.time() + max(10, args.smoke_timeout) | |
| last_err = "" | |
| while time.time() < deadline: | |
| try: | |
| req = urllib.request.Request( | |
| url, headers={"User-Agent": "ai-tester-platform/deploy-smoke"} | |
| ) | |
| with urllib.request.urlopen(req, timeout=10) as response: | |
| status = int(getattr(response, "status", 200) or 200) | |
| body = response.read().decode("utf-8", errors="ignore")[:300] | |
| if status == 200: | |
| print(f" ✓ {status} {body}") | |
| return 0 | |
| last_err = f"HTTP {status}: {body}" | |
| except urllib.error.HTTPError as exc: | |
| last_err = f"HTTPError {exc.code}: {exc.reason}" | |
| except Exception as exc: | |
| last_err = str(exc) | |
| print(f" …waiting (last: {last_err[:120]})", flush=True) | |
| time.sleep(5) | |
| print(f" ✗ smoke check timed out after {args.smoke_timeout}s — last: {last_err}") | |
| return 1 | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--all", action="store_true", help="Run all steps") | |
| parser.add_argument("--secrets", action="store_true") | |
| parser.add_argument("--schema", action="store_true") | |
| parser.add_argument("--env", action="store_true") | |
| parser.add_argument("--smoke", action="store_true") | |
| parser.add_argument( | |
| "--execute", | |
| action="store_true", | |
| help="Actually run the steps (without this flag, every step is dry-run)", | |
| ) | |
| parser.add_argument( | |
| "--include-admin-password", | |
| action="store_true", | |
| help="Pass --include-superadmin-password to the secrets generator", | |
| ) | |
| parser.add_argument( | |
| "--env-include", | |
| default="", | |
| help="Comma-separated allowlist forwarded to push_env_to_render", | |
| ) | |
| parser.add_argument( | |
| "--public-url", | |
| default="", | |
| help="Override base URL for the smoke check (e.g. https://your-app.onrender.com)", | |
| ) | |
| parser.add_argument("--smoke-timeout", type=int, default=300) | |
| args = parser.parse_args() | |
| if not any([args.all, args.secrets, args.schema, args.env, args.smoke]): | |
| parser.print_help() | |
| return 0 | |
| steps = [] | |
| if args.all or args.secrets: | |
| steps.append(("secrets", step_secrets)) | |
| if args.all or args.schema: | |
| steps.append(("schema", step_schema)) | |
| if args.all or args.env: | |
| steps.append(("env", step_env)) | |
| if args.all or args.smoke: | |
| steps.append(("smoke", step_smoke)) | |
| print("=" * 60) | |
| print(f"deploy.py: mode = {'EXECUTE' if args.execute else 'dry-run'}") | |
| print(f"steps: {', '.join(name for name, _ in steps)}") | |
| if _LOADED_ENV: | |
| print(f"loaded env: {_LOADED_ENV.relative_to(ROOT)}") | |
| print("=" * 60) | |
| failed: List[str] = [] | |
| for name, fn in steps: | |
| rc = fn(args) | |
| if rc != 0: | |
| failed.append(name) | |
| if not args.execute: | |
| # Dry-run failures are usually missing creds; keep going so | |
| # the user sees every step. | |
| continue | |
| # In execute mode, stop at first failure to avoid cascading damage. | |
| break | |
| print("\n" + "=" * 60) | |
| if failed: | |
| print(f"deploy.py: FAILED steps: {', '.join(failed)}") | |
| return 1 | |
| print("deploy.py: OK ✓") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |