Files
Heimdall/scripts/ci/check-efcore-usage.py
T
arnaud.dartois 119ea0f568
Heimdall Gitea / Detect CI scope (pull_request) Successful in 7s
Heimdall Gitea / Build and tests (pull_request) Failing after 14m53s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Build and scan NVIDIA Agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 3s
test: cover agent update rollback and recording retries
2026-11-05 12:18:17 +01:00

66 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Reject direct database commands in production source outside documented EF exceptions."""
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parents[2]
SOURCE_ROOT = ROOT / "src"
# These operations cannot be expressed portably through EF's LINQ/change tracker.
# Keep the exception narrow by path and explain it in the file next to the operation.
EF_CORE_EXCEPTIONS = {
"src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs": "PostgreSQL VACUUM/REINDEX and catalog inspection",
"src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs": "PostgreSQL partition DDL and catalog inspection",
"src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs": "transaction-scoped PostgreSQL advisory lock",
"src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs": "transaction-scoped PostgreSQL advisory lock for serialized recording quota checks",
"src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs": "idempotent PostgreSQL bulk insert with ON CONFLICT DO NOTHING",
"src/Heimdall.Agent/Data/AgentOutboxDatabaseInitializer.cs": "baseline and migrate pre-EF local SQLite outbox schemas",
}
DATABASE_API = re.compile(
r"\b(?:Sqlite|Npgsql|Sql|MySql|Db)(?:Connection|Command|DataReader)\b"
r"|\.CreateCommand\s*\(|\.GetDbConnection\s*\(|\.CommandText\s*=|"
r"\.Execute(?:Reader|NonQuery|Scalar)(?:Async)?\s*\(|\b(?:ExecuteSqlRaw|ExecuteSqlInterpolated|"
r"SqlQueryRaw|SqlQuery|FromSqlRaw|FromSqlInterpolated|FromSql)\s*(?:Async)?\s*\(",
)
def inspect_source(path: str, content: str) -> list[str]:
"""Return policy violations for one repository-relative C# source file."""
if not path.startswith("src/") or "/Migrations/" in path or path.endswith(".Designer.cs"):
return []
if not DATABASE_API.search(content):
return []
rationale = EF_CORE_EXCEPTIONS.get(path)
if rationale and "EF Core exception:" in content:
return []
return [f"{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception"]
def check_tree(root: Path = ROOT) -> list[str]:
failures = []
for path in sorted((root / "src").rglob("*.cs")):
relative = path.relative_to(root).as_posix()
try:
content = path.read_text(encoding="utf-8-sig")
except UnicodeDecodeError:
failures.append(f"{relative}: source is not valid UTF-8")
continue
failures.extend(inspect_source(relative, content))
return failures
def main() -> int:
failures = check_tree()
if failures:
print("EF Core persistence policy violations:", file=sys.stderr)
print("\n".join(f"- {failure}" for failure in failures), file=sys.stderr)
return 1
print("EF Core persistence policy passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())