From edd727ca9c5aee69bdd27c9fd08179e5d1cf52ab Mon Sep 17 00:00:00 2001 From: lxp <2770281812@qq.com> Date: Fri, 9 Oct 2026 18:34:00 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 9 + README.md | 6 +- cadworld-adminapi/docs/admin-api.md | 3214 +++++++++++++++++ .../controller/ComponentAssetController.java | 4 + .../controller/ComponentController.java | 13 + .../controller/InterfaceBrepController.java | 3 + .../InterfaceDefinitionController.java | 8 + .../controller/InterfacePoseController.java | 4 + .../controller/OperationLogController.java | 4 + .../controller/UserManagementController.java | 7 + .../cadworld/logging/ApiRequestLog.java | 13 + .../logging/ApiRequestLogResponseAdvice.java | 31 + .../logging/ApiRequestLoggingFilter.java | 123 + .../src/main/resources/application-test.yml | 4 +- .../src/main/resources/application.yml | 2 + .../com/linkerbot/cadworld/AdminApiTest.java | 61 + .../linkerbot/cadworld/UploadHttpTest.java | 17 +- .../logging/ApiRequestLogCapture.java | 44 + .../logging/ApiRequestLoggingFilterTest.java | 81 + 19 files changed, 3641 insertions(+), 7 deletions(-) create mode 100644 AGENTS.md create mode 100644 cadworld-adminapi/docs/admin-api.md create mode 100644 cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLog.java create mode 100644 cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLogResponseAdvice.java create mode 100644 cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilter.java create mode 100644 cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLogCapture.java create mode 100644 cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilterTest.java diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..38aaa34 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,9 @@ +## 代码实现原则 +- 优先保证业务正确性、可维护性、可读性,再考虑炫技。 +- 修改代码时忽略.sql文件,如果遇到需要改表结构,直接发我sql。 +## 日志规范 +- 关键业务节点必须补充必要日志,方便线上排查。 +- 不要打印密码、Token、手机号、身份证、支付密钥等敏感信息。 +- 异常日志必须包含足够定位问题的信息。 +## 回复规范 +- 永远用中文回复。 \ No newline at end of file diff --git a/README.md b/README.md index b18c20e..9c8c1bb 100644 --- a/README.md +++ b/README.md @@ -64,10 +64,14 @@ java -jar cadworld-adminapi/target/cadworld-adminapi-0.0.1-SNAPSHOT.jar 资源通过后台上传和读取,无需客户端直连 MinIO。MinIO 实现首次使用时检查 bucket,不存在时尝试创建,因此账号需有对应权限。线上地址配置应包含实际域名及反向代理路径,上传和下载地址均使用 `/admin-api` 前缀。 -接口文档:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`/api-docs`。日志配置集中在 `cadworld-common`,按应用名输出 `cadworld-adminapi.log` 和独立的 `cadworld-adminapi-error.log`,并携带请求编号。普通日志按天及 100 MB 滚动,保留 30 天、最多 10 GB;ERROR 日志按天及 50 MB 滚动,保留 60 天、最多 5 GB。归档文件保存在 `logs/archive`(支持 `LOG_PATH` 覆盖)。测试环境项目包日志为 DEBUG,生产环境为 INFO。 +接口文档:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`/api-docs`。日志配置集中在 `cadworld-common`,按应用名输出 `cadworld-adminapi.log` 和独立的 `cadworld-adminapi-error.log`,并携带请求编号。普通日志按天及 100 MB 滚动,保留 30 天、最多 10 GB;ERROR 日志按天及 50 MB 滚动,保留 60 天、最多 5 GB。归档文件保存在 `logs/archive`(支持 `LOG_PATH` 覆盖)。测试环境项目包日志为 DEBUG,生产环境为 INFO;Mapper 日志保持 INFO,避免 SQL 参数输出敏感数据。 + +全部后台业务接口通过 `@ApiRequestLog` 提供中文说明,统一输出请求开始与结束日志,包含路由模板、请求编号、结果、HTTP 状态、业务错误码及耗时。成功记录 INFO,业务或参数失败记录 WARN,服务异常记录 ERROR。文件流上传、下载以及 MVC 之前的 multipart 超限也覆盖;不输出请求体、查询参数、文件内容或完整对象路径。接口运行日志写入运行日志文件;数据库操作日志继续按组件库和接口库写操作的既有范围记录。 ## 后台接口 +前端联调文档:[后台接口文档](cadworld-adminapi/docs/admin-api.md),按模块列出全部业务接口、入参及返回示例、上传流程和错误处理。 + 响应沿用 `{code, message, data, requestId}`,分页数据为 `{items, page, size, total}`。新建用户和操作日志列表的页码从 1 开始,默认每页 20,最多 100。 | 路径 | 方法及行为 | diff --git a/cadworld-adminapi/docs/admin-api.md b/cadworld-adminapi/docs/admin-api.md new file mode 100644 index 0000000..8d11506 --- /dev/null +++ b/cadworld-adminapi/docs/admin-api.md @@ -0,0 +1,3214 @@ +# cadworld 后台接口文档(前端联调用) + +适用模块:`cadworld-adminapi`。依据当前 Controller、请求 DTO、业务校验及实际响应编写,核对日期:2026-10-09。 + +- 本地默认服务地址:`http://127.0.0.1:8992`。 +- 业务接口前缀:`/admin-api`。旧 `/api/interfaces`、`/api/components` 不提供管理接口。 +- 测试环境 Swagger:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`http://127.0.0.1:8992/api-docs`。生产环境默认关闭文档页面。 +- 当前阶段不需要登录,也不需要 `Authorization` 请求头;操作人由服务端统一配置,默认 `0 / TEST_OPERATOR`。 +- 所有 ID、对象 Key、时间、URL、哈希和令牌均以实际接口返回为准。示例使用虚构名称和配置;`` 等为占位符,调用时替换为创建会话的返回值。 +- 示例中 JSON 可以直接作为结构参考;几何、文件内容、哈希、候选姿态 ID 必须来自同一组实际数据,不能混用不同文件或不同修订的示例值。 + +## 目录 + +1. [通用约定](#common) +2. [接口库管理](#interfaces) +3. [组件库管理及上传会话](#components) +4. [资源上传与下载](#assets) +5. [STEP 精确解析](#step) +6. [用户管理](#users) +7. [操作日志](#operation-logs) +8. [前端调用流程](#flows) +9. [错误处理](#errors) + + + +## 1. 通用约定 + +### 1.1 请求及响应 + +JSON 请求使用 `Content-Type: application/json`。文件接口分别使用 multipart 或原始文件流,详见对应接口。除文件接口外,所有成功返回均为 HTTP `200`,创建也不使用 `201`。 + +请求可以携带 `X-Request-Id`。服务端会将其放入响应头及 JSON 的 `requestId`;不传时自动生成。建议用于排查联调错误。 + +```json +{ + "code": "OK", + "message": "success", + "data": { + "success": true + }, + "requestId": "req-demo-001" +} +``` + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| code | string | 成功为 `OK`,失败为业务错误码 | +| message | string | 成功为 `success`;失败为提示信息,具体文字不保证固定 | +| data | object / array / string | 每个接口的数据类型不同,见对应示例 | +| requestId | string | 本次请求编号,与响应头 `X-Request-Id` 对应 | + +普通 DTO 的 `null` 字段默认不输出;失败响应通常没有 `data`。接口定义和 STEP 等 JSON 树响应中仍可能出现显式 `null`。前端应兼容字段缺省与 `null`,不要要求失败响应必须有 `data`。 + +资源上传成功返回 HTTP `204`,没有 JSON;资源下载成功返回文件内容,不使用上述响应封装。 + +### 1.2 分页与时间 + +```json +{ + "code": "OK", + "message": "success", + "data": { + "items": [], + "page": 1, + "size": 20, + "total": 0 + }, + "requestId": "req-demo-001" +} +``` + +组件、用户和操作日志列表使用 `items / page / size / total`;`page` 从 1 开始,默认 1;`size` 默认 20,超过 100 按 100 处理。前端传正整数,用户和日志接口会对非正数返回 `422`。接口库列表不分页,`data` 直接为数组。 + +时间使用 ISO 本地时间,例如 `2026-10-09T17:00:00.123`,不带 `Z` 或时区偏移。日志时间及服务端维护的创建/更新时间按上海时区处理。 + +### 1.3 几何单位 + +| 数据 | 单位或顺序 | +| --- | --- | +| 接口定义和端口中的 `positionM`、`pointM`、`pointOnPlaneM`、`diameterM` | 米 | +| 接口容差及候选误差中的 `*AngleRad` | 弧度 | +| `normal`、`axis`、`outwardNormal`、`displayForward` | 三维方向向量,后端归一化;不得为零向量 | +| `quaternionXYZW` | 四元数顺序 `[x, y, z, w]` | +| STEP 返回的 `*Mm`、`areaMm2` | 毫米、平方毫米 | +| `assemblyMetadata.dimensions.*Mm` | 毫米 | + +STEP 点坐标转换到接口几何前,乘以返回的 `scaleToMeters`,当前为 `0.001`。 + +### 1.4 接口运行日志 + +全部 29 个业务接口均记录运行日志,包含接口的中文说明、HTTP 方法、路由模板、请求编号、处理结果、HTTP 状态、业务错误码和耗时。查询、用户管理、文件下载、STEP 解析和姿态计算也记录运行日志;第 7 节数据库操作日志的记录范围仍按原规则执行。 + +```text +接口开始 description=查询用户列表 method=GET path=/admin-api/users requestId=req-demo-001 +接口结束 description=查询用户列表 method=GET path=/admin-api/users requestId=req-demo-001 result=SUCCESS httpStatus=200 code=OK durationMs=8 exceptionType=- +``` + +成功请求的开始和结束日志为 INFO;参数校验或业务失败的结束日志为 WARN;服务端错误或请求处理中抛出的未处理异常为 ERROR。文件流接口没有 JSON 业务错误码时,使用 `HTTP_204`、`HTTP_200` 等状态标识。文件流已开始发送后发生异常时,日志可能同时显示原 HTTP 状态和 `result=FAILURE`,需结合异常类型及请求编号排查。 + +路由只输出模板,例如 `/admin-api/users/{id}`、`/admin-api/component-assets/**`,不输出请求体、查询关键词、手机号、上传令牌、文件内容或完整文件路径。测试环境的 Mapper 日志保持 INFO,不输出 SQL 参数。向后端反馈问题时提供响应头或 JSON 中的 `requestId`,用于关联运行日志和业务操作日志。 + + + +## 2. 接口库管理 + +这里的“接口”指机械安装接口模板。接口定义 ID 是字符串,例如 `mount-2-hole`。 + +| 方法 | 路径 | 功能 | +| --- | --- | --- | +| GET | `/admin-api/interfaces` | 列表及关键词搜索 | +| GET | `/admin-api/interfaces/{id}` | 详情 | +| POST | `/admin-api/interfaces` | 新增 | +| PUT | `/admin-api/interfaces/{id}` | 修改 | +| DELETE | `/admin-api/interfaces/{id}` | 删除 | +| POST | `/admin-api/interfaces/{id}/assets` | 绑定源文件 | +| POST | `/admin-api/interfaces/{id}/pose-candidates` | 计算候选姿态 | +| POST | `/admin-api/interfaces/{id}/confirm-port` | 确认组件端口姿态 | + +### 2.1 接口定义字段 + +| 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| id | string | 创建时是 | 唯一且非空;建议不超过 64 字符;修改以路径 ID 为准 | +| name | string | 是 | 非空,建议不超过 128 字符 | +| description | string | 否 | 默认空串,建议不超过 500 字符 | +| geometry | object | 是 | 安装平面与完整孔组,见下表 | +| tolerances | object | 是 | 三个容差必须提供正值 | +| displayForward | number[3] | 否 | 安装面内的默认前方;不传则服务端生成,不能平行于面法向 | +| connectableTargets | string[] | 否 | 可连接目标路径,一维字符串数组;例如 `["机械臂/末端工具", "移动底盘/附件"]` | +| geometryRevision | integer | 修改时是 | 详情返回的当前修订号;创建自动为 1 | +| sourceAssetKey | string | 否 | 源文件上传后返回的存储 Key;前端不能通过保存定义直接绑定文件 | +| sourceGeometryHash | string | 否 | 已绑定源文件的 SHA-256,通常带 `sha256:`;源文件变更时可随保存传入新哈希以清除旧绑定,最终绑定由上传源文件接口完成 | + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| geometry.plane.pointM | number[3] | 平面上的一点,米 | +| geometry.plane.outwardNormal | number[3] | 安装面的向外法向 | +| geometry.holes | object[] | 至少两个不同孔位,必须提供完整孔组 | +| geometry.holes[].id | string | 同一孔组内唯一且非空 | +| geometry.holes[].pointOnPlaneM | number[3] | 孔轴与安装面的交点,米 | +| geometry.holes[].axis | number[3] | 孔轴方向,必须穿过安装面 | +| geometry.holes[].diameterM | number | 可选;提供时必须为正数,单位米 | +| tolerances.positionM | number | 位置容差,正数;示例 0.0002 m = 0.2 mm | +| tolerances.axisAngleRad | number | 孔轴角度容差,范围 `(0, π/2)` | +| tolerances.planeAngleRad | number | 平面角度容差,范围 `(0, π/2)` | + +后端归一化法向和孔轴、校正允许容差内的孔交点,并按孔 ID 排序。不要依赖提交孔数组的原始顺序。 + +不支持旧结构字段 `profiles`、`mateRules`、`frameInComponent`、`allowedClockingDeg`、`xAxisAngleDeg`。端口计算及确认使用本文的 `geometryInLink / selectedPose` 结构。 + +### 2.2 查询接口列表 + + + +`GET /admin-api/interfaces` + +| Query 参数 | 必填 | 说明 | +| --- | --- | --- | +| keyword | 否 | 按名称或描述模糊搜索;省略时返回全部,按更新时间倒序 | + +**请求示例** + +```http +GET /admin-api/interfaces?keyword=双孔 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": [ + { + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "孔距 40 mm,孔径 4 mm", + "geometryRevision": 1, + "geometry": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "displayForward": [ + 1.0, + 0.0, + 0.0 + ], + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ] + } + ], + "requestId": "req-demo-001" +} +``` + +### 2.3 查询接口详情 + + + +`GET /admin-api/interfaces/{id}` + +路径参数 `id`:接口定义字符串 ID。 + +**请求示例** + +```http +GET /admin-api/interfaces/mount-2-hole HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "孔距 40 mm,孔径 4 mm", + "geometryRevision": 1, + "geometry": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "displayForward": [ + 1.0, + 0.0, + 0.0 + ], + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ] + }, + "requestId": "req-demo-001" +} +``` + +### 2.4 新增接口 + + + +`POST /admin-api/interfaces` + +请求字段见 2.1。ID 不可与已有定义或已删除定义的历史 ID 重复。 + +**请求示例** + +```http +POST /admin-api/interfaces HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "孔距 40 mm,孔径 4 mm", + "geometry": { + "plane": { + "pointM": [ + 0, + 0, + 0 + ], + "outwardNormal": [ + 0, + 0, + 1 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + } + ] + }, + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "displayForward": [ + 1, + 0, + 0 + ], + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ] +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "孔距 40 mm,孔径 4 mm", + "geometryRevision": 1, + "geometry": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "displayForward": [ + 1.0, + 0.0, + 0.0 + ], + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ] + }, + "requestId": "req-demo-001" +} +``` + +### 2.5 修改接口 + + + +`PUT /admin-api/interfaces/{id}` + +请求字段见 2.1,必须携带当前 `geometryRevision`,并提交完整定义。省略描述、目标或展示方向可能将其恢复为空值/默认值。 + +**请求示例** + +```http +PUT /admin-api/interfaces/mount-2-hole HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "更新后的接口说明", + "geometry": { + "plane": { + "pointM": [ + 0, + 0, + 0 + ], + "outwardNormal": [ + 0, + 0, + 1 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + } + ] + }, + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "displayForward": [ + 1, + 0, + 0 + ], + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ], + "geometryRevision": 1 +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "更新后的接口说明", + "geometryRevision": 2, + "geometry": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "displayForward": [ + 1.0, + 0.0, + 0.0 + ], + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ], + "sourceAssetKey": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/plate.step", + "sourceGeometryHash": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7" + }, + "requestId": "req-demo-001" +} +``` + +示例从修订 1 更新为 2。修改名称、描述、孔组、容差或可连接目标等会产生新修订;仅展示方向变化且其他内容不变时通常保留修订号。始终以响应为准。 + +旧修订仍保留历史快照。修订号不匹配返回 `422 / INVALID_INTERFACE`;前端应重新查询详情,再提示用户重新确认修改。引用旧修订的组件端口,在下一次保存组件时需要重新计算并确认。 + +### 2.6 删除接口 + + + +`DELETE /admin-api/interfaces/{id}` + +删除当前定义,保留历史快照。删除后的 ID 不可重新创建;删除接口不会清理存储中的源文件。 + +**请求示例** + +```http +DELETE /admin-api/interfaces/mount-2-hole HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "success": true + }, + "requestId": "req-demo-001" +} +``` + +### 2.7 上传并绑定接口源文件 + + + +`POST /admin-api/interfaces/{id}/assets` + +| 位置 | 字段 | 必填 | 说明 | +| --- | --- | --- | --- | +| Path | id | 是 | 已创建的接口定义 ID | +| Query | geometryRevision | 是 | 当前修订号 | +| multipart | file | 是 | 非空原始文件;通常为 STEP/STP | + +先保存接口定义,再上传源文件。后端校验修订号,计算文件 SHA-256,并更新当前修订的源文件绑定。该接口本身不执行 STEP 解析或校验文件拓扑;需要精确解析时先调用第 5 节接口。 + +单个文件和整个 multipart 请求默认均限制 100 MB;边界开销也占请求大小。当前修订已有不同内容的源文件时,绑定会被拒绝,应按源文件变更流程先保存新修订。 + +**请求示例** + +```bash +curl -X POST 'http://127.0.0.1:8992/admin-api/interfaces/mount-2-hole/assets?geometryRevision=1' \ + -H 'X-Request-Id: req-demo-001' \ + -F 'file=@./plate.step' +``` + +浏览器使用 `FormData`,字段名为 `file`;不要手动设置 multipart 的 `Content-Type`,让浏览器生成 boundary。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/plate.step", + "requestId": "req-demo-001" +} +``` + +成功 `data` 是对象 Key 字符串,不是 URL。再调用接口详情可获得 `sourceAssetKey` 和 `sourceGeometryHash`。源文件可通过 `/admin-api/component-assets/{objectKey}` 下载,对象路径各段需要 URL 编码。 + +**上传后的详情示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": "mount-2-hole", + "name": "双孔安装接口", + "description": "孔距 40 mm,孔径 4 mm", + "geometryRevision": 1, + "geometry": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "displayForward": [ + 1.0, + 0.0, + 0.0 + ], + "tolerances": { + "positionM": 0.0002, + "axisAngleRad": 0.017453292519943295, + "planeAngleRad": 0.017453292519943295 + }, + "connectableTargets": [ + "机械臂/末端工具", + "移动底盘/附件" + ], + "sourceAssetKey": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/plate.step", + "sourceGeometryHash": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7" + }, + "requestId": "req-demo-001" +} +``` + +### 2.8 计算姿态候选 + + + +`POST /admin-api/interfaces/{id}/pose-candidates` + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| definitionRevision | integer | 是 | 使用的模板修订号 | +| linkName | string | 是 | 端口所属原始 URDF link | +| geometryInLink | object | 是 | 实测安装面和完整孔组;与 `geometry` 结构一致,坐标位于该 link 的局部坐标系 | +| sourceGeometryHash | string | 是 | 原始 URDF 和资源清单形成的源几何哈希,算法见 8.3 | + +**请求示例** + +```http +POST /admin-api/interfaces/mount-2-hole/pose-candidates HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "definitionRevision": 1, + "linkName": "base_link", + "geometryInLink": { + "plane": { + "pointM": [ + 0, + 0, + 0 + ], + "outwardNormal": [ + 0, + 0, + 1 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + } + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "solverVersion": "mount-geometry-3", + "candidates": [ + { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ], + "registrationSide": 1, + "maxHoleOffsetM": 0.0, + "rmsHoleOffsetM": 0.0, + "maxAxisAngleRad": 0.0 + }, + { + "id": "f2fb42e5f5f75f7ec7491ce6dadc61717543d1f38453d95517a1955e86a06c82", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 1.0, + 0.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h2" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h1" + } + ], + "orientationDirectionInLink": [ + -1.0, + 0.0, + 0.0 + ], + "registrationSide": 1, + "maxHoleOffsetM": 0.0, + "rmsHoleOffsetM": 0.0, + "maxAxisAngleRad": 0.0 + } + ], + "reasons": [] + }, + "requestId": "req-demo-001" +} +``` + +| 候选字段 | 说明 | +| --- | --- | +| id | 候选的稳定标识;必须使用当前响应中的值 | +| templateInLink.positionM | 模板坐标系原点在 link 中的位置,米 | +| templateInLink.quaternionXYZW | 模板坐标系到 link 的旋转 | +| holeMapping | 模板孔 ID 与实测孔 ID 的对应 | +| orientationDirectionInLink | 默认前方映射到 link 后的方向 | +| registrationSide | 匹配侧别,为 `1` 或 `-1` | +| maxHoleOffsetM / rmsHoleOffsetM | 最大/均方根孔位误差,米 | +| maxAxisAngleRad | 最大孔轴角度误差,弧度 | + +候选可能不唯一,由前端展示并让用户选择。几何结构合法但无法匹配时仍返回 HTTP `200 / OK`,此时 `candidates` 为空,应展示 `reasons`,并返回几何确认流程。 + +**无法匹配的返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "solverVersion": "mount-geometry-3", + "candidates": [], + "reasons": [ + "孔 h1 的孔距组合与模板不符,请核对该孔及完整孔组", + "孔 h2 的孔距组合与模板不符,请核对该孔及完整孔组" + ] + }, + "requestId": "req-demo-001" +} +``` + +### 2.9 确认端口姿态 + + + +`POST /admin-api/interfaces/{id}/confirm-port` + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| id | string | 是 | 组件端口 ID,同一组件内唯一 | +| linkName | string | 是 | 所属原始 link 名称 | +| definitionId | string | 是 | 必须与 URL 的接口 ID 相同 | +| definitionRevision | integer | 是 | 对应模板修订号 | +| geometryInLink | object | 是 | 与计算候选时一致的实测几何 | +| selectedPose | object | 是 | 至少提供当前候选 `id`;建议同时复制候选的姿态、孔映射和方向字段 | +| sourceGeometryHash | string | 是 | 与计算候选时一致的 URDF 源几何哈希 | +| solverVersion | string | 是 | 复制候选集返回值,当前为 `mount-geometry-3` | +| connectableTargets | array | 否 | 不传或为空时使用模板目标;多目标建议采用二维路径数组,见下文 | + +**请求示例** + +```http +POST /admin-api/interfaces/mount-2-hole/confirm-port HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0, + 0, + 0 + ], + "outwardNormal": [ + 0, + 0, + 1 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + [ + "机械臂", + "末端工具" + ] + ] +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + "机械臂/末端工具" + ] + }, + "requestId": "req-demo-001" +} +``` + +服务端依据候选 `id` 重新计算,返回规范化端口;提交的旋转和孔映射不会作为最终可信结果。该接口只计算和确认,不自动保存组件。 + +**可连接目标的输入兼容规则**:接口定义 CRUD 使用一维路径字符串数组;`confirm-port` 和 `componentJson.interfaces` 会把一维字符串数组视为“一条级联路径”,例如 `["机械臂", "末端工具"]` 被合并为 `"机械臂/末端工具"`。多个目标请提交二维数组,例如 `[["机械臂", "末端工具"], ["移动底盘", "附件"]]`。返回统一为一维路径字符串数组。将确认结果用于保存组件时,多目标应先转换为二维数组,避免被合并为一条路径。 + + + +## 3. 组件库管理及上传会话 + +组件 ID 为数值型。新增、修改均需完整提交必填字段。 + +| 方法 | 路径 | 功能 | +| --- | --- | --- | +| GET | `/admin-api/components` | 分页搜索 | +| GET | `/admin-api/components/{id}` | 详情 | +| POST | `/admin-api/components` | 新增 | +| PUT | `/admin-api/components/{id}` | 修改 | +| DELETE | `/admin-api/components/{id}` | 删除 | +| POST | `/admin-api/components/cover-image-upload-sessions` | 创建封面会话 | +| POST | `/admin-api/components/cover-image-upload-sessions/upload-url` | 获取封面上传地址 | +| POST | `/admin-api/components/cover-image-upload-sessions/complete` | 完成封面上传 | +| POST | `/admin-api/components/urdf-upload-sessions` | 创建 URDF/RFS 会话 | +| POST | `/admin-api/components/urdf-upload-sessions/upload-url` | 获取单文件上传地址 | +| POST | `/admin-api/components/urdf-upload-sessions/complete` | 完成 URDF/RFS 上传 | + +### 3.1 组件请求与响应字段 + +| Body 字段 | 类型 | 必填 | 限制或说明 | +| --- | --- | --- | --- | +| componentName | string | 是 | 非空、最多 64 字符,名称不可重复 | +| category | string | 否 | 最多 64 字符,自由填写分类;当前字段名为 `category`,不是 `componentType` | +| robotType | string | 是 | 非空、最多 32 字符;当前不是后端枚举,例如 `humanoid` | +| company | string | 是 | 非空、最多 64 字符 | +| model | string | 是 | 非空、最多 64 字符 | +| source | string | 是 | 非空、最多 255 字符;使用完成 URDF/RFS 上传返回的对象 Key,不填下载 URL | +| coverImageKey | string | 否 | 最多 512 字符;使用完成封面上传返回的 Key | +| description | string | 否 | 组件说明 | +| componentJson | object | 是 | 组件模型数据与端口;无端口可先传 `{ "interfaces": [] }` | +| assemblyMetadata | object | 是 | 检索用的语义元数据,见下表 | + +| assemblyMetadata 字段 | 类型 | 说明 | +| --- | --- | --- | +| tags | string[] | 标签;可为空,省略归一化为 `[]`,空白和重复项会被整理 | +| capabilities | string[] | 能力标签;可为空,省略归一化为 `[]` | +| dimensions | object | 尺寸;可为空对象,省略归一化为 `{}` | +| dimensions.lengthMm / widthMm / heightMm | number | 可选;提供时必须大于 0,单位毫米 | + +服务端会将能力及分类信息合并到返回的标签中。详情响应额外包含 `id`、`sourceUrl`、`coverImageUrl`、`createdAt`、`updatedAt`;这些不是保存时必须传入的字段。`sourceUrl` 和 `coverImageUrl` 已由后端生成,用于读取资源。 + +列表返回基础信息和 `assemblyMetadata`,不包含 `componentJson`、`coverImageKey`。详情、新增和修改响应包含完整组件。可选文本为空时通常返回空字符串。 + +`componentJson.interfaces` 非空时,必须同时提供原始 `urdfSource` 快照、资源清单以及已经确认的端口。后端会核对源文件资源、link、源哈希、模板当前修订和选中候选;不能只填端口名称和坐标。详见 8.3。 + +每次成功新增/修改会由后端写入或递增 `componentJson.componentRevision`。存在 `interfaces` 数组时会返回 `interfaceSchemaVersion: 3`;前端不自行生成这些版本值。 + +### 3.2 查询组件列表 + + + +`GET /admin-api/components` + +| Query 参数 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| page | integer | 否 | 默认 1,请传正整数 | +| size | integer | 否 | 默认 20,上限 100,请传正整数 | +| keyword | string | 否 | 搜索组件名称、分类、标签和能力;当前不搜索厂商及型号 | + +**请求示例** + +```http +GET /admin-api/components?page=1&size=20 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "items": [ + { + "id": 1, + "componentName": "双孔安装底座", + "category": "安装件", + "robotType": "humanoid", + "company": "示例厂商", + "model": "BASE-001", + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "sourceUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "coverImageUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "description": "双孔固定底座", + "assemblyMetadata": { + "tags": [ + "安装件", + "底座", + "固定安装" + ], + "capabilities": [ + "固定安装" + ], + "dimensions": { + "lengthMm": 80.0, + "widthMm": 50.0, + "heightMm": 10.0 + } + }, + "createdAt": "2026-10-09T17:10:24.926", + "updatedAt": "2026-10-09T17:10:24.926" + } + ], + "page": 1, + "size": 20, + "total": 1 + }, + "requestId": "req-demo-001" +} +``` + +搜索示例:`GET /admin-api/components?page=1&size=20&keyword=底座`;查询字符串使用 URL 编码。结果按更新时间倒序。 + +### 3.3 查询组件详情 + + + +`GET /admin-api/components/{id}` + +路径参数 `id`:数值型组件 ID。 + +**请求示例** + +```http +GET /admin-api/components/1 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 1, + "componentName": "双孔安装底座", + "category": "安装件", + "robotType": "humanoid", + "company": "示例厂商", + "model": "BASE-001", + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "sourceUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "coverImageKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "coverImageUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "description": "双孔固定底座", + "componentJson": { + "urdfSource": { + "xml": "", + "documentHash": "7fa86878484ac25bb466ba4f49e095caf6df3f3ab1a4234ee423a6aba6277a7a", + "resources": [], + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" + }, + "interfaces": [ + { + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + "机械臂/末端工具" + ] + } + ], + "interfaceSchemaVersion": 3, + "componentRevision": 1 + }, + "assemblyMetadata": { + "tags": [ + "安装件", + "底座", + "固定安装" + ], + "capabilities": [ + "固定安装" + ], + "dimensions": { + "lengthMm": 80.0, + "widthMm": 50.0, + "heightMm": 10.0 + } + }, + "createdAt": "2026-10-09T17:10:24.926", + "updatedAt": "2026-10-09T17:10:24.926" + }, + "requestId": "req-demo-001" +} +``` + +### 3.4 新增组件 + + + +`POST /admin-api/components` + +请求字段见 3.1。示例展示带已确认端口的完整保存结构;没有端口时可以将 `componentJson` 简化为 `{ "interfaces": [] }`。 + +**请求示例** + +```http +POST /admin-api/components HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "componentName": "双孔安装底座", + "category": "安装件", + "robotType": "humanoid", + "company": "示例厂商", + "model": "BASE-001", + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "coverImageKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "description": "双孔固定底座", + "componentJson": { + "urdfSource": { + "xml": "", + "documentHash": "7fa86878484ac25bb466ba4f49e095caf6df3f3ab1a4234ee423a6aba6277a7a", + "resources": [], + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" + }, + "interfaces": [ + { + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + [ + "机械臂", + "末端工具" + ] + ] + } + ] + }, + "assemblyMetadata": { + "tags": [ + "安装件", + "底座" + ], + "capabilities": [ + "固定安装" + ], + "dimensions": { + "lengthMm": 80, + "widthMm": 50, + "heightMm": 10 + } + } +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 1, + "componentName": "双孔安装底座", + "category": "安装件", + "robotType": "humanoid", + "company": "示例厂商", + "model": "BASE-001", + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "sourceUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "coverImageKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "coverImageUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "description": "双孔固定底座", + "componentJson": { + "urdfSource": { + "xml": "", + "documentHash": "7fa86878484ac25bb466ba4f49e095caf6df3f3ab1a4234ee423a6aba6277a7a", + "resources": [], + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" + }, + "interfaces": [ + { + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + "机械臂/末端工具" + ] + } + ], + "interfaceSchemaVersion": 3, + "componentRevision": 1 + }, + "assemblyMetadata": { + "tags": [ + "安装件", + "底座", + "固定安装" + ], + "capabilities": [ + "固定安装" + ], + "dimensions": { + "lengthMm": 80.0, + "widthMm": 50.0, + "heightMm": 10.0 + } + }, + "createdAt": "2026-10-09T17:10:24.926", + "updatedAt": "2026-10-09T17:10:24.926" + }, + "requestId": "req-demo-001" +} +``` + +### 3.5 修改组件 + + + +`PUT /admin-api/components/{id}` + +请求字段同新增。使用完整必填字段;省略分类、封面和描述会将这些可选文本重置为空。 + +**请求示例** + +```http +PUT /admin-api/components/1 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "componentName": "双孔安装底座 V2", + "category": "安装件", + "robotType": "humanoid", + "company": "示例厂商", + "model": "BASE-001", + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "coverImageKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "description": "更新后的组件说明", + "componentJson": { + "urdfSource": { + "xml": "", + "documentHash": "7fa86878484ac25bb466ba4f49e095caf6df3f3ab1a4234ee423a6aba6277a7a", + "resources": [], + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" + }, + "interfaces": [ + { + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + [ + "机械臂", + "末端工具" + ] + ] + } + ] + }, + "assemblyMetadata": { + "tags": [ + "安装件", + "底座" + ], + "capabilities": [ + "固定安装" + ], + "dimensions": { + "lengthMm": 80, + "widthMm": 50, + "heightMm": 10 + } + } +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 1, + "componentName": "双孔安装底座 V2", + "category": "安装件", + "robotType": "humanoid", + "company": "示例厂商", + "model": "BASE-001", + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "sourceUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "coverImageKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "coverImageUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "description": "更新后的组件说明", + "componentJson": { + "urdfSource": { + "xml": "", + "documentHash": "7fa86878484ac25bb466ba4f49e095caf6df3f3ab1a4234ee423a6aba6277a7a", + "resources": [], + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" + }, + "interfaces": [ + { + "id": "port-1", + "linkName": "base_link", + "definitionId": "mount-2-hole", + "definitionRevision": 1, + "geometryInLink": { + "plane": { + "pointM": [ + 0.0, + 0.0, + 0.0 + ], + "outwardNormal": [ + 0.0, + 0.0, + 1.0 + ] + }, + "holes": [ + { + "id": "h1", + "pointOnPlaneM": [ + -0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + }, + { + "id": "h2", + "pointOnPlaneM": [ + 0.02, + 0.0, + 0.0 + ], + "axis": [ + 0.0, + 0.0, + 1.0 + ], + "diameterM": 0.004 + } + ] + }, + "selectedPose": { + "id": "fc9c1d72317f9890f0969552f3f73ad9df5f7b6bc5756d7e58963888a25ff4c1", + "templateInLink": { + "positionM": [ + 0.0, + 0.0, + 0.0 + ], + "quaternionXYZW": [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + }, + "holeMapping": [ + { + "templateHoleId": "h1", + "observedHoleId": "h1" + }, + { + "templateHoleId": "h2", + "observedHoleId": "h2" + } + ], + "orientationDirectionInLink": [ + 1.0, + 0.0, + 0.0 + ] + }, + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f", + "solverVersion": "mount-geometry-3", + "connectableTargets": [ + "机械臂/末端工具" + ] + } + ], + "interfaceSchemaVersion": 3, + "componentRevision": 2 + }, + "assemblyMetadata": { + "tags": [ + "安装件", + "底座", + "固定安装" + ], + "capabilities": [ + "固定安装" + ], + "dimensions": { + "lengthMm": 80.0, + "widthMm": 50.0, + "heightMm": 10.0 + } + }, + "createdAt": "2026-10-09T17:10:24.926", + "updatedAt": "2026-10-09T17:10:24.957" + }, + "requestId": "req-demo-001" +} +``` + +### 3.6 删除组件 + + + +`DELETE /admin-api/components/{id}` + +物理删除组件及关联资源索引,不删除 MinIO 中已经上传的对象。 + +**请求示例** + +```http +DELETE /admin-api/components/1 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "success": true + }, + "requestId": "req-demo-001" +} +``` + +### 3.7 上传会话通用规则 + +- 先创建会话,再为每个文件获取上传 URL,随后向 URL 发起原始文件流 PUT,最后提交对象 Key 列表完成上传。 +- 会话默认有效期 30 分钟;创建会话只返回 `uploadSessionToken / keyPrefix`,不返回 `expiresAt`。令牌过期或服务端临时密钥因重启变化时,重新创建会话。 +- `keyPrefix` 是服务端生成的完整前缀;不要自己拼操作人、日期或 UUID。 +- `objectPath` 是相对路径,例如 `robot.urdf`、`meshes/base.stl`;不能以 `/` 开头或结尾,不能包含空路径段、`.` 或 `..`。建议统一使用 `/`。 +- 获取 URL 时 `objectPath` 最多 512 字符、`contentType` 最多 255 字符;拼接后的完整对象 Key 也不得超过 512 字符。 +- `objectKeys` 必须是获取上传地址时返回的完整 Key,属于同一会话且已经上传,不可重复;不能提交 URL 或仅文件名。 +- 上传会话令牌放在获取 URL、完成上传的 JSON 请求体中;它不是 `Authorization` 登录令牌,也不需要添加到返回的上传 URL。 +- 完成上传仅校验文件并返回可保存字段,不自动创建或修改组件。 + +### 3.8 创建封面上传会话 + + + +`POST /admin-api/components/cover-image-upload-sessions` + +**请求示例** + +```http +POST /admin-api/components/cover-image-upload-sessions HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "uploadSessionToken": "", + "keyPrefix": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/" + }, + "requestId": "req-demo-001" +} +``` + +### 3.9 获取封面文件上传地址 + + + +`POST /admin-api/components/cover-image-upload-sessions/upload-url` + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| uploadSessionToken | string | 是 | 本类型创建会话的返回值 | +| objectPath | string | 是 | 当前会话中的相对文件路径 | +| contentType | string | 否 | 文件 MIME 类型,建议与实际 PUT 请求保持一致 | + +**请求示例** + +```http +POST /admin-api/components/cover-image-upload-sessions/upload-url HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "uploadSessionToken": "", + "objectPath": "cover.png", + "contentType": "image/png" +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "uploadUrl": "http://127.0.0.1:8992/admin-api/component-assets/upload?objectKey=components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "objectKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png" + }, + "requestId": "req-demo-001" +} +``` + +取得 URL 后按第 4.1 节上传文件,收到 `204` 再调用完成上传接口。 + +### 3.10 完成封面上传 + + + +`POST /admin-api/components/cover-image-upload-sessions/complete` + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| uploadSessionToken | string | 是 | 创建会话返回值 | +| objectKeys | string[] | 是 | 已上传的完整对象 Key;必须恰好 1 个 | + +封面扩展名支持 `.jpg`、`.jpeg`、`.png`、`.webp`、`.gif`,不区分大小写。完成后将 `coverImageKey` 用于保存组件,`coverImageUrl` 用于预览。 + +**请求示例** + +```http +POST /admin-api/components/cover-image-upload-sessions/complete HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "uploadSessionToken": "", + "objectKeys": [ + "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png" + ] +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "coverImageKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png", + "coverImageUrl": "http://127.0.0.1:8992/admin-api/component-assets/components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png" + }, + "requestId": "req-demo-001" +} +``` + +### 3.11 创建 URDF/RFS 上传会话 + + + +`POST /admin-api/components/urdf-upload-sessions` + +**请求示例** + +```http +POST /admin-api/components/urdf-upload-sessions HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "uploadSessionToken": "", + "keyPrefix": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/" + }, + "requestId": "req-demo-001" +} +``` + +### 3.12 获取 URDF/RFS 文件上传地址 + + + +`POST /admin-api/components/urdf-upload-sessions/upload-url` + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| uploadSessionToken | string | 是 | 本类型创建会话的返回值 | +| objectPath | string | 是 | 当前会话中的相对文件路径 | +| contentType | string | 否 | 文件 MIME 类型,建议与实际 PUT 请求保持一致 | + +**请求示例** + +```http +POST /admin-api/components/urdf-upload-sessions/upload-url HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "uploadSessionToken": "", + "objectPath": "robot.urdf", + "contentType": "application/xml" +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "uploadUrl": "http://127.0.0.1:8992/admin-api/component-assets/upload?objectKey=components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf", + "objectKey": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf" + }, + "requestId": "req-demo-001" +} +``` + +取得 URL 后按第 4.1 节上传文件,收到 `204` 再调用完成上传接口。 + +### 3.13 完成 URDF/RFS 上传 + + + +`POST /admin-api/components/urdf-upload-sessions/complete` + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| uploadSessionToken | string | 是 | 创建会话返回值 | +| objectKeys | string[] | 是 | 已上传的完整对象 Key;1~1000 个,不可重复 | + +所有模型、网格、纹理等文件上传完毕后一起提交。必须恰好包含一个主文件:`.urdf`、`.rfs` 或 `.rfs.json`。URDF 和 RFS 不能同时存在,同类主文件也不能超过一个。资源文件可以有多个,并应保持相对目录结构。 + +返回 `source` 是主文件对象 Key,最长 255 字符;用于新增或修改组件。此接口不解析或返回完整 `componentJson`,前端仍需根据模型准备保存数据。 + +**请求示例** + +```http +POST /admin-api/components/urdf-upload-sessions/complete HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "uploadSessionToken": "", + "objectKeys": [ + "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf" + ] +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "source": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf" + }, + "requestId": "req-demo-001" +} +``` + + + +## 4. 资源上传与下载 + +这些接口通过后台读写 MinIO,前端不需要 MinIO Access Key、Secret Key 或直连存储桶。 + +### 4.1 上传原始文件流 + + + +`PUT /admin-api/component-assets/upload` + +| 位置 | 字段 | 必填 | 说明 | +| --- | --- | --- | --- | +| Query | objectKey | 是 | 获取上传地址返回的完整对象 Key;应直接使用返回的 `uploadUrl` | +| Header | Content-Type | 否 | 真实文件 MIME 类型;省略时按通用二进制类型处理 | +| Body | 文件二进制 | 是 | 直接发送 File/Blob/ArrayBuffer;不用 FormData,不做 JSON 或 Base64 包装 | + +**请求示例** + +```bash +curl -X PUT \ + 'http://127.0.0.1:8992/admin-api/component-assets/upload?objectKey=components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf' \ + -H 'Content-Type: application/xml' \ + -H 'X-Request-Id: req-demo-001' \ + --data-binary '@./robot.urdf' +``` + +**成功返回示例** + +```http +HTTP/1.1 204 No Content +X-Request-Id: req-demo-001 +``` + +响应体为空,不执行 `response.json()`。失败时仍按第 9 节处理 JSON 错误响应。当前应用只允许写入配置操作人的组件资源目录;接口源文件通过第 2.7 节上传。 + +这里的 PUT 是原始文件流,Spring multipart 的 100 MB 限制不直接作用于此接口;实际大小还可能受到部署网关限制,前端应与部署环境保持一致。 + +### 4.2 下载或读取资源 + + + +`GET /admin-api/component-assets/{objectKey}` + +`objectKey` 表示包含多级 `/` 的完整对象路径,不只是最后一个文件名。通常直接使用组件详情返回的 `sourceUrl / coverImageUrl`。 + +**请求示例** + +```http +GET /admin-api/component-assets/components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例** + +```http +HTTP/1.1 200 OK +Content-Type: application/xml +Cache-Control: public, max-age=3600 +X-Request-Id: req-demo-001 + + +``` + +图片等文件返回对应 MIME 类型和二进制内容,服务端在知道大小时返回 `Content-Length`。读取时使用 `text()`、`blob()` 或 `arrayBuffer()`,不要统一按 JSON 解析。资源不存在时返回 JSON 错误响应,例如 `404 / MINIO_OBJECT_NOT_FOUND`。 + +如需从 Key 手动拼路径,对每个路径段编码后用 `/` 连接;不要把整个带斜杠的路径当作一个普通路径段。 + + + +## 5. STEP 精确解析 + +### 5.1 分析 STEP/STP + + + +`POST /admin-api/interface-brep/analyze` + +| 位置 | 字段 | 必填 | 说明 | +| --- | --- | --- | --- | +| multipart | file | 是 | 非空 `.step` 或 `.stp` 文件,扩展名不区分大小写;不接受 STL | + +默认单文件及整个 multipart 请求上限均为 100 MB;默认解析超时 120 秒、输出上限 100 MB。该接口只返回解析数据,不创建接口定义,也不绑定或永久保存上传文件。 + +**请求示例** + +```bash +curl -X POST 'http://127.0.0.1:8992/admin-api/interface-brep/analyze' \ + -H 'X-Request-Id: req-demo-001' \ + -F 'file=@./box.step' +``` + +浏览器使用 FormData;不要手动指定 multipart boundary。前端 HTTP 超时应略大于服务端解析超时。 + +以下响应是实际生成的盒体 STEP 的**结构节选**:只保留一个面、一条边,并截取少量显示采样和三角网格。实际响应返回完整数组;`faceCount / edgeCount` 是完整模型计数。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "schemaVersion": "interface-step-brep/v1", + "sourceName": "source.step", + "sourceSha256": "073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7", + "sourceUnits": "mm", + "scaleToMeters": 0.001, + "kernel": "OCCT 7.8", + "triangulationPurpose": "display-and-picking-only", + "linearDeflectionMm": 0.2, + "displayMeshSimplificationPasses": 0, + "faceCount": 6, + "edgeCount": 12, + "faces": [ + { + "id": "brep:face:1", + "sourceRef": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7:face:1", + "surfaceType": "plane", + "isPlanar": true, + "normal": [ + -1.0, + -0.0, + 0.0 + ], + "planeLocationMm": [ + 0.0, + 0.0, + 0.0 + ], + "xDirection": [ + 0.0, + 0.0, + 1.0 + ], + "pointMm": [ + 0.0, + 10.0, + 15.0 + ], + "areaMm2": 600.0, + "orientation": "reversed", + "adjacentFaceIds": [ + "brep:face:3", + "brep:face:4", + "brep:face:5", + "brep:face:6" + ], + "triangles": { + "positionsMm": [ + 0.0, + 0.0, + 30.0, + 0.0, + 20.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 20.0, + 30.0 + ], + "indices": [ + 0, + 1, + 2 + ] + }, + "wires": [ + { + "id": "brep:face:1:wire:1", + "sourceRef": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7:face:1:wire:1", + "isOuter": true, + "isCircular": false, + "centerMm": null, + "radiusMm": null, + "axis": null, + "fitResidualMm": null, + "circularityMethod": null, + "edges": [ + { + "id": "brep:edge:1", + "sourceRef": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7:edge:1", + "curveType": "line", + "orientation": "forward", + "firstParameter": 0.0, + "lastParameter": 30.0, + "startMm": [ + 0.0, + 0.0, + 0.0 + ], + "endMm": [ + 0.0, + 0.0, + 30.0 + ], + "samplesMm": [ + [ + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 30.0 + ] + ], + "isExact": true, + "selectableAsBoundary": true, + "direction": [ + 0.0, + 0.0, + 1.0 + ] + } + ] + } + ] + } + ] + }, + "requestId": "req-demo-001" +} +``` + +| data 字段 | 说明 | +| --- | --- | +| schemaVersion | 当前为 `interface-step-brep/v1` | +| sourceName | 解析器使用的文件名,当前通常为 `source.step` 或 `source.stp`,不是前端原文件名 | +| sourceSha256 | 原始 STEP 文件字节的 SHA-256,64 位小写十六进制,无 `sha256:` 前缀 | +| sourceUnits / scaleToMeters | 输出坐标单位及转换到米的比例,当前 `mm / 0.001` | +| kernel | 几何内核版本标识 | +| triangulationPurpose | `display-and-picking-only`:三角网格仅用于显示和拾取 | +| linearDeflectionMm / displayMeshSimplificationPasses | 显示网格精度和简化次数 | +| faceCount / edgeCount | 原模型面和边数量 | +| faces | 完整面数组,包括曲面类型、法向/轴、面积、线环、边和显示网格 | + +| 嵌套字段 | 说明 | +| --- | --- | +| faces[].id / sourceRef | 精确面的 ID 与源文件引用;后续拾取应保留这些标识 | +| faces[].surfaceType / isPlanar | 曲面类型及是否平面;字段依据类型出现 | +| faces[].normal / planeLocationMm / xDirection | 平面法向、平面位置和面内基准方向,仅平面类型提供 | +| faces[].axis / axisLocationMm / radiusMm | 圆柱轴、轴位置和半径,仅圆柱类型提供 | +| faces[].pointMm / areaMm2 / orientation | 面参考点、面积以及 `forward / reversed` 方向 | +| faces[].adjacentFaceIds | 相邻面的 ID | +| faces[].triangles.positionsMm | 扁平位置数组 `[x0,y0,z0,x1,y1,z1,...]`,毫米 | +| faces[].triangles.indices | 三角形顶点索引数组,每三个索引组成一个三角形 | +| faces[].wires[] | 线环;含 `id / sourceRef / isOuter / isCircular / edges` | +| wires[].centerMm / radiusMm / axis | 圆形线环的圆心、半径和轴;非圆环可为 null | +| wires[].fitResidualMm / circularityMethod | 圆形拟合残差和方法;可能为 null | +| edges[].id / sourceRef / curveType | 精确边引用与曲线类型,例如 `line / circle / ellipse / bspline` | +| edges[].startMm / endMm / samplesMm | 端点及显示用的采样点,单位毫米 | +| edges[].firstParameter / lastParameter / orientation | 底层曲线参数范围和方向,不是统一的毫米长度 | +| edges[].isExact / selectableAsBoundary | 是否原始精确边及能否选作边界 | +| edges[].direction | 直线方向;圆边可返回圆心、半径、axis、xDirection、isFullCircle;椭圆返回长短半径 | + +不能从显示三角网格反推并保存精确接口;保存几何时应基于精确平面、孔轴及原始拓扑引用,并转换为米。该接口不记录业务操作日志。 + + + +## 6. 用户管理 + +用户 ID 为数值型。本阶段仅管理手机号、昵称、类型和状态,不提供密码、登录和角色/菜单权限配置。 + +| 方法 | 路径 | 功能 | +| --- | --- | --- | +| GET | `/admin-api/users` | 分页及筛选 | +| GET | `/admin-api/users/{id}` | 详情 | +| POST | `/admin-api/users` | 创建 | +| PUT | `/admin-api/users/{id}` | 修改 | +| DELETE | `/admin-api/users/{id}` | 逻辑删除 | + +### 6.1 用户保存字段 + +| Body 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| phone | string | 是 | 大陆手机号,正则 `^1[3-9]\d{9}$`;不可与已有或已删除用户重复 | +| nickname | string | 是 | 非空、最多 64 字符 | +| status | string | 否 | `ACTIVE` 或 `DISABLED`;创建默认 ACTIVE,修改省略或 null 时保留原值 | +| userType | string | 否 | `NORMAL` 或 `ADMIN`;创建默认 NORMAL,修改省略或 null 时保留原值 | + +枚举必须使用上述大写值。修改时仍必须提交 `phone` 和 `nickname`,不是 PATCH。响应额外提供 `id / createdAt / updatedAt`;`deleted` 不暴露给前端。 + +### 6.2 查询用户列表 + + + +`GET /admin-api/users` + +| Query 参数 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| page | integer | 否 | 默认 1,最小 1 | +| size | integer | 否 | 默认 20,最小 1,上限 100 | +| keyword | string | 否 | 手机号或昵称模糊匹配 | +| userType | string | 否 | NORMAL / ADMIN | +| status | string | 否 | ACTIVE / DISABLED | + +**请求示例** + +```http +GET /admin-api/users?page=1&size=20&keyword=示例&userType=ADMIN&status=DISABLED HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "items": [ + { + "id": 1, + "phone": "13800000001", + "nickname": "示例管理员", + "status": "DISABLED", + "userType": "ADMIN", + "createdAt": "2026-10-09T17:10:24.51", + "updatedAt": "2026-10-09T17:10:24.563" + } + ], + "page": 1, + "size": 20, + "total": 1 + }, + "requestId": "req-demo-001" +} +``` + +按更新时间、ID 倒序;已逻辑删除的用户不会出现在列表中。 + +### 6.3 查询用户详情 + + + +`GET /admin-api/users/{id}` + +路径参数 `id`:用户数值 ID。 + +**请求示例** + +```http +GET /admin-api/users/1 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 1, + "phone": "13800000001", + "nickname": "示例用户", + "status": "ACTIVE", + "userType": "NORMAL", + "createdAt": "2026-10-09T17:10:24.51", + "updatedAt": "2026-10-09T17:10:24.51" + }, + "requestId": "req-demo-001" +} +``` + +### 6.4 创建用户 + + + +`POST /admin-api/users` + +请求字段见 6.1。 + +**请求示例** + +```http +POST /admin-api/users HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "phone": "13800000001", + "nickname": "示例用户", + "status": "ACTIVE", + "userType": "NORMAL" +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 1, + "phone": "13800000001", + "nickname": "示例用户", + "status": "ACTIVE", + "userType": "NORMAL", + "createdAt": "2026-10-09T17:10:24.51", + "updatedAt": "2026-10-09T17:10:24.51" + }, + "requestId": "req-demo-001" +} +``` + +### 6.5 修改用户 + + + +`PUT /admin-api/users/{id}` + +请求字段见 6.1。 + +**请求示例** + +```http +PUT /admin-api/users/1 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +Content-Type: application/json +``` + +```json +{ + "phone": "13800000001", + "nickname": "示例管理员", + "status": "DISABLED", + "userType": "ADMIN" +} +``` + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 1, + "phone": "13800000001", + "nickname": "示例管理员", + "status": "DISABLED", + "userType": "ADMIN", + "createdAt": "2026-10-09T17:10:24.51", + "updatedAt": "2026-10-09T17:10:24.563" + }, + "requestId": "req-demo-001" +} +``` + +### 6.6 逻辑删除用户 + + + +`DELETE /admin-api/users/{id}` + +删除后详情及列表都查不到该用户,但历史数据和手机号唯一约束仍保留;手机号不能分配给新用户。重复删除返回 `404 / USER_NOT_FOUND`。 + +**请求示例** + +```http +DELETE /admin-api/users/1 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "success": true + }, + "requestId": "req-demo-001" +} +``` + +用户管理操作不写入本文第 7 节的业务操作日志。 + + + +## 7. 操作日志 + +只读模块,提供列表和详情。记录组件库、接口库写操作的成功与失败;用户管理、查询、下载、STEP 分析、姿态候选及确认不产生该类业务日志。 + +业务日志保存失败不改变原接口结果;前端不要以“日志列表是否立即出现记录”作为写操作是否成功的判断依据。 + +| 动作值 | 含义 | +| --- | --- | +| CREATE | 新增组件或接口 | +| UPDATE | 修改组件或接口 | +| DELETE | 删除组件或接口 | +| PREPARE_UPLOAD | 创建上传会话 | +| PREPARE_UPLOAD_URL | 获取单文件上传地址 | +| UPLOAD | 资源文件上传或接口源文件上传 | +| COMPLETE_UPLOAD | 完成上传会话 | + +### 7.1 查询操作日志列表 + + + +`GET /admin-api/operation-logs` + +| Query 参数 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| page | integer | 否 | 默认 1,最小 1 | +| size | integer | 否 | 默认 20,最小 1,上限 100 | +| module | string | 否 | COMPONENT / INTERFACE | +| action | string | 否 | 上表动作值 | +| success | boolean | 否 | true 成功、false 失败;省略查询全部 | +| operatorId | integer | 否 | 操作人 ID;默认测试操作人 0 | +| from | string | 否 | 开始时间,包含该边界;如 `2026-10-09T00:00:00` | +| to | string | 否 | 结束时间,包含该边界;如 `2026-10-09T23:59:59.999` | + +**请求示例** + +```http +GET /admin-api/operation-logs?page=1&size=20&module=INTERFACE&action=UPDATE&success=false&operatorId=0 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "items": [ + { + "id": 14, + "module": "INTERFACE", + "action": "UPDATE", + "targetId": "mount-2-hole", + "operatorId": 0, + "operatorName": "TEST_OPERATOR", + "requestPath": "/admin-api/interfaces/mount-2-hole", + "requestMethod": "PUT", + "clientIp": "127.0.0.1", + "requestId": "req-demo-001", + "operatedAt": "2026-10-09T17:10:26.262", + "durationMs": 3, + "success": false, + "httpStatus": 422, + "errorSummary": "接口已修改,请刷新后保存" + } + ], + "page": 1, + "size": 20, + "total": 1 + }, + "requestId": "req-demo-001" +} +``` + +时间查询示例:`GET /admin-api/operation-logs?page=1&size=20&module=COMPONENT&success=true&operatorId=0&from=2026-10-09T00%3A00%3A00&to=2026-10-09T23%3A59%3A59.999`。 + +开始时间晚于结束时间返回 `422 / INVALID_REQUEST`。`module / action` 当前是精确字符串筛选,输入未使用的值通常得到空列表;前端下拉框使用本文列出的值。结果按操作时间、ID 倒序。 + +**成功操作的分页示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "items": [ + { + "id": 10, + "module": "COMPONENT", + "action": "CREATE", + "targetId": "1", + "operatorId": 0, + "operatorName": "TEST_OPERATOR", + "requestPath": "/admin-api/components", + "requestMethod": "POST", + "clientIp": "127.0.0.1", + "requestId": "req-demo-001", + "operatedAt": "2026-10-09T17:10:24.908", + "durationMs": 22, + "success": true, + "httpStatus": 200 + } + ], + "page": 1, + "size": 20, + "total": 1 + }, + "requestId": "req-demo-001" +} +``` + +### 7.2 查询操作日志详情 + + + +`GET /admin-api/operation-logs/{id}` + +路径参数 `id`:数值型日志 ID。 + +**请求示例** + +```http +GET /admin-api/operation-logs/14 HTTP/1.1 +Host: 127.0.0.1:8992 +X-Request-Id: req-demo-001 +``` + +无请求体。 + +**成功返回示例:HTTP 200** + +```json +{ + "code": "OK", + "message": "success", + "data": { + "id": 14, + "module": "INTERFACE", + "action": "UPDATE", + "targetId": "mount-2-hole", + "operatorId": 0, + "operatorName": "TEST_OPERATOR", + "requestPath": "/admin-api/interfaces/mount-2-hole", + "requestMethod": "PUT", + "clientIp": "127.0.0.1", + "requestId": "req-demo-001", + "operatedAt": "2026-10-09T17:10:26.262", + "durationMs": 3, + "success": false, + "httpStatus": 422, + "errorSummary": "接口已修改,请刷新后保存" + }, + "requestId": "req-demo-001" +} +``` + +| 返回字段 | 类型 | 说明 | +| --- | --- | --- | +| id | integer | 日志 ID | +| module / action | string | 业务模块及动作 | +| targetId | string | 业务对象 ID、对象 Key 或会话前缀;失败发生较早时可能缺省 | +| operatorId / operatorName | integer / string | 操作人 ID 和名称 | +| requestPath / requestMethod | string | 请求路径及 HTTP 方法 | +| clientIp | string | 服务端看到的请求来源 IP | +| requestId | string | 产生该日志的原请求编号;与查询日志接口外层 requestId 含义不同 | +| operatedAt | string | 操作时间,上海时区本地时间 | +| durationMs | integer | 请求处理耗时,毫秒 | +| success | boolean | 成功/失败 | +| httpStatus | integer | 原操作的 HTTP 状态码 | +| errorSummary | string | 失败摘要;成功日志通常缺省 | + +不提供日志新增、修改、删除接口;不返回请求体、文件内容、密钥或上传会话令牌。 + + + +## 8. 前端调用流程 + +### 8.1 创建或编辑组件 + +1. 通过 URDF/RFS 会话上传模型及资源,完成上传后取得 `source`。 +2. 如需封面,通过封面会话上传,完成后取得 `coverImageKey / coverImageUrl`。 +3. 前端解析模型并准备 `componentJson`、`assemblyMetadata`;需要端口时执行 8.3。 +4. 调用 `POST /admin-api/components` 或 `PUT /admin-api/components/{id}`。 +5. 以后展示资源使用详情返回的 `sourceUrl / coverImageUrl`。 + +### 8.2 浏览器上传示例 + +以下以 URDF/RFS 会话为例;封面流程将会话路径替换为 `cover-image-upload-sessions`,完成结果字段使用 `coverImageKey`。 + +```javascript +const apiBase = 'http://127.0.0.1:8992'; + +async function readJsonResponse(response) { + const body = await response.json(); + if (!response.ok || body.code !== 'OK') { + throw new Error(body.message || `HTTP ${response.status}`); + } + return body.data; +} + +async function postJson(path, body) { + const response = await fetch(`${apiBase}${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body) + }); + return readJsonResponse(response); +} + +// files 是 [{ file: File, objectPath: 'robot.urdf' }, +// { file: File, objectPath: 'meshes/base.stl' }, ...]。 +// 目录选择时保留模型引用所需的相对目录,主文件只能有一个。 +async function uploadModel(files) { + const path = '/admin-api/components/urdf-upload-sessions'; + const session = await postJson(path); + const objectKeys = []; + + for (const { file, objectPath } of files) { + const contentType = file.type || 'application/octet-stream'; + const prepared = await postJson(`${path}/upload-url`, { + uploadSessionToken: session.uploadSessionToken, + objectPath, + contentType + }); + const response = await fetch(prepared.uploadUrl, { + method: 'PUT', + headers: { 'Content-Type': contentType }, + body: file + }); + if (response.status !== 204) { + // 失败通常为 JSON;如网关返回非 JSON,保留 HTTP 状态信息。 + const error = await response.json().catch(() => ({})); + throw new Error(error.message || `上传失败,HTTP ${response.status}`); + } + objectKeys.push(prepared.objectKey); + } + + return postJson(`${path}/complete`, { + uploadSessionToken: session.uploadSessionToken, + objectKeys + }); // { source: 'components/urdf/...' },随后保存组件 +} +``` + +当前应用没有统一启用跨域配置。前端开发代理、网关入口或服务端跨域设置需与后端协调;上传 URL 和下载 URL 也应使用实际可访问的统一入口,不只代理列表接口。 + +### 8.3 保存带机械端口的组件 + +1. 取得接口模板详情,记录 `geometryRevision`。 +2. 保存原始 URDF XML 快照,并为其引用的网格/纹理建立资源清单;资源先通过模型会话上传。 +3. 用 link 局部坐标中的实际几何调用 `/pose-candidates`。 +4. 用户选择候选后,携带候选 ID、对应修订和源哈希调用 `/confirm-port`。 +5. 将规范化端口加入 `componentJson.interfaces`;按照 2.9 处理多目标路径的输入格式。 +6. 将同一原始快照放入 `componentJson.urdfSource`,保存组件。接口定义或源文件改变后,重新执行识别和确认。 + +`urdfSource` 结构: + +```json +{ + "xml": "", + "documentHash": "7fa86878484ac25bb466ba4f49e095caf6df3f3ab1a4234ee423a6aba6277a7a", + "resources": [], + "sourceGeometryHash": "d16fa71567b7e89283c4870161ba4be526a67622217f1c515d36a0573a20dc5f" +} +``` + +上例 URDF 只有一个根 link,没有网格/纹理引用,所以 `resources` 为空。实际模型每个 mesh/texture 的 `filename` 引用都必须有对应资源项: + +```json +{ + "reference": "meshes/base.stl", + "sourceKey": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/meshes/base.stl", + "sha256": "" +} +``` + +哈希算法均为 UTF-8 文本或原始文件字节的 SHA-256,小写 64 位十六进制: + +```text +documentHash = SHA256(原始 XML 的 UTF-8 字节) + +将 resources 按 reference 升序排序,构建 manifest: +reference + "\t" + sha256 +多项之间使用 "\n",最后一项不附加换行 + +sourceGeometryHash = SHA256(documentHash + "\n" + manifest) +``` + +资源为空时仍计算 `SHA256(documentHash + "\n")`。不要格式化或修改 XML 后继续使用旧哈希。资源 `sha256` 必须根据真实字节计算,服务端会再次读取已上传对象验证。 + +`urdfSource.xml` 必须是合法 URDF:根节点为 robot,link/joint 名称不重复、父子 link 存在、没有环且只有一个根 link。端口 `linkName` 必须存在于该原始快照;每个端口的 `sourceGeometryHash` 必须等于 `urdfSource.sourceGeometryHash`。 + +注意区分三类哈希:STEP 分析返回 `sourceSha256` 是 STEP 文件哈希;接口定义的 `sourceGeometryHash` 是其绑定源文件哈希且通常带 `sha256:`;组件端口的 `sourceGeometryHash` 是上述 URDF 文档及资源清单哈希。三者不可直接互换。 + + + +## 9. 错误处理 + +前端同时检查 HTTP 状态与 JSON `code`。提示可使用 `message`,排查时带上 `requestId`。以下响应示例中的提示文字用于说明,字段结构与业务错误码以实际响应为准。 + +### 9.1 常见失败返回 + +**重复手机号失败示例:HTTP 409** + +```json +{ + "code": "USER_PHONE_DUPLICATE", + "message": "手机号已存在,包括已删除的用户", + "requestId": "req-demo-001" +} +``` + +**接口修订过期失败示例:HTTP 422** + +```json +{ + "code": "INVALID_INTERFACE", + "message": "接口已修改,请刷新后保存", + "requestId": "req-demo-001" +} +``` + +**查询已删除用户失败示例:HTTP 404** + +```json +{ + "code": "USER_NOT_FOUND", + "message": "用户不存在", + "requestId": "req-demo-001" +} +``` + +| HTTP | code | 前端处理建议 | +| --- | --- | --- | +| 422 | INVALID_REQUEST | 必填、字段长度、枚举、JSON 格式、参数类型或几何结构不合法,提示修改输入 | +| 422 | INVALID_INTERFACE | 接口不存在、ID 已占用/归档、修订过期或源文件绑定不合法;注意接口库“对象不存在”当前也可能返回此码 | +| 409 | USER_PHONE_DUPLICATE | 手机号冲突,已删除用户也会占用手机号 | +| 404 | USER_NOT_FOUND | 用户不存在或已删除 | +| 409 | COMPONENT_NAME_DUPLICATE | 组件名称重复 | +| 404 | COMPONENT_NOT_FOUND | 组件不存在 | +| 404 | OPERATION_LOG_NOT_FOUND | 日志不存在 | +| 422 | INVALID_COMPONENT_UPLOAD_SESSION / INVALID_COMPONENT_COVER_UPLOAD_SESSION | 上传会话过期、类型或操作人不匹配;重新创建对应类型会话 | +| 422 | INVALID_COMPONENT_UPLOAD_OBJECT | 对象路径、前缀、长度、重复 Key 或文件列表不合法 | +| 422 | COMPONENT_UPLOAD_OBJECT_MISSING | 文件尚未上传成功;检查 PUT 结果及提交 Key | +| 422 | COMPONENT_COVER_IMAGE_TYPE_INVALID / COMPONENT_COVER_IMAGE_KEY_TOO_LONG | 封面扩展名或 Key 长度不符合要求 | +| 422 | COMPONENT_MAIN_FILE_NOT_FOUND / COMPONENT_MAIN_FILE_NOT_UNIQUE / COMPONENT_MAIN_FILE_TYPE_CONFLICT / COMPONENT_MAIN_FILE_PATH_TOO_LONG | 模型主文件不存在、多个主文件、混合 URDF/RFS 或主文件路径过长 | +| 413 | INVALID_REQUEST | multipart 文件或整个请求超过大小限制 | +| 413 | INTERFACE_BREP_UPLOAD_TOO_LARGE / INTERFACE_BREP_OUTPUT_TOO_LARGE | STEP 输入/输出超过解析限制 | +| 422 | INTERFACE_BREP_INVALID_STEP | STEP 无法解析或精确拓扑不合法 | +| 503 | INTERFACE_BREP_UNAVAILABLE | 解析服务、脚本或 Python/OCP 依赖不可用,联系后端 | +| 504 | INTERFACE_BREP_TIMEOUT | STEP 解析超时,拆分文件后重试 | +| 500 | MINIO_CONFIG_ERROR / STORAGE_CONFIG_ERROR | 存储配置缺失或非法,联系后端 | +| 502 | MINIO_BUCKET_FAILED / MINIO_UPLOAD_FAILED / MINIO_OBJECT_CHECK_FAILED / MINIO_DOWNLOAD_FAILED | 存储连接、权限或读写失败,联系后端 | +| 404 | MINIO_OBJECT_NOT_FOUND | 资源对象不存在 | +| 422 | INVALID_STORAGE_OBJECT_KEY | 存储对象 Key 不合法 | +| 503 | DATABASE_UNAVAILABLE | 数据库连接不可用,联系后端 | +| 500 | INTERNAL_ERROR | 未分类系统异常,反馈 requestId | +| 404 | NOT_FOUND | 路由不存在,检查路径及前缀 | + +下载失败或上传失败可能返回 JSON;网关错误也可能返回非 JSON。文件请求的错误处理应兼容这两种情况。 + +### 9.2 联调检查要点 + +- 创建、修改和删除成功是 HTTP 200,文件流上传成功是 HTTP 204;不要统一按 201 或统一解析 JSON。 +- 接口库列表是数组,其余三个分页列表是 `data.items`。 +- 保存组件使用 Key,展示模型/封面使用后端生成的 URL。 +- 文件流上传使用 PUT 原始二进制;接口源文件及 STEP 分析使用 POST FormData。 +- 会话令牌、对象 Key、源几何哈希、模板修订和候选姿态 ID 使用当前实际返回值。 +- 用户删除是逻辑删除;组件删除是物理删除;接口删除保留历史且 ID 不能复用。 +- 文件与端口保存失败时先展示错误提示,重新确认相关数据后重试,不自行补偿旋转或伪造哈希。 + diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentAssetController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentAssetController.java index 51257ed..dddc980 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentAssetController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentAssetController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import com.linkerbot.cadworld.audit.AuditOperation; import com.linkerbot.cadworld.service.client.ObjectStorageClient; @@ -34,6 +36,7 @@ public class ComponentAssetController { private final ObjectStorageClient objectStorageClient; @AuditOperation(module = "COMPONENT", action = "UPLOAD") + @ApiRequestLog("上传组件资源文件") @PutMapping("/upload") @ResponseStatus(HttpStatus.NO_CONTENT) public void upload( @@ -50,6 +53,7 @@ public class ComponentAssetController { ); } + @ApiRequestLog("下载组件资源文件") @GetMapping("/**") public void download(HttpServletRequest request, HttpServletResponse response) throws IOException { String requestUri = request.getRequestURI(); diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentController.java index 131abd2..8b2d33e 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/ComponentController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import com.linkerbot.cadworld.audit.AuditOperation; import com.linkerbot.cadworld.common.api.ApiResponse; @@ -44,6 +46,7 @@ public class ComponentController { private final ComponentUrdfUploadService componentUrdfUploadService; @AuditOperation(module = "COMPONENT", action = "CREATE") + @ApiRequestLog("新增组件") @PostMapping public ApiResponse create( @Valid @RequestBody CreateComponentRequest request @@ -52,6 +55,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD") + @ApiRequestLog("创建封面上传会话") @PostMapping("/cover-image-upload-sessions") public ApiResponse prepareCoverImageUploadSession( ) { @@ -59,6 +63,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL") + @ApiRequestLog("获取封面上传地址") @PostMapping("/cover-image-upload-sessions/upload-url") public ApiResponse prepareCoverImageObjectUploadUrl( @Valid @RequestBody PrepareObjectUploadUrlRequest request @@ -67,6 +72,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD") + @ApiRequestLog("完成封面上传") @PostMapping("/cover-image-upload-sessions/complete") public ApiResponse completeCoverImageUploadSession( @Valid @RequestBody CompleteCoverImageUploadRequest request @@ -75,6 +81,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD") + @ApiRequestLog("创建模型上传会话") @PostMapping("/urdf-upload-sessions") public ApiResponse prepareUrdfUploadSession( ) { @@ -82,6 +89,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL") + @ApiRequestLog("获取模型上传地址") @PostMapping("/urdf-upload-sessions/upload-url") public ApiResponse prepareUrdfObjectUploadUrl( @Valid @RequestBody PrepareObjectUploadUrlRequest request @@ -90,6 +98,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD") + @ApiRequestLog("完成模型上传") @PostMapping("/urdf-upload-sessions/complete") public ApiResponse completeUrdfUploadSession( @Valid @RequestBody CompleteUrdfUploadRequest request @@ -97,6 +106,7 @@ public class ComponentController { return ApiResponse.success(componentUrdfUploadService.completeUploadSession(operatorProvider.userId(), request)); } + @ApiRequestLog("查询组件列表") @GetMapping public ApiResponse> list( @RequestParam(defaultValue = "1") long page, @@ -106,12 +116,14 @@ public class ComponentController { return ApiResponse.success(componentService.listComponents(page, Math.min(size, 100), keyword)); } + @ApiRequestLog("查询组件详情") @GetMapping("/{id}") public ApiResponse detail(@PathVariable Long id) { return ApiResponse.success(componentService.getComponent(id)); } @AuditOperation(module = "COMPONENT", action = "UPDATE") + @ApiRequestLog("修改组件") @PutMapping("/{id}") public ApiResponse update( @PathVariable Long id, @@ -121,6 +133,7 @@ public class ComponentController { } @AuditOperation(module = "COMPONENT", action = "DELETE") + @ApiRequestLog("删除组件") @DeleteMapping("/{id}") public ApiResponse delete( @PathVariable Long id diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceBrepController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceBrepController.java index 2cc4f05..8cf385f 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceBrepController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceBrepController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import com.fasterxml.jackson.databind.JsonNode; import com.linkerbot.cadworld.common.api.ApiResponse; import com.linkerbot.cadworld.service.InterfaceBrepService; @@ -17,6 +19,7 @@ import org.springframework.web.multipart.MultipartFile; public class InterfaceBrepController { private final InterfaceBrepService service; + @ApiRequestLog("解析 STEP 精确拓扑") @PostMapping(value = "/analyze", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ApiResponse analyze(@RequestPart("file") MultipartFile file) { return ApiResponse.success(service.analyze(file)); diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceDefinitionController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceDefinitionController.java index cefeaf9..fa18ee0 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceDefinitionController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfaceDefinitionController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import com.linkerbot.cadworld.audit.AuditOperation; import com.fasterxml.jackson.databind.JsonNode; @@ -23,16 +25,22 @@ import org.springframework.web.bind.annotation.*; public class InterfaceDefinitionController { private final InterfaceDefinitionService service; private final ObjectStorageClient objectStorageClient; + @ApiRequestLog("查询接口列表") @GetMapping public ApiResponse> list(@RequestParam(required = false) String keyword) { return ApiResponse.success(service.list(keyword)); } + @ApiRequestLog("查询接口详情") @GetMapping("/{id}") public ApiResponse get(@PathVariable String id) { return ApiResponse.success(service.get(id)); } @AuditOperation(module = "INTERFACE", action = "CREATE") + @ApiRequestLog("新增接口定义") @PostMapping public ApiResponse create(@RequestBody JsonNode request) { return ApiResponse.success(service.create(request)); } @AuditOperation(module = "INTERFACE", action = "UPDATE") + @ApiRequestLog("修改接口定义") @PutMapping("/{id}") public ApiResponse update(@PathVariable String id, @RequestBody JsonNode request) { return ApiResponse.success(service.update(id, request)); } @AuditOperation(module = "INTERFACE", action = "DELETE") + @ApiRequestLog("删除接口定义") @DeleteMapping("/{id}") public ApiResponse delete(@PathVariable String id) { service.delete(id); return ApiResponse.success(SuccessResponse.ok()); } @AuditOperation(module = "INTERFACE", action = "UPLOAD") + @ApiRequestLog("上传接口源文件") @PostMapping("/{id}/assets") public ApiResponse uploadAsset(@PathVariable String id, @RequestParam int geometryRevision, diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfacePoseController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfacePoseController.java index 29d7589..84d0339 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfacePoseController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/InterfacePoseController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*; import com.linkerbot.cadworld.common.api.ApiResponse; import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver; @@ -18,11 +20,13 @@ public class InterfacePoseController { private final InterfaceDefinitionService definitions; private final MechanicalInterfaceSolver solver; private final ObjectMapper objectMapper; + @ApiRequestLog("计算接口姿态候选") @PostMapping("/pose-candidates") public ApiResponse candidates(@PathVariable String id,@RequestBody JsonNode body){ PoseRequest request=read(body,PoseRequest.class); return ApiResponse.success(solver.enumeratePortPoses(definitions.geometryDefinition(id,request.definitionRevision()),request)); } + @ApiRequestLog("确认组件端口姿态") @PostMapping("/confirm-port") public ApiResponse confirm(@PathVariable String id,@RequestBody JsonNode body){ Port request=read(body,Port.class); diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/OperationLogController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/OperationLogController.java index 3fa11d2..ed4c866 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/OperationLogController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/OperationLogController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import com.linkerbot.cadworld.common.api.ApiResponse; import com.linkerbot.cadworld.common.api.PageResponse; import com.linkerbot.cadworld.entity.OperationLog; @@ -18,6 +20,7 @@ import org.springframework.web.bind.annotation.*; public class OperationLogController { private final OperationLogService service; + @ApiRequestLog("查询操作日志列表") @GetMapping public ApiResponse> list( @RequestParam(defaultValue = "1") @Min(1) long page, @@ -31,6 +34,7 @@ public class OperationLogController { return ApiResponse.success(service.list(page, Math.min(size, 100), module, action, success, operatorId, from, to)); } + @ApiRequestLog("查询操作日志详情") @GetMapping("/{id}") public ApiResponse get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); } } diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/UserManagementController.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/UserManagementController.java index 7857d93..4fd3ba2 100644 --- a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/UserManagementController.java +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/controller/UserManagementController.java @@ -1,5 +1,7 @@ package com.linkerbot.cadworld.controller; +import com.linkerbot.cadworld.logging.ApiRequestLog; + import com.linkerbot.cadworld.common.api.ApiResponse; import com.linkerbot.cadworld.common.api.PageResponse; import com.linkerbot.cadworld.dto.common.SuccessResponse; @@ -21,6 +23,7 @@ import org.springframework.web.bind.annotation.*; public class UserManagementController { private final UserManagementService service; + @ApiRequestLog("查询用户列表") @GetMapping public ApiResponse> list( @RequestParam(defaultValue = "1") @Min(1) long page, @@ -31,15 +34,19 @@ public class UserManagementController { return ApiResponse.success(service.list(page, Math.min(size, 100), keyword, userType, status)); } + @ApiRequestLog("查询用户详情") @GetMapping("/{id}") public ApiResponse get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); } + @ApiRequestLog("创建用户") @PostMapping public ApiResponse create(@Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.create(request)); } + @ApiRequestLog("修改用户") @PutMapping("/{id}") public ApiResponse update(@PathVariable Long id, @Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.update(id, request)); } + @ApiRequestLog("逻辑删除用户") @DeleteMapping("/{id}") public ApiResponse delete(@PathVariable Long id) { service.delete(id); diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLog.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLog.java new file mode 100644 index 0000000..e761fd0 --- /dev/null +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLog.java @@ -0,0 +1,13 @@ +package com.linkerbot.cadworld.logging; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** 接口运行日志中的业务说明,不改变数据库操作日志的记录范围。 */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface ApiRequestLog { + String value(); +} diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLogResponseAdvice.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLogResponseAdvice.java new file mode 100644 index 0000000..072b194 --- /dev/null +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLogResponseAdvice.java @@ -0,0 +1,31 @@ +package com.linkerbot.cadworld.logging; + +import com.linkerbot.cadworld.common.api.ApiResponse; +import org.springframework.core.MethodParameter; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +/** 只提取业务错误码,不记录响应数据或可能包含敏感字段的错误提示。 */ +@RestControllerAdvice +public class ApiRequestLogResponseAdvice implements ResponseBodyAdvice { + @Override + public boolean supports(MethodParameter parameter, Class> converter) { + return true; + } + + @Override + public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType contentType, + Class> converter, + ServerHttpRequest request, ServerHttpResponse response) { + if (request instanceof ServletServerHttpRequest servlet && body instanceof ApiResponse envelope) { + servlet.getServletRequest().setAttribute(ApiRequestLoggingFilter.RESULT_CODE_ATTRIBUTE, + envelope.getCode()); + } + return body; + } +} diff --git a/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilter.java b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilter.java new file mode 100644 index 0000000..786c427 --- /dev/null +++ b/cadworld-adminapi/src/main/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilter.java @@ -0,0 +1,123 @@ +package com.linkerbot.cadworld.logging; + +import com.linkerbot.cadworld.common.api.ApiCode; +import com.linkerbot.cadworld.common.api.RequestIdHolder; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import org.springframework.web.util.ServletRequestPathUtils; +import org.springframework.web.util.pattern.PathPattern; + +/** + * 在 multipart 解析前记录接口开始,在响应完成后记录结果;不读取请求参数、文件或响应内容。 + * 路径只输出路由模板,避免关键词、文件名等用户输入进入日志。 + */ +@Slf4j +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 2) +public class ApiRequestLoggingFilter extends OncePerRequestFilter { + static final String RESULT_CODE_ATTRIBUTE = "cadworld.runtimeLogResultCode"; + + private final List endpoints; + + public ApiRequestLoggingFilter( + @Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mappings) { + endpoints = mappings.getHandlerMethods().entrySet().stream() + .filter(entry -> entry.getValue().hasMethodAnnotation(ApiRequestLog.class)) + .map(entry -> new Endpoint(entry.getKey(), + entry.getValue().getMethodAnnotation(ApiRequestLog.class).value())) + .toList(); + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return !request.getRequestURI().startsWith(request.getContextPath() + "/admin-api/"); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + MatchedEndpoint endpoint; + try { + endpoint = resolveEndpoint(request); + } catch (RuntimeException failure) { + // 日志定位失败不能改变原接口的处理结果,也不输出可能包含用户输入的异常消息。 + log.warn("接口日志定位失败 method={} exceptionType={}", + request.getMethod(), failure.getClass().getSimpleName()); + endpoint = null; + } + if (endpoint == null) { + chain.doFilter(request, response); + return; + } + + long started = System.nanoTime(); + String requestId = RequestIdHolder.get(); + log.info("接口开始 description={} method={} path={} requestId={}", + endpoint.description(), request.getMethod(), endpoint.pattern().getPatternString(), requestId); + Throwable failure = null; + try { + chain.doFilter(request, response); + } catch (IOException | ServletException | RuntimeException | Error exception) { + failure = exception; + throw exception; + } finally { + long durationMs = (System.nanoTime() - started) / 1_000_000; + String code = (String) request.getAttribute(RESULT_CODE_ATTRIBUTE); + boolean success = failure == null && response.getStatus() < 400 + && (code == null || ApiCode.OK.equals(code)); + String resultCode = code == null ? "HTTP_" + response.getStatus() : code; + String exceptionType = failure == null ? "-" : failure.getClass().getSimpleName(); + String message = "接口结束 description={} method={} path={} requestId={} result={} httpStatus={} " + + "code={} durationMs={} exceptionType={}"; + Object[] values = {endpoint.description(), request.getMethod(), endpoint.pattern().getPatternString(), + requestId, success ? "SUCCESS" : "FAILURE", response.getStatus(), resultCode, + durationMs, exceptionType}; + if (failure != null || response.getStatus() >= 500) { + log.error(message, values); + } else if (!success) { + log.warn(message, values); + } else { + log.info(message, values); + } + } + } + + private MatchedEndpoint resolveEndpoint(HttpServletRequest request) { + if (!ServletRequestPathUtils.hasParsedRequestPath(request)) { + ServletRequestPathUtils.parseAndCache(request); + } + MatchedEndpoint best = null; + for (Endpoint endpoint : endpoints) { + // 只匹配路径及 HTTP 方法,避免提前解析 multipart 或访问请求参数。 + // 即使 Content-Type 不合法,也能记录对应接口的最终失败结果。 + if (endpoint.mapping().getMethodsCondition().getMatchingCondition(request) == null) { + continue; + } + var matchingPaths = endpoint.mapping().getPathPatternsCondition().getMatchingCondition(request); + if (matchingPaths == null) { + continue; + } + PathPattern pattern = matchingPaths.getFirstPattern(); + if (best == null || pattern.compareTo(best.pattern()) < 0) { + best = new MatchedEndpoint(endpoint.description(), pattern); + } + } + return best; + } + + private record Endpoint(RequestMappingInfo mapping, String description) { } + + private record MatchedEndpoint(String description, PathPattern pattern) { } +} diff --git a/cadworld-adminapi/src/main/resources/application-test.yml b/cadworld-adminapi/src/main/resources/application-test.yml index a65b14b..212bc5c 100644 --- a/cadworld-adminapi/src/main/resources/application-test.yml +++ b/cadworld-adminapi/src/main/resources/application-test.yml @@ -1,8 +1,8 @@ spring: datasource: url: ${APP_DB_URL:jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai} - username: ${APP_DB_USERNAME:} - password: ${APP_DB_PASSWORD:} + username: ${APP_DB_USERNAME:root} + password: ${APP_DB_PASSWORD:mysql_QRWm4M} driver-class-name: com.mysql.cj.jdbc.Driver hikari: pool-name: CadworldAdminHikariCP diff --git a/cadworld-adminapi/src/main/resources/application.yml b/cadworld-adminapi/src/main/resources/application.yml index 245a82d..a3a7ed0 100644 --- a/cadworld-adminapi/src/main/resources/application.yml +++ b/cadworld-adminapi/src/main/resources/application.yml @@ -68,4 +68,6 @@ logging: level: root: INFO com.linkerbot.cadworld: INFO + # 即使测试环境开启项目 DEBUG,也不输出可能包含手机号、模型数据等信息的 SQL 参数。 + com.linkerbot.cadworld.mapper: INFO org.springframework.web: INFO diff --git a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/AdminApiTest.java b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/AdminApiTest.java index b7ca0f6..f5f2eb0 100644 --- a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/AdminApiTest.java +++ b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/AdminApiTest.java @@ -34,6 +34,9 @@ class AdminApiTest { @Autowired JdbcTemplate jdbc; @Autowired OperationLogService logs; @Autowired TransactionTemplate transactions; + @Autowired + @org.springframework.beans.factory.annotation.Qualifier("requestMappingHandlerMapping") + org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping mappings; @BeforeEach void clean() { @@ -42,6 +45,64 @@ class AdminApiTest { } } + @Test + void allManagementEndpointsHaveRuntimeLogDescriptions() { + var handlers = mappings.getHandlerMethods().values().stream() + .filter(handler -> handler.getBeanType().getPackageName() + .equals("com.linkerbot.cadworld.controller")) + .toList(); + assertThat(handlers).hasSize(29); + for (var handler : handlers) { + var description = handler.getMethodAnnotation(com.linkerbot.cadworld.logging.ApiRequestLog.class); + assertThat(description).as(handler.toString()).isNotNull(); + assertThat(description.value()).isNotBlank(); + } + } + + @Test + void requestLogsCoverSuccessfulAndRejectedCallsWithoutSensitiveValues() throws Exception { + String phone = "13800000001"; + String token = "PRIVATE_UPLOAD_TOKEN"; + String password = "PRIVATE_PASSWORD"; + var applicationLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("com.linkerbot.cadworld"); + var previousLevel = applicationLogger.getLevel(); + var mapperLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("com.linkerbot.cadworld.mapper"); + var sqlLogs = new ch.qos.logback.core.read.ListAppender(); + sqlLogs.start(); + mapperLogger.addAppender(sqlLogs); + applicationLogger.setLevel(ch.qos.logback.classic.Level.DEBUG); + try (var captured = new com.linkerbot.cadworld.logging.ApiRequestLogCapture()) { + mvc.perform(post("/admin-api/users").header("X-Request-Id", "user-create-log") + .contentType(MediaType.APPLICATION_JSON) + .content(json.writeValueAsString(Map.of("phone", phone, "nickname", "日志测试用户", + "uploadSessionToken", token, "password", password)))) + .andExpect(status().isOk()); + mvc.perform(get("/admin-api/users").header("X-Request-Id", "user-list-log") + .param("keyword", phone).param("token", token)) + .andExpect(status().isOk()); + mvc.perform(post("/admin-api/users").header("X-Request-Id", "user-rejected-log") + .contentType(MediaType.APPLICATION_JSON) + .content(json.writeValueAsString(Map.of("phone", phone, "nickname", "日志测试用户", + "userType", "PRIVATE_INVALID_TYPE", "uploadSessionToken", token)))) + .andExpect(status().isUnprocessableEntity()); + + assertThat(captured.messages()).hasSize(6); + String messages = String.join("\n", captured.messages()); + assertThat(messages).contains("description=创建用户", "description=查询用户列表", + "requestId=user-list-log", "result=SUCCESS", "httpStatus=200", "code=OK", + "requestId=user-rejected-log", "result=FAILURE", "httpStatus=422", + "code=INVALID_REQUEST", "durationMs="); + assertThat(messages).doesNotContain(phone, token, password, "PRIVATE_INVALID_TYPE", "keyword="); + assertThat(captured.events().getLast().getLevel()).isEqualTo(ch.qos.logback.classic.Level.WARN); + assertThat(sqlLogs.list).isEmpty(); + assertThat(logCount()).isZero(); + } finally { + applicationLogger.setLevel(previousLevel); + mapperLogger.detachAppender(sqlLogs); + sqlLogs.stop(); + } + } + @Test void userCrudFiltersAndLogicalDeletionKeepPhoneReserved() throws Exception { JsonNode created = send("/admin-api/users", Map.of("phone", "13812345678", "nickname", "测试用户")); diff --git a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/UploadHttpTest.java b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/UploadHttpTest.java index 3f3a36c..b11b883 100644 --- a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/UploadHttpTest.java +++ b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/UploadHttpTest.java @@ -35,9 +35,18 @@ class UploadHttpTest { }); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); - var response = http.postForEntity("/admin-api/interfaces/missing/assets?geometryRevision=1", new HttpEntity<>(body, headers), String.class); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE); - assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND http_status=413 AND success=FALSE AND target_id='missing'", Long.class)) - .isEqualTo(1); + headers.set("X-Request-Id", "oversize-runtime-log"); + try (var captured = new com.linkerbot.cadworld.logging.ApiRequestLogCapture()) { + var response = http.postForEntity("/admin-api/interfaces/missing/assets?geometryRevision=1", new HttpEntity<>(body, headers), String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE); + org.awaitility.Awaitility.await().atMost(java.time.Duration.ofSeconds(5)).untilAsserted(() -> { + assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND http_status=413 AND success=FALSE AND target_id='missing'", Long.class)) + .isEqualTo(1); + assertThat(captured.messages()).hasSize(2); + assertThat(captured.messages().getLast()).contains("description=上传接口源文件", + "requestId=oversize-runtime-log", "result=FAILURE", "httpStatus=413", + "code=INVALID_REQUEST"); + }); + } } } diff --git a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLogCapture.java b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLogCapture.java new file mode 100644 index 0000000..1d03508 --- /dev/null +++ b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLogCapture.java @@ -0,0 +1,44 @@ +package com.linkerbot.cadworld.logging; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import org.slf4j.LoggerFactory; + +/** 捕获请求日志,包括真实 Servlet 服务线程产生的日志。 */ +public final class ApiRequestLogCapture implements AutoCloseable { + private final Logger logger = (Logger) LoggerFactory.getLogger(ApiRequestLoggingFilter.class); + private final Level previousLevel = logger.getLevel(); + private final List events = new CopyOnWriteArrayList<>(); + private final AppenderBase appender = new AppenderBase<>() { + @Override + protected void append(ILoggingEvent event) { + event.prepareForDeferredProcessing(); + events.add(event); + } + }; + + public ApiRequestLogCapture() { + appender.start(); + logger.setLevel(Level.INFO); + logger.addAppender(appender); + } + + public List events() { + return List.copyOf(events); + } + + public List messages() { + return events().stream().map(ILoggingEvent::getFormattedMessage).toList(); + } + + @Override + public void close() { + logger.detachAppender(appender); + logger.setLevel(previousLevel); + appender.stop(); + } +} diff --git a/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilterTest.java b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilterTest.java new file mode 100644 index 0000000..3f1fcd9 --- /dev/null +++ b/cadworld-adminapi/src/test/java/com/linkerbot/cadworld/logging/ApiRequestLoggingFilterTest.java @@ -0,0 +1,81 @@ +package com.linkerbot.cadworld.logging; + +import ch.qos.logback.classic.Level; +import com.linkerbot.cadworld.common.api.RequestIdHolder; +import com.linkerbot.cadworld.common.web.RequestIdFilter; +import java.io.IOException; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import org.springframework.web.util.pattern.PathPatternParser; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ApiRequestLoggingFilterTest { + @Test + void binaryUploadLogs204WithoutReadingParametersOrFileContent() throws Exception { + var filter = filter("/admin-api/component-assets/upload", RequestMethod.PUT); + var request = spy(new MockHttpServletRequest("PUT", "/admin-api/component-assets/upload")); + request.setQueryString("objectKey=13800000001-secret-token.txt"); + request.setContent("private file content".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + request.addHeader("X-Request-Id", "binary-log-test"); + var response = new MockHttpServletResponse(); + try (var captured = new ApiRequestLogCapture()) { + new RequestIdFilter().doFilter(request, response, (req, res) -> + filter.doFilter(req, res, (innerRequest, innerResponse) -> response.setStatus(204))); + + assertThat(captured.messages()).hasSize(2); + assertThat(captured.messages().getLast()).contains("description=测试接口", "result=SUCCESS", + "httpStatus=204", "code=HTTP_204", "requestId=binary-log-test"); + assertThat(String.join("\n", captured.messages())) + .doesNotContain("13800000001", "secret-token", "private file content"); + verify(request, never()).getParameter(anyString()); + verify(request, never()).getParameterMap(); + verify(request, never()).getInputStream(); + assertThat(response.getContentAsByteArray()).isEmpty(); + } + } + + @Test + void downloadFailureRetainsOriginalExceptionAndHidesSensitiveMessagesAndFilePath() throws Exception { + var filter = filter("/admin-api/component-assets/**", RequestMethod.GET); + var request = new MockHttpServletRequest("GET", "/cadworld/admin-api/component-assets/13800000001-private-token.png"); + request.setContextPath("/cadworld"); + request.addHeader("X-Request-Id", "download-log-test"); + var response = new MockHttpServletResponse(); + IOException failure = new IOException("password=private-password, phone=13800000001"); + try (var captured = new ApiRequestLogCapture()) { + assertThatThrownBy(() -> new RequestIdFilter().doFilter(request, response, (req, res) -> + filter.doFilter(req, res, (innerRequest, innerResponse) -> { throw failure; }))) + .isSameAs(failure); + + assertThat(captured.events()).hasSize(2); + assertThat(captured.events().getLast().getLevel()).isEqualTo(Level.ERROR); + assertThat(captured.messages().getLast()).contains("result=FAILURE", "exceptionType=IOException", + "path=/admin-api/component-assets/**", "requestId=download-log-test"); + assertThat(String.join("\n", captured.messages())) + .doesNotContain("13800000001", "private-token", "private-password"); + assertThat(captured.events().getLast().getThrowableProxy()).isNull(); + assertThat(RequestIdHolder.get()).isNull(); + } + } + + private ApiRequestLoggingFilter filter(String path, RequestMethod method) throws Exception { + var options = new RequestMappingInfo.BuilderConfiguration(); + options.setPatternParser(PathPatternParser.defaultInstance); + var mapping = RequestMappingInfo.paths(path).methods(method).options(options).build(); + var handler = new HandlerMethod(this, getClass().getDeclaredMethod("endpoint")); + var mappings = mock(RequestMappingHandlerMapping.class); + when(mappings.getHandlerMethods()).thenReturn(Map.of(mapping, handler)); + return new ApiRequestLoggingFilter(mappings); + } + + @ApiRequestLog("测试接口") + void endpoint() { } +}