diff --git a/src/ekb_cli/api/platform/piper_client.py b/src/ekb_cli/api/platform/piper_client.py new file mode 100644 index 0000000..4e193d5 --- /dev/null +++ b/src/ekb_cli/api/platform/piper_client.py @@ -0,0 +1,156 @@ +"""Piper HTTP 客户端(传输层)。 + +工作流配置(节点设计)子域,域名为 piper.ekuaibao.com。 + +认证方式与 unity.ekuaibao.com 不同: + - 使用 EASO JWT(aud=EASO,由 GET /api/engine/realm/$EASO/actions/jwt 换取) + - 需要 platformid Header(指定当前操作的自建应用 ID) + - hose-access-token Cookie + +三步认证链路(均在 get_piper_client() 内自动完成): + 1. accessToken → business-center.ekuaibao.com → hose-access-token + 2. accessToken → app.ekuaibao.com/api/engine/realm/$EASO/actions/jwt → EASO JWT + 3. EASO JWT → Authorization: Bearer → piper.ekuaibao.com 接口 + +调用时需传入 platform_id,因为不同自建应用的工作流接口需要对应的 platformid Header。 +""" + +from __future__ import annotations +import httpx +from typing import Any + +from ekb_cli.errors import AuthenticationError, ApiResponseError, NotLoggedInError + +PIPER_BASE_URL = "https://piper.ekuaibao.com" +_EKB_BASE_URL = "https://app.ekuaibao.com" +_BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com" +_UA = ( + "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" +) + + +class PiperClient: + """Piper 工作流配置客户端(piper.ekuaibao.com),使用 EASO JWT 认证。""" + + def __init__(self, platform_id: str, easo_jwt: str, hose_token: str): + self.platform_id = platform_id + self._client = httpx.Client( + base_url=PIPER_BASE_URL, + headers={ + "Authorization": f"Bearer {easo_jwt}", + "platformid": platform_id, + "Accept": "application/json, text/plain, */*", + "User-Agent": _UA, + }, + cookies={"hose-access-token": hose_token}, + timeout=30, + ) + + def _handle_error(self, e: httpx.HTTPStatusError) -> None: + if e.response.status_code == 401: + raise AuthenticationError("Piper token 已过期,请重新登录") + raise ApiResponseError(e.response.status_code, str(e)) + + def get(self, path: str, **params) -> Any: + try: + resp = self._client.get(path, params=params or None) + 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 _fetch_hose_token(access_token: str, corp_id: str) -> str: + """Step 1:用主站 accessToken 换取 hose-access-token(约 30 天)。""" + resp = httpx.get( + f"{_BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken", + params={"corpId": corp_id, "ekbAccessToken": access_token, "environment": "app"}, + timeout=10, + ) + try: + resp.raise_for_status() + except httpx.HTTPStatusError as e: + raise ApiResponseError(e.response.status_code, f"hose-access-token 换取失败: {e}") + data = resp.json() + token = data.get("data", "") + if not token: + raise ApiResponseError(0, f"hose-access-token 换取失败,响应结构异常:{data}") + return token + + +def _fetch_easo_jwt(access_token: str, corp_id: str, staff_id: str) -> str: + """Step 2:换取 EASO JWT(aud=EASO,约 2 小时)。 + + 用于 piper.ekuaibao.com 的工作流配置接口。 + """ + resp = httpx.get( + f"{_EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt", + params={"corpId": corp_id}, + headers={ + "accesstoken": access_token, + "corpid": corp_id, + "staffid": staff_id, + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": _UA, + }, + timeout=30, + ) + try: + 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)) + raw = resp.json() + if isinstance(raw, dict) and raw.get("errorCode") == 401: + raise AuthenticationError(raw.get("errorMessage", "认证已过期,请重新执行 `ekb auth add` 更新 token")) + jwt = raw.get("id") or raw.get("value", "") + if not jwt: + raise ApiResponseError(0, f"EASO JWT 换取失败,响应结构异常:{raw}") + return jwt + + +# ── 工厂函数 ───────────────────────────────────────────────── + +def get_piper_client(platform_id: str) -> PiperClient: + """从当前配置创建 PiperClient,自动完成三步认证链路。 + + Args: + platform_id: 自建应用 ID,用于 platformid Header。 + + 未登录时抛出 NotLoggedInError。 + """ + from ekb_cli import config + + corp = config.get_current_corp() + if not corp: + raise NotLoggedInError() + corp_id = config.get_current_corp_id() + access_token = corp["access_token"] + staff_id = corp["staff_id"] + + hose_token = _fetch_hose_token(access_token, corp_id) + easo_jwt = _fetch_easo_jwt(access_token, corp_id, staff_id) + + return PiperClient( + platform_id=platform_id, + easo_jwt=easo_jwt, + hose_token=hose_token, + ) diff --git a/src/ekb_cli/api/platform/schemas.py b/src/ekb_cli/api/platform/schemas.py index 86fd465..54be619 100644 --- a/src/ekb_cli/api/platform/schemas.py +++ b/src/ekb_cli/api/platform/schemas.py @@ -101,6 +101,42 @@ class WorkflowStats(BaseModel): pipelineAllCount: int = 0 +class WorkflowAlarm(BaseModel): + """工作流告警配置""" + model_config = _cfg + alarmUser: List[Any] = [] + alarmType: List[str] = [] + active: bool = True + alarmScope: str = "" + + +class WorkflowDetail(BaseModel): + """工作流完整配置(piper.ekuaibao.com/api/easo/pipelines/{id}) + + 包含所有节点的完整配置,节点类型各异(trigger / action / control), + 通用字段由 WorkflowTask 描述,各节点特有字段通过 extra="allow" 兜住。 + """ + model_config = _cfg + id: str + label: str = "" # 工作流名称 + desc: Optional[str] = None + customDesc: Optional[str] = None + state: int = 0 # 0=停用 / 1=启用 + debugState: int = 0 + runTimes: int = 0 + errorTimes: int = 0 + updateTime: str = "" + updateUser: Optional[str] = None + staffName: Optional[str] = None + version: str = "" + dataLimit: int = 20 + source: int = 0 + queueJobs: bool = False + tasksVersion: int = 0 + tasks: List[WorkflowTask] = [] + alarm: Optional[WorkflowAlarm] = None + + class WorkflowCharge(BaseModel): """企业工作流资源包/配额""" model_config = _cfg diff --git a/src/ekb_cli/api/platform/workflow_api.py b/src/ekb_cli/api/platform/workflow_api.py index 0a8206a..fa5a6ee 100644 --- a/src/ekb_cli/api/platform/workflow_api.py +++ b/src/ekb_cli/api/platform/workflow_api.py @@ -1,13 +1,17 @@ """工作流(EASO Pipeline)API 调用封装 -域名:unity.ekuaibao.com -认证:Bearer JWT(由 EasoClient 持有,通过 easo_client.get_easo_client() 获取) +两个域名: + - unity.ekuaibao.com(EasoClient):工作流列表 / 统计 / 配额 + - piper.ekuaibao.com(PiperClient):工作流详情(节点配置) + +认证方式见各 client 模块。 响应:标准 EkbResponse 包装(code / msg / data) """ from ekb_cli.api.platform.easo_client import EasoClient +from ekb_cli.api.platform.piper_client import PiperClient from ekb_cli.api.schemas import EkbResponse -from ekb_cli.api.platform.schemas import WorkflowPage, WorkflowStats, WorkflowCharge +from ekb_cli.api.platform.schemas import WorkflowPage, WorkflowStats, WorkflowCharge, WorkflowDetail def list_workflows( @@ -49,3 +53,14 @@ def get_workflow_charge(client: EasoClient) -> WorkflowCharge: raw = client.get("/api/easo/charge") resp = EkbResponse[WorkflowCharge].model_validate(raw) return resp.data + + +def get_workflow(client: PiperClient, pipeline_id: str) -> WorkflowDetail: + """获取指定工作流的完整配置(节点列表及各节点参数)。 + + 对应接口:GET piper.ekuaibao.com/api/easo/pipelines/{pipeline_id} + 认证:EASO JWT + platformid Header(由 PiperClient 持有) + """ + raw = client.get(f"/api/easo/pipelines/{pipeline_id}") + resp = EkbResponse[WorkflowDetail].model_validate(raw) + return resp.data diff --git a/src/ekb_cli/commands/platform/__init__.py b/src/ekb_cli/commands/platform/__init__.py index e8e466f..5e50a45 100644 --- a/src/ekb_cli/commands/platform/__init__.py +++ b/src/ekb_cli/commands/platform/__init__.py @@ -4,6 +4,7 @@ import typer from ekb_cli.commands.platform.list import cmd_list from ekb_cli.commands.platform.workflow_list import cmd_workflow_list +from ekb_cli.commands.platform.workflow_get import cmd_workflow_get from ekb_cli.commands.platform.workflow_stats import cmd_workflow_stats from ekb_cli.commands.platform.workflow_charge import cmd_workflow_charge @@ -11,5 +12,6 @@ app = typer.Typer(help="自建应用(DataLink Platform)管理") app.command("list")(cmd_list) app.command("workflow-list")(cmd_workflow_list) +app.command("workflow-get")(cmd_workflow_get) app.command("workflow-stats")(cmd_workflow_stats) app.command("workflow-charge")(cmd_workflow_charge) diff --git a/src/ekb_cli/commands/platform/workflow_get.py b/src/ekb_cli/commands/platform/workflow_get.py new file mode 100644 index 0000000..85de014 --- /dev/null +++ b/src/ekb_cli/commands/platform/workflow_get.py @@ -0,0 +1,54 @@ +"""ekb platform workflow-get:查看工作流完整配置(节点列表)""" + +import typer +from rich.console import Console +from rich.table import Table +from rich import print as rprint + +from ekb_cli.services.platform import get_workflow_cmd + +console = Console() + +GROUP_LABEL = {"trigger": "触发", "action": "动作", "control": "控制"} +STATE_LABEL = {"success": "[green]✓[/green]", "error": "[red]✗[/red]", "": ""} + + +def cmd_workflow_get( + platform_id: str = typer.Argument(..., help="自建应用 ID"), + pipeline_id: str = typer.Argument(..., help="工作流 ID"), +): + """查看指定工作流的完整配置(触发器 + 节点列表)""" + wf = get_workflow_cmd(platform_id, pipeline_id) + + state_text = "[green]启用[/green]" if wf.state == 1 else "[dim]停用[/dim]" + console.print(f"\n[bold]{wf.label}[/bold] {state_text} [dim]v{wf.version}[/dim]") + if wf.desc: + console.print(f"[dim]{wf.desc}[/dim]") + console.print( + f"执行 {wf.runTimes} 次 / 失败 {wf.errorTimes} 次 " + f"更新:{wf.updateTime} 更新人:{wf.updateUser or '-'}\n" + ) + + if not wf.tasks: + rprint("[yellow]暂无节点[/yellow]") + return + + table = Table(title=f"节点列表(共 {len(wf.tasks)} 个)", show_lines=True) + table.add_column("步骤", style="bold", justify="right") + table.add_column("类型") + table.add_column("名称") + table.add_column("分组") + table.add_column("描述") + table.add_column("状态", justify="center") + + for task in wf.tasks: + table.add_row( + str(task.orderIndex), + task.type, + task.label, + GROUP_LABEL.get(task.groupName, task.groupName), + (task.desc or "")[:60], + STATE_LABEL.get(task.status, task.status), + ) + + console.print(table) diff --git a/src/ekb_cli/server/platform_router.py b/src/ekb_cli/server/platform_router.py index a2a7176..ccc01e2 100644 --- a/src/ekb_cli/server/platform_router.py +++ b/src/ekb_cli/server/platform_router.py @@ -1,22 +1,26 @@ """Server:Platform 路由 对应 CLI 命令: - ekb platform list → GET /platforms - ekb platform workflow-list → GET /platforms/{platform_id}/workflows - ekb platform workflow-stats → GET /platforms/{platform_id}/workflows/stats - ekb platform workflow-charge → GET /platforms/workflows/charge + ekb platform list → GET /platforms + ekb platform workflow-list → GET /platforms/{platform_id}/workflows + ekb platform workflow-get → GET /platforms/{platform_id}/workflows/{wf_id} + ekb platform workflow-stats → GET /platforms/{platform_id}/workflows/stats + ekb platform workflow-charge → GET /platforms/workflows/charge 设计约定: - 自建应用列表使用 EkbClient(主站认证) -- 工作流相关接口使用 EasoClient(EASO Bearer JWT),通过 EasoClientDep 注入 +- 工作流列表/统计/配额使用 EasoClient(EASO realm token) +- 工作流详情使用 PiperClient(EASO JWT + platformid Header) """ from fastapi import APIRouter, Query from ekb_cli.server.deps import ClientDep, EasoClientDep +from ekb_cli.api.platform.piper_client import get_piper_client from ekb_cli.services.platform import ( list_platforms, list_workflows, + get_workflow, get_workflow_stats, get_workflow_charge, ) @@ -31,6 +35,26 @@ def route_list_platforms(client: ClientDep): return {"total": len(platforms), "items": [p.model_dump() for p in platforms]} +@router.get("/workflows/charge", summary="企业工作流资源包配额") +def route_workflow_charge(client: EasoClientDep): + """获取企业工作流资源包总量/已用/剩余""" + return get_workflow_charge(client).model_dump() + + +@router.get("/{platform_id}/workflows/stats", summary="工作流执行统计") +def route_workflow_stats(platform_id: str, client: EasoClientDep): + """获取指定自建应用的工作流执行统计(总数/成功/失败等)""" + return get_workflow_stats(client, platform_id).model_dump() + + +@router.get("/{platform_id}/workflows/{pipeline_id}", summary="工作流完整配置(节点列表)") +def route_get_workflow(platform_id: str, pipeline_id: str): + """获取指定工作流的完整配置,包含所有节点及其参数""" + with get_piper_client(platform_id) as client: + result = get_workflow(client, pipeline_id) + return result.model_dump() + + @router.get("/{platform_id}/workflows", summary="列出指定应用的工作流") def route_list_workflows( platform_id: str, @@ -41,15 +65,3 @@ def route_list_workflows( """分页获取指定自建应用下的工作流列表""" result = list_workflows(client, platform_id, page=page, page_size=page_size) return result.model_dump() - - -@router.get("/{platform_id}/workflows/stats", summary="工作流执行统计") -def route_workflow_stats(platform_id: str, client: EasoClientDep): - """获取指定自建应用的工作流执行统计(总数/成功/失败等)""" - return get_workflow_stats(client, platform_id).model_dump() - - -@router.get("/workflows/charge", summary="企业工作流资源包配额") -def route_workflow_charge(client: EasoClientDep): - """获取企业工作流资源包总量/已用/剩余""" - return get_workflow_charge(client).model_dump() diff --git a/src/ekb_cli/services/platform/__init__.py b/src/ekb_cli/services/platform/__init__.py index 7317e27..b0228d8 100644 --- a/src/ekb_cli/services/platform/__init__.py +++ b/src/ekb_cli/services/platform/__init__.py @@ -32,9 +32,11 @@ def list_platforms_cmd() -> List[Platform]: # ── 工作流子模块 re-export ──────────────────────────────────── from ekb_cli.services.platform.workflow_service import ( # noqa: F401, E402 list_workflows, + get_workflow, get_workflow_stats, get_workflow_charge, list_workflows_cmd, + get_workflow_cmd, get_workflow_stats_cmd, get_workflow_charge_cmd, ) diff --git a/src/ekb_cli/services/platform/workflow_service.py b/src/ekb_cli/services/platform/workflow_service.py index e4b4c3a..2dcf722 100644 --- a/src/ekb_cli/services/platform/workflow_service.py +++ b/src/ekb_cli/services/platform/workflow_service.py @@ -1,24 +1,87 @@ """Service 层:工作流(EASO Pipeline)业务逻辑 -域:unity.ekuaibao.com(EASO 子系统) -认证:EasoClient(Bearer JWT,通过 get_easo_client() 获取) +域: + - unity.ekuaibao.com(EasoClient):列表 / 统计 / 配额 + - piper.ekuaibao.com(PiperClient):工作流配置详情 职责: - 分页列出指定自建应用下的工作流 +- 获取单个工作流完整配置(节点列表) - 查询工作流执行统计 - 查询企业工作流配额 - 统一抛出 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.piper_client import PiperClient, get_piper_client +from ekb_cli.api.platform.schemas import WorkflowPage, WorkflowStats, WorkflowCharge, WorkflowDetail from ekb_cli.api.platform.workflow_api import ( list_workflows as api_list_workflows, + get_workflow as api_get_workflow, 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(client: PiperClient, pipeline_id: str) -> WorkflowDetail: + """获取单个工作流的完整配置(包含所有节点及参数)""" + return api_get_workflow(client, pipeline_id) + + +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_cmd(platform_id: str, pipeline_id: str) -> WorkflowDetail: + """CLI 便捷函数:自动获取 PiperClient 并查询工作流完整配置""" + with get_piper_client(platform_id) as client: + return get_workflow(client, pipeline_id) + + +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) + + + # ── 查询 ───────────────────────────────────────────────────── def list_workflows(