WIP-CHECKPOINT[auth-refactor]: 固化工程师崩溃前部分成果 + 同树其他未提交WIP(仅源码,不含密钥/二进制)-- 待重激活工程师续作
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
# =============================================================================
|
||||
# 企微IT智能服务台 — 阶段5 自动化 外部客户端基类
|
||||
# =============================================================================
|
||||
# 说明:提供异步 HTTP 客户端通用能力:
|
||||
# 1. 超时控制(连接/读取分开)
|
||||
# 2. 重试(tenacity:指数退避 + 抖动,仅重试超时/5xx,4xx 不重试)
|
||||
# 3. 审计钩子(出入参记录到 ActionLog,由调用方注入回调)
|
||||
#
|
||||
# 所有外部客户端(Dify / EHR / 未来 aTrust)均继承此类,
|
||||
# 保证超时、重试、审计行为在全项目一致,且方法签名完整、异常可捕获、
|
||||
# 出入参可被 ActionLog 记录(满足架构审计要求)。
|
||||
# =============================================================================
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Awaitable, Callable, Dict, Optional
|
||||
|
||||
import httpx
|
||||
from tenacity import (
|
||||
AsyncRetrying,
|
||||
retry_if_exception_type,
|
||||
stop_after_attempt,
|
||||
wait_exponential_jitter,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 默认超时(秒)
|
||||
DEFAULT_CONNECT_TIMEOUT = 5.0
|
||||
DEFAULT_READ_TIMEOUT = 20.0
|
||||
# 默认重试次数
|
||||
DEFAULT_MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class BaseClientError(Exception):
|
||||
"""外部客户端通用异常(可被自动化引擎捕获并转人工)。"""
|
||||
|
||||
def __init__(self, message: str, code: int = -1, detail: str = ""):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.detail = detail
|
||||
|
||||
|
||||
class BaseClient:
|
||||
"""异步外部客户端基类。
|
||||
|
||||
Attributes:
|
||||
base_url: 外部系统基址(不含尾部斜杠)
|
||||
timeout: httpx 超时配置
|
||||
_audit: 审计回调(可选),签名
|
||||
async (event, direction, system, request, response, status, latency_ms, error)
|
||||
"""
|
||||
|
||||
# 子类声明系统标识,用于审计与日志
|
||||
system_name: str = "external"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
timeout: Optional[float] = None,
|
||||
audit: Optional[Callable[..., Awaitable[None]]] = None,
|
||||
):
|
||||
self.base_url = (base_url or "").rstrip("/")
|
||||
read = timeout or DEFAULT_READ_TIMEOUT
|
||||
self.timeout = httpx.Timeout(connect=DEFAULT_CONNECT_TIMEOUT, read=read)
|
||||
self._audit = audit
|
||||
|
||||
async def _emit_audit(
|
||||
self,
|
||||
event: str,
|
||||
direction: str,
|
||||
request: Any = None,
|
||||
response: Any = None,
|
||||
status: str = "",
|
||||
latency_ms: Optional[int] = None,
|
||||
error: str = "",
|
||||
) -> None:
|
||||
"""审计钩子:记录出入参(落 ActionLog)。
|
||||
|
||||
为什么单独成方法:审计失败绝不影响主流程(仅记 warning),
|
||||
避免外部审计系统抖动拖累自动化处置。
|
||||
"""
|
||||
if self._audit is None:
|
||||
return
|
||||
try:
|
||||
await self._audit(
|
||||
event=event,
|
||||
direction=direction,
|
||||
system=self.system_name,
|
||||
request=request,
|
||||
response=response,
|
||||
status=status,
|
||||
latency_ms=latency_ms,
|
||||
error=error,
|
||||
)
|
||||
except Exception as e: # 审计失败不影响主流程
|
||||
logger.warning(f"[{self.system_name}] 审计钩子执行失败: {e}")
|
||||
|
||||
async def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
json_data: Optional[Dict] = None,
|
||||
params: Optional[Dict] = None,
|
||||
headers: Optional[Dict] = None,
|
||||
event: str = "",
|
||||
retry: bool = True,
|
||||
) -> Dict[str, Any]:
|
||||
"""统一请求封装(带超时 + 重试 + 审计)。
|
||||
|
||||
Args:
|
||||
method: HTTP 方法
|
||||
path: 路径(自动拼接 base_url)
|
||||
json_data/params/headers: 请求参数
|
||||
event: 审计事件名(如 "dify.intent")
|
||||
retry: 是否启用重试(仅对超时/5xx 重试,4xx 不重试)
|
||||
|
||||
Returns:
|
||||
Dict: 解析后的 JSON 响应
|
||||
|
||||
Raises:
|
||||
BaseClientError: 网络/HTTP/业务错误
|
||||
"""
|
||||
url = f"{self.base_url}{path}"
|
||||
start = time.monotonic()
|
||||
|
||||
async def _do() -> httpx.Response:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
return await client.request(
|
||||
method, url, json=json_data, params=params, headers=headers
|
||||
)
|
||||
|
||||
try:
|
||||
if retry:
|
||||
resp: Optional[httpx.Response] = None
|
||||
async for attempt in AsyncRetrying(
|
||||
stop=stop_after_attempt(DEFAULT_MAX_ATTEMPTS),
|
||||
wait=wait_exponential_jitter(initial=0.5, max=3.0),
|
||||
retry=retry_if_exception_type(
|
||||
(httpx.TimeoutException, httpx.ConnectError, httpx.HTTPStatusError)
|
||||
),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
resp = await _do()
|
||||
# 4xx 是业务错误,不重试
|
||||
if resp.status_code >= 400 and resp.status_code < 500:
|
||||
raise httpx.HTTPStatusError(
|
||||
message=f"HTTP {resp.status_code}",
|
||||
request=resp.request,
|
||||
response=resp,
|
||||
)
|
||||
assert resp is not None
|
||||
else:
|
||||
resp = await _do()
|
||||
|
||||
latency_ms = int((time.monotonic() - start) * 1000)
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
data = {"raw": resp.text}
|
||||
|
||||
status = "success" if resp.status_code < 400 else f"http_{resp.status_code}"
|
||||
await self._emit_audit(event, "out", json_data or params, data, status, latency_ms)
|
||||
if resp.status_code >= 400:
|
||||
raise BaseClientError(
|
||||
message=f"{self.system_name} 返回 HTTP {resp.status_code}",
|
||||
code=resp.status_code,
|
||||
detail=resp.text[:500],
|
||||
)
|
||||
return data
|
||||
except (httpx.TimeoutException, httpx.ConnectError) as e:
|
||||
latency_ms = int((time.monotonic() - start) * 1000)
|
||||
await self._emit_audit(event, "out", json_data or params, None, "error", latency_ms, str(e))
|
||||
raise BaseClientError(message=f"{self.system_name} 网络异常: {e}", code=-1, detail=str(e))
|
||||
except BaseClientError:
|
||||
raise
|
||||
except Exception as e:
|
||||
latency_ms = int((time.monotonic() - start) * 1000)
|
||||
await self._emit_audit(event, "out", json_data or params, None, "error", latency_ms, str(e))
|
||||
raise BaseClientError(message=f"{self.system_name} 请求异常: {e}", code=-1, detail=str(e))
|
||||
@@ -0,0 +1,140 @@
|
||||
# =============================================================================
|
||||
# 企微IT智能服务台 — 阶段5 自动化 Dify 客户端
|
||||
# =============================================================================
|
||||
# 说明:Dify 承担意图识别与 AI 编排。
|
||||
# 1. 意图识别:根据员工消息判断命中哪个自动化场景
|
||||
# (password_reset / software_install / virus_dispose / terminal_locate)
|
||||
# 2. AI 编排(可选):生成处置方案草案
|
||||
#
|
||||
# 认证:Dify 开放 API 使用 Bearer Token(API Key)。
|
||||
# 配置:AUTOMATION_DIFY_BASE_URL / AUTOMATION_DIFY_API_KEY(来自 settings)。
|
||||
#
|
||||
# 容错:若 Dify 未配置或无结构化输出,detect_intent 走关键词兜底,
|
||||
# 保证 P0 四个场景在无真实 Dify 环境下也能演示闭环。
|
||||
# =============================================================================
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from app.config import settings
|
||||
from app.integrations.base import BaseClient, BaseClientError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DifyClient(BaseClient):
|
||||
"""Dify API 客户端(意图识别 / AI 编排)。"""
|
||||
|
||||
system_name = "dify"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
api_key: str,
|
||||
base_url: str,
|
||||
timeout: Optional[float] = None,
|
||||
audit=None,
|
||||
):
|
||||
super().__init__(base_url=base_url, timeout=timeout, audit=audit)
|
||||
self.api_key = api_key
|
||||
|
||||
def _headers(self) -> Dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
async def chat_completions(
|
||||
self,
|
||||
query: str,
|
||||
user: str = "automation",
|
||||
conversation_id: str = "",
|
||||
response_mode: str = "blocking",
|
||||
) -> Dict[str, Any]:
|
||||
"""调用 Dify Chat 补全(兼容 OpenAI Chat Completions 格式)。
|
||||
|
||||
Returns:
|
||||
Dict: {"answer": str, "conversation_id": str, ...}
|
||||
"""
|
||||
body = {
|
||||
"inputs": {},
|
||||
"query": query,
|
||||
"user": user,
|
||||
"response_mode": response_mode,
|
||||
}
|
||||
if conversation_id:
|
||||
body["conversation_id"] = conversation_id
|
||||
return await self.request(
|
||||
"POST", "/v1/chat-messages",
|
||||
json_data=body, headers=self._headers(), event="dify.chat",
|
||||
)
|
||||
|
||||
async def detect_intent(self, message: str, employee_id: str = "") -> Dict[str, Any]:
|
||||
"""意图识别:把员工消息发给 Dify,期望返回结构化场景意图。
|
||||
|
||||
解析策略:
|
||||
1. 优先尝试从 answer 中解析 JSON(scenario_key + confidence)
|
||||
2. 失败则走关键词兜底(无 Dify 结构化输出时也能跑通 P0)
|
||||
|
||||
Returns:
|
||||
Dict: {"scenario_key": str|None, "confidence": float, "raw": str, "error": str}
|
||||
"""
|
||||
try:
|
||||
data = await self.chat_completions(query=message, user=employee_id or "automation")
|
||||
answer = data.get("answer", "")
|
||||
except BaseClientError as e:
|
||||
logger.warning(f"Dify 意图识别失败,转关键词兜底: {e}")
|
||||
fb = self._fallback_intent(message)
|
||||
fb["error"] = str(e)
|
||||
return fb
|
||||
|
||||
intent = self._parse_intent(answer)
|
||||
if intent["scenario_key"] is None:
|
||||
# 关键词兜底
|
||||
fb = self._fallback_intent(message)
|
||||
fb["raw"] = answer
|
||||
return fb
|
||||
return intent
|
||||
|
||||
@staticmethod
|
||||
def _parse_intent(answer: str) -> Dict[str, Any]:
|
||||
"""尝试从 Dify 返回中解析 JSON 意图。"""
|
||||
try:
|
||||
m = re.search(r"\{.*\}", answer, re.DOTALL)
|
||||
if m:
|
||||
obj = json.loads(m.group(0))
|
||||
return {
|
||||
"scenario_key": obj.get("scenario_key"),
|
||||
"confidence": float(obj.get("confidence", 0.0)),
|
||||
"raw": answer,
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
return {"scenario_key": None, "confidence": 0.0, "raw": answer}
|
||||
|
||||
@staticmethod
|
||||
def _fallback_intent(message: str) -> Dict[str, Any]:
|
||||
"""关键词兜底意图识别(无 Dify 结构化输出时使用)。"""
|
||||
text = (message or "").lower()
|
||||
rules = [
|
||||
(("密码", "重置", "password", "忘密码", "修改密码"), "password_reset"),
|
||||
(("安装", "软件", "install", "software", "wps", "office", "下载"), "software_install"),
|
||||
(("病毒", "杀毒", "virus", "勒索", "木马", "火绒", "huorong"), "virus_dispose"),
|
||||
(("定位", "终端", "电脑在哪", "locate", "terminal", "找电脑"), "terminal_locate"),
|
||||
]
|
||||
for keywords, key in rules:
|
||||
if any(k in text for k in keywords):
|
||||
return {"scenario_key": key, "confidence": 0.75, "raw": ""}
|
||||
return {"scenario_key": None, "confidence": 0.0, "raw": ""}
|
||||
|
||||
|
||||
async def get_dify_client(audit=None) -> Optional[DifyClient]:
|
||||
"""从 settings 构建 Dify 客户端;未配置返回 None。"""
|
||||
base_url = settings.automation_dify_base_url
|
||||
api_key = settings.automation_dify_api_key
|
||||
if not base_url or not api_key:
|
||||
return None
|
||||
return DifyClient(api_key=api_key, base_url=base_url, audit=audit)
|
||||
@@ -0,0 +1,76 @@
|
||||
# =============================================================================
|
||||
# 企微IT智能服务台 — 阶段5 自动化 北森 EHR 客户端(静态映射兜底)
|
||||
# =============================================================================
|
||||
# 说明:当联软(主映射源)无法解析员工→终端时,使用北森 EHR 提供的
|
||||
# 员工-部门-资产静态映射作为兜底。
|
||||
#
|
||||
# 认证:北森开放 API 通常使用 App Key + App Secret(Bearer 或签名)。
|
||||
# 此处用占位实现:AUTOMATION_EHR_BASE_URL / AUTOMATION_EHR_API_KEY。
|
||||
# 具体签名方式以真实环境文档为准,结构上可被单测 mock。
|
||||
#
|
||||
# 接口设计为占位骨架:方法签名完整、异常可捕获、出入参可被 ActionLog 记录,
|
||||
# 本地无真实密钥/环境时仅结构正确,可被单元测试 mock。
|
||||
# =============================================================================
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from app.config import settings
|
||||
from app.integrations.base import BaseClient, BaseClientError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EhrClient(BaseClient):
|
||||
"""北森 EHR 客户端(静态映射兜底)。"""
|
||||
|
||||
system_name = "ehr"
|
||||
|
||||
def __init__(self, api_key: str, base_url: str, timeout=None, audit=None):
|
||||
super().__init__(base_url=base_url, timeout=timeout, audit=audit)
|
||||
self.api_key = api_key
|
||||
|
||||
def _headers(self) -> Dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
async def get_employee_profile(self, employee_id: str) -> Dict[str, Any]:
|
||||
"""查询员工档案(部门、岗位、资产编号等),作为映射兜底。"""
|
||||
return await self.request(
|
||||
"GET",
|
||||
f"/api/v1/employees/{employee_id}",
|
||||
headers=self._headers(),
|
||||
event="ehr.get_employee_profile",
|
||||
)
|
||||
|
||||
async def get_terminal_by_employee(self, employee_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""根据员工查兜底终端信息。
|
||||
|
||||
北森通常只给资产编号/部门,真正的终端 IP 仍需联软;
|
||||
此处返回 hint(如 last_known_hostname / asset_no),供 mapping_resolver 合并。
|
||||
"""
|
||||
try:
|
||||
profile = await self.get_employee_profile(employee_id)
|
||||
return {
|
||||
"employee_id": employee_id,
|
||||
"department": profile.get("department", ""),
|
||||
"asset_no": profile.get("asset_no", ""),
|
||||
"terminal_hint": profile.get("last_known_hostname", ""),
|
||||
"source": "ehr",
|
||||
}
|
||||
except BaseClientError as e:
|
||||
logger.warning(f"EHR 映射兜底失败 employee={employee_id}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def get_ehr_client(audit=None) -> Optional[EhrClient]:
|
||||
"""从 settings 构建 EHR 客户端;未配置返回 None。"""
|
||||
base_url = settings.automation_ehr_base_url
|
||||
api_key = settings.automation_ehr_api_key
|
||||
if not base_url or not api_key:
|
||||
return None
|
||||
return EhrClient(api_key=api_key, base_url=base_url, audit=audit)
|
||||
@@ -0,0 +1,95 @@
|
||||
# =============================================================================
|
||||
# 企微IT智能服务台 — 阶段5 自动化 外部客户端工厂
|
||||
# =============================================================================
|
||||
# 说明:集中解析各外部系统的配置来源:
|
||||
# - 优先使用 settings 中的 AUTOMATION_* 环境变量(架构约定)
|
||||
# - 缺失时回退到既有 system_configs 表配置
|
||||
# (huorong/lianruan/ragflow 在 app/integrations/*/config.py 中已有 getter)
|
||||
#
|
||||
# 为什么有工厂:自动化引擎既能用新加的 AUTOMATION_* 配置,也能复用阶段1-4
|
||||
# 已落地的集成配置,避免重复维护两套配置源。
|
||||
# =============================================================================
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def build_huorong_client(
|
||||
db: AsyncSession, audit: Optional[Callable[..., Any]] = None
|
||||
):
|
||||
"""构建火绒客户端:settings 优先,否则 system_configs。"""
|
||||
from app.integrations.huorong.client import HuorongClient
|
||||
|
||||
if (
|
||||
settings.automation_huorong_base_url
|
||||
and settings.automation_huorong_access_key_id
|
||||
and settings.automation_huorong_access_key_secret
|
||||
):
|
||||
return HuorongClient(
|
||||
access_key_id=settings.automation_huorong_access_key_id,
|
||||
access_key_secret=settings.automation_huorong_access_key_secret,
|
||||
base_url=settings.automation_huorong_base_url,
|
||||
)
|
||||
from app.integrations.huorong.config import get_huorong_client
|
||||
|
||||
return await get_huorong_client(db)
|
||||
|
||||
|
||||
async def build_lianruan_client(
|
||||
db: AsyncSession, audit: Optional[Callable[..., Any]] = None
|
||||
):
|
||||
"""构建联软客户端:settings 优先,否则 system_configs。"""
|
||||
from app.integrations.lianruan.client import LianruanClient
|
||||
|
||||
if (
|
||||
settings.automation_lianruan_base_url
|
||||
and settings.automation_lianruan_api_account
|
||||
and settings.automation_lianruan_api_password
|
||||
):
|
||||
return LianruanClient(
|
||||
base_url=settings.automation_lianruan_base_url,
|
||||
api_account=settings.automation_lianruan_api_account,
|
||||
api_password=settings.automation_lianruan_api_password,
|
||||
validate_key=settings.automation_lianruan_validate_key,
|
||||
)
|
||||
from app.integrations.lianruan.config import get_lianruan_client
|
||||
|
||||
return await get_lianruan_client(db)
|
||||
|
||||
|
||||
async def build_ragflow_client(
|
||||
db: AsyncSession, audit: Optional[Callable[..., Any]] = None
|
||||
):
|
||||
"""构建 RAGFlow 客户端:settings 优先,否则 system_configs。"""
|
||||
from app.integrations.ragflow.client import RagflowClient
|
||||
|
||||
if settings.automation_ragflow_base_url and settings.automation_ragflow_api_key:
|
||||
return RagflowClient(
|
||||
api_key=settings.automation_ragflow_api_key,
|
||||
base_url=settings.automation_ragflow_base_url,
|
||||
)
|
||||
from app.integrations.ragflow.config import get_ragflow_client
|
||||
|
||||
return await get_ragflow_client(db)
|
||||
|
||||
|
||||
async def build_dify_client(audit: Optional[Callable[..., Any]] = None):
|
||||
"""构建 Dify 客户端(仅 settings)。"""
|
||||
from app.integrations.dify import get_dify_client
|
||||
|
||||
return await get_dify_client(audit=audit)
|
||||
|
||||
|
||||
async def build_ehr_client(audit: Optional[Callable[..., Any]] = None):
|
||||
"""构建 EHR 客户端(仅 settings)。"""
|
||||
from app.integrations.ehr import get_ehr_client
|
||||
|
||||
return await get_ehr_client(audit=audit)
|
||||
Reference in New Issue
Block a user