step上传

This commit is contained in:
lxp
2026-11-02 14:32:15 +08:00
parent c5df2162d0
commit d5624c5f0d
21 changed files with 797 additions and 6 deletions
@@ -0,0 +1,58 @@
package com.linkerbot.vibemake.adminapi.controller;
import com.linkerbot.vibemake.bean.Contracts.ProjectView;
import com.linkerbot.vibemake.bean.StepContracts.*;
import com.linkerbot.vibemake.common.ApiResponse;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.common.RequestTooLargeException;
import com.linkerbot.vibemake.service.admin.AdminStepService;
import com.linkerbot.vibemake.service.oss.StepResources;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin-api/projects/{projectCode}/step")
public class AdminStepController {
private final AdminStepService steps;
@PostMapping("/signature")
@Operation(summary = "生成 STEP 单文件 OSS 直传签名,默认最大 500 MiB")
public ResponseEntity<ApiResponse<StepUploadSignature>> signature(
@PathVariable String projectCode, @RequestBody(required = false) StepUploadInput input) {
return ResponseEntity.ok().cacheControl(CacheControl.noStore())
.body(ApiResponse.success(steps.signature(projectCode, input)));
}
@PutMapping
@Operation(summary = "核验并绑定 STEP 文件")
public ApiResponse<ProjectView> confirm(
@PathVariable String projectCode, @RequestBody(required = false) StepConfirmInput input) {
return ApiResponse.success(steps.confirm(projectCode, input));
}
@DeleteMapping
@Operation(summary = "移除 STEP 绑定,保留 OSS 对象")
public ApiResponse<Void> clear(@PathVariable String projectCode) {
steps.clear(projectCode);
return ApiResponse.success(null);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ApiResponse<Object>> invalidJson(HttpMessageNotReadableException error) {
BusinessException failure = StepResources.invalidFile();
// 保留通用 JSON 正文配额的 413,不能将流式读取超限误报为文件参数错误。
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
if (cause instanceof RequestTooLargeException large) {
failure = large;
break;
}
}
return ResponseEntity.status(failure.status()).cacheControl(CacheControl.noStore())
.body(ApiResponse.failure(failure));
}
}
@@ -77,6 +77,8 @@ vibemake:
legacy-public-base-urls: ${OSS_LEGACY_PUBLIC_BASE_URLS:}
project-resources:
signature-validity: ${PROJECT_RESOURCE_SIGNATURE_VALIDITY:1h}
step:
max-file-bytes: ${STEP_MAX_FILE_BYTES:524288000}
urdf:
max-file-bytes: ${URDF_MAX_FILE_BYTES:52428800}
max-total-bytes: ${URDF_MAX_TOTAL_BYTES:209715200}
@@ -132,6 +132,7 @@ class AdminWorkflowTest {
gitea.reset();
oss.setEnabled(false);
ossObjects.objects.clear();
ossObjects.unavailable = false;
admin = userService.login(UUID.randomUUID() + "@example.invalid");
ordinary = userService.login(UUID.randomUUID() + "@example.invalid");
auth.bootstrap(admin.getUserCode(), PASSWORD);
@@ -489,6 +490,168 @@ class AdminWorkflowTest {
assertThat(bound.path("modelPartsFiles").size()).isEqualTo(1200);
}
private JsonNode stepSignature(String code, List<Map<String, Object>> files) throws Exception {
MvcResult result = mvc.perform(signed(body(post("/admin-api/projects/" + code + "/step/signature"),
Map.of("files", files)))).andReturn();
assertThat(result.getResponse().getStatus()).isEqualTo(200);
assertThat(result.getResponse().getHeader("Cache-Control")).isEqualTo("no-store");
return json.readTree(result.getResponse().getContentAsString()).path("data");
}
@Test
void stepUploadReplaceRetryAndClearPreserveOtherResourcesAndGitState() throws Exception {
String code = createProject();
String endpoint = "/admin-api/projects/" + code;
JsonNode empty = request(signed(get(endpoint)), 200).path("data").path("project");
for (String field : List.of("stepMainUrl", "stepFileName", "stepSizeBytes"))
assertThat(empty.has(field) && empty.path(field).isNull()).as(field).isTrue();
enableOss();
String sha = initialSha(code);
request(signed(body(put(endpoint + "/publication"), Map.of("commitSha", sha))), 200);
String urdfPrefix = "/urdf/" + code + "/" + "b".repeat(32) + "/";
jdbc.update("UPDATE project SET urdf_main_object_key=?, urdf_prefix=?, cover_url=? WHERE project_code=?",
urdfPrefix + "robot.urdf", urdfPrefix, "https://images.example.com/cover.png", code);
JsonNode before = request(signed(get(endpoint)), 200).path("data").path("project");
List<Map<String, Object>> files = List.of(Map.of("relativePath", "机械 臂.STEP", "sizeBytes", 524288000L));
JsonNode signature = stepSignature(code, files);
assertThat(signature.path("mainRelativePath").asText()).isEqualTo("机械 臂.STEP");
assertThat(java.time.OffsetDateTime.parse(signature.path("expiresAt").asText()).getOffset())
.isEqualTo(java.time.ZoneOffset.UTC);
JsonNode policy = json.readTree(Base64.getDecoder().decode(signature.path("files").get(0)
.path("formFields").path("policy").asText()));
assertThat(java.time.Instant.parse(signature.path("expiresAt").asText()))
.isEqualTo(java.time.Instant.parse(policy.path("expiration").asText()));
assertThat(request(signed(get(endpoint)), 200).path("data").path("project").path("stepMainUrl").isNull()).isTrue();
storeResourceFiles(signature, files);
assertThat(request(signed(get(endpoint)), 200).path("data").path("project").path("stepMainUrl").isNull()).isTrue();
Map<String, Object> confirmation = Map.of("batchCode", signature.path("batchCode").asText(), "files", files);
JsonNode bound = request(signed(body(put(endpoint + "/step"), confirmation)), 200).path("data");
assertThat(bound.has("project")).isFalse();
assertThat(bound.path("projectCode").asText()).isEqualTo(code);
assertThat(bound.path("stepMainUrl").asText()).contains("/project-resources/" + code + "/step/").endsWith("/model.STEP");
assertThat(bound.path("stepFileName").asText()).isEqualTo("机械 臂.STEP");
assertThat(bound.path("stepSizeBytes").asLong()).isEqualTo(524288000L);
assertThat(bound.has("id")).isFalse();
assertThat(jdbc.queryForObject("SELECT step_object_key FROM project WHERE project_code=?", String.class, code))
.startsWith("/project-resources/" + code + "/step/");
assertThat(request(signed(body(put(endpoint + "/step"), confirmation)), 200).path("data").path("stepMainUrl"))
.isEqualTo(bound.path("stepMainUrl"));
Map<String, Object> attemptedMetadata = new LinkedHashMap<>(metadata());
attemptedMetadata.put("stepMainUrl", "https://example.invalid/arbitrary.step");
attemptedMetadata.put("stepFileName", "override.step");
attemptedMetadata.put("stepSizeBytes", 1L);
JsonNode metadataUpdated = request(signed(body(patch(endpoint), attemptedMetadata)), 200).path("data");
assertThat(metadataUpdated.path("stepFileName")).isEqualTo(bound.path("stepFileName"));
assertThat(metadataUpdated.path("stepMainUrl")).isEqualTo(bound.path("stepMainUrl"));
assertThat(metadataUpdated.path("stepSizeBytes")).isEqualTo(bound.path("stepSizeBytes"));
List<Map<String, Object>> replacementFiles = List.of(Map.of("relativePath", "new.stp", "sizeBytes", 1L));
JsonNode replacement = stepSignature(code, replacementFiles);
storeResourceFiles(replacement, replacementFiles);
assertThat(request(signed(get(endpoint)), 200).path("data").path("project").path("stepMainUrl"))
.isEqualTo(bound.path("stepMainUrl"));
JsonNode replaced = request(signed(body(put(endpoint + "/step"),
Map.of("batchCode", replacement.path("batchCode").asText(), "files", replacementFiles))), 200).path("data");
assertThat(replaced.path("stepMainUrl")).isNotEqualTo(bound.path("stepMainUrl"));
JsonNode listed = request(signed(get("/admin-api/projects")), 200).path("data").path("items").get(0).path("project");
assertThat(listed.path("stepMainUrl")).isEqualTo(replaced.path("stepMainUrl"));
int objects = ossObjects.objects.size();
oss.setEnabled(false);
assertThat(request(signed(delete(endpoint + "/step")), 200).path("data").isNull()).isTrue();
request(signed(delete(endpoint + "/step")), 200);
JsonNode cleared = request(signed(get(endpoint)), 200).path("data").path("project");
for (String field : List.of("stepMainUrl", "stepFileName", "stepSizeBytes"))
assertThat(cleared.path(field).isNull()).as(field).isTrue();
for (String field : List.of("urdfMainUrl", "urdfBaseUrl", "coverUrl", "repoStatus", "publishStatus", "publishedCommitSha", "publishedAt"))
assertThat(cleared.path(field)).as(field).isEqualTo(before.path(field));
assertThat(initialSha(code)).isEqualTo(sha);
assertThat(ossObjects.objects).hasSize(objects);
// 与 URDF 相同:不保存批次历史,旧请求可以重新确认已上传对象。
enableOss();
assertThat(request(signed(body(put(endpoint + "/step"), confirmation)), 200).path("data").path("stepMainUrl"))
.isEqualTo(bound.path("stepMainUrl"));
}
@Test
void stepConfirmationFailuresPreserveBindingAndEnforceProjectNamespaces() throws Exception {
String code = createProject();
String endpoint = "/admin-api/projects/" + code;
enableOss();
List<Map<String, Object>> files = List.of(Map.of("relativePath", "a.step", "sizeBytes", 10L));
JsonNode signature = stepSignature(code, files);
Map<String, Object> confirmation = Map.of("batchCode", signature.path("batchCode").asText(), "files", files);
assertThat(request(signed(body(put(endpoint + "/step"), confirmation)), 409).path("code").asText())
.isEqualTo("STEP_FILE_MISSING");
storeResourceFiles(signature, files);
JsonNode bound = request(signed(body(put(endpoint + "/step"), confirmation)), 200).path("data");
JsonNode replacement = stepSignature(code, files);
Map<String, Object> nextConfirmation = Map.of("batchCode", replacement.path("batchCode").asText(), "files", files);
assertThat(request(signed(body(put(endpoint + "/step"), nextConfirmation)), 409).path("code").asText())
.isEqualTo("STEP_FILE_MISSING");
ossObjects.objects.put(replacement.path("files").get(0).path("objectKey").asText(), new OssObjectStore.Metadata(11, "bad"));
assertThat(request(signed(body(put(endpoint + "/step"), nextConfirmation)), 409).path("code").asText())
.isEqualTo("STEP_FILE_SIZE_MISMATCH");
ossObjects.unavailable = true;
assertThat(request(signed(body(put(endpoint + "/step"), confirmation)), 502).path("code").asText())
.isEqualTo("OSS_ERROR");
ossObjects.unavailable = false;
String another = createProject();
assertThat(request(signed(body(put("/admin-api/projects/" + another + "/step"), confirmation)), 409).path("code").asText())
.isEqualTo("STEP_FILE_MISSING");
JsonNode urdf = request(signed(body(post(endpoint + "/urdf/signature"), Map.of("files", urdfFiles()))), 200).path("data");
storeResourceFiles(urdf, urdfFiles());
assertThat(request(signed(body(put(endpoint + "/step"),
Map.of("batchCode", urdf.path("batchCode").asText(), "files", files))), 409).path("code").asText())
.isEqualTo("STEP_FILE_MISSING");
assertThat(request(signed(get(endpoint)), 200).path("data").path("project").path("stepMainUrl"))
.isEqualTo(bound.path("stepMainUrl"));
}
@ParameterizedTest
@ValueSource(strings = {"{}", "null", "{\"files\":null}", "{\"files\":[]}", "{\"files\":[null]}",
"{\"files\":[{\"relativePath\":\"a.step\"}]}",
"{\"files\":[{\"relativePath\":\"a.step\",\"sizeBytes\":1.5}]}",
"{\"files\":[{\"relativePath\":\"a.step\",\"sizeBytes\":\"1\"}]}",
"{\"files\":[{\"relativePath\":\"a.step\",\"sizeBytes\":9223372036854775808}]}",
"{\"files\":[{\"relativePath\":\"a.step\",\"sizeBytes\":0}]}",
"{\"files\":[{\"relativePath\":\"../a.step\",\"sizeBytes\":1}]}",
"{\"files\":[{\"relativePath\":\"a.step.exe\",\"sizeBytes\":1}]}",
"{\"files\":[{\"relativePath\":\"a.step\",\"sizeBytes\":1},{\"relativePath\":\"b.stp\",\"sizeBytes\":1}]}"})
void stepInvalidRequestsUseDedicatedErrorCode(String input) throws Exception {
String code = createProject();
enableOss();
assertThat(request(signed(post("/admin-api/projects/" + code + "/step/signature")
.contentType(MediaType.APPLICATION_JSON).content(input)), 400).path("code").asText())
.isEqualTo("STEP_INVALID_FILE");
}
@Test
void stepEndpointsRequireAdminAndReadyNonDeletedProjectAndRejectOversizeFiles() throws Exception {
String code = createProject();
String endpoint = "/admin-api/projects/" + code + "/step";
List<Map<String, Object>> files = List.of(Map.of("relativePath", "a.step", "sizeBytes", 1L));
Map<String, Object> signatureInput = Map.of("files", files);
Map<String, Object> confirmation = Map.of("batchCode", "a".repeat(32), "files", files);
String ordinaryToken = tokens.issue(ordinary.getId(), ordinary.getSessionVersion());
for (MockHttpServletRequestBuilder operation : List.of(body(post(endpoint + "/signature"), signatureInput),
body(put(endpoint), confirmation), delete(endpoint))) request(operation, 401);
for (MockHttpServletRequestBuilder operation : List.of(body(post(endpoint + "/signature"), signatureInput),
body(put(endpoint), confirmation), delete(endpoint)))
request(operation.header("Authorization", "Bearer " + ordinaryToken), 403);
request(signed(body(post(endpoint + "/signature"), signatureInput)), 503);
enableOss();
assertThat(request(signed(body(post(endpoint + "/signature"),
Map.of("files", List.of(Map.of("relativePath", "a.step", "sizeBytes", 524288001L))))), 413).path("code").asText())
.isEqualTo("STEP_FILE_TOO_LARGE");
assertThat(request(signed(body(put(endpoint), Map.of("batchCode", "../other", "files", files))), 400).path("code").asText())
.isEqualTo("STEP_INVALID_FILE");
jdbc.update("UPDATE project SET repo_status='CREATING' WHERE project_code=?", code);
for (MockHttpServletRequestBuilder operation : List.of(body(post(endpoint + "/signature"), signatureInput),
body(put(endpoint), confirmation), delete(endpoint))) request(signed(operation), 409);
jdbc.update("UPDATE project SET repo_status='READY', deleted=1 WHERE project_code=?", code);
for (MockHttpServletRequestBuilder operation : List.of(body(post(endpoint + "/signature"), signatureInput),
body(put(endpoint), confirmation), delete(endpoint))) request(signed(operation), 404);
}
private List<Map<String, Object>> urdfFiles() {
return List.of(
Map.of("relativePath", "urdf/机械臂.URDF", "sizeBytes", 12),
@@ -8,9 +8,11 @@ import java.util.concurrent.ConcurrentHashMap;
final class FakeOssObjectStore implements OssObjectStore {
final Map<String, Metadata> objects = new ConcurrentHashMap<>();
boolean unavailable;
@Override
public Metadata head(String objectKey) {
if (unavailable) throw new BusinessException(502, "OSS_ERROR", "OSS 暂时不可用");
Metadata metadata = objects.get(objectKey);
if (metadata == null)
throw new BusinessException(400, "URDF_FILE_MISSING", "URDF 文件未上传完整,请重新上传");