311 lines
9.2 KiB
Python
311 lines
9.2 KiB
Python
"""Static, offline architecture checks for PLoop's Python source tree."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import ast
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
|
||
|
||
DOMAIN_FORBIDDEN_IMPORTS = {
|
||
"alembic",
|
||
"fastapi",
|
||
"pydantic",
|
||
"pathlib",
|
||
"redis",
|
||
"sqlalchemy",
|
||
"subprocess",
|
||
}
|
||
PLOOP_LAYERS = {"api", "application", "domain", "infra", "worker"}
|
||
FILE_IO_METHODS = {
|
||
"open",
|
||
"read_bytes",
|
||
"read_text",
|
||
"write_bytes",
|
||
"write_text",
|
||
}
|
||
PROTECTED_ASSIGNMENTS = {
|
||
("run", "phase"),
|
||
("run", "status"),
|
||
("shard", "lease"),
|
||
("artifact", "sealed"),
|
||
}
|
||
LEGACY_EXECUTOR = Path("execute.py")
|
||
FUTURE_EXECUTOR = Path("infra/adapters/runner.py")
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Violation:
|
||
path: Path
|
||
line: int
|
||
rule_id: str
|
||
message: str
|
||
remediation: str
|
||
|
||
def render(self) -> str:
|
||
return (
|
||
f"{self.path.as_posix()}:{self.line}: {self.rule_id} {self.message}"
|
||
f";{self.remediation}"
|
||
)
|
||
|
||
|
||
def main() -> int:
|
||
arguments = _parser().parse_args()
|
||
violations = check_tree(arguments.root)
|
||
print(f"violations={len(violations)}")
|
||
for violation in violations:
|
||
print(violation.render())
|
||
return 1 if violations else 0
|
||
|
||
|
||
def check_tree(root: Path) -> tuple[Violation, ...]:
|
||
resolved_root = root.resolve()
|
||
violations: list[Violation] = []
|
||
for path in sorted(resolved_root.rglob("*.py")):
|
||
relative_path = path.relative_to(resolved_root)
|
||
try:
|
||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(relative_path))
|
||
except SyntaxError as error:
|
||
violations.append(
|
||
Violation(
|
||
relative_path,
|
||
error.lineno or 1,
|
||
"PARSE001",
|
||
"Python 源文件无法解析",
|
||
"修正语法后重新运行检查",
|
||
)
|
||
)
|
||
continue
|
||
violations.extend(_check_module(relative_path, tree))
|
||
return tuple(violations)
|
||
|
||
|
||
def _parser() -> argparse.ArgumentParser:
|
||
parser = argparse.ArgumentParser(
|
||
description="Check PLoop Python architecture and dangerous-call boundaries."
|
||
)
|
||
parser.add_argument("root", type=Path)
|
||
return parser
|
||
|
||
|
||
def _check_module(path: Path, tree: ast.Module) -> tuple[Violation, ...]:
|
||
violations: list[Violation] = []
|
||
for node in ast.walk(tree):
|
||
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
||
for module in _imported_modules(node):
|
||
violations.extend(_import_violations(path, node.lineno, module))
|
||
if isinstance(node, ast.Call):
|
||
violations.extend(_call_violations(path, node))
|
||
if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
|
||
violations.extend(_assignment_violations(path, node))
|
||
return tuple(violations)
|
||
|
||
|
||
def _imported_modules(node: ast.Import | ast.ImportFrom) -> tuple[str, ...]:
|
||
if isinstance(node, ast.Import):
|
||
return tuple(alias.name for alias in node.names)
|
||
if node.module is None:
|
||
return ()
|
||
return (node.module,)
|
||
|
||
|
||
def _import_violations(path: Path, line: int, module: str) -> tuple[Violation, ...]:
|
||
violations: list[Violation] = []
|
||
if _is_domain(path) and _is_domain_forbidden(module):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
line,
|
||
"ARCH001",
|
||
"domain 不得导入框架、I/O 或其他 PLoop 分层包",
|
||
"改为 domain port、value object 或 pkg/kernel 依赖",
|
||
)
|
||
)
|
||
if _is_pkg(path) and _is_ploop_layer(module):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
line,
|
||
"ARCH002",
|
||
"pkg 不得反向导入 PLoop 分层包",
|
||
"将依赖倒置到调用层或保留在所属 bounded context",
|
||
)
|
||
)
|
||
if _is_application(path) and _starts_with(module, "ploop.infra"):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
line,
|
||
"ARCH003",
|
||
"application 不得直接导入 infra implementation",
|
||
"依赖 repository port,composition root 默认不设例外",
|
||
)
|
||
)
|
||
if _is_api_or_worker_handler(path) and (
|
||
_starts_with(module, "ploop.infra") or _module_root(module) == "sqlalchemy"
|
||
):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
line,
|
||
"ARCH004",
|
||
"API 或 worker handler 不得直接导入 infra 或 ORM",
|
||
"改为调用 application command 或 query service",
|
||
)
|
||
)
|
||
if _module_root(module) == "subprocess" and not _allows_subprocess(path):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
line,
|
||
"EXEC001",
|
||
"subprocess 只允许位于受控 runner",
|
||
"移至 infra/adapters/runner.py;M1 前仅 execute.py 兼容",
|
||
)
|
||
)
|
||
return tuple(violations)
|
||
|
||
|
||
def _call_violations(path: Path, node: ast.Call) -> tuple[Violation, ...]:
|
||
violations: list[Violation] = []
|
||
if _is_subprocess_call(node.func) and not _allows_subprocess(path):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
node.lineno,
|
||
"EXEC001",
|
||
"subprocess 调用只允许位于受控 runner",
|
||
"移至 infra/adapters/runner.py;M1 前仅 execute.py 兼容",
|
||
)
|
||
)
|
||
if any(
|
||
keyword.arg == "shell" and isinstance(keyword.value, ast.Constant) and keyword.value.value is True
|
||
for keyword in node.keywords
|
||
):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
node.lineno,
|
||
"EXEC002",
|
||
"禁止 shell=True",
|
||
"传递固定参数数组给受控 runner",
|
||
)
|
||
)
|
||
if _is_domain(path) and _is_file_io_call(node.func):
|
||
violations.append(
|
||
_violation(
|
||
path,
|
||
node.lineno,
|
||
"ARCH001",
|
||
"domain 不得执行文件 I/O",
|
||
"通过 port 由 infra 执行文件操作",
|
||
)
|
||
)
|
||
return tuple(violations)
|
||
|
||
|
||
def _assignment_violations(
|
||
path: Path, node: ast.Assign | ast.AnnAssign | ast.AugAssign
|
||
) -> tuple[Violation, ...]:
|
||
if _is_domain_execution(path):
|
||
return ()
|
||
targets = node.targets if isinstance(node, ast.Assign) else (node.target,)
|
||
for target in targets:
|
||
if _attribute_pair(target) in PROTECTED_ASSIGNMENTS:
|
||
return (
|
||
_violation(
|
||
path,
|
||
node.lineno,
|
||
"STATE001",
|
||
"受保护 Run、Shard 或 Artifact 字段只能由 domain/execution 写入",
|
||
"改为调用 aggregate 的领域方法",
|
||
),
|
||
)
|
||
return ()
|
||
|
||
|
||
def _is_domain_forbidden(module: str) -> bool:
|
||
root = _module_root(module)
|
||
if root in DOMAIN_FORBIDDEN_IMPORTS:
|
||
return True
|
||
if not module.startswith("ploop."):
|
||
return False
|
||
parts = module.split(".")
|
||
return parts[1] != "domain" and parts[1:3] != ["pkg", "kernel"]
|
||
|
||
|
||
def _is_ploop_layer(module: str) -> bool:
|
||
return module.startswith("ploop.") and len(module.split(".")) > 1 and module.split(".")[1] in PLOOP_LAYERS
|
||
|
||
|
||
def _module_root(module: str) -> str:
|
||
return module.split(".", 1)[0]
|
||
|
||
|
||
def _starts_with(module: str, prefix: str) -> bool:
|
||
return module == prefix or module.startswith(f"{prefix}.")
|
||
|
||
|
||
def _is_domain(path: Path) -> bool:
|
||
return path.parts[:1] == ("domain",)
|
||
|
||
|
||
def _is_pkg(path: Path) -> bool:
|
||
return path.parts[:1] == ("pkg",)
|
||
|
||
|
||
def _is_application(path: Path) -> bool:
|
||
return path.parts[:1] == ("application",)
|
||
|
||
|
||
def _is_api_or_worker_handler(path: Path) -> bool:
|
||
if path.parts[:1] == ("api",):
|
||
return True
|
||
|
||
return path.parts[:1] == ("worker",) and (
|
||
path.name == "handler.py" or "handler" in path.parts
|
||
)
|
||
|
||
|
||
def _is_domain_execution(path: Path) -> bool:
|
||
return path.parts[:2] == ("domain", "execution")
|
||
|
||
|
||
def _allows_subprocess(path: Path) -> bool:
|
||
return path == LEGACY_EXECUTOR or path == FUTURE_EXECUTOR
|
||
|
||
|
||
def _is_subprocess_call(function: ast.expr) -> bool:
|
||
return _dotted_name(function).split(".", 1)[0] == "subprocess"
|
||
|
||
|
||
def _is_file_io_call(function: ast.expr) -> bool:
|
||
dotted = _dotted_name(function)
|
||
return dotted == "open" or dotted.rsplit(".", 1)[-1] in FILE_IO_METHODS
|
||
|
||
|
||
def _attribute_pair(target: ast.expr) -> tuple[str, str] | None:
|
||
if not isinstance(target, ast.Attribute) or not isinstance(target.value, ast.Name):
|
||
return None
|
||
return (target.value.id, target.attr)
|
||
|
||
|
||
def _dotted_name(node: ast.expr) -> str:
|
||
if isinstance(node, ast.Name):
|
||
return node.id
|
||
if isinstance(node, ast.Attribute):
|
||
parent = _dotted_name(node.value)
|
||
return f"{parent}.{node.attr}" if parent else node.attr
|
||
return ""
|
||
|
||
|
||
def _violation(
|
||
path: Path, line: int, rule_id: str, message: str, remediation: str
|
||
) -> Violation:
|
||
return Violation(path, line, rule_id, message, remediation)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|