367 lines
16 KiB
Python
367 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
"""守部门树上「负责人姓名」这一格:复用已读到内存的人员行,但不许因此少认一个人。
|
||
|
||
``GET /org/tree`` 拼人员节点时把 ``users`` 整张读了一次,紧接着 ``_managers_by_id``
|
||
又按 ``users.id`` 把部门负责人读第二次——远端库上这是白跑的一趟十几毫秒。现在负责人
|
||
先到本次请求已经 load 的那批人里找,只对找不到的发一次 ``IN``。
|
||
|
||
省这一趟换来的风险只有一个:**复用集合的口径比负责人查询窄**。树上那批人过过两道筛
|
||
(``status=在职``、剔掉内置系统账号),还可能过过数据范围;负责人查询原本一道都不过。
|
||
所以负责人是停用的人、是内置系统账号、或在本次数据范围之外时,名字必须照样写在部门
|
||
节点上——那是三种真实的库状态(人停了但历史部门还挂他、部门挂着 admin、部门负责人
|
||
只看自己那一支却撞上别支的人当负责人)。这个脚本一次钉四条:
|
||
|
||
1. **报文一字不差**:同一次请求,复用写法与「负责人一律回库问」的老写法,JSON 逐字节相同;
|
||
2. **通常确实少问一条**:超管与部门负责人两种范围下都量;
|
||
3. **三种复用不到的负责人,名字照旧写出来**(停用 / 内置系统账号 / 范围外):临时改动
|
||
全程在未提交事务里,跑完整体回滚,当场复核库里没被动过;
|
||
4. **``/org/units`` 这类没得复用的调用点行为不变**:不传 ``known`` 时口径与老写法一致。
|
||
|
||
cd backend && PYTHONPATH=. python3 scripts/check_org_tree_managers.py
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import sys
|
||
|
||
from sqlalchemy import event, select
|
||
|
||
from app import deps, models, permissions, readcache
|
||
from app.api import org as org_api
|
||
from app.db import SessionLocal, engine
|
||
from app.service import org, personref
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
|
||
#: 数语句条数:这一层买的就是「少排几次队」,判据只看条数。
|
||
ROWS: list[str] = []
|
||
|
||
|
||
#: 顺带记下参数:判"只有查不到的那几个 id 才回库"要看清 IN 里到底塞了谁。
|
||
PARAMS: list[dict] = []
|
||
|
||
|
||
@event.listens_for(engine, "after_cursor_execute")
|
||
def _count(conn, cursor, statement, parameters, context, many): # noqa: ANN001
|
||
ROWS.append(" ".join(statement.split())[:120])
|
||
PARAMS.append(dict(parameters or {}))
|
||
|
||
|
||
def check(label: str, ok: bool, detail: str = "") -> None:
|
||
global PASSED
|
||
if ok:
|
||
PASSED += 1
|
||
print(f"[通过] {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
|
||
|
||
|
||
def cold() -> None:
|
||
"""把只读缓存整场作废:量的总是「第一次问」,不是缓存里的存货。"""
|
||
readcache.invalidate_everywhere()
|
||
|
||
|
||
def counted(fn):
|
||
"""跑一趟,交回 ``(结果, 这一趟问了几条库, 每条的参数)``。"""
|
||
cold()
|
||
start, pstart = len(ROWS), len(PARAMS)
|
||
value = fn()
|
||
return value, len(ROWS) - start, PARAMS[pstart:]
|
||
|
||
|
||
def in_values(params: list[dict]) -> set:
|
||
"""把那次 ``IN`` 里塞进去的值抠出来(SQLAlchemy 会展开成 id_1、id_2…)。"""
|
||
out: set = set()
|
||
for row in params:
|
||
for key, value in row.items():
|
||
if str(key).startswith("id_") and isinstance(value, int):
|
||
out.add(value)
|
||
return out
|
||
|
||
|
||
#: 改造前 ``_managers_by_id`` 的写法:负责人一律回库问,不看内存里有没有。
|
||
def managers_by_id_from_db(db, units, known=()):
|
||
ids = sorted({int(row.manager_person_id) for row in units if row.manager_person_id})
|
||
if not ids:
|
||
return {}
|
||
return {
|
||
row.id: row
|
||
for row in db.execute(select(models.User).where(models.User.id.in_(ids))).scalars().all()
|
||
}
|
||
|
||
|
||
_current = org_api._managers_by_id
|
||
|
||
|
||
def as_old_style():
|
||
"""临时把实现换回老写法,用来交回"改造前"的那份报文。"""
|
||
org_api._managers_by_id = managers_by_id_from_db
|
||
|
||
|
||
def as_new_style():
|
||
org_api._managers_by_id = _current
|
||
|
||
|
||
def tree(db, user, warm: bool = True) -> tuple[str, int]:
|
||
"""跑一次 ``GET /org/tree``,交回 ``(逐字节报文, 这一趟问了几条库)``。
|
||
|
||
``warm`` 的那一趟先跑不收:Session 级的一次性读取(内置账号名走的那条
|
||
``oa_system_setting``)只在第一次发生,先抹平它,两个写法量的才是同一件事。
|
||
量本身连量两趟取小的那个——见函数体里那句注释。
|
||
"""
|
||
if warm:
|
||
cold()
|
||
org_api.unit_tree(db=db, user=user)
|
||
best: tuple[str, int] | None = None
|
||
for _ in range(2):
|
||
# 连跑两趟取问得少的那一趟:Redis 那层恰好过期时,其中一趟会多问一条,
|
||
# 那个数不是这一层的成本。真退步的话两趟都长,取小值挡不住它。
|
||
cold()
|
||
start = len(ROWS)
|
||
payload = org_api.unit_tree(db=db, user=user)
|
||
taken = (json.dumps(payload, ensure_ascii=False), len(ROWS) - start)
|
||
if best is None or taken[1] < best[1]:
|
||
best = taken
|
||
assert best is not None
|
||
return best
|
||
|
||
|
||
def manager_names(payload_json: str) -> dict[str, str]:
|
||
"""部门节点 id -> 负责人姓名,从报文里读出来(判"名字还在不在"用)。"""
|
||
out: dict[str, str] = {}
|
||
|
||
def walk(nodes):
|
||
for node in nodes:
|
||
if node.get("type") == "unit":
|
||
out[str(node["id"])] = str(node.get("manager_name") or "")
|
||
walk(node.get("children") or [])
|
||
|
||
walk(json.loads(payload_json)["data"])
|
||
return out
|
||
|
||
|
||
def pick_admin(db):
|
||
"""内置超管:账号名是部署自己定的(``[seed] admin_account``),所以按"系统账号里的那个"找。"""
|
||
row = db.execute(
|
||
select(models.User)
|
||
.where(models.User.account.in_(org.system_account_names()))
|
||
.order_by(models.User.id)
|
||
).scalars().first()
|
||
if row is None:
|
||
row = db.execute(
|
||
select(models.User).where(models.User.role == models.ROLE_ADMIN).order_by(models.User.id)
|
||
).scalars().first()
|
||
return deps.CurrentUser.resolve(db, row, personref.ref_of(row)) if row else None
|
||
|
||
|
||
def pick_restricted(db):
|
||
"""一个数据范围真受限的人:不受限就量不出「负责人在范围外」那一条。"""
|
||
rows = db.execute(
|
||
select(models.User)
|
||
.where(models.User.role != models.ROLE_ADMIN,
|
||
models.User.status == models.UserStatus.ACTIVE,
|
||
models.User.organization_id.is_not(None))
|
||
.order_by(models.User.id)
|
||
).scalars().all()
|
||
for person in rows:
|
||
user = deps.CurrentUser.resolve(db, person, personref.ref_of(person))
|
||
if not permissions.unrestricted(user):
|
||
return user
|
||
return None
|
||
|
||
|
||
def same_payload(db, user, label: str) -> int:
|
||
"""老写法与新写法各跑一趟:报文必须逐字节相同,新写法必须少问库。"""
|
||
as_old_style()
|
||
try:
|
||
old_json, old_stmts = tree(db, user)
|
||
finally:
|
||
as_new_style()
|
||
new_json, new_stmts = tree(db, user)
|
||
check(f"{label}:报文与逐条问库逐字节相同", new_json == old_json,
|
||
f"长度 {len(new_json)} vs {len(old_json)}")
|
||
return new_stmts - old_stmts
|
||
|
||
|
||
def main() -> int:
|
||
db = SessionLocal()
|
||
try:
|
||
admin, scoped = pick_admin(db), pick_restricted(db)
|
||
check("样例账号在位:一个超管 + 一个数据范围真受限的人",
|
||
admin is not None and scoped is not None and admin.is_admin and not scoped.is_admin,
|
||
f"admin={admin and admin.account} scoped={scoped and scoped.account}")
|
||
|
||
# ---- 1 / 2:常态下报文相同、条数更少 --------------------------------
|
||
delta_admin = same_payload(db, admin, "超管看全公司")
|
||
delta_scoped = same_payload(db, scoped, "非超管按数据范围")
|
||
check(f"超管:复用人员行确实少问库(差 {delta_admin} 条)", delta_admin < 0, f"{delta_admin}")
|
||
check(f"非超管:这一趟不许变慢(差 {delta_scoped} 条)", delta_scoped <= 0, f"{delta_scoped}")
|
||
|
||
# 常态报文里得真有负责人,否则"名字还在"这三条是空跑
|
||
names = manager_names(tree(db, admin)[0])
|
||
check("样例数据里有挂着负责人的部门", any(names.values()), str(names))
|
||
|
||
units = db.execute(
|
||
select(models.Unit).where(models.Unit.manager_person_id.is_not(None))
|
||
.order_by(models.Unit.id)
|
||
).scalars().all()
|
||
anchor = units[0]
|
||
unit_id, original = anchor.id, anchor.manager_person_id
|
||
|
||
# ---- 3:三种复用不到的负责人 ----------------------------------------
|
||
try:
|
||
# (a) 负责人停用:树上没有他这一行,名字还得写在部门节点上
|
||
victim = db.execute(
|
||
select(models.User)
|
||
.where(models.User.status == models.UserStatus.ACTIVE,
|
||
models.User.account.not_in(org.system_account_names()))
|
||
.order_by(models.User.id.desc())
|
||
).scalars().first()
|
||
check("找得到一个人可临时改成停用", victim is not None)
|
||
if victim is not None:
|
||
anchor.manager_person_id = victim.id
|
||
victim.status = models.UserStatus.DISABLED
|
||
db.flush()
|
||
as_old_style()
|
||
try:
|
||
old_json, old_stmts = tree(db, admin)
|
||
finally:
|
||
as_new_style()
|
||
new_json, new_stmts = tree(db, admin)
|
||
check("负责人停用:报文与老写法逐字节相同",
|
||
new_json == old_json
|
||
and manager_names(new_json)[str(unit_id)] == victim.display_name,
|
||
f"实得「{manager_names(new_json)[str(unit_id)]}」期望「{victim.display_name}」")
|
||
check(f"负责人停用:这一趟照样回库问({old_stmts} → {new_stmts} 条)",
|
||
new_stmts == old_stmts, f"{old_stmts} → {new_stmts}")
|
||
db.rollback()
|
||
|
||
# (b) 负责人是内置系统账号:树上剔掉了他,名字还得在
|
||
db.refresh(anchor)
|
||
system_person = db.execute(
|
||
select(models.User).where(models.User.account.in_(org.system_account_names()))
|
||
.order_by(models.User.id)
|
||
).scalars().first()
|
||
check("找得到一个内置系统账号", system_person is not None)
|
||
if system_person is not None:
|
||
anchor.manager_person_id = system_person.id
|
||
db.flush()
|
||
as_old_style()
|
||
try:
|
||
old_json, _ = tree(db, admin)
|
||
finally:
|
||
as_new_style()
|
||
new_json, new_stmts = tree(db, admin)
|
||
check("负责人是内置系统账号:报文与老写法逐字节相同",
|
||
new_json == old_json
|
||
and manager_names(new_json)[str(unit_id)] == system_person.display_name,
|
||
f"实得「{manager_names(new_json)[str(unit_id)]}」"
|
||
f"期望「{system_person.display_name}」")
|
||
db.rollback()
|
||
|
||
# (c) 负责人在本次数据范围之外:非超管看不见他,名字还得在
|
||
db.refresh(anchor)
|
||
outsider = db.execute(
|
||
select(models.User)
|
||
.where(models.User.status == models.UserStatus.ACTIVE,
|
||
models.User.account.not_in(org.system_account_names()),
|
||
models.User.id != scoped.person_id)
|
||
.order_by(models.User.id)
|
||
).scalars().first()
|
||
# 只挑本次报文里真看得见的部门:看不见的那个部门本来就不该写名字
|
||
visible_ids = [
|
||
key for key, _name in manager_names(tree(db, scoped)[0]).items()
|
||
]
|
||
scoped_unit = db.execute(
|
||
select(models.Unit)
|
||
.where(models.Unit.id.in_([models.as_id(v) for v in visible_ids]))
|
||
.order_by(models.Unit.id)
|
||
).scalars().first()
|
||
check("找得到一个范围外的在职人,以及一个范围内看得见的部门",
|
||
outsider is not None and scoped_unit is not None)
|
||
if outsider is not None and scoped_unit is not None:
|
||
scoped_unit_id = scoped_unit.id
|
||
scoped_unit.manager_person_id = outsider.id
|
||
db.flush()
|
||
as_old_style()
|
||
try:
|
||
old_json, old_stmts = tree(db, scoped)
|
||
finally:
|
||
as_new_style()
|
||
new_json, new_stmts = tree(db, scoped)
|
||
check("负责人在范围外:报文与老写法逐字节相同", new_json == old_json)
|
||
check("负责人在范围外:名字仍写在部门节点上",
|
||
manager_names(new_json)[str(scoped_unit_id)] == outsider.display_name,
|
||
f"实得「{manager_names(new_json)[str(scoped_unit_id)]}」"
|
||
f"期望「{outsider.display_name}」")
|
||
check(f"负责人在范围外:这一趟照样回库问({old_stmts} → {new_stmts} 条)",
|
||
new_stmts == old_stmts, f"{old_stmts} → {new_stmts}")
|
||
db.rollback()
|
||
finally:
|
||
db.rollback()
|
||
back = db.execute(select(models.Unit.manager_person_id).where(models.Unit.id == unit_id)).scalar()
|
||
check("跑完库里负责人没被动过", back == original, f"{back} != {original}")
|
||
|
||
# ---- 4:没得复用的调用点(``/org/units``)口径不变 -------------------
|
||
rows = db.execute(select(models.Unit)).scalars().all()
|
||
want = managers_by_id_from_db(db, rows)
|
||
got = _current(db, rows)
|
||
check("不传 known 时与老写法取到同一批负责人",
|
||
sorted(want) == sorted(got) and all(want[k] is got[k] for k in want),
|
||
f"{sorted(want)} vs {sorted(got)}")
|
||
check("没有负责人时不问库", _current(db, []) == {} and managers_by_id_from_db(db, []) == {})
|
||
|
||
# ---- 5:该问的才问 ----
|
||
active = db.execute(
|
||
select(models.User)
|
||
.where(models.User.status == models.UserStatus.ACTIVE,
|
||
models.User.account.not_in(org.system_account_names()))
|
||
.order_by(models.User.id).limit(2)
|
||
).scalars().all()
|
||
anchor_unit = db.get(models.Unit, unit_id)
|
||
check("找得到两个人:一个用来复用、一个用来验「该问的才问」", len(active) >= 2,
|
||
f"只找到 {len(active)} 个在职人")
|
||
if len(active) >= 2:
|
||
holder, other_person = active[0], active[1]
|
||
original_manager = anchor_unit.manager_person_id
|
||
try:
|
||
anchor_unit.manager_person_id = holder.id
|
||
db.flush()
|
||
_got, trips, _p = counted(lambda: _current(db, [anchor_unit], known=[holder]))
|
||
check(f"负责人已在内存里:一条都不问({trips} 条)", trips == 0, f"{trips}")
|
||
other = db.execute(
|
||
select(models.Unit).where(models.Unit.id != anchor_unit.id)
|
||
.order_by(models.Unit.id).limit(1)
|
||
).scalars().first()
|
||
original_other = other.manager_person_id
|
||
try:
|
||
# 第二个部门挂一个不在内存里的人:只有他该被回库问到
|
||
other.manager_person_id = other_person.id
|
||
db.flush()
|
||
got, trips2, params = counted(
|
||
lambda: _current(db, [anchor_unit, other], known=[holder]))
|
||
check(f"一半复用得到、一半复用不到:只问查不到的那一个({trips2} 条)",
|
||
trips2 == 1, f"{trips2}")
|
||
check("回库那一次问的只有那一个不在内存里的人",
|
||
in_values(params) == {other_person.id}
|
||
and got.get(holder.id) is holder
|
||
and got.get(other_person.id).id == other_person.id,
|
||
f"IN 里是 {sorted(in_values(params))},期望 {{{other_person.id}}}")
|
||
finally:
|
||
other.manager_person_id = original_other
|
||
db.flush()
|
||
finally:
|
||
anchor_unit.manager_person_id = original_manager
|
||
db.rollback()
|
||
return 1 if FAILS else 0
|
||
finally:
|
||
as_new_style()
|
||
db.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|