2438 lines
104 KiB
Python
2438 lines
104 KiB
Python
"""Hub 组织人员镜像同步(夜间定时 + 一键实时)。
|
||
|
||
对端口径见《Hub 权限接口交互文档》第 11 节:``GET /api/v1/auth/directory`` 一次
|
||
返回完整组织树和同一批人员的扁平清单。落库规则按文档的六条约定来:
|
||
|
||
* 人员以扁平清单 ``users`` 为准(合成节点 ``organization_id=0`` 里也带着真实部门);
|
||
* ``status`` 非 1 一律置为本地「已停用」,不删除账号;
|
||
* ``truncated`` 为真时清单不完整,只写不撤,绝不按截断结果下线本地人员;
|
||
* ``permission_version`` 没变化时定时任务跳过写入,手动「立即同步」永远强拉;
|
||
* 组织层级成环靠深度上限挡住,不做静默丢弃;
|
||
* 部门同理:Hub 已经不存在的同步部门(``oa_unit.hub_org_id`` 不为空且没出现在这次导出
|
||
里)在清单完整时置为停用,本地自建部门(``hub_org_id`` 为空)永远不碰。
|
||
|
||
凭证:全量目录接口(文档第 11 节)现在用长期密钥认服务端调用——配了「目录密钥」
|
||
(``hub_directory_key`` / ``OA_HUB_DIRECTORY_KEY``)就以请求头 ``X-Directory-Key`` 带出去,
|
||
同步记录里写 ``credential=directory_key``,不必登录换 token。没配密钥才退回老的
|
||
Bearer 口径(长期 token 或集成账号登录换 token),两者都没有就是匿名拉,只在对方
|
||
不校验的部署上拉得到(``credential=anonymous``)。
|
||
|
||
本地账号的边界:只有 ``users.source='hub'`` 的账号会被同步改名、换部门、停用;
|
||
本地手工建的账号靠 ``account`` 唯一键被「认领」(认领后同样标成 ``hub``),而
|
||
``role='admin'`` 的超管默认受 ``OA_HUB_SYNC_PROTECT_ADMINS`` 保护,同步碰不到,
|
||
免得哪天 Hub 里没有 admin 就把系统锁死。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import secrets
|
||
import threading
|
||
from collections.abc import Iterator
|
||
from dataclasses import dataclass, field
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
from sqlalchemy import delete, func, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import hubconfig
|
||
from .. import models
|
||
from ..security import hash_password
|
||
from . import hub as hub_api
|
||
from . import hub_refs
|
||
from . import hub_perm
|
||
from . import org
|
||
from . import sso_handoff
|
||
from . import sync_jobs
|
||
|
||
logger = logging.getLogger("unisoa.hub.sync")
|
||
|
||
# permission_version 等运行态放在系统设置里,避免为两个数字再建一张表。
|
||
STATE_KEY = "hub_directory"
|
||
|
||
# Hub 组织节点的合成节点:未分配组织的人挂在这里,本地不建对应部门。
|
||
UNASSIGNED = "unassigned"
|
||
|
||
_run_lock = threading.Lock()
|
||
|
||
|
||
class HubSyncError(Exception):
|
||
"""同步没能跑完(配置缺失、Hub 不可用、数据不完整等)。"""
|
||
|
||
|
||
@dataclass
|
||
class SyncStats:
|
||
total_users: int = 0
|
||
returned_users: int = 0
|
||
created: int = 0
|
||
updated: int = 0
|
||
adopted: int = 0
|
||
offboarded: int = 0
|
||
units_created: int = 0
|
||
units_updated: int = 0
|
||
units_offboarded: int = 0
|
||
units_bound: int = 0
|
||
units_unbound: int = 0
|
||
units_local: int = 0
|
||
units_local_hanging: int = 0
|
||
skipped: int = 0
|
||
protected: int = 0
|
||
#: Hub 那边有人跟应急账号(``hub_local_accounts``,存在库里)同名,账号名让给本地,不认领
|
||
emergency: int = 0
|
||
# 人员身份只看 Hub 主键,下面几项都是"主键对不上/主键要动别的引用"的情形,
|
||
# 同步记录里出现就说明 Hub 那边数据有问题,值得点进详情看一眼。
|
||
no_hub_id: int = 0
|
||
renamed: int = 0
|
||
conflicts: int = 0
|
||
unbound: int = 0
|
||
# 这次同步改过的名字:老值 -> 新值。审批岗位、岗位组、代理人这些是按字符串
|
||
# 存人员的,同步完要照着这几张表把它们一起搬走,见 service/hub_refs.py。
|
||
display_name_map: dict[str, str] = field(default_factory=dict)
|
||
dn_map: dict[str, str] = field(default_factory=dict)
|
||
path_map: dict[str, str] = field(default_factory=dict)
|
||
unit_name_map: dict[str, str] = field(default_factory=dict)
|
||
account_map: dict[str, str] = field(default_factory=dict)
|
||
refs_rewritten: int = 0
|
||
refs_ambiguous: int = 0
|
||
permission_version: int = 0
|
||
member_limit: int = 0
|
||
truncated: bool = False
|
||
# 增量轮询(变更流水)专用:这趟停在哪个游标、落了几条、跳过几条
|
||
cursor_seq: int = 0
|
||
changes_applied: int = 0
|
||
changes_skipped: int = 0
|
||
credential: str = "anonymous"
|
||
messages: list[str] = field(default_factory=list)
|
||
|
||
def note(self, text: str) -> None:
|
||
if text and len(self.messages) < 20:
|
||
self.messages.append(text)
|
||
|
||
@property
|
||
def changed(self) -> int:
|
||
return (
|
||
self.created
|
||
+ self.updated
|
||
+ self.offboarded
|
||
+ self.units_created
|
||
+ self.units_updated
|
||
+ self.units_offboarded
|
||
+ self.units_bound
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 运行态
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def state(db: Session) -> dict[str, Any]:
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
value = row.value if row is not None and isinstance(row.value, dict) else {}
|
||
return dict(value)
|
||
|
||
|
||
def set_state(db: Session, patch: dict[str, Any]) -> dict[str, Any]:
|
||
"""往 ``hub_directory`` 这行系统设置里增量写几个键(同步运行态)。"""
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
if row is None:
|
||
row = models.SystemSetting(key=STATE_KEY, value={}, description="Hub 组织人员同步状态")
|
||
db.add(row)
|
||
merged = dict(row.value or {})
|
||
merged.update(patch)
|
||
row.value = merged
|
||
db.commit()
|
||
return merged
|
||
|
||
|
||
def latest_run(db: Session) -> models.HubSyncRun | None:
|
||
return db.execute(
|
||
select(models.HubSyncRun).order_by(models.HubSyncRun.started_at.desc()).limit(1)
|
||
).scalar_one_or_none()
|
||
|
||
|
||
def running() -> bool:
|
||
"""现在是不是有一趟同步正在跑(同一进程内的互斥锁,界面与调度都用它显示状态)。"""
|
||
return _run_lock.locked()
|
||
|
||
|
||
def recent_runs(db: Session, limit: int = 20) -> list[models.HubSyncRun]:
|
||
return list(
|
||
db.execute(
|
||
select(models.HubSyncRun).order_by(models.HubSyncRun.started_at.desc()).limit(limit)
|
||
).scalars().all()
|
||
)
|
||
|
||
|
||
TRIGGER_LABELS = {
|
||
models.HubSyncRun.TRIGGER_SCHEDULE: "定时",
|
||
models.HubSyncRun.TRIGGER_MANUAL: "手动",
|
||
models.HubSyncRun.TRIGGER_CHANGES: "增量",
|
||
}
|
||
|
||
CREDENTIAL_LABELS = {
|
||
"directory_key": "目录密钥(X-Directory-Key)",
|
||
"token": "长期 token",
|
||
"account": "集成账号",
|
||
"anonymous": "匿名(不带凭证)",
|
||
}
|
||
|
||
|
||
def credential_mode() -> str:
|
||
"""拉全量目录用哪种凭证,给状态接口和排障用。"""
|
||
return hubconfig.get().credential_mode
|
||
|
||
|
||
def credential_label(mode: str = "") -> str:
|
||
return CREDENTIAL_LABELS.get(mode or credential_mode(), "匿名(不带凭证)")
|
||
|
||
|
||
def status_payload(db: Session) -> dict[str, Any]:
|
||
cfg = hubconfig.get()
|
||
run = latest_run(db)
|
||
current = state(db)
|
||
return {
|
||
"enabled": cfg.hub_enabled,
|
||
"configured": bool(cfg.hub_base_url),
|
||
"base_url": cfg.hub_base_url,
|
||
"login_mode": cfg.hub_login_mode,
|
||
"login_enabled": cfg.login_on,
|
||
"auto_provision": cfg.hub_auto_provision,
|
||
"verify_token": cfg.hub_verify_token,
|
||
"sync_enabled": cfg.hub_sync_enabled,
|
||
# sync_time 留着只为兼容:排期现在可能是"每周三四"这种,完整口径看下面的 schedule
|
||
"sync_time": cfg.hub_sync_time,
|
||
"schedule": sync_jobs.summary_view(db),
|
||
"sync_orgs": cfg.hub_sync_orgs,
|
||
"sync_offboard": cfg.hub_sync_offboard,
|
||
"member_limit": cfg.hub_sync_member_limit,
|
||
"credential": credential_mode(),
|
||
"credential_label": credential_label(),
|
||
# 目录密钥只回"有没有配",明文从不出接口;没配时同步多半会被 Hub 拒掉
|
||
"directory_key_set": bool(cfg.hub_directory_key),
|
||
"directory_needs_token": cfg.hub_directory_needs_token,
|
||
"password_managed_by_hub": cfg.hub_password_managed_by_hub,
|
||
"timeout_seconds": cfg.hub_timeout_seconds,
|
||
"api_paths": cfg.api_paths,
|
||
# 应急总闸打开时([hub] disabled 或 OA_HUB_DISABLED)其它配置一律让位
|
||
"forced_off": cfg.forced_off,
|
||
"forced_off_reason": hubconfig.forced_off_reason(cfg),
|
||
# 被 OA_HUB_DISABLED 钉住时界面上这个开关是灰的,只有重启摘掉变量才解
|
||
"forced_off_locked": cfg.forced_off_locked,
|
||
# 配置来自哪个文件,页面上写清楚,免得有人在界面上找配置入口
|
||
"config_file": cfg.config_file,
|
||
"protect_admins": cfg.hub_sync_protect_admins,
|
||
"permission_version": int(current.get("permission_version") or 0),
|
||
"total_users": int(current.get("total_users") or 0),
|
||
"running": running(),
|
||
"last_run": None if run is None else serialize_run(run),
|
||
# 免登(门户票据换身份)的配置口径,密钥本身从不出接口
|
||
"sso": sso_status(),
|
||
# 统一身份权限(角色 / 权限码 / 数据范围)这一层的口径
|
||
"permission": hub_perm.status_payload(),
|
||
# 增量同步(变更流水)的当前状态:游标走到哪、落后多少、上次哪时候拉的
|
||
"changes": changes_status(db),
|
||
}
|
||
|
||
|
||
def sso_status() -> dict[str, Any]:
|
||
"""免登通道的配置状态(给状态接口/界面用,应用密钥只回"配了没有")。"""
|
||
cfg = hubconfig.get()
|
||
missing: list[str] = []
|
||
if not cfg.hub_base_url:
|
||
missing.append("Hub 站点地址")
|
||
if not cfg.hub_app_code.strip():
|
||
missing.append("应用编码")
|
||
if not cfg.hub_integration_key.strip():
|
||
missing.append("免登应用密钥")
|
||
return {
|
||
"enabled": cfg.hub_sso_enabled,
|
||
"active": cfg.sso_on,
|
||
"only": cfg.sso_only,
|
||
"configured": cfg.sso_ready,
|
||
"missing": missing,
|
||
"app_code": cfg.hub_app_code,
|
||
"integration_key_set": bool(cfg.hub_integration_key.strip()),
|
||
"portal_url": cfg.portal_url,
|
||
"state_required": cfg.hub_sso_state_required,
|
||
"verify_path": cfg.hub_path_ticket_verify,
|
||
# launch_path 是按本系统应用编码算好的那一条,template 是配置里的原始写法
|
||
"launch_path": cfg.launch_path(),
|
||
"launch_path_template": cfg.hub_path_launch,
|
||
"auto_provision": cfg.hub_auto_provision,
|
||
# 免登落地的三条本系统地址(后端回调 / 别名 / 前端落地页),管理员照抄进 Hub
|
||
**sso_handoff.view(),
|
||
}
|
||
|
||
|
||
def serialize_run(row: models.HubSyncRun) -> dict[str, Any]:
|
||
return {
|
||
"id": row.id,
|
||
"trigger": row.trigger,
|
||
"trigger_label": TRIGGER_LABELS.get(row.trigger, row.trigger),
|
||
"status": row.status,
|
||
"started_at": row.started_at.strftime("%Y-%m-%d %H:%M:%S") if row.started_at else "",
|
||
"finished_at": row.finished_at.strftime("%Y-%m-%d %H:%M:%S") if row.finished_at else "",
|
||
"duration_ms": row.duration_ms,
|
||
"total_users": row.total_users,
|
||
"returned_users": row.returned_users,
|
||
"created": row.created,
|
||
"updated": row.updated,
|
||
"offboarded": row.offboarded,
|
||
"units_created": row.units_created,
|
||
"units_updated": row.units_updated,
|
||
"units_offboarded": row.units_offboarded,
|
||
"permission_version": row.permission_version,
|
||
"member_limit": row.member_limit,
|
||
"truncated": bool(row.truncated),
|
||
"credential": row.credential,
|
||
"credential_label": credential_label(row.credential),
|
||
"cursor_seq": int(row.cursor_seq or 0),
|
||
"changes_applied": int(row.changes_applied or 0),
|
||
"operator": row.operator,
|
||
"operator_name": row.operator_name,
|
||
"message": row.message,
|
||
"unchanged": (
|
||
row.created
|
||
+ row.updated
|
||
+ row.offboarded
|
||
+ row.units_created
|
||
+ row.units_updated
|
||
+ row.units_offboarded
|
||
)
|
||
== 0,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 组织
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _iter_org_nodes(
|
||
organizations: list[dict[str, Any]], parent_id: int | None = None, depth: int = 0
|
||
) -> Iterator[tuple[dict[str, Any], int | None]]:
|
||
"""先序展开组织树(父在子前),深度超过 64 层直接截断。"""
|
||
if depth > 64 or not isinstance(organizations, list):
|
||
return
|
||
for node in organizations:
|
||
if not isinstance(node, dict):
|
||
continue
|
||
yield node, parent_id
|
||
children = node.get("children") or []
|
||
hub_id = models.as_id(node.get("organization_id"))
|
||
yield from _iter_org_nodes(children, hub_id or parent_id, depth + 1)
|
||
|
||
|
||
def _hub_parent_id(node: dict[str, Any]) -> int:
|
||
"""节点自己声明的上级:先看 ``parent_id``,再从它自己的 id 路径里取倒数第二段。
|
||
|
||
Hub 的 ``path`` 是按 organization_id 拼的(``/1/8/10/``),最后一段是自己,
|
||
倒数第二段就是上级。有些下发只给 path 不给 parent_id,这一条能兜住。
|
||
"""
|
||
parent = models.as_id(node.get("parent_id")) or 0
|
||
if parent and int(parent) > 0:
|
||
return int(parent)
|
||
parts = [piece for piece in str(node.get("path") or "").split("/") if piece]
|
||
if len(parts) >= 2:
|
||
upper = models.as_id(parts[-2]) or 0
|
||
if upper > 0:
|
||
return int(upper)
|
||
return 0
|
||
|
||
|
||
def _org_tree(organizations: Any, stats: SyncStats | None = None) -> list[dict[str, Any]]:
|
||
"""把 Hub 下发的组织清单整理成一棵能先序展开的树。
|
||
|
||
Hub 有两种口径,都得支持:
|
||
|
||
* 嵌套下发 —— ``children`` 里带着下级(本地验收桩一直用这种);
|
||
* 扁平下发 —— 一张清单把所有组织平铺,``children`` 是空的,层级只写在
|
||
``parent_id`` 与 id 路径 ``path`` 里(真实 Hub 的 ``auth/directory`` 就是这种)。
|
||
|
||
只认嵌套会发生什么:扁平清单被当成一排根部门,组织架构摊平、``path`` 与身份 DN 全部
|
||
停在一级,于是按「本部门及下级」算的数据范围、审批岗位里勾了含下级的部门、按部门路径
|
||
存的引用统统解析不到人 —— 数据看着在,就是不对。所以这里统一还原成树,上级按
|
||
``parent_id`` -> ``path`` -> 原本的嵌套顺序 依次取。
|
||
|
||
对不上号的上级(不在这份清单里、或者自己指自己)不猜,按根部门处理并写进同步记录;
|
||
万一下发里成环,断在最外层的那个节点上,不能让本地递归爬树爬到天荒地老。
|
||
"""
|
||
if not isinstance(organizations, list):
|
||
return []
|
||
by_id: dict[int, dict[str, Any]] = {}
|
||
order: list[int] = []
|
||
nested_parent: dict[int, int] = {}
|
||
duplicates = 0
|
||
for node, parent_hub_id in _iter_org_nodes(organizations):
|
||
hub_id = models.as_id(node.get("organization_id"))
|
||
if not hub_id or int(hub_id) <= 0:
|
||
continue
|
||
hub_id = int(hub_id)
|
||
if hub_id in by_id:
|
||
duplicates += 1
|
||
continue # 同一个组织下发两次:以第一次出现的位置为准
|
||
clone = dict(node)
|
||
clone["children"] = []
|
||
by_id[hub_id] = clone
|
||
order.append(hub_id)
|
||
parent = models.as_id(parent_hub_id) or 0
|
||
if parent and int(parent) > 0 and int(parent) != hub_id:
|
||
nested_parent[hub_id] = int(parent)
|
||
|
||
roots: list[dict[str, Any]] = []
|
||
parent_of: dict[int, int] = {}
|
||
broken: list[str] = []
|
||
for hub_id in order:
|
||
node = by_id[hub_id]
|
||
upper = _hub_parent_id(node) or nested_parent.get(hub_id, 0)
|
||
if upper == hub_id:
|
||
upper = 0
|
||
parent = by_id.get(upper) if upper else None
|
||
if parent is None:
|
||
if upper:
|
||
broken.append(str(node.get("name") or hub_id))
|
||
roots.append(node)
|
||
continue
|
||
parent_of[hub_id] = upper
|
||
parent["children"].append(node)
|
||
|
||
# 断环:沿 parent 往上爬,回到自己就把这一条改挂到根上
|
||
cycled: list[str] = []
|
||
for hub_id in order:
|
||
chain: list[int] = []
|
||
cursor: int | None = hub_id
|
||
guard = 0
|
||
while cursor is not None and guard <= 64:
|
||
guard += 1
|
||
if cursor in chain:
|
||
node = by_id[hub_id]
|
||
upper = parent_of.pop(hub_id, 0)
|
||
parent = by_id.get(upper) if upper else None
|
||
if parent is not None:
|
||
# 只掐断向上的那一条,子树原样跟着它走:把 children 一起清掉等于
|
||
# 把整支下级从这次同步里抹掉,它们会被当成"Hub 里没有了"而停用。
|
||
parent["children"] = [row for row in parent["children"] if row is not node]
|
||
roots.append(node)
|
||
cycled.append(str(node.get("name") or hub_id))
|
||
break
|
||
chain.append(cursor)
|
||
cursor = parent_of.get(cursor)
|
||
|
||
if stats is not None:
|
||
if broken:
|
||
shown = "、".join(broken[:5]) + ("…" if len(broken) > 5 else "")
|
||
stats.note(
|
||
f"Hub 有 {len(broken)} 个组织的上级不在这份清单里,本次按一级部门落库:{shown}"
|
||
)
|
||
if cycled:
|
||
shown = "、".join(cycled[:5]) + ("…" if len(cycled) > 5 else "")
|
||
stats.note(f"Hub 的组织层级里出现了环,已拆到一级:{shown}")
|
||
if duplicates:
|
||
stats.note(f"Hub 清单里有 {duplicates} 个组织重复下发,只认第一次出现的那条")
|
||
return roots
|
||
|
||
|
||
def _record_pair(mapping: dict[str, str], old: str, new: str) -> None:
|
||
"""记下一条"旧名 -> 新名",给收尾的引用搬运查表用。
|
||
|
||
只记这一行自己的前后值,**不要把链条接下去**:一趟同步里每个名字都只属于某一行,
|
||
旧名上的引用本来就指向那一行,它的新值就是这条映射。接力(甲从 A 改到 B、乙从 B 改到 C)
|
||
和互换(甲 A<->B、乙 B<->A)都靠这两条独立的映射各自指回本人;一旦接成 A->C,
|
||
甲的引用就会跑到乙身上去。
|
||
"""
|
||
if not old or not new or old == new:
|
||
return
|
||
mapping[old] = new
|
||
|
||
|
||
def _set_unit_paths(
|
||
unit: models.Unit, parent: models.Unit | None, stats: SyncStats | None = None
|
||
) -> bool:
|
||
"""按 O2OA 口径重算 ``path``/``distinguished_name``,返回有没有变化。"""
|
||
parent_path = parent.path if parent else ""
|
||
# ``oa_unit.path`` 与 ``distinguished_name`` 都是 512:父级越深,本地能放下的名字越短。
|
||
# 超出的部分在拼路径这一步就裁掉(DN 多出的 2 个字符也算进去),否则 Hub 给个长名
|
||
# 会让整批同步在写库那一刻回滚。
|
||
room = max(1, min(255, 510 - len(parent_path)))
|
||
if len(unit.name) > room:
|
||
unit.name = unit.name[:room]
|
||
new_path = f"{parent_path}{unit.name}\\"
|
||
new_dn = f"o={new_path[:-1]}"
|
||
parent_name = parent.name if parent else ""
|
||
if unit.path == new_path and unit.distinguished_name == new_dn and unit.parent_name == parent_name:
|
||
return False
|
||
if stats is not None:
|
||
_record_pair(stats.path_map, unit.path or "", new_path)
|
||
unit.parent_name = parent_name
|
||
unit.path = new_path
|
||
unit.distinguished_name = new_dn
|
||
unit.short_name = unit.name
|
||
return True
|
||
|
||
|
||
def _sync_identity_rows_of(db: Session, unit: models.Unit, stats: SyncStats) -> None:
|
||
"""部门改名/挪动后,把挂在下面的人的身份 DN 一起搬走。"""
|
||
rows = db.execute(
|
||
select(models.Identity).where(models.Identity.unit_id == unit.id)
|
||
).scalars().all()
|
||
for row in rows:
|
||
dn = org.dn_for(unit.path[:-1], row.person_name, row.name)
|
||
if dn == row.distinguished_name:
|
||
continue
|
||
clash = db.execute(
|
||
select(models.Identity.id).where(
|
||
models.Identity.distinguished_name == dn, models.Identity.id != row.id
|
||
)
|
||
).scalar_one_or_none()
|
||
if clash:
|
||
stats.note(f"身份 DN 撞车,保持原值:{dn}")
|
||
continue
|
||
_record_pair(stats.dn_map, row.distinguished_name, dn)
|
||
row.unit_name = unit.name
|
||
row.unit_path = unit.path[:-1]
|
||
row.distinguished_name = dn
|
||
|
||
|
||
def _refresh_paths(
|
||
db: Session, unit: models.Unit, parent: models.Unit | None, stats: SyncStats, depth: int = 0
|
||
) -> None:
|
||
if _set_unit_paths(unit, parent, stats):
|
||
_sync_identity_rows_of(db, unit, stats)
|
||
if depth > 64:
|
||
stats.note(f"组织层级超过 64 层,停止下探:{unit.path}")
|
||
return
|
||
children = db.execute(
|
||
select(models.Unit).where(models.Unit.parent_id == unit.id)
|
||
).scalars().all()
|
||
for child in children:
|
||
_refresh_paths(db, child, unit, stats, depth + 1)
|
||
|
||
|
||
def _unit_weight(db: Session, unit: models.Unit) -> tuple[int, int]:
|
||
"""解绑撞车主键时决定"留哪一个":挂在下面的人多的那个赢,平手留后建的。"""
|
||
people = (
|
||
db.execute(
|
||
select(func.count(models.User.id)).where(models.User.organization_id == unit.id)
|
||
).scalar_one()
|
||
or 0
|
||
)
|
||
return (people, unit.id)
|
||
|
||
|
||
def _hub_units(db: Session, stats: SyncStats) -> dict[int, models.Unit]:
|
||
"""``hub_org_id -> 本地部门``,顺带保证一个 Hub 组织只对一个本地部门。
|
||
|
||
一个 Hub 组织对出两个本地部门(早先"删了部门再同步"会留下这种行)时,组织树会裂成
|
||
两支、人也分家,挂在两边身上的权限各算各的。这里保留人多的那一支,多出来的那行
|
||
**只解掉 Hub 主键、不删数据**,它就此变成本地自建部门,交给管理员合并或删掉。
|
||
"""
|
||
mapped: dict[int, models.Unit] = {}
|
||
rows = db.execute(
|
||
select(models.Unit).where(models.Unit.hub_org_id.isnot(None)).order_by(models.Unit.id)
|
||
).scalars().all()
|
||
for unit in rows:
|
||
hub_id = int(unit.hub_org_id or 0)
|
||
holder = mapped.get(hub_id)
|
||
if holder is None:
|
||
mapped[hub_id] = unit
|
||
continue
|
||
keep, drop = (unit, holder) if _unit_weight(db, unit) > _unit_weight(db, holder) else (holder, unit)
|
||
mapped[hub_id] = keep
|
||
drop.hub_org_id = None
|
||
stats.units_unbound += 1
|
||
stats.note(f"{drop.name} 与 {keep.name} 都写着 Hub 组织 {hub_id},前者已解绑成本地部门(留人多的那支)")
|
||
return mapped
|
||
|
||
|
||
def _local_units_by_code(db: Session) -> dict[str, list[models.Unit]]:
|
||
"""本地自建部门(``hub_org_id`` 为空)按组织编码分组,给"按编码认领"用。"""
|
||
out: dict[str, list[models.Unit]] = {}
|
||
rows = db.execute(
|
||
select(models.Unit)
|
||
.where(models.Unit.hub_org_id.is_(None), models.Unit.code.isnot(None), models.Unit.code != "")
|
||
.order_by(models.Unit.id)
|
||
).scalars().all()
|
||
for unit in rows:
|
||
out.setdefault(str(unit.code), []).append(unit)
|
||
return out
|
||
|
||
|
||
def _report_local_units(db: Session, seen: set[int], stats: SyncStats) -> None:
|
||
"""本地自建部门同步一律不碰,这里只把规模与风险数出来给界面、日志看。
|
||
|
||
值得提醒的是"挂在 Hub 已经不在了的部门下面"这一类:结构照样保留(Hub 只管自己那一支,
|
||
不会把本地部门摘走),但父级一旦被停用,这条支路在 Hub 眼里就断了,得有人手工挪走。
|
||
"""
|
||
rows = db.execute(select(models.Unit).order_by(models.Unit.id)).scalars().all()
|
||
by_id = {row.id: row for row in rows}
|
||
locals_ = [row for row in rows if not row.hub_org_id]
|
||
stats.units_local = len(locals_)
|
||
hanging = 0
|
||
for unit in locals_:
|
||
node = by_id.get(unit.parent_id) if unit.parent_id else None
|
||
guard = 0
|
||
while node is not None and guard < 64:
|
||
if node.hub_org_id and (
|
||
node.hub_org_id not in seen or node.status == models.UnitStatus.DISABLED
|
||
):
|
||
hanging += 1
|
||
break
|
||
node = by_id.get(node.parent_id) if node.parent_id else None
|
||
guard += 1
|
||
stats.units_local_hanging = hanging
|
||
if hanging:
|
||
stats.note(
|
||
f"{hanging} 个本地自建部门挂在 Hub 已消失/停用的部门下面,结构与状态都原样保留,"
|
||
"请手工把它们挪到还在的部门下"
|
||
)
|
||
|
||
|
||
def _sync_units(db: Session, organizations: list[dict[str, Any]], stats: SyncStats) -> dict[int, int]:
|
||
"""Hub 组织树 -> ``oa_unit``,返回 ``{hub_org_id: 本地 unit_id}``。
|
||
|
||
**每次都是全量,但只接管 Hub 的那一部分**:Hub 决定 ``name`` / ``code`` / ``status`` /
|
||
``parent_id``(层级挪动会连带刷子树路径与身份 DN),本地决定 ``alias`` / ``description``
|
||
/ ``order_number`` / ``manager_person_id``,以及挂在任何部门下面的自建部门。
|
||
``hub_org_id`` 写上一律不清空(界面上改不动,Hub 里消失也只是停用不删除),组织架构、
|
||
部门负责人、按部门配的权限与审批规则全靠它长期对上号。
|
||
|
||
字段按文档第 11 节的组织节点落库:``organization_id`` -> ``hub_org_id``、
|
||
``code`` -> ``code``、``name`` -> ``name``、``status`` -> ``status``(``1`` 之外一律停用);
|
||
``path`` 是 Hub 自己按 id 拼的 ``/1/2/``,本地另有 O2OA 口径的 ``path``/DN,不落这一列;
|
||
但它和 ``parent_id`` 一起被 ``_org_tree`` 用来还原层级(真实 Hub 是扁平下发、``children``
|
||
为空,只认嵌套的话整个组织架构会被摊平,见 ``docs/hub-integration.md`` 第 6 节)。
|
||
``member_count`` 是导出批次的直属人数,本地按 ``organization_id`` 现算,同样不落库。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
mapped = _hub_units(db, stats)
|
||
local_by_code = _local_units_by_code(db)
|
||
|
||
seen: set[int] = set()
|
||
order: list[tuple[models.Unit, models.Unit | None]] = []
|
||
for node, parent_hub_id in _iter_org_nodes(_org_tree(organizations, stats)):
|
||
hub_id = models.as_id(node.get("organization_id"))
|
||
code = models.clip(str(node.get("code") or "").strip(), 190)
|
||
if not hub_id or hub_id <= 0 or code == UNASSIGNED:
|
||
continue # 未分配组织的合成节点,本地不落部门
|
||
name = models.clip(str(node.get("name") or "").strip(), 255) or f"组织{hub_id}"
|
||
status = models.UnitStatus.normalize(models.as_id(node.get("status")))
|
||
parent = mapped.get(models.as_id(parent_hub_id) or 0) if parent_hub_id else None
|
||
seen.add(hub_id)
|
||
|
||
unit = mapped.get(hub_id)
|
||
claimed = False
|
||
if unit is None:
|
||
# 本系统自己加的部门:组织编码跟 Hub 这个部门一模一样、而且这个编码本地只有一处,
|
||
# 就认定是同一个部门,认下来(补写 hub_org_id),而不是再建一个重名部门。
|
||
candidates = local_by_code.get(code) or [] if code else []
|
||
if len(candidates) > 1:
|
||
stats.note(f"本地有 {len(candidates)} 个部门都用编码 {code},认领不了,本次按新部门建")
|
||
local_by_code[code] = []
|
||
elif len(candidates) == 1 and cfg.hub_sync_bind_local_by_code:
|
||
unit = candidates[0]
|
||
claimed = True
|
||
local_by_code.pop(code, None)
|
||
|
||
if unit is None:
|
||
unit = models.Unit(
|
||
name=name,
|
||
code=code,
|
||
alias=code,
|
||
description="由统一身份同步创建",
|
||
parent_id=parent.id if parent else None,
|
||
hub_org_id=hub_id,
|
||
status=status,
|
||
)
|
||
db.add(unit)
|
||
db.flush()
|
||
mapped[hub_id] = unit
|
||
stats.units_created += 1
|
||
else:
|
||
parent_id = parent.id if parent else None
|
||
changed = (
|
||
unit.name != name
|
||
or unit.parent_id != parent_id
|
||
or unit.status != status
|
||
or unit.hub_org_id != hub_id
|
||
or bool(code and unit.code != code)
|
||
)
|
||
if changed:
|
||
_record_pair(stats.unit_name_map, unit.name, name)
|
||
unit.name = name
|
||
unit.parent_id = parent_id
|
||
unit.status = status
|
||
unit.hub_org_id = hub_id
|
||
if code:
|
||
unit.code = code
|
||
if claimed:
|
||
stats.units_bound += 1
|
||
stats.note(
|
||
f"本地部门 {name}(编码 {code})已按编码认成 Hub 组织 {hub_id},"
|
||
"此后名称与层级由 Hub 接管"
|
||
)
|
||
else:
|
||
stats.units_updated += 1
|
||
mapped[hub_id] = unit
|
||
order.append((unit, parent))
|
||
|
||
# 第二轮再算路径:此时父级已经全部落库,改名/挪动会连带刷子树与身份 DN。
|
||
for unit, parent in order:
|
||
_refresh_paths(db, unit, parent, stats)
|
||
|
||
_offboard_missing_units(db, seen, stats)
|
||
_report_local_units(db, seen, stats)
|
||
return {hub_id: unit.id for hub_id, unit in mapped.items()}
|
||
|
||
|
||
def _offboard_missing_units(db: Session, seen: set[int], stats: SyncStats) -> None:
|
||
"""Hub 已经不存在的同步部门置为停用(本地自建部门不在 ``seen`` 判据里,永不处理)。
|
||
|
||
这里是"停用"而不是"删除":``hub_org_id`` 一丢就再也对不回 Hub 的那个组织,下趟同步
|
||
只会新建一个空部门,负责人、按部门配的权限与审批规则全丢。宁可留着停用的壳子,
|
||
等对方把组织加回来就自动接上。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
if not cfg.hub_sync_offboard:
|
||
return
|
||
if stats.truncated:
|
||
# 导出被 member_limit 截断时组织树也不完整,这时下线部门属于误伤。
|
||
return
|
||
rows = db.execute(
|
||
select(models.Unit).where(
|
||
models.Unit.hub_org_id.isnot(None),
|
||
models.Unit.status != models.UnitStatus.DISABLED,
|
||
)
|
||
).scalars().all()
|
||
for row in rows:
|
||
if row.hub_org_id in seen:
|
||
continue
|
||
row.status = models.UnitStatus.DISABLED
|
||
stats.units_offboarded += 1
|
||
if stats.units_offboarded:
|
||
stats.note(
|
||
f"Hub 已不存在的 {stats.units_offboarded} 个同步部门已停用"
|
||
"(部门本身保留,Hub 里加回来会自动接上)"
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 人员
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def is_emergency_account(account: str) -> bool:
|
||
"""这个账号名是不是应急账号(``hub_local_accounts`` + 内置超管,永远只用本地口令登录)。
|
||
|
||
这类账号绝不能被统一身份接管:Hub 哪天建一个同名的号,本地这个后门就会被标成
|
||
``source=hub``,从此跟着 Hub 停用 —— Hub 一停用人就进不来了,应急通道形同虚设。
|
||
与 ``hub_sync_protect_admins`` 无关,那个开关可以关,这条不行。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
return str(account or "").strip().lower() in cfg.local_only_accounts
|
||
|
||
|
||
def _protect_from_hub(cfg, person: models.User) -> bool:
|
||
"""``hub_sync_protect_admins`` 开关下的"这个人不能被 Hub 接管"判据。
|
||
|
||
护的是**本地自建**的管理员(内置超管、界面上手工建的管理员):Hub 那边有没有这个人
|
||
都不确定,让 Hub 去改名、换部门、停用等于把自己的后门交给别人堵。
|
||
同步建起来的人后来被授予管理员角色**不算**在内 —— 那个人归 Hub 管,跟着它改名、
|
||
它说停用就停用才是对的;否则这个人的资料会永远停在被提升的那一刻,越同步越乱。
|
||
"""
|
||
return bool(
|
||
cfg.hub_sync_protect_admins
|
||
and person.role == models.ROLE_ADMIN
|
||
and person.source == models.AccountSource.LOCAL
|
||
)
|
||
|
||
|
||
def _map_status(hub_status: int) -> int:
|
||
"""Hub 只保证「1=启用,其余为停用/待审核」,本地一律折成停用。"""
|
||
return models.UserStatus.ACTIVE if int(hub_status or 0) == 1 else models.UserStatus.DISABLED
|
||
|
||
|
||
def _ensure_identity(db: Session, person: models.User, unit: models.Unit | None, stats: SyncStats) -> None:
|
||
if org.person_identities(db, person.id):
|
||
return
|
||
unit_path = unit.path[:-1] if unit else ""
|
||
dn = org.dn_for(unit_path, person.display_name, person.account)
|
||
if db.execute(
|
||
select(models.Identity.id).where(models.Identity.distinguished_name == dn)
|
||
).scalar_one_or_none():
|
||
stats.note(f"身份 DN 已存在,跳过新建:{dn}")
|
||
return
|
||
db.add(
|
||
models.Identity(
|
||
name=person.display_name,
|
||
person_id=person.id,
|
||
person_name=person.display_name,
|
||
unit_id=unit.id if unit else None,
|
||
unit_name=unit.name if unit else "",
|
||
unit_path=unit_path,
|
||
distinguished_name=dn,
|
||
is_default=True,
|
||
)
|
||
)
|
||
|
||
|
||
def _move_person_identity(db: Session, person: models.User, unit: models.Unit | None, stats: SyncStats) -> None:
|
||
unit_id = unit.id if unit else None
|
||
unit_path = unit.path[:-1] if unit else ""
|
||
for row in org.person_identities(db, person.id):
|
||
dn = org.dn_for(unit_path, person.display_name, row.name)
|
||
if dn != row.distinguished_name and db.execute(
|
||
select(models.Identity.id).where(
|
||
models.Identity.distinguished_name == dn, models.Identity.id != row.id
|
||
)
|
||
).scalar_one_or_none():
|
||
stats.note(f"身份 DN 撞车,保持原值:{dn}")
|
||
continue
|
||
row.unit_id = unit_id
|
||
row.unit_name = unit.name if unit else ""
|
||
row.unit_path = unit_path
|
||
row.person_name = person.display_name
|
||
row.distinguished_name = dn
|
||
|
||
|
||
def _apply_account_renames(
|
||
db: Session,
|
||
plan: dict[int, tuple[models.User, str, str]],
|
||
holders: dict[str, int],
|
||
by_account: dict[str, models.User],
|
||
stats: SyncStats,
|
||
) -> None:
|
||
"""按"谁先把账号腾开"的顺序把改名的行落库。
|
||
|
||
``users.account`` 上有唯一键,而本项目的 Session 关了 autoflush:一边循环一边改账号,
|
||
遇到「甲把 qianjiu2 让给乙」这种接力,两条 UPDATE 会攒到收尾一起发出去,先发的那条
|
||
撞上唯一键,整趟同步直接失败(不是跳过一个人,是一行都没写)。所以先把要改的挑出来,
|
||
目标账号没人占就先改并当场 flush;互相占用的环就先统统挪到临时账号,再落最终值。
|
||
"""
|
||
remaining = dict(plan)
|
||
guard = 0
|
||
while remaining and guard <= len(plan):
|
||
guard += 1
|
||
progressed = False
|
||
for person_id in list(remaining):
|
||
person, account, old_account = remaining[person_id]
|
||
holder_id = holders.get(account)
|
||
if holder_id is not None and holder_id != person_id:
|
||
if holder_id in remaining:
|
||
continue # 等占着这个账号的那个人先腾开
|
||
# 起跑时看是空的,结果这一趟里新建的号先占上了:不抢,保持原账号
|
||
stats.conflicts += 1
|
||
remaining.pop(person_id, None)
|
||
continue
|
||
person.account = account
|
||
holders.pop(old_account, None)
|
||
holders[account] = person_id
|
||
by_account.pop(old_account, None)
|
||
by_account[account] = person
|
||
_record_pair(stats.account_map, old_account, account)
|
||
db.flush()
|
||
stats.renamed += 1
|
||
remaining.pop(person_id, None)
|
||
progressed = True
|
||
if not progressed:
|
||
break
|
||
if not remaining:
|
||
return
|
||
# 还剩互相占用的环:先把环上的人统统挪到临时账号,把彼此盯着的账号腾干净再落最终值。
|
||
# 腾的时候要把 holders / by_account 里的旧账号一起抹掉,否则下一轮查目标账号还是会
|
||
# 看成"被别人占着",整个环一个账号都换不出去。
|
||
for person, _account, old_account in remaining.values():
|
||
if holders.get(old_account) == person.id:
|
||
holders.pop(old_account, None)
|
||
by_account.pop(old_account, None)
|
||
staging = f"hub-tmp-{old_account}"[:190]
|
||
suffix = 2
|
||
while holders.get(staging) is not None: # 万一本地真有个 hub-tmp-xxx,往后加号
|
||
staging = f"hub-tmp-{old_account}-{suffix}"[:190]
|
||
suffix += 1
|
||
person.account = staging
|
||
holders[staging] = person.id
|
||
db.flush()
|
||
for person, account, old_account in remaining.values():
|
||
holder_id = holders.get(account)
|
||
if holder_id is not None and holder_id != person.id:
|
||
stats.conflicts += 1
|
||
person.account = old_account # 抢不过就退回原账号,别把人留在临时账号上
|
||
holders[old_account] = person.id
|
||
by_account[old_account] = person
|
||
continue
|
||
person.account = account
|
||
holders[account] = person.id
|
||
by_account[account] = person
|
||
_record_pair(stats.account_map, old_account, account)
|
||
stats.renamed += 1
|
||
db.flush()
|
||
|
||
|
||
def _plan_account_renames(
|
||
db: Session,
|
||
users: list[dict[str, Any]],
|
||
by_hub_id: dict[int, models.User],
|
||
by_account: dict[str, models.User],
|
||
stats: SyncStats,
|
||
) -> None:
|
||
"""把这一趟 Hub 要求的账号改名一次性排好再落库(见 ``_apply_account_renames``)。
|
||
|
||
分两遍扫:先收齐"Hub 要求换账号"的人,再判断目标账号是不是被一个不打算动的人占着。
|
||
一遍扫不行的原因是清单有先后 —— 甲要乙的账号、乙也要甲的账号时,先扫到的那个会以为
|
||
对面是"不动的人"而被判成撞车,结果两个人一个都没换成,而这其实是能换的(互换)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
holders = {account: person.id for account, person in by_account.items()}
|
||
wanted: dict[int, tuple[models.User, str, str]] = {}
|
||
for item in users:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
account = models.clip(str(item.get("account") or "").strip(), 190)
|
||
hub_user_id = models.as_id(item.get("user_id"))
|
||
if not account or not hub_user_id:
|
||
continue
|
||
person = by_hub_id.get(int(hub_user_id))
|
||
if person is None or person.account == account:
|
||
continue
|
||
if _protect_from_hub(cfg, person) or is_emergency_account(person.account):
|
||
continue
|
||
wanted[person.id] = (person, account, person.account)
|
||
plan: dict[int, tuple[models.User, str, str]] = {}
|
||
for person_id, (person, account, old_account) in wanted.items():
|
||
holder_id = holders.get(account)
|
||
if holder_id is not None and holder_id != person.id and holder_id not in wanted:
|
||
# 账号已经属于另一个不动的人:不抢,主键与其余信息照旧跟 Hub 对齐
|
||
stats.conflicts += 1
|
||
continue
|
||
plan[person.id] = (person, account, old_account)
|
||
if plan:
|
||
_apply_account_renames(db, plan, holders, by_account, stats)
|
||
|
||
|
||
def _sync_people(
|
||
db: Session,
|
||
users: list[dict[str, Any]],
|
||
unit_map: dict[int, int],
|
||
stats: SyncStats,
|
||
now: datetime,
|
||
) -> set[int]:
|
||
"""Hub 扁平人员清单 -> ``users``,返回这次清单里出现的 Hub 主键。
|
||
|
||
**身份只认 Hub 的 ``user_id``**(每次都是全量清单,本地不自造主键):账号会被人先注册
|
||
走、也会在 Hub 侧改名,姓名更是常改,只有 Hub 主键从头到尾指着同一个人。于是——
|
||
|
||
* 清单里没带 ``user_id`` 的人不建号也不认领,只计数上报(宁可少一个人,也别把
|
||
两个不同的人并成一条);
|
||
* 先按 ``hub_user_id`` 找人;找不到才看账号,而账号只允许认领**还没绑过主键**的
|
||
本地账号(手工建的、或历史遗留的),认领后写 ``source=hub``;
|
||
* 账号已经绑在别人身上就跳过并计数,绝不覆盖 ``hub_user_id``——那等于把两个人的
|
||
权限、待办、流程历史搅在一起;
|
||
* 已绑主键的人,账号跟着 Hub 改(新账号没人占用才改),姓名/邮箱/部门/状态一律以
|
||
Hub 为准。改走的旧账号会记进 ``account_map``,收尾时把按账号存的审批引用一起搬走。
|
||
|
||
两条护栏:``hub_sync_protect_admins`` 打开时**本地自建**的 ``role=admin`` 账号全程跳过
|
||
(防止 Hub 里没有 admin 时把自己锁在系统外);``hub_local_accounts`` 里的应急账号永远不
|
||
被接管,也不参与改名。两条都只管本地账号,统一身份同步进来的人后来被授予管理员角色,
|
||
照样跟着 Hub 走。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
by_hub_id: dict[int, models.User] = {}
|
||
by_account: dict[str, models.User] = {}
|
||
for row in db.execute(select(models.User).order_by(models.User.id)).scalars().all():
|
||
if row.account:
|
||
by_account.setdefault(row.account, row)
|
||
if row.hub_user_id:
|
||
by_hub_id[int(row.hub_user_id)] = row
|
||
|
||
seen_ids: set[int] = set()
|
||
_plan_account_renames(db, users, by_hub_id, by_account, stats)
|
||
|
||
for item in users:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
account = models.clip(str(item.get("account") or "").strip(), 190)
|
||
hub_user_id = models.as_id(item.get("user_id"))
|
||
if not hub_user_id or hub_user_id <= 0:
|
||
# 没有 Hub 主键就没有身份可言:不建号、不认领,也参与不了后面的离职判定。
|
||
stats.no_hub_id += 1
|
||
continue
|
||
if not account:
|
||
stats.no_hub_id += 1
|
||
continue
|
||
seen_ids.add(int(hub_user_id))
|
||
display_name = models.clip(str(item.get("display_name") or "").strip(), 100) or account
|
||
status = _map_status(models.as_id(item.get("status")) or 0)
|
||
hub_org_id = models.as_id(item.get("organization_id")) or 0
|
||
unit_id = unit_map.get(hub_org_id) if hub_org_id else None
|
||
|
||
person = by_hub_id.get(int(hub_user_id))
|
||
if person is None:
|
||
holder = by_account.get(account)
|
||
if holder is not None and holder.hub_user_id:
|
||
# 这个账号已经代表 Hub 里的另一个人了,不能当成同一个人。
|
||
stats.conflicts += 1
|
||
continue
|
||
if holder is None:
|
||
if not cfg.hub_auto_provision:
|
||
stats.skipped += 1
|
||
continue
|
||
email = models.clip(str(item.get("email") or "").strip(), 190)
|
||
if not email and cfg.hub_sync_email_domain:
|
||
email = f"{account}@{cfg.hub_sync_email_domain}"
|
||
person = models.User(
|
||
account=account,
|
||
display_name=display_name,
|
||
email=email,
|
||
# 同步建的号不在本地设密码,登录一律回 Hub 校验。
|
||
password_hash=hash_password(secrets.token_urlsafe(24)),
|
||
organization_id=unit_id,
|
||
role=models.ROLE_MEMBER,
|
||
status=status,
|
||
source=models.AccountSource.HUB,
|
||
hub_user_id=int(hub_user_id),
|
||
hub_synced_at=now,
|
||
)
|
||
db.add(person)
|
||
db.flush()
|
||
by_account[account] = person
|
||
by_hub_id[int(hub_user_id)] = person
|
||
_ensure_identity(db, person, db.get(models.Unit, unit_id) if unit_id else None, stats)
|
||
stats.created += 1
|
||
continue
|
||
# 账号对上了一个从没绑过 Hub 的本地账号:认领它,本地主键与它身上的权限、
|
||
# 待办、流程历史都原样留着(users.id 不变是按 id 挂的权限不掉的关键)。
|
||
if is_emergency_account(holder.account):
|
||
# 撞上了应急账号的名字:让给本地,Hub 这个人这次不处理(不建号也不认领)
|
||
stats.emergency += 1
|
||
continue
|
||
person = holder
|
||
|
||
if _protect_from_hub(cfg, person):
|
||
stats.protected += 1
|
||
continue
|
||
|
||
moved = False
|
||
if not person.hub_user_id:
|
||
person.hub_user_id = int(hub_user_id)
|
||
by_hub_id[int(hub_user_id)] = person
|
||
if person.source != models.AccountSource.HUB:
|
||
person.source = models.AccountSource.HUB
|
||
stats.adopted += 1
|
||
# 账号改名已经在 _plan_account_renames 里统一落库了;这里再动一次就会撞上
|
||
# users.account 的唯一键,所以只认结果:没改成就是在起跑阶段被判成有歧义。
|
||
if person.display_name != display_name:
|
||
if person.display_name:
|
||
_record_pair(stats.display_name_map, person.display_name, display_name)
|
||
person.display_name = display_name
|
||
moved = True
|
||
email = models.clip(str(item.get("email") or "").strip(), 190)
|
||
if email and person.email != email:
|
||
person.email = email
|
||
# Hub 里查不到这个部门时保留原部门,别把人踢成无部门。
|
||
if unit_id and person.organization_id != unit_id:
|
||
person.organization_id = unit_id
|
||
_move_person_identity(db, person, db.get(models.Unit, unit_id), stats)
|
||
moved = True
|
||
if person.status != status:
|
||
person.status = status
|
||
person.hub_synced_at = now
|
||
if moved:
|
||
stats.updated += 1
|
||
|
||
if stats.adopted:
|
||
stats.note(f"认领本地同名账号 {stats.adopted} 个,已标记为统一身份账号(本地主键与权限不变)")
|
||
if stats.renamed:
|
||
stats.note(f"{stats.renamed} 人的登录账号已跟随 Hub 改名,按账号存下的审批引用同步搬走")
|
||
if stats.conflicts:
|
||
stats.note(
|
||
f"{stats.conflicts} 人的账号在本地已属于另一个统一身份,本次跳过没有覆盖,"
|
||
"请人工核对是重复账号还是 Hub 数据错了"
|
||
)
|
||
if stats.no_hub_id:
|
||
stats.note(f"Hub 有 {stats.no_hub_id} 人没带 user_id(或没带账号),无法按主键认人,本次未处理")
|
||
if stats.skipped:
|
||
stats.note(f"Hub 有 {stats.skipped} 人本地没有对应账号,OA_HUB_AUTO_PROVISION=false 未建号")
|
||
if stats.protected:
|
||
stats.note(
|
||
f"{stats.protected} 个本地自建的管理员账号按 OA_HUB_SYNC_PROTECT_ADMINS 跳过,"
|
||
"同步没有改它们(统一身份同步来的账号不受这一项影响,照常跟着 Hub 走)"
|
||
)
|
||
if stats.emergency:
|
||
stats.note(
|
||
f"Hub 有 {stats.emergency} 个人跟本地应急账号(OA_HUB_LOCAL_ACCOUNTS)同名,"
|
||
"账号名让给了本地,这些人本次没有同步;要么 Hub 换个账号名,要么把应急账号改成别的名字"
|
||
)
|
||
return seen_ids
|
||
|
||
|
||
def _offboard_missing(db: Session, seen_ids: set[int], stats: SyncStats, now: datetime) -> None:
|
||
"""Hub 已经不存在的同步账号置为停用(只停用不删除,也不碰本地账号)。
|
||
|
||
判据只有 ``hub_user_id`` 这一个:以前还附带"账号也找不到",于是 Hub 里改了账号的人
|
||
会被判成离职、连带他的待办和权限一起停掉。现在账号只是普通字段,不参与身份判定。
|
||
没有主键的 ``source=hub`` 账号(历史遗留)不做离职判定,只报数量让人去补绑。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
rows = db.execute(
|
||
select(models.User).where(models.User.source == models.AccountSource.HUB)
|
||
).scalars().all()
|
||
for row in rows:
|
||
if not row.hub_user_id:
|
||
stats.unbound += 1
|
||
continue
|
||
if int(row.hub_user_id) in seen_ids:
|
||
continue
|
||
if cfg.hub_sync_protect_admins and row.role == models.ROLE_ADMIN:
|
||
stats.protected += 1
|
||
continue
|
||
row.hub_synced_at = now
|
||
if row.status == models.UserStatus.DISABLED:
|
||
continue
|
||
row.status = models.UserStatus.DISABLED
|
||
stats.offboarded += 1
|
||
if stats.offboarded:
|
||
stats.note(
|
||
f"{stats.offboarded} 人没出现在 Hub 清单里,本地已置停用(只停用不删行,待办与审批轨迹都在)。"
|
||
"注意 Hub 的目录接口不下发已停用人员:在 Hub 被停用的人也会表现为「不在清单里」,"
|
||
"所以这一条同时覆盖 Hub 侧的停用;Hub 重新启用后下一趟同步会自动恢复"
|
||
)
|
||
if stats.unbound:
|
||
stats.note(
|
||
f"{stats.unbound} 个标成统一身份却没有 Hub 主键的账号本次没做离职判定,"
|
||
"请在人员页补绑或改回本地账号"
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 主流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def sync_users(
|
||
db: Session,
|
||
*,
|
||
trigger: str = models.HubSyncRun.TRIGGER_SCHEDULE,
|
||
operator: str = "",
|
||
operator_name: str = "",
|
||
) -> dict[str, Any]:
|
||
"""拉一次 Hub 全量并落库,返回这次同步的汇总。"""
|
||
cfg = hubconfig.get()
|
||
manual = trigger == models.HubSyncRun.TRIGGER_MANUAL
|
||
if not cfg.hub_enabled or not cfg.hub_base_url:
|
||
raise HubSyncError("未启用统一身份认证,请检查 OA_HUB_ENABLED / OA_HUB_BASE_URL")
|
||
if not cfg.hub_sync_enabled and not manual:
|
||
raise HubSyncError("定时同步已关闭,请到「系统设置 → 同步定时任务」打开「允许定时同步」")
|
||
if not _run_lock.acquire(blocking=False):
|
||
raise HubSyncError("已有同步任务正在执行,请稍后再试")
|
||
|
||
now = datetime.now()
|
||
member_limit = max(1, min(5000, int(cfg.hub_sync_member_limit or 2000)))
|
||
run = models.HubSyncRun(
|
||
trigger=trigger,
|
||
status="running",
|
||
started_at=now,
|
||
operator=operator,
|
||
operator_name=operator_name,
|
||
member_limit=member_limit,
|
||
)
|
||
db.add(run)
|
||
db.commit()
|
||
run_id = run.id
|
||
|
||
stats = SyncStats()
|
||
stats.member_limit = member_limit
|
||
try:
|
||
hub_client = hub_api.client()
|
||
# 目录密钥走 X-Directory-Key 头(客户端自己加);这里拿到的 token 是老的 Bearer 口径,
|
||
# 没配凭证时是空串,客户端就不带 Authorization 头。
|
||
token, stats.credential = hub_api.sync_token(hub_client)
|
||
payload = hub_client.directory(
|
||
token,
|
||
include_disabled=cfg.hub_sync_include_disabled_units,
|
||
include_disabled_users=True,
|
||
member_limit=member_limit,
|
||
)
|
||
stats.permission_version = models.as_id(payload.get("permission_version")) or 0
|
||
stats.truncated = bool(payload.get("truncated"))
|
||
stats.total_users = models.as_id(payload.get("total_users")) or 0
|
||
hub_users = payload.get("users") if isinstance(payload.get("users"), list) else []
|
||
stats.returned_users = models.as_id(payload.get("returned_users")) or len(hub_users)
|
||
|
||
if not hub_users and stats.total_users == 0:
|
||
raise HubSyncError("Hub 返回的人员清单为空,已放弃写入(避免把本地同步账号全部停用)")
|
||
|
||
previous = state(db).get("permission_version")
|
||
if (
|
||
not manual
|
||
and cfg.hub_sync_skip_unchanged
|
||
and stats.permission_version
|
||
and previous is not None
|
||
and int(previous) == stats.permission_version
|
||
):
|
||
_finish(db, run_id, stats, models.HubSyncRun.STATUS_SKIPPED, "permission_version 未变化,无需写入")
|
||
return {"run": serialize_run(latest_run(db) or run), "skipped": True}
|
||
|
||
unit_map: dict[int, int] = {}
|
||
if cfg.hub_sync_orgs:
|
||
organizations = payload.get("organizations") if isinstance(payload.get("organizations"), list) else []
|
||
unit_map = _sync_units(db, organizations, stats)
|
||
|
||
seen_ids = _sync_people(db, hub_users, unit_map, stats, datetime.now())
|
||
|
||
if stats.truncated:
|
||
stats.note(
|
||
f"人员清单被 member_limit={cfg.hub_sync_member_limit} 截断,"
|
||
"本次只写入不撤销,请调大 OA_HUB_SYNC_MEMBER_LIMIT"
|
||
)
|
||
elif cfg.hub_sync_offboard:
|
||
_offboard_missing(db, seen_ids, stats, datetime.now())
|
||
else:
|
||
stats.note("OA_HUB_SYNC_OFFBOARD=false,Hub 里已消失的账号本次未停用")
|
||
|
||
_carry_references(db, stats)
|
||
|
||
status = models.HubSyncRun.STATUS_PARTIAL if stats.truncated else models.HubSyncRun.STATUS_SUCCESS
|
||
_finish(db, run_id, stats, status, ";".join(stats.messages))
|
||
return {"run": serialize_run(latest_run(db) or run), "skipped": False}
|
||
except HubSyncError as exc:
|
||
db.rollback()
|
||
_finish(db, run_id, stats, models.HubSyncRun.STATUS_FAILED, str(exc))
|
||
raise
|
||
except hub_api.HubError as exc:
|
||
db.rollback()
|
||
_finish(db, run_id, stats, models.HubSyncRun.STATUS_FAILED, exc.message)
|
||
raise HubSyncError(exc.message) from exc
|
||
except Exception as exc: # pragma: no cover - 兜底,别把调度线程带崩
|
||
logger.exception("Hub 同步失败")
|
||
db.rollback()
|
||
_finish(db, run_id, stats, models.HubSyncRun.STATUS_FAILED, f"同步异常:{exc}")
|
||
raise HubSyncError(f"同步异常:{exc}") from exc
|
||
finally:
|
||
_run_lock.release()
|
||
|
||
|
||
def _carry_references(db: Session, stats: SyncStats) -> None:
|
||
"""同步改了名字,就把按字符串存着的审批与共享引用一起搬走。
|
||
|
||
权限角色、数据范围、部门负责人都是按主键挂的,同步不动主键,天然不受影响;会出问题的是
|
||
审批岗位、岗位组、流程环节审批人、日程与网盘共享名单那一类按身份 DN / 部门路径 / 账号 /
|
||
姓名存的字符串。这里在同一个事务里把它们搬到新值,让"配好权限之后再全量同步"是安全的。
|
||
有歧义、搬不了的一律不动,只把数量写进同步记录。
|
||
"""
|
||
maps = hub_refs.build_maps(
|
||
dn_map=stats.dn_map,
|
||
path_map=stats.path_map,
|
||
unit_name_map=stats.unit_name_map,
|
||
account_map=stats.account_map,
|
||
display_name_map=stats.display_name_map,
|
||
)
|
||
if maps.empty:
|
||
return
|
||
report = hub_refs.rewrite(db, maps)
|
||
stats.refs_rewritten = report.rewritten
|
||
stats.refs_ambiguous = report.skipped
|
||
if report.rewritten:
|
||
stats.note(
|
||
f"随本次改名搬走 {report.rewritten} 处按字符串存的审批岗位/共享名单,流程照常找得到人"
|
||
)
|
||
if report.skipped:
|
||
stats.note(
|
||
f"{report.skipped} 个改掉的名字本地有歧义,相关配置保持原样,请到流程设计与岗位组里手工确认"
|
||
)
|
||
if report.homonyms:
|
||
stats.note(
|
||
"改过去的名字本地已有同名的(" + "、".join(report.homonyms[:3]) + "),"
|
||
"按名字配的审批人会一并命中这几个,请核对一下"
|
||
)
|
||
# 只查这次"没敢搬"的名字:那些配置还指着旧名,流程走到会没人可派
|
||
broken, samples = hub_refs.stale_references(db, set(report.dropped_names))
|
||
if broken:
|
||
detail = "、".join(item["value"] for item in samples[:3])
|
||
stats.note(
|
||
f"设计器里还有 {broken} 处审批人配置指着改掉的名字(如 {detail}),"
|
||
"自动搬运会改错对象所以没动,请去流程设计/岗位组里手工确认"
|
||
)
|
||
|
||
|
||
def _finish(
|
||
db: Session,
|
||
run_id: str,
|
||
stats: SyncStats,
|
||
status: str,
|
||
message: str,
|
||
*,
|
||
state_patch: dict[str, Any] | None = None,
|
||
) -> None:
|
||
run = db.get(models.HubSyncRun, run_id)
|
||
now = datetime.now()
|
||
if run is not None:
|
||
run.status = status
|
||
run.finished_at = now
|
||
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
|
||
run.total_users = stats.total_users
|
||
run.returned_users = stats.returned_users
|
||
run.created = stats.created
|
||
run.updated = stats.updated
|
||
run.offboarded = stats.offboarded
|
||
run.units_created = stats.units_created
|
||
run.units_updated = stats.units_updated
|
||
run.units_offboarded = stats.units_offboarded
|
||
run.permission_version = stats.permission_version
|
||
run.member_limit = stats.member_limit or run.member_limit
|
||
run.truncated = stats.truncated
|
||
run.credential = stats.credential
|
||
run.cursor_seq = int(stats.cursor_seq or 0)
|
||
run.changes_applied = int(stats.changes_applied or 0)
|
||
run.message = (message or "")[:2000]
|
||
if state_patch is not None:
|
||
# 增量轮询只更新自己的那几个键,不碰 permission_version / total_users,
|
||
# 否则会把上一次全量的版本号称成 0,害得夜间全量误判成"版本变了"。
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
if row is None:
|
||
row = models.SystemSetting(key=STATE_KEY, value={}, description="Hub 组织人员同步状态")
|
||
db.add(row)
|
||
row.value = {**(row.value or {}), **state_patch}
|
||
if state_patch is None and status in (models.HubSyncRun.STATUS_SUCCESS, models.HubSyncRun.STATUS_PARTIAL):
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
if row is None:
|
||
row = models.SystemSetting(key=STATE_KEY, value={}, description="Hub 组织人员同步状态")
|
||
db.add(row)
|
||
row.value = {
|
||
**(row.value or {}),
|
||
"permission_version": stats.permission_version,
|
||
"total_users": stats.total_users,
|
||
"last_sync_at": now.strftime("%Y-%m-%d %H:%M:%S"),
|
||
"last_status": status,
|
||
}
|
||
db.commit()
|
||
logger.info(
|
||
"Hub 同步 %s(%s,凭证 %s):人员 新增%d/更新%d/停用%d,"
|
||
"部门 新增%d/更新%d/停用%d,版本 %s,member_limit %s%s",
|
||
status,
|
||
stats.total_users,
|
||
stats.credential,
|
||
stats.created,
|
||
stats.updated,
|
||
stats.offboarded,
|
||
stats.units_created,
|
||
stats.units_updated,
|
||
stats.units_offboarded,
|
||
stats.permission_version,
|
||
stats.member_limit,
|
||
"(已截断)" if stats.truncated else "",
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 增量同步(变更流水,文档 6.2 / 6.3)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 单趟最多翻多少批(每批 ``hub_sync.changes.limit`` 条);``has_more`` 抽风时给线程兜个底
|
||
MAX_CHANGE_ROUNDS = 100
|
||
|
||
#: 一条变更的处理结论
|
||
APPLIED = "applied" # 已经落到本地
|
||
IGNORED = "ignored" # 与本地无关(不认识的人/部门、payload 里没有可用字段)
|
||
NEEDS_FULL = "needs_full" # 光凭这一条推不出正确结果,要回全量重对齐
|
||
|
||
EVENT_USER = "user"
|
||
EVENT_ORGANIZATION = "organization"
|
||
OP_DELETE = "delete"
|
||
|
||
|
||
def changes_cursor(db: Session) -> int | None:
|
||
"""本地游标;``None`` 表示从没对齐过,第一步必须先走全量(文档 6.3 第 1 步)。"""
|
||
raw = state(db).get("changes_cursor")
|
||
if raw is None:
|
||
return None
|
||
try:
|
||
return int(raw)
|
||
except (TypeError, ValueError):
|
||
return None
|
||
|
||
|
||
def changes_status(db: Session) -> dict[str, Any]:
|
||
"""给状态接口看的增量同步运行态(游标走到哪、还差多少、上次什么时候拉的)。"""
|
||
cfg = hubconfig.get()
|
||
current = state(db)
|
||
cursor = changes_cursor(db)
|
||
newest = int(current.get("changes_newest_seq") or 0)
|
||
return {
|
||
"enabled": cfg.hub_sync_changes_enabled,
|
||
"interval_seconds": cfg.hub_sync_changes_interval_seconds,
|
||
"limit": cfg.hub_sync_changes_limit,
|
||
"full_on_gap": cfg.hub_sync_changes_full_on_gap,
|
||
"path": cfg.hub_path_directory_changes,
|
||
"cursor": cursor,
|
||
"applied_total": int(current.get("changes_applied_total") or 0),
|
||
"newest_seq": newest,
|
||
# 落后多少条:只在拉过一次之后才知道,没同步过时给 None 而不是假的 0
|
||
"lag": max(0, newest - cursor) if cursor is not None else None,
|
||
"poll_at": str(current.get("changes_poll_at") or ""),
|
||
"error": str(current.get("changes_error") or ""),
|
||
"error_at": str(current.get("changes_error_at") or ""),
|
||
}
|
||
|
||
|
||
def _stamp(value: object) -> datetime | None:
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return None
|
||
try:
|
||
return datetime.strptime(text, "%Y-%m-%d %H:%M:%S")
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def _event_id(event: dict[str, Any], data: dict[str, Any]) -> int | None:
|
||
"""变更事件的主键:先认 ``entity_id``,再退回 ``data`` 里那三个键。
|
||
|
||
``data`` 的键名随来源变化——``source=hub`` 的事件用 ``id``,``source=wecom`` 用
|
||
``organization_id``/``user_id``(文档 6.4 明说了这个坑),``entity_id`` 才是稳定那个。
|
||
"""
|
||
for source, key in ((event, "entity_id"), (data, "user_id"), (data, "organization_id"), (data, "id")):
|
||
value = models.as_id(source.get(key))
|
||
if value:
|
||
return int(value)
|
||
return None
|
||
|
||
|
||
def _person_by_hub_id(db: Session, hub_user_id: int) -> models.User | None:
|
||
return db.execute(
|
||
select(models.User).where(models.User.hub_user_id == int(hub_user_id))
|
||
).scalars().first()
|
||
|
||
|
||
def _hub_unit_map(db: Session) -> dict[int, int]:
|
||
"""``hub_org_id -> 本地 unit_id``,增量事件换算部门用。"""
|
||
rows = db.execute(
|
||
select(models.Unit.id, models.Unit.hub_org_id).where(models.Unit.hub_org_id.isnot(None))
|
||
).all()
|
||
return {int(hub_id): int(unit_id) for unit_id, hub_id in rows if hub_id}
|
||
|
||
|
||
def _apply_user_event(
|
||
db: Session,
|
||
event: dict[str, Any],
|
||
stats: SyncStats,
|
||
now: datetime,
|
||
unit_map: dict[int, int],
|
||
) -> str:
|
||
"""落一条人员变更。三种 payload 分开走,口径与全量同步完全一致。
|
||
|
||
* **完整人员对象**(``source=wecom`` 同步写入、待认领绑定已有账号):直接把这个人塞给
|
||
全量那套 :func:`_sync_people`,认主键、认领本地同名号、改名、换部门、护栏一次都不少;
|
||
* **补丁**(``source=hub`` 的调部门 / 注册审核通过):``{"id":..,"organization_id":..}``
|
||
或 ``{"id":..,"status":..}``,只动那一个字段;
|
||
* **``delete``**(管理员删除用户):本地按主键软删——停用 + 吊销刷新令牌,
|
||
单据与流程历史原样留着(文档 6.3 第 4 条:``delete`` 按主键软删除)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
data = event.get("data") if isinstance(event.get("data"), dict) else {}
|
||
op = str(event.get("op") or "").strip().lower()
|
||
hub_user_id = _event_id(event, data)
|
||
if not hub_user_id:
|
||
stats.changes_skipped += 1
|
||
stats.note("有一条人员变更没带主键,已跳过,等夜间全量校对")
|
||
return IGNORED
|
||
|
||
person = _person_by_hub_id(db, int(hub_user_id))
|
||
|
||
if op == OP_DELETE:
|
||
if person is None:
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
if is_emergency_account(person.account) or _protect_from_hub(cfg, person):
|
||
stats.protected += 1
|
||
stats.note(f"{person.account} 是本地应急/受保护账号,Hub 的删除事件没有停用它")
|
||
return IGNORED
|
||
db.execute(delete(models.RefreshToken).where(models.RefreshToken.person == str(person.id)))
|
||
if person.status != models.UserStatus.DISABLED:
|
||
person.status = models.UserStatus.DISABLED
|
||
stats.offboarded += 1
|
||
return APPLIED
|
||
|
||
account = str(data.get("account") or "").strip()
|
||
if account:
|
||
_sync_people(
|
||
db,
|
||
[
|
||
{
|
||
"user_id": int(hub_user_id),
|
||
"account": account,
|
||
"display_name": data.get("display_name") or "",
|
||
"email": data.get("email") or "",
|
||
"organization_id": data.get("organization_id"),
|
||
# 完整对象没带 status 时按在职处理:Hub 的 delete 事件才是离职信号
|
||
"status": data.get("status", 1),
|
||
}
|
||
],
|
||
unit_map,
|
||
stats,
|
||
now,
|
||
)
|
||
return APPLIED
|
||
|
||
if person is None:
|
||
# 补丁指的人本地还没有:多半是这条事件比我们的游标还早、而全量里也没这个人,
|
||
# 为它重拉整棵目录不划算,夜间全量校对会兜住。
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
if is_emergency_account(person.account) or _protect_from_hub(cfg, person):
|
||
stats.protected += 1
|
||
return IGNORED
|
||
|
||
if "organization_id" in data:
|
||
hub_org_id = models.as_id(data.get("organization_id")) or 0
|
||
if hub_org_id and hub_org_id not in unit_map:
|
||
stats.note(
|
||
f"有人被调去 Hub 组织 {hub_org_id},本地还没镜像到这个部门,改拉一次全量对齐层级"
|
||
)
|
||
return NEEDS_FULL
|
||
unit = db.get(models.Unit, unit_map[int(hub_org_id)]) if hub_org_id else None
|
||
target_id = unit.id if unit else None
|
||
if person.organization_id != target_id:
|
||
person.organization_id = target_id
|
||
_move_person_identity(db, person, unit, stats)
|
||
stats.updated += 1
|
||
return APPLIED
|
||
|
||
if "status" in data:
|
||
status = _map_status(models.as_id(data.get("status")) or 0)
|
||
if person.status != status:
|
||
person.status = status
|
||
stats.updated += 1
|
||
return APPLIED
|
||
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
|
||
|
||
def _upsert_single_unit(
|
||
db: Session, node: dict[str, Any], stats: SyncStats, mapped: dict[int, models.Unit]
|
||
) -> str:
|
||
"""把单个组织节点落成 ``oa_unit``。
|
||
|
||
字段口径与 :func:`_sync_units` 一致(``organization_id``/``code``/``name``/``status``/
|
||
``parent_id``),差别在**这里绝不做"Hub 里没出现就停用"的判定**:增量事件只描述发生了
|
||
的那一件事,把它当全量清单用会把整个组织架构停掉。父级还没镜像过来时先按"不知道父级"
|
||
落,同时回 ``NEEDS_FULL``,层级由随后那趟全量刷准(文档 6.4:禁止靠增量 payload 推导父子)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
hub_id = models.as_id(node.get("organization_id")) or models.as_id(node.get("id"))
|
||
code = models.clip(str(node.get("code") or "").strip(), 190)
|
||
if not hub_id or int(hub_id) <= 0 or code == UNASSIGNED:
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
hub_id = int(hub_id)
|
||
name = models.clip(str(node.get("name") or "").strip(), 255) or f"组织{hub_id}"
|
||
status = models.UnitStatus.normalize(models.as_id(node.get("status")))
|
||
parent_hub_id = models.as_id(node.get("parent_id")) or 0
|
||
parent = mapped.get(parent_hub_id) if parent_hub_id else None
|
||
needs_full = bool(parent_hub_id and parent is None and parent_hub_id != hub_id)
|
||
if needs_full:
|
||
stats.note(f"Hub 组织 {hub_id} 的上级 {parent_hub_id} 本地还没有,先落节点,层级由全量重对齐")
|
||
|
||
unit = mapped.get(hub_id)
|
||
claimed = False
|
||
if unit is None:
|
||
candidates = [row for row in _local_units_by_code(db).get(code, [])] if code else []
|
||
if len(candidates) == 1 and cfg.hub_sync_bind_local_by_code:
|
||
unit = candidates[0]
|
||
claimed = True
|
||
elif len(candidates) > 1:
|
||
stats.note(f"本地有 {len(candidates)} 个部门都用编码 {code},认领不了,按新部门建")
|
||
|
||
if unit is None:
|
||
unit = models.Unit(
|
||
name=name,
|
||
code=code,
|
||
alias=code,
|
||
description="由统一身份同步创建",
|
||
parent_id=parent.id if parent else None,
|
||
hub_org_id=hub_id,
|
||
status=status,
|
||
)
|
||
db.add(unit)
|
||
db.flush()
|
||
mapped[hub_id] = unit
|
||
stats.units_created += 1
|
||
else:
|
||
parent_id = parent.id if parent else unit.parent_id
|
||
changed = (
|
||
unit.name != name
|
||
or unit.parent_id != parent_id
|
||
or unit.status != status
|
||
or bool(code and unit.code != code)
|
||
)
|
||
if changed:
|
||
_record_pair(stats.unit_name_map, unit.name, name)
|
||
unit.name = name
|
||
unit.parent_id = parent_id
|
||
unit.status = status
|
||
if code:
|
||
unit.code = code
|
||
if claimed:
|
||
stats.units_bound += 1
|
||
else:
|
||
stats.units_updated += 1
|
||
mapped[hub_id] = unit
|
||
|
||
_refresh_paths(db, unit, parent, stats)
|
||
return NEEDS_FULL if needs_full else APPLIED
|
||
|
||
|
||
def _apply_org_event(
|
||
db: Session, event: dict[str, Any], stats: SyncStats, org_map: dict[int, models.Unit]
|
||
) -> str:
|
||
"""落一条组织变更。
|
||
|
||
文档 6.4 说得很直白:状态与移动事件只带 ``id`` 加一个字段,不带 ``path``,组织停用也
|
||
不会给子孙逐个发事件,**收到这类事件应当回头拉全量**。所以这里:
|
||
|
||
* 完整组织对象(带 ``name``)→ 落这一个节点;
|
||
* 只带 ``status`` 的补丁 → 本节点状态照抄(子树留全量判),并要求回全量;
|
||
* 只带 ``parent_id`` 的补丁 → 一个字段都不动,直接要求回全量(没 ``path`` 就挪不准);
|
||
* ``delete`` → 本地按主键停用(软删,留着壳子等 Hub 加回来)。
|
||
"""
|
||
data = event.get("data") if isinstance(event.get("data"), dict) else {}
|
||
op = str(event.get("op") or "").strip().lower()
|
||
hub_org_id = _event_id(event, data)
|
||
if not hub_org_id:
|
||
stats.changes_skipped += 1
|
||
stats.note("有一条组织变更没带主键,已跳过,等夜间全量校对")
|
||
return IGNORED
|
||
|
||
unit = org_map.get(int(hub_org_id))
|
||
|
||
if op == OP_DELETE:
|
||
if unit is None:
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
if unit.status != models.UnitStatus.DISABLED:
|
||
unit.status = models.UnitStatus.DISABLED
|
||
stats.units_offboarded += 1
|
||
stats.note(f"Hub 删除了组织 {hub_org_id},本地部门 {unit.name} 已停用(部门本身保留)")
|
||
return APPLIED
|
||
|
||
if str(data.get("name") or "").strip():
|
||
return _upsert_single_unit(db, data, stats, org_map)
|
||
|
||
if "parent_id" in data:
|
||
stats.note(
|
||
f"Hub 组织 {hub_org_id} 挪了上级,增量事件不带 path,推不出新层级,改拉一次全量"
|
||
)
|
||
return NEEDS_FULL
|
||
|
||
if "status" in data:
|
||
new_status = models.UnitStatus.normalize(models.as_id(data.get("status")))
|
||
if unit is not None and unit.status != new_status:
|
||
unit.status = new_status
|
||
stats.units_updated += 1
|
||
if new_status != models.UnitStatus.ACTIVE:
|
||
stats.note(
|
||
f"Hub 组织 {hub_org_id} 被停用:整棵子树的可达性以下一趟全量为准"
|
||
"(Hub 不会给子孙逐个发事件)"
|
||
)
|
||
return NEEDS_FULL
|
||
return APPLIED
|
||
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
|
||
|
||
def _apply_event(
|
||
db: Session,
|
||
event: Any,
|
||
stats: SyncStats,
|
||
now: datetime,
|
||
unit_map: dict[int, int],
|
||
org_map: dict[int, models.Unit],
|
||
) -> str:
|
||
if not isinstance(event, dict):
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
entity = str(event.get("entity") or "").strip().lower()
|
||
if entity == EVENT_USER:
|
||
return _apply_user_event(db, event, stats, now, unit_map)
|
||
if entity == EVENT_ORGANIZATION:
|
||
return _apply_org_event(db, event, stats, org_map)
|
||
stats.changes_skipped += 1
|
||
stats.note(f"变更流水里出现了不认识的实体类型 {entity or '(空)'},已跳过")
|
||
return IGNORED
|
||
|
||
|
||
def _probe_newest_seq(hub_client: hub_api.HubClient, token: str) -> int:
|
||
"""探一下 Hub 流水的最新 ``seq``:首次全量之后从这里开始追(文档 6.3 第 1 步)。"""
|
||
payload = hub_client.directory_changes(0, limit=1, token=token)
|
||
return models.as_id(payload.get("newest_seq")) or 0
|
||
|
||
|
||
def _pull_changes(
|
||
db: Session,
|
||
*,
|
||
operator: str = "",
|
||
operator_name: str = "",
|
||
manual: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""按游标把变更流水拉干净并落库;需要回全量时不写游标,交给 :func:`sync_changes` 收尾。"""
|
||
cfg = hubconfig.get()
|
||
if not cfg.sync_allowed:
|
||
raise HubSyncError("未启用统一身份认证,请检查 hub_enabled / hub_base_url")
|
||
if not cfg.hub_sync_changes_enabled and not manual:
|
||
raise HubSyncError("增量同步已关闭(hub_sync.changes.enabled = false)")
|
||
if not _run_lock.acquire(blocking=False):
|
||
raise HubSyncError("已有同步任务正在执行,请稍后再试")
|
||
|
||
now = datetime.now()
|
||
set_state(db, {"changes_poll_at": now.strftime("%Y-%m-%d %H:%M:%S")})
|
||
run = models.HubSyncRun(
|
||
trigger=models.HubSyncRun.TRIGGER_CHANGES,
|
||
status="running",
|
||
started_at=now,
|
||
operator=operator,
|
||
operator_name=operator_name,
|
||
)
|
||
db.add(run)
|
||
db.commit()
|
||
run_id = run.id
|
||
|
||
stats = SyncStats()
|
||
try:
|
||
hub_client = hub_api.client()
|
||
token, stats.credential = hub_api.sync_token(hub_client)
|
||
cursor = changes_cursor(db)
|
||
bootstrap = cursor is None
|
||
if bootstrap:
|
||
# 从没对齐过:先把游标探到流水尾部。全量落完之后从这里开始追,
|
||
# 中间真有的改动会在下一轮增量里重放一次(都是幂等 upsert,重放无害)。
|
||
cursor = _probe_newest_seq(hub_client, token)
|
||
stats.cursor_seq = int(cursor or 0)
|
||
|
||
needs_full = bootstrap
|
||
newest = int(cursor or 0)
|
||
committed_applied = 0
|
||
rounds = 0
|
||
while not bootstrap and rounds < MAX_CHANGE_ROUNDS:
|
||
rounds += 1
|
||
payload = hub_client.directory_changes(cursor, limit=cfg.hub_sync_changes_limit, token=token)
|
||
oldest = models.as_id(payload.get("oldest_seq")) or 0
|
||
newest = models.as_id(payload.get("newest_seq")) or newest
|
||
batch = [row for row in (payload.get("changes") or []) if isinstance(row, dict)]
|
||
batch_cursor = models.as_id(payload.get("cursor"))
|
||
|
||
# 游标 0 表示"一条都没见过",这时最老的流水就是能拿到的第一条,不算缺口;
|
||
# 真正的缺口是"取过一些、但那批已经被裁剪"(文档 6.2:必须回到全量)。
|
||
if oldest and int(cursor) > 0 and int(cursor) < oldest:
|
||
needs_full = True
|
||
stats.note(
|
||
f"本地游标 {cursor} 比 Hub 侧最老的流水 {oldest} 还旧,"
|
||
"中间那段已经取不回来,改拉一次全量重对齐"
|
||
)
|
||
else:
|
||
# 每批现取一次映射:同批的组织事件可能刚建新部门,后面的人员事件要用到
|
||
org_map = _hub_units(db, stats)
|
||
unit_map = {hub_id: unit.id for hub_id, unit in org_map.items()}
|
||
for event in batch:
|
||
outcome = _apply_event(db, event, stats, datetime.now(), unit_map, org_map)
|
||
if outcome == APPLIED:
|
||
stats.changes_applied += 1
|
||
elif outcome == NEEDS_FULL:
|
||
needs_full = True
|
||
break
|
||
previous_cursor = int(cursor)
|
||
if batch_cursor is not None:
|
||
cursor = int(batch_cursor)
|
||
elif batch:
|
||
cursor = max(int(row.get("seq") or 0) for row in batch)
|
||
stats.cursor_seq = int(cursor)
|
||
|
||
if needs_full:
|
||
break
|
||
db.commit()
|
||
committed_applied = stats.changes_applied
|
||
if not payload.get("has_more"):
|
||
break
|
||
if int(cursor) <= previous_cursor:
|
||
# Hub 说还有、但游标一步没动:再多翻几轮也只是原地打转,停手等下一趟
|
||
stats.note("Hub 返回 has_more=true 但游标没有前进,本轮到此为止,下一趟接着拉")
|
||
break
|
||
|
||
# 游标只有在"这批落干净了"或"明知补不回来、决定跳过"时才往前推;
|
||
# 要回全量的那一批先丢掉,等全量盖完由 sync_changes 推游标。
|
||
give_up = needs_full and not cfg.hub_sync_changes_full_on_gap
|
||
if needs_full and cfg.hub_sync_changes_full_on_gap:
|
||
db.rollback()
|
||
stats.changes_applied = committed_applied
|
||
patch = {
|
||
"changes_newest_seq": int(newest or 0),
|
||
"changes_error": "",
|
||
"changes_error_at": "",
|
||
}
|
||
if not needs_full or give_up:
|
||
patch["changes_cursor"] = int(cursor or 0)
|
||
patch["changes_applied_total"] = (
|
||
int(state(db).get("changes_applied_total") or 0) + stats.changes_applied
|
||
)
|
||
_finish(
|
||
db,
|
||
run_id,
|
||
stats,
|
||
models.HubSyncRun.STATUS_SUCCESS,
|
||
";".join(stats.messages),
|
||
state_patch=patch,
|
||
)
|
||
return {
|
||
"run": serialize_run(latest_run(db) or run),
|
||
"cursor": int(cursor or 0),
|
||
"applied": stats.changes_applied,
|
||
"skipped": stats.changes_skipped,
|
||
"needs_full": bool(needs_full),
|
||
"bootstrap": bootstrap,
|
||
"rounds": rounds,
|
||
"messages": stats.messages,
|
||
}
|
||
except HubSyncError as exc:
|
||
db.rollback()
|
||
_finish(
|
||
db, run_id, stats, models.HubSyncRun.STATUS_FAILED, str(exc),
|
||
state_patch={"changes_error": str(exc)[:500], "changes_error_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
|
||
)
|
||
raise
|
||
except hub_api.HubError as exc:
|
||
db.rollback()
|
||
_finish(
|
||
db, run_id, stats, models.HubSyncRun.STATUS_FAILED, exc.message,
|
||
state_patch={"changes_error": exc.message[:500], "changes_error_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
|
||
)
|
||
raise HubSyncError(exc.message) from exc
|
||
except Exception as exc: # pragma: no cover - 兜底,别把调度线程带崩
|
||
logger.exception("Hub 增量同步失败")
|
||
db.rollback()
|
||
_finish(
|
||
db, run_id, stats, models.HubSyncRun.STATUS_FAILED, f"增量同步异常:{exc}",
|
||
state_patch={"changes_error": str(exc)[:500], "changes_error_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")},
|
||
)
|
||
raise HubSyncError(f"增量同步异常:{exc}") from exc
|
||
finally:
|
||
_run_lock.release()
|
||
|
||
|
||
def sync_changes(
|
||
db: Session,
|
||
*,
|
||
operator: str = "",
|
||
operator_name: str = "",
|
||
manual: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""增量同步一趟:拉变更流水落库,必要时改拉一次全量重对齐(文档 6.3 第 2、3 步)。
|
||
|
||
游标只在"这批真的处理干净"之后才提交(``has_more=false``),中途失败下次从原地重拉。
|
||
需要回全量时(首次对齐、流水缺口、只带 ``id`` 的组织层级事件、本地没镜像到的部门),
|
||
先释放同步锁再跑 :func:`sync_users`,全量落成功才把游标推上去——全量失败就留在原地,
|
||
下一轮重试,绝不会出现"流水没落库但游标已经跑掉"。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
result = _pull_changes(db, operator=operator, operator_name=operator_name, manual=manual)
|
||
if not result.get("needs_full"):
|
||
return {**result, "full_resync": False}
|
||
|
||
if not cfg.hub_sync_changes_full_on_gap:
|
||
result["full_resync"] = False
|
||
result["messages"] = [
|
||
*result.get("messages", []),
|
||
"已关闭「落后过多就回全量」:推不出的那几条只记日志,游标照常往前推,差异等夜间全量校对补齐",
|
||
]
|
||
return result
|
||
|
||
try:
|
||
full = sync_users(
|
||
db,
|
||
trigger=models.HubSyncRun.TRIGGER_SCHEDULE,
|
||
operator=operator or "hub-changes",
|
||
operator_name=operator_name or "增量同步触发的全量",
|
||
)
|
||
result["full_resync"] = True
|
||
result["full_run"] = full.get("run")
|
||
set_state(db, {"changes_cursor": int(result.get("cursor") or 0)})
|
||
except HubSyncError as exc:
|
||
result["full_resync"] = False
|
||
result["full_error"] = str(exc)
|
||
result["messages"] = [*result.get("messages", []), f"需要回全量重对齐,但全量没跑成:{exc}"]
|
||
return result
|
||
|
||
|
||
def changes_due(db: Session, now: datetime | None = None) -> bool:
|
||
"""这一分钟要不要去拉一次变更流水。"""
|
||
cfg = hubconfig.get()
|
||
now = now or datetime.now()
|
||
if not cfg.sync_allowed or not cfg.hub_sync_enabled or not cfg.hub_sync_changes_enabled:
|
||
return False
|
||
current = state(db)
|
||
last = _stamp(current.get("changes_poll_at"))
|
||
if last is not None and (now - last).total_seconds() < cfg.hub_sync_changes_interval_seconds:
|
||
return False
|
||
if str(current.get("changes_error") or ""):
|
||
failed_at = _stamp(current.get("changes_error_at"))
|
||
if failed_at is not None and (now - failed_at).total_seconds() < cfg.hub_sync_retry_minutes * 60:
|
||
return False
|
||
return True
|
||
|
||
|
||
def run_scheduled_changes(db: Session, now: datetime | None = None) -> bool:
|
||
"""调度线程每轮调一次;真的拉了一批才返回 True。"""
|
||
if not changes_due(db, now):
|
||
return False
|
||
try:
|
||
result = sync_changes(db)
|
||
except HubSyncError as exc:
|
||
logger.warning("Hub 增量同步失败:%s", exc)
|
||
return False
|
||
except Exception: # pragma: no cover - defensive
|
||
logger.exception("Hub 增量同步异常")
|
||
return False
|
||
if result.get("applied") or result.get("needs_full"):
|
||
logger.info(
|
||
"Hub 增量同步:落了 %s 条变更,游标 %s,%s",
|
||
result.get("applied", 0),
|
||
result.get("cursor", 0),
|
||
"并回了一次全量" if result.get("full_resync") else ("需要回全量但没跑成" if result.get("needs_full") else "无缺口"),
|
||
)
|
||
return True
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 定时调度
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def due_now(db: Session, now: datetime | None = None) -> bool:
|
||
"""这一分钟要不要拉一次全量。
|
||
|
||
判定搬到 :mod:`app.service.sync_jobs` 了——那边要同时服务"界面上显示下一次几点跑"
|
||
和"调度线程问该不该跑",两件事必须走同一段代码。这里留着转发,一是老调用点
|
||
(含验收脚本)都叫这个名字,二是"同步的口径去 hub_sync 找"仍然说得通。
|
||
"""
|
||
return sync_jobs.full_due(db, now)
|
||
|
||
|
||
def run_scheduled(db: Session, now: datetime | None = None) -> bool:
|
||
"""调度线程每分钟调一次;真正跑起来才返回 True。"""
|
||
if not due_now(db, now):
|
||
return False
|
||
try:
|
||
sync_users(db, trigger=models.HubSyncRun.TRIGGER_SCHEDULE)
|
||
except HubSyncError as exc:
|
||
logger.warning("定时同步 Hub 组织人员失败:%s", exc)
|
||
return False
|
||
except Exception: # pragma: no cover - defensive
|
||
logger.exception("定时同步 Hub 组织人员异常")
|
||
return False
|
||
return True
|
||
|
||
|
||
def preview(db: Session, *, member_limit: int | None = None) -> dict[str, Any]:
|
||
"""只拉不写:先看清 Hub 那边有什么、本地会动多少,再决定要不要真同步。
|
||
|
||
文档第 11 节的建议是正式同步前把 ``member_limit`` 调够大,所以这里默认沿用同步
|
||
口径的 ``OA_HUB_SYNC_MEMBER_LIMIT``,并把 ``truncated`` 原样带回去。整个过程只读,
|
||
不占同步锁,也不写 ``oa_hub_sync_run``。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
if not cfg.hub_enabled or not cfg.hub_base_url:
|
||
raise HubSyncError("未启用统一身份认证,请检查 OA_HUB_ENABLED / OA_HUB_BASE_URL")
|
||
limit = max(1, min(5000, int(member_limit or cfg.hub_sync_member_limit or 2000)))
|
||
hub_client = hub_api.client()
|
||
token, mode = hub_api.sync_token(hub_client)
|
||
try:
|
||
payload = hub_client.directory(
|
||
token,
|
||
include_disabled=True,
|
||
include_disabled_users=True,
|
||
member_limit=limit,
|
||
)
|
||
except hub_api.HubError as exc:
|
||
raise HubSyncError(exc.message) from exc
|
||
|
||
organizations = payload.get("organizations") if isinstance(payload.get("organizations"), list) else []
|
||
hub_users = [row for row in (payload.get("users") or []) if isinstance(row, dict)]
|
||
truncated = bool(payload.get("truncated"))
|
||
|
||
org_ids: set[int] = set()
|
||
orgs: list[dict[str, Any]] = []
|
||
parents: dict[int, int] = {}
|
||
for node, parent_hub_id in _iter_org_nodes(_org_tree(organizations)):
|
||
hub_id = models.as_id(node.get("organization_id"))
|
||
code = str(node.get("code") or "").strip()
|
||
if not hub_id or hub_id <= 0 or code == UNASSIGNED:
|
||
continue
|
||
org_ids.add(hub_id)
|
||
parents[hub_id] = models.as_id(parent_hub_id) or 0
|
||
orgs.append(
|
||
{
|
||
"hub_org_id": hub_id,
|
||
"code": code,
|
||
"name": str(node.get("name") or ""),
|
||
"status": models.UnitStatus.normalize(models.as_id(node.get("status"))),
|
||
"status_label": models.UnitStatus.label(models.as_id(node.get("status"))),
|
||
"member_count": int(models.as_id(node.get("member_count")) or 0),
|
||
}
|
||
)
|
||
units_all = list(db.execute(select(models.Unit).order_by(models.Unit.id)).scalars().all())
|
||
unit_by_id = {row.id: row for row in units_all}
|
||
known_units = {
|
||
int(row.hub_org_id): row for row in units_all if row.hub_org_id
|
||
}
|
||
local_units = [row for row in units_all if not row.hub_org_id]
|
||
local_by_code: dict[str, list[models.Unit]] = {}
|
||
for row in local_units:
|
||
if row.code:
|
||
local_by_code.setdefault(str(row.code), []).append(row)
|
||
|
||
# 组织侧预检:会改名/挪层级的部门、能按编码认领下来的本地部门、挂在将消失部门下的本地部门
|
||
unit_name_map: dict[str, str] = {}
|
||
renamed_units = 0
|
||
moved_units = 0
|
||
claimable = 0
|
||
claimed_codes: set[str] = set()
|
||
for row in orgs:
|
||
known = known_units.get(int(row["hub_org_id"]))
|
||
if known is None:
|
||
candidates = local_by_code.get(row["code"]) or [] if row["code"] else []
|
||
if len(candidates) == 1 and row["code"] not in claimed_codes:
|
||
claimable += 1
|
||
claimed_codes.add(row["code"])
|
||
continue
|
||
if known.name != row["name"] and known.name:
|
||
renamed_units += 1
|
||
unit_name_map[known.name] = row["name"]
|
||
local_parent = unit_by_id.get(known.parent_id) if known.parent_id else None
|
||
local_parent_hub = int(local_parent.hub_org_id or 0) if local_parent and local_parent.hub_org_id else 0
|
||
if local_parent_hub != int(parents.get(int(row["hub_org_id"])) or 0):
|
||
moved_units += 1
|
||
hanging_units = 0
|
||
for row in local_units:
|
||
node = unit_by_id.get(row.parent_id) if row.parent_id else None
|
||
guard = 0
|
||
while node is not None and guard < 64:
|
||
if node.hub_org_id and (
|
||
node.hub_org_id not in org_ids or node.status == models.UnitStatus.DISABLED
|
||
):
|
||
hanging_units += 1
|
||
break
|
||
node = unit_by_id.get(node.parent_id) if node.parent_id else None
|
||
guard += 1
|
||
|
||
by_hub_id: dict[int, models.User] = {}
|
||
by_account: dict[str, models.User] = {}
|
||
hub_source: list[models.User] = []
|
||
for row in db.execute(select(models.User).order_by(models.User.id)).scalars().all():
|
||
if row.account:
|
||
by_account.setdefault(row.account, row)
|
||
if row.hub_user_id:
|
||
by_hub_id[int(row.hub_user_id)] = row
|
||
if row.source == models.AccountSource.HUB:
|
||
hub_source.append(row)
|
||
|
||
# 人员侧预检:身份只按 Hub 主键算,跟同步用的是同一套判据
|
||
seen_ids: set[int] = set()
|
||
new_people = 0
|
||
adopted = 0
|
||
inactive = 0
|
||
unassigned = 0
|
||
protected = 0
|
||
conflicts = 0
|
||
no_id = 0
|
||
account_map: dict[str, str] = {}
|
||
person_name_map: dict[str, str] = {}
|
||
for item in hub_users:
|
||
account = str(item.get("account") or "").strip()
|
||
hub_user_id = models.as_id(item.get("user_id")) or 0
|
||
if not account or not hub_user_id:
|
||
no_id += 1
|
||
continue
|
||
seen_ids.add(int(hub_user_id))
|
||
if int(models.as_id(item.get("status")) or 0) != 1:
|
||
inactive += 1
|
||
hub_org_id = models.as_id(item.get("organization_id")) or 0
|
||
if not hub_org_id or hub_org_id not in org_ids:
|
||
unassigned += 1
|
||
person = by_hub_id.get(int(hub_user_id))
|
||
if person is not None:
|
||
if _protect_from_hub(cfg, person) or is_emergency_account(person.account):
|
||
protected += 1
|
||
if person.account and person.account != account:
|
||
account_map[person.account] = account
|
||
display_name = str(item.get("display_name") or "").strip()
|
||
if display_name and person.display_name and person.display_name != display_name:
|
||
person_name_map[person.display_name] = display_name
|
||
continue
|
||
holder = by_account.get(account)
|
||
if holder is None:
|
||
new_people += 1
|
||
elif holder.hub_user_id:
|
||
# 账号已经代表 Hub 里的另一个人了,同步会跳过,不会把两个人并起来
|
||
conflicts += 1
|
||
elif is_emergency_account(holder.account) or _protect_from_hub(cfg, holder):
|
||
protected += 1
|
||
else:
|
||
adopted += 1
|
||
|
||
offboard_candidates = [
|
||
row.account
|
||
for row in hub_source
|
||
if row.hub_user_id
|
||
and int(row.hub_user_id) not in seen_ids
|
||
and not (cfg.hub_sync_protect_admins and row.role == models.ROLE_ADMIN)
|
||
]
|
||
unbound = len([row for row in hub_source if not row.hub_user_id])
|
||
|
||
# 影响预检:Hub 一改名字就会牵动的"按字符串存的"配置(审批岗位、共享名单…)。
|
||
# 权限角色与数据范围是按 users.id / oa_unit.id 挂的,同步不动主键,所以不在这里出现。
|
||
refs_total, refs_samples = hub_refs.scan(
|
||
db,
|
||
hub_refs.build_maps(
|
||
unit_name_map=unit_name_map,
|
||
display_name_map=person_name_map,
|
||
account_map=account_map,
|
||
),
|
||
)
|
||
|
||
return {
|
||
"credential": mode,
|
||
"credential_label": credential_label(mode),
|
||
"permission_version": models.as_id(payload.get("permission_version")) or 0,
|
||
"total_users": models.as_id(payload.get("total_users")) or 0,
|
||
"returned_users": models.as_id(payload.get("returned_users")) or len(hub_users),
|
||
"member_limit": models.as_id(payload.get("member_limit")) or limit,
|
||
"truncated": truncated,
|
||
"organizations": {
|
||
"total": len(orgs),
|
||
"new": len(org_ids - set(known_units)) - claimable,
|
||
"known": len(org_ids & set(known_units)),
|
||
"disabled": len([row for row in orgs if row["status"] != models.UnitStatus.ACTIVE]),
|
||
"offboard_candidates": len(set(known_units) - org_ids),
|
||
"renamed": renamed_units,
|
||
"moved": moved_units,
|
||
# 本系统自己加的部门:同步不碰它们,只报规模与风险
|
||
"local_units": len(local_units),
|
||
"claimable_by_code": claimable,
|
||
"local_hanging_units": hanging_units,
|
||
},
|
||
"users": {
|
||
"new": new_people,
|
||
"adopt_candidates": adopted,
|
||
"inactive": inactive,
|
||
"unassigned": unassigned,
|
||
"protected_admins": protected,
|
||
"offboard_candidates": len(offboard_candidates),
|
||
"no_hub_id": no_id,
|
||
"account_conflicts": conflicts,
|
||
"account_renames": len(account_map),
|
||
"name_renames": len(person_name_map),
|
||
"unbound": unbound,
|
||
# Hub 的目录接口只回启用的人(我们照常带 include_disabled_users=true),
|
||
# 所以 inactive 恒为 0,"在 Hub 被停用"会算进 offboard_candidates。
|
||
"directory_hides_disabled_users": True,
|
||
"disabled_note": (
|
||
"统一身份的目录接口不下发已停用人员,inactive 因此恒为 0;"
|
||
"在 Hub 被停用的人会落在 offboard_candidates 里,本地按离职停用处理(不删行)"
|
||
),
|
||
},
|
||
"impact": {
|
||
"renamed_units": renamed_units,
|
||
"moved_units": moved_units,
|
||
"renamed_accounts": len(account_map),
|
||
"renamed_people": len(person_name_map),
|
||
"refs_at_risk": refs_total,
|
||
"samples": refs_samples,
|
||
"note": (
|
||
"权限角色、数据范围、部门负责人都按主键存,同步不改主键也不删行,不会掉;"
|
||
"这里列的是按名字/账号/身份 DN 存下的审批岗位与共享名单,同步会自动搬到新值,"
|
||
"搬不动的会写进同步记录"
|
||
),
|
||
},
|
||
"offboard_accounts": offboard_candidates[:20],
|
||
"organization_sample": orgs[:10],
|
||
"warning": (
|
||
f"人员清单被 member_limit={limit} 截断,本次数字只能当规模参考,"
|
||
"正式同步前先调大 OA_HUB_SYNC_MEMBER_LIMIT"
|
||
if truncated
|
||
else ""
|
||
),
|
||
}
|
||
|
||
|
||
def probe(db: Session | None = None) -> dict[str, Any]:
|
||
"""连通性自检:目录接口能不能拉、同步凭证(可无)好不好用、免登与增量接口通不通。
|
||
|
||
``db`` 只用来顺带回显增量游标(自检本身不写库)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
steps: list[dict[str, Any]] = []
|
||
ok = True
|
||
member_limit = max(1, min(5000, int(cfg.hub_sync_member_limit or 2000)))
|
||
try:
|
||
hub_client = hub_api.client()
|
||
token, mode = hub_api.sync_token(hub_client)
|
||
payload = hub_client.directory(
|
||
token, include_disabled=True, include_disabled_users=True, member_limit=member_limit
|
||
)
|
||
total = models.as_id(payload.get("total_users")) or 0
|
||
version = models.as_id(payload.get("permission_version")) or 0
|
||
steps.append(
|
||
{
|
||
"name": f"全量目录接口 {cfg.hub_path_directory}",
|
||
"ok": True,
|
||
"detail": f"凭证 {credential_label(mode)};共 {total} 人,permission_version {version}",
|
||
}
|
||
)
|
||
except hub_api.HubError as exc:
|
||
mode = credential_mode()
|
||
steps.append({"name": f"全量目录接口 {cfg.hub_path_directory}", "ok": False, "detail": exc.message})
|
||
ok = False
|
||
|
||
if mode == "directory_key":
|
||
# 上面那一步就是用密钥拉的,拉通了就说明密钥是对的
|
||
steps.append(
|
||
{
|
||
"name": "目录密钥",
|
||
"ok": True,
|
||
"detail": "已配置,随请求头 X-Directory-Key 带出(明文不回显)",
|
||
}
|
||
)
|
||
elif mode == "anonymous":
|
||
steps.append(
|
||
{
|
||
"name": "同步凭证",
|
||
"ok": not cfg.hub_directory_needs_token,
|
||
"detail": (
|
||
"未配置任何凭证:Hub 的目录接口要目录密钥(X-Directory-Key),"
|
||
"不配上多半拉不到,请到系统设置里填「目录密钥」"
|
||
),
|
||
}
|
||
)
|
||
else:
|
||
try:
|
||
state_info = hub_api.client().verify_token(hub_api.service_token())
|
||
steps.append(
|
||
{
|
||
"name": "同步凭证",
|
||
"ok": bool(state_info.active),
|
||
"detail": (
|
||
f"{credential_label(mode)}有效,集成账号 {state_info.account}"
|
||
if state_info.active
|
||
else f"{credential_label(mode)}已失效:{state_info.reason}(同步会失败)"
|
||
),
|
||
}
|
||
)
|
||
ok = ok and state_info.active
|
||
except hub_api.HubError as exc:
|
||
steps.append({"name": "同步凭证", "ok": False, "detail": f"{exc.message}(同步会失败)"})
|
||
ok = False
|
||
|
||
if cfg.login_on:
|
||
try:
|
||
challenge = hub_api.client().captcha()
|
||
steps.append(
|
||
{
|
||
"name": f"登录验证码接口 {cfg.hub_path_captcha}",
|
||
"ok": True,
|
||
"detail": f"返回 {len(challenge)} 个字段",
|
||
}
|
||
)
|
||
except hub_api.HubError as exc:
|
||
steps.append(
|
||
{"name": f"登录验证码接口 {cfg.hub_path_captcha}", "ok": False, "detail": exc.message}
|
||
)
|
||
ok = False
|
||
else:
|
||
steps.append(
|
||
{
|
||
"name": f"登录验证码接口 {cfg.hub_path_captcha}",
|
||
"ok": True,
|
||
"detail": (
|
||
"当前登录模式不走账号密码(免登或本地口令),跳过"
|
||
if cfg.hub_login_mode == "sso"
|
||
else "登录校验未走 Hub,跳过"
|
||
),
|
||
}
|
||
)
|
||
|
||
# 免登:拿一张注定不存在的票据打一次校验接口,是"只验密钥、不消费真票据"的唯一办法
|
||
# (密钥不对会 401,密钥对但票据不存在才会回 active:false + ticket_invalid)。
|
||
if not cfg.hub_sso_enabled:
|
||
steps.append(
|
||
{"name": f"免登票据接口 {cfg.hub_path_ticket_verify}", "ok": True, "detail": "未启用统一门户免登,跳过"}
|
||
)
|
||
elif not cfg.sso_ready:
|
||
steps.append(
|
||
{
|
||
"name": f"免登票据接口 {cfg.hub_path_ticket_verify}",
|
||
"ok": False,
|
||
"detail": "缺 " + "、".join(sso_status()["missing"]) + ":免登整条通道用不了",
|
||
}
|
||
)
|
||
ok = False
|
||
else:
|
||
try:
|
||
probe_ticket = secrets.token_hex(32)
|
||
identity = hub_api.client().verify_ticket(probe_ticket)
|
||
del probe_ticket # 探完就扔:票据不进日志、不进 detail
|
||
if identity.active:
|
||
detail = "接口通,但 Hub 把一张随机票据认成了有效,请核对 Hub 侧实现"
|
||
elif identity.reason in (hub_api.TICKET_INVALID, ""):
|
||
detail = (
|
||
f"接口与免登应用密钥都通(随机票据按预期回 {identity.reason or 'ticket_invalid'});"
|
||
f"应用编码 {cfg.hub_app_code}"
|
||
)
|
||
else:
|
||
detail = f"接口通,但返回了意料之外的结果:{identity.reason}"
|
||
steps.append({"name": f"免登票据接口 {cfg.hub_path_ticket_verify}", "ok": True, "detail": detail})
|
||
except hub_api.HubRejected as exc:
|
||
hint, _reason = hub_api.ticket_reject(exc.code)
|
||
steps.append(
|
||
{
|
||
"name": f"免登票据接口 {cfg.hub_path_ticket_verify}",
|
||
"ok": False,
|
||
"detail": f"{exc.message}(免登会失败)——该查:{hint}",
|
||
}
|
||
)
|
||
ok = False
|
||
except hub_api.HubError as exc:
|
||
steps.append(
|
||
{
|
||
"name": f"免登票据接口 {cfg.hub_path_ticket_verify}",
|
||
"ok": False,
|
||
"detail": f"{exc.message}(免登会失败;密钥被停用/超宽限期也是这一句)",
|
||
}
|
||
)
|
||
ok = False
|
||
|
||
# 门户可见性(文档 3.1):应用注册了、密钥也对,但应用没启用、或这个账号没命中任何
|
||
# 授权角色时,门户里压根没有这张卡片 —— 用户那边只会说"我进不去 OA"。
|
||
apps_path = cfg.hub_path_apps
|
||
if not cfg.sso_on:
|
||
steps.append({"name": f"门户可见性 {apps_path}", "ok": True, "detail": "免登没开或已被总闸关掉,跳过"})
|
||
elif not token:
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": True,
|
||
"detail": f"当前凭证是{credential_label(mode)},没有可用的用户令牌可问,跳过",
|
||
}
|
||
)
|
||
else:
|
||
try:
|
||
wanted = cfg.hub_app_code.strip().lower()
|
||
hit = next(
|
||
(
|
||
row
|
||
for row in hub_api.client().apps(token)
|
||
if str(row.get("code") or "").strip().lower() == wanted
|
||
),
|
||
None,
|
||
)
|
||
if hit is None:
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": False,
|
||
"detail": (
|
||
f"可见应用列表里没有 {cfg.hub_app_code}:应用未注册、已停用,"
|
||
"或这个账号没命中应用的任何授权角色"
|
||
),
|
||
}
|
||
)
|
||
ok = False
|
||
elif str(hit.get("status")) != "1" or str(hit.get("visible")) != "1":
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": False,
|
||
"detail": (
|
||
f"应用在门户里看不到:status={hit.get('status')}、visible={hit.get('visible')},"
|
||
"请在 Hub 管理端启用并设为可见"
|
||
),
|
||
}
|
||
)
|
||
ok = False
|
||
else:
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": True,
|
||
"detail": (
|
||
f"门户里能看到「{hit.get('name') or cfg.hub_app_code}」"
|
||
f"(sso_mode={hit.get('sso_mode') or 'ticket'})"
|
||
),
|
||
}
|
||
)
|
||
except hub_api.HubError as exc:
|
||
# 这一项查不通不该把整次自检判死:有的 Hub 没开这个接口,或只给了目录密钥
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": True,
|
||
"detail": f"没能问到可见应用列表({exc.message}),不影响免登本身",
|
||
}
|
||
)
|
||
|
||
if not cfg.hub_sync_changes_enabled:
|
||
steps.append(
|
||
{
|
||
"name": f"变更流水接口 {cfg.hub_path_directory_changes}",
|
||
"ok": True,
|
||
"detail": "增量同步已关闭,跳过(只剩夜间全量与界面上的立即同步)",
|
||
}
|
||
)
|
||
else:
|
||
try:
|
||
token_for_changes, _mode = hub_api.sync_token(hub_client)
|
||
changes_probe = hub_client.directory_changes(0, limit=1, token=token_for_changes)
|
||
steps.append(
|
||
{
|
||
"name": f"变更流水接口 {cfg.hub_path_directory_changes}",
|
||
"ok": True,
|
||
"detail": (
|
||
f"最新流水 seq {models.as_id(changes_probe.get('newest_seq')) or 0},"
|
||
f"最老可取 seq {models.as_id(changes_probe.get('oldest_seq')) or 0}"
|
||
+ (
|
||
f";本地游标 {changes_cursor(db)}"
|
||
if db is not None and changes_cursor(db) is not None
|
||
else ""
|
||
)
|
||
),
|
||
}
|
||
)
|
||
except hub_api.HubError as exc:
|
||
steps.append(
|
||
{"name": f"变更流水接口 {cfg.hub_path_directory_changes}", "ok": False, "detail": exc.message}
|
||
)
|
||
ok = False
|
||
|
||
# 权限那一层(《Hub 权限接口交互文档》):角色/权限码/数据范围问不问得到、目录对不对得上。
|
||
# 只有"生效模式"下问不到才算整次自检不合格;对照模式下问不到只报问题,不判死。
|
||
permission_steps = hub_perm.probe_steps(token)
|
||
steps.extend(permission_steps)
|
||
ok = ok and all(bool(row.get("ok")) for row in permission_steps)
|
||
|
||
return {
|
||
"ok": ok,
|
||
"base_url": cfg.hub_base_url,
|
||
# 当前用的五个接口路径,排障时一眼看出打的是哪儿
|
||
"api_paths": cfg.api_paths,
|
||
"login_enabled": cfg.login_on,
|
||
"credential": mode,
|
||
"credential_label": credential_label(mode),
|
||
"directory_key_set": bool(cfg.hub_directory_key),
|
||
"directory_needs_token": cfg.hub_directory_needs_token,
|
||
"sso": sso_status(),
|
||
"permission": hub_perm.status_payload(),
|
||
"member_limit": member_limit,
|
||
"steps": steps,
|
||
"message": "统一身份认证服务连通正常" if ok else "统一身份认证服务检查未通过,详见各项说明",
|
||
}
|