重构第2批:API 层加固 + 新增 service 层

api/__init__.py:
- EkbClient.get/post 捕获 HTTP 错误,转换为 AuthenticationError /
  ApiResponseError;识别快报 errorCode=401 结构
- get_client() 改为抛出 NotLoggedInError(原为 RuntimeError)
- 新增 close() 方法便于非 with 场景使用

新增 services/ 目录(业务逻辑层):
- auth_service.py:企业认证配置的增删查改,返回 CorpInfo dataclass
- agent_service.py:Agent CRUD + copy + 高阶组合查询 get_dedup_rules_across_agents
  AgentCreateInput / AgentUpdateInput dataclass 统一输入结构
- rule_service.py:Rule 查询(支持按编码/ID 查找)+ CRUD
- __init__.py:统一 re-export,上层只从此处导入
This commit is contained in:
gitea committed 2026-04-14 11:06:06 +08:00
1 parent 4faba77234
commit 475ce518f9
5 files changed
+491 -10

No files matched your search

+41 -10
View File
@@ -1,8 +1,17 @@
"""HTTP 客户端:封装对快报 API 的请求,使用 accesstoken + corpid + staffid 认证"""
"""HTTP 客户端:封装对快报 API 的请求,使用 accesstoken + corpid + staffid 认证
异常约定:
- HTTP 401 → AuthenticationError
- HTTP 其他非 2xx → ApiResponseError
- 快报业务码非 200 → ApiResponseError
- 未登录(无配置)→ NotLoggedInError
"""
import httpx
from typing import Any
from ekb_cli.errors import AuthenticationError, ApiResponseError, NotLoggedInError
BASE_URL = "https://app.ekuaibao.com"
@@ -25,15 +34,34 @@ class EkbClient:
def get(self, path: str, **params) -> Any:
params["corpId"] = self.corp_id
resp = self._client.get(f"/api{path}", params=params)
resp.raise_for_status()
return resp.json()
try:
resp = self._client.get(f"/api{path}", params=params)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
data = resp.json()
# 快报 errorCode 结构(未登录等场景)
if isinstance(data, dict) and data.get("errorCode") == 401:
raise AuthenticationError(data.get("errorMessage", "认证失败"))
return data
def post(self, path: str, body: dict = None, **params) -> Any:
params["corpId"] = self.corp_id
resp = self._client.post(f"/api{path}", json=body or {}, params=params)
resp.raise_for_status()
return resp.json()
try:
resp = self._client.post(f"/api{path}", json=body or {}, params=params)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise AuthenticationError()
raise ApiResponseError(e.response.status_code, str(e))
data = resp.json()
if isinstance(data, dict) and data.get("errorCode") == 401:
raise AuthenticationError(data.get("errorMessage", "认证失败"))
return data
def __enter__(self):
return self
@@ -41,13 +69,16 @@ class EkbClient:
def __exit__(self, *args):
self._client.close()
def close(self):
self._client.close()
def get_client() -> EkbClient:
"""从当前配置获取已认证的客户端,未登录时抛出友好错误"""
"""从当前配置获取已认证的客户端,未登录时抛出 NotLoggedInError"""
from ekb_cli import config
corp = config.get_current_corp()
if not corp:
raise RuntimeError("未登录,请先执行 `ekb auth add` 添加企业认证")
raise NotLoggedInError()
corp_id = config.get_current_corp_id()
return EkbClient(
corp_id=corp_id,
@@ -56,7 +87,7 @@ def get_client() -> EkbClient:
)
# ── 统一 re-export:commands 只从这里导入,内部拆分对外透明 ──────────
# ── 统一 re-export:commands / services 只从这里导入 ──────────
from ekb_cli.api.agent import ( # noqa: E402
check_agent_name,
list_agents,
+36
View File
@@ -0,0 +1,36 @@
"""Service 层统一 re-export
commands / server 从此处导入所有 service 函数,
内部模块拆分对上层透明。
"""
from ekb_cli.services.auth_service import ( # noqa: F401
CorpInfo,
CorpDetail,
list_corps,
whoami,
add_corp,
use_corp,
remove_corp,
)
from ekb_cli.services.agent_service import ( # noqa: F401
AgentCreateInput,
AgentUpdateInput,
MODE_NAMES,
MODE_DISPLAY,
DEFAULT_ICON,
list_agents,
get_agent,
create_agent,
copy_agent,
update_agent,
delete_agent,
get_dedup_rules_across_agents,
)
from ekb_cli.services.rule_service import ( # noqa: F401
VALID_LEVELS,
list_rules,
get_rule,
create_rule,
update_rule,
)
+217
View File
@@ -0,0 +1,217 @@
"""Service 层:Agent 业务逻辑
将原本散落在 commands/agent/*.py 中的编排逻辑集中到此处。
CLI 和 Server 共用同一套逻辑,只有输出格式不同。
职责:
- 参数校验(mode 合法性、samplingRate 范围)
- 多步编排(check_name → save、get → merge → save)
- 高阶组合查询(获取所有 Agent 关联的去重规则)
- 统一抛出 EkbError 子类,不关心上层如何渲染
"""
from dataclasses import dataclass, field
from typing import Optional
from ekb_cli.api import EkbClient
from ekb_cli.api import (
check_agent_name as api_check_name,
list_agents as api_list_agents,
get_agent as api_get_agent,
save_agent as api_save_agent,
delete_agent as api_delete_agent,
)
from ekb_cli.api.schemas import AgentDetail, AgentSummary, AgentRuleRef, PageData
from ekb_cli.errors import NotFoundError, ConflictError, InputError
# ── 枚举常量 ─────────────────────────────────────────────────
#: 前端传入的模式字符串 → 快报 API 的 int 值
MODE_NAMES: dict[str, int] = {"auto": 0, "semi": 1, "assist": 2}
#: 快报 API int 值 → 可读中文
MODE_DISPLAY: dict[int, str] = {0: "全自动", 1: "半自动", 2: "辅助"}
DEFAULT_ICON = "https://statics.ekuaibao.com/eui/eui-static/male5.png"
# ── 输入数据类 ───────────────────────────────────────────────
@dataclass
class AgentCreateInput:
"""新建 Agent 的输入参数"""
name: str
description: str = ""
mode: str = "assist" # "auto" / "semi" / "assist"
sampling_rate: int = 0
agree_terms: str = ""
reject_terms: str = ""
exempt_terms: str = ""
review_terms: str = ""
rule_ids: list[str] = field(default_factory=list)
icon: str = DEFAULT_ICON
@dataclass
class AgentUpdateInput:
"""更新 Agent 的输入参数(所有字段可选,None 表示不修改)"""
agent_id: str
name: Optional[str] = None
description: Optional[str] = None
mode: Optional[str] = None # "auto" / "semi" / "assist"
sampling_rate: Optional[int] = None
state: Optional[int] = None
agree_terms: Optional[str] = None
reject_terms: Optional[str] = None
exempt_terms: Optional[str] = None
review_terms: Optional[str] = None
# ── 查询 ─────────────────────────────────────────────────────
def list_agents(client: EkbClient) -> PageData[AgentSummary]:
"""列出所有 Agent(分页,默认 size=1000 拉全量)"""
return api_list_agents(client)
def get_agent(client: EkbClient, agent_id: str) -> AgentDetail:
"""获取 Agent 详情,不存在时抛出 NotFoundError"""
detail = api_get_agent(client, agent_id)
if not detail:
raise NotFoundError("Agent", agent_id)
return detail
# ── 创建 ─────────────────────────────────────────────────────
def create_agent(client: EkbClient, inp: AgentCreateInput) -> AgentDetail:
"""新建 Agent
校验:
- mode 必须是 auto / semi / assist
- 名称不能与已有 Agent 重复
"""
if inp.mode not in MODE_NAMES:
raise InputError(f"mode 必须是 auto / semi / assist,当前:{inp.mode}")
if not api_check_name(client, inp.name):
raise ConflictError(f"名称「{inp.name}」已存在,请换一个")
payload = {
"icon": inp.icon,
"name": inp.name,
"description": inp.description,
"mode": MODE_NAMES[inp.mode],
"agreeTerms": inp.agree_terms,
"rejectTerms": inp.reject_terms,
"exemptTerms": inp.exempt_terms,
"reviewTerms": inp.review_terms,
"state": 1,
"ruleIds": inp.rule_ids,
}
return api_save_agent(client, payload)
# ── 复制 ─────────────────────────────────────────────────────
def copy_agent(client: EkbClient, agent_id: str) -> tuple[AgentDetail, AgentDetail]:
"""复制 Agent,新 Agent 名称自动追加「(副本)」
Returns:
(源 Agent, 新 Agent)
"""
src = get_agent(client, agent_id) # 不存在会抛 NotFoundError
new_name = src.name + "(副本)"
if not api_check_name(client, new_name):
raise ConflictError(f"名称「{new_name}」已存在,无法复制")
payload = {
"icon": src.icon,
"name": new_name,
"description": src.description,
"mode": src.mode,
"agreeTerms": src.agreeTerms,
"rejectTerms": src.rejectTerms,
"exemptTerms": src.exemptTerms,
"reviewTerms": src.reviewTerms,
"state": 1,
"ruleIds": [r.id for r in src.agentRule],
}
# 半自动模式需带上抽检比例
if src.mode == 1:
payload["samplingRate"] = src.samplingRate
new = api_save_agent(client, payload)
return src, new
# ── 更新 ─────────────────────────────────────────────────────
def update_agent(client: EkbClient, inp: AgentUpdateInput) -> AgentDetail:
"""更新 Agent(patch 式:只改传入字段,其余保持原值)
校验:
- mode 若传入必须是 auto / semi / assist
- sampling_rate 若传入必须在 0-100
"""
if inp.mode is not None and inp.mode not in MODE_NAMES:
raise InputError(f"mode 必须是 auto / semi / assist,当前:{inp.mode}")
if inp.sampling_rate is not None and not (0 <= inp.sampling_rate <= 100):
raise InputError("sampling-rate 范围是 0-100")
# 先拉原始数据,再 merge
d = get_agent(client, inp.agent_id)
mode_val = MODE_NAMES[inp.mode] if inp.mode is not None else d.mode
payload: dict = {
"id": d.id,
"icon": d.icon,
"name": inp.name if inp.name is not None else d.name,
"description": inp.description if inp.description is not None else d.description,
"mode": mode_val,
"agreeTerms": inp.agree_terms if inp.agree_terms is not None else d.agreeTerms,
"rejectTerms": inp.reject_terms if inp.reject_terms is not None else d.rejectTerms,
"exemptTerms": inp.exempt_terms if inp.exempt_terms is not None else d.exemptTerms,
"reviewTerms": inp.review_terms if inp.review_terms is not None else d.reviewTerms,
"state": inp.state if inp.state is not None else d.state,
"ruleIds": [r.id for r in d.agentRule],
}
if mode_val == 1:
payload["samplingRate"] = (
inp.sampling_rate if inp.sampling_rate is not None else d.samplingRate
)
return api_save_agent(client, payload)
# ── 删除 ─────────────────────────────────────────────────────
def delete_agent(client: EkbClient, agent_id: str) -> AgentDetail:
"""删除 Agent(软删除:state=2),返回被删除的 Agent 用于确认展示"""
detail = get_agent(client, agent_id)
api_delete_agent(client, agent_id)
return detail
# ── 高阶组合接口 ─────────────────────────────────────────────
def get_dedup_rules_across_agents(client: EkbClient) -> list[AgentRuleRef]:
"""遍历所有 Agent,收集其关联规则并去重
用途:统计企业内实际被引用的规则集合。
Returns:
去重后的规则列表(保持首次出现的顺序)
"""
page = api_list_agents(client)
seen: set[str] = set()
rules: list[AgentRuleRef] = []
for summary in page.items:
detail = api_get_agent(client, summary.id)
for r in detail.agentRule:
if r.id not in seen:
seen.add(r.id)
rules.append(r)
return rules
+81
View File
@@ -0,0 +1,81 @@
"""Service 层:认证/企业配置管理
职责:封装 config 模块的数据操作,向上提供类型化返回值。
CLI 和 Server 都调用此层,不直接操作 config。
注意:auth add 的交互式输入逻辑(prompt)留在 CLI 层,
此层只处理数据写入,不涉及 I/O。
"""
from dataclasses import dataclass
from typing import Optional
from ekb_cli import config
from ekb_cli.errors import NotFoundError, NotLoggedInError
# ── 数据类 ────────────────────────────────────────────────────
@dataclass
class CorpInfo:
"""企业信息(不含敏感 token,用于展示和返回)"""
corp_id: str
name: str
is_current: bool
@dataclass
class CorpDetail:
"""企业完整信息(含 token,用于内部传递)"""
corp_id: str
name: str
access_token: str
staff_id: str
is_current: bool
# ── 查询 ──────────────────────────────────────────────────────
def list_corps() -> list[CorpInfo]:
"""列出所有已配置的企业"""
data = config.get_all()
current = data.get("current")
return [
CorpInfo(corp_id=cid, name=info["name"], is_current=(cid == current))
for cid, info in data.get("corps", {}).items()
]
def whoami() -> CorpInfo:
"""获取当前企业信息,未登录时抛出 NotLoggedInError"""
corp = config.get_current_corp()
corp_id = config.get_current_corp_id()
if not corp or not corp_id:
raise NotLoggedInError()
current = config.get_current_corp_id()
return CorpInfo(corp_id=corp_id, name=corp["name"], is_current=(corp_id == current))
# ── 写操作 ────────────────────────────────────────────────────
def add_corp(corp_id: str, name: str, access_token: str, staff_id: str) -> CorpInfo:
"""添加企业认证,返回添加后的企业信息"""
config.add_corp(corp_id=corp_id, name=name, access_token=access_token, staff_id=staff_id)
current = config.get_current_corp_id()
return CorpInfo(corp_id=corp_id, name=name, is_current=(current == corp_id))
def use_corp(corp_id: str) -> CorpInfo:
"""切换当前企业,企业不存在时抛出 NotFoundError"""
try:
config.use_corp(corp_id)
except ValueError:
raise NotFoundError("企业", corp_id)
data = config.get_all()
info = data["corps"][corp_id]
return CorpInfo(corp_id=corp_id, name=info["name"], is_current=True)
def remove_corp(corp_id: str) -> None:
"""删除企业认证配置"""
config.remove_corp(corp_id)
+116
View File
@@ -0,0 +1,116 @@
"""Service 层:审核规则(Rule)业务逻辑
将原本散落在 commands/agent/rule_*.py 中的逻辑集中到此处。
CLI 和 Server 共用同一套逻辑。
职责:
- 参数校验(level 合法性)
- 按编码/ID 查找单条规则(快报无直接 get 接口,需拉全量过滤)
- 规则 CRUD 编排
"""
from typing import Optional
from ekb_cli.api import EkbClient
from ekb_cli.api.rule import (
list_rules as api_list_rules,
save_rule as api_save_rule,
update_rule as api_update_rule,
)
from ekb_cli.api.schemas import PageData, Rule, RuleWithAgents
from ekb_cli.errors import NotFoundError, InputError
# ── 枚举常量 ─────────────────────────────────────────────────
VALID_LEVELS = {"严重", "一般"}
# ── 查询 ─────────────────────────────────────────────────────
def list_rules(
client: EkbClient,
level: Optional[str] = None,
) -> tuple[PageData[RuleWithAgents], list[RuleWithAgents]]:
"""列出所有规则,可按 level 筛选
Returns:
(原始分页数据, 筛选后的 items 列表)
返回原始分页是为了让调用方能拿到 totalItems 等元数据
"""
page = api_list_rules(client)
items = page.items
if level:
items = [r for r in items if r.level == level]
return page, items
def get_rule(client: EkbClient, rule_ref: str) -> RuleWithAgents:
"""按 ID 或编码查找单条规则
rule_ref 支持以下格式:
- 完整 ID(长字符串)
- 编码数字,如 "1" / "0001" / "#0001"
快报无直接的 rule/detail 接口,因此拉全量后客户端过滤。
"""
page = api_list_rules(client)
# 纯数字且不超过 4 位 → 按编码匹配(补零对齐)
stripped = rule_ref.lstrip("#")
if stripped.isdigit() and len(stripped) <= 4:
code = f"#{stripped.zfill(4)}"
rule = next((r for r in page.items if r.code == code), None)
else:
rule = next((r for r in page.items if r.id == rule_ref), None)
if not rule:
raise NotFoundError("规则", rule_ref)
return rule
# ── 创建 ─────────────────────────────────────────────────────
def create_rule(
client: EkbClient,
purpose: str,
description: str,
level: str = "严重",
) -> Rule:
"""新建审核规则
校验:level 必须是 严重 / 一般
"""
if level not in VALID_LEVELS:
raise InputError(f"--level 只接受 严重 / 一般,当前值:{level}")
payload = {"purpose": purpose, "description": description, "level": level}
return api_save_rule(client, payload)
# ── 更新 ─────────────────────────────────────────────────────
def update_rule(
client: EkbClient,
rule_ref: str,
purpose: Optional[str] = None,
description: Optional[str] = None,
level: Optional[str] = None,
) -> Rule:
"""更新审核规则(patch 式)
rule_ref 同 get_rule,支持 ID 或编码。
只传需要修改的字段,其余保持原值。
"""
if level is not None and level not in VALID_LEVELS:
raise InputError(f"--level 只接受 严重 / 一般,当前值:{level}")
current = get_rule(client, rule_ref)
payload = {
"id": current.id,
"code": current.code,
"purpose": purpose if purpose is not None else current.purpose,
"description": description if description is not None else current.description,
"level": level if level is not None else current.level,
}
return api_update_rule(client, payload)