去掉component_asset表,使用明确的 DTO 和参数校验,统一 connectableTargets 格式。区分编辑版本与几何修订,普通信息修改不会让组件端口失效;过期版本返回 409。上传时校验会话和文件大小,采用流式处理,绑定失败自动清理本次上传对象。修复并发重名创建、分页参数、HTTP 状态码及失败操作日志。
This commit is contained in:
@@ -5,6 +5,8 @@ APP_DB_URL='jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEn
|
||||
APP_DB_USERNAME=
|
||||
APP_DB_PASSWORD=
|
||||
APP_STORAGE_PROVIDER=minio
|
||||
# Maximum bytes per upload, including raw PUT streams (default 100 MiB).
|
||||
APP_STORAGE_MAX_UPLOAD_BYTES=104857600
|
||||
APP_MINIO_ENDPOINT=
|
||||
APP_MINIO_ACCESS_KEY=
|
||||
APP_MINIO_SECRET_KEY=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
## 代码实现原则
|
||||
- 优先保证业务正确性、可维护性、可读性,再考虑炫技。
|
||||
- 修改代码时忽略.sql文件,如果遇到需要改表结构,直接发我sql。
|
||||
- 修改代码时忽略.sql文件,如果遇到需要改表结构,直接发我sql,要求表字段规范且有中文注释。
|
||||
## 日志规范
|
||||
- 关键业务节点必须补充必要日志,方便线上排查。
|
||||
- 不要打印密码、Token、手机号、身份证、支付密钥等敏感信息。
|
||||
|
||||
@@ -31,9 +31,47 @@ mysql -h 39.105.93.138 -P 3306 -u YOUR_USER -p cadworld < db/upgrade.sql
|
||||
mysql -h 39.105.93.138 -P 3306 -u YOUR_USER -p cadworld < db/init.sql
|
||||
```
|
||||
|
||||
两个脚本均可重复执行,不包含删表语句、数据改写或 Flyway 历史处理。增量脚本新增接口定义、历史修订、组件资源索引、操作日志表,并为 `sys_user` 增加 `deleted`。仅初始化本次业务需要的六张表;原系统其他业务表无需迁移。
|
||||
原有两个脚本保留不变。执行初始化或增量脚本后,还需执行下面的接口重构补充 SQL。当前业务使用五张表:`sys_user`、`component`、`interface_definition_v2`、`interface_definition_revision`、`sys_operation_log`;组件资源索引代码已移除。
|
||||
|
||||
用户删除保留数据及手机号唯一索引,已删除用户的手机号不能重新注册。组件删除沿用物理删除及资源索引级联清理;接口删除保留历史修订,原接口 ID 不能再次创建。删除操作不会清理 MinIO 中的资源对象。
|
||||
用户删除保留数据及手机号唯一索引,已删除用户的手机号不能重新注册。组件删除沿用物理删除;接口删除保留历史修订,原接口 ID 不能再次创建。删除操作不会清理 MinIO 中的资源对象。
|
||||
|
||||
### 接口重构补充 SQL
|
||||
|
||||
按项目约定,不改动 `.sql` 文件,新增结构单独提供。下面 SQL 需手动在目标数据库执行,可重复执行;应用不会自动迁移。先检查重复组件名,存在重复记录时需先整理,否则唯一索引无法建立。
|
||||
|
||||
<!-- schema-refactor -->
|
||||
```sql
|
||||
-- 检查已有组件名称是否重复。
|
||||
SELECT component_name, COUNT(*) AS duplicate_count
|
||||
FROM component
|
||||
GROUP BY component_name
|
||||
HAVING COUNT(*) > 1;
|
||||
|
||||
SET @cadworld_edit_revision_ddl = IF(
|
||||
EXISTS (SELECT 1 FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'interface_definition_v2' AND COLUMN_NAME = 'edit_revision'),
|
||||
'SELECT 1',
|
||||
'ALTER TABLE interface_definition_v2 ADD COLUMN edit_revision BIGINT NOT NULL DEFAULT 1 COMMENT ''编辑版本号,每次修改或源文件绑定变化时递增,用于防止旧数据覆盖''');
|
||||
PREPARE cadworld_edit_revision_statement FROM @cadworld_edit_revision_ddl;
|
||||
EXECUTE cadworld_edit_revision_statement;
|
||||
DEALLOCATE PREPARE cadworld_edit_revision_statement;
|
||||
|
||||
SET @cadworld_component_name_ddl = IF(
|
||||
EXISTS (SELECT 1 FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'component' AND INDEX_NAME = 'uk_component_name'),
|
||||
'SELECT 1',
|
||||
'ALTER TABLE component ADD UNIQUE KEY uk_component_name (component_name) COMMENT ''组件名称唯一索引,防止并发创建同名组件''');
|
||||
PREPARE cadworld_component_name_statement FROM @cadworld_component_name_ddl;
|
||||
EXECUTE cadworld_component_name_statement;
|
||||
DEALLOCATE PREPARE cadworld_component_name_statement;
|
||||
|
||||
-- 该表只重复登记模型和封面对象键,业务代码已不依赖它。
|
||||
DROP TABLE IF EXISTS component_asset;
|
||||
```
|
||||
|
||||
前端联调变更见 [后台接口文档](cadworld-adminapi/docs/admin-api.md):接口修改携带 `editRevision` 和 `geometryRevision`;组件修改携带 `componentJson.componentRevision`;原始文件 PUT 发送上传地址响应中的 `uploadHeaders`。版本冲突返回 HTTP 409,不覆盖其他人的修改。
|
||||
|
||||
## 配置与启动
|
||||
|
||||
@@ -58,6 +96,7 @@ java -jar cadworld-adminapi/target/cadworld-adminapi-0.0.1-SNAPSHOT.jar
|
||||
| APP_STORAGE_PUBLIC_API_BASE_URL | 生成上传地址所用的后台外部地址 |
|
||||
| APP_STORAGE_PUBLIC_BASE_URL | 生成下载地址的资源前缀,默认 `/admin-api/component-assets` |
|
||||
| APP_STORAGE_LOCAL_ROOT | 本地存储目录,默认 `./data/assets` |
|
||||
| APP_STORAGE_MAX_UPLOAD_BYTES | 文件上传大小限制,默认 104857600 字节;原始 PUT 流同样检查 |
|
||||
| APP_UPLOAD_SESSION_SECRET | 至少 32 个 UTF-8 字节的上传签名密钥;留空时生成进程内随机密钥,重启后原上传会话失效 |
|
||||
| APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME | 测试操作人,默认 `0 / TEST_OPERATOR` |
|
||||
| LOG_PATH | 运行日志目录,默认 `logs` |
|
||||
|
||||
@@ -69,7 +69,7 @@ JSON 请求使用 `Content-Type: application/json`。文件接口分别使用 mu
|
||||
}
|
||||
```
|
||||
|
||||
组件、用户和操作日志列表使用 `items / page / size / total`;`page` 从 1 开始,默认 1;`size` 默认 20,超过 100 按 100 处理。前端传正整数,用户和日志接口会对非正数返回 `422`。接口库列表不分页,`data` 直接为数组。
|
||||
组件、用户和操作日志列表使用 `items / page / size / total`;`page` 从 1 开始,默认 1;`size` 默认 20,超过 100 按 100 处理。前端传正整数,组件、用户和日志接口会对非正数返回 `422`。接口库列表不分页,`data` 直接为数组。
|
||||
|
||||
时间使用 ISO 本地时间,例如 `2026-10-09T17:00:00.123`,不带 `Z` 或时区偏移。日志时间及服务端维护的创建/更新时间按上海时区处理。
|
||||
|
||||
@@ -120,14 +120,15 @@ STEP 点坐标转换到接口几何前,乘以返回的 `scaleToMeters`,当
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| id | string | 创建时是 | 唯一且非空;建议不超过 64 字符;修改以路径 ID 为准 |
|
||||
| name | string | 是 | 非空,建议不超过 128 字符 |
|
||||
| description | string | 否 | 默认空串,建议不超过 500 字符 |
|
||||
| id | string | 创建时是 | 唯一且非空;最多 64 字符;修改时若提供 ID,必须与路径一致 |
|
||||
| name | string | 是 | 非空,最多 128 字符 |
|
||||
| description | string | 否 | 默认空串,最多 500 字符 |
|
||||
| geometry | object | 是 | 安装平面与完整孔组,见下表 |
|
||||
| tolerances | object | 是 | 三个容差必须提供正值 |
|
||||
| displayForward | number[3] | 否 | 安装面内的默认前方;不传则服务端生成,不能平行于面法向 |
|
||||
| connectableTargets | string[] | 否 | 可连接目标路径,一维字符串数组;例如 `["机械臂/末端工具", "移动底盘/附件"]` |
|
||||
| geometryRevision | integer | 修改时是 | 详情返回的当前修订号;创建自动为 1 |
|
||||
| geometryRevision | integer | 修改时是 | 当前几何修订号;创建自动为 1,几何、容差或源文件变化时递增 |
|
||||
| editRevision | integer | 修改时是 | 当前编辑版本;创建为 1,每次修改或源文件绑定变化时递增;从详情/保存响应取值 |
|
||||
| sourceAssetKey | string | 否 | 源文件上传后返回的存储 Key;前端不能通过保存定义直接绑定文件 |
|
||||
| sourceGeometryHash | string | 否 | 已绑定源文件的 SHA-256,通常带 `sha256:`;源文件变更时可随保存传入新哈希以清除旧绑定,最终绑定由上传源文件接口完成 |
|
||||
|
||||
@@ -237,7 +238,8 @@ X-Request-Id: req-demo-001
|
||||
"connectableTargets": [
|
||||
"机械臂/末端工具",
|
||||
"移动底盘/附件"
|
||||
]
|
||||
],
|
||||
"editRevision": 1
|
||||
}
|
||||
],
|
||||
"requestId": "req-demo-001"
|
||||
@@ -330,7 +332,8 @@ X-Request-Id: req-demo-001
|
||||
"connectableTargets": [
|
||||
"机械臂/末端工具",
|
||||
"移动底盘/附件"
|
||||
]
|
||||
],
|
||||
"editRevision": 1
|
||||
},
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
@@ -487,7 +490,8 @@ Content-Type: application/json
|
||||
"connectableTargets": [
|
||||
"机械臂/末端工具",
|
||||
"移动底盘/附件"
|
||||
]
|
||||
],
|
||||
"editRevision": 1
|
||||
},
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
@@ -499,7 +503,7 @@ Content-Type: application/json
|
||||
|
||||
`PUT /admin-api/interfaces/{id}`
|
||||
|
||||
请求字段见 2.1,必须携带当前 `geometryRevision`,并提交完整定义。省略描述、目标或展示方向可能将其恢复为空值/默认值。
|
||||
请求字段见 2.1,必须携带当前 `geometryRevision` 和 `editRevision`,并提交完整定义。省略描述、目标或展示方向可能将其恢复为空值/默认值。
|
||||
|
||||
**请求示例**
|
||||
|
||||
@@ -573,7 +577,8 @@ Content-Type: application/json
|
||||
"机械臂/末端工具",
|
||||
"移动底盘/附件"
|
||||
],
|
||||
"geometryRevision": 1
|
||||
"geometryRevision": 1,
|
||||
"editRevision": 1
|
||||
}
|
||||
```
|
||||
|
||||
@@ -587,7 +592,7 @@ Content-Type: application/json
|
||||
"id": "mount-2-hole",
|
||||
"name": "双孔安装接口",
|
||||
"description": "更新后的接口说明",
|
||||
"geometryRevision": 2,
|
||||
"geometryRevision": 1,
|
||||
"geometry": {
|
||||
"plane": {
|
||||
"pointM": [
|
||||
@@ -646,16 +651,17 @@ Content-Type: application/json
|
||||
"机械臂/末端工具",
|
||||
"移动底盘/附件"
|
||||
],
|
||||
"sourceAssetKey": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/plate.step",
|
||||
"sourceGeometryHash": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7"
|
||||
"sourceAssetKey": "",
|
||||
"sourceGeometryHash": "",
|
||||
"editRevision": 2
|
||||
},
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
```
|
||||
|
||||
示例从修订 1 更新为 2。修改名称、描述、孔组、容差或可连接目标等会产生新修订;仅展示方向变化且其他内容不变时通常保留修订号。始终以响应为准。
|
||||
名称、描述、可连接目标或展示方向修改只增加 `editRevision`,不增加 `geometryRevision`。几何、容差或源文件变化才产生新几何修订。下面示例只修改描述,几何修订仍为 1、编辑版本变为 2;始终以响应为准。
|
||||
|
||||
旧修订仍保留历史快照。修订号不匹配返回 `422 / INVALID_INTERFACE`;前端应重新查询详情,再提示用户重新确认修改。引用旧修订的组件端口,在下一次保存组件时需要重新计算并确认。
|
||||
旧修订仍保留历史快照。编辑版本或几何修订号不匹配返回 `409 / INTERFACE_REVISION_CONFLICT`;前端应重新查询详情并保留本地编辑内容,再由用户确认合并。引用旧修订的组件端口,在下一次保存组件时需要重新计算并确认。
|
||||
|
||||
### 2.6 删除接口
|
||||
|
||||
@@ -702,7 +708,7 @@ X-Request-Id: req-demo-001
|
||||
|
||||
先保存接口定义,再上传源文件。后端校验修订号,计算文件 SHA-256,并更新当前修订的源文件绑定。该接口本身不执行 STEP 解析或校验文件拓扑;需要精确解析时先调用第 5 节接口。
|
||||
|
||||
单个文件和整个 multipart 请求默认均限制 100 MB;边界开销也占请求大小。当前修订已有不同内容的源文件时,绑定会被拒绝,应按源文件变更流程先保存新修订。
|
||||
单个文件和整个 multipart 请求默认均限制 100 MB;边界开销也占请求大小。源文件还受存储上传大小限制,绑定失败会补偿清理本次上传对象。上传成功后重新查询接口详情,取得最新 `editRevision`。当前修订已有不同内容的源文件时,绑定会被拒绝,应按源文件变更流程先保存新修订。
|
||||
|
||||
**请求示例**
|
||||
|
||||
@@ -720,12 +726,12 @@ curl -X POST 'http://127.0.0.1:8992/admin-api/interfaces/mount-2-hole/assets?geo
|
||||
{
|
||||
"code": "OK",
|
||||
"message": "success",
|
||||
"data": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/plate.step",
|
||||
"data": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/22222222-2222-4222-8222-222222222222/plate.step",
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
```
|
||||
|
||||
成功 `data` 是对象 Key 字符串,不是 URL。再调用接口详情可获得 `sourceAssetKey` 和 `sourceGeometryHash`。源文件可通过 `/admin-api/component-assets/{objectKey}` 下载,对象路径各段需要 URL 编码。
|
||||
成功 `data` 是对象 Key 字符串,不是 URL;Key 含本次上传的随机路径段,应保存服务端返回值,不要自行推导。再调用接口详情可获得 `sourceAssetKey` 和 `sourceGeometryHash`。源文件可通过 `/admin-api/component-assets/{objectKey}` 下载,对象路径各段需要 URL 编码。
|
||||
|
||||
**上传后的详情示例:HTTP 200**
|
||||
|
||||
@@ -796,8 +802,9 @@ curl -X POST 'http://127.0.0.1:8992/admin-api/interfaces/mount-2-hole/assets?geo
|
||||
"机械臂/末端工具",
|
||||
"移动底盘/附件"
|
||||
],
|
||||
"sourceAssetKey": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/plate.step",
|
||||
"sourceGeometryHash": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7"
|
||||
"sourceAssetKey": "interfaces/6d6f756e742d322d686f6c65/1/073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7/22222222-2222-4222-8222-222222222222/plate.step",
|
||||
"sourceGeometryHash": "sha256:073b7cf3dbe11a465f34da53b9b5e765a489e970cbb0f6c3c2d8cd01553aedc7",
|
||||
"editRevision": 2
|
||||
},
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
@@ -1010,7 +1017,7 @@ Content-Type: application/json
|
||||
| selectedPose | object | 是 | 至少提供当前候选 `id`;建议同时复制候选的姿态、孔映射和方向字段 |
|
||||
| sourceGeometryHash | string | 是 | 与计算候选时一致的 URDF 源几何哈希 |
|
||||
| solverVersion | string | 是 | 复制候选集返回值,当前为 `mount-geometry-3` |
|
||||
| connectableTargets | array | 否 | 不传或为空时使用模板目标;多目标建议采用二维路径数组,见下文 |
|
||||
| connectableTargets | array | 否 | 不传或为空时使用模板目标;一维数组表示多个独立目标;兼容二维 Cascader 路径数组 |
|
||||
|
||||
**请求示例**
|
||||
|
||||
@@ -1211,7 +1218,7 @@ Content-Type: application/json
|
||||
|
||||
服务端依据候选 `id` 重新计算,返回规范化端口;提交的旋转和孔映射不会作为最终可信结果。该接口只计算和确认,不自动保存组件。
|
||||
|
||||
**可连接目标的输入兼容规则**:接口定义 CRUD 使用一维路径字符串数组;`confirm-port` 和 `componentJson.interfaces` 会把一维字符串数组视为“一条级联路径”,例如 `["机械臂", "末端工具"]` 被合并为 `"机械臂/末端工具"`。多个目标请提交二维数组,例如 `[["机械臂", "末端工具"], ["移动底盘", "附件"]]`。返回统一为一维路径字符串数组。将确认结果用于保存组件时,多目标应先转换为二维数组,避免被合并为一条路径。
|
||||
**可连接目标的输入兼容规则**:接口定义、姿态确认和组件端口统一使用一维路径字符串数组,例如 `["机械臂/末端工具", "移动底盘/附件"]` 表示两个独立目标;兼容二维 Cascader 路径数组 `[["机械臂", "末端工具"], ["移动底盘", "附件"]]`。返回始终为一维字符串数组,可以直接用于后续确认和组件保存,无需再次转换。
|
||||
|
||||
<a id="components"></a>
|
||||
|
||||
@@ -1261,7 +1268,7 @@ Content-Type: application/json
|
||||
|
||||
`componentJson.interfaces` 非空时,必须同时提供原始 `urdfSource` 快照、资源清单以及已经确认的端口。后端会核对源文件资源、link、源哈希、模板当前修订和选中候选;不能只填端口名称和坐标。详见 8.3。
|
||||
|
||||
每次成功新增/修改会由后端写入或递增 `componentJson.componentRevision`。存在 `interfaces` 数组时会返回 `interfaceSchemaVersion: 3`;前端不自行生成这些版本值。
|
||||
每次成功新增/修改会由后端写入或递增 `componentJson.componentRevision`。修改时必须携带详情返回的当前值;缺少版本返回 `422 / INVALID_COMPONENT_REVISION`,版本冲突返回 `409 / COMPONENT_REVISION_CONFLICT`,旧数据不会覆盖新记录。历史组件未包含该字段时按 0 处理,修改时传 0。存在 `interfaces` 数组时会返回 `interfaceSchemaVersion: 3`;前端不自行生成这些版本值。
|
||||
|
||||
### 3.2 查询组件列表
|
||||
|
||||
@@ -1776,7 +1783,7 @@ Content-Type: application/json
|
||||
|
||||
`PUT /admin-api/components/{id}`
|
||||
|
||||
请求字段同新增。使用完整必填字段;省略分类、封面和描述会将这些可选文本重置为空。
|
||||
请求字段同新增,另须在 `componentJson` 中携带详情返回的 `componentRevision`。使用完整必填字段;省略分类、封面和描述会将这些可选文本重置为空。
|
||||
|
||||
**请求示例**
|
||||
|
||||
@@ -1894,7 +1901,8 @@ Content-Type: application/json
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
"componentRevision": 1
|
||||
},
|
||||
"assemblyMetadata": {
|
||||
"tags": [
|
||||
@@ -2160,7 +2168,10 @@ Content-Type: application/json
|
||||
"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"
|
||||
"objectKey": "components/cover-images/0/20261009/22222222-2222-4222-8222-222222222222/cover.png",
|
||||
"uploadHeaders": {
|
||||
"X-Upload-Session-Token": "<uploadSessionToken>"
|
||||
}
|
||||
},
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
@@ -2280,7 +2291,10 @@ Content-Type: application/json
|
||||
"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"
|
||||
"objectKey": "components/urdf/0/20261009/11111111-1111-4111-8111-111111111111/robot.urdf",
|
||||
"uploadHeaders": {
|
||||
"X-Upload-Session-Token": "<uploadSessionToken>"
|
||||
}
|
||||
},
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
@@ -2349,6 +2363,7 @@ Content-Type: application/json
|
||||
| 位置 | 字段 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| Query | objectKey | 是 | 获取上传地址返回的完整对象 Key;应直接使用返回的 `uploadUrl` |
|
||||
| Header | X-Upload-Session-Token | 是 | 获取上传地址返回的 `uploadHeaders` 中的会话凭证;使用同一会话的当前值 |
|
||||
| Header | Content-Type | 否 | 真实文件 MIME 类型;省略时按通用二进制类型处理 |
|
||||
| Body | 文件二进制 | 是 | 直接发送 File/Blob/ArrayBuffer;不用 FormData,不做 JSON 或 Base64 包装 |
|
||||
|
||||
@@ -2358,6 +2373,7 @@ Content-Type: application/json
|
||||
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-Upload-Session-Token: <uploadSessionToken>' \
|
||||
-H 'X-Request-Id: req-demo-001' \
|
||||
--data-binary '@./robot.urdf'
|
||||
```
|
||||
@@ -2369,9 +2385,9 @@ HTTP/1.1 204 No Content
|
||||
X-Request-Id: req-demo-001
|
||||
```
|
||||
|
||||
响应体为空,不执行 `response.json()`。失败时仍按第 9 节处理 JSON 错误响应。当前应用只允许写入配置操作人的组件资源目录;接口源文件通过第 2.7 节上传。
|
||||
响应体为空,不执行 `response.json()`。失败时仍按第 9 节处理 JSON 错误响应。后端在实际 PUT 时校验会话签名、签发者、有效期、操作人和精确会话目录;不能直接拼接对象路径绕过会话。接口源文件通过第 2.7 节上传。
|
||||
|
||||
这里的 PUT 是原始文件流,Spring multipart 的 100 MB 限制不直接作用于此接口;实际大小还可能受到部署网关限制,前端应与部署环境保持一致。
|
||||
原始 PUT 和接口源文件上传均受 `APP_STORAGE_MAX_UPLOAD_BYTES` 限制,默认 104857600 字节(100 MiB)。缺少 Content-Length 的流式上传同样检查实际读取大小;超限返回 `413 / UPLOAD_TOO_LARGE`。部署网关还可设置更小的限制。
|
||||
|
||||
### 4.2 下载或读取资源
|
||||
|
||||
@@ -3067,7 +3083,7 @@ async function uploadModel(files) {
|
||||
const response = await fetch(prepared.uploadUrl, {
|
||||
method: 'PUT',
|
||||
headers: { ...prepared.uploadHeaders, 'Content-Type': contentType },
|
||||
body: file
|
||||
body: file
|
||||
});
|
||||
if (response.status !== 204) {
|
||||
// 失败通常为 JSON;如网关返回非 JSON,保留 HTTP 状态信息。
|
||||
@@ -3089,7 +3105,7 @@ async function uploadModel(files) {
|
||||
### 8.3 保存带机械端口的组件
|
||||
|
||||
1. 取得接口模板详情,记录 `geometryRevision`;编辑模板时还需携带 `editRevision`。
|
||||
2. 保存原始 URDF XML 快照,并为其引用的网格/纹理建立资源清单;资源先通过模型会话上传。
|
||||
2. 保存原始 URDF XML 快照,并为其引用的网格/纹理建立资源清单;资源先通过模型会话上传。
|
||||
3. 用 link 局部坐标中的实际几何调用 `/pose-candidates`。
|
||||
4. 用户选择候选后,携带候选 ID、对应修订和源哈希调用 `/confirm-port`。
|
||||
5. 将规范化端口加入 `componentJson.interfaces`;按照 2.9 处理多目标路径的输入格式。
|
||||
@@ -3153,11 +3169,11 @@ sourceGeometryHash = SHA256(documentHash + "\n" + manifest)
|
||||
```
|
||||
|
||||
**接口编辑版本过期失败示例:HTTP 409**
|
||||
|
||||
|
||||
```json
|
||||
{
|
||||
"code": "INTERFACE_REVISION_CONFLICT",
|
||||
"message": "接口已修改,请刷新后保存",
|
||||
"message": "接口已修改,请刷新后保存",
|
||||
"requestId": "req-demo-001"
|
||||
}
|
||||
```
|
||||
@@ -3176,7 +3192,14 @@ sourceGeometryHash = SHA256(documentHash + "\n" + manifest)
|
||||
| --- | --- | --- |
|
||||
| 422 | INVALID_REQUEST | 必填、字段长度、枚举、JSON 格式、参数类型或几何结构不合法,提示修改输入 |
|
||||
| 422 | INVALID_INTERFACE / INVALID_INTERFACE_ASSET | 接口业务校验或源文件绑定不合法 |
|
||||
| 409 | USER_PHONE_DUPLICATE | 手机号冲突,已删除用户也会占用手机号 |
|
||||
| 404 | INTERFACE_NOT_FOUND | 当前接口定义不存在 |
|
||||
| 409 | INTERFACE_ID_DUPLICATE | 接口 ID 已占用或归档 |
|
||||
| 409 | INTERFACE_REVISION_CONFLICT / COMPONENT_REVISION_CONFLICT | 编辑数据已过期;重新查询详情并确认修改 |
|
||||
| 422 | INVALID_COMPONENT_REVISION | 修改组件缺少合法的客户端版本 |
|
||||
| 405 | INVALID_REQUEST | HTTP 方法不支持,检查 Allow 响应头 |
|
||||
| 415 | INVALID_REQUEST | Content-Type 不支持 |
|
||||
| 413 | UPLOAD_TOO_LARGE | 文件超出存储上传大小限制 |
|
||||
| 409 | USER_PHONE_DUPLICATE | 手机号冲突,已删除用户也会占用手机号 |
|
||||
| 404 | USER_NOT_FOUND | 用户不存在或已删除 |
|
||||
| 409 | COMPONENT_NAME_DUPLICATE | 组件名称重复 |
|
||||
| 404 | COMPONENT_NOT_FOUND | 组件不存在 |
|
||||
@@ -3193,7 +3216,7 @@ sourceGeometryHash = SHA256(documentHash + "\n" + manifest)
|
||||
| 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 / MINIO_DELETE_FAILED | 存储连接、权限或读写失败,联系后端 |
|
||||
| 404 | MINIO_OBJECT_NOT_FOUND | 资源对象不存在 |
|
||||
| 404 | MINIO_OBJECT_NOT_FOUND | 资源对象不存在 |
|
||||
| 422 | INVALID_STORAGE_OBJECT_KEY | 存储对象 Key 不合法 |
|
||||
| 503 | DATABASE_UNAVAILABLE | 数据库连接不可用,联系后端 |
|
||||
| 500 | INTERNAL_ERROR | 未分类系统异常,反馈 requestId |
|
||||
|
||||
+30
-5
@@ -12,6 +12,10 @@ import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
import org.springframework.web.util.ServletRequestPathUtils;
|
||||
import org.springframework.web.util.pattern.PathPattern;
|
||||
|
||||
/** Multipart size failures can occur before an MVC interceptor is invoked. */
|
||||
@Slf4j
|
||||
@@ -35,16 +39,15 @@ public class EarlyFailureAuditFilter extends OncePerRequestFilter {
|
||||
chain.doFilter(request, response);
|
||||
} finally {
|
||||
if (response.getStatus() >= 400 && request.getAttribute(OperationAuditInterceptor.CONTEXT) == null
|
||||
&& request.getRequestURI().startsWith("/admin-api/")) {
|
||||
&& request.getRequestURI().startsWith(request.getContextPath() + "/admin-api/")) {
|
||||
try {
|
||||
// DispatcherServlet clears its parsed path before returning to filters.
|
||||
org.springframework.web.util.ServletRequestPathUtils.parseAndCache(request);
|
||||
var handler = mappings.getHandler(request);
|
||||
var handler = resolveWriteHandler(request);
|
||||
if (handler != null) {
|
||||
audit.preHandle(request, response, handler.getHandler());
|
||||
audit.preHandle(request, response, handler);
|
||||
if (request.getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
|
||||
request.setAttribute(OperationAuditInterceptor.CONTEXT, new OperationAuditInterceptor.Context(context.event(), started));
|
||||
audit.afterCompletion(request, response, handler.getHandler(), null);
|
||||
audit.afterCompletion(request, response, handler, null);
|
||||
}
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
@@ -53,4 +56,26 @@ public class EarlyFailureAuditFilter extends OncePerRequestFilter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HandlerMethod resolveWriteHandler(HttpServletRequest request) {
|
||||
ServletRequestPathUtils.parseAndCache(request);
|
||||
HandlerMethod best = null;
|
||||
PathPattern bestPattern = null;
|
||||
for (var entry : mappings.getHandlerMethods().entrySet()) {
|
||||
if (!entry.getValue().hasMethodAnnotation(AuditOperation.class)
|
||||
|| entry.getKey().getMethodsCondition().getMatchingCondition(request) == null) continue;
|
||||
var paths = entry.getKey().getPathPatternsCondition().getMatchingCondition(request);
|
||||
if (paths == null) continue;
|
||||
PathPattern pattern = paths.getFirstPattern();
|
||||
if (bestPattern == null || pattern.compareTo(bestPattern) < 0) {
|
||||
best = entry.getValue();
|
||||
bestPattern = pattern;
|
||||
}
|
||||
}
|
||||
if (bestPattern != null) {
|
||||
var match = bestPattern.matchAndExtract(ServletRequestPathUtils.getParsedRequestPath(request).pathWithinApplication());
|
||||
if (match != null) request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, match.getUriVariables());
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -41,11 +41,13 @@ public class ComponentAssetController {
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void upload(
|
||||
@RequestParam String objectKey,
|
||||
@RequestHeader(ComponentUploadSupport.UPLOAD_TOKEN_HEADER) String uploadSessionToken,
|
||||
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
|
||||
HttpServletRequest request
|
||||
) throws IOException {
|
||||
componentUploadSupport.uploadObject(
|
||||
operatorProvider.userId(),
|
||||
uploadSessionToken,
|
||||
objectKey,
|
||||
contentType,
|
||||
request.getInputStream(),
|
||||
|
||||
+5
-2
@@ -23,7 +23,9 @@ import com.linkerbot.cadworld.service.ComponentCoverImageUploadService;
|
||||
import com.linkerbot.cadworld.service.ComponentService;
|
||||
import com.linkerbot.cadworld.service.ComponentUrdfUploadService;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -37,6 +39,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/components")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class ComponentController {
|
||||
|
||||
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
|
||||
@@ -109,8 +112,8 @@ public class ComponentController {
|
||||
@ApiRequestLog("查询组件列表")
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<ComponentListItemResponse>> list(
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size,
|
||||
@RequestParam(defaultValue = "1") @Min(1) long page,
|
||||
@RequestParam(defaultValue = "20") @Min(1) long size,
|
||||
@RequestParam(required = false) String keyword
|
||||
) {
|
||||
return ApiResponse.success(componentService.listComponents(page, Math.min(size, 100), keyword));
|
||||
|
||||
+41
-37
@@ -1,66 +1,70 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||
import com.linkerbot.cadworld.dto.interfaces.SaveInterfaceDefinitionRequest;
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
import com.linkerbot.cadworld.service.InterfaceAssetService;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/interfaces")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class InterfaceDefinitionController {
|
||||
private final InterfaceDefinitionService service;
|
||||
private final ObjectStorageClient objectStorageClient;
|
||||
private final InterfaceAssetService assets;
|
||||
|
||||
@ApiRequestLog("查询接口列表")
|
||||
@GetMapping public ApiResponse<List<JsonNode>> list(@RequestParam(required = false) String keyword) { return ApiResponse.success(service.list(keyword)); }
|
||||
@GetMapping
|
||||
public ApiResponse<List<JsonNode>> list(@RequestParam(required = false) String keyword) {
|
||||
return ApiResponse.success(service.list(keyword));
|
||||
}
|
||||
|
||||
@ApiRequestLog("查询接口详情")
|
||||
@GetMapping("/{id}") public ApiResponse<JsonNode> get(@PathVariable String id) { return ApiResponse.success(service.get(id)); }
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<JsonNode> get(@PathVariable String id) {
|
||||
return ApiResponse.success(service.get(id));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "CREATE")
|
||||
@ApiRequestLog("新增接口定义")
|
||||
@PostMapping public ApiResponse<JsonNode> create(@RequestBody JsonNode request) { return ApiResponse.success(service.create(request)); }
|
||||
@PostMapping
|
||||
public ApiResponse<JsonNode> create(@Valid @RequestBody SaveInterfaceDefinitionRequest request) {
|
||||
return ApiResponse.success(service.create(request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "UPDATE")
|
||||
@ApiRequestLog("修改接口定义")
|
||||
@PutMapping("/{id}") public ApiResponse<JsonNode> update(@PathVariable String id, @RequestBody JsonNode request) { return ApiResponse.success(service.update(id, request)); }
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<JsonNode> update(@PathVariable String id, @Valid @RequestBody SaveInterfaceDefinitionRequest request) {
|
||||
return ApiResponse.success(service.update(id, request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "DELETE")
|
||||
@ApiRequestLog("删除接口定义")
|
||||
@DeleteMapping("/{id}") public ApiResponse<SuccessResponse> delete(@PathVariable String id) { service.delete(id); return ApiResponse.success(SuccessResponse.ok()); }
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResponse<SuccessResponse> delete(@PathVariable String id) {
|
||||
service.delete(id);
|
||||
return ApiResponse.success(SuccessResponse.ok());
|
||||
}
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "UPLOAD")
|
||||
@ApiRequestLog("上传接口源文件")
|
||||
@PostMapping("/{id}/assets")
|
||||
@PostMapping(value = "/{id}/assets", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ApiResponse<String> uploadAsset(@PathVariable String id,
|
||||
@RequestParam int geometryRevision,
|
||||
@RequestPart("file") MultipartFile file) throws IOException {
|
||||
if (file == null || file.isEmpty()) throw new IllegalArgumentException("接口源文件不能为空");
|
||||
String name = file.getOriginalFilename() == null ? "source.step" : file.getOriginalFilename().replace('\\', '/');
|
||||
name = name.substring(name.lastIndexOf('/') + 1).replaceAll("[^A-Za-z0-9._-]", "_");
|
||||
if(service.get(id).path("geometryRevision").asInt()!=geometryRevision)throw new IllegalArgumentException("接口已修订,请刷新");
|
||||
String key;
|
||||
{
|
||||
try {
|
||||
byte[] bytes = file.getBytes();
|
||||
String hash = java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
key = "interfaces/" + java.util.HexFormat.of().formatHex(id.getBytes(java.nio.charset.StandardCharsets.UTF_8)) + "/" + geometryRevision + "/" + hash + "/" + name;
|
||||
objectStorageClient.putObject(key, file.getContentType(), new java.io.ByteArrayInputStream(bytes), bytes.length);
|
||||
service.attachAsset(id, geometryRevision, key, "sha256:" + hash);
|
||||
} catch (NoSuchAlgorithmException exception) {
|
||||
throw new IllegalStateException("SHA-256 不可用", exception);
|
||||
}
|
||||
}
|
||||
return ApiResponse.success(key);
|
||||
@RequestParam @Min(1) int geometryRevision,
|
||||
@RequestPart("file") MultipartFile file) {
|
||||
return ApiResponse.success(assets.upload(id, geometryRevision, file));
|
||||
}
|
||||
}
|
||||
|
||||
+35
-38
@@ -1,60 +1,57 @@
|
||||
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;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.CandidateSet;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.Port;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.PoseRequest;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import java.io.IOException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/interfaces/{id}")
|
||||
public class InterfacePoseController {
|
||||
private final InterfaceDefinitionService definitions;
|
||||
private final MechanicalInterfaceSolver solver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@ApiRequestLog("计算接口姿态候选")
|
||||
@PostMapping("/pose-candidates")
|
||||
public ApiResponse<CandidateSet> candidates(@PathVariable String id,@RequestBody JsonNode body){
|
||||
PoseRequest request=read(body,PoseRequest.class);
|
||||
return ApiResponse.success(solver.enumeratePortPoses(definitions.geometryDefinition(id,request.definitionRevision()),request));
|
||||
public ApiResponse<CandidateSet> candidates(@PathVariable String id, @RequestBody JsonNode body) {
|
||||
PoseRequest request = read(body, PoseRequest.class);
|
||||
var definition = definitions.geometryDefinition(id, request.definitionRevision());
|
||||
return ApiResponse.success(solver.enumeratePortPoses(definition, request));
|
||||
}
|
||||
|
||||
@ApiRequestLog("确认组件端口姿态")
|
||||
@PostMapping("/confirm-port")
|
||||
public ApiResponse<Port> confirm(@PathVariable String id,@RequestBody JsonNode body){
|
||||
Port request=read(body,Port.class);
|
||||
if(!id.equals(request.definitionId()))throw new IllegalArgumentException("URL 与端口定义不一致");
|
||||
return ApiResponse.success(solver.confirmPortPose(definitions.geometryDefinition(id,request.definitionRevision()),request));
|
||||
}
|
||||
private <T> T read(JsonNode body,Class<T> type){
|
||||
try{return objectMapper.readerFor(type).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(normalizePortBody(body));}
|
||||
catch(java.io.IOException | IllegalArgumentException e){throw new IllegalArgumentException("不支持的接口数据结构:"+rootMessage(e),e);}
|
||||
}
|
||||
private JsonNode normalizePortBody(JsonNode body){
|
||||
if(body==null||!body.isObject())return body;
|
||||
ObjectNode copy=body.deepCopy();JsonNode targets=copy.get("connectableTargets");
|
||||
if(targets!=null&&!targets.isNull()){
|
||||
ArrayNode normalized=objectMapper.createArrayNode();flattenTargets(targets,normalized);copy.set("connectableTargets",normalized);
|
||||
public ApiResponse<Port> confirm(@PathVariable String id, @RequestBody JsonNode body) {
|
||||
Port request = read(body, Port.class);
|
||||
if (!id.equals(request.definitionId())) {
|
||||
throw new IllegalArgumentException("URL 与端口定义不一致");
|
||||
}
|
||||
return copy;
|
||||
var definition = definitions.geometryDefinition(id, request.definitionRevision());
|
||||
return ApiResponse.success(solver.confirmPortPose(definition, request));
|
||||
}
|
||||
private void flattenTargets(JsonNode node,ArrayNode output){
|
||||
if(node==null||node.isNull())return;
|
||||
if(node.isArray()){
|
||||
boolean path=true;StringBuilder joined=new StringBuilder();
|
||||
for(JsonNode child:node){if(!child.isTextual()){path=false;break;}if(joined.length()>0)joined.append('/');joined.append(child.asText());}
|
||||
if(path){String value=joined.toString().trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);return;}
|
||||
node.forEach(child->flattenTargets(child,output));return;
|
||||
|
||||
private <T> T read(JsonNode body, Class<T> type) {
|
||||
try {
|
||||
return objectMapper.readerFor(type).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(body);
|
||||
} catch (IOException | IllegalArgumentException exception) {
|
||||
throw new IllegalArgumentException("不支持的接口数据结构:" + rootMessage(exception), exception);
|
||||
}
|
||||
String value=node.asText("").trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);
|
||||
}
|
||||
private boolean containsTarget(ArrayNode output,String value){for(JsonNode item:output)if(value.equals(item.asText()))return true;return false;}
|
||||
private String rootMessage(Throwable error){Throwable current=error;while(current.getCause()!=null)current=current.getCause();return current.getMessage()==null?"字段格式错误":current.getMessage();}
|
||||
|
||||
private String rootMessage(Throwable error) {
|
||||
Throwable current = error;
|
||||
while (current.getCause() != null) current = current.getCause();
|
||||
return current.getMessage() == null ? "字段格式错误" : current.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ app:
|
||||
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}/admin-api/component-assets}
|
||||
local-root: ${APP_STORAGE_LOCAL_ROOT:./data/assets}
|
||||
upload-session-ttl: PT30M
|
||||
max-upload-bytes: ${APP_STORAGE_MAX_UPLOAD_BYTES:104857600}
|
||||
minio:
|
||||
endpoint: ${APP_MINIO_ENDPOINT:}
|
||||
access-key: ${APP_MINIO_ACCESS_KEY:}
|
||||
|
||||
@@ -40,7 +40,8 @@ class AdminApiTest {
|
||||
|
||||
@BeforeEach
|
||||
void clean() {
|
||||
for (String table : new String[]{"component_asset", "component", "interface_definition_revision", "interface_definition_v2", "sys_user", "sys_operation_log"}) {
|
||||
TestSchemaSupport.prepare(jdbc);
|
||||
for (String table : new String[]{"component", "interface_definition_revision", "interface_definition_v2", "sys_user", "sys_operation_log"}) {
|
||||
jdbc.update("DELETE FROM " + table);
|
||||
}
|
||||
}
|
||||
@@ -143,7 +144,9 @@ class AdminApiTest {
|
||||
JsonNode result = send("/admin-api/components", component("sample"));
|
||||
long id = result.path("data").path("id").asLong();
|
||||
assertThat(result.path("data").path("sourceUrl").asText()).contains("/admin-api/component-assets/");
|
||||
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(component("renamed"))))
|
||||
var update = json.valueToTree(component("renamed"));
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) update).set("componentJson", result.path("data").path("componentJson"));
|
||||
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON).content(update.toString()))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components")).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components/{id}", id)).andExpect(status().isOk());
|
||||
@@ -173,16 +176,17 @@ class AdminApiTest {
|
||||
JsonNode created = send("/admin-api/interfaces", request).path("data");
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) created).put("name", "新版");
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.geometryRevision").value(2));
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.geometryRevision").value(1))
|
||||
.andExpect(jsonPath("$.data.editRevision").value(2));
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM interface_definition_revision", Long.class)).isEqualTo(2);
|
||||
.andExpect(status().isConflict());
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM interface_definition_revision", Long.class)).isEqualTo(1);
|
||||
mvc.perform(get("/admin-api/interfaces")).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/interfaces/mount")).andExpect(status().isOk());
|
||||
assertThat(logCount()).isEqualTo(4);
|
||||
// Historical revisions survive deletion and still prohibit ID reuse.
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(request.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
.andExpect(status().isConflict());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -193,7 +197,9 @@ class AdminApiTest {
|
||||
Map.of("uploadSessionToken", token, "objectPath", "cover.png", "contentType", "image/png")).path("data");
|
||||
assertThat(upload.path("uploadUrl").asText()).contains("/admin-api/component-assets/upload");
|
||||
String key = upload.path("objectKey").asText();
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key).contentType("image/png").content(new byte[]{1, 2, 3}))
|
||||
assertThat(upload.path("uploadHeaders").path("X-Upload-Session-Token").asText()).isEqualTo(token);
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key)
|
||||
.header("X-Upload-Session-Token", token).contentType("image/png").content(new byte[]{1, 2, 3}))
|
||||
.andExpect(status().isNoContent());
|
||||
send("/admin-api/components/cover-image-upload-sessions/complete", Map.of("uploadSessionToken", token, "objectKeys", new String[]{key}));
|
||||
mvc.perform(get("/admin-api/component-assets/" + key)).andExpect(status().isOk()).andExpect(content().bytes(new byte[]{1, 2, 3}));
|
||||
@@ -201,6 +207,33 @@ class AdminApiTest {
|
||||
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString()).doesNotContain(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceUploadBindsHashAndRetriesWithoutChangingGeometryOrLeakingNewKeys() throws Exception {
|
||||
send("/admin-api/interfaces", interfaceRequest("source-upload"));
|
||||
byte[] bytes = {1, 2, 3};
|
||||
var file = new org.springframework.mock.web.MockMultipartFile("file", "plate.step", "application/octet-stream", bytes);
|
||||
var response = mvc.perform(multipart("/admin-api/interfaces/source-upload/assets")
|
||||
.file(file).param("geometryRevision", "1")).andExpect(status().isOk()).andReturn();
|
||||
String key = json.readTree(response.getResponse().getContentAsString()).path("data").asText();
|
||||
mvc.perform(get("/admin-api/interfaces/source-upload"))
|
||||
.andExpect(jsonPath("$.data.geometryRevision").value(1))
|
||||
.andExpect(jsonPath("$.data.editRevision").value(2))
|
||||
.andExpect(jsonPath("$.data.sourceAssetKey").value(key))
|
||||
.andExpect(jsonPath("$.data.sourceGeometryHash").value(
|
||||
"sha256:039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81"));
|
||||
mvc.perform(multipart("/admin-api/interfaces/source-upload/assets").file(file).param("geometryRevision", "1"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data").value(key));
|
||||
mvc.perform(get("/admin-api/interfaces/source-upload")).andExpect(jsonPath("$.data.editRevision").value(2));
|
||||
mvc.perform(multipart("/admin-api/interfaces/source-upload/assets")
|
||||
.file(new org.springframework.mock.web.MockMultipartFile("file", "plate.step", "application/octet-stream", new byte[]{9}))
|
||||
.param("geometryRevision", "1"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(multipart("/admin-api/interfaces/source-upload/assets").file(file).param("geometryRevision", "2"))
|
||||
.andExpect(status().isConflict());
|
||||
mvc.perform(get("/admin-api/component-assets/" + key)).andExpect(status().isOk()).andExpect(content().bytes(bytes));
|
||||
assertThat(logCount()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiresNewLogSurvivesOuterRollbackAndOldRoutesAreAbsent() throws Exception {
|
||||
transactions.executeWithoutResult(tx -> {
|
||||
@@ -229,6 +262,144 @@ class AdminApiTest {
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleAndConcurrentComponentUpdatesCannotOverwriteEachOther() throws Exception {
|
||||
JsonNode created = send("/admin-api/components", component("concurrent")).path("data");
|
||||
long id = created.path("id").asLong();
|
||||
var body = (com.fasterxml.jackson.databind.node.ObjectNode) json.valueToTree(component("editor"));
|
||||
body.set("componentJson", created.get("componentJson"));
|
||||
var gate = new java.util.concurrent.CountDownLatch(1);
|
||||
try (var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) {
|
||||
java.util.concurrent.Callable<Integer> update = () -> {
|
||||
gate.await();
|
||||
return mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(body.toString())).andReturn().getResponse().getStatus();
|
||||
};
|
||||
var first = workers.submit(update);
|
||||
var second = workers.submit(update);
|
||||
gate.countDown();
|
||||
assertThat(java.util.List.of(first.get(10, java.util.concurrent.TimeUnit.SECONDS), second.get(10, java.util.concurrent.TimeUnit.SECONDS)))
|
||||
.containsExactlyInAnyOrder(200, 409);
|
||||
}
|
||||
mvc.perform(get("/admin-api/components/{id}", id)).andExpect(jsonPath("$.data.componentJson.componentRevision").value(2));
|
||||
assertThat(logCount()).isEqualTo(3);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE success=FALSE", Long.class)).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentComponentCreationHasDatabaseNameUniqueness() throws Exception {
|
||||
var gate = new java.util.concurrent.CountDownLatch(1);
|
||||
String body = json.writeValueAsString(component("same-name"));
|
||||
try (var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) {
|
||||
java.util.concurrent.Callable<Integer> create = () -> {
|
||||
gate.await();
|
||||
return mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(body)).andReturn().getResponse().getStatus();
|
||||
};
|
||||
var first = workers.submit(create);
|
||||
var second = workers.submit(create);
|
||||
gate.countDown();
|
||||
assertThat(java.util.List.of(first.get(10, java.util.concurrent.TimeUnit.SECONDS), second.get(10, java.util.concurrent.TimeUnit.SECONDS)))
|
||||
.containsExactlyInAnyOrder(200, 409);
|
||||
}
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM component", Long.class)).isEqualTo(1);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM information_schema.tables WHERE LOWER(table_name)='component_asset'", Long.class)).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void componentUpdatesRequireClientRevisionAndPaginationRejectsNonPositiveValues() throws Exception {
|
||||
long id = send("/admin-api/components", component("revision-required")).path("data").path("id").asLong();
|
||||
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(component("new")))).andExpect(status().isUnprocessableEntity());
|
||||
for (String value : new String[]{"0", "-1"}) {
|
||||
mvc.perform(get("/admin-api/components").param("page", value)).andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(get("/admin-api/components").param("size", value)).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void interfaceFieldLengthsFailBeforeDatabaseAndHttpErrorsHaveCorrectStatus() throws Exception {
|
||||
var body = interfaceRequest("invalid-length");
|
||||
body.put("name", "x".repeat(129));
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(body.toString()))
|
||||
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.message", org.hamcrest.Matchers.containsString("name")));
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM interface_definition_v2", Long.class)).isZero();
|
||||
body.put("name", "valid").put("unsupportedField", "must not be silently ignored");
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(body.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
body.remove("unsupportedField");
|
||||
body.putArray("connectableTargets").add(123);
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(body.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(patch("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isMethodNotAllowed()).andExpect(header().exists("Allow"));
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.TEXT_PLAIN).content("{}"))
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void flatTargetArraysSurvivePoseConfirmationAndRoundTrip() throws Exception {
|
||||
var request = interfaceRequest("roundtrip");
|
||||
request.putArray("connectableTargets").add("A").add("B");
|
||||
JsonNode definition = send("/admin-api/interfaces", request).path("data");
|
||||
var pose = json.createObjectNode().put("definitionRevision", 1).put("linkName", "base").put("sourceGeometryHash", "hash");
|
||||
pose.set("geometryInLink", definition.get("geometry"));
|
||||
JsonNode candidates = send("/admin-api/interfaces/roundtrip/pose-candidates", pose).path("data");
|
||||
var port = json.createObjectNode().put("id", "port").put("linkName", "base")
|
||||
.put("definitionId", "roundtrip").put("definitionRevision", 1).put("sourceGeometryHash", "hash")
|
||||
.put("solverVersion", candidates.path("solverVersion").asText());
|
||||
port.set("geometryInLink", definition.get("geometry"));
|
||||
port.putObject("selectedPose").put("id", candidates.path("candidates").get(0).path("id").asText());
|
||||
port.set("connectableTargets", definition.get("connectableTargets"));
|
||||
JsonNode confirmed = send("/admin-api/interfaces/roundtrip/confirm-port", port).path("data");
|
||||
assertThat(confirmed.path("connectableTargets").toString()).isEqualTo("[\"A\",\"B\"]");
|
||||
assertThat(send("/admin-api/interfaces/roundtrip/confirm-port", confirmed).path("data").path("connectableTargets"))
|
||||
.isEqualTo(confirmed.get("connectableTargets"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void actualUploadRejectsMissingForgedExpiredAndCrossSessionTokens() throws Exception {
|
||||
JsonNode session = send("/admin-api/components/cover-image-upload-sessions", null).path("data");
|
||||
String key = session.path("keyPrefix").asText() + "cover.png";
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key).content(new byte[]{1}))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key)
|
||||
.header("X-Upload-Session-Token", "forged-token").content(new byte[]{1}))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
String expired = uploadTokens
|
||||
.generateToken(0L, com.linkerbot.cadworld.enums.ComponentUploadType.COVER_IMAGE,
|
||||
session.path("keyPrefix").asText(), java.time.Instant.now().minusSeconds(30));
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key)
|
||||
.header("X-Upload-Session-Token", expired).content(new byte[]{1}))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", "components/cover-images/0/other/cover.png")
|
||||
.header("X-Upload-Session-Token", session.path("uploadSessionToken").asText()).content(new byte[]{1}))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isEqualTo(5);
|
||||
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString()).doesNotContain(expired, "forged-token", session.path("uploadSessionToken").asText());
|
||||
}
|
||||
|
||||
@Autowired com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider uploadTokens;
|
||||
|
||||
private com.fasterxml.jackson.databind.node.ObjectNode interfaceRequest(String id) throws Exception {
|
||||
return (com.fasterxml.jackson.databind.node.ObjectNode) json.readTree("""
|
||||
{"id":"%s","name":"安装接口","geometry":{"plane":{"pointM":[0,0,0],"outwardNormal":[0,0,1]},
|
||||
"holes":[{"id":"a","pointOnPlaneM":[-0.02,0,0],"axis":[0,0,1],"diameterM":0.004},
|
||||
{"id":"b","pointOnPlaneM":[0.02,0,0],"axis":[0,0,1],"diameterM":0.004}]},
|
||||
"tolerances":{"positionM":0.0002,"axisAngleRad":0.0174533,"planeAngleRad":0.0174533}}
|
||||
""".formatted(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceUploadUnsupportedMediaTypeStillHasExactlyOneFailedAudit() throws Exception {
|
||||
mvc.perform(post("/admin-api/interfaces/missing/assets").param("geometryRevision", "1")
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
assertThat(logCount()).isEqualTo(1);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND success=FALSE AND target_id='missing' AND http_status=415", Long.class))
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
private JsonNode send(String path, Object body) throws Exception {
|
||||
var request = post(path);
|
||||
if (body != null) request.contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(body));
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.jdbc.datasource.init.ScriptUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
@@ -20,6 +26,27 @@ import static org.assertj.core.api.Assertions.*;
|
||||
"app.minio.bucket=cadworld-verification", "logging.file.path=target/integration-logs"
|
||||
})
|
||||
class ExternalServicesIT extends AdminApiTest {
|
||||
@Autowired com.linkerbot.cadworld.service.client.ObjectStorageClient storage;
|
||||
|
||||
@Test
|
||||
void minioStreamLimitPreservesExistingObjectAndMapsTo413() throws Exception {
|
||||
String key = "limit-verification/" + java.util.UUID.randomUUID() + "/model.rfs";
|
||||
try {
|
||||
storage.putObject(key, "application/octet-stream", new java.io.ByteArrayInputStream(new byte[]{1, 2}), 2);
|
||||
var bounded = com.linkerbot.cadworld.service.support.UploadLimits.bounded(
|
||||
new java.io.ByteArrayInputStream(new byte[9]), 8);
|
||||
assertThatThrownBy(() -> storage.putObject(key, "application/octet-stream", bounded, -1))
|
||||
.isInstanceOf(com.linkerbot.cadworld.common.exception.BizException.class)
|
||||
.extracting("httpStatus").isEqualTo(413);
|
||||
var downloaded = new java.io.ByteArrayOutputStream();
|
||||
storage.writeObjectTo(key, downloaded);
|
||||
assertThat(downloaded.toByteArray()).containsExactly((byte) 1, (byte) 2);
|
||||
} finally {
|
||||
storage.deleteObject(key);
|
||||
}
|
||||
assertThat(storage.objectExists(key)).isFalse();
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void prepareAndVerifySql() throws Exception {
|
||||
String url = System.getProperty("cadworld.it.db-url", "jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai");
|
||||
@@ -46,6 +73,22 @@ class ExternalServicesIT extends AdminApiTest {
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
String readme = Files.readString(db.getParent().resolve("README.md"));
|
||||
var supplement = Pattern.compile("<!-- schema-refactor -->\\s*```sql\\s*(.*?)```", Pattern.DOTALL)
|
||||
.matcher(readme);
|
||||
assertThat(supplement.find()).as("README must provide the schema supplement").isTrue();
|
||||
var sql = new ByteArrayResource(supplement.group(1).getBytes(StandardCharsets.UTF_8));
|
||||
ScriptUtils.executeSqlScript(connection, sql);
|
||||
ScriptUtils.executeSqlScript(connection, sql);
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='interface_definition_v2' AND column_name='edit_revision'")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='component' AND index_name='uk_component_name' AND non_unique=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='component_asset'")) {
|
||||
result.next(); assertThat(result.getInt(1)).isZero();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import java.sql.Connection;
|
||||
import org.springframework.jdbc.core.ConnectionCallback;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/** Applies the separately delivered schema changes to disposable test databases only. */
|
||||
final class TestSchemaSupport {
|
||||
private TestSchemaSupport() { }
|
||||
|
||||
static void prepare(JdbcTemplate jdbc) {
|
||||
jdbc.execute((ConnectionCallback<Void>) connection -> {
|
||||
if (!"H2".equals(connection.getMetaData().getDatabaseProductName())
|
||||
&& !"cadworld_verification".equals(connection.getCatalog())) {
|
||||
throw new IllegalStateException("Schema preparation requires a disposable test database");
|
||||
}
|
||||
try (var statement = connection.createStatement()) {
|
||||
boolean hasRevision = false;
|
||||
String componentTable = "component";
|
||||
try (var columns = connection.getMetaData().getColumns(connection.getCatalog(), null, "%", "%")) {
|
||||
while (columns.next()) {
|
||||
if ("interface_definition_v2".equalsIgnoreCase(columns.getString("TABLE_NAME"))
|
||||
&& "edit_revision".equalsIgnoreCase(columns.getString("COLUMN_NAME"))) hasRevision = true;
|
||||
if ("component".equalsIgnoreCase(columns.getString("TABLE_NAME"))) componentTable = columns.getString("TABLE_NAME");
|
||||
}
|
||||
}
|
||||
if (!hasRevision) statement.execute("ALTER TABLE interface_definition_v2 ADD COLUMN edit_revision BIGINT NOT NULL DEFAULT 1 COMMENT '编辑版本号,每次修改递增,用于防止旧数据覆盖'");
|
||||
boolean hasNameIndex = false;
|
||||
try (var indexes = connection.getMetaData().getIndexInfo(connection.getCatalog(), null, componentTable, false, false)) {
|
||||
while (indexes.next()) {
|
||||
if ("uk_component_name".equalsIgnoreCase(indexes.getString("INDEX_NAME"))) hasNameIndex = true;
|
||||
}
|
||||
}
|
||||
if (!hasNameIndex) statement.execute("CREATE UNIQUE INDEX uk_component_name ON component(component_name)");
|
||||
statement.execute("DROP TABLE IF EXISTS component_asset");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import static org.assertj.core.api.Assertions.*;
|
||||
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
|
||||
"spring.servlet.multipart.max-file-size=1KB", "spring.servlet.multipart.max-request-size=2KB",
|
||||
"app.storage.max-upload-bytes=1024",
|
||||
"app.storage.provider=local", "app.storage.local-root=target/test-http-assets", "logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
@@ -27,6 +28,28 @@ class UploadHttpTest {
|
||||
@Autowired TestRestTemplate http;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
|
||||
@Test
|
||||
void realChunkedPutCannotBypassUploadLimit() throws Exception {
|
||||
var session = http.postForObject("/admin-api/components/cover-image-upload-sessions", null,
|
||||
com.fasterxml.jackson.databind.JsonNode.class).path("data");
|
||||
String objectKey = session.path("keyPrefix").asText() + "chunked.png";
|
||||
var uri = org.springframework.web.util.UriComponentsBuilder.fromUriString(http.getRootUri())
|
||||
.path("/admin-api/component-assets/upload").queryParam("objectKey", objectKey)
|
||||
.build().encode().toUri();
|
||||
var request = java.net.http.HttpRequest.newBuilder(uri)
|
||||
.header("X-Upload-Session-Token", session.path("uploadSessionToken").asText())
|
||||
.header("Content-Type", "image/png")
|
||||
.PUT(java.net.http.HttpRequest.BodyPublishers.ofInputStream(
|
||||
() -> new java.io.ByteArrayInputStream(new byte[1025]))).build();
|
||||
try (var client = java.net.http.HttpClient.newHttpClient()) {
|
||||
var response = client.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
|
||||
assertThat(response.statusCode()).isEqualTo(413);
|
||||
assertThat(response.body()).contains("UPLOAD_TOO_LARGE");
|
||||
}
|
||||
assertThat(http.getForEntity("/admin-api/component-assets/" + objectKey, String.class).getStatusCode())
|
||||
.isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void realServletMultipartSizeFailureReturns413AndPersistsAudit() {
|
||||
var body = new LinkedMultiValueMap<String, Object>();
|
||||
|
||||
+5
-1
@@ -20,7 +20,11 @@ class OperationAuditInterceptorTest {
|
||||
var request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||
var response = new MockHttpServletResponse();
|
||||
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||
when(mappings.getHandler(request)).thenReturn(new org.springframework.web.servlet.HandlerExecutionChain(handler));
|
||||
var options = new org.springframework.web.servlet.mvc.method.RequestMappingInfo.BuilderConfiguration();
|
||||
options.setPatternParser(new org.springframework.web.util.pattern.PathPatternParser());
|
||||
var mapping = org.springframework.web.servlet.mvc.method.RequestMappingInfo.paths("/admin-api/components")
|
||||
.methods(org.springframework.web.bind.annotation.RequestMethod.POST).options(options).build();
|
||||
when(mappings.getHandlerMethods()).thenReturn(java.util.Map.of(mapping, handler));
|
||||
var filter = new EarlyFailureAuditFilter(mappings, audit);
|
||||
filter.doFilter(request, response, (req, res) -> ((jakarta.servlet.http.HttpServletResponse) res).setStatus(413));
|
||||
var captured = org.mockito.ArgumentCaptor.forClass(com.linkerbot.cadworld.entity.OperationLog.class);
|
||||
|
||||
+4
-1
@@ -1,7 +1,10 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record PrepareObjectUploadUrlResponse(
|
||||
String uploadUrl,
|
||||
String objectKey
|
||||
String objectKey,
|
||||
Map<String, String> uploadHeaders
|
||||
) {
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.linkerbot.cadworld.dto.interfaces;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.json.ConnectableTargetsDeserializer;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.MountGeometry;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.Tolerances;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
|
||||
public record SaveInterfaceDefinitionRequest(
|
||||
@Size(max = 64) String id,
|
||||
@NotBlank @Size(max = 128) String name,
|
||||
@Size(max = 500) String description,
|
||||
@Min(1) Integer geometryRevision,
|
||||
@Min(1) Long editRevision,
|
||||
@NotNull MountGeometry geometry,
|
||||
@NotNull Tolerances tolerances,
|
||||
@JsonDeserialize(using = ConnectableTargetsDeserializer.class) List<String> connectableTargets,
|
||||
@Size(min = 3, max = 3) double[] displayForward,
|
||||
@Size(max = 512) String sourceAssetKey,
|
||||
@Size(max = 128) String sourceGeometryHash
|
||||
) {
|
||||
public SaveInterfaceDefinitionRequest {
|
||||
connectableTargets = connectableTargets == null ? List.of() : List.copyOf(connectableTargets);
|
||||
}
|
||||
|
||||
@JsonAnySetter
|
||||
public void rejectUnknownField(String field, JsonNode value) {
|
||||
throw new IllegalArgumentException("不支持的接口字段:" + field);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.linkerbot.cadworld.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Getter; import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
@TableName("component_asset")
|
||||
public class ComponentAsset extends BaseEntity {
|
||||
@TableId(type = IdType.AUTO) private Long id;
|
||||
private Long componentId;
|
||||
private String objectKey;
|
||||
private String relativePath;
|
||||
private String assetKind;
|
||||
private String contentType;
|
||||
private Long size;
|
||||
private String sha256;
|
||||
private Boolean isPrimary;
|
||||
}
|
||||
+1
@@ -15,6 +15,7 @@ public class InterfaceDefinitionEntity extends BaseEntity {
|
||||
private String name;
|
||||
private String description;
|
||||
private Integer geometryRevision;
|
||||
private Long editRevision;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode geometryJson;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode tolerancesJson;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode connectableTargetsJson;
|
||||
|
||||
+4
-1
@@ -1,6 +1,8 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import java.util.List;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.linkerbot.cadworld.common.json.ConnectableTargetsDeserializer;
|
||||
|
||||
/** Mechanical interface wire contract. All distances are metres; quaternions are XYZW. */
|
||||
public final class InterfaceGeometry {
|
||||
@@ -29,7 +31,8 @@ public final class InterfaceGeometry {
|
||||
double[] orientationDirectionInLink) {}
|
||||
public record Port(String id, String linkName, String definitionId, int definitionRevision,
|
||||
MountGeometry geometryInLink, SelectedPose selectedPose,
|
||||
String sourceGeometryHash, String solverVersion, List<String> connectableTargets) {
|
||||
String sourceGeometryHash, String solverVersion,
|
||||
@JsonDeserialize(using = ConnectableTargetsDeserializer.class) List<String> connectableTargets) {
|
||||
public Port(String id, String linkName, String definitionId, int definitionRevision,
|
||||
MountGeometry geometryInLink, SelectedPose selectedPose,
|
||||
String sourceGeometryHash, String solverVersion) {
|
||||
+54
-4
@@ -8,6 +8,9 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.transaction.CannotCreateTransactionException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
@@ -40,19 +43,66 @@ public class GlobalExceptionHandler {
|
||||
MethodArgumentNotValidException.class,
|
||||
BindException.class,
|
||||
ConstraintViolationException.class,
|
||||
HttpMediaTypeNotSupportedException.class,
|
||||
HttpRequestMethodNotSupportedException.class,
|
||||
org.springframework.http.converter.HttpMessageNotReadableException.class,
|
||||
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class,
|
||||
org.springframework.web.bind.MissingServletRequestParameterException.class,
|
||||
MissingRequestHeaderException.class,
|
||||
org.springframework.web.multipart.support.MissingServletRequestPartException.class,
|
||||
org.springframework.web.method.annotation.HandlerMethodValidationException.class,
|
||||
IllegalArgumentException.class
|
||||
})
|
||||
public ResponseEntity<ApiResponse<Void>> handleBadRequest(Exception exception, HttpServletRequest request) {
|
||||
request.setAttribute("cadworld.operationError", "请求参数或数据格式不合法");
|
||||
String message = validationMessage(exception);
|
||||
request.setAttribute("cadworld.operationError", message);
|
||||
return ResponseEntity.unprocessableEntity()
|
||||
.body(ApiResponse.failure(ApiCode.INVALID_REQUEST, exception.getMessage()));
|
||||
.body(ApiResponse.failure(ApiCode.INVALID_REQUEST, message));
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleMethodNotAllowed(HttpRequestMethodNotSupportedException exception,
|
||||
HttpServletRequest request) {
|
||||
request.setAttribute("cadworld.operationError", "请求方法不支持");
|
||||
var headers = new HttpHeaders();
|
||||
if (exception.getSupportedHttpMethods() != null) headers.setAllow(exception.getSupportedHttpMethods());
|
||||
return new ResponseEntity<>(ApiResponse.failure(ApiCode.INVALID_REQUEST, "请求方法不支持"),
|
||||
headers, HttpStatus.METHOD_NOT_ALLOWED);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleUnsupportedMediaType(HttpServletRequest request) {
|
||||
request.setAttribute("cadworld.operationError", "请求内容类型不支持");
|
||||
return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
|
||||
.body(ApiResponse.failure(ApiCode.INVALID_REQUEST, "请求内容类型不支持"));
|
||||
}
|
||||
|
||||
private String validationMessage(Exception exception) {
|
||||
if (exception instanceof BindException binding) {
|
||||
return binding.getBindingResult().getFieldErrors().stream()
|
||||
.map(error -> error.getField() + ": " + error.getDefaultMessage())
|
||||
.distinct().sorted().collect(Collectors.joining(";"));
|
||||
}
|
||||
if (exception instanceof ConstraintViolationException violations) {
|
||||
return violations.getConstraintViolations().stream()
|
||||
.map(error -> error.getPropertyPath() + ": " + error.getMessage())
|
||||
.distinct().sorted().collect(Collectors.joining(";"));
|
||||
}
|
||||
if (exception instanceof org.springframework.http.converter.HttpMessageNotReadableException) {
|
||||
return "请求体格式不合法,请检查字段类型和JSON结构";
|
||||
}
|
||||
if (exception instanceof org.springframework.web.method.annotation.MethodArgumentTypeMismatchException mismatch) {
|
||||
return "参数 " + mismatch.getName() + " 格式不合法";
|
||||
}
|
||||
if (exception instanceof MissingRequestHeaderException missing) {
|
||||
return "缺少请求头 " + missing.getHeaderName();
|
||||
}
|
||||
if (exception instanceof org.springframework.web.bind.MissingServletRequestParameterException missing) {
|
||||
return "缺少请求参数 " + missing.getParameterName();
|
||||
}
|
||||
if (exception instanceof org.springframework.web.multipart.support.MissingServletRequestPartException missing) {
|
||||
return "缺少上传字段 " + missing.getRequestPartName();
|
||||
}
|
||||
if (exception instanceof IllegalArgumentException) return exception.getMessage();
|
||||
return "请求参数或数据格式不合法";
|
||||
}
|
||||
|
||||
@ExceptionHandler({CannotCreateTransactionException.class, DataAccessResourceFailureException.class})
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.linkerbot.cadworld.common.json;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
|
||||
/** Flat strings are separate targets; nested arrays are Cascader paths. */
|
||||
public class ConnectableTargetsDeserializer extends JsonDeserializer<List<String>> {
|
||||
@Override
|
||||
public List<String> deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||
JsonNode value = parser.readValueAsTree();
|
||||
if (!value.isArray()) {
|
||||
throw context.weirdStringException("", List.class, "连接目标必须为数组");
|
||||
}
|
||||
var targets = new LinkedHashSet<String>();
|
||||
for (JsonNode item : value) {
|
||||
String target;
|
||||
if (item.isTextual()) {
|
||||
target = item.asText().trim();
|
||||
} else if (item.isArray() && !item.isEmpty()) {
|
||||
var segments = new ArrayList<String>();
|
||||
for (JsonNode segment : item) {
|
||||
if (!segment.isTextual() || segment.asText().isBlank()) {
|
||||
throw context.weirdStringException(item.toString(), List.class, "连接目标路径必须由非空字符串组成");
|
||||
}
|
||||
segments.add(segment.asText().trim());
|
||||
}
|
||||
target = String.join("/", segments);
|
||||
} else {
|
||||
throw context.weirdStringException(item.toString(), List.class, "连接目标必须是字符串或路径数组");
|
||||
}
|
||||
if (target.isEmpty() || target.length() > 512) {
|
||||
throw context.weirdStringException("", List.class, "连接目标不能为空,长度不能超过512字符");
|
||||
}
|
||||
targets.add(target);
|
||||
if (targets.size() > 100) {
|
||||
throw context.weirdStringException("", List.class, "连接目标不能超过100个");
|
||||
}
|
||||
}
|
||||
return List.copyOf(targets);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getNullValue(DeserializationContext context) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.linkerbot.cadworld.config;
|
||||
import java.time.Duration;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.ConstructorBinding;
|
||||
import org.springframework.boot.context.properties.bind.DefaultValue;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.storage")
|
||||
public record StorageProperties(
|
||||
@@ -12,19 +13,17 @@ public record StorageProperties(
|
||||
String publicBaseUrl,
|
||||
String publicApiBaseUrl,
|
||||
String localRoot,
|
||||
Duration uploadSessionTtl
|
||||
Duration uploadSessionTtl,
|
||||
@DefaultValue("104857600") long maxUploadBytes
|
||||
) {
|
||||
@ConstructorBinding
|
||||
public StorageProperties { }
|
||||
|
||||
public StorageProperties(String provider, String urdfPrefix, String coverImagePrefix,
|
||||
String publicBaseUrl, String publicApiBaseUrl, String localRoot,
|
||||
Duration uploadSessionTtl) {
|
||||
this.provider = provider;
|
||||
this.urdfPrefix = urdfPrefix;
|
||||
this.coverImagePrefix = coverImagePrefix;
|
||||
this.publicBaseUrl = publicBaseUrl;
|
||||
this.publicApiBaseUrl = publicApiBaseUrl;
|
||||
this.localRoot = localRoot;
|
||||
this.uploadSessionTtl = uploadSessionTtl;
|
||||
this(provider, urdfPrefix, coverImagePrefix, publicBaseUrl, publicApiBaseUrl,
|
||||
localRoot, uploadSessionTtl, 104857600L);
|
||||
}
|
||||
|
||||
public StorageProperties(String provider, String urdfPrefix, String coverImagePrefix,
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.linkerbot.cadworld.mapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.cadworld.entity.ComponentAsset;
|
||||
public interface ComponentAssetMapper extends BaseMapper<ComponentAsset> {}
|
||||
+50
-42
@@ -1,64 +1,72 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.*;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.Port;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentPortValidationService {
|
||||
private final InterfaceDefinitionService definitions;
|
||||
private final MechanicalInterfaceSolver solver;
|
||||
private final ObjectMapper mapper;
|
||||
private final UrdfSourceValidation sourceValidation;
|
||||
private final UrdfAssetVerifier assetVerifier;
|
||||
public JsonNode validate(JsonNode componentJson){
|
||||
if(componentJson==null||!componentJson.isObject())throw new IllegalArgumentException("组件模型数据不合法");
|
||||
ObjectNode result=componentJson.deepCopy();
|
||||
JsonNode interfaces=result.get("interfaces");
|
||||
if(interfaces==null)return result;
|
||||
if(!interfaces.isArray())throw new IllegalArgumentException("接口必须是数组");
|
||||
Set<String> links=interfaces.isEmpty()?Set.of():sourceValidation.validate(result.get("urdfSource"));
|
||||
if(!interfaces.isEmpty())assetVerifier.verify(result.get("urdfSource"));
|
||||
ArrayNode confirmed=mapper.createArrayNode();Set<String> ids=new HashSet<>();
|
||||
for(JsonNode raw:interfaces){
|
||||
Port port=readPort(raw);
|
||||
if(!links.contains(port.linkName()))throw new IllegalArgumentException("接口所属 link 不存在于原始 URDF:"+port.linkName());
|
||||
if(!port.sourceGeometryHash().equals(result.path("urdfSource").path("sourceGeometryHash").asText()))throw new IllegalArgumentException("接口源几何已变化,请重新识别");
|
||||
if(definitions.get(port.definitionId()).path("geometryRevision").asInt()!=port.definitionRevision())throw new IllegalArgumentException("接口定义已修订,请重新确认组件接口");
|
||||
if(!ids.add(port.id()))throw new IllegalArgumentException("组件端口 ID 重复");
|
||||
Port canonical=solver.confirmPortPose(definitions.geometryDefinition(port.definitionId(),port.definitionRevision()),port);
|
||||
public JsonNode validate(JsonNode componentJson) {
|
||||
if (componentJson == null || !componentJson.isObject()) {
|
||||
throw new IllegalArgumentException("组件模型数据不合法");
|
||||
}
|
||||
ObjectNode result = componentJson.deepCopy();
|
||||
JsonNode interfaces = result.get("interfaces");
|
||||
if (interfaces == null) return result;
|
||||
if (!interfaces.isArray()) throw new IllegalArgumentException("接口必须是数组");
|
||||
|
||||
JsonNode source = result.get("urdfSource");
|
||||
Set<String> links = interfaces.isEmpty() ? Set.of() : sourceValidation.validate(source);
|
||||
if (!interfaces.isEmpty()) assetVerifier.verify(source);
|
||||
ArrayNode confirmed = mapper.createArrayNode();
|
||||
Set<String> ids = new HashSet<>();
|
||||
for (JsonNode raw : interfaces) {
|
||||
Port port = readPort(raw);
|
||||
if (!links.contains(port.linkName())) {
|
||||
throw new IllegalArgumentException("接口所属 link 不存在于原始 URDF:" + port.linkName());
|
||||
}
|
||||
if (!port.sourceGeometryHash().equals(source.path("sourceGeometryHash").asText())) {
|
||||
throw new IllegalArgumentException("接口源几何已变化,请重新识别");
|
||||
}
|
||||
if (definitions.get(port.definitionId()).path("geometryRevision").asInt() != port.definitionRevision()) {
|
||||
throw new IllegalArgumentException("接口定义已修订,请重新确认组件接口");
|
||||
}
|
||||
if (!ids.add(port.id())) throw new IllegalArgumentException("组件端口 ID 重复");
|
||||
Port canonical = solver.confirmPortPose(
|
||||
definitions.geometryDefinition(port.definitionId(), port.definitionRevision()), port);
|
||||
confirmed.add(mapper.valueToTree(canonical));
|
||||
}
|
||||
result.set("interfaces",confirmed);result.put("interfaceSchemaVersion",3);
|
||||
result.set("interfaces", confirmed);
|
||||
result.put("interfaceSchemaVersion", 3);
|
||||
return result;
|
||||
}
|
||||
public Port readPort(JsonNode raw){
|
||||
try{return mapper.readerFor(Port.class).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(normalizePort(raw));}
|
||||
catch(java.io.IOException | IllegalArgumentException e){throw new IllegalArgumentException("不支持的接口结构,请重新识别并确认姿态:"+rootMessage(e),e);}
|
||||
}
|
||||
private JsonNode normalizePort(JsonNode raw){
|
||||
if(raw==null||!raw.isObject())return raw;
|
||||
ObjectNode copy=raw.deepCopy();JsonNode targets=copy.get("connectableTargets");
|
||||
if(targets!=null&&!targets.isNull()){
|
||||
ArrayNode normalized=mapper.createArrayNode();flattenTargets(targets,normalized);copy.set("connectableTargets",normalized);
|
||||
|
||||
public Port readPort(JsonNode raw) {
|
||||
try {
|
||||
return mapper.readerFor(Port.class).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(raw);
|
||||
} catch (IOException | IllegalArgumentException exception) {
|
||||
throw new IllegalArgumentException("不支持的接口结构,请重新识别并确认姿态:" + rootMessage(exception), exception);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
private void flattenTargets(JsonNode node,ArrayNode output){
|
||||
if(node==null||node.isNull())return;
|
||||
if(node.isArray()){
|
||||
boolean path=true;StringBuilder joined=new StringBuilder();
|
||||
for(JsonNode child:node){if(!child.isTextual()){path=false;break;}if(joined.length()>0)joined.append('/');joined.append(child.asText());}
|
||||
if(path){String value=joined.toString().trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);return;}
|
||||
node.forEach(child->flattenTargets(child,output));return;
|
||||
}
|
||||
String value=node.asText("").trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);
|
||||
|
||||
private String rootMessage(Throwable error) {
|
||||
Throwable current = error;
|
||||
while (current.getCause() != null) current = current.getCause();
|
||||
return current.getMessage() == null ? "字段格式错误" : current.getMessage();
|
||||
}
|
||||
private boolean containsTarget(ArrayNode output,String value){for(JsonNode item:output)if(value.equals(item.asText()))return true;return false;}
|
||||
private String rootMessage(Throwable error){Throwable current=error;while(current.getCause()!=null)current=current.getCause();return current.getMessage()==null?"字段格式错误":current.getMessage();}
|
||||
}
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.support.UploadLimits;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.DigestInputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class InterfaceAssetService {
|
||||
private final InterfaceDefinitionService definitions;
|
||||
private final ObjectStorageClient storage;
|
||||
private final StorageProperties properties;
|
||||
|
||||
public String upload(String definitionId, int geometryRevision, MultipartFile file) {
|
||||
if (file == null || file.isEmpty()) throw new BizException(422, "INVALID_INTERFACE_ASSET", "接口源文件不能为空");
|
||||
var current = definitions.get(definitionId);
|
||||
if (geometryRevision < 1 || current.path("geometryRevision").asInt() != geometryRevision) {
|
||||
throw new BizException(409, "INTERFACE_REVISION_CONFLICT", "接口已修订,请刷新后重新上传");
|
||||
}
|
||||
UploadLimits.checkLength(file.getSize(), properties.maxUploadBytes());
|
||||
Path temporary = null;
|
||||
String uploadedKey = null;
|
||||
try {
|
||||
temporary = Files.createTempFile("cadworld-interface-", ".upload");
|
||||
MessageDigest digest = sha256();
|
||||
try (var input = new DigestInputStream(UploadLimits.bounded(file.getInputStream(), properties.maxUploadBytes()), digest)) {
|
||||
Files.copy(input, temporary, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
String hash = "sha256:" + HexFormat.of().formatHex(digest.digest());
|
||||
String oldKey = current.path("sourceAssetKey").asText();
|
||||
if (hash.equals(current.path("sourceGeometryHash").asText())
|
||||
&& !oldKey.isBlank() && storage.objectExists(oldKey)) {
|
||||
// Revalidate under the database lock even for an idempotent retry.
|
||||
definitions.attachAsset(definitionId, geometryRevision, oldKey, hash, oldKey);
|
||||
return oldKey;
|
||||
}
|
||||
if (!current.path("sourceGeometryHash").asText().isBlank()
|
||||
&& !hash.equals(current.path("sourceGeometryHash").asText())) {
|
||||
throw new BizException(422, "INVALID_INTERFACE_ASSET", "该修订已有源文件,请创建新几何修订");
|
||||
}
|
||||
String key = "interfaces/" + HexFormat.of().formatHex(definitionId.getBytes(StandardCharsets.UTF_8))
|
||||
+ "/" + geometryRevision + "/" + hash.substring(7) + "/" + UUID.randomUUID()
|
||||
+ "/" + filename(file.getOriginalFilename());
|
||||
if (key.length() > 512) throw new BizException(422, "INVALID_INTERFACE_ASSET", "源文件对象路径超过512字符,请缩短文件名或接口ID");
|
||||
// Each request owns its object; compensation cannot delete another upload's object.
|
||||
uploadedKey = key;
|
||||
try (var input = Files.newInputStream(temporary)) {
|
||||
storage.putObject(key, file.getContentType(), input, Files.size(temporary));
|
||||
}
|
||||
definitions.attachAsset(definitionId, geometryRevision, key, hash, oldKey);
|
||||
return key;
|
||||
} catch (IOException exception) {
|
||||
compensate(uploadedKey, definitionId, geometryRevision);
|
||||
log.error("接口源文件处理失败 definitionId={} geometryRevision={} requestId={}",
|
||||
definitionId, geometryRevision, RequestIdHolder.get(), exception);
|
||||
throw new BizException(500, "INTERFACE_ASSET_PROCESSING_FAILED", "接口源文件处理失败,请重试");
|
||||
} catch (RuntimeException exception) {
|
||||
compensate(uploadedKey, definitionId, geometryRevision);
|
||||
throw exception;
|
||||
} finally {
|
||||
if (temporary != null) {
|
||||
try {
|
||||
Files.deleteIfExists(temporary);
|
||||
} catch (IOException exception) {
|
||||
log.warn("接口源文件临时文件清理失败 definitionId={} requestId={}", definitionId, RequestIdHolder.get(), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void compensate(String key, String definitionId, int revision) {
|
||||
if (key == null) return;
|
||||
try {
|
||||
storage.deleteObject(key);
|
||||
} catch (RuntimeException exception) {
|
||||
log.error("接口源文件补偿清理失败 definitionId={} geometryRevision={} requestId={} objectKey={}",
|
||||
definitionId, revision, RequestIdHolder.get(), key, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String filename(String original) {
|
||||
String name = original == null ? "source.step" : original.replace('\\', '/');
|
||||
name = name.substring(name.lastIndexOf('/') + 1).replaceAll("[^A-Za-z0-9._-]", "_");
|
||||
return name.isBlank() ? "source.step" : name;
|
||||
}
|
||||
|
||||
private MessageDigest sha256() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException exception) {
|
||||
throw new IllegalStateException("SHA-256 不可用", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-3
@@ -2,13 +2,15 @@ package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.util.List;
|
||||
import com.linkerbot.cadworld.dto.interfaces.SaveInterfaceDefinitionRequest;
|
||||
|
||||
public interface InterfaceDefinitionService {
|
||||
List<JsonNode> list(String keyword);
|
||||
JsonNode get(String id);
|
||||
JsonNode create(JsonNode request);
|
||||
JsonNode update(String id, JsonNode request);
|
||||
JsonNode create(SaveInterfaceDefinitionRequest request);
|
||||
JsonNode update(String id, SaveInterfaceDefinitionRequest request);
|
||||
void delete(String id);
|
||||
void attachAsset(String definitionId, int geometryRevision, String objectKey, String sha256);
|
||||
void attachAsset(String definitionId, int geometryRevision, String objectKey, String sha256,
|
||||
String expectedAssetKey);
|
||||
com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.Definition geometryDefinition(String id, int revision);
|
||||
}
|
||||
|
||||
+28
-3
@@ -42,7 +42,7 @@ public class LocalObjectStorageClient implements ObjectStorageClient {
|
||||
throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "STORAGE_CONFIG_ERROR", "上传会话有效期配置非法");
|
||||
}
|
||||
String base = StringUtils.hasText(properties.publicApiBaseUrl())
|
||||
? properties.publicApiBaseUrl().trim() : "http://127.0.0.1:8084";
|
||||
? properties.publicApiBaseUrl().trim() : "http://127.0.0.1:8992";
|
||||
return UriComponentsBuilder.fromUriString(base.replaceAll("/+$", ""))
|
||||
.path("/admin-api/component-assets/upload")
|
||||
.queryParam("objectKey", normalizeKey(objectKey))
|
||||
@@ -52,12 +52,37 @@ public class LocalObjectStorageClient implements ObjectStorageClient {
|
||||
@Override
|
||||
public void putObject(String objectKey, String contentType, InputStream inputStream, long contentLength) {
|
||||
Path target = resolve(objectKey);
|
||||
Path temporary = null;
|
||||
try {
|
||||
Files.createDirectories(Objects.requireNonNull(target.getParent()));
|
||||
Files.copy(inputStream, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
temporary = Files.createTempFile(target.getParent(), ".upload-", ".tmp");
|
||||
Files.copy(inputStream, temporary, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
try {
|
||||
Files.move(temporary, target, java.nio.file.StandardCopyOption.ATOMIC_MOVE,
|
||||
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (java.nio.file.AtomicMoveNotSupportedException exception) {
|
||||
Files.move(temporary, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
log.error("Failed to write local object {}", objectKey, exception);
|
||||
throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "LOCAL_STORAGE_WRITE_FAILED", "文件写入本地目录失败");
|
||||
throw new BizException(500, "LOCAL_STORAGE_WRITE_FAILED", "文件写入本地目录失败");
|
||||
} finally {
|
||||
if (temporary != null) {
|
||||
try {
|
||||
Files.deleteIfExists(temporary);
|
||||
} catch (IOException exception) {
|
||||
log.warn("Failed to clean local upload temporary file", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteObject(String objectKey) {
|
||||
try {
|
||||
Files.deleteIfExists(resolve(objectKey));
|
||||
} catch (IOException exception) {
|
||||
throw new BizException(500, "LOCAL_STORAGE_DELETE_FAILED", "清理本地文件失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+15
@@ -9,6 +9,8 @@ import io.minio.GetObjectResponse;
|
||||
import io.minio.MakeBucketArgs;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import com.linkerbot.cadworld.service.support.UploadLimits;
|
||||
import io.minio.StatObjectArgs;
|
||||
import io.minio.StatObjectResponse;
|
||||
import java.io.InputStream;
|
||||
@@ -68,6 +70,7 @@ public class MinioObjectStorageClient implements ObjectStorageClient {
|
||||
.stream(inputStream, objectSize, partSize)
|
||||
.build());
|
||||
} catch (Exception exception) {
|
||||
UploadLimits.rethrowIfExceeded(exception);
|
||||
restoreInterrupt(exception);
|
||||
log.error("Failed to upload object to MinIO. objectKey={}", objectKey, exception);
|
||||
throw new BizException(HttpStatus.BAD_GATEWAY.value(), "MINIO_UPLOAD_FAILED", "文件上传到 MinIO 失败");
|
||||
@@ -98,6 +101,18 @@ public class MinioObjectStorageClient implements ObjectStorageClient {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteObject(String objectKey) {
|
||||
validateConfiguration();
|
||||
try {
|
||||
getMinioClient().removeObject(RemoveObjectArgs.builder()
|
||||
.bucket(properties.bucket().trim()).object(normalizeObjectKey(objectKey)).build());
|
||||
} catch (Exception exception) {
|
||||
restoreInterrupt(exception);
|
||||
throw new BizException(502, "MINIO_DELETE_FAILED", "清理 MinIO 文件失败");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public StoredObject statObject(String objectKey) {
|
||||
validateConfiguration();
|
||||
|
||||
+4
@@ -14,6 +14,10 @@ public interface ObjectStorageClient {
|
||||
|
||||
boolean objectExists(String objectKey);
|
||||
|
||||
default void deleteObject(String objectKey) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
default StoredObject statObject(String objectKey) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
+1
-1
@@ -50,7 +50,7 @@ public class ComponentCoverImageUploadServiceImpl implements ComponentCoverImage
|
||||
request.objectPath(),
|
||||
request.contentType()
|
||||
);
|
||||
return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey());
|
||||
return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey(), upload.uploadHeaders());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+28
-46
@@ -3,6 +3,8 @@ package com.linkerbot.cadworld.service.impl;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata;
|
||||
@@ -11,18 +13,18 @@ import com.linkerbot.cadworld.dto.component.ComponentResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
|
||||
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
|
||||
import com.linkerbot.cadworld.entity.Component;
|
||||
import com.linkerbot.cadworld.entity.ComponentAsset;
|
||||
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||
import com.linkerbot.cadworld.mapper.ComponentAssetMapper;
|
||||
import com.linkerbot.cadworld.service.ComponentService;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentServiceImpl implements ComponentService {
|
||||
|
||||
private static final String COMPONENT_NOT_FOUND = "COMPONENT_NOT_FOUND";
|
||||
@@ -30,22 +32,9 @@ public class ComponentServiceImpl implements ComponentService {
|
||||
private static final String COMPONENT_NAME_DUPLICATE_MESSAGE = "组件名称已存在,请更换名称";
|
||||
|
||||
private final ComponentMapper componentMapper;
|
||||
private final ComponentAssetMapper componentAssetMapper;
|
||||
private final ObjectStorageUrlResolver objectStorageUrlResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService portValidation;
|
||||
|
||||
@Autowired
|
||||
public ComponentServiceImpl(ComponentMapper componentMapper, ComponentAssetMapper componentAssetMapper,
|
||||
ObjectStorageUrlResolver objectStorageUrlResolver,
|
||||
ObjectMapper objectMapper,
|
||||
com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService portValidation) {
|
||||
this.componentMapper = componentMapper;
|
||||
this.componentAssetMapper = componentAssetMapper;
|
||||
this.objectStorageUrlResolver = objectStorageUrlResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.portValidation = portValidation;
|
||||
}
|
||||
private final ComponentPortValidationService portValidation;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
@@ -58,7 +47,6 @@ public class ComponentServiceImpl implements ComponentService {
|
||||
request.assemblyMetadata());
|
||||
try {
|
||||
componentMapper.insert(component);
|
||||
syncAssetIndex(component);
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw duplicateComponentNameException();
|
||||
}
|
||||
@@ -90,15 +78,21 @@ public class ComponentServiceImpl implements ComponentService {
|
||||
@Override
|
||||
@Transactional
|
||||
public ComponentResponse updateComponent(Long userId, Long id, UpdateComponentRequest request) {
|
||||
Component component = requireComponent(id);
|
||||
Component component = componentMapper.selectOne(new LambdaQueryWrapper<Component>()
|
||||
.eq(Component::getId, id).last("FOR UPDATE"));
|
||||
if (component == null) {
|
||||
throw new BizException(404, COMPONENT_NOT_FOUND, "组件不存在");
|
||||
}
|
||||
assertRevisionMatches(component, request.componentJson());
|
||||
String componentName = request.componentName().trim();
|
||||
assertComponentNameAvailable(componentName, id);
|
||||
apply(component, componentName, request.category(), request.robotType(), request.company(),
|
||||
request.model(), request.source(), request.coverImageKey(), request.description(), request.componentJson(),
|
||||
request.assemblyMetadata());
|
||||
try {
|
||||
componentMapper.updateById(component);
|
||||
syncAssetIndex(component);
|
||||
if (componentMapper.updateById(component) != 1) {
|
||||
throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已删除,请刷新后保存");
|
||||
}
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw duplicateComponentNameException();
|
||||
}
|
||||
@@ -142,7 +136,7 @@ public class ComponentServiceImpl implements ComponentService {
|
||||
String source,
|
||||
String coverImageKey,
|
||||
String description,
|
||||
com.fasterxml.jackson.databind.JsonNode componentJson,
|
||||
JsonNode componentJson,
|
||||
ComponentAssemblyMetadata assemblyMetadata) {
|
||||
component.setComponentName(componentName.trim());
|
||||
component.setCategory(normalizeOptionalText(category));
|
||||
@@ -152,9 +146,10 @@ public class ComponentServiceImpl implements ComponentService {
|
||||
component.setSource(source.trim());
|
||||
component.setCoverImageKey(normalizeOptionalText(coverImageKey));
|
||||
component.setDescription(normalizeOptionalText(description));
|
||||
int previousRevision=component.getComponentJson()==null?0:component.getComponentJson().path("componentRevision").asInt(0);
|
||||
var validated=(com.fasterxml.jackson.databind.node.ObjectNode)portValidation.validate(componentJson);
|
||||
validated.put("componentRevision",previousRevision+1);
|
||||
int previousRevision = component.getComponentJson() == null ? 0
|
||||
: component.getComponentJson().path("componentRevision").asInt(0);
|
||||
ObjectNode validated = (ObjectNode) portValidation.validate(componentJson);
|
||||
validated.put("componentRevision", Math.incrementExact(previousRevision));
|
||||
component.setComponentJson(validated);
|
||||
component.setAssemblyMetadata(objectMapper.valueToTree(
|
||||
ComponentTagSupport.mergeLegacy(assemblyMetadata, category)
|
||||
@@ -211,28 +206,15 @@ public class ComponentServiceImpl implements ComponentService {
|
||||
return objectStorageUrlResolver.resolvePublicUrl(coverImageKey);
|
||||
}
|
||||
|
||||
private void syncAssetIndex(Component component) {
|
||||
if (componentAssetMapper == null || component.getId() == null) {
|
||||
return;
|
||||
private void assertRevisionMatches(Component current, JsonNode submitted) {
|
||||
var revision = submitted == null ? null : submitted.get("componentRevision");
|
||||
if (revision == null || !revision.isIntegralNumber() || !revision.canConvertToInt()
|
||||
|| revision.intValue() < 0) {
|
||||
throw new BizException(422, "INVALID_COMPONENT_REVISION", "修改组件必须提供 componentJson.componentRevision");
|
||||
}
|
||||
componentAssetMapper.delete(new LambdaQueryWrapper<ComponentAsset>()
|
||||
.eq(ComponentAsset::getComponentId, component.getId()));
|
||||
addAsset(component, component.getSource(), "RFS", true);
|
||||
addAsset(component, component.getCoverImageKey(), "COVER", false);
|
||||
}
|
||||
|
||||
private void addAsset(Component component, String objectKey, String assetKind, boolean primary) {
|
||||
if (!StringUtils.hasText(objectKey)) {
|
||||
return;
|
||||
int expected = current.getComponentJson() == null ? 0 : current.getComponentJson().path("componentRevision").asInt(0);
|
||||
if (revision.intValue() != expected) {
|
||||
throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已修改,请刷新后保存");
|
||||
}
|
||||
ComponentAsset asset = new ComponentAsset();
|
||||
asset.setComponentId(component.getId());
|
||||
asset.setObjectKey(objectKey.trim());
|
||||
int separator = objectKey.lastIndexOf('/');
|
||||
asset.setRelativePath(separator >= 0 ? objectKey.substring(separator + 1) : objectKey);
|
||||
asset.setAssetKind(assetKind);
|
||||
asset.setIsPrimary(primary);
|
||||
asset.setSize(0L);
|
||||
componentAssetMapper.insert(asset);
|
||||
}
|
||||
}
|
||||
|
||||
+24
-4
@@ -11,7 +11,9 @@ import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import com.linkerbot.cadworld.service.support.UploadLimits;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -20,6 +22,7 @@ import org.springframework.util.StringUtils;
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentUploadSupport {
|
||||
public static final String UPLOAD_TOKEN_HEADER = "X-Upload-Session-Token";
|
||||
|
||||
private final StorageProperties storageProperties;
|
||||
private final ObjectStorageClient objectStorageClient;
|
||||
@@ -96,8 +99,10 @@ public class ComponentUploadSupport {
|
||||
userId, uploadSessionToken, expectedType, invalidCode);
|
||||
String objectKey = resolveObjectKey(claims.keyPrefix(), objectPath);
|
||||
return new PreparedObjectUpload(
|
||||
objectStorageClient.createUploadUrl(objectKey, contentType, resolveUploadSessionTtl()),
|
||||
objectKey
|
||||
objectStorageClient.createUploadUrl(objectKey, contentType,
|
||||
Duration.between(java.time.Instant.now(), claims.expiresAt())),
|
||||
objectKey,
|
||||
Map.of(UPLOAD_TOKEN_HEADER, uploadSessionToken)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -125,18 +130,32 @@ public class ComponentUploadSupport {
|
||||
}
|
||||
|
||||
public void uploadObject(Long userId,
|
||||
String uploadSessionToken,
|
||||
String objectKey,
|
||||
String contentType,
|
||||
InputStream inputStream,
|
||||
long contentLength) {
|
||||
var claims = requireActualUploadSession(userId, uploadSessionToken);
|
||||
String normalizedKey = normalizeObjectKey(objectKey);
|
||||
validateSessionObjectKey(claims.keyPrefix(), normalizedKey);
|
||||
String userSegment = "/" + userId + "/";
|
||||
String urdfPrefix = normalizeConfiguredPrefix(storageProperties.urdfPrefix(), "components/urdf") + userSegment;
|
||||
String coverPrefix = normalizeConfiguredPrefix(storageProperties.coverImagePrefix(), "components/cover-images") + userSegment;
|
||||
if (!normalizedKey.startsWith(urdfPrefix) && !normalizedKey.startsWith(coverPrefix)) {
|
||||
throw invalidUploadObject("无权上传到该对象路径");
|
||||
}
|
||||
objectStorageClient.putObject(normalizedKey, contentType, inputStream, contentLength);
|
||||
UploadLimits.checkLength(contentLength, storageProperties.maxUploadBytes());
|
||||
objectStorageClient.putObject(normalizedKey, contentType,
|
||||
UploadLimits.bounded(inputStream, storageProperties.maxUploadBytes()), contentLength);
|
||||
}
|
||||
|
||||
private ComponentUploadSessionTokenProvider.UploadSessionClaims requireActualUploadSession(Long userId, String token) {
|
||||
try {
|
||||
var claims = componentUploadSessionTokenProvider.parseToken(token);
|
||||
return requireUploadSession(userId, token, claims.uploadType(), "INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
} catch (JwtException | IllegalArgumentException exception) {
|
||||
throw invalidUploadSession("INVALID_COMPONENT_UPLOAD_SESSION", "上传会话无效或已过期");
|
||||
}
|
||||
}
|
||||
|
||||
private BizException invalidUploadSession(String code, String message) {
|
||||
@@ -204,7 +223,8 @@ public class ComponentUploadSupport {
|
||||
|
||||
public record PreparedObjectUpload(
|
||||
String uploadUrl,
|
||||
String objectKey
|
||||
String objectKey,
|
||||
Map<String, String> uploadHeaders
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ public class ComponentUrdfUploadServiceImpl implements ComponentUrdfUploadServic
|
||||
request.objectPath(),
|
||||
request.contentType()
|
||||
);
|
||||
return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey());
|
||||
return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey(), upload.uploadHeaders());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+196
-68
@@ -1,11 +1,13 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.dto.interfaces.SaveInterfaceDefinitionRequest;
|
||||
import com.linkerbot.cadworld.entity.InterfaceDefinitionEntity;
|
||||
import com.linkerbot.cadworld.entity.InterfaceDefinitionRevisionEntity;
|
||||
import com.linkerbot.cadworld.mapper.InterfaceDefinitionMapper;
|
||||
@@ -14,87 +16,213 @@ import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class InterfaceDefinitionServiceImpl implements InterfaceDefinitionService {
|
||||
private final InterfaceDefinitionMapper definitionMapper;
|
||||
private final InterfaceDefinitionRevisionMapper revisionMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final MechanicalInterfaceSolver solver;
|
||||
|
||||
@Override
|
||||
public List<JsonNode> list(String keyword) {
|
||||
LambdaQueryWrapper<InterfaceDefinitionEntity> query=new LambdaQueryWrapper<>();
|
||||
if(keyword!=null&&!keyword.isBlank())query.and(w->w.like(InterfaceDefinitionEntity::getName,keyword).or().like(InterfaceDefinitionEntity::getDescription,keyword));
|
||||
return definitionMapper.selectList(query.orderByDesc(InterfaceDefinitionEntity::getUpdatedAt)).stream().map(this::toJson).toList();
|
||||
}
|
||||
public JsonNode get(String id){return toJson(require(id));}
|
||||
@Transactional public JsonNode create(JsonNode request){
|
||||
String id=required(request,"id");
|
||||
if(definitionMapper.selectById(id)!=null||revisionMapper.selectById(id+":1")!=null)throw invalid("接口 ID 已存在或已归档");
|
||||
return save(new InterfaceDefinitionEntity(),request,id,false);
|
||||
}
|
||||
@Transactional public JsonNode update(String id,JsonNode request){
|
||||
InterfaceDefinitionEntity entity=definitionMapper.selectOne(new LambdaQueryWrapper<InterfaceDefinitionEntity>().eq(InterfaceDefinitionEntity::getId,id).last("FOR UPDATE"));
|
||||
if(entity==null)throw invalid("接口不存在");
|
||||
if(request.path("geometryRevision").asInt()!=entity.getGeometryRevision())throw invalid("接口已修改,请刷新后保存");
|
||||
return save(entity,request,id,true);
|
||||
}
|
||||
private JsonNode save(InterfaceDefinitionEntity entity,JsonNode request,String id,boolean existing){
|
||||
rejectLegacy(request);
|
||||
MountGeometry geometry=objectMapper.convertValue(request.get("geometry"),MountGeometry.class);
|
||||
Tolerances tolerances=objectMapper.convertValue(request.get("tolerances"),Tolerances.class);
|
||||
int revision=existing?entity.getGeometryRevision()+1:1;
|
||||
List<String> connectableTargets=targets(request.get("connectableTargets"));
|
||||
Definition definition=new Definition(id,revision,required(request,"name"),geometry,tolerances,connectableTargets,
|
||||
objectMapper.convertValue(request.get("displayForward"),double[].class));
|
||||
solver.validateDefinition(definition);
|
||||
JsonNode normalizedGeometry=objectMapper.valueToTree(solver.normalize(geometry,tolerances));
|
||||
boolean displayOnly=existing && normalizedGeometry.equals(entity.getGeometryJson())
|
||||
&& objectMapper.valueToTree(tolerances).equals(entity.getTolerancesJson())
|
||||
&& definition.name().equals(entity.getName())
|
||||
&& request.path("description").asText("").equals(entity.getDescription()==null?"":entity.getDescription())
|
||||
&& connectableTargets.equals(targets(entity.getConnectableTargetsJson()))
|
||||
&& (request.path("sourceGeometryHash").asText("").isBlank()
|
||||
|| request.path("sourceGeometryHash").asText().equals(entity.getSourceGeometryHash()));
|
||||
if(displayOnly)revision=entity.getGeometryRevision();
|
||||
entity.setDisplayForwardJson(objectMapper.valueToTree(solver.displayForward(definition)));
|
||||
entity.setId(id);entity.setName(definition.name());entity.setDescription(request.path("description").asText(""));
|
||||
entity.setGeometryRevision(revision);entity.setGeometryJson(objectMapper.valueToTree(solver.normalize(geometry,tolerances)));
|
||||
entity.setTolerancesJson(objectMapper.valueToTree(tolerances));
|
||||
entity.setConnectableTargetsJson(objectMapper.valueToTree(connectableTargets));
|
||||
String sourceHash=request.path("sourceGeometryHash").asText("");
|
||||
if(!sourceHash.isBlank() && !sourceHash.equals(entity.getSourceGeometryHash()) && !("sha256:"+sourceHash).equals(entity.getSourceGeometryHash())) {
|
||||
entity.setSourceAssetKey("");entity.setSourceGeometryHash("");
|
||||
var query = new LambdaQueryWrapper<InterfaceDefinitionEntity>();
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
query.and(matches -> matches.like(InterfaceDefinitionEntity::getName, keyword)
|
||||
.or().like(InterfaceDefinitionEntity::getDescription, keyword));
|
||||
}
|
||||
if(existing)definitionMapper.updateById(entity);else definitionMapper.insert(entity);
|
||||
InterfaceDefinitionRevisionEntity snapshot=new InterfaceDefinitionRevisionEntity();
|
||||
snapshot.setId(id+":"+revision);snapshot.setDefinitionId(id);snapshot.setGeometryRevision(revision);snapshot.setDefinitionJson(toJson(entity, connectableTargets));
|
||||
if(displayOnly)revisionMapper.updateById(snapshot);else revisionMapper.insert(snapshot);
|
||||
return definitionMapper.selectList(query.orderByDesc(InterfaceDefinitionEntity::getUpdatedAt))
|
||||
.stream().map(this::toJson).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonNode get(String id) {
|
||||
return toJson(require(id, false));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public JsonNode create(SaveInterfaceDefinitionRequest request) {
|
||||
if (!StringUtils.hasText(request.id())) {
|
||||
throw invalid("id 不能为空");
|
||||
}
|
||||
String id = request.id().trim();
|
||||
if (definitionMapper.selectById(id) != null || revisionMapper.selectById(id + ":1") != null) {
|
||||
throw new BizException(409, "INTERFACE_ID_DUPLICATE", "接口 ID 已存在或已归档");
|
||||
}
|
||||
try {
|
||||
return save(new InterfaceDefinitionEntity(), request, id, false);
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw new BizException(409, "INTERFACE_ID_DUPLICATE", "接口 ID 已存在或已归档");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public JsonNode update(String id, SaveInterfaceDefinitionRequest request) {
|
||||
InterfaceDefinitionEntity entity = require(id, true);
|
||||
if (request.id() != null && !id.equals(request.id())) {
|
||||
throw invalid("URL 与接口定义 ID 不一致");
|
||||
}
|
||||
if (request.editRevision() == null || request.geometryRevision() == null) {
|
||||
throw invalid("修改接口必须提供 editRevision 和 geometryRevision");
|
||||
}
|
||||
if (!request.editRevision().equals(entity.getEditRevision())
|
||||
|| !request.geometryRevision().equals(entity.getGeometryRevision())) {
|
||||
throw new BizException(409, "INTERFACE_REVISION_CONFLICT", "接口已修改,请刷新后保存");
|
||||
}
|
||||
return save(entity, request, id, true);
|
||||
}
|
||||
|
||||
private JsonNode save(InterfaceDefinitionEntity entity, SaveInterfaceDefinitionRequest request,
|
||||
String id, boolean existing) {
|
||||
Definition proposed = new Definition(id, existing ? entity.getGeometryRevision() : 1,
|
||||
request.name().trim(), request.geometry(), request.tolerances(),
|
||||
request.connectableTargets(), request.displayForward());
|
||||
solver.validateDefinition(proposed);
|
||||
JsonNode geometry = objectMapper.valueToTree(solver.normalize(request.geometry(), request.tolerances()));
|
||||
JsonNode tolerances = objectMapper.valueToTree(request.tolerances());
|
||||
boolean sourceChanged = existing && StringUtils.hasText(request.sourceGeometryHash())
|
||||
&& !normalizeHash(request.sourceGeometryHash()).equals(normalizeHash(entity.getSourceGeometryHash()));
|
||||
boolean geometryChanged = existing && (sourceChanged || !geometry.equals(entity.getGeometryJson())
|
||||
|| !tolerances.equals(entity.getTolerancesJson()));
|
||||
int geometryRevision = existing
|
||||
? (geometryChanged ? Math.incrementExact(entity.getGeometryRevision()) : entity.getGeometryRevision())
|
||||
: 1;
|
||||
long editRevision = existing ? Math.incrementExact(entity.getEditRevision()) : 1L;
|
||||
|
||||
entity.setId(id);
|
||||
entity.setName(proposed.name());
|
||||
entity.setDescription(request.description() == null ? "" : request.description());
|
||||
entity.setGeometryRevision(geometryRevision);
|
||||
entity.setEditRevision(editRevision);
|
||||
entity.setGeometryJson(geometry);
|
||||
entity.setTolerancesJson(tolerances);
|
||||
entity.setConnectableTargetsJson(objectMapper.valueToTree(request.connectableTargets()));
|
||||
entity.setDisplayForwardJson(objectMapper.valueToTree(solver.displayForward(proposed)));
|
||||
// Source bindings are established by server-side file hashing only.
|
||||
if (sourceChanged) {
|
||||
entity.setSourceAssetKey("");
|
||||
entity.setSourceGeometryHash("");
|
||||
}
|
||||
if (existing) {
|
||||
if (definitionMapper.updateById(entity) != 1) {
|
||||
throw new BizException(409, "INTERFACE_REVISION_CONFLICT", "接口已删除,请刷新后保存");
|
||||
}
|
||||
} else {
|
||||
definitionMapper.insert(entity);
|
||||
}
|
||||
saveSnapshot(entity, !existing || geometryChanged);
|
||||
return toJson(entity);
|
||||
}
|
||||
public Definition geometryDefinition(String id,int revision){
|
||||
InterfaceDefinitionRevisionEntity entity=revisionMapper.selectById(id+":"+revision);
|
||||
if(entity==null)throw invalid("接口几何修订不存在,请重新识别");
|
||||
JsonNode n=entity.getDefinitionJson();
|
||||
return new Definition(id,revision,n.path("name").asText(),objectMapper.convertValue(n.get("geometry"),MountGeometry.class),objectMapper.convertValue(n.get("tolerances"),Tolerances.class),targets(n.get("connectableTargets")),objectMapper.convertValue(n.get("displayForward"),double[].class));
|
||||
|
||||
@Override
|
||||
public Definition geometryDefinition(String id, int revision) {
|
||||
InterfaceDefinitionRevisionEntity snapshot = revisionMapper.selectById(id + ":" + revision);
|
||||
if (snapshot == null) {
|
||||
throw invalid("接口几何修订不存在,请重新识别");
|
||||
}
|
||||
JsonNode json = snapshot.getDefinitionJson();
|
||||
return new Definition(id, revision, json.path("name").asText(),
|
||||
objectMapper.convertValue(json.get("geometry"), MountGeometry.class),
|
||||
objectMapper.convertValue(json.get("tolerances"), Tolerances.class),
|
||||
targets(json.get("connectableTargets")),
|
||||
objectMapper.convertValue(json.get("displayForward"), double[].class));
|
||||
}
|
||||
@Transactional public void delete(String id){require(id);definitionMapper.deleteById(id);}
|
||||
@Transactional public void attachAsset(String id,int revision,String key,String hash){
|
||||
InterfaceDefinitionEntity e=definitionMapper.selectOne(new LambdaQueryWrapper<InterfaceDefinitionEntity>().eq(InterfaceDefinitionEntity::getId,id).last("FOR UPDATE"));
|
||||
if(e==null||e.getGeometryRevision()!=revision)throw invalid("接口已修订,请刷新后重新保存源文件");
|
||||
if(e.getSourceGeometryHash()!=null && !e.getSourceGeometryHash().isBlank() && !hash.equals(e.getSourceGeometryHash()))throw invalid("该修订已有源文件,请创建新几何修订");
|
||||
e.setSourceAssetKey(key);e.setSourceGeometryHash(hash);definitionMapper.updateById(e);
|
||||
InterfaceDefinitionRevisionEntity snapshot=revisionMapper.selectById(id+":"+revision);
|
||||
if(snapshot==null)throw invalid("接口修订不存在");
|
||||
snapshot.setDefinitionJson(toJson(e));revisionMapper.updateById(snapshot);
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void delete(String id) {
|
||||
require(id, true);
|
||||
definitionMapper.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void attachAsset(String id, int revision, String key, String hash, String expectedAssetKey) {
|
||||
InterfaceDefinitionEntity entity = require(id, true);
|
||||
if (entity.getGeometryRevision() != revision) {
|
||||
throw new BizException(409, "INTERFACE_REVISION_CONFLICT", "接口已修订,请刷新后重新保存源文件");
|
||||
}
|
||||
if (StringUtils.hasText(entity.getSourceGeometryHash()) && !hash.equals(entity.getSourceGeometryHash())) {
|
||||
throw invalid("该修订已有源文件,请创建新几何修订");
|
||||
}
|
||||
if (key.equals(entity.getSourceAssetKey()) && hash.equals(entity.getSourceGeometryHash())) {
|
||||
return;
|
||||
}
|
||||
String boundKey = entity.getSourceAssetKey() == null ? "" : entity.getSourceAssetKey();
|
||||
if (!boundKey.equals(expectedAssetKey)) {
|
||||
throw new BizException(409, "INTERFACE_REVISION_CONFLICT", "源文件绑定已变化,请刷新后重试");
|
||||
}
|
||||
entity.setSourceAssetKey(key);
|
||||
entity.setSourceGeometryHash(hash);
|
||||
entity.setEditRevision(Math.incrementExact(entity.getEditRevision()));
|
||||
if (definitionMapper.updateById(entity) != 1) {
|
||||
throw new BizException(409, "INTERFACE_REVISION_CONFLICT", "接口已删除,请刷新后重试");
|
||||
}
|
||||
saveSnapshot(entity, false);
|
||||
}
|
||||
|
||||
private void saveSnapshot(InterfaceDefinitionEntity entity, boolean insert) {
|
||||
var snapshot = new InterfaceDefinitionRevisionEntity();
|
||||
snapshot.setId(entity.getId() + ":" + entity.getGeometryRevision());
|
||||
snapshot.setDefinitionId(entity.getId());
|
||||
snapshot.setGeometryRevision(entity.getGeometryRevision());
|
||||
snapshot.setDefinitionJson(toJson(entity));
|
||||
if (insert) {
|
||||
revisionMapper.insert(snapshot);
|
||||
} else if (revisionMapper.updateById(snapshot) != 1) {
|
||||
throw new IllegalStateException("接口几何修订快照缺失");
|
||||
}
|
||||
}
|
||||
|
||||
private InterfaceDefinitionEntity require(String id, boolean lock) {
|
||||
InterfaceDefinitionEntity entity = lock
|
||||
? definitionMapper.selectOne(new LambdaQueryWrapper<InterfaceDefinitionEntity>()
|
||||
.eq(InterfaceDefinitionEntity::getId, id).last("FOR UPDATE"))
|
||||
: definitionMapper.selectById(id);
|
||||
if (entity == null) {
|
||||
throw new BizException(404, "INTERFACE_NOT_FOUND", "接口不存在");
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
private JsonNode toJson(InterfaceDefinitionEntity entity) {
|
||||
ObjectNode json = objectMapper.createObjectNode();
|
||||
json.put("id", entity.getId());
|
||||
json.put("name", entity.getName());
|
||||
json.put("description", entity.getDescription());
|
||||
json.put("geometryRevision", entity.getGeometryRevision());
|
||||
json.put("editRevision", entity.getEditRevision());
|
||||
json.set("geometry", entity.getGeometryJson());
|
||||
json.set("displayForward", entity.getDisplayForwardJson());
|
||||
json.set("tolerances", entity.getTolerancesJson());
|
||||
json.set("connectableTargets", entity.getConnectableTargetsJson());
|
||||
if (entity.getSourceAssetKey() != null) json.put("sourceAssetKey", entity.getSourceAssetKey());
|
||||
if (entity.getSourceGeometryHash() != null) json.put("sourceGeometryHash", entity.getSourceGeometryHash());
|
||||
return json;
|
||||
}
|
||||
|
||||
private List<String> targets(JsonNode value) {
|
||||
if (value == null || value.isNull()) return List.of();
|
||||
try {
|
||||
return objectMapper.readerForListOf(String.class).readValue(value);
|
||||
} catch (java.io.IOException exception) {
|
||||
throw new IllegalStateException("接口连接目标存储格式不合法", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeHash(String hash) {
|
||||
String value = hash == null ? "" : hash.trim();
|
||||
return value.startsWith("sha256:") ? value.substring(7) : value;
|
||||
}
|
||||
|
||||
private BizException invalid(String message) {
|
||||
return new BizException(422, "INVALID_INTERFACE", message);
|
||||
}
|
||||
private InterfaceDefinitionEntity require(String id){InterfaceDefinitionEntity e=definitionMapper.selectById(id);if(e==null)throw invalid("接口不存在");return e;}
|
||||
private JsonNode toJson(InterfaceDefinitionEntity e){return toJson(e, targets(e.getConnectableTargetsJson()));}
|
||||
private JsonNode toJson(InterfaceDefinitionEntity e,List<String> connectableTargets){ObjectNode n=objectMapper.createObjectNode();n.put("id",e.getId());n.put("name",e.getName());n.put("description",e.getDescription());n.put("geometryRevision",e.getGeometryRevision());n.set("geometry",e.getGeometryJson());n.set("displayForward",e.getDisplayForwardJson());n.set("tolerances",e.getTolerancesJson());n.set("connectableTargets",objectMapper.valueToTree(connectableTargets));if(e.getSourceAssetKey()!=null)n.put("sourceAssetKey",e.getSourceAssetKey());if(e.getSourceGeometryHash()!=null)n.put("sourceGeometryHash",e.getSourceGeometryHash());return n;}
|
||||
private List<String> targets(JsonNode value){if(value==null||value.isNull()||!value.isArray())return List.of();List<String> result=new java.util.ArrayList<>();value.forEach(item->{String target=item.asText("").trim();if(!target.isEmpty()&&!result.contains(target))result.add(target);});return List.copyOf(result);}
|
||||
private String required(JsonNode n,String key){String s=n.path(key).asText("").trim();if(s.isEmpty())throw invalid(key+" 不能为空");return s;}
|
||||
private void rejectLegacy(JsonNode n){for(String key:List.of("profiles","mateRules","frameInComponent","allowedClockingDeg","xAxisAngleDeg"))if(n.has(key))throw invalid("不支持的接口结构:"+key);}
|
||||
private BizException invalid(String message){return new BizException(422,"INVALID_INTERFACE",message);}
|
||||
}
|
||||
|
||||
+1
@@ -52,6 +52,7 @@ public class ComponentUploadSessionTokenProvider {
|
||||
private Claims parseClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(secretKey)
|
||||
.requireIssuer(properties.issuer())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.linkerbot.cadworld.service.support;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import java.io.FilterInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
public final class UploadLimits {
|
||||
private UploadLimits() { }
|
||||
|
||||
public static void checkLength(long length, long limit) {
|
||||
if (limit <= 0) throw new BizException(500, "STORAGE_CONFIG_ERROR", "上传大小限制配置非法");
|
||||
if (length > limit) throw tooLarge();
|
||||
}
|
||||
|
||||
public static InputStream bounded(InputStream input, long limit) {
|
||||
checkLength(0, limit);
|
||||
return new FilterInputStream(input) {
|
||||
private long count;
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
int value = in.read();
|
||||
if (value >= 0) checkLength(++count, limit);
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
int read = in.read(bytes, offset, (int) Math.min(length, remainingIncludingProbe()));
|
||||
if (read > 0) {
|
||||
count += read;
|
||||
checkLength(count, limit);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long skip(long length) throws IOException {
|
||||
if (length <= 0) return 0;
|
||||
long skipped = in.skip(Math.min(length, remainingIncludingProbe()));
|
||||
count += skipped;
|
||||
checkLength(count, limit);
|
||||
return skipped;
|
||||
}
|
||||
|
||||
private long remainingIncludingProbe() {
|
||||
long remaining = limit - count;
|
||||
return remaining == Long.MAX_VALUE ? Long.MAX_VALUE : remaining + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean markSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void mark(int readLimit) {
|
||||
// Rewinding would make the byte limit ambiguous; this stream is forward-only.
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void reset() throws IOException {
|
||||
throw new IOException("Bounded upload streams do not support reset");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static void rethrowIfExceeded(Throwable exception) {
|
||||
for (Throwable cause = exception; cause != null; cause = cause.getCause()) {
|
||||
if (cause instanceof BizException failure && "UPLOAD_TOO_LARGE".equals(failure.getCode())) throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private static BizException tooLarge() {
|
||||
return new BizException(413, "UPLOAD_TOO_LARGE", "上传文件超过大小限制");
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
|
||||
class InterfaceAssetServiceTest {
|
||||
final InterfaceDefinitionService definitions = mock(InterfaceDefinitionService.class);
|
||||
final ObjectStorageClient storage = mock(ObjectStorageClient.class);
|
||||
final InterfaceAssetService service = new InterfaceAssetService(definitions, storage,
|
||||
new StorageProperties("local", "models", "covers", "http://localhost", "http://localhost", ".", Duration.ofMinutes(30), 16));
|
||||
|
||||
@BeforeEach
|
||||
void currentDefinition() {
|
||||
when(definitions.get("mount")).thenReturn(new ObjectMapper().createObjectNode().put("geometryRevision", 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hashesFromStreamAndNeverLoadsMultipartBytes() throws Exception {
|
||||
var file = spy(new MockMultipartFile("file", "source.step", "application/octet-stream", new byte[]{1, 2, 3}));
|
||||
doThrow(new AssertionError("getBytes must not be used")).when(file).getBytes();
|
||||
String key = service.upload("mount", 1, file);
|
||||
assertThat(key).startsWith("interfaces/6d6f756e74/1/").endsWith("/source.step");
|
||||
verify(file, never()).getBytes();
|
||||
verify(definitions).attachAsset(eq("mount"), eq(1), eq(key), startsWith("sha256:"), eq(""));
|
||||
verify(storage, never()).deleteObject(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindingFailureDeletesOnlyTheObjectOwnedByThisRequest() {
|
||||
var conflict = new BizException(409, "INTERFACE_REVISION_CONFLICT", "接口已修订");
|
||||
doThrow(conflict).when(definitions).attachAsset(anyString(), anyInt(), anyString(), anyString(), anyString());
|
||||
assertThatThrownBy(() -> service.upload("mount", 1,
|
||||
new MockMultipartFile("file", "source.step", "application/octet-stream", new byte[]{1})))
|
||||
.isSameAs(conflict);
|
||||
var key = ArgumentCaptor.forClass(String.class);
|
||||
verify(storage).putObject(key.capture(), anyString(), any(InputStream.class), eq(1L));
|
||||
verify(storage).deleteObject(key.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void compensationFailureDoesNotReplaceOriginalBusinessFailure() {
|
||||
var conflict = new BizException(409, "CONFLICT", "接口已修订");
|
||||
doThrow(conflict).when(definitions).attachAsset(anyString(), anyInt(), anyString(), anyString(), anyString());
|
||||
doThrow(new IllegalStateException("storage unavailable")).when(storage).deleteObject(anyString());
|
||||
assertThatThrownBy(() -> service.upload("mount", 1,
|
||||
new MockMultipartFile("file", "source.step", "application/octet-stream", new byte[]{1})))
|
||||
.isSameAs(conflict);
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleRevisionAndOversizeFilesFailBeforeStorageWrites() {
|
||||
var file = new MockMultipartFile("file", "source.step", "application/octet-stream", new byte[17]);
|
||||
assertThatThrownBy(() -> service.upload("mount", 2, file)).isInstanceOf(BizException.class)
|
||||
.extracting("httpStatus").isEqualTo(409);
|
||||
assertThatThrownBy(() -> service.upload("mount", 1, file)).isInstanceOf(BizException.class)
|
||||
.extracting("httpStatus").isEqualTo(413);
|
||||
verifyNoInteractions(storage);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.config.UploadSessionProperties;
|
||||
import com.linkerbot.cadworld.enums.ComponentUploadType;
|
||||
import com.linkerbot.cadworld.service.client.LocalObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class UploadIntegrityTest {
|
||||
@TempDir Path root;
|
||||
final String secret = "test-upload-signing-key-32-bytes-long";
|
||||
|
||||
@Test
|
||||
void unknownLengthUploadIsBoundedAndCannotDestroyExistingObject() throws Exception {
|
||||
var properties = new StorageProperties("local", "components/urdf", "components/cover-images", "http://localhost",
|
||||
"http://localhost", root.toString(), Duration.ofMinutes(30), 8);
|
||||
var storage = new LocalObjectStorageClient(properties);
|
||||
var tokens = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("upload", secret));
|
||||
var support = new ComponentUploadSupport(properties, storage, tokens);
|
||||
String prefix = "components/urdf/0/session/";
|
||||
String key = prefix + "model.rfs";
|
||||
String token = tokens.generateToken(0L, ComponentUploadType.URDF, prefix, Instant.now().plusSeconds(60));
|
||||
support.uploadObject(0L, token, key, "application/octet-stream", new ByteArrayInputStream(new byte[]{1, 2}), -1);
|
||||
assertThatThrownBy(() -> support.uploadObject(0L, token, key, "application/octet-stream", new ByteArrayInputStream(new byte[9]), -1))
|
||||
.isInstanceOf(BizException.class).extracting("httpStatus").isEqualTo(413);
|
||||
assertThat(java.nio.file.Files.readAllBytes(root.resolve(key))).containsExactly((byte) 1, (byte) 2);
|
||||
try (var files = java.nio.file.Files.walk(root)) {
|
||||
assertThat(files.filter(java.nio.file.Files::isRegularFile).count()).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadTokenFromAnotherIssuerIsRejectedEvenWithTheSameSigningKey() {
|
||||
var expected = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("expected", secret));
|
||||
var other = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("other", secret));
|
||||
String token = other.generateToken(0L, ComponentUploadType.URDF, "components/urdf/0/session/", Instant.now().plusSeconds(60));
|
||||
assertThatThrownBy(() -> expected.parseToken(token)).isInstanceOf(io.jsonwebtoken.JwtException.class);
|
||||
}
|
||||
}
|
||||
-1
@@ -38,7 +38,6 @@ class ComponentServiceImplTest {
|
||||
void setUp() {
|
||||
service = new ComponentServiceImpl(
|
||||
componentMapper,
|
||||
null,
|
||||
objectStorageUrlResolver,
|
||||
new ObjectMapper(), new com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService(
|
||||
MechanicalTestFixtures.definitions(),MechanicalTestFixtures.SOLVER,new ObjectMapper(),
|
||||
|
||||
+44
-13
@@ -24,17 +24,19 @@ class InterfaceDefinitionRevisionTest {
|
||||
new Hole("b",new double[]{.02,0,0},new double[]{0,0,1},.004)));
|
||||
InterfaceDefinitionEntity current(){
|
||||
InterfaceDefinitionEntity e=new InterfaceDefinitionEntity();
|
||||
e.setId("mount");e.setName("mount");e.setGeometryRevision(1);
|
||||
e.setId("mount");e.setName("mount");e.setGeometryRevision(1);e.setEditRevision(1L);
|
||||
e.setGeometryJson(json.valueToTree(geometry));e.setTolerancesJson(json.valueToTree(Tolerances.defaults()));
|
||||
e.setSourceGeometryHash("sha256:old");e.setSourceAssetKey("interfaces/old.step");
|
||||
when(definitions.selectOne(any())).thenReturn(e);return e;
|
||||
when(definitions.selectOne(any())).thenReturn(e);
|
||||
when(definitions.updateById(any(InterfaceDefinitionEntity.class))).thenReturn(1);
|
||||
when(revisions.updateById(any(InterfaceDefinitionRevisionEntity.class))).thenReturn(1);return e;
|
||||
}
|
||||
ObjectNode request(){
|
||||
ObjectNode n=json.createObjectNode().put("id","mount").put("name","updated").put("geometryRevision",1);
|
||||
ObjectNode n=json.createObjectNode().put("id","mount").put("name","updated").put("geometryRevision",1).put("editRevision",1);
|
||||
n.set("geometry",json.valueToTree(geometry));n.set("tolerances",json.valueToTree(Tolerances.defaults()));return n;
|
||||
}
|
||||
@Test void editsAppendRevisionAndDoNotOverwriteOldSnapshot(){
|
||||
current();var result=service.update("mount",request());
|
||||
current();var result=service.update("mount",dto(changedGeometry()));
|
||||
assertThat(result.path("geometryRevision").asInt()).isEqualTo(2);
|
||||
assertThat(result.path("sourceAssetKey").asText()).isEqualTo("interfaces/old.step");
|
||||
ArgumentCaptor<InterfaceDefinitionRevisionEntity> capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
|
||||
@@ -42,16 +44,16 @@ class InterfaceDefinitionRevisionTest {
|
||||
verify(revisions,never()).updateById(any(InterfaceDefinitionRevisionEntity.class));
|
||||
}
|
||||
@Test void staleEditsAndAssetUploadsAreRejected(){
|
||||
current();assertThatThrownBy(()->service.update("mount",request().put("geometryRevision",2))).hasMessageContaining("刷新");
|
||||
assertThatThrownBy(()->service.attachAsset("mount",2,"other.step","sha256:new")).hasMessageContaining("修订");
|
||||
assertThatThrownBy(()->service.attachAsset("mount",1,"other.step","sha256:new")).hasMessageContaining("新几何修订");
|
||||
current();assertThatThrownBy(()->service.update("mount",dto(request().put("geometryRevision",2)))).hasMessageContaining("刷新");
|
||||
assertThatThrownBy(()->service.attachAsset("mount",2,"other.step","sha256:new","interfaces/old.step")).hasMessageContaining("修订");
|
||||
assertThatThrownBy(()->service.attachAsset("mount",1,"other.step","sha256:new","interfaces/old.step")).hasMessageContaining("新几何修订");
|
||||
verify(definitions,never()).updateById(any(InterfaceDefinitionEntity.class));
|
||||
}
|
||||
@Test void displayOnlyEditPersistsWithoutInvalidatingGeometryRevision(){
|
||||
InterfaceDefinitionEntity e=current();
|
||||
ObjectNode body=request().put("name",e.getName());
|
||||
body.set("displayForward",json.valueToTree(new double[]{0,1,0}));
|
||||
var result=service.update("mount",body);
|
||||
var result=service.update("mount",dto(body));
|
||||
assertThat(result.path("geometryRevision").asInt()).isEqualTo(1);
|
||||
assertThat(result.path("displayForward")).isEqualTo(body.path("displayForward"));
|
||||
ArgumentCaptor<InterfaceDefinitionRevisionEntity> capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
|
||||
@@ -60,13 +62,42 @@ class InterfaceDefinitionRevisionTest {
|
||||
assertThat(service.geometryDefinition("mount",1).displayForward()).containsExactly(0,1,0);
|
||||
}
|
||||
@Test void replacingSourceClearsOldAssetAndAttachesOnlyToNewRevision(){
|
||||
InterfaceDefinitionEntity e=current();var result=service.update("mount",request().put("sourceGeometryHash","new"));
|
||||
InterfaceDefinitionEntity e=current();var result=service.update("mount",dto(request().put("sourceGeometryHash","new")));
|
||||
assertThat(result.path("sourceAssetKey").asText()).isEmpty();
|
||||
assertThat(e.getSourceGeometryHash()).isEmpty();
|
||||
InterfaceDefinitionRevisionEntity snapshot=new InterfaceDefinitionRevisionEntity();snapshot.setId("mount:2");
|
||||
when(revisions.selectById("mount:2")).thenReturn(snapshot);
|
||||
service.attachAsset("mount",2,"interfaces/new.step","sha256:new");
|
||||
assertThat(snapshot.getDefinitionJson().path("sourceAssetKey").asText()).isEqualTo("interfaces/new.step");
|
||||
assertThat(snapshot.getDefinitionJson().path("geometryRevision").asInt()).isEqualTo(2);
|
||||
service.attachAsset("mount",2,"interfaces/new.step","sha256:new","");
|
||||
ArgumentCaptor<InterfaceDefinitionRevisionEntity> capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
|
||||
verify(revisions).updateById(capture.capture());
|
||||
assertThat(capture.getValue().getDefinitionJson().path("sourceAssetKey").asText()).isEqualTo("interfaces/new.step");
|
||||
assertThat(capture.getValue().getDefinitionJson().path("geometryRevision").asInt()).isEqualTo(2);
|
||||
}
|
||||
ObjectNode changedGeometry() {
|
||||
ObjectNode body = request();
|
||||
((ObjectNode) body.path("geometry").path("holes").get(1))
|
||||
.set("pointOnPlaneM", json.valueToTree(new double[]{.03,0,0}));
|
||||
return body;
|
||||
}
|
||||
com.linkerbot.cadworld.dto.interfaces.SaveInterfaceDefinitionRequest dto(ObjectNode body) {
|
||||
return json.convertValue(body, com.linkerbot.cadworld.dto.interfaces.SaveInterfaceDefinitionRequest.class);
|
||||
}
|
||||
@Test void metadataEditsDoNotInvalidateGeometryButRejectStaleEditors() {
|
||||
InterfaceDefinitionEntity entity = current();
|
||||
var result = service.update("mount", dto(request()));
|
||||
assertThat(result.path("geometryRevision").asInt()).isEqualTo(1);
|
||||
assertThat(result.path("editRevision").asLong()).isEqualTo(2);
|
||||
assertThatThrownBy(() -> service.update("mount", dto(request())))
|
||||
.isInstanceOf(com.linkerbot.cadworld.common.exception.BizException.class)
|
||||
.hasMessageContaining("刷新");
|
||||
assertThat(entity.getEditRevision()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test void concurrentUploadsCannotReplaceAnotherSuccessfulBinding() {
|
||||
InterfaceDefinitionEntity entity = current();
|
||||
assertThatThrownBy(() -> service.attachAsset("mount", 1, "interfaces/loser.step", "sha256:old", ""))
|
||||
.isInstanceOf(com.linkerbot.cadworld.common.exception.BizException.class)
|
||||
.hasMessageContaining("绑定已变化");
|
||||
assertThat(entity.getSourceAssetKey()).isEqualTo("interfaces/old.step");
|
||||
verify(definitions, never()).updateById(any(InterfaceDefinitionEntity.class));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user