feat(platform): 新增自建应用子域 API/Service 层

新增 api/platform/ 子包(对齐 api/sealai/ 结构):
- platform_api: list_platforms(DataLink Platform 列表)
- easo_client: EasoClient + get_easo_client()(EASO Bearer JWT 认证)
- workflow_api: list_workflows / get_workflow_stats / get_workflow_charge
- schemas: Platform / Workflow* 模型(从全局 schemas.py 独立出来)

新增 services/platform/ 子包:
- list_platforms / list_platforms_cmd
- list_workflows / get_workflow_stats / get_workflow_charge 及 _cmd 变体

全局 api/schemas.py 清理 platform/workflow 相关模型,只保留通用结构。
未实现子模块(entity/page/card/variable/log)在各层以 README 预留。
This commit is contained in:
gitea committed 2026-04-16 17:54:35 +08:00
1 parent f7c065f59b
commit 474349e7e4
14 files changed
+644

No files matched your search

+6
View File
@@ -102,3 +102,9 @@ from ekb_cli.api.rule import ( # noqa: E402
update_rule,
delete_rule,
)
from ekb_cli.api.platform import ( # noqa: E402
list_platforms,
list_workflows,
get_workflow_stats,
get_workflow_charge,
)
@@ -0,0 +1,25 @@
# api/platform — 自建应用域传输层
## 已实现
| 文件 | 说明 |
|---|---|
| `easo_client.py` | EASO 工作流客户端(`unity.ekuaibao.com` + Bearer JWT) |
| `platform_api.py` | 自建应用列表接口 |
| `workflow_api.py` | 工作流列表 / 统计 / 配额接口 |
## 待实现(预留)
以下模块接口尚未抓包或开发,待后续按需补充:
| 模块 | 预估接口 | 说明 |
|---|---|---|
| **业务对象(Entity)** | `POST /api/v2/datalink/entity/platformId/$id` | 获取平台下的实体/数据表列表 |
| **页面设计器** | 待抓包 | 自定义页面配置相关接口 |
| **互联卡片** | 待抓包 | 卡片配置/联动相关接口 |
| **应用变量** | 待抓包 | 全局变量定义相关接口 |
| **应用扩展** | 待抓包 | 扩展能力配置接口 |
| **应用日志** | `GET /api/easo/pipelines/logs`(运行日志) | 与工作流列表同接口,参数不同 |
| **平台凭证(Realm)** | `GET /api/v2/datalink/platform/realm` | appKey / appSecret 查询 |
新增接口时,在本目录创建对应 `xxx_api.py`,并在 `__init__.py` 补充 re-export。
+24
View File
@@ -0,0 +1,24 @@
"""api/platform 子包:自建应用域传输层统一 re-export
包含两类客户端:
- 快报主站 EkbClient(由父包 api/ 提供)→ 用于 platform_api
- EASO 客户端 EasoClient(本包提供)→ 用于 workflow_api
commands / services 只从此处导入,内部文件拆分对上层透明。
"""
from ekb_cli.api.platform.schemas import ( # noqa: F401
Platform,
Workflow,
WorkflowTask,
WorkflowPage,
WorkflowStats,
WorkflowCharge,
)
from ekb_cli.api.platform.easo_client import EasoClient, get_easo_client # noqa: F401
from ekb_cli.api.platform.platform_api import list_platforms # noqa: F401
from ekb_cli.api.platform.workflow_api import ( # noqa: F401
list_workflows,
get_workflow_stats,
get_workflow_charge,
)
+92
View File
@@ -0,0 +1,92 @@
"""EASO HTTP 客户端(传输层)。
与快报主站的 EkbClient 并列,同属 api/ 传输层。
区别:EASO 工作流子域使用 Bearer JWT 认证,域名固定为 unity.ekuaibao.com。
Bearer JWT 通过快报主站接口换取:
GET /api/engine/realm/$EASO/actions/jwt → {"value": "<token>"}
使用方:services/platform/workflow_service 通过 get_easo_client() 获取实例,
并在 _cmd 函数中以 with 上下文管理器管理生命周期。
"""
from __future__ import annotations
import httpx
from typing import Any
from ekb_cli.errors import AuthenticationError, ApiResponseError, NotLoggedInError
EASO_BASE_URL = "https://unity.ekuaibao.com"
class EasoClient:
"""EASO 工作流客户端(unity.ekuaibao.com),使用 Bearer JWT 认证。"""
def __init__(self, corp_id: str, access_token: str, bearer_token: str):
self.corp_id = corp_id
self._client = httpx.Client(
base_url=EASO_BASE_URL,
headers={
"Authorization": f"Bearer {bearer_token}",
"accesstoken": access_token,
"corporationid": corp_id,
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/147.0.0.0 Safari/537.36"
),
},
timeout=30,
)
def _handle_error(self, e: httpx.HTTPStatusError) -> None:
if e.response.status_code == 401:
raise AuthenticationError("EASO token 已过期,请重新登录")
raise ApiResponseError(e.response.status_code, str(e))
def get(self, path: str, **params) -> Any:
params["corpId"] = self.corp_id
try:
resp = self._client.get(path, params=params)
resp.raise_for_status()
except httpx.HTTPStatusError as e:
self._handle_error(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
def __exit__(self, *args):
self._client.close()
def close(self):
self._client.close()
def get_easo_client() -> EasoClient:
"""从当前配置创建 EasoClient(自动通过快报主站换取 EASO Bearer JWT)。
未登录时抛出 NotLoggedInError。
"""
from ekb_cli import config
from ekb_cli.api import get_client
corp = config.get_current_corp()
if not corp:
raise NotLoggedInError()
corp_id = config.get_current_corp_id()
with get_client() as ekb:
raw = ekb.get("/engine/realm/$EASO/actions/jwt")
bearer = raw.get("value", "")
return EasoClient(
corp_id=corp_id,
access_token=corp["access_token"],
bearer_token=bearer,
)
+16
View File
@@ -0,0 +1,16 @@
"""自建应用(DataLink Platform)API 调用封装"""
from typing import List
from ekb_cli.api import EkbClient
from ekb_cli.api.platform.schemas import Platform
def list_platforms(client: EkbClient) -> List[Platform]:
"""获取企业下所有启用的自建应用。
对应接口:GET /api/v2/datalink/platform/search?scope=enable
响应结构:{"items": [...]}(非 EkbResponse 包装)
"""
raw = client.get("/v2/datalink/platform/search", scope="enable")
return [Platform.model_validate(item) for item in raw.get("items", [])]
+112
View File
@@ -0,0 +1,112 @@
"""api/platform 子域:自建应用与工作流 Pydantic 模型
包含两类模型:
- Platform:自建应用(DataLink Platform)摘要
- Workflow / WorkflowPage / WorkflowStats / WorkflowCharge:工作流(EASO Pipeline)相关模型
设计原则:
- extra="allow" 兼容快报可能新增的字段
- 该文件只存放 platform 子域专属模型;跨子域通用结构(EkbResponse / PageData)保留在父层 schemas.py
"""
from typing import Any, List, Optional
from pydantic import BaseModel, ConfigDict
# 允许字段多于定义(快报可能新增字段),已知字段必须类型正确
_cfg = ConfigDict(extra="allow")
# ── 自建应用(DataLink Platform)─────────────────────────────
class Platform(BaseModel):
"""自建应用(DataLink Platform)摘要
对应快报「应用中心 → 自建应用」列表中的每一条记录。
接口:GET /api/v2/datalink/platform/search?scope=enable
响应结构:{"items": [...]}(非 EkbResponse 包装)
"""
model_config = _cfg
id: str
name: str
nameSpell: str = ""
enName: Optional[str] = None
code: str = ""
corporationId: str
active: bool = True
type: str = "" # 固定为 DATA_LINK
groupType: str = "" # NORMAL / SPECIAL
platformType: str = "" # HAB
source: str = "" # CUSTOM_CREATE
adminIds: List[str] = []
desc: str = ""
importMethod: List[str] = []
createTime: int = 0
updateTime: int = 0
icon: Optional[Any] = None
# ── 工作流(EASO Pipeline)───────────────────────────────────
class WorkflowTask(BaseModel):
"""工作流中的单个节点(trigger / action / control)"""
model_config = _cfg
name: str = ""
type: str = "" # clock / ekuaibao-ebot-trigger / http / stop / ...
label: str = ""
desc: str = ""
groupName: str = "" # trigger / action / control
orderIndex: int = 0
status: str = "" # success / ...
class Workflow(BaseModel):
"""工作流摘要(pipelineList 中的单条)"""
model_config = _cfg
id: str
pipelineName: str = ""
state: int = 0 # 0=停用 / 1=启用
runningCount: int = 0
errorCount: int = 0
updateTime: str = ""
updateUser: Optional[str] = None
tasks: List[Any] = [] # 节点结构复杂,先用 Any 承接
desc: Optional[str] = None
customDesc: Optional[str] = None
class WorkflowPage(BaseModel):
"""工作流分页响应(EkbResponse.data)"""
model_config = _cfg
pipelineNum: int = 0 # 该应用下工作流总数
runningNum: int = 0
allRunCount: int = 0
errorCount: int = 0
number: int = 1
size: int = 20
totalPages: int = 0
totalItems: int = 0
pipelineList: List[Workflow] = []
class WorkflowStats(BaseModel):
"""工作流执行统计"""
model_config = _cfg
total: int = 0
completed: int = 0
failed: int = 0
started: int = 0
pipelineOpenCount: int = 0
pipelineCloseCount: int = 0
pipelineAllCount: int = 0
class WorkflowCharge(BaseModel):
"""企业工作流资源包/配额"""
model_config = _cfg
corporationId: str = ""
status: str = "" # ACTIVED / ...
orderType: str = ""
total: int = 0
used: int = 0
remaining: int = 0
+51
View File
@@ -0,0 +1,51 @@
"""工作流(EASO Pipeline)API 调用封装
域名:unity.ekuaibao.com
认证:Bearer JWT(由 EasoClient 持有,通过 easo_client.get_easo_client() 获取)
响应:标准 EkbResponse 包装(code / msg / data)
"""
from ekb_cli.api.platform.easo_client import EasoClient
from ekb_cli.api.schemas import EkbResponse
from ekb_cli.api.platform.schemas import WorkflowPage, WorkflowStats, WorkflowCharge
def list_workflows(
client: EasoClient,
platform_id: str,
page: int = 1,
page_size: int = 20,
) -> WorkflowPage:
"""分页获取指定自建应用下的工作流列表。
对应接口:GET /api/easo/pipelines/logs
参数:platformId / number(页码)/ pageSize
"""
raw = client.get(
"/api/easo/pipelines/logs",
platformId=platform_id,
number=page,
pageSize=page_size,
)
resp = EkbResponse[WorkflowPage].model_validate(raw)
return resp.data
def get_workflow_stats(client: EasoClient, platform_id: str) -> WorkflowStats:
"""获取指定自建应用的工作流执行统计(总数/成功/失败等)。
对应接口:GET /api/easo/stats
"""
raw = client.get("/api/easo/stats", platformId=platform_id)
resp = EkbResponse[WorkflowStats].model_validate(raw)
return resp.data
def get_workflow_charge(client: EasoClient) -> WorkflowCharge:
"""获取企业工作流资源包/配额信息。
对应接口:GET /api/easo/charge
"""
raw = client.get("/api/easo/charge")
resp = EkbResponse[WorkflowCharge].model_validate(raw)
return resp.data
+4
View File
@@ -3,6 +3,10 @@
分为两部分:
1. 快报 API 响应模型(EkbResponse / PageData / Rule / Agent 系列)
2. ekb-cli HTTP Server 的请求/响应模型(*Request / *Response / ApiResult)
约定:
- 子域专属模型放在各自的 api/<domain>/schemas.py(如 api/platform/schemas.py)
- 本文件只保留跨子域通用模型和 Server 请求/响应模型
"""
from typing import Any, Generic, List, Optional, TypeVar
+11
View File
@@ -51,6 +51,17 @@ from ekb_cli.services.rule_service import ( # noqa: F401
get_rule_cmd,
create_rule_cmd,
)
from ekb_cli.services.platform import ( # noqa: F401
list_platforms,
list_platforms_cmd,
# 工作流
list_workflows,
get_workflow_stats,
get_workflow_charge,
list_workflows_cmd,
get_workflow_stats_cmd,
get_workflow_charge_cmd,
)
# SealAI 子域服务:通过 services.sealai 子包统一导出,
# commands/server 使用 `from ekb_cli.services.sealai import xxx`
@@ -0,0 +1,22 @@
# services/platform — 自建应用域服务层
## 已实现
| 文件 | 说明 |
|---|---|
| `__init__.py` | 自建应用列表(`list_platforms` / `list_platforms_cmd`) |
| `workflow_service.py` | 工作流列表 / 统计 / 配额(`list_workflows` / `get_workflow_stats` / `get_workflow_charge` 及对应 `_cmd`) |
## 待实现(预留)
以下模块服务层尚未开发,待接口确认后按需补充:
| 文件(待建) | 对应业务 | 依赖 API |
|---|---|---|
| `entity_service.py` | 业务对象(实体/数据表)CRUD | `api/platform/entity_api.py`(待建) |
| `page_service.py` | 页面设计器 | 待抓包 |
| `card_service.py` | 互联卡片 | 待抓包 |
| `variable_service.py` | 应用变量 | 待抓包 |
| `log_service.py` | 应用日志 | `api/easo/pipelines/logs`(运行日志参数) |
新增服务时,在本目录创建对应 `xxx_service.py`,并在 `__init__.py` 和父级 `services/__init__.py` 补充 re-export。
+41
View File
@@ -0,0 +1,41 @@
"""Service 层:自建应用(DataLink Platform)业务逻辑
职责:
- 列出当前企业下所有启用的自建应用
- 统一抛出 EkbError 子类,不关心上层如何渲染
"""
from typing import List
from ekb_cli.api import EkbClient, get_client
from ekb_cli.api.platform.schemas import Platform
from ekb_cli.api.platform.platform_api import list_platforms as api_list_platforms
# ── 查询 ─────────────────────────────────────────────────────
def list_platforms(client: EkbClient) -> List[Platform]:
"""列出所有启用的自建应用"""
return api_list_platforms(client)
# ── CLI 便捷函数(自管 client 生命周期)────────────────────────
# commands/* 层调用这批函数,不需要自行 import get_client,
# 保持 commands → services → api 的依赖方向。
def list_platforms_cmd() -> List[Platform]:
"""CLI 便捷函数:自动获取当前企业 client 并列出所有自建应用"""
with get_client() as client:
return list_platforms(client)
# ── 工作流子模块 re-export ────────────────────────────────────
from ekb_cli.services.platform.workflow_service import ( # noqa: F401, E402
list_workflows,
get_workflow_stats,
get_workflow_charge,
list_workflows_cmd,
get_workflow_stats_cmd,
get_workflow_charge_cmd,
)
@@ -0,0 +1,66 @@
"""Service 层:工作流(EASO Pipeline)业务逻辑
域:unity.ekuaibao.com(EASO 子系统)
认证:EasoClient(Bearer JWT,通过 get_easo_client() 获取)
职责:
- 分页列出指定自建应用下的工作流
- 查询工作流执行统计
- 查询企业工作流配额
- 统一抛出 EkbError 子类,不关心上层如何渲染
"""
from ekb_cli.api.platform.easo_client import EasoClient, get_easo_client
from ekb_cli.api.platform.schemas import WorkflowPage, WorkflowStats, WorkflowCharge
from ekb_cli.api.platform.workflow_api import (
list_workflows as api_list_workflows,
get_workflow_stats as api_get_workflow_stats,
get_workflow_charge as api_get_workflow_charge,
)
# ── 查询 ─────────────────────────────────────────────────────
def list_workflows(
client: EasoClient,
platform_id: str,
page: int = 1,
page_size: int = 20,
) -> WorkflowPage:
"""列出指定自建应用下的工作流(分页)"""
return api_list_workflows(client, platform_id, page, page_size)
def get_workflow_stats(client: EasoClient, platform_id: str) -> WorkflowStats:
"""获取指定自建应用的工作流执行统计"""
return api_get_workflow_stats(client, platform_id)
def get_workflow_charge(client: EasoClient) -> WorkflowCharge:
"""获取企业工作流资源包/配额"""
return api_get_workflow_charge(client)
# ── CLI 便捷函数(自管 client 生命周期)────────────────────────
# commands/* 层调用这批函数,保持 commands → services → api 依赖方向。
def list_workflows_cmd(
platform_id: str,
page: int = 1,
page_size: int = 20,
) -> WorkflowPage:
"""CLI 便捷函数:自动获取 EasoClient 并列出工作流"""
with get_easo_client() as client:
return list_workflows(client, platform_id, page, page_size)
def get_workflow_stats_cmd(platform_id: str) -> WorkflowStats:
"""CLI 便捷函数:自动获取 EasoClient 并查询工作流统计"""
with get_easo_client() as client:
return get_workflow_stats(client, platform_id)
def get_workflow_charge_cmd() -> WorkflowCharge:
"""CLI 便捷函数:自动获取 EasoClient 并查询工作流配额"""
with get_easo_client() as client:
return get_workflow_charge(client)