Compose a build-time policy engine enforcing architectural layering rules: static…
- User
Compose a build-time policy engine enforcing architectural layering rules: static analysis, enforcement feedback, exemption workflow, and metrics.
Assistant
Compose a build-time policy engine enforcing architectural layering rules: static analysis, enforcement feedback, exemption workflow, and metrics.
The user wants a "build-time policy engine" to enforce "architectural layering rules." This implies a system that runs during the build process (likely CI/CD or a pre-commit hook) to check if the code dependencies adhere to a predefined layered architecture (e.g., UI -> Service -> Repository).
Key components requested:
Design Choices & Philosophy:
networkx), and easy CLI creation (click or argparse). It can analyze any language if we parse import statements, but for a concrete example, I'll assume a generic import structure or Python imports for simplicity. To make it robust, I'll define an abstract "Parser" interface so users can adapt it to Java, TS, etc.Step-by-Step Implementation Plan:
Drafting the Code Structure (Mental or Scratchpad):
config.yaml: Layers defined by regex (e.g., src/ui/** is UI).policy_engine.py: Main entry point.analyzer.py: Logic to parse files.models.py: Data classes for Layer, Violation, Rule.Self-Correction during thought process: Writing a full AST parser for every language is too much code. I will implement a simple regex-based import parser for Python-style imports as a proof of concept, but structure the code so the parsing logic is pluggable.
Exemption Workflow: How does this work in practice? Usually, a developer adds an entry to exemptions.json. The build fails unless the violation is in the exemption list and valid.
Metrics: Just simple counters for now (Total violations, violations per layer, open exemptions).
Refining the Solution: I will provide a complete, runnable Python implementation.
arch_config.yaml (The Rules)exemptions.json (The Waivers)engine.py (The System)Let's focus on the engine.py structure:
LayerMap: maps files to layers.DependencyGraph: nodes and edges.RuleChecker: iterates graph, applies rules.Reporter: prints output.Key Edge Case: Cycles. Layered architecture usually forbids cycles between layers. I should check for that too.
Final Polish:
Ensure the code is modular. Use argparse for CLI. Use networkx if I want to be fancy, but raw python dicts are often clearer for a standalone script without dependencies. I'll stick to standard library where possible to make it "copy-paste runnable," maybe with a comment about networkx. Actually, standard lib collections is fine.
Let's write the code.
I will use a mock project structure concept to drive the logic. Layer: Presentation -> Business -> Data. Rule: Presentation cannot access Data.
Exemption Workflow detail: If a violation occurs:
exemptions.json?Let's assemble.
This solution implements a Build-Time Policy Engine called ArchGuard. It is designed to run as part of a CI/CD pipeline or a pre-commit hook to enforce architectural layering (e.g., preventing the UI from directly accessing the Database).
YAML): Defines layers and access rules.Scanner): Parses source code to build a Dependency Graph (AST-based or Regex-based).Enforcer): Validates the graph against the rules.JSON): Handles technical debt waivers with expiration dates.Requires Python 3.7+.
pip install pyyaml
Create a file named arch_config.yaml. This defines your layers and which layers can communicate with which.
# arch_config.yaml
layers:
- name: UI
includes:
- "src/ui/**"
- "src/components/**"
- name: Service
includes:
- "src/services/**"
- "src/controllers/**"
- name: Data
includes:
- "src/repository/**"
- "src/db/**"
rules:
# UI can talk to Service, but NOT Data
- from: UI
to: Service
allowed: true
- from: UI
to: Data
allowed: false
# Service can talk to Data
- from: Service
to: Data
allowed: true
# Disallow cyclic dependencies (implicit in strict layering)
- from: Data
to: UI
allowed: false
Create a file named exemptions.json. This allows specific files to bypass rules temporarily (e.g., during refactoring).
[
{
"id": "EX-001",
"file": "src/ui/LegacyDashboard.py",
"from_layer": "UI",
"to_layer": "Data",
"reason": "Tech debt: Refactoring required by Q4",
"expires": "2025-12-31"
}
]
Save this as engine.py.
To see it in action, create a mock project structure:
Directory Structure:
/
├── engine.py
├── arch_config.yaml
├── exemptions.json
└── src/
├── ui/
│ └── Dashboard.py
├── services/
│ └── UserAuth.py
└── db/
└── DatabaseConnection.py
src/ui/Dashboard.py (Clean)
# Allowed: UI -> Service
from src.services.UserAuth import login
src/ui/AdminPanel.py (Violation)
# NOT Allowed: UI -> Data
from src.db.DatabaseConnection import get_conn
Running the engine:
python engine.py
StaticAnalyzer class walks the directory tree. It uses Regex to parse import statements (simpler than full AST parsing but effective for standard imports). It normalizes file paths to match the layer configuration.PolicyEngine calculates the source layer and target layer for every import. It compares this against the rules list. If a rule is allowed: false, it generates a violation.exemptions.json.is_exempt=True.import os
import re
import json
import yaml
import glob
import fnmatch
from datetime import datetime
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Dict, Set, Optional
# --- Data Models ---
@dataclass
class Dependency:
"""Represents a single code dependency (import)."""
importer_path: str
imported_module: str
line_number: int
@dataclass
class Layer:
"""Represents an architectural layer."""
name: str
includes: List[str] # Glob patterns
@dataclass
class Rule:
"""Represents an allowed or denied access rule."""
from_layer: str
to_layer: str
allowed: bool
@dataclass
class Exemption:
"""Represents a policy waiver."""
id: str
file: str
from_layer: str
to_layer: str
reason: str
expires: str
@dataclass
class Violation:
"""Represents a policy breach."""
file: str
line: int
from_layer: str
to_layer: str
dependency: str
is_exempt: bool = False
exemption_reason: str = ""
# --- Core Components ---
class ConfigLoader:
def __init__(self, config_path):
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
self.layers = [Layer(**l) for l in self.config['layers']]
self.rules = [Rule(**r) for r in self.config['rules']]
def get_layer(self, file_path: str) -> Optional[str]:
"""Determine which layer a file belongs to based on glob patterns."""
for layer in self.layers:
for pattern in layer.includes:
# Normalize path for matching
if fnmatch.fnmatch(file_path, pattern) or \
fnmatch.fnmatch(file_path, pattern.replace("**", "*")):
return layer.name
return "Unknown"
class ExemptionManager:
def __init__(self, exemption_path):
self.path = exemption_path
self.exemptions = []
if os.path.exists(exemption_path):
with open(exemption_path, 'r') as f:
data = json.load(f)
self.exemptions = [Exemption(**e) for e in data]
def is_exempt(self, file_path: str, from_layer: str, to_layer: str) -> (bool, str):
"""Check if a specific violation is waived and not expired."""
now = datetime.now()
for ex in self.exemptions:
# Basic wildcard matching for exemption file paths
file_match = fnmatch.fnmatch(file_path, ex.file)
if file_match and ex.from_layer == from_layer and ex.to_layer == to_layer:
exp_date = datetime.strptime(ex.expires, "%Y-%m-%d")
if exp_date >= now:
return True, ex.reason
else:
print(f"Warning: Exemption {ex.id} has expired.")
return False, ""
class StaticAnalyzer:
"""
Parses source files to extract dependencies.
Currently implemented for Python imports. Can be adapted for JS/TS/Java.
"""
def __init__(self, source_root):
self.root = source_root
def scan(self) -> List[Dependency]:
dependencies = []
# Regex for python import: 'from X import Y' or 'import X'
import_pattern = re.compile(r'^\s*(?:from\s+([^\s]+)\s+import|import\s+([^\s]+))')
files = glob.glob(os.path.join(self.root, "**/*.py"), recursive=True)
for file_path in files:
# Convert file path to module path for matching logic
# e.g. src/ui/main.py -> src.ui.main
try:
with open(file_path, 'r', encoding='utf-8') as f:
for i, line in enumerate(f, 1):
match = import_pattern.match(line)
if match:
module = match.group(1) or match.group(2)
# Only track internal dependencies (not stdlib or venv)
if "src" in module:
dependencies.append(Dependency(file_path, module, i))
except Exception as e:
print(f"Error scanning {file_path}: {e}")
return dependencies
class PolicyEngine:
def __init__(self, config: ConfigLoader, exemptions: ExemptionManager):
self.config = config
self.exemptions = exemptions
self.violations = []
def enforce(self, dependencies: List[Dependency]) -> List[Violation]:
self.violations = []
for dep in dependencies:
# 1. Identify Layers
importer_layer = self.config.get_layer(dep.importer_path)
# Map imported module string back to a file path (heuristic)
# e.g. src.services.auth -> src/services/auth.py
possible_path = dep.imported_module.replace('.', os.sep) + ".py"
imported_layer = self.config.get_layer(possible_path)
# Skip if we can't map to layers
if importer_layer == "Unknown" or imported_layer == "Unknown":
continue
# Skip self-references
if importer_layer == imported_layer:
continue
# 2. Find Rule
applicable_rule = next(
(r for r in self.config.rules
if r.from_layer == importer_layer and r.to_layer == imported_layer),
None
)
# 3. Check Policy
if applicable_rule:
if not applicable_rule.allowed:
# It is a violation. Check Exemptions.
is_waived, reason = self.exemptions.is_exempt(
dep.importer_path, importer_layer, imported_layer
)
if is_waived:
self.violations.append(Violation(
dep.importer_path, dep.line_number,
importer_layer, imported_layer,
dep.imported_module, True, reason
))
else:
self.violations.append(Violation(
dep.importer_path, dep.line_number,
importer_layer, imported_layer,
dep.imported_module, False
))
return self.violations
class Reporter:
@staticmethod
def print_report(violations: List[Violation]):
hard_violations = [v for v in violations if not v.is_exempt]
waived_violations = [v for v in violations if v.is_exempt]
print("\n--- ARCHGUARD REPORT ---\n")
if waived_violations:
print(f"[{len(waived_violations)}] WAIVED VIOLATIONS (Technical Debt):")
for v in waived_violations:
print(f" [WAIVED] {v.file}:{v.line} ({v.from_layer}->{v.to_layer})")
print(f" Reason: {v.exemption_reason}")
print("")
if hard_violations:
print(f"[{len(hard_violations)}] HARD VIOLATIONS (Build Breaker):")
for v in hard_violations:
print(f" [FAIL] {v.file}:{v.line}")
print(f" Layer Breach: {v.from_layer} attempted access to {v.to_layer}")
print(f" Dependency: {v.dependency}")
print("")
# Metrics
print("--- METRICS ---")
print(f"Total Dependencies Checked: {len(violations)}")
print(f"Policy Compliance: {100 * (1 - len(hard_violations) / max(1, len(violations))):.2f}%")
if hard_violations:
print("\n⛔ BUILD FAILED: Architectural rules violated.")
return 1
print("\n✅ BUILD PASSED: Architecture is clean.")
return 0
# --- Main Execution ---
if __name__ == "__main__":
import sys
# Setup paths
CONFIG_FILE = "arch_config.yaml"
EXEMPTION_FILE = "exemptions.json"
SOURCE_DIR = "src" # Assuming code is in a 'src' folder relative to script
print(f"Scanning directory: {SOURCE_DIR}...")
# Initialize components
try:
config = ConfigLoader(CONFIG_FILE)
except FileNotFoundError:
print("Error: arch_config.yaml not found.")
sys.exit(1)
exemptions = ExemptionManager(EXEMPTION_FILE)
analyzer = StaticAnalyzer(SOURCE_DIR)
engine = PolicyEngine(config, exemptions)
# Run Analysis
deps = analyzer.scan()
violations = engine.enforce(deps)
# Report and Exit Code
exit_code = Reporter.print_report(violations)
sys.exit(exit_code)