3028 lines
136 KiB
Python
3028 lines
136 KiB
Python
"""Hub 组织人员镜像同步(夜间定时 + 一键实时)。
|
||
|
||
对端口径见《Hub 权限接口交互文档》第 11 节:``GET /api/v1/auth/directory`` 一次
|
||
返回完整组织树和同一批人员的扁平清单。落库规则按文档的六条约定来:
|
||
|
||
* 人员以扁平清单 ``users`` 为准(合成节点 ``organization_id=0`` 里也带着真实部门);
|
||
* ``status`` 非 1 一律置为本地「已停用」,不删除账号;
|
||
* ``truncated`` 为真时清单不完整,只写不撤,绝不按截断结果下线本地人员;
|
||
* ``permission_version`` 没变化时定时任务跳过写入,手动「立即同步」永远强拉;
|
||
* 组织层级成环靠深度上限挡住,不做静默丢弃;
|
||
* 部门同理:Hub 已经不存在的同步部门(``oa_unit.hub_org_id`` 不为空且没出现在这次导出
|
||
里)在清单完整时置为停用,本地自建部门(``hub_org_id`` 为空)永远不碰;
|
||
* 手机号(``users.mobile``)只在 Hub **确实带了号码**时才动这一列:Hub 压根没下发这个
|
||
字段,和下发了但洗不出合法号码,是两回事——前者保留本地值继续用,后者计数报出来,
|
||
两者都不把人家的号码清空。
|
||
|
||
* 企业微信 UserID(``users.wecom_user_id``)比手机号多一种情况:**"带了字段但值是空的"
|
||
是一句话,不是一个缺失**。企微 UserID 会被删掉再分配给另一名员工,所以 Hub 明确说
|
||
"这个人没有企微号"时本地跟着清空;压根不带这个字段时仍然原样保留(见 6 节与
|
||
:func:`_hub_wecom_user_id`)。
|
||
|
||
凭证:全量目录接口(文档第 11 节)现在用长期密钥认服务端调用——配了「目录密钥」
|
||
(``hub_directory_key`` / ``OA_HUB_DIRECTORY_KEY``)就以请求头 ``X-Directory-Key`` 带出去,
|
||
同步记录里写 ``credential=directory_key``,不必登录换 token。没配密钥才退回老的
|
||
Bearer 口径(长期 token 或集成账号登录换 token),两者都没有就是匿名拉,只在对方
|
||
不校验的部署上拉得到(``credential=anonymous``)。
|
||
|
||
本地账号的边界:只有 ``users.source='hub'`` 的账号会被同步改名、换部门、停用;
|
||
本地手工建的账号靠 ``account`` 唯一键被「认领」(认领后同样标成 ``hub``),而
|
||
``role='admin'`` 的超管默认受 ``OA_HUB_SYNC_PROTECT_ADMINS`` 保护,同步碰不到,
|
||
免得哪天 Hub 里没有 admin 就把系统锁死。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import re
|
||
import secrets
|
||
import threading
|
||
from collections.abc import 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 是"没号就不带键",不会给一个空串。
|
||
#: 目录接口的文档(对接指南 6.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)
|
||
|
||
|
||
@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
|
||
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
|
||
#: UserID 已经挂在别的账号上、本次没敢覆盖的人数(企微号重新分配过,或本地有重复账号)
|
||
wecom_conflicts: 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
|
||
permission_version: int = 0
|
||
member_limit: int = 0
|
||
truncated: bool = False
|
||
# 增量轮询(变更流水)专用:这趟停在哪个游标、落了几条、跳过几条
|
||
cursor_seq: int = 0
|
||
changes_applied: int = 0
|
||
changes_skipped: int = 0
|
||
credential: str = "anonymous"
|
||
messages: list[str] = field(default_factory=list)
|
||
|
||
def note(self, text: str) -> None:
|
||
if text and len(self.messages) < 20:
|
||
self.messages.append(text)
|
||
|
||
@property
|
||
def changed(self) -> int:
|
||
return (
|
||
self.created
|
||
+ self.updated
|
||
+ self.offboarded
|
||
+ self.units_created
|
||
+ self.units_updated
|
||
+ self.units_offboarded
|
||
+ self.units_bound
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 运行态
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def state(db: Session) -> dict[str, Any]:
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
value = row.value if row is not None and isinstance(row.value, dict) else {}
|
||
return dict(value)
|
||
|
||
|
||
def set_state(db: Session, patch: dict[str, Any]) -> dict[str, Any]:
|
||
"""往 ``hub_directory`` 这行系统设置里增量写几个键(同步运行态)。"""
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
if row is None:
|
||
row = models.SystemSetting(key=STATE_KEY, value={}, description="Hub 组织人员同步状态")
|
||
db.add(row)
|
||
merged = dict(row.value or {})
|
||
merged.update(patch)
|
||
row.value = merged
|
||
db.commit()
|
||
return merged
|
||
|
||
|
||
def latest_run(db: Session) -> models.HubSyncRun | None:
|
||
return db.execute(
|
||
select(models.HubSyncRun).order_by(models.HubSyncRun.started_at.desc()).limit(1)
|
||
).scalar_one_or_none()
|
||
|
||
|
||
def running() -> bool:
|
||
"""现在是不是有一趟同步正在跑(界面与调度都用它显示状态)。
|
||
|
||
本进程那把进程内锁和跨副本那把 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 serialize_run(row: models.HubSyncRun) -> dict[str, Any]:
|
||
return {
|
||
"id": row.id,
|
||
"trigger": row.trigger,
|
||
"trigger_label": TRIGGER_LABELS.get(row.trigger, row.trigger),
|
||
"status": row.status,
|
||
"started_at": row.started_at.strftime("%Y-%m-%d %H:%M:%S") if row.started_at else "",
|
||
"finished_at": row.finished_at.strftime("%Y-%m-%d %H:%M:%S") if row.finished_at else "",
|
||
"duration_ms": row.duration_ms,
|
||
"total_users": row.total_users,
|
||
"returned_users": row.returned_users,
|
||
"created": row.created,
|
||
"updated": row.updated,
|
||
"offboarded": row.offboarded,
|
||
"units_created": row.units_created,
|
||
"units_updated": row.units_updated,
|
||
"units_offboarded": row.units_offboarded,
|
||
"permission_version": row.permission_version,
|
||
"member_limit": row.member_limit,
|
||
"truncated": bool(row.truncated),
|
||
"credential": row.credential,
|
||
"credential_label": credential_label(row.credential),
|
||
"cursor_seq": int(row.cursor_seq or 0),
|
||
"changes_applied": int(row.changes_applied or 0),
|
||
"operator": row.operator,
|
||
"operator_name": row.operator_name,
|
||
"message": row.message,
|
||
"unchanged": (
|
||
row.created
|
||
+ row.updated
|
||
+ row.offboarded
|
||
+ row.units_created
|
||
+ row.units_updated
|
||
+ row.units_offboarded
|
||
)
|
||
== 0,
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 组织
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def _iter_org_nodes(
|
||
organizations: list[dict[str, Any]], parent_id: int | None = None, depth: int = 0
|
||
) -> Iterator[tuple[dict[str, Any], int | None]]:
|
||
"""先序展开组织树(父在子前),深度超过 64 层直接截断。"""
|
||
if depth > 64 or not isinstance(organizations, list):
|
||
return
|
||
for node in organizations:
|
||
if not isinstance(node, dict):
|
||
continue
|
||
yield node, parent_id
|
||
children = node.get("children") or []
|
||
hub_id = models.as_id(node.get("organization_id"))
|
||
yield from _iter_org_nodes(children, hub_id or parent_id, depth + 1)
|
||
|
||
|
||
def _hub_parent_id(node: dict[str, Any]) -> int:
|
||
"""节点自己声明的上级:先看 ``parent_id``,再从它自己的 id 路径里取倒数第二段。
|
||
|
||
Hub 的 ``path`` 是按 organization_id 拼的(``/1/8/10/``),最后一段是自己,
|
||
倒数第二段就是上级。有些下发只给 path 不给 parent_id,这一条能兜住。
|
||
"""
|
||
parent = models.as_id(node.get("parent_id")) or 0
|
||
if parent and int(parent) > 0:
|
||
return int(parent)
|
||
parts = [piece for piece in str(node.get("path") or "").split("/") if piece]
|
||
if len(parts) >= 2:
|
||
upper = models.as_id(parts[-2]) or 0
|
||
if upper > 0:
|
||
return int(upper)
|
||
return 0
|
||
|
||
|
||
def _org_tree(organizations: Any, stats: SyncStats | None = None) -> list[dict[str, Any]]:
|
||
"""把 Hub 下发的组织清单整理成一棵能先序展开的树。
|
||
|
||
Hub 有两种口径,都得支持:
|
||
|
||
* 嵌套下发 —— ``children`` 里带着下级(本地验收桩一直用这种);
|
||
* 扁平下发 —— 一张清单把所有组织平铺,``children`` 是空的,层级只写在
|
||
``parent_id`` 与 id 路径 ``path`` 里(真实 Hub 的 ``auth/directory`` 就是这种)。
|
||
|
||
只认嵌套会发生什么:扁平清单被当成一排根部门,组织架构摊平、``path`` 与部门 DN 全部
|
||
停在一级,于是按「本部门及下级」算的数据范围、审批岗位里勾了含下级的部门、按部门路径
|
||
存的引用统统解析不到人 —— 数据看着在,就是不对。所以这里统一还原成树,上级按
|
||
``parent_id`` -> ``path`` -> 原本的嵌套顺序 依次取。
|
||
|
||
对不上号的上级(不在这份清单里、或者自己指自己)不猜,按根部门处理并写进同步记录;
|
||
万一下发里成环,断在最外层的那个节点上,不能让本地递归爬树爬到天荒地老。
|
||
"""
|
||
if not isinstance(organizations, list):
|
||
return []
|
||
by_id: dict[int, dict[str, Any]] = {}
|
||
order: list[int] = []
|
||
nested_parent: dict[int, int] = {}
|
||
duplicates = 0
|
||
for node, parent_hub_id in _iter_org_nodes(organizations):
|
||
hub_id = models.as_id(node.get("organization_id"))
|
||
if not hub_id or int(hub_id) <= 0:
|
||
continue
|
||
hub_id = int(hub_id)
|
||
if hub_id in by_id:
|
||
duplicates += 1
|
||
continue # 同一个组织下发两次:以第一次出现的位置为准
|
||
clone = dict(node)
|
||
clone["children"] = []
|
||
by_id[hub_id] = clone
|
||
order.append(hub_id)
|
||
parent = models.as_id(parent_hub_id) or 0
|
||
if parent and int(parent) > 0 and int(parent) != hub_id:
|
||
nested_parent[hub_id] = int(parent)
|
||
|
||
roots: list[dict[str, Any]] = []
|
||
parent_of: dict[int, int] = {}
|
||
broken: list[str] = []
|
||
for hub_id in order:
|
||
node = by_id[hub_id]
|
||
upper = _hub_parent_id(node) or nested_parent.get(hub_id, 0)
|
||
if upper == hub_id:
|
||
upper = 0
|
||
parent = by_id.get(upper) if upper else None
|
||
if parent is None:
|
||
if upper:
|
||
broken.append(str(node.get("name") or hub_id))
|
||
roots.append(node)
|
||
continue
|
||
parent_of[hub_id] = upper
|
||
parent["children"].append(node)
|
||
|
||
# 断环:沿 parent 往上爬,回到自己就把这一条改挂到根上
|
||
cycled: list[str] = []
|
||
for hub_id in order:
|
||
chain: list[int] = []
|
||
cursor: int | None = hub_id
|
||
guard = 0
|
||
while cursor is not None and guard <= 64:
|
||
guard += 1
|
||
if cursor in chain:
|
||
node = by_id[hub_id]
|
||
upper = parent_of.pop(hub_id, 0)
|
||
parent = by_id.get(upper) if upper else None
|
||
if parent is not None:
|
||
# 只掐断向上的那一条,子树原样跟着它走:把 children 一起清掉等于
|
||
# 把整支下级从这次同步里抹掉,它们会被当成"Hub 里没有了"而停用。
|
||
parent["children"] = [row for row in parent["children"] if row is not node]
|
||
roots.append(node)
|
||
cycled.append(str(node.get("name") or hub_id))
|
||
break
|
||
chain.append(cursor)
|
||
cursor = parent_of.get(cursor)
|
||
|
||
if stats is not None:
|
||
if broken:
|
||
shown = "、".join(broken[:5]) + ("…" if len(broken) > 5 else "")
|
||
stats.note(
|
||
f"Hub 有 {len(broken)} 个组织的上级不在这份清单里,本次按一级部门落库:{shown}"
|
||
)
|
||
if cycled:
|
||
shown = "、".join(cycled[:5]) + ("…" if len(cycled) > 5 else "")
|
||
stats.note(f"Hub 的组织层级里出现了环,已拆到一级:{shown}")
|
||
if duplicates:
|
||
stats.note(f"Hub 清单里有 {duplicates} 个组织重复下发,只认第一次出现的那条")
|
||
return roots
|
||
|
||
|
||
def _record_pair(mapping: dict[str, str], old: str, new: str) -> None:
|
||
"""记下一条"旧名 -> 新名",给收尾的引用搬运查表用。
|
||
|
||
只记这一行自己的前后值,**不要把链条接下去**:一趟同步里每个名字都只属于某一行,
|
||
旧名上的引用本来就指向那一行,它的新值就是这条映射。接力(甲从 A 改到 B、乙从 B 改到 C)
|
||
和互换(甲 A<->B、乙 B<->A)都靠这两条独立的映射各自指回本人;一旦接成 A->C,
|
||
甲的引用就会跑到乙身上去。
|
||
"""
|
||
if not old or not new or old == new:
|
||
return
|
||
mapping[old] = new
|
||
|
||
|
||
def _set_unit_paths(
|
||
unit: models.Unit, parent: models.Unit | None, stats: SyncStats | None = None
|
||
) -> bool:
|
||
"""按 O2OA 口径重算 ``path``/``distinguished_name``,返回有没有变化。"""
|
||
parent_path = parent.path if parent else ""
|
||
# ``oa_unit.path`` 与 ``distinguished_name`` 都是 512:父级越深,本地能放下的名字越短。
|
||
# 超出的部分在拼路径这一步就裁掉(DN 多出的 2 个字符也算进去),否则 Hub 给个长名
|
||
# 会让整批同步在写库那一刻回滚。
|
||
room = max(1, min(255, 510 - len(parent_path)))
|
||
if len(unit.name) > room:
|
||
unit.name = unit.name[:room]
|
||
new_path = f"{parent_path}{unit.name}\\"
|
||
new_dn = f"o={new_path[:-1]}"
|
||
parent_name = parent.name if parent else ""
|
||
if unit.path == new_path and unit.distinguished_name == new_dn and unit.parent_name == parent_name:
|
||
return False
|
||
if stats is not None:
|
||
_record_pair(stats.path_map, unit.path or "", new_path)
|
||
unit.parent_name = parent_name
|
||
unit.path = new_path
|
||
unit.distinguished_name = new_dn
|
||
unit.short_name = unit.name
|
||
return True
|
||
|
||
|
||
def _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 _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 里消失也只是停用不删除),组织架构、
|
||
部门负责人、按部门配的权限与审批规则全靠它长期对上号。
|
||
|
||
字段按文档第 11 节的组织节点落库:``organization_id`` -> ``hub_org_id``、
|
||
``code`` -> ``code``、``name`` -> ``name``、``status`` -> ``status``(``1`` 之外一律停用);
|
||
``path`` 是 Hub 自己按 id 拼的 ``/1/2/``,本地另有 O2OA 口径的 ``path``/DN,不落这一列;
|
||
但它和 ``parent_id`` 一起被 ``_org_tree`` 用来还原层级(真实 Hub 是扁平下发、``children``
|
||
为空,只认嵌套的话整个组织架构会被摊平,见 ``docs/hub-integration.md`` 第 6 节)。
|
||
``member_count`` 是导出批次的直属人数,本地按 ``organization_id`` 现算,同样不落库。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
mapped = _hub_units(db, stats)
|
||
local_by_code = _local_units_by_code(db)
|
||
|
||
seen: set[int] = set()
|
||
order: list[tuple[models.Unit, models.Unit | None]] = []
|
||
for index, (node, parent_hub_id) in enumerate(
|
||
_iter_org_nodes(_org_tree(organizations, stats))
|
||
):
|
||
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
|
||
if unit is None:
|
||
# 本系统自己加的部门:组织编码跟 Hub 这个部门一模一样、而且这个编码本地只有一处,
|
||
# 就认定是同一个部门,认下来(补写 hub_org_id),而不是再建一个重名部门。
|
||
candidates = local_by_code.get(code) or [] if code else []
|
||
if len(candidates) > 1:
|
||
stats.note(f"本地有 {len(candidates)} 个部门都用编码 {code},认领不了,本次按新部门建")
|
||
local_by_code[code] = []
|
||
elif len(candidates) == 1 and cfg.hub_sync_bind_local_by_code:
|
||
unit = candidates[0]
|
||
claimed = True
|
||
local_by_code.pop(code, None)
|
||
|
||
if unit is None:
|
||
unit = models.Unit(
|
||
name=name,
|
||
code=code,
|
||
alias=code,
|
||
description="由统一身份同步创建",
|
||
parent_id=parent.id if parent else None,
|
||
hub_org_id=hub_id,
|
||
status=status,
|
||
)
|
||
db.add(unit)
|
||
db.flush()
|
||
mapped[hub_id] = unit
|
||
stats.units_created += 1
|
||
else:
|
||
parent_id = parent.id if parent else None
|
||
changed = (
|
||
unit.name != name
|
||
or unit.parent_id != parent_id
|
||
or unit.status != status
|
||
or unit.hub_org_id != hub_id
|
||
or bool(code and unit.code != code)
|
||
)
|
||
if changed:
|
||
_record_pair(stats.unit_name_map, unit.name, name)
|
||
unit.name = name
|
||
unit.parent_id = parent_id
|
||
unit.status = status
|
||
unit.hub_org_id = hub_id
|
||
if code:
|
||
unit.code = code
|
||
if claimed:
|
||
stats.units_bound += 1
|
||
stats.note(
|
||
f"本地部门 {name}(编码 {code})已按编码认成 Hub 组织 {hub_id},"
|
||
"此后名称与层级由 Hub 接管"
|
||
)
|
||
else:
|
||
stats.units_updated += 1
|
||
mapped[hub_id] = unit
|
||
order.append((unit, parent))
|
||
|
||
# 第二轮再算路径:此时父级已经全部落库,改名/挪动会连带刷子树与部门 DN。
|
||
for unit, parent in order:
|
||
_refresh_paths(db, unit, parent, stats)
|
||
|
||
_offboard_missing_units(db, seen, stats)
|
||
_report_local_units(db, seen, stats)
|
||
return {hub_id: unit.id for hub_id, unit in mapped.items()}
|
||
|
||
|
||
def _offboard_missing_units(db: Session, seen: set[int], stats: SyncStats) -> None:
|
||
"""Hub 已经不存在的同步部门置为停用(本地自建部门不在 ``seen`` 判据里,永不处理)。
|
||
|
||
这里是"停用"而不是"删除":``hub_org_id`` 一丢就再也对不回 Hub 的那个组织,下趟同步
|
||
只会新建一个空部门,负责人、按部门配的权限与审批规则全丢。宁可留着停用的壳子,
|
||
等对方把组织加回来就自动接上。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
if not cfg.hub_sync_offboard:
|
||
return
|
||
if stats.truncated:
|
||
# 导出被 member_limit 截断时组织树也不完整,这时下线部门属于误伤。
|
||
return
|
||
rows = db.execute(
|
||
select(models.Unit).where(
|
||
models.Unit.hub_org_id.isnot(None),
|
||
models.Unit.status != models.UnitStatus.DISABLED,
|
||
)
|
||
).scalars().all()
|
||
for row in rows:
|
||
if row.hub_org_id in seen:
|
||
continue
|
||
row.status = models.UnitStatus.DISABLED
|
||
stats.units_offboarded += 1
|
||
if stats.units_offboarded:
|
||
stats.note(
|
||
f"Hub 已不存在的 {stats.units_offboarded} 个同步部门已停用"
|
||
"(部门本身保留,Hub 里加回来会自动接上)"
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 人员
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def is_emergency_account(account: str) -> bool:
|
||
"""这个账号名是不是应急账号(``hub_local_accounts`` + 内置超管,永远只用本地口令登录)。
|
||
|
||
这类账号绝不能被统一身份接管:Hub 哪天建一个同名的号,本地这个后门就会被标成
|
||
``source=hub``,从此跟着 Hub 停用 —— Hub 一停用人就进不来了,应急通道形同虚设。
|
||
与 ``hub_sync_protect_admins`` 无关,那个开关可以关,这条不行。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
return str(account or "").strip().lower() in cfg.local_only_accounts
|
||
|
||
|
||
def _protect_from_hub(cfg, person: models.User) -> bool:
|
||
"""``hub_sync_protect_admins`` 开关下的"这个人不能被 Hub 接管"判据。
|
||
|
||
护的是**本地自建**的管理员(内置超管、界面上手工建的管理员):Hub 那边有没有这个人
|
||
都不确定,让 Hub 去改名、换部门、停用等于把自己的后门交给别人堵。
|
||
同步建起来的人后来被授予管理员角色**不算**在内 —— 那个人归 Hub 管,跟着它改名、
|
||
它说停用就停用才是对的;否则这个人的资料会永远停在被提升的那一刻,越同步越乱。
|
||
"""
|
||
return bool(
|
||
cfg.hub_sync_protect_admins
|
||
and person.role == models.ROLE_ADMIN
|
||
and person.source == models.AccountSource.LOCAL
|
||
)
|
||
|
||
|
||
def _map_status(hub_status: int) -> int:
|
||
"""Hub 只保证「1=启用,其余为停用/待审核」,本地一律折成停用。"""
|
||
return models.UserStatus.ACTIVE if int(hub_status or 0) == 1 else models.UserStatus.DISABLED
|
||
|
||
|
||
def _apply_account_renames(
|
||
db: Session,
|
||
plan: dict[int, tuple[models.User, str, str]],
|
||
holders: dict[str, int],
|
||
by_account: dict[str, models.User],
|
||
stats: SyncStats,
|
||
) -> None:
|
||
"""按"谁先把账号腾开"的顺序把改名的行落库。
|
||
|
||
``users.account`` 上有唯一键,而本项目的 Session 关了 autoflush:一边循环一边改账号,
|
||
遇到「甲把 qianjiu2 让给乙」这种接力,两条 UPDATE 会攒到收尾一起发出去,先发的那条
|
||
撞上唯一键,整趟同步直接失败(不是跳过一个人,是一行都没写)。所以先把要改的挑出来,
|
||
目标账号没人占就先改并当场 flush;互相占用的环就先统统挪到临时账号,再落最终值。
|
||
"""
|
||
remaining = dict(plan)
|
||
guard = 0
|
||
while remaining and guard <= len(plan):
|
||
guard += 1
|
||
progressed = False
|
||
for person_id in list(remaining):
|
||
person, account, old_account = remaining[person_id]
|
||
holder_id = holders.get(account)
|
||
if holder_id is not None and holder_id != person_id:
|
||
if holder_id in remaining:
|
||
continue # 等占着这个账号的那个人先腾开
|
||
# 起跑时看是空的,结果这一趟里新建的号先占上了:不抢,保持原账号
|
||
stats.conflicts += 1
|
||
remaining.pop(person_id, None)
|
||
continue
|
||
person.account = account
|
||
holders.pop(old_account, None)
|
||
holders[account] = person_id
|
||
by_account.pop(old_account, None)
|
||
by_account[account] = person
|
||
_record_pair(stats.account_map, old_account, account)
|
||
db.flush()
|
||
stats.renamed += 1
|
||
remaining.pop(person_id, None)
|
||
progressed = True
|
||
if not progressed:
|
||
break
|
||
if not remaining:
|
||
return
|
||
# 还剩互相占用的环:先把环上的人统统挪到临时账号,把彼此盯着的账号腾干净再落最终值。
|
||
# 腾的时候要把 holders / by_account 里的旧账号一起抹掉,否则下一轮查目标账号还是会
|
||
# 看成"被别人占着",整个环一个账号都换不出去。
|
||
for person, _account, old_account in remaining.values():
|
||
if holders.get(old_account) == person.id:
|
||
holders.pop(old_account, None)
|
||
by_account.pop(old_account, None)
|
||
staging = f"hub-tmp-{old_account}"[:190]
|
||
suffix = 2
|
||
while holders.get(staging) is not None: # 万一本地真有个 hub-tmp-xxx,往后加号
|
||
staging = f"hub-tmp-{old_account}-{suffix}"[:190]
|
||
suffix += 1
|
||
person.account = staging
|
||
holders[staging] = person.id
|
||
db.flush()
|
||
for person, account, old_account in remaining.values():
|
||
holder_id = holders.get(account)
|
||
if holder_id is not None and holder_id != person.id:
|
||
stats.conflicts += 1
|
||
person.account = old_account # 抢不过就退回原账号,别把人留在临时账号上
|
||
holders[old_account] = person.id
|
||
by_account[old_account] = person
|
||
continue
|
||
person.account = account
|
||
holders[account] = person.id
|
||
by_account[account] = person
|
||
_record_pair(stats.account_map, old_account, account)
|
||
stats.renamed += 1
|
||
db.flush()
|
||
|
||
|
||
def _plan_account_renames(
|
||
db: Session,
|
||
users: list[dict[str, Any]],
|
||
by_hub_id: dict[int, models.User],
|
||
by_account: dict[str, models.User],
|
||
stats: SyncStats,
|
||
) -> None:
|
||
"""把这一趟 Hub 要求的账号改名一次性排好再落库(见 ``_apply_account_renames``)。
|
||
|
||
分两遍扫:先收齐"Hub 要求换账号"的人,再判断目标账号是不是被一个不打算动的人占着。
|
||
一遍扫不行的原因是清单有先后 —— 甲要乙的账号、乙也要甲的账号时,先扫到的那个会以为
|
||
对面是"不动的人"而被判成撞车,结果两个人一个都没换成,而这其实是能换的(互换)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
holders = {account: person.id for account, person in by_account.items()}
|
||
wanted: dict[int, tuple[models.User, str, str]] = {}
|
||
for item in users:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
account = models.clip(str(item.get("account") or "").strip(), 190)
|
||
hub_user_id = models.as_id(item.get("user_id"))
|
||
if not account or not hub_user_id:
|
||
continue
|
||
person = by_hub_id.get(int(hub_user_id))
|
||
if person is None or person.account == account:
|
||
continue
|
||
if _protect_from_hub(cfg, person) or is_emergency_account(person.account):
|
||
continue
|
||
wanted[person.id] = (person, account, person.account)
|
||
plan: dict[int, tuple[models.User, str, str]] = {}
|
||
for person_id, (person, account, old_account) in wanted.items():
|
||
holder_id = holders.get(account)
|
||
if holder_id is not None and holder_id != person.id and holder_id not in wanted:
|
||
# 账号已经属于另一个不动的人:不抢,主键与其余信息照旧跟 Hub 对齐
|
||
stats.conflicts += 1
|
||
continue
|
||
plan[person.id] = (person, account, old_account)
|
||
if plan:
|
||
_apply_account_renames(db, plan, holders, by_account, stats)
|
||
|
||
|
||
def _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``、按值现查一次。
|
||
|
||
一个 UserID 只允许挂一个人。企微号被删掉再分配给别人时,Hub 会把同一个号发到新任
|
||
身上,本地照着写就变成两个账号共用一个收件地址——撞上就谁都不动、计数上报,交人工
|
||
核对:少发一条通知是小事,把张三的待办推到李四手机上是大事。
|
||
"""
|
||
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
|
||
holder = by_wecom_id.get(value) if by_wecom_id is not None else _wecom_holder(db, value)
|
||
if holder is not None and holder.id != person.id:
|
||
stats.wecom_conflicts += 1
|
||
return False
|
||
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,
|
||
) -> set[int]:
|
||
"""Hub 扁平人员清单 -> ``users``,返回这次清单里出现的 Hub 主键。
|
||
|
||
**身份只认 Hub 的 ``user_id``**(每次都是全量清单,本地不自造主键):账号会被人先注册
|
||
走、也会在 Hub 侧改名,姓名更是常改,只有 Hub 主键从头到尾指着同一个人。于是——
|
||
|
||
* 清单里没带 ``user_id`` 的人不建号也不认领,只计数上报(宁可少一个人,也别把
|
||
两个不同的人并成一条);
|
||
* 先按 ``hub_user_id`` 找人;找不到才看账号,而账号只允许认领**还没绑过主键**的
|
||
本地账号(手工建的、或历史遗留的),认领后写 ``source=hub``;
|
||
* 账号已经绑在别人身上就跳过并计数,绝不覆盖 ``hub_user_id``——那等于把两个人的
|
||
权限、待办、流程历史搅在一起;
|
||
* 已绑主键的人,账号跟着 Hub 改(新账号没人占用才改),姓名/邮箱/部门/状态一律以
|
||
Hub 为准。改走的旧账号会记进 ``account_map``,收尾时把按账号存的审批引用一起搬走。
|
||
* 手机号只在 Hub 这次**给了合法号码**时覆盖:Hub 的目录接口现在不一定下发这一列,
|
||
而本地这列可能是 HR 自己录的,"没下发"绝不能被写成"清空"。
|
||
* 企业微信 UserID(``wecom_user_id``)跟着一起对齐,但比手机号多认一种情况: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)
|
||
|
||
# 这一列这次到底有没有下发:清单里只要有一个人带过企微键就算下发了,
|
||
# 于是"这个人没带"读成"这个人没企微号"(清空),而不是"接口没这个字段"(不动)。
|
||
# 一趟全量一个判断,绝不按单条 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)
|
||
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:
|
||
stats.updated += 1
|
||
|
||
if stats.adopted:
|
||
stats.note(f"认领本地同名账号 {stats.adopted} 个,已标记为统一身份账号(本地主键与权限不变)")
|
||
if stats.renamed:
|
||
stats.note(f"{stats.renamed} 人的登录账号已跟随 Hub 改名,按账号存下的审批引用同步搬走")
|
||
if stats.conflicts:
|
||
stats.note(
|
||
f"{stats.conflicts} 人的账号在本地已属于另一个统一身份,本次跳过没有覆盖,"
|
||
"请人工核对是重复账号还是 Hub 数据错了"
|
||
)
|
||
if stats.no_hub_id:
|
||
stats.note(f"Hub 有 {stats.no_hub_id} 人没带 user_id(或没带账号),无法按主键认人,本次未处理")
|
||
if stats.skipped:
|
||
stats.note(f"Hub 有 {stats.skipped} 人本地没有对应账号,OA_HUB_AUTO_PROVISION=false 未建号")
|
||
if stats.protected:
|
||
stats.note(
|
||
f"{stats.protected} 个本地自建的管理员账号按 OA_HUB_SYNC_PROTECT_ADMINS 跳过,"
|
||
"同步没有改它们(统一身份同步来的账号不受这一项影响,照常跟着 Hub 走)"
|
||
)
|
||
if stats.emergency:
|
||
stats.note(
|
||
f"Hub 有 {stats.emergency} 个人跟本地应急账号(OA_HUB_LOCAL_ACCOUNTS)同名,"
|
||
"账号名让给了本地,这些人本次没有同步;要么 Hub 换个账号名,要么把应急账号改成别的名字"
|
||
)
|
||
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"{stats.wecom_conflicts} 人的企业微信 UserID 已经挂在别的本地账号上,本次没有覆盖,"
|
||
"请人工核对是企微号重新分配过、还是本地有重复账号;两个人共用一个号一定会推错人"
|
||
)
|
||
return seen_ids
|
||
|
||
|
||
def _offboard_missing(db: Session, seen_ids: set[int], stats: SyncStats, now: datetime) -> None:
|
||
"""Hub 已经不存在的同步账号置为停用(只停用不删除,也不碰本地账号)。
|
||
|
||
判据只有 ``hub_user_id`` 这一个:以前还附带"账号也找不到",于是 Hub 里改了账号的人
|
||
会被判成离职、连带他的待办和权限一起停掉。现在账号只是普通字段,不参与身份判定。
|
||
没有主键的 ``source=hub`` 账号(历史遗留)不做离职判定,只报数量让人去补绑。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
rows = db.execute(
|
||
select(models.User).where(models.User.source == models.AccountSource.HUB)
|
||
).scalars().all()
|
||
for row in rows:
|
||
if not row.hub_user_id:
|
||
stats.unbound += 1
|
||
continue
|
||
if int(row.hub_user_id) in seen_ids:
|
||
continue
|
||
if cfg.hub_sync_protect_admins and row.role == models.ROLE_ADMIN:
|
||
stats.protected += 1
|
||
continue
|
||
row.hub_synced_at = now
|
||
if row.status == models.UserStatus.DISABLED:
|
||
continue
|
||
row.status = models.UserStatus.DISABLED
|
||
stats.offboarded += 1
|
||
if stats.offboarded:
|
||
stats.note(
|
||
f"{stats.offboarded} 人没出现在 Hub 清单里,本地已置停用(只停用不删行,待办与审批轨迹都在)。"
|
||
"注意 Hub 的目录接口不下发已停用人员:在 Hub 被停用的人也会表现为「不在清单里」,"
|
||
"所以这一条同时覆盖 Hub 侧的停用;Hub 重新启用后下一趟同步会自动恢复"
|
||
)
|
||
if stats.unbound:
|
||
stats.note(
|
||
f"{stats.unbound} 个标成统一身份却没有 Hub 主键的账号本次没做离职判定,"
|
||
"请在人员页补绑或改回本地账号"
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 主流程
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def sync_users(
|
||
db: Session,
|
||
*,
|
||
trigger: str = models.HubSyncRun.TRIGGER_SCHEDULE,
|
||
operator: str = "",
|
||
operator_name: str = "",
|
||
) -> dict[str, Any]:
|
||
"""拉一次 Hub 全量并落库,返回这次同步的汇总。"""
|
||
cfg = hubconfig.get()
|
||
manual = trigger == models.HubSyncRun.TRIGGER_MANUAL
|
||
if not cfg.hub_enabled or not cfg.hub_base_url:
|
||
raise HubSyncError("未启用统一身份认证,请检查 OA_HUB_ENABLED / OA_HUB_BASE_URL")
|
||
if not cfg.hub_sync_enabled and not manual:
|
||
raise HubSyncError("定时同步已关闭,请到「系统设置 → 同步定时任务」打开「允许定时同步」")
|
||
lock_token = _acquire_sync_locks()
|
||
|
||
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
|
||
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)
|
||
|
||
seen_ids = _sync_people(db, hub_users, unit_map, stats, datetime.now())
|
||
_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 = models.HubSyncRun.STATUS_PARTIAL if stats.truncated else models.HubSyncRun.STATUS_SUCCESS
|
||
_finish(db, run_id, stats, status, ";".join(stats.messages))
|
||
return {"run": serialize_run(latest_run(db) or run), "skipped": False}
|
||
except 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.message = (message or "")[:2000]
|
||
if state_patch is not None:
|
||
# 增量轮询只更新自己的那几个键,不碰 permission_version / total_users,
|
||
# 否则会把上一次全量的版本号称成 0,害得夜间全量误判成"版本变了"。
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
if row is None:
|
||
row = models.SystemSetting(key=STATE_KEY, value={}, description="Hub 组织人员同步状态")
|
||
db.add(row)
|
||
row.value = {**(row.value or {}), **state_patch}
|
||
if state_patch is None and status in (models.HubSyncRun.STATUS_SUCCESS, models.HubSyncRun.STATUS_PARTIAL):
|
||
row = db.get(models.SystemSetting, STATE_KEY)
|
||
if row is None:
|
||
row = models.SystemSetting(key=STATE_KEY, value={}, description="Hub 组织人员同步状态")
|
||
db.add(row)
|
||
row.value = {
|
||
**(row.value or {}),
|
||
"permission_version": stats.permission_version,
|
||
"total_users": stats.total_users,
|
||
"last_sync_at": now.strftime("%Y-%m-%d %H:%M:%S"),
|
||
"last_status": status,
|
||
}
|
||
db.commit()
|
||
logger.info(
|
||
"Hub 同步 %s(%s,凭证 %s):人员 新增%d/更新%d/停用%d,"
|
||
"部门 新增%d/更新%d/停用%d,版本 %s,member_limit %s%s",
|
||
status,
|
||
stats.total_users,
|
||
stats.credential,
|
||
stats.created,
|
||
stats.updated,
|
||
stats.offboarded,
|
||
stats.units_created,
|
||
stats.units_updated,
|
||
stats.units_offboarded,
|
||
stats.permission_version,
|
||
stats.member_limit,
|
||
"(已截断)" if stats.truncated else "",
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 增量同步(变更流水,文档 6.2 / 6.3)
|
||
# ---------------------------------------------------------------------------
|
||
|
||
#: 单趟最多翻多少批(每批 ``hub_sync.changes.limit`` 条);``has_more`` 抽风时给线程兜个底
|
||
MAX_CHANGE_ROUNDS = 100
|
||
|
||
#: 一条变更的处理结论
|
||
APPLIED = "applied" # 已经落到本地
|
||
IGNORED = "ignored" # 与本地无关(不认识的人/部门、payload 里没有可用字段)
|
||
NEEDS_FULL = "needs_full" # 光凭这一条推不出正确结果,要回全量重对齐
|
||
|
||
EVENT_USER = "user"
|
||
EVENT_ORGANIZATION = "organization"
|
||
OP_DELETE = "delete"
|
||
|
||
|
||
def _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`` 表示从没对齐过,第一步必须先走全量(文档 6.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``(文档 6.4 明说了这个坑),``entity_id`` 才是稳定那个,
|
||
所以文档 6.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``**(管理员删除用户):本地按主键软删——停用 + 吊销刷新令牌,
|
||
单据与流程历史原样留着(文档 6.3 第 4 条:``delete`` 按主键软删除)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
data = event.get("data") if isinstance(event.get("data"), dict) else {}
|
||
op = str(event.get("op") or "").strip().lower()
|
||
hub_user_id = _event_id(event, data)
|
||
if not hub_user_id:
|
||
stats.changes_skipped += 1
|
||
stats.note("有一条人员变更没带主键,已跳过,等夜间全量校对")
|
||
return IGNORED
|
||
|
||
person = _person_by_hub_id(db, int(hub_user_id))
|
||
|
||
if op == OP_DELETE:
|
||
if person is None:
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
if is_emergency_account(person.account) or _protect_from_hub(cfg, person):
|
||
stats.protected += 1
|
||
stats.note(f"{person.account} 是本地应急/受保护账号,Hub 的删除事件没有停用它")
|
||
return IGNORED
|
||
db.execute(delete(models.RefreshToken).where(models.RefreshToken.person == str(person.id)))
|
||
if person.status != models.UserStatus.DISABLED:
|
||
person.status = models.UserStatus.DISABLED
|
||
stats.offboarded += 1
|
||
return APPLIED
|
||
|
||
account = str(data.get("account") or "").strip()
|
||
if account:
|
||
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]
|
||
_sync_people(db, [person_payload], unit_map, stats, now)
|
||
return APPLIED
|
||
|
||
if person is None:
|
||
# 补丁指的人本地还没有:多半是这条事件比我们的游标还早、而全量里也没这个人,
|
||
# 为它重拉整棵目录不划算,夜间全量校对会兜住。
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
if is_emergency_account(person.account) or _protect_from_hub(cfg, person):
|
||
stats.protected += 1
|
||
return IGNORED
|
||
|
||
# 号码先落这一列,但**不在这里短路**: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 与手机号走的是同一类补丁:先落列、同样不在这里短路。
|
||
wecom_changed = _apply_wecom_user_id(db, person, data, None, stats)
|
||
|
||
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``,层级由随后那趟全量刷准(文档 6.4:禁止靠增量 payload 推导父子)。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
hub_id = models.as_id(node.get("organization_id")) or models.as_id(node.get("id"))
|
||
code = models.clip(str(node.get("code") or "").strip(), 190)
|
||
if not hub_id or int(hub_id) <= 0 or code == UNASSIGNED:
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
hub_id = int(hub_id)
|
||
name = models.clip(str(node.get("name") or "").strip(), 255) or f"组织{hub_id}"
|
||
status = models.UnitStatus.normalize(models.as_id(node.get("status")))
|
||
parent_hub_id = models.as_id(node.get("parent_id")) or 0
|
||
parent = mapped.get(parent_hub_id) if parent_hub_id else None
|
||
needs_full = bool(parent_hub_id and parent is None and parent_hub_id != hub_id)
|
||
if needs_full:
|
||
stats.note(f"Hub 组织 {hub_id} 的上级 {parent_hub_id} 本地还没有,先落节点,层级由全量重对齐")
|
||
|
||
unit = mapped.get(hub_id)
|
||
claimed = False
|
||
if unit is None:
|
||
candidates = [row for row in _local_units_by_code(db).get(code, [])] if code else []
|
||
if len(candidates) == 1 and cfg.hub_sync_bind_local_by_code:
|
||
unit = candidates[0]
|
||
claimed = True
|
||
elif len(candidates) > 1:
|
||
stats.note(f"本地有 {len(candidates)} 个部门都用编码 {code},认领不了,按新部门建")
|
||
|
||
if unit is None:
|
||
unit = models.Unit(
|
||
name=name,
|
||
code=code,
|
||
alias=code,
|
||
description="由统一身份同步创建",
|
||
parent_id=parent.id if parent else None,
|
||
hub_org_id=hub_id,
|
||
status=status,
|
||
)
|
||
db.add(unit)
|
||
db.flush()
|
||
mapped[hub_id] = unit
|
||
stats.units_created += 1
|
||
else:
|
||
parent_id = parent.id if parent else unit.parent_id
|
||
changed = (
|
||
unit.name != name
|
||
or unit.parent_id != parent_id
|
||
or unit.status != status
|
||
or bool(code and unit.code != code)
|
||
)
|
||
if changed:
|
||
_record_pair(stats.unit_name_map, unit.name, name)
|
||
unit.name = name
|
||
unit.parent_id = parent_id
|
||
unit.status = status
|
||
if code:
|
||
unit.code = code
|
||
if claimed:
|
||
stats.units_bound += 1
|
||
else:
|
||
stats.units_updated += 1
|
||
mapped[hub_id] = unit
|
||
|
||
_refresh_paths(db, unit, parent, stats)
|
||
return NEEDS_FULL if needs_full else APPLIED
|
||
|
||
|
||
def _apply_org_event(
|
||
db: Session, event: dict[str, Any], stats: SyncStats, org_map: dict[int, models.Unit]
|
||
) -> str:
|
||
"""落一条组织变更。
|
||
|
||
文档 6.4 说得很直白:状态与移动事件只带 ``id`` 加一个字段,不带 ``path``,组织停用也
|
||
不会给子孙逐个发事件,**收到这类事件应当回头拉全量**。所以这里:
|
||
|
||
* 完整组织对象(带 ``name``)→ 落这一个节点;
|
||
* 只带 ``status`` 的补丁 → 本节点状态照抄(子树留全量判),并要求回全量;
|
||
* 只带 ``parent_id`` 的补丁 → 一个字段都不动,直接要求回全量(没 ``path`` 就挪不准);
|
||
* ``delete`` → 本地按主键停用(软删,留着壳子等 Hub 加回来)。
|
||
"""
|
||
data = event.get("data") if isinstance(event.get("data"), dict) else {}
|
||
op = str(event.get("op") or "").strip().lower()
|
||
hub_org_id = _event_id(event, data)
|
||
if not hub_org_id:
|
||
stats.changes_skipped += 1
|
||
stats.note("有一条组织变更没带主键,已跳过,等夜间全量校对")
|
||
return IGNORED
|
||
|
||
unit = org_map.get(int(hub_org_id))
|
||
|
||
if op == OP_DELETE:
|
||
if unit is None:
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
if unit.status != models.UnitStatus.DISABLED:
|
||
unit.status = models.UnitStatus.DISABLED
|
||
stats.units_offboarded += 1
|
||
stats.note(f"Hub 删除了组织 {hub_org_id},本地部门 {unit.name} 已停用(部门本身保留)")
|
||
return APPLIED
|
||
|
||
if str(data.get("name") or "").strip():
|
||
return _upsert_single_unit(db, data, stats, org_map)
|
||
|
||
if "parent_id" in data:
|
||
stats.note(
|
||
f"Hub 组织 {hub_org_id} 挪了上级,增量事件不带 path,推不出新层级,改拉一次全量"
|
||
)
|
||
return NEEDS_FULL
|
||
|
||
if "status" in data:
|
||
new_status = models.UnitStatus.normalize(models.as_id(data.get("status")))
|
||
if unit is not None and unit.status != new_status:
|
||
unit.status = new_status
|
||
stats.units_updated += 1
|
||
if new_status != models.UnitStatus.ACTIVE:
|
||
stats.note(
|
||
f"Hub 组织 {hub_org_id} 被停用:整棵子树的可达性以下一趟全量为准"
|
||
"(Hub 不会给子孙逐个发事件)"
|
||
)
|
||
return NEEDS_FULL
|
||
return APPLIED
|
||
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
|
||
|
||
def _apply_event(
|
||
db: Session,
|
||
event: Any,
|
||
stats: SyncStats,
|
||
now: datetime,
|
||
unit_map: dict[int, int],
|
||
org_map: dict[int, models.Unit],
|
||
) -> str:
|
||
if not isinstance(event, dict):
|
||
stats.changes_skipped += 1
|
||
return IGNORED
|
||
entity = str(event.get("entity") or "").strip().lower()
|
||
if entity == EVENT_USER:
|
||
return _apply_user_event(db, event, stats, now, unit_map)
|
||
if entity == EVENT_ORGANIZATION:
|
||
return _apply_org_event(db, event, stats, org_map)
|
||
stats.changes_skipped += 1
|
||
stats.note(f"变更流水里出现了不认识的实体类型 {entity or '(空)'},已跳过")
|
||
return IGNORED
|
||
|
||
|
||
def _probe_newest_seq(hub_client: hub_api.HubClient, token: str) -> int:
|
||
"""探一下 Hub 流水的最新 ``seq``:首次全量之后从这里开始追(文档 6.3 第 1 步)。"""
|
||
payload = hub_client.directory_changes(0, limit=1, token=token)
|
||
return models.as_id(payload.get("newest_seq")) or 0
|
||
|
||
|
||
def _pull_changes(
|
||
db: Session,
|
||
*,
|
||
operator: str = "",
|
||
operator_name: str = "",
|
||
manual: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""按游标把变更流水拉干净并落库;需要回全量时不写游标,交给 :func:`sync_changes` 收尾。"""
|
||
cfg = hubconfig.get()
|
||
if not cfg.sync_allowed:
|
||
raise HubSyncError("未启用统一身份认证,请检查 hub_enabled / hub_base_url")
|
||
if not cfg.hub_sync_changes_enabled and not manual:
|
||
raise HubSyncError("增量同步已关闭(hub_sync.changes.enabled = false)")
|
||
lock_token = _acquire_sync_locks()
|
||
|
||
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)
|
||
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 表示"一条都没见过",这时最老的流水就是能拿到的第一条,不算缺口;
|
||
# 真正的缺口是"取过一些、但那批已经被裁剪"(文档 6.2:必须回到全量)。
|
||
if oldest and int(cursor) > 0 and int(cursor) < oldest:
|
||
needs_full = True
|
||
stats.note(
|
||
f"本地游标 {cursor} 比 Hub 侧最老的流水 {oldest} 还旧,"
|
||
"中间那段已经取不回来,改拉一次全量重对齐"
|
||
)
|
||
else:
|
||
# 每批现取一次映射:同批的组织事件可能刚建新部门,后面的人员事件要用到
|
||
org_map = _hub_units(db, stats)
|
||
unit_map = {hub_id: unit.id for hub_id, unit in org_map.items()}
|
||
for event in batch:
|
||
outcome = _apply_event(db, event, stats, datetime.now(), unit_map, org_map)
|
||
if outcome == APPLIED:
|
||
stats.changes_applied += 1
|
||
elif outcome == NEEDS_FULL:
|
||
needs_full = True
|
||
break
|
||
previous_cursor = int(cursor)
|
||
if batch_cursor is not None:
|
||
cursor = int(batch_cursor)
|
||
elif batch:
|
||
cursor = max(int(row.get("seq") or 0) for row in batch)
|
||
stats.cursor_seq = int(cursor)
|
||
|
||
if needs_full:
|
||
break
|
||
db.commit()
|
||
committed_applied = stats.changes_applied
|
||
if not payload.get("has_more"):
|
||
break
|
||
if int(cursor) <= previous_cursor:
|
||
# Hub 说还有、但游标一步没动:再多翻几轮也只是原地打转,停手等下一趟
|
||
stats.note("Hub 返回 has_more=true 但游标没有前进,本轮到此为止,下一趟接着拉")
|
||
break
|
||
|
||
# 游标只有在"这批落干净了"或"明知补不回来、决定跳过"时才往前推;
|
||
# 要回全量的那一批先丢掉,等全量盖完由 sync_changes 推游标。
|
||
give_up = needs_full and not cfg.hub_sync_changes_full_on_gap
|
||
if needs_full and cfg.hub_sync_changes_full_on_gap:
|
||
db.rollback()
|
||
stats.changes_applied = committed_applied
|
||
patch = {
|
||
"changes_newest_seq": int(newest or 0),
|
||
"changes_error": "",
|
||
"changes_error_at": "",
|
||
}
|
||
if not needs_full or give_up:
|
||
patch["changes_cursor"] = int(cursor or 0)
|
||
patch["changes_applied_total"] = (
|
||
int(state(db).get("changes_applied_total") or 0) + stats.changes_applied
|
||
)
|
||
_finish(
|
||
db,
|
||
run_id,
|
||
stats,
|
||
models.HubSyncRun.STATUS_SUCCESS,
|
||
";".join(stats.messages),
|
||
state_patch=patch,
|
||
)
|
||
return {
|
||
"run": serialize_run(latest_run(db) or run),
|
||
"cursor": int(cursor or 0),
|
||
"applied": stats.changes_applied,
|
||
"skipped": stats.changes_skipped,
|
||
"needs_full": bool(needs_full),
|
||
"bootstrap": bootstrap,
|
||
"rounds": rounds,
|
||
"messages": stats.messages,
|
||
}
|
||
except 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]:
|
||
"""增量同步一趟:拉变更流水落库,必要时改拉一次全量重对齐(文档 6.3 第 2、3 步)。
|
||
|
||
游标只在"这批真的处理干净"之后才提交(``has_more=false``),中途失败下次从原地重拉。
|
||
需要回全量时(首次对齐、流水缺口、只带 ``id`` 的组织层级事件、本地没镜像到的部门),
|
||
先释放同步锁再跑 :func:`sync_users`,全量落成功才把游标推上去——全量失败就留在原地,
|
||
下一轮重试,绝不会出现"流水没落库但游标已经跑掉"。
|
||
"""
|
||
cfg = hubconfig.get()
|
||
result = _pull_changes(db, operator=operator, operator_name=operator_name, manual=manual)
|
||
if not result.get("needs_full"):
|
||
return {**result, "full_resync": False}
|
||
|
||
if not cfg.hub_sync_changes_full_on_gap:
|
||
result["full_resync"] = False
|
||
result["messages"] = [
|
||
*result.get("messages", []),
|
||
"已关闭「落后过多就回全量」:推不出的那几条只记日志,游标照常往前推,差异等夜间全量校对补齐",
|
||
]
|
||
return result
|
||
|
||
try:
|
||
full = sync_users(
|
||
db,
|
||
trigger=models.HubSyncRun.TRIGGER_SCHEDULE,
|
||
operator=operator or "hub-changes",
|
||
operator_name=operator_name or "增量同步触发的全量",
|
||
)
|
||
result["full_resync"] = True
|
||
result["full_run"] = full.get("run")
|
||
set_state(db, {"changes_cursor": int(result.get("cursor") or 0)})
|
||
except HubSyncError as exc:
|
||
result["full_resync"] = False
|
||
result["full_error"] = str(exc)
|
||
result["messages"] = [*result.get("messages", []), f"需要回全量重对齐,但全量没跑成:{exc}"]
|
||
return result
|
||
|
||
|
||
def changes_due(
|
||
db: Session, now: datetime | None = None, 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)
|
||
|
||
# 手机号预检:界面要能回答"同步完手机上会有号码吗"——取决于 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
|
||
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.hub_user_id:
|
||
# 账号已经代表 Hub 里的另一个人了,同步会跳过,不会把两个人并起来
|
||
conflicts += 1
|
||
elif is_emergency_account(holder.account) or _protect_from_hub(cfg, holder):
|
||
protected += 1
|
||
else:
|
||
adopted += 1
|
||
|
||
offboard_candidates = [
|
||
row.account
|
||
for row in hub_source
|
||
if row.hub_user_id
|
||
and int(row.hub_user_id) not in seen_ids
|
||
and not (cfg.hub_sync_protect_admins and row.role == models.ROLE_ADMIN)
|
||
]
|
||
unbound = len([row for row in hub_source if not row.hub_user_id])
|
||
|
||
# 影响预检:Hub 一改名字就会牵动的"按字符串存的"配置(审批岗位、共享名单…)。
|
||
# 权限角色与数据范围是按 users.id / oa_unit.id 挂的,同步不动主键,所以不在这里出现。
|
||
refs_total, refs_samples = hub_refs.scan(
|
||
db,
|
||
hub_refs.build_maps(
|
||
unit_name_map=unit_name_map,
|
||
display_name_map=person_name_map,
|
||
account_map=account_map,
|
||
),
|
||
)
|
||
|
||
return {
|
||
"credential": mode,
|
||
"credential_label": credential_label(mode),
|
||
"permission_version": models.as_id(payload.get("permission_version")) or 0,
|
||
"total_users": models.as_id(payload.get("total_users")) or 0,
|
||
"returned_users": models.as_id(payload.get("returned_users")) or len(hub_users),
|
||
"member_limit": models.as_id(payload.get("member_limit")) or limit,
|
||
"truncated": truncated,
|
||
"organizations": {
|
||
"total": len(orgs),
|
||
"new": len(org_ids - set(known_units)) - claimable,
|
||
"known": len(org_ids & set(known_units)),
|
||
"disabled": len([row for row in orgs if row["status"] != models.UnitStatus.ACTIVE]),
|
||
"offboard_candidates": len(set(known_units) - org_ids),
|
||
"renamed": renamed_units,
|
||
"moved": moved_units,
|
||
# 本系统自己加的部门:同步不碰它们,只报规模与风险
|
||
"local_units": len(local_units),
|
||
"claimable_by_code": claimable,
|
||
"local_hanging_units": hanging_units,
|
||
},
|
||
"users": {
|
||
"new": new_people,
|
||
"adopt_candidates": adopted,
|
||
"inactive": inactive,
|
||
"unassigned": unassigned,
|
||
"protected_admins": protected,
|
||
"offboard_candidates": len(offboard_candidates),
|
||
"no_hub_id": no_id,
|
||
"account_conflicts": conflicts,
|
||
"account_renames": len(account_map),
|
||
"name_renames": len(person_name_map),
|
||
"unbound": unbound,
|
||
# 号码来源看清了再决定要不要动本地这一列: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": (
|
||
f"人员清单被 member_limit={limit} 截断,本次数字只能当规模参考,"
|
||
"正式同步前先调大 OA_HUB_SYNC_MEMBER_LIMIT"
|
||
if truncated
|
||
else ""
|
||
),
|
||
}
|
||
|
||
|
||
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
|
||
|
||
# 门户可见性(文档 3.1):应用注册了、密钥也对,但应用没启用、或这个账号没命中任何
|
||
# 授权角色时,门户里压根没有这张卡片 —— 用户那边只会说"我进不去 OA"。
|
||
apps_path = cfg.hub_path_apps
|
||
if not cfg.sso_on:
|
||
steps.append({"name": f"门户可见性 {apps_path}", "ok": True, "detail": "免登没开或已被总闸关掉,跳过"})
|
||
elif not token:
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": True,
|
||
"detail": f"当前凭证是{credential_label(mode)},没有可用的用户令牌可问,跳过",
|
||
}
|
||
)
|
||
else:
|
||
try:
|
||
wanted = cfg.hub_app_code.strip().lower()
|
||
hit = next(
|
||
(
|
||
row
|
||
for row in hub_api.client().apps(token)
|
||
if str(row.get("code") or "").strip().lower() == wanted
|
||
),
|
||
None,
|
||
)
|
||
if hit is None:
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": False,
|
||
"detail": (
|
||
f"可见应用列表里没有 {cfg.hub_app_code}:应用未注册、已停用,"
|
||
"或这个账号没命中应用的任何授权角色"
|
||
),
|
||
}
|
||
)
|
||
ok = False
|
||
elif str(hit.get("status")) != "1" or str(hit.get("visible")) != "1":
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": False,
|
||
"detail": (
|
||
f"应用在门户里看不到:status={hit.get('status')}、visible={hit.get('visible')},"
|
||
"请在 Hub 管理端启用并设为可见"
|
||
),
|
||
}
|
||
)
|
||
ok = False
|
||
else:
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": True,
|
||
"detail": (
|
||
f"门户里能看到「{hit.get('name') or cfg.hub_app_code}」"
|
||
f"(sso_mode={hit.get('sso_mode') or 'ticket'})"
|
||
),
|
||
}
|
||
)
|
||
except hub_api.HubError as exc:
|
||
# 这一项查不通不该把整次自检判死:有的 Hub 没开这个接口,或只给了目录密钥
|
||
steps.append(
|
||
{
|
||
"name": f"门户可见性 {apps_path}",
|
||
"ok": True,
|
||
"detail": f"没能问到可见应用列表({exc.message}),不影响免登本身",
|
||
}
|
||
)
|
||
|
||
if not cfg.hub_sync_changes_enabled:
|
||
steps.append(
|
||
{
|
||
"name": f"变更流水接口 {cfg.hub_path_directory_changes}",
|
||
"ok": True,
|
||
"detail": "增量同步已关闭,跳过(只剩夜间全量与界面上的立即同步)",
|
||
}
|
||
)
|
||
else:
|
||
try:
|
||
token_for_changes, _mode = hub_api.sync_token(hub_client)
|
||
changes_probe = hub_client.directory_changes(0, limit=1, token=token_for_changes)
|
||
steps.append(
|
||
{
|
||
"name": f"变更流水接口 {cfg.hub_path_directory_changes}",
|
||
"ok": True,
|
||
"detail": (
|
||
f"最新流水 seq {models.as_id(changes_probe.get('newest_seq')) or 0},"
|
||
f"最老可取 seq {models.as_id(changes_probe.get('oldest_seq')) or 0}"
|
||
+ (
|
||
f";本地游标 {changes_cursor(db)}"
|
||
if db is not None and changes_cursor(db) is not None
|
||
else ""
|
||
)
|
||
),
|
||
}
|
||
)
|
||
except hub_api.HubError as exc:
|
||
steps.append(
|
||
{"name": f"变更流水接口 {cfg.hub_path_directory_changes}", "ok": False, "detail": exc.message}
|
||
)
|
||
ok = False
|
||
|
||
# 权限那一层(《Hub 权限接口交互文档》):角色/权限码/数据范围问不问得到、目录对不对得上。
|
||
# 只有"生效模式"下问不到才算整次自检不合格;对照模式下问不到只报问题,不判死。
|
||
permission_steps = hub_perm.probe_steps(token)
|
||
steps.extend(permission_steps)
|
||
ok = ok and all(bool(row.get("ok")) for row in permission_steps)
|
||
|
||
return {
|
||
"ok": ok,
|
||
"base_url": cfg.hub_base_url,
|
||
# 当前用的五个接口路径,排障时一眼看出打的是哪儿
|
||
"api_paths": cfg.api_paths,
|
||
"login_enabled": cfg.login_on,
|
||
"credential": mode,
|
||
"credential_label": credential_label(mode),
|
||
"directory_key_set": bool(cfg.hub_directory_key),
|
||
"directory_needs_token": cfg.hub_directory_needs_token,
|
||
"sso": sso_status(),
|
||
"permission": hub_perm.status_payload(),
|
||
"member_limit": member_limit,
|
||
"steps": steps,
|
||
"message": "统一身份认证服务连通正常" if ok else "统一身份认证服务检查未通过,详见各项说明",
|
||
}
|