refactor: use EF Core for SQLite persistence
Heimdall Gitea / Detect CI scope (pull_request) Successful in 4s
Heimdall Gitea / Build and tests (pull_request) Successful in 14m48s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 4m24s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 9m12s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 4s

This commit is contained in:
Arnaud Dartois committed 2026-10-26 08:19:44 +01:00
1 parent 7c4cff90d8
commit f832d2fb62
36 files changed
+1174 -309

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
#!/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/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())
+23
View File
@@ -43,6 +43,29 @@ def load_test_plan():
spec.loader.exec_module(module)
return module
def load_efcore_policy():
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class EfCorePolicyTests(unittest.TestCase):
def test_current_production_sources_follow_policy(self):
self.assertEqual(load_efcore_policy().check_tree(REPO_ROOT), [])
def test_agent_ado_net_is_rejected(self):
failures = load_efcore_policy().inspect_source(
'src/Heimdall.Agent/Services/Example.cs',
'using Microsoft.Data.Sqlite; var connection = new SqliteConnection();')
self.assertEqual(len(failures), 1)
def test_provider_specific_sql_requires_explicit_exception_marker(self):
policy = load_efcore_policy()
path = 'src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs'
self.assertEqual(policy.inspect_source(path, 'db.Database.ExecuteSqlRaw("VACUUM");'), [
f'{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception'])
self.assertEqual(policy.inspect_source(path, '// EF Core exception: PostgreSQL maintenance\ndb.Database.ExecuteSqlRaw("VACUUM");'), [])
class TestPlanTests(unittest.TestCase):
def test_domain_change_reaches_dependent_suites(self):
suites = load_test_plan().plan(['src/Heimdall.Domain/Camera.cs'])['suites']
+1
View File
@@ -9,6 +9,7 @@ else
docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet
fi
bash docker/scripts/test-backup-restore.sh
python3 scripts/ci/check-efcore-usage.py
dotnet restore Heimdall.slnx --locked-mode
dotnet build Heimdall.slnx -c Release --no-restore -m:2
# NuGet advisory report is kept separate from compiler warning suppressions.