后台管理初始化

This commit is contained in:
lxp
2026-10-09 16:49:06 +08:00
parent 348c0ccc98
commit b591e87850
125 changed files with 6667 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
# Shell environment only: copy to .env, fill the values, then source it as described in README.
SPRING_PROFILES_ACTIVE=test
SERVER_PORT=8992
APP_DB_URL='jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai'
APP_DB_USERNAME=
APP_DB_PASSWORD=
APP_STORAGE_PROVIDER=minio
APP_MINIO_ENDPOINT=
APP_MINIO_ACCESS_KEY=
APP_MINIO_SECRET_KEY=
APP_MINIO_BUCKET=
APP_STORAGE_PUBLIC_API_BASE_URL=http://127.0.0.1:8992
APP_STORAGE_PUBLIC_BASE_URL=http://127.0.0.1:8992/admin-api/component-assets
# At least 32 UTF-8 bytes. Empty uses a random key and invalidates sessions on restart.
APP_UPLOAD_SESSION_SECRET=
APP_ADMIN_OPERATOR_ID=0
APP_ADMIN_OPERATOR_NAME=TEST_OPERATOR
APP_INTERFACE_BREP_PYTHON=python3
APP_INTERFACE_BREP_SCRIPT=classpath:scripts/step_brep_topology.py
LOG_PATH=logs
+57
View File
@@ -0,0 +1,57 @@
# Maven 构建产物
target/
*.class
# IDE 本地配置
.idea/
*.iml
*.ipr
*.iws
.vscode/
.classpath
.project
.settings/
.factorypath
# 本地环境配置(保留配置示例和 test/prod 配置)
.env
.env.*
!.env.example
application-local.yml
application-local.yaml
application-local.properties
# Python 环境和缓存
.venv/
venv/
__pycache__/
*.py[cod]
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
.coverage.*
htmlcov/
# 运行日志、本地上传文件和 JVM 转储
**/logs/*
!**/logs/.gitkeep
*.log
*.log.*
/data/
/cadworld-*/data/
*.pid
*.hprof
hs_err_pid*
replay_pid*
# 操作系统文件和编辑器临时文件
.DS_Store
._*
Thumbs.db
Desktop.ini
*.swp
*.swo
*~
*.tmp
*.temp
+134
View File
@@ -1,2 +1,136 @@
# cadworld
Java 21 / Spring Boot 3.4.4 / MyBatis-Plus 后台多模块项目。包名统一为 `com.linkerbot.cadworld`,Maven groupId 为 `com.linkerbot`。当前包含接口库、组件库、用户管理和操作日志,默认端口 `8992`。
## 模块
| 模块 | 内容 |
| --- | --- |
| cadworld-adminapi | 后台启动应用、Controller、Web 配置、操作日志拦截 |
| cadworld-service | 业务服务、Mapper、MinIO/本地存储、几何与资源校验 |
| cadworld-bean | 实体、DTO、枚举 |
| cadworld-common | 响应、异常、JSON 类型处理、请求编号、进程执行工具 |
| cadworld-api | 预留前台 API 模块 |
| cadworld-security | 预留 admin/api/common 三个安全子模块 |
本阶段后台接口不鉴权,没有登录、角色或菜单权限接口。日志和上传流程统一使用配置的测试操作人,默认 `0 / TEST_OPERATOR`,不要求 `sys_user` 中存在该用户。上传会话签名用于限制会话类型、对象目录及有效期,与账号登录认证独立。
## 数据库准备
默认测试库为 `39.105.93.138:3306/cadworld`,账号和密码必须自行通过环境变量提供。应用启动不执行建表或迁移。
已有库包含所给 `cadworld.sql` 中的 `sys_user` 和 `component` 表时,执行增量脚本:
```bash
mysql -h 39.105.93.138 -P 3306 -u YOUR_USER -p cadworld < db/upgrade.sql
```
对于已经创建好的空数据库,执行初始化脚本:
```bash
mysql -h 39.105.93.138 -P 3306 -u YOUR_USER -p cadworld < db/init.sql
```
两个脚本均可重复执行,不包含删表语句、数据改写或 Flyway 历史处理。增量脚本新增接口定义、历史修订、组件资源索引、操作日志表,并为 `sys_user` 增加 `deleted`。仅初始化本次业务需要的六张表;原系统其他业务表无需迁移。
用户删除保留数据及手机号唯一索引,已删除用户的手机号不能重新注册。组件删除沿用物理删除及资源索引级联清理;接口删除保留历史修订,原接口 ID 不能再次创建。删除操作不会清理 MinIO 中的资源对象。
## 配置与启动
```bash
cp .env.example .env
# 填写 .env 中的数据库和 MinIO 参数。
set -a
source .env
set +a
mvn clean verify
java -jar cadworld-adminapi/target/cadworld-adminapi-0.0.1-SNAPSHOT.jar
```
`.env` 通过 shell 导入,Spring Boot 不自动读取该文件。默认 profile 为 `test`;使用 `prod` 时必须设置 `APP_DB_URL`、`APP_DB_USERNAME`、`APP_DB_PASSWORD`,Swagger 默认关闭。
| 环境变量 | 用途 |
| --- | --- |
| APP_DB_URL / APP_DB_USERNAME / APP_DB_PASSWORD | MySQL 连接配置 |
| SERVER_PORT | 后台端口,默认 8992 |
| APP_STORAGE_PROVIDER | 默认 `minio`;支持 `local` 用于本地开发和测试 |
| APP_MINIO_ENDPOINT / APP_MINIO_ACCESS_KEY / APP_MINIO_SECRET_KEY / APP_MINIO_BUCKET | MinIO 连接及 bucket,均需配置 |
| APP_STORAGE_PUBLIC_API_BASE_URL | 生成上传地址所用的后台外部地址 |
| APP_STORAGE_PUBLIC_BASE_URL | 生成下载地址的资源前缀,默认 `/admin-api/component-assets` |
| APP_STORAGE_LOCAL_ROOT | 本地存储目录,默认 `./data/assets` |
| APP_UPLOAD_SESSION_SECRET | 至少 32 个 UTF-8 字节的上传签名密钥;留空时生成进程内随机密钥,重启后原上传会话失效 |
| APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME | 测试操作人,默认 `0 / TEST_OPERATOR` |
| LOG_PATH | 运行日志目录,默认 `logs` |
资源通过后台上传和读取,无需客户端直连 MinIO。MinIO 实现首次使用时检查 bucket,不存在时尝试创建,因此账号需有对应权限。线上地址配置应包含实际域名及反向代理路径,上传和下载地址均使用 `/admin-api` 前缀。
接口文档:`http://127.0.0.1:8992/swagger-ui.html`;OpenAPI:`/api-docs`。日志配置集中在 `cadworld-common`,按应用名输出 `cadworld-adminapi.log` 和独立的 `cadworld-adminapi-error.log`,并携带请求编号。普通日志按天及 100 MB 滚动,保留 30 天、最多 10 GB;ERROR 日志按天及 50 MB 滚动,保留 60 天、最多 5 GB。归档文件保存在 `logs/archive`(支持 `LOG_PATH` 覆盖)。测试环境项目包日志为 DEBUG,生产环境为 INFO。
## 后台接口
响应沿用 `{code, message, data, requestId}`,分页数据为 `{items, page, size, total}`。新建用户和操作日志列表的页码从 1 开始,默认每页 20,最多 100。
| 路径 | 方法及行为 |
| --- | --- |
| /admin-api/interfaces | GET 列表(keyword),POST 创建 |
| /admin-api/interfaces/{id} | GET 详情,PUT 修改,DELETE 删除 |
| /admin-api/interfaces/{id}/assets | POST 源文件上传,参数 geometryRevision、file |
| /admin-api/interfaces/{id}/pose-candidates | POST 计算姿态候选 |
| /admin-api/interfaces/{id}/confirm-port | POST 校验并确认端口 |
| /admin-api/interface-brep/analyze | POST multipart STEP/STP 精确解析 |
| /admin-api/components | GET 分页列表(page、size、keyword),POST 创建 |
| /admin-api/components/{id} | GET 详情,PUT 修改,DELETE 删除 |
| /admin-api/components/cover-image-upload-sessions | POST 创建封面上传会话;子路径 /upload-url、/complete 均为 POST |
| /admin-api/components/urdf-upload-sessions | POST 创建 URDF/RFS 上传会话;子路径 /upload-url、/complete 均为 POST |
| /admin-api/component-assets/upload | PUT 文件流上传,参数 objectKey |
| /admin-api/component-assets/{objectKey} | GET 资源文件 |
| /admin-api/users | GET 分页用户列表,POST 创建 |
| /admin-api/users/{id} | GET 详情,PUT 修改,DELETE 逻辑删除 |
| /admin-api/operation-logs | GET 分页操作日志 |
| /admin-api/operation-logs/{id} | GET 日志详情 |
用户创建及修改请求示例:
```json
{"phone":"13812345678","nickname":"测试用户","status":"ACTIVE","userType":"NORMAL"}
```
手机号为大陆手机号,昵称必填且最多 64 字符;状态为 `ACTIVE/DISABLED`,用户类型为 `NORMAL/ADMIN`。创建时省略状态和类型默认为 `ACTIVE/NORMAL`,修改时省略则保留原值。用户列表支持 `keyword`(手机号/昵称)、`userType`、`status` 筛选,查询排除已逻辑删除用户。
操作日志列表支持 `module`(`COMPONENT/INTERFACE`)、`action`、`success`、`operatorId`、`from`、`to`。时间使用上海时区的 ISO 本地时间,例如 `2026-10-09T16:00:00`。
日志动作:`CREATE`、`UPDATE`、`DELETE`、`PREPARE_UPLOAD`、`PREPARE_UPLOAD_URL`、`UPLOAD`、`COMPLETE_UPLOAD`。成功及失败的写操作均记录;查询、下载、STEP 分析、姿态计算及用户管理不记录业务操作日志。日志只保存操作元信息和标识,不保存请求体、文件或上传令牌;日志持久化使用独立事务,失败时输出运行错误日志并保留原请求结果。
## STEP 解析运行环境
建议使用 Python 3.12,OCCT 依赖锁定为 `cadquery-ocp==7.8.1.1`:
```bash
python3.12 -m venv cadworld-adminapi/.venv
cadworld-adminapi/.venv/bin/pip install -r cadworld-adminapi/requirements-interface-brep.txt
export APP_INTERFACE_BREP_PYTHON="$PWD/cadworld-adminapi/.venv/bin/python"
```
解析脚本包含在后台 JAR 中,每次分析提取到临时目录并在完成后清理。`APP_INTERFACE_BREP_SCRIPT` 可覆盖为外部脚本路径。默认超时 120 秒、上传及输出限制各 100 MB,可使用 `APP_INTERFACE_BREP_TIMEOUT_SECONDS`、`APP_INTERFACE_BREP_MAX_UPLOAD_BYTES`、`APP_INTERFACE_BREP_MAX_OUTPUT_BYTES` 调整;上传体积还受 Spring multipart 限制。
接口解析仅使用 OCCT 原生 STEP B-Rep。缺少运行库、解析失败、超时及输出过大返回明确错误,不回退到三角网格拟合。
## 验证
```bash
mvn clean verify
cadworld-adminapi/.venv/bin/python -m unittest discover -s cadworld-adminapi/scripts/tests
```
默认 Java 测试使用 Mock/H2 和本地临时资源目录,不连接共享数据库或 MinIO。可选集成测试使用专用可清空的 `cadworld_verification` 数据库,并执行初始化、升级、重复执行及数据保留检查,再将相同的用户/组件/接口/日志/上传用例运行于 MySQL 和 MinIO。
Python 测试包含程序生成的真实 STEP 文件及无效文件解析;另有一个依赖外部原始模型的回归用例,缺少该模型时跳过,不会复制来源项目的业务资源。
准备独立 MySQL(默认 `127.0.0.1:13306`,数据库 `cadworld_verification`,root 空密码)及独立 MinIO(默认 `127.0.0.1:19000`,账号 `cadworld-test`,密码 `cadworld-test-secret`),执行:
```bash
mvn -P integration verify
```
可通过 `-Dcadworld.it.db-url=...`、`-Dcadworld.it.db-user=...`、`-Dcadworld.it.db-password=...`、`-Dcadworld.it.minio-endpoint=...`、`-Dcadworld.it.minio-user=...`、`-Dcadworld.it.minio-password=...` 覆盖测试服务配置。集成测试会重建该专用数据库中的业务表,并拒绝使用其他数据库名称;MinIO 使用专用 `cadworld-verification` bucket。
+79
View File
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-adminapi</artifactId>
<packaging>jar</packaging>
<name>cadworld-adminapi</name>
<dependencies>
<dependency>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld-service</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>scripts</directory>
<targetPath>scripts</targetPath>
<includes>
<include>step_brep_topology.py</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<cadworld.project-root>${maven.multiModuleProjectDirectory}</cadworld.project-root>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
@@ -0,0 +1 @@
cadquery-ocp==7.8.1.1
@@ -0,0 +1,555 @@
#!/usr/bin/env python3
"""Extract auditable STEP B-Rep topology and a display-only triangulation.
The JSON keeps exact OCCT Face/Wire/Edge identities and analytic curve parameters.
Triangle data and sampled edge points are emitted only for Three.js display/picking.
They are never used as the source of saved interface geometry.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import sys
from pathlib import Path
from typing import Any
from OCP.Bnd import Bnd_Box
from OCP.BRep import BRep_Tool
from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Surface
from OCP.BRepBndLib import BRepBndLib
from OCP.BRepGProp import BRepGProp
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.BRepTools import BRepTools, BRepTools_WireExplorer
from OCP.GProp import GProp_GProps
from OCP.GeomAbs import (
GeomAbs_BSplineCurve,
GeomAbs_BSplineSurface,
GeomAbs_BezierCurve,
GeomAbs_BezierSurface,
GeomAbs_Circle,
GeomAbs_Cone,
GeomAbs_Cylinder,
GeomAbs_Ellipse,
GeomAbs_Hyperbola,
GeomAbs_Line,
GeomAbs_OffsetCurve,
GeomAbs_OffsetSurface,
GeomAbs_OtherCurve,
GeomAbs_OtherSurface,
GeomAbs_Parabola,
GeomAbs_Plane,
GeomAbs_Sphere,
GeomAbs_SurfaceOfExtrusion,
GeomAbs_SurfaceOfRevolution,
GeomAbs_Torus,
)
from OCP.IFSelect import IFSelect_RetDone
from OCP.Interface import Interface_Static
from OCP.STEPControl import STEPControl_Reader
from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE, TopAbs_REVERSED
from OCP.TopExp import TopExp
from OCP.TopLoc import TopLoc_Location
from OCP.TopTools import TopTools_IndexedMapOfShape
from OCP.TopoDS import TopoDS
CURVE_TYPES = {
GeomAbs_Line: "line",
GeomAbs_Circle: "circle",
GeomAbs_Ellipse: "ellipse",
GeomAbs_Hyperbola: "hyperbola",
GeomAbs_Parabola: "parabola",
GeomAbs_BezierCurve: "bezier",
GeomAbs_BSplineCurve: "bspline",
GeomAbs_OffsetCurve: "offset",
GeomAbs_OtherCurve: "other",
}
SURFACE_TYPES = {
GeomAbs_Plane: "plane",
GeomAbs_Cylinder: "cylinder",
GeomAbs_Cone: "cone",
GeomAbs_Sphere: "sphere",
GeomAbs_Torus: "torus",
GeomAbs_BezierSurface: "bezier",
GeomAbs_BSplineSurface: "bspline",
GeomAbs_SurfaceOfRevolution: "revolution",
GeomAbs_SurfaceOfExtrusion: "extrusion",
GeomAbs_OffsetSurface: "offset",
GeomAbs_OtherSurface: "other",
}
def xyz(point: Any) -> list[float]:
return [float(point.X()), float(point.Y()), float(point.Z())]
def direction_xyz(direction: Any, reverse: bool = False) -> list[float]:
sign = -1.0 if reverse else 1.0
return [sign * float(direction.X()), sign * float(direction.Y()), sign * float(direction.Z())]
def distance(first: list[float], second: list[float]) -> float:
return math.sqrt(sum((a - b) ** 2 for a, b in zip(first, second)))
def dot(first: list[float], second: list[float]) -> float:
return sum(a * b for a, b in zip(first, second))
def normalized(vector: list[float]) -> list[float]:
length = math.sqrt(dot(vector, vector))
return [value / length for value in vector] if length > 1e-12 else [0.0, 0.0, 0.0]
def cross(first: list[float], second: list[float]) -> list[float]:
return [
first[1] * second[2] - first[2] * second[1],
first[2] * second[0] - first[0] * second[2],
first[0] * second[1] - first[1] * second[0],
]
def solve_three_by_three(matrix: list[list[float]], values: list[float]) -> list[float] | None:
augmented = [row[:] + [value] for row, value in zip(matrix, values)]
for column in range(3):
pivot = max(range(column, 3), key=lambda row: abs(augmented[row][column]))
if abs(augmented[pivot][column]) < 1e-12:
return None
augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
divisor = augmented[column][column]
augmented[column] = [value / divisor for value in augmented[column]]
for row in range(3):
if row == column:
continue
factor = augmented[row][column]
augmented[row] = [
current - factor * pivot_value
for current, pivot_value in zip(augmented[row], augmented[column])
]
return [augmented[row][3] for row in range(3)]
def source_hash(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def shape_diagonal_mm(shape: Any) -> float:
box = Bnd_Box()
BRepBndLib.Add_s(shape, box, True)
if box.IsVoid():
return 100.0
xmin, ymin, zmin, xmax, ymax, zmax = box.Get()
return math.sqrt((xmax - xmin) ** 2 + (ymax - ymin) ** 2 + (zmax - zmin) ** 2)
def sample_curve(curve: BRepAdaptor_Curve, reversed_edge: bool) -> list[list[float]]:
first = float(curve.FirstParameter())
last = float(curve.LastParameter())
curve_type = curve.GetType()
if not math.isfinite(first) or not math.isfinite(last):
return []
if curve_type == GeomAbs_Line:
count = 2
elif curve_type in (GeomAbs_Circle, GeomAbs_Ellipse):
count = max(12, min(64, int(math.ceil(abs(last - first) / (math.pi / 24.0))) + 1))
else:
count = 32
points = [xyz(curve.Value(first + (last - first) * index / (count - 1))) for index in range(count)]
return list(reversed(points)) if reversed_edge else points
def edge_payload(edge: Any, edge_index: int, file_hash: str) -> dict[str, Any]:
curve = BRepAdaptor_Curve(edge)
curve_type = CURVE_TYPES.get(curve.GetType(), "other")
reversed_edge = edge.Orientation() == TopAbs_REVERSED
samples = sample_curve(curve, reversed_edge)
payload: dict[str, Any] = {
"id": f"brep:edge:{edge_index}",
"sourceRef": f"sha256:{file_hash}:edge:{edge_index}",
"curveType": curve_type,
"orientation": "reversed" if reversed_edge else "forward",
"firstParameter": float(curve.FirstParameter()),
"lastParameter": float(curve.LastParameter()),
"startMm": samples[0] if samples else None,
"endMm": samples[-1] if samples else None,
"samplesMm": samples,
"isExact": True,
# Any native STEP edge with a usable sampled trace can define the
# outer wire. Analytic line/circle parameters are preferred when
# available, while B-Spline/Bezier/ellipse edges retain their exact
# sourceRef plus display samples instead of being rejected by type.
"selectableAsBoundary": len(samples) >= 2,
}
if curve_type == "line":
line = curve.Line()
payload["direction"] = direction_xyz(line.Direction(), reversed_edge)
elif curve_type == "circle":
circle = curve.Circle()
payload.update({
"centerMm": xyz(circle.Location()),
"radiusMm": float(circle.Radius()),
"axis": direction_xyz(circle.Axis().Direction()),
"xDirection": direction_xyz(circle.Position().XDirection()),
"isFullCircle": abs(abs(float(curve.LastParameter()) - float(curve.FirstParameter())) - math.tau) <= 1e-6,
})
elif curve_type == "ellipse":
ellipse = curve.Ellipse()
payload.update({
"centerMm": xyz(ellipse.Location()),
"majorRadiusMm": float(ellipse.MajorRadius()),
"minorRadiusMm": float(ellipse.MinorRadius()),
"axis": direction_xyz(ellipse.Axis().Direction()),
})
return payload
def fitted_circular_wire_payload(
edges: list[dict[str, Any]],
face_normal: list[float] | None,
) -> dict[str, Any]:
if face_normal is None:
return {"isCircular": False}
points: list[list[float]] = []
for edge in edges:
for point in edge.get("samplesMm", []):
if not points or distance(points[-1], point) > 1e-8:
points.append(point)
if len(points) < 8:
return {"isCircular": False}
closure_tolerance_mm = 0.01
if distance(points[0], points[-1]) > closure_tolerance_mm:
return {"isCircular": False}
if distance(points[0], points[-1]) <= 1e-8:
points.pop()
normal = normalized(face_normal)
if dot(normal, normal) < 0.99:
return {"isCircular": False}
reference_axes = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
reference = min(reference_axes, key=lambda axis: abs(dot(axis, normal)))
x_axis = normalized(cross(normal, reference))
y_axis = normalized(cross(normal, x_axis))
origin = [sum(point[index] for point in points) / len(points) for index in range(3)]
projected = []
plane_residuals = []
for point in points:
offset = [point[index] - origin[index] for index in range(3)]
projected.append([dot(offset, x_axis), dot(offset, y_axis)])
plane_residuals.append(abs(dot(offset, normal)))
normal_matrix = [[0.0] * 3 for _ in range(3)]
normal_values = [0.0] * 3
for x_value, y_value in projected:
row = [2.0 * x_value, 2.0 * y_value, 1.0]
target = x_value * x_value + y_value * y_value
for row_index in range(3):
normal_values[row_index] += row[row_index] * target
for column_index in range(3):
normal_matrix[row_index][column_index] += row[row_index] * row[column_index]
solution = solve_three_by_three(normal_matrix, normal_values)
if solution is None:
return {"isCircular": False}
center_x, center_y, constant = solution
radius_squared = constant + center_x * center_x + center_y * center_y
if radius_squared <= 1e-12:
return {"isCircular": False}
radius = math.sqrt(radius_squared)
radial_residuals = [
abs(math.hypot(x_value - center_x, y_value - center_y) - radius)
for x_value, y_value in projected
]
max_residual = max(max(radial_residuals), max(plane_residuals))
circularity_tolerance_mm = max(0.005, radius * 0.0005)
if max_residual > circularity_tolerance_mm:
return {
"isCircular": False,
"fitResidualMm": max_residual,
}
radial_vectors = [(x_value - center_x, y_value - center_y) for x_value, y_value in projected]
sweep = 0.0
for index, current in enumerate(radial_vectors):
following = radial_vectors[(index + 1) % len(radial_vectors)]
cross_value = current[0] * following[1] - current[1] * following[0]
dot_value = current[0] * following[0] + current[1] * following[1]
sweep += abs(math.atan2(cross_value, dot_value))
if abs(sweep - math.tau) > 0.05:
return {"isCircular": False, "fitResidualMm": max_residual}
center = [
origin[index] + x_axis[index] * center_x + y_axis[index] * center_y
for index in range(3)
]
return {
"isCircular": True,
"centerMm": center,
"radiusMm": radius,
"axis": normal,
"fitResidualMm": max_residual,
"circularityMethod": "verified-fit",
}
def circular_wire_payload(
edges: list[dict[str, Any]],
face_normal: list[float] | None = None,
) -> dict[str, Any]:
if edges and all(edge["curveType"] == "circle" for edge in edges):
first = edges[0]
center = first.get("centerMm")
radius = first.get("radiusMm")
axis = normalized(first.get("axis", [0.0, 0.0, 0.0]))
if center is not None and radius is not None:
same_circle = all(
distance(center, edge.get("centerMm", [math.inf] * 3)) <= 1e-5
and abs(radius - float(edge.get("radiusMm", math.inf))) <= 1e-6
and abs(dot(axis, normalized(edge.get("axis", [0.0, 0.0, 0.0])))) >= 1.0 - 1e-8
for edge in edges[1:]
)
sweep = sum(abs(float(edge["lastParameter"]) - float(edge["firstParameter"])) for edge in edges)
if same_circle and abs(sweep - math.tau) <= 1e-5:
return {
"isCircular": True,
"centerMm": center,
"radiusMm": radius,
"axis": axis,
"fitResidualMm": 0.0,
"circularityMethod": "analytic",
}
return fitted_circular_wire_payload(edges, face_normal)
def face_triangulation(face: Any) -> dict[str, Any]:
location = TopLoc_Location()
triangulation = BRep_Tool.Triangulation_s(face, location)
if triangulation is None or triangulation.NbTriangles() <= 0:
return {"positionsMm": [], "indices": []}
transformation = location.Transformation()
used_nodes: dict[int, int] = {}
positions: list[float] = []
indices: list[int] = []
reversed_face = face.Orientation() == TopAbs_REVERSED
for triangle_index in range(1, triangulation.NbTriangles() + 1):
nodes = list(triangulation.Triangle(triangle_index).Get())
if reversed_face:
nodes[1], nodes[2] = nodes[2], nodes[1]
for node_index in nodes:
local_index = used_nodes.get(node_index)
if local_index is None:
point = triangulation.Node(node_index).Transformed(transformation)
local_index = len(positions) // 3
used_nodes[node_index] = local_index
positions.extend(xyz(point))
indices.append(local_index)
return {"positionsMm": positions, "indices": indices}
def surface_payload(face: Any) -> tuple[str, dict[str, Any]]:
adaptor = BRepAdaptor_Surface(face, True)
surface_type = SURFACE_TYPES.get(adaptor.GetType(), "other")
reversed_face = face.Orientation() == TopAbs_REVERSED
payload: dict[str, Any] = {"surfaceType": surface_type, "isPlanar": surface_type == "plane"}
if surface_type == "plane":
plane = adaptor.Plane()
payload.update({
"normal": direction_xyz(plane.Axis().Direction(), reversed_face),
"planeLocationMm": xyz(plane.Location()),
"xDirection": direction_xyz(plane.Position().XDirection()),
})
elif surface_type == "cylinder":
cylinder = adaptor.Cylinder()
payload.update({
"axis": direction_xyz(cylinder.Axis().Direction()),
"axisLocationMm": xyz(cylinder.Location()),
"radiusMm": float(cylinder.Radius()),
})
return surface_type, payload
def default_display_deflection_mm(diagonal_mm: float) -> float:
# Triangles are only used to render and pick the exact B-Rep faces. The
# previous 0.05-0.5 mm range produced browser payloads above 100 MB for
# otherwise valid components, without improving the saved interface data.
return max(0.2, min(2.0, diagonal_mm * 0.002))
def maximum_display_deflection_mm(initial_deflection_mm: float) -> float:
# Keep an adaptive escape hatch for highly detailed components. Exact
# Face/Wire/Edge data is unchanged; only the display mesh becomes coarser.
return max(2.0, min(10.0, initial_deflection_mm * 10.0))
def analyze(
input_path: Path,
linear_deflection_override_mm: float | None = None,
simplification_passes: int = 0,
) -> dict[str, Any]:
file_hash = source_hash(input_path)
Interface_Static.SetCVal_s("xstep.cascade.unit", "MM")
reader = STEPControl_Reader()
status = reader.ReadFile(str(input_path))
if status != IFSelect_RetDone:
raise RuntimeError(f"OCCT 无法读取 STEP 文件,状态:{status}")
transferred = reader.TransferRoots()
if transferred <= 0:
raise RuntimeError("STEP 文件没有可转换的根装配或实体。")
shape = reader.OneShape()
if shape.IsNull():
raise RuntimeError("STEP 文件转换后没有有效形状。")
diagonal_mm = shape_diagonal_mm(shape)
linear_deflection_mm = (
linear_deflection_override_mm
if linear_deflection_override_mm is not None
else default_display_deflection_mm(diagonal_mm)
)
BRepMesh_IncrementalMesh(shape, linear_deflection_mm, False, 0.5, True)
face_map = TopTools_IndexedMapOfShape()
edge_map = TopTools_IndexedMapOfShape()
TopExp.MapShapes_s(shape, TopAbs_FACE, face_map)
TopExp.MapShapes_s(shape, TopAbs_EDGE, edge_map)
edge_cache: dict[int, dict[str, Any]] = {}
edge_owners: dict[int, set[int]] = {}
faces: list[dict[str, Any]] = []
for face_index in range(1, face_map.Extent() + 1):
face = TopoDS.Face_s(face_map.FindKey(face_index))
properties = GProp_GProps()
BRepGProp.SurfaceProperties_s(face, properties)
center_of_mass = xyz(properties.CentreOfMass())
surface_type, surface = surface_payload(face)
outer_wire = BRepTools.OuterWire_s(face)
wires: list[dict[str, Any]] = []
wire_explorer = BRepTools_WireExplorer(outer_wire, face) if not outer_wire.IsNull() else None
# Enumerate outer wire first so its role is deterministic, then all inner wires.
ordered_wires: list[Any] = []
if wire_explorer is not None:
ordered_wires.append(outer_wire)
from OCP.TopExp import TopExp_Explorer
from OCP.TopAbs import TopAbs_WIRE
explorer = TopExp_Explorer(face, TopAbs_WIRE)
while explorer.More():
wire = TopoDS.Wire_s(explorer.Current())
if outer_wire.IsNull() or not wire.IsSame(outer_wire):
ordered_wires.append(wire)
explorer.Next()
for wire_index, wire in enumerate(ordered_wires, start=1):
is_outer = not outer_wire.IsNull() and wire.IsSame(outer_wire)
wire_edges: list[dict[str, Any]] = []
edge_explorer = BRepTools_WireExplorer(wire, face)
while edge_explorer.More():
edge = TopoDS.Edge_s(edge_explorer.Current())
edge_index = edge_map.FindIndex(edge)
if edge_index <= 0:
edge_index = edge_map.Add(edge)
if edge_index not in edge_cache:
edge_cache[edge_index] = edge_payload(edge, edge_index, file_hash)
wire_edges.append(dict(edge_cache[edge_index]))
edge_owners.setdefault(edge_index, set()).add(face_index)
edge_explorer.Next()
circular = circular_wire_payload(wire_edges, surface.get("normal"))
wires.append({
"id": f"brep:face:{face_index}:wire:{wire_index}",
"sourceRef": f"sha256:{file_hash}:face:{face_index}:wire:{wire_index}",
"isOuter": is_outer,
"isCircular": circular["isCircular"],
"centerMm": circular.get("centerMm"),
"radiusMm": circular.get("radiusMm"),
"axis": circular.get("axis"),
"fitResidualMm": circular.get("fitResidualMm"),
"circularityMethod": circular.get("circularityMethod"),
"edges": wire_edges,
})
faces.append({
"id": f"brep:face:{face_index}",
"sourceRef": f"sha256:{file_hash}:face:{face_index}",
**surface,
"pointMm": center_of_mass,
"areaMm2": float(properties.Mass()),
"orientation": "reversed" if face.Orientation() == TopAbs_REVERSED else "forward",
"adjacentFaceIds": [],
"triangles": face_triangulation(face),
"wires": wires,
})
adjacent: dict[int, set[int]] = {index: set() for index in range(1, len(faces) + 1)}
for owners in edge_owners.values():
for owner in owners:
adjacent[owner].update(other for other in owners if other != owner)
for face_index, face in enumerate(faces, start=1):
face["adjacentFaceIds"] = [f"brep:face:{index}" for index in sorted(adjacent[face_index])]
return {
"schemaVersion": "interface-step-brep/v1",
"sourceName": input_path.name,
"sourceSha256": file_hash,
"sourceUnits": "mm",
"scaleToMeters": 0.001,
"kernel": "OCCT 7.8",
"triangulationPurpose": "display-and-picking-only",
"linearDeflectionMm": linear_deflection_mm,
"displayMeshSimplificationPasses": simplification_passes,
"faceCount": len(faces),
"edgeCount": edge_map.Extent(),
"faces": faces,
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("input", type=Path)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--max-output-bytes", type=int)
args = parser.parse_args()
if args.input.suffix.lower() not in (".step", ".stp"):
raise ValueError("只支持 .step 或 .stp 文件。")
input_path = args.input.resolve()
result = analyze(input_path)
serialized = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
# If a complex but valid component still exceeds the response budget,
# remesh only the display/picking triangles at a coarser tolerance. The
# authoritative analytic B-Rep metadata and source references stay intact.
simplification_passes = 0
max_deflection_mm = maximum_display_deflection_mm(result["linearDeflectionMm"])
while (
args.max_output_bytes is not None
and len(serialized) > args.max_output_bytes
and simplification_passes < 4
and result["linearDeflectionMm"] < max_deflection_mm
):
simplification_passes += 1
next_deflection_mm = min(max_deflection_mm, result["linearDeflectionMm"] * 2.0)
result = analyze(input_path, next_deflection_mm, simplification_passes)
serialized = json.dumps(result, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_bytes(serialized)
print(json.dumps({
"schemaVersion": result["schemaVersion"],
"faceCount": result["faceCount"],
"edgeCount": result["edgeCount"],
"output": str(args.output),
}, ensure_ascii=False))
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as error:
print(f"STEP_BREP_ERROR: {error}", file=sys.stderr)
raise SystemExit(2)
@@ -0,0 +1,47 @@
"""Exercise the actual OCCT reader and packaged-script CLI with generated STEP files."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox
from OCP.IFSelect import IFSelect_RetDone
from OCP.STEPControl import STEPControl_AsIs, STEPControl_Writer
SCRIPT = Path(__file__).resolve().parents[1] / "step_brep_topology.py"
class RealStepTest(unittest.TestCase):
def test_real_box_has_exact_topology_units_and_hash(self):
with tempfile.TemporaryDirectory() as directory:
source = Path(directory) / "box.step"
output = Path(directory) / "topology.json"
writer = STEPControl_Writer()
writer.Transfer(BRepPrimAPI_MakeBox(10, 20, 30).Shape(), STEPControl_AsIs)
self.assertEqual(writer.Write(str(source)), IFSelect_RetDone)
process = subprocess.run([sys.executable, str(SCRIPT), str(source), "--output", str(output)], capture_output=True, text=True, timeout=30)
self.assertEqual(process.returncode, 0, process.stderr)
result = json.loads(output.read_text())
self.assertEqual(result["faceCount"], 6)
self.assertEqual(result["edgeCount"], 12)
self.assertEqual(result["scaleToMeters"], 0.001)
self.assertEqual(result["sourceSha256"], hashlib.sha256(source.read_bytes()).hexdigest())
self.assertEqual(result["triangulationPurpose"], "display-and-picking-only")
self.assertTrue(all(face["wires"] and face["sourceRef"].startswith("sha256:") for face in result["faces"]))
def test_invalid_step_is_rejected_without_a_topology_file(self):
with tempfile.TemporaryDirectory() as directory:
source = Path(directory) / "invalid.step"
output = Path(directory) / "topology.json"
source.write_text("not a STEP document")
process = subprocess.run([sys.executable, str(SCRIPT), str(source), "--output", str(output)], capture_output=True, text=True, timeout=30)
self.assertNotEqual(process.returncode, 0)
self.assertIn("STEP_BREP_ERROR", process.stderr)
self.assertFalse(output.exists())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,88 @@
from __future__ import annotations
import importlib.util
import math
import unittest
from pathlib import Path
SCRIPT_PATH = Path(__file__).resolve().parents[1] / "step_brep_topology.py"
SPEC = importlib.util.spec_from_file_location("step_brep_topology", SCRIPT_PATH)
if SPEC is None or SPEC.loader is None:
raise RuntimeError(f"无法加载 STEP B-Rep 解析脚本:{SCRIPT_PATH}")
STEP_BREP = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(STEP_BREP)
def sampled_edge(points: list[list[float]]) -> dict[str, object]:
return {
"curveType": "bspline",
"samplesMm": points,
}
class FittedCircularWireTest(unittest.TestCase):
def test_accepts_closed_planar_bspline_circle(self) -> None:
center = [12.5, -3.25, 7.0]
radius = 2.5
points = [
[
center[0] + radius * math.cos(math.tau * index / 64),
center[1] + radius * math.sin(math.tau * index / 64),
center[2],
]
for index in range(65)
]
result = STEP_BREP.circular_wire_payload([sampled_edge(points)], [0.0, 0.0, 1.0])
self.assertTrue(result["isCircular"])
self.assertEqual(result["circularityMethod"], "verified-fit")
self.assertAlmostEqual(result["radiusMm"], radius, places=6)
self.assertLess(result["fitResidualMm"], 1e-6)
def test_rejects_closed_ellipse(self) -> None:
points = [
[4.0 * math.cos(math.tau * index / 64), 2.0 * math.sin(math.tau * index / 64), 0.0]
for index in range(65)
]
result = STEP_BREP.circular_wire_payload([sampled_edge(points)], [0.0, 0.0, 1.0])
self.assertFalse(result["isCircular"])
def test_rejects_open_circular_arc(self) -> None:
points = [
[2.5 * math.cos(math.pi * index / 32), 2.5 * math.sin(math.pi * index / 32), 0.0]
for index in range(33)
]
result = STEP_BREP.circular_wire_payload([sampled_edge(points)], [0.0, 0.0, 1.0])
self.assertFalse(result["isCircular"])
class InterfaceStepRegressionTest(unittest.TestCase):
def test_primary_mounting_face_exposes_nine_bspline_holes(self) -> None:
project_root = Path(__file__).resolve().parents[3]
fixture = project_root / "模型文件" / "step" / (
"未命名-_X2_817090e888c5914d_X0_dm-j10010l_X2_7535673a8f6c5b50_X0_001.step"
)
if not fixture.is_file():
self.skipTest(f"STEP 回归样例不存在:{fixture}")
topology = STEP_BREP.analyze(fixture)
face = next(item for item in topology["faces"] if item["id"] == "brep:face:7")
holes = [wire for wire in face["wires"] if not wire["isOuter"] and wire["isCircular"]]
self.assertEqual(len(holes), 9)
for hole in holes:
self.assertEqual(hole["circularityMethod"], "verified-fit")
self.assertAlmostEqual(hole["radiusMm"], 2.50005, places=4)
self.assertLessEqual(hole["fitResidualMm"], 0.005)
self.assertTrue(hole["sourceRef"].startswith("sha256:"))
self.assertTrue(hole["edges"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,15 @@
package com.linkerbot.cadworld;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@SpringBootApplication
@ConfigurationPropertiesScan("com.linkerbot.cadworld.config")
@MapperScan("com.linkerbot.cadworld.mapper")
public class AdminApiApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApiApplication.class, args);
}
}
@@ -0,0 +1,13 @@
package com.linkerbot.cadworld.audit;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuditOperation {
String module();
String action();
}
@@ -0,0 +1,46 @@
package com.linkerbot.cadworld.audit;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.dto.component.ComponentResponse;
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/** Only reads known identifiers from responses; tokens and request bodies are never retained. */
@RestControllerAdvice
public class AuditResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter parameter, Class<? extends HttpMessageConverter<?>> converter) { return true; }
@Override
public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType type,
Class<? extends HttpMessageConverter<?>> converter, ServerHttpRequest request, ServerHttpResponse response) {
if (request instanceof ServletServerHttpRequest servlet && body instanceof ApiResponse<?> envelope
&& servlet.getServletRequest().getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
Object data = envelope.getData();
String id = switch (data) {
case ComponentResponse component -> String.valueOf(component.id());
case JsonNode json when json.hasNonNull("id") -> json.get("id").asText();
case PrepareCoverImageUploadSessionResponse session -> session.keyPrefix();
case PrepareUrdfUploadSessionResponse session -> session.keyPrefix();
case PrepareObjectUploadUrlResponse upload -> upload.objectKey();
case CompleteCoverImageUploadResponse upload -> upload.coverImageKey();
case CompleteUrdfUploadResponse upload -> upload.source();
case null, default -> null;
};
if (id != null && context.event().getTargetId() == null) context.event().setTargetId(OperationAuditInterceptor.limit(id, 512));
}
return body;
}
}
@@ -0,0 +1,56 @@
package com.linkerbot.cadworld.audit;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
/** Multipart size failures can occur before an MVC interceptor is invoked. */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class EarlyFailureAuditFilter extends OncePerRequestFilter {
private final RequestMappingHandlerMapping mappings;
private final OperationAuditInterceptor audit;
public EarlyFailureAuditFilter(@Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mappings,
OperationAuditInterceptor audit) {
this.mappings = mappings;
this.audit = audit;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
long started = System.nanoTime();
try {
chain.doFilter(request, response);
} finally {
if (response.getStatus() >= 400 && request.getAttribute(OperationAuditInterceptor.CONTEXT) == null
&& request.getRequestURI().startsWith("/admin-api/")) {
try {
// DispatcherServlet clears its parsed path before returning to filters.
org.springframework.web.util.ServletRequestPathUtils.parseAndCache(request);
var handler = mappings.getHandler(request);
if (handler != null) {
audit.preHandle(request, response, handler.getHandler());
if (request.getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
request.setAttribute(OperationAuditInterceptor.CONTEXT, new OperationAuditInterceptor.Context(context.event(), started));
audit.afterCompletion(request, response, handler.getHandler(), null);
}
}
} catch (Exception failure) {
log.error("Failed to resolve early operation failure at {} {}", request.getMethod(), request.getRequestURI(), failure);
}
}
}
}
}
@@ -0,0 +1,75 @@
package com.linkerbot.cadworld.audit;
import com.linkerbot.cadworld.common.api.RequestIdHolder;
import com.linkerbot.cadworld.entity.OperationLog;
import com.linkerbot.cadworld.service.AdminOperatorProvider;
import com.linkerbot.cadworld.service.OperationLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
@Slf4j
@Component
@RequiredArgsConstructor
public class OperationAuditInterceptor implements HandlerInterceptor {
static final String CONTEXT = "cadworld.auditContext";
private final OperationLogService service;
private final AdminOperatorProvider operator;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod method)) return true;
AuditOperation annotation = method.getMethodAnnotation(AuditOperation.class);
if (annotation == null) return true;
OperationLog event = new OperationLog();
event.setModule(annotation.module());
event.setAction(annotation.action());
event.setOperatorId(operator.userId());
event.setOperatorName(operator.name());
event.setRequestPath(limit(request.getRequestURI(), 512));
event.setRequestMethod(request.getMethod());
event.setClientIp(limit(request.getRemoteAddr(), 64));
event.setRequestId(limit(RequestIdHolder.get(), 64));
event.setOperatedAt(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
Object variables = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (variables instanceof Map<?, ?> values && values.get("id") != null) {
event.setTargetId(limit(values.get("id").toString(), 512));
} else if ("UPLOAD".equals(annotation.action())) {
event.setTargetId(limit(request.getParameter("objectKey"), 512));
}
request.setAttribute(CONTEXT, new Context(event, System.nanoTime()));
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
if (!(request.getAttribute(CONTEXT) instanceof Context context)) return;
OperationLog event = context.event();
Object error = request.getAttribute("cadworld.operationError");
boolean success = response.getStatus() < 400 && exception == null && error == null;
event.setSuccess(success);
event.setHttpStatus(response.getStatus());
event.setDurationMs((System.nanoTime() - context.started()) / 1_000_000);
if (!success) event.setErrorSummary(limit(error == null ? "请求失败,HTTP " + response.getStatus() : error.toString(), 1000));
try {
service.record(event);
} catch (Exception failure) {
log.error("Failed to persist operation log. requestId={}, module={}, action={}",
event.getRequestId(), event.getModule(), event.getAction(), failure);
}
}
static String limit(String value, int length) {
return value == null ? null : value.substring(0, Math.min(length, value.length()));
}
record Context(OperationLog event, long started) { }
}
@@ -0,0 +1,16 @@
package com.linkerbot.cadworld.config;
import com.linkerbot.cadworld.audit.OperationAuditInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
private final OperationAuditInterceptor audit;
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(audit).addPathPatterns("/admin-api/**"); }
}
@@ -0,0 +1,75 @@
package com.linkerbot.cadworld.controller;
import com.linkerbot.cadworld.audit.AuditOperation;
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;
@RestController
@RequestMapping("/admin-api/component-assets")
@RequiredArgsConstructor
public class ComponentAssetController {
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
private static final String ASSET_PATH_PREFIX = "/admin-api/component-assets/";
private final ComponentUploadSupport componentUploadSupport;
private final ObjectStorageClient objectStorageClient;
@AuditOperation(module = "COMPONENT", action = "UPLOAD")
@PutMapping("/upload")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void upload(
@RequestParam String objectKey,
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
HttpServletRequest request
) throws IOException {
componentUploadSupport.uploadObject(
operatorProvider.userId(),
objectKey,
contentType,
request.getInputStream(),
request.getContentLengthLong()
);
}
@GetMapping("/**")
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestUri = request.getRequestURI();
int prefixIndex = requestUri.indexOf(ASSET_PATH_PREFIX);
if (prefixIndex < 0) {
response.sendError(HttpStatus.NOT_FOUND.value());
return;
}
String encodedKey = requestUri.substring(prefixIndex + ASSET_PATH_PREFIX.length());
String objectKey = UriUtils.decode(encodedKey, StandardCharsets.UTF_8);
ObjectStorageClient.StoredObject object = objectStorageClient.statObject(objectKey);
response.setStatus(HttpStatus.OK.value());
response.setContentType(object.contentType() == null || object.contentType().isBlank()
? MediaType.APPLICATION_OCTET_STREAM_VALUE
: object.contentType());
if (object.contentLength() >= 0) {
response.setContentLengthLong(object.contentLength());
}
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
objectStorageClient.writeObjectTo(objectKey, response.getOutputStream());
}
}
@@ -0,0 +1,131 @@
package com.linkerbot.cadworld.controller;
import com.linkerbot.cadworld.audit.AuditOperation;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadRequest;
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
import com.linkerbot.cadworld.dto.common.SuccessResponse;
import com.linkerbot.cadworld.dto.component.ComponentListItemResponse;
import com.linkerbot.cadworld.dto.component.ComponentResponse;
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
import com.linkerbot.cadworld.service.ComponentCoverImageUploadService;
import com.linkerbot.cadworld.service.ComponentService;
import com.linkerbot.cadworld.service.ComponentUrdfUploadService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/admin-api/components")
@RequiredArgsConstructor
public class ComponentController {
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
private final ComponentService componentService;
private final ComponentCoverImageUploadService componentCoverImageUploadService;
private final ComponentUrdfUploadService componentUrdfUploadService;
@AuditOperation(module = "COMPONENT", action = "CREATE")
@PostMapping
public ApiResponse<ComponentResponse> create(
@Valid @RequestBody CreateComponentRequest request
) {
return ApiResponse.success(componentService.createComponent(operatorProvider.userId(), request));
}
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD")
@PostMapping("/cover-image-upload-sessions")
public ApiResponse<PrepareCoverImageUploadSessionResponse> prepareCoverImageUploadSession(
) {
return ApiResponse.success(componentCoverImageUploadService.prepareUploadSession(operatorProvider.userId()));
}
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL")
@PostMapping("/cover-image-upload-sessions/upload-url")
public ApiResponse<PrepareObjectUploadUrlResponse> prepareCoverImageObjectUploadUrl(
@Valid @RequestBody PrepareObjectUploadUrlRequest request
) {
return ApiResponse.success(componentCoverImageUploadService.prepareObjectUploadUrl(operatorProvider.userId(), request));
}
@AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD")
@PostMapping("/cover-image-upload-sessions/complete")
public ApiResponse<CompleteCoverImageUploadResponse> completeCoverImageUploadSession(
@Valid @RequestBody CompleteCoverImageUploadRequest request
) {
return ApiResponse.success(componentCoverImageUploadService.completeUploadSession(operatorProvider.userId(), request));
}
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD")
@PostMapping("/urdf-upload-sessions")
public ApiResponse<PrepareUrdfUploadSessionResponse> prepareUrdfUploadSession(
) {
return ApiResponse.success(componentUrdfUploadService.prepareUploadSession(operatorProvider.userId()));
}
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL")
@PostMapping("/urdf-upload-sessions/upload-url")
public ApiResponse<PrepareObjectUploadUrlResponse> prepareUrdfObjectUploadUrl(
@Valid @RequestBody PrepareObjectUploadUrlRequest request
) {
return ApiResponse.success(componentUrdfUploadService.prepareObjectUploadUrl(operatorProvider.userId(), request));
}
@AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD")
@PostMapping("/urdf-upload-sessions/complete")
public ApiResponse<CompleteUrdfUploadResponse> completeUrdfUploadSession(
@Valid @RequestBody CompleteUrdfUploadRequest request
) {
return ApiResponse.success(componentUrdfUploadService.completeUploadSession(operatorProvider.userId(), request));
}
@GetMapping
public ApiResponse<PageResponse<ComponentListItemResponse>> list(
@RequestParam(defaultValue = "1") long page,
@RequestParam(defaultValue = "20") long size,
@RequestParam(required = false) String keyword
) {
return ApiResponse.success(componentService.listComponents(page, Math.min(size, 100), keyword));
}
@GetMapping("/{id}")
public ApiResponse<ComponentResponse> detail(@PathVariable Long id) {
return ApiResponse.success(componentService.getComponent(id));
}
@AuditOperation(module = "COMPONENT", action = "UPDATE")
@PutMapping("/{id}")
public ApiResponse<ComponentResponse> update(
@PathVariable Long id,
@Valid @RequestBody UpdateComponentRequest request
) {
return ApiResponse.success(componentService.updateComponent(operatorProvider.userId(), id, request));
}
@AuditOperation(module = "COMPONENT", action = "DELETE")
@DeleteMapping("/{id}")
public ApiResponse<SuccessResponse> delete(
@PathVariable Long id
) {
componentService.deleteComponent(operatorProvider.userId(), id);
return ApiResponse.success(SuccessResponse.ok());
}
}
@@ -0,0 +1,24 @@
package com.linkerbot.cadworld.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.service.InterfaceBrepService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/admin-api/interface-brep")
@RequiredArgsConstructor
public class InterfaceBrepController {
private final InterfaceBrepService service;
@PostMapping(value = "/analyze", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ApiResponse<JsonNode> analyze(@RequestPart("file") MultipartFile file) {
return ApiResponse.success(service.analyze(file));
}
}
@@ -0,0 +1,58 @@
package com.linkerbot.cadworld.controller;
import com.linkerbot.cadworld.audit.AuditOperation;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.dto.common.SuccessResponse;
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/admin-api/interfaces")
@RequiredArgsConstructor
public class InterfaceDefinitionController {
private final InterfaceDefinitionService service;
private final ObjectStorageClient objectStorageClient;
@GetMapping public ApiResponse<List<JsonNode>> list(@RequestParam(required = false) String keyword) { return ApiResponse.success(service.list(keyword)); }
@GetMapping("/{id}") public ApiResponse<JsonNode> get(@PathVariable String id) { return ApiResponse.success(service.get(id)); }
@AuditOperation(module = "INTERFACE", action = "CREATE")
@PostMapping public ApiResponse<JsonNode> create(@RequestBody JsonNode request) { return ApiResponse.success(service.create(request)); }
@AuditOperation(module = "INTERFACE", action = "UPDATE")
@PutMapping("/{id}") public ApiResponse<JsonNode> update(@PathVariable String id, @RequestBody JsonNode request) { return ApiResponse.success(service.update(id, request)); }
@AuditOperation(module = "INTERFACE", action = "DELETE")
@DeleteMapping("/{id}") public ApiResponse<SuccessResponse> delete(@PathVariable String id) { service.delete(id); return ApiResponse.success(SuccessResponse.ok()); }
@AuditOperation(module = "INTERFACE", action = "UPLOAD")
@PostMapping("/{id}/assets")
public ApiResponse<String> uploadAsset(@PathVariable String id,
@RequestParam int geometryRevision,
@RequestPart("file") MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) throw new IllegalArgumentException("接口源文件不能为空");
String name = file.getOriginalFilename() == null ? "source.step" : file.getOriginalFilename().replace('\\', '/');
name = name.substring(name.lastIndexOf('/') + 1).replaceAll("[^A-Za-z0-9._-]", "_");
if(service.get(id).path("geometryRevision").asInt()!=geometryRevision)throw new IllegalArgumentException("接口已修订,请刷新");
String key;
{
try {
byte[] bytes = file.getBytes();
String hash = java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
key = "interfaces/" + java.util.HexFormat.of().formatHex(id.getBytes(java.nio.charset.StandardCharsets.UTF_8)) + "/" + geometryRevision + "/" + hash + "/" + name;
objectStorageClient.putObject(key, file.getContentType(), new java.io.ByteArrayInputStream(bytes), bytes.length);
service.attachAsset(id, geometryRevision, key, "sha256:" + hash);
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 不可用", exception);
}
}
return ApiResponse.success(key);
}
}
@@ -0,0 +1,56 @@
package com.linkerbot.cadworld.controller;
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController @RequiredArgsConstructor
@RequestMapping("/admin-api/interfaces/{id}")
public class InterfacePoseController {
private final InterfaceDefinitionService definitions;
private final MechanicalInterfaceSolver solver;
private final ObjectMapper objectMapper;
@PostMapping("/pose-candidates")
public ApiResponse<CandidateSet> candidates(@PathVariable String id,@RequestBody JsonNode body){
PoseRequest request=read(body,PoseRequest.class);
return ApiResponse.success(solver.enumeratePortPoses(definitions.geometryDefinition(id,request.definitionRevision()),request));
}
@PostMapping("/confirm-port")
public ApiResponse<Port> confirm(@PathVariable String id,@RequestBody JsonNode body){
Port request=read(body,Port.class);
if(!id.equals(request.definitionId()))throw new IllegalArgumentException("URL 与端口定义不一致");
return ApiResponse.success(solver.confirmPortPose(definitions.geometryDefinition(id,request.definitionRevision()),request));
}
private <T> T read(JsonNode body,Class<T> type){
try{return objectMapper.readerFor(type).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(normalizePortBody(body));}
catch(java.io.IOException | IllegalArgumentException e){throw new IllegalArgumentException("不支持的接口数据结构:"+rootMessage(e),e);}
}
private JsonNode normalizePortBody(JsonNode body){
if(body==null||!body.isObject())return body;
ObjectNode copy=body.deepCopy();JsonNode targets=copy.get("connectableTargets");
if(targets!=null&&!targets.isNull()){
ArrayNode normalized=objectMapper.createArrayNode();flattenTargets(targets,normalized);copy.set("connectableTargets",normalized);
}
return copy;
}
private void flattenTargets(JsonNode node,ArrayNode output){
if(node==null||node.isNull())return;
if(node.isArray()){
boolean path=true;StringBuilder joined=new StringBuilder();
for(JsonNode child:node){if(!child.isTextual()){path=false;break;}if(joined.length()>0)joined.append('/');joined.append(child.asText());}
if(path){String value=joined.toString().trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);return;}
node.forEach(child->flattenTargets(child,output));return;
}
String value=node.asText("").trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);
}
private boolean containsTarget(ArrayNode output,String value){for(JsonNode item:output)if(value.equals(item.asText()))return true;return false;}
private String rootMessage(Throwable error){Throwable current=error;while(current.getCause()!=null)current=current.getCause();return current.getMessage()==null?"字段格式错误":current.getMessage();}
}
@@ -0,0 +1,36 @@
package com.linkerbot.cadworld.controller;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.entity.OperationLog;
import com.linkerbot.cadworld.service.OperationLogService;
import jakarta.validation.constraints.Min;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/admin-api/operation-logs")
@RequiredArgsConstructor
@Validated
public class OperationLogController {
private final OperationLogService service;
@GetMapping
public ApiResponse<PageResponse<OperationLog>> list(
@RequestParam(defaultValue = "1") @Min(1) long page,
@RequestParam(defaultValue = "20") @Min(1) long size,
@RequestParam(required = false) String module,
@RequestParam(required = false) String action,
@RequestParam(required = false) Boolean success,
@RequestParam(required = false) Long operatorId,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime from,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime to) {
return ApiResponse.success(service.list(page, Math.min(size, 100), module, action, success, operatorId, from, to));
}
@GetMapping("/{id}")
public ApiResponse<OperationLog> get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); }
}
@@ -0,0 +1,48 @@
package com.linkerbot.cadworld.controller;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.dto.common.SuccessResponse;
import com.linkerbot.cadworld.dto.user.SaveUserRequest;
import com.linkerbot.cadworld.dto.user.UserResponse;
import com.linkerbot.cadworld.enums.UserStatus;
import com.linkerbot.cadworld.enums.UserType;
import com.linkerbot.cadworld.service.UserManagementService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/admin-api/users")
@RequiredArgsConstructor
@Validated
public class UserManagementController {
private final UserManagementService service;
@GetMapping
public ApiResponse<PageResponse<UserResponse>> list(
@RequestParam(defaultValue = "1") @Min(1) long page,
@RequestParam(defaultValue = "20") @Min(1) long size,
@RequestParam(required = false) String keyword,
@RequestParam(required = false) UserType userType,
@RequestParam(required = false) UserStatus status) {
return ApiResponse.success(service.list(page, Math.min(size, 100), keyword, userType, status));
}
@GetMapping("/{id}")
public ApiResponse<UserResponse> get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); }
@PostMapping
public ApiResponse<UserResponse> create(@Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.create(request)); }
@PutMapping("/{id}")
public ApiResponse<UserResponse> update(@PathVariable Long id, @Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.update(id, request)); }
@DeleteMapping("/{id}")
public ApiResponse<SuccessResponse> delete(@PathVariable Long id) {
service.delete(id);
return ApiResponse.success(SuccessResponse.ok());
}
}
@@ -0,0 +1,14 @@
spring:
datasource:
url: ${APP_DB_URL}
username: ${APP_DB_USERNAME}
password: ${APP_DB_PASSWORD}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: false
@@ -0,0 +1,21 @@
spring:
datasource:
url: ${APP_DB_URL:jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai}
username: ${APP_DB_USERNAME:}
password: ${APP_DB_PASSWORD:}
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
pool-name: CadworldAdminHikariCP
minimum-idle: 1
maximum-pool-size: 10
connection-timeout: 5000
springdoc:
api-docs:
enabled: true
swagger-ui:
enabled: true
logging:
level:
com.linkerbot.cadworld: DEBUG
@@ -0,0 +1,71 @@
spring:
application:
name: cadworld-adminapi
profiles:
default: test
sql:
init:
mode: never
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
jackson:
default-property-inclusion: non_null
time-zone: Asia/Shanghai
lifecycle:
timeout-per-shutdown-phase: 30s
server:
port: ${SERVER_PORT:8992}
shutdown: graceful
compression:
enabled: true
min-response-size: 2KB
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
springdoc:
api-docs:
path: /api-docs
swagger-ui:
path: /swagger-ui.html
app:
admin:
operator:
id: ${APP_ADMIN_OPERATOR_ID:0}
name: ${APP_ADMIN_OPERATOR_NAME:TEST_OPERATOR}
upload-session:
issuer: cadworld-upload
# Empty means a random, process-local signing key. Set a stable key for restarts/multiple instances.
secret: ${APP_UPLOAD_SESSION_SECRET:}
storage:
provider: ${APP_STORAGE_PROVIDER:minio}
urdf-prefix: components/urdf
cover-image-prefix: components/cover-images
public-api-base-url: ${APP_STORAGE_PUBLIC_API_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}}
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}/admin-api/component-assets}
local-root: ${APP_STORAGE_LOCAL_ROOT:./data/assets}
upload-session-ttl: PT30M
minio:
endpoint: ${APP_MINIO_ENDPOINT:}
access-key: ${APP_MINIO_ACCESS_KEY:}
secret-key: ${APP_MINIO_SECRET_KEY:}
bucket: ${APP_MINIO_BUCKET:}
interface-brep:
python: ${APP_INTERFACE_BREP_PYTHON:python3}
script: ${APP_INTERFACE_BREP_SCRIPT:classpath:scripts/step_brep_topology.py}
timeout-seconds: ${APP_INTERFACE_BREP_TIMEOUT_SECONDS:120}
max-upload-bytes: ${APP_INTERFACE_BREP_MAX_UPLOAD_BYTES:104857600}
max-output-bytes: ${APP_INTERFACE_BREP_MAX_OUTPUT_BYTES:104857600}
logging:
file:
path: ${LOG_PATH:logs}
level:
root: INFO
com.linkerbot.cadworld: INFO
org.springframework.web: INFO
@@ -0,0 +1,183 @@
package com.linkerbot.cadworld;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.cadworld.entity.OperationLog;
import com.linkerbot.cadworld.service.OperationLogService;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import 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.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.support.TransactionTemplate;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:admin;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
"app.storage.provider=local", "app.storage.local-root=target/test-assets", "logging.file.path=target/test-logs"
})
@ActiveProfiles("verification")
@AutoConfigureMockMvc
class AdminApiTest {
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired OperationLogService logs;
@Autowired TransactionTemplate transactions;
@BeforeEach
void clean() {
for (String table : new String[]{"component_asset", "component", "interface_definition_revision", "interface_definition_v2", "sys_user", "sys_operation_log"}) {
jdbc.update("DELETE FROM " + table);
}
}
@Test
void userCrudFiltersAndLogicalDeletionKeepPhoneReserved() throws Exception {
JsonNode created = send("/admin-api/users", Map.of("phone", "13812345678", "nickname", "测试用户"));
long id = created.path("data").path("id").asLong();
assertThat(created.path("data").path("status").asText()).isEqualTo("ACTIVE");
assertThat(created.path("data").path("userType").asText()).isEqualTo("NORMAL");
mvc.perform(put("/admin-api/users/{id}", id).contentType(MediaType.APPLICATION_JSON)
.content("{\"phone\":\"13812345678\",\"nickname\":\"管理员\",\"status\":\"DISABLED\",\"userType\":\"ADMIN\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.userType").value("ADMIN"));
mvc.perform(get("/admin-api/users").param("keyword", "管理员").param("userType", "ADMIN").param("status", "DISABLED"))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(1));
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isOk());
mvc.perform(delete("/admin-api/users/{id}", id)).andExpect(status().isOk());
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isNotFound());
mvc.perform(get("/admin-api/users")).andExpect(jsonPath("$.data.total").value(0));
assertThat(jdbc.queryForObject("SELECT deleted FROM sys_user WHERE id=?", Integer.class, id)).isEqualTo(1);
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON)
.content("{\"phone\":\"13812345678\",\"nickname\":\"新用户\"}"))
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("USER_PHONE_DUPLICATE"));
assertThat(logCount()).isZero();
}
@Test
void invalidUserFieldsEnumsAndPaginationAreRejected() throws Exception {
for (String body : new String[]{
"{\"phone\":\"123\",\"nickname\":\"x\"}",
"{\"phone\":\"13812345678\",\"nickname\":\" \"}",
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"status\":\"INVALID\"}",
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"userType\":\"ROOT\"}"}) {
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isUnprocessableEntity());
}
mvc.perform(get("/admin-api/users").param("page", "0")).andExpect(status().isUnprocessableEntity());
mvc.perform(get("/admin-api/users").param("size", "0")).andExpect(status().isUnprocessableEntity());
}
@Test
void componentCrudAndEveryFailureAreAuditedButReadsAreExcluded() throws Exception {
JsonNode result = send("/admin-api/components", component("sample"));
long id = result.path("data").path("id").asLong();
assertThat(result.path("data").path("sourceUrl").asText()).contains("/admin-api/component-assets/");
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(component("renamed"))))
.andExpect(status().isOk());
mvc.perform(get("/admin-api/components")).andExpect(status().isOk());
mvc.perform(get("/admin-api/components/{id}", id)).andExpect(status().isOk());
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isOk());
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isNotFound());
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isUnprocessableEntity());
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{invalid"))
.andExpect(status().isUnprocessableEntity());
assertThat(logCount()).isEqualTo(6);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE success=FALSE", Long.class)).isEqualTo(3);
mvc.perform(get("/admin-api/operation-logs").param("module", "COMPONENT").param("success", "false").param("operatorId", "0"))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(3));
Long logId = jdbc.queryForObject("SELECT MIN(id) FROM sys_operation_log", Long.class);
mvc.perform(get("/admin-api/operation-logs/{id}", logId)).andExpect(status().isOk()).andExpect(jsonPath("$.data.operatorName").value("TEST_OPERATOR"));
assertThat(logCount()).isEqualTo(6);
}
@Test
void interfaceRevisionsAndRejectedStaleEditsAreAudited() throws Exception {
JsonNode request = json.readTree("""
{"id":"mount","name":"安装接口","geometry":{"plane":{"pointM":[0,0,0],"outwardNormal":[0,0,1]},
"holes":[{"id":"a","pointOnPlaneM":[-0.02,0,0],"axis":[0,0,1],"diameterM":0.004},
{"id":"b","pointOnPlaneM":[0.02,0,0],"axis":[0,0,1],"diameterM":0.004}]},
"tolerances":{"positionM":0.0002,"axisAngleRad":0.0174533,"planeAngleRad":0.0174533}}
""");
JsonNode created = send("/admin-api/interfaces", request).path("data");
((com.fasterxml.jackson.databind.node.ObjectNode) created).put("name", "新版");
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
.andExpect(status().isOk()).andExpect(jsonPath("$.data.geometryRevision").value(2));
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
.andExpect(status().isUnprocessableEntity());
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM interface_definition_revision", Long.class)).isEqualTo(2);
mvc.perform(get("/admin-api/interfaces")).andExpect(status().isOk());
mvc.perform(delete("/admin-api/interfaces/mount")).andExpect(status().isOk());
assertThat(logCount()).isEqualTo(4);
// Historical revisions survive deletion and still prohibit ID reuse.
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(request.toString()))
.andExpect(status().isUnprocessableEntity());
}
@Test
void uploadWorkflowUsesAdminUrlsAndDoesNotStoreToken() throws Exception {
JsonNode session = send("/admin-api/components/cover-image-upload-sessions", null).path("data");
String token = session.path("uploadSessionToken").asText();
JsonNode upload = send("/admin-api/components/cover-image-upload-sessions/upload-url",
Map.of("uploadSessionToken", token, "objectPath", "cover.png", "contentType", "image/png")).path("data");
assertThat(upload.path("uploadUrl").asText()).contains("/admin-api/component-assets/upload");
String key = upload.path("objectKey").asText();
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key).contentType("image/png").content(new byte[]{1, 2, 3}))
.andExpect(status().isNoContent());
send("/admin-api/components/cover-image-upload-sessions/complete", Map.of("uploadSessionToken", token, "objectKeys", new String[]{key}));
mvc.perform(get("/admin-api/component-assets/" + key)).andExpect(status().isOk()).andExpect(content().bytes(new byte[]{1, 2, 3}));
assertThat(logCount()).isEqualTo(4);
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString()).doesNotContain(token);
}
@Test
void requiresNewLogSurvivesOuterRollbackAndOldRoutesAreAbsent() throws Exception {
transactions.executeWithoutResult(tx -> {
jdbc.update("INSERT INTO sys_user(phone,nickname,status,user_type,deleted) VALUES ('13912345678','rollback','ACTIVE','NORMAL',0)");
OperationLog event = new OperationLog();
event.setModule("COMPONENT"); event.setAction("CREATE"); event.setOperatorId(0L); event.setOperatorName("TEST_OPERATOR");
event.setRequestPath("/admin-api/components"); event.setRequestMethod("POST"); event.setOperatedAt(java.time.LocalDateTime.now());
event.setDurationMs(1L); event.setSuccess(false); event.setHttpStatus(422);
logs.record(event);
tx.setRollbackOnly();
});
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isZero();
assertThat(logCount()).isEqualTo(1);
for (String path : new String[]{"/api/interfaces", "/api/components", "/api/component-assets/a", "/api/auth/me", "/api/projects"}) {
mvc.perform(get(path)).andExpect(status().isNotFound());
}
}
@Test
void analysisAndPoseCalculationsAreExcludedFromAudit() throws Exception {
mvc.perform(multipart("/admin-api/interface-brep/analyze")
.file(new org.springframework.mock.web.MockMultipartFile("file", "bad.stl", "application/octet-stream", new byte[]{1})))
.andExpect(status().isUnprocessableEntity());
mvc.perform(post("/admin-api/interfaces/missing/pose-candidates").contentType(MediaType.APPLICATION_JSON).content("{}"))
.andExpect(status().isUnprocessableEntity());
assertThat(logCount()).isZero();
}
private JsonNode send(String path, Object body) throws Exception {
var request = post(path);
if (body != null) request.contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(body));
return json.readTree(mvc.perform(request).andExpect(status().isOk()).andReturn().getResponse().getContentAsString());
}
private Map<String, Object> component(String name) {
return Map.of("componentName", name, "robotType", "humanoid", "company", "test", "model", "m1", "source", "components/sample.rfs",
"componentJson", Map.of("interfaces", new Object[0]), "assemblyMetadata", Map.of("tags", new String[]{"test"}, "capabilities", new Object[0], "dimensions", Map.of()));
}
private long logCount() { return jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log", Long.class); }
}
@@ -0,0 +1,51 @@
package com.linkerbot.cadworld;
import java.nio.file.Path;
import java.sql.DriverManager;
import org.junit.jupiter.api.BeforeAll;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import static org.assertj.core.api.Assertions.*;
/** Opt-in integration profile: dedicated disposable MySQL schema and MinIO bucket only. */
@SpringBootTest(properties = {
"spring.datasource.url=${cadworld.it.db-url:jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai}",
"spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver",
"spring.datasource.username=${cadworld.it.db-user:root}", "spring.datasource.password=${cadworld.it.db-password:}",
"spring.sql.init.mode=never", "app.storage.provider=minio",
"app.minio.endpoint=${cadworld.it.minio-endpoint:http://127.0.0.1:19000}",
"app.minio.access-key=${cadworld.it.minio-user:cadworld-test}", "app.minio.secret-key=${cadworld.it.minio-password:cadworld-test-secret}",
"app.minio.bucket=cadworld-verification", "logging.file.path=target/integration-logs"
})
class ExternalServicesIT extends AdminApiTest {
@BeforeAll
static void prepareAndVerifySql() throws Exception {
String url = System.getProperty("cadworld.it.db-url", "jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai");
// Refuse accidental execution against the shared cadworld database.
if (!url.matches("jdbc:mysql://[^/]+/cadworld_verification(?:\\?.*)?")) {
throw new IllegalArgumentException("Integration database must be named cadworld_verification");
}
Path db = Path.of(System.getProperty("cadworld.project-root", "..")).resolve("db");
try (var connection = DriverManager.getConnection(url, System.getProperty("cadworld.it.db-user", "root"), System.getProperty("cadworld.it.db-password", ""));
var statement = connection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS component_asset, component, interface_definition_revision, interface_definition_v2, sys_operation_log, sys_user");
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
statement.executeUpdate("INSERT INTO sys_user(phone,nickname,status,user_type) VALUES ('13800000000','sentinel','ACTIVE','NORMAL')");
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
}
// Simulate precisely the supplied pre-upgrade tables while retaining a real user row.
statement.execute("DROP TABLE component_asset, interface_definition_revision, interface_definition_v2, sys_operation_log");
statement.execute("ALTER TABLE sys_user DROP COLUMN deleted");
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
}
}
}
}
@@ -0,0 +1,43 @@
package com.linkerbot.cadworld;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.util.LinkedMultiValueMap;
import static org.assertj.core.api.Assertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"spring.datasource.url=jdbc:h2:mem:upload-http;MODE=MySQL;DB_CLOSE_DELAY=-1",
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
"spring.servlet.multipart.max-file-size=1KB", "spring.servlet.multipart.max-request-size=2KB",
"app.storage.provider=local", "app.storage.local-root=target/test-http-assets", "logging.file.path=target/test-logs"
})
@ActiveProfiles("verification")
class UploadHttpTest {
@Autowired TestRestTemplate http;
@Autowired JdbcTemplate jdbc;
@Test
void realServletMultipartSizeFailureReturns413AndPersistsAudit() {
var body = new LinkedMultiValueMap<String, Object>();
body.add("file", new ByteArrayResource(new byte[4096]) {
@Override public String getFilename() { return "oversize.step"; }
});
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
var response = http.postForEntity("/admin-api/interfaces/missing/assets?geometryRevision=1", new HttpEntity<>(body, headers), String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND http_status=413 AND success=FALSE AND target_id='missing'", Long.class))
.isEqualTo(1);
}
}
@@ -0,0 +1,48 @@
package com.linkerbot.cadworld.audit;
import com.linkerbot.cadworld.config.AdminOperatorProperties;
import com.linkerbot.cadworld.service.AdminOperatorProvider;
import com.linkerbot.cadworld.service.OperationLogService;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
class OperationAuditInterceptorTest {
@Test
void multipartFailureBeforeMvcIsAuditedOnce() throws Exception {
OperationLogService service = mock(OperationLogService.class);
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, new AdminOperatorProvider(new AdminOperatorProperties(0, "TEST_OPERATOR")));
var mappings = mock(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.class);
var request = new MockHttpServletRequest("POST", "/admin-api/components");
var response = new MockHttpServletResponse();
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
when(mappings.getHandler(request)).thenReturn(new org.springframework.web.servlet.HandlerExecutionChain(handler));
var filter = new EarlyFailureAuditFilter(mappings, audit);
filter.doFilter(request, response, (req, res) -> ((jakarta.servlet.http.HttpServletResponse) res).setStatus(413));
var captured = org.mockito.ArgumentCaptor.forClass(com.linkerbot.cadworld.entity.OperationLog.class);
verify(service).record(captured.capture());
assertThat(captured.getValue().getSuccess()).isFalse();
assertThat(captured.getValue().getHttpStatus()).isEqualTo(413);
}
@Test
void logFailureDoesNotChangeTheBusinessResponse() throws Exception {
OperationLogService service = mock(OperationLogService.class);
doThrow(new IllegalStateException("database unavailable")).when(service).record(any());
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, new AdminOperatorProvider(new AdminOperatorProperties(0, "TEST_OPERATOR")));
var request = new MockHttpServletRequest("POST", "/admin-api/components");
var response = new MockHttpServletResponse();
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
audit.preHandle(request, response, handler);
audit.afterCompletion(request, response, handler, null);
verify(service).record(any());
assertThat(response.getStatus()).isEqualTo(200);
}
@AuditOperation(module = "COMPONENT", action = "CREATE")
void operation() { }
}
@@ -0,0 +1,74 @@
package com.linkerbot.cadworld.mechanicalinterface;
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.cadworld.controller.InterfacePoseController;
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.List;
import org.junit.jupiter.api.Test;
class InterfaceBoundaryTest {
final ObjectMapper mapper=new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
final MechanicalInterfaceSolver solver=new MechanicalInterfaceSolver();
final MountGeometry geometry=new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),List.of(
new Hole("a",new double[]{-.02,0,0},new double[]{0,0,1},.004),
new Hole("b",new double[]{.02,0,0},new double[]{0,0,1},.004)));
final Definition definition=new Definition("two",1,"two",geometry,Tolerances.defaults());
@Test void endpointsRejectUnknownRotationEvenWhenGlobalJacksonIgnoresUnknownFields(){
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
InterfacePoseController controller=new InterfacePoseController(definitions,solver,mapper);
ObjectNode request=mapper.valueToTree(new PoseRequest(1,"base",geometry,"sha"));
request.put("mountRotationRpy",0);
assertThatThrownBy(()->controller.candidates("two",request)).hasMessageContaining("不支持");
verifyNoInteractions(definitions);
}
@Test void confirmationRecomputesTransformAndMappingFromCandidateId(){
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
Port submitted=new Port("port","base","two",1,geometry,
new SelectedPose(chosen.id(),new RigidPose(new double[]{99,99,99},new double[4]),List.of(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION);
Port confirmed=solver.confirmPortPose(definition,submitted);
assertThat(confirmed.selectedPose().templateInLink().positionM()).containsExactly(chosen.templateInLink().positionM());
assertThat(confirmed.selectedPose().holeMapping()).isEqualTo(chosen.holeMapping());
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
assertThatThrownBy(()->new InterfacePoseController(definitions,solver,mapper).confirm("another",mapper.valueToTree(submitted)))
.hasMessageContaining("不一致");
}
@Test void confirmFlattensCascaderPathTargetsBeforeStrictPortBinding(){
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
ObjectNode request=mapper.valueToTree(new Port("port","base","two",1,geometry,
new SelectedPose(chosen.id(),chosen.templateInLink(),chosen.holeMapping(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION,
List.of("humanoid/left_arm")));
request.set("connectableTargets",mapper.createArrayNode().add(mapper.createArrayNode().add("humanoid").add("left_arm")));
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
when(definitions.geometryDefinition("two",1)).thenReturn(definition);
Port confirmed=new InterfacePoseController(definitions,solver,mapper).confirm("two",request).getData();
assertThat(confirmed.connectableTargets()).containsExactly("humanoid/left_arm");
}
@Test void storedBytesAreVerifiedAndUnsafeStorageKeysNeverFetched() throws Exception {
byte[] bytes="real mesh bytes".getBytes(StandardCharsets.UTF_8);
String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
ObjectStorageClient storage=mock(ObjectStorageClient.class);
doAnswer(invocation->{invocation.<OutputStream>getArgument(1).write(bytes);return null;}).when(storage).writeObjectTo(eq("objects/mesh"),any());
UrdfAssetVerifier verifier=new UrdfAssetVerifier(storage);
ObjectNode source=mapper.createObjectNode();source.putArray("resources").addObject().put("reference","a.stl").put("sourceKey","objects/mesh").put("sha256",hash);
verifier.verify(source);
((ObjectNode)source.path("resources").get(0)).put("sha256","tampered");
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("已变化");
clearInvocations(storage);
for(String key:List.of("https://remote.test/a","/etc/passwd","objects/../secret","objects\\secret")) {
((ObjectNode)source.path("resources").get(0)).put("sourceKey",key);
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("存储对象");
}
verifyNoInteractions(storage);
}
}
@@ -0,0 +1,97 @@
-- Run against a selected empty cadworld database. No database is created or selected here.
CREATE TABLE IF NOT EXISTS `sys_user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`phone` varchar(32) NOT NULL,
`nickname` varchar(64) NOT NULL,
`status` varchar(32) NOT NULL DEFAULT 'ACTIVE',
`deleted` tinyint NOT NULL DEFAULT 0,
`user_type` varchar(32) NOT NULL DEFAULT 'NORMAL',
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`),
UNIQUE KEY `uk_sys_user_phone` (`phone`)
);
CREATE TABLE IF NOT EXISTS `component` (
`id` bigint NOT NULL AUTO_INCREMENT,
`component_name` varchar(64) NOT NULL DEFAULT '',
`category` varchar(64) NOT NULL,
`robot_type` varchar(32) NOT NULL DEFAULT 'humanoid',
`company` varchar(64) NOT NULL DEFAULT '',
`model` varchar(64) NOT NULL DEFAULT '',
`source` varchar(255) NOT NULL DEFAULT '',
`cover_image_key` varchar(512) NOT NULL DEFAULT '',
`description` text NOT NULL,
`component_json` LONGTEXT NOT NULL,
`assembly_metadata` LONGTEXT NOT NULL,
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`),
KEY `idx_component_type_company` (`category`,`company`),
KEY `idx_component_type_model` (`category`,`model`),
KEY `idx_component_robot_type_component_type` (`robot_type`,`category`)
);
CREATE TABLE IF NOT EXISTS interface_definition_v2 (
id VARCHAR(64) NOT NULL PRIMARY KEY,
name VARCHAR(128) NOT NULL,
description VARCHAR(500) NULL,
geometry_revision INT NOT NULL,
geometry_json LONGTEXT NOT NULL,
tolerances_json LONGTEXT NOT NULL,
connectable_targets_json LONGTEXT NULL,
display_forward_json LONGTEXT NULL,
source_asset_key VARCHAR(512) NULL,
source_geometry_hash VARCHAR(128) NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
);
CREATE TABLE IF NOT EXISTS interface_definition_revision (
id VARCHAR(96) NOT NULL PRIMARY KEY,
definition_id VARCHAR(64) NOT NULL,
geometry_revision INT NOT NULL,
definition_json LONGTEXT NOT NULL,
UNIQUE KEY uk_interface_geometry_revision (definition_id, geometry_revision)
);
CREATE TABLE IF NOT EXISTS component_asset (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
component_id BIGINT NOT NULL,
object_key VARCHAR(512) NOT NULL,
relative_path VARCHAR(512) NOT NULL,
asset_kind VARCHAR(32) NOT NULL,
content_type VARCHAR(128) NULL,
size BIGINT NOT NULL DEFAULT 0,
sha256 VARCHAR(128) NULL,
is_primary TINYINT NOT NULL DEFAULT 0,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
CONSTRAINT fk_component_asset_component FOREIGN KEY (component_id) REFERENCES component(id) ON DELETE CASCADE,
UNIQUE KEY uk_component_asset_object_key (object_key),
KEY idx_component_asset_component (component_id)
);
CREATE TABLE IF NOT EXISTS sys_operation_log (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
module VARCHAR(32) NOT NULL,
action VARCHAR(32) NOT NULL,
target_id VARCHAR(512) NULL,
operator_id BIGINT NOT NULL,
operator_name VARCHAR(64) NOT NULL,
request_path VARCHAR(512) NOT NULL,
request_method VARCHAR(16) NOT NULL,
client_ip VARCHAR(64) NULL,
request_id VARCHAR(64) NULL,
operated_at DATETIME(3) NOT NULL,
duration_ms BIGINT NOT NULL,
success TINYINT NOT NULL,
http_status INT NOT NULL,
error_summary VARCHAR(1000) NULL,
KEY idx_operation_module_time (module, operated_at),
KEY idx_operation_operator_time (operator_id, operated_at),
KEY idx_operation_result_time (success, operated_at)
);
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-api</artifactId>
<packaging>jar</packaging>
<name>cadworld-api</name>
</project>
+29
View File
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-bean</artifactId>
<packaging>jar</packaging>
<name>cadworld-bean</name>
<dependencies>
<dependency>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,8 @@
package com.linkerbot.cadworld.dto.common;
public record SuccessResponse(boolean success) {
public static SuccessResponse ok() {
return new SuccessResponse(true);
}
}
@@ -0,0 +1,12 @@
package com.linkerbot.cadworld.dto.component;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.List;
public record CompleteCoverImageUploadRequest(
@NotBlank String uploadSessionToken,
@NotEmpty @Size(max = 1) List<@NotBlank String> objectKeys
) {
}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.dto.component;
public record CompleteCoverImageUploadResponse(
String coverImageKey,
String coverImageUrl
) {
}
@@ -0,0 +1,12 @@
package com.linkerbot.cadworld.dto.component;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.List;
public record CompleteUrdfUploadRequest(
@NotBlank String uploadSessionToken,
@NotEmpty @Size(max = 1000) List<@NotBlank String> objectKeys
) {
}
@@ -0,0 +1,4 @@
package com.linkerbot.cadworld.dto.component;
public record CompleteUrdfUploadResponse(String source) {
}
@@ -0,0 +1,52 @@
package com.linkerbot.cadworld.dto.component;
import jakarta.validation.Valid;
import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.util.StringUtils;
/**
* 供拼装规划器检索的组件语义元数据。
*
* <p>组件的可视模型和接口仍保留在 componentJson;这里仅保存可查询的能力与尺寸,
* 不将人体部位或机器人形态写成后端规则。</p>
*/
public record ComponentAssemblyMetadata(
@NotNull List<String> tags,
@NotNull List<String> capabilities,
@NotNull @Valid Dimensions dimensions
) {
public ComponentAssemblyMetadata {
tags = normalize(tags);
capabilities = normalize(capabilities);
dimensions = dimensions == null ? Dimensions.empty() : dimensions;
}
public static ComponentAssemblyMetadata empty() {
return new ComponentAssemblyMetadata(List.of(), List.of(), Dimensions.empty());
}
private static List<String> normalize(List<String> source) {
if (source == null) {
return List.of();
}
return source.stream()
.filter(StringUtils::hasText)
.map(String::trim)
.distinct()
.toList();
}
public record Dimensions(
@DecimalMin(value = "0.0", inclusive = false) BigDecimal lengthMm,
@DecimalMin(value = "0.0", inclusive = false) BigDecimal widthMm,
@DecimalMin(value = "0.0", inclusive = false) BigDecimal heightMm
) {
public static Dimensions empty() {
return new Dimensions(null, null, null);
}
}
}
@@ -0,0 +1,24 @@
package com.linkerbot.cadworld.dto.component;
import java.time.LocalDateTime;
public record ComponentListItemResponse(
Long id,
String componentName,
String category,
String robotType,
String company,
String model,
String source,
String sourceUrl,
String coverImageUrl,
String description,
ComponentAssemblyMetadata assemblyMetadata,
LocalDateTime createdAt,
LocalDateTime updatedAt
) {
public String componentType() {
return category;
}
}
@@ -0,0 +1,27 @@
package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import java.time.LocalDateTime;
public record ComponentResponse(
Long id,
String componentName,
String category,
String robotType,
String company,
String model,
String source,
String sourceUrl,
String coverImageKey,
String coverImageUrl,
String description,
JsonNode componentJson,
ComponentAssemblyMetadata assemblyMetadata,
LocalDateTime createdAt,
LocalDateTime updatedAt
) {
public String componentType() {
return category;
}
}
@@ -0,0 +1,28 @@
package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record CreateComponentRequest(
@NotBlank @Size(max = 64) String componentName,
@Size(max = 64) String category,
@NotBlank @Size(max = 32) String robotType,
@NotBlank @Size(max = 64) String company,
@NotBlank @Size(max = 64) String model,
@NotBlank @Size(max = 255) String source,
@Size(max = 512) String coverImageKey,
String description,
@NotNull JsonNode componentJson,
@NotNull @jakarta.validation.Valid ComponentAssemblyMetadata assemblyMetadata
) {
/** Compatibility constructor used by existing service tests and old callers. */
public CreateComponentRequest(String componentName, String componentType, String robotType, String company,
String model, String source, String coverImageKey, String description,
JsonNode componentJson) {
this(componentName, componentType, robotType, company, model, source, coverImageKey, description,
componentJson, ComponentAssemblyMetadata.empty());
}
}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.dto.component;
public record PrepareCoverImageUploadSessionResponse(
String uploadSessionToken,
String keyPrefix
) {
}
@@ -0,0 +1,11 @@
package com.linkerbot.cadworld.dto.component;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public record PrepareObjectUploadUrlRequest(
@NotBlank String uploadSessionToken,
@NotBlank @Size(max = 512) String objectPath,
@Size(max = 255) String contentType
) {
}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.dto.component;
public record PrepareObjectUploadUrlResponse(
String uploadUrl,
String objectKey
) {
}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.dto.component;
public record PrepareUrdfUploadSessionResponse(
String uploadSessionToken,
String keyPrefix
) {
}
@@ -0,0 +1,27 @@
package com.linkerbot.cadworld.dto.component;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record UpdateComponentRequest(
@NotBlank @Size(max = 64) String componentName,
@Size(max = 64) String category,
@NotBlank @Size(max = 32) String robotType,
@NotBlank @Size(max = 64) String company,
@NotBlank @Size(max = 64) String model,
@NotBlank @Size(max = 255) String source,
@Size(max = 512) String coverImageKey,
String description,
@NotNull JsonNode componentJson,
@NotNull @jakarta.validation.Valid ComponentAssemblyMetadata assemblyMetadata
) {
public UpdateComponentRequest(String componentName, String componentType, String robotType, String company,
String model, String source, String coverImageKey, String description,
JsonNode componentJson) {
this(componentName, componentType, robotType, company, model, source, coverImageKey, description,
componentJson, ComponentAssemblyMetadata.empty());
}
}
@@ -0,0 +1,15 @@
package com.linkerbot.cadworld.dto.user;
import com.linkerbot.cadworld.enums.UserStatus;
import com.linkerbot.cadworld.enums.UserType;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public record SaveUserRequest(
@NotBlank @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phone,
@NotBlank @Size(max = 64) String nickname,
UserStatus status,
UserType userType
) {
}
@@ -0,0 +1,9 @@
package com.linkerbot.cadworld.dto.user;
import com.linkerbot.cadworld.enums.UserStatus;
import com.linkerbot.cadworld.enums.UserType;
import java.time.LocalDateTime;
public record UserResponse(Long id, String phone, String nickname, UserStatus status, UserType userType,
LocalDateTime createdAt, LocalDateTime updatedAt) {
}
@@ -0,0 +1,18 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public abstract class BaseEntity {
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createdAt;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updatedAt;
}
@@ -0,0 +1,54 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@TableName(value = "component", autoResultMap = true)
public class Component extends BaseEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String componentName;
/** Free-form catalog category. It is not a robot body slot or an execution rule. */
private String category;
private String robotType;
@TableField(typeHandler = JsonNodeTypeHandler.class)
private JsonNode assemblyMetadata;
private String company;
private String model;
private String source;
private String coverImageKey;
private String description;
@TableField(typeHandler = JsonNodeTypeHandler.class)
private JsonNode componentJson;
/**
* Transitional accessors keep historical read-only code compiling while all persisted data uses
* the free-form {@code category} column.
*/
public String getComponentType() {
return category;
}
public void setComponentType(String componentType) {
this.category = componentType;
}
}
@@ -0,0 +1,20 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter; import lombok.Setter;
@Getter @Setter
@TableName("component_asset")
public class ComponentAsset extends BaseEntity {
@TableId(type = IdType.AUTO) private Long id;
private Long componentId;
private String objectKey;
private String relativePath;
private String assetKind;
private String contentType;
private Long size;
private String sha256;
private Boolean isPrimary;
}
@@ -0,0 +1,24 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
@TableName(value = "interface_definition_v2", autoResultMap = true)
public class InterfaceDefinitionEntity extends BaseEntity {
@TableId private String id;
private String name;
private String description;
private Integer geometryRevision;
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode geometryJson;
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode tolerancesJson;
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode connectableTargetsJson;
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode displayForwardJson;
private String sourceAssetKey;
private String sourceGeometryHash;
}
@@ -0,0 +1,14 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.mybatis.JsonNodeTypeHandler;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
@TableName(value = "interface_definition_revision", autoResultMap = true)
public class InterfaceDefinitionRevisionEntity {
@TableId private String id;
private String definitionId;
private Integer geometryRevision;
@TableField(typeHandler = JsonNodeTypeHandler.class) private JsonNode definitionJson;
}
@@ -0,0 +1,30 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@TableName("sys_operation_log")
public class OperationLog {
@TableId(type = IdType.AUTO)
private Long id;
private String module;
private String action;
private String targetId;
private Long operatorId;
private String operatorName;
private String requestPath;
private String requestMethod;
private String clientIp;
private String requestId;
private LocalDateTime operatedAt;
private Long durationMs;
private Boolean success;
private Integer httpStatus;
private String errorSummary;
}
@@ -0,0 +1,29 @@
package com.linkerbot.cadworld.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.linkerbot.cadworld.enums.UserStatus;
import com.linkerbot.cadworld.enums.UserType;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@TableName("sys_user")
public class SysUser extends BaseEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String phone;
private String nickname;
private UserStatus status;
private UserType userType;
@com.baomidou.mybatisplus.annotation.TableLogic
private Integer deleted;
}
@@ -0,0 +1,26 @@
package com.linkerbot.cadworld.enums;
import java.util.Arrays;
public enum ComponentUploadType {
URDF("component-urdf-upload"),
COVER_IMAGE("component-cover-image-upload");
private final String tokenType;
ComponentUploadType(String tokenType) {
this.tokenType = tokenType;
}
public String tokenType() {
return tokenType;
}
public static ComponentUploadType fromTokenType(String tokenType) {
return Arrays.stream(values())
.filter(value -> value.tokenType.equals(tokenType))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid upload session token type"));
}
}
@@ -0,0 +1,6 @@
package com.linkerbot.cadworld.enums;
public enum UserStatus {
ACTIVE,
DISABLED
}
@@ -0,0 +1,6 @@
package com.linkerbot.cadworld.enums;
public enum UserType {
NORMAL,
ADMIN
}
+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-common</artifactId>
<packaging>jar</packaging>
<name>cadworld-common</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,15 @@
package com.linkerbot.cadworld.common.api;
public final class ApiCode {
public static final String OK = "OK";
public static final String NOT_FOUND = "NOT_FOUND";
public static final String INVALID_REQUEST = "INVALID_REQUEST";
public static final String UNAUTHORIZED = "UNAUTHORIZED";
public static final String FORBIDDEN = "FORBIDDEN";
public static final String DATABASE_UNAVAILABLE = "DATABASE_UNAVAILABLE";
public static final String INTERNAL_ERROR = "INTERNAL_ERROR";
private ApiCode() {
}
}
@@ -0,0 +1,29 @@
package com.linkerbot.cadworld.common.api;
import lombok.Getter;
@Getter
public class ApiResponse<T> {
private static final String SUCCESS_MESSAGE = "success";
private final String code;
private final String message;
private final T data;
private final String requestId;
private ApiResponse(String code, String message, T data, String requestId) {
this.code = code;
this.message = message;
this.data = data;
this.requestId = requestId;
}
public static <T> ApiResponse<T> success(T data) {
return new ApiResponse<>(ApiCode.OK, SUCCESS_MESSAGE, data, RequestIdHolder.get());
}
public static <T> ApiResponse<T> failure(String code, String message) {
return new ApiResponse<>(code, message, null, RequestIdHolder.get());
}
}
@@ -0,0 +1,11 @@
package com.linkerbot.cadworld.common.api;
import java.util.List;
public record PageResponse<T>(
List<T> items,
long page,
long size,
long total
) {
}
@@ -0,0 +1,23 @@
package com.linkerbot.cadworld.common.api;
import org.slf4j.MDC;
public final class RequestIdHolder {
private static final String KEY = "requestId";
private RequestIdHolder() {
}
public static void set(String requestId) {
MDC.put(KEY, requestId);
}
public static String get() {
return MDC.get(KEY);
}
public static void clear() {
MDC.remove(KEY);
}
}
@@ -0,0 +1,16 @@
package com.linkerbot.cadworld.common.exception;
import lombok.Getter;
@Getter
public class BizException extends RuntimeException {
private final int httpStatus;
private final String code;
public BizException(int httpStatus, String code, String message) {
super(message);
this.httpStatus = httpStatus;
this.code = code;
}
}
@@ -0,0 +1,83 @@
package com.linkerbot.cadworld.common.exception;
import com.linkerbot.cadworld.common.api.ApiCode;
import com.linkerbot.cadworld.common.api.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.CannotCreateTransactionException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(org.springframework.web.multipart.MaxUploadSizeExceededException.class)
public ResponseEntity<ApiResponse<Void>> handleUploadTooLarge(HttpServletRequest request) {
request.setAttribute("cadworld.operationError", "上传文件超过大小限制");
return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
.body(ApiResponse.failure(ApiCode.INVALID_REQUEST, "上传文件超过大小限制"));
}
@ExceptionHandler(BizException.class)
public ResponseEntity<ApiResponse<Void>> handleBiz(BizException exception, HttpServletRequest request) {
request.setAttribute("cadworld.operationError", exception.getMessage());
return ResponseEntity.status(exception.getHttpStatus())
.body(ApiResponse.failure(exception.getCode(), exception.getMessage()));
}
@ExceptionHandler({
MethodArgumentNotValidException.class,
BindException.class,
ConstraintViolationException.class,
HttpMediaTypeNotSupportedException.class,
HttpRequestMethodNotSupportedException.class,
org.springframework.http.converter.HttpMessageNotReadableException.class,
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class,
org.springframework.web.bind.MissingServletRequestParameterException.class,
org.springframework.web.multipart.support.MissingServletRequestPartException.class,
org.springframework.web.method.annotation.HandlerMethodValidationException.class,
IllegalArgumentException.class
})
public ResponseEntity<ApiResponse<Void>> handleBadRequest(Exception exception, HttpServletRequest request) {
request.setAttribute("cadworld.operationError", "请求参数或数据格式不合法");
return ResponseEntity.unprocessableEntity()
.body(ApiResponse.failure(ApiCode.INVALID_REQUEST, exception.getMessage()));
}
@ExceptionHandler({CannotCreateTransactionException.class, DataAccessResourceFailureException.class})
public ResponseEntity<ApiResponse<Void>> handleDatabaseUnavailable(Exception exception, HttpServletRequest request) {
request.setAttribute("cadworld.operationError", "数据库暂不可用");
log.error("Database is unavailable", exception);
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(ApiResponse.failure(ApiCode.DATABASE_UNAVAILABLE, "数据库暂不可用,请检查数据库连接配置后重试"));
}
@ExceptionHandler({
NoResourceFoundException.class,
NoHandlerFoundException.class
})
public ResponseEntity<ApiResponse<Void>> handleNotFound(HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.failure(ApiCode.NOT_FOUND, "请求路径不存在: %s %s"
.formatted(request.getMethod(), request.getRequestURI())));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleUnknown(Exception exception, HttpServletRequest request) {
request.setAttribute("cadworld.operationError", "系统异常");
log.error("Unhandled exception at {} {}", request.getMethod(), request.getRequestURI(), exception);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.failure(ApiCode.INTERNAL_ERROR, "系统异常"));
}
}
@@ -0,0 +1,53 @@
package com.linkerbot.cadworld.common.mybatis;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
/**
* 统一的 JsonNode 持久化处理器。
*
* <p>显式按字符串写入 JSON,可以同时兼容 MySQL JSON 列和测试环境中的 CLOB/VARCHAR,
* 避免不同 JDBC 驱动把 JsonNode 当成 JAVA_OBJECT 处理。</p>
*/
public class JsonNodeTypeHandler extends BaseTypeHandler<JsonNode> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.toString());
}
@Override
public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parse(rs.getString(columnName));
}
@Override
public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parse(rs.getString(columnIndex));
}
@Override
public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parse(cs.getString(columnIndex));
}
private JsonNode parse(String value) throws SQLException {
if (value == null) {
return null;
}
try {
return OBJECT_MAPPER.readTree(value);
} catch (IOException exception) {
throw new SQLException("Failed to parse json column", exception);
}
}
}
@@ -0,0 +1,30 @@
package com.linkerbot.cadworld.common.process;
import java.io.*;
import java.nio.file.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
/** No shell interpretation; bounded output, deadline and cancellation apply to the whole process tree. */
public class ToolProcess {
public record Result(int exitCode,String output,boolean timedOut) {}
public Result run(List<String> command,Path directory,Duration timeout) throws IOException,InterruptedException {
ProcessBuilder builder=new ProcessBuilder(command).directory(directory.toFile()).redirectErrorStream(true);
builder.environment().put("LC_ALL","C");builder.environment().put("PYTHONUTF8","1");builder.environment().put("PYTHONDONTWRITEBYTECODE","1");
Process process=builder.start();StringBuilder output=new StringBuilder();
Thread reader=Thread.ofPlatform().daemon().start(()->{
try(Reader in=new InputStreamReader(process.getInputStream(),java.nio.charset.StandardCharsets.UTF_8)) {
char[] chars=new char[2048];int n;
while((n=in.read(chars))!=-1) synchronized(output){if(output.length()<65536)output.append(chars,0,Math.min(n,65536-output.length()));}
}catch(IOException ignored) { /* Cancellation closes the pipe. */ }
});
try {
boolean finished=process.waitFor(timeout.toMillis(),TimeUnit.MILLISECONDS);
if(!finished)kill(process);
reader.join(1000);
synchronized(output){return new Result(finished?process.exitValue():-1,output.toString(),!finished);}
} finally {if(process.isAlive())kill(process);}
}
private static void kill(Process process) {process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();}
}
@@ -0,0 +1,40 @@
package com.linkerbot.cadworld.common.web;
import com.linkerbot.cadworld.common.api.RequestIdHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
String requestId = Optional.ofNullable(request.getHeader("X-Request-Id"))
.filter(value -> !value.isBlank())
.orElseGet(() -> UUID.randomUUID().toString().replace("-", ""));
RequestIdHolder.set(requestId);
MDC.put("requestId", requestId);
response.setHeader("X-Request-Id", requestId);
try {
filterChain.doFilter(request, response);
} finally {
RequestIdHolder.clear();
MDC.remove("requestId");
}
}
}
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<springProperty scope="context" name="APP_NAME" source="spring.application.name" defaultValue="cadworld"/>
<springProperty scope="context" name="LOG_PATH" source="logging.file.path" defaultValue="logs"/>
<property name="LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS,Asia/Shanghai} [%thread] %-5level [%X{requestId:-}] %logger{36} - %msg%n%ex"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="APP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/${APP_NAME}.log</file>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/archive/${APP_NAME}.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz</fileNamePattern>
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
</appender>
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/${APP_NAME}-error.log</file>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
<charset>UTF-8</charset>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/archive/${APP_NAME}-error.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>60</maxHistory>
<totalSizeCap>5GB</totalSizeCap>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="APP_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</configuration>
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-security-admin</artifactId>
<packaging>jar</packaging>
<name>cadworld-security-admin</name>
</project>
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-security-api</artifactId>
<packaging>jar</packaging>
<name>cadworld-security-api</name>
</project>
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-security-common</artifactId>
<packaging>jar</packaging>
<name>cadworld-security-common</name>
</project>
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-security</artifactId>
<packaging>pom</packaging>
<name>cadworld-security</name>
<modules>
<module>cadworld-security-admin</module>
<module>cadworld-security-api</module>
<module>cadworld-security-common</module>
</modules>
</project>
+51
View File
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>cadworld-service</artifactId>
<packaging>jar</packaging>
<name>cadworld-service</name>
<dependencies>
<dependency>
<groupId>com.linkerbot</groupId>
<artifactId>cadworld-bean</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
</dependency>
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,12 @@
package com.linkerbot.cadworld.config;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "app.admin.operator")
public record AdminOperatorProperties(@Min(0) long id, @NotBlank @Size(max = 64) String name) {
}
@@ -0,0 +1,18 @@
package com.linkerbot.cadworld.config;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "app.interface-brep")
public record InterfaceBrepProperties(
@NotBlank String python,
@NotBlank String script,
@Min(1) @Max(600) int timeoutSeconds,
@Min(1) long maxUploadBytes,
@Min(1) long maxOutputBytes
) {
}
@@ -0,0 +1,12 @@
package com.linkerbot.cadworld.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "app.minio")
public record MinioProperties(
String endpoint,
String accessKey,
String secretKey,
String bucket
) {
}
@@ -0,0 +1,38 @@
package com.linkerbot.cadworld.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import java.time.LocalDateTime;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
@Bean
public MetaObjectHandler metaObjectHandler() {
return new MetaObjectHandler() {
@Override
public void insertFill(MetaObject metaObject) {
LocalDateTime now = LocalDateTime.now(java.time.ZoneId.of("Asia/Shanghai"));
this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, now);
this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, now);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updatedAt", LocalDateTime.now(java.time.ZoneId.of("Asia/Shanghai")), metaObject);
}
};
}
}
@@ -0,0 +1,34 @@
package com.linkerbot.cadworld.config;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.ConstructorBinding;
@ConfigurationProperties(prefix = "app.storage")
public record StorageProperties(
String provider,
String urdfPrefix,
String coverImagePrefix,
String publicBaseUrl,
String publicApiBaseUrl,
String localRoot,
Duration uploadSessionTtl
) {
@ConstructorBinding
public StorageProperties(String provider, String urdfPrefix, String coverImagePrefix,
String publicBaseUrl, String publicApiBaseUrl, String localRoot,
Duration uploadSessionTtl) {
this.provider = provider;
this.urdfPrefix = urdfPrefix;
this.coverImagePrefix = coverImagePrefix;
this.publicBaseUrl = publicBaseUrl;
this.publicApiBaseUrl = publicApiBaseUrl;
this.localRoot = localRoot;
this.uploadSessionTtl = uploadSessionTtl;
}
public StorageProperties(String provider, String urdfPrefix, String coverImagePrefix,
String publicBaseUrl, String publicApiBaseUrl, Duration uploadSessionTtl) {
this(provider, urdfPrefix, coverImagePrefix, publicBaseUrl, publicApiBaseUrl, "./data/assets", uploadSessionTtl);
}
}
@@ -0,0 +1,8 @@
package com.linkerbot.cadworld.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/** Upload tokens are independent of account authentication. */
@ConfigurationProperties(prefix = "app.upload-session")
public record UploadSessionProperties(String issuer, String secret) {
}
@@ -0,0 +1,4 @@
package com.linkerbot.cadworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.cadworld.entity.ComponentAsset;
public interface ComponentAssetMapper extends BaseMapper<ComponentAsset> {}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.cadworld.entity.Component;
public interface ComponentMapper extends BaseMapper<Component> {
}
@@ -0,0 +1,4 @@
package com.linkerbot.cadworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.cadworld.entity.InterfaceDefinitionEntity;
public interface InterfaceDefinitionMapper extends BaseMapper<InterfaceDefinitionEntity> {}
@@ -0,0 +1,6 @@
package com.linkerbot.cadworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.cadworld.entity.InterfaceDefinitionRevisionEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface InterfaceDefinitionRevisionMapper extends BaseMapper<InterfaceDefinitionRevisionEntity> {}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.cadworld.entity.OperationLog;
public interface OperationLogMapper extends BaseMapper<OperationLog> {
}
@@ -0,0 +1,7 @@
package com.linkerbot.cadworld.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.cadworld.entity.SysUser;
public interface SysUserMapper extends BaseMapper<SysUser> {
}
@@ -0,0 +1,64 @@
package com.linkerbot.cadworld.mechanicalinterface;
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
import java.util.HashSet;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service @RequiredArgsConstructor
public class ComponentPortValidationService {
private final InterfaceDefinitionService definitions;
private final MechanicalInterfaceSolver solver;
private final ObjectMapper mapper;
private final UrdfSourceValidation sourceValidation;
private final UrdfAssetVerifier assetVerifier;
public JsonNode validate(JsonNode componentJson){
if(componentJson==null||!componentJson.isObject())throw new IllegalArgumentException("组件模型数据不合法");
ObjectNode result=componentJson.deepCopy();
JsonNode interfaces=result.get("interfaces");
if(interfaces==null)return result;
if(!interfaces.isArray())throw new IllegalArgumentException("接口必须是数组");
Set<String> links=interfaces.isEmpty()?Set.of():sourceValidation.validate(result.get("urdfSource"));
if(!interfaces.isEmpty())assetVerifier.verify(result.get("urdfSource"));
ArrayNode confirmed=mapper.createArrayNode();Set<String> ids=new HashSet<>();
for(JsonNode raw:interfaces){
Port port=readPort(raw);
if(!links.contains(port.linkName()))throw new IllegalArgumentException("接口所属 link 不存在于原始 URDF:"+port.linkName());
if(!port.sourceGeometryHash().equals(result.path("urdfSource").path("sourceGeometryHash").asText()))throw new IllegalArgumentException("接口源几何已变化,请重新识别");
if(definitions.get(port.definitionId()).path("geometryRevision").asInt()!=port.definitionRevision())throw new IllegalArgumentException("接口定义已修订,请重新确认组件接口");
if(!ids.add(port.id()))throw new IllegalArgumentException("组件端口 ID 重复");
Port canonical=solver.confirmPortPose(definitions.geometryDefinition(port.definitionId(),port.definitionRevision()),port);
confirmed.add(mapper.valueToTree(canonical));
}
result.set("interfaces",confirmed);result.put("interfaceSchemaVersion",3);
return result;
}
public Port readPort(JsonNode raw){
try{return mapper.readerFor(Port.class).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(normalizePort(raw));}
catch(java.io.IOException | IllegalArgumentException e){throw new IllegalArgumentException("不支持的接口结构,请重新识别并确认姿态:"+rootMessage(e),e);}
}
private JsonNode normalizePort(JsonNode raw){
if(raw==null||!raw.isObject())return raw;
ObjectNode copy=raw.deepCopy();JsonNode targets=copy.get("connectableTargets");
if(targets!=null&&!targets.isNull()){
ArrayNode normalized=mapper.createArrayNode();flattenTargets(targets,normalized);copy.set("connectableTargets",normalized);
}
return copy;
}
private void flattenTargets(JsonNode node,ArrayNode output){
if(node==null||node.isNull())return;
if(node.isArray()){
boolean path=true;StringBuilder joined=new StringBuilder();
for(JsonNode child:node){if(!child.isTextual()){path=false;break;}if(joined.length()>0)joined.append('/');joined.append(child.asText());}
if(path){String value=joined.toString().trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);return;}
node.forEach(child->flattenTargets(child,output));return;
}
String value=node.asText("").trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);
}
private boolean containsTarget(ArrayNode output,String value){for(JsonNode item:output)if(value.equals(item.asText()))return true;return false;}
private String rootMessage(Throwable error){Throwable current=error;while(current.getCause()!=null)current=current.getCause();return current.getMessage()==null?"字段格式错误":current.getMessage();}
}
@@ -0,0 +1,49 @@
package com.linkerbot.cadworld.mechanicalinterface;
import java.util.List;
/** Mechanical interface wire contract. All distances are metres; quaternions are XYZW. */
public final class InterfaceGeometry {
private InterfaceGeometry() {}
public static final String SOLVER_VERSION = "mount-geometry-3";
public record RigidPose(double[] positionM, double[] quaternionXYZW) {}
public record Plane(double[] pointM, double[] outwardNormal) {}
public record Hole(String id, double[] pointOnPlaneM, double[] axis, Double diameterM) {}
public record MountGeometry(Plane plane, List<Hole> holes) {}
public record Tolerances(double positionM, double axisAngleRad, double planeAngleRad) {
public static Tolerances defaults() { return new Tolerances(0.0002, Math.PI / 180, Math.PI / 180); }
}
public record Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances,
List<String> connectableTargets, double[] displayForward) {
public Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances,
List<String> connectableTargets) {
this(id, geometryRevision, name, geometry, tolerances, connectableTargets, null);
}
public Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances) {
this(id, geometryRevision, name, geometry, tolerances, List.of());
}
}
public record HoleMapping(String templateHoleId, String observedHoleId) {}
/** Display reference mapped through the selected pose into the owning link frame. */
public record SelectedPose(String id, RigidPose templateInLink, List<HoleMapping> holeMapping,
double[] orientationDirectionInLink) {}
public record Port(String id, String linkName, String definitionId, int definitionRevision,
MountGeometry geometryInLink, SelectedPose selectedPose,
String sourceGeometryHash, String solverVersion, List<String> connectableTargets) {
public Port(String id, String linkName, String definitionId, int definitionRevision,
MountGeometry geometryInLink, SelectedPose selectedPose,
String sourceGeometryHash, String solverVersion) {
this(id, linkName, definitionId, definitionRevision, geometryInLink, selectedPose,
sourceGeometryHash, solverVersion, List.of());
}
}
public record PoseRequest(int definitionRevision, String linkName, MountGeometry geometryInLink, String sourceGeometryHash) {}
public record PoseCandidate(String id, RigidPose templateInLink, List<HoleMapping> holeMapping,
double[] orientationDirectionInLink, int registrationSide,
double maxHoleOffsetM, double rmsHoleOffsetM, double maxAxisAngleRad) {}
public record CandidateSet(String solverVersion, List<PoseCandidate> candidates, List<String> reasons) {}
public record HolePair(String parentHoleId, String childHoleId) {}
public record ResolvedConnection(String parentLinkName, String childLinkName, RigidPose childLinkInParentLink,
List<HolePair> holePairs, double maxHoleOffsetM, double maxAxisAngleRad,
double planeOffsetM, double orientationAngleRad) {}
}
@@ -0,0 +1,305 @@
package com.linkerbot.cadworld.mechanicalinterface;
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
import static com.linkerbot.cadworld.mechanicalinterface.RigidMath.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
import org.springframework.stereotype.Service;
/** The single authority for registering, confirming and connecting physical ports. */
@Service
public class MechanicalInterfaceSolver {
private record Match(int[] indices, double maximum, double rms, double axisMaximum) {}
public void validateDefinition(Definition definition) {
if (definition == null || blank(definition.id()) || blank(definition.name()) || definition.geometryRevision() < 1)
throw new IllegalArgumentException("接口定义或几何修订不合法");
tolerances(definition.tolerances());
normalize(definition.geometry(), definition.tolerances());
displayForward(definition);
}
/** Display metadata only; never enters pose enumeration or the connection transform. */
public double[] displayForward(Definition definition) {
double[] normal = unit(definition.geometry().plane().outwardNormal());
double[] direction = definition.displayForward();
if (direction == null) {
for (double[] axis : new double[][]{{1,0,0},{0,1,0},{0,0,1}}) {
double[] tangent = sub(axis,scale(normal,dot(axis,normal)));
if (norm(tangent)>1e-6) return unit(tangent);
}
}
direction = unit(direction);
if (Math.abs(dot(direction,normal))>1e-6)
throw new IllegalArgumentException("默认前方必须位于安装面内");
return direction;
}
public CandidateSet enumeratePortPoses(Definition definition, PoseRequest request) {
validateDefinition(definition);
if (request == null || request.definitionRevision() != definition.geometryRevision())
throw new IllegalArgumentException("接口几何修订已变化,请重新识别");
if (blank(request.linkName()) || blank(request.sourceGeometryHash()))
throw new IllegalArgumentException("缺少所属 link 或源几何哈希");
MountGeometry source = normalize(definition.geometry(), definition.tolerances());
MountGeometry target = normalize(request.geometryInLink(), definition.tolerances());
if (source.holes().size() != target.holes().size())
return rejected("接口需要 " + source.holes().size() + " 个孔,实测 " + target.holes().size() + " 个孔;必须确认完整孔组");
String fingerprint = definition.id() + ':' + definition.geometryRevision() + ':' + request.linkName() + ':'
+ request.sourceGeometryHash() + ':' + fingerprint(source) + ':' + fingerprint(target);
List<PoseCandidate> candidates = enumerate(source, target, definition.tolerances(), 1, fingerprint);
if (candidates.isEmpty()) candidates = enumerate(source, target, definition.tolerances(), -1, fingerprint);
return candidates.isEmpty() ? rejectionDetails(source, target, definition.tolerances())
: new CandidateSet(SOLVER_VERSION, candidates.stream().map(candidate -> new PoseCandidate(
candidate.id(), candidate.templateInLink(), candidate.holeMapping(),
rotate(rotation(candidate.templateInLink()), displayForward(definition)),
candidate.registrationSide(), candidate.maxHoleOffsetM(), candidate.rmsHoleOffsetM(),
candidate.maxAxisAngleRad())).toList(), List.of());
}
/** Necessary rigid invariants identify problematic evidence without guessing a replacement pose. */
private CandidateSet rejectionDetails(MountGeometry source, MountGeometry target, Tolerances tolerance) {
List<String> reasons = new ArrayList<>();
for (Hole observed : target.holes()) {
double tilt = angle(observed.axis(), target.plane().outwardNormal(), true);
boolean axisPossible = source.holes().stream().anyMatch(h ->
Math.abs(tilt - angle(h.axis(), source.plane().outwardNormal(), true))
<= tolerance.axisAngleRad() + tolerance.planeAngleRad() + 1e-10);
if (!axisPossible) reasons.add("孔 " + observed.id() + " 的孔轴与安装面夹角不符合模板,请核对孔轴或向外法向");
double[] distances = target.holes().stream().mapToDouble(h -> norm(sub(h.pointOnPlaneM(), observed.pointOnPlaneM()))).sorted().toArray();
boolean distancesPossible = source.holes().stream().anyMatch(anchor -> {
double[] expected = source.holes().stream().mapToDouble(h -> norm(sub(h.pointOnPlaneM(), anchor.pointOnPlaneM()))).sorted().toArray();
for (int i = 0; i < expected.length; i++)
if (Math.abs(expected[i] - distances[i]) > 2 * tolerance.positionM() + 1e-10) return false;
return true;
});
if (!distancesPossible) reasons.add("孔 " + observed.id() + " 的孔距组合与模板不符,请核对该孔及完整孔组");
}
if (reasons.isEmpty()) reasons.add("孔组 " + target.holes().stream().map(Hole::id).toList()
+ " 未找到满足全部孔位、孔轴及安装面约束的一一对应;请返回几何确认");
return new CandidateSet(SOLVER_VERSION, List.of(), List.copyOf(reasons));
}
public Port confirmPortPose(Definition definition, Port submitted) {
if (submitted == null || blank(submitted.id()) || submitted.selectedPose() == null
|| !definition.id().equals(submitted.definitionId())
|| !SOLVER_VERSION.equals(submitted.solverVersion()))
throw new IllegalArgumentException("不支持的接口结构,请重新识别并确认安装姿态");
CandidateSet result = enumeratePortPoses(definition, new PoseRequest(submitted.definitionRevision(),
submitted.linkName(), submitted.geometryInLink(), submitted.sourceGeometryHash()));
PoseCandidate chosen = result.candidates().stream().filter(p -> p.id().equals(submitted.selectedPose().id()))
.findFirst().orElseThrow(() -> new IllegalArgumentException("保存的安装姿态已失效,请重新选择"));
// Never trust a caller-provided quaternion or hole mapping.
List<String> targets = submitted.connectableTargets() == null || submitted.connectableTargets().isEmpty()
? normalizeTargets(definition.connectableTargets()) : normalizeTargets(submitted.connectableTargets());
return new Port(submitted.id(), submitted.linkName(), definition.id(), definition.geometryRevision(),
normalize(submitted.geometryInLink(), definition.tolerances()),
new SelectedPose(chosen.id(), chosen.templateInLink(), chosen.holeMapping(), chosen.orientationDirectionInLink()),
submitted.sourceGeometryHash(), SOLVER_VERSION, targets);
}
private List<String> normalizeTargets(List<String> values) {
if (values == null) return List.of();
return values.stream().filter(Objects::nonNull).map(String::trim).filter(value -> !value.isEmpty()).distinct().toList();
}
/**
* Resolves only the rigid transform implied by the saved port poses. When
* a hole pattern has multiple equivalent mating bases, the base is chosen
* by the saved in-plane forward references; a connection is rejected if no
* valid base makes those references point in the same direction.
*/
public ResolvedConnection resolveLockedConnection(Definition definition, Port parentInput, Port childInput) {
Port parent = confirmPortPose(definition, parentInput);
Port child = confirmPortPose(definition, childInput);
double[] templateNormal = unit(definition.geometry().plane().outwardNormal());
int parentSide = side(parent, templateNormal), childSide = side(child, templateNormal);
List<RigidPose> mateCandidates = List.of(identity());
if (parentSide == childSide) {
MountGeometry template = normalize(definition.geometry(), definition.tolerances());
List<PoseCandidate> flipped = enumerate(template, template, definition.tolerances(), -1, definition.id());
if (flipped.isEmpty()) throw new IllegalArgumentException("该孔阵的两侧没有合法对接基准,不能镜像或补偿旋转");
// A symmetric hole pattern can have several valid 180-degree
// mating bases. Prefer the one that keeps the two display-forward
// references pointing in the same direction after mating. The
// selected component poses remain authoritative; this only picks
// the geometrically equivalent hole mapping for the connection.
mateCandidates = flipped.stream().map(PoseCandidate::templateInLink).toList();
}
MountGeometry a = parent.geometryInLink(), b = child.geometryInLink();
Tolerances tolerance = definition.tolerances();
RigidPose transform = null;
Match match = null;
double planeOffset = 0;
double orientationError = Double.POSITIVE_INFINITY;
for (RigidPose mate : mateCandidates) {
RigidPose candidateTransform = compose(compose(parent.selectedPose().templateInLink(), mate),
inverse(child.selectedPose().templateInLink()));
double normalError = angle(a.plane().outwardNormal(),
scale(rotate(rotation(candidateTransform), b.plane().outwardNormal()), -1), false);
double candidatePlaneOffset = Math.abs(dot(sub(point(candidateTransform,b.plane().pointM()), a.plane().pointM()),
unit(a.plane().outwardNormal())));
Match candidateMatch = assignment(b.holes(), a.holes(), candidateTransform, tolerance, 1);
if (normalError > tolerance.planeAngleRad() + 1e-10
|| candidatePlaneOffset > tolerance.positionM() + 1e-10 || candidateMatch == null) continue;
double candidateOrientationError = angle(parent.selectedPose().orientationDirectionInLink(),
rotate(rotation(candidateTransform), child.selectedPose().orientationDirectionInLink()), false);
if (transform == null || candidateOrientationError < orientationError) {
transform = candidateTransform;
match = candidateMatch;
planeOffset = candidatePlaneOffset;
orientationError = candidateOrientationError;
}
}
if (transform == null || match == null)
throw new IllegalArgumentException("已保存姿态无法使安装面和全部实测孔对齐,请在组件管理中重新确认");
if (orientationError > tolerance.planeAngleRad() + 1e-10)
throw new IllegalArgumentException("已保存姿态的橙色前方方向无法同向,请在组件管理中重新选择安装姿态");
List<HolePair> pairs = new ArrayList<>();
for (int i=0;i<b.holes().size();i++) pairs.add(new HolePair(a.holes().get(match.indices()[i]).id(), b.holes().get(i).id()));
return new ResolvedConnection(parent.linkName(),child.linkName(),transform,List.copyOf(pairs),
match.maximum(),match.axisMaximum(),planeOffset,orientationError);
}
private int side(Port port,double[] templateNormal) {
return dot(rotate(rotation(port.selectedPose().templateInLink()),templateNormal),
unit(port.geometryInLink().plane().outwardNormal())) >= 0 ? 1 : -1;
}
private List<PoseCandidate> enumerate(MountGeometry source, MountGeometry target, Tolerances tolerance,
int side, String fingerprint) {
List<Hole> s=source.holes(), t=target.holes();
if(s.size()!=t.size())return List.of();
// A well-separated anchor pair avoids unstable angle estimates for close holes.
int first=0, second=1; double span=0;
for(int i=0;i<s.size();i++)for(int j=i+1;j<s.size();j++){
double distance=norm(sub(s.get(j).pointOnPlaneM(),s.get(i).pointOnPlaneM()));
if(distance>span){span=distance;first=i;second=j;}
}
double[] sourceBasis=basis(source.plane().outwardNormal(),sub(s.get(second).pointOnPlaneM(),s.get(first).pointOnPlaneM()));
double[] targetNormal=scale(target.plane().outwardNormal(),side);
Map<String,PoseCandidate> mappings=new TreeMap<>();
for(int i=0;i<t.size();i++)for(int j=0;j<t.size();j++){
if(i==j)continue;
double[] direction=sub(t.get(j).pointOnPlaneM(),t.get(i).pointOnPlaneM());
if(Math.abs(norm(direction)-span)>2*tolerance.positionM()+1e-10)continue;
double[] r=multiply(basis(targetNormal,direction),transpose(sourceBasis));
RigidPose pose=pose(sub(t.get(i).pointOnPlaneM(),rotate(r,s.get(first).pointOnPlaneM())),r);
Match rough=assignment(s,t,pose,tolerance,4);
if(rough==null)continue;
for(int iteration=0;iteration<3;iteration++){
pose=refine(s,t,rough.indices(),pose,targetNormal);
Match next=assignment(s,t,pose,tolerance,4);
if(next==null)break;
rough=next;
}
Match match=assignment(s,t,pose,tolerance,1);
if(match==null)continue;
double offset=Math.abs(dot(sub(point(pose,source.plane().pointM()),target.plane().pointM()),unit(targetNormal)));
if(offset>tolerance.positionM()+1e-10)continue;
List<HoleMapping> mapping=new ArrayList<>();
StringJoiner key=new StringJoiner("|");
for(int k=0;k<s.size();k++){
String targetId=t.get(match.indices()[k]).id();
mapping.add(new HoleMapping(s.get(k).id(),targetId));key.add(s.get(k).id()+"="+targetId);
}
double[] orientationDirection = unit(sub(
t.get(match.indices()[second]).pointOnPlaneM(),
t.get(match.indices()[first]).pointOnPlaneM()));
String mapKey=key.toString();
PoseCandidate candidate=new PoseCandidate(hash(SOLVER_VERSION+':'+fingerprint+':'+side+':'+mapKey),pose,
List.copyOf(mapping),orientationDirection,side,match.maximum(),match.rms(),match.axisMaximum());
PoseCandidate old=mappings.get(mapKey);
if(old==null||candidate.maxHoleOffsetM()<old.maxHoleOffsetM())mappings.put(mapKey,candidate);
}
List<PoseCandidate> unique=new ArrayList<>();
for(PoseCandidate candidate:mappings.values()){
boolean duplicate=unique.stream().anyMatch(old -> samePose(old.templateInLink(),candidate.templateInLink()));
if(!duplicate)unique.add(candidate);
}
return List.copyOf(unique);
}
private RigidPose refine(List<Hole> s,List<Hole> t,int[] indices,RigidPose current,double[] normal){
double[] sc=new double[3],tc=new double[3];
for(int i=0;i<s.size();i++){sc=add(sc,s.get(i).pointOnPlaneM());tc=add(tc,t.get(indices[i]).pointOnPlaneM());}
sc=scale(sc,1.0/s.size());tc=scale(tc,1.0/s.size());
double[] r=rotation(current);double cosine=0,sine=0;
for(int i=0;i<s.size();i++){
double[] a=rotate(r,sub(s.get(i).pointOnPlaneM(),sc)),b=sub(t.get(indices[i]).pointOnPlaneM(),tc);
cosine+=dot(a,b);sine+=dot(unit(normal),cross(a,b));
}
r=multiply(rotationAxis(normal,Math.atan2(sine,cosine)),r);
return pose(sub(tc,rotate(r,sc)),r);
}
private Match assignment(List<Hole> source,List<Hole> target,RigidPose pose,Tolerances tol,double allowance){
int n=source.size();if(n!=target.size())return null;
double limit=tol.positionM()*allowance,angleLimit=tol.axisAngleRad()*allowance;
double penalty=4*n+1;double[][] costs=new double[n][n],distances=new double[n][n],angles=new double[n][n];
double[] r=rotation(pose);
for(int i=0;i<n;i++)for(int j=0;j<n;j++){
double d=norm(sub(point(pose,source.get(i).pointOnPlaneM()),target.get(j).pointOnPlaneM()));
double a=angle(rotate(r,source.get(i).axis()),target.get(j).axis(),true);
distances[i][j]=d;angles[i][j]=a;
costs[i][j]=d>limit+1e-10||a>angleLimit+1e-10?penalty:d*d/(limit*limit)+a*a/(angleLimit*angleLimit);
}
int[] indices=minimumCostAssignment(costs);double max=0,sum=0,axis=0;
for(int i=0;i<n;i++){int j=indices[i];if(costs[i][j]>=penalty)return null;
max=Math.max(max,distances[i][j]);sum+=distances[i][j]*distances[i][j];axis=Math.max(axis,angles[i][j]);}
return new Match(indices,max,Math.sqrt(sum/n),axis);
}
/** Finite forbidden-edge penalty exceeds every possible all-valid assignment. */
static int[] minimumCostAssignment(double[][] costs){
int n=costs.length;double[] u=new double[n+1],v=new double[n+1];int[] p=new int[n+1],way=new int[n+1];
for(int i=1;i<=n;i++){p[0]=i;int j0=0;double[] min=new double[n+1];Arrays.fill(min,Double.POSITIVE_INFINITY);boolean[] used=new boolean[n+1];
do{used[j0]=true;int i0=p[j0],j1=0;double delta=Double.POSITIVE_INFINITY;
for(int j=1;j<=n;j++)if(!used[j]){double cur=costs[i0-1][j-1]-u[i0]-v[j];if(cur<min[j]){min[j]=cur;way[j]=j0;}if(min[j]<delta){delta=min[j];j1=j;}}
for(int j=0;j<=n;j++){if(used[j]){u[p[j]]+=delta;v[j]-=delta;}else min[j]-=delta;}j0=j1;
}while(p[j0]!=0);
do{int j1=way[j0];p[j0]=p[j1];j0=j1;}while(j0!=0);
}
int[] result=new int[n];for(int j=1;j<=n;j++)result[p[j]-1]=j-1;return result;
}
public MountGeometry normalize(MountGeometry geometry,Tolerances tolerance){
if(geometry==null||geometry.plane()==null||geometry.holes()==null||geometry.holes().size()<2)
throw new IllegalArgumentException("接口需要一个安装面和至少两个不同孔位");
double[] origin=vec(geometry.plane().pointM()).clone(), normal=unit(geometry.plane().outwardNormal());
List<Hole> holes=new ArrayList<>();Set<String> ids=new HashSet<>();
for(Hole hole:geometry.holes()){
if(hole==null||blank(hole.id())||!ids.add(hole.id()))throw new IllegalArgumentException("孔 ID 缺失或重复");
double[] p=vec(hole.pointOnPlaneM()),axis=unit(hole.axis());
double offset=dot(sub(p,origin),normal),denominator=dot(axis,normal);
if(Math.abs(offset)>tolerance.positionM()+1e-10||Math.abs(denominator)<1e-6)throw new IllegalArgumentException("孔 " + hole.id() + ":孔轴必须穿过安装面且孔位在安装面上");
if(hole.diameterM()!=null&&(!Double.isFinite(hole.diameterM())||hole.diameterM()<=0))throw new IllegalArgumentException("孔径必须为正数");
double[] intersection=sub(p,scale(axis,offset/denominator));
for(Hole previous:holes)if(norm(sub(previous.pointOnPlaneM(),intersection))<1e-8)throw new IllegalArgumentException("存在重复孔轴,请先归并沉孔和通孔边");
holes.add(new Hole(hole.id(),intersection,axis,hole.diameterM()));
}
holes.sort(Comparator.comparing(Hole::id));return new MountGeometry(new Plane(origin,normal),List.copyOf(holes));
}
private void tolerances(Tolerances t){
if(t==null||!Double.isFinite(t.positionM())||t.positionM()<=0||!Double.isFinite(t.axisAngleRad())||t.axisAngleRad()<=0||t.axisAngleRad()>=Math.PI/2
||!Double.isFinite(t.planeAngleRad())||t.planeAngleRad()<=0||t.planeAngleRad()>=Math.PI/2)throw new IllegalArgumentException("接口容差不合法");
}
private boolean samePose(RigidPose a,RigidPose b){
if(norm(sub(a.positionM(),b.positionM()))>1e-8)return false;double[] r=multiply(transpose(rotation(a)),rotation(b));
return Math.acos(Math.max(-1,Math.min(1,(r[0]+r[4]+r[8]-1)/2)))<1e-6;
}
private String fingerprint(MountGeometry g){
StringBuilder s=new StringBuilder(stableNumbers(g.plane().pointM())).append(stableNumbers(g.plane().outwardNormal()));
for(Hole h:g.holes())s.append(h.id().length()).append(':').append(h.id()).append(stableNumbers(h.pointOnPlaneM())).append(stableNumbers(h.axis())).append(h.diameterM());
return hash(s.toString());
}
// Normalize floating-point noise in identity encoding only, never in the solver calculation chain.
private String stableNumbers(double[] values){return Arrays.toString(Arrays.stream(values).map(v->{double n=Math.rint(v*1e12)/1e12;return n==0?0:n;}).toArray());}
private String hash(String input){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(input.getBytes(StandardCharsets.UTF_8)));}
catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);}}
private boolean blank(String value){return value==null||value.isBlank();}
private CandidateSet rejected(String reason){return new CandidateSet(SOLVER_VERSION,List.of(),List.of(reason));}
}
@@ -0,0 +1,53 @@
package com.linkerbot.cadworld.mechanicalinterface;
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
/** Small rigid-transform kernel: row-major rotation, column vectors, no Euler angles. */
public final class RigidMath {
private RigidMath() {}
public static double[] vec(double[] a) {
if (a == null || a.length != 3) throw new IllegalArgumentException("需要三个有限坐标");
for (double v : a) if (!Double.isFinite(v)) throw new IllegalArgumentException("坐标必须为有限数值");
return a;
}
public static double[] add(double[] a, double[] b) { return new double[]{a[0]+b[0],a[1]+b[1],a[2]+b[2]}; }
public static double[] sub(double[] a, double[] b) { return new double[]{a[0]-b[0],a[1]-b[1],a[2]-b[2]}; }
public static double[] scale(double[] a, double s) { return new double[]{a[0]*s,a[1]*s,a[2]*s}; }
public static double dot(double[] a,double[] b) { return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; }
public static double norm(double[] a) { return Math.sqrt(dot(a,a)); }
public static double[] unit(double[] a) { vec(a); double n=norm(a); if(n<1e-12) throw new IllegalArgumentException("法向/孔轴不能为零向量"); return scale(a,1/n); }
public static double[] cross(double[] a,double[] b) { return new double[]{a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]}; }
public static double angle(double[] a,double[] b,boolean unoriented) { double d=dot(unit(a),unit(b)); return Math.acos(Math.max(-1,Math.min(1,unoriented?Math.abs(d):d))); }
public static double[] rotate(double[] r,double[] p) { return new double[]{r[0]*p[0]+r[1]*p[1]+r[2]*p[2],r[3]*p[0]+r[4]*p[1]+r[5]*p[2],r[6]*p[0]+r[7]*p[1]+r[8]*p[2]}; }
public static double[] transpose(double[] r) { return new double[]{r[0],r[3],r[6],r[1],r[4],r[7],r[2],r[5],r[8]}; }
public static double[] multiply(double[] a,double[] b) { double[] r=new double[9]; for(int i=0;i<3;i++)for(int j=0;j<3;j++)for(int k=0;k<3;k++)r[i*3+j]+=a[i*3+k]*b[k*3+j]; return r; }
public static double[] basis(double[] z,double[] direction) {
z=unit(z); double[] x=unit(sub(direction,scale(z,dot(direction,z)))); double[] y=cross(z,x);
return new double[]{x[0],y[0],z[0],x[1],y[1],z[1],x[2],y[2],z[2]};
}
public static double[] rotationAxis(double[] axis,double angle) {
double[] a=unit(axis); double s=Math.sin(angle/2), c=Math.cos(angle/2);
return rotation(new RigidPose(new double[3],new double[]{a[0]*s,a[1]*s,a[2]*s,c}));
}
public static double[] rotation(RigidPose p) {
if(p==null)throw new IllegalArgumentException("缺少刚体位姿"); vec(p.positionM());
double[] q=p.quaternionXYZW(); if(q==null||q.length!=4)throw new IllegalArgumentException("四元数必须使用 XYZW");
double n=0; for(double v:q){ if(!Double.isFinite(v))throw new IllegalArgumentException("四元数必须有限"); n+=v*v; }
if(Math.abs(n-1)>1e-6)throw new IllegalArgumentException("必须使用单位四元数");
double x=q[0],y=q[1],z=q[2],w=q[3];
return new double[]{1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w),2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w),2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)};
}
public static RigidPose pose(double[] t,double[] r) {
double x,y,z,w, trace=r[0]+r[4]+r[8];
if(trace>0){double s=Math.sqrt(trace+1)*2;w=s/4;x=(r[7]-r[5])/s;y=(r[2]-r[6])/s;z=(r[3]-r[1])/s;}
else if(r[0]>r[4]&&r[0]>r[8]){double s=Math.sqrt(1+r[0]-r[4]-r[8])*2;w=(r[7]-r[5])/s;x=s/4;y=(r[1]+r[3])/s;z=(r[2]+r[6])/s;}
else if(r[4]>r[8]){double s=Math.sqrt(1+r[4]-r[0]-r[8])*2;w=(r[2]-r[6])/s;x=(r[1]+r[3])/s;y=s/4;z=(r[5]+r[7])/s;}
else{double s=Math.sqrt(1+r[8]-r[0]-r[4])*2;w=(r[3]-r[1])/s;x=(r[2]+r[6])/s;y=(r[5]+r[7])/s;z=s/4;}
double n=Math.sqrt(x*x+y*y+z*z+w*w); if(w<0)n=-n;
return new RigidPose(t.clone(),new double[]{x/n,y/n,z/n,w/n});
}
public static RigidPose identity() { return new RigidPose(new double[3],new double[]{0,0,0,1}); }
public static RigidPose compose(RigidPose a,RigidPose b) { double[] r=rotation(a); return pose(add(a.positionM(),rotate(r,b.positionM())),multiply(r,rotation(b))); }
public static RigidPose inverse(RigidPose a) { double[] r=transpose(rotation(a));return pose(scale(rotate(r,a.positionM()),-1),r); }
public static double[] point(RigidPose a,double[] p) { return add(a.positionM(),rotate(rotation(a),p)); }
}
@@ -0,0 +1,39 @@
package com.linkerbot.cadworld.mechanicalinterface;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
import java.io.OutputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
/** Hash stored bytes, not a digest supplied by the browser. No remote URLs are fetched. */
@Service @RequiredArgsConstructor
public class UrdfAssetVerifier {
private final ObjectStorageClient storage;
public void verify(JsonNode source) {
Map<String,String> checked = new HashMap<>();
for (JsonNode resource : source.path("resources")) {
String key=resource.path("sourceKey").asText(), expected=resource.path("sha256").asText();
if (key.isBlank() || key.startsWith("/") || key.contains(":") || key.contains("\\")
|| java.util.Arrays.asList(key.split("/")).contains(".."))
throw new IllegalArgumentException("URDF 资源必须引用已上传的存储对象");
try {
String digest=checked.get(key);
if(digest==null) {
MessageDigest sha=MessageDigest.getInstance("SHA-256");
try (DigestOutputStream sink=new DigestOutputStream(OutputStream.nullOutputStream(),sha)) {
storage.writeObjectTo(key,sink);
}
digest=HexFormat.of().formatHex(sha.digest()); checked.put(key,digest);
}
if(!expected.equals(digest)) throw new IllegalArgumentException("原始资源已变化,请重新识别:"+resource.path("reference").asText());
} catch (IllegalArgumentException e) { throw e; }
catch (Exception e) { throw new IllegalArgumentException("原始 URDF 资源无法验证:"+resource.path("reference").asText(),e); }
}
}
}
@@ -0,0 +1,67 @@
package com.linkerbot.cadworld.mechanicalinterface;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.springframework.stereotype.Service;
/** Validates immutable source identity and the link-local coordinate contract. */
@Service
public class UrdfSourceValidation {
public Set<String> validate(JsonNode source) {
if (source == null || !source.isObject()) throw new IllegalArgumentException("缺少原始 URDF 快照,请重新上传");
String xml = source.path("xml").asText();
String documentHash = hash(xml);
if (!documentHash.equals(source.path("documentHash").asText())) throw new IllegalArgumentException("原始 URDF 哈希不一致");
JsonNode resources = source.path("resources");
if (!resources.isArray()) throw new IllegalArgumentException("缺少 URDF 资源清单");
SortedMap<String,String> hashes = new TreeMap<>();
for (JsonNode resource : resources) {
String reference = resource.path("reference").asText();
String digest = resource.path("sha256").asText();
if (reference.isBlank() || reference.contains("\n") || reference.contains("\t")
|| !digest.matches("[a-f0-9]{64}") || resource.path("sourceKey").asText().isBlank()
|| hashes.putIfAbsent(reference,digest) != null)
throw new IllegalArgumentException("URDF 资源清单不完整或存在重复引用");
}
String manifest = String.join("\n", hashes.entrySet().stream().map(e -> e.getKey()+"\t"+e.getValue()).toList());
if (!hash(documentHash+"\n"+manifest).equals(source.path("sourceGeometryHash").asText()))
throw new IllegalArgumentException("源几何哈希已变化,请重新识别接口");
try {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
factory.setFeature("http://xml.org/sax/features/external-general-entities",false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities",false);
factory.setXIncludeAware(false);factory.setExpandEntityReferences(false);
Element robot=factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
if (!"robot".equals(robot.getTagName())) throw new IllegalArgumentException("URDF 根节点必须是 robot");
Set<String> links=new HashSet<>(), children=new HashSet<>(), joints=new HashSet<>();
Map<String,String> parents=new HashMap<>();
for (var n=robot.getFirstChild(); n!=null; n=n.getNextSibling()) if(n instanceof Element e && "link".equals(e.getTagName())) {
if(e.getAttribute("name").isBlank() || !links.add(e.getAttribute("name"))) throw new IllegalArgumentException("URDF link 名称缺失或重复");
}
for (var n=robot.getFirstChild(); n!=null; n=n.getNextSibling()) if(n instanceof Element e && "joint".equals(e.getTagName())) {
if(e.getAttribute("name").isBlank() || !joints.add(e.getAttribute("name"))) throw new IllegalArgumentException("URDF joint 名称缺失或重复");
String parent=linkAttribute(e,"parent"), child=linkAttribute(e,"child");
if(!links.contains(parent)||!links.contains(child)||!children.add(child)) throw new IllegalArgumentException("URDF 父子 link 不存在或存在多父连接");
parents.put(child,parent);
}
if(links.size()-children.size()!=1) throw new IllegalArgumentException("URDF 必须只有一个根 link");
for(String link:links){Set<String> visited=new HashSet<>();String node=link;while(node!=null){if(!visited.add(node))throw new IllegalArgumentException("URDF 存在环");node=parents.get(node);}}
for(String tag:List.of("mesh","texture")) {
NodeList nodes=robot.getElementsByTagName(tag);
for(int i=0;i<nodes.getLength();i++)if(!hashes.containsKey(((Element)nodes.item(i)).getAttribute("filename")))throw new IllegalArgumentException("URDF 资源清单遗漏引用");
}
return Set.copyOf(links);
} catch (IllegalArgumentException e) { throw e; }
catch (Exception e) { throw new IllegalArgumentException("原始 URDF 无法解析",e); }
}
private String linkAttribute(Element joint,String tag){NodeList list=joint.getElementsByTagName(tag);if(list.getLength()!=1)throw new IllegalArgumentException("URDF joint 缺少父子连接");return ((Element)list.item(0)).getAttribute("link");}
public static String hash(String text){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}}
}
@@ -0,0 +1,15 @@
package com.linkerbot.cadworld.service;
import com.linkerbot.cadworld.config.AdminOperatorProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/** A configured test identity, to be replaced when account authentication is enabled. */
@Component
@RequiredArgsConstructor
public class AdminOperatorProvider {
private final AdminOperatorProperties properties;
public Long userId() { return properties.id(); }
public String name() { return properties.name(); }
}
@@ -0,0 +1,16 @@
package com.linkerbot.cadworld.service;
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadRequest;
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
public interface ComponentCoverImageUploadService {
PrepareCoverImageUploadSessionResponse prepareUploadSession(Long userId);
PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request);
CompleteCoverImageUploadResponse completeUploadSession(Long userId, CompleteCoverImageUploadRequest request);
}
@@ -0,0 +1,20 @@
package com.linkerbot.cadworld.service;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.dto.component.ComponentListItemResponse;
import com.linkerbot.cadworld.dto.component.ComponentResponse;
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
public interface ComponentService {
ComponentResponse createComponent(Long userId, CreateComponentRequest request);
PageResponse<ComponentListItemResponse> listComponents(long page, long size, String keyword);
ComponentResponse getComponent(Long id);
ComponentResponse updateComponent(Long userId, Long id, UpdateComponentRequest request);
void deleteComponent(Long userId, Long id);
}
@@ -0,0 +1,16 @@
package com.linkerbot.cadworld.service;
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
public interface ComponentUrdfUploadService {
PrepareUrdfUploadSessionResponse prepareUploadSession(Long userId);
PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request);
CompleteUrdfUploadResponse completeUploadSession(Long userId, CompleteUrdfUploadRequest request);
}
@@ -0,0 +1,142 @@
package com.linkerbot.cadworld.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.cadworld.common.exception.BizException;
import com.linkerbot.cadworld.config.InterfaceBrepProperties;
import com.linkerbot.cadworld.common.process.ToolProcess;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
@RequiredArgsConstructor
public class InterfaceBrepService {
private final InterfaceBrepProperties properties;
private final ObjectMapper objectMapper;
public JsonNode analyze(MultipartFile file) {
validate(file);
Path temporaryDirectory = null;
try {
temporaryDirectory = Files.createTempDirectory("interface-brep-");
String suffix = extension(file.getOriginalFilename());
Path input = temporaryDirectory.resolve("source" + suffix);
Path output = temporaryDirectory.resolve("topology.json");
file.transferTo(input);
Path script = resolveScript(temporaryDirectory);
if (!Files.isRegularFile(script)) {
throw unavailable("STEP B-Rep 提取脚本不存在:" + script);
}
List<String> command = List.of(
properties.python(),
script.toString(),
input.toString(),
"--output",
output.toString(),
"--max-output-bytes",
Long.toString(properties.maxOutputBytes())
);
var result = new ToolProcess().run(
command,
script.getParent(),
Duration.ofSeconds(properties.timeoutSeconds())
);
if (result.timedOut()) {
throw new BizException(504, "INTERFACE_BREP_TIMEOUT",
"STEP 精确 B-Rep 解析超时,请拆分过大的装配 STEP 后重试。");
}
if (result.exitCode() != 0) {
String detail = result.output().replace("STEP_BREP_ERROR:", "").trim();
if (detail.contains("No module named 'OCP'")) {
throw unavailable("服务器未安装 OCCT Python 运行库,无法进行精确 B-Rep 解析。");
}
throw new BizException(422, "INTERFACE_BREP_INVALID_STEP",
detail.isBlank() ? "STEP 文件无法提取精确 B-Rep 拓扑。" : detail);
}
if (!Files.isRegularFile(output)) {
throw unavailable("STEP B-Rep 提取器未生成拓扑结果。");
}
long outputSize = Files.size(output);
if (outputSize <= 0 || outputSize > properties.maxOutputBytes()) {
throw new BizException(413, "INTERFACE_BREP_OUTPUT_TOO_LARGE",
"STEP B-Rep 结果过大,请上传单个组件或拆分后的 STEP。");
}
JsonNode topology = objectMapper.readTree(output.toFile());
if (!"interface-step-brep/v1".equals(topology.path("schemaVersion").asText())) {
throw unavailable("STEP B-Rep 提取器返回了不支持的数据版本。");
}
return topology;
} catch (BizException exception) {
throw exception;
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw unavailable("STEP B-Rep 解析被中断。");
} catch (IOException exception) {
throw unavailable("STEP B-Rep 解析服务不可用:" + exception.getMessage());
} finally {
deleteRecursively(temporaryDirectory);
}
}
private void validate(MultipartFile file) {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("请选择 STEP 或 STP 文件。");
}
String suffix = extension(file.getOriginalFilename());
if (!suffix.equals(".step") && !suffix.equals(".stp")) {
throw new IllegalArgumentException("接口模型只支持 STEP 或 STP;不再接受 STL。");
}
if (file.getSize() > properties.maxUploadBytes()) {
throw new BizException(413, "INTERFACE_BREP_UPLOAD_TOO_LARGE",
"STEP 文件超过接口 B-Rep 分析大小限制。");
}
}
private Path resolveScript(Path temporaryDirectory) throws IOException {
String configured = properties.script();
if (configured.startsWith("classpath:")) {
String resource = configured.substring("classpath:".length());
try (var input = new org.springframework.core.io.ClassPathResource(resource).getInputStream()) {
Path extracted = temporaryDirectory.resolve("step_brep_topology.py");
Files.copy(input, extracted);
return extracted;
}
}
return Path.of(configured).toAbsolutePath().normalize();
}
private static String extension(String fileName) {
if (fileName == null) return "";
String lower = fileName.toLowerCase(Locale.ROOT);
if (lower.endsWith(".step")) return ".step";
if (lower.endsWith(".stp")) return ".stp";
return "";
}
private static BizException unavailable(String message) {
return new BizException(503, "INTERFACE_BREP_UNAVAILABLE", message);
}
private static void deleteRecursively(Path directory) {
if (directory == null || !Files.exists(directory)) return;
try (var paths = Files.walk(directory)) {
paths.sorted((left, right) -> right.compareTo(left)).forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException ignored) {
// Temporary analysis files are best-effort cleanup only.
}
});
} catch (IOException ignored) {
// The request result must not be replaced by a cleanup failure.
}
}
}
@@ -0,0 +1,14 @@
package com.linkerbot.cadworld.service;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
public interface InterfaceDefinitionService {
List<JsonNode> list(String keyword);
JsonNode get(String id);
JsonNode create(JsonNode request);
JsonNode update(String id, JsonNode request);
void delete(String id);
void attachAsset(String definitionId, int geometryRevision, String objectKey, String sha256);
com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.Definition geometryDefinition(String id, int revision);
}
@@ -0,0 +1,44 @@
package com.linkerbot.cadworld.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.common.exception.BizException;
import com.linkerbot.cadworld.entity.OperationLog;
import com.linkerbot.cadworld.mapper.OperationLogMapper;
import java.time.LocalDateTime;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
@Service
@RequiredArgsConstructor
public class OperationLogService {
private final OperationLogMapper mapper;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(OperationLog log) { mapper.insert(log); }
public PageResponse<OperationLog> list(long page, long size, String module, String action, Boolean success,
Long operatorId, LocalDateTime from, LocalDateTime to) {
if (from != null && to != null && from.isAfter(to)) throw new IllegalArgumentException("开始时间不能晚于结束时间");
LambdaQueryWrapper<OperationLog> query = new LambdaQueryWrapper<OperationLog>()
.eq(StringUtils.hasText(module), OperationLog::getModule, module)
.eq(StringUtils.hasText(action), OperationLog::getAction, action)
.eq(success != null, OperationLog::getSuccess, success)
.eq(operatorId != null, OperationLog::getOperatorId, operatorId)
.ge(from != null, OperationLog::getOperatedAt, from)
.le(to != null, OperationLog::getOperatedAt, to)
.orderByDesc(OperationLog::getOperatedAt).orderByDesc(OperationLog::getId);
Page<OperationLog> result = mapper.selectPage(new Page<>(page, size), query);
return new PageResponse<>(result.getRecords(), page, size, result.getTotal());
}
public OperationLog get(Long id) {
OperationLog log = mapper.selectById(id);
if (log == null) throw new BizException(404, "OPERATION_LOG_NOT_FOUND", "操作日志不存在");
return log;
}
}
@@ -0,0 +1,15 @@
package com.linkerbot.cadworld.service;
import com.linkerbot.cadworld.common.api.PageResponse;
import com.linkerbot.cadworld.dto.user.SaveUserRequest;
import com.linkerbot.cadworld.dto.user.UserResponse;
import com.linkerbot.cadworld.enums.UserStatus;
import com.linkerbot.cadworld.enums.UserType;
public interface UserManagementService {
PageResponse<UserResponse> list(long page, long size, String keyword, UserType userType, UserStatus status);
UserResponse get(Long id);
UserResponse create(SaveUserRequest request);
UserResponse update(Long id, SaveUserRequest request);
void delete(Long id);
}

Some files were not shown because too many files have changed in this diff Show More