> 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, "系统异常"));
+ }
+}
diff --git a/cadworld-common/src/main/java/com/linkerbot/cadworld/common/mybatis/JsonNodeTypeHandler.java b/cadworld-common/src/main/java/com/linkerbot/cadworld/common/mybatis/JsonNodeTypeHandler.java
new file mode 100644
index 0000000..624951f
--- /dev/null
+++ b/cadworld-common/src/main/java/com/linkerbot/cadworld/common/mybatis/JsonNodeTypeHandler.java
@@ -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 持久化处理器。
+ *
+ * 显式按字符串写入 JSON,可以同时兼容 MySQL JSON 列和测试环境中的 CLOB/VARCHAR,
+ * 避免不同 JDBC 驱动把 JsonNode 当成 JAVA_OBJECT 处理。
+ */
+public class JsonNodeTypeHandler extends BaseTypeHandler {
+
+ 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);
+ }
+ }
+}
diff --git a/cadworld-common/src/main/java/com/linkerbot/cadworld/common/process/ToolProcess.java b/cadworld-common/src/main/java/com/linkerbot/cadworld/common/process/ToolProcess.java
new file mode 100644
index 0000000..a6ab146
--- /dev/null
+++ b/cadworld-common/src/main/java/com/linkerbot/cadworld/common/process/ToolProcess.java
@@ -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 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();}
+}
diff --git a/cadworld-common/src/main/java/com/linkerbot/cadworld/common/web/RequestIdFilter.java b/cadworld-common/src/main/java/com/linkerbot/cadworld/common/web/RequestIdFilter.java
new file mode 100644
index 0000000..138a89b
--- /dev/null
+++ b/cadworld-common/src/main/java/com/linkerbot/cadworld/common/web/RequestIdFilter.java
@@ -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");
+ }
+ }
+}
diff --git a/cadworld-common/src/main/resources/logback-spring.xml b/cadworld-common/src/main/resources/logback-spring.xml
new file mode 100644
index 0000000..8bb85be
--- /dev/null
+++ b/cadworld-common/src/main/resources/logback-spring.xml
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+
+
+
+ ${LOG_PATTERN}
+ UTF-8
+
+
+
+
+ ${LOG_PATH}/${APP_NAME}.log
+
+ ${LOG_PATTERN}
+ UTF-8
+
+
+ ${LOG_PATH}/archive/${APP_NAME}.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz
+ 100MB
+ 30
+ 10GB
+
+
+
+
+ ${LOG_PATH}/${APP_NAME}-error.log
+
+ ERROR
+
+
+ ${LOG_PATTERN}
+ UTF-8
+
+
+ ${LOG_PATH}/archive/${APP_NAME}-error.%d{yyyy-MM-dd,Asia/Shanghai}.%i.log.gz
+ 50MB
+ 60
+ 5GB
+
+
+
+
+
+
+
+
+
diff --git a/cadworld-security/cadworld-security-admin/pom.xml b/cadworld-security/cadworld-security-admin/pom.xml
new file mode 100644
index 0000000..bcd08a8
--- /dev/null
+++ b/cadworld-security/cadworld-security-admin/pom.xml
@@ -0,0 +1,17 @@
+
+
+ 4.0.0
+
+
+ com.linkerbot
+ cadworld-security
+ 0.0.1-SNAPSHOT
+ ../pom.xml
+
+
+ cadworld-security-admin
+ jar
+ cadworld-security-admin
+
diff --git a/cadworld-security/cadworld-security-api/pom.xml b/cadworld-security/cadworld-security-api/pom.xml
new file mode 100644
index 0000000..8f33967
--- /dev/null
+++ b/cadworld-security/cadworld-security-api/pom.xml
@@ -0,0 +1,17 @@
+
+
+ 4.0.0
+
+
+ com.linkerbot
+ cadworld-security
+ 0.0.1-SNAPSHOT
+ ../pom.xml
+
+
+ cadworld-security-api
+ jar
+ cadworld-security-api
+
diff --git a/cadworld-security/cadworld-security-common/pom.xml b/cadworld-security/cadworld-security-common/pom.xml
new file mode 100644
index 0000000..d608248
--- /dev/null
+++ b/cadworld-security/cadworld-security-common/pom.xml
@@ -0,0 +1,17 @@
+
+
+ 4.0.0
+
+
+ com.linkerbot
+ cadworld-security
+ 0.0.1-SNAPSHOT
+ ../pom.xml
+
+
+ cadworld-security-common
+ jar
+ cadworld-security-common
+
diff --git a/cadworld-security/pom.xml b/cadworld-security/pom.xml
new file mode 100644
index 0000000..635542d
--- /dev/null
+++ b/cadworld-security/pom.xml
@@ -0,0 +1,23 @@
+
+
+ 4.0.0
+
+
+ com.linkerbot
+ cadworld
+ 0.0.1-SNAPSHOT
+ ../pom.xml
+
+
+ cadworld-security
+ pom
+ cadworld-security
+
+
+ cadworld-security-admin
+ cadworld-security-api
+ cadworld-security-common
+
+
diff --git a/cadworld-service/pom.xml b/cadworld-service/pom.xml
new file mode 100644
index 0000000..daf6602
--- /dev/null
+++ b/cadworld-service/pom.xml
@@ -0,0 +1,51 @@
+
+
+ 4.0.0
+
+
+ com.linkerbot
+ cadworld
+ 0.0.1-SNAPSHOT
+ ../pom.xml
+
+
+ cadworld-service
+ jar
+ cadworld-service
+
+
+
+ com.linkerbot
+ cadworld-bean
+ ${project.version}
+
+
+ com.baomidou
+ mybatis-plus-spring-boot3-starter
+
+
+ com.baomidou
+ mybatis-plus-jsqlparser
+
+
+ io.minio
+ minio
+
+
+ io.jsonwebtoken
+ jjwt-api
+
+
+ io.jsonwebtoken
+ jjwt-impl
+ runtime
+
+
+ io.jsonwebtoken
+ jjwt-jackson
+ runtime
+
+
+
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/AdminOperatorProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/AdminOperatorProperties.java
new file mode 100644
index 0000000..0d68826
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/AdminOperatorProperties.java
@@ -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) {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/InterfaceBrepProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/InterfaceBrepProperties.java
new file mode 100644
index 0000000..23354ab
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/InterfaceBrepProperties.java
@@ -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
+) {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MinioProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MinioProperties.java
new file mode 100644
index 0000000..903b52b
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MinioProperties.java
@@ -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
+) {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MybatisPlusConfig.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MybatisPlusConfig.java
new file mode 100644
index 0000000..a2eb629
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/MybatisPlusConfig.java
@@ -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);
+ }
+ };
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/StorageProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/StorageProperties.java
new file mode 100644
index 0000000..e9dc0a6
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/StorageProperties.java
@@ -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);
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/config/UploadSessionProperties.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/UploadSessionProperties.java
new file mode 100644
index 0000000..494f741
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/config/UploadSessionProperties.java
@@ -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) {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/ComponentAssetMapper.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/ComponentAssetMapper.java
new file mode 100644
index 0000000..f673ea6
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/ComponentAssetMapper.java
@@ -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 {}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/ComponentMapper.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/ComponentMapper.java
new file mode 100644
index 0000000..26dff90
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/ComponentMapper.java
@@ -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 {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/InterfaceDefinitionMapper.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/InterfaceDefinitionMapper.java
new file mode 100644
index 0000000..d97bc94
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/InterfaceDefinitionMapper.java
@@ -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 {}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/InterfaceDefinitionRevisionMapper.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/InterfaceDefinitionRevisionMapper.java
new file mode 100644
index 0000000..f6ebbfc
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/InterfaceDefinitionRevisionMapper.java
@@ -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 {}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/OperationLogMapper.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/OperationLogMapper.java
new file mode 100644
index 0000000..3967b39
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/OperationLogMapper.java
@@ -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 {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/SysUserMapper.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/SysUserMapper.java
new file mode 100644
index 0000000..df7736d
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mapper/SysUserMapper.java
@@ -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 {
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/ComponentPortValidationService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/ComponentPortValidationService.java
new file mode 100644
index 0000000..e7aff8e
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/ComponentPortValidationService.java
@@ -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 links=interfaces.isEmpty()?Set.of():sourceValidation.validate(result.get("urdfSource"));
+ if(!interfaces.isEmpty())assetVerifier.verify(result.get("urdfSource"));
+ ArrayNode confirmed=mapper.createArrayNode();Set 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();}
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/InterfaceGeometry.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/InterfaceGeometry.java
new file mode 100644
index 0000000..f7eebcc
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/InterfaceGeometry.java
@@ -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 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 connectableTargets, double[] displayForward) {
+ public Definition(String id, int geometryRevision, String name, MountGeometry geometry, Tolerances tolerances,
+ List 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,
+ double[] orientationDirectionInLink) {}
+ public record Port(String id, String linkName, String definitionId, int definitionRevision,
+ MountGeometry geometryInLink, SelectedPose selectedPose,
+ String sourceGeometryHash, String solverVersion, List 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,
+ double[] orientationDirectionInLink, int registrationSide,
+ double maxHoleOffsetM, double rmsHoleOffsetM, double maxAxisAngleRad) {}
+ public record CandidateSet(String solverVersion, List candidates, List reasons) {}
+ public record HolePair(String parentHoleId, String childHoleId) {}
+ public record ResolvedConnection(String parentLinkName, String childLinkName, RigidPose childLinkInParentLink,
+ List holePairs, double maxHoleOffsetM, double maxAxisAngleRad,
+ double planeOffsetM, double orientationAngleRad) {}
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/MechanicalInterfaceSolver.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/MechanicalInterfaceSolver.java
new file mode 100644
index 0000000..e209618
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/MechanicalInterfaceSolver.java
@@ -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 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 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 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 normalizeTargets(List 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 mateCandidates = List.of(identity());
+ if (parentSide == childSide) {
+ MountGeometry template = normalize(definition.geometry(), definition.tolerances());
+ List 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 pairs = new ArrayList<>();
+ for (int i=0;i= 0 ? 1 : -1;
+ }
+
+ private List enumerate(MountGeometry source, MountGeometry target, Tolerances tolerance,
+ int side, String fingerprint) {
+ List 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;ispan){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 mappings=new TreeMap<>();
+ for(int i=0;i2*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 mapping=new ArrayList<>();
+ StringJoiner key=new StringJoiner("|");
+ for(int k=0;k 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 s,List t,int[] indices,RigidPose current,double[] normal){
+ double[] sc=new double[3],tc=new double[3];
+ for(int i=0;i source,List 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;ilimit+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=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 holes=new ArrayList<>();Set 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));}
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/RigidMath.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/RigidMath.java
new file mode 100644
index 0000000..6285bbc
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/RigidMath.java
@@ -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)); }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/UrdfAssetVerifier.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/UrdfAssetVerifier.java
new file mode 100644
index 0000000..4abcb2d
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/UrdfAssetVerifier.java
@@ -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 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); }
+ }
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/UrdfSourceValidation.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/UrdfSourceValidation.java
new file mode 100644
index 0000000..26b09af
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/mechanicalinterface/UrdfSourceValidation.java
@@ -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 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 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 links=new HashSet<>(), children=new HashSet<>(), joints=new HashSet<>();
+ Map 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 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 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);
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/ComponentUrdfUploadService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/ComponentUrdfUploadService.java
new file mode 100644
index 0000000..d1739ee
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/ComponentUrdfUploadService.java
@@ -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);
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/InterfaceBrepService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/InterfaceBrepService.java
new file mode 100644
index 0000000..d72b808
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/InterfaceBrepService.java
@@ -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 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.
+ }
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/InterfaceDefinitionService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/InterfaceDefinitionService.java
new file mode 100644
index 0000000..0e57152
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/InterfaceDefinitionService.java
@@ -0,0 +1,14 @@
+package com.linkerbot.cadworld.service;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.util.List;
+
+public interface InterfaceDefinitionService {
+ List 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);
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/OperationLogService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/OperationLogService.java
new file mode 100644
index 0000000..9c28a09
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/OperationLogService.java
@@ -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 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 query = new LambdaQueryWrapper()
+ .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 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;
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/UserManagementService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/UserManagementService.java
new file mode 100644
index 0000000..e8dda27
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/UserManagementService.java
@@ -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 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);
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/LocalObjectStorageClient.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/LocalObjectStorageClient.java
new file mode 100644
index 0000000..4046902
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/LocalObjectStorageClient.java
@@ -0,0 +1,125 @@
+package com.linkerbot.cadworld.service.client;
+
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.config.StorageProperties;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.Objects;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.util.UriComponentsBuilder;
+
+@Slf4j
+@Component
+@ConditionalOnProperty(name = "app.storage.provider", havingValue = "local")
+public class LocalObjectStorageClient implements ObjectStorageClient {
+
+ private final StorageProperties properties;
+ private final Path root;
+
+ public LocalObjectStorageClient(StorageProperties properties) {
+ this.properties = properties;
+ this.root = Path.of(StringUtils.hasText(properties.localRoot()) ? properties.localRoot() : "./data/assets")
+ .toAbsolutePath().normalize();
+ try {
+ Files.createDirectories(root);
+ } catch (IOException exception) {
+ throw new IllegalStateException("无法创建本地资源目录: " + root, exception);
+ }
+ }
+
+ @Override
+ public String createUploadUrl(String objectKey, String contentType, Duration duration) {
+ if (duration == null || duration.isZero() || duration.isNegative()) {
+ throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "STORAGE_CONFIG_ERROR", "上传会话有效期配置非法");
+ }
+ String base = StringUtils.hasText(properties.publicApiBaseUrl())
+ ? properties.publicApiBaseUrl().trim() : "http://127.0.0.1:8084";
+ return UriComponentsBuilder.fromUriString(base.replaceAll("/+$", ""))
+ .path("/admin-api/component-assets/upload")
+ .queryParam("objectKey", normalizeKey(objectKey))
+ .build().encode().toUriString();
+ }
+
+ @Override
+ public void putObject(String objectKey, String contentType, InputStream inputStream, long contentLength) {
+ Path target = resolve(objectKey);
+ try {
+ Files.createDirectories(Objects.requireNonNull(target.getParent()));
+ Files.copy(inputStream, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
+ } catch (IOException exception) {
+ log.error("Failed to write local object {}", objectKey, exception);
+ throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "LOCAL_STORAGE_WRITE_FAILED", "文件写入本地目录失败");
+ }
+ }
+
+ @Override
+ public boolean objectExists(String objectKey) {
+ return Files.isRegularFile(resolve(objectKey), LinkOption.NOFOLLOW_LINKS);
+ }
+
+ @Override
+ public StoredObject statObject(String objectKey) {
+ Path file = resolve(objectKey);
+ try {
+ if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
+ throw notFound();
+ }
+ return new StoredObject(Files.probeContentType(file), Files.size(file));
+ } catch (IOException exception) {
+ throw notFound();
+ }
+ }
+
+ @Override
+ public void writeObjectTo(String objectKey, OutputStream outputStream) {
+ Path file = resolve(objectKey);
+ try {
+ if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) throw notFound();
+ try (InputStream input = Files.newInputStream(file)) {
+ input.transferTo(outputStream);
+ }
+ } catch (IOException exception) {
+ throw notFound();
+ }
+ }
+
+ private Path resolve(String key) {
+ String normalizedKey = normalizeKey(key);
+ Path candidate = root.resolve(normalizedKey).normalize();
+ if (!candidate.startsWith(root)) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_STORAGE_OBJECT_KEY", "对象路径非法");
+ }
+ // Check every existing path component so a symlink in the bundle cannot
+ // redirect uploads or downloads outside the configured storage root.
+ Path current = root;
+ for (String segment : normalizedKey.split("/")) {
+ current = current.resolve(segment);
+ if (Files.isSymbolicLink(current)) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_STORAGE_OBJECT_KEY", "对象路径不能包含符号链接");
+ }
+ }
+ return candidate;
+ }
+
+ private String normalizeKey(String key) {
+ String normalized = key == null ? "" : key.trim().replace('\\', '/');
+ while (normalized.startsWith("/")) normalized = normalized.substring(1);
+ if (!StringUtils.hasText(normalized) || normalized.equals("..") || normalized.contains("../")) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_STORAGE_OBJECT_KEY", "对象路径非法");
+ }
+ return normalized;
+ }
+
+ private BizException notFound() {
+ return new BizException(HttpStatus.NOT_FOUND.value(), "LOCAL_OBJECT_NOT_FOUND", "文件不存在");
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/MinioObjectStorageClient.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/MinioObjectStorageClient.java
new file mode 100644
index 0000000..6d22258
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/MinioObjectStorageClient.java
@@ -0,0 +1,265 @@
+package com.linkerbot.cadworld.service.client;
+
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.config.MinioProperties;
+import com.linkerbot.cadworld.config.StorageProperties;
+import io.minio.BucketExistsArgs;
+import io.minio.GetObjectArgs;
+import io.minio.GetObjectResponse;
+import io.minio.MakeBucketArgs;
+import io.minio.MinioClient;
+import io.minio.PutObjectArgs;
+import io.minio.StatObjectArgs;
+import io.minio.StatObjectResponse;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+import java.time.Duration;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.util.UriComponentsBuilder;
+
+@Slf4j
+@Component
+@ConditionalOnProperty(name = "app.storage.provider", havingValue = "minio", matchIfMissing = true)
+public class MinioObjectStorageClient implements ObjectStorageClient {
+
+ private static final long UNKNOWN_SIZE_PART_SIZE = 10L * 1024 * 1024;
+
+ private final MinioProperties properties;
+ private final StorageProperties storageProperties;
+ private volatile MinioClient minioClient;
+ private volatile boolean bucketReady;
+
+ public MinioObjectStorageClient(MinioProperties properties, StorageProperties storageProperties) {
+ this.properties = properties;
+ this.storageProperties = storageProperties;
+ }
+
+ @Override
+ public String createUploadUrl(String objectKey, String contentType, Duration duration) {
+ validateConfiguration();
+ if (duration == null || duration.isZero() || duration.isNegative()) {
+ throw configError("MinIO 上传会话有效期配置非法");
+ }
+ String baseUrl = requireText(storageProperties.publicApiBaseUrl(), "APP_STORAGE_PUBLIC_API_BASE_URL");
+ return UriComponentsBuilder.fromUriString(trimTrailingSlash(baseUrl))
+ .path("/admin-api/component-assets/upload")
+ .queryParam("objectKey", normalizeObjectKey(objectKey))
+ .build()
+ .encode()
+ .toUriString();
+ }
+
+ @Override
+ public void putObject(String objectKey, String contentType, InputStream inputStream, long contentLength) {
+ validateConfiguration();
+ ensureBucket();
+ try {
+ long objectSize = contentLength >= 0 ? contentLength : -1;
+ long partSize = contentLength >= 0 ? -1 : UNKNOWN_SIZE_PART_SIZE;
+ getMinioClient().putObject(PutObjectArgs.builder()
+ .bucket(properties.bucket().trim())
+ .object(normalizeObjectKey(objectKey))
+ .contentType(normalizeContentType(contentType))
+ .stream(inputStream, objectSize, partSize)
+ .build());
+ } catch (Exception exception) {
+ restoreInterrupt(exception);
+ log.error("Failed to upload object to MinIO. objectKey={}", objectKey, exception);
+ throw new BizException(HttpStatus.BAD_GATEWAY.value(), "MINIO_UPLOAD_FAILED", "文件上传到 MinIO 失败");
+ }
+ }
+
+ @Override
+ public boolean objectExists(String objectKey) {
+ validateConfiguration();
+ ensureBucket();
+ try {
+ getMinioClient().statObject(StatObjectArgs.builder()
+ .bucket(properties.bucket().trim())
+ .object(normalizeObjectKey(objectKey))
+ .build());
+ return true;
+ } catch (io.minio.errors.ErrorResponseException exception) {
+ String code = exception.errorResponse() == null ? "" : exception.errorResponse().code();
+ if ("NoSuchKey".equals(code) || "NoSuchObject".equals(code) || "NotFound".equals(code)) {
+ return false;
+ }
+ log.error("Failed to check MinIO object. objectKey={}", objectKey, exception);
+ throw new BizException(HttpStatus.BAD_GATEWAY.value(), "MINIO_OBJECT_CHECK_FAILED", "校验 MinIO 上传结果失败");
+ } catch (Exception exception) {
+ restoreInterrupt(exception);
+ log.error("Failed to check MinIO object. objectKey={}", objectKey, exception);
+ throw new BizException(HttpStatus.BAD_GATEWAY.value(), "MINIO_OBJECT_CHECK_FAILED", "校验 MinIO 上传结果失败");
+ }
+ }
+
+ @Override
+ public StoredObject statObject(String objectKey) {
+ validateConfiguration();
+ ensureBucket();
+ String normalizedKey = normalizeObjectKey(objectKey);
+ try {
+ StatObjectResponse stat = getMinioClient().statObject(StatObjectArgs.builder()
+ .bucket(properties.bucket().trim())
+ .object(normalizedKey)
+ .build());
+ return new StoredObject(stat.contentType(), stat.size());
+ } catch (io.minio.errors.ErrorResponseException exception) {
+ throw mapDownloadException(objectKey, exception);
+ } catch (Exception exception) {
+ throw mapDownloadException(objectKey, exception);
+ }
+ }
+
+ @Override
+ public void writeObjectTo(String objectKey, OutputStream outputStream) {
+ validateConfiguration();
+ ensureBucket();
+ String normalizedKey = normalizeObjectKey(objectKey);
+ try (GetObjectResponse input = getMinioClient().getObject(GetObjectArgs.builder()
+ .bucket(properties.bucket().trim())
+ .object(normalizedKey)
+ .build())) {
+ input.transferTo(outputStream);
+ } catch (io.minio.errors.ErrorResponseException exception) {
+ throw mapDownloadException(objectKey, exception);
+ } catch (Exception exception) {
+ throw mapDownloadException(objectKey, exception);
+ }
+ }
+
+ private BizException mapDownloadException(String objectKey, Exception exception) {
+ restoreInterrupt(exception);
+ if (exception instanceof io.minio.errors.ErrorResponseException errorResponseException) {
+ String code = errorResponseException.errorResponse() == null ? "" : errorResponseException.errorResponse().code();
+ if ("NoSuchKey".equals(code) || "NoSuchObject".equals(code) || "NotFound".equals(code)) {
+ return new BizException(HttpStatus.NOT_FOUND.value(), "MINIO_OBJECT_NOT_FOUND", "文件不存在");
+ }
+ }
+ log.error("Failed to download MinIO object. objectKey={}", objectKey, exception);
+ return new BizException(HttpStatus.BAD_GATEWAY.value(), "MINIO_DOWNLOAD_FAILED", "从 MinIO 读取文件失败");
+ }
+
+ private void ensureBucket() {
+ if (bucketReady) {
+ return;
+ }
+ synchronized (this) {
+ if (bucketReady) {
+ return;
+ }
+ try {
+ String bucket = properties.bucket().trim();
+ if (!getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
+ getMinioClient().makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
+ }
+ bucketReady = true;
+ } catch (Exception exception) {
+ restoreInterrupt(exception);
+ log.error("Failed to initialize MinIO bucket. bucket={}, endpoint={}",
+ properties.bucket(), properties.endpoint(), exception);
+ throw new BizException(
+ HttpStatus.BAD_GATEWAY.value(),
+ "MINIO_BUCKET_FAILED",
+ "MinIO Bucket 初始化失败:" + classifyBucketFailure(exception));
+ }
+ }
+ }
+
+ private String classifyBucketFailure(Exception exception) {
+ if (exception instanceof io.minio.errors.ErrorResponseException errorResponseException
+ && errorResponseException.errorResponse() != null) {
+ String code = errorResponseException.errorResponse().code();
+ if ("AccessDenied".equals(code) || "InvalidAccessKeyId".equals(code)
+ || "SignatureDoesNotMatch".equals(code)) {
+ return "MinIO 账号或 Bucket 权限不足 (" + code + ")";
+ }
+ return "MinIO 返回错误 (" + code + ")";
+ }
+ Throwable cause = exception;
+ while (cause.getCause() != null && cause.getCause() != cause) {
+ cause = cause.getCause();
+ }
+ if (cause instanceof java.net.ConnectException) {
+ return "无法连接 MinIO,请检查 endpoint 和网络";
+ }
+ if (cause instanceof java.net.UnknownHostException) {
+ return "无法解析 MinIO 地址,请检查 Docker 网络和容器名";
+ }
+ return "请检查 MinIO endpoint、账号和 Bucket 权限";
+ }
+
+ private MinioClient getMinioClient() {
+ MinioClient client = minioClient;
+ if (client != null) {
+ return client;
+ }
+ synchronized (this) {
+ if (minioClient == null) {
+ minioClient = MinioClient.builder()
+ .endpoint(normalizeEndpoint(properties.endpoint()))
+ .credentials(properties.accessKey().trim(), properties.secretKey().trim())
+ .build();
+ }
+ return minioClient;
+ }
+ }
+
+ private void validateConfiguration() {
+ requireText(properties.endpoint(), "APP_MINIO_ENDPOINT");
+ requireText(properties.accessKey(), "APP_MINIO_ACCESS_KEY");
+ requireText(properties.secretKey(), "APP_MINIO_SECRET_KEY");
+ requireText(properties.bucket(), "APP_MINIO_BUCKET");
+ }
+
+ private String requireText(String value, String property) {
+ if (!StringUtils.hasText(value)) {
+ throw configError("MinIO 配置缺失: " + property);
+ }
+ return value.trim();
+ }
+
+ private BizException configError(String message) {
+ return new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "MINIO_CONFIG_ERROR", message);
+ }
+
+ private static String normalizeEndpoint(String endpoint) {
+ String value = endpoint.trim();
+ URI uri = URI.create(value.startsWith("http://") || value.startsWith("https://") ? value : "http://" + value);
+ return uri.toString();
+ }
+
+ private static String normalizeObjectKey(String objectKey) {
+ String normalized = objectKey == null ? "" : objectKey.trim().replace("\\", "/");
+ while (normalized.startsWith("/")) {
+ normalized = normalized.substring(1);
+ }
+ if (!StringUtils.hasText(normalized) || normalized.contains("../") || normalized.equals("..")) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_STORAGE_OBJECT_KEY", "对象路径非法");
+ }
+ return normalized;
+ }
+
+ private static String normalizeContentType(String contentType) {
+ return StringUtils.hasText(contentType) ? contentType.trim() : "application/octet-stream";
+ }
+
+ private static String trimTrailingSlash(String value) {
+ String result = value.trim();
+ while (result.endsWith("/")) {
+ result = result.substring(0, result.length() - 1);
+ }
+ return result;
+ }
+
+ private static void restoreInterrupt(Exception exception) {
+ if (exception instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/ObjectStorageClient.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/ObjectStorageClient.java
new file mode 100644
index 0000000..3e153b0
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/client/ObjectStorageClient.java
@@ -0,0 +1,27 @@
+package com.linkerbot.cadworld.service.client;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.time.Duration;
+
+public interface ObjectStorageClient {
+
+ String createUploadUrl(String objectKey, String contentType, Duration duration);
+
+ default void putObject(String objectKey, String contentType, InputStream inputStream, long contentLength) {
+ throw new UnsupportedOperationException();
+ }
+
+ boolean objectExists(String objectKey);
+
+ default StoredObject statObject(String objectKey) {
+ throw new UnsupportedOperationException();
+ }
+
+ default void writeObjectTo(String objectKey, OutputStream outputStream) {
+ throw new UnsupportedOperationException();
+ }
+
+ record StoredObject(String contentType, long contentLength) {
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentCoverImageUploadServiceImpl.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentCoverImageUploadServiceImpl.java
new file mode 100644
index 0000000..5f24940
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentCoverImageUploadServiceImpl.java
@@ -0,0 +1,86 @@
+package com.linkerbot.cadworld.service.impl;
+
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.config.StorageProperties;
+import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadRequest;
+import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
+import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
+import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
+import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
+import com.linkerbot.cadworld.enums.ComponentUploadType;
+import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
+import com.linkerbot.cadworld.service.ComponentCoverImageUploadService;
+import java.util.List;
+import java.util.Locale;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+
+@Service
+@RequiredArgsConstructor
+public class ComponentCoverImageUploadServiceImpl implements ComponentCoverImageUploadService {
+
+ private static final String DEFAULT_COVER_IMAGE_PREFIX = "components/cover-images";
+ private static final int COVER_IMAGE_KEY_MAX_LENGTH = 512;
+
+ private final StorageProperties storageProperties;
+ private final ComponentUploadSupport componentUploadSupport;
+ private final ObjectStorageUrlResolver objectStorageUrlResolver;
+
+ @Override
+ public PrepareCoverImageUploadSessionResponse prepareUploadSession(Long userId) {
+ ComponentUploadSupport.PreparedUploadSession session = componentUploadSupport.prepareUploadSession(
+ userId,
+ ComponentUploadType.COVER_IMAGE,
+ componentUploadSupport.normalizeConfiguredPrefix(storageProperties.coverImagePrefix(), DEFAULT_COVER_IMAGE_PREFIX)
+ );
+ return new PrepareCoverImageUploadSessionResponse(
+ session.uploadSessionToken(),
+ session.keyPrefix()
+ );
+ }
+
+ @Override
+ public PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request) {
+ ComponentUploadSupport.PreparedObjectUpload upload = componentUploadSupport.prepareObjectUpload(
+ userId,
+ request.uploadSessionToken(),
+ ComponentUploadType.COVER_IMAGE,
+ "INVALID_COMPONENT_COVER_UPLOAD_SESSION",
+ request.objectPath(),
+ request.contentType()
+ );
+ return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey());
+ }
+
+ @Override
+ public CompleteCoverImageUploadResponse completeUploadSession(Long userId, CompleteCoverImageUploadRequest request) {
+ ComponentUploadSessionTokenProvider.UploadSessionClaims claims = componentUploadSupport.requireUploadSession(
+ userId,
+ request.uploadSessionToken(),
+ ComponentUploadType.COVER_IMAGE,
+ "INVALID_COMPONENT_COVER_UPLOAD_SESSION"
+ );
+ List objectKeys = componentUploadSupport.verifyUploadedObjectKeys(
+ claims.keyPrefix(),
+ request.objectKeys()
+ );
+ String coverImageKey = objectKeys.getFirst();
+ if (!isSupportedImage(coverImageKey)) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_COVER_IMAGE_TYPE_INVALID", "封面图仅支持 jpg、jpeg、png、webp、gif");
+ }
+ if (coverImageKey.length() > COVER_IMAGE_KEY_MAX_LENGTH) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_COVER_IMAGE_KEY_TOO_LONG", "封面图对象 Key 过长,无法写入组件封面字段");
+ }
+ return new CompleteCoverImageUploadResponse(coverImageKey, objectStorageUrlResolver.resolvePublicUrl(coverImageKey));
+ }
+
+ private boolean isSupportedImage(String objectKey) {
+ String normalized = objectKey.toLowerCase(Locale.ROOT);
+ return normalized.endsWith(".jpg")
+ || normalized.endsWith(".jpeg")
+ || normalized.endsWith(".png")
+ || normalized.endsWith(".webp")
+ || normalized.endsWith(".gif");
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentServiceImpl.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentServiceImpl.java
new file mode 100644
index 0000000..2f79006
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentServiceImpl.java
@@ -0,0 +1,238 @@
+package com.linkerbot.cadworld.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.cadworld.common.api.PageResponse;
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata;
+import com.linkerbot.cadworld.dto.component.ComponentListItemResponse;
+import com.linkerbot.cadworld.dto.component.ComponentResponse;
+import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
+import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
+import com.linkerbot.cadworld.entity.Component;
+import com.linkerbot.cadworld.entity.ComponentAsset;
+import com.linkerbot.cadworld.mapper.ComponentMapper;
+import com.linkerbot.cadworld.mapper.ComponentAssetMapper;
+import com.linkerbot.cadworld.service.ComponentService;
+import org.springframework.dao.DuplicateKeyException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+@Service
+public class ComponentServiceImpl implements ComponentService {
+
+ private static final String COMPONENT_NOT_FOUND = "COMPONENT_NOT_FOUND";
+ private static final String COMPONENT_NAME_DUPLICATE = "COMPONENT_NAME_DUPLICATE";
+ private static final String COMPONENT_NAME_DUPLICATE_MESSAGE = "组件名称已存在,请更换名称";
+
+ private final ComponentMapper componentMapper;
+ private final ComponentAssetMapper componentAssetMapper;
+ private final ObjectStorageUrlResolver objectStorageUrlResolver;
+ private final ObjectMapper objectMapper;
+ private final com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService portValidation;
+
+ @Autowired
+ public ComponentServiceImpl(ComponentMapper componentMapper, ComponentAssetMapper componentAssetMapper,
+ ObjectStorageUrlResolver objectStorageUrlResolver,
+ ObjectMapper objectMapper,
+ com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService portValidation) {
+ this.componentMapper = componentMapper;
+ this.componentAssetMapper = componentAssetMapper;
+ this.objectStorageUrlResolver = objectStorageUrlResolver;
+ this.objectMapper = objectMapper;
+ this.portValidation = portValidation;
+ }
+
+ @Override
+ @Transactional
+ public ComponentResponse createComponent(Long userId, CreateComponentRequest request) {
+ String componentName = request.componentName().trim();
+ assertComponentNameAvailable(componentName, null);
+ Component component = new Component();
+ apply(component, componentName, request.category(), request.robotType(), request.company(),
+ request.model(), request.source(), request.coverImageKey(), request.description(), request.componentJson(),
+ request.assemblyMetadata());
+ try {
+ componentMapper.insert(component);
+ syncAssetIndex(component);
+ } catch (DuplicateKeyException exception) {
+ throw duplicateComponentNameException();
+ }
+ return toDetailResponse(componentMapper.selectById(component.getId()));
+ }
+
+ @Override
+ public PageResponse listComponents(long page, long size, String keyword) {
+ Page pageable = new Page<>(page, size);
+ LambdaQueryWrapper query = new LambdaQueryWrapper<>();
+ if (StringUtils.hasText(keyword)) {
+ query.and(matches -> {
+ for (String term : ComponentTagSupport.searchTerms(keyword)) {
+ matches.or().nested(candidate -> candidate.like(Component::getComponentName, term)
+ .or().like(Component::getCategory, term)
+ .or().apply("JSON_SEARCH(assembly_metadata, 'one', {0}, NULL, '$.tags[*]', '$.capabilities[*]') IS NOT NULL", "%" + term + "%"));
+ }
+ });
+ }
+ Page result = componentMapper.selectPage(pageable, query.orderByDesc(Component::getUpdatedAt));
+ return new PageResponse<>(result.getRecords().stream().map(this::toListItemResponse).toList(), page, size, result.getTotal());
+ }
+
+ @Override
+ public ComponentResponse getComponent(Long id) {
+ return toDetailResponse(requireComponent(id));
+ }
+
+ @Override
+ @Transactional
+ public ComponentResponse updateComponent(Long userId, Long id, UpdateComponentRequest request) {
+ Component component = requireComponent(id);
+ String componentName = request.componentName().trim();
+ assertComponentNameAvailable(componentName, id);
+ apply(component, componentName, request.category(), request.robotType(), request.company(),
+ request.model(), request.source(), request.coverImageKey(), request.description(), request.componentJson(),
+ request.assemblyMetadata());
+ try {
+ componentMapper.updateById(component);
+ syncAssetIndex(component);
+ } catch (DuplicateKeyException exception) {
+ throw duplicateComponentNameException();
+ }
+ return toDetailResponse(componentMapper.selectById(component.getId()));
+ }
+
+ @Override
+ @Transactional
+ public void deleteComponent(Long userId, Long id) {
+ Component component = requireComponent(id);
+ componentMapper.deleteById(component.getId());
+ }
+
+ private Component requireComponent(Long id) {
+ Component component = componentMapper.selectById(id);
+ if (component == null) {
+ throw new BizException(HttpStatus.NOT_FOUND.value(), COMPONENT_NOT_FOUND, "组件不存在");
+ }
+ return component;
+ }
+
+ private void assertComponentNameAvailable(String componentName, Long excludedId) {
+ Long count = componentMapper.selectCount(new LambdaQueryWrapper()
+ .eq(Component::getComponentName, componentName)
+ .ne(excludedId != null, Component::getId, excludedId));
+ if (count != null && count > 0) {
+ throw duplicateComponentNameException();
+ }
+ }
+
+ private BizException duplicateComponentNameException() {
+ return new BizException(HttpStatus.CONFLICT.value(), COMPONENT_NAME_DUPLICATE, COMPONENT_NAME_DUPLICATE_MESSAGE);
+ }
+
+ private void apply(Component component,
+ String componentName,
+ String category,
+ String robotType,
+ String company,
+ String model,
+ String source,
+ String coverImageKey,
+ String description,
+ com.fasterxml.jackson.databind.JsonNode componentJson,
+ ComponentAssemblyMetadata assemblyMetadata) {
+ component.setComponentName(componentName.trim());
+ component.setCategory(normalizeOptionalText(category));
+ component.setRobotType(robotType.trim());
+ component.setCompany(company.trim());
+ component.setModel(model.trim());
+ component.setSource(source.trim());
+ component.setCoverImageKey(normalizeOptionalText(coverImageKey));
+ component.setDescription(normalizeOptionalText(description));
+ int previousRevision=component.getComponentJson()==null?0:component.getComponentJson().path("componentRevision").asInt(0);
+ var validated=(com.fasterxml.jackson.databind.node.ObjectNode)portValidation.validate(componentJson);
+ validated.put("componentRevision",previousRevision+1);
+ component.setComponentJson(validated);
+ component.setAssemblyMetadata(objectMapper.valueToTree(
+ ComponentTagSupport.mergeLegacy(assemblyMetadata, category)
+ ));
+ }
+
+ private ComponentListItemResponse toListItemResponse(Component component) {
+ return new ComponentListItemResponse(
+ component.getId(),
+ component.getComponentName(),
+ component.getCategory(),
+ component.getRobotType(),
+ component.getCompany(),
+ component.getModel(),
+ component.getSource(),
+ objectStorageUrlResolver.resolvePublicUrl(component.getSource()),
+ resolveCoverImageUrl(component.getCoverImageKey()),
+ component.getDescription(),
+ metadataOf(component),
+ component.getCreatedAt(),
+ component.getUpdatedAt()
+ );
+ }
+
+ private ComponentResponse toDetailResponse(Component component) {
+ return new ComponentResponse(
+ component.getId(),
+ component.getComponentName(),
+ component.getCategory(),
+ component.getRobotType(),
+ component.getCompany(),
+ component.getModel(),
+ component.getSource(),
+ objectStorageUrlResolver.resolvePublicUrl(component.getSource()),
+ component.getCoverImageKey(),
+ resolveCoverImageUrl(component.getCoverImageKey()),
+ component.getDescription(),
+ component.getComponentJson(),
+ metadataOf(component),
+ component.getCreatedAt(),
+ component.getUpdatedAt()
+ );
+ }
+
+ private String normalizeOptionalText(String value) {
+ return StringUtils.hasText(value) ? value.trim() : "";
+ }
+
+ private ComponentAssemblyMetadata metadataOf(Component component) {
+ return ComponentTagSupport.metadata(component, objectMapper);
+ }
+
+ private String resolveCoverImageUrl(String coverImageKey) {
+ return objectStorageUrlResolver.resolvePublicUrl(coverImageKey);
+ }
+
+ private void syncAssetIndex(Component component) {
+ if (componentAssetMapper == null || component.getId() == null) {
+ return;
+ }
+ componentAssetMapper.delete(new LambdaQueryWrapper()
+ .eq(ComponentAsset::getComponentId, component.getId()));
+ addAsset(component, component.getSource(), "RFS", true);
+ addAsset(component, component.getCoverImageKey(), "COVER", false);
+ }
+
+ private void addAsset(Component component, String objectKey, String assetKind, boolean primary) {
+ if (!StringUtils.hasText(objectKey)) {
+ return;
+ }
+ ComponentAsset asset = new ComponentAsset();
+ asset.setComponentId(component.getId());
+ asset.setObjectKey(objectKey.trim());
+ int separator = objectKey.lastIndexOf('/');
+ asset.setRelativePath(separator >= 0 ? objectKey.substring(separator + 1) : objectKey);
+ asset.setAssetKind(assetKind);
+ asset.setIsPrimary(primary);
+ asset.setSize(0L);
+ componentAssetMapper.insert(asset);
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentTagSupport.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentTagSupport.java
new file mode 100644
index 0000000..7811c3c
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentTagSupport.java
@@ -0,0 +1,63 @@
+package com.linkerbot.cadworld.service.impl;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata;
+import com.linkerbot.cadworld.entity.Component;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.springframework.util.StringUtils;
+
+/** Read compatibility for catalog entries created before name/tag-based authoring. */
+final class ComponentTagSupport {
+ private ComponentTagSupport() {}
+
+ private static final Map> LEGACY_TAGS = Map.ofEntries(
+ Map.entry("torso", List.of("躯干")), Map.entry("head", List.of("头部")),
+ Map.entry("neck", List.of("颈部")), Map.entry("waist", List.of("腰部")),
+ Map.entry("left_arm", List.of("左臂", "手臂")), Map.entry("right_arm", List.of("右臂", "手臂")),
+ Map.entry("left_hand", List.of("左手", "手部")), Map.entry("right_hand", List.of("右手", "手部")),
+ Map.entry("left_leg", List.of("左腿", "腿部")), Map.entry("right_leg", List.of("右腿", "腿部")),
+ Map.entry("left_foot", List.of("左脚", "足部")), Map.entry("right_foot", List.of("右脚", "足部")),
+ Map.entry("unclassified", List.of())
+ );
+
+ static ComponentAssemblyMetadata metadata(Component component, ObjectMapper mapper) {
+ ComponentAssemblyMetadata metadata = component.getAssemblyMetadata() == null || component.getAssemblyMetadata().isNull()
+ ? ComponentAssemblyMetadata.empty()
+ : mapper.convertValue(component.getAssemblyMetadata(), ComponentAssemblyMetadata.class);
+ return mergeLegacy(metadata, component.getCategory());
+ }
+
+ static ComponentAssemblyMetadata mergeLegacy(ComponentAssemblyMetadata metadata, String category) {
+ ComponentAssemblyMetadata source = metadata == null ? ComponentAssemblyMetadata.empty() : metadata;
+ List values = new ArrayList<>(source.tags());
+ values.addAll(source.capabilities());
+ if (StringUtils.hasText(category)) values.addAll(LEGACY_TAGS.getOrDefault(category.trim(), List.of(category.trim())));
+ LinkedHashSet tags = new LinkedHashSet<>();
+ values.forEach(value -> {
+ for (String tag : value.split("[,,、;;\\n]")) {
+ if (StringUtils.hasText(tag)) tags.add(tag.trim());
+ }
+ });
+ return new ComponentAssemblyMetadata(List.copyOf(tags), source.capabilities(), source.dimensions());
+ }
+
+ static List searchTerms(String query) {
+ String value = query == null ? "" : query.trim();
+ if (List.of("爪子", "夹爪", "抓取爪").contains(value)) return List.of("爪子", "夹爪", "抓取爪");
+ if (List.of("铲子", "铲具").contains(value)) return List.of("铲子", "铲具");
+ List terms = new ArrayList<>(List.of(value));
+ LEGACY_TAGS.forEach((key, tags) -> {
+ if (tags.contains(value)) terms.add(key);
+ });
+ return terms;
+ }
+
+ static boolean matches(String source, String query) {
+ String text = source == null ? "" : source.toLowerCase(Locale.ROOT);
+ return searchTerms(query).stream().anyMatch(term -> text.contains(term.toLowerCase(Locale.ROOT)));
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentUploadSupport.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentUploadSupport.java
new file mode 100644
index 0000000..255171b
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentUploadSupport.java
@@ -0,0 +1,210 @@
+package com.linkerbot.cadworld.service.impl;
+
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.config.StorageProperties;
+import com.linkerbot.cadworld.enums.ComponentUploadType;
+import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
+import com.linkerbot.cadworld.service.client.ObjectStorageClient;
+import io.jsonwebtoken.JwtException;
+import java.io.InputStream;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.UUID;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+
+@Component
+@RequiredArgsConstructor
+public class ComponentUploadSupport {
+
+ private final StorageProperties storageProperties;
+ private final ObjectStorageClient objectStorageClient;
+ private final ComponentUploadSessionTokenProvider componentUploadSessionTokenProvider;
+
+ public PreparedUploadSession prepareUploadSession(Long userId, ComponentUploadType uploadType, String keyPrefixRoot) {
+ Duration uploadSessionTtl = resolveUploadSessionTtl();
+ String keyPrefix = buildKeyPrefix(keyPrefixRoot, userId);
+ java.time.Instant expiresAt = java.time.Instant.now().plus(uploadSessionTtl);
+ return new PreparedUploadSession(
+ componentUploadSessionTokenProvider.generateToken(userId, uploadType, keyPrefix, expiresAt),
+ keyPrefix
+ );
+ }
+
+ public ComponentUploadSessionTokenProvider.UploadSessionClaims requireUploadSession(Long userId,
+ String token,
+ ComponentUploadType expectedType,
+ String invalidCode) {
+ try {
+ ComponentUploadSessionTokenProvider.UploadSessionClaims claims = componentUploadSessionTokenProvider.parseToken(token);
+ if (claims.uploadType() != expectedType) {
+ throw invalidUploadSession(invalidCode, "上传会话类型不匹配");
+ }
+ if (!StringUtils.hasText(claims.keyPrefix())) {
+ throw invalidUploadSession(invalidCode, "上传会话缺少对象前缀");
+ }
+ if (!userId.equals(claims.userId())) {
+ throw invalidUploadSession(invalidCode, "上传会话与当前用户不匹配");
+ }
+ return claims;
+ } catch (JwtException | IllegalArgumentException exception) {
+ throw invalidUploadSession(invalidCode, "上传会话无效或已过期");
+ }
+ }
+
+ public List verifyUploadedObjectKeys(String keyPrefix, List submittedObjectKeys) {
+ if (!StringUtils.hasText(keyPrefix) || submittedObjectKeys == null || submittedObjectKeys.isEmpty()) {
+ throw invalidUploadObject("上传文件列表不能为空");
+ }
+ String normalizedPrefix = normalizeObjectKey(keyPrefix);
+ if (!normalizedPrefix.endsWith("/")) {
+ normalizedPrefix += "/";
+ }
+
+ final String requiredPrefix = normalizedPrefix;
+ List objectKeys = submittedObjectKeys.stream()
+ .map(this::normalizeObjectKey)
+ .peek(key -> validateSessionObjectKey(requiredPrefix, key))
+ .distinct()
+ .toList();
+ if (objectKeys.size() != submittedObjectKeys.size()) {
+ throw invalidUploadObject("上传文件列表包含重复对象");
+ }
+ for (String objectKey : objectKeys) {
+ if (!objectStorageClient.objectExists(objectKey)) {
+ throw new BizException(
+ HttpStatus.UNPROCESSABLE_ENTITY.value(),
+ "COMPONENT_UPLOAD_OBJECT_MISSING",
+ "未检测到已上传文件: " + objectKey
+ );
+ }
+ }
+ return objectKeys;
+ }
+
+ public PreparedObjectUpload prepareObjectUpload(Long userId,
+ String uploadSessionToken,
+ ComponentUploadType expectedType,
+ String invalidCode,
+ String objectPath,
+ String contentType) {
+ ComponentUploadSessionTokenProvider.UploadSessionClaims claims = requireUploadSession(
+ userId, uploadSessionToken, expectedType, invalidCode);
+ String objectKey = resolveObjectKey(claims.keyPrefix(), objectPath);
+ return new PreparedObjectUpload(
+ objectStorageClient.createUploadUrl(objectKey, contentType, resolveUploadSessionTtl()),
+ objectKey
+ );
+ }
+
+ public String normalizeConfiguredPrefix(String configuredPrefix, String defaultPrefix) {
+ String prefix = StringUtils.hasText(configuredPrefix) ? configuredPrefix.trim() : defaultPrefix;
+ prefix = prefix.replace("\\", "/");
+ while (prefix.startsWith("/")) {
+ prefix = prefix.substring(1);
+ }
+ while (prefix.endsWith("/")) {
+ prefix = prefix.substring(0, prefix.length() - 1);
+ }
+ return StringUtils.hasText(prefix) ? prefix : defaultPrefix;
+ }
+
+ public Duration resolveUploadSessionTtl() {
+ Duration configured = storageProperties.uploadSessionTtl();
+ if (configured == null) {
+ return Duration.ofMinutes(30);
+ }
+ if (configured.isZero() || configured.isNegative()) {
+ throw new BizException(HttpStatus.INTERNAL_SERVER_ERROR.value(), "STORAGE_CONFIG_ERROR", "对象存储上传会话有效期配置非法");
+ }
+ return configured;
+ }
+
+ public void uploadObject(Long userId,
+ String objectKey,
+ String contentType,
+ InputStream inputStream,
+ long contentLength) {
+ String normalizedKey = normalizeObjectKey(objectKey);
+ String userSegment = "/" + userId + "/";
+ String urdfPrefix = normalizeConfiguredPrefix(storageProperties.urdfPrefix(), "components/urdf") + userSegment;
+ String coverPrefix = normalizeConfiguredPrefix(storageProperties.coverImagePrefix(), "components/cover-images") + userSegment;
+ if (!normalizedKey.startsWith(urdfPrefix) && !normalizedKey.startsWith(coverPrefix)) {
+ throw invalidUploadObject("无权上传到该对象路径");
+ }
+ objectStorageClient.putObject(normalizedKey, contentType, inputStream, contentLength);
+ }
+
+ private BizException invalidUploadSession(String code, String message) {
+ return new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), code, message);
+ }
+
+ private BizException invalidUploadObject(String message) {
+ return new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", message);
+ }
+
+ private String normalizeObjectKey(String objectKey) {
+ if (!StringUtils.hasText(objectKey)) {
+ throw invalidUploadObject("上传文件路径不能为空");
+ }
+ return objectKey.trim().replace("\\", "/");
+ }
+
+ private void validateSessionObjectKey(String keyPrefix, String objectKey) {
+ if (!objectKey.startsWith(keyPrefix) || objectKey.length() <= keyPrefix.length() || objectKey.endsWith("/")) {
+ throw invalidUploadObject("上传文件不属于当前会话");
+ }
+ String relativePath = objectKey.substring(keyPrefix.length());
+ for (String segment : relativePath.split("/")) {
+ if (!StringUtils.hasText(segment) || ".".equals(segment) || "..".equals(segment)) {
+ throw invalidUploadObject("上传文件路径非法");
+ }
+ }
+ if (objectKey.length() > 512) {
+ throw invalidUploadObject("上传文件路径过长");
+ }
+ }
+
+ private String buildKeyPrefix(String keyPrefixRoot, Long userId) {
+ return keyPrefixRoot + "/"
+ + userId + "/"
+ + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + "/"
+ + UUID.randomUUID() + "/";
+ }
+
+ private String resolveObjectKey(String keyPrefix, String objectPath) {
+ if (!StringUtils.hasText(objectPath)) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径不能为空");
+ }
+ String normalized = objectPath.trim().replace("\\", "/");
+ if (normalized.startsWith("/") || normalized.endsWith("/")) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径非法");
+ }
+ for (String segment : normalized.split("/")) {
+ if (!StringUtils.hasText(segment) || ".".equals(segment) || "..".equals(segment)) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径非法");
+ }
+ }
+ String objectKey = keyPrefix + normalized;
+ if (objectKey.length() > 512) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "INVALID_COMPONENT_UPLOAD_OBJECT", "上传文件路径过长");
+ }
+ return objectKey;
+ }
+
+ public record PreparedUploadSession(
+ String uploadSessionToken,
+ String keyPrefix
+ ) {
+ }
+
+ public record PreparedObjectUpload(
+ String uploadUrl,
+ String objectKey
+ ) {
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentUrdfUploadServiceImpl.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentUrdfUploadServiceImpl.java
new file mode 100644
index 0000000..720e746
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ComponentUrdfUploadServiceImpl.java
@@ -0,0 +1,107 @@
+package com.linkerbot.cadworld.service.impl;
+
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.config.StorageProperties;
+import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
+import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
+import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
+import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
+import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
+import com.linkerbot.cadworld.enums.ComponentUploadType;
+import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
+import com.linkerbot.cadworld.service.ComponentUrdfUploadService;
+import java.util.List;
+import java.util.Locale;
+import lombok.RequiredArgsConstructor;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+
+@Service
+@RequiredArgsConstructor
+public class ComponentUrdfUploadServiceImpl implements ComponentUrdfUploadService {
+
+ private static final String DEFAULT_URDF_PREFIX = "components/urdf";
+ private static final int SOURCE_MAX_LENGTH = 255;
+
+ private final StorageProperties storageProperties;
+ private final ComponentUploadSupport componentUploadSupport;
+
+ @Override
+ public PrepareUrdfUploadSessionResponse prepareUploadSession(Long userId) {
+ ComponentUploadSupport.PreparedUploadSession session = componentUploadSupport.prepareUploadSession(
+ userId,
+ ComponentUploadType.URDF,
+ componentUploadSupport.normalizeConfiguredPrefix(storageProperties.urdfPrefix(), DEFAULT_URDF_PREFIX)
+ );
+ return new PrepareUrdfUploadSessionResponse(
+ session.uploadSessionToken(),
+ session.keyPrefix()
+ );
+ }
+
+ @Override
+ public PrepareObjectUploadUrlResponse prepareObjectUploadUrl(Long userId, PrepareObjectUploadUrlRequest request) {
+ ComponentUploadSupport.PreparedObjectUpload upload = componentUploadSupport.prepareObjectUpload(
+ userId,
+ request.uploadSessionToken(),
+ ComponentUploadType.URDF,
+ "INVALID_COMPONENT_UPLOAD_SESSION",
+ request.objectPath(),
+ request.contentType()
+ );
+ return new PrepareObjectUploadUrlResponse(upload.uploadUrl(), upload.objectKey());
+ }
+
+ @Override
+ public CompleteUrdfUploadResponse completeUploadSession(Long userId, CompleteUrdfUploadRequest request) {
+ ComponentUploadSessionTokenProvider.UploadSessionClaims claims = componentUploadSupport.requireUploadSession(
+ userId,
+ request.uploadSessionToken(),
+ ComponentUploadType.URDF,
+ "INVALID_COMPONENT_UPLOAD_SESSION"
+ );
+ List objectKeys = componentUploadSupport.verifyUploadedObjectKeys(
+ claims.keyPrefix(),
+ request.objectKeys()
+ );
+ String source = resolveMainSource(objectKeys);
+ if (source.length() > SOURCE_MAX_LENGTH) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_MAIN_FILE_PATH_TOO_LONG", "主文件路径过长,无法写入组件 source 字段");
+ }
+ return new CompleteUrdfUploadResponse(source);
+ }
+
+ private String resolveMainSource(List objectKeys) {
+ List urdfKeys = objectKeys.stream()
+ .filter(this::isUrdfFile)
+ .toList();
+ List rfsKeys = objectKeys.stream()
+ .filter(this::isRfsFile)
+ .toList();
+ if (urdfKeys.isEmpty() && rfsKeys.isEmpty()) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_MAIN_FILE_NOT_FOUND", "未检测到 .urdf 或 .rfs 主文件");
+ }
+ if (!urdfKeys.isEmpty() && !rfsKeys.isEmpty()) {
+ throw new BizException(HttpStatus.UNPROCESSABLE_ENTITY.value(), "COMPONENT_MAIN_FILE_TYPE_CONFLICT", "检测到 .urdf 和 .rfs 主文件,二者不能同时存在");
+ }
+ List candidateKeys = urdfKeys.isEmpty() ? rfsKeys : urdfKeys;
+ String extension = urdfKeys.isEmpty() ? ".rfs" : ".urdf";
+ if (candidateKeys.size() > 1) {
+ throw new BizException(
+ HttpStatus.UNPROCESSABLE_ENTITY.value(),
+ "COMPONENT_MAIN_FILE_NOT_UNIQUE",
+ "检测到多个 " + extension + " 主文件,无法确定主文件"
+ );
+ }
+ return candidateKeys.getFirst();
+ }
+
+ private boolean isUrdfFile(String key) {
+ return key.toLowerCase(Locale.ROOT).endsWith(".urdf");
+ }
+
+ private boolean isRfsFile(String key) {
+ String normalized = key.toLowerCase(Locale.ROOT);
+ return normalized.endsWith(".rfs") || normalized.endsWith(".rfs.json");
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/InterfaceDefinitionServiceImpl.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/InterfaceDefinitionServiceImpl.java
new file mode 100644
index 0000000..7005475
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/InterfaceDefinitionServiceImpl.java
@@ -0,0 +1,100 @@
+package com.linkerbot.cadworld.service.impl;
+
+import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.entity.InterfaceDefinitionEntity;
+import com.linkerbot.cadworld.entity.InterfaceDefinitionRevisionEntity;
+import com.linkerbot.cadworld.mapper.InterfaceDefinitionMapper;
+import com.linkerbot.cadworld.mapper.InterfaceDefinitionRevisionMapper;
+import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
+import com.linkerbot.cadworld.service.InterfaceDefinitionService;
+import java.util.List;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service @RequiredArgsConstructor
+public class InterfaceDefinitionServiceImpl implements InterfaceDefinitionService {
+ private final InterfaceDefinitionMapper definitionMapper;
+ private final InterfaceDefinitionRevisionMapper revisionMapper;
+ private final ObjectMapper objectMapper;
+ private final MechanicalInterfaceSolver solver;
+
+ public List list(String keyword) {
+ LambdaQueryWrapper query=new LambdaQueryWrapper<>();
+ if(keyword!=null&&!keyword.isBlank())query.and(w->w.like(InterfaceDefinitionEntity::getName,keyword).or().like(InterfaceDefinitionEntity::getDescription,keyword));
+ return definitionMapper.selectList(query.orderByDesc(InterfaceDefinitionEntity::getUpdatedAt)).stream().map(this::toJson).toList();
+ }
+ public JsonNode get(String id){return toJson(require(id));}
+ @Transactional public JsonNode create(JsonNode request){
+ String id=required(request,"id");
+ if(definitionMapper.selectById(id)!=null||revisionMapper.selectById(id+":1")!=null)throw invalid("接口 ID 已存在或已归档");
+ return save(new InterfaceDefinitionEntity(),request,id,false);
+ }
+ @Transactional public JsonNode update(String id,JsonNode request){
+ InterfaceDefinitionEntity entity=definitionMapper.selectOne(new LambdaQueryWrapper().eq(InterfaceDefinitionEntity::getId,id).last("FOR UPDATE"));
+ if(entity==null)throw invalid("接口不存在");
+ if(request.path("geometryRevision").asInt()!=entity.getGeometryRevision())throw invalid("接口已修改,请刷新后保存");
+ return save(entity,request,id,true);
+ }
+ private JsonNode save(InterfaceDefinitionEntity entity,JsonNode request,String id,boolean existing){
+ rejectLegacy(request);
+ MountGeometry geometry=objectMapper.convertValue(request.get("geometry"),MountGeometry.class);
+ Tolerances tolerances=objectMapper.convertValue(request.get("tolerances"),Tolerances.class);
+ int revision=existing?entity.getGeometryRevision()+1:1;
+ List connectableTargets=targets(request.get("connectableTargets"));
+ Definition definition=new Definition(id,revision,required(request,"name"),geometry,tolerances,connectableTargets,
+ objectMapper.convertValue(request.get("displayForward"),double[].class));
+ solver.validateDefinition(definition);
+ JsonNode normalizedGeometry=objectMapper.valueToTree(solver.normalize(geometry,tolerances));
+ boolean displayOnly=existing && normalizedGeometry.equals(entity.getGeometryJson())
+ && objectMapper.valueToTree(tolerances).equals(entity.getTolerancesJson())
+ && definition.name().equals(entity.getName())
+ && request.path("description").asText("").equals(entity.getDescription()==null?"":entity.getDescription())
+ && connectableTargets.equals(targets(entity.getConnectableTargetsJson()))
+ && (request.path("sourceGeometryHash").asText("").isBlank()
+ || request.path("sourceGeometryHash").asText().equals(entity.getSourceGeometryHash()));
+ if(displayOnly)revision=entity.getGeometryRevision();
+ entity.setDisplayForwardJson(objectMapper.valueToTree(solver.displayForward(definition)));
+ entity.setId(id);entity.setName(definition.name());entity.setDescription(request.path("description").asText(""));
+ entity.setGeometryRevision(revision);entity.setGeometryJson(objectMapper.valueToTree(solver.normalize(geometry,tolerances)));
+ entity.setTolerancesJson(objectMapper.valueToTree(tolerances));
+ entity.setConnectableTargetsJson(objectMapper.valueToTree(connectableTargets));
+ String sourceHash=request.path("sourceGeometryHash").asText("");
+ if(!sourceHash.isBlank() && !sourceHash.equals(entity.getSourceGeometryHash()) && !("sha256:"+sourceHash).equals(entity.getSourceGeometryHash())) {
+ entity.setSourceAssetKey("");entity.setSourceGeometryHash("");
+ }
+ if(existing)definitionMapper.updateById(entity);else definitionMapper.insert(entity);
+ InterfaceDefinitionRevisionEntity snapshot=new InterfaceDefinitionRevisionEntity();
+ snapshot.setId(id+":"+revision);snapshot.setDefinitionId(id);snapshot.setGeometryRevision(revision);snapshot.setDefinitionJson(toJson(entity, connectableTargets));
+ if(displayOnly)revisionMapper.updateById(snapshot);else revisionMapper.insert(snapshot);
+ return toJson(entity);
+ }
+ public Definition geometryDefinition(String id,int revision){
+ InterfaceDefinitionRevisionEntity entity=revisionMapper.selectById(id+":"+revision);
+ if(entity==null)throw invalid("接口几何修订不存在,请重新识别");
+ JsonNode n=entity.getDefinitionJson();
+ return new Definition(id,revision,n.path("name").asText(),objectMapper.convertValue(n.get("geometry"),MountGeometry.class),objectMapper.convertValue(n.get("tolerances"),Tolerances.class),targets(n.get("connectableTargets")),objectMapper.convertValue(n.get("displayForward"),double[].class));
+ }
+ @Transactional public void delete(String id){require(id);definitionMapper.deleteById(id);}
+ @Transactional public void attachAsset(String id,int revision,String key,String hash){
+ InterfaceDefinitionEntity e=definitionMapper.selectOne(new LambdaQueryWrapper().eq(InterfaceDefinitionEntity::getId,id).last("FOR UPDATE"));
+ if(e==null||e.getGeometryRevision()!=revision)throw invalid("接口已修订,请刷新后重新保存源文件");
+ if(e.getSourceGeometryHash()!=null && !e.getSourceGeometryHash().isBlank() && !hash.equals(e.getSourceGeometryHash()))throw invalid("该修订已有源文件,请创建新几何修订");
+ e.setSourceAssetKey(key);e.setSourceGeometryHash(hash);definitionMapper.updateById(e);
+ InterfaceDefinitionRevisionEntity snapshot=revisionMapper.selectById(id+":"+revision);
+ if(snapshot==null)throw invalid("接口修订不存在");
+ snapshot.setDefinitionJson(toJson(e));revisionMapper.updateById(snapshot);
+ }
+ private InterfaceDefinitionEntity require(String id){InterfaceDefinitionEntity e=definitionMapper.selectById(id);if(e==null)throw invalid("接口不存在");return e;}
+ private JsonNode toJson(InterfaceDefinitionEntity e){return toJson(e, targets(e.getConnectableTargetsJson()));}
+private JsonNode toJson(InterfaceDefinitionEntity e,List connectableTargets){ObjectNode n=objectMapper.createObjectNode();n.put("id",e.getId());n.put("name",e.getName());n.put("description",e.getDescription());n.put("geometryRevision",e.getGeometryRevision());n.set("geometry",e.getGeometryJson());n.set("displayForward",e.getDisplayForwardJson());n.set("tolerances",e.getTolerancesJson());n.set("connectableTargets",objectMapper.valueToTree(connectableTargets));if(e.getSourceAssetKey()!=null)n.put("sourceAssetKey",e.getSourceAssetKey());if(e.getSourceGeometryHash()!=null)n.put("sourceGeometryHash",e.getSourceGeometryHash());return n;}
+ private List targets(JsonNode value){if(value==null||value.isNull()||!value.isArray())return List.of();List result=new java.util.ArrayList<>();value.forEach(item->{String target=item.asText("").trim();if(!target.isEmpty()&&!result.contains(target))result.add(target);});return List.copyOf(result);}
+ private String required(JsonNode n,String key){String s=n.path(key).asText("").trim();if(s.isEmpty())throw invalid(key+" 不能为空");return s;}
+ private void rejectLegacy(JsonNode n){for(String key:List.of("profiles","mateRules","frameInComponent","allowedClockingDeg","xAxisAngleDeg"))if(n.has(key))throw invalid("不支持的接口结构:"+key);}
+ private BizException invalid(String message){return new BizException(422,"INVALID_INTERFACE",message);}
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ObjectStorageUrlResolver.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ObjectStorageUrlResolver.java
new file mode 100644
index 0000000..ba99fd5
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/ObjectStorageUrlResolver.java
@@ -0,0 +1,41 @@
+package com.linkerbot.cadworld.service.impl;
+
+import com.linkerbot.cadworld.config.StorageProperties;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.stream.Collectors;
+import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.util.UriUtils;
+
+@Component
+@RequiredArgsConstructor
+public class ObjectStorageUrlResolver {
+
+ private final StorageProperties storageProperties;
+
+ public String resolvePublicUrl(String objectKey) {
+ if (!StringUtils.hasText(objectKey)) {
+ return "";
+ }
+ if (!StringUtils.hasText(storageProperties.publicBaseUrl())) {
+ throw new IllegalStateException("Object storage public base URL is not configured");
+ }
+ return trimTrailingSlash(storageProperties.publicBaseUrl().trim()) + "/" + encodePath(objectKey.trim());
+ }
+
+ private String encodePath(String path) {
+ return Arrays.stream(path.split("/", -1))
+ .map(segment -> UriUtils.encodePathSegment(segment, StandardCharsets.UTF_8))
+ .collect(Collectors.joining("/"));
+ }
+
+ private String trimTrailingSlash(String value) {
+ String result = value;
+ while (result.endsWith("/")) {
+ result = result.substring(0, result.length() - 1);
+ }
+ return result;
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/UserManagementServiceImpl.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/UserManagementServiceImpl.java
new file mode 100644
index 0000000..3013fad
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/impl/UserManagementServiceImpl.java
@@ -0,0 +1,93 @@
+package com.linkerbot.cadworld.service.impl;
+
+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.dto.user.SaveUserRequest;
+import com.linkerbot.cadworld.dto.user.UserResponse;
+import com.linkerbot.cadworld.entity.SysUser;
+import com.linkerbot.cadworld.enums.UserStatus;
+import com.linkerbot.cadworld.enums.UserType;
+import com.linkerbot.cadworld.mapper.SysUserMapper;
+import com.linkerbot.cadworld.service.UserManagementService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.dao.DuplicateKeyException;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+@Service
+@RequiredArgsConstructor
+public class UserManagementServiceImpl implements UserManagementService {
+ private final SysUserMapper mapper;
+
+ @Override
+ public PageResponse list(long page, long size, String keyword, UserType type, UserStatus status) {
+ LambdaQueryWrapper query = new LambdaQueryWrapper()
+ .eq(type != null, SysUser::getUserType, type).eq(status != null, SysUser::getStatus, status);
+ if (StringUtils.hasText(keyword)) {
+ String term = keyword.trim();
+ query.and(q -> q.like(SysUser::getPhone, term).or().like(SysUser::getNickname, term));
+ }
+ Page result = mapper.selectPage(new Page<>(page, size),
+ query.orderByDesc(SysUser::getUpdatedAt).orderByDesc(SysUser::getId));
+ return new PageResponse<>(result.getRecords().stream().map(this::response).toList(), page, size, result.getTotal());
+ }
+
+ @Override
+ public UserResponse get(Long id) { return response(require(id)); }
+
+ @Override
+ @Transactional
+ public UserResponse create(SaveUserRequest request) {
+ SysUser user = new SysUser();
+ user.setDeleted(0);
+ apply(user, request);
+ try {
+ mapper.insert(user);
+ } catch (DuplicateKeyException exception) {
+ throw duplicatePhone();
+ }
+ return response(require(user.getId()));
+ }
+
+ @Override
+ @Transactional
+ public UserResponse update(Long id, SaveUserRequest request) {
+ SysUser user = require(id);
+ apply(user, request);
+ try {
+ if (mapper.updateById(user) == 0) throw notFound();
+ } catch (DuplicateKeyException exception) {
+ throw duplicatePhone();
+ }
+ return response(require(id));
+ }
+
+ @Override
+ @Transactional
+ public void delete(Long id) {
+ require(id);
+ if (mapper.deleteById(id) == 0) throw notFound();
+ }
+
+ private void apply(SysUser user, SaveUserRequest request) {
+ user.setPhone(request.phone().trim());
+ user.setNickname(request.nickname().trim());
+ user.setStatus(request.status() == null ? (user.getStatus() == null ? UserStatus.ACTIVE : user.getStatus()) : request.status());
+ user.setUserType(request.userType() == null ? (user.getUserType() == null ? UserType.NORMAL : user.getUserType()) : request.userType());
+ }
+
+ private SysUser require(Long id) {
+ SysUser user = mapper.selectById(id);
+ if (user == null) throw notFound();
+ return user;
+ }
+
+ private BizException notFound() { return new BizException(404, "USER_NOT_FOUND", "用户不存在"); }
+ private BizException duplicatePhone() { return new BizException(409, "USER_PHONE_DUPLICATE", "手机号已存在,包括已删除的用户"); }
+ private UserResponse response(SysUser user) {
+ return new UserResponse(user.getId(), user.getPhone(), user.getNickname(), user.getStatus(), user.getUserType(), user.getCreatedAt(), user.getUpdatedAt());
+ }
+}
diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/support/ComponentUploadSessionTokenProvider.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/support/ComponentUploadSessionTokenProvider.java
new file mode 100644
index 0000000..96616b1
--- /dev/null
+++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/support/ComponentUploadSessionTokenProvider.java
@@ -0,0 +1,62 @@
+package com.linkerbot.cadworld.service.support;
+
+import com.linkerbot.cadworld.config.UploadSessionProperties;
+import com.linkerbot.cadworld.enums.ComponentUploadType;
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.security.Keys;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Date;
+import javax.crypto.SecretKey;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ComponentUploadSessionTokenProvider {
+
+ private static final String TOKEN_TYPE_CLAIM = "type";
+ private static final String KEY_PREFIX_CLAIM = "keyPrefix";
+
+ private final UploadSessionProperties properties;
+ private final SecretKey secretKey;
+
+ public ComponentUploadSessionTokenProvider(UploadSessionProperties properties) {
+ this.properties = properties;
+ this.secretKey = properties.secret() == null || properties.secret().isBlank()
+ ? Jwts.SIG.HS256.key().build()
+ : Keys.hmacShaKeyFor(properties.secret().getBytes(StandardCharsets.UTF_8));
+ }
+
+ public String generateToken(Long userId, ComponentUploadType uploadType, String keyPrefix, Instant expiresAt) {
+ return Jwts.builder()
+ .issuer(properties.issuer())
+ .subject(String.valueOf(userId))
+ .claim(TOKEN_TYPE_CLAIM, uploadType.tokenType())
+ .claim(KEY_PREFIX_CLAIM, keyPrefix)
+ .issuedAt(new Date())
+ .expiration(Date.from(expiresAt))
+ .signWith(secretKey)
+ .compact();
+ }
+
+ public UploadSessionClaims parseToken(String token) {
+ Claims claims = parseClaims(token);
+ return new UploadSessionClaims(
+ Long.valueOf(claims.getSubject()),
+ ComponentUploadType.fromTokenType(claims.get(TOKEN_TYPE_CLAIM, String.class)),
+ claims.get(KEY_PREFIX_CLAIM, String.class),
+ claims.getExpiration().toInstant()
+ );
+ }
+
+ private Claims parseClaims(String token) {
+ return Jwts.parser()
+ .verifyWith(secretKey)
+ .build()
+ .parseSignedClaims(token)
+ .getPayload();
+ }
+
+ public record UploadSessionClaims(Long userId, ComponentUploadType uploadType, String keyPrefix, Instant expiresAt) {
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/mechanicalinterface/MechanicalInterfaceSolverTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/mechanicalinterface/MechanicalInterfaceSolverTest.java
new file mode 100644
index 0000000..ab6c0fe
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/mechanicalinterface/MechanicalInterfaceSolverTest.java
@@ -0,0 +1,114 @@
+package com.linkerbot.cadworld.mechanicalinterface;
+
+import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
+import static com.linkerbot.cadworld.mechanicalinterface.RigidMath.*;
+import static org.assertj.core.api.Assertions.*;
+import java.util.*;
+import org.junit.jupiter.api.Test;
+
+class MechanicalInterfaceSolverTest {
+ final MechanicalInterfaceSolver solver=new MechanicalInterfaceSolver();
+ MountGeometry geometry(double[][] points){
+ List holes=new ArrayList<>();
+ for(int i=0;i poses(Definition d,MountGeometry g){return solver.enumeratePortPoses(d,new PoseRequest(1,"link",g,"source-hash")).candidates();}
+ Port port(Definition d,MountGeometry g,int index){PoseCandidate p=poses(d,g).get(index);return solver.confirmPortPose(d,new Port("port","link",d.id(),1,g,new SelectedPose(p.id(),p.templateInLink(),p.holeMapping(),p.orientationDirectionInLink()),"source-hash",SOLVER_VERSION));}
+ MountGeometry transformed(MountGeometry g,RigidPose pose,boolean reverseNormal){
+ double[] r=rotation(pose);
+ return new MountGeometry(new Plane(point(pose,g.plane().pointM()),scale(rotate(r,g.plane().outwardNormal()),reverseNormal?-1:1)),g.holes().stream().map(h->new Hole(h.id(),point(pose,h.pointOnPlaneM()),rotate(r,h.axis()),h.diameterM())).toList());
+ }
+ @Test void enumeratesGeometrySymmetriesInsteadOfHoleCount(){
+ assertThat(poses(definition(square()),square())).hasSize(4);
+ MountGeometry rectangle=geometry(new double[][]{{-.03,-.02,0},{.03,-.02,0},{.03,.02,0},{-.03,.02,0}});
+ assertThat(poses(definition(rectangle),rectangle)).hasSize(2);
+ MountGeometry pair=geometry(new double[][]{{-.02,0,0},{.02,0,0}});
+ assertThat(poses(definition(pair),pair)).hasSize(2);
+ }
+ @Test void unorderedObservationsHaveStableIds(){
+ MountGeometry g=square();List reversed=new ArrayList<>(g.holes());Collections.reverse(reversed);
+ assertThat(poses(definition(g),new MountGeometry(g.plane(),reversed)).stream().map(PoseCandidate::id).toList())
+ .isEqualTo(poses(definition(g),g).stream().map(PoseCandidate::id).toList());
+ }
+ @Test void candidateDirectionsAreUnitAndStableWhenObservationOrderChanges(){
+ MountGeometry g=square();
+ List original=poses(definition(g),g);
+ List shuffled=new ArrayList<>(g.holes());
+ Collections.rotate(shuffled,2);
+ List reordered=poses(definition(g),new MountGeometry(g.plane(),shuffled));
+ assertThat(reordered.stream().map(PoseCandidate::id).toList())
+ .isEqualTo(original.stream().map(PoseCandidate::id).toList());
+ for(int i=0;i before=poses(original,g), after=poses(calibrated,g);
+ assertThat(after).hasSize(2);
+ assertThat(after.stream().map(PoseCandidate::id).toList()).isEqualTo(before.stream().map(PoseCandidate::id).toList());
+ assertThat(dot(after.get(0).orientationDirectionInLink(),after.get(1).orientationDirectionInLink())).isCloseTo(-1,within(1e-10));
+ assertThat(dot(after.get(0).orientationDirectionInLink(),before.get(0).orientationDirectionInLink())).isCloseTo(0,within(1e-10));
+ Port parent=port(original,g,0), child=port(original,g,1);
+ ResolvedConnection oldConnection=solver.resolveLockedConnection(original,parent,child);
+ ResolvedConnection newConnection=solver.resolveLockedConnection(calibrated,parent,child);
+ assertThat(newConnection.childLinkInParentLink().positionM()).containsExactly(oldConnection.childLinkInParentLink().positionM());
+ assertThat(oldConnection.orientationAngleRad()).isCloseTo(0, within(1e-10));
+ assertThat(newConnection.orientationAngleRad()).isCloseTo(0, within(1e-10));
+ }
+ @Test void displayForwardMustBeFiniteNonzeroAndInPlane(){
+ for(double[] forward:new double[][]{{0,0,0},{0,0,1},{Double.NaN,1,0}})
+ assertThatThrownBy(()->solver.validateDefinition(new Definition("mount",1,"Mount",square(),Tolerances.defaults(),List.of(),forward)))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+ @Test void confirmationAlwaysStoresServerDerivedCandidateDirection(){
+ MountGeometry g=square();Definition d=definition(g);PoseCandidate candidate=poses(d,g).get(0);
+ SelectedPose submittedPose=new SelectedPose(candidate.id(),identity(),List.of(),new double[]{0,0,0});
+ Port confirmed=solver.confirmPortPose(d,new Port("port","link",d.id(),1,g,submittedPose,"source-hash",SOLVER_VERSION));
+ assertThat(confirmed.selectedPose().orientationDirectionInLink())
+ .containsExactly(candidate.orientationDirectionInLink());
+ }
+ @Test void compositeRotationAndTranslationRoundTrip(){
+ MountGeometry g=square();RigidPose transform=compose(pose(new double[]{.3,-.2,.4},rotationAxis(new double[]{0,1,0},Math.PI/2)),pose(new double[3],rotationAxis(new double[]{1,0,0},.71)));
+ MountGeometry moved=transformed(g,transform,false);assertThat(poses(definition(g),moved)).hasSize(4);
+ Port a=port(definition(g),g,0), b=port(definition(g),moved,2);
+ ResolvedConnection resolved=solver.resolveLockedConnection(definition(g),a,b);
+ assertThat(resolved.maxHoleOffsetM()).isLessThan(1e-10);
+ assertThat(resolved.maxAxisAngleRad()).isLessThan(1e-7);
+ }
+ @Test void asymmetricComplementaryFacesMateButSameHandedFacesDoNot(){
+ MountGeometry g=geometry(new double[][]{{0,0,0},{.04,0,0},{.009,.017,0}});
+ Definition d=definition(g);MountGeometry opposite=transformed(g,identity(),true);
+ assertThat(poses(d,g)).hasSize(1);assertThat(poses(d,opposite)).hasSize(1);
+ assertThat(solver.resolveLockedConnection(d,port(d,g,0),port(d,opposite,0)).maxHoleOffsetM()).isLessThan(1e-10);
+ assertThatThrownBy(()->solver.resolveLockedConnection(d,port(d,g,0),port(d,g,0))).hasMessageContaining("对接基准");
+ }
+ @Test void savedSelectionsAreNeverReplacedByBestMatch(){
+ MountGeometry g=square();Definition d=definition(g);Port a=port(d,g,0),b=port(d,g,1);
+ ResolvedConnection first=solver.resolveLockedConnection(d,a,b),second=solver.resolveLockedConnection(d,a,b);
+ assertThat(first.childLinkInParentLink().quaternionXYZW()).containsExactly(second.childLinkInParentLink().quaternionXYZW());
+ assertThat(Arrays.toString(first.childLinkInParentLink().quaternionXYZW())).isNotEqualTo(Arrays.toString(solver.resolveLockedConnection(d,a,a).childLinkInParentLink().quaternionXYZW()));
+ }
+ @Test void badHoleOrAxisRejectsEntirePattern(){
+ MountGeometry g=square();List holes=new ArrayList<>(g.holes());Hole h=holes.get(0);
+ holes.set(0,new Hole(h.id(),add(h.pointOnPlaneM(),new double[]{.005,0,0}),h.axis(),h.diameterM()));
+ assertThat(poses(definition(g),new MountGeometry(g.plane(),holes))).isEmpty();
+ holes.set(0,new Hole(h.id(),h.pointOnPlaneM(),unit(new double[]{.2,0,1}),h.diameterM()));
+ assertThat(poses(definition(g),new MountGeometry(g.plane(),holes))).isEmpty();
+ assertThat(solver.enumeratePortPoses(definition(g),new PoseRequest(1,"link",new MountGeometry(g.plane(),holes),"source-hash")).reasons())
+ .anyMatch(reason -> reason.contains("h0") && reason.contains("孔轴"));
+ assertThat(poses(definition(g),new MountGeometry(g.plane(),holes.subList(0,3)))).isEmpty();
+ }
+ @Test void invalidSourceOrVersionFailsClosed(){
+ MountGeometry g=square();Definition d=definition(g);Port p=port(d,g,0);
+ assertThatThrownBy(()->solver.confirmPortPose(d,new Port(p.id(),p.linkName(),p.definitionId(),2,g,p.selectedPose(),p.sourceGeometryHash(),SOLVER_VERSION))).hasMessageContaining("修订");
+ assertThatThrownBy(()->solver.confirmPortPose(d,new Port(p.id(),p.linkName(),p.definitionId(),1,g,p.selectedPose(),"different",SOLVER_VERSION))).hasMessageContaining("失效");
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/InterfaceBrepServiceTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/InterfaceBrepServiceTest.java
new file mode 100644
index 0000000..6852bf7
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/InterfaceBrepServiceTest.java
@@ -0,0 +1,63 @@
+package com.linkerbot.cadworld.service;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.cadworld.config.InterfaceBrepProperties;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.springframework.mock.web.MockMultipartFile;
+
+import static org.assertj.core.api.Assertions.*;
+
+class InterfaceBrepServiceTest {
+ @TempDir Path temp;
+
+ @Test
+ void invalidExtensionEmptyAndOversizeFilesAreRejectedBeforeProcessLaunch() {
+ InterfaceBrepService service = service("missing", "missing", 1, 3);
+ assertThatThrownBy(() -> service.analyze(file("a.stl", "x"))).hasMessageContaining("STEP");
+ assertThatThrownBy(() -> service.analyze(file("a.step", ""))).hasMessageContaining("请选择");
+ assertThatThrownBy(() -> service.analyze(file("a.step", "large"))).hasMessageContaining("超过");
+ }
+
+ @Test
+ void missingExecutableAndMissingScriptHaveExplicitErrors() throws Exception {
+ assertThatThrownBy(() -> service("missing", temp.resolve("missing.py").toString(), 1, 100).analyze(file("a.step", "x")))
+ .hasMessageContaining("脚本不存在");
+ Path script = script("exit 0");
+ assertThatThrownBy(() -> service(temp.resolve("missing-binary").toString(), script.toString(), 1, 100).analyze(file("a.step", "x")))
+ .hasMessageContaining("服务不可用");
+ }
+
+ @Test
+ void validOutputInvalidSchemaAndProcessTimeoutAreHandled() throws Exception {
+ Path valid = script("printf '{\"schemaVersion\":\"interface-step-brep/v1\",\"faces\":[]}' > \"$3\"");
+ assertThat(service("/bin/sh", valid.toString(), 1, 100).analyze(file("a.step", "x")).path("schemaVersion").asText())
+ .isEqualTo("interface-step-brep/v1");
+ Path invalid = script("printf '{\"schemaVersion\":\"unknown\"}' > \"$3\"");
+ assertThatThrownBy(() -> service("/bin/sh", invalid.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("版本");
+ Path slow = script("sleep 5");
+ assertThatThrownBy(() -> service("/bin/sh", slow.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("超时");
+ }
+
+ @Test
+ void missingOcpAndInvalidStepRemainDifferentErrors() throws Exception {
+ Path noOcp = script("echo \"No module named 'OCP'\"; exit 1");
+ assertThatThrownBy(() -> service("/bin/sh", noOcp.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("未安装");
+ Path invalid = script("echo 'STEP_BREP_ERROR:invalid topology'; exit 1");
+ assertThatThrownBy(() -> service("/bin/sh", invalid.toString(), 1, 100).analyze(file("a.step", "x"))).hasMessageContaining("invalid topology");
+ }
+
+ private InterfaceBrepService service(String python, String script, int timeout, long max) {
+ return new InterfaceBrepService(new InterfaceBrepProperties(python, script, timeout, max, 10000), new ObjectMapper());
+ }
+ private Path script(String content) throws Exception {
+ Path script = Files.createTempFile(temp, "extractor-", ".sh");
+ Files.writeString(script, content);
+ return script;
+ }
+ private MockMultipartFile file(String name, String content) {
+ return new MockMultipartFile("file", name, "application/octet-stream", content.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/UploadSessionTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/UploadSessionTest.java
new file mode 100644
index 0000000..f9e9417
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/UploadSessionTest.java
@@ -0,0 +1,37 @@
+package com.linkerbot.cadworld.service;
+
+import com.linkerbot.cadworld.config.StorageProperties;
+import com.linkerbot.cadworld.config.UploadSessionProperties;
+import com.linkerbot.cadworld.enums.ComponentUploadType;
+import com.linkerbot.cadworld.service.client.ObjectStorageClient;
+import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
+import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
+import java.time.Duration;
+import java.time.Instant;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+class UploadSessionTest {
+ @Test
+ void tokenTypeOwnerExpiryAndPathAreCheckedIndependentlyOfUserAuthentication() {
+ var tokens = new ComponentUploadSessionTokenProvider(new UploadSessionProperties("test", "test-upload-signing-key-32-bytes-long"));
+ var storage = mock(ObjectStorageClient.class);
+ var properties = new StorageProperties("local", "components/urdf", "components/cover-images", "http://localhost/admin-api/component-assets", "http://localhost", Duration.ofMinutes(30));
+ var support = new ComponentUploadSupport(properties, storage, tokens);
+ ComponentUploadType type = ComponentUploadType.values()[0];
+ String token = tokens.generateToken(0L, type, "components/urdf/0/session/", Instant.now().plusSeconds(60));
+ assertThat(support.requireUploadSession(0L, token, type, "INVALID").userId()).isZero();
+ assertThatThrownBy(() -> support.requireUploadSession(1L, token, type, "INVALID")).hasMessageContaining("用户");
+ ComponentUploadType other = ComponentUploadType.values()[1];
+ assertThatThrownBy(() -> support.requireUploadSession(0L, token, other, "INVALID")).hasMessageContaining("类型");
+ String expired = tokens.generateToken(0L, type, "components/urdf/0/session/", Instant.now().minusSeconds(60));
+ assertThatThrownBy(() -> support.requireUploadSession(0L, expired, type, "INVALID")).hasMessageContaining("过期");
+ for (String path : new String[]{"../escape", "/absolute", "a/../../escape", "a//b"}) {
+ assertThatThrownBy(() -> support.prepareObjectUpload(0L, token, type, "INVALID", path, "application/octet-stream"))
+ .hasMessageContaining("路径非法");
+ }
+ verifyNoInteractions(storage);
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/client/LocalObjectStorageClientTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/client/LocalObjectStorageClientTest.java
new file mode 100644
index 0000000..4cfaf76
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/client/LocalObjectStorageClientTest.java
@@ -0,0 +1,34 @@
+package com.linkerbot.cadworld.service.client;
+
+import com.linkerbot.cadworld.config.StorageProperties;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.file.Path;
+import java.time.Duration;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class LocalObjectStorageClientTest {
+
+ @TempDir
+ Path tempDir;
+
+ @Test
+ void writesReadsAndRejectsTraversal() {
+ LocalObjectStorageClient client = new LocalObjectStorageClient(new StorageProperties(
+ "local", "components/urdf", "components/cover-images", "", "", tempDir.toString(), Duration.ofMinutes(5)));
+
+ client.putObject("components/urdf/1/model.rfs", "application/json",
+ new ByteArrayInputStream("{}".getBytes()), 2);
+
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ client.writeObjectTo("components/urdf/1/model.rfs", output);
+ assertArrayEquals("{}".getBytes(), output.toByteArray());
+ assertTrue(client.objectExists("components/urdf/1/model.rfs"));
+ assertThrows(RuntimeException.class, () -> client.objectExists("../outside"));
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentCoverImageUploadServiceImplTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentCoverImageUploadServiceImplTest.java
new file mode 100644
index 0000000..4e8cbea
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentCoverImageUploadServiceImplTest.java
@@ -0,0 +1,21 @@
+package com.linkerbot.cadworld.service.impl;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.lang.reflect.Method;
+import org.junit.jupiter.api.Test;
+
+class ComponentCoverImageUploadServiceImplTest {
+
+ @Test
+ void acceptsGifCoverObjectsAlongsideExistingImageTypes() throws Exception {
+ ComponentCoverImageUploadServiceImpl service = new ComponentCoverImageUploadServiceImpl(null, null, null);
+ Method method = ComponentCoverImageUploadServiceImpl.class.getDeclaredMethod("isSupportedImage", String.class);
+ method.setAccessible(true);
+
+ assertTrue((Boolean) method.invoke(service, "projects/cover/cover.GIF"));
+ assertTrue((Boolean) method.invoke(service, "projects/cover/cover.webp"));
+ assertFalse((Boolean) method.invoke(service, "projects/cover/cover.svg"));
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentServiceImplTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentServiceImplTest.java
new file mode 100644
index 0000000..1846dd8
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentServiceImplTest.java
@@ -0,0 +1,190 @@
+package com.linkerbot.cadworld.service.impl;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
+import com.linkerbot.cadworld.dto.component.ComponentResponse;
+import com.linkerbot.cadworld.entity.Component;
+import com.linkerbot.cadworld.mapper.ComponentMapper;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.dao.DuplicateKeyException;
+import org.springframework.http.HttpStatus;
+
+@ExtendWith(MockitoExtension.class)
+class ComponentServiceImplTest {
+
+ @Mock
+ private ComponentMapper componentMapper;
+ @Mock
+ private ObjectStorageUrlResolver objectStorageUrlResolver;
+
+ private ComponentServiceImpl service;
+
+ @BeforeEach
+ void setUp() {
+ service = new ComponentServiceImpl(
+ componentMapper,
+ null,
+ objectStorageUrlResolver,
+ new ObjectMapper(), new com.linkerbot.cadworld.mechanicalinterface.ComponentPortValidationService(
+ MechanicalTestFixtures.definitions(),MechanicalTestFixtures.SOLVER,new ObjectMapper(),
+ new com.linkerbot.cadworld.mechanicalinterface.UrdfSourceValidation(),
+ org.mockito.Mockito.mock(com.linkerbot.cadworld.mechanicalinterface.UrdfAssetVerifier.class)));
+ }
+
+ @Test
+ void createComponentRejectsDuplicateNameBeforeInsert() {
+ when(componentMapper.selectCount(any())).thenReturn(1L);
+
+ assertThatThrownBy(() -> service.createComponent(1L, request(" 机械臂 ")))
+ .isInstanceOf(BizException.class)
+ .extracting("code", "httpStatus", "message")
+ .containsExactly("COMPONENT_NAME_DUPLICATE", HttpStatus.CONFLICT.value(), "组件名称已存在,请更换名称");
+ verify(componentMapper, never()).insert(any(Component.class));
+ }
+
+ @Test
+ void createComponentMapsDuplicateKeyToBizException() {
+ when(componentMapper.selectCount(any())).thenReturn(0L);
+ when(componentMapper.insert(any(Component.class))).thenThrow(new DuplicateKeyException("Duplicate entry"));
+
+ assertThatThrownBy(() -> service.createComponent(1L, request("机械臂")))
+ .isInstanceOf(BizException.class)
+ .extracting("code", "httpStatus", "message")
+ .containsExactly("COMPONENT_NAME_DUPLICATE", HttpStatus.CONFLICT.value(), "组件名称已存在,请更换名称");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"arm_1", "arm_2", "arm_3", "arm_4", "arm_5", "arm_6", "arm_7", "arm_8"})
+ void createComponentAcceptsManipulatorSegments(String componentType) {
+ AtomicReference inserted = new AtomicReference<>();
+ when(componentMapper.selectCount(any())).thenReturn(0L);
+ when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
+ Component component = invocation.getArgument(0);
+ component.setId(99L);
+ inserted.set(component);
+ return 1;
+ });
+ when(componentMapper.selectById(99L)).thenAnswer(invocation -> inserted.get());
+
+ ComponentResponse response = service.createComponent(1L, request("机械臂-" + componentType, componentType, "manipulator"));
+
+ assertThat(response.componentType()).isEqualTo(componentType);
+ assertThat(response.robotType()).isEqualTo("manipulator");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "torso", "head", "neck", "waist",
+ "left_arm", "right_arm", "left_hand", "right_hand",
+ "left_leg", "right_leg", "left_foot", "right_foot"
+ })
+ void createComponentAcceptsHumanoidSplitComponentTypes(String componentType) {
+ AtomicReference inserted = new AtomicReference<>();
+ when(componentMapper.selectCount(any())).thenReturn(0L);
+ when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
+ Component component = invocation.getArgument(0);
+ component.setId(99L);
+ inserted.set(component);
+ return 1;
+ });
+ when(componentMapper.selectById(99L)).thenAnswer(invocation -> inserted.get());
+
+ ComponentResponse response = service.createComponent(1L, request("人形-" + componentType, componentType, "humanoid"));
+
+ assertThat(response.componentType()).isEqualTo(componentType);
+ assertThat(response.robotType()).isEqualTo("humanoid");
+ }
+
+ @Test
+ void createComponentAllowsFreeCategoryRegardlessOfRobotSource() {
+ AtomicReference inserted = new AtomicReference<>();
+ when(componentMapper.selectCount(any())).thenReturn(0L);
+ when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
+ Component component = invocation.getArgument(0);
+ component.setId(101L);
+ inserted.set(component);
+ return 1;
+ });
+ when(componentMapper.selectById(101L)).thenAnswer(invocation -> inserted.get());
+
+ ComponentResponse response = service.createComponent(1L, request("机械臂躯干", "安装基座", "manipulator"));
+
+ assertThat(response.category()).isEqualTo("安装基座");
+ assertThat(response.robotType()).isEqualTo("manipulator");
+ verify(componentMapper).insert(any(Component.class));
+ }
+
+ @Test
+ void createComponentDoesNotRestrictCategoryToRobotSource() {
+ AtomicReference inserted = new AtomicReference<>();
+ when(componentMapper.selectCount(any())).thenReturn(0L);
+ when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
+ Component component = invocation.getArgument(0);
+ component.setId(102L);
+ inserted.set(component);
+ return 1;
+ });
+ when(componentMapper.selectById(102L)).thenAnswer(invocation -> inserted.get());
+
+ ComponentResponse response = service.createComponent(1L, request("人形机械臂一段", "柔性执行器", "humanoid"));
+
+ assertThat(response.category()).isEqualTo("柔性执行器");
+ assertThat(response.robotType()).isEqualTo("humanoid");
+ verify(componentMapper).insert(any(Component.class));
+ }
+
+ @Test
+ void createsNameAndTagsWithoutCategoryOrDescription() {
+ AtomicReference inserted = new AtomicReference<>();
+ when(componentMapper.selectCount(any())).thenReturn(0L);
+ when(componentMapper.insert(any(Component.class))).thenAnswer(invocation -> {
+ Component value = invocation.getArgument(0);
+ value.setId(103L); inserted.set(value); return 1;
+ });
+ when(componentMapper.selectById(103L)).thenAnswer(invocation -> inserted.get());
+ var metadata = new com.linkerbot.cadworld.dto.component.ComponentAssemblyMetadata(
+ java.util.List.of("工具", "末端执行器,铲取"), java.util.List.of(), null);
+ var request = new CreateComponentRequest("铲子", null, "humanoid", "未指定", "未指定",
+ "shovel.rfs", "", null, new ObjectMapper().createObjectNode(), metadata);
+ try (var factory = jakarta.validation.Validation.buildDefaultValidatorFactory()) {
+ assertThat(factory.getValidator().validate(request)).isEmpty();
+ }
+ var response = service.createComponent(1L, request);
+ assertThat(response.category()).isEmpty();
+ assertThat(response.description()).isEmpty();
+ assertThat(response.assemblyMetadata().tags()).containsExactly("工具", "末端执行器", "铲取");
+ }
+
+ private CreateComponentRequest request(String componentName) {
+ return request(componentName, "left_arm", "humanoid");
+ }
+
+ private CreateComponentRequest request(String componentName, String componentType, String robotType) {
+ return new CreateComponentRequest(
+ componentName,
+ componentType,
+ robotType,
+ "示例公司",
+ "M1",
+ "components/urdf/arm.urdf",
+ "",
+ "示例组件",
+ new ObjectMapper().createObjectNode()
+ );
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentUploadSupportTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentUploadSupportTest.java
new file mode 100644
index 0000000..369d867
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/ComponentUploadSupportTest.java
@@ -0,0 +1,88 @@
+package com.linkerbot.cadworld.service.impl;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import com.linkerbot.cadworld.common.exception.BizException;
+import com.linkerbot.cadworld.service.client.ObjectStorageClient;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+
+class ComponentUploadSupportTest {
+
+ private static final String KEY_PREFIX = "components/urdf/1/20260920/session-id/";
+
+ @Test
+ void verifiesExactObjectsWithoutListingTheBucket() {
+ RecordingObjectStorageClient storageClient = new RecordingObjectStorageClient(List.of(
+ KEY_PREFIX + "LeKiwi.rfs",
+ KEY_PREFIX + "meshes/body.stl"
+ ));
+ ComponentUploadSupport support = createSupport(storageClient);
+
+ List objectKeys = support.verifyUploadedObjectKeys(KEY_PREFIX, List.of(
+ KEY_PREFIX + "LeKiwi.rfs",
+ KEY_PREFIX + "meshes/body.stl"
+ ));
+
+ assertEquals(List.of(
+ KEY_PREFIX + "LeKiwi.rfs",
+ KEY_PREFIX + "meshes/body.stl"
+ ), objectKeys);
+ assertEquals(objectKeys, storageClient.checkedObjectKeys);
+ }
+
+ @Test
+ void rejectsAnObjectOutsideTheUploadSessionPrefix() {
+ RecordingObjectStorageClient storageClient = new RecordingObjectStorageClient(List.of());
+ ComponentUploadSupport support = createSupport(storageClient);
+
+ BizException exception = assertThrows(BizException.class, () -> support.verifyUploadedObjectKeys(
+ KEY_PREFIX,
+ List.of("components/urdf/1/another-session/LeKiwi.rfs")
+ ));
+
+ assertEquals("INVALID_COMPONENT_UPLOAD_OBJECT", exception.getCode());
+ assertEquals(List.of(), storageClient.checkedObjectKeys);
+ }
+
+ @Test
+ void rejectsAnObjectThatWasNotUploaded() {
+ RecordingObjectStorageClient storageClient = new RecordingObjectStorageClient(List.of());
+ ComponentUploadSupport support = createSupport(storageClient);
+
+ BizException exception = assertThrows(BizException.class, () -> support.verifyUploadedObjectKeys(
+ KEY_PREFIX,
+ List.of(KEY_PREFIX + "missing.rfs")
+ ));
+
+ assertEquals("COMPONENT_UPLOAD_OBJECT_MISSING", exception.getCode());
+ }
+
+ private ComponentUploadSupport createSupport(ObjectStorageClient storageClient) {
+ return new ComponentUploadSupport(null, storageClient, null);
+ }
+
+ private static final class RecordingObjectStorageClient implements ObjectStorageClient {
+
+ private final List existingObjectKeys;
+ private final List checkedObjectKeys = new ArrayList<>();
+
+ private RecordingObjectStorageClient(List existingObjectKeys) {
+ this.existingObjectKeys = existingObjectKeys;
+ }
+
+ @Override
+ public String createUploadUrl(String objectKey, String contentType, Duration duration) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean objectExists(String objectKey) {
+ checkedObjectKeys.add(objectKey);
+ return existingObjectKeys.contains(objectKey);
+ }
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/InterfaceDefinitionRevisionTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/InterfaceDefinitionRevisionTest.java
new file mode 100644
index 0000000..7518a30
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/InterfaceDefinitionRevisionTest.java
@@ -0,0 +1,72 @@
+package com.linkerbot.cadworld.service.impl;
+
+import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.Mockito.*;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.linkerbot.cadworld.entity.InterfaceDefinitionEntity;
+import com.linkerbot.cadworld.entity.InterfaceDefinitionRevisionEntity;
+import com.linkerbot.cadworld.mapper.InterfaceDefinitionMapper;
+import com.linkerbot.cadworld.mapper.InterfaceDefinitionRevisionMapper;
+import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
+import java.util.List;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+class InterfaceDefinitionRevisionTest {
+ final ObjectMapper json=new ObjectMapper();
+ final InterfaceDefinitionMapper definitions=mock(InterfaceDefinitionMapper.class);
+ final InterfaceDefinitionRevisionMapper revisions=mock(InterfaceDefinitionRevisionMapper.class);
+ final InterfaceDefinitionServiceImpl service=new InterfaceDefinitionServiceImpl(definitions,revisions,json,new MechanicalInterfaceSolver());
+ final MountGeometry geometry=new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),List.of(
+ new Hole("a",new double[]{-.02,0,0},new double[]{0,0,1},.004),
+ new Hole("b",new double[]{.02,0,0},new double[]{0,0,1},.004)));
+ InterfaceDefinitionEntity current(){
+ InterfaceDefinitionEntity e=new InterfaceDefinitionEntity();
+ e.setId("mount");e.setName("mount");e.setGeometryRevision(1);
+ e.setGeometryJson(json.valueToTree(geometry));e.setTolerancesJson(json.valueToTree(Tolerances.defaults()));
+ e.setSourceGeometryHash("sha256:old");e.setSourceAssetKey("interfaces/old.step");
+ when(definitions.selectOne(any())).thenReturn(e);return e;
+ }
+ ObjectNode request(){
+ ObjectNode n=json.createObjectNode().put("id","mount").put("name","updated").put("geometryRevision",1);
+ n.set("geometry",json.valueToTree(geometry));n.set("tolerances",json.valueToTree(Tolerances.defaults()));return n;
+ }
+ @Test void editsAppendRevisionAndDoNotOverwriteOldSnapshot(){
+ current();var result=service.update("mount",request());
+ assertThat(result.path("geometryRevision").asInt()).isEqualTo(2);
+ assertThat(result.path("sourceAssetKey").asText()).isEqualTo("interfaces/old.step");
+ ArgumentCaptor capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
+ verify(revisions).insert(capture.capture());assertThat(capture.getValue().getId()).isEqualTo("mount:2");
+ verify(revisions,never()).updateById(any(InterfaceDefinitionRevisionEntity.class));
+ }
+ @Test void staleEditsAndAssetUploadsAreRejected(){
+ current();assertThatThrownBy(()->service.update("mount",request().put("geometryRevision",2))).hasMessageContaining("刷新");
+ assertThatThrownBy(()->service.attachAsset("mount",2,"other.step","sha256:new")).hasMessageContaining("修订");
+ assertThatThrownBy(()->service.attachAsset("mount",1,"other.step","sha256:new")).hasMessageContaining("新几何修订");
+ verify(definitions,never()).updateById(any(InterfaceDefinitionEntity.class));
+ }
+ @Test void displayOnlyEditPersistsWithoutInvalidatingGeometryRevision(){
+ InterfaceDefinitionEntity e=current();
+ ObjectNode body=request().put("name",e.getName());
+ body.set("displayForward",json.valueToTree(new double[]{0,1,0}));
+ var result=service.update("mount",body);
+ assertThat(result.path("geometryRevision").asInt()).isEqualTo(1);
+ assertThat(result.path("displayForward")).isEqualTo(body.path("displayForward"));
+ ArgumentCaptor capture=ArgumentCaptor.forClass(InterfaceDefinitionRevisionEntity.class);
+ verify(revisions).updateById(capture.capture());verify(revisions,never()).insert(any(InterfaceDefinitionRevisionEntity.class));
+ when(revisions.selectById("mount:1")).thenReturn(capture.getValue());
+ assertThat(service.geometryDefinition("mount",1).displayForward()).containsExactly(0,1,0);
+ }
+ @Test void replacingSourceClearsOldAssetAndAttachesOnlyToNewRevision(){
+ InterfaceDefinitionEntity e=current();var result=service.update("mount",request().put("sourceGeometryHash","new"));
+ assertThat(result.path("sourceAssetKey").asText()).isEmpty();
+ assertThat(e.getSourceGeometryHash()).isEmpty();
+ InterfaceDefinitionRevisionEntity snapshot=new InterfaceDefinitionRevisionEntity();snapshot.setId("mount:2");
+ when(revisions.selectById("mount:2")).thenReturn(snapshot);
+ service.attachAsset("mount",2,"interfaces/new.step","sha256:new");
+ assertThat(snapshot.getDefinitionJson().path("sourceAssetKey").asText()).isEqualTo("interfaces/new.step");
+ assertThat(snapshot.getDefinitionJson().path("geometryRevision").asInt()).isEqualTo(2);
+ }
+}
diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/MechanicalTestFixtures.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/MechanicalTestFixtures.java
new file mode 100644
index 0000000..178a694
--- /dev/null
+++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/impl/MechanicalTestFixtures.java
@@ -0,0 +1,46 @@
+package com.linkerbot.cadworld.service.impl;
+
+import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
+import static org.mockito.Mockito.*;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.linkerbot.cadworld.entity.Component;
+import com.linkerbot.cadworld.mechanicalinterface.*;
+import com.linkerbot.cadworld.service.InterfaceDefinitionService;
+import java.util.*;
+
+final class MechanicalTestFixtures {
+ static final ObjectMapper JSON=new ObjectMapper();
+ static final MechanicalInterfaceSolver SOLVER=new MechanicalInterfaceSolver();
+ static final String XML="";
+ static final String DOCUMENT_HASH=UrdfSourceValidation.hash(XML);
+ static final String SOURCE_HASH=UrdfSourceValidation.hash(DOCUMENT_HASH+"\n");
+ static MountGeometry geometry() {
+ return new MountGeometry(new Plane(new double[3],new double[]{0,0,1}), List.of(
+ new Hole("h0",new double[]{-.02,-.02,0},new double[]{0,0,1},.004),
+ new Hole("h1",new double[]{.02,-.02,0},new double[]{0,0,1},.004),
+ new Hole("h2",new double[]{.02,.02,0},new double[]{0,0,1},.004),
+ new Hole("h3",new double[]{-.02,.02,0},new double[]{0,0,1},.004)));
+ }
+ static Definition definition() { return new Definition("square",1,"Square",geometry(),Tolerances.defaults()); }
+ static InterfaceDefinitionService definitions() {
+ var service=mock(InterfaceDefinitionService.class);
+ lenient().when(service.geometryDefinition("square",1)).thenReturn(definition());
+ lenient().when(service.get("square")).thenReturn(JSON.valueToTree(Map.of("geometryRevision",1)));
+ return service;
+ }
+ static ObjectNode source() {
+ ObjectNode result=JSON.createObjectNode(); result.put("xml",XML);result.put("documentHash",DOCUMENT_HASH);
+ result.put("sourceGeometryHash",SOURCE_HASH);result.putArray("resources");return result;
+ }
+ static Port port(String id,int candidate) {
+ var pose=SOLVER.enumeratePortPoses(definition(),new PoseRequest(1,"base",geometry(),SOURCE_HASH)).candidates().get(candidate);
+ return SOLVER.confirmPortPose(definition(),new Port(id,"base","square",1,geometry(),new SelectedPose(pose.id(),pose.templateInLink(),pose.holeMapping(),pose.orientationDirectionInLink()),SOURCE_HASH,SOLVER_VERSION));
+ }
+ static Component component(long id,int candidate,String... portIds) {
+ Component component=new Component();component.setId(id);component.setComponentName("component-"+id);component.setSource("uploaded.rfs");
+ ObjectNode json=JSON.createObjectNode();json.put("interfaceSchemaVersion",3);json.put("componentRevision",1);json.set("urdfSource",source());
+ json.set("interfaces",JSON.valueToTree(Arrays.stream(portIds).map(name->port(name,candidate)).toList()));
+ component.setComponentJson(json);return component;
+ }
+}
diff --git a/db/init.sql b/db/init.sql
new file mode 100644
index 0000000..9459250
--- /dev/null
+++ b/db/init.sql
@@ -0,0 +1,105 @@
+-- Run against a selected empty cadworld database. No database is created or selected here.
+SET NAMES utf8mb4;
+
+CREATE TABLE IF NOT EXISTS `sys_user` (
+ `id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户主键 ID',
+ `phone` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '手机号,当前按大陆手机号格式校验',
+ `nickname` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户昵称',
+ `status` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'ACTIVE' COMMENT '用户状态,例如 ACTIVE',
+ `user_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'NORMAL' COMMENT '用户类型:NORMAL 普通用户,ADMIN 管理员',
+ `created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',
+ `updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间',
+ PRIMARY KEY (`id`),
+ UNIQUE KEY `uk_sys_user_phone` (`phone`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='系统用户表';
+
+CREATE TABLE IF NOT EXISTS `component` (
+ `id` bigint NOT NULL AUTO_INCREMENT COMMENT '组件主键 ID',
+ `component_name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '组件名称',
+ `category` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '自由组件分类,仅用于检索和展示',
+ `robot_type` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'humanoid' COMMENT '组件所属机器人类型:humanoid/quadruped/manipulator',
+ `company` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '组件公司',
+ `model` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '组件模型',
+ `source` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '资源url',
+ `cover_image_key` varchar(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '组件封面图对象Key',
+ `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '组件描述',
+ `component_json` json NOT NULL COMMENT '组件 JSON 数据',
+ `assembly_metadata` json NOT NULL COMMENT '自由拼装检索元数据:tags/capabilities/dimensions',
+ `created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',
+ `updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间',
+ 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`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='组件表';
+
+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 JSON NOT NULL,
+ tolerances_json JSON NOT NULL,
+ connectable_targets_json JSON NULL,
+ display_forward_json JSON 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)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='接口定义';
+
+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 JSON NOT NULL,
+ UNIQUE KEY uk_interface_geometry_revision (definition_id, geometry_revision)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='接口历史几何修订';
+
+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)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='组件资源索引';
+
+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)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='组件库和接口库管理操作日志';
+
+-- Keep the phone unique index, including logically deleted users.
+SET @cadworld_deleted_ddl = IF(
+ EXISTS (SELECT 1 FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sys_user' AND COLUMN_NAME = 'deleted'),
+ 'SELECT 1',
+ 'ALTER TABLE sys_user ADD COLUMN deleted TINYINT NOT NULL DEFAULT 0 COMMENT ''逻辑删除:0正常,1删除''');
+PREPARE cadworld_deleted_statement FROM @cadworld_deleted_ddl;
+EXECUTE cadworld_deleted_statement;
+DEALLOCATE PREPARE cadworld_deleted_statement;
diff --git a/db/upgrade.sql b/db/upgrade.sql
new file mode 100644
index 0000000..361852a
--- /dev/null
+++ b/db/upgrade.sql
@@ -0,0 +1,74 @@
+-- Existing database must already contain sys_user and component from cadworld.sql.
+-- No DROP, data rewrite or Flyway history changes. Safe to rerun after a partial upgrade.
+SET NAMES utf8mb4;
+
+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 JSON NOT NULL,
+ tolerances_json JSON NOT NULL,
+ connectable_targets_json JSON NULL,
+ display_forward_json JSON 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)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='接口定义';
+
+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 JSON NOT NULL,
+ UNIQUE KEY uk_interface_geometry_revision (definition_id, geometry_revision)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='接口历史几何修订';
+
+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)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='组件资源索引';
+
+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)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='组件库和接口库管理操作日志';
+
+-- Keep the phone unique index, including logically deleted users.
+SET @cadworld_deleted_ddl = IF(
+ EXISTS (SELECT 1 FROM information_schema.COLUMNS
+ WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sys_user' AND COLUMN_NAME = 'deleted'),
+ 'SELECT 1',
+ 'ALTER TABLE sys_user ADD COLUMN deleted TINYINT NOT NULL DEFAULT 0 COMMENT ''逻辑删除:0正常,1删除''');
+PREPARE cadworld_deleted_statement FROM @cadworld_deleted_ddl;
+EXECUTE cadworld_deleted_statement;
+DEALLOCATE PREPARE cadworld_deleted_statement;
diff --git a/logs/.gitkeep b/logs/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 0000000..bd63673
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,115 @@
+
+
+ 4.0.0
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 3.4.4
+
+
+
+ com.linkerbot
+ cadworld
+ 0.0.1-SNAPSHOT
+ pom
+ cadworld
+
+
+ cadworld-common
+ cadworld-bean
+ cadworld-service
+ cadworld-adminapi
+ cadworld-api
+ cadworld-security
+
+
+
+ 21
+ 3.5.11
+ 0.12.6
+ 8.5.17
+ 2.8.6
+ UTF-8
+ UTF-8
+
+
+
+
+
+ com.baomidou
+ mybatis-plus-spring-boot3-starter
+ ${mybatis-plus.version}
+
+
+ com.baomidou
+ mybatis-plus-jsqlparser
+ ${mybatis-plus.version}
+
+
+ com.baomidou
+ mybatis-plus-core
+ ${mybatis-plus.version}
+
+
+ io.minio
+ minio
+ ${minio.version}
+
+
+ io.jsonwebtoken
+ jjwt-api
+ ${jjwt.version}
+
+
+ io.jsonwebtoken
+ jjwt-impl
+ ${jjwt.version}
+
+
+ io.jsonwebtoken
+ jjwt-jackson
+ ${jjwt.version}
+
+
+ org.springdoc
+ springdoc-openapi-starter-webmvc-ui
+ ${springdoc.version}
+
+
+
+
+
+
+ org.projectlombok
+ lombok
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+
+