unis-oa/backend/app/service/hub_sync.py

3795 lines
180 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

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

"""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`` 为空)永远不碰;
* 手机号(``users.mobile``)只在 Hub **确实带了号码**时才动这一列:Hub 压根没下发这个
字段,和下发了但洗不出合法号码,是两回事——前者保留本地值继续用,后者计数报出来,
两者都不把人家的号码清空。
* 企业微信 UserID(``users.wecom_user_id``)比手机号多一种情况:**"带了字段但值是空的"
是一句话,不是一个缺失**。企微 UserID 会被删掉再分配给另一名员工,所以 Hub 明确说
"这个人没有企微号"时本地跟着清空;压根不带这个字段时仍然原样保留(见 6 节与
:func:`_hub_wecom_user_id`)。Hub 把同一个号同时发给几个人(通讯录里真有这样的事)
时本地**照抄**,几个人都挂着这个号,只在同步记录里报数 —— 这一列是上游的镜像,
不是本地唯一键。
凭证:全量目录接口(文档第 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 re
import secrets
import threading
from collections.abc import Iterable, Iterator
from dataclasses import dataclass, field
from datetime import datetime, timedelta
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 cache
from . import hub as hub_api
from . import hub_refs
from . import hub_perm
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()
#: 本进程的终止时刻(没配 Redis 时只有这一份管用)
_cancel_at: datetime | None = None
#: 跨副本互斥的锁名。两副本同时拉全量 = 同一棵组织树被写两遍、同步记录各记一条,
#: 界面上分不清哪一趟是真的;手动点了「立即同步」的那台和调度线程所在的机器尤其容易撞上。
#: 进程内的 ``_run_lock`` 只管本进程,这一把管所有副本,**Redis 没配时它直接放行**,
#: 退回这份代码昨天的行为(见 :mod:`app.cache`)。
LOCK_SYNC = "hub_sync"
#: 这把锁的兜底持有时间(秒)。一趟全量同步跑到 1 小时说明 Hub 或网络出问题了;
#: 到期自己释放,所以进程被 ``kill -9`` 也不会把同步永久锁死。极端情况下一趟真跑过
#: 1 小时,会出现两副本同时拉 —— 那与接 Redis 之前一样,不是新问题。
LOCK_SYNC_TTL_SECONDS = 3600.0
#: 一条记录挂着「进行中」多久就算残留(秒)。
#:
#: 进程被 ``kill -9``、容器重启、发布时打断一趟同步,``oa_hub_sync_run`` 里那条
#: ``status='running'`` 就再也没人收尾了:锁其实早没了(最多只剩 Redis 那把在等 TTL),
#: 界面上却永远显示「进行中」,连带把「立即同步」按钮一直按住。取
#: :data:`LOCK_SYNC_TTL_SECONDS` 的一半 —— 真在跑的同步都持着锁,够不着这一档,
#: 而且 :func:`status_payload` 只在 ``not running()`` 时才来收。
STALE_RUN_GRACE_SECONDS = 1800.0
#: 自动收尾时写在记录上的那句话(手动终止另有说法,见 :func:`terminate_sync`)
STALE_RUN_MESSAGE = "同步进程中断:这条记录没能自己收尾,已标记为终止(不影响下一趟同步)"
#: 「终止」信号的 Redis 键名后缀(真键名过 :func:`app.cache.key` 加前缀)。
#: 存的是**按下终止的那一刻**而不是一个布尔:判据是"这一趟开始之后有没有人按过",
#: 于是刚终止完立刻重开的那一趟不会被上一趟留下的旧标记误停。
CANCEL_KEY_NAME = "hub_sync_cancel"
#: 这个标记留多久(秒):只给正在跑的那一趟看,一小时足够任何一趟走到下一个检查点
CANCEL_TTL_SECONDS = 3600.0
#: 每处理多少条看一次终止信号。一万人的清单也就四百次读,换的是"叫停之后几秒内
#: 真停手"而不是"两千个人之后才停";一次都看不到也没关系,收尾前的检查点兜得住。
CANCEL_CHECK_EVERY = 25
class HubSyncError(Exception):
"""同步没能跑完(配置缺失、Hub 不可用、数据不完整等)。"""
class HubSyncCancelled(HubSyncError):
"""这一趟被人在界面上「终止」了。
单独一个类型只为了一件事:记录要写「已终止」而不是「失败」。走 ``HubSyncError``
那条兜底分支的话,一次人为终止会被记成同步失败,接着触发 ``retry_minutes`` 补试,
刚被我叫停的活儿又被调度线程捞起来重跑。
"""
#: Hub 人员对象里手机号可能用的字段名。目录接口的文档(第 11 节)只写了
#: ``account``/``display_name``/``email``,号码是各家部署陆续补上的字段,
#: 企业微信同步过去的那批还常写作 ``phone``,所以一次都认了。
MOBILE_KEYS = ("mobile", "phone", "telephone", "phone_number", "phonenumber", "mobile_number")
def _hub_mobile(item: dict[str, Any]) -> tuple[str, bool]:
"""从 Hub 人员对象里取手机号,回 ``(洗好的号码, Hub 有没有给东西)``。
两个返回值分开是有意的:``("", False)`` 是**这个接口压根不带手机号**(Hub 侧的
口径,天天报警没意义),``("", True)`` 是**带了号码但不是号码**(``无``、
``010-62345678`` 这种座机、缺位的号),那是 Hub 的脏数据,要数出来让人去追。
洗号的口径见 :func:`app.models.normalize_mobile`。
"""
for key in MOBILE_KEYS:
raw = str(item.get(key) or "").strip()
if raw:
return models.normalize_mobile(raw), True
return "", False
#: Hub 人员对象里企业微信 UserID 用的字段名。**实测(2026-10-21,member_limit=5000)
#: 是 ``users[].wecom_userid``:100 人里 98 人带这一键**,另外 2 人(``admin``、
#: ``penghongfei``)**压根不带这个键**——Hub 是"没号就不带键",不会给一个空串。
#: 目录接口的文档(对接指南 10.1)到现 在也只写了 ``user_id``/``account``/
#: ``display_name``/``email``/``organization_id``/``status``,这一列是 Hub 把自己那份
#: 通讯录映射一并下发之后才多出来的,各家写法不一(``WecomUserID`` 这种 Go 结构体名也
#: 见过),所以键名一律先归一化再比,不赌拼写;排在前面的是当前口径。
WECOM_USER_ID_KEYS = ("wecomuserid", "externaluserid", "externalid")
#: 套了一层列表时(``external_identities[]`` 那种结构)的字段名与值键,同样按归一化后的
#: 键名比对;值键里不收 ``id``/``user_id``——那是这条映射记录自己的主键,拿去当企微号会使错人
WECOM_LIST_KEYS = ("externalidentities",)
#: 值键里**不收 ``userid``/``user_id``**:Hub 的人员主键就叫这个,拿它当企微号
#: 等于把每个人的 Hub 主键当成收件地址
WECOM_VALUE_KEYS = ("externalid", "wecomuserid")
#: ``provider`` 去掉大小写与分隔符之后长这样的,就算企业微信
WECOM_PROVIDERS = ("wecom", "wechatwork", "workweixin", "qywx", "enterprisewechat")
#: :func:`_hub_wecom_user_id` 的第二个返回值:Hub 这一次到底给了什么
WECOM_ABSENT = "absent" # 压根不带企微字段 —— 本地这一列原样保留
WECOM_OK = "ok" # 带了一个洗得干净的 UserID —— 写
WECOM_BLANK = "blank" # 带了字段但值是空的:Hub 明确说这人没有企微号,本地跟着清空
WECOM_DIRTY = "dirty" # 带了字段但不是个合法 UserID:Hub 的脏数据,不覆盖本地的好值
def _wecom_key(name: object) -> str:
"""字段名归一化:去掉 ``_``/``-``/空格并转小写。
``wecom_userid``(Hub 目录实测口径)、``WecomUserID``(Go 结构体字段名)、
``wecomUserId``(JSON 驼峰)归一化之后是同一个键,取字段不再赌对方怎么写。
"""
return re.sub(r"[^0-9a-z]", "", str(name or "").lower())
def _is_wecom_provider(value: object) -> bool:
"""``external_identities[].provider`` 说的是不是企业微信(大小写与分隔符都不敏感)。"""
return _wecom_key(value) in WECOM_PROVIDERS
def _wecom_candidates(item: dict[str, Any]) -> list[Any]:
"""这条人员对象里所有"可能装着企微 UserID"的键值,按可信度排序(平铺字段优先)。
返回空列表 = 这条对象压根没提企微字段;只出现过键、值是空的也算"提过"。
"""
out: list[tuple[int, Any]] = []
for key, value in item.items():
name = _wecom_key(key)
if name in WECOM_USER_ID_KEYS:
out.append((WECOM_USER_ID_KEYS.index(name), value))
continue
if name in WECOM_LIST_KEYS and isinstance(value, list):
for row in value:
if not isinstance(row, dict):
continue
if not _is_wecom_provider(row.get("provider") or row.get("type")):
continue
for sub_key, sub_value in row.items():
if _wecom_key(sub_key) in WECOM_VALUE_KEYS:
out.append((len(WECOM_USER_ID_KEYS), sub_value))
out.sort(key=lambda pair: pair[0])
return [value for _, value in out]
def _wecom_keys_in(item: dict[str, Any]) -> list[str]:
"""这条 payload 里**真实出现过**的企微字段键名。
增量事件把 payload 转交给 :func:`_sync_people` 时只搬这几个键,绝不凭空补一个
``"wecom_userid": None``:补了就把"这条事件没提企微号"说成"这个人没有企微号",
本地对得好好的号会被清掉。
"""
return [
key
for key in item
if _wecom_key(key) in WECOM_USER_ID_KEYS or _wecom_key(key) in WECOM_LIST_KEYS
]
def _hub_wecom_user_id(item: dict[str, Any]) -> tuple[str, str]:
"""从 Hub 人员对象里取企业微信 UserID,回 ``(洗好的 UserID, 下面四种状态之一)``。
与 :func:`_hub_mobile` 的差别只有一处,但这一处必须分开:**带了字段、值是空的**
是 Hub 在说"这个人不再有企微号",不是"这个接口没这个字段"。企微 UserID 会被删掉
再分配给另一名员工,本地留着旧号的后果是待办推到拿走这个号的下一任手机上
(``docs/wecom-app-notification-plan.md`` 的 C14 就是这条)。所以:
* 一个候选键都没有 → ``WECOM_ABSENT``,这一列怎么办由调用方看整趟清单定;
* 有候选键、洗得出合法值 → ``WECOM_OK``;
* 有候选键、值全为空(``""``/``null``)→ ``WECOM_BLANK``;
* 有候选键、值不是个合法 UserID(中文、带空格、超长)→ ``WECOM_DIRTY``,
那是 Hub 的脏数据,计数报出来让人回去改,别拿它覆盖本地已经对上的号。
实测口径补一句:Hub 是**没号就不带键**(98/100 带键、剩下 2 人连键都没有),
所以 ``WECOM_BLANK`` 在目录接口上基本不会出现,"这个人没号"实际表现为
``WECOM_ABSENT``——那半由 :func:`_sync_people` 按整趟清单判断,见那儿。
"""
candidates = _wecom_candidates(item)
if not candidates:
return "", WECOM_ABSENT
dirty = False
for value in candidates:
# 不用 ``str(value or "")``:那样数字 0 会变成空串,同一个意思在
# ``"0"``(判成脏数据、保住本地好值)和 ``0``(判成没号、清空本地)两条路上分叉
raw = "" if value is None else str(value).strip()
if not raw:
continue # 这个键是空的,先看下一个候选键
cleaned = models.normalize_wecom_user_id(raw)
if cleaned:
return cleaned, WECOM_OK
dirty = True
return "", (WECOM_DIRTY if dirty else WECOM_BLANK)
#: 同步记录 ``details`` 里每类名单最多留几条。计数不受这个上限影响,
#: 上限只防止一次批量改名往一行的 JSON 里塞进上千个名字。
DETAIL_ITEM_LIMIT = 20
#: ``details.notes`` 里每条提示的字数上限:``message`` 整列只留 2000 字,
#: 提示一多就被裁掉后半句,这里按条存原文(各自截断),界面上能看全。
DETAIL_NOTE_CHARS = 400
@dataclass
class SyncStats:
#: 这一趟的开始时间:终止信号比它新才算数(见 :func:`cancel_requested`)
started_at: datetime | None = None
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
#: 这一趟真的换掉过登录名的人的本地主键。改名落在 ``_plan_account_renames``(主循环之前),
#: 主循环靠这份名单把这些人算进 ``updated``——否则"只做了一次改名的同步"在同步历史里
#: 会被显示成「无变更」,见 serialize_run 的 unchanged 口径
renamed_ids: set[int] = field(default_factory=set)
conflicts: int = 0
unbound: int = 0
# 手机号分三个数才说得清:"Hub 没下发这个字段"(下面两个都是 0)与"下发了但不是
# 号码"(invalid 非 0)处理方式完全不同,前者是 Hub 的接口口径,后者是那边的脏数据。
#: 这次清单里洗得出合法号码的人数(不管本地有没有跟着变)
mobile_returned: int = 0
#: 本地真正写入/刷新了手机号的人数
mobile_updated: int = 0
#: Hub 带了手机号字段、但洗不出合法号码(占位、座机、残缺号码)的人数
mobile_invalid: int = 0
# 企业微信 UserID 也是这一趟才有的列,四个数各说各的事:没有这四个数,界面上
# "企微 UserID 一列空着"到底是 Hub 没下发、还是这个人真没号,谁也分不清。
#: 这次清单里带了合法企微 UserID 的人数(不管本地有没有跟着变)
wecom_returned: int = 0
#: 本地真正写入/刷新企微 UserID 的人数
wecom_updated: int = 0
#: Hub 明确说这个人没有企微号,本地把这一列清空的人数
wecom_cleared: int = 0
#: Hub 带了企微字段、但洗不出合法 UserID(中文、带空格、超长)的人数
wecom_invalid: int = 0
#: Hub 发的 UserID 和别人是同一个号的人数(本地照抄,共用这个号的人都挂着它)
wecom_conflicts: int = 0
#: 已停用、且这一趟完整清单里查无此人的同步账号,把登录名让出去的人数
#: (见 :func:`_retire_lost_accounts`;行本身不删,权限与轨迹都还在)
reclaimed: int = 0
#: Hub 换了 ``organization_id`` 之后按「编码 + 名称」认回原部门的个数(见 :func:`_sync_units`)
units_rebound: int = 0
#: 撞上部门停用熔断、这一趟没敢停用的部门数(见 :func:`_offboard_missing_units`)
units_offboard_guarded: int = 0
#: 撞上离职停用熔断、这一趟没敢停用的人数(见 :func:`_offboard_missing`)
offboard_guarded: int = 0
#: 已停用的僵尸账号腾出来的企业微信 UserID 个数(号还给 Hub 认定的现任主人)
wecom_released: int = 0
# 这次同步改过的名字:老值 -> 新值。审批岗位、岗位组、代理人这些是按字符串
# 存人员的,同步完要照着这几张表把它们一起搬走,见 service/hub_refs.py。
display_name_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
# 「这一趟到底动了谁」的名字:只留前 DETAIL_ITEM_LIMIT 条,写进同步记录的 details,
# 界面上能逐条展开。计数(renamed / reclaimed / units_rebound)走 SyncStats 上的
# 同名字段,不受这个上限影响,所以上限只是防止一条 JSON 装下上千个名字。
#: 登录账号改名前后对照(``旧账号 → 新账号``)
account_renames: list[str] = field(default_factory=list)
#: 姓名(display_name)改名前后对照
name_renames: list[str] = field(default_factory=list)
#: 让出登录名的僵尸同步账号(``原账号 → hub-lost-…``)
reclaimed_accounts: list[str] = field(default_factory=list)
#: 按「编码 + 名称」认回原部门的部门名(Hub 换过 organization_id)
rebound_units: list[str] = field(default_factory=list)
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 detail(self, bucket: str, text: str) -> None:
"""往有界明细里记一条名字级信息(桶名见 :class:`SyncStats` 上那四个列表字段)。"""
rows = getattr(self, bucket)
if text and len(rows) < DETAIL_ITEM_LIMIT:
rows.append(text)
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:
"""现在是不是有一趟同步正在跑(界面与调度都用它显示状态)。
本进程那把进程内锁和跨副本那把 Redis 锁都算:界面上"正在同步"不该只看得见
自己这一个副本。没配 Redis 时后一半恒为假,与之前一致。
"""
return _run_lock.locked() or cache.locked(LOCK_SYNC)
def request_cancel() -> datetime:
"""按下「终止」:记下这一刻,让正在跑的那一趟在下一个检查点自己停手。
进程内一份 + Redis 一份:同步可能跑在另一条线程、另一个副本上,只有本进程的
:data:`_cancel_at` 就只能管得住同一个进程里的那一趟。
"""
global _cancel_at
now = datetime.now()
_cancel_at = now
cache.set_json(cache.key(CANCEL_KEY_NAME), now.timestamp(), CANCEL_TTL_SECONDS)
return now
def cancel_requested(since: datetime | None = None) -> bool:
"""``since`` 之后有没有人按过终止。``since`` 传这一趟的开始时间。"""
marker = _cancel_at
remote = cache.get_json(cache.key(CANCEL_KEY_NAME))
if isinstance(remote, (int, float)):
moment = datetime.fromtimestamp(float(remote))
if marker is None or moment > marker:
marker = moment
return marker is not None and (since is None or marker > since)
def _raise_if_cancelled(stats: SyncStats) -> None:
"""检查点:按过终止就从这儿抛出去,由调用方记成「已终止」。"""
if cancel_requested(stats.started_at):
raise HubSyncCancelled("这趟同步已被手动终止")
def _acquire_sync_locks() -> str:
"""两道互斥一起拿:先本进程的 ``_run_lock``(挡住同进程里重复点「立即同步」),
再跨副本那把。任何一道拿不到就把已经拿到的那半还回去再报错。"""
if not _run_lock.acquire(blocking=False):
raise HubSyncError("已有同步任务正在执行,请稍后再试")
lock_token = cache.try_lock(LOCK_SYNC, ttl_seconds=LOCK_SYNC_TTL_SECONDS)
if not lock_token:
_run_lock.release()
holder = cache.lock_holder(LOCK_SYNC)
raise HubSyncError(f"另一个副本{f'({holder})' if holder else ''}正在跑同步,请稍后再试")
return lock_token
def _release_sync_locks(lock_token: str) -> None:
cache.release_lock(LOCK_SYNC, lock_token)
try:
_run_lock.release()
except RuntimeError:
# 界面上有人按过「终止」,这把锁已经被交还过一次(见 :func:`terminate_sync`)。
# 活儿已经干完了,没必要为一把空锁把整趟同步报成异常。
logger.debug("同步锁已被提前放行,忽略这一次 release")
def stale_runs(
db: Session,
*,
grace_seconds: float = STALE_RUN_GRACE_SECONDS,
now: datetime | None = None,
) -> list[models.HubSyncRun]:
"""还挂着「进行中」、但其实已经没有人在收尾的那几趟同步。"""
now = now or datetime.now()
cutoff = now - timedelta(seconds=max(0.0, float(grace_seconds)))
return list(
db.execute(
select(models.HubSyncRun)
.where(
models.HubSyncRun.status == models.HubSyncRun.STATUS_RUNNING,
models.HubSyncRun.started_at <= cutoff,
)
.order_by(models.HubSyncRun.started_at.desc())
)
.scalars()
.all()
)
def _mark_cancelled(
db: Session, rows: list[models.HubSyncRun], message: str, now: datetime | None = None
) -> int:
"""给这几条记录补上收尾:状态改成「已终止」,耗时按开始到现在算。"""
if not rows:
return 0
now = now or datetime.now()
for row in rows:
row.status = models.HubSyncRun.STATUS_CANCELLED
row.finished_at = now
row.duration_ms = int((now - row.started_at).total_seconds() * 1000)
row.message = (message or STALE_RUN_MESSAGE)[:2000]
db.commit()
return len(rows)
def reap_stale_runs(
db: Session,
*,
grace_seconds: float = STALE_RUN_GRACE_SECONDS,
message: str = "",
) -> int:
"""把没人收尾的「进行中」记录标成「已终止」,返回标掉的条数。
只改这条记录,不碰锁也不碰数据:同步是一步一提交的,被打断的那趟本来就停在
某个中间态,下一趟照常从 Hub 全量重对齐,不需要这里假装它跑完了。
有锁(本进程或别的副本)在的时候一个字都不改:真在跑的同步不许被写坏,而卡死
那种场景本来就没有人持锁。界面上的「终止」走 :func:`terminate_sync`,那边按
``grace_seconds=0`` 直接点名要动哪几条。
"""
if running():
return 0
rows = stale_runs(db, grace_seconds=grace_seconds)
if not rows:
return 0
count = _mark_cancelled(db, rows, message or STALE_RUN_MESSAGE)
logger.warning(
"Hub 同步:%d 条记录停在「进行中」超过 %d 秒又没人持锁,已标记为终止(%s)",
count,
int(grace_seconds),
"、".join(row.id for row in rows[:5]),
)
return count
def terminate_sync(db: Session, *, operator_name: str = "", grace_seconds: float = 0.0) -> dict[str, Any]:
"""界面上的「终止」:给挂着「进行中」的同步收尾,并把同步锁放行。
``grace_seconds=0`` 是故意的 —— 按下这个按钮就是在说"别管它还在不在跑,现在放行"。
所以真在跑的那一趟也会被记成已终止:它的线程照旧跑到底,收尾时把这条记录改成真实
结果(见 :func:`_finish`),锁却已经被这里放行,于是可能有两副本并行拉一趟全量。
代价最多是白跑一遍,换的是再不会有人被卡死在「进行中」上出不来。
"""
# 先看一眼"现在有没有人在跑":有的话这次终止是要把它叫停,界面得把这句话说明白
was_running = running()
request_cancel()
holder = cache.lock_holder(LOCK_SYNC)
rows = stale_runs(db, grace_seconds=grace_seconds)
count = _mark_cancelled(db, rows, f"{operator_name or '管理员'}在界面上终止了这趟同步")
released = cache.force_release(LOCK_SYNC) or bool(holder)
released_local = False
if _run_lock.locked():
# 本进程那把锁可能正被另一条线程拿着(同步跑在调度线程里,而这次请求在
# worker 线程里)。``threading.Lock`` 允许跨线程交还,代价是拿它那条线程随后
# 自己 release 会抛 RuntimeError —— 已由 :func:`_release_sync_locks` 兜住。
try:
_run_lock.release()
released_local = True
except RuntimeError: # pragma: no cover - 只在竞争下走到
released_local = False
logger.warning(
"Hub 同步已手动终止:%d 条「进行中」记录收尾,跨副本锁%s,本进程锁%s",
count,
"已放行" if released else "本来没人拿",
"已放行" if released_local else "本来没人拿",
)
return {
"cancelled": count,
# 回的是收尾之后的样子:状态已经是「已终止」,带着耗时与谁按的按钮
"runs": [serialize_run(row) for row in rows],
# 锁这一栏分开说:Redis 那把跨副本,本进程这把只管当前副本,两种卡法都要看得见
"lock_released": released,
"holder": holder,
"local_lock_released": released_local,
# 终止时确实有一趟在跑:它会在下一个检查点自己停手(见 request_cancel)
"stopping": was_running,
"running": running(),
}
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()
# 顺手收一次残留:上一趟进程被打断时留下的「进行中」不该永远挂在页面上
# (持着锁的时候它自己会跳过,见 :func:`reap_stale_runs`)
reap_stale_runs(db)
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,
# 熔断现在是不是在冷却:不写清楚的话,管理员看到的"不可用"会像是刚试过
"breaker": hub_api.breaker_state(),
"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(),
# 增量同步(变更流水)的当前状态:游标走到哪、落后多少、上次哪时候拉的
# 上面那份 current 就是这一行,别再为同一行多跑两趟
"changes": changes_status(db, current=current),
}
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 _run_status(stats: SyncStats) -> str:
"""这一趟以什么状态收口:清单没拉全、或者熔断把人 / 部门整批挡下来没停的,都不算成功。
单独拎出来是因为"少干了活"必须看得见——标成 success 的话,第二天没人会去翻那几条 note。
"""
return (
models.HubSyncRun.STATUS_PARTIAL
if stats.truncated or stats.offboard_guarded or stats.units_offboard_guarded
else models.HubSyncRun.STATUS_SUCCESS
)
def run_details(stats: SyncStats) -> dict[str, Any]:
"""把"这一趟到底动了谁"整理成结构化明细,写进 ``oa_hub_sync_run.details``。
为什么不能只靠 ``message``:那是整段 2000 字的纯文本,多条提示拼在一起,超了就
裁掉后半句;界面上翻来覆去也只有「更新 N 人」这种数。改名、僵尸账号让位、按编码
认回部门这三件事都是**要点开名字去核对**的,光有数字说不出该核对谁。所以这里存
有界名单(每类前 :data:`DETAIL_ITEM_LIMIT` 条)+ 完整计数 + 按条原文的提示,
名单被裁掉时总数照样准。
增量轮询每几十秒就记一行,所以这里刻意只放小字段,不塞清单本身。
"""
return {
# 可核对的名单(有界)
"account_renames": stats.account_renames,
"name_renames": stats.name_renames,
"reclaimed_accounts": stats.reclaimed_accounts,
"rebound_units": stats.rebound_units,
# 对应的总数:名单被上限裁掉时,界面靠它说"共 N 条,这里只列了前 M 条"
"renamed": stats.renamed,
"reclaimed": stats.reclaimed,
"units_rebound": stats.units_rebound,
"name_renamed": len(stats.display_name_map),
# 只报规模的计数:以前同样只在 message 文本里,读的人得自己从句子中扒数字
"counts": {
"adopted": stats.adopted,
"protected": stats.protected,
"conflicts": stats.conflicts,
"unbound": stats.unbound,
"no_hub_id": stats.no_hub_id,
"emergency": stats.emergency,
"skipped": stats.skipped,
"units_bound": stats.units_bound,
"refs_rewritten": stats.refs_rewritten,
"refs_ambiguous": stats.refs_ambiguous,
"changes_skipped": stats.changes_skipped,
},
# 手机号与企业微信两个字段各三个数,来源不同结论完全不同(Hub 没下发 / 下发但是脏值)
"mobile": {
"returned": stats.mobile_returned,
"updated": stats.mobile_updated,
"invalid": stats.mobile_invalid,
},
"wecom": {
"returned": stats.wecom_returned,
"updated": stats.wecom_updated,
"cleared": stats.wecom_cleared,
"invalid": stats.wecom_invalid,
"conflicts": stats.wecom_conflicts,
"released": stats.wecom_released,
},
# 熔断挡下来的量:非 0 就意味着这一趟"少干了活",见 _run_status
"guards": {"people": stats.offboard_guarded, "units": stats.units_offboard_guarded},
# 提示原文按条存,不受 message 那 2000 字的整段截断影响
"notes": [text[:DETAIL_NOTE_CHARS] for text in stats.messages],
}
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),
# 改名 / 让位 / 认回部门:这三个数不是"新建还是更新"能表达的动作,单独回显
"renamed": int(row.renamed or 0),
"reclaimed": int(row.reclaimed or 0),
"units_rebound": int(row.units_rebound or 0),
"operator": row.operator,
"operator_name": row.operator_name,
"message": row.message,
"details": row.details or {},
"unchanged": (
row.created
+ row.updated
+ row.offboarded
+ row.units_created
+ row.units_updated
+ row.units_offboarded
# 「只做了一次批量改名的同步」和「让位了 68 个账号的同步」都不是无变更
+ int(row.renamed or 0)
+ int(row.reclaimed or 0)
+ int(row.units_rebound or 0)
)
== 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 _refresh_paths(
db: Session, unit: models.Unit, parent: models.Unit | None, stats: SyncStats, depth: int = 0
) -> None:
_set_unit_paths(unit, parent, 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 _ghost_unit_candidates(
db: Session, run_org_ids: set[int], busy_keys: set[tuple[str, str]]
) -> dict[tuple[str, str], list[models.Unit]]:
"""把"Hub 主键已经不在这趟清单里"的本地部门按 ``(编码, 名称)`` 分组,给换主键认领用。
Hub 重导一遍数据会把 ``organization_id`` 整体换号(实测测试站 2026-11-04:25~36 变成
2~13),而本地只认主键,认不出来就整棵树再建一遍:界面上两个「紫光汇智」、两套部门,
人挂到新的一套上,按 ``oa_unit.id`` 配的权限与审批规则留在老的一套上,悄悄失效。
这里把"主键已经消失、编码和名称都还在"的行挑出来当认领候选,把部门主键留住。
``busy_keys`` 是这一趟已经被别的本地部门对上的 ``(编码, 名称)``。那种同码重复是上一次
换号留下的壳子(真库现在有 12 组),再认一次只会多出第三个部门,所以不认。
"""
if not run_org_ids:
return {} # 清单里一个部门都没有,"不在清单里"证明不了任何事
out: dict[tuple[str, str], list[models.Unit]] = {}
rows = db.execute(
select(models.Unit).where(models.Unit.hub_org_id.is_not(None)).order_by(models.Unit.id)
).scalars().all()
for unit in rows:
if int(unit.hub_org_id or 0) in run_org_ids:
continue
key = (str(unit.code or ""), str(unit.name or ""))
if not key[0] or key in busy_keys:
continue
out.setdefault(key, []).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``(层级挪动会连带刷子树路径),本地决定 ``alias`` / ``description``
/ ``order_number`` / ``manager_person_id``,以及挂在任何部门下面的自建部门。
``hub_org_id`` 写上一律不清空(界面上改不动,Hub 里消失也只是停用不删除),组织架构、
部门负责人、按部门配的权限与审批规则全靠它长期对上号。唯一的例外是 Hub 自己把
``organization_id`` 整体换了号(重导数据、合并组织):那时清单里的主键本地一个都找不到,
照旧逻辑会整棵树复制一遍,人搬去新行、按 ``oa_unit.id`` 配的规则留在老行上悄悄失效。
所以开了「按编码认领本地部门」时,编码与名称都对得上、且原主键已经不在这趟清单里的
老部门会被认回来(换新主键,本地主键不动),见 :func:`_ghost_unit_candidates`。
字段按文档第 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)
# 先物化整棵树:认领"换了主键的老部门"要先知道这趟清单里到底有哪些组织
nodes = list(_iter_org_nodes(_org_tree(organizations, stats)))
run_org_ids = {int(models.as_id(node.get("organization_id")) or 0) for node, _ in nodes}
run_org_ids.discard(0)
busy_keys = {
(str(unit.code or ""), str(unit.name or ""))
for hub_id, unit in mapped.items()
if unit.code and hub_id in run_org_ids
}
ghosts = _ghost_unit_candidates(db, run_org_ids, busy_keys) if cfg.hub_sync_bind_local_by_code else {}
rebinds: list[tuple[str, int, int]] = []
seen: set[int] = set()
order: list[tuple[models.Unit, models.Unit | None]] = []
for index, (node, parent_hub_id) in enumerate(nodes):
if index and index % CANCEL_CHECK_EVERY == 0:
_raise_if_cancelled(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
rebound_from = 0
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 and ghosts:
# Hub 把 organization_id 整体换了号(重导、合并):编码和名称都对得上的老部门
# 认回来,别新建。新建等于整棵树复制一份,人跟着搬到新行上,而按 oa_unit.id
# 配的权限与审批规则还留在老行上,悄悄就失效了。
candidates = ghosts.get((code, name)) or []
if len(candidates) > 1:
# 同码同名有好几具壳子(上一次换号留下的):只有一支底下真住着人就认那一支,
# 口径同 _hub_units 的"留人多的那支";都住着人或都不住人就不猜
with_people = [u for u in candidates if _unit_weight(db, u)[0] > 0]
candidates = with_people if len(with_people) == 1 else []
if len(candidates) == 1:
old_unit = candidates[0]
rebound_from = int(old_unit.hub_org_id or 0)
old_unit.hub_org_id = hub_id # 旧主键当场让开:这一行此后代表 Hub 的新组织
unit = old_unit
claimed = True
ghosts.pop((code, name), None)
elif candidates:
# 同名同编码的僵尸不止一个:不猜谁是谁,按新部门建,交人工合并
stats.note(
f"本地有 {len(candidates)} 个已停用的部门都叫 {name}(编码 {code}),"
f"分不清 Hub 组织 {hub_id} 是哪一个,本次按新部门建"
)
ghosts.pop((code, name), 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 or rebound_from:
_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
if rebound_from:
stats.units_rebound += 1
rebinds.append((name, rebound_from, hub_id))
stats.detail("rebound_units", f"{name}(Hub {rebound_from} → {hub_id})")
else:
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)
if rebinds:
stats.note(
f"Hub 换了 {len(rebinds)} 个部门的主键,本地按「编码 + 名称」把它们认回了原部门"
f"(例如 {rebinds[0][0]}:Hub {rebinds[0][1]} → {rebinds[0][2]}):"
"部门主键没变,挂在它上面的权限、审批规则与部门负责人都留在原地,"
"也没有另建一套重名部门;这一趟不会把它们判成已消失"
)
_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 的那个组织,下趟同步
只会新建一个空部门,负责人、按部门配的权限与审批规则全丢。宁可留着停用的壳子,
等对方把组织加回来就自动接上。
也带一道熔断,口径同人员侧(共用 ``hub_sync_offboard_guard_percent``):一趟要停用的
部门超过 ``max(5, 同步部门总数 × 百分比)`` 时一个都不停,只报数并把这趟标成「部分完成」。
部门比人少得多,所以下限用 :data:`UNIT_OFFBOARD_GUARD_MIN`,不能用人员那侧的 20。
停用一个部门等于把它下面所有人的数据范围、按部门配的审批规则一起摘掉,
错一批比少停几个代价大得多。
"""
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()
pending = [row for row in rows if row.hub_org_id not in seen]
guard = int(cfg.hub_sync_offboard_guard_percent or 0)
if guard and pending:
total = int(
db.execute(
select(func.count())
.select_from(models.Unit)
.where(models.Unit.hub_org_id.is_not(None))
).scalar()
or 0
)
ceiling = max(
_floor_value(cfg, "hub_sync_unit_offboard_guard_min", UNIT_OFFBOARD_GUARD_MIN),
total * guard // 100,
)
if len(pending) > ceiling:
stats.units_offboard_guarded = len(pending)
stats.note(
f"{len(pending)} 个同步部门没出现在 Hub 清单里,超过部门停用熔断线"
f"({guard}%,本次上限 {ceiling} 个),这一趟一个部门都没停用。"
"停一个部门会连带摘掉它下面所有人的数据范围与按部门配的审批规则,"
"先核对 Hub 拉到的是不是这套环境该有的组织(换站点、换目录密钥、"
"对方正在重导都会撞上),确认没问题再把 OA_HUB_SYNC_OFFBOARD_GUARD_PERCENT 调大或设 0"
)
return
for row in pending:
row.status = models.UnitStatus.DISABLED
stats.units_offboarded += 1
if stats.units_offboarded:
stats.note(
f"Hub 已不存在的 {stats.units_offboarded} 个同步部门已停用"
"(部门本身保留,Hub 里加回来会自动接上)"
)
def find_shell_units(
units: Iterable[models.Unit], *, roster_org_ids: set[int] | None = None
) -> list[models.Unit]:
"""Hub 换过 ``organization_id`` 之后留在树上的「重名壳子」部门。
成因:Hub 那边把部门挪了主键(重建、合并、换环境重导),本地这一支靠「编码 + 名称」
认回了原部门(见 :func:`_sync_units`),旧的那一具就脱开了:``hub_org_id`` 指向一个
清单里已经不存在、且永远不会再出现的组织,状态停在停用,编码和名称都已被在职的孪生
部门占用。同步既不认它(主键对不上)也不会合并它(本地从不自动并部门),于是组织树
上常年挂着几具和在职部门同名的死壳子,部门下拉框里一排重复名字。
四条判据缺一不可:绑过 Hub、**已停用**、编码与名称和某个**在职**的 Hub 部门完全一样、
(给了 ``roster_org_ids`` 时)这一趟 Hub 清单里确实没有它。最后一条只在体检时加:
本地判据本身已经说明"这个身份有人接着",清理接口不为了再确认一遍去拉一次 Hub。
只删得掉"没人在用"的那几具,见 :func:`shell_unit_blockers`。
"""
rows = [row for row in units if row.hub_org_id]
roster = {int(value) for value in (roster_org_ids or set())}
twin_keys = {
(str(row.code or ""), str(row.name or ""))
for row in rows
if row.status == models.UnitStatus.ACTIVE
and row.code
and (roster_org_ids is None or int(row.hub_org_id) in roster)
}
if not twin_keys:
return []
shells: list[models.Unit] = []
for row in rows:
if row.status != models.UnitStatus.DISABLED:
continue
if roster_org_ids is not None and int(row.hub_org_id) in roster:
continue # Hub 这一趟还认得它,那不是壳子,是正常停用的部门
if (str(row.code or ""), str(row.name or "")) not in twin_keys:
continue # 没有在职的孪生部门顶着同一个身份,删掉就真没人接着了
shells.append(row)
return shells
def shell_unit_blockers(db: Session, unit: models.Unit) -> list[str]:
"""这个壳子部门还不能删的原因,空列表 = 可以放心删。
删部门是不可逆的:``oa_unit.id`` 是本地主键,挂在它上面的东西不会因为改名跟着搬。
所以只放行"三样都干净"的:没有直属人员、没有下级部门(否则子树的 ``parent_id``
会指向一个不存在的行)、也没有权限角色把它当自定义数据范围。最后这一条尤其要紧:
数据范围是按 ``oa_unit.id`` 存的,删掉之后角色不会报错,只会**安静地少一片范围**。
"""
blockers: list[str] = []
members = int(
db.execute(
select(func.count()).select_from(models.User).where(models.User.organization_id == unit.id)
).scalar()
or 0
)
if members:
blockers.append(f"直属人员 {members} 人")
children = int(
db.execute(
select(func.count()).select_from(models.Unit).where(models.Unit.parent_id == unit.id)
).scalar()
or 0
)
if children:
blockers.append(f"下级部门 {children} 个")
scoped = [
role.name
for role in db.execute(select(models.AuthRole)).scalars().all()
if str(unit.id) in {str(value) for value in (role.data_unit_ids or [])}
]
if scoped:
blockers.append("权限角色把它当数据范围:" + "、".join(scoped[:3]))
return blockers
# ---------------------------------------------------------------------------
# 人员
# ---------------------------------------------------------------------------
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 _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
stats.renamed_ids.add(person.id)
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
stats.detail("account_renames", f"{old_account} → {account}")
stats.renamed_ids.add(person.id)
db.flush()
#: 僵尸账号让位之后挂的账号名前缀。带上 Hub 主键,是为了在人员列表里一眼看得出这条是谁、
#: 为什么长成这样,也让同一个人在同一趟同步里算得出同一个名字(幂等判定靠它)。
LOST_ACCOUNT_PREFIX = "hub-lost-"
#: 离职停用熔断的绝对下限(配置项 ``hub_sync_offboard_guard_min_people`` 的出厂默认值):
#: 等着停用的人少到这个数以内,就不算"整家公司被判离职",照常停用。没有这条下限,
#: 几十人的小部署裁掉几个人就会被比例挡下来,天天弹熔断。
OFFBOARD_GUARD_MIN_PEOPLE = 20
#: 部门停用熔断的绝对下限(``hub_sync_unit_offboard_guard_min`` 的出厂默认值):部门总数
#: 比人数少得多,用人员那侧的 20 这条线永远不会触发。
UNIT_OFFBOARD_GUARD_MIN = 5
#: 清单人数下限(``hub_sync_roster_floor_percent`` 的出厂默认值,相对上一次同步看到的人数)。
#: Hub 在清库或重导的时候目录会突然只剩几个人,这时"本地有、清单里没有"什么也证明不了,
#: 账号名先原样留着。
ROSTER_FLOOR_PERCENT = 50
def _floor_value(cfg: Any, field: str, fallback: int) -> int:
"""读熔断下限:优先用配置项,字段缺失或不是数就回落到上面的出厂默认值。
回落而不是报错,是因为这三条线只是"挡误伤"的松紧,配置读不到时按出厂值拦比
完全不拦安全;单测与脚本里也常拿半截配置对象进来。
"""
try:
value = int(getattr(cfg, field, None))
except (TypeError, ValueError):
return fallback
return value if value >= 0 else fallback
def _roster_hub_ids(users: list[dict[str, Any]]) -> set[int]:
"""这一趟 Hub 清单里出现过的 ``user_id`` 集合(正整数,去重)。"""
ids: set[int] = set()
for item in users:
if not isinstance(item, dict):
continue
hub_user_id = models.as_id(item.get("user_id"))
if hub_user_id and int(hub_user_id) > 0:
ids.add(int(hub_user_id))
return ids
def _is_lost_account(cfg, person: models.User, roster: set[int]) -> bool:
"""这条本地账号算不算"Hub 已查无此人、可以把登录名腾出去"。
四个条件缺一不可:同步来的号(``source=hub``)、已经被停用、这一趟**完整**清单里没有
他的 Hub 主键、账号名不在应急名单里。判据与理由都写在 :func:`_retire_lost_accounts`,
「同步前体检」也调这一个函数,免得预检报一堆冲突、真跑起来却一个都没有。
"""
if not cfg.hub_sync_reclaim_lost_accounts or not roster:
return False
if person.source != models.AccountSource.HUB or not person.hub_user_id:
return False
if int(person.hub_user_id) in roster:
return False
# 这一趟才发现"查无此人"的先只停用,账号名留到下一趟再动:Hub 抖一下不该把人改名
if person.status != models.UserStatus.DISABLED:
return False
account = person.account or ""
if not account or account.startswith(LOST_ACCOUNT_PREFIX):
return False # 已经让过位,别每趟再改一次
return not is_emergency_account(account)
def _roster_floor_percent() -> int:
"""清单人数下限的百分比(提示文字要照着它说"一半"还是"三成",别把数写死在句子里)。"""
return _floor_value(hubconfig.get(), "hub_sync_roster_floor_percent", ROSTER_FLOOR_PERCENT)
def _roster_floor(db: Session) -> int:
"""敢拿这趟清单去改登录名时,清单里至少要有多少人;``0`` = 不设限。
Hub 在清库或重导的时候目录会突然只剩几个人(实测 2026-11-05 测试站一天之内从 100 人
掉到 1 人),这时"本地有、清单里没有"证明不了人已经走了,照着让位就是把上百个登录名
一次性刷成 ``hub-lost-*``。基准取这两个里**较小、但仍然可信**的那个:
* 上一次同步记下来的人数(``hub_directory.total_users``);
* 本地带 ``hub_user_id`` 的账号数:它只增不减(离职只停用),所以哪怕上一趟同步已经
只看到七个人,"本地攒着几百号人"这件事仍然拦得住再一次的批量改名。
不足熔断人数底线(``hub_sync_offboard_guard_min_people``)的数不当基准(小部署、
第一次同步没有参照物),两个都不可信就返回 0 放行。清单确实长期只有基准以下时会一直
挡着(比例由 ``hub_sync_roster_floor_percent`` 决定,默认一半):那时不让位等于
回到旧行为(撞车只报数、交人工核对),比悄悄改掉全库的登录名好。
"""
baselines = [
models.as_id(state(db).get("total_users")) or 0,
int(
db.execute(
select(func.count())
.select_from(models.User)
.where(models.User.hub_user_id.is_not(None))
).scalar()
or 0
),
]
cfg = hubconfig.get()
# 基准本身也要"可信":几十号人以下的参照物当不了下限的参照,沿用人员侧那条人数底线
floor_base = _floor_value(cfg, "hub_sync_offboard_guard_min_people", OFFBOARD_GUARD_MIN_PEOPLE)
usable = [size for size in baselines if size >= floor_base]
percent = _floor_value(cfg, "hub_sync_roster_floor_percent", ROSTER_FLOOR_PERCENT)
return min(usable) * percent // 100 if usable else 0
def _roster_wecom_owners(users: list[dict[str, Any]]) -> dict[str, int]:
"""这一趟清单里「企业微信 UserID -> 号主 Hub 主键」,用来判断某个号现在该在谁身上。"""
owners: dict[str, int] = {}
for item in users:
if not isinstance(item, dict):
continue
hub_user_id = models.as_id(item.get("user_id"))
value, state = _hub_wecom_user_id(item)
if state == WECOM_OK and value and hub_user_id:
owners.setdefault(value, int(hub_user_id))
return owners
def _retire_lost_accounts(
db: Session,
users: list[dict[str, Any]],
by_account: dict[str, models.User],
stats: SyncStats,
by_wecom_id: dict[str, models.User] | None = None,
*,
complete_roster: bool = False,
) -> None:
"""把"本地已停用 + Hub 已查无此人"的同步账号从登录名上挪开,给 Hub 的现任主人让位。
为什么会有这种账号:Hub 把人合并或重导之后,账号名会挪到另一个 ``user_id`` 上,而占着
这个名字的本地行绑的是那个已经被删掉的 ``user_id`` —— Hub 的变更流水只记 upsert、不记删除,
本地根本等不到"这个人没了"的那条消息。``_plan_account_renames`` 的口径是"账号已经属于
另一个统一身份就不抢",于是活着的人永远拿不回 Hub 给他的账号名,每一趟同步都原样撞一次车,
界面上就是同一个人两条:一条正常、登录名还是上辈子别人的,一条停用、占着正确的登录名。
让位只动账号名,不动人:本地行、待办、审批轨迹、按主键挂的权限都原样留着,账号名换成
``hub-lost-<user_id>-<原名>``,按账号存的引用跟着这一行一起搬(``account_map`` 记的就是
这一跳,不做链式拼接,见 :func:`_record_pair`)。
四道门槛,缺一个都不让位:
* **这一趟清单人数对得上**:Hub 目录被清空或正在重导时(实测 2026-11-05 测试站一天之内
从 100 人掉到 1 人),"不在清单里"同样证明不了人走了,下限见 :func:`_roster_floor`;
* **调用方声明这一趟是完整清单**(``complete_roster=True``):``truncated`` 说明人没拉全,
增量事件手里只有一条 payload,两种情况都证明不了"不在清单里"等于"Hub 查无此人"。
所以这个参数默认 ``False``,只有 ``sync_users`` 在清单没被截断时才传 ``True``——
一条人员事件就想改掉全库的登录名,是这里最贵的一种误伤;
* **本地这一行已经被停用过**:停用是上一趟同步(或管理员)已经做过的判断,账号名这才敢动。
刚发现"查无此人"的那一趟只停用,下一趟才让位,Hub 抖一下不至于把人的登录名也改了;
* **这一行是同步建/同步认领的**(``source=hub``):本地手工建的号哪怕在登录时被补绑过
一个 Hub 主键,账号名也是本地自己起的,轮不到同步去改;应急账号
(``hub_local_accounts``)更不用提,那个名字就是它存在的意义。
``hub_sync_reclaim_lost_accounts`` 关掉就退回老口径:一律不抢,撞车只报数,交人工核对。
"""
cfg = hubconfig.get()
if not complete_roster or stats.truncated:
return # 清单没拉全 / 只搬来一条增量事件,"不在清单里"证明不了任何事
roster = _roster_hub_ids(users)
floor = _roster_floor(db)
if len(roster) < floor:
# 清单人数比基准少得太离谱:Hub 多半在清库/重导,先不动任何人的登录名
stats.note(
f"这一趟 Hub 清单只有 {len(roster)} 个人,不足可参照基准的 {_roster_floor_percent()}%"
f"({floor} 人):"
"Hub 多半正在清库或重导,「不在清单里」证明不了人已经走了,"
"所以这一趟一个账号名都不让位。同步本身照写不误;"
"核对过 Hub 那边确实只剩这些人的话,下一趟会照常腾位置"
)
return
lost = [
(account, person)
for account, person in list(by_account.items())
if _is_lost_account(cfg, person, roster)
]
if not lost:
return
# 企业微信 UserID 也一起腾开:号被 Hub 挪给了另一个还活着的人,本地却压在一具僵尸行上,
# _apply_wecom_user_id 就永远判成"这个号已挂在别人身上"不敢写 —— 结果是活人的待办
# 一直推到死号上,或者干脆推不到。清空只在清单明说"这个号现在归 user_id=X"时才做。
wecom_owners = _roster_wecom_owners(users)
retired: list[tuple[str, str]] = []
released_wecom: list[str] = []
for account, person in lost:
staging = models.clip(f"{LOST_ACCOUNT_PREFIX}{int(person.hub_user_id)}-{account}", 190)
suffix = 2
while staging in by_account: # 万一本地真有这么个账号,往后加号
staging = models.clip(f"{LOST_ACCOUNT_PREFIX}{int(person.hub_user_id)}-{account}-{suffix}", 190)
suffix += 1
person.account = staging
by_account.pop(account, None)
by_account[staging] = person
_record_pair(stats.account_map, account, staging)
retired.append((account, staging))
stats.detail("reclaimed_accounts", f"{account} → {staging}")
held = person.wecom_user_id or ""
owner = wecom_owners.get(held)
if held and owner is not None and owner != int(person.hub_user_id or 0):
if by_wecom_id is not None and by_wecom_id.get(held) is person:
by_wecom_id.pop(held, None)
person.wecom_user_id = ""
released_wecom.append(held)
db.flush()
stats.reclaimed += len(retired)
stats.wecom_released += len(released_wecom)
# 让位的人不在这一趟清单里(正因如此才算查无此人),主循环不会替他们计数,这里自己补上:
# 否则改了 97 个登录名的一趟同步,在同步历史里仍然显示「无变更」
stats.updated += len(retired)
stats.note(
f"{len(retired)} 个已停用的同步账号在 Hub 里已经查无此人,却一直占着登录名"
f"(账号名已改成 {LOST_ACCOUNT_PREFIX}user_id-原名 让位):"
f"例如 {retired[0][0]} → {retired[0][1]}。本地行、待办与按主键挂的权限都没动,"
"按账号存的审批引用跟着这一行一起搬走了;它们腾开的账号名,这一趟会归回 Hub 的现任主人"
)
if released_wecom:
stats.note(
f"其中 {len(released_wecom)} 个企业微信 UserID 也从这些僵尸账号上清空了"
f"(如 {released_wecom[0]}):Hub 说这些号现在属于别人,"
"留着就等于把现任主人的待办推到已经不在这个人身上"
)
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,
by_wecom_id: dict[str, models.User] | None = None,
*,
complete_roster: bool = False,
) -> None:
"""把这一趟 Hub 要求的账号改名一次性排好再落库(见 ``_apply_account_renames``)。
分两遍扫:先收齐"Hub 要求换账号"的人,再判断目标账号是不是被一个不打算动的人占着。
一遍扫不行的原因是清单有先后 —— 甲要乙的账号、乙也要甲的账号时,先扫到的那个会以为
对面是"不动的人"而被判成撞车,结果两个人一个都没换成,而这其实是能换的(互换)。
排之前先跑一遍 :func:`_retire_lost_accounts`:占着账号、但 Hub 里已经查无此人的停用行
不算"不动的人",让它先把名字腾开,否则下面每一个都要在它身上撞车,而且永远撞不好。
让位只在 ``complete_roster=True`` 时发生(见那个函数),增量事件传默认的 ``False``。
"""
cfg = hubconfig.get()
_retire_lost_accounts(db, users, by_account, stats, by_wecom_id, complete_roster=complete_roster)
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 _wecom_holder(db: Session, value: str) -> models.User | None:
"""这个企微 UserID 现在挂在哪个本地账号上。增量事件一次一问,不为一条变更预建全表索引。"""
return db.execute(
select(models.User).where(models.User.wecom_user_id == value)
).scalars().first()
def _apply_wecom_user_id(
db: Session,
person: models.User,
item: dict[str, Any],
by_wecom_id: dict[str, models.User] | None,
stats: SyncStats,
absent_is_no_account: bool = False,
) -> bool:
"""按 Hub 给的企业微信 UserID 落 ``users.wecom_user_id``,回本地这一列有没有变。
``absent_is_no_account`` 是调用方从**整趟清单**得出的判断:这一列这次确实下发过
(清单里有人带这个键),那这个人没带就是没企微号,按清空处理。实测 Hub 就是
"没号就不带键"(2026-10-21:100 人里 98 人带键,另 2 人连键都没有,一个空串都不给),
只看单条 payload 的话这种人永远是 ``WECOM_ABSENT``,号被收回去了本地还留着,
下一个拿走这个号的人就会收到别人的待办。增量补丁一律不传这个标记:一条补丁
证明不了整个接口有没有这一列(实测最近 30 条 wecom 事件里只有 3 条带这个键)。
``by_wecom_id`` 是「企微 UserID -> 账号」的查重表:全量同步在内存里建一次(一趟
几百号人,逐条查库不值),增量事件传 ``None``、按值现查一次。
**这一列是上游镜像,不是本地唯一键**:Hub 把同一个号同时发给几个人,本地就给几个人
都写上这个号,只在同步记录里报 ``wecom_conflicts`` 让人回企微通讯录核对。老口径是
"一个号只挂一个人、撞上就后到的那个不写",代价是被让开的人这一列永远是空的 ——
界面上分不清"Hub 没给号"和"Hub 给了、本地没敢写",按这一列找人的下游还会少找一个
(实测 2026-11-05 测试站:``user_id=1`` 与 ``user_id=455`` 都带着 ``chenhao2``)。
"""
value, state = _hub_wecom_user_id(item)
if state == WECOM_ABSENT:
if not absent_is_no_account:
return False
state = WECOM_BLANK
if state == WECOM_DIRTY:
stats.wecom_invalid += 1
return False
old = person.wecom_user_id or ""
if state == WECOM_BLANK:
if not old:
return False
if by_wecom_id is not None and by_wecom_id.get(old) is person:
by_wecom_id.pop(old, None)
person.wecom_user_id = ""
stats.wecom_cleared += 1
return True
stats.wecom_returned += 1
if old == value:
return False
if by_wecom_id is not None:
holder = by_wecom_id.get(value)
else:
# Session 是 ``autoflush=False`` 建的(app/db.py):同一批变更里前一条刚写上这个号、
# 还没 flush,直接查库会查不到人,冲突就漏报了。问库之前先把这一笔刷出去。
db.flush()
holder = _wecom_holder(db, value)
if holder is not None and holder.id != person.id:
# 同一个号发给了几个人:照抄 Hub,后来的人一样挂上,只是把这件事报出来
stats.wecom_conflicts += 1
if old and by_wecom_id is not None and by_wecom_id.get(old) is person:
by_wecom_id.pop(old, None)
person.wecom_user_id = value
if by_wecom_id is not None:
by_wecom_id[value] = person
stats.wecom_updated += 1
return True
def _sync_people(
db: Session,
users: list[dict[str, Any]],
unit_map: dict[int, int],
stats: SyncStats,
now: datetime,
*,
complete_roster: bool = False,
report: bool = True,
) -> set[int]:
"""Hub 扁平人员清单 -> ``users``,返回这次清单里出现的 Hub 主键。
**身份只认 Hub 的 ``user_id``**(每次都是全量清单,本地不自造主键):账号会被人先注册
走、也会在 Hub 侧改名,姓名更是常改,只有 Hub 主键从头到尾指着同一个人。于是——
* 清单里没带 ``user_id`` 的人不建号也不认领,只计数上报(宁可少一个人,也别把
两个不同的人并成一条);
* 先按 ``hub_user_id`` 找人;找不到才看账号,而账号只允许认领**还没绑过主键**的
本地账号(手工建的、或历史遗留的),认领后写 ``source=hub``;
* 账号已经绑在别人身上就跳过并计数,绝不覆盖 ``hub_user_id``——那等于把两个人的
权限、待办、流程历史搅在一起;
(唯一的例外:占着这个名字的那一行如果**已停用、且这一趟完整清单里查无此人**,
同步会先把它改名让位、再把账号名还给 Hub 的现任主人,见 :func:`_retire_lost_accounts`。
不加这一条,Hub 合并过一次人之后账号名就永久卡死了,每一趟都撞在同一个死号上。
让位只在全量同步里发生:调用方要用 ``complete_roster=True`` 明说"这就是 Hub 的全部人",
增量事件一次只搬一个人,传默认的 ``False``,一个账号名都不会动。)
* 已绑主键的人,账号跟着 Hub 改(新账号没人占用才改),姓名/邮箱/部门/状态一律以
Hub 为准。改走的旧账号会记进 ``account_map``,收尾时把按账号存的审批引用一起搬走。
* 手机号只在 Hub 这次**给了合法号码**时覆盖:Hub 的目录接口现在不一定下发这一列,
而本地这列可能是 HR 自己录的,"没下发"绝不能被写成"清空"。
* 企业微信 UserID(``wecom_user_id``)跟着一起对齐,但比手机号多认一种情况:Hub
带着这个字段、值却是空的,那是 Hub 在说这个人没有企微号,本地跟着清空(企微号会
被删掉重新分配给别人,留着旧号等于把待办推给下一任);不带这个字段时照旧不碰。
Hub 把同一个号发给几个人,本地就给几个人都写上这个号,同时计数报出来。
两条护栏:``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] = {}
by_wecom_id: 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
if row.wecom_user_id:
by_wecom_id.setdefault(row.wecom_user_id, row)
seen_ids: set[int] = set()
_plan_account_renames(db, users, by_hub_id, by_account, stats, by_wecom_id,
complete_roster=complete_roster)
# 这一列这次到底有没有下发:清单里只要有一个人带过企微键就算下发了,
# 于是"这个人没带"读成"这个人没企微号"(清空),而不是"接口没这个字段"(不动)。
# 一趟全量一个判断,绝不按单条 payload 猜——见 _apply_wecom_user_id 的说明。
wecom_column = any(_wecom_candidates(item) for item in users if isinstance(item, dict))
for index, item in enumerate(users):
if index and index % CANCEL_CHECK_EVERY == 0:
_raise_if_cancelled(stats)
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}"
mobile, mobile_given = _hub_mobile(item)
# 建号时就带上号:这三个计数是"Hub 到底有没有下发手机号"的判据,
# 首轮同步全员新建,漏记会误报成 Hub 没下发这个字段。
if mobile:
stats.mobile_returned += 1
stats.mobile_updated += 1
elif mobile_given:
stats.mobile_invalid += 1
person = models.User(
account=account,
display_name=display_name,
email=email,
mobile=mobile,
# 同步建的号不在本地设密码,登录一律回 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
# 企微 UserID 走公共那条路(查重、清洗、计数都在一处),建号这一趟不重复写;
# 刚 flush 完主键就有了,所以冲突判定与老账号一样准。
_apply_wecom_user_id(db, person, item, by_wecom_id, stats, wecom_column)
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)
stats.detail("name_renames", f"{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
mobile, mobile_given = _hub_mobile(item)
if mobile:
stats.mobile_returned += 1
if person.mobile != mobile:
person.mobile = mobile
stats.mobile_updated += 1
moved = True
elif mobile_given:
stats.mobile_invalid += 1
if _apply_wecom_user_id(db, person, item, by_wecom_id, stats, wecom_column):
moved = True
# Hub 里查不到这个部门时保留原部门,别把人踢成无部门。
if unit_id and person.organization_id != unit_id:
# 部门只改 users 上那一列:它就是"这个人在哪个部门"的唯一口径
person.organization_id = unit_id
moved = True
if person.status != status:
person.status = status
person.hub_synced_at = now
if moved or person.id in stats.renamed_ids:
# 改名是 _plan_account_renames 提前落的,主循环这一趟可能再没动过别的列;
# 不把改名的人算进 updated,同步历史会把这趟写成「无变更」
stats.updated += 1
if report:
_report_run_notes(stats)
return seen_ids
def _report_run_notes(stats: SyncStats) -> None:
"""把这趟同步里"需要人来核对"的那几件事写进同步记录。
这些计数字段是**整趟累计**的,所以一趟只许调用一次:全量同步在
:func:`_sync_people` 末尾调,增量同步由 :func:`_pull_changes` 收尾时调一次。
以前它写在 ``_sync_people`` 里,而增量每条完整人员事件都要调一次这个函数,
实测(2026-11-05 测试站一趟变更同步)同样两句提示在一条同步记录里重复了 5 遍,
数字还停在第一次的「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 not stats.reclaimed
else f"(已查无此人的那批已经让位腾出账号名,剩下的都是本地还有活人占着的)"
)
)
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 换个账号名,要么把应急账号改成别的名字"
)
if stats.mobile_invalid:
stats.note(
f"Hub 有 {stats.mobile_invalid} 人带了手机号但洗不出合法号码(占位、座机或残缺号码),"
"本地号码原样保留,请回 Hub 那边改成正经号码"
)
if stats.wecom_invalid:
stats.note(
f"Hub 有 {stats.wecom_invalid} 人带了企业微信字段但洗不出合法 UserID"
"(含中文、带空格或超过 64 字节),本地这一列原样保留,请回企微通讯录改成正经 UserID"
)
if stats.wecom_cleared:
stats.note(
f"{stats.wecom_cleared} 人的企业微信 UserID 已清空:这一列 Hub 这次是下发过的,"
"这几个人没带(或带了个空值),就是没有企微号。清空是必要的——"
"企微号会被删除后重新分配给别的员工,留着旧号等于把待办推给下一任"
)
if stats.wecom_conflicts:
stats.note(
f"Hub 给 {stats.wecom_conflicts} 个人下发的企业微信 UserID 和别人是同一个号,"
"本地照抄:共用这个号的几个人都挂着它,发给这个号会同时送达他们。"
"这是 Hub 那份通讯录本身的样子,不是本地有重复账号;"
"这个号该只归一个人收的话,请回企业微信通讯录把它改到一个人的名下"
)
def _offboard_missing(db: Session, seen_ids: set[int], stats: SyncStats, now: datetime) -> None:
"""Hub 已经不存在的同步账号置为停用(只停用不删除,也不碰本地账号)。
判据只有 ``hub_user_id`` 这一个:以前还附带"账号也找不到",于是 Hub 里改了账号的人
会被判成离职、连带他的待办和权限一起停掉。现在账号只是普通字段,不参与身份判定。
没有主键的 ``source=hub`` 账号(历史遗留)不做离职判定,只报数量让人去补绑。
停用的是"这一整批",所以带一道熔断:等着停用的人数超过 ``hub_sync_offboard_guard_percent``
(且不少于 :data:`OFFBOARD_GUARD_MIN_PEOPLE`)时,这一趟一个都不停,只把人数报进同步记录、
并让这一趟以「部分完成」收口。判成离职这件事不可自动挽回 —— 下一趟同步只会把清单里的
人重新启用,指错了 Hub 的话那些被停的人永远回不来,所以宁可停下来问一句。
设成 0 关掉熔断,回到"照单全停"。
"""
cfg = hubconfig.get()
rows = db.execute(
select(models.User).where(models.User.source == models.AccountSource.HUB)
).scalars().all()
pending: list[models.User] = []
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
pending.append(row)
# 熔断:Hub 换了一套数据(重导、合并,甚至只是把 hub_base_url 指到另一套环境)时,
# 本地这批 hub_user_id 会一次性全部"查无此人",照停用等于把整家公司判成离职 ——
# 权限、待办、部门负责人当场全没,而且下一趟同步不会自己长回来。
# 宁可这一趟一个人都不动、把"本该停用多少人"报出来让人先看清单,也不要悄悄写下去。
guard = int(cfg.hub_sync_offboard_guard_percent or 0)
if guard:
ceiling = max(
_floor_value(cfg, "hub_sync_offboard_guard_min_people", OFFBOARD_GUARD_MIN_PEOPLE),
len(rows) * guard // 100,
)
if len(pending) > ceiling:
stats.offboard_guarded = len(pending)
stats.note(
f"{len(pending)} 人没出现在 Hub 清单里,超过离职停用熔断线"
f"({guard}%,本次上限 {ceiling} 人),这一趟一个人都没停用。"
"先看一眼 Hub 到底拉到了谁(系统设置 → 统一身份 → 同步前体检):"
"换过 Hub 站点或目录密钥、Hub 重导过人员,都会一次性撞上这一条;"
"确认清单没问题,再把 OA_HUB_SYNC_OFFBOARD_GUARD_PERCENT 调大或设成 0 关掉熔断"
)
return
for row in pending:
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("定时同步已关闭,请到「系统设置 → 同步定时任务」打开「允许定时同步」")
lock_token = _acquire_sync_locks()
# 建「进行中」记录这一段在下面的 try 之外,所以它得自己负责交还锁:这里漏出去
# 一次异常(库断了、死锁、补列没跟上导致 INSERT 报错),``_run_lock`` 就永久扣在
# 这个进程上,之后每一次同步 —— 包括调度线程每几十秒那趟增量 —— 都只会回
# 「已有同步任务正在执行,请稍后再试」,直到重启或有人按「终止」。
try:
now = datetime.now()
member_limit = max(1, min(5000, int(cfg.hub_sync_member_limit or 2000)))
run = models.HubSyncRun(
trigger=trigger,
status=models.HubSyncRun.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(started_at=now)
stats.member_limit = member_limit
except Exception:
_release_sync_locks(lock_token)
raise
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}
# 拉目录那一下是整趟最慢的一步(几秒到几十秒),回来先问一次:
# 这期间有人按了终止,就别再往库里写后半截了
_raise_if_cancelled(stats)
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)
# complete_roster:清单没被 member_limit 截断,才敢说"不在清单里 = Hub 查无此人"
seen_ids = _sync_people(
db, hub_users, unit_map, stats, datetime.now(), complete_roster=not stats.truncated
)
_note_field_coverage(stats, bool(hub_users))
_raise_if_cancelled(stats)
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 = _run_status(stats)
_finish(db, run_id, stats, status, ";".join(stats.messages))
return {"run": serialize_run(latest_run(db) or run), "skipped": False}
except HubSyncCancelled as exc:
db.rollback()
_finish(db, run_id, stats, models.HubSyncRun.STATUS_CANCELLED, str(exc))
raise
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:
_release_sync_locks(lock_token)
def _note_field_coverage(stats: SyncStats, has_users: bool) -> None:
"""把"Hub 到底有没有下发手机号 / 企业微信 UserID"写进同步记录。
这两列的号从哪来是可以查证的:清单里一个候选字段都没出现过(``mobile_returned``
与 ``mobile_invalid`` 都是 0,企微那三项也一样),说明是 Hub 的目录接口还没下发这一
列,本地已有的值照旧算数;反之带了却洗不出来的那些在 :func:`_sync_people` 里已经
单独报过了。不写这几句,界面上只会看到"这一列空着",谁也分不清是没同步还是根本没下发。
"""
if stats.mobile_updated:
stats.note(f"{stats.mobile_updated} 人的手机号已按 Hub 刷新")
if has_users and not stats.mobile_returned and not stats.mobile_invalid:
stats.note(
"Hub 目录这次没有下发任何手机号,本地这一列保持原样(HR 仍可手工录入);"
"要让号码跟着 Hub 走,得先让目录接口在 users[] 里带 mobile 字段"
)
if stats.wecom_updated:
stats.note(f"{stats.wecom_updated} 人的企业微信 UserID 已按 Hub 刷新")
if (
has_users
and not stats.wecom_returned
and not stats.wecom_invalid
and not stats.wecom_cleared
):
stats.note(
"Hub 目录这次没有下发任何企业微信 UserID,本地这一列保持原样;"
"要让这一列跟着 Hub 走,得先让目录接口在 users[] 里带 wecom_user_id 字段"
"(带 external_identities 那种嵌套结构也认)"
)
def _carry_references(db: Session, stats: SyncStats) -> None:
"""同步改了名字,就把按字符串存着的审批与共享引用一起搬走。
权限角色、数据范围、部门负责人都是按主键挂的,同步不动主键,天然不受影响;会出问题的是
审批岗位、岗位组、流程环节审批人、日程与网盘共享名单那一类按部门路径 / 账号 /
姓名存的字符串。这里在同一个事务里把它们搬到新值,让"配好权限之后再全量同步"是安全的。
有歧义、搬不了的一律不动,只把数量写进同步记录。
个人资料里的收款账户(``oa_bank_account``)也是按登录账号挂的,跟着一起搬。
"""
maps = hub_refs.build_maps(
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.accounts_moved:
stats.note(
f"随本次改名搬走 {report.accounts_moved} 条个人资料里填的收款账户,"
"开户行与收款账号仍跟着本人走"
)
if report.accounts_stuck:
stats.note(
"这些账号改名后没能带走收款账户(新账号上已经存着一条):"
+ "、".join(report.accounts_stuck[:3])
+ ",请到个人资料里核对"
)
if report.skipped:
stats.note(
f"{report.skipped} 个改掉的名字本地有歧义,相关配置保持原样,请到流程设计与岗位组里手工确认"
)
if report.homonyms:
stats.note(
"改过去的名字本地已有同名的(" + "、".join(report.homonyms[:3]) + "),"
"按名字配的审批人会一并命中这几个,请核对一下"
)
# 登录账号改名是唯一搬不动的那一类:历史行按口径不跟着搬,老账号上的单会查不到
drift = hub_refs.runtime_drift(db, maps.accounts)
if drift:
detail = "、".join(f"{old}({count} 条)" for old, _new, count in drift[:3])
stats.note(
f"这几个登录账号改了名,库里还压着按旧账号存的历史行:{detail}。"
"历史单据与待办按口径不跟着改名搬(那张单记的是当时的那个人),"
"所以改名前的单会从「我发起的」「我的待办」里查不到;"
"登录账号是本部署对外认人的业务键,请核对该不该由 Hub 改这个账号"
)
# 只查这次"没敢搬"的名字:那些配置还指着旧名,流程走到会没人可派
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.renamed = int(stats.renamed or 0)
run.reclaimed = int(stats.reclaimed or 0)
run.units_rebound = int(stats.units_rebound or 0)
# details 里带完整提示原文,所以 message 被 2000 字裁掉也不会真的丢信息
run.details = run_details(stats)
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/认回%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.units_rebound,
stats.permission_version,
stats.member_limit,
"(已截断)" if stats.truncated else "",
)
# ---------------------------------------------------------------------------
# 增量同步(变更流水,文档 10.2 / 10.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 _cursor_of(current: dict[str, Any]) -> int | None:
"""从**已经读出来**的运行态里取游标,口径与 :func:`changes_cursor` 一致。"""
raw = current.get("changes_cursor")
if raw is None:
return None
try:
return int(raw)
except (TypeError, ValueError):
return None
def changes_cursor(db: Session) -> int | None:
"""本地游标;``None`` 表示从没对齐过,第一步必须先走全量(文档 10.3 第 1 步)。"""
return _cursor_of(state(db))
def changes_status(db: Session, current: dict[str, Any] | None = None) -> dict[str, Any]:
"""给状态接口看的增量同步运行态(游标走到哪、还差多少、上次什么时候拉的)。
``current`` 是调用方已经读出来的那一份运行态(:func:`state` 的结果):一次 ``/hub/schedule``
里状态、下一次轮询、到点判定问的是同一段历史,各读一次等于同一行问五遍。传了就用传的,
不传照旧自己读——不缓存,谁都没法拿到上一秒的数。
"""
cfg = hubconfig.get()
current = state(db) if current is None else current
cursor = _cursor_of(current)
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``,再按 ``entity`` 是人是部门挑 ``data`` 里的键。
``data`` 的键名随来源变化——``source=hub`` 的事件用 ``id``,``source=wecom`` 用
``organization_id``/``user_id``(文档 10.4 明说了这个坑),``entity_id`` 才是稳定那个,
所以文档 10.2 要求"先按 ``source`` 与 ``entity`` 分支再取值",这里照做。
不分支会认错人:一条「把某人调去 12 号部门」的补丁长这样
``{"entity": "user", "data": {"id": 10086, "organization_id": 12}}``,
旧写法在 ``entity_id`` 缺席时先撞上 ``organization_id``,把部门号当人主键使——
轻则查无此人被跳过,重则改到 12 号那个人身上。人的事件只认 ``user_id``/``id``,
部门的事件只认 ``organization_id``/``id``,两边都不拿对方的字段凑数。
"""
entity = str(event.get("entity") or "").strip().lower()
if entity == EVENT_USER:
data_keys: tuple[str, ...] = ("user_id", "id")
elif entity == EVENT_ORGANIZATION:
data_keys = ("organization_id", "id")
else:
# 实体类型没带或不认识:维持老口径挨个试,别比原来更严格
data_keys = ("user_id", "organization_id", "id")
for source, key in ((event, "entity_id"), *((data, item) for item in data_keys)):
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``**(管理员删除用户):本地按主键软删——停用 + 吊销刷新令牌,
单据与流程历史原样留着(文档 10.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:
person_payload: dict[str, Any] = {
"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),
}
# 号码字段名跟着 Hub 的部署走,原样递给 _sync_people,认哪个字段由 _hub_mobile 决定
for key in MOBILE_KEYS:
if key in data:
person_payload[key] = data[key]
# 企微 UserID 同理:**只搬事件里真出现过的键**(键名随对方写法变,见 _wecom_keys_in)。
# 在这里凭空补一个 None 进去,"这条事件没提企微号"就会被读成"这个人没有企微号"而清空本地值
for key in _wecom_keys_in(data):
person_payload[key] = data[key]
# complete_roster 用默认的 False:一条变更不是清单,一个账号名都不许让位;
# report=False 是同一条理由——提示写的是整趟累计数,由 _pull_changes 收尾时统一报一次
_sync_people(db, [person_payload], unit_map, stats, now, report=False)
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
# 号码先落这一列,但**不在这里短路**:Hub 一条补丁里既调部门又改号是合法的,
# 直接 return 会把部门那半丢掉。只有下面部门与状态两条分支都没命中时,才由
# ``mobile_changed`` 把这条变更判成"落了"(否则它会被算成没用的变更跳过)。
mobile, mobile_given = _hub_mobile(data)
mobile_changed = False
if mobile_given:
if mobile and person.mobile != mobile:
person.mobile = mobile
stats.mobile_returned += 1
stats.mobile_updated += 1
mobile_changed = True
elif not mobile:
stats.mobile_invalid += 1
# 企微 UserID 与手机号走的是同一类补丁:先落列、同样不在这里短路。
# 全量那趟的汇总提示由 _pull_changes 收尾统一报,这一条补丁只把**需要人来处理的两种**
# 当场说清楚:号撞在别人身上、以及带过来的值洗不出合法 UserID。正常改号与清空不刷提示。
conflicts_before, invalid_before = stats.wecom_conflicts, stats.wecom_invalid
wecom_changed = _apply_wecom_user_id(db, person, data, None, stats)
if stats.wecom_conflicts > conflicts_before:
stats.note(
f"{person.account} 这条事件带来的企业微信 UserID {person.wecom_user_id} "
"本地已经挂在别的账号上:照抄 Hub 两边都留着,发给这个号会同时送达他们,"
"请回企业微信通讯录把它改到一个人的名下"
)
elif stats.wecom_invalid > invalid_before:
stats.note(
f"{person.account} 这条事件带的企业微信字段洗不出合法 UserID,本地这一列原样保留"
)
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
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
if mobile_changed or wecom_changed:
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``,层级由随后那趟全量刷准(文档 10.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:
"""落一条组织变更。
文档 10.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``:首次全量之后从这里开始追(文档 10.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)")
lock_token = _acquire_sync_locks()
# 同 :func:`sync_users`:写游标与建记录这两步出错了要自己把锁还回去,否则增量
# 同步一轮失败就把整个进程的组织同步按死在「已有同步任务正在执行」上。
try:
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=models.HubSyncRun.STATUS_RUNNING,
started_at=now,
operator=operator,
operator_name=operator_name,
)
db.add(run)
db.commit()
run_id = run.id
stats = SyncStats(started_at=now)
except Exception:
_release_sync_locks(lock_token)
raise
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
_raise_if_cancelled(stats)
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 表示"一条都没见过",这时最老的流水就是能拿到的第一条,不算缺口;
# 真正的缺口是"取过一些、但那批已经被裁剪"(文档 10.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
)
_report_run_notes(stats)
_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 HubSyncCancelled as exc:
db.rollback()
# 人为叫停不算故障:别把 changes_error 写上,否则下一轮要白等一个 retry 周期
_finish(
db, run_id, stats, models.HubSyncRun.STATUS_CANCELLED, str(exc),
state_patch={"changes_error": "", "changes_error_at": ""},
)
raise
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:
_release_sync_locks(lock_token)
def sync_changes(
db: Session,
*,
operator: str = "",
operator_name: str = "",
manual: bool = False,
) -> dict[str, Any]:
"""增量同步一趟:拉变更流水落库,必要时改拉一次全量重对齐(文档 10.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, current: dict[str, Any] | None = None
) -> bool:
"""这一分钟要不要去拉一次变更流水。
``current`` 同 :func:`changes_status`:界面把三档结论拼在一页时要看同一份快照,
调度线程照旧自己读(传 ``None``)。
"""
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) if current is None else current
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)
# 僵尸账号让位(判据与同步完全一致,见 _is_lost_account):这些行会把登录名腾开,
# 原本压在它们身上的"账号撞车"下一趟就不再发生了。预检必须按腾开之后的样子报,
# 否则界面上永远列一堆同步根本不会再撞的冲突,让人白核对一轮。
# 清单被截断、或人数比基准少得太离谱(Hub 在清库/重导)的那一趟不让位,预检跟着不算。
roster_ids = _roster_hub_ids(hub_users)
roster_floor = _roster_floor(db)
releases_allowed = not truncated and len(roster_ids) >= roster_floor
released_accounts: set[str] = set()
if releases_allowed:
released_accounts = {
row.account
for row in hub_source
if row.account and _is_lost_account(cfg, row, roster_ids)
}
# 手机号预检:界面要能回答"同步完手机上会有号码吗"——取决于 Hub 下不下发这一列
mobile_returned = 0
mobile_invalid = 0
def _mobile_of(item: dict[str, Any]) -> None:
nonlocal mobile_returned, mobile_invalid
mobile, given = _hub_mobile(item)
if mobile:
mobile_returned += 1
elif given:
mobile_invalid += 1
# 人员侧预检:身份只按 Hub 主键算,跟同步用的是同一套判据
seen_ids: set[int] = set()
new_people = 0
adopted = 0
inactive = 0
unassigned = 0
protected = 0
conflicts = 0
released = 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))
_mobile_of(item)
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.account in released_accounts:
# 占着这个账号的是"Hub 已查无此人"的停用同步号:同步会把它的登录名腾开,
# 于是这个人按清单里的账号建号,不算撞车
released += 1
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)
]
# 熔断预演:跟 _offboard_missing 用同一套算法,预检说"会被挡"就必须真跑也会被挡。
# 这里只数"还没停用的",已经是停用状态的不构成一次新的停用。
offboard_pending = [
row.account
for row in hub_source
if row.hub_user_id
and int(row.hub_user_id) not in seen_ids
and row.status != models.UserStatus.DISABLED
and not (cfg.hub_sync_protect_admins and row.role == models.ROLE_ADMIN)
]
offboard_guard = int(cfg.hub_sync_offboard_guard_percent or 0)
guard_min_people = _floor_value(cfg, "hub_sync_offboard_guard_min_people", OFFBOARD_GUARD_MIN_PEOPLE)
guard_min_units = _floor_value(cfg, "hub_sync_unit_offboard_guard_min", UNIT_OFFBOARD_GUARD_MIN)
offboard_ceiling = (
max(guard_min_people, len(hub_source) * offboard_guard // 100) if offboard_guard else 0
)
offboard_guarded = bool(offboard_guard) and len(offboard_pending) > offboard_ceiling
unbound = len([row for row in hub_source if not row.hub_user_id])
# 部门侧:会停用哪些、熔断挡不挡、Hub 换过主键之后本地留了几具重名的壳子
unit_pending = [
known_units[hub_id]
for hub_id in set(known_units) - org_ids
if known_units[hub_id].status != models.UnitStatus.DISABLED
]
unit_ceiling = (
max(guard_min_units, len(known_units) * offboard_guard // 100) if offboard_guard else 0
)
unit_guarded = bool(offboard_guard) and len(unit_pending) > unit_ceiling
# 重名壳子:判据与「一键清理」共用同一个函数,预检报了的数量必须真删得掉
zombie_units = find_shell_units(known_units.values(), roster_org_ids=org_ids)
zombie_blocked = {unit.id: shell_unit_blockers(db, unit) for unit in zombie_units}
# 影响预检: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,
),
)
warnings: list[str] = []
if truncated:
warnings.append(
f"人员清单被 member_limit={limit} 截断,本次数字只能当规模参考,"
"正式同步前先调大 OA_HUB_SYNC_MEMBER_LIMIT"
)
if offboard_guarded:
warnings.append(
f"有 {len(offboard_pending)} 人会被判成离职,超过熔断线"
f"({offboard_guard}% / 上限 {offboard_ceiling} 人):真同步时这一趟一个人都不停用。"
"先核对 Hub 拉到的是不是这套环境该有的人(换过站点或目录密钥最容易撞上),"
"确认没问题再把 OA_HUB_SYNC_OFFBOARD_GUARD_PERCENT 调大或设 0"
)
if unit_guarded:
warnings.append(
f"有 {len(unit_pending)} 个部门会被判成「Hub 已消失」而停用,超过部门停用熔断线"
f"({offboard_guard}% / 上限 {unit_ceiling} 个):真同步时这一趟一个部门都不停。"
"停一个部门会连带摘掉它下面所有人的数据范围与按部门配的审批规则,先核对组织清单"
)
if not releases_allowed and not truncated:
warnings.append(
f"Hub 这次只回了 {len(roster_ids)} 个人,不足可参照基准的 {_roster_floor_percent()}%"
f"({roster_floor} 人):目录像是在清空或重导,"
"真同步时这一趟不会动任何人的登录名(account_releases=0),"
"但清单里没有的人照样会被停用,先核对 Hub 那边的人对不对得上"
)
if zombie_units:
warnings.append(
f"本地有 {len(zombie_units)} 个已停用的部门跟在职部门重名"
f"(例如 {zombie_units[0].name}):那是 Hub 换过 organization_id 留下的壳子,"
"同步不会再认它们也不会自动合并,要清掉得先在部门上解绑再删除"
)
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),
# 真会被这一趟停用的部门,以及熔断挡不挡得住(口径与人员那侧同一个百分比)
"offboard_pending": len(unit_pending),
"offboard_guard": {
"percent": offboard_guard,
"ceiling": unit_ceiling,
"min_units": guard_min_units,
"tripped": unit_guarded,
},
# Hub 换过 organization_id 之后留在树上的重名壳子:编码与名称都已被在职部门占用,
# 同步不会再认它们,也不会自动合并,需要在部门里手工处理
"zombie_units": len(zombie_units),
"zombie_unit_samples": [
{
"id": unit.id,
"name": unit.name,
"code": unit.code,
# 非空 = 这一具删不掉(还有人/有下级/被角色当数据范围),界面要说清为什么
"blockers": zombie_blocked[unit.id],
}
for unit in zombie_units[:5]
],
# 能一键删掉的那几具(其余要先把人挪走、下级删掉或改角色数据范围)
"zombie_units_deletable": len([1 for reasons in zombie_blocked.values() if not reasons]),
"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),
# 真会被这一趟停用的只有还没停用的那批,以及熔断挡不挡得住
"offboard_pending": len(offboard_pending),
"offboard_guard": {
"percent": offboard_guard,
"ceiling": offboard_ceiling,
"min_people": guard_min_people,
"tripped": offboard_guarded,
},
"no_hub_id": no_id,
"account_conflicts": conflicts,
# 会让位腾出登录名的僵尸同步号(Hub 已查无此人 + 本地已停用)
"account_releases": released,
# 这一趟到底让不让位:清单人数不够就说明 Hub 目录可疑,账号名原地留着
"account_releases_allowed": releases_allowed,
"account_release_floor": roster_floor,
"account_release_floor_percent": _roster_floor_percent(),
"account_renames": len(account_map),
"name_renames": len(person_name_map),
"unbound": unbound,
# 号码来源看清了再决定要不要动本地这一列:with_mobile=0 且 mobile_invalid=0
# 就是 Hub 目录压根没下发这个字段,同步不会凭空变出号码来。
"with_mobile": mobile_returned,
"mobile_invalid": mobile_invalid,
"mobile_note": (
"Hub 目录没有下发手机号字段:同步不会动本地已有的号码,"
"这一列目前只能靠本地录入(或让 Hub 在 users[] 里带 mobile)"
if not mobile_returned and not mobile_invalid
else "Hub 带了号码,同步会按 Hub 覆盖本地;洗不出合法号码的人会计数并保留本地值"
),
# 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": (
"权限角色、数据范围、部门负责人都按主键存,同步不改主键也不删行,不会掉;"
"这里列的是按名字/账号存下的审批岗位与共享名单,同步会自动搬到新值,"
"搬不动的会写进同步记录"
),
},
"offboard_accounts": offboard_candidates[:20],
"organization_sample": orgs[:10],
"warning": ";".join(warnings),
}
def probe(db: Session | None = None) -> dict[str, Any]:
"""连通性自检:目录接口能不能拉、同步凭证(可无)好不好用、免登与增量接口通不通。
整段跑在 :func:`app.service.hub.probe_mode` 里:自检是管理员主动点的"现在就真试一次",
必须绕开熔断,不然刚冷却的那几秒会把"其实已经好了"报成"不可用"。
"""
with hub_api.probe_mode():
return _probe_steps(db)
def _probe_steps(db: Session | None = None) -> dict[str, Any]:
"""自检本体:逐项打 Hub,把每一项的结果攒起来。"""
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
# 门户可见性(文档 7.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 "统一身份认证服务检查未通过,详见各项说明",
}