重构,去掉接口
This commit is contained in:
+6
-4
@@ -4,7 +4,7 @@ SERVER_PORT=8992
|
||||
APP_DB_URL='jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai'
|
||||
APP_DB_USERNAME=
|
||||
APP_DB_PASSWORD=
|
||||
# Maximum bytes per upload, including raw PUT streams (default 100 MiB).
|
||||
# Maximum bytes per OSS object, enforced in policy and when saving (default 100 MiB).
|
||||
APP_STORAGE_MAX_UPLOAD_BYTES=104857600
|
||||
OSS_ACCESS_KEY_ID=
|
||||
OSS_ACCESS_KEY_SECRET=
|
||||
@@ -12,12 +12,14 @@ OSS_REGION=oss-cn-beijing
|
||||
OSS_BUCKET=linkerbot
|
||||
# 默认 test: cadworld_dev,prod: cadworld;需要覆盖时取消注释。
|
||||
# OSS_ROOT_PREFIX=cadworld_dev
|
||||
APP_STORAGE_PUBLIC_API_BASE_URL=http://127.0.0.1:8992
|
||||
APP_STORAGE_PUBLIC_BASE_URL=http://127.0.0.1:8992/admin-api/component-assets
|
||||
# At least 32 UTF-8 bytes. Empty uses a random key and invalidates sessions on restart.
|
||||
APP_UPLOAD_SESSION_SECRET=
|
||||
APP_ADMIN_OPERATOR_ID=0
|
||||
APP_ADMIN_OPERATOR_NAME=TEST_OPERATOR
|
||||
APP_INTERFACE_BREP_PYTHON=python3
|
||||
APP_INTERFACE_BREP_SCRIPT=classpath:scripts/step_brep_topology.py
|
||||
LOG_PATH=logs
|
||||
|
||||
# OSS 目录上传签名有效期(不超过会话剩余有效期)
|
||||
OSS_UPLOAD_SIGNATURE_TTL=PT5M
|
||||
# 上传会话有效期,续签不会延长此时间。
|
||||
OSS_UPLOAD_SESSION_TTL=PT30M
|
||||
|
||||
@@ -1,191 +1,116 @@
|
||||
# cadworld
|
||||
|
||||
Java 21 / Spring Boot 3.4.4 / MyBatis-Plus 后台多模块项目。包名统一为 `com.linkerbot.cadworld`,Maven groupId 为 `com.linkerbot`。当前包含接口库、组件库、用户管理和操作日志,默认端口 `8992`。
|
||||
Java 21 / Spring Boot 3.4.4 / MyBatis-Plus 后台多模块项目。后台只保留组件库、用户管理和操作日志,默认端口 `8992`。
|
||||
|
||||
## 模块
|
||||
## 项目模块
|
||||
|
||||
| 模块 | 内容 |
|
||||
| --- | --- |
|
||||
| cadworld-adminapi | 后台启动应用、Controller、Web 配置、操作日志拦截 |
|
||||
| cadworld-service | 业务服务、Mapper、阿里云 OSS、几何与资源校验 |
|
||||
| cadworld-bean | 实体、DTO、枚举 |
|
||||
| cadworld-common | 响应、异常、JSON 类型处理、请求编号、进程执行工具 |
|
||||
| cadworld-adminapi | 后台启动应用、Controller、Web 配置、运行日志和审计 |
|
||||
| cadworld-service | 业务服务、Mapper、阿里云 OSS 签名、资源校验 |
|
||||
| cadworld-bean | 实体、请求和响应 DTO、枚举 |
|
||||
| cadworld-common | 统一响应、异常、JSON 类型处理、请求编号和操作目标上下文 |
|
||||
| cadworld-api | 预留前台 API 模块 |
|
||||
| cadworld-security | 预留 admin/api/common 三个安全子模块 |
|
||||
| cadworld-security | 预留安全子模块 |
|
||||
|
||||
本阶段后台接口不鉴权,没有登录、角色或菜单权限接口。日志和上传流程统一使用配置的测试操作人,默认 `0 / TEST_OPERATOR`,不要求 `sys_user` 中存在该用户。上传会话签名用于限制会话类型、对象目录及有效期,与账号登录认证独立。
|
||||
当前没有登录和权限接口。上传和审计使用配置操作人,默认 `0 / TEST_OPERATOR`,无需在 `sys_user` 中创建对应记录。上传会话令牌绑定操作人、组件、上传批次和资源目录。
|
||||
|
||||
## 数据库准备
|
||||
## 数据库
|
||||
|
||||
默认测试库为 `39.105.93.138:3306/cadworld`,账号和密码必须自行通过环境变量提供。应用启动不执行建表或迁移。
|
||||
运行代码只访问 `component`、`sys_user`、`sys_operation_log` 三张业务表。使用已重建的组件表和通用操作日志表;`sys_user` 结构和用户管理行为保持不变。
|
||||
|
||||
已有库包含所给 `cadworld.sql` 中的 `sys_user` 和 `component` 表时,执行增量脚本:
|
||||
组件存储基本信息、零件参数、两组自定义字段、STEP 对象键、URDF 目录及实际文件清单、`version` 和维护时间。通用日志存储模块、动作、目标快照、操作人、请求元信息和结果,不依赖组件专属列。
|
||||
|
||||
```bash
|
||||
mysql -h 39.105.93.138 -P 3306 -u YOUR_USER -p cadworld < db/upgrade.sql
|
||||
```
|
||||
应用启动不建表、不迁移旧数据。本次未修改 `.sql` 文件;仓库中历史 SQL 不代表当前组件和日志结构,请使用已经建好的表。MySQL 需支持现有建表语句中的 JSON / TEXT 表达式默认值。
|
||||
|
||||
对于已经创建好的空数据库,执行初始化脚本:
|
||||
|
||||
```bash
|
||||
mysql -h 39.105.93.138 -P 3306 -u YOUR_USER -p cadworld < db/init.sql
|
||||
```
|
||||
|
||||
原有两个脚本保留不变。执行初始化或增量脚本后,还需执行下面的接口重构补充 SQL。当前业务使用五张表:`sys_user`、`component`、`interface_definition_v2`、`interface_definition_revision`、`sys_operation_log`;组件资源索引代码已移除。
|
||||
|
||||
用户删除保留数据及手机号唯一索引,已删除用户的手机号不能重新注册。组件删除沿用物理删除;接口删除保留历史修订,原接口 ID 不能再次创建。删除操作不会清理 OSS 中的资源对象。
|
||||
|
||||
### 接口重构补充 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,不覆盖其他人的修改。
|
||||
组件名称允许重复,编码唯一且不可修改。组件物理删除,用户逻辑删除;已删除用户的手机号仍被占用。组件替换资源或删除记录均不自动删除 OSS 文件。
|
||||
|
||||
## 配置与启动
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# 填写 .env 中的数据库和阿里云 OSS 参数。
|
||||
# 填写数据库、OSS 参数和上传会话密钥。
|
||||
set -a
|
||||
source .env
|
||||
set +a
|
||||
mvn clean verify
|
||||
mvn -pl cadworld-adminapi -am -DskipTests package
|
||||
java -jar cadworld-adminapi/target/cadworld-adminapi-0.0.1-SNAPSHOT.jar
|
||||
```
|
||||
|
||||
`.env` 通过 shell 导入,Spring Boot 不自动读取该文件。默认 profile 为 `test`;使用 `prod` 时必须设置 `APP_DB_URL`、`APP_DB_USERNAME`、`APP_DB_PASSWORD`,Swagger 默认关闭。
|
||||
Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile 为 `test`;生产使用 `SPRING_PROFILES_ACTIVE=prod`,提供数据库连接变量。生产 Swagger 默认关闭。
|
||||
|
||||
| 环境变量 | 用途 |
|
||||
| --- | --- |
|
||||
| APP_DB_URL / APP_DB_USERNAME / APP_DB_PASSWORD | MySQL 连接配置 |
|
||||
| SERVER_PORT | 后台端口,默认 8992 |
|
||||
| OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET | 阿里云 OSS 凭证,必填;仅通过环境变量或 Git 忽略的 `.env` 提供 |
|
||||
| OSS_REGION / OSS_BUCKET | 默认 `oss-cn-beijing / linkerbot`;签名地域自动转换为 `cn-beijing` |
|
||||
| OSS_ROOT_PREFIX | 桶内根目录;`test` 默认 `cadworld_dev`,`prod` 默认 `cadworld`,各部署环境可独立覆盖 |
|
||||
| APP_STORAGE_PUBLIC_API_BASE_URL | 生成上传地址所用的后台外部地址 |
|
||||
| APP_STORAGE_PUBLIC_BASE_URL | 生成下载地址的资源前缀,默认 `/admin-api/component-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` |
|
||||
| OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET | 阿里云 OSS 凭证,通过环境变量或被 Git 忽略的 `.env` 提供 |
|
||||
| OSS_REGION / OSS_BUCKET | 默认 `oss-cn-beijing / linkerbot`,签名地域使用 `cn-beijing` |
|
||||
| OSS_ROOT_PREFIX | 桶内环境根目录;`test` 默认 `cadworld_dev`,`prod` 默认 `cadworld` |
|
||||
| APP_STORAGE_PUBLIC_BASE_URL | 返回资源访问地址所用的前缀,默认指向 `/admin-api/component-assets` |
|
||||
| APP_STORAGE_MAX_UPLOAD_BYTES | 每个 OSS 文件的大小上限,默认 104857600 字节(100 MiB),签名策略与保存检查一致 |
|
||||
| OSS_UPLOAD_SESSION_TTL | 上传会话有效期,默认 `PT30M`;续签不延长会话 |
|
||||
| OSS_UPLOAD_SIGNATURE_TTL | OSS 签名有效期,默认 `PT5M`,不超过会话剩余时间 |
|
||||
| APP_UPLOAD_SESSION_SECRET | 至少 32 个 UTF-8 字节;留空使用进程随机密钥,重启后原会话失效;多实例需配置相同密钥 |
|
||||
| APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME | 当前配置操作人,默认 `0 / TEST_OPERATOR` |
|
||||
| LOG_PATH | 运行日志目录,默认 `logs` |
|
||||
|
||||
运行时只使用阿里云 OSS,通过 HTTPS 和 V4 签名访问已有存储桶,不自动创建桶。账号需要对应目录下的上传、读取和删除权限。资源继续通过后台上传和读取,无需客户端直连 OSS;线上地址配置应包含实际域名及反向代理路径,上传和下载地址均使用 `/admin-api` 前缀。
|
||||
运行时使用已有 OSS 桶,不自动创建桶。前端通过 OSS V4 表单签名直接上传,后端通过 HEAD 检查文件,资源下载仍由后台代理。OSS 需配置前端站点的 CORS,允许表单 POST;上传字段原样使用,`file` 放在表单最后。凭证需有目标目录上传和读取权限。
|
||||
|
||||
数据库资源字段及 URDF 资源清单只保存桶内相对对象键,例如 `cadworld_dev/components/urdf/.../robot.urdf`;访问 URL 由后台生成,不入库。所有上传、入库和存储读写都校验当前环境根目录,完整 URL、跨环境路径或目录越界返回 `422 / INVALID_STORAGE_OBJECT_KEY`。根目录不要配置成完整 URL。新增路径包含根目录后的总长度仍受原字段限制。
|
||||
对象路径:
|
||||
|
||||
本次切换不迁移历史 MinIO 文件或数据库记录,旧资源需要重新上传;切换后旧上传会话也需要重新创建。更改根目录会使原目录对象不能被当前环境访问。
|
||||
```text
|
||||
{环境根目录}/components/{组件编码}/step/{上传批次}/{文件名}
|
||||
{环境根目录}/components/{组件编码}/urdf/{上传批次}/{相对路径}
|
||||
```
|
||||
|
||||
接口文档:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`/api-docs`。日志配置集中在 `cadworld-common`,按应用名输出 `cadworld-adminapi.log` 和独立的 `cadworld-adminapi-error.log`,并携带请求编号。普通日志按天及 100 MB 滚动,保留 30 天、最多 10 GB;ERROR 日志按天及 50 MB 滚动,保留 60 天、最多 5 GB。归档文件保存在 `logs/archive`(支持 `LOG_PATH` 覆盖)。测试环境项目包日志为 DEBUG,生产环境为 INFO;Mapper 日志保持 INFO,避免 SQL 参数输出敏感数据。
|
||||
数据库只保存对象键,不保存完整 URL。返回 URL 对每段路径编码,访问路径区分大小写;根目录不要填写 URL。跨环境、越界、非法路径会被拒绝。更改环境根目录后,原目录资源不能由该部署访问。
|
||||
|
||||
全部后台业务接口通过 `@ApiRequestLog` 提供中文说明,统一输出请求开始与结束日志,包含路由模板、请求编号、结果、HTTP 状态、业务错误码及耗时。成功记录 INFO,业务或参数失败记录 WARN,服务异常记录 ERROR。文件流上传、下载以及 MVC 之前的 multipart 超限也覆盖;不输出请求体、查询参数、文件内容或完整对象路径。接口运行日志写入运行日志文件;数据库操作日志继续按组件库和接口库写操作的既有范围记录。
|
||||
## 上传与接口
|
||||
|
||||
## 后台接口
|
||||
上传只使用 `POST /admin-api/storage/upload-signature`。新增首次传 `{}`,获得后端编码、一个上传会话令牌和 STEP / URDF 两组授权;编辑传 `componentId`;续签传原 `uploadSessionToken`。申请签名不创建组件记录。
|
||||
|
||||
前端联调文档:[后台接口文档](cadworld-adminapi/docs/admin-api.md),按模块列出全部业务接口、入参及返回示例、上传流程和错误处理。
|
||||
前端流程为:**获取编码和签名 → STEP 文件和 URDF 文件夹直传 OSS → POST / PUT 保存组件**。URDF 去掉选中文件夹最外层目录,保留内部结构。保存提交对象键,后端校验归属、实际存在性、大小及主文件后才写数据库。PUT 必须带详情中的 `version`,并发修改返回 409。
|
||||
|
||||
响应沿用 `{code, message, data, requestId}`,分页数据为 `{items, page, size, total}`。新建用户和操作日志列表的页码从 1 开始,默认每页 20,最多 100。
|
||||
完整请求、响应及浏览器上传代码见 [后台接口文档](cadworld-adminapi/docs/admin-api.md)。
|
||||
|
||||
| 路径 | 方法及行为 |
|
||||
| 路径 | 方法 |
|
||||
| --- | --- |
|
||||
| /admin-api/interfaces | GET 列表(keyword),POST 创建 |
|
||||
| /admin-api/interfaces/{id} | GET 详情,PUT 修改,DELETE 删除 |
|
||||
| /admin-api/interfaces/{id}/assets | POST 源文件上传,参数 geometryRevision、file |
|
||||
| /admin-api/interfaces/{id}/pose-candidates | POST 计算姿态候选 |
|
||||
| /admin-api/interfaces/{id}/confirm-port | POST 校验并确认端口 |
|
||||
| /admin-api/interface-brep/analyze | POST multipart STEP/STP 精确解析 |
|
||||
| /admin-api/components | GET 分页列表(page、size、keyword),POST 创建 |
|
||||
| /admin-api/components/{id} | GET 详情,PUT 修改,DELETE 删除 |
|
||||
| /admin-api/components/cover-image-upload-sessions | POST 创建封面上传会话;子路径 /upload-url、/complete 均为 POST |
|
||||
| /admin-api/components/urdf-upload-sessions | POST 创建 URDF/RFS 上传会话;子路径 /upload-url、/complete 均为 POST |
|
||||
| /admin-api/component-assets/upload | PUT 文件流上传,参数 objectKey |
|
||||
| /admin-api/component-assets/{objectKey} | GET 资源文件 |
|
||||
| /admin-api/users | GET 分页用户列表,POST 创建 |
|
||||
| /admin-api/storage/upload-signature | POST,新增签名、编辑签名、续签 |
|
||||
| /admin-api/components | GET 分页列表,POST 新增 |
|
||||
| /admin-api/components/{id} | GET 详情,PUT 全量表单修改,DELETE 删除 |
|
||||
| /admin-api/component-assets/{objectKey} | GET 下载资源 |
|
||||
| /admin-api/users | GET 分页列表,POST 新增 |
|
||||
| /admin-api/users/{id} | GET 详情,PUT 修改,DELETE 逻辑删除 |
|
||||
| /admin-api/operation-logs | GET 分页操作日志 |
|
||||
| /admin-api/operation-logs/{id} | GET 日志详情 |
|
||||
| /admin-api/operation-logs | GET 分页列表,支持通用目标与模块筛选 |
|
||||
| /admin-api/operation-logs/{id} | GET 详情 |
|
||||
|
||||
用户创建及修改请求示例:
|
||||
统一响应为 `{code, message, data, requestId}`,成功 `code=OK`。分页为 `{items, page, size, total}`,页码从 1 开始,默认每页 20,上限 100。下载成功直接返回文件流。
|
||||
|
||||
```json
|
||||
{"phone":"13812345678","nickname":"测试用户","status":"ACTIVE","userType":"NORMAL"}
|
||||
```
|
||||
接口库、端口、姿态和 BREP 路由已移除,Python 工具不再需要。旧上传会话、上传确认、封面和后台文件流上传路由均返回 404。
|
||||
|
||||
手机号为大陆手机号,昵称必填且最多 64 字符;状态为 `ACTIVE/DISABLED`,用户类型为 `NORMAL/ADMIN`。创建时省略状态和类型默认为 `ACTIVE/NORMAL`,修改时省略则保留原值。用户列表支持 `keyword`(手机号/昵称)、`userType`、`status` 筛选,查询排除已逻辑删除用户。
|
||||
## 日志
|
||||
|
||||
操作日志列表支持 `module`(`COMPONENT/INTERFACE`)、`action`、`success`、`operatorId`、`from`、`to`。时间使用上海时区的 ISO 本地时间,例如 `2026-10-09T16:00:00`。
|
||||
当前业务操作日志仅持久化组件 `CREATE / UPDATE / DELETE` 的成功和失败。资源校验及替换结果归入对应保存事件。日志表、审计基础设施和查询仍支持其他业务模块。
|
||||
|
||||
日志动作:`CREATE`、`UPDATE`、`DELETE`、`PREPARE_UPLOAD`、`PREPARE_UPLOAD_URL`、`UPLOAD`、`COMPLETE_UPLOAD`。成功及失败的写操作均记录;查询、下载、STEP 分析、姿态计算及用户管理不记录业务操作日志。日志只保存操作元信息和标识,不保存请求体、文件或上传令牌;日志持久化使用独立事务,失败时输出运行错误日志并保留原请求结果。
|
||||
日志保留目标主键、编码和名称快照,删除后仍可追溯;写入使用独立事务,失败不改变业务结果。签名、续签、查询、下载和用户管理只输出运行日志。日志不保存请求体、表单值、令牌、签名或敏感信息,定位使用请求编号、路由模板和安全的异常信息。
|
||||
|
||||
## STEP 解析运行环境
|
||||
运行日志配置集中在 `cadworld-common`,输出 `cadworld-adminapi.log` 与 `cadworld-adminapi-error.log`,按时间和大小归档。Mapper 日志保持 INFO,避免输出 SQL 参数。
|
||||
|
||||
建议使用 Python 3.12,OCCT 依赖锁定为 `cadquery-ocp==7.8.1.1`:
|
||||
|
||||
```bash
|
||||
python3.12 -m venv cadworld-adminapi/.venv
|
||||
cadworld-adminapi/.venv/bin/pip install -r cadworld-adminapi/requirements-interface-brep.txt
|
||||
export APP_INTERFACE_BREP_PYTHON="$PWD/cadworld-adminapi/.venv/bin/python"
|
||||
```
|
||||
|
||||
解析脚本包含在后台 JAR 中,每次分析提取到临时目录并在完成后清理。`APP_INTERFACE_BREP_SCRIPT` 可覆盖为外部脚本路径。默认超时 120 秒、上传及输出限制各 100 MB,可使用 `APP_INTERFACE_BREP_TIMEOUT_SECONDS`、`APP_INTERFACE_BREP_MAX_UPLOAD_BYTES`、`APP_INTERFACE_BREP_MAX_OUTPUT_BYTES` 调整;上传体积还受 Spring multipart 限制。
|
||||
|
||||
接口解析仅使用 OCCT 原生 STEP B-Rep。缺少运行库、解析失败、超时及输出过大返回明确错误,不回退到三角网格拟合。
|
||||
测试环境 Swagger:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`/api-docs`。
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
mvn clean verify
|
||||
cadworld-adminapi/.venv/bin/python -m unittest discover -s cadworld-adminapi/scripts/tests
|
||||
mvn -pl cadworld-adminapi -am clean test
|
||||
mvn -pl cadworld-adminapi -am -DskipTests package
|
||||
```
|
||||
|
||||
默认 Java 测试使用 SDK Mock、H2 和仅存在于测试代码中的内存资源替身,不连接共享数据库或真实 OSS。Python 测试包含程序生成的真实 STEP 文件及无效文件解析;缺少外部原始模型时,对应回归用例跳过。
|
||||
自动测试通过 Java 在 H2 创建临时表,使用内存 OSS,不连接业务 MySQL、不执行业务数据库 DDL。覆盖签名与续签、资源校验及替换、默认值、自定义字段、版本冲突、审计、删除快照、旧路由 404 和用户管理回归,并校验 OSS V4 签名策略。
|
||||
|
||||
MySQL 集成测试使用可清空的专用 `cadworld_verification` 数据库,验证初始化、升级、重复执行及数据保留,并运行业务接口用例。资源仍使用内存替身。准备独立 MySQL(默认 `127.0.0.1:13306`,root 空密码)后执行:
|
||||
真实 OSS 的独立测试需显式配置凭证并启用 `oss-integration` profile:
|
||||
|
||||
```bash
|
||||
mvn -P integration verify
|
||||
mvn -pl cadworld-adminapi -am -Poss-integration verify
|
||||
```
|
||||
|
||||
可通过 `-Dcadworld.it.db-url=...`、`-Dcadworld.it.db-user=...`、`-Dcadworld.it.db-password=...` 覆盖配置。测试会重建专用数据库中的业务表,并拒绝使用其他数据库名称。
|
||||
|
||||
真实 OSS 测试使用独立 Spring 上下文,不加载数据库,只通过以下入口显式启用:
|
||||
|
||||
```bash
|
||||
# 先按启动说明加载 .env 中的 OSS 凭证。
|
||||
mvn -P oss-integration verify
|
||||
```
|
||||
|
||||
默认仅访问 `cadworld_dev/verification/<本次UUID>/`,可通过 `-Dcadworld.it.oss-root-prefix=...` 设置其他测试根目录;禁止使用默认生产目录 `cadworld`。测试验证上传、元数据、下载、未知长度超限保护及删除,仅清理本次创建的对象,不创建或删除存储桶。
|
||||
|
||||
若真实测试清理失败,未清理对象键会记录到 `cadworld-adminapi/logs/oss-verification-pending/`,供后续清理且不会被 `mvn clean` 删除。删除返回 `AccessDenied` 时,请检查当前凭证是否具有该目录的 `oss:DeleteObject` 权限,以及桶策略或保留策略是否限制删除;补齐权限后按记录清理。
|
||||
该测试默认写入 `cadworld_dev/verification/{UUID}` 目录,完成后清理测试对象;可通过 `-Dcadworld.it.oss-root-prefix=测试根目录` 覆盖根目录,默认生产目录被禁止使用。清理失败时保留准确对象键记录,常规测试和打包不执行它。
|
||||
|
||||
+358
-3121
File diff suppressed because it is too large
Load Diff
@@ -42,13 +42,6 @@
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>scripts</directory>
|
||||
<targetPath>scripts</targetPath>
|
||||
<includes>
|
||||
<include>step_brep_topology.py</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@@ -59,25 +52,6 @@
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/OssObjectStorageIT.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
<cadworld.project-root>${maven.multiModuleProjectDirectory}</cadworld.project-root>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>oss-integration</id>
|
||||
<build>
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
cadquery-ocp==7.8.1.1
|
||||
@@ -1,555 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract auditable STEP B-Rep topology and a display-only triangulation.
|
||||
|
||||
The JSON keeps exact OCCT Face/Wire/Edge identities and analytic curve parameters.
|
||||
Triangle data and sampled edge points are emitted only for Three.js display/picking.
|
||||
They are never used as the source of saved interface geometry.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from OCP.Bnd import Bnd_Box
|
||||
from OCP.BRep import BRep_Tool
|
||||
from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface
|
||||
from OCP.BRepBndLib import BRepBndLib
|
||||
from OCP.BRepGProp import BRepGProp
|
||||
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
||||
from OCP.BRepTools import BRepTools, BRepTools_WireExplorer
|
||||
from OCP.GProp import GProp_GProps
|
||||
from OCP.GeomAbs import (
|
||||
GeomAbs_BSplineCurve,
|
||||
GeomAbs_BSplineSurface,
|
||||
GeomAbs_BezierCurve,
|
||||
GeomAbs_BezierSurface,
|
||||
GeomAbs_Circle,
|
||||
GeomAbs_Cone,
|
||||
GeomAbs_Cylinder,
|
||||
GeomAbs_Ellipse,
|
||||
GeomAbs_Hyperbola,
|
||||
GeomAbs_Line,
|
||||
GeomAbs_OffsetCurve,
|
||||
GeomAbs_OffsetSurface,
|
||||
GeomAbs_OtherCurve,
|
||||
GeomAbs_OtherSurface,
|
||||
GeomAbs_Parabola,
|
||||
GeomAbs_Plane,
|
||||
GeomAbs_Sphere,
|
||||
GeomAbs_SurfaceOfExtrusion,
|
||||
GeomAbs_SurfaceOfRevolution,
|
||||
GeomAbs_Torus,
|
||||
)
|
||||
from OCP.IFSelect import IFSelect_RetDone
|
||||
from OCP.Interface import Interface_Static
|
||||
from OCP.STEPControl import STEPControl_Reader
|
||||
from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE, TopAbs_REVERSED
|
||||
from OCP.TopExp import TopExp
|
||||
from OCP.TopLoc import TopLoc_Location
|
||||
from OCP.TopTools import TopTools_IndexedMapOfShape
|
||||
from OCP.TopoDS import TopoDS
|
||||
|
||||
|
||||
CURVE_TYPES = {
|
||||
GeomAbs_Line: "line",
|
||||
GeomAbs_Circle: "circle",
|
||||
GeomAbs_Ellipse: "ellipse",
|
||||
GeomAbs_Hyperbola: "hyperbola",
|
||||
GeomAbs_Parabola: "parabola",
|
||||
GeomAbs_BezierCurve: "bezier",
|
||||
GeomAbs_BSplineCurve: "bspline",
|
||||
GeomAbs_OffsetCurve: "offset",
|
||||
GeomAbs_OtherCurve: "other",
|
||||
}
|
||||
|
||||
SURFACE_TYPES = {
|
||||
GeomAbs_Plane: "plane",
|
||||
GeomAbs_Cylinder: "cylinder",
|
||||
GeomAbs_Cone: "cone",
|
||||
GeomAbs_Sphere: "sphere",
|
||||
GeomAbs_Torus: "torus",
|
||||
GeomAbs_BezierSurface: "bezier",
|
||||
GeomAbs_BSplineSurface: "bspline",
|
||||
GeomAbs_SurfaceOfRevolution: "revolution",
|
||||
GeomAbs_SurfaceOfExtrusion: "extrusion",
|
||||
GeomAbs_OffsetSurface: "offset",
|
||||
GeomAbs_OtherSurface: "other",
|
||||
}
|
||||
|
||||
|
||||
def xyz(point: Any) -> list[float]:
|
||||
return [float(point.X()), float(point.Y()), float(point.Z())]
|
||||
|
||||
|
||||
def direction_xyz(direction: Any, reverse: bool = False) -> list[float]:
|
||||
sign = -1.0 if reverse else 1.0
|
||||
return [sign * float(direction.X()), sign * float(direction.Y()), sign * float(direction.Z())]
|
||||
|
||||
|
||||
def distance(first: list[float], second: list[float]) -> float:
|
||||
return math.sqrt(sum((a - b) ** 2 for a, b in zip(first, second)))
|
||||
|
||||
|
||||
def dot(first: list[float], second: list[float]) -> float:
|
||||
return sum(a * b for a, b in zip(first, second))
|
||||
|
||||
|
||||
def normalized(vector: list[float]) -> list[float]:
|
||||
length = math.sqrt(dot(vector, vector))
|
||||
return [value / length for value in vector] if length > 1e-12 else [0.0, 0.0, 0.0]
|
||||
|
||||
|
||||
def cross(first: list[float], second: list[float]) -> list[float]:
|
||||
return [
|
||||
first[1] * second[2] - first[2] * second[1],
|
||||
first[2] * second[0] - first[0] * second[2],
|
||||
first[0] * second[1] - first[1] * second[0],
|
||||
]
|
||||
|
||||
|
||||
def solve_three_by_three(matrix: list[list[float]], values: list[float]) -> list[float] | None:
|
||||
augmented = [row[:] + [value] for row, value in zip(matrix, values)]
|
||||
for column in range(3):
|
||||
pivot = max(range(column, 3), key=lambda row: abs(augmented[row][column]))
|
||||
if abs(augmented[pivot][column]) < 1e-12:
|
||||
return None
|
||||
augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
|
||||
divisor = augmented[column][column]
|
||||
augmented[column] = [value / divisor for value in augmented[column]]
|
||||
for row in range(3):
|
||||
if row == column:
|
||||
continue
|
||||
factor = augmented[row][column]
|
||||
augmented[row] = [
|
||||
current - factor * pivot_value
|
||||
for current, pivot_value in zip(augmented[row], augmented[column])
|
||||
]
|
||||
return [augmented[row][3] for row in range(3)]
|
||||
|
||||
|
||||
def source_hash(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def shape_diagonal_mm(shape: Any) -> float:
|
||||
box = Bnd_Box()
|
||||
BRepBndLib.Add_s(shape, box, True)
|
||||
if box.IsVoid():
|
||||
return 100.0
|
||||
xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
|
||||
return math.sqrt((xmax - xmin) ** 2 + (ymax - ymin) ** 2 + (zmax - zmin) ** 2)
|
||||
|
||||
|
||||
def sample_curve(curve: BRepAdaptor_Curve, reversed_edge: bool) -> list[list[float]]:
|
||||
first = float(curve.FirstParameter())
|
||||
last = float(curve.LastParameter())
|
||||
curve_type = curve.GetType()
|
||||
if not math.isfinite(first) or not math.isfinite(last):
|
||||
return []
|
||||
if curve_type == GeomAbs_Line:
|
||||
count = 2
|
||||
elif curve_type in (GeomAbs_Circle, GeomAbs_Ellipse):
|
||||
count = max(12, min(64, int(math.ceil(abs(last - first) / (math.pi / 24.0))) + 1))
|
||||
else:
|
||||
count = 32
|
||||
points = [xyz(curve.Value(first + (last - first) * index / (count - 1))) for index in range(count)]
|
||||
return list(reversed(points)) if reversed_edge else points
|
||||
|
||||
|
||||
def edge_payload(edge: Any, edge_index: int, file_hash: str) -> dict[str, Any]:
|
||||
curve = BRepAdaptor_Curve(edge)
|
||||
curve_type = CURVE_TYPES.get(curve.GetType(), "other")
|
||||
reversed_edge = edge.Orientation() == TopAbs_REVERSED
|
||||
samples = sample_curve(curve, reversed_edge)
|
||||
payload: dict[str, Any] = {
|
||||
"id": f"brep:edge:{edge_index}",
|
||||
"sourceRef": f"sha256:{file_hash}:edge:{edge_index}",
|
||||
"curveType": curve_type,
|
||||
"orientation": "reversed" if reversed_edge else "forward",
|
||||
"firstParameter": float(curve.FirstParameter()),
|
||||
"lastParameter": float(curve.LastParameter()),
|
||||
"startMm": samples[0] if samples else None,
|
||||
"endMm": samples[-1] if samples else None,
|
||||
"samplesMm": samples,
|
||||
"isExact": True,
|
||||
# Any native STEP edge with a usable sampled trace can define the
|
||||
# outer wire. Analytic line/circle parameters are preferred when
|
||||
# available, while B-Spline/Bezier/ellipse edges retain their exact
|
||||
# sourceRef plus display samples instead of being rejected by type.
|
||||
"selectableAsBoundary": len(samples) >= 2,
|
||||
}
|
||||
if curve_type == "line":
|
||||
line = curve.Line()
|
||||
payload["direction"] = direction_xyz(line.Direction(), reversed_edge)
|
||||
elif curve_type == "circle":
|
||||
circle = curve.Circle()
|
||||
payload.update({
|
||||
"centerMm": xyz(circle.Location()),
|
||||
"radiusMm": float(circle.Radius()),
|
||||
"axis": direction_xyz(circle.Axis().Direction()),
|
||||
"xDirection": direction_xyz(circle.Position().XDirection()),
|
||||
"isFullCircle": abs(abs(float(curve.LastParameter()) - float(curve.FirstParameter())) - math.tau) <= 1e-6,
|
||||
})
|
||||
elif curve_type == "ellipse":
|
||||
ellipse = curve.Ellipse()
|
||||
payload.update({
|
||||
"centerMm": xyz(ellipse.Location()),
|
||||
"majorRadiusMm": float(ellipse.MajorRadius()),
|
||||
"minorRadiusMm": float(ellipse.MinorRadius()),
|
||||
"axis": direction_xyz(ellipse.Axis().Direction()),
|
||||
})
|
||||
return payload
|
||||
|
||||
|
||||
def fitted_circular_wire_payload(
|
||||
edges: list[dict[str, Any]],
|
||||
face_normal: list[float] | None,
|
||||
) -> dict[str, Any]:
|
||||
if face_normal is None:
|
||||
return {"isCircular": False}
|
||||
points: list[list[float]] = []
|
||||
for edge in edges:
|
||||
for point in edge.get("samplesMm", []):
|
||||
if not points or distance(points[-1], point) > 1e-8:
|
||||
points.append(point)
|
||||
if len(points) < 8:
|
||||
return {"isCircular": False}
|
||||
closure_tolerance_mm = 0.01
|
||||
if distance(points[0], points[-1]) > closure_tolerance_mm:
|
||||
return {"isCircular": False}
|
||||
if distance(points[0], points[-1]) <= 1e-8:
|
||||
points.pop()
|
||||
|
||||
normal = normalized(face_normal)
|
||||
if dot(normal, normal) < 0.99:
|
||||
return {"isCircular": False}
|
||||
reference_axes = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
|
||||
reference = min(reference_axes, key=lambda axis: abs(dot(axis, normal)))
|
||||
x_axis = normalized(cross(normal, reference))
|
||||
y_axis = normalized(cross(normal, x_axis))
|
||||
origin = [sum(point[index] for point in points) / len(points) for index in range(3)]
|
||||
projected = []
|
||||
plane_residuals = []
|
||||
for point in points:
|
||||
offset = [point[index] - origin[index] for index in range(3)]
|
||||
projected.append([dot(offset, x_axis), dot(offset, y_axis)])
|
||||
plane_residuals.append(abs(dot(offset, normal)))
|
||||
|
||||
normal_matrix = [[0.0] * 3 for _ in range(3)]
|
||||
normal_values = [0.0] * 3
|
||||
for x_value, y_value in projected:
|
||||
row = [2.0 * x_value, 2.0 * y_value, 1.0]
|
||||
target = x_value * x_value + y_value * y_value
|
||||
for row_index in range(3):
|
||||
normal_values[row_index] += row[row_index] * target
|
||||
for column_index in range(3):
|
||||
normal_matrix[row_index][column_index] += row[row_index] * row[column_index]
|
||||
solution = solve_three_by_three(normal_matrix, normal_values)
|
||||
if solution is None:
|
||||
return {"isCircular": False}
|
||||
center_x, center_y, constant = solution
|
||||
radius_squared = constant + center_x * center_x + center_y * center_y
|
||||
if radius_squared <= 1e-12:
|
||||
return {"isCircular": False}
|
||||
radius = math.sqrt(radius_squared)
|
||||
radial_residuals = [
|
||||
abs(math.hypot(x_value - center_x, y_value - center_y) - radius)
|
||||
for x_value, y_value in projected
|
||||
]
|
||||
max_residual = max(max(radial_residuals), max(plane_residuals))
|
||||
circularity_tolerance_mm = max(0.005, radius * 0.0005)
|
||||
if max_residual > circularity_tolerance_mm:
|
||||
return {
|
||||
"isCircular": False,
|
||||
"fitResidualMm": max_residual,
|
||||
}
|
||||
|
||||
radial_vectors = [(x_value - center_x, y_value - center_y) for x_value, y_value in projected]
|
||||
sweep = 0.0
|
||||
for index, current in enumerate(radial_vectors):
|
||||
following = radial_vectors[(index + 1) % len(radial_vectors)]
|
||||
cross_value = current[0] * following[1] - current[1] * following[0]
|
||||
dot_value = current[0] * following[0] + current[1] * following[1]
|
||||
sweep += abs(math.atan2(cross_value, dot_value))
|
||||
if abs(sweep - math.tau) > 0.05:
|
||||
return {"isCircular": False, "fitResidualMm": max_residual}
|
||||
|
||||
center = [
|
||||
origin[index] + x_axis[index] * center_x + y_axis[index] * center_y
|
||||
for index in range(3)
|
||||
]
|
||||
return {
|
||||
"isCircular": True,
|
||||
"centerMm": center,
|
||||
"radiusMm": radius,
|
||||
"axis": normal,
|
||||
"fitResidualMm": max_residual,
|
||||
"circularityMethod": "verified-fit",
|
||||
}
|
||||
|
||||
|
||||
def circular_wire_payload(
|
||||
edges: list[dict[str, Any]],
|
||||
face_normal: list[float] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if edges and all(edge["curveType"] == "circle" for edge in edges):
|
||||
first = edges[0]
|
||||
center = first.get("centerMm")
|
||||
radius = first.get("radiusMm")
|
||||
axis = normalized(first.get("axis", [0.0, 0.0, 0.0]))
|
||||
if center is not None and radius is not None:
|
||||
same_circle = all(
|
||||
distance(center, edge.get("centerMm", [math.inf] * 3)) <= 1e-5
|
||||
and abs(radius - float(edge.get("radiusMm", math.inf))) <= 1e-6
|
||||
and abs(dot(axis, normalized(edge.get("axis", [0.0, 0.0, 0.0])))) >= 1.0 - 1e-8
|
||||
for edge in edges[1:]
|
||||
)
|
||||
sweep = sum(abs(float(edge["lastParameter"]) - float(edge["firstParameter"])) for edge in edges)
|
||||
if same_circle and abs(sweep - math.tau) <= 1e-5:
|
||||
return {
|
||||
"isCircular": True,
|
||||
"centerMm": center,
|
||||
"radiusMm": radius,
|
||||
"axis": axis,
|
||||
"fitResidualMm": 0.0,
|
||||
"circularityMethod": "analytic",
|
||||
}
|
||||
return fitted_circular_wire_payload(edges, face_normal)
|
||||
|
||||
|
||||
def face_triangulation(face: Any) -> dict[str, Any]:
|
||||
location = TopLoc_Location()
|
||||
triangulation = BRep_Tool.Triangulation_s(face, location)
|
||||
if triangulation is None or triangulation.NbTriangles() <= 0:
|
||||
return {"positionsMm": [], "indices": []}
|
||||
transformation = location.Transformation()
|
||||
used_nodes: dict[int, int] = {}
|
||||
positions: list[float] = []
|
||||
indices: list[int] = []
|
||||
reversed_face = face.Orientation() == TopAbs_REVERSED
|
||||
for triangle_index in range(1, triangulation.NbTriangles() + 1):
|
||||
nodes = list(triangulation.Triangle(triangle_index).Get())
|
||||
if reversed_face:
|
||||
nodes[1], nodes[2] = nodes[2], nodes[1]
|
||||
for node_index in nodes:
|
||||
local_index = used_nodes.get(node_index)
|
||||
if local_index is None:
|
||||
point = triangulation.Node(node_index).Transformed(transformation)
|
||||
local_index = len(positions) // 3
|
||||
used_nodes[node_index] = local_index
|
||||
positions.extend(xyz(point))
|
||||
indices.append(local_index)
|
||||
return {"positionsMm": positions, "indices": indices}
|
||||
|
||||
|
||||
def surface_payload(face: Any) -> tuple[str, dict[str, Any]]:
|
||||
adaptor = BRepAdaptor_Surface(face, True)
|
||||
surface_type = SURFACE_TYPES.get(adaptor.GetType(), "other")
|
||||
reversed_face = face.Orientation() == TopAbs_REVERSED
|
||||
payload: dict[str, Any] = {"surfaceType": surface_type, "isPlanar": surface_type == "plane"}
|
||||
if surface_type == "plane":
|
||||
plane = adaptor.Plane()
|
||||
payload.update({
|
||||
"normal": direction_xyz(plane.Axis().Direction(), reversed_face),
|
||||
"planeLocationMm": xyz(plane.Location()),
|
||||
"xDirection": direction_xyz(plane.Position().XDirection()),
|
||||
})
|
||||
elif surface_type == "cylinder":
|
||||
cylinder = adaptor.Cylinder()
|
||||
payload.update({
|
||||
"axis": direction_xyz(cylinder.Axis().Direction()),
|
||||
"axisLocationMm": xyz(cylinder.Location()),
|
||||
"radiusMm": float(cylinder.Radius()),
|
||||
})
|
||||
return surface_type, payload
|
||||
|
||||
|
||||
def default_display_deflection_mm(diagonal_mm: float) -> float:
|
||||
# Triangles are only used to render and pick the exact B-Rep faces. The
|
||||
# previous 0.05-0.5 mm range produced browser payloads above 100 MB for
|
||||
# otherwise valid components, without improving the saved interface data.
|
||||
return max(0.2, min(2.0, diagonal_mm * 0.002))
|
||||
|
||||
|
||||
def maximum_display_deflection_mm(initial_deflection_mm: float) -> float:
|
||||
# Keep an adaptive escape hatch for highly detailed components. Exact
|
||||
# Face/Wire/Edge data is unchanged; only the display mesh becomes coarser.
|
||||
return max(2.0, min(10.0, initial_deflection_mm * 10.0))
|
||||
|
||||
|
||||
def analyze(
|
||||
input_path: Path,
|
||||
linear_deflection_override_mm: float | None = None,
|
||||
simplification_passes: int = 0,
|
||||
) -> dict[str, Any]:
|
||||
file_hash = source_hash(input_path)
|
||||
Interface_Static.SetCVal_s("xstep.cascade.unit", "MM")
|
||||
reader = STEPControl_Reader()
|
||||
status = reader.ReadFile(str(input_path))
|
||||
if status != IFSelect_RetDone:
|
||||
raise RuntimeError(f"OCCT 无法读取 STEP 文件,状态:{status}")
|
||||
transferred = reader.TransferRoots()
|
||||
if transferred <= 0:
|
||||
raise RuntimeError("STEP 文件没有可转换的根装配或实体。")
|
||||
shape = reader.OneShape()
|
||||
if shape.IsNull():
|
||||
raise RuntimeError("STEP 文件转换后没有有效形状。")
|
||||
|
||||
diagonal_mm = shape_diagonal_mm(shape)
|
||||
linear_deflection_mm = (
|
||||
linear_deflection_override_mm
|
||||
if linear_deflection_override_mm is not None
|
||||
else default_display_deflection_mm(diagonal_mm)
|
||||
)
|
||||
BRepMesh_IncrementalMesh(shape, linear_deflection_mm, False, 0.5, True)
|
||||
|
||||
face_map = TopTools_IndexedMapOfShape()
|
||||
edge_map = TopTools_IndexedMapOfShape()
|
||||
TopExp.MapShapes_s(shape, TopAbs_FACE, face_map)
|
||||
TopExp.MapShapes_s(shape, TopAbs_EDGE, edge_map)
|
||||
|
||||
edge_cache: dict[int, dict[str, Any]] = {}
|
||||
edge_owners: dict[int, set[int]] = {}
|
||||
faces: list[dict[str, Any]] = []
|
||||
|
||||
for face_index in range(1, face_map.Extent() + 1):
|
||||
face = TopoDS.Face_s(face_map.FindKey(face_index))
|
||||
properties = GProp_GProps()
|
||||
BRepGProp.SurfaceProperties_s(face, properties)
|
||||
center_of_mass = xyz(properties.CentreOfMass())
|
||||
surface_type, surface = surface_payload(face)
|
||||
outer_wire = BRepTools.OuterWire_s(face)
|
||||
wires: list[dict[str, Any]] = []
|
||||
wire_explorer = BRepTools_WireExplorer(outer_wire, face) if not outer_wire.IsNull() else None
|
||||
|
||||
# Enumerate outer wire first so its role is deterministic, then all inner wires.
|
||||
ordered_wires: list[Any] = []
|
||||
if wire_explorer is not None:
|
||||
ordered_wires.append(outer_wire)
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopAbs import TopAbs_WIRE
|
||||
explorer = TopExp_Explorer(face, TopAbs_WIRE)
|
||||
while explorer.More():
|
||||
wire = TopoDS.Wire_s(explorer.Current())
|
||||
if outer_wire.IsNull() or not wire.IsSame(outer_wire):
|
||||
ordered_wires.append(wire)
|
||||
explorer.Next()
|
||||
|
||||
for wire_index, wire in enumerate(ordered_wires, start=1):
|
||||
is_outer = not outer_wire.IsNull() and wire.IsSame(outer_wire)
|
||||
wire_edges: list[dict[str, Any]] = []
|
||||
edge_explorer = BRepTools_WireExplorer(wire, face)
|
||||
while edge_explorer.More():
|
||||
edge = TopoDS.Edge_s(edge_explorer.Current())
|
||||
edge_index = edge_map.FindIndex(edge)
|
||||
if edge_index <= 0:
|
||||
edge_index = edge_map.Add(edge)
|
||||
if edge_index not in edge_cache:
|
||||
edge_cache[edge_index] = edge_payload(edge, edge_index, file_hash)
|
||||
wire_edges.append(dict(edge_cache[edge_index]))
|
||||
edge_owners.setdefault(edge_index, set()).add(face_index)
|
||||
edge_explorer.Next()
|
||||
circular = circular_wire_payload(wire_edges, surface.get("normal"))
|
||||
wires.append({
|
||||
"id": f"brep:face:{face_index}:wire:{wire_index}",
|
||||
"sourceRef": f"sha256:{file_hash}:face:{face_index}:wire:{wire_index}",
|
||||
"isOuter": is_outer,
|
||||
"isCircular": circular["isCircular"],
|
||||
"centerMm": circular.get("centerMm"),
|
||||
"radiusMm": circular.get("radiusMm"),
|
||||
"axis": circular.get("axis"),
|
||||
"fitResidualMm": circular.get("fitResidualMm"),
|
||||
"circularityMethod": circular.get("circularityMethod"),
|
||||
"edges": wire_edges,
|
||||
})
|
||||
|
||||
faces.append({
|
||||
"id": f"brep:face:{face_index}",
|
||||
"sourceRef": f"sha256:{file_hash}:face:{face_index}",
|
||||
**surface,
|
||||
"pointMm": center_of_mass,
|
||||
"areaMm2": float(properties.Mass()),
|
||||
"orientation": "reversed" if face.Orientation() == TopAbs_REVERSED else "forward",
|
||||
"adjacentFaceIds": [],
|
||||
"triangles": face_triangulation(face),
|
||||
"wires": wires,
|
||||
})
|
||||
|
||||
adjacent: dict[int, set[int]] = {index: set() for index in range(1, len(faces) + 1)}
|
||||
for owners in edge_owners.values():
|
||||
for owner in owners:
|
||||
adjacent[owner].update(other for other in owners if other != owner)
|
||||
for face_index, face in enumerate(faces, start=1):
|
||||
face["adjacentFaceIds"] = [f"brep:face:{index}" for index in sorted(adjacent[face_index])]
|
||||
|
||||
return {
|
||||
"schemaVersion": "interface-step-brep/v1",
|
||||
"sourceName": input_path.name,
|
||||
"sourceSha256": file_hash,
|
||||
"sourceUnits": "mm",
|
||||
"scaleToMeters": 0.001,
|
||||
"kernel": "OCCT 7.8",
|
||||
"triangulationPurpose": "display-and-picking-only",
|
||||
"linearDeflectionMm": linear_deflection_mm,
|
||||
"displayMeshSimplificationPasses": simplification_passes,
|
||||
"faceCount": len(faces),
|
||||
"edgeCount": edge_map.Extent(),
|
||||
"faces": faces,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("input", type=Path)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--max-output-bytes", type=int)
|
||||
args = parser.parse_args()
|
||||
if args.input.suffix.lower() not in (".step", ".stp"):
|
||||
raise ValueError("只支持 .step 或 .stp 文件。")
|
||||
input_path = args.input.resolve()
|
||||
result = analyze(input_path)
|
||||
serialized = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
# If a complex but valid component still exceeds the response budget,
|
||||
# remesh only the display/picking triangles at a coarser tolerance. The
|
||||
# authoritative analytic B-Rep metadata and source references stay intact.
|
||||
simplification_passes = 0
|
||||
max_deflection_mm = maximum_display_deflection_mm(result["linearDeflectionMm"])
|
||||
while (
|
||||
args.max_output_bytes is not None
|
||||
and len(serialized) > args.max_output_bytes
|
||||
and simplification_passes < 4
|
||||
and result["linearDeflectionMm"] < max_deflection_mm
|
||||
):
|
||||
simplification_passes += 1
|
||||
next_deflection_mm = min(max_deflection_mm, result["linearDeflectionMm"] * 2.0)
|
||||
result = analyze(input_path, next_deflection_mm, simplification_passes)
|
||||
serialized = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_bytes(serialized)
|
||||
print(json.dumps({
|
||||
"schemaVersion": result["schemaVersion"],
|
||||
"faceCount": result["faceCount"],
|
||||
"edgeCount": result["edgeCount"],
|
||||
"output": str(args.output),
|
||||
}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception as error:
|
||||
print(f"STEP_BREP_ERROR: {error}", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
@@ -1,47 +0,0 @@
|
||||
"""Exercise the actual OCCT reader and packaged-script CLI with generated STEP files."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox
|
||||
from OCP.IFSelect import IFSelect_RetDone
|
||||
from OCP.STEPControl import STEPControl_AsIs, STEPControl_Writer
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "step_brep_topology.py"
|
||||
|
||||
|
||||
class RealStepTest(unittest.TestCase):
|
||||
def test_real_box_has_exact_topology_units_and_hash(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source = Path(directory) / "box.step"
|
||||
output = Path(directory) / "topology.json"
|
||||
writer = STEPControl_Writer()
|
||||
writer.Transfer(BRepPrimAPI_MakeBox(10, 20, 30).Shape(), STEPControl_AsIs)
|
||||
self.assertEqual(writer.Write(str(source)), IFSelect_RetDone)
|
||||
process = subprocess.run([sys.executable, str(SCRIPT), str(source), "--output", str(output)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(process.returncode, 0, process.stderr)
|
||||
result = json.loads(output.read_text())
|
||||
self.assertEqual(result["faceCount"], 6)
|
||||
self.assertEqual(result["edgeCount"], 12)
|
||||
self.assertEqual(result["scaleToMeters"], 0.001)
|
||||
self.assertEqual(result["sourceSha256"], hashlib.sha256(source.read_bytes()).hexdigest())
|
||||
self.assertEqual(result["triangulationPurpose"], "display-and-picking-only")
|
||||
self.assertTrue(all(face["wires"] and face["sourceRef"].startswith("sha256:") for face in result["faces"]))
|
||||
|
||||
def test_invalid_step_is_rejected_without_a_topology_file(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source = Path(directory) / "invalid.step"
|
||||
output = Path(directory) / "topology.json"
|
||||
source.write_text("not a STEP document")
|
||||
process = subprocess.run([sys.executable, str(SCRIPT), str(source), "--output", str(output)], capture_output=True, text=True, timeout=30)
|
||||
self.assertNotEqual(process.returncode, 0)
|
||||
self.assertIn("STEP_BREP_ERROR", process.stderr)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,88 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import math
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
SCRIPT_PATH = Path(__file__).resolve().parents[1] / "step_brep_topology.py"
|
||||
SPEC = importlib.util.spec_from_file_location("step_brep_topology", SCRIPT_PATH)
|
||||
if SPEC is None or SPEC.loader is None:
|
||||
raise RuntimeError(f"无法加载 STEP B-Rep 解析脚本:{SCRIPT_PATH}")
|
||||
STEP_BREP = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(STEP_BREP)
|
||||
|
||||
|
||||
def sampled_edge(points: list[list[float]]) -> dict[str, object]:
|
||||
return {
|
||||
"curveType": "bspline",
|
||||
"samplesMm": points,
|
||||
}
|
||||
|
||||
|
||||
class FittedCircularWireTest(unittest.TestCase):
|
||||
def test_accepts_closed_planar_bspline_circle(self) -> None:
|
||||
center = [12.5, -3.25, 7.0]
|
||||
radius = 2.5
|
||||
points = [
|
||||
[
|
||||
center[0] + radius * math.cos(math.tau * index / 64),
|
||||
center[1] + radius * math.sin(math.tau * index / 64),
|
||||
center[2],
|
||||
]
|
||||
for index in range(65)
|
||||
]
|
||||
|
||||
result = STEP_BREP.circular_wire_payload([sampled_edge(points)], [0.0, 0.0, 1.0])
|
||||
|
||||
self.assertTrue(result["isCircular"])
|
||||
self.assertEqual(result["circularityMethod"], "verified-fit")
|
||||
self.assertAlmostEqual(result["radiusMm"], radius, places=6)
|
||||
self.assertLess(result["fitResidualMm"], 1e-6)
|
||||
|
||||
def test_rejects_closed_ellipse(self) -> None:
|
||||
points = [
|
||||
[4.0 * math.cos(math.tau * index / 64), 2.0 * math.sin(math.tau * index / 64), 0.0]
|
||||
for index in range(65)
|
||||
]
|
||||
|
||||
result = STEP_BREP.circular_wire_payload([sampled_edge(points)], [0.0, 0.0, 1.0])
|
||||
|
||||
self.assertFalse(result["isCircular"])
|
||||
|
||||
def test_rejects_open_circular_arc(self) -> None:
|
||||
points = [
|
||||
[2.5 * math.cos(math.pi * index / 32), 2.5 * math.sin(math.pi * index / 32), 0.0]
|
||||
for index in range(33)
|
||||
]
|
||||
|
||||
result = STEP_BREP.circular_wire_payload([sampled_edge(points)], [0.0, 0.0, 1.0])
|
||||
|
||||
self.assertFalse(result["isCircular"])
|
||||
|
||||
|
||||
class InterfaceStepRegressionTest(unittest.TestCase):
|
||||
def test_primary_mounting_face_exposes_nine_bspline_holes(self) -> None:
|
||||
project_root = Path(__file__).resolve().parents[3]
|
||||
fixture = project_root / "模型文件" / "step" / (
|
||||
"未命名-_X2_817090e888c5914d_X0_dm-j10010l_X2_7535673a8f6c5b50_X0_001.step"
|
||||
)
|
||||
if not fixture.is_file():
|
||||
self.skipTest(f"STEP 回归样例不存在:{fixture}")
|
||||
|
||||
topology = STEP_BREP.analyze(fixture)
|
||||
face = next(item for item in topology["faces"] if item["id"] == "brep:face:7")
|
||||
holes = [wire for wire in face["wires"] if not wire["isOuter"] and wire["isCircular"]]
|
||||
|
||||
self.assertEqual(len(holes), 9)
|
||||
for hole in holes:
|
||||
self.assertEqual(hole["circularityMethod"], "verified-fit")
|
||||
self.assertAlmostEqual(hole["radiusMm"], 2.50005, places=4)
|
||||
self.assertLessEqual(hole["fitResidualMm"], 0.005)
|
||||
self.assertTrue(hole["sourceRef"].startswith("sha256:"))
|
||||
self.assertTrue(hole["edges"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -10,4 +10,5 @@ import java.lang.annotation.Target;
|
||||
public @interface AuditOperation {
|
||||
String module();
|
||||
String action();
|
||||
String targetType() default "";
|
||||
}
|
||||
|
||||
+9
-22
@@ -1,13 +1,7 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiCode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
@@ -17,7 +11,7 @@ import org.springframework.http.server.ServletServerHttpRequest;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
/** Only reads known identifiers from responses; tokens and request bodies are never retained. */
|
||||
/** 只读取通用响应结果,目标快照由业务上下文提供,不读取表单或上传签名。 */
|
||||
@RestControllerAdvice
|
||||
public class AuditResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||
@Override
|
||||
@@ -25,21 +19,14 @@ public class AuditResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||
|
||||
@Override
|
||||
public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType type,
|
||||
Class<? extends HttpMessageConverter<?>> converter, ServerHttpRequest request, ServerHttpResponse response) {
|
||||
Class<? extends HttpMessageConverter<?>> converter,
|
||||
ServerHttpRequest request, ServerHttpResponse response) {
|
||||
if (request instanceof ServletServerHttpRequest servlet && body instanceof ApiResponse<?> envelope
|
||||
&& servlet.getServletRequest().getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
|
||||
Object data = envelope.getData();
|
||||
String id = switch (data) {
|
||||
case ComponentResponse component -> String.valueOf(component.id());
|
||||
case JsonNode json when json.hasNonNull("id") -> json.get("id").asText();
|
||||
case PrepareCoverImageUploadSessionResponse session -> session.keyPrefix();
|
||||
case PrepareUrdfUploadSessionResponse session -> session.keyPrefix();
|
||||
case PrepareObjectUploadUrlResponse upload -> upload.objectKey();
|
||||
case CompleteCoverImageUploadResponse upload -> upload.coverImageKey();
|
||||
case CompleteUrdfUploadResponse upload -> upload.source();
|
||||
case null, default -> null;
|
||||
};
|
||||
if (id != null && context.event().getTargetId() == null) context.event().setTargetId(OperationAuditInterceptor.limit(id, 512));
|
||||
&& !ApiCode.OK.equals(envelope.getCode())
|
||||
&& servlet.getServletRequest().getAttribute(OperationAuditInterceptor.CONTEXT)
|
||||
instanceof OperationAuditInterceptor.Context context) {
|
||||
context.event().setErrorCode(OperationAuditInterceptor.limit(envelope.getCode(), 64));
|
||||
context.event().setErrorSummary(OperationAuditInterceptor.limit(envelope.getMessage(), 1000));
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
+4
-1
@@ -1,5 +1,6 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@@ -51,7 +52,8 @@ public class EarlyFailureAuditFilter extends OncePerRequestFilter {
|
||||
}
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
log.error("Failed to resolve early operation failure at {} {}", request.getMethod(), request.getRequestURI(), failure);
|
||||
log.error("早期审计失败 method={} requestId={} exceptionType={}",
|
||||
request.getMethod(), RequestIdHolder.get(), failure.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,6 +75,7 @@ public class EarlyFailureAuditFilter extends OncePerRequestFilter {
|
||||
}
|
||||
}
|
||||
if (bestPattern != null) {
|
||||
request.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, bestPattern);
|
||||
var match = bestPattern.matchAndExtract(ServletRequestPathUtils.getParsedRequestPath(request).pathWithinApplication());
|
||||
if (match != null) request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, match.getUriVariables());
|
||||
}
|
||||
|
||||
+35
-19
@@ -1,5 +1,6 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.OperationTargetHolder;
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import com.linkerbot.cadworld.entity.OperationLog;
|
||||
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||
@@ -29,21 +30,22 @@ public class OperationAuditInterceptor implements HandlerInterceptor {
|
||||
if (!(handler instanceof HandlerMethod method)) return true;
|
||||
AuditOperation annotation = method.getMethodAnnotation(AuditOperation.class);
|
||||
if (annotation == null) return true;
|
||||
OperationTargetHolder.clear();
|
||||
OperationLog event = new OperationLog();
|
||||
event.setModule(annotation.module());
|
||||
event.setAction(annotation.action());
|
||||
event.setTargetType(annotation.targetType());
|
||||
event.setOperatorId(operator.userId());
|
||||
event.setOperatorName(operator.name());
|
||||
event.setRequestPath(limit(request.getRequestURI(), 512));
|
||||
event.setRequestMethod(request.getMethod());
|
||||
event.setOperatorName(limit(operator.name(), 128));
|
||||
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
event.setRequestPath(limit(pattern == null ? "<unmatched>" : pattern.toString(), 512));
|
||||
event.setRequestMethod(limit(request.getMethod(), 16));
|
||||
event.setClientIp(limit(request.getRemoteAddr(), 64));
|
||||
event.setRequestId(limit(RequestIdHolder.get(), 64));
|
||||
event.setOperatedAt(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
|
||||
Object variables = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
||||
if (variables instanceof Map<?, ?> values && values.get("id") != null) {
|
||||
event.setTargetId(limit(values.get("id").toString(), 512));
|
||||
} else if ("UPLOAD".equals(annotation.action())) {
|
||||
event.setTargetId(limit(request.getParameter("objectKey"), 512));
|
||||
event.setTargetId(limit(values.get("id").toString(), 128));
|
||||
}
|
||||
request.setAttribute(CONTEXT, new Context(event, System.nanoTime()));
|
||||
return true;
|
||||
@@ -52,24 +54,38 @@ public class OperationAuditInterceptor implements HandlerInterceptor {
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
|
||||
if (!(request.getAttribute(CONTEXT) instanceof Context context)) return;
|
||||
OperationLog event = context.event();
|
||||
Object error = request.getAttribute("cadworld.operationError");
|
||||
boolean success = response.getStatus() < 400 && exception == null && error == null;
|
||||
event.setSuccess(success);
|
||||
event.setHttpStatus(response.getStatus());
|
||||
event.setDurationMs((System.nanoTime() - context.started()) / 1_000_000);
|
||||
if (!success) event.setErrorSummary(limit(error == null ? "请求失败,HTTP " + response.getStatus() : error.toString(), 1000));
|
||||
try {
|
||||
service.record(event);
|
||||
} catch (Exception failure) {
|
||||
log.error("Failed to persist operation log. requestId={}, module={}, action={}",
|
||||
event.getRequestId(), event.getModule(), event.getAction(), failure);
|
||||
OperationLog event = context.event();
|
||||
var target = OperationTargetHolder.get();
|
||||
if (target != null) {
|
||||
event.setTargetType(limit(target.type(), 64));
|
||||
event.setTargetId(limit(target.id(), 128));
|
||||
event.setTargetCode(limit(target.code(), 128));
|
||||
event.setTargetName(limit(target.name(), 256));
|
||||
}
|
||||
Object error = request.getAttribute("cadworld.operationError");
|
||||
boolean success = response.getStatus() < 400 && exception == null && error == null && event.getErrorCode().isEmpty();
|
||||
event.setSuccess(success);
|
||||
event.setHttpStatus(response.getStatus());
|
||||
event.setDurationMs((System.nanoTime() - context.started()) / 1_000_000);
|
||||
if (!success && event.getErrorSummary().isEmpty()) {
|
||||
event.setErrorCode(exception == null ? "HTTP_" + response.getStatus() : "INTERNAL_ERROR");
|
||||
event.setErrorSummary("请求失败,请根据请求编号查询运行日志");
|
||||
}
|
||||
try {
|
||||
service.record(event);
|
||||
} catch (Exception failure) {
|
||||
// 数据库异常原文可能包含SQL参数,只记录定位字段和异常类型。
|
||||
log.error("操作日志写入失败 requestId={} module={} action={} exceptionType={}",
|
||||
event.getRequestId(), event.getModule(), event.getAction(), failure.getClass().getSimpleName());
|
||||
}
|
||||
} finally {
|
||||
OperationTargetHolder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
static String limit(String value, int length) {
|
||||
return value == null ? null : value.substring(0, Math.min(length, value.length()));
|
||||
return value == null ? "" : value.substring(0, Math.min(length, value.length()));
|
||||
}
|
||||
|
||||
record Context(OperationLog event, long started) { }
|
||||
}
|
||||
|
||||
+2
-33
@@ -1,11 +1,7 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
@@ -15,11 +11,7 @@ import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
@@ -27,36 +19,13 @@ import org.springframework.web.util.UriUtils;
|
||||
@RequestMapping("/admin-api/component-assets")
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentAssetController {
|
||||
|
||||
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
|
||||
|
||||
private static final String ASSET_PATH_PREFIX = "/admin-api/component-assets/";
|
||||
|
||||
private final ComponentUploadSupport componentUploadSupport;
|
||||
private final ObjectStorageClient objectStorageClient;
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "UPLOAD")
|
||||
@ApiRequestLog("上传组件资源文件")
|
||||
@PutMapping("/upload")
|
||||
@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(),
|
||||
request.getContentLengthLong()
|
||||
);
|
||||
}
|
||||
|
||||
@ApiRequestLog("下载组件资源文件")
|
||||
@GetMapping("/**")
|
||||
// 对象键至少包含环境根目录和文件名两段路径。
|
||||
@GetMapping("/*/*/**")
|
||||
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
String requestUri = request.getRequestURI();
|
||||
int prefixIndex = requestUri.indexOf(ASSET_PATH_PREFIX);
|
||||
|
||||
+19
-103
@@ -1,146 +1,62 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
|
||||
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.component.CompleteCoverImageUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentListItemResponse;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
|
||||
import com.linkerbot.cadworld.service.ComponentCoverImageUploadService;
|
||||
import com.linkerbot.cadworld.dto.component.*;
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||
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;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/components")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class ComponentController {
|
||||
|
||||
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
|
||||
|
||||
private final AdminOperatorProvider operatorProvider;
|
||||
private final ComponentService componentService;
|
||||
private final ComponentCoverImageUploadService componentCoverImageUploadService;
|
||||
private final ComponentUrdfUploadService componentUrdfUploadService;
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "CREATE")
|
||||
@AuditOperation(module = "COMPONENT", action = "CREATE", targetType = "COMPONENT")
|
||||
@ApiRequestLog("新增组件")
|
||||
@PostMapping
|
||||
public ApiResponse<ComponentResponse> create(
|
||||
@Valid @RequestBody CreateComponentRequest request
|
||||
) {
|
||||
public ApiResponse<ComponentResponse> create(@Valid @RequestBody CreateComponentRequest request) {
|
||||
return ApiResponse.success(componentService.createComponent(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD")
|
||||
@ApiRequestLog("创建封面上传会话")
|
||||
@PostMapping("/cover-image-upload-sessions")
|
||||
public ApiResponse<PrepareCoverImageUploadSessionResponse> prepareCoverImageUploadSession(
|
||||
) {
|
||||
return ApiResponse.success(componentCoverImageUploadService.prepareUploadSession(operatorProvider.userId()));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL")
|
||||
@ApiRequestLog("获取封面上传地址")
|
||||
@PostMapping("/cover-image-upload-sessions/upload-url")
|
||||
public ApiResponse<PrepareObjectUploadUrlResponse> prepareCoverImageObjectUploadUrl(
|
||||
@Valid @RequestBody PrepareObjectUploadUrlRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentCoverImageUploadService.prepareObjectUploadUrl(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD")
|
||||
@ApiRequestLog("完成封面上传")
|
||||
@PostMapping("/cover-image-upload-sessions/complete")
|
||||
public ApiResponse<CompleteCoverImageUploadResponse> completeCoverImageUploadSession(
|
||||
@Valid @RequestBody CompleteCoverImageUploadRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentCoverImageUploadService.completeUploadSession(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD")
|
||||
@ApiRequestLog("创建模型上传会话")
|
||||
@PostMapping("/urdf-upload-sessions")
|
||||
public ApiResponse<PrepareUrdfUploadSessionResponse> prepareUrdfUploadSession(
|
||||
) {
|
||||
return ApiResponse.success(componentUrdfUploadService.prepareUploadSession(operatorProvider.userId()));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL")
|
||||
@ApiRequestLog("获取模型上传地址")
|
||||
@PostMapping("/urdf-upload-sessions/upload-url")
|
||||
public ApiResponse<PrepareObjectUploadUrlResponse> prepareUrdfObjectUploadUrl(
|
||||
@Valid @RequestBody PrepareObjectUploadUrlRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentUrdfUploadService.prepareObjectUploadUrl(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD")
|
||||
@ApiRequestLog("完成模型上传")
|
||||
@PostMapping("/urdf-upload-sessions/complete")
|
||||
public ApiResponse<CompleteUrdfUploadResponse> completeUrdfUploadSession(
|
||||
@Valid @RequestBody CompleteUrdfUploadRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentUrdfUploadService.completeUploadSession(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@ApiRequestLog("查询组件列表")
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<ComponentListItemResponse>> list(
|
||||
@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));
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) String category) {
|
||||
return ApiResponse.success(componentService.listComponents(page, Math.min(size, 100), keyword, category));
|
||||
}
|
||||
|
||||
@ApiRequestLog("查询组件详情")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<ComponentResponse> detail(@PathVariable Long id) {
|
||||
@GetMapping("/{id:[0-9]+}")
|
||||
public ApiResponse<ComponentResponse> detail(@PathVariable @Min(1) Long id) {
|
||||
return ApiResponse.success(componentService.getComponent(id));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "UPDATE")
|
||||
@AuditOperation(module = "COMPONENT", action = "UPDATE", targetType = "COMPONENT")
|
||||
@ApiRequestLog("修改组件")
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<ComponentResponse> update(
|
||||
@PathVariable Long id,
|
||||
@Valid @RequestBody UpdateComponentRequest request
|
||||
) {
|
||||
@PutMapping("/{id:[0-9]+}")
|
||||
public ApiResponse<ComponentResponse> update(@PathVariable @Min(1) Long id,
|
||||
@Valid @RequestBody UpdateComponentRequest request) {
|
||||
return ApiResponse.success(componentService.updateComponent(operatorProvider.userId(), id, request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "DELETE")
|
||||
@AuditOperation(module = "COMPONENT", action = "DELETE", targetType = "COMPONENT")
|
||||
@ApiRequestLog("删除组件")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResponse<SuccessResponse> delete(
|
||||
@PathVariable Long id
|
||||
) {
|
||||
@DeleteMapping("/{id:[0-9]+}")
|
||||
public ApiResponse<SuccessResponse> delete(@PathVariable @Min(1) Long id) {
|
||||
componentService.deleteComponent(operatorProvider.userId(), id);
|
||||
return ApiResponse.success(SuccessResponse.ok());
|
||||
}
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.service.InterfaceBrepService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/interface-brep")
|
||||
@RequiredArgsConstructor
|
||||
public class InterfaceBrepController {
|
||||
private final InterfaceBrepService service;
|
||||
|
||||
@ApiRequestLog("解析 STEP 精确拓扑")
|
||||
@PostMapping(value = "/analyze", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ApiResponse<JsonNode> analyze(@RequestPart("file") MultipartFile file) {
|
||||
return ApiResponse.success(service.analyze(file));
|
||||
}
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
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 jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
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 InterfaceAssetService assets;
|
||||
|
||||
@ApiRequestLog("查询接口列表")
|
||||
@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));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "CREATE")
|
||||
@ApiRequestLog("新增接口定义")
|
||||
@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, @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());
|
||||
}
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "UPLOAD")
|
||||
@ApiRequestLog("上传接口源文件")
|
||||
@PostMapping(value = "/{id}/assets", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ApiResponse<String> uploadAsset(@PathVariable String id,
|
||||
@RequestParam @Min(1) int geometryRevision,
|
||||
@RequestPart("file") MultipartFile file) {
|
||||
return ApiResponse.success(assets.upload(id, geometryRevision, file));
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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
|
||||
@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);
|
||||
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 与端口定义不一致");
|
||||
}
|
||||
var definition = definitions.geometryDefinition(id, request.definitionRevision());
|
||||
return ApiResponse.success(solver.confirmPortPose(definition, request));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private String rootMessage(Throwable error) {
|
||||
Throwable current = error;
|
||||
while (current.getCause() != null) current = current.getCause();
|
||||
return current.getMessage() == null ? "字段格式错误" : current.getMessage();
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -29,9 +29,13 @@ public class OperationLogController {
|
||||
@RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) Boolean success,
|
||||
@RequestParam(required = false) Long operatorId,
|
||||
@RequestParam(required = false) String targetType,
|
||||
@RequestParam(required = false) String targetId,
|
||||
@RequestParam(required = false) String targetCode,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime from,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime to) {
|
||||
return ApiResponse.success(service.list(page, Math.min(size, 100), module, action, success, operatorId, from, to));
|
||||
return ApiResponse.success(service.list(page, Math.min(size, 100), module, action, success, operatorId, targetType, targetId, targetCode, keyword, from, to));
|
||||
}
|
||||
|
||||
@ApiRequestLog("查询操作日志详情")
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.dto.storage.UploadSignatureRequest;
|
||||
import com.linkerbot.cadworld.dto.storage.UploadSignatureResponse;
|
||||
import com.linkerbot.cadworld.logging.ApiRequestLog;
|
||||
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||
import com.linkerbot.cadworld.service.UploadSignatureService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/storage")
|
||||
@RequiredArgsConstructor
|
||||
public class StorageController {
|
||||
private final UploadSignatureService signatures;
|
||||
private final AdminOperatorProvider operatorProvider;
|
||||
|
||||
@ApiRequestLog("获取组件 OSS 上传签名")
|
||||
@PostMapping("/upload-signature")
|
||||
public ApiResponse<UploadSignatureResponse> sign(@Valid @RequestBody UploadSignatureRequest request) {
|
||||
return ApiResponse.success(signatures.sign(operatorProvider.userId(), request));
|
||||
}
|
||||
}
|
||||
@@ -44,23 +44,15 @@ app:
|
||||
secret: ${APP_UPLOAD_SESSION_SECRET:}
|
||||
storage:
|
||||
root-prefix: ${OSS_ROOT_PREFIX:cadworld}
|
||||
urdf-prefix: components/urdf
|
||||
cover-image-prefix: components/cover-images
|
||||
public-api-base-url: ${APP_STORAGE_PUBLIC_API_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}}
|
||||
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}/admin-api/component-assets}
|
||||
upload-session-ttl: PT30M
|
||||
upload-session-ttl: ${OSS_UPLOAD_SESSION_TTL:PT30M}
|
||||
upload-signature-ttl: ${OSS_UPLOAD_SIGNATURE_TTL:PT5M}
|
||||
max-upload-bytes: ${APP_STORAGE_MAX_UPLOAD_BYTES:104857600}
|
||||
oss:
|
||||
access-key-id: ${OSS_ACCESS_KEY_ID:}
|
||||
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
|
||||
region: ${OSS_REGION:oss-cn-beijing}
|
||||
bucket: ${OSS_BUCKET:linkerbot}
|
||||
interface-brep:
|
||||
python: ${APP_INTERFACE_BREP_PYTHON:python3}
|
||||
script: ${APP_INTERFACE_BREP_SCRIPT:classpath:scripts/step_brep_topology.py}
|
||||
timeout-seconds: ${APP_INTERFACE_BREP_TIMEOUT_SECONDS:120}
|
||||
max-upload-bytes: ${APP_INTERFACE_BREP_MAX_UPLOAD_BYTES:104857600}
|
||||
max-output-bytes: ${APP_INTERFACE_BREP_MAX_OUTPUT_BYTES:104857600}
|
||||
|
||||
logging:
|
||||
file:
|
||||
|
||||
@@ -2,11 +2,16 @@ package com.linkerbot.cadworld;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.common.api.OperationTargetHolder;
|
||||
import com.linkerbot.cadworld.entity.OperationLog;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
@@ -14,7 +19,7 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
@@ -22,9 +27,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:admin;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"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",
|
||||
"app.storage.root-prefix=cadworld_dev", "logging.file.path=target/test-logs"
|
||||
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa",
|
||||
"spring.datasource.password=", "spring.sql.init.mode=never",
|
||||
"app.storage.root-prefix=cadworld_dev", "app.storage.max-upload-bytes=1024",
|
||||
"app.upload-session.secret=test-upload-signing-key-32-bytes-long",
|
||||
"logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
@org.springframework.context.annotation.Import(InMemoryObjectStorageConfiguration.class)
|
||||
@@ -33,461 +40,410 @@ class AdminApiTest {
|
||||
@Autowired MockMvc mvc;
|
||||
@Autowired ObjectMapper json;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
@Autowired InMemoryObjectStorageConfiguration.InMemoryObjectStorageClient storage;
|
||||
@Autowired ComponentUploadSessionTokenProvider tokens;
|
||||
@Autowired OperationLogService logs;
|
||||
@Autowired TransactionTemplate transactions;
|
||||
@Autowired
|
||||
@org.springframework.beans.factory.annotation.Qualifier("requestMappingHandlerMapping")
|
||||
@Autowired @org.springframework.beans.factory.annotation.Qualifier("requestMappingHandlerMapping")
|
||||
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping mappings;
|
||||
|
||||
@Autowired InMemoryObjectStorageConfiguration.InMemoryObjectStorageClient memoryStorage;
|
||||
|
||||
@BeforeEach
|
||||
void clean() {
|
||||
memoryStorage.clear();
|
||||
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);
|
||||
storage.clear();
|
||||
for (String table : List.of("component", "sys_user", "sys_operation_log")) jdbc.update("DELETE FROM " + table);
|
||||
OperationTargetHolder.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneSignatureEndpointGeneratesCodeWithoutDatabaseRecordAndRenewsSameBatch() throws Exception {
|
||||
JsonNode first = sign(Map.of());
|
||||
assertThat(first.path("componentCode").asText()).matches("CW-[A-F0-9]{32}");
|
||||
String step = first.path("step").path("keyPrefix").asText();
|
||||
String urdf = first.path("urdf").path("keyPrefix").asText();
|
||||
assertThat(step).startsWith("cadworld_dev/components/" + first.path("componentCode").asText() + "/step/");
|
||||
assertThat(urdf).isEqualTo(step.replace("/step/", "/urdf/"));
|
||||
assertThat(first.path("step").path("uploadMethod").asText()).isEqualTo("POST");
|
||||
assertThat(Instant.parse(first.path("expiresAt").asText()))
|
||||
.isBefore(Instant.parse(first.path("sessionExpiresAt").asText()));
|
||||
JsonNode renewed = sign(Map.of("uploadSessionToken", first.path("uploadSessionToken").asText()));
|
||||
for (String field : List.of("componentCode", "uploadSessionToken", "sessionExpiresAt", "step", "urdf")) {
|
||||
// 内存签名的表单不含时间戳,两次续签授权内容相同。
|
||||
assertThat(renewed.get(field)).isEqualTo(first.get(field));
|
||||
}
|
||||
assertThat(count("component")).isZero();
|
||||
assertThat(count("sys_operation_log")).isZero();
|
||||
mvc.perform(post("/admin-api/storage/upload-signature").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(Map.of("componentId", 1, "uploadSessionToken",
|
||||
first.path("uploadSessionToken").asText())))).andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/storage/upload-signature").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"componentId\":999}")).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allManagementEndpointsHaveRuntimeLogDescriptions() {
|
||||
var handlers = mappings.getHandlerMethods().values().stream()
|
||||
.filter(handler -> handler.getBeanType().getPackageName()
|
||||
.equals("com.linkerbot.cadworld.controller"))
|
||||
.toList();
|
||||
assertThat(handlers).hasSize(29);
|
||||
for (var handler : handlers) {
|
||||
var description = handler.getMethodAnnotation(com.linkerbot.cadworld.logging.ApiRequestLog.class);
|
||||
assertThat(description).as(handler.toString()).isNotNull();
|
||||
assertThat(description.value()).isNotBlank();
|
||||
}
|
||||
void componentDefaultsSearchUrlsAndDuplicateNamesMatchNewSchema() throws Exception {
|
||||
Map<String,Object> body = uploaded();
|
||||
body.put("manufacturer", null);
|
||||
body.put("tags", List.of(" 安装板 ", "", "安装板", "轻量化"));
|
||||
body.put("basicFields", List.of(Map.of("name", " 额定电压 ", "value", "24V")));
|
||||
JsonNode created = create(body);
|
||||
assertThat(created.path("manufacturer").asText()).isEmpty();
|
||||
assertThat(created.path("massKg").decimalValue()).isZero();
|
||||
assertThat(created.path("lengthMm").decimalValue()).isZero();
|
||||
assertThat(created.path("parameterFields")).isEmpty();
|
||||
assertThat(created.path("tags").toString()).isEqualTo("[\"安装板\",\"轻量化\"]");
|
||||
assertThat(created.path("basicFields").get(0).path("name").asText()).isEqualTo("额定电压");
|
||||
assertThat(created.path("version").asLong()).isEqualTo(1);
|
||||
assertThat(created.path("urdfBaseUrl").asText()).endsWith("/");
|
||||
assertThat(created.path("stepUrl").asText()).contains("model%20one.STEP");
|
||||
assertThat(created.path("urdfFiles").get(1).path("relativePath").asText()).isEqualTo("meshes/base.stl");
|
||||
assertThat(created.path("urdfFiles").get(1).path("sizeBytes").asLong()).isEqualTo(3);
|
||||
mvc.perform(get("/admin-api/components/{id}", created.path("id").asLong()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.componentCode").value(created.path("componentCode").asText()));
|
||||
create(uploaded()); // 同名组件允许创建,编码不同。
|
||||
mvc.perform(get("/admin-api/components").param("keyword", created.path("componentCode").asText()).param("category","安装板"))
|
||||
.andExpect(jsonPath("$.data.total").value(1)).andExpect(jsonPath("$.data.items[0].urdfFiles").doesNotExist());
|
||||
mvc.perform(get("/admin-api/components").param("category","其他"))
|
||||
.andExpect(jsonPath("$.data.total").value(0));
|
||||
mvc.perform(get("/admin-api/components").param("size","101"))
|
||||
.andExpect(jsonPath("$.data.size").value(100));
|
||||
mvc.perform(get("/admin-api/components").param("page","0")).andExpect(status().isUnprocessableEntity());
|
||||
assertThat(jdbc.queryForList("SELECT table_name FROM information_schema.tables WHERE table_schema='PUBLIC'", String.class))
|
||||
.containsExactlyInAnyOrder("COMPONENT","SYS_USER","SYS_OPERATION_LOG");
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestLogsCoverSuccessfulAndRejectedCallsWithoutSensitiveValues() throws Exception {
|
||||
String phone = "13800000001";
|
||||
String token = "PRIVATE_UPLOAD_TOKEN";
|
||||
String password = "PRIVATE_PASSWORD";
|
||||
var applicationLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("com.linkerbot.cadworld");
|
||||
var previousLevel = applicationLogger.getLevel();
|
||||
var mapperLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("com.linkerbot.cadworld.mapper");
|
||||
var sqlLogs = new ch.qos.logback.core.read.ListAppender<ch.qos.logback.classic.spi.ILoggingEvent>();
|
||||
sqlLogs.start();
|
||||
mapperLogger.addAppender(sqlLogs);
|
||||
applicationLogger.setLevel(ch.qos.logback.classic.Level.DEBUG);
|
||||
try (var captured = new com.linkerbot.cadworld.logging.ApiRequestLogCapture()) {
|
||||
mvc.perform(post("/admin-api/users").header("X-Request-Id", "user-create-log")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(Map.of("phone", phone, "nickname", "日志测试用户",
|
||||
"uploadSessionToken", token, "password", password))))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/users").header("X-Request-Id", "user-list-log")
|
||||
.param("keyword", phone).param("token", token))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(post("/admin-api/users").header("X-Request-Id", "user-rejected-log")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(Map.of("phone", phone, "nickname", "日志测试用户",
|
||||
"userType", "PRIVATE_INVALID_TYPE", "uploadSessionToken", token))))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
|
||||
assertThat(captured.messages()).hasSize(6);
|
||||
String messages = String.join("\n", captured.messages());
|
||||
assertThat(messages).contains("description=创建用户", "description=查询用户列表",
|
||||
"requestId=user-list-log", "result=SUCCESS", "httpStatus=200", "code=OK",
|
||||
"requestId=user-rejected-log", "result=FAILURE", "httpStatus=422",
|
||||
"code=INVALID_REQUEST", "durationMs=");
|
||||
assertThat(messages).doesNotContain(phone, token, password, "PRIVATE_INVALID_TYPE", "keyword=");
|
||||
assertThat(captured.events().getLast().getLevel()).isEqualTo(ch.qos.logback.classic.Level.WARN);
|
||||
assertThat(sqlLogs.list).isEmpty();
|
||||
assertThat(logCount()).isZero();
|
||||
} finally {
|
||||
applicationLogger.setLevel(previousLevel);
|
||||
mapperLogger.detachAppender(sqlLogs);
|
||||
sqlLogs.stop();
|
||||
}
|
||||
void duplicateCreationCannotReuseCodeAndCreateRequiresBothModels() throws Exception {
|
||||
Map<String,Object> body = uploaded();
|
||||
create(body);
|
||||
expectCreateError(body, 409, "COMPONENT_CODE_DUPLICATE");
|
||||
Map<String,Object> missing = uploaded();
|
||||
missing.remove("stepObjectKey");
|
||||
expectCreateError(missing, 422, "INVALID_REQUEST");
|
||||
assertThat(count("component")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void userCrudFiltersAndLogicalDeletionKeepPhoneReserved() throws Exception {
|
||||
JsonNode created = send("/admin-api/users", Map.of("phone", "13812345678", "nickname", "测试用户"));
|
||||
long id = created.path("data").path("id").asLong();
|
||||
assertThat(created.path("data").path("status").asText()).isEqualTo("ACTIVE");
|
||||
assertThat(created.path("data").path("userType").asText()).isEqualTo("NORMAL");
|
||||
mvc.perform(put("/admin-api/users/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"管理员\",\"status\":\"DISABLED\",\"userType\":\"ADMIN\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.userType").value("ADMIN"));
|
||||
mvc.perform(get("/admin-api/users").param("keyword", "管理员").param("userType", "ADMIN").param("status", "DISABLED"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(1));
|
||||
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/users/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/admin-api/users")).andExpect(jsonPath("$.data.total").value(0));
|
||||
assertThat(jdbc.queryForObject("SELECT deleted FROM sys_user WHERE id=?", Integer.class, id)).isEqualTo(1);
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"新用户\"}"))
|
||||
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("USER_PHONE_DUPLICATE"));
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidUserFieldsEnumsAndPaginationAreRejected() throws Exception {
|
||||
for (String body : new String[]{
|
||||
"{\"phone\":\"123\",\"nickname\":\"x\"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\" \"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"status\":\"INVALID\"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"userType\":\"ROOT\"}"}) {
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
mvc.perform(get("/admin-api/users").param("page", "0")).andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(get("/admin-api/users").param("size", "0")).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void componentCrudAndEveryFailureAreAuditedButReadsAreExcluded() throws Exception {
|
||||
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/");
|
||||
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());
|
||||
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{invalid"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isEqualTo(6);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE success=FALSE", Long.class)).isEqualTo(3);
|
||||
mvc.perform(get("/admin-api/operation-logs").param("module", "COMPONENT").param("success", "false").param("operatorId", "0"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(3));
|
||||
Long logId = jdbc.queryForObject("SELECT MIN(id) FROM sys_operation_log", Long.class);
|
||||
mvc.perform(get("/admin-api/operation-logs/{id}", logId)).andExpect(status().isOk()).andExpect(jsonPath("$.data.operatorName").value("TEST_OPERATOR"));
|
||||
assertThat(logCount()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interfaceRevisionsAndRejectedStaleEditsAreAudited() throws Exception {
|
||||
JsonNode request = json.readTree("""
|
||||
{"id":"mount","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}}
|
||||
""");
|
||||
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(1))
|
||||
.andExpect(jsonPath("$.data.editRevision").value(2));
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.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().isConflict());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadWorkflowUsesAdminUrlsAndDoesNotStoreToken() throws Exception {
|
||||
JsonNode session = send("/admin-api/components/cover-image-upload-sessions", null).path("data");
|
||||
String token = session.path("uploadSessionToken").asText();
|
||||
JsonNode upload = send("/admin-api/components/cover-image-upload-sessions/upload-url",
|
||||
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();
|
||||
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}));
|
||||
assertThat(logCount()).isEqualTo(4);
|
||||
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString()).doesNotContain(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modelAndCoverUploadKeysAreStoredAsRelativePathsAndDownloadUrlsWork() throws Exception {
|
||||
JsonNode session = send("/admin-api/components/urdf-upload-sessions", null).path("data");
|
||||
assertThat(session.path("keyPrefix").asText()).startsWith("cadworld_dev/components/urdf/");
|
||||
String token = session.path("uploadSessionToken").asText();
|
||||
JsonNode upload = send("/admin-api/components/urdf-upload-sessions/upload-url",
|
||||
Map.of("uploadSessionToken", token, "objectPath", "模型 robot.urdf", "contentType", "application/xml")).path("data");
|
||||
String key = upload.path("objectKey").asText();
|
||||
byte[] bytes = "<robot name=\"demo\"><link name=\"base\"/></robot>".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key)
|
||||
.header("X-Upload-Session-Token", token).contentType("application/xml").content(bytes))
|
||||
.andExpect(status().isNoContent());
|
||||
JsonNode complete = send("/admin-api/components/urdf-upload-sessions/complete",
|
||||
Map.of("uploadSessionToken", token, "objectKeys", new String[]{key})).path("data");
|
||||
assertThat(complete.path("source").asText()).isEqualTo(key);
|
||||
|
||||
JsonNode coverSession = send("/admin-api/components/cover-image-upload-sessions", null).path("data");
|
||||
String coverToken = coverSession.path("uploadSessionToken").asText();
|
||||
String coverKey = send("/admin-api/components/cover-image-upload-sessions/upload-url",
|
||||
Map.of("uploadSessionToken", coverToken, "objectPath", "cover.png", "contentType", "image/png"))
|
||||
.path("data").path("objectKey").asText();
|
||||
assertThat(coverKey).startsWith("cadworld_dev/components/cover-images/");
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", coverKey)
|
||||
.header("X-Upload-Session-Token", coverToken).contentType("image/png").content(new byte[]{1, 2}))
|
||||
.andExpect(status().isNoContent());
|
||||
send("/admin-api/components/cover-image-upload-sessions/complete",
|
||||
Map.of("uploadSessionToken", coverToken, "objectKeys", new String[]{coverKey}));
|
||||
|
||||
var body = json.valueToTree(component("relative-path-component"));
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) body).put("source", key).put("coverImageKey", coverKey);
|
||||
JsonNode result = send("/admin-api/components", body).path("data");
|
||||
long id = result.path("id").asLong();
|
||||
assertThat(jdbc.queryForObject("SELECT source FROM component WHERE id=?", String.class, id)).isEqualTo(key);
|
||||
assertThat(jdbc.queryForObject("SELECT cover_image_key FROM component WHERE id=?", String.class, id)).isEqualTo(coverKey);
|
||||
assertThat(result.path("sourceUrl").asText()).contains("/admin-api/component-assets/cadworld_dev/");
|
||||
mvc.perform(get(java.net.URI.create(result.path("sourceUrl").asText())))
|
||||
.andExpect(status().isOk()).andExpect(content().bytes(bytes))
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_XML))
|
||||
.andExpect(header().longValue("Content-Length", bytes.length));
|
||||
mvc.perform(get(java.net.URI.create(result.path("coverImageUrl").asText())))
|
||||
.andExpect(status().isOk()).andExpect(content().bytes(new byte[]{1, 2}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveAndDownloadRejectFullUrlsAndOtherEnvironmentKeys() throws Exception {
|
||||
for (String invalid : new String[]{"https://linkerbot.oss-cn-beijing.aliyuncs.com/cadworld_dev/model.rfs",
|
||||
"cadworld/model.rfs", "cadworld_dev/../model.rfs"}) {
|
||||
var body = (com.fasterxml.jackson.databind.node.ObjectNode) json.valueToTree(component("invalid-path"));
|
||||
body.put("source", invalid);
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content(body.toString()))
|
||||
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_STORAGE_OBJECT_KEY"));
|
||||
body.put("source", "cadworld_dev/components/sample.rfs").put("coverImageKey", invalid);
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content(body.toString()))
|
||||
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_STORAGE_OBJECT_KEY"));
|
||||
body.remove("coverImageKey");
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) body.path("componentJson"))
|
||||
.putObject("urdfSource").putArray("resources").addObject().put("sourceKey", invalid);
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content(body.toString()))
|
||||
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_STORAGE_OBJECT_KEY"));
|
||||
}
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM component", Long.class)).isZero();
|
||||
JsonNode created = send("/admin-api/components", component("preserved-path")).path("data");
|
||||
var update = (com.fasterxml.jackson.databind.node.ObjectNode) json.valueToTree(component("preserved-path"));
|
||||
update.set("componentJson", created.path("componentJson"));
|
||||
update.put("source", created.path("sourceUrl").asText());
|
||||
mvc.perform(put("/admin-api/components/{id}", created.path("id").asLong())
|
||||
.contentType(MediaType.APPLICATION_JSON).content(update.toString()))
|
||||
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_STORAGE_OBJECT_KEY"));
|
||||
assertThat(jdbc.queryForObject("SELECT source FROM component WHERE id=?", String.class, created.path("id").asLong()))
|
||||
.isEqualTo(created.path("source").asText());
|
||||
mvc.perform(get("/admin-api/component-assets/cadworld/production.rfs"))
|
||||
.andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.code").value("INVALID_STORAGE_OBJECT_KEY"));
|
||||
}
|
||||
|
||||
@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 -> {
|
||||
jdbc.update("INSERT INTO sys_user(phone,nickname,status,user_type,deleted) VALUES ('13912345678','rollback','ACTIVE','NORMAL',0)");
|
||||
OperationLog event = new OperationLog();
|
||||
event.setModule("COMPONENT"); event.setAction("CREATE"); event.setOperatorId(0L); event.setOperatorName("TEST_OPERATOR");
|
||||
event.setRequestPath("/admin-api/components"); event.setRequestMethod("POST"); event.setOperatedAt(java.time.LocalDateTime.now());
|
||||
event.setDurationMs(1L); event.setSuccess(false); event.setHttpStatus(422);
|
||||
logs.record(event);
|
||||
tx.setRollbackOnly();
|
||||
});
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isZero();
|
||||
assertThat(logCount()).isEqualTo(1);
|
||||
for (String path : new String[]{"/api/interfaces", "/api/components", "/api/component-assets/a", "/api/auth/me", "/api/projects"}) {
|
||||
mvc.perform(get(path)).andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void analysisAndPoseCalculationsAreExcludedFromAudit() throws Exception {
|
||||
mvc.perform(multipart("/admin-api/interface-brep/analyze")
|
||||
.file(new org.springframework.mock.web.MockMultipartFile("file", "bad.stl", "application/octet-stream", new byte[]{1})))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/interfaces/missing/pose-candidates").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleAndConcurrentComponentUpdatesCannotOverwriteEachOther() throws Exception {
|
||||
JsonNode created = send("/admin-api/components", component("concurrent")).path("data");
|
||||
void fullFormUpdateClearsFieldsPreservesModelsAndRejectsChangedCodeAndStaleVersion() throws Exception {
|
||||
JsonNode created = create(uploaded());
|
||||
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();
|
||||
Map<String,Object> form = update(1);
|
||||
form.put("basicFields", List.of(Map.of("name", "用途", "value", "固定")));
|
||||
JsonNode changed = data(mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(form))).andExpect(status().isOk()).andReturn());
|
||||
assertThat(changed.path("basicFields").size()).isEqualTo(1);
|
||||
assertThat(changed.path("stepObjectKey")).isEqualTo(created.path("stepObjectKey"));
|
||||
assertThat(changed.path("urdfFiles")).isEqualTo(created.path("urdfFiles"));
|
||||
Map<String,Object> clear = update(2);
|
||||
clear.put("basicFields", List.of());
|
||||
clear.put("parameterFields", List.of());
|
||||
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());
|
||||
.content(json.writeValueAsString(clear))).andExpect(status().isOk()).andExpect(jsonPath("$.data.basicFields").isEmpty());
|
||||
expectUpdateError(id, clear, 409, "COMPONENT_REVISION_CONFLICT");
|
||||
Map<String,Object> wrongCode = update(3);
|
||||
wrongCode.put("componentCode", "CW-"+"F".repeat(32));
|
||||
expectUpdateError(id, wrongCode, 422, "COMPONENT_CODE_IMMUTABLE");
|
||||
assertThat(count("component")).isEqualTo(1);
|
||||
assertThat(OperationTargetHolder.get()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingOneModelSwitchesOnlyAfterSuccessfulSaveAndKeepsOldObjects() throws Exception {
|
||||
JsonNode created = create(uploaded());
|
||||
long id = created.path("id").asLong();
|
||||
JsonNode session = sign(Map.of("componentId", id));
|
||||
assertThat(session.path("componentCode")).isEqualTo(created.path("componentCode"));
|
||||
String newKey = session.path("step").path("keyPrefix").asText() + "replacement.stp";
|
||||
Map<String,Object> form = update(1);
|
||||
form.put("uploadSessionToken", session.path("uploadSessionToken").asText());
|
||||
form.put("stepObjectKey", newKey);
|
||||
expectUpdateError(id, form, 422, "COMPONENT_UPLOAD_OBJECT_MISSING");
|
||||
assertThat(jdbc.queryForObject("SELECT step_object_key FROM component WHERE id=?",String.class,id))
|
||||
.isEqualTo(created.path("stepObjectKey").asText());
|
||||
storage.simulateDirectUpload(newKey,"application/octet-stream",new byte[]{4,5});
|
||||
JsonNode changed = data(mvc.perform(put("/admin-api/components/{id}",id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(form))).andExpect(status().isOk()).andReturn());
|
||||
assertThat(changed.path("stepObjectKey").asText()).isEqualTo(newKey);
|
||||
assertThat(changed.path("urdfMainObjectKey")).isEqualTo(created.path("urdfMainObjectKey"));
|
||||
assertThat(storage.objectExists(created.path("stepObjectKey").asText())).isTrue();
|
||||
Map<String,Object> another = uploaded();
|
||||
form.put("version",2);
|
||||
form.put("uploadSessionToken",another.get("uploadSessionToken"));
|
||||
form.put("stepObjectKey",another.get("stepObjectKey"));
|
||||
expectUpdateError(id,form,422,"INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacingUrdfPreservesStepAndStoresVerifiedManifest() throws Exception {
|
||||
JsonNode created = create(uploaded());
|
||||
long id = created.path("id").asLong();
|
||||
JsonNode session = sign(Map.of("componentId", id));
|
||||
String prefix = session.path("urdf").path("keyPrefix").asText();
|
||||
String main = prefix + "robot.urdf";
|
||||
String mesh = prefix + "meshes/new.stl";
|
||||
Map<String,Object> form = update(1);
|
||||
form.put("uploadSessionToken", session.path("uploadSessionToken").asText());
|
||||
form.put("urdfObjectKeys", List.of(main, mesh));
|
||||
storage.simulateDirectUpload(main, "application/xml", new byte[]{1});
|
||||
expectUpdateError(id, form, 422, "COMPONENT_UPLOAD_OBJECT_MISSING");
|
||||
assertThat(jdbc.queryForObject("SELECT urdf_prefix FROM component WHERE id=?", String.class, id))
|
||||
.isEqualTo(created.path("urdfPrefix").asText());
|
||||
storage.simulateDirectUpload(mesh, "application/octet-stream", new byte[]{2,3,4,5});
|
||||
JsonNode changed = data(mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(form))).andExpect(status().isOk()).andReturn());
|
||||
assertThat(changed.path("stepObjectKey")).isEqualTo(created.path("stepObjectKey"));
|
||||
assertThat(changed.path("urdfPrefix").asText()).isEqualTo(prefix);
|
||||
assertThat(changed.path("urdfMainObjectKey").asText()).isEqualTo(main);
|
||||
assertThat(changed.path("urdfFiles").get(1).path("relativePath").asText()).isEqualTo("meshes/new.stl");
|
||||
assertThat(changed.path("urdfFiles").get(1).path("sizeBytes").asLong()).isEqualTo(4);
|
||||
assertThat(storage.objectExists(created.path("urdfMainObjectKey").asText())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void newAndExistingSessionsCannotBeUsedForAnotherComponent() throws Exception {
|
||||
JsonNode first = create(uploaded());
|
||||
JsonNode second = create(uploaded());
|
||||
JsonNode editSession = sign(Map.of("componentId",first.path("id").asLong()));
|
||||
Map<String,Object> body = uploaded();
|
||||
body.put("uploadSessionToken",editSession.path("uploadSessionToken").asText());
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
Map<String,Object> form = update(1);
|
||||
form.put("uploadSessionToken",editSession.path("uploadSessionToken").asText());
|
||||
form.put("stepObjectKey",editSession.path("step").path("keyPrefix").asText()+"new.step");
|
||||
expectUpdateError(second.path("id").asLong(),form,422,"INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fileManifestsRejectWrongDirectoriesDuplicateFilesAndInvalidMainFiles() throws Exception {
|
||||
Map<String,Object> body = uploaded();
|
||||
String main = ((List<String>)body.get("urdfObjectKeys")).getFirst();
|
||||
body.put("urdfObjectKeys",List.of(main,main));
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
body.put("urdfObjectKeys",List.of(main.substring(0,main.lastIndexOf('/')+1)+"robot.rfs"));
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
body.put("urdfObjectKeys",List.of(main,main.replace("robot.urdf","other.urdf")));
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
body.put("urdfObjectKeys",List.of("cadworld/components/escape.urdf"));
|
||||
expectCreateError(body,422,"INVALID_STORAGE_OBJECT_KEY");
|
||||
body.put("urdfObjectKeys",List.of(main.substring(0,main.lastIndexOf('/')+1)+"../robot.urdf"));
|
||||
expectCreateError(body,422,"INVALID_STORAGE_OBJECT_KEY");
|
||||
body.put("urdfObjectKeys",List.of(main));
|
||||
body.put("stepObjectKey",main);
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
Map<String,Object> other = uploaded();
|
||||
body.put("stepObjectKey",other.get("stepObjectKey"));
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
assertThat(count("component")).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void actualObjectSizeAndNonemptyMainFilesAreCheckedAtSave() throws Exception {
|
||||
Map<String,Object> body = uploaded();
|
||||
String step = body.get("stepObjectKey").toString();
|
||||
storage.simulateDirectUpload(step,"application/octet-stream",new byte[1025]);
|
||||
expectCreateError(body,413,"UPLOAD_TOO_LARGE");
|
||||
storage.simulateDirectUpload(step,"application/octet-stream",new byte[0]);
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
storage.simulateDirectUpload(step,"application/octet-stream",new byte[]{1});
|
||||
String main = ((List<String>)body.get("urdfObjectKeys")).getFirst();
|
||||
storage.simulateDirectUpload(main,"application/xml",new byte[0]);
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
storage.simulateDirectUpload(main,"application/xml",new byte[]{1});
|
||||
String mesh = ((List<String>)body.get("urdfObjectKeys")).get(1);
|
||||
storage.simulateDirectUpload(mesh,"application/octet-stream",new byte[1025]);
|
||||
expectCreateError(body,413,"UPLOAD_TOO_LARGE");
|
||||
assertThat(count("component")).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidExpiredWrongOwnerAndCrossEnvironmentTokensNeverCreateRows() throws Exception {
|
||||
Map<String,Object> body = uploaded();
|
||||
var original = tokens.parseToken(body.get("uploadSessionToken").toString());
|
||||
for (String token : List.of("forged-token",
|
||||
tokens.generateToken(new ComponentUploadSessionTokenProvider.UploadSessionClaims(99L,null,
|
||||
original.componentCode(),original.batch(),original.stepPrefix(),original.urdfPrefix(),original.expiresAt())),
|
||||
tokens.generateToken(new ComponentUploadSessionTokenProvider.UploadSessionClaims(0L,null,
|
||||
original.componentCode(),original.batch(),original.stepPrefix(),original.urdfPrefix(),Instant.now().minusSeconds(60))),
|
||||
tokens.generateToken(new ComponentUploadSessionTokenProvider.UploadSessionClaims(0L,null,
|
||||
original.componentCode(),original.batch(),original.stepPrefix().replace("cadworld_dev/","cadworld/"),
|
||||
original.urdfPrefix().replace("cadworld_dev/","cadworld/"),original.expiresAt())))) {
|
||||
body.put("uploadSessionToken",token);
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
}
|
||||
assertThat(count("component")).isZero();
|
||||
assertThat(jdbc.queryForList("SELECT error_summary FROM sys_operation_log").toString()).doesNotContain("forged-token");
|
||||
}
|
||||
|
||||
@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());
|
||||
void formValidationAndCustomFieldLimitsAreAppliedBeforeDatabaseWrites() throws Exception {
|
||||
Map<String,Object> body = uploaded();
|
||||
body.put("basicFields",List.of(Map.of("name","电压","value","24"),Map.of("name"," 电压 ","value","48")));
|
||||
expectCreateError(body,422,"DUPLICATE_CUSTOM_FIELD");
|
||||
body.put("basicFields",List.of(Map.of("name","电压","value","24")));
|
||||
body.put("parameterFields",List.of(Map.of("name","电压","value","48")));
|
||||
create(body); // 不同表单允许同名。
|
||||
body = uploaded();
|
||||
body.put("basicFields", java.util.stream.IntStream.range(0,101).mapToObj(i -> Map.of("name","字段"+i,"value","")).toList());
|
||||
expectCreateError(body,422,"INVALID_REQUEST");
|
||||
body.put("basicFields",List.of(Map.of("name","x","value","x".repeat(2001))));
|
||||
expectCreateError(body,422,"INVALID_REQUEST");
|
||||
body.remove("basicFields");
|
||||
for (String field : List.of("massKg","lengthMm","widthMm","heightMm")) {
|
||||
body.put(field,-1);
|
||||
expectCreateError(body,422,"INVALID_REQUEST");
|
||||
body.remove(field);
|
||||
}
|
||||
body.put("massKg", "1000000000000");
|
||||
expectCreateError(body,422,"INVALID_REQUEST");
|
||||
body.put("massKg", "0.0000001");
|
||||
expectCreateError(body,422,"INVALID_REQUEST");
|
||||
assertThat(count("component")).isEqualTo(1);
|
||||
}
|
||||
|
||||
@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"));
|
||||
void concurrentEditsOnlyAllowOneVersionToCommit() throws Exception {
|
||||
long id = create(uploaded()).path("id").asLong();
|
||||
String body = json.writeValueAsString(update(1));
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Callable<Integer> edit = () -> {
|
||||
start.await();
|
||||
return mvc.perform(put("/admin-api/components/{id}",id).contentType(MediaType.APPLICATION_JSON).content(body))
|
||||
.andReturn().getResponse().getStatus();
|
||||
};
|
||||
Future<Integer> a = executor.submit(edit), b = executor.submit(edit);
|
||||
start.countDown();
|
||||
assertThat(List.of(a.get(10,TimeUnit.SECONDS),b.get(10,TimeUnit.SECONDS))).containsExactlyInAnyOrder(200,409);
|
||||
}
|
||||
assertThat(jdbc.queryForObject("SELECT version FROM component WHERE id=?",Long.class,id)).isEqualTo(2);
|
||||
}
|
||||
|
||||
@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", "cadworld_dev/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));
|
||||
void auditSnapshotsSurviveDeletionAndQueriesSupportOtherModules() throws Exception {
|
||||
JsonNode created = create(uploaded());
|
||||
long id = created.path("id").asLong();
|
||||
String code = created.path("componentCode").asText();
|
||||
mvc.perform(delete("/admin-api/components/{id}",id).header("X-Request-Id","delete-snapshot"))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components/{id}",id)).andExpect(status().isNotFound());
|
||||
mvc.perform(delete("/admin-api/components/{id}",id)).andExpect(status().isNotFound());
|
||||
assertThat(count("sys_operation_log")).isEqualTo(3); // 成功新增、成功删除、失败删除各一条。
|
||||
Map<String,Object> deleted = jdbc.queryForMap("SELECT * FROM sys_operation_log WHERE request_id='delete-snapshot'");
|
||||
assertThat(deleted.get("TARGET_CODE")).isEqualTo(code);
|
||||
assertThat(deleted.get("TARGET_NAME")).isEqualTo("测试组件");
|
||||
assertThat(deleted.get("REQUEST_PATH")).isEqualTo("/admin-api/components/{id:[0-9]+}");
|
||||
assertThat(deleted.get("TARGET_ID")).isEqualTo(String.valueOf(id));
|
||||
OperationLog order = new OperationLog();
|
||||
order.setModule("ORDER"); order.setAction("CREATE"); order.setTargetType("ORDER");
|
||||
order.setTargetId("order-uuid"); order.setTargetCode("ORDER-001"); order.setTargetName("订单测试");
|
||||
order.setOperatedAt(LocalDateTime.now()); order.setSuccess(true); order.setHttpStatus(200);
|
||||
logs.record(order);
|
||||
mvc.perform(get("/admin-api/operation-logs").param("module","ORDER").param("targetId","order-uuid"))
|
||||
.andExpect(jsonPath("$.data.total").value(1));
|
||||
mvc.perform(get("/admin-api/operation-logs").param("module","COMPONENT").param("targetType","COMPONENT").param("targetCode",code))
|
||||
.andExpect(jsonPath("$.data.total").value(2));
|
||||
mvc.perform(get("/admin-api/operation-logs").param("success","false").param("action","DELETE"))
|
||||
.andExpect(jsonPath("$.data.items[0].errorCode").value("COMPONENT_NOT_FOUND"));
|
||||
mvc.perform(get("/admin-api/operation-logs").param("keyword","订单"))
|
||||
.andExpect(jsonPath("$.data.total").value(1));
|
||||
mvc.perform(get("/admin-api/operation-logs/{id}",deleted.get("ID"))).andExpect(status().isOk());
|
||||
assertThat(OperationTargetHolder.get()).isNull();
|
||||
}
|
||||
|
||||
@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);
|
||||
void userCrudAndLogicalDeletionRemainUnaudited() throws Exception {
|
||||
JsonNode user = data(mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"测试用户\"}")).andExpect(status().isOk()).andReturn());
|
||||
long id = user.path("id").asLong();
|
||||
mvc.perform(put("/admin-api/users/{id}",id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"管理员\",\"status\":\"DISABLED\",\"userType\":\"ADMIN\"}"))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/users").param("userType","ADMIN").param("status","DISABLED"))
|
||||
.andExpect(jsonPath("$.data.total").value(1));
|
||||
mvc.perform(delete("/admin-api/users/{id}",id)).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/users/{id}",id)).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"再次创建\"}"))
|
||||
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("USER_PHONE_DUPLICATE"));
|
||||
assertThat(count("sys_operation_log")).isZero();
|
||||
}
|
||||
|
||||
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));
|
||||
return json.readTree(mvc.perform(request).andExpect(status().isOk()).andReturn().getResponse().getContentAsString());
|
||||
@Test
|
||||
void runtimeLogsHideBodiesTokensAndSqlParametersAndEveryEndpointHasDescription() throws Exception {
|
||||
for (var handler : mappings.getHandlerMethods().values()) {
|
||||
if (handler.getBeanType().getPackageName().equals("com.linkerbot.cadworld.controller")) {
|
||||
assertThat(handler.getMethodAnnotation(com.linkerbot.cadworld.logging.ApiRequestLog.class)).isNotNull();
|
||||
}
|
||||
}
|
||||
Map<String,Object> body = uploaded();
|
||||
body.put("basicFields",List.of(Map.of("name","备注","value","PRIVATE_FIELD_VALUE")));
|
||||
var mapperLogger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger("com.linkerbot.cadworld.mapper");
|
||||
var capture = new ch.qos.logback.core.read.ListAppender<ch.qos.logback.classic.spi.ILoggingEvent>();
|
||||
capture.start(); mapperLogger.addAppender(capture);
|
||||
try (var runtime = new com.linkerbot.cadworld.logging.ApiRequestLogCapture()) {
|
||||
create(body);
|
||||
body.put("uploadSessionToken","PRIVATE_TOKEN");
|
||||
expectCreateError(body,422,"INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
mvc.perform(get("/admin-api/users").param("keyword","13800000001"));
|
||||
String messages = String.join("\n",runtime.messages());
|
||||
assertThat(messages).contains("description=新增组件","result=SUCCESS","result=FAILURE","durationMs=");
|
||||
assertThat(messages).doesNotContain("PRIVATE_FIELD_VALUE","PRIVATE_TOKEN",body.get("stepObjectKey").toString(),"13800000001");
|
||||
assertThat(capture.list).isEmpty();
|
||||
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString())
|
||||
.doesNotContain("PRIVATE_FIELD_VALUE","PRIVATE_TOKEN",body.get("uploadSessionToken").toString(),
|
||||
"FAKE_TEST_POLICY","FAKE_TEST_SIGNATURE");
|
||||
} finally { mapperLogger.detachAppender(capture); capture.stop(); }
|
||||
}
|
||||
|
||||
private Map<String, Object> component(String name) {
|
||||
return Map.of("componentName", name, "robotType", "humanoid", "company", "test", "model", "m1", "source", "cadworld_dev/components/sample.rfs",
|
||||
"componentJson", Map.of("interfaces", new Object[0]), "assemblyMetadata", Map.of("tags", new String[]{"test"}, "capabilities", new Object[0], "dimensions", Map.of()));
|
||||
@Test
|
||||
void removedEndpointsReturn404AndDownloadsStillWork() throws Exception {
|
||||
for (String route : List.of("/admin-api/interfaces","/admin-api/interfaces/mount",
|
||||
"/admin-api/interface-brep/analyze","/admin-api/interfaces/mount/pose-candidates",
|
||||
"/admin-api/interfaces/mount/confirm-port","/admin-api/components/upload-sessions",
|
||||
"/admin-api/components/upload-sessions/complete","/admin-api/components/urdf-upload-sessions/complete",
|
||||
"/admin-api/components/cover-image-upload-sessions/complete","/admin-api/component-assets/upload")) {
|
||||
mvc.perform(post(route).contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isNotFound());
|
||||
}
|
||||
Map<String,Object> body = uploaded();
|
||||
String key = ((List<String>)body.get("urdfObjectKeys")).get(1);
|
||||
mvc.perform(get("/admin-api/component-assets/"+key)).andExpect(status().isOk())
|
||||
.andExpect(content().bytes(new byte[]{1,2,3}));
|
||||
assertThat(count("sys_operation_log")).isZero();
|
||||
}
|
||||
|
||||
private long logCount() { return jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log", Long.class); }
|
||||
JsonNode sign(Map<String,?> body) throws Exception {
|
||||
return data(mvc.perform(post("/admin-api/storage/upload-signature").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(body))).andExpect(status().isOk()).andReturn());
|
||||
}
|
||||
Map<String,Object> uploaded() throws Exception {
|
||||
JsonNode session = sign(Map.of());
|
||||
String step = session.path("step").path("keyPrefix").asText()+"model one.STEP";
|
||||
String main = session.path("urdf").path("keyPrefix").asText()+"robot.urdf";
|
||||
String mesh = session.path("urdf").path("keyPrefix").asText()+"meshes/base.stl";
|
||||
storage.simulateDirectUpload(step,"application/octet-stream",new byte[]{1,2});
|
||||
storage.simulateDirectUpload(main,"application/xml","<robot/>".getBytes(StandardCharsets.UTF_8));
|
||||
storage.simulateDirectUpload(mesh,"application/octet-stream",new byte[]{1,2,3});
|
||||
Map<String,Object> body = new HashMap<>();
|
||||
body.put("componentName","测试组件"); body.put("category","安装板");
|
||||
body.put("uploadSessionToken",session.path("uploadSessionToken").asText());
|
||||
body.put("stepObjectKey",step); body.put("urdfObjectKeys",List.of(main,mesh));
|
||||
return body;
|
||||
}
|
||||
Map<String,Object> update(long version) {
|
||||
Map<String,Object> body = new HashMap<>();
|
||||
body.put("componentName","修改后的组件"); body.put("category","安装板"); body.put("version",version);
|
||||
return body;
|
||||
}
|
||||
JsonNode create(Map<String,?> body) throws Exception {
|
||||
return data(mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(body))).andExpect(status().isOk()).andReturn());
|
||||
}
|
||||
void expectCreateError(Map<String,?> body,int status,String code) throws Exception {
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(body))).andExpect(status().is(status)).andExpect(jsonPath("$.code").value(code));
|
||||
}
|
||||
void expectUpdateError(long id,Map<String,?> body,int status,String code) throws Exception {
|
||||
mvc.perform(put("/admin-api/components/{id}",id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(json.writeValueAsString(body))).andExpect(status().is(status)).andExpect(jsonPath("$.code").value(code));
|
||||
}
|
||||
JsonNode data(MvcResult result) throws Exception { return json.readTree(result.getResponse().getContentAsString(StandardCharsets.UTF_8)).path("data"); }
|
||||
long count(String table) { return jdbc.queryForObject("SELECT COUNT(*) FROM "+table,Long.class); }
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
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.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.*;
|
||||
|
||||
/** 显式启用的 MySQL 集成测试;资源使用测试代码中的内存替身。 */
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.url=${cadworld.it.db-url:jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai}",
|
||||
"spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver",
|
||||
"spring.datasource.username=${cadworld.it.db-user:root}", "spring.datasource.password=${cadworld.it.db-password:}",
|
||||
"spring.sql.init.mode=never", "app.storage.root-prefix=cadworld_dev",
|
||||
"logging.file.path=target/integration-logs"
|
||||
})
|
||||
class ExternalServicesIT extends AdminApiTest {
|
||||
@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");
|
||||
// Refuse accidental execution against the shared cadworld database.
|
||||
if (!url.matches("jdbc:mysql://[^/]+/cadworld_verification(?:\\?.*)?")) {
|
||||
throw new IllegalArgumentException("Integration database must be named cadworld_verification");
|
||||
}
|
||||
Path db = Path.of(System.getProperty("cadworld.project-root", "..")).resolve("db");
|
||||
try (var connection = DriverManager.getConnection(url, System.getProperty("cadworld.it.db-user", "root"), System.getProperty("cadworld.it.db-password", ""));
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute("DROP TABLE IF EXISTS component_asset, component, interface_definition_revision, interface_definition_v2, sys_operation_log, sys_user");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
|
||||
statement.executeUpdate("INSERT INTO sys_user(phone,nickname,status,user_type) VALUES ('13800000000','sentinel','ACTIVE','NORMAL')");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
// Simulate precisely the supplied pre-upgrade tables while retaining a real user row.
|
||||
statement.execute("DROP TABLE component_asset, interface_definition_revision, interface_definition_v2, sys_operation_log");
|
||||
statement.execute("ALTER TABLE sys_user DROP COLUMN deleted");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
-6
@@ -8,17 +8,21 @@ import com.linkerbot.cadworld.service.support.UploadLimits;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
/** 仅用于自动化业务测试;运行时始终使用真实 OSS。 */
|
||||
@TestConfiguration(proxyBeanMethods = false)
|
||||
class InMemoryObjectStorageConfiguration {
|
||||
@Bean
|
||||
org.springframework.beans.factory.InitializingBean testSchema(org.springframework.jdbc.core.JdbcTemplate jdbc) {
|
||||
return () -> TestSchemaSupport.prepare(jdbc);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
InMemoryObjectStorageClient inMemoryObjectStorageClient(StorageProperties properties, StorageObjectKeys keys) {
|
||||
@@ -39,10 +43,15 @@ class InMemoryObjectStorageConfiguration {
|
||||
void clear() { objects.clear(); }
|
||||
|
||||
@Override
|
||||
public String createUploadUrl(String key, String contentType, Duration duration) {
|
||||
return UriComponentsBuilder.fromUriString(properties.publicApiBaseUrl())
|
||||
.path("/admin-api/component-assets/upload")
|
||||
.queryParam("objectKey", keys.requireKey(key)).build().encode().toUriString();
|
||||
public UploadAuthorization createUploadAuthorization(String prefix, Instant expiresAt) {
|
||||
keys.requirePrefix(prefix);
|
||||
return new UploadAuthorization("https://test-bucket.oss-cn-beijing.aliyuncs.com/",
|
||||
Map.of("policy", "FAKE_TEST_POLICY", "x-oss-signature", "FAKE_TEST_SIGNATURE",
|
||||
"success_action_status", "204", "x-oss-forbid-overwrite", "true"), expiresAt);
|
||||
}
|
||||
|
||||
void simulateDirectUpload(String key, String contentType, byte[] bytes) {
|
||||
objects.put(keys.requireKey(key), new Entry(contentType, bytes.clone()));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -8,7 +8,6 @@ import com.linkerbot.cadworld.config.OssProperties;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.service.client.OssObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
@@ -50,36 +49,76 @@ class OssObjectStorageIT {
|
||||
}
|
||||
|
||||
@Test
|
||||
void realOssUploadMetadataDownloadLimitAndCleanup() throws IOException {
|
||||
String key = keys.underRoot("model.rfs");
|
||||
void realDirectoryPostUploadsMultipleFilesRejectsOverwriteAndLimitAndCleansExactKeys() throws Exception {
|
||||
String prefix = keys.underRoot("batch") + "/";
|
||||
String model = prefix + "robot.urdf";
|
||||
String mesh = prefix + "meshes/base.stl";
|
||||
String oversized = prefix + "oversized.rfs";
|
||||
String outside = keys.underRoot("outside.rfs");
|
||||
var attempted = java.util.List.of(model, mesh, oversized, outside);
|
||||
Path journal = Path.of("logs", "oss-verification-pending", RUN_ID + ".txt");
|
||||
Files.createDirectories(journal.getParent());
|
||||
Files.writeString(journal, key + "\n");
|
||||
Files.write(journal, attempted);
|
||||
Throwable originalFailure = null;
|
||||
try {
|
||||
storage.putObject(key, "application/octet-stream", new ByteArrayInputStream(new byte[]{1, 2}), 2);
|
||||
assertThat(storage.objectExists(key)).isTrue();
|
||||
assertThat(storage.statObject(key).contentLength()).isEqualTo(2);
|
||||
assertThat(storage.statObject(key).contentType()).isEqualTo("application/octet-stream");
|
||||
assertThatThrownBy(() -> storage.putObject(key, null, new ByteArrayInputStream(new byte[9]), -1))
|
||||
.isInstanceOf(BizException.class).extracting("httpStatus").isEqualTo(413);
|
||||
var authorization = storage.createUploadAuthorization(prefix, java.time.Instant.now().plusSeconds(300));
|
||||
try (var http = java.net.http.HttpClient.newBuilder().connectTimeout(java.time.Duration.ofSeconds(10)).build()) {
|
||||
assertThat(post(http, authorization, model, new byte[]{1,2})).isEqualTo(204);
|
||||
assertThat(post(http, authorization, mesh, new byte[]{3,4})).isEqualTo(204);
|
||||
assertThat(storage.statObject(model).contentLength()).isEqualTo(2);
|
||||
assertThat(storage.statObject(mesh).contentLength()).isEqualTo(2);
|
||||
assertThat(post(http, authorization, model, new byte[]{9})).isEqualTo(409);
|
||||
assertThat(post(http, authorization, oversized, new byte[9])).isBetween(400,499);
|
||||
assertThat(post(http, authorization, outside, new byte[]{1})).isBetween(400,499);
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
storage.writeObjectTo(key, output);
|
||||
assertThat(output.toByteArray()).containsExactly((byte) 1, (byte) 2);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
storage.writeObjectTo(model, output);
|
||||
assertThat(output.toByteArray()).containsExactly((byte)1,(byte)2);
|
||||
output.reset(); storage.writeObjectTo(mesh,output);
|
||||
assertThat(output.toByteArray()).containsExactly((byte)3,(byte)4);
|
||||
} catch (Exception | Error failure) {
|
||||
originalFailure = failure;
|
||||
throw failure;
|
||||
} finally {
|
||||
try {
|
||||
storage.deleteObject(key);
|
||||
Files.deleteIfExists(journal);
|
||||
} catch (RuntimeException | IOException cleanupFailure) {
|
||||
var pending = new java.util.ArrayList<String>();
|
||||
for (String key : attempted) {
|
||||
try {
|
||||
if (storage.objectExists(key)) storage.deleteObject(key);
|
||||
} catch (RuntimeException failure) {
|
||||
pending.add(key);
|
||||
System.err.println("OSS 验证对象清理失败 key=" + key + " errorCode="
|
||||
+ (failure instanceof BizException error ? error.getCode() : failure.getClass().getSimpleName()));
|
||||
}
|
||||
}
|
||||
if (pending.isEmpty()) Files.deleteIfExists(journal);
|
||||
else {
|
||||
Files.write(journal,pending);
|
||||
var cleanupFailure = new AssertionError("OSS 清理失败,准确 Key 记录在 " + journal);
|
||||
if (originalFailure == null) throw cleanupFailure;
|
||||
originalFailure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
}
|
||||
assertThat(storage.objectExists(key)).isFalse();
|
||||
assertThatThrownBy(() -> storage.statObject(key))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("OSS_OBJECT_NOT_FOUND");
|
||||
}
|
||||
|
||||
private int post(java.net.http.HttpClient http,
|
||||
com.linkerbot.cadworld.service.client.ObjectStorageClient.UploadAuthorization authorization,
|
||||
String key, byte[] bytes) throws Exception {
|
||||
String boundary = "cadworld-" + UUID.randomUUID();
|
||||
ByteArrayOutputStream body = new ByteArrayOutputStream();
|
||||
for (var field : authorization.uploadFields().entrySet()) {
|
||||
multipartField(body,boundary,field.getKey(),field.getValue());
|
||||
}
|
||||
multipartField(body,boundary,"key",key);
|
||||
body.write(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"file.bin\"\r\n"
|
||||
+ "Content-Type: application/octet-stream\r\n\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
body.write(bytes);
|
||||
body.write(("\r\n--" + boundary + "--\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
var request = java.net.http.HttpRequest.newBuilder(java.net.URI.create(authorization.uploadUrl()))
|
||||
.timeout(java.time.Duration.ofSeconds(30))
|
||||
.header("Content-Type","multipart/form-data; boundary=" + boundary)
|
||||
.POST(java.net.http.HttpRequest.BodyPublishers.ofByteArray(body.toByteArray())).build();
|
||||
return http.send(request,java.net.http.HttpResponse.BodyHandlers.discarding()).statusCode();
|
||||
}
|
||||
private void multipartField(ByteArrayOutputStream body, String boundary, String name, String value) throws IOException {
|
||||
body.write(("--"+boundary+"\r\nContent-Disposition: form-data; name=\""+name+"\"\r\n\r\n"+value+"\r\n")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,13 @@ class StorageEnvironmentTest {
|
||||
assertThat(context.getBean(StorageProperties.class).rootPrefix()).isEqualTo("cadworld"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signatureTtlDefaultsToFiveMinutesAndEnvironmentOverrideIsBound() {
|
||||
runner.run(context -> assertThat(context.getBean(StorageProperties.class).uploadSignatureTtl()).isEqualTo(java.time.Duration.ofMinutes(5)));
|
||||
runner.withPropertyValues("OSS_UPLOAD_SIGNATURE_TTL=PT2M").run(context ->
|
||||
assertThat(context.getBean(StorageProperties.class).uploadSignatureTtl()).isEqualTo(java.time.Duration.ofMinutes(2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootOverrideWorksInBothProfilesAndIsAddedOnce() {
|
||||
for (String profile : new String[]{"test", "prod"}) {
|
||||
|
||||
@@ -1,40 +1,73 @@
|
||||
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. */
|
||||
/** 只初始化进程内H2测试库,不读取旧SQL脚本,不允许接入业务数据库。 */
|
||||
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;
|
||||
});
|
||||
String product = jdbc.execute((org.springframework.jdbc.core.ConnectionCallback<String>)
|
||||
connection -> connection.getMetaData().getDatabaseProductName());
|
||||
if (!"H2".equals(product)) throw new IllegalStateException("测试初始化只允许使用H2");
|
||||
jdbc.execute("""
|
||||
CREATE TABLE IF NOT EXISTS component (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
component_code VARCHAR(64) NOT NULL DEFAULT '' UNIQUE,
|
||||
component_name VARCHAR(128) NOT NULL DEFAULT '',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '',
|
||||
manufacturer VARCHAR(128) NOT NULL DEFAULT '',
|
||||
description CLOB NOT NULL DEFAULT '',
|
||||
material VARCHAR(128) NOT NULL DEFAULT '',
|
||||
mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0,
|
||||
length_mm DECIMAL(18,6) NOT NULL DEFAULT 0,
|
||||
width_mm DECIMAL(18,6) NOT NULL DEFAULT 0,
|
||||
height_mm DECIMAL(18,6) NOT NULL DEFAULT 0,
|
||||
tags CLOB NOT NULL DEFAULT '[]',
|
||||
basic_fields CLOB NOT NULL DEFAULT '[]',
|
||||
parameter_fields CLOB NOT NULL DEFAULT '[]',
|
||||
step_object_key VARCHAR(512) NOT NULL DEFAULT '',
|
||||
urdf_prefix VARCHAR(512) NOT NULL DEFAULT '',
|
||||
urdf_main_object_key VARCHAR(512) NOT NULL DEFAULT '',
|
||||
urdf_files CLOB NOT NULL DEFAULT '[]',
|
||||
version BIGINT NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""");
|
||||
jdbc.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sys_operation_log (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
module VARCHAR(64) NOT NULL DEFAULT '',
|
||||
action VARCHAR(64) NOT NULL DEFAULT '',
|
||||
target_type VARCHAR(64) NOT NULL DEFAULT '',
|
||||
target_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
target_code VARCHAR(128) NOT NULL DEFAULT '',
|
||||
target_name VARCHAR(256) NOT NULL DEFAULT '',
|
||||
operator_id BIGINT NOT NULL DEFAULT 0,
|
||||
operator_name VARCHAR(128) NOT NULL DEFAULT '',
|
||||
request_path VARCHAR(512) NOT NULL DEFAULT '',
|
||||
request_method VARCHAR(16) NOT NULL DEFAULT '',
|
||||
client_ip VARCHAR(64) NOT NULL DEFAULT '',
|
||||
request_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
operated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||
success BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
http_status INTEGER NOT NULL DEFAULT 0,
|
||||
error_code VARCHAR(64) NOT NULL DEFAULT '',
|
||||
error_summary VARCHAR(1000) NOT NULL DEFAULT ''
|
||||
)
|
||||
""");
|
||||
jdbc.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sys_user (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
phone VARCHAR(32) NOT NULL UNIQUE,
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE',
|
||||
user_type VARCHAR(32) NOT NULL DEFAULT 'NORMAL',
|
||||
deleted INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,76 +1,43 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:upload-http;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"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.root-prefix=cadworld_dev", "logging.file.path=target/test-logs"
|
||||
"spring.datasource.driver-class-name=org.h2.Driver","spring.datasource.username=sa","spring.datasource.password=",
|
||||
"spring.sql.init.mode=never","app.storage.root-prefix=cadworld_dev","app.storage.max-upload-bytes=1024",
|
||||
"logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
@org.springframework.context.annotation.Import(InMemoryObjectStorageConfiguration.class)
|
||||
class UploadHttpTest {
|
||||
@Autowired TestRestTemplate http;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
@Autowired InMemoryObjectStorageConfiguration.InMemoryObjectStorageClient storage;
|
||||
|
||||
@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>();
|
||||
body.add("file", new ByteArrayResource(new byte[4096]) {
|
||||
@Override public String getFilename() { return "oversize.step"; }
|
||||
});
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
headers.set("X-Request-Id", "oversize-runtime-log");
|
||||
try (var captured = new com.linkerbot.cadworld.logging.ApiRequestLogCapture()) {
|
||||
var response = http.postForEntity("/admin-api/interfaces/missing/assets?geometryRevision=1", new HttpEntity<>(body, headers), String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE);
|
||||
org.awaitility.Awaitility.await().atMost(java.time.Duration.ofSeconds(5)).untilAsserted(() -> {
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND http_status=413 AND success=FALSE AND target_id='missing'", Long.class))
|
||||
.isEqualTo(1);
|
||||
assertThat(captured.messages()).hasSize(2);
|
||||
assertThat(captured.messages().getLast()).contains("description=上传接口源文件",
|
||||
"requestId=oversize-runtime-log", "result=FAILURE", "httpStatus=413",
|
||||
"code=INVALID_REQUEST");
|
||||
});
|
||||
}
|
||||
void oversizeDirectUploadIsRejectedAtComponentSaveWithoutCreatingRowAndAuditedOnce() {
|
||||
JsonNode session = http.postForObject("/admin-api/storage/upload-signature",Map.of(),JsonNode.class).path("data");
|
||||
String step = session.path("step").path("keyPrefix").asText()+"model.step";
|
||||
String main = session.path("urdf").path("keyPrefix").asText()+"robot.urdf";
|
||||
storage.simulateDirectUpload(step,"application/octet-stream",new byte[1025]);
|
||||
storage.simulateDirectUpload(main,"application/xml",new byte[]{1});
|
||||
var response = http.postForEntity("/admin-api/components",Map.of(
|
||||
"componentName","超限测试","category","安装板","uploadSessionToken",session.path("uploadSessionToken").asText(),
|
||||
"stepObjectKey",step,"urdfObjectKeys",List.of(main)),String.class);
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(413);
|
||||
assertThat(response.getBody()).contains("UPLOAD_TOO_LARGE");
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM component",Long.class)).isZero();
|
||||
org.awaitility.Awaitility.await().atMost(java.time.Duration.ofSeconds(5)).untilAsserted(() ->
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE action='CREATE' AND success=FALSE",Long.class)).isEqualTo(1));
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -19,20 +19,20 @@ import static org.mockito.Mockito.*;
|
||||
|
||||
class ApiRequestLoggingFilterTest {
|
||||
@Test
|
||||
void binaryUploadLogs204WithoutReadingParametersOrFileContent() throws Exception {
|
||||
var filter = filter("/admin-api/component-assets/upload", RequestMethod.PUT);
|
||||
var request = spy(new MockHttpServletRequest("PUT", "/admin-api/component-assets/upload"));
|
||||
void binaryDownloadLogs200WithoutReadingParametersOrFileContent() throws Exception {
|
||||
var filter = filter("/admin-api/component-assets/**", RequestMethod.GET);
|
||||
var request = spy(new MockHttpServletRequest("GET", "/admin-api/component-assets/test.urdf"));
|
||||
request.setQueryString("objectKey=13800000001-secret-token.txt");
|
||||
request.setContent("private file content".getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
request.addHeader("X-Request-Id", "binary-log-test");
|
||||
var response = new MockHttpServletResponse();
|
||||
try (var captured = new ApiRequestLogCapture()) {
|
||||
new RequestIdFilter().doFilter(request, response, (req, res) ->
|
||||
filter.doFilter(req, res, (innerRequest, innerResponse) -> response.setStatus(204)));
|
||||
filter.doFilter(req, res, (innerRequest, innerResponse) -> response.setStatus(200)));
|
||||
|
||||
assertThat(captured.messages()).hasSize(2);
|
||||
assertThat(captured.messages().getLast()).contains("description=测试接口", "result=SUCCESS",
|
||||
"httpStatus=204", "code=HTTP_204", "requestId=binary-log-test");
|
||||
"httpStatus=200", "code=HTTP_200", "requestId=binary-log-test");
|
||||
assertThat(String.join("\n", captured.messages()))
|
||||
.doesNotContain("13800000001", "secret-token", "private file content");
|
||||
verify(request, never()).getParameter(anyString());
|
||||
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.controller.InterfacePoseController;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class InterfaceBoundaryTest {
|
||||
final ObjectMapper mapper=new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
final MechanicalInterfaceSolver solver=new MechanicalInterfaceSolver();
|
||||
final MountGeometry geometry=new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),List.of(
|
||||
new Hole("a",new double[]{-.02,0,0},new double[]{0,0,1},.004),
|
||||
new Hole("b",new double[]{.02,0,0},new double[]{0,0,1},.004)));
|
||||
final Definition definition=new Definition("two",1,"two",geometry,Tolerances.defaults());
|
||||
|
||||
@Test void endpointsRejectUnknownRotationEvenWhenGlobalJacksonIgnoresUnknownFields(){
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
InterfacePoseController controller=new InterfacePoseController(definitions,solver,mapper);
|
||||
ObjectNode request=mapper.valueToTree(new PoseRequest(1,"base",geometry,"sha"));
|
||||
request.put("mountRotationRpy",0);
|
||||
assertThatThrownBy(()->controller.candidates("two",request)).hasMessageContaining("不支持");
|
||||
verifyNoInteractions(definitions);
|
||||
}
|
||||
@Test void confirmationRecomputesTransformAndMappingFromCandidateId(){
|
||||
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
|
||||
Port submitted=new Port("port","base","two",1,geometry,
|
||||
new SelectedPose(chosen.id(),new RigidPose(new double[]{99,99,99},new double[4]),List.of(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION);
|
||||
Port confirmed=solver.confirmPortPose(definition,submitted);
|
||||
assertThat(confirmed.selectedPose().templateInLink().positionM()).containsExactly(chosen.templateInLink().positionM());
|
||||
assertThat(confirmed.selectedPose().holeMapping()).isEqualTo(chosen.holeMapping());
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
assertThatThrownBy(()->new InterfacePoseController(definitions,solver,mapper).confirm("another",mapper.valueToTree(submitted)))
|
||||
.hasMessageContaining("不一致");
|
||||
}
|
||||
@Test void confirmFlattensCascaderPathTargetsBeforeStrictPortBinding(){
|
||||
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
|
||||
ObjectNode request=mapper.valueToTree(new Port("port","base","two",1,geometry,
|
||||
new SelectedPose(chosen.id(),chosen.templateInLink(),chosen.holeMapping(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION,
|
||||
List.of("humanoid/left_arm")));
|
||||
request.set("connectableTargets",mapper.createArrayNode().add(mapper.createArrayNode().add("humanoid").add("left_arm")));
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
when(definitions.geometryDefinition("two",1)).thenReturn(definition);
|
||||
Port confirmed=new InterfacePoseController(definitions,solver,mapper).confirm("two",request).getData();
|
||||
assertThat(confirmed.connectableTargets()).containsExactly("humanoid/left_arm");
|
||||
}
|
||||
@Test void storedBytesAreVerifiedAndUnsafeStorageKeysNeverFetched() throws Exception {
|
||||
byte[] bytes="real mesh bytes".getBytes(StandardCharsets.UTF_8);
|
||||
String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
ObjectStorageClient storage=mock(ObjectStorageClient.class);
|
||||
doAnswer(invocation->{invocation.<OutputStream>getArgument(1).write(bytes);return null;}).when(storage).writeObjectTo(eq("cadworld/objects/mesh"),any());
|
||||
UrdfAssetVerifier verifier=new UrdfAssetVerifier(storage, new com.linkerbot.cadworld.service.support.StorageObjectKeys(
|
||||
new com.linkerbot.cadworld.config.StorageProperties("cadworld", null, null, null, null, java.time.Duration.ofMinutes(30))));
|
||||
ObjectNode source=mapper.createObjectNode();source.putArray("resources").addObject().put("reference","a.stl").put("sourceKey","cadworld/objects/mesh").put("sha256",hash);
|
||||
verifier.verify(source);
|
||||
((ObjectNode)source.path("resources").get(0)).put("sha256","tampered");
|
||||
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("已变化");
|
||||
clearInvocations(storage);
|
||||
for(String key:List.of("https://remote.test/a","/etc/passwd","objects/../secret","objects\\secret")) {
|
||||
((ObjectNode)source.path("resources").get(0)).put("sourceKey",key);
|
||||
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("存储对象路径非法");
|
||||
}
|
||||
verifyNoInteractions(storage);
|
||||
}
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
|
||||
public record CompleteCoverImageUploadRequest(
|
||||
@NotBlank String uploadSessionToken,
|
||||
@NotEmpty @Size(max = 1) List<@NotBlank String> objectKeys
|
||||
) {
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
public record CompleteCoverImageUploadResponse(
|
||||
String coverImageKey,
|
||||
String coverImageUrl
|
||||
) {
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
|
||||
public record CompleteUrdfUploadRequest(
|
||||
@NotBlank String uploadSessionToken,
|
||||
@NotEmpty @Size(max = 1000) List<@NotBlank String> objectKeys
|
||||
) {
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
public record CompleteUrdfUploadResponse(String source) {
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.DecimalMin;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 供拼装规划器检索的组件语义元数据。
|
||||
*
|
||||
* <p>组件的可视模型和接口仍保留在 componentJson;这里仅保存可查询的能力与尺寸,
|
||||
* 不将人体部位或机器人形态写成后端规则。</p>
|
||||
*/
|
||||
public record ComponentAssemblyMetadata(
|
||||
@NotNull List<String> tags,
|
||||
@NotNull List<String> capabilities,
|
||||
@NotNull @Valid Dimensions dimensions
|
||||
) {
|
||||
|
||||
public ComponentAssemblyMetadata {
|
||||
tags = normalize(tags);
|
||||
capabilities = normalize(capabilities);
|
||||
dimensions = dimensions == null ? Dimensions.empty() : dimensions;
|
||||
}
|
||||
|
||||
public static ComponentAssemblyMetadata empty() {
|
||||
return new ComponentAssemblyMetadata(List.of(), List.of(), Dimensions.empty());
|
||||
}
|
||||
|
||||
private static List<String> normalize(List<String> source) {
|
||||
if (source == null) {
|
||||
return List.of();
|
||||
}
|
||||
return source.stream()
|
||||
.filter(StringUtils::hasText)
|
||||
.map(String::trim)
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
|
||||
public record Dimensions(
|
||||
@DecimalMin(value = "0.0", inclusive = false) BigDecimal lengthMm,
|
||||
@DecimalMin(value = "0.0", inclusive = false) BigDecimal widthMm,
|
||||
@DecimalMin(value = "0.0", inclusive = false) BigDecimal heightMm
|
||||
) {
|
||||
public static Dimensions empty() {
|
||||
return new Dimensions(null, null, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** 新增和全量修改共用的表单字段。 */
|
||||
public interface ComponentForm {
|
||||
String componentName();
|
||||
String category();
|
||||
String manufacturer();
|
||||
String description();
|
||||
String material();
|
||||
BigDecimal massKg();
|
||||
BigDecimal lengthMm();
|
||||
BigDecimal widthMm();
|
||||
BigDecimal heightMm();
|
||||
List<String> tags();
|
||||
List<CustomField> basicFields();
|
||||
List<CustomField> parameterFields();
|
||||
}
|
||||
+5
-19
@@ -1,24 +1,10 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
public record ComponentListItemResponse(
|
||||
Long id,
|
||||
String componentName,
|
||||
String category,
|
||||
String robotType,
|
||||
String company,
|
||||
String model,
|
||||
String source,
|
||||
String sourceUrl,
|
||||
String coverImageUrl,
|
||||
String description,
|
||||
ComponentAssemblyMetadata assemblyMetadata,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
|
||||
public String componentType() {
|
||||
return category;
|
||||
}
|
||||
}
|
||||
Long id, String componentCode, String componentName, String category, String manufacturer,
|
||||
String description, List<String> tags, String stepUrl, String urdfUrl, Long version,
|
||||
LocalDateTime createdAt, LocalDateTime updatedAt
|
||||
) { }
|
||||
|
||||
+9
-22
@@ -1,27 +1,14 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
public record ComponentResponse(
|
||||
Long id,
|
||||
String componentName,
|
||||
String category,
|
||||
String robotType,
|
||||
String company,
|
||||
String model,
|
||||
String source,
|
||||
String sourceUrl,
|
||||
String coverImageKey,
|
||||
String coverImageUrl,
|
||||
String description,
|
||||
JsonNode componentJson,
|
||||
ComponentAssemblyMetadata assemblyMetadata,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
|
||||
public String componentType() {
|
||||
return category;
|
||||
}
|
||||
}
|
||||
Long id, String componentCode, String componentName, String category, String manufacturer,
|
||||
String description, String material, BigDecimal massKg, BigDecimal lengthMm, BigDecimal widthMm,
|
||||
BigDecimal heightMm, List<String> tags, List<CustomField> basicFields, List<CustomField> parameterFields,
|
||||
String stepObjectKey, String stepUrl, String urdfPrefix, String urdfBaseUrl,
|
||||
String urdfMainObjectKey, String urdfUrl, List<UrdfFile> urdfFiles, Long version,
|
||||
LocalDateTime createdAt, LocalDateTime updatedAt
|
||||
) { }
|
||||
|
||||
+20
-22
@@ -1,28 +1,26 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
public record CreateComponentRequest(
|
||||
@NotBlank @Size(max = 64) String componentName,
|
||||
@Size(max = 64) String category,
|
||||
@NotBlank @Size(max = 32) String robotType,
|
||||
@NotBlank @Size(max = 64) String company,
|
||||
@NotBlank @Size(max = 64) String model,
|
||||
@NotBlank @Size(max = 255) String source,
|
||||
@Size(max = 512) String coverImageKey,
|
||||
@NotBlank @Size(max = 128) String componentName,
|
||||
@NotBlank @Size(max = 64) String category,
|
||||
@Size(max = 128) String manufacturer,
|
||||
String description,
|
||||
@NotNull JsonNode componentJson,
|
||||
@NotNull @jakarta.validation.Valid ComponentAssemblyMetadata assemblyMetadata
|
||||
) {
|
||||
|
||||
/** Compatibility constructor used by existing service tests and old callers. */
|
||||
public CreateComponentRequest(String componentName, String componentType, String robotType, String company,
|
||||
String model, String source, String coverImageKey, String description,
|
||||
JsonNode componentJson) {
|
||||
this(componentName, componentType, robotType, company, model, source, coverImageKey, description,
|
||||
componentJson, ComponentAssemblyMetadata.empty());
|
||||
}
|
||||
@Size(max = 128) String material,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal massKg,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal lengthMm,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal widthMm,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal heightMm,
|
||||
List<@NotNull String> tags,
|
||||
@Size(max = 100) List<@NotNull @Valid CustomField> basicFields,
|
||||
@Size(max = 100) List<@NotNull @Valid CustomField> parameterFields,
|
||||
@NotBlank @Size(max = 4096) String uploadSessionToken,
|
||||
@NotBlank @Size(max = 512) String stepObjectKey,
|
||||
@NotEmpty @Size(max = 1000) List<@NotBlank @Size(max = 512) String> urdfObjectKeys
|
||||
) implements ComponentForm {
|
||||
@Override public String toString() { return "CreateComponentRequest[redacted]"; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record CustomField(@NotBlank @Size(max = 64) String name,
|
||||
@NotNull @Size(max = 2000) String value) { }
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
public record PrepareCoverImageUploadSessionResponse(
|
||||
String uploadSessionToken,
|
||||
String keyPrefix
|
||||
) {
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record PrepareObjectUploadUrlRequest(
|
||||
@NotBlank String uploadSessionToken,
|
||||
@NotBlank @Size(max = 512) String objectPath,
|
||||
@Size(max = 255) String contentType
|
||||
) {
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record PrepareObjectUploadUrlResponse(
|
||||
String uploadUrl,
|
||||
String objectKey,
|
||||
Map<String, String> uploadHeaders
|
||||
) {
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
public record PrepareUrdfUploadSessionResponse(
|
||||
String uploadSessionToken,
|
||||
String keyPrefix
|
||||
) {
|
||||
}
|
||||
+22
-21
@@ -1,27 +1,28 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
public record UpdateComponentRequest(
|
||||
@NotBlank @Size(max = 64) String componentName,
|
||||
@Size(max = 64) String category,
|
||||
@NotBlank @Size(max = 32) String robotType,
|
||||
@NotBlank @Size(max = 64) String company,
|
||||
@NotBlank @Size(max = 64) String model,
|
||||
@NotBlank @Size(max = 255) String source,
|
||||
@Size(max = 512) String coverImageKey,
|
||||
@Size(max = 64) String componentCode,
|
||||
@NotBlank @Size(max = 128) String componentName,
|
||||
@NotBlank @Size(max = 64) String category,
|
||||
@Size(max = 128) String manufacturer,
|
||||
String description,
|
||||
@NotNull JsonNode componentJson,
|
||||
@NotNull @jakarta.validation.Valid ComponentAssemblyMetadata assemblyMetadata
|
||||
) {
|
||||
|
||||
public UpdateComponentRequest(String componentName, String componentType, String robotType, String company,
|
||||
String model, String source, String coverImageKey, String description,
|
||||
JsonNode componentJson) {
|
||||
this(componentName, componentType, robotType, company, model, source, coverImageKey, description,
|
||||
componentJson, ComponentAssemblyMetadata.empty());
|
||||
}
|
||||
@Size(max = 128) String material,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal massKg,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal lengthMm,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal widthMm,
|
||||
@DecimalMin("0") @Digits(integer = 12, fraction = 6) BigDecimal heightMm,
|
||||
List<@NotNull String> tags,
|
||||
@Size(max = 100) List<@NotNull @Valid CustomField> basicFields,
|
||||
@Size(max = 100) List<@NotNull @Valid CustomField> parameterFields,
|
||||
@NotNull @Min(1) @Max(4294967295L) Long version,
|
||||
@Size(max = 4096) String uploadSessionToken,
|
||||
@Size(max = 512) String stepObjectKey,
|
||||
@Size(min = 1, max = 1000) List<@NotBlank @Size(max = 512) String> urdfObjectKeys
|
||||
) implements ComponentForm {
|
||||
@Override public String toString() { return "UpdateComponentRequest[redacted]"; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.linkerbot.cadworld.dto.component;
|
||||
|
||||
public record UrdfFile(String relativePath, long sizeBytes) { }
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.linkerbot.cadworld.dto.storage;
|
||||
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record UploadSignatureRequest(@Positive Long componentId,
|
||||
@Size(max = 4096) String uploadSessionToken) {
|
||||
@Override public String toString() { return "UploadSignatureRequest[componentId=" + componentId + "]"; }
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.linkerbot.cadworld.dto.storage;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
public record UploadSignatureResponse(String componentCode, String uploadSessionToken,
|
||||
Instant sessionExpiresAt, Instant expiresAt,
|
||||
UploadAuthorization step, UploadAuthorization urdf) {
|
||||
public record UploadAuthorization(String uploadUrl, String keyPrefix,
|
||||
Map<String, String> uploadFields, String uploadMethod) {
|
||||
public UploadAuthorization { uploadFields = Map.copyOf(uploadFields); }
|
||||
@Override public String toString() { return "UploadAuthorization[uploadMethod=" + uploadMethod + "]"; }
|
||||
}
|
||||
@Override public String toString() { return "UploadSignatureResponse[expiresAt=" + expiresAt + "]"; }
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
package com.linkerbot.cadworld.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
|
||||
import java.math.BigDecimal;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@@ -13,42 +11,28 @@ import lombok.Setter;
|
||||
@Setter
|
||||
@TableName(value = "component", autoResultMap = true)
|
||||
public class Component extends BaseEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String componentCode;
|
||||
private String componentName;
|
||||
|
||||
/** Free-form catalog category. It is not a robot body slot or an execution rule. */
|
||||
private String category;
|
||||
|
||||
private String robotType;
|
||||
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||
private JsonNode assemblyMetadata;
|
||||
|
||||
private String company;
|
||||
|
||||
private String model;
|
||||
|
||||
private String source;
|
||||
|
||||
private String coverImageKey;
|
||||
|
||||
private String manufacturer;
|
||||
private String description;
|
||||
|
||||
private String material;
|
||||
private BigDecimal massKg;
|
||||
private BigDecimal lengthMm;
|
||||
private BigDecimal widthMm;
|
||||
private BigDecimal heightMm;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||
private JsonNode componentJson;
|
||||
|
||||
/**
|
||||
* Transitional accessors keep historical read-only code compiling while all persisted data uses
|
||||
* the free-form {@code category} column.
|
||||
*/
|
||||
public String getComponentType() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setComponentType(String componentType) {
|
||||
this.category = componentType;
|
||||
}
|
||||
private JsonNode tags;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||
private JsonNode basicFields;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||
private JsonNode parameterFields;
|
||||
private String stepObjectKey;
|
||||
private String urdfPrefix;
|
||||
private String urdfMainObjectKey;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class)
|
||||
private JsonNode urdfFiles;
|
||||
private Long version;
|
||||
}
|
||||
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.linkerbot.cadworld.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter @Setter
|
||||
@TableName(value = "interface_definition_v2", autoResultMap = true)
|
||||
public class InterfaceDefinitionEntity extends BaseEntity {
|
||||
@TableId private String id;
|
||||
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;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode displayForwardJson;
|
||||
private String sourceAssetKey;
|
||||
private String sourceGeometryHash;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package com.linkerbot.cadworld.entity;
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
@Getter @Setter
|
||||
@TableName(value = "interface_definition_revision", autoResultMap = true)
|
||||
public class InterfaceDefinitionRevisionEntity {
|
||||
@TableId private String id;
|
||||
private String definitionId;
|
||||
private Integer geometryRevision;
|
||||
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode definitionJson;
|
||||
}
|
||||
@@ -13,18 +13,22 @@ import lombok.Setter;
|
||||
public class OperationLog {
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String module;
|
||||
private String action;
|
||||
private String targetId;
|
||||
private Long operatorId;
|
||||
private String operatorName;
|
||||
private String requestPath;
|
||||
private String requestMethod;
|
||||
private String clientIp;
|
||||
private String requestId;
|
||||
private String module = "";
|
||||
private String action = "";
|
||||
private String targetType = "";
|
||||
private String targetId = "";
|
||||
private String targetCode = "";
|
||||
private String targetName = "";
|
||||
private Long operatorId = 0L;
|
||||
private String operatorName = "";
|
||||
private String requestPath = "";
|
||||
private String requestMethod = "";
|
||||
private String clientIp = "";
|
||||
private String requestId = "";
|
||||
private LocalDateTime operatedAt;
|
||||
private Long durationMs;
|
||||
private Boolean success;
|
||||
private Integer httpStatus;
|
||||
private String errorSummary;
|
||||
private Long durationMs = 0L;
|
||||
private Boolean success = false;
|
||||
private Integer httpStatus = 0;
|
||||
private String errorCode = "";
|
||||
private String errorSummary = "";
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.linkerbot.cadworld.enums;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public enum ComponentUploadType {
|
||||
|
||||
URDF("component-urdf-upload"),
|
||||
COVER_IMAGE("component-cover-image-upload");
|
||||
|
||||
private final String tokenType;
|
||||
|
||||
ComponentUploadType(String tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public String tokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public static ComponentUploadType fromTokenType(String tokenType) {
|
||||
return Arrays.stream(values())
|
||||
.filter(value -> value.tokenType.equals(tokenType))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalArgumentException("Invalid upload session token type"));
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
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 {
|
||||
private InterfaceGeometry() {}
|
||||
public static final String SOLVER_VERSION = "mount-geometry-3";
|
||||
public record RigidPose(double[] positionM, double[] quaternionXYZW) {}
|
||||
public record Plane(double[] pointM, double[] outwardNormal) {}
|
||||
public record Hole(String id, double[] pointOnPlaneM, double[] axis, Double diameterM) {}
|
||||
public record MountGeometry(Plane plane, List<Hole> holes) {}
|
||||
public record Tolerances(double positionM, double axisAngleRad, double planeAngleRad) {
|
||||
public static Tolerances defaults() { return new Tolerances(0.0002, Math.PI / 180, Math.PI / 180); }
|
||||
}
|
||||
public record Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances,
|
||||
List<String> connectableTargets, double[] displayForward) {
|
||||
public Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances,
|
||||
List<String> connectableTargets) {
|
||||
this(id, geometryRevision, name, geometry, tolerances, connectableTargets, null);
|
||||
}
|
||||
public Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances) {
|
||||
this(id, geometryRevision, name, geometry, tolerances, List.of());
|
||||
}
|
||||
}
|
||||
public record HoleMapping(String templateHoleId, String observedHoleId) {}
|
||||
/** Display reference mapped through the selected pose into the owning link frame. */
|
||||
public record SelectedPose(String id, RigidPose templateInLink, List<HoleMapping> holeMapping,
|
||||
double[] orientationDirectionInLink) {}
|
||||
public record Port(String id, String linkName, String definitionId, int definitionRevision,
|
||||
MountGeometry geometryInLink, SelectedPose selectedPose,
|
||||
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) {
|
||||
this(id, linkName, definitionId, definitionRevision, geometryInLink, selectedPose,
|
||||
sourceGeometryHash, solverVersion, List.of());
|
||||
}
|
||||
}
|
||||
public record PoseRequest(int definitionRevision, String linkName, MountGeometry geometryInLink, String sourceGeometryHash) {}
|
||||
public record PoseCandidate(String id, RigidPose templateInLink, List<HoleMapping> holeMapping,
|
||||
double[] orientationDirectionInLink, int registrationSide,
|
||||
double maxHoleOffsetM, double rmsHoleOffsetM, double maxAxisAngleRad) {}
|
||||
public record CandidateSet(String solverVersion, List<PoseCandidate> candidates, List<String> reasons) {}
|
||||
public record HolePair(String parentHoleId, String childHoleId) {}
|
||||
public record ResolvedConnection(String parentLinkName, String childLinkName, RigidPose childLinkInParentLink,
|
||||
List<HolePair> holePairs, double maxHoleOffsetM, double maxAxisAngleRad,
|
||||
double planeOffsetM, double orientationAngleRad) {}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.linkerbot.cadworld.common.api;
|
||||
|
||||
/** 请求内的业务对象快照,由业务层提供,审计层只读取通用字段。 */
|
||||
public final class OperationTargetHolder {
|
||||
private static final ThreadLocal<Target> CURRENT = new ThreadLocal<>();
|
||||
private OperationTargetHolder() { }
|
||||
public static void set(String type, String id, String code, String name) {
|
||||
CURRENT.set(new Target(type, id, code, name));
|
||||
}
|
||||
public static Target get() { return CURRENT.get(); }
|
||||
public static void clear() { CURRENT.remove(); }
|
||||
public record Target(String type, String id, String code, String name) { }
|
||||
}
|
||||
+13
-2
@@ -1,6 +1,8 @@
|
||||
package com.linkerbot.cadworld.common.exception;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.ApiCode;
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
@@ -108,7 +110,7 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler({CannotCreateTransactionException.class, DataAccessResourceFailureException.class})
|
||||
public ResponseEntity<ApiResponse<Void>> handleDatabaseUnavailable(Exception exception, HttpServletRequest request) {
|
||||
request.setAttribute("cadworld.operationError", "数据库暂不可用");
|
||||
log.error("Database is unavailable", exception);
|
||||
logFailure("数据库不可用", exception, request);
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(ApiResponse.failure(ApiCode.DATABASE_UNAVAILABLE, "数据库暂不可用,请检查数据库连接配置后重试"));
|
||||
}
|
||||
@@ -126,8 +128,17 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleUnknown(Exception exception, HttpServletRequest request) {
|
||||
request.setAttribute("cadworld.operationError", "系统异常");
|
||||
log.error("Unhandled exception at {} {}", request.getMethod(), request.getRequestURI(), exception);
|
||||
logFailure("请求处理异常", exception, request);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(ApiResponse.failure(ApiCode.INTERNAL_ERROR, "系统异常"));
|
||||
}
|
||||
private void logFailure(String description, Exception exception, HttpServletRequest request) {
|
||||
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
String location = java.util.Arrays.stream(exception.getStackTrace()).limit(3)
|
||||
.map(StackTraceElement::toString).collect(Collectors.joining(" <- "));
|
||||
log.error("{} method={} path={} requestId={} exceptionType={} location={}", description,
|
||||
request.getMethod(), pattern == null ? "<unmatched>" : pattern,
|
||||
RequestIdHolder.get(), exception.getClass().getSimpleName(), location);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.linkerbot.cadworld.common.process;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** No shell interpretation; bounded output, deadline and cancellation apply to the whole process tree. */
|
||||
public class ToolProcess {
|
||||
public record Result(int exitCode,String output,boolean timedOut) {}
|
||||
public Result run(List<String> command,Path directory,Duration timeout) throws IOException,InterruptedException {
|
||||
ProcessBuilder builder=new ProcessBuilder(command).directory(directory.toFile()).redirectErrorStream(true);
|
||||
builder.environment().put("LC_ALL","C");builder.environment().put("PYTHONUTF8","1");builder.environment().put("PYTHONDONTWRITEBYTECODE","1");
|
||||
Process process=builder.start();StringBuilder output=new StringBuilder();
|
||||
Thread reader=Thread.ofPlatform().daemon().start(()->{
|
||||
try(Reader in=new InputStreamReader(process.getInputStream(),java.nio.charset.StandardCharsets.UTF_8)) {
|
||||
char[] chars=new char[2048];int n;
|
||||
while((n=in.read(chars))!=-1) synchronized(output){if(output.length()<65536)output.append(chars,0,Math.min(n,65536-output.length()));}
|
||||
}catch(IOException ignored) { /* Cancellation closes the pipe. */ }
|
||||
});
|
||||
try {
|
||||
boolean finished=process.waitFor(timeout.toMillis(),TimeUnit.MILLISECONDS);
|
||||
if(!finished)kill(process);
|
||||
reader.join(1000);
|
||||
synchronized(output){return new Result(finished?process.exitValue():-1,output.toString(),!finished);}
|
||||
} finally {if(process.isAlive())kill(process);}
|
||||
}
|
||||
private static void kill(Process process) {process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.linkerbot.cadworld.config;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Validated
|
||||
@ConfigurationProperties(prefix = "app.interface-brep")
|
||||
public record InterfaceBrepProperties(
|
||||
@NotBlank String python,
|
||||
@NotBlank String script,
|
||||
@Min(1) @Max(600) int timeoutSeconds,
|
||||
@Min(1) long maxUploadBytes,
|
||||
@Min(1) long maxOutputBytes
|
||||
) {
|
||||
}
|
||||
+3
-14
@@ -2,24 +2,13 @@ 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(
|
||||
@DefaultValue("cadworld") String rootPrefix,
|
||||
String urdfPrefix,
|
||||
String coverImagePrefix,
|
||||
String publicBaseUrl,
|
||||
String publicApiBaseUrl,
|
||||
Duration uploadSessionTtl,
|
||||
@DefaultValue("PT30M") Duration uploadSessionTtl,
|
||||
@DefaultValue("PT5M") Duration uploadSignatureTtl,
|
||||
@DefaultValue("104857600") long maxUploadBytes
|
||||
) {
|
||||
@ConstructorBinding
|
||||
public StorageProperties { }
|
||||
|
||||
public StorageProperties(String rootPrefix, String urdfPrefix, String coverImagePrefix,
|
||||
String publicBaseUrl, String publicApiBaseUrl, Duration uploadSessionTtl) {
|
||||
this(rootPrefix, urdfPrefix, coverImagePrefix, publicBaseUrl, publicApiBaseUrl, uploadSessionTtl, 104857600L);
|
||||
}
|
||||
}
|
||||
) { }
|
||||
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
package com.linkerbot.cadworld.mapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.cadworld.entity.InterfaceDefinitionEntity;
|
||||
public interface InterfaceDefinitionMapper extends BaseMapper<InterfaceDefinitionEntity> {}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package com.linkerbot.cadworld.mapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.linkerbot.cadworld.entity.InterfaceDefinitionRevisionEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
@Mapper
|
||||
public interface InterfaceDefinitionRevisionMapper extends BaseMapper<InterfaceDefinitionRevisionEntity> {}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
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
|
||||
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("接口必须是数组");
|
||||
|
||||
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);
|
||||
return result;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private String rootMessage(Throwable error) {
|
||||
Throwable current = error;
|
||||
while (current.getCause() != null) current = current.getCause();
|
||||
return current.getMessage() == null ? "字段格式错误" : current.getMessage();
|
||||
}
|
||||
}
|
||||
-305
@@ -1,305 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.RigidMath.*;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** The single authority for registering, confirming and connecting physical ports. */
|
||||
@Service
|
||||
public class MechanicalInterfaceSolver {
|
||||
private record Match(int[] indices, double maximum, double rms, double axisMaximum) {}
|
||||
|
||||
public void validateDefinition(Definition definition) {
|
||||
if (definition == null || blank(definition.id()) || blank(definition.name()) || definition.geometryRevision() < 1)
|
||||
throw new IllegalArgumentException("接口定义或几何修订不合法");
|
||||
tolerances(definition.tolerances());
|
||||
normalize(definition.geometry(), definition.tolerances());
|
||||
displayForward(definition);
|
||||
}
|
||||
|
||||
/** Display metadata only; never enters pose enumeration or the connection transform. */
|
||||
public double[] displayForward(Definition definition) {
|
||||
double[] normal = unit(definition.geometry().plane().outwardNormal());
|
||||
double[] direction = definition.displayForward();
|
||||
if (direction == null) {
|
||||
for (double[] axis : new double[][]{{1,0,0},{0,1,0},{0,0,1}}) {
|
||||
double[] tangent = sub(axis,scale(normal,dot(axis,normal)));
|
||||
if (norm(tangent)>1e-6) return unit(tangent);
|
||||
}
|
||||
}
|
||||
direction = unit(direction);
|
||||
if (Math.abs(dot(direction,normal))>1e-6)
|
||||
throw new IllegalArgumentException("默认前方必须位于安装面内");
|
||||
return direction;
|
||||
}
|
||||
|
||||
public CandidateSet enumeratePortPoses(Definition definition, PoseRequest request) {
|
||||
validateDefinition(definition);
|
||||
if (request == null || request.definitionRevision() != definition.geometryRevision())
|
||||
throw new IllegalArgumentException("接口几何修订已变化,请重新识别");
|
||||
if (blank(request.linkName()) || blank(request.sourceGeometryHash()))
|
||||
throw new IllegalArgumentException("缺少所属 link 或源几何哈希");
|
||||
MountGeometry source = normalize(definition.geometry(), definition.tolerances());
|
||||
MountGeometry target = normalize(request.geometryInLink(), definition.tolerances());
|
||||
if (source.holes().size() != target.holes().size())
|
||||
return rejected("接口需要 " + source.holes().size() + " 个孔,实测 " + target.holes().size() + " 个孔;必须确认完整孔组");
|
||||
String fingerprint = definition.id() + ':' + definition.geometryRevision() + ':' + request.linkName() + ':'
|
||||
+ request.sourceGeometryHash() + ':' + fingerprint(source) + ':' + fingerprint(target);
|
||||
List<PoseCandidate> candidates = enumerate(source, target, definition.tolerances(), 1, fingerprint);
|
||||
if (candidates.isEmpty()) candidates = enumerate(source, target, definition.tolerances(), -1, fingerprint);
|
||||
return candidates.isEmpty() ? rejectionDetails(source, target, definition.tolerances())
|
||||
: new CandidateSet(SOLVER_VERSION, candidates.stream().map(candidate -> new PoseCandidate(
|
||||
candidate.id(), candidate.templateInLink(), candidate.holeMapping(),
|
||||
rotate(rotation(candidate.templateInLink()), displayForward(definition)),
|
||||
candidate.registrationSide(), candidate.maxHoleOffsetM(), candidate.rmsHoleOffsetM(),
|
||||
candidate.maxAxisAngleRad())).toList(), List.of());
|
||||
}
|
||||
|
||||
/** Necessary rigid invariants identify problematic evidence without guessing a replacement pose. */
|
||||
private CandidateSet rejectionDetails(MountGeometry source, MountGeometry target, Tolerances tolerance) {
|
||||
List<String> reasons = new ArrayList<>();
|
||||
for (Hole observed : target.holes()) {
|
||||
double tilt = angle(observed.axis(), target.plane().outwardNormal(), true);
|
||||
boolean axisPossible = source.holes().stream().anyMatch(h ->
|
||||
Math.abs(tilt - angle(h.axis(), source.plane().outwardNormal(), true))
|
||||
<= tolerance.axisAngleRad() + tolerance.planeAngleRad() + 1e-10);
|
||||
if (!axisPossible) reasons.add("孔 " + observed.id() + " 的孔轴与安装面夹角不符合模板,请核对孔轴或向外法向");
|
||||
double[] distances = target.holes().stream().mapToDouble(h -> norm(sub(h.pointOnPlaneM(), observed.pointOnPlaneM()))).sorted().toArray();
|
||||
boolean distancesPossible = source.holes().stream().anyMatch(anchor -> {
|
||||
double[] expected = source.holes().stream().mapToDouble(h -> norm(sub(h.pointOnPlaneM(), anchor.pointOnPlaneM()))).sorted().toArray();
|
||||
for (int i = 0; i < expected.length; i++)
|
||||
if (Math.abs(expected[i] - distances[i]) > 2 * tolerance.positionM() + 1e-10) return false;
|
||||
return true;
|
||||
});
|
||||
if (!distancesPossible) reasons.add("孔 " + observed.id() + " 的孔距组合与模板不符,请核对该孔及完整孔组");
|
||||
}
|
||||
if (reasons.isEmpty()) reasons.add("孔组 " + target.holes().stream().map(Hole::id).toList()
|
||||
+ " 未找到满足全部孔位、孔轴及安装面约束的一一对应;请返回几何确认");
|
||||
return new CandidateSet(SOLVER_VERSION, List.of(), List.copyOf(reasons));
|
||||
}
|
||||
|
||||
public Port confirmPortPose(Definition definition, Port submitted) {
|
||||
if (submitted == null || blank(submitted.id()) || submitted.selectedPose() == null
|
||||
|| !definition.id().equals(submitted.definitionId())
|
||||
|| !SOLVER_VERSION.equals(submitted.solverVersion()))
|
||||
throw new IllegalArgumentException("不支持的接口结构,请重新识别并确认安装姿态");
|
||||
CandidateSet result = enumeratePortPoses(definition, new PoseRequest(submitted.definitionRevision(),
|
||||
submitted.linkName(), submitted.geometryInLink(), submitted.sourceGeometryHash()));
|
||||
PoseCandidate chosen = result.candidates().stream().filter(p -> p.id().equals(submitted.selectedPose().id()))
|
||||
.findFirst().orElseThrow(() -> new IllegalArgumentException("保存的安装姿态已失效,请重新选择"));
|
||||
// Never trust a caller-provided quaternion or hole mapping.
|
||||
List<String> targets = submitted.connectableTargets() == null || submitted.connectableTargets().isEmpty()
|
||||
? normalizeTargets(definition.connectableTargets()) : normalizeTargets(submitted.connectableTargets());
|
||||
return new Port(submitted.id(), submitted.linkName(), definition.id(), definition.geometryRevision(),
|
||||
normalize(submitted.geometryInLink(), definition.tolerances()),
|
||||
new SelectedPose(chosen.id(), chosen.templateInLink(), chosen.holeMapping(), chosen.orientationDirectionInLink()),
|
||||
submitted.sourceGeometryHash(), SOLVER_VERSION, targets);
|
||||
}
|
||||
|
||||
private List<String> normalizeTargets(List<String> values) {
|
||||
if (values == null) return List.of();
|
||||
return values.stream().filter(Objects::nonNull).map(String::trim).filter(value -> !value.isEmpty()).distinct().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves only the rigid transform implied by the saved port poses. When
|
||||
* a hole pattern has multiple equivalent mating bases, the base is chosen
|
||||
* by the saved in-plane forward references; a connection is rejected if no
|
||||
* valid base makes those references point in the same direction.
|
||||
*/
|
||||
public ResolvedConnection resolveLockedConnection(Definition definition, Port parentInput, Port childInput) {
|
||||
Port parent = confirmPortPose(definition, parentInput);
|
||||
Port child = confirmPortPose(definition, childInput);
|
||||
double[] templateNormal = unit(definition.geometry().plane().outwardNormal());
|
||||
int parentSide = side(parent, templateNormal), childSide = side(child, templateNormal);
|
||||
List<RigidPose> mateCandidates = List.of(identity());
|
||||
if (parentSide == childSide) {
|
||||
MountGeometry template = normalize(definition.geometry(), definition.tolerances());
|
||||
List<PoseCandidate> flipped = enumerate(template, template, definition.tolerances(), -1, definition.id());
|
||||
if (flipped.isEmpty()) throw new IllegalArgumentException("该孔阵的两侧没有合法对接基准,不能镜像或补偿旋转");
|
||||
// A symmetric hole pattern can have several valid 180-degree
|
||||
// mating bases. Prefer the one that keeps the two display-forward
|
||||
// references pointing in the same direction after mating. The
|
||||
// selected component poses remain authoritative; this only picks
|
||||
// the geometrically equivalent hole mapping for the connection.
|
||||
mateCandidates = flipped.stream().map(PoseCandidate::templateInLink).toList();
|
||||
}
|
||||
MountGeometry a = parent.geometryInLink(), b = child.geometryInLink();
|
||||
Tolerances tolerance = definition.tolerances();
|
||||
RigidPose transform = null;
|
||||
Match match = null;
|
||||
double planeOffset = 0;
|
||||
double orientationError = Double.POSITIVE_INFINITY;
|
||||
for (RigidPose mate : mateCandidates) {
|
||||
RigidPose candidateTransform = compose(compose(parent.selectedPose().templateInLink(), mate),
|
||||
inverse(child.selectedPose().templateInLink()));
|
||||
double normalError = angle(a.plane().outwardNormal(),
|
||||
scale(rotate(rotation(candidateTransform), b.plane().outwardNormal()), -1), false);
|
||||
double candidatePlaneOffset = Math.abs(dot(sub(point(candidateTransform,b.plane().pointM()), a.plane().pointM()),
|
||||
unit(a.plane().outwardNormal())));
|
||||
Match candidateMatch = assignment(b.holes(), a.holes(), candidateTransform, tolerance, 1);
|
||||
if (normalError > tolerance.planeAngleRad() + 1e-10
|
||||
|| candidatePlaneOffset > tolerance.positionM() + 1e-10 || candidateMatch == null) continue;
|
||||
double candidateOrientationError = angle(parent.selectedPose().orientationDirectionInLink(),
|
||||
rotate(rotation(candidateTransform), child.selectedPose().orientationDirectionInLink()), false);
|
||||
if (transform == null || candidateOrientationError < orientationError) {
|
||||
transform = candidateTransform;
|
||||
match = candidateMatch;
|
||||
planeOffset = candidatePlaneOffset;
|
||||
orientationError = candidateOrientationError;
|
||||
}
|
||||
}
|
||||
if (transform == null || match == null)
|
||||
throw new IllegalArgumentException("已保存姿态无法使安装面和全部实测孔对齐,请在组件管理中重新确认");
|
||||
if (orientationError > tolerance.planeAngleRad() + 1e-10)
|
||||
throw new IllegalArgumentException("已保存姿态的橙色前方方向无法同向,请在组件管理中重新选择安装姿态");
|
||||
List<HolePair> pairs = new ArrayList<>();
|
||||
for (int i=0;i<b.holes().size();i++) pairs.add(new HolePair(a.holes().get(match.indices()[i]).id(), b.holes().get(i).id()));
|
||||
return new ResolvedConnection(parent.linkName(),child.linkName(),transform,List.copyOf(pairs),
|
||||
match.maximum(),match.axisMaximum(),planeOffset,orientationError);
|
||||
}
|
||||
|
||||
private int side(Port port,double[] templateNormal) {
|
||||
return dot(rotate(rotation(port.selectedPose().templateInLink()),templateNormal),
|
||||
unit(port.geometryInLink().plane().outwardNormal())) >= 0 ? 1 : -1;
|
||||
}
|
||||
|
||||
private List<PoseCandidate> enumerate(MountGeometry source, MountGeometry target, Tolerances tolerance,
|
||||
int side, String fingerprint) {
|
||||
List<Hole> s=source.holes(), t=target.holes();
|
||||
if(s.size()!=t.size())return List.of();
|
||||
// A well-separated anchor pair avoids unstable angle estimates for close holes.
|
||||
int first=0, second=1; double span=0;
|
||||
for(int i=0;i<s.size();i++)for(int j=i+1;j<s.size();j++){
|
||||
double distance=norm(sub(s.get(j).pointOnPlaneM(),s.get(i).pointOnPlaneM()));
|
||||
if(distance>span){span=distance;first=i;second=j;}
|
||||
}
|
||||
double[] sourceBasis=basis(source.plane().outwardNormal(),sub(s.get(second).pointOnPlaneM(),s.get(first).pointOnPlaneM()));
|
||||
double[] targetNormal=scale(target.plane().outwardNormal(),side);
|
||||
Map<String,PoseCandidate> mappings=new TreeMap<>();
|
||||
for(int i=0;i<t.size();i++)for(int j=0;j<t.size();j++){
|
||||
if(i==j)continue;
|
||||
double[] direction=sub(t.get(j).pointOnPlaneM(),t.get(i).pointOnPlaneM());
|
||||
if(Math.abs(norm(direction)-span)>2*tolerance.positionM()+1e-10)continue;
|
||||
double[] r=multiply(basis(targetNormal,direction),transpose(sourceBasis));
|
||||
RigidPose pose=pose(sub(t.get(i).pointOnPlaneM(),rotate(r,s.get(first).pointOnPlaneM())),r);
|
||||
Match rough=assignment(s,t,pose,tolerance,4);
|
||||
if(rough==null)continue;
|
||||
for(int iteration=0;iteration<3;iteration++){
|
||||
pose=refine(s,t,rough.indices(),pose,targetNormal);
|
||||
Match next=assignment(s,t,pose,tolerance,4);
|
||||
if(next==null)break;
|
||||
rough=next;
|
||||
}
|
||||
Match match=assignment(s,t,pose,tolerance,1);
|
||||
if(match==null)continue;
|
||||
double offset=Math.abs(dot(sub(point(pose,source.plane().pointM()),target.plane().pointM()),unit(targetNormal)));
|
||||
if(offset>tolerance.positionM()+1e-10)continue;
|
||||
List<HoleMapping> mapping=new ArrayList<>();
|
||||
StringJoiner key=new StringJoiner("|");
|
||||
for(int k=0;k<s.size();k++){
|
||||
String targetId=t.get(match.indices()[k]).id();
|
||||
mapping.add(new HoleMapping(s.get(k).id(),targetId));key.add(s.get(k).id()+"="+targetId);
|
||||
}
|
||||
double[] orientationDirection = unit(sub(
|
||||
t.get(match.indices()[second]).pointOnPlaneM(),
|
||||
t.get(match.indices()[first]).pointOnPlaneM()));
|
||||
String mapKey=key.toString();
|
||||
PoseCandidate candidate=new PoseCandidate(hash(SOLVER_VERSION+':'+fingerprint+':'+side+':'+mapKey),pose,
|
||||
List.copyOf(mapping),orientationDirection,side,match.maximum(),match.rms(),match.axisMaximum());
|
||||
PoseCandidate old=mappings.get(mapKey);
|
||||
if(old==null||candidate.maxHoleOffsetM()<old.maxHoleOffsetM())mappings.put(mapKey,candidate);
|
||||
}
|
||||
List<PoseCandidate> unique=new ArrayList<>();
|
||||
for(PoseCandidate candidate:mappings.values()){
|
||||
boolean duplicate=unique.stream().anyMatch(old -> samePose(old.templateInLink(),candidate.templateInLink()));
|
||||
if(!duplicate)unique.add(candidate);
|
||||
}
|
||||
return List.copyOf(unique);
|
||||
}
|
||||
|
||||
private RigidPose refine(List<Hole> s,List<Hole> t,int[] indices,RigidPose current,double[] normal){
|
||||
double[] sc=new double[3],tc=new double[3];
|
||||
for(int i=0;i<s.size();i++){sc=add(sc,s.get(i).pointOnPlaneM());tc=add(tc,t.get(indices[i]).pointOnPlaneM());}
|
||||
sc=scale(sc,1.0/s.size());tc=scale(tc,1.0/s.size());
|
||||
double[] r=rotation(current);double cosine=0,sine=0;
|
||||
for(int i=0;i<s.size();i++){
|
||||
double[] a=rotate(r,sub(s.get(i).pointOnPlaneM(),sc)),b=sub(t.get(indices[i]).pointOnPlaneM(),tc);
|
||||
cosine+=dot(a,b);sine+=dot(unit(normal),cross(a,b));
|
||||
}
|
||||
r=multiply(rotationAxis(normal,Math.atan2(sine,cosine)),r);
|
||||
return pose(sub(tc,rotate(r,sc)),r);
|
||||
}
|
||||
|
||||
private Match assignment(List<Hole> source,List<Hole> target,RigidPose pose,Tolerances tol,double allowance){
|
||||
int n=source.size();if(n!=target.size())return null;
|
||||
double limit=tol.positionM()*allowance,angleLimit=tol.axisAngleRad()*allowance;
|
||||
double penalty=4*n+1;double[][] costs=new double[n][n],distances=new double[n][n],angles=new double[n][n];
|
||||
double[] r=rotation(pose);
|
||||
for(int i=0;i<n;i++)for(int j=0;j<n;j++){
|
||||
double d=norm(sub(point(pose,source.get(i).pointOnPlaneM()),target.get(j).pointOnPlaneM()));
|
||||
double a=angle(rotate(r,source.get(i).axis()),target.get(j).axis(),true);
|
||||
distances[i][j]=d;angles[i][j]=a;
|
||||
costs[i][j]=d>limit+1e-10||a>angleLimit+1e-10?penalty:d*d/(limit*limit)+a*a/(angleLimit*angleLimit);
|
||||
}
|
||||
int[] indices=minimumCostAssignment(costs);double max=0,sum=0,axis=0;
|
||||
for(int i=0;i<n;i++){int j=indices[i];if(costs[i][j]>=penalty)return null;
|
||||
max=Math.max(max,distances[i][j]);sum+=distances[i][j]*distances[i][j];axis=Math.max(axis,angles[i][j]);}
|
||||
return new Match(indices,max,Math.sqrt(sum/n),axis);
|
||||
}
|
||||
|
||||
/** Finite forbidden-edge penalty exceeds every possible all-valid assignment. */
|
||||
static int[] minimumCostAssignment(double[][] costs){
|
||||
int n=costs.length;double[] u=new double[n+1],v=new double[n+1];int[] p=new int[n+1],way=new int[n+1];
|
||||
for(int i=1;i<=n;i++){p[0]=i;int j0=0;double[] min=new double[n+1];Arrays.fill(min,Double.POSITIVE_INFINITY);boolean[] used=new boolean[n+1];
|
||||
do{used[j0]=true;int i0=p[j0],j1=0;double delta=Double.POSITIVE_INFINITY;
|
||||
for(int j=1;j<=n;j++)if(!used[j]){double cur=costs[i0-1][j-1]-u[i0]-v[j];if(cur<min[j]){min[j]=cur;way[j]=j0;}if(min[j]<delta){delta=min[j];j1=j;}}
|
||||
for(int j=0;j<=n;j++){if(used[j]){u[p[j]]+=delta;v[j]-=delta;}else min[j]-=delta;}j0=j1;
|
||||
}while(p[j0]!=0);
|
||||
do{int j1=way[j0];p[j0]=p[j1];j0=j1;}while(j0!=0);
|
||||
}
|
||||
int[] result=new int[n];for(int j=1;j<=n;j++)result[p[j]-1]=j-1;return result;
|
||||
}
|
||||
|
||||
public MountGeometry normalize(MountGeometry geometry,Tolerances tolerance){
|
||||
if(geometry==null||geometry.plane()==null||geometry.holes()==null||geometry.holes().size()<2)
|
||||
throw new IllegalArgumentException("接口需要一个安装面和至少两个不同孔位");
|
||||
double[] origin=vec(geometry.plane().pointM()).clone(), normal=unit(geometry.plane().outwardNormal());
|
||||
List<Hole> holes=new ArrayList<>();Set<String> ids=new HashSet<>();
|
||||
for(Hole hole:geometry.holes()){
|
||||
if(hole==null||blank(hole.id())||!ids.add(hole.id()))throw new IllegalArgumentException("孔 ID 缺失或重复");
|
||||
double[] p=vec(hole.pointOnPlaneM()),axis=unit(hole.axis());
|
||||
double offset=dot(sub(p,origin),normal),denominator=dot(axis,normal);
|
||||
if(Math.abs(offset)>tolerance.positionM()+1e-10||Math.abs(denominator)<1e-6)throw new IllegalArgumentException("孔 " + hole.id() + ":孔轴必须穿过安装面且孔位在安装面上");
|
||||
if(hole.diameterM()!=null&&(!Double.isFinite(hole.diameterM())||hole.diameterM()<=0))throw new IllegalArgumentException("孔径必须为正数");
|
||||
double[] intersection=sub(p,scale(axis,offset/denominator));
|
||||
for(Hole previous:holes)if(norm(sub(previous.pointOnPlaneM(),intersection))<1e-8)throw new IllegalArgumentException("存在重复孔轴,请先归并沉孔和通孔边");
|
||||
holes.add(new Hole(hole.id(),intersection,axis,hole.diameterM()));
|
||||
}
|
||||
holes.sort(Comparator.comparing(Hole::id));return new MountGeometry(new Plane(origin,normal),List.copyOf(holes));
|
||||
}
|
||||
|
||||
private void tolerances(Tolerances t){
|
||||
if(t==null||!Double.isFinite(t.positionM())||t.positionM()<=0||!Double.isFinite(t.axisAngleRad())||t.axisAngleRad()<=0||t.axisAngleRad()>=Math.PI/2
|
||||
||!Double.isFinite(t.planeAngleRad())||t.planeAngleRad()<=0||t.planeAngleRad()>=Math.PI/2)throw new IllegalArgumentException("接口容差不合法");
|
||||
}
|
||||
private boolean samePose(RigidPose a,RigidPose b){
|
||||
if(norm(sub(a.positionM(),b.positionM()))>1e-8)return false;double[] r=multiply(transpose(rotation(a)),rotation(b));
|
||||
return Math.acos(Math.max(-1,Math.min(1,(r[0]+r[4]+r[8]-1)/2)))<1e-6;
|
||||
}
|
||||
private String fingerprint(MountGeometry g){
|
||||
StringBuilder s=new StringBuilder(stableNumbers(g.plane().pointM())).append(stableNumbers(g.plane().outwardNormal()));
|
||||
for(Hole h:g.holes())s.append(h.id().length()).append(':').append(h.id()).append(stableNumbers(h.pointOnPlaneM())).append(stableNumbers(h.axis())).append(h.diameterM());
|
||||
return hash(s.toString());
|
||||
}
|
||||
// Normalize floating-point noise in identity encoding only, never in the solver calculation chain.
|
||||
private String stableNumbers(double[] values){return Arrays.toString(Arrays.stream(values).map(v->{double n=Math.rint(v*1e12)/1e12;return n==0?0:n;}).toArray());}
|
||||
private String hash(String input){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8)));}
|
||||
catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);}}
|
||||
private boolean blank(String value){return value==null||value.isBlank();}
|
||||
private CandidateSet rejected(String reason){return new CandidateSet(SOLVER_VERSION,List.of(),List.of(reason));}
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
|
||||
/** Small rigid-transform kernel: row-major rotation, column vectors, no Euler angles. */
|
||||
public final class RigidMath {
|
||||
private RigidMath() {}
|
||||
public static double[] vec(double[] a) {
|
||||
if (a == null || a.length != 3) throw new IllegalArgumentException("需要三个有限坐标");
|
||||
for (double v : a) if (!Double.isFinite(v)) throw new IllegalArgumentException("坐标必须为有限数值");
|
||||
return a;
|
||||
}
|
||||
public static double[] add(double[] a, double[] b) { return new double[]{a[0]+b[0],a[1]+b[1],a[2]+b[2]}; }
|
||||
public static double[] sub(double[] a, double[] b) { return new double[]{a[0]-b[0],a[1]-b[1],a[2]-b[2]}; }
|
||||
public static double[] scale(double[] a, double s) { return new double[]{a[0]*s,a[1]*s,a[2]*s}; }
|
||||
public static double dot(double[] a,double[] b) { return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; }
|
||||
public static double norm(double[] a) { return Math.sqrt(dot(a,a)); }
|
||||
public static double[] unit(double[] a) { vec(a); double n=norm(a); if(n<1e-12) throw new IllegalArgumentException("法向/孔轴不能为零向量"); return scale(a,1/n); }
|
||||
public static double[] cross(double[] a,double[] b) { return new double[]{a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}; }
|
||||
public static double angle(double[] a,double[] b,boolean unoriented) { double d=dot(unit(a),unit(b)); return Math.acos(Math.max(-1,Math.min(1,unoriented?Math.abs(d):d))); }
|
||||
public static double[] rotate(double[] r,double[] p) { return new double[]{r[0]*p[0]+r[1]*p[1]+r[2]*p[2],r[3]*p[0]+r[4]*p[1]+r[5]*p[2],r[6]*p[0]+r[7]*p[1]+r[8]*p[2]}; }
|
||||
public static double[] transpose(double[] r) { return new double[]{r[0],r[3],r[6],r[1],r[4],r[7],r[2],r[5],r[8]}; }
|
||||
public static double[] multiply(double[] a,double[] b) { double[] r=new double[9]; for(int i=0;i<3;i++)for(int j=0;j<3;j++)for(int k=0;k<3;k++)r[i*3+j]+=a[i*3+k]*b[k*3+j]; return r; }
|
||||
public static double[] basis(double[] z,double[] direction) {
|
||||
z=unit(z); double[] x=unit(sub(direction,scale(z,dot(direction,z)))); double[] y=cross(z,x);
|
||||
return new double[]{x[0],y[0],z[0],x[1],y[1],z[1],x[2],y[2],z[2]};
|
||||
}
|
||||
public static double[] rotationAxis(double[] axis,double angle) {
|
||||
double[] a=unit(axis); double s=Math.sin(angle/2), c=Math.cos(angle/2);
|
||||
return rotation(new RigidPose(new double[3],new double[]{a[0]*s,a[1]*s,a[2]*s,c}));
|
||||
}
|
||||
public static double[] rotation(RigidPose p) {
|
||||
if(p==null)throw new IllegalArgumentException("缺少刚体位姿"); vec(p.positionM());
|
||||
double[] q=p.quaternionXYZW(); if(q==null||q.length!=4)throw new IllegalArgumentException("四元数必须使用 XYZW");
|
||||
double n=0; for(double v:q){ if(!Double.isFinite(v))throw new IllegalArgumentException("四元数必须有限"); n+=v*v; }
|
||||
if(Math.abs(n-1)>1e-6)throw new IllegalArgumentException("必须使用单位四元数");
|
||||
double x=q[0],y=q[1],z=q[2],w=q[3];
|
||||
return new double[]{1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w),2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w),2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)};
|
||||
}
|
||||
public static RigidPose pose(double[] t,double[] r) {
|
||||
double x,y,z,w, trace=r[0]+r[4]+r[8];
|
||||
if(trace>0){double s=Math.sqrt(trace+1)*2;w=s/4;x=(r[7]-r[5])/s;y=(r[2]-r[6])/s;z=(r[3]-r[1])/s;}
|
||||
else if(r[0]>r[4]&&r[0]>r[8]){double s=Math.sqrt(1+r[0]-r[4]-r[8])*2;w=(r[7]-r[5])/s;x=s/4;y=(r[1]+r[3])/s;z=(r[2]+r[6])/s;}
|
||||
else if(r[4]>r[8]){double s=Math.sqrt(1+r[4]-r[0]-r[8])*2;w=(r[2]-r[6])/s;x=(r[1]+r[3])/s;y=s/4;z=(r[5]+r[7])/s;}
|
||||
else{double s=Math.sqrt(1+r[8]-r[0]-r[4])*2;w=(r[3]-r[1])/s;x=(r[2]+r[6])/s;y=(r[5]+r[7])/s;z=s/4;}
|
||||
double n=Math.sqrt(x*x+y*y+z*z+w*w); if(w<0)n=-n;
|
||||
return new RigidPose(t.clone(),new double[]{x/n,y/n,z/n,w/n});
|
||||
}
|
||||
public static RigidPose identity() { return new RigidPose(new double[3],new double[]{0,0,0,1}); }
|
||||
public static RigidPose compose(RigidPose a,RigidPose b) { double[] r=rotation(a); return pose(add(a.positionM(),rotate(r,b.positionM())),multiply(r,rotation(b))); }
|
||||
public static RigidPose inverse(RigidPose a) { double[] r=transpose(rotation(a));return pose(scale(rotate(r,a.positionM()),-1),r); }
|
||||
public static double[] point(RigidPose a,double[] p) { return add(a.positionM(),rotate(rotation(a),p)); }
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
import java.io.OutputStream;
|
||||
import java.security.DigestOutputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Hash stored bytes, not a digest supplied by the browser. No remote URLs are fetched. */
|
||||
@Service @RequiredArgsConstructor
|
||||
public class UrdfAssetVerifier {
|
||||
private final ObjectStorageClient storage;
|
||||
private final StorageObjectKeys storageObjectKeys;
|
||||
public void verify(JsonNode source) {
|
||||
Map<String,String> checked = new HashMap<>();
|
||||
for (JsonNode resource : source.path("resources")) {
|
||||
String key=storageObjectKeys.requireKey(resource.path("sourceKey").asText());
|
||||
String expected=resource.path("sha256").asText();
|
||||
try {
|
||||
String digest=checked.get(key);
|
||||
if(digest==null) {
|
||||
MessageDigest sha=MessageDigest.getInstance("SHA-256");
|
||||
try (DigestOutputStream sink=new DigestOutputStream(OutputStream.nullOutputStream(),sha)) {
|
||||
storage.writeObjectTo(key,sink);
|
||||
}
|
||||
digest=HexFormat.of().formatHex(sha.digest()); checked.put(key,digest);
|
||||
}
|
||||
if(!expected.equals(digest)) throw new IllegalArgumentException("原始资源已变化,请重新识别:"+resource.path("reference").asText());
|
||||
} catch (IllegalArgumentException e) { throw e; }
|
||||
catch (Exception e) { throw new IllegalArgumentException("原始 URDF 资源无法验证:"+resource.path("reference").asText(),e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
-67
@@ -1,67 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import java.io.StringReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Validates immutable source identity and the link-local coordinate contract. */
|
||||
@Service
|
||||
public class UrdfSourceValidation {
|
||||
public Set<String> validate(JsonNode source) {
|
||||
if (source == null || !source.isObject()) throw new IllegalArgumentException("缺少原始 URDF 快照,请重新上传");
|
||||
String xml = source.path("xml").asText();
|
||||
String documentHash = hash(xml);
|
||||
if (!documentHash.equals(source.path("documentHash").asText())) throw new IllegalArgumentException("原始 URDF 哈希不一致");
|
||||
JsonNode resources = source.path("resources");
|
||||
if (!resources.isArray()) throw new IllegalArgumentException("缺少 URDF 资源清单");
|
||||
SortedMap<String,String> hashes = new TreeMap<>();
|
||||
for (JsonNode resource : resources) {
|
||||
String reference = resource.path("reference").asText();
|
||||
String digest = resource.path("sha256").asText();
|
||||
if (reference.isBlank() || reference.contains("\n") || reference.contains("\t")
|
||||
|| !digest.matches("[a-f0-9]{64}") || resource.path("sourceKey").asText().isBlank()
|
||||
|| hashes.putIfAbsent(reference,digest) != null)
|
||||
throw new IllegalArgumentException("URDF 资源清单不完整或存在重复引用");
|
||||
}
|
||||
String manifest = String.join("\n", hashes.entrySet().stream().map(e -> e.getKey()+"\t"+e.getValue()).toList());
|
||||
if (!hash(documentHash+"\n"+manifest).equals(source.path("sourceGeometryHash").asText()))
|
||||
throw new IllegalArgumentException("源几何哈希已变化,请重新识别接口");
|
||||
try {
|
||||
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities",false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities",false);
|
||||
factory.setXIncludeAware(false);factory.setExpandEntityReferences(false);
|
||||
Element robot=factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
|
||||
if (!"robot".equals(robot.getTagName())) throw new IllegalArgumentException("URDF 根节点必须是 robot");
|
||||
Set<String> links=new HashSet<>(), children=new HashSet<>(), joints=new HashSet<>();
|
||||
Map<String,String> parents=new HashMap<>();
|
||||
for (var n=robot.getFirstChild(); n!=null; n=n.getNextSibling()) if(n instanceof Element e && "link".equals(e.getTagName())) {
|
||||
if(e.getAttribute("name").isBlank() || !links.add(e.getAttribute("name"))) throw new IllegalArgumentException("URDF link 名称缺失或重复");
|
||||
}
|
||||
for (var n=robot.getFirstChild(); n!=null; n=n.getNextSibling()) if(n instanceof Element e && "joint".equals(e.getTagName())) {
|
||||
if(e.getAttribute("name").isBlank() || !joints.add(e.getAttribute("name"))) throw new IllegalArgumentException("URDF joint 名称缺失或重复");
|
||||
String parent=linkAttribute(e,"parent"), child=linkAttribute(e,"child");
|
||||
if(!links.contains(parent)||!links.contains(child)||!children.add(child)) throw new IllegalArgumentException("URDF 父子 link 不存在或存在多父连接");
|
||||
parents.put(child,parent);
|
||||
}
|
||||
if(links.size()-children.size()!=1) throw new IllegalArgumentException("URDF 必须只有一个根 link");
|
||||
for(String link:links){Set<String> visited=new HashSet<>();String node=link;while(node!=null){if(!visited.add(node))throw new IllegalArgumentException("URDF 存在环");node=parents.get(node);}}
|
||||
for(String tag:List.of("mesh","texture")) {
|
||||
NodeList nodes=robot.getElementsByTagName(tag);
|
||||
for(int i=0;i<nodes.getLength();i++)if(!hashes.containsKey(((Element)nodes.item(i)).getAttribute("filename")))throw new IllegalArgumentException("URDF 资源清单遗漏引用");
|
||||
}
|
||||
return Set.copyOf(links);
|
||||
} catch (IllegalArgumentException e) { throw e; }
|
||||
catch (Exception e) { throw new IllegalArgumentException("原始 URDF 无法解析",e); }
|
||||
}
|
||||
private String linkAttribute(Element joint,String tag){NodeList list=joint.getElementsByTagName(tag);if(list.getLength()!=1)throw new IllegalArgumentException("URDF joint 缺少父子连接");return ((Element)list.item(0)).getAttribute("link");}
|
||||
public static String hash(String text){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
|
||||
|
||||
public interface ComponentCoverImageUploadService {
|
||||
|
||||
PrepareCoverImageUploadSessionResponse prepareUploadSession(Long userId);
|
||||
|
||||
PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request);
|
||||
|
||||
CompleteCoverImageUploadResponse completeUploadSession(Long userId, CompleteCoverImageUploadRequest request);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ public interface ComponentService {
|
||||
|
||||
ComponentResponse createComponent(Long userId, CreateComponentRequest request);
|
||||
|
||||
PageResponse<ComponentListItemResponse> listComponents(long page, long size, String keyword);
|
||||
PageResponse<ComponentListItemResponse> listComponents(long page, long size, String keyword, String category);
|
||||
|
||||
ComponentResponse getComponent(Long id);
|
||||
|
||||
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
|
||||
|
||||
public interface ComponentUrdfUploadService {
|
||||
|
||||
PrepareUrdfUploadSessionResponse prepareUploadSession(Long userId);
|
||||
|
||||
PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request);
|
||||
|
||||
CompleteUrdfUploadResponse completeUploadSession(Long userId, CompleteUrdfUploadRequest request);
|
||||
}
|
||||
-113
@@ -1,113 +0,0 @@
|
||||
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 com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
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;
|
||||
private final StorageObjectKeys storageObjectKeys;
|
||||
|
||||
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.startsWith(storageObjectKeys.rootPrefix()) && 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 = storageObjectKeys.rootPrefix() + "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");
|
||||
storageObjectKeys.requireKey(key);
|
||||
// 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={} keySummary={} exceptionType={}",
|
||||
definitionId, revision, RequestIdHolder.get(), StorageObjectKeys.summary(key), exception.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
-142
@@ -1,142 +0,0 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.InterfaceBrepProperties;
|
||||
import com.linkerbot.cadworld.common.process.ToolProcess;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class InterfaceBrepService {
|
||||
private final InterfaceBrepProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public JsonNode analyze(MultipartFile file) {
|
||||
validate(file);
|
||||
Path temporaryDirectory = null;
|
||||
try {
|
||||
temporaryDirectory = Files.createTempDirectory("interface-brep-");
|
||||
String suffix = extension(file.getOriginalFilename());
|
||||
Path input = temporaryDirectory.resolve("source" + suffix);
|
||||
Path output = temporaryDirectory.resolve("topology.json");
|
||||
file.transferTo(input);
|
||||
|
||||
Path script = resolveScript(temporaryDirectory);
|
||||
if (!Files.isRegularFile(script)) {
|
||||
throw unavailable("STEP B-Rep 提取脚本不存在:" + script);
|
||||
}
|
||||
List<String> command = List.of(
|
||||
properties.python(),
|
||||
script.toString(),
|
||||
input.toString(),
|
||||
"--output",
|
||||
output.toString(),
|
||||
"--max-output-bytes",
|
||||
Long.toString(properties.maxOutputBytes())
|
||||
);
|
||||
var result = new ToolProcess().run(
|
||||
command,
|
||||
script.getParent(),
|
||||
Duration.ofSeconds(properties.timeoutSeconds())
|
||||
);
|
||||
if (result.timedOut()) {
|
||||
throw new BizException(504, "INTERFACE_BREP_TIMEOUT",
|
||||
"STEP 精确 B-Rep 解析超时,请拆分过大的装配 STEP 后重试。");
|
||||
}
|
||||
if (result.exitCode() != 0) {
|
||||
String detail = result.output().replace("STEP_BREP_ERROR:", "").trim();
|
||||
if (detail.contains("No module named 'OCP'")) {
|
||||
throw unavailable("服务器未安装 OCCT Python 运行库,无法进行精确 B-Rep 解析。");
|
||||
}
|
||||
throw new BizException(422, "INTERFACE_BREP_INVALID_STEP",
|
||||
detail.isBlank() ? "STEP 文件无法提取精确 B-Rep 拓扑。" : detail);
|
||||
}
|
||||
if (!Files.isRegularFile(output)) {
|
||||
throw unavailable("STEP B-Rep 提取器未生成拓扑结果。");
|
||||
}
|
||||
long outputSize = Files.size(output);
|
||||
if (outputSize <= 0 || outputSize > properties.maxOutputBytes()) {
|
||||
throw new BizException(413, "INTERFACE_BREP_OUTPUT_TOO_LARGE",
|
||||
"STEP B-Rep 结果过大,请上传单个组件或拆分后的 STEP。");
|
||||
}
|
||||
JsonNode topology = objectMapper.readTree(output.toFile());
|
||||
if (!"interface-step-brep/v1".equals(topology.path("schemaVersion").asText())) {
|
||||
throw unavailable("STEP B-Rep 提取器返回了不支持的数据版本。");
|
||||
}
|
||||
return topology;
|
||||
} catch (BizException exception) {
|
||||
throw exception;
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw unavailable("STEP B-Rep 解析被中断。");
|
||||
} catch (IOException exception) {
|
||||
throw unavailable("STEP B-Rep 解析服务不可用:" + exception.getMessage());
|
||||
} finally {
|
||||
deleteRecursively(temporaryDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
private void validate(MultipartFile file) {
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw new IllegalArgumentException("请选择 STEP 或 STP 文件。");
|
||||
}
|
||||
String suffix = extension(file.getOriginalFilename());
|
||||
if (!suffix.equals(".step") && !suffix.equals(".stp")) {
|
||||
throw new IllegalArgumentException("接口模型只支持 STEP 或 STP;不再接受 STL。");
|
||||
}
|
||||
if (file.getSize() > properties.maxUploadBytes()) {
|
||||
throw new BizException(413, "INTERFACE_BREP_UPLOAD_TOO_LARGE",
|
||||
"STEP 文件超过接口 B-Rep 分析大小限制。");
|
||||
}
|
||||
}
|
||||
|
||||
private Path resolveScript(Path temporaryDirectory) throws IOException {
|
||||
String configured = properties.script();
|
||||
if (configured.startsWith("classpath:")) {
|
||||
String resource = configured.substring("classpath:".length());
|
||||
try (var input = new org.springframework.core.io.ClassPathResource(resource).getInputStream()) {
|
||||
Path extracted = temporaryDirectory.resolve("step_brep_topology.py");
|
||||
Files.copy(input, extracted);
|
||||
return extracted;
|
||||
}
|
||||
}
|
||||
return Path.of(configured).toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
private static String extension(String fileName) {
|
||||
if (fileName == null) return "";
|
||||
String lower = fileName.toLowerCase(Locale.ROOT);
|
||||
if (lower.endsWith(".step")) return ".step";
|
||||
if (lower.endsWith(".stp")) return ".stp";
|
||||
return "";
|
||||
}
|
||||
|
||||
private static BizException unavailable(String message) {
|
||||
return new BizException(503, "INTERFACE_BREP_UNAVAILABLE", message);
|
||||
}
|
||||
|
||||
private static void deleteRecursively(Path directory) {
|
||||
if (directory == null || !Files.exists(directory)) return;
|
||||
try (var paths = Files.walk(directory)) {
|
||||
paths.sorted((left, right) -> right.compareTo(left)).forEach(path -> {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException ignored) {
|
||||
// Temporary analysis files are best-effort cleanup only.
|
||||
}
|
||||
});
|
||||
} catch (IOException ignored) {
|
||||
// The request result must not be replaced by a cleanup failure.
|
||||
}
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
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(SaveInterfaceDefinitionRequest request);
|
||||
JsonNode update(String id, SaveInterfaceDefinitionRequest request);
|
||||
void delete(String id);
|
||||
void attachAsset(String definitionId, int geometryRevision, String objectKey, String sha256,
|
||||
String expectedAssetKey);
|
||||
com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.Definition geometryDefinition(String id, int revision);
|
||||
}
|
||||
+9
-1
@@ -22,16 +22,24 @@ public class OperationLogService {
|
||||
public void record(OperationLog log) { mapper.insert(log); }
|
||||
|
||||
public PageResponse<OperationLog> list(long page, long size, String module, String action, Boolean success,
|
||||
Long operatorId, LocalDateTime from, LocalDateTime to) {
|
||||
Long operatorId, String targetType, String targetId, String targetCode, String keyword,
|
||||
LocalDateTime from, LocalDateTime to) {
|
||||
if (from != null && to != null && from.isAfter(to)) throw new IllegalArgumentException("开始时间不能晚于结束时间");
|
||||
LambdaQueryWrapper<OperationLog> query = new LambdaQueryWrapper<OperationLog>()
|
||||
.eq(StringUtils.hasText(module), OperationLog::getModule, module)
|
||||
.eq(StringUtils.hasText(action), OperationLog::getAction, action)
|
||||
.eq(StringUtils.hasText(targetType), OperationLog::getTargetType, targetType)
|
||||
.eq(StringUtils.hasText(targetId), OperationLog::getTargetId, targetId)
|
||||
.eq(StringUtils.hasText(targetCode), OperationLog::getTargetCode, targetCode)
|
||||
.eq(success != null, OperationLog::getSuccess, success)
|
||||
.eq(operatorId != null, OperationLog::getOperatorId, operatorId)
|
||||
.ge(from != null, OperationLog::getOperatedAt, from)
|
||||
.le(to != null, OperationLog::getOperatedAt, to)
|
||||
.orderByDesc(OperationLog::getOperatedAt).orderByDesc(OperationLog::getId);
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
query.and(q -> q.like(OperationLog::getTargetName, keyword.trim())
|
||||
.or().like(OperationLog::getTargetCode, keyword.trim()));
|
||||
}
|
||||
Page<OperationLog> result = mapper.selectPage(new Page<>(page, size), query);
|
||||
return new PageResponse<>(result.getRecords(), page, size, result.getTotal());
|
||||
}
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.dto.storage.UploadSignatureRequest;
|
||||
import com.linkerbot.cadworld.dto.storage.UploadSignatureResponse;
|
||||
import com.linkerbot.cadworld.dto.storage.UploadSignatureResponse.UploadAuthorization;
|
||||
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider.UploadSessionClaims;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class UploadSignatureService {
|
||||
private final ComponentUploadSupport support;
|
||||
private final ComponentUploadSessionTokenProvider tokens;
|
||||
private final ObjectStorageClient storage;
|
||||
private final ComponentMapper components;
|
||||
|
||||
public UploadSignatureResponse sign(Long userId, UploadSignatureRequest request) {
|
||||
UploadSessionClaims session;
|
||||
String token;
|
||||
boolean renewal = request.uploadSessionToken() != null;
|
||||
if (renewal) {
|
||||
if (request.componentId() != null || !StringUtils.hasText(request.uploadSessionToken())) {
|
||||
throw new BizException(422, "INVALID_UPLOAD_SIGNATURE_REQUEST", "续签只能提供非空的uploadSessionToken");
|
||||
}
|
||||
token = request.uploadSessionToken();
|
||||
session = support.requireUploadSession(userId, token);
|
||||
if (session.componentId() != null) {
|
||||
var component = components.selectById(session.componentId());
|
||||
if (component == null) throw new BizException(404, "COMPONENT_NOT_FOUND", "组件不存在");
|
||||
support.requireComponent(session, component.getId(), component.getComponentCode());
|
||||
}
|
||||
} else {
|
||||
String code;
|
||||
if (request.componentId() == null) {
|
||||
code = "CW-" + randomId().toUpperCase(Locale.ROOT);
|
||||
} else {
|
||||
var component = components.selectById(request.componentId());
|
||||
if (component == null) throw new BizException(404, "COMPONENT_NOT_FOUND", "组件不存在");
|
||||
code = component.getComponentCode();
|
||||
}
|
||||
String batch = randomId();
|
||||
Instant expiry = Instant.now().truncatedTo(ChronoUnit.SECONDS).plus(support.sessionTtl());
|
||||
session = new UploadSessionClaims(userId, request.componentId(), code, batch,
|
||||
support.prefix(code, batch, "step"), support.prefix(code, batch, "urdf"), expiry);
|
||||
token = tokens.generateToken(session);
|
||||
}
|
||||
Instant expiresAt = Instant.now().plus(support.signatureTtl());
|
||||
if (expiresAt.isAfter(session.expiresAt())) expiresAt = session.expiresAt();
|
||||
var step = authorize(session.stepPrefix(), expiresAt);
|
||||
var urdf = authorize(session.urdfPrefix(), expiresAt);
|
||||
log.info("组件上传签名完成 componentCode={} componentId={} renewal={} userId={} requestId={} expiresAt={}",
|
||||
session.componentCode(), session.componentId(), renewal, userId, RequestIdHolder.get(), expiresAt);
|
||||
return new UploadSignatureResponse(session.componentCode(), token, session.expiresAt(), expiresAt, step, urdf);
|
||||
}
|
||||
|
||||
private UploadAuthorization authorize(String prefix, Instant expiresAt) {
|
||||
var authorization = storage.createUploadAuthorization(prefix, expiresAt);
|
||||
return new UploadAuthorization(authorization.uploadUrl(), prefix, authorization.uploadFields(), "POST");
|
||||
}
|
||||
|
||||
private String randomId() { return UUID.randomUUID().toString().replace("-", ""); }
|
||||
}
|
||||
+13
-19
@@ -2,30 +2,24 @@ package com.linkerbot.cadworld.service.client;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
public interface ObjectStorageClient {
|
||||
|
||||
String createUploadUrl(String objectKey, String contentType, Duration duration);
|
||||
|
||||
default UploadAuthorization createUploadAuthorization(String keyPrefix, Instant expiresAt) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
default void putObject(String objectKey, String contentType, InputStream inputStream, long contentLength) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
boolean objectExists(String objectKey);
|
||||
|
||||
default void deleteObject(String objectKey) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
default StoredObject statObject(String objectKey) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
default void writeObjectTo(String objectKey, OutputStream outputStream) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
record StoredObject(String contentType, long contentLength) {
|
||||
default void deleteObject(String objectKey) { throw new UnsupportedOperationException(); }
|
||||
default StoredObject statObject(String objectKey) { throw new UnsupportedOperationException(); }
|
||||
default void writeObjectTo(String objectKey, OutputStream outputStream) { throw new UnsupportedOperationException(); }
|
||||
record StoredObject(String contentType, long contentLength) { }
|
||||
record UploadAuthorization(String uploadUrl, Map<String, String> uploadFields, Instant expiresAt) {
|
||||
public UploadAuthorization { uploadFields = Map.copyOf(uploadFields); }
|
||||
@Override
|
||||
public String toString() { return "UploadAuthorization[expiresAt=" + expiresAt + "]"; }
|
||||
}
|
||||
}
|
||||
|
||||
+55
-10
@@ -18,12 +18,21 @@ import java.io.InterruptedIOException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import com.aliyun.oss.model.PolicyConditions;
|
||||
import com.aliyun.oss.model.MatchMode;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -33,8 +42,17 @@ public class OssObjectStorageClient implements ObjectStorageClient {
|
||||
private final StorageProperties storageProperties;
|
||||
private final StorageObjectKeys keys;
|
||||
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public OssObjectStorageClient(@Lazy OSS oss, OssProperties properties,
|
||||
StorageProperties storageProperties, StorageObjectKeys keys) {
|
||||
this(oss, properties, storageProperties, keys, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public OssObjectStorageClient(OSS oss, OssProperties properties, StorageProperties storageProperties,
|
||||
StorageObjectKeys keys, Clock clock) {
|
||||
this.clock = clock;
|
||||
this.oss = oss;
|
||||
this.properties = properties;
|
||||
this.storageProperties = storageProperties;
|
||||
@@ -42,16 +60,43 @@ public class OssObjectStorageClient implements ObjectStorageClient {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createUploadUrl(String objectKey, String contentType, Duration duration) {
|
||||
String key = keys.requireKey(objectKey);
|
||||
public UploadAuthorization createUploadAuthorization(String keyPrefix, Instant expiresAt) {
|
||||
String prefix = keys.requirePrefix(keyPrefix);
|
||||
properties.validate();
|
||||
if (duration == null || duration.isZero() || duration.isNegative()
|
||||
|| !StringUtils.hasText(storageProperties.publicApiBaseUrl())) {
|
||||
throw new BizException(500, "STORAGE_CONFIG_ERROR", "上传会话有效期或后台访问地址配置非法");
|
||||
Instant signingTime = clock.instant();
|
||||
if (expiresAt == null || !expiresAt.isAfter(signingTime)) {
|
||||
throw new BizException(422, "INVALID_UPLOAD_SESSION", "上传会话已过期");
|
||||
}
|
||||
UploadLimits.checkLength(0, storageProperties.maxUploadBytes());
|
||||
String date = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC).format(signingTime);
|
||||
String timestamp = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC).format(signingTime);
|
||||
var fields = new LinkedHashMap<String, String>();
|
||||
fields.put("x-oss-signature-version", "OSS4-HMAC-SHA256");
|
||||
fields.put("x-oss-credential", properties.accessKeyId().trim() + "/" + date + "/" + properties.regionId() + "/oss/aliyun_v4_request");
|
||||
fields.put("x-oss-date", timestamp);
|
||||
fields.put("success_action_status", "204");
|
||||
fields.put("x-oss-forbid-overwrite", "true");
|
||||
PolicyConditions conditions = new PolicyConditions();
|
||||
conditions.addConditionItem("bucket", properties.bucket().trim());
|
||||
conditions.addConditionItem(MatchMode.StartWith, "key", prefix);
|
||||
conditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, storageProperties.maxUploadBytes());
|
||||
fields.forEach(conditions::addConditionItem);
|
||||
try {
|
||||
String policy = oss.generatePostPolicy(Date.from(expiresAt), conditions);
|
||||
fields.put("policy", Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)));
|
||||
// The overload with signing date calculates V4; the single-argument overload signs V1.
|
||||
fields.put("x-oss-signature", oss.calculatePostSignature(policy, Date.from(signingTime)));
|
||||
log.info("OSS 目录签名成功 bucket={} keySummary={} requestId={} expiresAt={}",
|
||||
properties.bucket().trim(), StorageObjectKeys.summary(prefix), RequestIdHolder.get(), expiresAt);
|
||||
return new UploadAuthorization("https://" + properties.bucket().trim() + ".oss-" + properties.regionId() + ".aliyuncs.com/", fields, expiresAt);
|
||||
} catch (RuntimeException exception) {
|
||||
OSSException ossError = exception instanceof OSSException error ? error : null;
|
||||
log.error("OSS 目录签名失败 bucket={} keySummary={} requestId={} ossErrorCode={} ossRequestId={} exceptionType={}",
|
||||
properties.bucket().trim(), StorageObjectKeys.summary(prefix), RequestIdHolder.get(),
|
||||
ossError == null ? "-" : ossError.getErrorCode(), ossError == null ? "-" : ossError.getRequestId(),
|
||||
exception.getClass().getSimpleName());
|
||||
throw new BizException(500, "OSS_UPLOAD_SIGN_FAILED", "生成 OSS 上传签名失败");
|
||||
}
|
||||
return UriComponentsBuilder.fromUriString(storageProperties.publicApiBaseUrl().trim().replaceAll("/+$", ""))
|
||||
.path("/admin-api/component-assets/upload")
|
||||
.queryParam("objectKey", key).build().encode().toUriString();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.enums.ComponentUploadType;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import com.linkerbot.cadworld.service.ComponentCoverImageUploadService;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentCoverImageUploadServiceImpl implements ComponentCoverImageUploadService {
|
||||
|
||||
private static final String DEFAULT_COVER_IMAGE_PREFIX = "components/cover-images";
|
||||
private static final int COVER_IMAGE_KEY_MAX_LENGTH = 512;
|
||||
|
||||
private final StorageProperties storageProperties;
|
||||
private final ComponentUploadSupport componentUploadSupport;
|
||||
private final ObjectStorageUrlResolver objectStorageUrlResolver;
|
||||
|
||||
@Override
|
||||
public PrepareCoverImageUploadSessionResponse prepareUploadSession(Long userId) {
|
||||
ComponentUploadSupport.PreparedUploadSession session = componentUploadSupport.prepareUploadSession(
|
||||
userId,
|
||||
ComponentUploadType.COVER_IMAGE,
|
||||
componentUploadSupport.normalizeConfiguredPrefix(storageProperties.coverImagePrefix(), DEFAULT_COVER_IMAGE_PREFIX)
|
||||
);
|
||||
return new PrepareCoverImageUploadSessionResponse(
|
||||
session.uploadSessionToken(),
|
||||
session.keyPrefix()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request) {
|
||||
ComponentUploadSupport.PreparedObjectUpload upload = componentUploadSupport.prepareObjectUpload(
|
||||
userId,
|
||||
request.uploadSessionToken(),
|
||||
ComponentUploadType.COVER_IMAGE,
|
||||
"INVALID_COMPONENT_COVER_UPLOAD_SESSION",
|
||||
request.objectPath(),
|
||||
request.contentType()
|
||||
);
|
||||
return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey(), upload.uploadHeaders());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompleteCoverImageUploadResponse completeUploadSession(Long userId, CompleteCoverImageUploadRequest request) {
|
||||
ComponentUploadSessionTokenProvider.UploadSessionClaims claims = componentUploadSupport.requireUploadSession(
|
||||
userId,
|
||||
request.uploadSessionToken(),
|
||||
ComponentUploadType.COVER_IMAGE,
|
||||
"INVALID_COMPONENT_COVER_UPLOAD_SESSION"
|
||||
);
|
||||
List<String> objectKeys = componentUploadSupport.verifyUploadedObjectKeys(
|
||||
claims.keyPrefix(),
|
||||
request.objectKeys()
|
||||
);
|
||||
String coverImageKey = objectKeys.getFirst();
|
||||
if (!isSupportedImage(coverImageKey)) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_COVER_IMAGE_TYPE_INVALID", "封面图仅支持 jpg、jpeg、png、webp、gif");
|
||||
}
|
||||
if (coverImageKey.length() > COVER_IMAGE_KEY_MAX_LENGTH) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_COVER_IMAGE_KEY_TOO_LONG", "封面图对象 Key 过长,无法写入组件封面字段");
|
||||
}
|
||||
return new CompleteCoverImageUploadResponse(coverImageKey, objectStorageUrlResolver.resolvePublicUrl(coverImageKey));
|
||||
}
|
||||
|
||||
private boolean isSupportedImage(String objectKey) {
|
||||
String normalized = objectKey.toLowerCase(Locale.ROOT);
|
||||
return normalized.endsWith(".jpg")
|
||||
|| normalized.endsWith(".jpeg")
|
||||
|| normalized.endsWith(".png")
|
||||
|| normalized.endsWith(".webp")
|
||||
|| normalized.endsWith(".gif");
|
||||
}
|
||||
}
|
||||
+170
-188
@@ -1,226 +1,208 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.common.api.OperationTargetHolder;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentListItemResponse;
|
||||
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.dto.component.*;
|
||||
import com.linkerbot.cadworld.entity.Component;
|
||||
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||
import com.linkerbot.cadworld.service.ComponentService;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentServiceImpl implements ComponentService {
|
||||
|
||||
private static final String COMPONENT_NOT_FOUND = "COMPONENT_NOT_FOUND";
|
||||
private static final String COMPONENT_NAME_DUPLICATE = "COMPONENT_NAME_DUPLICATE";
|
||||
private static final String COMPONENT_NAME_DUPLICATE_MESSAGE = "组件名称已存在,请更换名称";
|
||||
|
||||
private static final TypeReference<List<String>> TAGS = new TypeReference<>() { };
|
||||
private static final TypeReference<List<CustomField>> FIELDS = new TypeReference<>() { };
|
||||
private static final TypeReference<List<UrdfFile>> FILES = new TypeReference<>() { };
|
||||
private final ComponentMapper componentMapper;
|
||||
private final ObjectStorageUrlResolver objectStorageUrlResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ComponentPortValidationService portValidation;
|
||||
private final StorageObjectKeys storageObjectKeys;
|
||||
private final ObjectStorageUrlResolver urls;
|
||||
private final ComponentUploadSupport uploads;
|
||||
private final TransactionTemplate transactions;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ComponentResponse createComponent(Long userId, CreateComponentRequest request) {
|
||||
String componentName = request.componentName().trim();
|
||||
assertComponentNameAvailable(componentName, null);
|
||||
var session = uploads.requireUploadSession(userId, request.uploadSessionToken());
|
||||
uploads.requireComponent(session, null, session.componentCode());
|
||||
OperationTargetHolder.set("COMPONENT", "", session.componentCode(), text(request.componentName()));
|
||||
Component component = new Component();
|
||||
apply(component, componentName, request.category(), request.robotType(), request.company(),
|
||||
request.model(), request.source(), request.coverImageKey(), request.description(), request.componentJson(),
|
||||
request.assemblyMetadata());
|
||||
component.setComponentCode(session.componentCode());
|
||||
applyForm(component, request);
|
||||
component.setStepObjectKey(uploads.verifyStep(session, request.stepObjectKey()));
|
||||
applyUrdf(component, uploads.verifyUrdf(session, request.urdfObjectKeys()));
|
||||
component.setVersion(1L);
|
||||
log.info("组件上传资源校验完成 componentCode={} urdfFileCount={} requestId={}",
|
||||
component.getComponentCode(), request.urdfObjectKeys().size(), RequestIdHolder.get());
|
||||
ComponentResponse response;
|
||||
try {
|
||||
componentMapper.insert(component);
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw duplicateComponentNameException();
|
||||
}
|
||||
return toDetailResponse(componentMapper.selectById(component.getId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResponse<ComponentListItemResponse> listComponents(long page, long size, String keyword) {
|
||||
Page<Component> pageable = new Page<>(page, size);
|
||||
LambdaQueryWrapper<Component> query = new LambdaQueryWrapper<>();
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
query.and(matches -> {
|
||||
for (String term : ComponentTagSupport.searchTerms(keyword)) {
|
||||
matches.or().nested(candidate -> candidate.like(Component::getComponentName, term)
|
||||
.or().like(Component::getCategory, term)
|
||||
.or().apply("JSON_SEARCH(assembly_metadata, 'one', {0}, NULL, '$.tags[*]', '$.capabilities[*]') IS NOT NULL", "%" + term + "%"));
|
||||
}
|
||||
response = transactions.execute(status -> {
|
||||
componentMapper.insert(component);
|
||||
snapshot(component);
|
||||
return detail(require(component.getId()));
|
||||
});
|
||||
}
|
||||
Page<Component> result = componentMapper.selectPage(pageable, query.orderByDesc(Component::getUpdatedAt));
|
||||
return new PageResponse<>(result.getRecords().stream().map(this::toListItemResponse).toList(), page, size, result.getTotal());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComponentResponse getComponent(Long id) {
|
||||
return toDetailResponse(requireComponent(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public ComponentResponse updateComponent(Long userId, Long id, UpdateComponentRequest request) {
|
||||
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 {
|
||||
if (componentMapper.updateById(component) != 1) {
|
||||
throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已删除,请刷新后保存");
|
||||
}
|
||||
} catch (DuplicateKeyException exception) {
|
||||
throw duplicateComponentNameException();
|
||||
throw new BizException(409, "COMPONENT_CODE_DUPLICATE", "组件编码已存在,请勿重复新增");
|
||||
}
|
||||
return toDetailResponse(componentMapper.selectById(component.getId()));
|
||||
log.info("组件新增成功 componentId={} componentCode={} userId={} requestId={}",
|
||||
component.getId(), component.getComponentCode(), userId, RequestIdHolder.get());
|
||||
return response;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteComponent(Long userId, Long id) {
|
||||
Component component = requireComponent(id);
|
||||
componentMapper.deleteById(component.getId());
|
||||
public ComponentResponse updateComponent(Long userId, Long id, UpdateComponentRequest request) {
|
||||
Component current = require(id);
|
||||
snapshot(current);
|
||||
if (request.componentCode() != null && !Objects.equals(current.getComponentCode(), request.componentCode())) {
|
||||
throw new BizException(422, "COMPONENT_CODE_IMMUTABLE", "组件编码不可修改");
|
||||
}
|
||||
if (!Objects.equals(current.getVersion(), request.version())) throw revisionConflict();
|
||||
if (current.getVersion() >= 4294967295L) {
|
||||
throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件版本已达到上限");
|
||||
}
|
||||
boolean replacing = request.stepObjectKey() != null || request.urdfObjectKeys() != null;
|
||||
if (replacing) {
|
||||
var session = uploads.requireUploadSession(userId, request.uploadSessionToken());
|
||||
uploads.requireComponent(session, id, current.getComponentCode());
|
||||
if (request.stepObjectKey() != null) current.setStepObjectKey(uploads.verifyStep(session, request.stepObjectKey()));
|
||||
if (request.urdfObjectKeys() != null) applyUrdf(current, uploads.verifyUrdf(session, request.urdfObjectKeys()));
|
||||
log.info("组件替换资源校验完成 componentId={} replaceStep={} replaceUrdf={} requestId={}",
|
||||
id, request.stepObjectKey() != null, request.urdfObjectKeys() != null, RequestIdHolder.get());
|
||||
} else if (request.uploadSessionToken() != null) {
|
||||
throw new BizException(422, "INVALID_COMPONENT_UPLOAD_OBJECT", "上传令牌须与替换文件清单一起提交");
|
||||
}
|
||||
applyForm(current, request);
|
||||
current.setVersion(request.version() + 1);
|
||||
ComponentResponse response = transactions.execute(status -> {
|
||||
int changed = componentMapper.update(current, new LambdaUpdateWrapper<Component>()
|
||||
.eq(Component::getId, id).eq(Component::getVersion, request.version()));
|
||||
if (changed != 1) throw revisionConflict();
|
||||
snapshot(current);
|
||||
return detail(require(id));
|
||||
});
|
||||
log.info("组件修改成功 componentId={} version={} userId={} requestId={}",
|
||||
id, current.getVersion(), userId, RequestIdHolder.get());
|
||||
return response;
|
||||
}
|
||||
|
||||
private Component requireComponent(Long id) {
|
||||
Component component = componentMapper.selectById(id);
|
||||
if (component == null) {
|
||||
throw new BizException(HttpStatus.NOT_FOUND.value(), COMPONENT_NOT_FOUND, "组件不存在");
|
||||
@Override
|
||||
public void deleteComponent(Long userId, Long id) {
|
||||
transactions.executeWithoutResult(status -> {
|
||||
Component current = componentMapper.selectOne(new LambdaQueryWrapper<Component>()
|
||||
.eq(Component::getId, id).last("FOR UPDATE"));
|
||||
if (current == null) throw notFound();
|
||||
snapshot(current);
|
||||
if (componentMapper.deleteById(id) != 1) throw notFound();
|
||||
});
|
||||
log.info("组件删除成功 componentId={} userId={} requestId={}", id, userId, RequestIdHolder.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ComponentResponse getComponent(Long id) { return detail(require(id)); }
|
||||
|
||||
@Override
|
||||
public PageResponse<ComponentListItemResponse> listComponents(long page, long size, String keyword, String category) {
|
||||
var query = new LambdaQueryWrapper<Component>()
|
||||
.select(Component::getId, Component::getComponentCode, Component::getComponentName,
|
||||
Component::getCategory, Component::getManufacturer, Component::getDescription,
|
||||
Component::getTags, Component::getStepObjectKey, Component::getUrdfMainObjectKey,
|
||||
Component::getVersion, Component::getCreatedAt, Component::getUpdatedAt)
|
||||
.eq(!text(category).isEmpty(), Component::getCategory, text(category));
|
||||
if (!text(keyword).isEmpty()) {
|
||||
query.and(q -> q.like(Component::getComponentName, text(keyword))
|
||||
.or().like(Component::getComponentCode, text(keyword)));
|
||||
}
|
||||
Page<Component> result = componentMapper.selectPage(new Page<>(page, size),
|
||||
query.orderByDesc(Component::getUpdatedAt).orderByDesc(Component::getId));
|
||||
var items = result.getRecords().stream().map(c -> new ComponentListItemResponse(c.getId(),
|
||||
c.getComponentCode(), c.getComponentName(), c.getCategory(), c.getManufacturer(),
|
||||
c.getDescription(), read(c.getTags(), TAGS), urls.resolvePublicUrl(c.getStepObjectKey()),
|
||||
urls.resolvePublicUrl(c.getUrdfMainObjectKey()), c.getVersion(),
|
||||
c.getCreatedAt(), c.getUpdatedAt())).toList();
|
||||
return new PageResponse<>(items, page, size, result.getTotal());
|
||||
}
|
||||
|
||||
private void applyForm(Component component, ComponentForm form) {
|
||||
component.setComponentName(text(form.componentName()));
|
||||
component.setCategory(text(form.category()));
|
||||
component.setManufacturer(text(form.manufacturer()));
|
||||
String description = form.description() == null ? "" : form.description();
|
||||
if (description.getBytes(StandardCharsets.UTF_8).length > 65535) {
|
||||
throw new BizException(422, "INVALID_COMPONENT_FORM", "零件说明超过TEXT字段容量");
|
||||
}
|
||||
component.setDescription(description);
|
||||
component.setMaterial(text(form.material()));
|
||||
component.setMassKg(number(form.massKg()));
|
||||
component.setLengthMm(number(form.lengthMm()));
|
||||
component.setWidthMm(number(form.widthMm()));
|
||||
component.setHeightMm(number(form.heightMm()));
|
||||
component.setTags(objectMapper.valueToTree(form.tags() == null ? List.of()
|
||||
: form.tags().stream().filter(Objects::nonNull).map(String::trim).filter(t -> !t.isEmpty()).distinct().toList()));
|
||||
component.setBasicFields(objectMapper.valueToTree(fields(form.basicFields())));
|
||||
component.setParameterFields(objectMapper.valueToTree(fields(form.parameterFields())));
|
||||
}
|
||||
|
||||
private List<CustomField> fields(List<CustomField> source) {
|
||||
if (source == null) return List.of();
|
||||
Set<String> names = new HashSet<>();
|
||||
return source.stream().map(field -> {
|
||||
String name = text(field.name());
|
||||
if (!names.add(name)) throw new BizException(422, "DUPLICATE_CUSTOM_FIELD", "同一表单中的自定义字段名不可重复");
|
||||
return new CustomField(name, field.value());
|
||||
}).toList();
|
||||
}
|
||||
|
||||
private void applyUrdf(Component component, ComponentUploadSupport.VerifiedUrdf urdf) {
|
||||
component.setUrdfPrefix(urdf.prefix());
|
||||
component.setUrdfMainObjectKey(urdf.mainObjectKey());
|
||||
component.setUrdfFiles(objectMapper.valueToTree(urdf.files()));
|
||||
}
|
||||
|
||||
private ComponentResponse detail(Component c) {
|
||||
return new ComponentResponse(c.getId(), c.getComponentCode(), c.getComponentName(), c.getCategory(),
|
||||
c.getManufacturer(), c.getDescription(), c.getMaterial(), c.getMassKg(), c.getLengthMm(),
|
||||
c.getWidthMm(), c.getHeightMm(), read(c.getTags(), TAGS), read(c.getBasicFields(), FIELDS),
|
||||
read(c.getParameterFields(), FIELDS), c.getStepObjectKey(), urls.resolvePublicUrl(c.getStepObjectKey()),
|
||||
c.getUrdfPrefix(), urls.resolvePublicUrl(c.getUrdfPrefix()), c.getUrdfMainObjectKey(),
|
||||
urls.resolvePublicUrl(c.getUrdfMainObjectKey()), read(c.getUrdfFiles(), FILES),
|
||||
c.getVersion(), c.getCreatedAt(), c.getUpdatedAt());
|
||||
}
|
||||
|
||||
private <T> List<T> read(JsonNode node, TypeReference<List<T>> type) {
|
||||
return node == null ? List.of() : objectMapper.convertValue(node, type);
|
||||
}
|
||||
|
||||
private Component require(Long id) {
|
||||
Component component = componentMapper.selectById(id);
|
||||
if (component == null) throw notFound();
|
||||
return component;
|
||||
}
|
||||
|
||||
private void assertComponentNameAvailable(String componentName, Long excludedId) {
|
||||
Long count = componentMapper.selectCount(new LambdaQueryWrapper<Component>()
|
||||
.eq(Component::getComponentName, componentName)
|
||||
.ne(excludedId != null, Component::getId, excludedId));
|
||||
if (count != null && count > 0) {
|
||||
throw duplicateComponentNameException();
|
||||
}
|
||||
private void snapshot(Component component) {
|
||||
OperationTargetHolder.set("COMPONENT", component.getId() == null ? "" : component.getId().toString(),
|
||||
component.getComponentCode(), component.getComponentName());
|
||||
}
|
||||
|
||||
private BizException duplicateComponentNameException() {
|
||||
return new BizException(HttpStatus.CONFLICT.value(), COMPONENT_NAME_DUPLICATE, COMPONENT_NAME_DUPLICATE_MESSAGE);
|
||||
}
|
||||
|
||||
private void apply(Component component,
|
||||
String componentName,
|
||||
String category,
|
||||
String robotType,
|
||||
String company,
|
||||
String model,
|
||||
String source,
|
||||
String coverImageKey,
|
||||
String description,
|
||||
JsonNode componentJson,
|
||||
ComponentAssemblyMetadata assemblyMetadata) {
|
||||
component.setComponentName(componentName.trim());
|
||||
component.setCategory(normalizeOptionalText(category));
|
||||
component.setRobotType(robotType.trim());
|
||||
component.setCompany(company.trim());
|
||||
component.setModel(model.trim());
|
||||
component.setSource(storageObjectKeys.requireKey(source));
|
||||
component.setCoverImageKey(storageObjectKeys.optionalKey(coverImageKey));
|
||||
component.setDescription(normalizeOptionalText(description));
|
||||
int previousRevision = component.getComponentJson() == null ? 0
|
||||
: component.getComponentJson().path("componentRevision").asInt(0);
|
||||
ObjectNode validated = (ObjectNode) portValidation.validate(componentJson);
|
||||
for (JsonNode resource : validated.path("urdfSource").path("resources")) {
|
||||
String key = storageObjectKeys.requireKey(resource.path("sourceKey").asText());
|
||||
((ObjectNode) resource).put("sourceKey", key);
|
||||
}
|
||||
validated.put("componentRevision", Math.incrementExact(previousRevision));
|
||||
component.setComponentJson(validated);
|
||||
component.setAssemblyMetadata(objectMapper.valueToTree(
|
||||
ComponentTagSupport.mergeLegacy(assemblyMetadata, category)
|
||||
));
|
||||
}
|
||||
|
||||
private ComponentListItemResponse toListItemResponse(Component component) {
|
||||
return new ComponentListItemResponse(
|
||||
component.getId(),
|
||||
component.getComponentName(),
|
||||
component.getCategory(),
|
||||
component.getRobotType(),
|
||||
component.getCompany(),
|
||||
component.getModel(),
|
||||
component.getSource(),
|
||||
objectStorageUrlResolver.resolvePublicUrl(component.getSource()),
|
||||
resolveCoverImageUrl(component.getCoverImageKey()),
|
||||
component.getDescription(),
|
||||
metadataOf(component),
|
||||
component.getCreatedAt(),
|
||||
component.getUpdatedAt()
|
||||
);
|
||||
}
|
||||
|
||||
private ComponentResponse toDetailResponse(Component component) {
|
||||
return new ComponentResponse(
|
||||
component.getId(),
|
||||
component.getComponentName(),
|
||||
component.getCategory(),
|
||||
component.getRobotType(),
|
||||
component.getCompany(),
|
||||
component.getModel(),
|
||||
component.getSource(),
|
||||
objectStorageUrlResolver.resolvePublicUrl(component.getSource()),
|
||||
component.getCoverImageKey(),
|
||||
resolveCoverImageUrl(component.getCoverImageKey()),
|
||||
component.getDescription(),
|
||||
component.getComponentJson(),
|
||||
metadataOf(component),
|
||||
component.getCreatedAt(),
|
||||
component.getUpdatedAt()
|
||||
);
|
||||
}
|
||||
|
||||
private String normalizeOptionalText(String value) {
|
||||
return StringUtils.hasText(value) ? value.trim() : "";
|
||||
}
|
||||
|
||||
private ComponentAssemblyMetadata metadataOf(Component component) {
|
||||
return ComponentTagSupport.metadata(component, objectMapper);
|
||||
}
|
||||
|
||||
private String resolveCoverImageUrl(String coverImageKey) {
|
||||
return objectStorageUrlResolver.resolvePublicUrl(coverImageKey);
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
int expected = current.getComponentJson() == null ? 0 : current.getComponentJson().path("componentRevision").asInt(0);
|
||||
if (revision.intValue() != expected) {
|
||||
throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已修改,请刷新后保存");
|
||||
}
|
||||
private String text(String value) { return value == null ? "" : value.trim(); }
|
||||
private BigDecimal number(BigDecimal value) { return value == null ? BigDecimal.ZERO : value; }
|
||||
private BizException notFound() { return new BizException(404, "COMPONENT_NOT_FOUND", "组件不存在"); }
|
||||
private BizException revisionConflict() {
|
||||
return new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已修改或删除,请刷新后保存");
|
||||
}
|
||||
}
|
||||
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata;
|
||||
import com.linkerbot.cadworld.entity.Component;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/** Read compatibility for catalog entries created before name/tag-based authoring. */
|
||||
final class ComponentTagSupport {
|
||||
private ComponentTagSupport() {}
|
||||
|
||||
private static final Map<String, List<String>> LEGACY_TAGS = Map.ofEntries(
|
||||
Map.entry("torso", List.of("躯干")), Map.entry("head", List.of("头部")),
|
||||
Map.entry("neck", List.of("颈部")), Map.entry("waist", List.of("腰部")),
|
||||
Map.entry("left_arm", List.of("左臂", "手臂")), Map.entry("right_arm", List.of("右臂", "手臂")),
|
||||
Map.entry("left_hand", List.of("左手", "手部")), Map.entry("right_hand", List.of("右手", "手部")),
|
||||
Map.entry("left_leg", List.of("左腿", "腿部")), Map.entry("right_leg", List.of("右腿", "腿部")),
|
||||
Map.entry("left_foot", List.of("左脚", "足部")), Map.entry("right_foot", List.of("右脚", "足部")),
|
||||
Map.entry("unclassified", List.of())
|
||||
);
|
||||
|
||||
static ComponentAssemblyMetadata metadata(Component component, ObjectMapper mapper) {
|
||||
ComponentAssemblyMetadata metadata = component.getAssemblyMetadata() == null || component.getAssemblyMetadata().isNull()
|
||||
? ComponentAssemblyMetadata.empty()
|
||||
: mapper.convertValue(component.getAssemblyMetadata(), ComponentAssemblyMetadata.class);
|
||||
return mergeLegacy(metadata, component.getCategory());
|
||||
}
|
||||
|
||||
static ComponentAssemblyMetadata mergeLegacy(ComponentAssemblyMetadata metadata, String category) {
|
||||
ComponentAssemblyMetadata source = metadata == null ? ComponentAssemblyMetadata.empty() : metadata;
|
||||
List<String> values = new ArrayList<>(source.tags());
|
||||
values.addAll(source.capabilities());
|
||||
if (StringUtils.hasText(category)) values.addAll(LEGACY_TAGS.getOrDefault(category.trim(), List.of(category.trim())));
|
||||
LinkedHashSet<String> tags = new LinkedHashSet<>();
|
||||
values.forEach(value -> {
|
||||
for (String tag : value.split("[,,、;;\\n]")) {
|
||||
if (StringUtils.hasText(tag)) tags.add(tag.trim());
|
||||
}
|
||||
});
|
||||
return new ComponentAssemblyMetadata(List.copyOf(tags), source.capabilities(), source.dimensions());
|
||||
}
|
||||
|
||||
static List<String> searchTerms(String query) {
|
||||
String value = query == null ? "" : query.trim();
|
||||
if (List.of("爪子", "夹爪", "抓取爪").contains(value)) return List.of("爪子", "夹爪", "抓取爪");
|
||||
if (List.of("铲子", "铲具").contains(value)) return List.of("铲子", "铲具");
|
||||
List<String> terms = new ArrayList<>(List.of(value));
|
||||
LEGACY_TAGS.forEach((key, tags) -> {
|
||||
if (tags.contains(value)) terms.add(key);
|
||||
});
|
||||
return terms;
|
||||
}
|
||||
|
||||
static boolean matches(String source, String query) {
|
||||
String text = source == null ? "" : source.toLowerCase(Locale.ROOT);
|
||||
return searchTerms(query).stream().anyMatch(term -> text.contains(term.toLowerCase(Locale.ROOT)));
|
||||
}
|
||||
}
|
||||
+85
-185
@@ -2,229 +2,129 @@ package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.enums.ComponentUploadType;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import com.linkerbot.cadworld.dto.component.UrdfFile;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import java.io.InputStream;
|
||||
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 com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider.UploadSessionClaims;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
import com.linkerbot.cadworld.service.support.UploadLimits;
|
||||
import io.jsonwebtoken.JwtException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentUploadSupport {
|
||||
public static final String UPLOAD_TOKEN_HEADER = "X-Upload-Session-Token";
|
||||
private final StorageProperties properties;
|
||||
private final ObjectStorageClient storage;
|
||||
private final ComponentUploadSessionTokenProvider tokens;
|
||||
private final StorageObjectKeys keys;
|
||||
|
||||
private final StorageProperties storageProperties;
|
||||
private final ObjectStorageClient objectStorageClient;
|
||||
private final ComponentUploadSessionTokenProvider componentUploadSessionTokenProvider;
|
||||
private final StorageObjectKeys storageObjectKeys;
|
||||
|
||||
public PreparedUploadSession prepareUploadSession(Long userId, ComponentUploadType uploadType, String keyPrefixRoot) {
|
||||
Duration uploadSessionTtl = resolveUploadSessionTtl();
|
||||
String keyPrefix = buildKeyPrefix(keyPrefixRoot, userId);
|
||||
java.time.Instant expiresAt = java.time.Instant.now().plus(uploadSessionTtl);
|
||||
return new PreparedUploadSession(
|
||||
componentUploadSessionTokenProvider.generateToken(userId, uploadType, keyPrefix, expiresAt),
|
||||
keyPrefix
|
||||
);
|
||||
}
|
||||
|
||||
public ComponentUploadSessionTokenProvider.UploadSessionClaims requireUploadSession(Long userId,
|
||||
String token,
|
||||
ComponentUploadType expectedType,
|
||||
String invalidCode) {
|
||||
public UploadSessionClaims requireUploadSession(Long userId, String token) {
|
||||
try {
|
||||
ComponentUploadSessionTokenProvider.UploadSessionClaims claims = componentUploadSessionTokenProvider.parseToken(token);
|
||||
if (claims.uploadType() != expectedType) {
|
||||
throw invalidUploadSession(invalidCode, "上传会话类型不匹配");
|
||||
if (!StringUtils.hasText(token)) throw invalidSession();
|
||||
UploadSessionClaims session = tokens.parseToken(token);
|
||||
if (!Objects.equals(userId, session.userId())
|
||||
|| session.componentCode() == null || !session.componentCode().matches("CW-[A-F0-9]{32}")
|
||||
|| session.batch() == null || !session.batch().matches("[a-f0-9]{32}")
|
||||
|| (session.componentId() != null && session.componentId() <= 0)
|
||||
|| !prefix(session.componentCode(), session.batch(), "step").equals(session.stepPrefix())
|
||||
|| !prefix(session.componentCode(), session.batch(), "urdf").equals(session.urdfPrefix())) {
|
||||
throw invalidSession();
|
||||
}
|
||||
if (!StringUtils.hasText(claims.keyPrefix())) {
|
||||
throw invalidUploadSession(invalidCode, "上传会话缺少对象前缀");
|
||||
}
|
||||
storageObjectKeys.requirePrefix(claims.keyPrefix());
|
||||
if (!userId.equals(claims.userId())) {
|
||||
throw invalidUploadSession(invalidCode, "上传会话与当前用户不匹配");
|
||||
}
|
||||
return claims;
|
||||
return session;
|
||||
} catch (JwtException | IllegalArgumentException exception) {
|
||||
throw invalidUploadSession(invalidCode, "上传会话无效或已过期");
|
||||
throw invalidSession();
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> verifyUploadedObjectKeys(String keyPrefix, List<String> submittedObjectKeys) {
|
||||
if (!StringUtils.hasText(keyPrefix) || submittedObjectKeys == null || submittedObjectKeys.isEmpty()) {
|
||||
throw invalidUploadObject("上传文件列表不能为空");
|
||||
}
|
||||
String normalizedPrefix = storageObjectKeys.requirePrefix(keyPrefix);
|
||||
|
||||
final String requiredPrefix = normalizedPrefix;
|
||||
List<String> objectKeys = submittedObjectKeys.stream()
|
||||
.map(this::normalizeObjectKey)
|
||||
.peek(key -> validateSessionObjectKey(requiredPrefix, key))
|
||||
.distinct()
|
||||
.toList();
|
||||
if (objectKeys.size() != submittedObjectKeys.size()) {
|
||||
throw invalidUploadObject("上传文件列表包含重复对象");
|
||||
}
|
||||
for (String objectKey : objectKeys) {
|
||||
if (!objectStorageClient.objectExists(objectKey)) {
|
||||
throw new BizException(
|
||||
HttpStatus.UNPROCESSABLE_ENTITY.value(),
|
||||
"COMPONENT_UPLOAD_OBJECT_MISSING",
|
||||
"未检测到已上传文件: " + objectKey
|
||||
);
|
||||
}
|
||||
}
|
||||
return objectKeys;
|
||||
public String prefix(String code, String batch, String kind) {
|
||||
return keys.requirePrefix(keys.underRoot("components/" + code + "/" + kind + "/" + batch) + "/");
|
||||
}
|
||||
|
||||
public PreparedObjectUpload prepareObjectUpload(Long userId,
|
||||
String uploadSessionToken,
|
||||
ComponentUploadType expectedType,
|
||||
String invalidCode,
|
||||
String objectPath,
|
||||
String contentType) {
|
||||
ComponentUploadSessionTokenProvider.UploadSessionClaims claims = requireUploadSession(
|
||||
userId, uploadSessionToken, expectedType, invalidCode);
|
||||
String objectKey = resolveObjectKey(claims.keyPrefix(), objectPath);
|
||||
return new PreparedObjectUpload(
|
||||
objectStorageClient.createUploadUrl(objectKey, contentType,
|
||||
Duration.between(java.time.Instant.now(), claims.expiresAt())),
|
||||
objectKey,
|
||||
Map.of(UPLOAD_TOKEN_HEADER, uploadSessionToken)
|
||||
);
|
||||
public void requireComponent(UploadSessionClaims session, Long id, String code) {
|
||||
if (!Objects.equals(session.componentId(), id) || !Objects.equals(session.componentCode(), code)) {
|
||||
throw invalidSession();
|
||||
}
|
||||
}
|
||||
|
||||
public String normalizeConfiguredPrefix(String configuredPrefix, String defaultPrefix) {
|
||||
String prefix = StringUtils.hasText(configuredPrefix) ? configuredPrefix.trim() : defaultPrefix;
|
||||
prefix = prefix.replace("\\", "/");
|
||||
while (prefix.startsWith("/")) {
|
||||
prefix = prefix.substring(1);
|
||||
public Duration sessionTtl() { return positiveTtl(properties.uploadSessionTtl(), Duration.ofMinutes(30)); }
|
||||
public Duration signatureTtl() { return positiveTtl(properties.uploadSignatureTtl(), Duration.ofMinutes(5)); }
|
||||
|
||||
private Duration positiveTtl(Duration value, Duration fallback) {
|
||||
Duration ttl = value == null ? fallback : value;
|
||||
if (ttl.isZero() || ttl.isNegative()) {
|
||||
throw new BizException(500, "STORAGE_CONFIG_ERROR", "上传有效期配置必须大于零");
|
||||
}
|
||||
while (prefix.endsWith("/")) {
|
||||
prefix = prefix.substring(0, prefix.length() - 1);
|
||||
}
|
||||
return StringUtils.hasText(prefix) ? prefix : defaultPrefix;
|
||||
return ttl;
|
||||
}
|
||||
|
||||
public Duration resolveUploadSessionTtl() {
|
||||
Duration configured = storageProperties.uploadSessionTtl();
|
||||
if (configured == null) {
|
||||
return Duration.ofMinutes(30);
|
||||
public String verifyStep(UploadSessionClaims session, String submittedKey) {
|
||||
String key = validateSessionObjectKey(session.stepPrefix(), submittedKey);
|
||||
String path = key.substring(session.stepPrefix().length());
|
||||
String lower = path.toLowerCase(Locale.ROOT);
|
||||
if (path.contains("/") || !(lower.endsWith(".step") || lower.endsWith(".stp"))) {
|
||||
throw invalidObject("STEP模型必须为目录下的一个 .step 或 .stp 文件");
|
||||
}
|
||||
if (configured.isZero() || configured.isNegative()) {
|
||||
throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "STORAGE_CONFIG_ERROR", "对象存储上传会话有效期配置非法");
|
||||
}
|
||||
return configured;
|
||||
if (stat(key).contentLength() == 0) throw invalidObject("STEP模型不能为空");
|
||||
return key;
|
||||
}
|
||||
|
||||
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 = storageObjectKeys.underRoot(normalizeConfiguredPrefix(storageProperties.urdfPrefix(), "components/urdf")) + userSegment;
|
||||
String coverPrefix = storageObjectKeys.underRoot(normalizeConfiguredPrefix(storageProperties.coverImagePrefix(), "components/cover-images")) + userSegment;
|
||||
if (!normalizedKey.startsWith(urdfPrefix) && !normalizedKey.startsWith(coverPrefix)) {
|
||||
throw invalidUploadObject("无权上传到该对象路径");
|
||||
public VerifiedUrdf verifyUrdf(UploadSessionClaims session, List<String> submittedKeys) {
|
||||
if (submittedKeys == null || submittedKeys.isEmpty() || submittedKeys.size() > 1000) {
|
||||
throw invalidObject("URDF文件数量必须为1至1000");
|
||||
}
|
||||
UploadLimits.checkLength(contentLength, storageProperties.maxUploadBytes());
|
||||
objectStorageClient.putObject(normalizedKey, contentType,
|
||||
UploadLimits.bounded(inputStream, storageProperties.maxUploadBytes()), contentLength);
|
||||
// 在访问 OSS 前先验证整份清单,避免非法清单触发部分远程读取。
|
||||
List<String> objectKeys = submittedKeys.stream()
|
||||
.map(key -> validateSessionObjectKey(session.urdfPrefix(), key)).toList();
|
||||
if (new HashSet<>(objectKeys).size() != objectKeys.size()) throw invalidObject("文件清单包含重复对象");
|
||||
List<String> mains = objectKeys.stream().filter(key -> key.toLowerCase(Locale.ROOT).endsWith(".urdf")).toList();
|
||||
if (mains.size() != 1) throw invalidObject("URDF目录必须恰好包含一个 .urdf 主文件");
|
||||
List<UrdfFile> files = new ArrayList<>();
|
||||
for (String key : objectKeys) {
|
||||
var object = stat(key);
|
||||
if (key.equals(mains.getFirst()) && object.contentLength() == 0) throw invalidObject("URDF主文件不能为空");
|
||||
files.add(new UrdfFile(key.substring(session.urdfPrefix().length()), object.contentLength()));
|
||||
}
|
||||
return new VerifiedUrdf(session.urdfPrefix(), mains.getFirst(), List.copyOf(files));
|
||||
}
|
||||
|
||||
private ComponentUploadSessionTokenProvider.UploadSessionClaims requireActualUploadSession(Long userId, String token) {
|
||||
private ObjectStorageClient.StoredObject stat(String key) {
|
||||
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) {
|
||||
return new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), code, message);
|
||||
}
|
||||
|
||||
private BizException invalidUploadObject(String message) {
|
||||
return new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", message);
|
||||
}
|
||||
|
||||
private String normalizeObjectKey(String objectKey) {
|
||||
if (!StringUtils.hasText(objectKey)) {
|
||||
throw invalidUploadObject("上传文件路径不能为空");
|
||||
}
|
||||
return storageObjectKeys.requireKey(objectKey);
|
||||
}
|
||||
|
||||
private void validateSessionObjectKey(String keyPrefix, String objectKey) {
|
||||
if (!objectKey.startsWith(keyPrefix) || objectKey.length() <= keyPrefix.length() || objectKey.endsWith("/")) {
|
||||
throw invalidUploadObject("上传文件不属于当前会话");
|
||||
}
|
||||
String relativePath = objectKey.substring(keyPrefix.length());
|
||||
for (String segment : relativePath.split("/")) {
|
||||
if (!StringUtils.hasText(segment) || ".".equals(segment) || "..".equals(segment)) {
|
||||
throw invalidUploadObject("上传文件路径非法");
|
||||
var object = storage.statObject(key);
|
||||
if (object.contentLength() < 0) throw invalidObject("无法确认文件实际大小");
|
||||
UploadLimits.checkLength(object.contentLength(), properties.maxUploadBytes());
|
||||
return object;
|
||||
} catch (BizException exception) {
|
||||
if (exception.getHttpStatus() == 404) {
|
||||
throw new BizException(422, "COMPONENT_UPLOAD_OBJECT_MISSING", "未检测到已上传文件");
|
||||
}
|
||||
}
|
||||
if (objectKey.length() > 512) {
|
||||
throw invalidUploadObject("上传文件路径过长");
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
private String buildKeyPrefix(String keyPrefixRoot, Long userId) {
|
||||
return storageObjectKeys.underRoot(keyPrefixRoot) + "/"
|
||||
+ userId + "/"
|
||||
+ LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + "/"
|
||||
+ UUID.randomUUID() + "/";
|
||||
public String validateSessionObjectKey(String prefix, String submittedKey) {
|
||||
String key = keys.requireKey(submittedKey);
|
||||
if (!key.startsWith(prefix) || key.length() <= prefix.length()) {
|
||||
throw invalidObject("文件不属于当前组件上传目录");
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
private String resolveObjectKey(String keyPrefix, String objectPath) {
|
||||
if (!StringUtils.hasText(objectPath)) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径不能为空");
|
||||
}
|
||||
String normalized = objectPath.trim().replace("\\", "/");
|
||||
if (normalized.startsWith("/") || normalized.endsWith("/")) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径非法");
|
||||
}
|
||||
for (String segment : normalized.split("/")) {
|
||||
if (!StringUtils.hasText(segment) || ".".equals(segment) || "..".equals(segment)) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径非法");
|
||||
}
|
||||
}
|
||||
String objectKey = keyPrefix + normalized;
|
||||
if (objectKey.length() > 512) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径过长");
|
||||
}
|
||||
return storageObjectKeys.requireKey(objectKey);
|
||||
private BizException invalidSession() {
|
||||
return new BizException(422, "INVALID_COMPONENT_UPLOAD_SESSION", "上传会话无效、已过期或与当前组件不匹配");
|
||||
}
|
||||
|
||||
public record PreparedUploadSession(
|
||||
String uploadSessionToken,
|
||||
String keyPrefix
|
||||
) {
|
||||
private BizException invalidObject(String message) {
|
||||
return new BizException(422, "INVALID_COMPONENT_UPLOAD_OBJECT", message);
|
||||
}
|
||||
|
||||
public record PreparedObjectUpload(
|
||||
String uploadUrl,
|
||||
String objectKey,
|
||||
Map<String, String> uploadHeaders
|
||||
) {
|
||||
}
|
||||
public record VerifiedUrdf(String prefix, String mainObjectKey, List<UrdfFile> files) { }
|
||||
}
|
||||
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.enums.ComponentUploadType;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import com.linkerbot.cadworld.service.ComponentUrdfUploadService;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentUrdfUploadServiceImpl implements ComponentUrdfUploadService {
|
||||
|
||||
private static final String DEFAULT_URDF_PREFIX = "components/urdf";
|
||||
private static final int SOURCE_MAX_LENGTH = 255;
|
||||
|
||||
private final StorageProperties storageProperties;
|
||||
private final ComponentUploadSupport componentUploadSupport;
|
||||
|
||||
@Override
|
||||
public PrepareUrdfUploadSessionResponse prepareUploadSession(Long userId) {
|
||||
ComponentUploadSupport.PreparedUploadSession session = componentUploadSupport.prepareUploadSession(
|
||||
userId,
|
||||
ComponentUploadType.URDF,
|
||||
componentUploadSupport.normalizeConfiguredPrefix(storageProperties.urdfPrefix(), DEFAULT_URDF_PREFIX)
|
||||
);
|
||||
return new PrepareUrdfUploadSessionResponse(
|
||||
session.uploadSessionToken(),
|
||||
session.keyPrefix()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request) {
|
||||
ComponentUploadSupport.PreparedObjectUpload upload = componentUploadSupport.prepareObjectUpload(
|
||||
userId,
|
||||
request.uploadSessionToken(),
|
||||
ComponentUploadType.URDF,
|
||||
"INVALID_COMPONENT_UPLOAD_SESSION",
|
||||
request.objectPath(),
|
||||
request.contentType()
|
||||
);
|
||||
return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey(), upload.uploadHeaders());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompleteUrdfUploadResponse completeUploadSession(Long userId, CompleteUrdfUploadRequest request) {
|
||||
ComponentUploadSessionTokenProvider.UploadSessionClaims claims = componentUploadSupport.requireUploadSession(
|
||||
userId,
|
||||
request.uploadSessionToken(),
|
||||
ComponentUploadType.URDF,
|
||||
"INVALID_COMPONENT_UPLOAD_SESSION"
|
||||
);
|
||||
List<String> objectKeys = componentUploadSupport.verifyUploadedObjectKeys(
|
||||
claims.keyPrefix(),
|
||||
request.objectKeys()
|
||||
);
|
||||
String source = resolveMainSource(objectKeys);
|
||||
if (source.length() > SOURCE_MAX_LENGTH) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_MAIN_FILE_PATH_TOO_LONG", "主文件路径过长,无法写入组件 source 字段");
|
||||
}
|
||||
return new CompleteUrdfUploadResponse(source);
|
||||
}
|
||||
|
||||
private String resolveMainSource(List<String> objectKeys) {
|
||||
List<String> urdfKeys = objectKeys.stream()
|
||||
.filter(this::isUrdfFile)
|
||||
.toList();
|
||||
List<String> rfsKeys = objectKeys.stream()
|
||||
.filter(this::isRfsFile)
|
||||
.toList();
|
||||
if (urdfKeys.isEmpty() && rfsKeys.isEmpty()) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_MAIN_FILE_NOT_FOUND", "未检测到 .urdf 或 .rfs 主文件");
|
||||
}
|
||||
if (!urdfKeys.isEmpty() && !rfsKeys.isEmpty()) {
|
||||
throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_MAIN_FILE_TYPE_CONFLICT", "检测到 .urdf 和 .rfs 主文件,二者不能同时存在");
|
||||
}
|
||||
List<String> candidateKeys = urdfKeys.isEmpty() ? rfsKeys : urdfKeys;
|
||||
String extension = urdfKeys.isEmpty() ? ".rfs" : ".urdf";
|
||||
if (candidateKeys.size() > 1) {
|
||||
throw new BizException(
|
||||
HttpStatus.UNPROCESSABLE_ENTITY.value(),
|
||||
"COMPONENT_MAIN_FILE_NOT_UNIQUE",
|
||||
"检测到多个 " + extension + " 主文件,无法确定主文件"
|
||||
);
|
||||
}
|
||||
return candidateKeys.getFirst();
|
||||
}
|
||||
|
||||
private boolean isUrdfFile(String key) {
|
||||
return key.toLowerCase(Locale.ROOT).endsWith(".urdf");
|
||||
}
|
||||
|
||||
private boolean isRfsFile(String key) {
|
||||
String normalized = key.toLowerCase(Locale.ROOT);
|
||||
return normalized.endsWith(".rfs") || normalized.endsWith(".rfs.json");
|
||||
}
|
||||
}
|
||||
-231
@@ -1,231 +0,0 @@
|
||||
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;
|
||||
import com.linkerbot.cadworld.mapper.InterfaceDefinitionRevisionMapper;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
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
|
||||
public class InterfaceDefinitionServiceImpl implements InterfaceDefinitionService {
|
||||
private final InterfaceDefinitionMapper definitionMapper;
|
||||
private final InterfaceDefinitionRevisionMapper revisionMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final MechanicalInterfaceSolver solver;
|
||||
private final StorageObjectKeys storageObjectKeys;
|
||||
|
||||
@Override
|
||||
public List<JsonNode> list(String keyword) {
|
||||
var query = new LambdaQueryWrapper<InterfaceDefinitionEntity>();
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
query.and(matches -> matches.like(InterfaceDefinitionEntity::getName, keyword)
|
||||
.or().like(InterfaceDefinitionEntity::getDescription, keyword));
|
||||
}
|
||||
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) {
|
||||
storageObjectKeys.optionalKey(request.sourceAssetKey());
|
||||
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);
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
|
||||
@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(storageObjectKeys.requireKey(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);
|
||||
}
|
||||
}
|
||||
+27
-33
@@ -1,63 +1,57 @@
|
||||
package com.linkerbot.cadworld.service.support;
|
||||
|
||||
import com.linkerbot.cadworld.config.UploadSessionProperties;
|
||||
import com.linkerbot.cadworld.enums.ComponentUploadType;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import javax.crypto.SecretKey;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 一个组件上传会话同时绑定 STEP 与 URDF,不包含文件内容或表单数据。 */
|
||||
@Component
|
||||
public class ComponentUploadSessionTokenProvider {
|
||||
|
||||
private static final String TOKEN_TYPE_CLAIM = "type";
|
||||
private static final String KEY_PREFIX_CLAIM = "keyPrefix";
|
||||
|
||||
private final UploadSessionProperties properties;
|
||||
private final SecretKey secretKey;
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public ComponentUploadSessionTokenProvider(UploadSessionProperties properties) {
|
||||
this(properties, Clock.systemUTC());
|
||||
}
|
||||
|
||||
public ComponentUploadSessionTokenProvider(UploadSessionProperties properties, Clock clock) {
|
||||
this.properties = properties;
|
||||
this.clock = clock;
|
||||
this.secretKey = properties.secret() == null || properties.secret().isBlank()
|
||||
? Jwts.SIG.HS256.key().build()
|
||||
: Keys.hmacShaKeyFor(properties.secret().getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public String generateToken(Long userId, ComponentUploadType uploadType, String keyPrefix, Instant expiresAt) {
|
||||
return Jwts.builder()
|
||||
.issuer(properties.issuer())
|
||||
.subject(String.valueOf(userId))
|
||||
.claim(TOKEN_TYPE_CLAIM, uploadType.tokenType())
|
||||
.claim(KEY_PREFIX_CLAIM, keyPrefix)
|
||||
.issuedAt(new Date())
|
||||
.expiration(Date.from(expiresAt))
|
||||
.signWith(secretKey)
|
||||
.compact();
|
||||
public String generateToken(UploadSessionClaims session) {
|
||||
return Jwts.builder().issuer(properties.issuer()).subject(String.valueOf(session.userId()))
|
||||
.claim("type", "COMPONENT_UPLOAD").claim("componentId", session.componentId())
|
||||
.claim("componentCode", session.componentCode()).claim("batch", session.batch())
|
||||
.claim("stepPrefix", session.stepPrefix()).claim("urdfPrefix", session.urdfPrefix())
|
||||
.issuedAt(Date.from(clock.instant())).expiration(Date.from(session.expiresAt()))
|
||||
.signWith(secretKey).compact();
|
||||
}
|
||||
|
||||
public UploadSessionClaims parseToken(String token) {
|
||||
Claims claims = parseClaims(token);
|
||||
return new UploadSessionClaims(
|
||||
Long.valueOf(claims.getSubject()),
|
||||
ComponentUploadType.fromTokenType(claims.get(TOKEN_TYPE_CLAIM, String.class)),
|
||||
claims.get(KEY_PREFIX_CLAIM, String.class),
|
||||
claims.getExpiration().toInstant()
|
||||
);
|
||||
Claims claims = Jwts.parser().verifyWith(secretKey).requireIssuer(properties.issuer())
|
||||
.require("type", "COMPONENT_UPLOAD").clock(() -> Date.from(clock.instant()))
|
||||
.build().parseSignedClaims(token).getPayload();
|
||||
Number id = claims.get("componentId", Number.class);
|
||||
return new UploadSessionClaims(Long.valueOf(claims.getSubject()), id == null ? null : id.longValue(),
|
||||
claims.get("componentCode", String.class), claims.get("batch", String.class),
|
||||
claims.get("stepPrefix", String.class), claims.get("urdfPrefix", String.class),
|
||||
claims.getExpiration().toInstant());
|
||||
}
|
||||
|
||||
private Claims parseClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(secretKey)
|
||||
.requireIssuer(properties.issuer())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
public record UploadSessionClaims(Long userId, ComponentUploadType uploadType, String keyPrefix, Instant expiresAt) {
|
||||
}
|
||||
public record UploadSessionClaims(Long userId, Long componentId, String componentCode, String batch,
|
||||
String stepPrefix, String urdfPrefix, Instant expiresAt) { }
|
||||
}
|
||||
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.RigidMath.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MechanicalInterfaceSolverTest {
|
||||
final MechanicalInterfaceSolver solver=new MechanicalInterfaceSolver();
|
||||
MountGeometry geometry(double[][] points){
|
||||
List<Hole> holes=new ArrayList<>();
|
||||
for(int i=0;i<points.length;i++)holes.add(new Hole("h"+i,points[i],new double[]{0,0,1},0.004));
|
||||
return new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),holes);
|
||||
}
|
||||
Definition definition(MountGeometry g){return new Definition("mount",1,"Mount",g,Tolerances.defaults());}
|
||||
MountGeometry square(){return geometry(new double[][]{{-.02,-.02,0},{.02,-.02,0},{.02,.02,0},{-.02,.02,0}});}
|
||||
List<PoseCandidate> poses(Definition d,MountGeometry g){return solver.enumeratePortPoses(d,new PoseRequest(1,"link",g,"source-hash")).candidates();}
|
||||
Port port(Definition d,MountGeometry g,int index){PoseCandidate p=poses(d,g).get(index);return solver.confirmPortPose(d,new Port("port","link",d.id(),1,g,new SelectedPose(p.id(),p.templateInLink(),p.holeMapping(),p.orientationDirectionInLink()),"source-hash",SOLVER_VERSION));}
|
||||
MountGeometry transformed(MountGeometry g,RigidPose pose,boolean reverseNormal){
|
||||
double[] r=rotation(pose);
|
||||
return new MountGeometry(new Plane(point(pose,g.plane().pointM()),scale(rotate(r,g.plane().outwardNormal()),reverseNormal?-1:1)),g.holes().stream().map(h->new Hole(h.id(),point(pose,h.pointOnPlaneM()),rotate(r,h.axis()),h.diameterM())).toList());
|
||||
}
|
||||
@Test void enumeratesGeometrySymmetriesInsteadOfHoleCount(){
|
||||
assertThat(poses(definition(square()),square())).hasSize(4);
|
||||
MountGeometry rectangle=geometry(new double[][]{{-.03,-.02,0},{.03,-.02,0},{.03,.02,0},{-.03,.02,0}});
|
||||
assertThat(poses(definition(rectangle),rectangle)).hasSize(2);
|
||||
MountGeometry pair=geometry(new double[][]{{-.02,0,0},{.02,0,0}});
|
||||
assertThat(poses(definition(pair),pair)).hasSize(2);
|
||||
}
|
||||
@Test void unorderedObservationsHaveStableIds(){
|
||||
MountGeometry g=square();List<Hole> reversed=new ArrayList<>(g.holes());Collections.reverse(reversed);
|
||||
assertThat(poses(definition(g),new MountGeometry(g.plane(),reversed)).stream().map(PoseCandidate::id).toList())
|
||||
.isEqualTo(poses(definition(g),g).stream().map(PoseCandidate::id).toList());
|
||||
}
|
||||
@Test void candidateDirectionsAreUnitAndStableWhenObservationOrderChanges(){
|
||||
MountGeometry g=square();
|
||||
List<PoseCandidate> original=poses(definition(g),g);
|
||||
List<Hole> shuffled=new ArrayList<>(g.holes());
|
||||
Collections.rotate(shuffled,2);
|
||||
List<PoseCandidate> reordered=poses(definition(g),new MountGeometry(g.plane(),shuffled));
|
||||
assertThat(reordered.stream().map(PoseCandidate::id).toList())
|
||||
.isEqualTo(original.stream().map(PoseCandidate::id).toList());
|
||||
for(int i=0;i<original.size();i++) {
|
||||
assertThat(norm(original.get(i).orientationDirectionInLink())).isCloseTo(1.0,within(1e-10));
|
||||
assertThat(reordered.get(i).orientationDirectionInLink())
|
||||
.containsExactly(original.get(i).orientationDirectionInLink());
|
||||
}
|
||||
}
|
||||
@Test void displayForwardRotatesArrowsAndSelectsMatchingMatingBase(){
|
||||
MountGeometry g=geometry(new double[][]{{-.02,0,0},{.02,0,0}});
|
||||
Definition original=definition(g);
|
||||
Definition calibrated=new Definition(original.id(),1,original.name(),g,original.tolerances(),List.of(),new double[]{0,1,0});
|
||||
List<PoseCandidate> before=poses(original,g), after=poses(calibrated,g);
|
||||
assertThat(after).hasSize(2);
|
||||
assertThat(after.stream().map(PoseCandidate::id).toList()).isEqualTo(before.stream().map(PoseCandidate::id).toList());
|
||||
assertThat(dot(after.get(0).orientationDirectionInLink(),after.get(1).orientationDirectionInLink())).isCloseTo(-1,within(1e-10));
|
||||
assertThat(dot(after.get(0).orientationDirectionInLink(),before.get(0).orientationDirectionInLink())).isCloseTo(0,within(1e-10));
|
||||
Port parent=port(original,g,0), child=port(original,g,1);
|
||||
ResolvedConnection oldConnection=solver.resolveLockedConnection(original,parent,child);
|
||||
ResolvedConnection newConnection=solver.resolveLockedConnection(calibrated,parent,child);
|
||||
assertThat(newConnection.childLinkInParentLink().positionM()).containsExactly(oldConnection.childLinkInParentLink().positionM());
|
||||
assertThat(oldConnection.orientationAngleRad()).isCloseTo(0, within(1e-10));
|
||||
assertThat(newConnection.orientationAngleRad()).isCloseTo(0, within(1e-10));
|
||||
}
|
||||
@Test void displayForwardMustBeFiniteNonzeroAndInPlane(){
|
||||
for(double[] forward:new double[][]{{0,0,0},{0,0,1},{Double.NaN,1,0}})
|
||||
assertThatThrownBy(()->solver.validateDefinition(new Definition("mount",1,"Mount",square(),Tolerances.defaults(),List.of(),forward)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
@Test void confirmationAlwaysStoresServerDerivedCandidateDirection(){
|
||||
MountGeometry g=square();Definition d=definition(g);PoseCandidate candidate=poses(d,g).get(0);
|
||||
SelectedPose submittedPose=new SelectedPose(candidate.id(),identity(),List.of(),new double[]{0,0,0});
|
||||
Port confirmed=solver.confirmPortPose(d,new Port("port","link",d.id(),1,g,submittedPose,"source-hash",SOLVER_VERSION));
|
||||
assertThat(confirmed.selectedPose().orientationDirectionInLink())
|
||||
.containsExactly(candidate.orientationDirectionInLink());
|
||||
}
|
||||
@Test void compositeRotationAndTranslationRoundTrip(){
|
||||
MountGeometry g=square();RigidPose transform=compose(pose(new double[]{.3,-.2,.4},rotationAxis(new double[]{0,1,0},Math.PI/2)),pose(new double[3],rotationAxis(new double[]{1,0,0},.71)));
|
||||
MountGeometry moved=transformed(g,transform,false);assertThat(poses(definition(g),moved)).hasSize(4);
|
||||
Port a=port(definition(g),g,0), b=port(definition(g),moved,2);
|
||||
ResolvedConnection resolved=solver.resolveLockedConnection(definition(g),a,b);
|
||||
assertThat(resolved.maxHoleOffsetM()).isLessThan(1e-10);
|
||||
assertThat(resolved.maxAxisAngleRad()).isLessThan(1e-7);
|
||||
}
|
||||
@Test void asymmetricComplementaryFacesMateButSameHandedFacesDoNot(){
|
||||
MountGeometry g=geometry(new double[][]{{0,0,0},{.04,0,0},{.009,.017,0}});
|
||||
Definition d=definition(g);MountGeometry opposite=transformed(g,identity(),true);
|
||||
assertThat(poses(d,g)).hasSize(1);assertThat(poses(d,opposite)).hasSize(1);
|
||||
assertThat(solver.resolveLockedConnection(d,port(d,g,0),port(d,opposite,0)).maxHoleOffsetM()).isLessThan(1e-10);
|
||||
assertThatThrownBy(()->solver.resolveLockedConnection(d,port(d,g,0),port(d,g,0))).hasMessageContaining("对接基准");
|
||||
}
|
||||
@Test void savedSelectionsAreNeverReplacedByBestMatch(){
|
||||
MountGeometry g=square();Definition d=definition(g);Port a=port(d,g,0),b=port(d,g,1);
|
||||
ResolvedConnection first=solver.resolveLockedConnection(d,a,b),second=solver.resolveLockedConnection(d,a,b);
|
||||
assertThat(first.childLinkInParentLink().quaternionXYZW()).containsExactly(second.childLinkInParentLink().quaternionXYZW());
|
||||
assertThat(Arrays.toString(first.childLinkInParentLink().quaternionXYZW())).isNotEqualTo(Arrays.toString(solver.resolveLockedConnection(d,a,a).childLinkInParentLink().quaternionXYZW()));
|
||||
}
|
||||
@Test void badHoleOrAxisRejectsEntirePattern(){
|
||||
MountGeometry g=square();List<Hole> holes=new ArrayList<>(g.holes());Hole h=holes.get(0);
|
||||
holes.set(0,new Hole(h.id(),add(h.pointOnPlaneM(),new double[]{.005,0,0}),h.axis(),h.diameterM()));
|
||||
assertThat(poses(definition(g),new MountGeometry(g.plane(),holes))).isEmpty();
|
||||
holes.set(0,new Hole(h.id(),h.pointOnPlaneM(),unit(new double[]{.2,0,1}),h.diameterM()));
|
||||
assertThat(poses(definition(g),new MountGeometry(g.plane(),holes))).isEmpty();
|
||||
assertThat(solver.enumeratePortPoses(definition(g),new PoseRequest(1,"link",new MountGeometry(g.plane(),holes),"source-hash")).reasons())
|
||||
.anyMatch(reason -> reason.contains("h0") && reason.contains("孔轴"));
|
||||
assertThat(poses(definition(g),new MountGeometry(g.plane(),holes.subList(0,3)))).isEmpty();
|
||||
}
|
||||
@Test void invalidSourceOrVersionFailsClosed(){
|
||||
MountGeometry g=square();Definition d=definition(g);Port p=port(d,g,0);
|
||||
assertThatThrownBy(()->solver.confirmPortPose(d,new Port(p.id(),p.linkName(),p.definitionId(),2,g,p.selectedPose(),p.sourceGeometryHash(),SOLVER_VERSION))).hasMessageContaining("修订");
|
||||
assertThatThrownBy(()->solver.confirmPortPose(d,new Port(p.id(),p.linkName(),p.definitionId(),1,g,p.selectedPose(),"different",SOLVER_VERSION))).hasMessageContaining("失效");
|
||||
}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
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 StorageProperties properties = new StorageProperties("cadworld", "models", "covers", "http://localhost", "http://localhost", Duration.ofMinutes(30), 16);
|
||||
final InterfaceAssetService service = new InterfaceAssetService(definitions, storage, properties,
|
||||
new com.linkerbot.cadworld.service.support.StorageObjectKeys(properties));
|
||||
|
||||
@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("cadworld/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);
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.config.InterfaceBrepProperties;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class InterfaceBrepServiceTest {
|
||||
@TempDir Path temp;
|
||||
|
||||
@Test
|
||||
void invalidExtensionEmptyAndOversizeFilesAreRejectedBeforeProcessLaunch() {
|
||||
InterfaceBrepService service = service("missing", "missing", 1, 3);
|
||||
assertThatThrownBy(() -> service.analyze(file("a.stl", "x"))).hasMessageContaining("STEP");
|
||||
assertThatThrownBy(() -> service.analyze(file("a.step", ""))).hasMessageContaining("请选择");
|
||||
assertThatThrownBy(() -> service.analyze(file("a.step", "large"))).hasMessageContaining("超过");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingExecutableAndMissingScriptHaveExplicitErrors() throws Exception {
|
||||
assertThatThrownBy(() -> service("missing", temp.resolve("missing.py").toString(), 1, 100).analyze(file("a.step", "x")))
|
||||
.hasMessageContaining("脚本不存在");
|
||||
Path script = script("exit 0");
|
||||
assertThatThrownBy(() -> service(temp.resolve("missing-binary").toString(), script.toString(), 1, 100).analyze(file("a.step", "x")))
|
||||
.hasMessageContaining("服务不可用");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validOutputInvalidSchemaAndProcessTimeoutAreHandled() throws Exception {
|
||||
Path valid = script("printf '{\"schemaVersion\":\"interface-step-brep/v1\",\"faces\":[]}' > \"$3\"");
|
||||
assertThat(service("/bin/sh", valid.toString(), 1, 100).analyze(file("a.step", "x")).path("schemaVersion").asText())
|
||||
.isEqualTo("interface-step-brep/v1");
|
||||
Path invalid = script("printf '{\"schemaVersion\":\"unknown\"}' > \"$3\"");
|
||||
assertThatThrownBy(() -> service("/bin/sh", invalid.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("版本");
|
||||
Path slow = script("sleep 5");
|
||||
assertThatThrownBy(() -> service("/bin/sh", slow.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("超时");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingOcpAndInvalidStepRemainDifferentErrors() throws Exception {
|
||||
Path noOcp = script("echo \"No module named 'OCP'\"; exit 1");
|
||||
assertThatThrownBy(() -> service("/bin/sh", noOcp.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("未安装");
|
||||
Path invalid = script("echo 'STEP_BREP_ERROR:invalid topology'; exit 1");
|
||||
assertThatThrownBy(() -> service("/bin/sh", invalid.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("invalid topology");
|
||||
}
|
||||
|
||||
private InterfaceBrepService service(String python, String script, int timeout, long max) {
|
||||
return new InterfaceBrepService(new InterfaceBrepProperties(python, script, timeout, max, 10000), new ObjectMapper());
|
||||
}
|
||||
private Path script(String content) throws Exception {
|
||||
Path script = Files.createTempFile(temp, "extractor-", ".sh");
|
||||
Files.writeString(script, content);
|
||||
return script;
|
||||
}
|
||||
private MockMultipartFile file(String name, String content) {
|
||||
return new MockMultipartFile("file", name, "application/octet-stream", content.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -33,6 +33,6 @@ class StorageObjectKeysTest {
|
||||
}
|
||||
|
||||
private StorageProperties properties(String root) {
|
||||
return new StorageProperties(root, null, null, null, null, Duration.ofMinutes(30));
|
||||
return new StorageProperties(root, null, Duration.ofMinutes(30), Duration.ofMinutes(5), 1024);
|
||||
}
|
||||
}
|
||||
|
||||
+23
-43
@@ -1,34 +1,24 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.*;
|
||||
import com.linkerbot.cadworld.service.client.OssObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
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.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import com.linkerbot.cadworld.config.OssProperties;
|
||||
import com.linkerbot.cadworld.service.client.OssObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class UploadIntegrityTest {
|
||||
final String secret = "test-upload-signing-key-32-bytes-long";
|
||||
|
||||
@Test
|
||||
void unknownLengthUploadIsBoundedAndCannotDestroyExistingObject() throws Exception {
|
||||
var properties = new StorageProperties("cadworld_dev", "components/urdf", "components/cover-images", "http://localhost",
|
||||
"http://localhost", Duration.ofMinutes(30), 8);
|
||||
var keys = new StorageObjectKeys(properties);
|
||||
void unknownLengthUploadIsBoundedAndCannotDestroyExistingObject() {
|
||||
var properties = new StorageProperties("cadworld_dev","http://localhost",
|
||||
Duration.ofMinutes(30),Duration.ofMinutes(5),8);
|
||||
var sdk = mock(OSS.class);
|
||||
var stored = new AtomicReference<byte[]>();
|
||||
when(sdk.putObject(any(PutObjectRequest.class))).thenAnswer(call -> {
|
||||
@@ -36,25 +26,15 @@ class UploadIntegrityTest {
|
||||
stored.set(request.getInputStream().readAllBytes());
|
||||
return null;
|
||||
});
|
||||
var storage = new OssObjectStorageClient(sdk,
|
||||
new OssProperties("test-key", "test-secret", "oss-cn-beijing", "test-bucket"), properties, keys);
|
||||
var tokens = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("upload", secret));
|
||||
var support = new ComponentUploadSupport(properties, storage, tokens, keys);
|
||||
String prefix = "cadworld_dev/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(stored.get()).containsExactly((byte) 1, (byte) 2);
|
||||
verify(sdk, times(1)).putObject(any(PutObjectRequest.class));
|
||||
}
|
||||
|
||||
@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);
|
||||
var client = new OssObjectStorageClient(sdk,
|
||||
new OssProperties("test-key","test-secret","oss-cn-beijing","test-bucket"),
|
||||
properties,new StorageObjectKeys(properties));
|
||||
String key = "cadworld_dev/components/CW-TEST/urdf/batch/robot.urdf";
|
||||
client.putObject(key,"application/octet-stream",new ByteArrayInputStream(new byte[]{1,2}),-1);
|
||||
assertThatThrownBy(() -> client.putObject(key,"application/octet-stream",
|
||||
new ByteArrayInputStream(new byte[9]),-1)).isInstanceOf(BizException.class)
|
||||
.extracting("httpStatus").isEqualTo(413);
|
||||
assertThat(stored.get()).containsExactly((byte)1,(byte)2);
|
||||
verify(sdk,times(1)).putObject(any(PutObjectRequest.class));
|
||||
}
|
||||
}
|
||||
|
||||
+24
-25
@@ -1,37 +1,36 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.config.UploadSessionProperties;
|
||||
import com.linkerbot.cadworld.enums.ComponentUploadType;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
|
||||
import java.time.Duration;
|
||||
import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider.UploadSessionClaims;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class UploadSessionTest {
|
||||
final String secret = "test-upload-signing-key-32-bytes-long";
|
||||
final Instant now = Instant.parse("2026-10-10T12:00:00Z");
|
||||
final Clock clock = Clock.fixed(now, ZoneOffset.UTC);
|
||||
final ComponentUploadSessionTokenProvider tokens = new ComponentUploadSessionTokenProvider(
|
||||
new UploadSessionProperties("upload",secret),clock);
|
||||
|
||||
@Test
|
||||
void tokenTypeOwnerExpiryAndPathAreCheckedIndependentlyOfUserAuthentication() {
|
||||
var tokens = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("test", "test-upload-signing-key-32-bytes-long"));
|
||||
var storage = mock(ObjectStorageClient.class);
|
||||
var properties = new StorageProperties("cadworld", "components/urdf", "components/cover-images", "http://localhost/admin-api/component-assets", "http://localhost", Duration.ofMinutes(30));
|
||||
var support = new ComponentUploadSupport(properties, storage, tokens, new com.linkerbot.cadworld.service.support.StorageObjectKeys(properties));
|
||||
ComponentUploadType type = ComponentUploadType.values()[0];
|
||||
String token = tokens.generateToken(0L, type, "cadworld/components/urdf/0/session/", Instant.now().plusSeconds(60));
|
||||
assertThat(support.requireUploadSession(0L, token, type, "INVALID").userId()).isZero();
|
||||
assertThatThrownBy(() -> support.requireUploadSession(1L, token, type, "INVALID")).hasMessageContaining("用户");
|
||||
ComponentUploadType other = ComponentUploadType.values()[1];
|
||||
assertThatThrownBy(() -> support.requireUploadSession(0L, token, other, "INVALID")).hasMessageContaining("类型");
|
||||
String expired = tokens.generateToken(0L, type, "cadworld/components/urdf/0/session/", Instant.now().minusSeconds(60));
|
||||
assertThatThrownBy(() -> support.requireUploadSession(0L, expired, type, "INVALID")).hasMessageContaining("过期");
|
||||
for (String path : new String[]{"../escape", "/absolute", "a/../../escape", "a//b"}) {
|
||||
assertThatThrownBy(() -> support.prepareObjectUpload(0L, token, type, "INVALID", path, "application/octet-stream"))
|
||||
.hasMessageContaining("路径非法");
|
||||
}
|
||||
verifyNoInteractions(storage);
|
||||
void issuerExpiryAndSignatureAreVerifiedAndOneTokenContainsBothDirectories() {
|
||||
var claims = new UploadSessionClaims(0L,123L,"CW-"+"A".repeat(32),"a".repeat(32),
|
||||
"cadworld_dev/components/CW/step/batch/","cadworld_dev/components/CW/urdf/batch/",now.plusSeconds(60));
|
||||
String token = tokens.generateToken(claims);
|
||||
assertThat(tokens.parseToken(token)).isEqualTo(claims);
|
||||
var other = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("other",secret),clock);
|
||||
assertThatThrownBy(() -> other.parseToken(token)).isInstanceOf(io.jsonwebtoken.JwtException.class);
|
||||
var expired = new UploadSessionClaims(0L,null,claims.componentCode(),claims.batch(),
|
||||
claims.stepPrefix(),claims.urdfPrefix(),now.minusSeconds(1));
|
||||
assertThatThrownBy(() -> tokens.parseToken(tokens.generateToken(expired)))
|
||||
.isInstanceOf(io.jsonwebtoken.ExpiredJwtException.class);
|
||||
String[] parts = token.split("\\.");
|
||||
parts[1] = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString("{\"sub\":\"99\"}".getBytes());
|
||||
assertThatThrownBy(() -> tokens.parseToken(String.join(".",parts)))
|
||||
.isInstanceOf(io.jsonwebtoken.JwtException.class);
|
||||
}
|
||||
}
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.linkerbot.cadworld.service;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.*;
|
||||
import com.linkerbot.cadworld.dto.storage.UploadSignatureRequest;
|
||||
import com.linkerbot.cadworld.entity.Component;
|
||||
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import com.linkerbot.cadworld.service.support.*;
|
||||
import java.time.*;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class UploadSignatureServiceTest {
|
||||
final StorageProperties properties = new StorageProperties("cadworld_dev","http://localhost",
|
||||
Duration.ofMinutes(30),Duration.ofMinutes(5),1024);
|
||||
final ObjectStorageClient storage = mock(ObjectStorageClient.class);
|
||||
final ComponentMapper mapper = mock(ComponentMapper.class);
|
||||
final ComponentUploadSessionTokenProvider tokens = new ComponentUploadSessionTokenProvider(
|
||||
new UploadSessionProperties("upload","test-upload-signing-key-32-bytes-long"));
|
||||
final ComponentUploadSupport support = new ComponentUploadSupport(properties,storage,tokens,new StorageObjectKeys(properties));
|
||||
final UploadSignatureService service = new UploadSignatureService(support,tokens,storage,mapper);
|
||||
|
||||
@BeforeEach
|
||||
void authorize() {
|
||||
when(storage.createUploadAuthorization(anyString(),any())).thenAnswer(call ->
|
||||
new ObjectStorageClient.UploadAuthorization("https://oss.test",Map.of("policy","PRIVATE_POLICY"),call.getArgument(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstSignatureAllocatesCodeWithoutInsertingAndReturnsTwoBoundDirectories() {
|
||||
var response = service.sign(7L,new UploadSignatureRequest(null,null));
|
||||
assertThat(response.componentCode()).matches("CW-[A-F0-9]{32}");
|
||||
assertThat(response.urdf().keyPrefix()).isEqualTo(response.step().keyPrefix().replace("/step/","/urdf/"));
|
||||
var session = tokens.parseToken(response.uploadSessionToken());
|
||||
assertThat(session.userId()).isEqualTo(7L);
|
||||
assertThat(session.componentId()).isNull();
|
||||
assertThat(session.stepPrefix()).isEqualTo(response.step().keyPrefix());
|
||||
assertThat(response.expiresAt()).isBeforeOrEqualTo(response.sessionExpiresAt());
|
||||
assertThat(response.toString()).doesNotContain(response.uploadSessionToken(),"PRIVATE_POLICY");
|
||||
assertThat(response.step().toString()).doesNotContain("PRIVATE_POLICY");
|
||||
verifyNoInteractions(mapper);
|
||||
verify(storage,times(2)).createUploadAuthorization(anyString(),any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renewsWithinRemainingSessionTimeAndRejectsMixedParametersOrWrongOwner() {
|
||||
var first = service.sign(7L,new UploadSignatureRequest(null,null));
|
||||
var session = tokens.parseToken(first.uploadSessionToken());
|
||||
Instant expiry = Instant.now().plusSeconds(30).truncatedTo(java.time.temporal.ChronoUnit.SECONDS);
|
||||
String token = tokens.generateToken(new ComponentUploadSessionTokenProvider.UploadSessionClaims(7L,null,
|
||||
session.componentCode(),session.batch(),session.stepPrefix(),session.urdfPrefix(),expiry));
|
||||
var renewed = service.sign(7L,new UploadSignatureRequest(null,token));
|
||||
assertThat(renewed.expiresAt()).isEqualTo(expiry);
|
||||
assertThat(renewed.sessionExpiresAt()).isEqualTo(expiry);
|
||||
assertThat(renewed.step().keyPrefix()).isEqualTo(first.step().keyPrefix());
|
||||
assertThatThrownBy(() -> service.sign(8L,new UploadSignatureRequest(null,token)))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("INVALID_COMPONENT_UPLOAD_SESSION");
|
||||
assertThatThrownBy(() -> service.sign(7L,new UploadSignatureRequest(1L,token)))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("INVALID_UPLOAD_SIGNATURE_REQUEST");
|
||||
assertThatThrownBy(() -> service.sign(7L,new UploadSignatureRequest(null,"")))
|
||||
.isInstanceOf(BizException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void editingUsesExistingCodeWithNewBatchAndDeletedComponentCannotRenew() {
|
||||
Component component = new Component();
|
||||
component.setId(123L); component.setComponentCode("CW-"+"B".repeat(32));
|
||||
when(mapper.selectById(123L)).thenReturn(component);
|
||||
var first = service.sign(7L,new UploadSignatureRequest(123L,null));
|
||||
var second = service.sign(7L,new UploadSignatureRequest(123L,null));
|
||||
assertThat(first.componentCode()).isEqualTo(component.getComponentCode());
|
||||
assertThat(second.step().keyPrefix()).isNotEqualTo(first.step().keyPrefix());
|
||||
assertThat(tokens.parseToken(first.uploadSessionToken()).componentId()).isEqualTo(123L);
|
||||
when(mapper.selectById(123L)).thenReturn(null);
|
||||
assertThatThrownBy(() -> service.sign(7L,new UploadSignatureRequest(null,first.uploadSessionToken())))
|
||||
.isInstanceOf(BizException.class).extracting("httpStatus").isEqualTo(404);
|
||||
}
|
||||
}
|
||||
+59
-7
@@ -34,12 +34,12 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
class OssObjectStorageClientTest {
|
||||
final OSS sdk = mock(OSS.class);
|
||||
final StorageProperties storage = new StorageProperties("cadworld_dev", "components/urdf", "components/cover-images",
|
||||
"https://admin.test/admin-api/component-assets", "https://admin.test", Duration.ofMinutes(30), 8);
|
||||
final StorageProperties storage = new StorageProperties("cadworld_dev",
|
||||
"https://admin.test/admin-api/component-assets", Duration.ofMinutes(30), Duration.ofMinutes(5), 8);
|
||||
final StorageObjectKeys keys = new StorageObjectKeys(storage);
|
||||
final OssProperties properties = new OssProperties("PRIVATE_ACCESS_KEY", "PRIVATE_SECRET", "oss-cn-beijing", "test-bucket");
|
||||
final OssObjectStorageClient client = new OssObjectStorageClient(sdk, properties, storage, keys);
|
||||
final String key = "cadworld_dev/components/urdf/0/session/model.rfs";
|
||||
final String key = "cadworld_dev/components/CW-TEST/urdf/batch/model.urdf";
|
||||
|
||||
@Test
|
||||
void java21JaxbRuntimeCanParseSdkErrorModels() throws Exception {
|
||||
@@ -57,15 +57,67 @@ class OssObjectStorageClientTest {
|
||||
assertThat(properties.endpoint()).isEqualTo("https://oss-cn-beijing.aliyuncs.com");
|
||||
assertThat(new OssProperties("a", "b", "cn-beijing", "c").endpoint()).isEqualTo(properties.endpoint());
|
||||
assertThat(properties.toString()).doesNotContain(properties.accessKeyId(), properties.accessKeySecret());
|
||||
assertThat(client.createUploadUrl(key, null, Duration.ofMinutes(1)))
|
||||
.isEqualTo("https://admin.test/admin-api/component-assets/upload?objectKey=" + key);
|
||||
assertThatThrownBy(() -> client.createUploadUrl(key, null, Duration.ZERO))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("STORAGE_CONFIG_ERROR");
|
||||
assertThatThrownBy(() -> new OssProperties("", "secret", "oss-cn-beijing", "bucket").validate())
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("OSS_ACCESS_KEY_ID");
|
||||
verifyNoInteractions(sdk);
|
||||
}
|
||||
|
||||
@Test
|
||||
void v4PostSignatureUsesUtcDateAndExactDirectoryPolicyWithoutNetwork() throws Exception {
|
||||
var signingTime = java.time.Instant.parse("2026-10-10T23:59:58Z");
|
||||
var expiry = signingTime.plusSeconds(300);
|
||||
OSS localSdk = new com.linkerbot.cadworld.config.OssClientConfiguration().ossClient(properties);
|
||||
try {
|
||||
var signer = new OssObjectStorageClient(localSdk, properties, storage, keys,
|
||||
java.time.Clock.fixed(signingTime,java.time.ZoneOffset.UTC));
|
||||
var result = signer.createUploadAuthorization("cadworld_dev/components/urdf/0/session/", expiry);
|
||||
var fields = result.uploadFields();
|
||||
assertThat(result.uploadUrl()).isEqualTo("https://test-bucket.oss-cn-beijing.aliyuncs.com/");
|
||||
assertThat(fields.get("x-oss-date")).isEqualTo("20261010T235958Z");
|
||||
assertThat(fields.get("x-oss-credential")).isEqualTo("PRIVATE_ACCESS_KEY/20261010/cn-beijing/oss/aliyun_v4_request");
|
||||
String policy = new String(java.util.Base64.getDecoder().decode(fields.get("policy")),java.nio.charset.StandardCharsets.UTF_8);
|
||||
var json = new com.fasterxml.jackson.databind.ObjectMapper().readTree(policy);
|
||||
assertThat(java.time.Instant.parse(json.path("expiration").asText())).isEqualTo(expiry);
|
||||
var conditions = json.path("conditions");
|
||||
assertThat(conditions.toString()).contains("[\"starts-with\",\"$key\",\"cadworld_dev/components/urdf/0/session/\"]", "[\"content-length-range\",0,8]");
|
||||
for (var entry : fields.entrySet()) {
|
||||
if (!entry.getKey().equals("policy") && !entry.getKey().equals("x-oss-signature")) {
|
||||
assertThat(conditions.toString()).contains(entry.getKey(),entry.getValue());
|
||||
}
|
||||
}
|
||||
assertThat(conditions.toString()).contains("test-bucket", "x-oss-forbid-overwrite", "true").doesNotContain("Content-Type");
|
||||
// Independent HMAC calculation verifies the SDK overload, raw-vs-base64 policy and UTC scope.
|
||||
byte[] signingKey = hmac(("aliyun_v4"+properties.accessKeySecret()).getBytes(java.nio.charset.StandardCharsets.UTF_8),"20261010");
|
||||
signingKey = hmac(signingKey,"cn-beijing");
|
||||
signingKey = hmac(signingKey,"oss");
|
||||
signingKey = hmac(signingKey,"aliyun_v4_request");
|
||||
String expected = java.util.HexFormat.of().formatHex(hmac(signingKey,fields.get("policy")));
|
||||
assertThat(fields.get("x-oss-signature")).isEqualTo(expected);
|
||||
assertThat(result.toString()).doesNotContain(fields.get("policy"),expected,properties.accessKeySecret());
|
||||
} finally { localSdk.shutdown(); }
|
||||
}
|
||||
|
||||
private byte[] hmac(byte[] key, String data) throws Exception {
|
||||
var mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(new javax.crypto.spec.SecretKeySpec(key,"HmacSHA256"));
|
||||
return mac.doFinal(data.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingFailureReturnsSafeErrorAndNeverLogsPolicyOrSdkExceptionMessage() {
|
||||
when(sdk.generatePostPolicy(any(),any())).thenThrow(new ClientException("PRIVATE_SIGNED_POLICY_AND_SECRET"));
|
||||
var logger = (Logger) LoggerFactory.getLogger(OssObjectStorageClient.class);
|
||||
var captured = new ListAppender<ILoggingEvent>(); captured.start(); logger.addAppender(captured);
|
||||
try {
|
||||
assertThatThrownBy(() -> client.createUploadAuthorization("cadworld_dev/session/",java.time.Instant.now().plusSeconds(60)))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("OSS_UPLOAD_SIGN_FAILED");
|
||||
assertThat(captured.list).allSatisfy(event -> {
|
||||
assertThat(event.getFormattedMessage()).doesNotContain("PRIVATE_SIGNED_POLICY_AND_SECRET",properties.accessKeySecret());
|
||||
assertThat(event.getThrowableProxy()).isNull();
|
||||
});
|
||||
} finally { logger.detachAppender(captured); captured.stop(); }
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadsExactKeyMetadataAndBytes() {
|
||||
when(sdk.putObject(any(PutObjectRequest.class))).thenAnswer(call -> {
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ComponentCoverImageUploadServiceImplTest {
|
||||
|
||||
@Test
|
||||
void acceptsGifCoverObjectsAlongsideExistingImageTypes() throws Exception {
|
||||
ComponentCoverImageUploadServiceImpl service = new ComponentCoverImageUploadServiceImpl(null, null, null);
|
||||
Method method = ComponentCoverImageUploadServiceImpl.class.getDeclaredMethod("isSupportedImage", String.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertTrue((Boolean) method.invoke(service, "projects/cover/cover.GIF"));
|
||||
assertTrue((Boolean) method.invoke(service, "projects/cover/cover.webp"));
|
||||
assertFalse((Boolean) method.invoke(service, "projects/cover/cover.svg"));
|
||||
}
|
||||
}
|
||||
+29
-179
@@ -1,191 +1,41 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.common.api.OperationTargetHolder;
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentResponse;
|
||||
import com.linkerbot.cadworld.config.StorageProperties;
|
||||
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
|
||||
import com.linkerbot.cadworld.entity.Component;
|
||||
import com.linkerbot.cadworld.mapper.ComponentMapper;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.SimpleTransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ComponentServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private ComponentMapper componentMapper;
|
||||
@Mock
|
||||
private ObjectStorageUrlResolver objectStorageUrlResolver;
|
||||
|
||||
private ComponentServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new ComponentServiceImpl(
|
||||
componentMapper,
|
||||
objectStorageUrlResolver,
|
||||
new ObjectMapper(), new com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService(
|
||||
MechanicalTestFixtures.definitions(),MechanicalTestFixtures.SOLVER,new ObjectMapper(),
|
||||
new com.linkerbot.cadworld.mechanicalinterface.UrdfSourceValidation(),
|
||||
org.mockito.Mockito.mock(com.linkerbot.cadworld.mechanicalinterface.UrdfAssetVerifier.class)),
|
||||
new com.linkerbot.cadworld.service.support.StorageObjectKeys(
|
||||
new com.linkerbot.cadworld.config.StorageProperties("cadworld", null, null, null, null, java.time.Duration.ofMinutes(30))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createComponentRejectsDuplicateNameBeforeInsert() {
|
||||
when(componentMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
assertThatThrownBy(() -> service.createComponent(1L, request(" 机械臂 ")))
|
||||
.isInstanceOf(BizException.class)
|
||||
.extracting("code", "httpStatus", "message")
|
||||
.containsExactly("COMPONENT_NAME_DUPLICATE", HttpStatus.CONFLICT.value(), "组件名称已存在,请更换名称");
|
||||
verify(componentMapper, never()).insert(any(Component.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createComponentMapsDuplicateKeyToBizException() {
|
||||
when(componentMapper.selectCount(any())).thenReturn(0L);
|
||||
when(componentMapper.insert(any(Component.class))).thenThrow(new DuplicateKeyException("Duplicate entry"));
|
||||
|
||||
assertThatThrownBy(() -> service.createComponent(1L, request("机械臂")))
|
||||
.isInstanceOf(BizException.class)
|
||||
.extracting("code", "httpStatus", "message")
|
||||
.containsExactly("COMPONENT_NAME_DUPLICATE", HttpStatus.CONFLICT.value(), "组件名称已存在,请更换名称");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"arm_1", "arm_2", "arm_3", "arm_4", "arm_5", "arm_6", "arm_7", "arm_8"})
|
||||
void createComponentAcceptsManipulatorSegments(String componentType) {
|
||||
AtomicReference<Component> inserted = new AtomicReference<>();
|
||||
when(componentMapper.selectCount(any())).thenReturn(0L);
|
||||
when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
|
||||
Component component = invocation.getArgument(0);
|
||||
component.setId(99L);
|
||||
inserted.set(component);
|
||||
return 1;
|
||||
});
|
||||
when(componentMapper.selectById(99L)).thenAnswer(invocation -> inserted.get());
|
||||
|
||||
ComponentResponse response = service.createComponent(1L, request("机械臂-" + componentType, componentType, "manipulator"));
|
||||
|
||||
assertThat(response.componentType()).isEqualTo(componentType);
|
||||
assertThat(response.robotType()).isEqualTo("manipulator");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"torso", "head", "neck", "waist",
|
||||
"left_arm", "right_arm", "left_hand", "right_hand",
|
||||
"left_leg", "right_leg", "left_foot", "right_foot"
|
||||
})
|
||||
void createComponentAcceptsHumanoidSplitComponentTypes(String componentType) {
|
||||
AtomicReference<Component> inserted = new AtomicReference<>();
|
||||
when(componentMapper.selectCount(any())).thenReturn(0L);
|
||||
when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
|
||||
Component component = invocation.getArgument(0);
|
||||
component.setId(99L);
|
||||
inserted.set(component);
|
||||
return 1;
|
||||
});
|
||||
when(componentMapper.selectById(99L)).thenAnswer(invocation -> inserted.get());
|
||||
|
||||
ComponentResponse response = service.createComponent(1L, request("人形-" + componentType, componentType, "humanoid"));
|
||||
|
||||
assertThat(response.componentType()).isEqualTo(componentType);
|
||||
assertThat(response.robotType()).isEqualTo("humanoid");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createComponentAllowsFreeCategoryRegardlessOfRobotSource() {
|
||||
AtomicReference<Component> inserted = new AtomicReference<>();
|
||||
when(componentMapper.selectCount(any())).thenReturn(0L);
|
||||
when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
|
||||
Component component = invocation.getArgument(0);
|
||||
component.setId(101L);
|
||||
inserted.set(component);
|
||||
return 1;
|
||||
});
|
||||
when(componentMapper.selectById(101L)).thenAnswer(invocation -> inserted.get());
|
||||
|
||||
ComponentResponse response = service.createComponent(1L, request("机械臂躯干", "安装基座", "manipulator"));
|
||||
|
||||
assertThat(response.category()).isEqualTo("安装基座");
|
||||
assertThat(response.robotType()).isEqualTo("manipulator");
|
||||
verify(componentMapper).insert(any(Component.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createComponentDoesNotRestrictCategoryToRobotSource() {
|
||||
AtomicReference<Component> inserted = new AtomicReference<>();
|
||||
when(componentMapper.selectCount(any())).thenReturn(0L);
|
||||
when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
|
||||
Component component = invocation.getArgument(0);
|
||||
component.setId(102L);
|
||||
inserted.set(component);
|
||||
return 1;
|
||||
});
|
||||
when(componentMapper.selectById(102L)).thenAnswer(invocation -> inserted.get());
|
||||
|
||||
ComponentResponse response = service.createComponent(1L, request("人形机械臂一段", "柔性执行器", "humanoid"));
|
||||
|
||||
assertThat(response.category()).isEqualTo("柔性执行器");
|
||||
assertThat(response.robotType()).isEqualTo("humanoid");
|
||||
verify(componentMapper).insert(any(Component.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsNameAndTagsWithoutCategoryOrDescription() {
|
||||
AtomicReference<Component> inserted = new AtomicReference<>();
|
||||
when(componentMapper.selectCount(any())).thenReturn(0L);
|
||||
when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
|
||||
Component value = invocation.getArgument(0);
|
||||
value.setId(103L); inserted.set(value); return 1;
|
||||
});
|
||||
when(componentMapper.selectById(103L)).thenAnswer(invocation -> inserted.get());
|
||||
var metadata = new com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata(
|
||||
java.util.List.of("工具", "末端执行器,铲取"), java.util.List.of(), null);
|
||||
var request = new CreateComponentRequest("铲子", null, "humanoid", "未指定", "未指定",
|
||||
"cadworld/shovel.rfs", "", null, new ObjectMapper().createObjectNode(), metadata);
|
||||
try (var factory = jakarta.validation.Validation.buildDefaultValidatorFactory()) {
|
||||
assertThat(factory.getValidator().validate(request)).isEmpty();
|
||||
}
|
||||
var response = service.createComponent(1L, request);
|
||||
assertThat(response.category()).isEmpty();
|
||||
assertThat(response.description()).isEmpty();
|
||||
assertThat(response.assemblyMetadata().tags()).containsExactly("工具", "末端执行器", "铲取");
|
||||
}
|
||||
|
||||
private CreateComponentRequest request(String componentName) {
|
||||
return request(componentName, "left_arm", "humanoid");
|
||||
}
|
||||
|
||||
private CreateComponentRequest request(String componentName, String componentType, String robotType) {
|
||||
return new CreateComponentRequest(
|
||||
componentName,
|
||||
componentType,
|
||||
robotType,
|
||||
"示例公司",
|
||||
"M1",
|
||||
"cadworld/components/urdf/arm.urdf",
|
||||
"",
|
||||
"示例组件",
|
||||
new ObjectMapper().createObjectNode()
|
||||
);
|
||||
void concurrentChangeBetweenReadAndWriteIsRejectedByConditionalDatabaseUpdate() {
|
||||
ComponentMapper mapper = mock(ComponentMapper.class);
|
||||
Component component = new Component();
|
||||
component.setId(1L); component.setComponentCode("CW-"+"A".repeat(32)); component.setVersion(1L);
|
||||
when(mapper.selectById(1L)).thenReturn(component);
|
||||
when(mapper.update(any(Component.class),any(com.baomidou.mybatisplus.core.conditions.Wrapper.class))).thenReturn(0);
|
||||
PlatformTransactionManager manager = mock(PlatformTransactionManager.class);
|
||||
when(manager.getTransaction(any())).thenReturn(new SimpleTransactionStatus());
|
||||
var service = new ComponentServiceImpl(mapper,new ObjectMapper(),
|
||||
new ObjectStorageUrlResolver(new StorageProperties("cadworld_dev","http://localhost",
|
||||
Duration.ofMinutes(30),Duration.ofMinutes(5),1024)),
|
||||
mock(ComponentUploadSupport.class),new TransactionTemplate(manager));
|
||||
var request = new UpdateComponentRequest(null,"测试","分类",null,null,null,
|
||||
null,null,null,null,null,null,null,1L,null,null,null);
|
||||
try {
|
||||
assertThatThrownBy(() -> service.updateComponent(0L,1L,request))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("COMPONENT_REVISION_CONFLICT");
|
||||
verify(manager).rollback(any());
|
||||
} finally { OperationTargetHolder.clear(); }
|
||||
}
|
||||
}
|
||||
|
||||
+34
-74
@@ -1,90 +1,50 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import com.linkerbot.cadworld.common.exception.BizException;
|
||||
import com.linkerbot.cadworld.config.*;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.support.*;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class ComponentUploadSupportTest {
|
||||
|
||||
private static final String KEY_PREFIX = "cadworld/components/urdf/1/20260920/session-id/";
|
||||
final StorageProperties properties = new StorageProperties("cadworld_dev","http://localhost",
|
||||
Duration.ofMinutes(30),Duration.ofMinutes(5),8);
|
||||
final ObjectStorageClient storage = mock(ObjectStorageClient.class);
|
||||
final ComponentUploadSupport support = new ComponentUploadSupport(properties,storage,
|
||||
new ComponentUploadSessionTokenProvider(new UploadSessionProperties("upload","test-upload-signing-key-32-bytes-long")),
|
||||
new StorageObjectKeys(properties));
|
||||
final String code = "CW-"+"A".repeat(32), batch = "a".repeat(32);
|
||||
final ComponentUploadSessionTokenProvider.UploadSessionClaims session =
|
||||
new ComponentUploadSessionTokenProvider.UploadSessionClaims(0L,null,code,batch,
|
||||
support.prefix(code,batch,"step"),support.prefix(code,batch,"urdf"),Instant.now().plusSeconds(60));
|
||||
|
||||
@Test
|
||||
void verifiesExactObjectsWithoutListingTheBucket() {
|
||||
RecordingObjectStorageClient storageClient = new RecordingObjectStorageClient(List.of(
|
||||
KEY_PREFIX + "LeKiwi.rfs",
|
||||
KEY_PREFIX + "meshes/body.stl"
|
||||
));
|
||||
ComponentUploadSupport support = createSupport(storageClient);
|
||||
|
||||
List<String> objectKeys = support.verifyUploadedObjectKeys(KEY_PREFIX, List.of(
|
||||
KEY_PREFIX + "LeKiwi.rfs",
|
||||
KEY_PREFIX + "meshes/body.stl"
|
||||
));
|
||||
|
||||
assertEquals(List.of(
|
||||
KEY_PREFIX + "LeKiwi.rfs",
|
||||
KEY_PREFIX + "meshes/body.stl"
|
||||
), objectKeys);
|
||||
assertEquals(objectKeys, storageClient.checkedObjectKeys);
|
||||
void validatesEntireManifestBeforeAccessingStorageAndRejectsUnknownSize() {
|
||||
String main = session.urdfPrefix()+"robot.urdf";
|
||||
assertThatThrownBy(() -> support.verifyUrdf(session,List.of(main,main)))
|
||||
.isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> support.verifyUrdf(session,List.of(main,"cadworld_dev/outside.stl")))
|
||||
.isInstanceOf(BizException.class);
|
||||
verifyNoInteractions(storage);
|
||||
when(storage.statObject(main)).thenReturn(new ObjectStorageClient.StoredObject(null,-1));
|
||||
assertThatThrownBy(() -> support.verifyUrdf(session,List.of(main)))
|
||||
.isInstanceOf(BizException.class).extracting("code").isEqualTo("INVALID_COMPONENT_UPLOAD_OBJECT");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnObjectOutsideTheUploadSessionPrefix() {
|
||||
RecordingObjectStorageClient storageClient = new RecordingObjectStorageClient(List.of());
|
||||
ComponentUploadSupport support = createSupport(storageClient);
|
||||
|
||||
BizException exception = assertThrows(BizException.class, () -> support.verifyUploadedObjectKeys(
|
||||
KEY_PREFIX,
|
||||
List.of("cadworld/components/urdf/1/another-session/LeKiwi.rfs")
|
||||
));
|
||||
|
||||
assertEquals("INVALID_COMPONENT_UPLOAD_OBJECT", exception.getCode());
|
||||
assertEquals(List.of(), storageClient.checkedObjectKeys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsAnObjectThatWasNotUploaded() {
|
||||
RecordingObjectStorageClient storageClient = new RecordingObjectStorageClient(List.of());
|
||||
ComponentUploadSupport support = createSupport(storageClient);
|
||||
|
||||
BizException exception = assertThrows(BizException.class, () -> support.verifyUploadedObjectKeys(
|
||||
KEY_PREFIX,
|
||||
List.of(KEY_PREFIX + "missing.rfs")
|
||||
));
|
||||
|
||||
assertEquals("COMPONENT_UPLOAD_OBJECT_MISSING", exception.getCode());
|
||||
}
|
||||
|
||||
private ComponentUploadSupport createSupport(ObjectStorageClient storageClient) {
|
||||
return new ComponentUploadSupport(null, storageClient, null,
|
||||
new com.linkerbot.cadworld.service.support.StorageObjectKeys(
|
||||
new com.linkerbot.cadworld.config.StorageProperties("cadworld", null, null, null, null, Duration.ofMinutes(30))));
|
||||
}
|
||||
|
||||
private static final class RecordingObjectStorageClient implements ObjectStorageClient {
|
||||
|
||||
private final List<String> existingObjectKeys;
|
||||
private final List<String> checkedObjectKeys = new ArrayList<>();
|
||||
|
||||
private RecordingObjectStorageClient(List<String> existingObjectKeys) {
|
||||
this.existingObjectKeys = existingObjectKeys;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createUploadUrl(String objectKey, String contentType, Duration duration) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean objectExists(String objectKey) {
|
||||
checkedObjectKeys.add(objectKey);
|
||||
return existingObjectKeys.contains(objectKey);
|
||||
}
|
||||
void stepRejectsSubdirectoriesAndWrongExtensionAndAllowsStpCaseInsensitively() {
|
||||
assertThatThrownBy(() -> support.verifyStep(session,session.stepPrefix()+"nested/model.step"))
|
||||
.isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> support.verifyStep(session,session.stepPrefix()+"model.stl"))
|
||||
.isInstanceOf(BizException.class);
|
||||
verifyNoInteractions(storage);
|
||||
String key = session.stepPrefix()+"model.STP";
|
||||
when(storage.statObject(key)).thenReturn(new ObjectStorageClient.StoredObject(null,2));
|
||||
assertThat(support.verifyStep(session,key)).isEqualTo(key);
|
||||
}
|
||||
}
|
||||
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.entity.InterfaceDefinitionEntity;
|
||||
import com.linkerbot.cadworld.entity.InterfaceDefinitionRevisionEntity;
|
||||
import com.linkerbot.cadworld.mapper.InterfaceDefinitionMapper;
|
||||
import com.linkerbot.cadworld.mapper.InterfaceDefinitionRevisionMapper;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
class InterfaceDefinitionRevisionTest {
|
||||
final ObjectMapper json=new ObjectMapper();
|
||||
final InterfaceDefinitionMapper definitions=mock(InterfaceDefinitionMapper.class);
|
||||
final InterfaceDefinitionRevisionMapper revisions=mock(InterfaceDefinitionRevisionMapper.class);
|
||||
final InterfaceDefinitionServiceImpl service=new InterfaceDefinitionServiceImpl(definitions,revisions,json,new MechanicalInterfaceSolver(),
|
||||
new com.linkerbot.cadworld.service.support.StorageObjectKeys(
|
||||
new com.linkerbot.cadworld.config.StorageProperties("cadworld", null, null, null, null, java.time.Duration.ofMinutes(30))));
|
||||
final MountGeometry geometry=new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),List.of(
|
||||
new Hole("a",new double[]{-.02,0,0},new double[]{0,0,1},.004),
|
||||
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.setEditRevision(1L);
|
||||
e.setGeometryJson(json.valueToTree(geometry));e.setTolerancesJson(json.valueToTree(Tolerances.defaults()));
|
||||
e.setSourceGeometryHash("sha256:old");e.setSourceAssetKey("cadworld/interfaces/old.step");
|
||||
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).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",dto(changedGeometry()));
|
||||
assertThat(result.path("geometryRevision").asInt()).isEqualTo(2);
|
||||
assertThat(result.path("sourceAssetKey").asText()).isEqualTo("cadworld/interfaces/old.step");
|
||||
ArgumentCaptor<InterfaceDefinitionRevisionEntity> capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
|
||||
verify(revisions).insert(capture.capture());assertThat(capture.getValue().getId()).isEqualTo("mount:2");
|
||||
verify(revisions,never()).updateById(any(InterfaceDefinitionRevisionEntity.class));
|
||||
}
|
||||
@Test void staleEditsAndAssetUploadsAreRejected(){
|
||||
current();assertThatThrownBy(()->service.update("mount",dto(request().put("geometryRevision",2)))).hasMessageContaining("刷新");
|
||||
assertThatThrownBy(()->service.attachAsset("mount",2,"other.step","sha256:new","cadworld/interfaces/old.step")).hasMessageContaining("修订");
|
||||
assertThatThrownBy(()->service.attachAsset("mount",1,"other.step","sha256:new","cadworld/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",dto(body));
|
||||
assertThat(result.path("geometryRevision").asInt()).isEqualTo(1);
|
||||
assertThat(result.path("displayForward")).isEqualTo(body.path("displayForward"));
|
||||
ArgumentCaptor<InterfaceDefinitionRevisionEntity> capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
|
||||
verify(revisions).updateById(capture.capture());verify(revisions,never()).insert(any(InterfaceDefinitionRevisionEntity.class));
|
||||
when(revisions.selectById("mount:1")).thenReturn(capture.getValue());
|
||||
assertThat(service.geometryDefinition("mount",1).displayForward()).containsExactly(0,1,0);
|
||||
}
|
||||
@Test void replacingSourceClearsOldAssetAndAttachesOnlyToNewRevision(){
|
||||
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");
|
||||
service.attachAsset("mount",2,"cadworld/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("cadworld/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, "cadworld/interfaces/loser.step", "sha256:old", ""))
|
||||
.isInstanceOf(com.linkerbot.cadworld.common.exception.BizException.class)
|
||||
.hasMessageContaining("绑定已变化");
|
||||
assertThat(entity.getSourceAssetKey()).isEqualTo("cadworld/interfaces/old.step");
|
||||
verify(definitions, never()).updateById(any(InterfaceDefinitionEntity.class));
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package com.linkerbot.cadworld.service.impl;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.entity.Component;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.*;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import java.util.*;
|
||||
|
||||
final class MechanicalTestFixtures {
|
||||
static final ObjectMapper JSON=new ObjectMapper();
|
||||
static final MechanicalInterfaceSolver SOLVER=new MechanicalInterfaceSolver();
|
||||
static final String XML="<robot name=\"fixture\"><link name=\"base\"/></robot>";
|
||||
static final String DOCUMENT_HASH=UrdfSourceValidation.hash(XML);
|
||||
static final String SOURCE_HASH=UrdfSourceValidation.hash(DOCUMENT_HASH+"\n");
|
||||
static MountGeometry geometry() {
|
||||
return new MountGeometry(new Plane(new double[3],new double[]{0,0,1}), List.of(
|
||||
new Hole("h0",new double[]{-.02,-.02,0},new double[]{0,0,1},.004),
|
||||
new Hole("h1",new double[]{.02,-.02,0},new double[]{0,0,1},.004),
|
||||
new Hole("h2",new double[]{.02,.02,0},new double[]{0,0,1},.004),
|
||||
new Hole("h3",new double[]{-.02,.02,0},new double[]{0,0,1},.004)));
|
||||
}
|
||||
static Definition definition() { return new Definition("square",1,"Square",geometry(),Tolerances.defaults()); }
|
||||
static InterfaceDefinitionService definitions() {
|
||||
var service=mock(InterfaceDefinitionService.class);
|
||||
lenient().when(service.geometryDefinition("square",1)).thenReturn(definition());
|
||||
lenient().when(service.get("square")).thenReturn(JSON.valueToTree(Map.of("geometryRevision",1)));
|
||||
return service;
|
||||
}
|
||||
static ObjectNode source() {
|
||||
ObjectNode result=JSON.createObjectNode(); result.put("xml",XML);result.put("documentHash",DOCUMENT_HASH);
|
||||
result.put("sourceGeometryHash",SOURCE_HASH);result.putArray("resources");return result;
|
||||
}
|
||||
static Port port(String id,int candidate) {
|
||||
var pose=SOLVER.enumeratePortPoses(definition(),new PoseRequest(1,"base",geometry(),SOURCE_HASH)).candidates().get(candidate);
|
||||
return SOLVER.confirmPortPose(definition(),new Port(id,"base","square",1,geometry(),new SelectedPose(pose.id(),pose.templateInLink(),pose.holeMapping(),pose.orientationDirectionInLink()),SOURCE_HASH,SOLVER_VERSION));
|
||||
}
|
||||
static Component component(long id,int candidate,String... portIds) {
|
||||
Component component=new Component();component.setId(id);component.setComponentName("component-"+id);component.setSource("uploaded.rfs");
|
||||
ObjectNode json=JSON.createObjectNode();json.put("interfaceSchemaVersion",3);json.put("componentRevision",1);json.set("urdfSource",source());
|
||||
json.set("interfaces",JSON.valueToTree(Arrays.stream(portIds).map(name->port(name,candidate)).toList()));
|
||||
component.setComponentJson(json);return component;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user