项目新增URDF字段

This commit is contained in:
lxp
2026-10-16 15:02:26 +08:00
parent 9a25d36f8e
commit 61c60f8052
26 changed files with 1136 additions and 18 deletions
@@ -0,0 +1,52 @@
package com.linkerbot.community.api.controller;
import com.linkerbot.community.bean.Contracts.ProjectView;
import com.linkerbot.community.bean.Contracts.UrdfConfirmInput;
import com.linkerbot.community.bean.Contracts.UrdfUploadInput;
import com.linkerbot.community.bean.Contracts.UrdfUploadSignature;
import com.linkerbot.community.common.ApiResponse;
import com.linkerbot.community.security.CurrentUser;
import com.linkerbot.community.service.UrdfService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/workspace/projects/{projectCode}/urdf")
@Tag(name = "项目 URDF")
public class UrdfController {
private final UrdfService urdf;
@PostMapping("/signature")
@Operation(summary = "生成 URDF 文件夹 OSS 直传签名,自动识别唯一主文件")
public ResponseEntity<ApiResponse<UrdfUploadSignature>> signature(
@PathVariable String projectCode, @Valid @RequestBody UrdfUploadInput input) {
return ResponseEntity.ok().cacheControl(CacheControl.noStore())
.body(ApiResponse.success(urdf.signature(CurrentUser.required(), projectCode, input)));
}
@PutMapping
@Operation(summary = "核验并绑定项目 URDF 资源包")
public ApiResponse<ProjectView> confirm(
@PathVariable String projectCode, @Valid @RequestBody UrdfConfirmInput input) {
return ApiResponse.success(urdf.confirm(CurrentUser.required(), projectCode, input));
}
@DeleteMapping
@Operation(summary = "清除项目 URDF 绑定,保留 OSS 对象")
public ApiResponse<Void> clear(@PathVariable String projectCode) {
urdf.clear(CurrentUser.required(), projectCode);
return ApiResponse.success(null);
}
}
@@ -27,6 +27,10 @@ community:
access-key-id: ${OSS_ACCESS_KEY_ID:}
access-key-secret: ${OSS_ACCESS_KEY_SECRET:}
public-base-url: ${OSS_PUBLIC_BASE_URL:https://linkerbot.oss-cn-beijing.aliyuncs.com}
urdf:
max-file-bytes: ${URDF_MAX_FILE_BYTES:52428800}
max-total-bytes: ${URDF_MAX_TOTAL_BYTES:209715200}
max-files: ${URDF_MAX_FILES:500}
ai:
enabled: ${AI_ENABLED:true}
api-key: ${ARK_API_KEY:}
@@ -0,0 +1,44 @@
package com.linkerbot.community.api;
import com.linkerbot.community.common.BusinessException;
import com.linkerbot.community.service.oss.OssObjectStore;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
final class FakeOssObjectStore implements OssObjectStore {
final Map<String, byte[]> objects = new ConcurrentHashMap<>();
boolean failNextCopy;
Runnable afterHead;
void reset() {
objects.clear();
failNextCopy = false;
afterHead = null;
}
@Override
public Metadata head(String objectKey) {
byte[] bytes = objects.get(objectKey);
if (bytes == null)
throw new BusinessException(400, "URDF_FILE_MISSING", "URDF 文件未上传完整,请重新上传");
Metadata metadata = new Metadata(bytes.length, Integer.toHexString(Arrays.hashCode(bytes)));
if (afterHead != null) {
Runnable action = afterHead;
afterHead = null;
action.run();
}
return metadata;
}
@Override
public void copy(String sourceKey, String targetKey, String sourceEtag) {
if (failNextCopy) {
failNextCopy = false;
throw new BusinessException(502, "OSS_ERROR", "OSS 资源访问失败,请稍后重试");
}
byte[] bytes = objects.get(sourceKey);
if (!head(sourceKey).etag().equals(sourceEtag)) throw BusinessException.conflict("源文件发生变化");
objects.put(targetKey, bytes.clone());
}
}
@@ -18,6 +18,9 @@ final class SchemaSupport {
while (matcher.find()) {
String ddl =
matcher.group()
// H2 的 JSON 字符串绑定与 MySQL 不同,测试以文本列承接服务层 JSON。
.replace("JSON NOT NULL DEFAULT (JSON_ARRAY())", "CLOB NOT NULL DEFAULT '[]'")
.replace(" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin", "")
.replaceAll(" COMMENT '[^']*'", "")
.replaceAll("\\) ENGINE=InnoDB[^;]*;", ");");
jdbc.execute(ddl);
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.community.security.CaptchaService;
import com.linkerbot.community.service.config.CommunityProperties;
import com.linkerbot.community.service.config.OssProperties;
import com.linkerbot.community.service.config.UrdfProperties;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
@@ -41,6 +42,10 @@ import java.util.concurrent.*;
class WorkflowTest {
@TestConfiguration
static class Config {
@Bean
@Primary
FakeOssObjectStore fakeOss() { return new FakeOssObjectStore(); }
@Bean
@Primary
FakeGiteaClient fakeGitea() {
@@ -64,12 +69,18 @@ class WorkflowTest {
@Autowired JdbcTemplate jdbc;
@Autowired FakeGiteaClient gitea;
@Autowired OssProperties oss;
@Autowired FakeOssObjectStore ossObjects;
@Autowired UrdfProperties urdfLimits;
@BeforeEach
void reset() throws Exception {
SchemaSupport.reset(jdbc);
gitea.reset();
oss.setEnabled(false);
ossObjects.reset();
urdfLimits.setMaxFileBytes(52428800);
urdfLimits.setMaxTotalBytes(209715200);
urdfLimits.setMaxFiles(500);
}
private JsonNode perform(MockHttpServletRequestBuilder builder, int status) throws Exception {
@@ -292,6 +303,194 @@ class WorkflowTest {
.path("data").path("coverUrl").asText()).isEqualTo(max);
}
private void enableUrdfOss() {
oss.setRegion("cn-hangzhou");
oss.setEndpoint("");
oss.setBucket("examplebucket");
oss.setAccessKeyId("UnitTestAccessKey");
oss.setAccessKeySecret("unit-test-secret");
oss.setPublicBaseUrl("https://images.example.com/assets/");
oss.setEnabled(true);
}
private List<Map<String, Object>> urdfFiles() {
return List.of(Map.of("relativePath", "urdf/机械 臂.URDF", "sizeBytes", 12),
Map.of("relativePath", "meshes/底盘.stl", "sizeBytes", 24),
Map.of("relativePath", "textures/a #?.png", "sizeBytes", 8));
}
private JsonNode uploadUrdf(String token, String code, List<Map<String, Object>> files) throws Exception {
JsonNode signature = perform(body(auth(post("/api/workspace/projects/" + code + "/urdf/signature"), token),
Map.of("files", files)), 200).path("data");
for (int index = 0; index < files.size(); index++)
ossObjects.objects.put(signature.path("files").get(index).path("objectKey").asText(),
new byte[((Number) files.get(index).get("sizeBytes")).intValue()]);
return signature;
}
private JsonNode confirmUrdf(String token, String code, JsonNode signature,
List<Map<String, Object>> files, int status) throws Exception {
return perform(body(auth(put("/api/workspace/projects/" + code + "/urdf"), token),
Map.of("batchCode", signature.path("batchCode").asText(), "files", files)), status);
}
@Test
void urdfSignaturesAndConfirmationRejectMissingMultipleAndInvalidPaths() throws Exception {
String owner = login("urdf-validation@example.com");
String other = login("urdf-stranger@example.com");
String code = create(owner, "URDF 校验");
String endpoint = "/api/workspace/projects/" + code + "/urdf";
Map<String, Object> good = Map.of("files", urdfFiles());
perform(body(post(endpoint + "/signature"), good), 401);
perform(body(auth(post(endpoint + "/signature"), owner), good), 503);
enableUrdfOss();
perform(body(auth(post(endpoint + "/signature"), other), good), 404);
perform(body(auth(put(endpoint), other), Map.of("batchCode", "a".repeat(32), "files", urdfFiles())), 404);
perform(auth(delete(endpoint), other), 404);
List<List<Map<String, Object>>> invalidCounts = List.of(List.of(),
List.of(Map.of("relativePath", "meshes/a.stl", "sizeBytes", 1)),
List.of(Map.of("relativePath", "a.urdf", "sizeBytes", 1),
Map.of("relativePath", "models/b.URDF", "sizeBytes", 1)));
for (int index = 0; index < invalidCounts.size(); index++) {
List<Map<String, Object>> files = invalidCounts.get(index);
String message = index < 2 ? "文件夹中未找到 URDF 文件"
: "文件夹中存在多个 URDF 文件,请仅保留一个后重新上传";
assertThat(perform(body(auth(post(endpoint + "/signature"), owner), Map.of("files", files)), 400)
.path("message").asText()).isEqualTo(message);
assertThat(perform(body(auth(put(endpoint), owner),
Map.of("batchCode", "a".repeat(32), "files", files)), 400)
.path("message").asText()).isEqualTo(message);
}
for (String path : List.of("../a.urdf", "/a.urdf", "a\\b.urdf", "a//b.urdf", "a/./b.urdf",
"a\u0000.urdf", "a".repeat(512) + ".urdf", "中".repeat(340) + ".urdf")) {
Map<String, Object> input = Map.of("files", List.of(Map.of("relativePath", path, "sizeBytes", 1)));
perform(body(auth(post(endpoint + "/signature"), owner), input), 400);
}
for (Object files : List.of(
List.of(Map.of("relativePath", "a.urdf", "sizeBytes", 1), Map.of("relativePath", "a.urdf", "sizeBytes", 1)),
List.of(Map.of("relativePath", "a.urdf", "sizeBytes", -1)),
List.of(Map.of("relativePath", "a.urdf"))))
perform(body(auth(post(endpoint + "/signature"), owner), Map.of("files", files)), 400);
perform(body(auth(put(endpoint), owner), Map.of("batchCode", "../another", "files", urdfFiles())), 400);
perform(body(auth(post(endpoint + "/signature"), owner), Map.of("files",
List.of(Map.of("relativePath", "a.urdf", "sizeBytes", 52428801)))), 413);
urdfLimits.setMaxTotalBytes(20);
perform(body(auth(post(endpoint + "/signature"), owner), good), 413);
urdfLimits.setMaxTotalBytes(209715200);
urdfLimits.setMaxFiles(2);
perform(body(auth(post(endpoint + "/signature"), owner), good), 413);
assertThat(jdbc.queryForObject("SELECT urdf_prefix FROM project WHERE project_code = ?", String.class, code)).isEmpty();
assertThat(ossObjects.objects).isEmpty();
}
@Test
void urdfUploadReplacesClearsAndUpdatesCommunityWithoutChangingRepository() throws Exception {
String owner = login("urdf-owner@example.com");
String code = create(owner, "URDF 项目");
String path = "/api/workspace/projects/" + code;
JsonNode initial = perform(auth(get(path), owner), 200).path("data");
assertThat(initial.path("urdfMainUrl").isNull()).isTrue();
assertThat(initial.path("urdfBaseUrl").isNull()).isTrue();
String sha = head(owner, code);
publish(owner, code, sha);
enableUrdfOss();
List<Map<String, Object>> files = urdfFiles();
JsonNode signature = uploadUrdf(owner, code, files);
assertThat(signature.path("mainRelativePath").asText()).isEqualTo("urdf/机械 臂.URDF");
assertThat(signature.path("uploadUrl").asText()).isEqualTo("https://examplebucket.oss-cn-hangzhou.aliyuncs.com");
assertThat(signature.toString()).doesNotContain("unit-test-secret");
assertThat(signature.has("id")).isFalse();
assertThat(perform(auth(get(path), owner), 200).path("data").path("urdfMainUrl").isNull()).isTrue();
String expectedPrefix = "vibemake_dev/urdf/" + code + "/" + signature.path("batchCode").asText() + "/";
JsonNode bound = confirmUrdf(owner, code, signature, files, 200).path("data");
String baseUrl = "https://images.example.com/assets/" + expectedPrefix;
assertThat(bound.path("urdfBaseUrl").asText()).isEqualTo(baseUrl);
assertThat(bound.path("urdfMainUrl").asText()).isEqualTo(baseUrl + "urdf/%E6%9C%BA%E6%A2%B0%20%E8%87%82.URDF");
assertThat(bound.has("id")).isFalse();
assertThat(jdbc.queryForObject("SELECT urdf_main_object_key FROM project WHERE project_code = ?", String.class, code))
.isEqualTo(expectedPrefix + "urdf/机械 臂.URDF");
assertThat(json.readTree(jdbc.queryForObject("SELECT urdf_files FROM project WHERE project_code = ?", String.class, code)))
.isEqualTo(json.valueToTree(files));
assertThat(perform(get("/api/community/projects/" + code), 200).path("data").path("urdfMainUrl")).isEqualTo(bound.path("urdfMainUrl"));
JsonNode replacement = uploadUrdf(owner, code, files);
JsonNode next = confirmUrdf(owner, code, replacement, files, 200).path("data");
assertThat(next.path("urdfMainUrl")).isNotEqualTo(bound.path("urdfMainUrl"));
assertThat(perform(get("/api/community/projects/" + code), 200).path("data").path("urdfMainUrl")).isEqualTo(next.path("urdfMainUrl"));
assertThat(head(owner, code)).isEqualTo(sha);
oss.setEnabled(false); // 清除绑定无需 OSS 可用。
perform(auth(delete(path + "/urdf"), owner), 200);
JsonNode cleared = perform(get("/api/community/projects/" + code), 200).path("data");
assertThat(cleared.path("urdfMainUrl").isNull()).isTrue();
assertThat(cleared.path("urdfBaseUrl").isNull()).isTrue();
assertThat(jdbc.queryForMap("SELECT urdf_main_object_key, urdf_prefix, urdf_files FROM project WHERE project_code = ?", code))
.containsEntry("URDF_MAIN_OBJECT_KEY", "").containsEntry("URDF_PREFIX", "");
assertThat(jdbc.queryForObject("SELECT urdf_files FROM project WHERE project_code = ?", String.class, code)).isEqualTo("[]");
assertThat(ossObjects.objects).hasSize(6);
JsonNode spec = perform(get("/v3/api-docs"), 200);
assertThat(spec.path("paths").has("/api/workspace/projects/{projectCode}/urdf/signature")).isTrue();
}
@Test
void urdfMissingMismatchedOrInvalidConfirmationPreservesPreviousBinding() throws Exception {
String owner = login("urdf-failure@example.com");
String code = create(owner, "URDF 失败保护");
enableUrdfOss();
List<Map<String, Object>> files = urdfFiles();
JsonNode first = uploadUrdf(owner, code, files);
JsonNode current = confirmUrdf(owner, code, first, files, 200).path("data");
JsonNode next = uploadUrdf(owner, code, files);
String missingKey = next.path("files").get(1).path("objectKey").asText();
ossObjects.objects.remove(missingKey);
assertThat(confirmUrdf(owner, code, next, files, 400).path("code").asText()).isEqualTo("URDF_FILE_MISSING");
ossObjects.objects.put(missingKey, new byte[23]);
assertThat(confirmUrdf(owner, code, next, files, 400).path("code").asText()).isEqualTo("URDF_FILE_SIZE_MISMATCH");
assertThat(confirmUrdf(owner, code, next, List.of(files.get(1)), 400).path("code").asText()).isEqualTo("URDF_MAIN_FILE_INVALID");
assertThat(perform(auth(get("/api/workspace/projects/" + code), owner), 200).path("data").path("urdfMainUrl"))
.isEqualTo(current.path("urdfMainUrl"));
// 模拟核验期间项目被删除,落库前必须重新校验。
ossObjects.objects.put(missingKey, new byte[24]);
ossObjects.afterHead = () -> jdbc.update("UPDATE project SET deleted = 1 WHERE project_code = ?", code);
confirmUrdf(owner, code, next, files, 404);
assertThat(jdbc.queryForObject("SELECT urdf_prefix FROM project WHERE project_code = ?", String.class, code))
.contains(first.path("batchCode").asText());
}
@Test
void urdfForkCopiesIndependentObjectsAndCopyFailureDoesNotReturnReady() throws Exception {
String owner = login("urdf-fork-source@example.com");
String other = login("urdf-fork-target@example.com");
String code = create(owner, "URDF 来源");
enableUrdfOss();
List<Map<String, Object>> files = urdfFiles();
JsonNode uploaded = uploadUrdf(owner, code, files);
JsonNode source = confirmUrdf(owner, code, uploaded, files, 200).path("data");
String sha = head(owner, code);
publish(owner, code, sha);
String forkEndpoint = "/api/community/projects/" + code + "/forks";
Map<String, Object> forkInput = Map.of("name", "独立副本", "publishedCommitSha", sha);
JsonNode fork = perform(body(auth(post(forkEndpoint), other), forkInput), 200).path("data");
String targetCode = fork.path("projectCode").asText();
assertThat(fork.path("repoStatus").asText()).isEqualTo("READY");
assertThat(fork.path("urdfMainUrl").asText()).contains("/urdf/" + targetCode + "/").doesNotContain("/urdf/" + code + "/");
String targetPrefix = jdbc.queryForObject("SELECT urdf_prefix FROM project WHERE project_code = ?", String.class, targetCode);
for (int index = 0; index < files.size(); index++)
assertThat(ossObjects.objects.get(targetPrefix + files.get(index).get("relativePath")))
.containsExactly(ossObjects.objects.get(uploaded.path("files").get(index).path("objectKey").asText()));
confirmUrdf(owner, code, uploadUrdf(owner, code, files), files, 200);
perform(auth(delete("/api/workspace/projects/" + code + "/urdf"), owner), 200);
assertThat(perform(auth(get("/api/workspace/projects/" + targetCode), other), 200).path("data").path("urdfMainUrl"))
.isEqualTo(fork.path("urdfMainUrl"));
confirmUrdf(owner, code, uploaded, files, 200);
ossObjects.failNextCopy = true;
JsonNode failure = perform(body(auth(post(forkEndpoint), other), forkInput), 502);
String failedCode = failure.path("data").path("projectCode").asText();
assertThat(failedCode).isNotEmpty();
assertThat(jdbc.queryForObject("SELECT repo_status FROM project WHERE project_code = ?", String.class, failedCode)).isEqualTo("FAILED");
assertThat(jdbc.queryForObject("SELECT urdf_prefix FROM project WHERE project_code = ?", String.class, failedCode)).isEmpty();
assertThat(perform(get("/api/community/projects/" + code), 200).path("data").path("urdfMainUrl"))
.isEqualTo(source.path("urdfMainUrl"));
}
@Test
void coverSignaturesAuthenticateValidateAndReturnDirectUploadForms() throws Exception {
String endpoint = "/api/uploads/project-covers/signature";