diff --git a/cadworld-adminapi/docs/admin-api.md b/cadworld-adminapi/docs/admin-api.md index 3c4d82c..2323ef9 100644 --- a/cadworld-adminapi/docs/admin-api.md +++ b/cadworld-adminapi/docs/admin-api.md @@ -2,6 +2,8 @@ 后台保留组件库、用户管理、操作日志三个模块。以下路径以 `/admin-api` 为前缀,默认服务地址 `http://127.0.0.1:8992`。 +用户端匹配与拼装接口由独立的 `cadworld-api` 服务提供,默认端口8991,详见[用户端 API 文档](../../cadworld-api/docs/api.md)。用户端默认组件、替代候选和详情同时返回 `bomList`、`urdfInfo`,通过编码访问组件,模型直接使用公开OSS/CDN地址。 + ## 1. 通用约定 JSON 请求设置 `Content-Type: application/json`。当前没有登录认证,操作人来自 `APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME`,默认 `0 / TEST_OPERATOR`。上传令牌与该操作人绑定。 diff --git a/cadworld-api/docs/api.md b/cadworld-api/docs/api.md new file mode 100644 index 0000000..6a133db --- /dev/null +++ b/cadworld-api/docs/api.md @@ -0,0 +1,640 @@ +# 用户端组件匹配与拼装 API(前端联调文档) + +本文说明前端如何提交拼装需求、展示匹配结果、切换替代组件及加载模型。示例编码和模型域名仅用于说明,实际结果取决于组件库。 + +## 1. 接口总览 + +本地默认服务地址:`http://127.0.0.1:8991`。线上地址由部署环境提供。 + +| 方法 | 路径 | 用途 | +| --- | --- | --- | +| POST | `/api/robot-matches` | 按需求匹配组件,返回默认拼装方案和兼容替代组件 | +| GET | `/api/components/{componentCode}` | 按组件编码获取详情,包括 BOM、URDF 信息和模型地址 | + +当前两个接口无需登录凭证。组件使用 `componentCode` 标识,不返回数据库 ID。模型通过响应中的公开 OSS/CDN 地址加载。 + +## 2. 请求与通用返回 + +POST 请求头: + +```http +Content-Type: application/json +X-Request-Id: frontend-match-001 +``` + +`X-Request-Id` 可选,用于联调排查;省略时后端生成。响应头和响应体均返回请求编号。 + +```json +{ + "code": "OK", + "message": "success", + "data": {}, + "requestId": "frontend-match-001" +} +``` + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `code` | string | `OK` 表示接口执行成功;其他值为错误编码 | +| `message` | string | 成功时为 `success`,失败时为错误说明 | +| `data` | object / null | 成功时为接口数据,失败时为 null | +| `requestId` | string | 请求编号,反馈问题时一并提供 | + +**HTTP 200 和 `code=OK` 表示请求执行成功,拼装是否达标需要继续检查 `data.status`。** 没有匹配组件时也返回 HTTP 200;请求参数错误返回 422,详情组件不存在或已删除返回 404,数据库不可用返回 503。 + +## 3. 匹配接口 + +`POST /api/robot-matches` + +### 3.1 请求示例 + +只指定所需角色即可匹配: + +```json +{ + "requiredParts": ["torso_0", "arm_r"] +} +``` + +包含关键词、整机条件和部件条件的请求: + +```json +{ + "userInput": "我要一个双足跑步机器人,整体20自由度,质量不超过10kg,躯干用铝合金,右臂扭矩至少20N·m", + "requirements": ["双足", "机器人", "跑步"], + "requiredParts": [ + "torso_0", "head_0", "waist_0", "arm_l", "arm_r", "hand_l", "hand_r", + "pedal_l", "pedal_r", "foot_l", "foot_r" + ], + "robotRequirements": { + "degreesOfFreedom": 20, + "functionDescription": "跑步", + "massKg": 10, + "operators": {"massKg": "lte"} + }, + "partRequirements": [ + {"category": "torso_0", "material": "铝合金"}, + {"category": "arm_r", "torqueNm": 20, "operators": {"torqueNm": "gte"}} + ] +} +``` + +### 3.2 顶层入参 + +| 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `userInput` | string | 否 | 最多 4000 字符,仅作上下文;后端不解析、不存储,也不覆盖结构化条件 | +| `requirements` | string[] | 否 | 最多 32 个关键词,每个非空且最多 128 字符;省略/null 表示无关键词要求 | +| `requiredParts` | string[] | 是 | 非空,最多 24 项;中英文别名归一化后去重,每个角色只选一个实例 | +| `robotRequirements` | object | 否 | 整机条件,字段见下表 | +| `partRequirements` | object[] | 否 | 最多 12 项;每项对应一个角色的条件,字段见下表 | + +`userInput` 中写出的条件不会自动生效,前端必须同时提供相应结构化字段。例如“质量不超过 10kg”需要传 `massKg: 10` 和 `operators.massKg: "lte"`。 + +### 3.3 整机条件 `robotRequirements` + +所有字段均可选。 + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `degreesOfFreedom` | integer | 标称总自由度,非负整数 | +| `massKg` | number | 整机质量目标,单位 kg,非负 | +| `functionDescription` | string | 整机功能要求,最多 512 字符,例如“跑步” | +| `operators` | object | 数值比较方式,只支持已提供的 `degreesOfFreedom`、`massKg` | + +### 3.4 部件条件 `partRequirements[]` + +| 字段 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `category` | string | 是 | 组件角色,必须包含在 `requiredParts` 中;同一角色不能重复定义条件 | +| `material` | string | 否 | 材质,最多 128 字符,例如“铝合金” | +| `degreesOfFreedom` | integer | 否 | 该部件自由度,非负整数 | +| `massKg` | number | 否 | 该部件质量目标,单位 kg,非负 | +| `torqueNm` | number | 否 | 该部件扭矩目标,单位 N·m,非负 | +| `functionDescription` | string | 否 | 功能要求,最多 512 字符 | +| `shape` | string | 否 | 形状要求,最多 128 字符 | +| `size` | string | 否 | 大小描述要求,最多 128 字符,例如“中型”;不是数值尺寸比较 | +| `operators` | object | 否 | 数值比较方式,只支持已提供的 `degreesOfFreedom`、`massKg`、`torqueNm` | + +### 3.5 数值、空值与运算符 + +可选条件省略或传 null 表示不约束该字段。字符串裁剪首尾空白,空字符串也表示不约束。显式传 `0` 表示要求数值为 0,与不传条件不同。 + +自由度只接受 0 至 2147483647 的 JSON 整数;`1.0`、`"1"`、布尔值和越界值均不合法。质量与扭矩使用 JSON 数值,最多 12 位整数、6 位小数。 + +| 运算符 | 含义 | 示例 | +| --- | --- | --- | +| `eq` | 等于,省略时的默认值 | `degreesOfFreedom: 20` 表示总自由度等于 20 | +| `gte` | 大于或等于 | `torqueNm: 20` 配合 `operators.torqueNm: "gte"` 表示至少 20 N·m | +| `lte` | 小于或等于 | `massKg: 10` 配合 `operators.massKg: "lte"` 表示不超过 10 kg | + +`operators` 不能对应未提供目标值的字段,也不能用于文本字段。未知请求字段、非法角色、重复部件条件、负数和非法运算符均返回 HTTP 422。 + +材质按同义词归一化后的等值匹配;功能、形状、大小按文本包含关系匹配。这些条件都可能因找不到合适组件而放宽,实际差异见 `unmetRequirements`。 + +### 3.6 角色映射 + +| 中文类型 | 标准编码 | +| --- | --- | +| 躯干_0 | torso_0 | +| 头_0 | head_0 | +| 腰_0 | waist_0 | +| 臂_l、臂_r | arm_l、arm_r | +| 手_l、手_r | hand_l、hand_r | +| 足_l、足_r | pedal_l、pedal_r | +| 脚_l、脚_r | foot_l、foot_r | +| 尾_0 | tail_0 | + +输入接受中英文别名和英文大小写,响应返回标准编码。左右侧独立;`pedal` 对应足,`foot` 对应脚。 + +### 3.7 匹配结果的业务约定 + +先按角色查询未删除组件,再评价参数、材质和关键词。默认同义词包括跑步/奔跑/跑动/running、机器人/robot、双足/两足/biped/bipedal、铝合金/aluminum alloy/aluminium alloy。材质采用同义词归一化后的等值匹配,功能、形状和大小采用扩展后的包含匹配。名称、分类、功能、说明、材质、形状和大小参与关键词评价。 + +优先返回能够覆盖更多所需部件的方案,再尽量满足参数、材质和关键词。参数与材质可以放宽,角色和连接规则始终保持匹配。不自动加入 `requiredParts` 之外的中间连接件。 + +有可用的所需躯干时优先以躯干为根;否则尝试其他所需角色。无法覆盖所有角色时返回可拼的连通部分,至少保留一个可用根组件。单个组件没有安装端口时仍可作为根或叶节点。 + +整机自由度和质量按选中组件字段求和,**不重复累加BOM,不从URDF再次计算**。质量为0视为未填写;只要一个组件质量未知,`totals.massKg=null`、`massComplete=false`,已知部分保存在 `knownMassKg`。不能据此宣布满足质量上限。功能命中表示元数据相关,不代表动力学验证。 + +拼装候选必须有 URDF 主文件,且 `urdfInfo` 是包含非空 `rootLink` 和 `frames` 数组的对象。父帧的 `interfaceType` 对应子角色,连接到子组件的 `rootLink`。结果为无环连通组合,每个端口最多使用一次。异常端口会被忽略,前端应使用返回的 `connections` 完成拼装。 + +`bomList` 和 `urdfInfo` 始终作为原始 JSON 返回,保留嵌套内容;详情里的 `urdfInfo` 也可能是其他对象或数组。接口匹配只评价元数据和连接类型,不验证机械承载或运动性能。 + +## 4. 匹配结果 + +### 4.1 `data` 字段 + +| 字段 | 类型 | 内容 | +| --- | --- | --- | +| `status` | string | 匹配状态,见下表 | +| `rootCategory` | string / null | 根角色;无结果时为 null | +| `parts` | object[] | 默认选中组件,字段见 4.2 | +| `connections` | object[] | 默认方案的整套父子连接,字段见 4.4 | +| `alternatives` | object[] | 每个已选角色一个分组,每组最多 5 个兼容替代组件,字段见 4.5 | +| `totals` | object | 默认方案的整机汇总,字段见 4.6 | +| `unmetRequirements` | object[] | 未满足的整机或部件条件,字段见 4.7 | +| `unmatchedKeywords` | string[] | 没有任何选中组件元数据命中的关键词 | +| `missingParts` | object[] | 未加入组合的角色和原因,字段见 4.7 | +| `searchLimited` | boolean | 搜索是否达到候选/搜索限制;true 时仍可展示当前方案,但不代表已找到最优方案或证明组件库无解 | + +| status | 含义 | +| --- | --- | +| `MATCHED` | 所需角色完整,所有提供条件和关键词均满足 | +| `FALLBACK` | 角色完整,部分条件或关键词不满足 | +| `PARTIAL` | 返回连通部分,存在缺失角色;也可能有参数不满足 | +| `NO_MATCH` | 没有可用装配候选,parts和connections为空;HTTP仍为200 | + +`searchLimited` 与 `status` 独立,例如 `MATCHED` 也可能同时返回 `searchLimited=true`。数组无内容时返回 `[]`。`parts` 的顺序不保证与请求一致,前端使用 `category` 和 `componentCode` 定位组件。 + +### 4.2 公开组件字段 + +`parts[]`、`alternatives[].items[].component` 和详情接口的 `data` 使用同一结构。 + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `componentCode` | string | 组件唯一编码,用于获取详情和区分组件 | +| `componentName` | string | 组件名称 | +| `category` | string | 组件角色;匹配结果使用标准英文编码 | +| `description` | string | 组件说明 | +| `material` | string | 材质 | +| `massKg` | number | 组件质量,单位 kg;0 表示未填写 | +| `degreesOfFreedom` | integer | 组件标称自由度 | +| `functionDescription` | string | 功能描述 | +| `shape` | string | 形状描述 | +| `size` | string | 大小描述 | +| `torqueNm` | number | 扭矩,单位 N·m | +| `bomList` | object / array | 原始 BOM JSON,内部结构由组件数据决定;允许 `{}`、`[]` 和嵌套内容 | +| `urdfInfo` | object / array | 原始 URDF 信息 JSON,保留完整 frames、axis、limits 等;匹配结果中为带 `rootLink`、`frames` 的对象 | +| `version` | integer | 组件数据版本号 | +| `stepUrl` | string | 公开 STEP 文件地址;没有文件时为空字符串 | +| `urdfUrl` | string | 公开 URDF 主文件地址;详情没有文件时为空字符串 | + +两个 JSON 字段均直接作为对象或数组使用,无需再执行 `JSON.parse`。组件未填写的描述字段可能为空字符串。响应不包含数据库 ID、独立 OSS 对象键、目录前缀、内部文件清单或上传令牌。 + +### 4.3 完整成功响应示例 + +以下响应对应 3.1 的最小请求 `{"requiredParts":["torso_0","arm_r"]}`,不是包含 11 个角色的整机请求。组件库提供了躯干、默认右臂和一个兼容的替代右臂。 + +```json +{ + "code": "OK", "message": "success", "requestId": "example-request", + "data": { + "status": "MATCHED", "rootCategory": "torso_0", + "parts": [ + { + "componentCode": "CW-00000000000000000000000000000001", + "componentName": "铝合金躯干", "category": "torso_0", "description": "机器人躯干", + "material": "铝合金", "massKg": 2, "degreesOfFreedom": 0, + "functionDescription": "支撑", "shape": "宽躯干", "size": "中型", "torqueNm": 0, + "bomList": {"items": [{"code": "BOLT-M4", "quantity": 4}]}, + "urdfInfo": { + "robotName": "torso", "rootLink": "BASE", + "frames": [{ + "name": "J1", "kind": "joint", "type": "fixed", "parent": "BASE", + "child": "LINK_arm_r", "interfaceType": "arm_r", "originExplicit": true, + "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0], + "axis": [0, 0, 0], "limits": {} + }] + }, + "version": 1, + "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP", + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf" + }, + { + "componentCode": "CW-00000000000000000000000000000002", + "componentName": "右臂", "category": "arm_r", "description": "机器人右臂", + "material": "铝合金", "massKg": 1, "degreesOfFreedom": 4, + "functionDescription": "摆臂", "shape": "", "size": "", "torqueNm": 20, + "bomList": [{"code": "ACTUATOR", "quantity": 4}], + "urdfInfo": {"robotName": "arm", "rootLink": "ARM_BASE", "frames": []}, + "version": 1, + "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/step/batch/model.STEP", + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/urdf/batch/robot.urdf" + } + ], + "connections": [{ + "parentCategory": "torso_0", "parentComponentCode": "CW-00000000000000000000000000000001", + "parentLink": "BASE", "frameName": "J1", "childCategory": "arm_r", + "childComponentCode": "CW-00000000000000000000000000000002", "childRootLink": "ARM_BASE", + "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0] + }], + "alternatives": [ + {"category": "torso_0", "items": []}, + { + "category": "arm_r", + "items": [ + { + "component": { + "componentCode": "CW-00000000000000000000000000000003", + "componentName": "高扭矩右臂", "category": "arm_r", "description": "机器人右臂", + "material": "铝合金", "massKg": 1.2, "degreesOfFreedom": 4, + "functionDescription": "摆臂", "shape": "", "size": "", "torqueNm": 25, + "bomList": [{"code": "ACTUATOR-25", "quantity": 4, "spec": {"torqueNm": 25}}], + "urdfInfo": {"robotName": "arm_v2", "rootLink": "ARM_V2_BASE", "frames": []}, + "version": 1, + "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/step/batch/model.STEP", + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/urdf/batch/robot.urdf" + }, + "connections": [{ + "parentCategory": "torso_0", "parentComponentCode": "CW-00000000000000000000000000000001", + "parentLink": "BASE", "frameName": "J1", "childCategory": "arm_r", + "childComponentCode": "CW-00000000000000000000000000000003", "childRootLink": "ARM_V2_BASE", + "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0] + }], + "totals": {"degreesOfFreedom": 4, "massKg": 3.2, "knownMassKg": 3.2, "massComplete": true}, + "unmetRequirements": [], + "unmatchedKeywords": [] + } + ] + } + ], + "totals": {"degreesOfFreedom": 4, "massKg": 3, "knownMassKg": 3, "massComplete": true}, + "unmetRequirements": [], "unmatchedKeywords": [], "missingParts": [], "searchLimited": false + } +} +``` + +### 4.4 连接字段 `connections[]` + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `parentCategory` | string | 父组件角色 | +| `parentComponentCode` | string | 父组件编码 | +| `parentLink` | string | 父组件模型内部的连接基准 link | +| `frameName` | string | 父组件用于安装的帧名称 | +| `childCategory` | string | 子组件角色 | +| `childComponentCode` | string | 子组件编码 | +| `childRootLink` | string | 子组件模型根 link | +| `xyz` | number[3] | 相对于父 `parentLink` 的平移 `[x,y,z]`,单位米 | +| `rpy` | number[3] | 相对于父 `parentLink` 的旋转 `[roll,pitch,yaw]`,单位弧度 | + +位姿不是世界坐标。示例中将右臂的 `ARM_BASE` 对齐到躯干 `BASE` 下的给定位姿。不同组件的 link 名称可能相同,应在对应组件实例内查找。 + +### 4.5 替代候选 `alternatives[]` + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `category` | string | 当前可替换的角色 | +| `items` | object[] | 0 至 5 个兼容替代项,空数组表示没有提供替代组件 | +| `items[].component` | object | 替代组件的完整公开数据,包括 BOM 和 URDF 信息 | +| `items[].connections` | object[] | 替换后的**整套**连接,不只是该部件的局部连接 | +| `items[].totals` | object | 替换后的整机汇总 | +| `items[].unmetRequirements` | object[] | 替换后的未满足条件 | +| `items[].unmatchedKeywords` | string[] | 替换后的未命中关键词 | + +替代组件兼容当前父组件和全部当前子组件,保持当前父子拓扑;仍可能不满足用户的材质、数值或文本要求。替换父组件时连接位姿可能改变,替换子组件时根 link 可能改变。 + +前端选择一个替代项后,应按角色替换 `parts` 中的组件,并整体采用该项的 `connections`、`totals`、`unmetRequirements` 和 `unmatchedKeywords`。上例替换右臂后,编码变为 `CW-00000000000000000000000000000003`,根 link 变为 `ARM_V2_BASE`,整机质量变为 3.2 kg。 + +替代项没有独立 `status`,可根据当前 `missingParts` 和替代项的未满足条件/关键词重新展示状态。这些替代项针对本次默认方案计算;多个角色的替代项不能直接任意组合。重新请求会生成新的默认方案,当前接口没有锁定已选编码或校验多部件替换的入参。 + +### 4.6 汇总 `totals` + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `degreesOfFreedom` | integer | 所选组件标称自由度之和 | +| `massKg` | number / null | 全部已选组件质量已知时的总质量;有未知质量时为 null | +| `knownMassKg` | number | 仅已知质量部分的合计 | +| `massComplete` | boolean | 是否所有已选组件质量均已填写;无组件时为 false | + +`PARTIAL` 的汇总只覆盖已返回的组件。`massComplete=true` 表示这些组件的质量已知,不表示所需角色齐全。不要把组件 `massKg=0` 或汇总 `massKg=null` 展示成真实的零质量。 + +### 4.7 未满足条件和缺件 + +`unmetRequirements[]` 字段: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `scope` | string | `PART` 表示部件条件,`ROBOT` 表示整机条件 | +| `category` | string / null | 部件标准角色;整机条件为 null | +| `field` | string | 未满足的请求字段,如 `torqueNm`、`massKg`、`material` | +| `operator` | string | 数值为 `eq/gte/lte`,材质为 `eq`,功能/形状/大小为 `contains` | +| `expected` | number / string | 用户要求的目标值 | +| `actual` | number / string / null | 实际值;未知质量或未命中的整机功能可为 null | +| `reason` | string | 原因,见下表 | + +| `unmetRequirements.reason` | 展示含义 | +| --- | --- | +| `VALUE_MISMATCH` | 数值不满足目标 | +| `UNKNOWN_MASS` | 质量未填写,无法确认是否满足质量要求 | +| `NO_TEXT_MATCH` | 材质、功能、形状或大小未命中 | + +`missingParts[]` 每项包含 `category`(缺失角色)和 `reason`(原因): + +| `missingParts.reason` | 展示含义 | +| --- | --- | +| `NO_COMPONENT` | 组件库没有该角色的可用组件 | +| `INVALID_ASSEMBLY_METADATA` | 有该角色的组件,但 URDF 文件或拼装信息不完整 | +| `NO_COMPATIBLE_CONNECTION` | 有候选组件,但未找到与当前组合兼容的连接 | +| `SEARCH_LIMIT` | 达到搜索限制,本次未找到可加入的组件 | + +### 4.8 降级示例:`FALLBACK` + +请求要求能跑步、质量不超过 2 kg、右臂扭矩至少 30 N·m: + +```json +{ + "requirements": ["跑步"], + "requiredParts": ["torso_0", "arm_r"], + "robotRequirements": { + "massKg": 2, + "functionDescription": "跑步", + "operators": {"massKg": "lte"} + }, + "partRequirements": [ + {"category": "arm_r", "torqueNm": 30, "operators": {"torqueNm": "gte"}} + ] +} +``` + +例如找到可拼装的完整组合,但合计 3.2 kg、右臂扭矩 25 N·m,且未命中跑步功能。HTTP 200、`code=OK`,下面仅展示 **`data` 的状态字段片段**;实际响应仍包含完整 `parts`、`connections` 和 `alternatives`: + +```json +{ + "status": "FALLBACK", + "rootCategory": "torso_0", + "totals": {"degreesOfFreedom": 4, "massKg": 3.2, "knownMassKg": 3.2, "massComplete": true}, + "unmetRequirements": [ + { + "scope": "PART", "category": "arm_r", "field": "torqueNm", "operator": "gte", + "expected": 30, "actual": 25, "reason": "VALUE_MISMATCH" + }, + { + "scope": "ROBOT", "category": null, "field": "massKg", "operator": "lte", + "expected": 2, "actual": 3.2, "reason": "VALUE_MISMATCH" + }, + { + "scope": "ROBOT", "category": null, "field": "functionDescription", "operator": "contains", + "expected": "跑步", "actual": null, "reason": "NO_TEXT_MATCH" + } + ], + "unmatchedKeywords": ["跑步"], + "missingParts": [], + "searchLimited": false +} +``` + +前端可以展示模型,同时提示“已提供可拼装方案,部分要求未满足”,并列出质量、扭矩和功能差异。 + +### 4.9 缺件示例:`PARTIAL` + +请求: + +```json +{ + "requiredParts": ["torso_0", "head_0", "arm_r"] +} +``` + +例如仅返回躯干和右臂的连通组合,组件库没有头部。HTTP 200、`code=OK`,以下为 **`data` 的状态字段片段**,实际响应的 `parts` 包含这两个组件: + +```json +{ + "status": "PARTIAL", + "rootCategory": "torso_0", + "totals": {"degreesOfFreedom": 4, "massKg": 3, "knownMassKg": 3, "massComplete": true}, + "unmetRequirements": [], + "unmatchedKeywords": [], + "missingParts": [{"category": "head_0", "reason": "NO_COMPONENT"}], + "searchLimited": false +} +``` + +前端展示已返回的组件,并提示缺失头部;不能把这份汇总作为完整整机数据。 + +### 4.10 无可用组件示例:`NO_MATCH` + +请求: + +```json +{ + "requirements": ["跑步"], + "requiredParts": ["torso_0", "arm_r"] +} +``` + +例如这两个角色都没有可用组件,返回 HTTP 200。**完整响应**: + +```json +{ + "code": "OK", + "message": "success", + "requestId": "frontend-match-004", + "data": { + "status": "NO_MATCH", + "rootCategory": null, + "parts": [], + "connections": [], + "alternatives": [], + "totals": {"degreesOfFreedom": 0, "massKg": null, "knownMassKg": 0, "massComplete": false}, + "unmetRequirements": [], + "unmatchedKeywords": ["跑步"], + "missingParts": [ + {"category": "torso_0", "reason": "NO_COMPONENT"}, + {"category": "arm_r", "reason": "NO_COMPONENT"} + ], + "searchLimited": false + } +} +``` + +前端展示“暂无可拼装组件”,结合 `missingParts` 提示原因。数据库故障属于接口错误,会返回 HTTP 503,不会返回此状态。 + +## 5. 组件详情 + +`GET /api/components/{componentCode}`,无请求体。 + +| 路径参数 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `componentCode` | string | 是 | 组件编码,非空且最多 64 字符;使用匹配结果中的编码 | + +请求示例: + +```http +GET /api/components/CW-00000000000000000000000000000001 +X-Request-Id: frontend-detail-001 +``` + +HTTP 200,完整响应示例: + +```json +{ + "code": "OK", + "message": "success", + "requestId": "frontend-detail-001", + "data": { + "componentCode": "CW-00000000000000000000000000000001", + "componentName": "铝合金躯干", + "category": "torso_0", + "description": "机器人躯干", + "material": "铝合金", + "massKg": 2, + "degreesOfFreedom": 0, + "functionDescription": "支撑", + "shape": "宽躯干", + "size": "中型", + "torqueNm": 0, + "bomList": { + "items": [{"code": "BOLT-M4", "quantity": 4}] + }, + "urdfInfo": { + "robotName": "torso", + "rootLink": "BASE", + "frames": [ + { + "name": "J1", + "kind": "joint", + "type": "fixed", + "parent": "BASE", + "child": "LINK_arm_r", + "interfaceType": "arm_r", + "originExplicit": true, + "xyz": [-0.1, 0.01, 0], + "rpy": [0, -1.5707963267949, 0], + "axis": [0, 0, 0], + "limits": {} + } + ] + }, + "version": 1, + "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP", + "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf" + } +} +``` + +返回字段见 4.2。详情可能返回不满足拼装要求的原始 `urdfInfo`,查看详情不表示该组件一定可以参与匹配。 + +## 6. 错误响应 + +| HTTP 状态 | `code` | 常见原因 | +| --- | --- | --- | +| 422 | `INVALID_REQUEST` | 必填项缺失、JSON 类型错误、未知字段、超长文本、负数、自由度小数或数值越界 | +| 422 | `INVALID_MATCH_REQUEST` | 不支持的角色、部件条件不属于所需角色、重复角色条件、非法运算符 | +| 404 | `COMPONENT_NOT_FOUND` | 详情编码不存在或组件已删除 | +| 503 | `DATABASE_UNAVAILABLE` | 数据库暂不可用 | +| 500 | `INTERNAL_ERROR` | 服务内部异常 | + +### 6.1 非法角色:HTTP 422 + +请求 `POST /api/robot-matches`: + +```json +{ + "requiredParts": ["unknown_part"] +} +``` + +响应: + +```json +{ + "code": "INVALID_MATCH_REQUEST", + "message": "不支持的组件角色", + "data": null, + "requestId": "frontend-invalid-001" +} +``` + +### 6.2 自由度类型错误:HTTP 422 + +请求中的自由度使用了字符串: + +```json +{ + "requiredParts": ["arm_r"], + "robotRequirements": {"degreesOfFreedom": "20"} +} +``` + +响应: + +```json +{ + "code": "INVALID_REQUEST", + "message": "请求体格式不合法,请检查字段类型和JSON结构", + "data": null, + "requestId": "frontend-invalid-002" +} +``` + +### 6.3 组件不存在:HTTP 404 + +请求 `GET /api/components/CW-NOT-FOUND`,响应: + +```json +{ + "code": "COMPONENT_NOT_FOUND", + "message": "组件不存在", + "data": null, + "requestId": "frontend-detail-002" +} +``` + +### 6.4 数据库不可用:HTTP 503 + +```json +{ + "code": "DATABASE_UNAVAILABLE", + "message": "数据库暂不可用,请检查数据库连接配置后重试", + "data": null, + "requestId": "frontend-match-005" +} +``` + +错误时按 HTTP 状态和 `code` 判断,`message` 用于提示,不作为固定业务分支条件。排查时提供 `requestId`。 + +## 7. 前端拼装与模型加载 + +1. 提交结构化匹配条件,读取 `data.status`;`FALLBACK`、`PARTIAL` 仍可以展示已有模型,同时展示未满足条件和缺件。 +2. 使用 `parts[].urdfUrl` 加载 URDF,用 `componentCode` 区分模型实例;需要 STEP 文件时使用 `stepUrl`。空地址不发起文件请求。 +3. 从 `rootCategory` 对应模型开始,按 `connections` 组装。在父组件实例内部查找 `parentLink`,将子 `childRootLink` 对齐到给定局部 `xyz/rpy`。不要假设连接数组已经按装配顺序排列。 +4. BOM 展示读取 `bomList`;关节、轴、限位等读取原始 `urdfInfo` 或已加载模型。不要重复累加 BOM 的质量和自由度。 +5. 选择替代组件后,按 4.5 同时更新组件、连接、汇总及未满足项。 + +模型资源由前端直接请求公开 OSS/CDN 地址,无需拼接 `/api/components/{componentCode}/assets/...` 路径,也不需要给模型地址附加管理员凭证。资源域名需允许前端源跨域读取 URDF 及 meshes,联调时由部署人员配置 OSS/CDN 的 GET/HEAD CORS。 + +URDF 相对 mesh 路径以主文件目录解析,保留服务器返回的完整目录。若文件使用 `package://`,前端 URDF 加载器需要配置对应 package 路径映射。STEP 格式解析和模型展示由前端加载器负责。 + +组件资源替换后应使用最新响应中的 URL。组件已删除时详情返回 404,但已有公开资源地址不保证立即失效;不要仅凭模型地址可访问就判断组件仍可使用。 diff --git a/cadworld-api/pom.xml b/cadworld-api/pom.xml index a28ffa1..4b65a13 100644 --- a/cadworld-api/pom.xml +++ b/cadworld-api/pom.xml @@ -14,4 +14,31 @@ cadworld-api jar cadworld-api + + + + com.linkerbot + cadworld-service + ${project.version} + + + com.mysql + mysql-connector-j + runtime + + + com.h2database + h2 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/ApiApplication.java b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/ApiApplication.java new file mode 100644 index 0000000..dcd28d4 --- /dev/null +++ b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/ApiApplication.java @@ -0,0 +1,25 @@ +package com.linkerbot.cadworld.api; + +import com.linkerbot.cadworld.config.MatchingProperties; +import com.linkerbot.cadworld.config.MybatisPlusConfig; +import com.linkerbot.cadworld.config.StorageProperties; +import com.linkerbot.cadworld.mapper.ComponentMapper; +import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Import; + +@SpringBootApplication(scanBasePackages = { + "com.linkerbot.cadworld.api", "com.linkerbot.cadworld.common", + "com.linkerbot.cadworld.service.matching" +}) +@EnableConfigurationProperties({StorageProperties.class, MatchingProperties.class}) +@Import({MybatisPlusConfig.class, ObjectStorageUrlResolver.class}) +@MapperScan(basePackageClasses = ComponentMapper.class) +public class ApiApplication { + public static void main(String[] args) { + SpringApplication.run(ApiApplication.class, args); + } +} diff --git a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/controller/ComponentMatchingController.java b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/controller/ComponentMatchingController.java new file mode 100644 index 0000000..0f08e71 --- /dev/null +++ b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/controller/ComponentMatchingController.java @@ -0,0 +1,38 @@ +package com.linkerbot.cadworld.api.controller; + +import com.linkerbot.cadworld.common.api.ApiResponse; +import com.linkerbot.cadworld.dto.matching.PublicComponentResponse; +import com.linkerbot.cadworld.dto.matching.RobotMatchRequest; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse; +import com.linkerbot.cadworld.service.matching.PublicComponentQueryService; +import com.linkerbot.cadworld.service.matching.RobotMatchingService; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +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.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api") +@Validated +@RequiredArgsConstructor +public class ComponentMatchingController { + private final RobotMatchingService matching; + private final PublicComponentQueryService components; + + @PostMapping("/robot-matches") + public ApiResponse match(@Valid @RequestBody RobotMatchRequest request) { + return ApiResponse.success(matching.match(request)); + } + + @GetMapping("/components/{componentCode}") + public ApiResponse detail(@PathVariable @NotBlank @Size(max = 64) String componentCode) { + return ApiResponse.success(components.get(componentCode)); + } +} diff --git a/cadworld-api/src/main/resources/application-prod.yml b/cadworld-api/src/main/resources/application-prod.yml new file mode 100644 index 0000000..27c8660 --- /dev/null +++ b/cadworld-api/src/main/resources/application-prod.yml @@ -0,0 +1,21 @@ +spring: + datasource: + url: ${APP_DB_URL} + username: ${APP_DB_USERNAME} + password: ${APP_DB_PASSWORD} + driver-class-name: com.mysql.cj.jdbc.Driver + hikari: + pool-name: CadworldApiHikariCP + minimum-idle: 1 + maximum-pool-size: 20 + connection-timeout: 5000 + +app: + storage: + root-prefix: ${OSS_ROOT_PREFIX:cadworld} + # 生产环境必须配置公开 OSS/CDN 域名,供前端直接加载模型。 + public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL} + +logging: + level: + com.linkerbot.cadworld: INFO diff --git a/cadworld-api/src/main/resources/application-test.yml b/cadworld-api/src/main/resources/application-test.yml new file mode 100644 index 0000000..db48b74 --- /dev/null +++ b/cadworld-api/src/main/resources/application-test.yml @@ -0,0 +1,20 @@ +spring: + datasource: + # 优先使用与管理端一致的 APP_DB_*,兼容原有 DB_* 环境变量。 + url: ${APP_DB_URL:${DB_URL:jdbc:mysql://127.0.0.1:3306/cadworld?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai}} + username: ${APP_DB_USERNAME:${DB_USERNAME:}} + password: ${APP_DB_PASSWORD:${DB_PASSWORD:}} + driver-class-name: com.mysql.cj.jdbc.Driver + hikari: + pool-name: CadworldApiHikariCP + minimum-idle: 1 + maximum-pool-size: 10 + connection-timeout: 5000 + +app: + storage: + root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev} + +logging: + level: + com.linkerbot.cadworld: DEBUG diff --git a/cadworld-api/src/main/resources/application.yml b/cadworld-api/src/main/resources/application.yml new file mode 100644 index 0000000..4d2cf51 --- /dev/null +++ b/cadworld-api/src/main/resources/application.yml @@ -0,0 +1,34 @@ +spring: + application: + name: cadworld-api + profiles: + default: test + sql: + init: + mode: never + jackson: + deserialization: + fail-on-unknown-properties: true +server: + port: ${SERVER_PORT:8991} +logging: + level: + root: INFO + # 测试环境开启项目 DEBUG 时,仍不输出 SQL 参数或完整请求内容。 + com.linkerbot.cadworld.mapper: INFO + org.springframework.web: INFO +mybatis-plus: + configuration: + map-underscore-to-camel-case: true +app: + storage: + # 配置公开 OSS/CDN 域名,不能填管理端下载代理地址;对象键已包含环境根目录。 + public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:} + matching: + candidates-per-role: 50 + preferred-candidates-per-role: 30 + beam-width: 128 + max-state-expansions: 50000 + # 可追加或覆盖同义词组,例如: + # synonyms: + # "[跑步]": [奔跑, 跑动, running] diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java new file mode 100644 index 0000000..1f6f451 --- /dev/null +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java @@ -0,0 +1,505 @@ +package com.linkerbot.cadworld.api; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.linkerbot.cadworld.config.MatchingProperties; +import com.linkerbot.cadworld.dto.matching.RobotMatchRequest; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse; +import com.linkerbot.cadworld.service.AdminOperatorProvider; +import com.linkerbot.cadworld.service.client.ObjectStorageClient; +import com.linkerbot.cadworld.service.matching.AssemblySearchEngine; +import com.linkerbot.cadworld.service.matching.PublicComponentQueryService; +import com.linkerbot.cadworld.service.matching.RequirementEvaluator; +import com.linkerbot.cadworld.service.matching.RobotMatchingService; +import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.http.MediaType; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(classes = ApiApplication.class, properties = { + "spring.datasource.url=jdbc:h2:mem:matching;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=never", + "app.storage.public-base-url=https://models.example.test", "logging.file.path=target/test-logs" +}) +@AutoConfigureMockMvc +class MatchingApiTest { + @Autowired private MockMvc mvc; + @Autowired private ObjectMapper json; + @Autowired private JdbcTemplate jdbc; + @Autowired private ApplicationContext context; + @Autowired private PublicComponentQueryService components; + @Autowired private RequirementEvaluator evaluator; + + @BeforeEach + void prepare() { + String product = jdbc.execute((org.springframework.jdbc.core.ConnectionCallback) + connection -> connection.getMetaData().getDatabaseProductName()); + assertThat(product).isEqualTo("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 '', + description CLOB NOT NULL DEFAULT '', material VARCHAR(128) NOT NULL DEFAULT '', + mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0, degrees_of_freedom INT NOT NULL DEFAULT 0, + function_description VARCHAR(512) NOT NULL DEFAULT '', shape VARCHAR(128) NOT NULL DEFAULT '', + size VARCHAR(128) NOT NULL DEFAULT '', torque_nm DECIMAL(18,6) NOT NULL DEFAULT 0, + bom_list CLOB NOT NULL, urdf_info CLOB NOT NULL, + 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, deleted TINYINT NOT NULL DEFAULT 0, + created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP) + """); + jdbc.update("DELETE FROM component"); + } + + @Test + void startsWithoutAdminOrOssBeansAndOnlyExposesUserRoutes() throws Exception { + assertThat(context.getBeansOfType(AdminOperatorProvider.class)).isEmpty(); + assertThat(context.getBeansOfType(ComponentUploadSessionTokenProvider.class)).isEmpty(); + assertThat(context.getBeansOfType(ObjectStorageClient.class)).isEmpty(); + mvc.perform(get("/admin-api/components")).andExpect(status().isNotFound()); + mvc.perform(get("/api/components/CW-NO/assets/1/step")).andExpect(status().isNotFound()); + JsonNode empty = match(request("torso_0")); + assertThat(empty.path("status").asText()).isEqualTo("NO_MATCH"); + assertThat(empty.path("parts")).isEmpty(); + assertThat(empty.path("missingParts").get(0).path("reason").asText()).isEqualTo("NO_COMPONENT"); + } + + @Test + void mapsEveryRoleAndDeduplicatesAliasesWithoutSwappingFeetOrSides() throws Exception { + List english = List.of("head_0", "waist_0", "arm_l", "arm_r", "hand_l", "hand_r", + "pedal_l", "pedal_r", "foot_l", "foot_r", "tail_0"); + List chinese = List.of("头_0", "腰_0", "臂_l", "臂_r", "手_l", "手_r", "足_l", "足_r", "脚_l", "脚_r", "尾_0"); + save("CW-TORSO", "躯干_0", 0, "1", "0", "", metadata("ROOT", english.toArray(String[]::new)), json.readTree("[]")); + for (int index = 0; index < english.size(); index++) save("CW-" + english.get(index), chinese.get(index), 1, "1", "0", ""); + List required = new ArrayList<>(chinese); + required.addAll(List.of("躯干_0", "torso_0", "ARM_L")); + JsonNode result = match(Map.of("requiredParts", required)); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("parts").size()).isEqualTo(12); + assertThat(result.path("connections").size()).isEqualTo(11); + assertThat(part(result, "pedal_l").path("componentCode").asText()).isEqualTo("CW-pedal_l"); + assertThat(part(result, "foot_l").path("componentCode").asText()).isEqualTo("CW-foot_l"); + } + + @Test + void returnsOriginalNestedJsonInSelectedAlternativeAndDetailWithEncodedDirectUrls() throws Exception { + JsonNode original = metadata("BASE", "arm_r"); + JsonNode bom = json.readTree("{\"items\":[{\"code\":\"bolt\",\"qty\":4,\"details\":{\"material\":\"steel\"}}]}"); + save("CW-A", "torso_0", 0, "1", "0", "", original, bom); + JsonNode alternativeBom = json.readTree("[{\"code\":\"plate\",\"children\":[{\"qty\":2}]}]"); + JsonNode alternativeInfo = metadata("OTHER_BASE", "arm_r"); + save("CW-B", "躯干_0", 0, "2", "0", "", alternativeInfo, alternativeBom); + save("CW-ARM", "臂_r", 4, "1", "20", ""); + jdbc.update("UPDATE component SET step_object_key=?,urdf_main_object_key=? WHERE component_code=?", + "cadworld_dev/components/CW-A/step/batch/模型 one.STEP", + "cadworld_dev/components/CW-A/urdf/batch/L20/机器人.urdf", "CW-A"); + JsonNode result = match(request("torso_0", "arm_r")); + JsonNode selected = part(result, "torso_0"); + assertThat(selected.get("bomList")).isEqualTo(bom); + assertThat(selected.get("urdfInfo")).isEqualTo(original); + assertThat(selected.path("stepUrl").asText()).startsWith("https://models.example.test/cadworld_dev/") + .endsWith("%E6%A8%A1%E5%9E%8B%20one.STEP"); + assertThat(selected.path("urdfUrl").asText()).contains("/urdf/batch/L20/").endsWith("%E6%9C%BA%E5%99%A8%E4%BA%BA.urdf"); + JsonNode replacement = alternatives(result, "torso_0").get(0).path("component"); + assertThat(replacement.get("bomList")).isEqualTo(alternativeBom); + assertThat(replacement.get("urdfInfo")).isEqualTo(alternativeInfo); + assertPublic(selected); + assertPublic(replacement); + MvcResult detail = mvc.perform(get("/api/components/CW-A").header("X-Request-Id", "matching-detail")) + .andExpect(status().isOk()).andExpect(jsonPath("$.requestId").value("matching-detail")).andReturn(); + JsonNode publicDetail = json.readTree(detail.getResponse().getContentAsString()).path("data"); + assertThat(publicDetail).isEqualTo(selected); + assertPublic(publicDetail); + Long id = jdbc.queryForObject("SELECT id FROM component WHERE component_code='CW-A'", Long.class); + mvc.perform(get("/api/components/" + id)).andExpect(status().isNotFound()); + } + + @Test + void publicDetailAlsoPreservesJsonArraysThatAreNotAssemblyMetadata() throws Exception { + JsonNode info = json.readTree("[{\"robotName\":\"legacy\"}]"); + save("CW-LEGACY", "torso_0", 0, "1", "0", "", info, json.readTree("{}")); + MvcResult detail = mvc.perform(get("/api/components/CW-LEGACY")).andExpect(status().isOk()).andReturn(); + assertThat(json.readTree(detail.getResponse().getContentAsString()).path("data").get("urdfInfo")).isEqualTo(info); + JsonNode result = match(request("torso_0")); + assertThat(result.path("status").asText()).isEqualTo("NO_MATCH"); + assertThat(result.path("missingParts").get(0).path("reason").asText()).isEqualTo("INVALID_ASSEMBLY_METADATA"); + } + + @Test + void structuredRequirementsAndSynonymsDetermineExactMatchNotUserInput() throws Exception { + save("CW-T", "torso_0", 0, "2", "0", "aluminium alloy", metadata("BASE", "arm_r"), json.readTree("[]")); + save("CW-R", "arm_r", 20, "3", "20", "steel"); + jdbc.update("UPDATE component SET component_name='双足机器人',function_description='用于奔跑',shape='双足' "); + Map body = new LinkedHashMap<>(request("torso_0", "arm_r")); + body.put("userInput", "这里写100自由度和质量1kg也不能覆盖结构化条件"); + body.put("requirements", List.of("running", "robot", "biped")); + body.put("robotRequirements", Map.of("degreesOfFreedom", 20, "massKg", 10, "functionDescription", "跑步", "operators", Map.of("massKg", "lte"))); + body.put("partRequirements", List.of(Map.of("category", "躯干_0", "material", " 铝合金 "), + Map.of("category", "arm_r", "torqueNm", 20, "operators", Map.of("torqueNm", "gte")))); + JsonNode result = match(body); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(20); + assertThat(result.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("5"); + assertThat(result.path("unmetRequirements")).isEmpty(); + assertThat(result.path("unmatchedKeywords")).isEmpty(); + } + + @Test + void completeConnectedAssemblyWinsOverSmallerAssemblyThatMeetsParameters() throws Exception { + save("CW-EXACT-LEAF", "torso_0", 20, "1", "0", "铝合金"); + save("CW-FALLBACK-T", "torso_0", 0, "8", "0", "steel", metadata("BASE", "arm_r"), json.readTree("[]")); + save("CW-FALLBACK-R", "arm_r", 4, "5", "10", "steel"); + Map body = new LinkedHashMap<>(request("torso_0", "arm_r")); + body.put("robotRequirements", Map.of("degreesOfFreedom", 20, "massKg", 10, "operators", Map.of("massKg", "lte"))); + body.put("partRequirements", List.of(Map.of("category", "torso_0", "material", "铝合金"), + Map.of("category", "arm_r", "torqueNm", 20, "operators", Map.of("torqueNm", "gte")))); + JsonNode result = match(body); + assertThat(result.path("status").asText()).isEqualTo("FALLBACK"); + assertThat(result.path("parts").size()).isEqualTo(2); + assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-FALLBACK-T"); + assertThat(result.path("unmetRequirements").size()).isEqualTo(4); + } + + @Test + void searchesGlobalDegreeCombinationInsteadOfChoosingEveryPartIndependently() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_l", "arm_r"), json.readTree("[]")); + save("CW-L5", "arm_l", 5, "1", "0", ""); + save("CW-L8", "arm_l", 8, "1", "0", ""); + save("CW-R7", "arm_r", 7, "1", "0", ""); + save("CW-R12", "arm_r", 12, "1", "0", ""); + Map body = new LinkedHashMap<>(request("torso_0", "arm_l", "arm_r")); + body.put("robotRequirements", Map.of("degreesOfFreedom", 20)); + JsonNode result = match(body); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(part(result, "arm_l").path("componentCode").asText()).isEqualTo("CW-L8"); + assertThat(part(result, "arm_r").path("componentCode").asText()).isEqualTo("CW-R12"); + assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(20); + } + + @Test + void followsChainsWithoutAssumingRequestedRoleOrderAndNeverCreatesCycles() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]")); + save("CW-R", "arm_r", 3, "1", "0", "", metadata("RIGHT", "head_0", "hand_r", "torso_0"), json.readTree("[]")); + save("CW-H", "head_0", 0, "1", "0", ""); + save("CW-HAND", "hand_r", 2, "1", "0", ""); + JsonNode result = match(request("head_0", "hand_r", "torso_0", "arm_r")); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("connections").size()).isEqualTo(3); + for (JsonNode connection : result.path("connections")) { + assertThat(connection.path("childCategory").asText()).isNotEqualTo("torso_0"); + } + } + + @Test + void doesNotAddUnrequestedConnectorsAndKeepsLeftRightIndependent() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_l", "arm_r"), json.readTree("[]")); + save("CW-L", "arm_l", 1, "1", "0", "", metadata("LEFT", "hand_l"), json.readTree("[]")); + save("CW-HAND", "hand_l", 1, "1", "0", ""); + JsonNode result = match(request("torso_0", "hand_l", "arm_r")); + assertThat(result.path("status").asText()).isEqualTo("PARTIAL"); + assertThat(result.path("parts").size()).isEqualTo(1); + assertThat(result.path("missingParts").size()).isEqualTo(2); + assertThat(result.path("missingParts").toString()).contains("NO_COMPONENT", "NO_COMPATIBLE_CONNECTION"); + } + + @Test + void missingTorsoUsesRootWithMostReachableRequestedParts() throws Exception { + save("CW-HEAD", "head_0", 0, "1", "0", ""); + save("CW-R", "arm_r", 3, "1", "0", "", metadata("RIGHT", "hand_r"), json.readTree("[]")); + save("CW-HAND", "hand_r", 2, "1", "0", ""); + JsonNode result = match(request("torso_0", "head_0", "arm_r", "hand_r")); + assertThat(result.path("status").asText()).isEqualTo("PARTIAL"); + assertThat(result.path("rootCategory").asText()).isEqualTo("arm_r"); + assertThat(result.path("parts").size()).isEqualTo(2); + } + + @Test + void unknownMassDoesNotPretendToMeetMassLimit() throws Exception { + save("CW-T", "torso_0", 0, "0", "0", "", metadata("BASE", "arm_r"), json.readTree("[]")); + save("CW-R", "arm_r", 4, "2", "0", ""); + Map body = new LinkedHashMap<>(request("torso_0", "arm_r")); + body.put("robotRequirements", Map.of("massKg", 10, "operators", Map.of("massKg", "lte"))); + body.put("partRequirements", List.of(Map.of("category", "torso_0", "massKg", 1, "operators", Map.of("massKg", "lte")))); + JsonNode result = match(body); + assertThat(result.path("status").asText()).isEqualTo("FALLBACK"); + assertThat(result.path("totals").path("massKg").isNull()).isTrue(); + assertThat(result.path("totals").path("knownMassKg").decimalValue()).isEqualByComparingTo("2"); + assertThat(result.path("totals").path("massComplete").asBoolean()).isFalse(); + assertThat(result.path("unmetRequirements").size()).isEqualTo(2); + for (JsonNode unmet : result.path("unmetRequirements")) assertThat(unmet.path("reason").asText()).isEqualTo("UNKNOWN_MASS"); + } + + @Test + void alternativesKeepChildrenRecomputePosesRootsAndGlobalConstraints() throws Exception { + JsonNode first = metadata("BASE_A", "arm_r"); + JsonNode second = metadata("BASE_B", "arm_r"); + ((com.fasterxml.jackson.databind.node.ObjectNode) second.path("frames").get(0)) + .set("xyz", json.readTree("[2,3,4]")); + save("CW-A", "torso_0", 5, "1", "0", "", first, json.readTree("[]")); + save("CW-B", "torso_0", 9, "3", "0", "", second, json.readTree("{\"replacement\":true}")); + save("CW-BAD", "torso_0", 5, "1", "0", ""); + save("CW-R", "arm_r", 1, "1", "0", "", metadata("ROOT_R"), json.readTree("[]")); + save("CW-R2", "arm_r", 1, "1", "0", "", metadata("NEW_ROOT_R"), json.readTree("[]")); + Map body = new LinkedHashMap<>(request("torso_0", "arm_r")); + body.put("robotRequirements", Map.of("degreesOfFreedom", 6, "massKg", 3, "operators", Map.of("massKg", "lte"))); + JsonNode result = match(body); + assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-A"); + JsonNode torsoItems = alternatives(result, "torso_0"); + assertThat(torsoItems.size()).isEqualTo(1); + JsonNode replacement = torsoItems.get(0); + assertThat(replacement.path("component").path("componentCode").asText()).isEqualTo("CW-B"); + assertThat(replacement.path("connections").get(0).path("xyz")).isEqualTo(json.readTree("[2,3,4]")); + assertThat(replacement.path("connections").get(0).path("parentLink").asText()).isEqualTo("BASE_B"); + assertThat(replacement.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("4"); + assertThat(replacement.path("unmetRequirements").size()).isEqualTo(2); + assertThat(alternatives(result, "arm_r").get(0).path("connections").get(0).path("childRootLink").asText()).isEqualTo("NEW_ROOT_R"); + } + + @Test + void ignoresInvalidAndDuplicatePortsWithoutChangingReturnedMetadata() throws Exception { + JsonNode metadata = json.readTree(""" + {"rootLink":"BASE","frames":[ + {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"A","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]}, + {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"B","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]}, + {"name":"bad_pose","kind":"joint","type":"fixed","parent":"BASE","child":"C","interfaceType":"head_0","xyz":[0,0],"rpy":[0,0,0]}, + {"name":"implicit","kind":"joint","type":"fixed","parent":"BASE","child":"D","interfaceType":"hand_r","originExplicit":false} + ]} + """); + save("CW-T", "torso_0", 0, "1", "0", "", metadata, json.readTree("[]")); + save("CW-R", "arm_r", 1, "1", "0", ""); + save("CW-H", "hand_r", 1, "1", "0", ""); + JsonNode result = match(request("torso_0", "arm_r", "hand_r")); + assertThat(result.path("parts").size()).isEqualTo(2); + assertThat(result.path("connections").get(0).path("xyz")).isEqualTo(json.readTree("[0,0,0]")); + assertThat(part(result, "torso_0").get("urdfInfo")).isEqualTo(metadata); + } + + @Test + void logicDeletedComponentsDisappearAndResourceReplacementChangesDirectUrl() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", ""); + String firstUrl = components.get("CW-T").urdfUrl(); + jdbc.update("UPDATE component SET version=2,urdf_main_object_key='cadworld/components/CW-T/urdf/new-batch/robot.urdf' WHERE component_code='CW-T'"); + assertThat(components.get("CW-T").urdfUrl()).isNotEqualTo(firstUrl).contains("/new-batch/"); + jdbc.update("UPDATE component SET deleted=1 WHERE component_code='CW-T'"); + mvc.perform(get("/api/components/CW-T")).andExpect(status().isNotFound()); + assertThat(match(request("torso_0")).path("status").asText()).isEqualTo("NO_MATCH"); + } + + @Test + void stableResultsAndAlternativesAreCappedAtFive() throws Exception { + for (int index = 9; index >= 0; index--) save("CW-" + index, "torso_0", 0, "1", "0", ""); + JsonNode first = match(request("torso_0")); + JsonNode second = match(request("torso_0")); + assertThat(first).isEqualTo(second); + assertThat(first.path("parts").get(0).path("componentCode").asText()).isEqualTo("CW-0"); + assertThat(alternatives(first, "torso_0").size()).isEqualTo(5); + } + + @Test + void boundedSearchReturnsBestKnownConnectedResultAndMarksLimit() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_l", "arm_r", "head_0"), json.readTree("[]")); + save("CW-L", "arm_l", 1, "1", "0", ""); + save("CW-R", "arm_r", 1, "1", "0", ""); + save("CW-H", "head_0", 1, "1", "0", ""); + MatchingProperties tiny = new MatchingProperties(50, 30, 128, 1, Map.of()); + RobotMatchingService service = new RobotMatchingService(components, evaluator, new AssemblySearchEngine(tiny, evaluator), tiny); + RobotMatchResponse result = service.match(json.convertValue(request("torso_0", "arm_l", "arm_r", "head_0"), RobotMatchRequest.class)); + assertThat(result.searchLimited()).isTrue(); + assertThat(result.status()).isEqualTo("PARTIAL"); + assertThat(result.parts()).hasSize(2); + assertThat(result.connections()).hasSize(1); + assertThat(result.missingParts()).allMatch((RobotMatchResponse.MissingPart missing) -> missing.reason().equals("SEARCH_LIMIT")); + } + + @Test + void candidateTruncationIsReportedRatherThanClaimingAnExactOptimum() throws Exception { + save("CW-A", "torso_0", 1, "1", "0", ""); + save("CW-B", "torso_0", 2, "1", "0", ""); + MatchingProperties tiny = new MatchingProperties(1, 1, 128, 50000, Map.of()); + RobotMatchingService service = new RobotMatchingService(components, evaluator, new AssemblySearchEngine(tiny, evaluator), tiny); + RobotMatchResponse result = service.match(json.convertValue(request("torso_0"), RobotMatchRequest.class)); + assertThat(result.parts()).hasSize(1); + assertThat(result.searchLimited()).isTrue(); + } + + @Test + void scansPastFirstDatabasePageAndKeepsAConnectorOutsidePreferredCandidates() throws Exception { + for (int index = 0; index < 205; index++) { + save(String.format(java.util.Locale.ROOT, "CW-P%03d", index), "torso_0", 0, "1", "0", ""); + } + save("CW-Z-CONNECTOR", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]")); + save("CW-ARM", "arm_r", 1, "1", "0", ""); + JsonNode result = match(request("torso_0", "arm_r")); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("searchLimited").asBoolean()).isTrue(); + assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-Z-CONNECTOR"); + } + + @Test + void keepsNumericExtremesOutsidePreferredCandidatesForGlobalGoals() throws Exception { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]")); + for (int index = 0; index < 60; index++) { + save(String.format(java.util.Locale.ROOT, "CW-P%03d", index), "arm_r", 1, "1", "0", ""); + } + save("CW-Z-EXTREME", "arm_r", 20, "1", "0", ""); + Map body = new LinkedHashMap<>(request("torso_0", "arm_r")); + body.put("robotRequirements", Map.of("degreesOfFreedom", 20)); + JsonNode result = match(body); + assertThat(result.path("status").asText()).isEqualTo("MATCHED"); + assertThat(result.path("searchLimited").asBoolean()).isTrue(); + assertThat(part(result, "arm_r").path("componentCode").asText()).isEqualTo("CW-Z-EXTREME"); + } + + @Test + void defaultsNumericComparisonToEqualityAndUsesGteLteWithoutRounding() throws Exception { + save("CW-R", "arm_r", 5, "1.000001", "20.000001", ""); + Map body = new LinkedHashMap<>(request("arm_r")); + body.put("robotRequirements", Map.of("degreesOfFreedom", 4, "operators", Map.of("degreesOfFreedom", "gte"))); + body.put("partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", new BigDecimal("20.000001"), + "massKg", new BigDecimal("1.000001"), "operators", Map.of("massKg", "lte")))); + assertThat(match(body).path("status").asText()).isEqualTo("MATCHED"); + body.put("partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", 20))); + JsonNode fallback = match(body); + assertThat(fallback.path("status").asText()).isEqualTo("FALLBACK"); + assertThat(fallback.path("unmetRequirements").get(0).path("operator").asText()).isEqualTo("eq"); + assertThat(fallback.path("unmetRequirements").get(0).path("actual").decimalValue()).isEqualByComparingTo("20.000001"); + } + + @ParameterizedTest + @ValueSource(strings = {"-1", "1.5", "1.0", "\"1\"", "true", "2147483648"}) + void rejectsInvalidDegreesBeforeSearching(String value) throws Exception { + mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON) + .content("{\"requiredParts\":[\"arm_r\"],\"robotRequirements\":{\"degreesOfFreedom\":" + value + "}}")) + .andExpect(status().isUnprocessableEntity()); + } + + @ParameterizedTest + @ValueSource(strings = {"-1", "20.0000001", "1000000000000", "\"bad\""}) + void rejectsInvalidTorqueBeforeSearching(String value) throws Exception { + mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON) + .content("{\"requiredParts\":[\"arm_r\"],\"partRequirements\":[{\"category\":\"arm_r\",\"torqueNm\":" + value + "}]}")) + .andExpect(status().isUnprocessableEntity()); + } + + @Test + void acceptsNumericBoundariesAndRejectsAmbiguousOrUnsupportedRequirements() throws Exception { + match(Map.of("requiredParts", List.of("arm_r"), "robotRequirements", Map.of("degreesOfFreedom", 2147483647), + "partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", new BigDecimal("999999999999.999999"))))); + List> invalid = List.of( + Map.of("requiredParts", List.of()), Map.of("requiredParts", List.of("unknown")), + Map.of("requiredParts", List.of("arm_r"), "robotRequirements", Map.of("operators", Map.of("massKg", "lte"))), + Map.of("requiredParts", List.of("arm_r"), "robotRequirements", Map.of("massKg", 10, "operators", Map.of("massKg", "lt"))), + Map.of("requiredParts", List.of("arm_r"), "partRequirements", List.of(Map.of("category", "head_0"))), + Map.of("requiredParts", List.of("arm_r"), "partRequirements", List.of(Map.of("category", "arm_r"), Map.of("category", "臂_r"))), + Map.of("requiredParts", List.of("arm_r"), "robotRequirements", Map.of("torqueNm", 1))); + for (Map body : invalid) { + mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(body))) + .andExpect(status().isUnprocessableEntity()); + } + } + + @Test + void businessLogsDoNotContainUserInputOrFullJson() throws Exception { + Logger logger = (Logger) LoggerFactory.getLogger(RobotMatchingService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + save("CW-T", "torso_0", 0, "1", "0", "", metadata("private-urdf-marker"), + json.readTree("{\"private-bom-marker\":true}")); + match(Map.of("requiredParts", List.of("torso_0"), "userInput", "private-input-marker")); + match(Map.of("requiredParts", List.of("torso_0"), "userInput", "private-input-marker", + "robotRequirements", Map.of("massKg", 0, "operators", Map.of("massKg", "lte")))); + String messages = appender.list.stream().map(ILoggingEvent::getFormattedMessage).reduce("", String::concat); + assertThat(messages).contains("组件匹配完成", "selectedCount=1", "massKg:VALUE_MISMATCH") + .doesNotContain("private-input-marker", "private-bom-marker", "private-urdf-marker"); + assertThat(json.convertValue(Map.of("requiredParts", List.of("torso_0"), "userInput", "private-input-marker"), + RobotMatchRequest.class).toString()).doesNotContain("private-input-marker"); + assertThat(components.get("CW-T").toString()).doesNotContain("private-bom-marker", "private-urdf-marker"); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + + private Map request(String... roles) { return Map.of("requiredParts", List.of(roles)); } + + private JsonNode match(Map body) throws Exception { + MvcResult result = mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON) + .content(json.writeValueAsString(body))).andExpect(status().isOk()).andReturn(); + return json.readTree(result.getResponse().getContentAsString()).path("data"); + } + + private JsonNode part(JsonNode response, String role) { + for (JsonNode component : response.path("parts")) if (component.path("category").asText().equals(role)) return component; + throw new AssertionError("缺少角色 " + role); + } + + private JsonNode alternatives(JsonNode response, String role) { + for (JsonNode group : response.path("alternatives")) if (group.path("category").asText().equals(role)) return group.path("items"); + throw new AssertionError("缺少替代候选组 " + role); + } + + private void assertPublic(JsonNode component) { + for (String field : List.of("id", "stepObjectKey", "urdfPrefix", "urdfMainObjectKey", "urdfFiles", "deleted", "uploadSessionToken")) { + assertThat(component.has(field)).as(field).isFalse(); + } + assertThat(component.get("bomList").isContainerNode()).isTrue(); + assertThat(component.get("urdfInfo").isContainerNode()).isTrue(); + } + + private JsonNode metadata(String root, String... ports) { + List> frames = new ArrayList<>(); + for (int index = 0; index < ports.length; index++) { + frames.add(Map.of("name", "J" + index, "kind", "joint", "type", "fixed", "parent", root, + "child", "LINK_" + ports[index], "interfaceType", ports[index], "originExplicit", true, + "xyz", List.of(index, 0, 0), "rpy", List.of(0, 0, 0), "axis", List.of(0, 0, 0))); + } + com.fasterxml.jackson.databind.node.ObjectNode info = json.valueToTree(Map.of("robotName", root, "rootLink", root, "frames", frames)); + for (JsonNode frame : info.path("frames")) ((com.fasterxml.jackson.databind.node.ObjectNode) frame).set("limits", json.createObjectNode()); + return info; + } + + private void save(String code, String category, int degrees, String mass, String torque, String material) throws Exception { + save(code, category, degrees, mass, torque, material, metadata("BASE_" + code), json.readTree("[]")); + } + + private void save(String code, String category, int degrees, String mass, String torque, String material, JsonNode info, JsonNode bom) throws Exception { + jdbc.update(""" + INSERT INTO component (component_code,component_name,category,mass_kg,degrees_of_freedom,torque_nm, + material,bom_list,urdf_info,step_object_key,urdf_main_object_key) + VALUES (?,?,?,?,?,?,?,?,?,?,?) + """, code, code, category, new BigDecimal(mass), degrees, new BigDecimal(torque), material, + json.writeValueAsString(bom), json.writeValueAsString(info), + "cadworld/components/" + code + "/step/batch/model.STEP", "cadworld/components/" + code + "/urdf/batch/robot.urdf"); + } +} diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingFailureTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingFailureTest.java new file mode 100644 index 0000000..5f80b5b --- /dev/null +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingFailureTest.java @@ -0,0 +1,30 @@ +package com.linkerbot.cadworld.api; + +import com.linkerbot.cadworld.api.controller.ComponentMatchingController; +import com.linkerbot.cadworld.common.exception.GlobalExceptionHandler; +import com.linkerbot.cadworld.service.matching.PublicComponentQueryService; +import com.linkerbot.cadworld.service.matching.RobotMatchingService; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class MatchingFailureTest { + @Test + void databaseFailureRemainsAnErrorInsteadOfBecomingNoMatch() throws Exception { + RobotMatchingService matching = mock(RobotMatchingService.class); + when(matching.match(any())).thenThrow(new DataAccessResourceFailureException("test database unavailable")); + MockMvc mvc = MockMvcBuilders.standaloneSetup(new ComponentMatchingController(matching, mock(PublicComponentQueryService.class))) + .setControllerAdvice(new GlobalExceptionHandler()).build(); + mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON).content("{\"requiredParts\":[\"torso_0\"]}")) + .andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.code").value("DATABASE_UNAVAILABLE")); + } +} diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java new file mode 100644 index 0000000..54c76e0 --- /dev/null +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PartRequirements.java @@ -0,0 +1,22 @@ +package com.linkerbot.cadworld.dto.matching; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.linkerbot.cadworld.dto.component.DegreesOfFreedomDeserializer; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.PositiveOrZero; +import jakarta.validation.constraints.Size; +import java.math.BigDecimal; +import java.util.Map; + +public record PartRequirements( + @NotBlank @Size(max = 64) String category, + @Size(max = 128) String material, + @Min(0) @JsonDeserialize(using = DegreesOfFreedomDeserializer.class) Integer degreesOfFreedom, + @PositiveOrZero @Digits(integer = 12, fraction = 6) BigDecimal massKg, + @PositiveOrZero @Digits(integer = 12, fraction = 6) BigDecimal torqueNm, + @Size(max = 512) String functionDescription, + @Size(max = 128) String shape, + @Size(max = 128) String size, + Map operators) { } diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java new file mode 100644 index 0000000..ccd787e --- /dev/null +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/PublicComponentResponse.java @@ -0,0 +1,15 @@ +package com.linkerbot.cadworld.dto.matching; + +import com.fasterxml.jackson.databind.JsonNode; +import java.math.BigDecimal; + +/** 用户端白名单:不得通过序列化实体添加数据库ID或内部存储字段。 */ +public record PublicComponentResponse( + String componentCode, String componentName, String category, String description, String material, + BigDecimal massKg, Integer degreesOfFreedom, String functionDescription, String shape, String size, + BigDecimal torqueNm, JsonNode bomList, JsonNode urdfInfo, Long version, String stepUrl, String urdfUrl) { + @Override + public String toString() { + return "PublicComponentResponse[componentCode=" + componentCode + ", category=" + category + ", version=" + version + "]"; + } +} diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchRequest.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchRequest.java new file mode 100644 index 0000000..b355566 --- /dev/null +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchRequest.java @@ -0,0 +1,22 @@ +package com.linkerbot.cadworld.dto.matching; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import java.util.List; + +public record RobotMatchRequest( + @Size(max = 4000) String userInput, + @Size(max = 32) List<@NotBlank @Size(max = 128) String> requirements, + @NotEmpty @Size(max = 24) List<@NotBlank @Size(max = 64) String> requiredParts, + @Valid RobotRequirements robotRequirements, + @Size(max = 12) List<@NotNull @Valid PartRequirements> partRequirements) { + @Override + public String toString() { + return "RobotMatchRequest[requiredPartCount=" + (requiredParts == null ? 0 : requiredParts.size()) + + ", keywordCount=" + (requirements == null ? 0 : requirements.size()) + + ", partRequirementCount=" + (partRequirements == null ? 0 : partRequirements.size()) + "]"; + } +} diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java new file mode 100644 index 0000000..a707abb --- /dev/null +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotMatchResponse.java @@ -0,0 +1,27 @@ +package com.linkerbot.cadworld.dto.matching; + +import java.math.BigDecimal; +import java.util.List; + +public record RobotMatchResponse( + String status, String rootCategory, List parts, + List connections, List alternatives, Totals totals, + List unmetRequirements, List unmatchedKeywords, + List missingParts, boolean searchLimited) { + + public record Connection(String parentCategory, String parentComponentCode, String parentLink, + String frameName, String childCategory, String childComponentCode, + String childRootLink, List xyz, List rpy) { } + + public record Totals(long degreesOfFreedom, BigDecimal massKg, BigDecimal knownMassKg, boolean massComplete) { } + + public record UnmetRequirement(String scope, String category, String field, String operator, + Object expected, Object actual, String reason) { } + + public record MissingPart(String category, String reason) { } + + public record Alternatives(String category, List items) { } + + public record Replacement(PublicComponentResponse component, List connections, Totals totals, + List unmetRequirements, List unmatchedKeywords) { } +} diff --git a/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotRequirements.java b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotRequirements.java new file mode 100644 index 0000000..1b8e549 --- /dev/null +++ b/cadworld-bean/src/main/java/com/linkerbot/cadworld/dto/matching/RobotRequirements.java @@ -0,0 +1,16 @@ +package com.linkerbot.cadworld.dto.matching; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.linkerbot.cadworld.dto.component.DegreesOfFreedomDeserializer; +import jakarta.validation.constraints.Digits; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.PositiveOrZero; +import jakarta.validation.constraints.Size; +import java.math.BigDecimal; +import java.util.Map; + +public record RobotRequirements( + @Min(0) @JsonDeserialize(using = DegreesOfFreedomDeserializer.class) Integer degreesOfFreedom, + @PositiveOrZero @Digits(integer = 12, fraction = 6) BigDecimal massKg, + @Size(max = 512) String functionDescription, + Map operators) { } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MatchingProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MatchingProperties.java new file mode 100644 index 0000000..03bf520 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MatchingProperties.java @@ -0,0 +1,39 @@ +package com.linkerbot.cadworld.config; + +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; +import org.springframework.validation.annotation.Validated; + +@Validated +@ConfigurationProperties(prefix = "app.matching") +public record MatchingProperties( + @Min(1) @Max(500) @DefaultValue("50") int candidatesPerRole, + @Min(1) @Max(500) @DefaultValue("30") int preferredCandidatesPerRole, + @Min(1) @Max(4096) @DefaultValue("128") int beamWidth, + @Min(1) @Max(1000000) @DefaultValue("50000") int maxStateExpansions, + Map> synonyms) { + + public MatchingProperties { + Map> groups = new LinkedHashMap<>(); + groups.put("跑步", List.of("奔跑", "跑动", "running")); + groups.put("机器人", List.of("robot")); + groups.put("双足", List.of("两足", "biped", "bipedal")); + groups.put("铝合金", List.of("aluminum alloy", "aluminium alloy")); + if (synonyms != null) { + synonyms.forEach((String key, List values) -> groups.put(key, List.copyOf(values))); + } + synonyms = Collections.unmodifiableMap(groups); + } + + @AssertTrue(message = "优先候选数量不得超过每角色候选上限") + public boolean isCandidateConfigurationValid() { + return preferredCandidatesPerRole <= candidatesPerRole; + } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java new file mode 100644 index 0000000..4248fb0 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyMetadata.java @@ -0,0 +1,69 @@ +package com.linkerbot.cadworld.service.matching; + +import com.fasterxml.jackson.databind.JsonNode; +import com.linkerbot.cadworld.entity.Component; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** 只解析装配所需字段,不修改将返回给前端的原始JSON。 */ +record AssemblyMetadata(String rootLink, List ports, int invalidPorts) { + private static final Set JOINT_TYPES = Set.of("fixed", "revolute", "continuous", "prismatic", "floating", "planar"); + private static final List ZERO_POSE = List.of(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO); + + static AssemblyMetadata read(Component component) { + JsonNode info = component.getUrdfInfo(); + if (NormalizedMatchRequest.text(component.getUrdfMainObjectKey()).isEmpty() || info == null || !info.isObject() + || !info.path("rootLink").isTextual() || info.path("rootLink").asText().isBlank() + || !info.path("frames").isArray()) return null; + Map nameCounts = new HashMap<>(); + for (JsonNode frame : info.path("frames")) { + if (frame.path("name").isTextual()) nameCounts.merge(frame.path("name").asText(), 1, Integer::sum); + } + List ports = new ArrayList<>(); + int invalid = 0; + for (JsonNode frame : info.path("frames")) { + // 没有interfaceType的普通URDF关节不是对外安装端口。 + if (!frame.hasNonNull("interfaceType") || frame.path("interfaceType").asText().isBlank()) continue; + ComponentRole role = frame.path("interfaceType").isTextual() + ? ComponentRole.find(frame.path("interfaceType").asText()).orElse(null) : null; + String name = frame.path("name").isTextual() ? frame.path("name").asText() : ""; + boolean implicitOrigin = frame.path("originExplicit").isBoolean() && !frame.path("originExplicit").asBoolean(); + List xyz = pose(frame.get("xyz"), implicitOrigin); + List rpy = pose(frame.get("rpy"), implicitOrigin); + if (role == null || name.isBlank() || nameCounts.getOrDefault(name, 0) != 1 + || !"joint".equals(frame.path("kind").asText()) || !JOINT_TYPES.contains(frame.path("type").asText()) + || !frame.path("parent").isTextual() || frame.path("parent").asText().isBlank() + || !frame.path("child").isTextual() || frame.path("child").asText().isBlank() + || xyz == null || rpy == null) { + invalid++; + continue; + } + ports.add(new Port(name, role, frame.path("parent").asText(), xyz, rpy)); + } + ports.sort(java.util.Comparator.comparing(Port::name)); + return new AssemblyMetadata(info.path("rootLink").asText(), List.copyOf(ports), invalid); + } + + int interfaceMask() { + int mask = 0; + for (Port port : ports) mask |= port.role().bit(); + return mask; + } + + private static List pose(JsonNode value, boolean implicitOrigin) { + if (value == null || value.isNull()) return implicitOrigin ? ZERO_POSE : null; + if (!value.isArray() || value.size() != 3) return null; + List result = new ArrayList<>(3); + for (JsonNode number : value) { + if (!number.isNumber() || !Double.isFinite(number.doubleValue())) return null; + result.add(number.decimalValue()); + } + return List.copyOf(result); + } + + record Port(String name, ComponentRole role, String parentLink, List xyz, List rpy) { } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java new file mode 100644 index 0000000..f915c70 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblySearchEngine.java @@ -0,0 +1,94 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.config.MatchingProperties; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class AssemblySearchEngine { + private final MatchingProperties properties; + private final RequirementEvaluator evaluator; + + static final Comparator FINAL_ORDER = Comparator.comparingInt((ScoredState state) -> state.state().parts().size()).reversed() + .thenComparingInt((ScoredState state) -> state.evaluation().unmet().size()) + .thenComparing((ScoredState state) -> state.evaluation().deviation()) + .thenComparing(Comparator.comparingInt((ScoredState state) -> state.evaluation().keywordScore()).reversed()) + .thenComparing(ScoredState::key); + + private static final Comparator BEAM_ORDER = Comparator.comparingInt((ScoredState state) -> state.estimate().possibleParts()).reversed() + .thenComparingInt((ScoredState state) -> state.estimate().unmet()) + .thenComparing((ScoredState state) -> state.estimate().deviation()) + .thenComparing(Comparator.comparingInt((ScoredState state) -> state.estimate().keywordScore()).reversed()) + .thenComparing(FINAL_ORDER); + + Result search(CandidatePool.Result pool, NormalizedMatchRequest request) { + Map summaries = new EnumMap<>(ComponentRole.class); + pool.candidates().forEach((ComponentRole role, List candidates) -> { + if (!candidates.isEmpty()) summaries.put(role, RequirementEvaluator.summarize(candidates, request.keywords().size())); + }); + List roots = pool.candidates().getOrDefault(ComponentRole.TORSO, List.of()).isEmpty() + ? request.roles() : List.of(ComponentRole.TORSO); + List beam = new ArrayList<>(); + for (ComponentRole role : roots) { + for (MatchingCandidate candidate : pool.candidates().get(role)) { + beam.add(score(AssemblyState.root(candidate), request, summaries)); + } + } + if (beam.isEmpty()) return new Result(null, pool.limited(), 0); + ScoredState best = beam.stream().min(FINAL_ORDER).orElseThrow(); + boolean limited = pool.limited() || beam.size() > properties.beamWidth(); + beam.sort(BEAM_ORDER); + beam = new ArrayList<>(beam.subList(0, Math.min(beam.size(), properties.beamWidth()))); + int expansions = 0; + boolean budgetExhausted = false; + while (!beam.isEmpty()) { + List next = new ArrayList<>(); + Set seen = new HashSet<>(); + expansion: + for (ScoredState current : beam) { + AssemblyState state = current.state(); + for (Map.Entry parent : state.parts().entrySet()) { + for (AssemblyMetadata.Port port : parent.getValue().metadata().ports()) { + if (state.parts().containsKey(port.role()) || state.portUsed(parent.getKey(), port.name())) continue; + for (MatchingCandidate child : pool.candidates().getOrDefault(port.role(), List.of())) { + if (expansions >= properties.maxStateExpansions()) { + budgetExhausted = true; + break expansion; + } + expansions++; + AssemblyState attached = state.attach(parent.getKey(), port, child); + String key = attached.key(); + if (!seen.add(key)) continue; + ScoredState scored = score(attached, request, summaries); + if (FINAL_ORDER.compare(scored, best) < 0) best = scored; + next.add(scored); + } + } + } + } + limited |= budgetExhausted || next.size() > properties.beamWidth(); + if (budgetExhausted || next.isEmpty()) break; + next.sort(BEAM_ORDER); + beam = new ArrayList<>(next.subList(0, Math.min(next.size(), properties.beamWidth()))); + } + return new Result(best, limited, expansions); + } + + ScoredState score(AssemblyState state, NormalizedMatchRequest request, + Map summaries) { + RequirementEvaluator.Evaluation evaluation = evaluator.evaluate(state, request); + return new ScoredState(state, evaluation, evaluator.estimate(state, evaluation, summaries, request), state.key()); + } + + record ScoredState(AssemblyState state, RequirementEvaluator.Evaluation evaluation, + RequirementEvaluator.Estimate estimate, String key) { } + record Result(ScoredState best, boolean limited, int expansions) { } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java new file mode 100644 index 0000000..4d5c377 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/AssemblyState.java @@ -0,0 +1,93 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Connection; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +record AssemblyState(ComponentRole root, Map parts, List edges) { + AssemblyState { + Map copy = new EnumMap<>(ComponentRole.class); + copy.putAll(parts); + parts = Collections.unmodifiableMap(copy); + edges = edges.stream().sorted(Comparator.comparingInt((Edge edge) -> edge.child().ordinal())).toList(); + } + + static AssemblyState root(MatchingCandidate candidate) { + return new AssemblyState(candidate.role(), Map.of(candidate.role(), candidate), List.of()); + } + + AssemblyState attach(ComponentRole parent, AssemblyMetadata.Port port, MatchingCandidate child) { + Map next = new EnumMap<>(ComponentRole.class); + next.putAll(parts); + next.put(child.role(), child); + List connections = new ArrayList<>(edges); + connections.add(new Edge(parent, port, child.role())); + return new AssemblyState(root, next, connections); + } + + boolean portUsed(ComponentRole parent, String name) { + return edges.stream().anyMatch((Edge edge) -> edge.parent() == parent && edge.port().name().equals(name)); + } + + AssemblyState replace(MatchingCandidate replacement) { + ComponentRole role = replacement.role(); + Map next = new EnumMap<>(ComponentRole.class); + next.putAll(parts); + next.put(role, replacement); + List connections = new ArrayList<>(); + Set used = new HashSet<>(); + for (Edge edge : edges) { + if (edge.parent() != role) { + connections.add(edge); + continue; + } + AssemblyMetadata.Port port = replacement.metadata().ports().stream() + .filter((AssemblyMetadata.Port available) -> available.role() == edge.child() && !used.contains(available.name())) + .sorted(Comparator.comparing((AssemblyMetadata.Port available) -> !available.name().equals(edge.port().name())) + .thenComparing(AssemblyMetadata.Port::name)) + .findFirst().orElse(null); + if (port == null) return null; + used.add(port.name()); + connections.add(new Edge(role, port, edge.child())); + } + return new AssemblyState(root, next, connections); + } + + List connections() { + return edges.stream().map((Edge edge) -> new Connection(edge.parent().code(), parts.get(edge.parent()).code(), + edge.port().parentLink(), edge.port().name(), edge.child().code(), parts.get(edge.child()).code(), + parts.get(edge.child()).metadata().rootLink(), edge.port().xyz(), edge.port().rpy())).toList(); + } + + int selectedMask() { + int mask = 0; + for (ComponentRole role : parts.keySet()) mask |= role.bit(); + return mask; + } + + String key() { + StringBuilder key = new StringBuilder(); + key.append(root.ordinal()).append('/'); + parts.forEach((ComponentRole role, MatchingCandidate candidate) -> { + key.append(role.ordinal()).append(':'); + appendToken(key, candidate.code()); + }); + for (Edge edge : edges) { + key.append(edge.parent().ordinal()).append('>').append(edge.child().ordinal()).append(':'); + appendToken(key, edge.port().name()); + } + return key.toString(); + } + + private static void appendToken(StringBuilder target, String value) { + target.append(value.length()).append(':').append(value).append('/'); + } + + record Edge(ComponentRole parent, AssemblyMetadata.Port port, ComponentRole child) { } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java new file mode 100644 index 0000000..986c42f --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java @@ -0,0 +1,142 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.config.MatchingProperties; +import com.linkerbot.cadworld.entity.Component; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +/** 分页扫描时仅保留优先候选、接口代表和数值极值,不把整张表装入内存。 */ +final class CandidatePool { + private final NormalizedMatchRequest request; + private final RequirementEvaluator evaluator; + private final MatchingProperties properties; + private final Map accumulators = new EnumMap<>(ComponentRole.class); + private final Comparator demandOrder; + private int scanned; + private int invalidMetadata; + private int invalidPorts; + private final List invalidCodeSamples = new ArrayList<>(); + + CandidatePool(NormalizedMatchRequest request, RequirementEvaluator evaluator, MatchingProperties properties) { + this.request = request; + this.evaluator = evaluator; + this.properties = properties; + this.demandOrder = Comparator.comparingInt((MatchingCandidate candidate) -> candidate.assessment().unmet().size()) + .thenComparing((MatchingCandidate candidate) -> candidate.assessment().deviation()) + .thenComparing((MatchingCandidate candidate) -> !candidate.assessment().robotFunctionMatched()) + .thenComparing(Comparator.comparingInt((MatchingCandidate candidate) -> + java.util.Arrays.stream(candidate.assessment().keywordScores()).sum()).reversed()) + .thenComparing(MatchingCandidate::code); + request.roles().forEach((ComponentRole role) -> accumulators.put(role, new Accumulator())); + } + + void accept(Component component) { + ComponentRole role = ComponentRole.require(component.getCategory()); + Accumulator accumulator = accumulators.get(role); + accumulator.observed++; + scanned++; + AssemblyMetadata metadata = AssemblyMetadata.read(component); + if (metadata == null) { + invalidMetadata++; + sampleInvalidCode(component.getComponentCode()); + return; + } + invalidPorts += metadata.invalidPorts(); + if (metadata.invalidPorts() > 0) sampleInvalidCode(component.getComponentCode()); + MatchingCandidate candidate = new MatchingCandidate(component, role, metadata, evaluator.assess(component, role, request)); + accumulator.accept(candidate); + } + + List invalidCodeSamples() { return List.copyOf(invalidCodeSamples); } + + private void sampleInvalidCode(String code) { + if (invalidCodeSamples.size() < 5) invalidCodeSamples.add(code); + } + + Result finish() { + Map> candidates = new EnumMap<>(ComponentRole.class); + Map observed = new EnumMap<>(ComponentRole.class); + Map eligible = new EnumMap<>(ComponentRole.class); + boolean limited = false; + for (Map.Entry entry : accumulators.entrySet()) { + List selected = entry.getValue().select(); + candidates.put(entry.getKey(), selected); + observed.put(entry.getKey(), entry.getValue().observed); + eligible.put(entry.getKey(), entry.getValue().eligible); + limited |= entry.getValue().eligible > selected.size(); + } + return new Result(Map.copyOf(candidates), Map.copyOf(observed), Map.copyOf(eligible), limited, + scanned, invalidMetadata, invalidPorts); + } + + private final class Accumulator { + private final List best = new ArrayList<>(); + private final Map interfaces = new HashMap<>(); + private MatchingCandidate minimumDegrees; + private MatchingCandidate maximumDegrees; + private MatchingCandidate minimumMass; + private MatchingCandidate maximumMass; + private int observed; + private int eligible; + + private void accept(MatchingCandidate candidate) { + eligible++; + best.add(candidate); + best.sort(demandOrder); + if (best.size() > properties.candidatesPerRole()) best.remove(best.size() - 1); + int requestedMask = request.roles().stream().mapToInt(ComponentRole::bit).reduce(0, (int left, int right) -> left | right); + int signature = candidate.metadata().interfaceMask() & requestedMask; + interfaces.merge(signature, candidate, (MatchingCandidate left, MatchingCandidate right) -> + demandOrder.compare(left, right) <= 0 ? left : right); + minimumDegrees = extreme(minimumDegrees, candidate, (MatchingCandidate value) -> + RequirementEvaluator.decimal(value.component().getDegreesOfFreedom()), true); + maximumDegrees = extreme(maximumDegrees, candidate, (MatchingCandidate value) -> + RequirementEvaluator.decimal(value.component().getDegreesOfFreedom()), false); + if (!RequirementEvaluator.unknownMass(candidate.component())) { + minimumMass = extreme(minimumMass, candidate, (MatchingCandidate value) -> value.component().getMassKg(), true); + maximumMass = extreme(maximumMass, candidate, (MatchingCandidate value) -> value.component().getMassKg(), false); + } + } + + private List select() { + Map selected = new LinkedHashMap<>(); + best.stream().limit(properties.preferredCandidatesPerRole()).forEach((MatchingCandidate candidate) -> add(selected, candidate)); + if (request.robot().degreesOfFreedom() != null) { + add(selected, minimumDegrees); + add(selected, maximumDegrees); + } + if (request.robot().massKg() != null) { + add(selected, minimumMass); + add(selected, maximumMass); + } + interfaces.entrySet().stream() + .sorted(Comparator.>comparingInt((Map.Entry entry) -> + Integer.bitCount(entry.getKey())).reversed().thenComparing(Map.Entry::getValue, demandOrder)) + .forEach((Map.Entry entry) -> add(selected, entry.getValue())); + best.forEach((MatchingCandidate candidate) -> add(selected, candidate)); + return selected.values().stream().sorted(demandOrder).toList(); + } + + private void add(Map selected, MatchingCandidate candidate) { + if (candidate != null && selected.size() < properties.candidatesPerRole()) selected.putIfAbsent(candidate.code(), candidate); + } + + private MatchingCandidate extreme(MatchingCandidate current, MatchingCandidate candidate, + Function value, boolean minimum) { + if (current == null) return candidate; + int compared = value.apply(candidate).compareTo(value.apply(current)); + if ((minimum ? compared < 0 : compared > 0) || (compared == 0 && demandOrder.compare(candidate, current) < 0)) return candidate; + return current; + } + } + + record Result(Map> candidates, Map observed, + Map eligible, boolean limited, int scanned, int invalidMetadata, int invalidPorts) { } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/ComponentRole.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/ComponentRole.java new file mode 100644 index 0000000..afa974b --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/ComponentRole.java @@ -0,0 +1,36 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.common.exception.BizException; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +public enum ComponentRole { + TORSO("torso_0", "躯干_0"), HEAD("head_0", "头_0"), WAIST("waist_0", "腰_0"), + ARM_L("arm_l", "臂_l"), ARM_R("arm_r", "臂_r"), HAND_L("hand_l", "手_l"), HAND_R("hand_r", "手_r"), + PEDAL_L("pedal_l", "足_l"), PEDAL_R("pedal_r", "足_r"), + FOOT_L("foot_l", "脚_l"), FOOT_R("foot_r", "脚_r"), TAIL("tail_0", "尾_0"); + + private final String code; + private final String chinese; + + ComponentRole(String code, String chinese) { + this.code = code; + this.chinese = chinese; + } + + public String code() { return code; } + int bit() { return 1 << ordinal(); } + List aliases() { return List.of(code, chinese); } + + public static Optional find(String value) { + String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT); + return Arrays.stream(values()).filter((ComponentRole role) -> + role.code.equals(normalized) || role.chinese.equals(normalized)).findFirst(); + } + + static ComponentRole require(String value) { + return find(value).orElseThrow(() -> new BizException(422, "INVALID_MATCH_REQUEST", "不支持的组件角色")); + } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchTextService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchTextService.java new file mode 100644 index 0000000..16c8caf --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchTextService.java @@ -0,0 +1,52 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.config.MatchingProperties; +import java.text.Normalizer; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.springframework.stereotype.Component; + +@Component +public class MatchTextService { + private final Map> expansions = new HashMap<>(); + private final Map canonical = new HashMap<>(); + + public MatchTextService(MatchingProperties properties) { + properties.synonyms().forEach((String key, List aliases) -> { + LinkedHashSet terms = new LinkedHashSet<>(); + terms.add(normalize(key)); + aliases.forEach((String alias) -> terms.add(normalize(alias))); + terms.remove(""); + if (terms.isEmpty()) throw new IllegalArgumentException("同义词组不能为空"); + List group = List.copyOf(terms); + for (String term : group) { + String previous = canonical.putIfAbsent(term, normalize(key)); + if (previous != null && !previous.equals(normalize(key))) { + throw new IllegalArgumentException("同义词不能属于多个不同词组"); + } + expansions.put(term, group); + } + }); + } + + boolean matches(String content, String query) { + String source = normalize(content); + String term = normalize(query); + if (term.isEmpty()) return true; + return expansions.getOrDefault(term, List.of(term)).stream().anyMatch(source::contains); + } + + boolean equivalent(String first, String second) { + String left = normalize(first); + String right = normalize(second); + return canonical.getOrDefault(left, left).equals(canonical.getOrDefault(right, right)); + } + + private String normalize(String value) { + return Normalizer.normalize(NormalizedMatchRequest.text(value), Normalizer.Form.NFKC) + .toLowerCase(Locale.ROOT).replaceAll("\\s+", ""); + } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java new file mode 100644 index 0000000..8e20ca1 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/MatchingCandidate.java @@ -0,0 +1,8 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.entity.Component; + +record MatchingCandidate(Component component, ComponentRole role, AssemblyMetadata metadata, + RequirementEvaluator.LocalAssessment assessment) { + String code() { return component.getComponentCode(); } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java new file mode 100644 index 0000000..2e2c180 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java @@ -0,0 +1,69 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.common.exception.BizException; +import com.linkerbot.cadworld.dto.matching.PartRequirements; +import com.linkerbot.cadworld.dto.matching.RobotMatchRequest; +import com.linkerbot.cadworld.dto.matching.RobotRequirements; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +record NormalizedMatchRequest(List roles, List keywords, + RobotRequirements robot, Map parts) { + static NormalizedMatchRequest from(RobotMatchRequest request) { + if (request.requiredParts() == null || request.requiredParts().isEmpty()) { + throw invalid("requiredParts不能为空"); + } + List roles = request.requiredParts().stream().map(ComponentRole::require) + .distinct().sorted(Comparator.comparingInt(ComponentRole::ordinal)).toList(); + RobotRequirements supplied = request.robotRequirements(); + RobotRequirements robot = supplied == null ? new RobotRequirements(null, null, null, Map.of()) + : new RobotRequirements(supplied.degreesOfFreedom(), supplied.massKg(), text(supplied.functionDescription()), + operators(supplied.operators(), numericValues(supplied.degreesOfFreedom(), supplied.massKg(), null))); + Map parts = new EnumMap<>(ComponentRole.class); + for (PartRequirements part : request.partRequirements() == null ? List.of() : request.partRequirements()) { + ComponentRole role = ComponentRole.require(part.category()); + if (!roles.contains(role)) throw invalid("部件条件的category必须包含在requiredParts中"); + if (parts.containsKey(role)) throw invalid("同一组件角色不得重复定义部件条件"); + parts.put(role, new PartRequirements(role.code(), text(part.material()), part.degreesOfFreedom(), + part.massKg(), part.torqueNm(), text(part.functionDescription()), text(part.shape()), text(part.size()), + operators(part.operators(), numericValues(part.degreesOfFreedom(), part.massKg(), part.torqueNm())))); + } + Set keywords = new LinkedHashSet<>(); + for (String keyword : request.requirements() == null ? List.of() : request.requirements()) { + if (!text(keyword).isEmpty()) keywords.add(text(keyword)); + } + return new NormalizedMatchRequest(roles, List.copyOf(keywords), robot, Map.copyOf(parts)); + } + + private static Map numericValues(Integer degrees, java.math.BigDecimal mass, java.math.BigDecimal torque) { + Map values = new LinkedHashMap<>(); + values.put("degreesOfFreedom", degrees); + values.put("massKg", mass); + if (torque != null) values.put("torqueNm", torque); + return values; + } + + private static Map operators(Map supplied, Map values) { + Map result = new LinkedHashMap<>(); + if (supplied != null) { + supplied.forEach((String field, String value) -> { + String operator = text(value).toLowerCase(Locale.ROOT); + if (!values.containsKey(field) || values.get(field) == null + || !Set.of("eq", "gte", "lte").contains(operator)) { + throw invalid("operators仅支持已提供数值字段的eq、gte、lte"); + } + result.put(field, operator); + }); + } + return Map.copyOf(result); + } + + static String text(String value) { return value == null ? "" : value.trim(); } + private static BizException invalid(String message) { return new BizException(422, "INVALID_MATCH_REQUEST", message); } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java new file mode 100644 index 0000000..a5ea878 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/PublicComponentQueryService.java @@ -0,0 +1,78 @@ +package com.linkerbot.cadworld.service.matching; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.linkerbot.cadworld.common.exception.BizException; +import com.linkerbot.cadworld.dto.matching.PublicComponentResponse; +import com.linkerbot.cadworld.entity.Component; +import com.linkerbot.cadworld.mapper.ComponentMapper; +import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@RequiredArgsConstructor +public class PublicComponentQueryService { + private final ComponentMapper mapper; + private final ObjectStorageUrlResolver urls; + + @Transactional(readOnly = true) + public PublicComponentResponse get(String componentCode) { + Component component = mapper.selectOne(publicFields().eq(Component::getComponentCode, componentCode)); + if (component == null) throw new BizException(404, "COMPONENT_NOT_FOUND", "组件不存在"); + return toResponse(component); + } + + void scan(List roles, Consumer consumer) { + List aliases = roles.stream().flatMap((ComponentRole role) -> role.aliases().stream()).toList(); + long cursor = 0; + while (true) { + List page = mapper.selectList(candidateFields().in(Component::getCategory, aliases) + .gt(Component::getId, cursor).orderByAsc(Component::getId).last("LIMIT 200")); + for (Component component : page) consumer.accept(component); + if (page.size() < 200) return; + cursor = page.get(page.size() - 1).getId(); + } + } + + Map load(Collection codes) { + Map result = new LinkedHashMap<>(); + if (codes.isEmpty()) return result; + for (Component component : mapper.selectList(publicFields().in(Component::getComponentCode, codes))) { + result.put(component.getComponentCode(), toResponse(component)); + } + if (result.size() != codes.size()) { + throw new BizException(409, "COMPONENT_REVISION_CONFLICT", "组件已变化,请重新匹配"); + } + return result; + } + + private PublicComponentResponse toResponse(Component component) { + String category = ComponentRole.find(component.getCategory()).map(ComponentRole::code).orElse(component.getCategory()); + return new PublicComponentResponse(component.getComponentCode(), component.getComponentName(), category, + component.getDescription(), component.getMaterial(), component.getMassKg(), component.getDegreesOfFreedom(), + component.getFunctionDescription(), component.getShape(), component.getSize(), component.getTorqueNm(), + component.getBomList(), component.getUrdfInfo(), component.getVersion(), + urls.resolvePublicUrl(component.getStepObjectKey()), urls.resolvePublicUrl(component.getUrdfMainObjectKey())); + } + + private LambdaQueryWrapper candidateFields() { + return new LambdaQueryWrapper().select(Component::getId, Component::getComponentCode, + Component::getComponentName, Component::getCategory, Component::getDescription, Component::getMaterial, + Component::getMassKg, Component::getDegreesOfFreedom, Component::getFunctionDescription, Component::getShape, + Component::getSize, Component::getTorqueNm, Component::getUrdfInfo, Component::getUrdfMainObjectKey); + } + + private LambdaQueryWrapper publicFields() { + return new LambdaQueryWrapper().select(Component::getComponentCode, Component::getComponentName, + Component::getCategory, Component::getDescription, Component::getMaterial, Component::getMassKg, + Component::getDegreesOfFreedom, Component::getFunctionDescription, Component::getShape, Component::getSize, + Component::getTorqueNm, Component::getBomList, Component::getUrdfInfo, Component::getVersion, + Component::getStepObjectKey, Component::getUrdfMainObjectKey); + } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java new file mode 100644 index 0000000..f21497c --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RequirementEvaluator.java @@ -0,0 +1,238 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.dto.matching.PartRequirements; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Totals; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.UnmetRequirement; +import com.linkerbot.cadworld.dto.matching.RobotRequirements; +import com.linkerbot.cadworld.entity.Component; +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class RequirementEvaluator { + private final MatchTextService text; + + LocalAssessment assess(Component component, ComponentRole role, NormalizedMatchRequest request) { + AssessmentBuilder assessment = new AssessmentBuilder("PART", role.code()); + PartRequirements requirement = request.parts().get(role); + if (requirement != null) { + assessment.number("degreesOfFreedom", requirement.degreesOfFreedom(), decimal(component.getDegreesOfFreedom()), + requirement.operators(), false); + assessment.number("massKg", requirement.massKg(), component.getMassKg(), requirement.operators(), unknownMass(component)); + assessment.number("torqueNm", requirement.torqueNm(), component.getTorqueNm(), requirement.operators(), false); + checkText(assessment, "material", requirement.material(), component.getMaterial(), true); + checkText(assessment, "functionDescription", requirement.functionDescription(), component.getFunctionDescription(), false); + checkText(assessment, "shape", requirement.shape(), component.getShape(), false); + checkText(assessment, "size", requirement.size(), component.getSize(), false); + } + int[] scores = new int[request.keywords().size()]; + for (int index = 0; index < scores.length; index++) { + String keyword = request.keywords().get(index); + scores[index] = Math.max(hit(component.getComponentName(), keyword, 5), hit(component.getFunctionDescription(), keyword, 5)); + scores[index] = Math.max(scores[index], hit(component.getDescription(), keyword, 2)); + scores[index] = Math.max(scores[index], hit(role.code(), keyword, 2)); + for (String alias : role.aliases()) scores[index] = Math.max(scores[index], hit(alias, keyword, 2)); + scores[index] = Math.max(scores[index], hit(component.getMaterial(), keyword, 1)); + scores[index] = Math.max(scores[index], hit(component.getShape(), keyword, 1)); + scores[index] = Math.max(scores[index], hit(component.getSize(), keyword, 1)); + } + return new LocalAssessment(List.copyOf(assessment.unmet), assessment.deviation, scores, + text.matches(component.getFunctionDescription(), request.robot().functionDescription())); + } + + Evaluation evaluate(AssemblyState state, NormalizedMatchRequest request) { + List unmet = new ArrayList<>(); + BigDecimal deviation = BigDecimal.ZERO; + long degrees = 0; + BigDecimal knownMass = BigDecimal.ZERO; + boolean massComplete = !state.parts().isEmpty(); + boolean functionMatched = false; + int[] scores = new int[request.keywords().size()]; + for (MatchingCandidate candidate : state.parts().values()) { + Component component = candidate.component(); + degrees += component.getDegreesOfFreedom() == null ? 0 : component.getDegreesOfFreedom(); + if (unknownMass(component)) massComplete = false; + else knownMass = knownMass.add(component.getMassKg()); + unmet.addAll(candidate.assessment().unmet()); + deviation = deviation.add(candidate.assessment().deviation()); + functionMatched |= candidate.assessment().robotFunctionMatched(); + mergeScores(scores, candidate.assessment().keywordScores()); + } + Totals totals = new Totals(degrees, massComplete ? knownMass : null, knownMass, massComplete); + AssessmentBuilder robot = new AssessmentBuilder("ROBOT", null); + robot.number("degreesOfFreedom", request.robot().degreesOfFreedom(), BigDecimal.valueOf(degrees), request.robot().operators(), false); + robot.number("massKg", request.robot().massKg(), totals.massKg(), request.robot().operators(), !massComplete); + if (!NormalizedMatchRequest.text(request.robot().functionDescription()).isEmpty() && !functionMatched) { + robot.unmet.add(new UnmetRequirement("ROBOT", null, "functionDescription", "contains", + request.robot().functionDescription(), null, "NO_TEXT_MATCH")); + } + unmet.addAll(robot.unmet); + List unmatched = new ArrayList<>(); + int keywordScore = 0; + for (int index = 0; index < scores.length; index++) { + keywordScore += scores[index]; + if (scores[index] == 0) unmatched.add(request.keywords().get(index)); + } + return new Evaluation(totals, List.copyOf(unmet), List.copyOf(unmatched), deviation.add(robot.deviation), keywordScore); + } + + /** 中间状态使用可达角色及剩余候选数值区间,避免把尚未组装完整的总量当最终结果排序。 */ + Estimate estimate(AssemblyState state, Evaluation evaluation, Map summaries, + NormalizedMatchRequest request) { + int selected = state.selectedMask(); + int possible = selected; + int interfaces = 0; + for (MatchingCandidate candidate : state.parts().values()) interfaces |= candidate.metadata().interfaceMask(); + int previous; + do { + previous = possible; + for (Map.Entry entry : summaries.entrySet()) { + if ((interfaces & entry.getKey().bit()) != 0 && (possible & entry.getKey().bit()) == 0) { + possible |= entry.getKey().bit(); + interfaces |= entry.getValue().interfaces(); + } + } + } while (previous != possible); + + int unmet = 0; + BigDecimal deviation = BigDecimal.ZERO; + BigDecimal minimumDegrees = BigDecimal.valueOf(evaluation.totals().degreesOfFreedom()); + BigDecimal maximumDegrees = minimumDegrees; + BigDecimal minimumMass = evaluation.totals().knownMassKg(); + BigDecimal maximumMass = minimumMass; + boolean massKnown = evaluation.totals().massComplete(); + boolean functionMatched = false; + int[] scores = new int[request.keywords().size()]; + for (MatchingCandidate candidate : state.parts().values()) { + unmet += candidate.assessment().unmet().size(); + deviation = deviation.add(candidate.assessment().deviation()); + functionMatched |= candidate.assessment().robotFunctionMatched(); + mergeScores(scores, candidate.assessment().keywordScores()); + } + for (Map.Entry entry : summaries.entrySet()) { + if ((possible & ~selected & entry.getKey().bit()) == 0) continue; + PoolSummary summary = entry.getValue(); + minimumDegrees = minimumDegrees.add(summary.minimumDegrees()); + maximumDegrees = maximumDegrees.add(summary.maximumDegrees()); + minimumMass = minimumMass.add(summary.minimumMass()); + maximumMass = maximumMass.add(summary.maximumMass()); + massKnown &= summary.hasKnownMass(); + functionMatched |= summary.functionMatched(); + unmet += summary.minimumUnmet(); + deviation = deviation.add(summary.minimumDeviation()); + mergeScores(scores, summary.keywordScores()); + } + RobotRequirements robot = request.robot(); + BigDecimal degreesGap = intervalGap(robot.degreesOfFreedom() == null ? null : decimal(robot.degreesOfFreedom()), minimumDegrees, maximumDegrees, + robot.operators().getOrDefault("degreesOfFreedom", "eq")); + BigDecimal massGap = robot.massKg() == null ? BigDecimal.ZERO : !massKnown ? BigDecimal.ONE + : intervalGap(robot.massKg(), minimumMass, maximumMass, robot.operators().getOrDefault("massKg", "eq")); + if (degreesGap.signum() > 0) unmet++; + if (massGap.signum() > 0) unmet++; + if (!NormalizedMatchRequest.text(robot.functionDescription()).isEmpty() && !functionMatched) unmet++; + int score = java.util.Arrays.stream(scores).sum(); + return new Estimate(Integer.bitCount(possible), unmet, deviation.add(degreesGap).add(massGap), score); + } + + static PoolSummary summarize(List candidates, int keywordCount) { + BigDecimal minimumDegrees = null; + BigDecimal maximumDegrees = BigDecimal.ZERO; + BigDecimal minimumMass = null; + BigDecimal maximumMass = BigDecimal.ZERO; + BigDecimal minimumDeviation = null; + int minimumUnmet = Integer.MAX_VALUE; + int interfaces = 0; + boolean functionMatched = false; + int[] scores = new int[keywordCount]; + for (MatchingCandidate candidate : candidates) { + BigDecimal degrees = decimal(candidate.component().getDegreesOfFreedom()); + minimumDegrees = minimumDegrees == null ? degrees : minimumDegrees.min(degrees); + maximumDegrees = maximumDegrees.max(degrees); + if (!unknownMass(candidate.component())) { + BigDecimal mass = candidate.component().getMassKg(); + minimumMass = minimumMass == null ? mass : minimumMass.min(mass); + maximumMass = maximumMass.max(mass); + } + minimumUnmet = Math.min(minimumUnmet, candidate.assessment().unmet().size()); + minimumDeviation = minimumDeviation == null ? candidate.assessment().deviation() + : minimumDeviation.min(candidate.assessment().deviation()); + interfaces |= candidate.metadata().interfaceMask(); + functionMatched |= candidate.assessment().robotFunctionMatched(); + mergeScores(scores, candidate.assessment().keywordScores()); + } + return new PoolSummary(minimumDegrees, maximumDegrees, minimumMass == null ? BigDecimal.ZERO : minimumMass, + maximumMass, minimumMass != null, interfaces, functionMatched, scores, minimumUnmet, minimumDeviation); + } + + private void checkText(AssessmentBuilder assessment, String field, String expected, String actual, boolean exact) { + if (NormalizedMatchRequest.text(expected).isEmpty()) return; + if (exact ? text.equivalent(actual, expected) : text.matches(actual, expected)) return; + assessment.unmet.add(new UnmetRequirement(assessment.scope, assessment.category, field, exact ? "eq" : "contains", + expected, actual, "NO_TEXT_MATCH")); + } + + private int hit(String content, String query, int weight) { return text.matches(content, query) ? weight : 0; } + static boolean unknownMass(Component component) { return component.getMassKg() == null || component.getMassKg().signum() <= 0; } + static BigDecimal decimal(Integer value) { return value == null ? BigDecimal.ZERO : BigDecimal.valueOf(value); } + + private static void mergeScores(int[] target, int[] source) { + for (int index = 0; index < target.length; index++) target[index] = Math.max(target[index], source[index]); + } + + private static BigDecimal intervalGap(BigDecimal expected, BigDecimal minimum, BigDecimal maximum, String operator) { + if (expected == null) return BigDecimal.ZERO; + BigDecimal actual = switch (operator) { + case "gte" -> maximum; + case "lte" -> minimum; + default -> expected.max(minimum).min(maximum); + }; + return gap(expected, actual, operator); + } + + private static BigDecimal gap(BigDecimal expected, BigDecimal actual, String operator) { + BigDecimal distance = switch (operator) { + case "gte" -> expected.subtract(actual).max(BigDecimal.ZERO); + case "lte" -> actual.subtract(expected).max(BigDecimal.ZERO); + default -> actual.subtract(expected).abs(); + }; + return distance.divide(expected.abs().max(BigDecimal.ONE), MathContext.DECIMAL64); + } + + private static final class AssessmentBuilder { + private final String scope; + private final String category; + private final List unmet = new ArrayList<>(); + private BigDecimal deviation = BigDecimal.ZERO; + + private AssessmentBuilder(String scope, String category) { this.scope = scope; this.category = category; } + + private void number(String field, Number target, BigDecimal actual, Map operators, boolean unknown) { + if (target == null) return; + String operator = operators.getOrDefault(field, "eq"); + BigDecimal expected = new BigDecimal(target.toString()); + if (unknown || actual == null) { + unmet.add(new UnmetRequirement(scope, category, field, operator, target, null, "UNKNOWN_MASS")); + deviation = deviation.add(BigDecimal.ONE); + return; + } + BigDecimal penalty = gap(expected, actual, operator); + if (penalty.signum() > 0) { + unmet.add(new UnmetRequirement(scope, category, field, operator, target, actual, "VALUE_MISMATCH")); + deviation = deviation.add(penalty); + } + } + } + + record LocalAssessment(List unmet, BigDecimal deviation, int[] keywordScores, boolean robotFunctionMatched) { } + record Evaluation(Totals totals, List unmet, List unmatched, BigDecimal deviation, int keywordScore) { } + record Estimate(int possibleParts, int unmet, BigDecimal deviation, int keywordScore) { } + record PoolSummary(BigDecimal minimumDegrees, BigDecimal maximumDegrees, BigDecimal minimumMass, BigDecimal maximumMass, + boolean hasKnownMass, int interfaces, boolean functionMatched, int[] keywordScores, + int minimumUnmet, BigDecimal minimumDeviation) { } +} diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java new file mode 100644 index 0000000..255ca11 --- /dev/null +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java @@ -0,0 +1,116 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.common.api.RequestIdHolder; +import com.linkerbot.cadworld.config.MatchingProperties; +import com.linkerbot.cadworld.dto.matching.PublicComponentResponse; +import com.linkerbot.cadworld.dto.matching.RobotMatchRequest; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Alternatives; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.MissingPart; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Replacement; +import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Totals; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Slf4j +@RequiredArgsConstructor +public class RobotMatchingService { + private final PublicComponentQueryService components; + private final RequirementEvaluator evaluator; + private final AssemblySearchEngine search; + private final MatchingProperties properties; + + @Transactional(readOnly = true) + public RobotMatchResponse match(RobotMatchRequest input) { + long started = System.nanoTime(); + NormalizedMatchRequest request = NormalizedMatchRequest.from(input); + CandidatePool collector = new CandidatePool(request, evaluator, properties); + components.scan(request.roles(), collector::accept); + CandidatePool.Result pool = collector.finish(); + AssemblySearchEngine.Result result = search.search(pool, request); + RobotMatchResponse response = response(request, pool, result); + if (pool.invalidMetadata() > 0 || pool.invalidPorts() > 0) { + log.warn("组件装配元数据异常 requestId={} invalidComponentCount={} invalidPortCount={} componentCodeSamples={}", + RequestIdHolder.get(), pool.invalidMetadata(), pool.invalidPorts(), collector.invalidCodeSamples()); + } + if (!response.unmetRequirements().isEmpty() || !response.missingParts().isEmpty() || !response.unmatchedKeywords().isEmpty()) { + List unmetFields = response.unmetRequirements().stream().map((RobotMatchResponse.UnmetRequirement item) -> + item.scope() + ":" + item.category() + ":" + item.field() + ":" + item.reason()).toList(); + List missingReasons = response.missingParts().stream().map((MissingPart item) -> item.category() + ":" + item.reason()).toList(); + log.info("组件匹配降级 requestId={} unmetFields={} missingReasons={} unmatchedKeywordCount={}", + RequestIdHolder.get(), unmetFields, missingReasons, response.unmatchedKeywords().size()); + } + log.info("组件匹配完成 requestId={} requestedCount={} scannedCount={} selectedCount={} status={} unmetCount={} missingCount={} searchLimited={} expansions={} durationMs={}", + RequestIdHolder.get(), request.roles().size(), pool.scanned(), response.parts().size(), response.status(), + response.unmetRequirements().size(), response.missingParts().size(), result.limited(), result.expansions(), + (System.nanoTime() - started) / 1_000_000); + return response; + } + + private RobotMatchResponse response(NormalizedMatchRequest request, CandidatePool.Result pool, AssemblySearchEngine.Result result) { + List missing = missing(request, pool, result); + if (result.best() == null) { + return new RobotMatchResponse("NO_MATCH", null, List.of(), List.of(), List.of(), + new Totals(0, null, BigDecimal.ZERO, false), List.of(), request.keywords(), missing, result.limited()); + } + AssemblyState selected = result.best().state(); + RequirementEvaluator.Evaluation evaluation = result.best().evaluation(); + Map> alternatives = replacements(selected, pool, request); + Set codes = new LinkedHashSet<>(); + selected.parts().values().forEach((MatchingCandidate candidate) -> codes.add(candidate.code())); + alternatives.values().forEach((List items) -> items.forEach((ReplacementState item) -> codes.add(item.candidate().code()))); + Map publicComponents = components.load(codes); + List parts = selected.parts().values().stream() + .map((MatchingCandidate candidate) -> publicComponents.get(candidate.code())).toList(); + List publicAlternatives = new ArrayList<>(); + alternatives.forEach((ComponentRole role, List items) -> publicAlternatives.add(new Alternatives(role.code(), + items.stream().map((ReplacementState item) -> new Replacement(publicComponents.get(item.candidate().code()), + item.state().connections(), item.evaluation().totals(), item.evaluation().unmet(), item.evaluation().unmatched())).toList()))); + String status = !missing.isEmpty() ? "PARTIAL" : !evaluation.unmet().isEmpty() || !evaluation.unmatched().isEmpty() ? "FALLBACK" : "MATCHED"; + return new RobotMatchResponse(status, selected.root().code(), parts, selected.connections(), List.copyOf(publicAlternatives), + evaluation.totals(), evaluation.unmet(), evaluation.unmatched(), missing, result.limited()); + } + + private Map> replacements(AssemblyState selected, CandidatePool.Result pool, + NormalizedMatchRequest request) { + Map> result = new EnumMap<>(ComponentRole.class); + Comparator order = Comparator.comparingInt((ReplacementState item) -> item.evaluation().unmet().size()) + .thenComparing((ReplacementState item) -> item.evaluation().deviation()) + .thenComparing(Comparator.comparingInt((ReplacementState item) -> item.evaluation().keywordScore()).reversed()) + .thenComparing((ReplacementState item) -> item.candidate().code()); + selected.parts().forEach((ComponentRole role, MatchingCandidate current) -> { + List compatible = new ArrayList<>(); + for (MatchingCandidate candidate : pool.candidates().get(role)) { + if (candidate.code().equals(current.code())) continue; + AssemblyState replaced = selected.replace(candidate); + if (replaced != null) compatible.add(new ReplacementState(candidate, replaced, evaluator.evaluate(replaced, request))); + } + result.put(role, compatible.stream().sorted(order).limit(5).toList()); + }); + return result; + } + + private List missing(NormalizedMatchRequest request, CandidatePool.Result pool, AssemblySearchEngine.Result result) { + List missing = new ArrayList<>(); + for (ComponentRole role : request.roles()) { + if (result.best() != null && result.best().state().parts().containsKey(role)) continue; + String reason = pool.observed().get(role) == 0 ? "NO_COMPONENT" : pool.eligible().get(role) == 0 + ? "INVALID_ASSEMBLY_METADATA" : result.limited() ? "SEARCH_LIMIT" : "NO_COMPATIBLE_CONNECTION"; + missing.add(new MissingPart(role.code(), reason)); + } + return List.copyOf(missing); + } + + private record ReplacementState(MatchingCandidate candidate, AssemblyState state, RequirementEvaluator.Evaluation evaluation) { } +} diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/MatchingConfigurationTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/MatchingConfigurationTest.java new file mode 100644 index 0000000..f2bcf61 --- /dev/null +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/matching/MatchingConfigurationTest.java @@ -0,0 +1,48 @@ +package com.linkerbot.cadworld.service.matching; + +import com.linkerbot.cadworld.config.MatchingProperties; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.source.ConfigurationPropertySources; +import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.core.io.ByteArrayResource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class MatchingConfigurationTest { + @Test + void yamlCanOverrideChineseGroupsAddNewGroupsAndKeepOtherDefaults() { + YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); + yaml.setResources(new ByteArrayResource(""" + app: + matching: + synonyms: + "[跑步]": [疾跑, sprint] + "[夹持]": [抓取, gripping] + """.getBytes(StandardCharsets.UTF_8))); + Properties properties = Objects.requireNonNull(yaml.getObject()); + Binder binder = new Binder(ConfigurationPropertySources.from(new PropertiesPropertySource("test", properties))); + MatchingProperties bound = binder.bind("app.matching", Bindable.of(MatchingProperties.class)) + .orElseThrow(() -> new IllegalStateException("同义词配置绑定失败")); + MatchTextService text = new MatchTextService(bound); + assertThat(text.matches("可以疾跑", "跑步")).isTrue(); + assertThat(text.matches("用于奔跑", "跑步")).isFalse(); + assertThat(text.matches("用于抓取", "夹持")).isTrue(); + assertThat(text.matches("机器人", "ROBOT")).isTrue(); + assertThat(text.equivalent(" ALUMINIUM ALLOY ", "铝合金")).isTrue(); + } + + @Test + void ambiguousSynonymGroupsFailInsteadOfSilentlyChangingMaterialOrFunctionMeaning() { + MatchingProperties properties = new MatchingProperties(50, 30, 128, 50000, Map.of("冲刺", List.of("跑步"))); + assertThatThrownBy(() -> new MatchTextService(properties)).isInstanceOf(IllegalArgumentException.class); + } +}