- 删 src/backend/src/platform/ 下 38 个转发壳 ⇒ 平台层只有真源(在 crates/) - 新增 src/backend/src/compat.rs 别名表(16 个域)⇒ routes.rs 的 1010 处 compat::<域>:: 调用点零改动,风险面从 1010 处降到 1 个文件 - test_support.rs 从 platform/ 迁到壳侧根(依赖装配根 ensure_schema_all ⇒ 认识业务层) - 全仓改写 import:crate::platform::X → sspf_core::X(44 处/9 文件); ssw_platform::platform::X → sspf_core::X(229 处/38 文件) - 修 check-contract-scan.py 的 plat_key 推导:按 crate 名判定(原按路径段数猜, M7 拆 crate 后必然失效 ⇒ CC6 静默失效);新增 derive_plat_key + 20 条断言自证 - 新增 AR15 防旧平台路径复活(三层判据,含目录级「含 .rs 才算复活」) - 闸门去壳路径:check-arch / check-boundary / check-module / check-contract-scan - 文档同步:CRATES-MIGRATION / contract / HANDOFF / HOWTO_MODULE / CLAUDE.md 验证:cargo build 零警告;cargo test 695 passed / 0 failed(与 M1 基线一致); check-arch 20/20;--self-test 10/10;check-boundary 12/12;check-contract 10/10 (反自证 12 例 + 20 条推导断言);check-module 123/123;check-citations 4/4; check-naming 3/0/1;verify.sh --smoke 14 步全绿。 至此 M1–M7 全部完成:crates/ 17 个包,src/backend/src/ 只剩装配 + 业务层。
266 lines
10 KiB
Python
266 lines
10 KiB
Python
#!/usr/bin/env python3
|
||
"""check-boundary-scan.py —— 平台层「零业务知识」扫描器(`check-boundary.sh` 的 CP1 后端)。
|
||
|
||
🔴 **为什么需要它**:CLAUDE.md 红线 12 要求「加一个业务模块只碰业务层」
|
||
⇒ 平台层(`crates/sspf-core/` + `crates/sspf-compat-*/` 等真源)里**不许出现任何业务标识符**
|
||
(🔴 M7 起转发壳已删除 ⇒ 平台层只有真源)
|
||
(业务表名 / 实体名 / 路由前缀 / 菜单 id / 菜单 url / 菜单 en_code)。
|
||
这条规则**只靠人看代码守不住** —— 加模块的人不会主动去看平台层 ⇒ 需要一把尺子。
|
||
|
||
🔴 **禁止的标识符清单从业务层自己派生**(不是手写常量表):
|
||
业务层说了什么 ⇒ 平台层就不许出现什么 ⇒ **加一个业务模块,这把尺子自动变严**,
|
||
不会出现「忘了同步常量表 ⇒ 漏检」。
|
||
|
||
🔴 **只扫「字符串字面量」**(注释不算):
|
||
注释里举例说明业务名是**文档行为**(例如解释 CTE 作用域)⇒ 允许;
|
||
代码里出现业务标识符才是**耦合** ⇒ 拦。
|
||
|
||
用法:
|
||
python3 scripts/check-boundary-scan.py <modules_dir> <scan_dir> [<scan_dir>...]
|
||
|
||
退出码:
|
||
0 = 干净(平台层零业务标识符)
|
||
1 = 发现泄漏(逐条打印 `文件:行号: [种类] token`)
|
||
2 = 用法错
|
||
"""
|
||
|
||
import os
|
||
import re
|
||
import sys
|
||
|
||
# 🔴 业务层里「哪些字段是业务知识」的抽取规则(与 `EntitySpec` / `MenuSpec` 的字段名对齐)。
|
||
SPEC_TABLE_RE = re.compile(r'table:\s*"([^"]+)"')
|
||
SPEC_ENTITY_RE = re.compile(r'entity:\s*"([^"]+)"')
|
||
SPEC_APP_RE = re.compile(r'app_code:\s*"([^"]+)"')
|
||
MENU_BLOCK_RE = re.compile(r'MenuSpec\s*\{(.*?)\n\};', re.DOTALL)
|
||
MENU_FIELD_RE = {
|
||
# 🔴 `\b` 不可省:否则 `parent_id: "0"` 里的 `id:` 会被当成菜单 id。
|
||
"id": re.compile(r'\bid:\s*"([^"]+)"'),
|
||
"en_code": re.compile(r'\ben_code:\s*"([^"]+)"'),
|
||
"url_address": re.compile(r'\burl_address:\s*"([^"]+)"'),
|
||
}
|
||
|
||
# 🔴 字符串字面量:`r#"..."#` / `r"..."` / `"..."`(普通串的转义 `\"` 不影响子串判定)。
|
||
LITERAL_RE = re.compile(r'r(#*)"(.*?)"\1|"((?:[^"\\]|\\.)*)"', re.DOTALL)
|
||
|
||
|
||
def strip_comments(src):
|
||
"""去掉 `//` 行注释与 `/* */` 块注释(保留字符串字面量里的内容)。
|
||
|
||
🔴 逐字符扫描 ⇒ 字符串里的 `//`(如 `"http://x"`)不会被误当注释。
|
||
"""
|
||
out = []
|
||
in_block = False
|
||
for line in src.splitlines():
|
||
if in_block:
|
||
end = line.find("*/")
|
||
if end == -1:
|
||
continue
|
||
line = line[end + 2:]
|
||
in_block = False
|
||
buf = []
|
||
in_str = False
|
||
i = 0
|
||
n = len(line)
|
||
while i < n:
|
||
c = line[i]
|
||
if in_str:
|
||
buf.append(c)
|
||
if c == "\\" and i + 1 < n:
|
||
buf.append(line[i + 1])
|
||
i += 2
|
||
continue
|
||
if c == '"':
|
||
in_str = False
|
||
i += 1
|
||
continue
|
||
if c == '"':
|
||
in_str = True
|
||
buf.append(c)
|
||
i += 1
|
||
continue
|
||
if line.startswith("//", i):
|
||
break
|
||
if line.startswith("/*", i):
|
||
in_block = True
|
||
rest = line[i + 2:]
|
||
end = rest.find("*/")
|
||
if end == -1:
|
||
break
|
||
line = rest[end + 2:]
|
||
buf = []
|
||
i = 0
|
||
n = len(line)
|
||
in_str = False
|
||
continue
|
||
buf.append(c)
|
||
i += 1
|
||
out.append("".join(buf))
|
||
return out
|
||
|
||
|
||
def literals_with_lines(path):
|
||
"""⇒ [(行号, 字面量内容)](注释已剔除)。"""
|
||
with open(path, "r", encoding="utf-8") as fh:
|
||
lines = strip_comments(fh.read())
|
||
out = []
|
||
for idx, line in enumerate(lines, start=1):
|
||
for m in LITERAL_RE.finditer(line):
|
||
content = m.group(2) if m.group(1) is not None else m.group(3)
|
||
if content is not None:
|
||
out.append((idx, content))
|
||
return out
|
||
|
||
|
||
def business_tokens(modules_dir, packs_dir=None):
|
||
"""从业务层派生「平台层不许出现」的标识符清单。
|
||
|
||
⇒ [(种类, token)],种类用于报错时点名「漏的是哪一类」。
|
||
|
||
🔴 **业务层现在有两处**(批次 12 交付物 ②「spec 单一真源」):
|
||
- `src/backend/src/modules/*.rs` —— **面 A** 的内嵌业务模块
|
||
(demo / shop / books);
|
||
- `packs/*/src/lib.rs` —— **业务包**(asset 等)。
|
||
两处都要扫 ⇒ 否则包里的业务表名 / 实体名会从「禁止清单」里消失
|
||
⇒ 平台层就可以写 `asset_data_resource` 而不被抓 ⇒ **尺子变弱**。
|
||
"""
|
||
tokens = []
|
||
seen = set()
|
||
|
||
def add(kind, value):
|
||
if not value:
|
||
return
|
||
key = (kind, value)
|
||
if key in seen:
|
||
return
|
||
seen.add(key)
|
||
tokens.append((kind, value))
|
||
|
||
sources = []
|
||
for name in sorted(os.listdir(modules_dir)):
|
||
if not name.endswith(".rs") or name == "mod.rs":
|
||
continue
|
||
sources.append(os.path.join(modules_dir, name))
|
||
|
||
# 🔴 **业务包**:包目录里的 `src/lib.rs` 是包声明的所在地。
|
||
if packs_dir and os.path.isdir(packs_dir):
|
||
for pkg in sorted(os.listdir(packs_dir)):
|
||
lib = os.path.join(packs_dir, pkg, "src", "lib.rs")
|
||
if os.path.isfile(lib):
|
||
sources.append(lib)
|
||
|
||
for path in sources:
|
||
with open(path, "r", encoding="utf-8") as fh:
|
||
src = "\n".join(strip_comments(fh.read()))
|
||
for m in SPEC_TABLE_RE.finditer(src):
|
||
add("业务表名", m.group(1))
|
||
for m in SPEC_ENTITY_RE.finditer(src):
|
||
add("业务实体名", m.group(1))
|
||
for m in SPEC_APP_RE.finditer(src):
|
||
add("业务路由前缀", "/api/ssw/{}/".format(m.group(1)))
|
||
for m in MENU_BLOCK_RE.finditer(src):
|
||
body = m.group(1)
|
||
for kind, rx in MENU_FIELD_RE.items():
|
||
for f in rx.finditer(body):
|
||
add("业务菜单 {}".format(kind), f.group(1))
|
||
return tokens
|
||
|
||
|
||
def rust_files(root):
|
||
"""⇒ root 下全部 `.rs` 文件(递归,按路径排序)。"""
|
||
out = []
|
||
for dirpath, dirnames, filenames in os.walk(root):
|
||
dirnames.sort()
|
||
for name in sorted(filenames):
|
||
if name.endswith(".rs"):
|
||
out.append(os.path.join(dirpath, name))
|
||
return out
|
||
|
||
|
||
def main(argv):
|
||
if len(argv) >= 2 and argv[1] == "--self-test":
|
||
return self_test()
|
||
|
||
if len(argv) < 3:
|
||
sys.stderr.write(
|
||
"用法: python3 scripts/check-boundary-scan.py <modules_dir> <scan_dir> [...]\n"
|
||
)
|
||
return 2
|
||
|
||
modules_dir = argv[1]
|
||
scan_dirs = argv[2:]
|
||
# 🔴 业务包目录(可省略 ⇒ 兼容旧调用;`check-boundary.sh` 会传)。
|
||
packs_dir = os.environ.get("SSW_PACKS_DIR") or None
|
||
tokens = business_tokens(modules_dir, packs_dir)
|
||
if not tokens:
|
||
sys.stderr.write("业务层没解析出任何标识符(modules_dir 有问题?)\n")
|
||
return 2
|
||
|
||
violations = []
|
||
scanned = 0
|
||
for root in scan_dirs:
|
||
for path in rust_files(root):
|
||
scanned += 1
|
||
rel = os.path.relpath(path)
|
||
for lineno, content in literals_with_lines(path):
|
||
for kind, token in tokens:
|
||
if token in content:
|
||
violations.append((rel, lineno, kind, token, content.strip()))
|
||
|
||
for rel, lineno, kind, token, content in violations:
|
||
print("{}:{}: [{}] {} ← 字面量: {}".format(rel, lineno, kind, token, content[:120]))
|
||
|
||
print("scanned_files={} tokens={} violations={}".format(scanned, len(tokens), len(violations)))
|
||
return 1 if violations else 0
|
||
|
||
|
||
def self_test():
|
||
"""🔴 **反自证**:造一个「平台层泄漏业务表名」的假文件 ⇒ 必须被抓出来。
|
||
|
||
🔴 **为什么必须有**:一把永远返回「干净」的尺子 = 没有尺子。
|
||
自证 = 用同一条规则去抓一个**明知存在**的泄漏 ⇒ 抓到了 ⇒ 规则本身有效。
|
||
"""
|
||
import tempfile
|
||
|
||
with tempfile.TemporaryDirectory() as tmp:
|
||
mods = os.path.join(tmp, "modules")
|
||
plat = os.path.join(tmp, "platform")
|
||
os.makedirs(mods)
|
||
os.makedirs(plat)
|
||
with open(os.path.join(mods, "demo.rs"), "w", encoding="utf-8") as fh:
|
||
fh.write(
|
||
'pub const DEMO_SPEC: EntitySpec = EntitySpec {\n'
|
||
' app_code: "demo",\n'
|
||
' entity: "DemoItem",\n'
|
||
' table: "demo_item",\n'
|
||
'};\n'
|
||
)
|
||
# 泄漏:平台层里出现了业务表名(**在字符串字面量里**)。
|
||
with open(os.path.join(plat, "leak.rs"), "w", encoding="utf-8") as fh:
|
||
fh.write('const SQL: &str = "SELECT * FROM demo_item";\n')
|
||
# 不泄漏:只在**注释**里提到业务表名(文档行为,允许)。
|
||
with open(os.path.join(plat, "doc.rs"), "w", encoding="utf-8") as fh:
|
||
fh.write('// 例:SELECT * FROM demo_item\nconst OK: &str = "SELECT 1";\n')
|
||
|
||
tokens = business_tokens(mods)
|
||
# 表名 + 实体名 + 路由前缀(假 spec 里没有 MenuSpec ⇒ 没有菜单那三类)。
|
||
if len(tokens) != 3:
|
||
print("self-test: token 抽取数不对: {}".format(len(tokens)))
|
||
return 1
|
||
|
||
hits = 0
|
||
for path in rust_files(plat):
|
||
for _lineno, content in literals_with_lines(path):
|
||
for _kind, token in tokens:
|
||
if token in content:
|
||
hits += 1
|
||
if hits != 1:
|
||
print("self-test: 应恰好抓到 1 处泄漏,实际 {} 处".format(hits))
|
||
return 1
|
||
|
||
print("self-test: OK(泄漏被抓到、注释里的举例未被误报)")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main(sys.argv)) |