unis-oa/backend/scripts/check_hub_sync_unit_reclaim.py

335 lines
17 KiB
Python
Raw Permalink 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
"""守「Hub 把 organization_id 整体换了号之后,组织架构会不会裂成两棵树」。
踩过的坑:Hub 重导一遍数据、或者合并过一次组织,``organization_id`` 会整体换号
(实测测试站 2026-11-04:25~36 变成 2~13)。本地只按主键认部门,认不出来就整棵树再建一遍,
于是组织架构页上出现两个「紫光汇智」:一套停用的老部门(真库留了 12 组),一套带人的新部门。
人是搬过去了,但**按 ``oa_unit.id`` 配的数据范围、按部门配的审批规则与部门负责人留在老行上**,
不报错,只是悄悄解析不到人;按部门路径存的引用也会指到那条已经空了的支路上。
修好的口径在 :func:`app.service.hub_sync._sync_units`:开了「按编码认领本地部门」
(``OA_HUB_SYNC_BIND_LOCAL_BY_CODE``)时,**编码与名称都对得上、而原主键已经不在这趟清单里**的
老部门会被认回来(换新主键,本地 ``oa_unit.id`` 不动)。钉二十条::
cd backend && PYTHONPATH=. python3 scripts/check_hub_sync_unit_reclaim.py
1. 换了主键的老部门被认回来,不新建;
2. 认回来只换 ``hub_org_id``:本地部门主键、名字与挂在它下面的人都留在原地;
3. 子部门跟着父部门一起接上,``path`` / 部门 DN 重算;
4. 停用的老部门被认回来时状态跟着 Hub 恢复;
5. 名称对不上就不认(按新部门建,老行停用),不靠编码硬猜;
6. 编码对不上同理不认;
7. 同名同编码有好几个僵尸、而且分不出谁住着人时不猜,按新部门建;只有一支底下挂着人时认那一支;
8. 这个编码名称已经被活部门占了时不再认第三次(真库那 12 组重复就是这种状态);
9. 编码名称都对不上的老部门照旧按「Hub 已消失」停用;
10. 认领汇总只写一条同步记录,逐部门一条会把 20 条上限刷满;
11. 再跑同一份清单不重复认领、不重复建号;
12. 关掉「按编码认领」就退回老行为(新建一套);
13. 清单里没有组织时一个都不认("不在清单里"证明不了任何事);
14. 认回来的部门不会被这一趟判成已消失;
15. 认领之后一个 Hub 组织仍然只对一个本地部门(唯一索引没被绕开);
16. 认领不会撞 ``uq_oa_unit_hub_org_id``(旧主键当场让开);
17. **部门停用熔断**:一趟要停用的部门超过上限 → 一个都不停,只报数并把这趟标成部分完成;
18. **熔断设 0 就关掉**:核对过清单没问题,照样能回到"照单停用";
19. **只有一支壳子住着人时认那一支**;
20. **被熔断挡下来的那趟以「部分完成」收口**:少干了活必须看得见。
全程待在同一个事务里,跑完 ``rollback``,库里不留任何临时部门。
"""
from __future__ import annotations
import dataclasses
import pathlib
import sys
from datetime import datetime
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from sqlalchemy import select # noqa: E402
from app import hubconfig, models # noqa: E402
from app.db import SessionLocal # noqa: E402
from app.service import hub_sync # noqa: E402
MARK = "zzunit-"
FAILS: list[str] = []
PASSED = 0
# 这批检查自己占的 Hub 组织主键段:真库的 organization_id 在个位数~几十这一段
OLD = {"a": 930001, "b": 930002, "c": 930003, "d1": 930004, "d2": 930005,
"live_e": 930006, "ghost_e": 930007, "g": 930008, "f": 930009}
NEW = {"a": 931001, "b": 931002, "c": 931003, "d": 931004, "e": 931005, "f": 931006}
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 add_unit(db, code, name, *, hub_org_id=None, parent=None, status=int(models.UnitStatus.ACTIVE)): # noqa: ANN001
row = models.Unit(
name=name,
code=code,
alias=code,
description="让位检查",
parent_id=parent.id if parent else None,
hub_org_id=hub_org_id,
status=status,
)
db.add(row)
db.flush()
return row
def org_node(hub_id, code, name, *, parent_id=None, status=1) -> dict:
return {
"organization_id": hub_id,
"code": code,
"name": name,
"status": status,
"parent_id": parent_id,
}
def shadow_orgs(db) -> list[dict]: # noqa: ANN001
"""把库里已有的 Hub 部门照本地现状列进清单,免得检查数字被真库那 26 个部门搅浑。"""
rows = db.execute(
select(models.Unit).where(models.Unit.hub_org_id.is_not(None))
).scalars().all()
by_id = {row.id: row for row in rows}
out = []
for row in rows:
parent = by_id.get(row.parent_id) if row.parent_id else None
out.append(
org_node(
int(row.hub_org_id),
str(row.code or ""),
str(row.name or ""),
parent_id=int(parent.hub_org_id) if parent and parent.hub_org_id else None,
status=1 if row.status == models.UnitStatus.ACTIVE else 0,
)
)
return out
def use_cfg(**patch: object) -> None:
"""把 ``hubconfig.get`` 换成一份改过几项的配置,其余字段照原样带着。"""
hubconfig.get = ( # type: ignore[assignment]
lambda db=None, _patch=patch: dataclasses.replace(cfg_obj, **_patch) # noqa: B023
)
def main() -> int:
global cfg_obj
real_get = hubconfig.get
base_cfg = real_get()
cfg_obj = dataclasses.replace(base_cfg, hub_sync_bind_local_by_code=True)
use_cfg()
db = SessionLocal()
now = datetime.now()
try:
# 先把真库已有的 Hub 部门照现状列进清单:它们这一趟都该"对得上号",
# 不然检查数字会被真库那 26 个部门搅浑。注意要在造临时部门之前拍这张快照,
# 否则这批 93000x 的老主键会被当成"还在清单里",僵尸判定就试不出来了。
base_shadow = shadow_orgs(db)
# ---- 本地现状:Hub 换号之前那一套部门(老主键 93000x) ----
unit_a = add_unit(db, f"{MARK}a", "换号甲", hub_org_id=OLD["a"],
status=int(models.UnitStatus.DISABLED)) # 上一趟被判成已消失、已停用
unit_b = add_unit(db, f"{MARK}b", "换号乙", hub_org_id=OLD["b"], parent=unit_a)
person = db.execute(
select(models.User).where(models.User.source == models.AccountSource.HUB)
).scalars().first()
person.organization_id = unit_b.id
unit_c = add_unit(db, f"{MARK}c", "老名字丙", hub_org_id=OLD["c"])
unit_d1 = add_unit(db, f"{MARK}d", "换号丁", hub_org_id=OLD["d1"])
unit_d2 = add_unit(db, f"{MARK}d", "换号丁", hub_org_id=OLD["d2"])
unit_live_e = add_unit(db, f"{MARK}e", "换号戊", hub_org_id=OLD["live_e"])
unit_ghost_e = add_unit(db, f"{MARK}e", "换号戊", hub_org_id=OLD["ghost_e"],
status=int(models.UnitStatus.DISABLED))
unit_g = add_unit(db, f"{MARK}g", "彻底没了", hub_org_id=OLD["g"])
unit_f = add_unit(db, f"{MARK}f", "关掉开关", hub_org_id=OLD["f"])
db.flush()
# Hub 换号之后的清单:主键全换成 93100x,编码与名称原样
nodes = base_shadow + [
org_node(NEW["a"], f"{MARK}a", "换号甲"),
org_node(NEW["b"], f"{MARK}b", "换号乙", parent_id=NEW["a"]),
org_node(NEW["c"], f"{MARK}c", "改了名字丙"), # 名称对不上 -> 不认
org_node(NEW["d"], f"{MARK}d", "换号丁"), # 两个僵尸 -> 不猜
org_node(NEW["e"], f"{MARK}e", "换号戊"), # 已经被活部门占了 -> 不认第三次
org_node(OLD["live_e"], f"{MARK}e", "换号戊"), # 活的那一支:主键还在清单里
]
stats = hub_sync.SyncStats(started_at=now)
mapped = hub_sync._sync_units(db, nodes, stats)
db.flush()
check("① 换了主键的老部门被认回来,没有新建",
mapped.get(NEW["a"]) == unit_a.id and mapped.get(NEW["b"]) == unit_b.id
and stats.units_rebound == 2 and stats.units_bound == 2,
f"rebound={stats.units_rebound} bound={stats.units_bound} mapped={mapped.get(NEW['a'])}/{unit_a.id}")
check("⑥ 编码对不上的老部门不认,按新部门建",
stats.units_created == 3, # 丙(改名)、丁(歧义)、戊(busy)
f"created={stats.units_created}")
check("② 本地部门主键与名称没动,人还在原来那个部门下",
unit_a.hub_org_id == NEW["a"] and unit_a.name == "换号甲"
and unit_b.hub_org_id == NEW["b"] and person.organization_id == unit_b.id,
f"hub={unit_a.hub_org_id} person_unit={person.organization_id}")
check("③ 子部门跟着接上,path 一起重算",
unit_b.parent_id == unit_a.id and unit_b.path.endswith("换号乙\\"),
f"parent={unit_b.parent_id} path={unit_b.path}")
check("④ 停用的老部门被认回来时状态跟着 Hub 恢复",
unit_a.status == models.UnitStatus.ACTIVE, f"status={unit_a.status}")
check("⑤ 名称对不上就不认:老行走停用、按新部门建",
unit_c.status == models.UnitStatus.DISABLED
and mapped.get(NEW["c"]) not in (None, unit_c.id),
f"c_status={unit_c.status} new={mapped.get(NEW['c'])}")
check("⑦ 同名同编码有好几个僵尸时不猜",
mapped.get(NEW["d"]) not in (unit_d1.id, unit_d2.id)
and unit_d1.status == models.UnitStatus.DISABLED
and unit_d2.status == models.UnitStatus.DISABLED,
f"new={mapped.get(NEW['d'])} d1={unit_d1.status} d2={unit_d2.status}")
check("⑧ 这个编码名称已经被活部门占了:不再认第三次",
unit_live_e.hub_org_id == OLD["live_e"]
and unit_live_e.status == models.UnitStatus.ACTIVE
and mapped.get(NEW["e"]) not in (unit_ghost_e.id,),
f"live_hub={unit_live_e.hub_org_id} new={mapped.get(NEW['e'])}")
check("⑨ 编码名称都对不上的老部门照旧停用",
unit_g.status == models.UnitStatus.DISABLED, f"g_status={unit_g.status}")
check("⑩ 认领汇总只写一条同步记录",
sum("认回了原部门" in text for text in stats.messages) == 1,
str([t for t in stats.messages if "认回" in t]))
check("⑯ 认领没撞唯一键:旧主键当场让开",
db.execute(select(models.Unit).where(models.Unit.hub_org_id == OLD["a"])).scalar() is None,
"旧 Hub 主键还被占着")
# 这一趟该停用的只有对不上号的五具壳子(丙/丁×2/彻底没了/关掉开关),
# 认回来的甲乙不在其中
check("⑭ 认回来的部门不会被这一趟判成已消失",
stats.units_offboarded == 5
and unit_a.status == models.UnitStatus.ACTIVE
and unit_b.status == models.UnitStatus.ACTIVE,
f"offboarded={stats.units_offboarded} a={unit_a.status} b={unit_b.status}")
# ⑪ 幂等:同一份清单再跑一遍,一个部门都不该再动
again = hub_sync.SyncStats(started_at=now)
hub_sync._sync_units(db, nodes, again)
check("⑪ 再跑一遍不重复认领、不重复建号、不重复停用",
again.units_rebound == 0 and again.units_created == 0
and again.units_offboarded == 0 and again.units_updated == 0,
f"rebound={again.units_rebound} created={again.units_created} "
f"offboarded={again.units_offboarded} updated={again.units_updated}")
# ⑮ 认领完还是一个 Hub 组织对一个部门(uq_oa_unit_hub_org_id 没被绕开)。
# 库上有唯一索引,"一个组织两个部门"那种历史脏行在这套 schema 上已经插不进来了。
from sqlalchemy import func # 就地用一次,别顶到文件头去
holders = {
hub_id: int(
db.execute(
select(func.count())
.select_from(models.Unit)
.where(models.Unit.hub_org_id == hub_id)
).scalar_one()
)
for hub_id in (NEW["a"], NEW["b"], OLD["a"], OLD["b"])
}
check("⑮ 认领之后一个 Hub 组织只对一个部门",
holders[NEW["a"]] == 1 and holders[NEW["b"]] == 1
and holders[OLD["a"]] == 0 and holders[OLD["b"]] == 0,
str(holders))
# ⑫ 关掉「按编码认领」就退回老行为
use_cfg(hub_sync_bind_local_by_code=False)
nodes_off = base_shadow + [org_node(NEW["f"], f"{MARK}f", "关掉开关")]
off = hub_sync.SyncStats(started_at=now)
mapped_off = hub_sync._sync_units(db, nodes_off, off)
check("⑫ 开关关掉之后不认领,按新部门建",
off.units_rebound == 0 and mapped_off.get(NEW["f"]) not in (None, unit_f.id)
and unit_f.hub_org_id == OLD["f"],
f"rebound={off.units_rebound} new={mapped_off.get(NEW['f'])} hub={unit_f.hub_org_id}")
# ⑬ 清单里一个组织都没有:不认、不新建
use_cfg()
empty = hub_sync.SyncStats(started_at=now)
hub_sync._sync_units(db, [], empty)
check("⑬ 空清单不认领任何部门", empty.units_rebound == 0 and empty.units_bound == 0,
f"rebound={empty.units_rebound} bound={empty.units_bound}")
# ⑲ 同码同名的壳子分不出谁是谁时看谁住着人:真库那 12 组重复就是这种形状
shell_t1 = add_unit(db, f"{MARK}t", "换号己", hub_org_id=930021,
status=int(models.UnitStatus.DISABLED))
shell_t2 = add_unit(db, f"{MARK}t", "换号己", hub_org_id=930022,
status=int(models.UnitStatus.DISABLED))
person.organization_id = shell_t2.id # 只有这一支底下还住着人
db.flush()
tie = hub_sync.SyncStats(started_at=now)
mapped_tie = hub_sync._sync_units(
db, base_shadow + [org_node(931011, f"{MARK}t", "换号己")], tie
)
check("⑲ 只有一支壳子底下挂着人时认那一支",
tie.units_rebound == 1 and mapped_tie.get(931011) == shell_t2.id
and shell_t2.hub_org_id == 931011
and shell_t1.status == models.UnitStatus.DISABLED,
f"rebound={tie.units_rebound} 认到={mapped_tie.get(931011)}/{shell_t2.id}")
# ⑰⑱ 部门停用熔断:Hub 目录少了一批组织时,别一声不响把半棵树停掉
fuse = [
add_unit(db, f"{MARK}fuse{i}", f"熔断部门{i}", hub_org_id=930010 + i)
for i in range(1, 7)
]
db.flush()
# 熔断这一段用"所有部门都在清单里"的节点表,只留那六个新壳子当等着停用的人数
fuse_nodes = nodes + [
org_node(NEW["f"], f"{MARK}f", "关掉开关"),
org_node(931011, f"{MARK}t", "换号己"),
]
use_cfg(hub_sync_offboard_guard_percent=1) # 上限退到绝对下限 5 个,六个就能触发
fuse_stats = hub_sync.SyncStats(started_at=now)
hub_sync._sync_units(db, fuse_nodes, fuse_stats)
check("⑰ 六个部门超过熔断上限(5 个)时一个都不停用",
fuse_stats.units_offboarded == 0 and fuse_stats.units_offboard_guarded == 6
and all(row.status == models.UnitStatus.ACTIVE for row in fuse),
f"offboarded={fuse_stats.units_offboarded} guarded={fuse_stats.units_offboard_guarded}")
check("⑰ 熔断那条写清了个数与出口",
any("部门停用熔断线" in text and "OFFBOARD_GUARD_PERCENT" in text
for text in fuse_stats.messages),
str([t for t in fuse_stats.messages if "熔断" in t][:1]))
check("⑳ 被熔断挡下来的那趟以「部分完成」收口",
hub_sync._run_status(fuse_stats) == models.HubSyncRun.STATUS_PARTIAL
and hub_sync._run_status(hub_sync.SyncStats(started_at=now))
== models.HubSyncRun.STATUS_SUCCESS,
hub_sync._run_status(fuse_stats))
use_cfg(hub_sync_offboard_guard_percent=0)
off_stats = hub_sync.SyncStats(started_at=now)
hub_sync._sync_units(db, fuse_nodes, off_stats)
check("⑱ 熔断设 0 之后照单停用",
off_stats.units_offboarded == 6
and all(row.status == models.UnitStatus.DISABLED for row in fuse),
f"offboarded={off_stats.units_offboarded}")
finally:
cfg_obj = base_cfg
hubconfig.get = real_get # type: ignore[assignment]
db.rollback()
db.close()
print()
if FAILS:
print(f"未通过 {len(FAILS)} 项:")
for name in FAILS:
print(f" - {name}")
return 1
print(f"全部通过({PASSED} 项):Hub 换组织主键之后认回原部门,组织架构不再裂成两棵树。")
return 0
if __name__ == "__main__":
raise SystemExit(main())