Files
planet/scripts/harness/backend-rules-check.sh
T

130 lines
5.0 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$ROOT_DIR/scripts/harness/lib.sh"
main() {
cd "$ROOT_DIR"
local uv_bin
uv_bin="$(harness_require_tool uv)"
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python - <<'PY'
import ast
import importlib
import inspect
import os
import pkgutil
import sys
from pathlib import Path
root = Path.cwd()
failures: list[str] = []
def fail(message: str) -> None:
failures.append(message)
class BackendDebugCallVisitor(ast.NodeVisitor):
def __init__(self, path: Path) -> None:
self.path = path
def visit_Call(self, node: ast.Call) -> None:
if isinstance(node.func, ast.Name) and node.func.id in {"print", "breakpoint"}:
fail(f"{self.path}:{node.lineno}: backend app code must use structured logging, not {node.func.id}()")
if (
isinstance(node.func, ast.Attribute)
and node.func.attr == "set_trace"
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "pdb"
):
fail(f"{self.path}:{node.lineno}: remove pdb.set_trace() from backend app code")
self.generic_visit(node)
for path in sorted((root / "backend/app").rglob("*.py")):
rel = path.relative_to(root)
try:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(rel))
except SyntaxError as exc:
fail(f"{rel}:{exc.lineno}: Python syntax error: {exc.msg}")
continue
BackendDebugCallVisitor(rel).visit(tree)
if not failures:
# Verify ASGI app and every collector can be imported and instantiated offline.
os.environ["DATABASE_URL"] = "postgresql+asyncpg://check:check@127.0.0.1:1/check"
os.environ["REDIS_URL"] = "redis://127.0.0.1:1/0"
backend_dir = str(root / "backend")
if backend_dir not in sys.path:
sys.path.insert(0, backend_dir)
try:
import app.main # noqa: F401
import app.services.collectors as collectors_pkg
from app.services.collectors import (
BaseCollector,
HTTPCollector,
IntervalCollector,
collector_registry,
)
from app.services.collectors.compute_base import ComputeCollector
except Exception as exc:
fail(f"backend/app/main.py: failed offline ASGI import: {type(exc).__name__}: {exc}")
else:
abstract_bases = (BaseCollector, HTTPCollector, IntervalCollector, ComputeCollector)
for mod in pkgutil.iter_modules(collectors_pkg.__path__, collectors_pkg.__name__ + "."):
try:
module = importlib.import_module(mod.name)
except Exception as exc:
fail(f"{mod.name}: failed to import collector module: {type(exc).__name__}: {exc}")
continue
for attr_name, obj in inspect.getmembers(module, inspect.isclass):
if obj.__module__ != mod.name or not issubclass(obj, BaseCollector):
continue
if obj in abstract_bases or attr_name.startswith("_"):
continue
if inspect.isabstract(obj):
fail(
f"{mod.name}.{attr_name}: abstract methods unimplemented: "
f"{sorted(obj.__abstractmethods__)}"
)
continue
try:
inst = obj()
except Exception as exc:
fail(f"{mod.name}.{attr_name}: zero-arg init failed: {type(exc).__name__}: {exc}")
continue
if not str(getattr(inst, "name", "") or "").strip():
fail(f"{mod.name}.{attr_name}: collector name must be non-empty")
if not callable(getattr(inst, "fetch", None)):
fail(f"{mod.name}.{attr_name}: collector missing callable fetch()")
run_fn = getattr(inst, "run", None)
if not callable(run_fn) or "db" not in inspect.signature(run_fn).parameters:
fail(f"{mod.name}.{attr_name}: collector run() must accept 'db'")
for key, col in sorted(collector_registry.all().items()):
if not isinstance(col, BaseCollector):
fail(f"collector_registry[{key!r}]: not a BaseCollector instance")
continue
if col.name != key:
fail(f"collector_registry[{key!r}]: registered key != collector.name ({col.name!r})")
if not callable(getattr(col, "fetch", None)):
fail(f"collector_registry[{key!r}]: missing callable fetch()")
run_fn = getattr(col, "run", None)
if not callable(run_fn) or "db" not in inspect.signature(run_fn).parameters:
fail(f"collector_registry[{key!r}]: run() must accept 'db'")
if failures:
for message in failures:
print(f"fail: {message}")
raise SystemExit(f"backend rules check failed: {len(failures)} failure(s)")
print("backend rules check passed")
PY
}
main "$@"