unis-oa/backend/scripts/check_memberships.py

205 lines
9.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""守"一个人挂几处岗位"这一问:反查与正向解析同一口径,而且不随人数排队。
审批按岗位找人(``oa_role.list_auth`` / ``oa_group`` 两列成员),本平台"一个人有几个
身份"就是指同一个人被挂进几处岗位。反向那一问(``org.memberships_for``,人员列表那一列
「岗位角色」用的就是它)是新添的,它的风险只有三种,这个脚本一个个钉:
1. **不许漏**:岗位正向解析出来的人(``expand_as`` 那一套),反查必须把这一处岗位算给他;
2. **不许多**:反查列出来的(直挂名的)人必须在正向名单里——多算一个人,界面上就
多一个人看起来"是某岗位的审批人",而真派待办时又轮不到他;
3. **不许按人排队**:问 1 个人与问一整页 20 个人必须问一样多次库。这一列是给列表页用的,
一旦按人发问就是每页 20 趟,比它省下的那点眼睛上的方便贵得多。
顺带钉三条口径:成员值绕经别的岗位进来的要标出来(``direct=false`` 与来路)、同一个岗位
在两列成员里各挂一次只算一处、成员认不出人时不算成任何人的岗位(与引擎"认不出的人不派活"
同一个门)。
临时造的四个岗位 / 分组都带 ``(校验-`` 前缀:开工前先按前缀扫一次上一次被掐断留下的
残留,收工再按前缀删一次,末尾另开一条连接复核库里确实是零。用真提交而不是未提交事务,
是因为成员绕经别的岗位时展开走并发块——worker 各一条连接,看不见没提交的行,而那正是
生产上跑的那条路。
cd backend && PYTHONPATH=. python3 scripts/check_memberships.py
"""
from __future__ import annotations
import sys
from sqlalchemy import event, func, select
from app import models, readcache
from app.db import SessionLocal, engine
from app.service import org
FAILS: list[str] = []
PASSED = 0
#: 判据只看语句条数:这一层买的就是"别按人排队"。
ROWS: list[str] = []
@event.listens_for(engine, "after_cursor_execute")
def _count(conn, cursor, statement, parameters, context, many): # noqa: ANN001
ROWS.append(" ".join(statement.split())[:120])
def check(label: str, passed: bool, detail: str = "") -> None:
global PASSED
if passed:
PASSED += 1
print(f"[通过] {label}")
else:
FAILS.append(label)
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
def counted(fn):
"""跑一趟,交回 ``(结果, 这一趟问了几条库)``;每次先把只读缓存清干净。"""
readcache.invalidate_everywhere()
start = len(ROWS)
value = fn()
return value, len(ROWS) - start
def forward(db, kind: str, name: str) -> list[str]:
"""正向那一份答案:这个岗位 / 分组现在解析得出谁。"""
return list(org.expand_as(db, kind, name))
def listed(rows, kind: str, name: str) -> bool:
return any(row["kind"] == kind and row["name"] == name for row in rows or [])
#: 临时岗位与分组的名字:都以这个前缀开头,收尾按前缀删,中途被掐断也扫得回来
TEMP_PREFIX = "(校验-"
ROLE_A, ROLE_B, ROLE_X, GROUP_C = "(校验-岗位甲", "(校验-岗位乙", "(校验-挂着没这个人", "(校验-分组丙"
def _wipe_temp(db) -> None:
"""删掉所有校验用的临时岗位与分组(开工前扫一次上一次的残留,收工再扫一次)。"""
for model in (models.Role, models.Group):
for row in db.execute(select(model).where(model.name.like(f"{TEMP_PREFIX}%"))).scalars():
db.delete(row)
db.commit()
readcache.invalidate_everywhere()
def main() -> int:
db = SessionLocal()
try:
return _checks(db)
finally:
_cleanup(db)
def _checks(db) -> int:
try:
role_rows = db.execute(select(models.Role.name, models.Role.list_auth)).all()
group_rows = db.execute(
select(models.Group.name, models.Group.list_identity, models.Group.list_person)
).all()
active = {
str(account)
for (account,) in db.execute(
select(models.User.account).where(models.User.status == models.UserStatus.ACTIVE)
)
}
check(
f"库里读到了配置与人员(岗位 {len(role_rows)} 个 / 分组 {len(group_rows)} 个 / 在职 {len(active)} 人)",
bool(active),
)
# 1) 不许漏:正向解析出的人,反查必须认这一处岗位
missed: list[str] = []
for kind, rows in (("role", role_rows), ("group", group_rows)):
for name, *_rest in rows:
people = [account for account in forward(db, kind, str(name)) if account in active]
if not people:
continue
reverse = org.memberships_for(db, people)
missed += [
f"{name}->{account}"
for account in people
if not listed(reverse.get(account), kind, str(name))
]
check("正向解析得出的每一个人都被算进那一处岗位(现网配置逐岗位逐人)", not missed, ",".join(missed[:4]))
# 2) 不许多:反查列出来的直挂名的人,正向也必须认他
reverse_active = org.memberships_for(db, sorted(active))
# 直挂名那批的 via 就是被问的那个账号本身,问的都是在职的,所以它就是要复核的人
holders = sorted({row["via"] for rows in reverse_active.values() for row in rows if row["direct"]})
over: list[str] = []
for account in holders:
for row in reverse_active.get(account, []):
if account not in set(forward(db, row["kind"], row["name"])):
over.append(f"{account} 被算成 {row['name']}")
check("反查列出来的人正向也认(不会多出一个看起来该批却收不到待办的人)", not over, ";".join(over[:4]))
# 3) 不许按人排队
sample = holders[:1] or sorted(active)[:1]
extras = sorted(set(sorted(active)) - set(sample))[:19]
_one, n_one = counted(lambda: org.memberships_for(db, sample))
_page, n_page = counted(lambda: org.memberships_for(db, sample + extras))
check(f"问 1 个人与问一整页 20 个人问一样多次库(各 {n_page} 条)", n_one == n_page, f"{n_one} vs {n_page}")
_empty, n_empty = counted(lambda: org.memberships_for(db, []))
check("空清单一条库都不问", n_empty == 0, f"{n_empty} 条")
# 4) 一个人挂两处岗位:临时岗位与分组是真提交进去的,收尾那一步删干净。
# 非得提交是因为成员值绕经别的岗位时,展开走的是并发块——每个 worker 自己一条
# 连接,看不见没提交的行;那正是生产上跑的那条路,不能为了测试把它绕开。
holder = (holders or sorted(active))[0]
_wipe_temp(db)
db.add_all([
models.Role(name=ROLE_A, list_auth=[holder]),
# 乙不直接挂人,挂的是甲:绕一层进来的那条要能看出是绕进来的
models.Role(name=ROLE_B, list_auth=[ROLE_A]),
models.Role(name=ROLE_X, list_auth=["(校验-查无此人"]),
models.Group(name=GROUP_C, list_identity=[holder], list_person=[holder]),
])
db.commit()
readcache.invalidate_everywhere()
rev = org.memberships_for(db, [holder])
mine = rev.get(holder, [])
check("同一个人挂两处岗位,反查就给出两处", listed(mine, "role", ROLE_A) and listed(mine, "role", ROLE_B),
str([row["name"] for row in mine]))
via_b = next((row for row in mine if row["name"] == ROLE_B), {})
check("绕经另一处岗位进来的标了来路(direct=false,via 是那个岗位名)",
via_b.get("direct") is False and via_b.get("via") == ROLE_A, str(via_b))
check("同一处岗位在两列成员里各挂一次,也只算一处",
sum(1 for row in mine if row["name"] == GROUP_C) == 1, str(mine))
check("临时岗位正向解析与反查给同一个人",
forward(db, "role", ROLE_A) == [holder] and listed(mine, "role", ROLE_A),
str(forward(db, "role", ROLE_A)))
rev_all, _n = counted(lambda: org.memberships_for(db, sample + extras))
check("成员认不出人时不算成任何人的岗位(与引擎「认不出的人不派活」同一个门)",
not any(row["name"] == ROLE_X for rows in rev_all.values() for row in rows),
str([row for rows in rev_all.values() for row in rows if row["name"] == ROLE_X]))
check("那个挂错成员的岗位正向也解析不出人", forward(db, "role", ROLE_X) == [],
str(forward(db, "role", ROLE_X)))
finally:
db.rollback()
_wipe_temp(db)
def _cleanup(db) -> None:
"""回滚之后另开一条连接复核:库里确实没留下校验用的岗位与分组。"""
probe = SessionLocal()
try:
left = probe.execute(
select(func.count()).select_from(models.Role).where(models.Role.name.like(f"{TEMP_PREFIX}%"))
).scalar_one() + probe.execute(
select(func.count()).select_from(models.Group).where(models.Group.name.like(f"{TEMP_PREFIX}%"))
).scalar_one()
check("收尾之后库里没留下校验用的临时岗位与分组", left == 0, f"{left} 个")
finally:
probe.close()
print(f"\n共 {PASSED + len(FAILS)} 项,通过 {PASSED},失败 {len(FAILS)}")
for item in FAILS:
print(f" 未通过:{item}")
if __name__ == "__main__":
main()
sys.exit(1 if FAILS else 0)