cad项目接口

This commit is contained in:
lxp
2026-11-03 15:11:09 +08:00
parent a97728df29
commit 8f0214a64e
19 changed files with 1091 additions and 5 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# 数据库初始化
业务数据库名为 `vibemake`,基础业务包含以下四张表及项目 Git 凭据表;完整部署还需执行 [管理端增量 SQL](admin-database.md),新增迁移任务与仓库写入操作表。由人工执行;应用不运行迁移或自动建表。以下 SQL 面向 MySQL 8.0.13 及以上(URDF JSON 默认值使用表达式)。
业务数据库名为 `vibemake`,基础业务包含以下四张表及项目 Git 凭据表;完整部署还需执行 [管理端增量 SQL](admin-database.md),新增迁移任务与仓库写入操作表。CAD 工作空间另行执行 [CAD 建表 SQL](cad-database.md),新增两张独立表。由人工执行;应用不运行迁移或自动建表。以下 SQL 面向 MySQL 8.0.13 及以上(URDF JSON 默认值使用表达式)。
```sql
CREATE DATABASE IF NOT EXISTS vibemake CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
+2
View File
@@ -8,6 +8,8 @@
ZIP、TAR.GZ 下载和 HTTPS Git 本地开发的独立前端交付文档见 [仓库下载与 Git 接入](frontend-repository-download-git.md),包含六个浏览器接口、页面流程、TypeScript 示例及联调清单。
CAD 个人工作空间使用独立的 `/api/cad/workspace/projects`,共用登录,但不创建 Git 仓库、不混入现有项目列表。接口、保存续编流程和私有 OSS 配置见 [CAD 工作空间前端对接](frontend-cad-workspace.md),上线前执行 [CAD 建表 SQL](cad-database.md)。
## 阅读导航
- [接入约定](#接入约定)
@@ -0,0 +1,78 @@
package com.linkerbot.vibemake.api.controller;
import com.linkerbot.vibemake.bean.CadContracts.*;
import com.linkerbot.vibemake.common.ApiResponse;
import com.linkerbot.vibemake.common.PageResponse;
import com.linkerbot.vibemake.security.CurrentUser;
import com.linkerbot.vibemake.service.cad.CadProjectService;
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.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletResponse;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/cad/workspace/projects")
@Tag(name = "CAD 个人工作空间")
public class CadWorkspaceController {
private final CadProjectService projects;
@ModelAttribute
public void noStore(HttpServletResponse response) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store");
}
@GetMapping
@Operation(summary = "我的 CAD 项目分页列表")
public ApiResponse<PageResponse<CadProjectView>> list(
@RequestParam(defaultValue = "1") long page, @RequestParam(defaultValue = "20") long size,
@RequestParam(required = false) String keyword) {
return ApiResponse.success(projects.list(CurrentUser.required(), keyword, page, size));
}
@PostMapping
@Operation(summary = "创建空 CAD 项目")
public ApiResponse<CadProjectView> create(@Valid @RequestBody CadCreateProjectInput input) {
return ApiResponse.success(projects.create(CurrentUser.required(), input));
}
@GetMapping("/{cadProjectCode}")
@Operation(summary = "我的 CAD 项目详情")
public ApiResponse<CadProjectView> detail(@PathVariable String cadProjectCode) {
return ApiResponse.success(projects.detail(CurrentUser.required(), cadProjectCode));
}
@PatchMapping("/{cadProjectCode}")
@Operation(summary = "修改 CAD 项目名称和描述")
public ApiResponse<CadProjectView> update(@PathVariable String cadProjectCode, @Valid @RequestBody CadUpdateProjectInput input) {
return ApiResponse.success(projects.update(CurrentUser.required(), cadProjectCode, input));
}
@DeleteMapping("/{cadProjectCode}")
@Operation(summary = "逻辑删除 CAD 项目")
public ApiResponse<Void> delete(@PathVariable String cadProjectCode) {
projects.delete(CurrentUser.required(), cadProjectCode);
return ApiResponse.success(null);
}
@PostMapping("/{cadProjectCode}/uploads/signature")
@Operation(summary = "申请 CAD 原生设计文件私有 OSS 直传签名")
public ApiResponse<CadUploadSignature> sign(@PathVariable String cadProjectCode, @Valid @RequestBody CadUploadInput input) {
return ApiResponse.success(projects.sign(CurrentUser.required(), cadProjectCode, input));
}
@PutMapping("/{cadProjectCode}/document")
@Operation(summary = "确认文件上传并保存 CAD 最新设计")
public ApiResponse<CadSaveResult> confirm(@PathVariable String cadProjectCode, @Valid @RequestBody CadConfirmInput input) {
return ApiResponse.success(projects.confirm(CurrentUser.required(), cadProjectCode, input.uploadCode()));
}
@GetMapping("/{cadProjectCode}/document")
@Operation(summary = "获取 CAD 当前设计的短期授权下载地址")
public ApiResponse<CadDocumentView> document(@PathVariable String cadProjectCode) {
return ApiResponse.success(projects.document(CurrentUser.required(), cadProjectCode));
}
}
@@ -60,6 +60,10 @@ vibemake:
file-write: ${RATE_FILE_WRITE_PER_MINUTE:10}
cover-sign: ${RATE_COVER_SIGN_PER_MINUTE:30}
urdf-sign: ${RATE_URDF_SIGN_PER_MINUTE:20}
cad-create: ${RATE_CAD_CREATE_PER_MINUTE:5}
cad-sign: ${RATE_CAD_SIGN_PER_MINUTE:20}
cad-save: ${RATE_CAD_SAVE_PER_MINUTE:30}
cad-read: ${RATE_CAD_READ_PER_MINUTE:60}
comment: ${RATE_COMMENT_PER_MINUTE:10}
like: ${RATE_LIKE_PER_MINUTE:60}
oss:
@@ -74,6 +78,18 @@ vibemake:
max-file-bytes: ${URDF_MAX_FILE_BYTES:52428800}
max-total-bytes: ${URDF_MAX_TOTAL_BYTES:209715200}
max-files: ${URDF_MAX_FILES:500}
cad:
max-file-bytes: ${CAD_MAX_FILE_BYTES:268435456}
upload-validity: ${CAD_UPLOAD_VALIDITY:15m}
download-validity: ${CAD_DOWNLOAD_VALIDITY:5m}
oss:
enabled: ${CAD_OSS_ENABLED:false}
region: ${CAD_OSS_REGION:cn-beijing}
endpoint: ${CAD_OSS_ENDPOINT:}
bucket: ${CAD_OSS_BUCKET:}
access-key-id: ${CAD_OSS_ACCESS_KEY_ID:}
access-key-secret: ${CAD_OSS_ACCESS_KEY_SECRET:}
root-directory: ${CAD_OSS_ROOT_DIRECTORY:${vibemake.oss.root-directory}}
ai:
enabled: ${AI_ENABLED:true}
api-key: ${ARK_API_KEY:}
@@ -0,0 +1,414 @@
package com.linkerbot.vibemake.api;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.bean.CadContracts.CadSaveResult;
import com.linkerbot.vibemake.bean.entity.User;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.security.TokenService;
import com.linkerbot.vibemake.service.UserService;
import com.linkerbot.vibemake.service.cad.CadObjectStore;
import com.linkerbot.vibemake.service.cad.CadProjectService;
import com.linkerbot.vibemake.service.config.CadProperties;
import com.linkerbot.vibemake.service.oss.OssPostSigner;
import com.linkerbot.vibemake.service.support.ProjectSupport;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.*;
import org.springframework.boot.test.context.*;
import org.springframework.context.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.*;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:cad;MODE=MySQL;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000",
"spring.datasource.username=sa", "spring.datasource.password=",
"spring.datasource.driver-class-name=org.h2.Driver",
"vibemake.repository-write.worker-enabled=false", "vibemake.oss.enabled=false",
"vibemake.cad.oss.enabled=true", "vibemake.cad.oss.bucket=private-cad-tests",
"vibemake.cad.oss.access-key-id=TestCadKey", "vibemake.cad.oss.access-key-secret=test-secret",
"vibemake.ai.enabled=false", "vibemake.git.enabled=false", "logging.level.org.springframework=WARN"
})
@ActiveProfiles("test")
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@Import(CadWorkspaceTest.Config.class)
class CadWorkspaceTest {
private static final String BASE = "/api/cad/workspace/projects";
@TestConfiguration
static class Config {
@Bean @Primary
FakeCadStore fakeCad(CadProperties properties, ObjectMapper json) {
return new FakeCadStore(properties, json);
}
}
static class FakeCadStore implements CadObjectStore {
final Map<String, byte[]> objects = new ConcurrentHashMap<>();
final CadProperties properties;
final OssPostSigner signer;
boolean unavailable;
Runnable afterSign;
Runnable afterSize;
CyclicBarrier sizeBarrier;
FakeCadStore(CadProperties properties, ObjectMapper json) {
this.properties = properties;
this.signer = new OssPostSigner(properties.getOss(), json);
}
private void available() {
if (!properties.getOss().isEnabled()) throw new BusinessException(503, "CAD_STORAGE_UNAVAILABLE", "关闭");
if (unavailable) throw new BusinessException(502, "CAD_OSS_ERROR", "不可用");
}
@Override
public SignedUpload signUpload(String key, String name, long size, Duration validity) {
available();
OssPostSigner.SignedPost post = signer.signPrivateObject(key, "application/octet-stream", size, validity, null);
if (afterSign != null) {
Runnable action = afterSign;
afterSign = null;
action.run();
}
return new SignedUpload(properties.getOss().uploadUrl(), post.formFields(), post.expiresAt());
}
@Override
public long size(String key) {
available();
byte[] bytes = objects.get(key);
if (bytes == null) throw new BusinessException(409, "CAD_FILE_MISSING", "缺文件");
if (sizeBarrier != null) {
try {
sizeBarrier.await(5, TimeUnit.SECONDS);
} catch (Exception error) {
throw new IllegalStateException(error);
}
}
if (afterSize != null) {
Runnable action = afterSize;
afterSize = null;
action.run();
}
return bytes.length;
}
@Override
public SignedDownload signDownload(String key, String name, Duration validity) {
available();
return new SignedDownload("https://private-cad-tests.example/" + key + "?signature=test",
ProjectSupport.now().plus(validity));
}
}
@Autowired MockMvc mvc;
@Autowired ObjectMapper json;
@Autowired JdbcTemplate jdbc;
@Autowired UserService users;
@Autowired TokenService tokens;
@Autowired CadProperties properties;
@Autowired CadProjectService service;
@Autowired FakeCadStore store;
private String token;
private long userId;
@BeforeEach
void reset() throws Exception {
SchemaSupport.reset(jdbc);
properties.getOss().setEnabled(true);
properties.setMaxFileBytes(268435456);
properties.setUploadValidity(Duration.ofMinutes(15));
properties.setDownloadValidity(Duration.ofMinutes(5));
store.objects.clear();
store.unavailable = false;
store.afterSign = null;
store.afterSize = null;
store.sizeBarrier = null;
User user = users.login("cad-owner@example.invalid");
userId = user.getId();
token = tokens.issue(user.getId(), user.getSessionVersion());
}
private MockHttpServletRequestBuilder auth(MockHttpServletRequestBuilder request) {
return request.header("Authorization", "Bearer " + token);
}
private JsonNode perform(MockHttpServletRequestBuilder request, int status) throws Exception {
MvcResult result = mvc.perform(request).andExpect(status().is(status)).andReturn();
return json.readTree(result.getResponse().getContentAsString());
}
private MockHttpServletRequestBuilder body(MockHttpServletRequestBuilder request, Object body) throws Exception {
return request.contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsBytes(body));
}
private String create(String name) throws Exception {
JsonNode project = perform(body(auth(post(BASE)), Map.of("name", name)), 200).path("data");
assertThat(project.has("id")).isFalse();
assertThat(project.has("ownerUserId")).isFalse();
assertThat(project.path("hasDocument").asBoolean()).isFalse();
assertThat(project.path("version").asLong()).isZero();
return project.path("cadProjectCode").asText();
}
private JsonNode sign(String code, long version, long size) throws Exception {
return perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "支架.sc", "sizeBytes", size, "expectedVersion", version)), 200).path("data");
}
private JsonNode upload(String code, long version, byte[] bytes) throws Exception {
JsonNode signature = sign(code, version, bytes.length);
store.objects.put(signature.path("formFields").path("key").asText(), bytes.clone());
return signature;
}
private JsonNode confirm(String code, JsonNode signature, int status) throws Exception {
return perform(body(auth(put(BASE + "/" + code + "/document")),
Map.of("uploadCode", signature.path("uploadCode").asText())), status);
}
@Test
void sharedLoginSeparateWorkspaceAndEditableSaveRoundTrip() throws Exception {
perform(auth(get("/api/users/me")), 200);
String code = create(" CAD 支架 ");
assertThat(perform(auth(get(BASE)), 200).path("data").path("total").asInt()).isEqualTo(1);
assertThat(perform(auth(get("/api/workspace/projects")), 200).path("data").path("total").asInt()).isZero();
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project", Long.class)).isZero();
assertThat(perform(auth(get(BASE + "/" + code + "/document")), 404).path("code").asText()).isEqualTo("CAD_DOCUMENT_NOT_FOUND");
JsonNode first = upload(code, 0, new byte[] {80, 75, 3, 4, 1});
assertThat(confirm(code, first, 200).path("data").path("version").asLong()).isEqualTo(1);
JsonNode opened = perform(auth(get(BASE + "/" + code + "/document")), 200).path("data");
assertThat(opened.path("version").asLong()).isEqualTo(1);
assertThat(opened.path("downloadUrl").asText()).contains(first.path("formFields").path("key").asText());
JsonNode second = upload(code, opened.path("version").asLong(), new byte[] {80, 75, 3, 4, 2, 3});
JsonNode saved = confirm(code, second, 200).path("data");
assertThat(saved.path("version").asLong()).isEqualTo(2);
JsonNode detail = perform(auth(get(BASE + "/" + code)), 200).path("data");
assertThat(detail.path("hasDocument").asBoolean()).isTrue();
assertThat(detail.path("fileName").asText()).isEqualTo("支架.sc");
assertThat(detail.path("sizeBytes").asLong()).isEqualTo(6);
assertThat(detail.path("savedAt").asText()).doesNotEndWith("Z");
assertThat(detail.has("documentObjectKey")).isFalse();
assertThat(jdbc.queryForObject("SELECT document_object_key FROM cad_project WHERE cad_project_code=?",
String.class, code)).isEqualTo(second.path("formFields").path("key").asText());
perform(body(auth(patch(BASE + "/" + code)), Map.of("name", "重命名", "description", "参数化支架")), 200);
assertThat(perform(auth(get(BASE + "?keyword=重命")), 200).path("data").path("total").asInt()).isEqualTo(1);
assertThat(perform(auth(get(BASE + "/" + code)), 200).path("data").path("version").asLong()).isEqualTo(2);
assertThat(store.objects).hasSize(2);
}
@Test
void confirmedBatchReplayReturnsOriginalReceiptEvenAfterLaterSaveExpiryAndOssFailure() throws Exception {
String code = create("幂等");
JsonNode first = upload(code, 0, new byte[] {1});
JsonNode original = confirm(code, first, 200).path("data");
confirm(code, upload(code, 1, new byte[] {2}), 200);
jdbc.update("UPDATE cad_project_upload SET expires_at=?", ProjectSupport.now().minusDays(1));
store.unavailable = true;
assertThat(confirm(code, first, 200).path("data")).isEqualTo(original);
assertThat(service.detail(userId, code).version()).isEqualTo(2);
}
@Test
void foreignUsersAndProjectsCannotAccessOrConfirmUploads() throws Exception {
String code = create("私有设计");
JsonNode pending = upload(code, 0, new byte[] {1});
String another = create("另一项目");
confirm(another, pending, 404);
User other = users.login("cad-other@example.invalid");
token = tokens.issue(other.getId(), other.getSessionVersion());
assertThat(perform(auth(get(BASE)), 200).path("data").path("total").asInt()).isZero();
perform(auth(get(BASE + "/" + code)), 404);
perform(auth(get(BASE + "/" + code + "/document")), 404);
perform(body(auth(patch(BASE + "/" + code)), Map.of("name", "越权")), 404);
perform(auth(delete(BASE + "/" + code)), 404);
perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "test.sc", "sizeBytes", 1, "expectedVersion", 0)), 404);
confirm(code, pending, 404);
}
@Test
void failuresDoNotReplaceSavedDocumentAndUnconfirmedExpiryIsEnforced() throws Exception {
String code = create("失败保护");
confirm(code, upload(code, 0, new byte[] {1}), 200);
JsonNode next = sign(code, 1, 2);
assertThat(confirm(code, next, 409).path("code").asText()).isEqualTo("CAD_FILE_MISSING");
String key = next.path("formFields").path("key").asText();
store.objects.put(key, new byte[] {2});
assertThat(confirm(code, next, 409).path("code").asText()).isEqualTo("CAD_FILE_SIZE_MISMATCH");
store.objects.put(key, new byte[] {2, 3});
store.unavailable = true;
assertThat(confirm(code, next, 502).path("code").asText()).isEqualTo("CAD_OSS_ERROR");
store.unavailable = false;
jdbc.update("UPDATE cad_project_upload SET expires_at=? WHERE upload_code=?",
ProjectSupport.now().minusSeconds(1), next.path("uploadCode").asText());
assertThat(confirm(code, next, 409).path("code").asText()).isEqualTo("CAD_UPLOAD_EXPIRED");
assertThat(service.detail(userId, code).version()).isEqualTo(1);
assertThat(service.detail(userId, code).sizeBytes()).isEqualTo(1);
}
@Test
void concurrentDifferentBatchesOnlyOneSaveWins() throws Exception {
String code = create("并发");
JsonNode first = upload(code, 0, new byte[] {1});
JsonNode second = upload(code, 0, new byte[] {2});
store.sizeBarrier = new CyclicBarrier(2);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<String> one = executor.submit(() -> confirmationOutcome(code, first));
Future<String> two = executor.submit(() -> confirmationOutcome(code, second));
assertThat(List.of(one.get(10, TimeUnit.SECONDS), two.get(10, TimeUnit.SECONDS)))
.containsExactlyInAnyOrder("saved:1", "CAD_VERSION_CONFLICT");
}
assertThat(service.detail(userId, code).version()).isEqualTo(1);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM cad_project_upload WHERE saved_version IS NOT NULL", Long.class)).isEqualTo(1);
}
@Test
void concurrentSameBatchOnlyIncrementsOnce() throws Exception {
String code = create("重复并发");
JsonNode batch = upload(code, 0, new byte[] {1});
store.sizeBarrier = new CyclicBarrier(2);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<CadSaveResult> one = executor.submit(() -> service.confirm(userId, code, batch.path("uploadCode").asText()));
Future<CadSaveResult> two = executor.submit(() -> service.confirm(userId, code, batch.path("uploadCode").asText()));
assertThat(one.get(10, TimeUnit.SECONDS)).isEqualTo(two.get(10, TimeUnit.SECONDS));
}
assertThat(service.detail(userId, code).version()).isEqualTo(1);
}
private String confirmationOutcome(String code, JsonNode batch) {
try {
return "saved:" + service.confirm(userId, code, batch.path("uploadCode").asText()).version();
} catch (BusinessException error) {
return error.code();
}
}
@Test
void failedReceiptWriteRollsBackDocumentAndAllowsRetry() throws Exception {
String code = create("事务回滚");
JsonNode batch = upload(code, 0, new byte[] {1});
jdbc.execute("ALTER TABLE cad_project_upload ADD CONSTRAINT reject_saved CHECK (saved_version IS NULL)");
assertThatThrownBy(() -> service.confirm(userId, code, batch.path("uploadCode").asText())).isInstanceOf(RuntimeException.class);
assertThat(service.detail(userId, code).version()).isZero();
assertThat(service.detail(userId, code).hasDocument()).isFalse();
jdbc.execute("ALTER TABLE cad_project_upload DROP CONSTRAINT reject_saved");
assertThat(confirm(code, batch, 200).path("data").path("version").asLong()).isEqualTo(1);
}
@Test
void deletionDuringHeadAndLaterReplayCannotRestoreProject() throws Exception {
String code = create("删除竞争");
JsonNode saved = upload(code, 0, new byte[] {1});
confirm(code, saved, 200);
JsonNode pending = upload(code, 1, new byte[] {2});
store.afterSize = () -> service.delete(userId, code);
confirm(code, pending, 404);
confirm(code, saved, 404);
perform(auth(get(BASE + "/" + code)), 404);
perform(auth(get(BASE + "/" + code + "/document")), 404);
perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "test.sc", "sizeBytes", 1, "expectedVersion", 1)), 404);
assertThat(perform(auth(get(BASE)), 200).path("data").path("total").asInt()).isZero();
assertThat(store.objects).hasSize(2);
}
@Test
void deletionDuringSigningDoesNotCreateOrReturnUploadBatch() throws Exception {
String code = create("签名删除竞争");
store.afterSign = () -> service.delete(userId, code);
perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "test.sc", "sizeBytes", 1, "expectedVersion", 0)), 404);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM cad_project_upload", Long.class)).isZero();
}
@Test
void staleVersionCannotObtainNewUploadCredentialsAndLogoutRevokesCadAccess() throws Exception {
String code = create("登录与版本");
confirm(code, upload(code, 0, new byte[] {1}), 200);
assertThat(perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "test.sc", "sizeBytes", 1, "expectedVersion", 0)), 409)
.path("code").asText()).isEqualTo("CAD_VERSION_CONFLICT");
perform(auth(post("/api/auth/logout")), 200);
perform(auth(get(BASE + "/" + code)), 401);
perform(auth(get("/api/users/me")), 401);
}
@Test
void validatesMetadataLimitsAndStorageDisabledWithoutBlockingProjectDeletion() throws Exception {
perform(body(auth(post(BASE)), Map.of("name", " ")), 400);
String code = create("参数检查");
perform(body(auth(patch(BASE + "/" + code)), Map.of()), 400);
perform(body(auth(patch(BASE + "/" + code)), Map.of("name", " ")), 400);
perform(auth(get(BASE + "?page=0")), 400);
perform(auth(get(BASE + "?size=101")), 400);
perform(auth(get(BASE + "?keyword=" + "a".repeat(101))), 400);
properties.setMaxFileBytes(1);
assertThat(perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "test.sc", "sizeBytes", 2, "expectedVersion", 0)), 413).path("code").asText()).isEqualTo("CAD_FILE_TOO_LARGE");
properties.getOss().setEnabled(false);
assertThat(perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", "test.sc", "sizeBytes", 1, "expectedVersion", 0)), 503).path("code").asText()).isEqualTo("CAD_STORAGE_UNAVAILABLE");
perform(auth(delete(BASE + "/" + code)), 200);
}
@ParameterizedTest
@ValueSource(strings = {"../design.sc", "dir/design.sc", "dir\\design.sc", "test.step", ".sc", "test.sc\n"})
void rejectsNonNativeOrUnsafeFileNames(String fileName) throws Exception {
String code = create("文件名检查");
perform(body(auth(post(BASE + "/" + code + "/uploads/signature")),
Map.of("fileName", fileName, "sizeBytes", 1, "expectedVersion", 0)), 400);
}
@ParameterizedTest
@ValueSource(strings = {"\"1\"", "1.5", "null", "-1", "9223372036854775808"})
void rejectsCoercedOrInvalidNumericInput(String number) throws Exception {
String code = create("数字检查");
for (String input : List.of(
"{\"fileName\":\"test.sc\",\"sizeBytes\":" + number + ",\"expectedVersion\":0}",
"{\"fileName\":\"test.sc\",\"sizeBytes\":1,\"expectedVersion\":" + number + "}")) {
perform(auth(post(BASE + "/" + code + "/uploads/signature")).contentType(MediaType.APPLICATION_JSON).content(input), 400);
}
}
@Test
void authenticationCorsNoStoreAndOpenApiExposeAllEightOperations() throws Exception {
mvc.perform(get(BASE)).andExpect(status().isUnauthorized()).andExpect(header().string("Cache-Control", "no-store"));
mvc.perform(auth(get(BASE)).header("Origin", "https://dev-vibemake.robotquan.com"))
.andExpect(status().isOk()).andExpect(header().string("Access-Control-Allow-Origin", "https://dev-vibemake.robotquan.com"))
.andExpect(header().string("Cache-Control", "no-store"));
JsonNode spec = perform(get("/v3/api-docs"), 200);
JsonNode paths = spec.path("paths");
assertThat(paths.path(BASE).has("get")).isTrue();
assertThat(paths.path(BASE).has("post")).isTrue();
assertThat(paths.path(BASE + "/{cadProjectCode}").has("get")).isTrue();
assertThat(paths.path(BASE + "/{cadProjectCode}").has("patch")).isTrue();
assertThat(paths.path(BASE + "/{cadProjectCode}").has("delete")).isTrue();
assertThat(paths.path(BASE + "/{cadProjectCode}/uploads/signature").has("post")).isTrue();
assertThat(paths.path(BASE + "/{cadProjectCode}/document").has("get")).isTrue();
assertThat(paths.path(BASE + "/{cadProjectCode}/document").has("put")).isTrue();
// 避免 CAD 和 Git 项目的同名 DTO 污染彼此的 OpenAPI 模型。
JsonNode schemas = spec.path("components").path("schemas");
assertThat(schemas.path("CadProjectView").path("properties").has("cadProjectCode")).isTrue();
assertThat(schemas.path("CadProjectView").path("properties").has("projectCode")).isFalse();
assertThat(schemas.path("ProjectView").path("properties").has("projectCode")).isTrue();
assertThat(schemas.path("ProjectView").path("properties").has("cadProjectCode")).isFalse();
}
}
@@ -14,7 +14,8 @@ final class SchemaSupport {
String content =
Files.readString(path)
+ "\n"
+ Files.readString(path.resolveSibling("admin-database.md"));
+ Files.readString(path.resolveSibling("admin-database.md"))
+ "\n" + Files.readString(path.resolveSibling("cad-database.md"));
Matcher matcher = Pattern.compile("CREATE TABLE [\\s\\S]*?;").matcher(content);
jdbc.execute("DROP ALL OBJECTS");
int tables = 0;
@@ -32,6 +33,6 @@ final class SchemaSupport {
jdbc.execute(ddl);
tables++;
}
if (tables != 7) throw new IllegalStateException("必须包含七张业务与审计表");
if (tables != 9) throw new IllegalStateException("必须包含九张业务与审计表");
}
}
@@ -1263,7 +1263,8 @@ class WorkflowTest {
"PROJECT",
"PROJECT_COMMENT",
"PROJECT_LIKE",
"PROJECT_IMPORT_TASK", "REPOSITORY_WRITE_OPERATION", "PROJECT_GIT_TOKEN");
"PROJECT_IMPORT_TASK", "REPOSITORY_WRITE_OPERATION", "PROJECT_GIT_TOKEN",
"CAD_PROJECT", "CAD_PROJECT_UPLOAD");
}
@Test
@@ -0,0 +1,56 @@
package com.linkerbot.vibemake.bean;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import jakarta.validation.constraints.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
public final class CadContracts {
private CadContracts() {}
public record CadCreateProjectInput(
@NotBlank @Size(max = 100) String name,
@Size(max = 2000) String description) {}
public record CadUpdateProjectInput(
@Size(min = 1, max = 100) String name,
@Size(max = 2000) String description) {}
public record CadUploadInput(
@NotBlank @Size(max = 255) String fileName,
@NotNull @Positive @JsonDeserialize(using = StrictLongDeserializer.class) Long sizeBytes,
@NotNull @PositiveOrZero @JsonDeserialize(using = StrictLongDeserializer.class) Long expectedVersion) {}
public record CadConfirmInput(@NotBlank @Size(max = 32) String uploadCode) {}
public record CadProjectView(
String cadProjectCode, String name, String description, boolean hasDocument,
long version, String fileName, long sizeBytes, LocalDateTime savedAt,
LocalDateTime createdAt, LocalDateTime updatedAt) {}
public record CadUploadSignature(
String uploadCode, String uploadUrl, Map<String, String> formFields,
LocalDateTime expiresAt) {}
public record CadSaveResult(String cadProjectCode, long version, LocalDateTime savedAt) {}
public record CadDocumentView(
String downloadUrl, LocalDateTime expiresAt, long version,
String fileName, long sizeBytes) {}
/** 文件大小和版本必须是真正的 JSON 整数,拒绝小数截断及字符串自动转换。 */
public static final class StrictLongDeserializer extends JsonDeserializer<Long> {
@Override
public Long deserialize(JsonParser parser, DeserializationContext context) throws IOException {
if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
return (Long) context.handleUnexpectedToken(Long.class, parser);
}
return parser.getLongValue();
}
}
}
@@ -0,0 +1,22 @@
package com.linkerbot.vibemake.bean.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@TableName("cad_project")
public class CadProject extends BaseEntity {
private String cadProjectCode;
private Long ownerUserId;
private String name;
private String description;
private String documentObjectKey;
private String fileName;
private Long sizeBytes;
private Long version;
private LocalDateTime savedAt;
private Boolean deleted;
}
@@ -0,0 +1,21 @@
package com.linkerbot.vibemake.bean.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@TableName("cad_project_upload")
public class CadProjectUpload extends BaseEntity {
private String uploadCode;
private Long cadProjectId;
private Long expectedVersion;
private String objectKey;
private String fileName;
private Long sizeBytes;
private LocalDateTime expiresAt;
private Long savedVersion;
private LocalDateTime savedAt;
}
@@ -0,0 +1,151 @@
package com.linkerbot.vibemake.service.cad;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.vibemake.common.BusinessException;
import com.linkerbot.vibemake.service.config.CadProperties;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.oss.OssPostSigner;
import com.linkerbot.vibemake.service.support.ProjectSupport;
import jakarta.annotation.PreDestroy;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.stereotype.Component;
@Component
public class AliyunCadObjectStore implements CadObjectStore {
private static final Logger log = LoggerFactory.getLogger(AliyunCadObjectStore.class);
private final CadProperties properties;
private final OssProperties publicOss;
private final OssPostSigner signer;
private OSS client;
@Autowired
public AliyunCadObjectStore(CadProperties properties, OssProperties publicOss, ObjectMapper json) {
this(properties, publicOss, json, null);
}
AliyunCadObjectStore(CadProperties properties, OssProperties publicOss, ObjectMapper json, OSS client) {
this.properties = properties;
this.publicOss = publicOss;
this.signer = new OssPostSigner(properties.getOss(), json);
this.client = client;
}
private synchronized OSS client() {
OssProperties oss = properties.getOss();
if (!oss.isEnabled()) throw new BusinessException(503, "CAD_STORAGE_UNAVAILABLE", "CAD 文件存储暂未开启");
if (oss.getBucket().equals(publicOss.getBucket())) throw unsafe();
if (client == null) {
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
configuration.setConnectionTimeout(5000);
configuration.setSocketTimeout(30000);
configuration.setMaxErrorRetry(1);
client = OSSClientBuilder.create().endpoint(oss.resolvedEndpoint()).region(oss.getRegion())
.credentialsProvider(new DefaultCredentialProvider(oss.getAccessKeyId(), oss.getAccessKeySecret()))
.clientConfiguration(configuration).build();
}
return client;
}
/** 每次签发上传/读取凭据均检查,防止部署误用公开 Bucket 或启用可覆盖的版本控制。 */
private OSS privateClient() {
OSS storage = client();
String bucket = properties.getOss().getBucket();
if (storage.getBucketAcl(bucket).getCannedACL() != CannedAccessControlList.Private
|| storage.getBucketPolicyStatus(bucket).isPublic()
|| !BucketVersioningConfiguration.OFF.equals(storage.getBucketVersioning(bucket).getStatus())) {
throw unsafe();
}
return storage;
}
private BusinessException unsafe() {
log.error("CAD 存储配置不安全 bucket={},需独立私有 Bucket、无公共策略且未开启版本控制",
properties.getOss().getBucket());
return new BusinessException(503, "CAD_STORAGE_UNSAFE", "CAD 私有存储配置异常,请联系管理员");
}
@Override
public SignedUpload signUpload(String objectKey, String fileName, long sizeBytes, Duration validity) {
try {
privateClient();
OssPostSigner.SignedPost post = signer.signPrivateObject(objectKey, "application/octet-stream",
sizeBytes, validity, disposition(fileName));
return new SignedUpload(properties.getOss().uploadUrl(), post.formFields(), post.expiresAt());
} catch (OSSException error) {
throw failure("sign-upload", objectKey, error);
} catch (ClientException error) {
throw transportFailure("sign-upload", objectKey, error);
}
}
@Override
public long size(String objectKey) {
try {
return privateClient().getObjectMetadata(properties.getOss().getBucket(), objectKey).getContentLength();
} catch (OSSException error) {
if ("NoSuchKey".equals(error.getErrorCode())) {
log.warn("CAD 上传对象尚不存在 objectKey={} ossRequestId={}", objectKey, error.getRequestId());
throw new BusinessException(409, "CAD_FILE_MISSING", "设计文件尚未上传完成");
}
throw failure("head", objectKey, error);
} catch (ClientException error) {
throw transportFailure("head", objectKey, error);
}
}
@Override
public SignedDownload signDownload(String objectKey, String fileName, Duration validity) {
try {
OSS storage = privateClient();
Instant expiresAt = Instant.now().plus(validity);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
properties.getOss().getBucket(), objectKey, HttpMethod.GET);
request.setExpiration(Date.from(expiresAt));
ResponseHeaderOverrides headers = new ResponseHeaderOverrides();
headers.setContentDisposition(disposition(fileName));
headers.setContentType("application/octet-stream");
headers.setCacheControl("private, no-store");
request.setResponseHeaders(headers);
String url = storage.generatePresignedUrl(request).toExternalForm();
return new SignedDownload(url, ProjectSupport.fromInstant(expiresAt));
} catch (OSSException error) {
throw failure("sign-download", objectKey, error);
} catch (ClientException error) {
throw transportFailure("sign-download", objectKey, error);
}
}
private String disposition(String fileName) {
return ContentDisposition.attachment().filename(fileName, StandardCharsets.UTF_8).build().toString();
}
private BusinessException failure(String operation, String key, OSSException error) {
log.error("CAD OSS 操作失败 operation={} objectKey={} ossCode={} ossRequestId={}",
operation, key, error.getErrorCode(), error.getRequestId());
return new BusinessException(502, "CAD_OSS_ERROR", "CAD 文件存储访问失败,请稍后重试");
}
private BusinessException transportFailure(String operation, String key, ClientException error) {
// SDK 异常正文可能带签名 URL,仅记录异常类型。
log.error("CAD OSS 网络异常 operation={} objectKey={} errorType={}",
operation, key, error.getClass().getSimpleName());
return new BusinessException(502, "CAD_OSS_ERROR", "CAD 文件存储访问失败,请稍后重试");
}
@PreDestroy
public synchronized void close() {
if (client != null) client.shutdown();
}
}
@@ -0,0 +1,17 @@
package com.linkerbot.vibemake.service.cad;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
/** CAD 专用私有存储边界,不复用公开资源的访问地址。 */
public interface CadObjectStore {
record SignedUpload(String uploadUrl, Map<String, String> formFields, LocalDateTime expiresAt) {}
record SignedDownload(String downloadUrl, LocalDateTime expiresAt) {}
SignedUpload signUpload(String objectKey, String fileName, long sizeBytes, Duration validity);
long size(String objectKey);
SignedDownload signDownload(String objectKey, String fileName, Duration validity);
}
@@ -0,0 +1,231 @@
package com.linkerbot.vibemake.service.cad;
import static com.linkerbot.vibemake.service.support.ProjectSupport.now;
import static com.linkerbot.vibemake.service.support.ProjectSupport.pageCheck;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkerbot.vibemake.bean.CadContracts.*;
import com.linkerbot.vibemake.bean.entity.CadProject;
import com.linkerbot.vibemake.bean.entity.CadProjectUpload;
import com.linkerbot.vibemake.common.*;
import com.linkerbot.vibemake.service.config.CadProperties;
import com.linkerbot.vibemake.service.mapper.CadProjectMapper;
import com.linkerbot.vibemake.service.mapper.CadProjectUploadMapper;
import com.linkerbot.vibemake.service.state.RateLimits;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
@Service
@RequiredArgsConstructor
public class CadProjectService {
private static final Logger log = LoggerFactory.getLogger(CadProjectService.class);
private final CadProjectMapper projects;
private final CadProjectUploadMapper uploads;
private final CadProperties properties;
private final CadObjectStore storage;
private final TransactionTemplate transactions;
private final RateLimits limits;
public PageResponse<CadProjectView> list(long userId, String keyword, long page, long size) {
pageCheck(page, size);
if (keyword != null && keyword.length() > 100) throw BusinessException.badRequest("搜索词最多 100 个字符");
String search = keyword == null ? "" : keyword.trim();
Page<CadProject> result = projects.selectPage(new Page<>(page, size),
new LambdaQueryWrapper<CadProject>().eq(CadProject::getOwnerUserId, userId)
.eq(CadProject::getDeleted, false).like(!search.isEmpty(), CadProject::getName, search)
.orderByDesc(CadProject::getUpdatedAt).orderByDesc(CadProject::getId));
return new PageResponse<>(result.getRecords().stream().map(this::view).toList(), page, size, result.getTotal());
}
public CadProjectView create(long userId, CadCreateProjectInput input) {
limits.operation("cad-create", userId);
CadProject project = new CadProject();
project.setOwnerUserId(userId);
project.setName(name(input.name()));
project.setDescription(input.description() == null ? "" : input.description().trim());
project.setDocumentObjectKey("");
project.setFileName("");
project.setSizeBytes(0L);
project.setVersion(0L);
project.setDeleted(false);
project.setCreatedAt(now());
project.setUpdatedAt(project.getCreatedAt());
for (int attempt = 0; attempt < 5; attempt++) {
project.setCadProjectCode(ProjectCodes.next());
try {
projects.insert(project);
log.info("创建 CAD 项目 cadProjectCode={}", project.getCadProjectCode());
return view(project);
} catch (DuplicateKeyException error) {
project.setId(null);
}
}
throw new BusinessException(503, "CAD_CODE_BUSY", "项目编码分配繁忙,请稍后重试");
}
public CadProjectView detail(long userId, String code) {
return view(owner(userId, code));
}
public CadProjectView update(long userId, String code, CadUpdateProjectInput input) {
if (input.name() == null && input.description() == null) throw BusinessException.badRequest("请提供名称或描述");
CadProjectView result = transactions.execute(status -> {
CadProject project = lockedOwner(userId, code);
if (input.name() != null) project.setName(name(input.name()));
if (input.description() != null) project.setDescription(input.description().trim());
project.setUpdatedAt(now());
projects.update(null, new LambdaUpdateWrapper<CadProject>().eq(CadProject::getId, project.getId())
.set(CadProject::getName, project.getName()).set(CadProject::getDescription, project.getDescription())
.set(CadProject::getUpdatedAt, project.getUpdatedAt()));
return view(project);
});
log.info("修改 CAD 项目信息 cadProjectCode={}", code);
return result;
}
public void delete(long userId, String code) {
transactions.executeWithoutResult(status -> {
CadProject project = lockedOwner(userId, code);
projects.update(null, new LambdaUpdateWrapper<CadProject>().eq(CadProject::getId, project.getId())
.set(CadProject::getDeleted, true).set(CadProject::getUpdatedAt, now()));
});
log.info("删除 CAD 项目 cadProjectCode={}", code);
}
public CadUploadSignature sign(long userId, String code, CadUploadInput input) {
CadProject project = owner(userId, code);
limits.operation("cad-sign", userId);
checkFile(input);
checkVersion(project, input.expectedVersion());
String uploadCode = Codes.next();
String key = properties.getOss().getRootDirectory() + "/cad-projects/" + code + "/" + uploadCode + "/design.sc";
CadObjectStore.SignedUpload signature = storage.signUpload(key, input.fileName(), input.sizeBytes(), properties.getUploadValidity());
transactions.executeWithoutResult(status -> {
CadProject current = lockedOwner(userId, code);
checkVersion(current, input.expectedVersion());
CadProjectUpload upload = new CadProjectUpload();
upload.setUploadCode(uploadCode);
upload.setCadProjectId(current.getId());
upload.setExpectedVersion(input.expectedVersion());
upload.setObjectKey(key);
upload.setFileName(input.fileName());
upload.setSizeBytes(input.sizeBytes());
upload.setExpiresAt(signature.expiresAt());
upload.setCreatedAt(now());
upload.setUpdatedAt(upload.getCreatedAt());
uploads.insert(upload);
});
log.info("签发 CAD 上传 cadProjectCode={} uploadCode={} expectedVersion={} sizeBytes={}",
code, uploadCode, input.expectedVersion(), input.sizeBytes());
return new CadUploadSignature(uploadCode, signature.uploadUrl(), signature.formFields(), signature.expiresAt());
}
public CadSaveResult confirm(long userId, String code, String uploadCode) {
CadProject project = owner(userId, code);
limits.operation("cad-save", userId);
CadProjectUpload upload = uploads.selectOne(new LambdaQueryWrapper<CadProjectUpload>()
.eq(CadProjectUpload::getCadProjectId, project.getId()).eq(CadProjectUpload::getUploadCode, uploadCode));
if (upload == null) throw BusinessException.notFound();
// HEAD 在事务之外执行,远程访问期间不占数据库行锁。已确认批次重试不再依赖 OSS。
if (upload.getSavedVersion() == null) {
checkExpiry(upload);
checkVersion(project, upload.getExpectedVersion());
if (storage.size(upload.getObjectKey()) != upload.getSizeBytes()) {
log.warn("CAD 文件大小不符 cadProjectCode={} uploadCode={} expectedBytes={}", code, uploadCode, upload.getSizeBytes());
throw new BusinessException(409, "CAD_FILE_SIZE_MISMATCH", "设计文件大小不符,请重新上传");
}
}
CadSaveResult result = transactions.execute(status -> {
CadProject current = lockedOwner(userId, code);
CadProjectUpload pending = uploads.lockUpload(current.getId(), uploadCode);
if (pending == null) throw BusinessException.notFound();
if (pending.getSavedVersion() != null) return receipt(code, pending);
checkExpiry(pending);
checkVersion(current, pending.getExpectedVersion());
long version = Math.addExact(current.getVersion(), 1L);
// 与 DATETIME(3) 一致,保证首次回执和数据库重放回执完全相同。
LocalDateTime savedAt = now().truncatedTo(ChronoUnit.MILLIS);
int changed = projects.update(null, new LambdaUpdateWrapper<CadProject>()
.eq(CadProject::getId, current.getId()).eq(CadProject::getDeleted, false)
.eq(CadProject::getVersion, pending.getExpectedVersion())
.set(CadProject::getDocumentObjectKey, pending.getObjectKey())
.set(CadProject::getFileName, pending.getFileName()).set(CadProject::getSizeBytes, pending.getSizeBytes())
.set(CadProject::getVersion, version).set(CadProject::getSavedAt, savedAt).set(CadProject::getUpdatedAt, savedAt));
if (changed != 1) throw new BusinessException(409, "CAD_VERSION_CONFLICT", "项目已发生变化,请刷新后重试");
pending.setSavedVersion(version);
pending.setSavedAt(savedAt);
pending.setUpdatedAt(savedAt);
if (uploads.updateById(pending) != 1) throw new IllegalStateException("CAD 上传批次确认失败");
return receipt(code, pending);
});
log.info("确认 CAD 保存 cadProjectCode={} uploadCode={} version={}", code, uploadCode, result.version());
return result;
}
public CadDocumentView document(long userId, String code) {
CadProject project = owner(userId, code);
limits.operation("cad-read", userId);
if (project.getVersion() == 0) throw new BusinessException(404, "CAD_DOCUMENT_NOT_FOUND", "项目尚未保存设计文件");
CadObjectStore.SignedDownload download = storage.signDownload(project.getDocumentObjectKey(), project.getFileName(), properties.getDownloadValidity());
log.info("签发 CAD 读取 cadProjectCode={} version={}", code, project.getVersion());
return new CadDocumentView(download.downloadUrl(), download.expiresAt(), project.getVersion(), project.getFileName(), project.getSizeBytes());
}
private CadProject owner(long userId, String code) {
CadProject project = projects.selectOne(new LambdaQueryWrapper<CadProject>()
.eq(CadProject::getCadProjectCode, code).eq(CadProject::getOwnerUserId, userId).eq(CadProject::getDeleted, false));
if (project == null) throw BusinessException.notFound();
return project;
}
private CadProject lockedOwner(long userId, String code) {
CadProject project = projects.lockOwner(userId, code);
if (project == null) throw BusinessException.notFound();
return project;
}
private CadProjectView view(CadProject project) {
return new CadProjectView(project.getCadProjectCode(), project.getName(), project.getDescription(), project.getVersion() > 0,
project.getVersion(), project.getFileName(), project.getSizeBytes(), project.getSavedAt(), project.getCreatedAt(), project.getUpdatedAt());
}
private CadSaveResult receipt(String code, CadProjectUpload upload) {
return new CadSaveResult(code, upload.getSavedVersion(), upload.getSavedAt());
}
private String name(String value) {
if (value == null || value.isBlank() || value.trim().length() > 100) throw BusinessException.badRequest("项目名称须为 1 至 100 个字符");
return value.trim();
}
private void checkFile(CadUploadInput input) {
String name = input.fileName();
if (name == null || name.isBlank() || name.length() > 255 || name.indexOf('/') >= 0
|| name.indexOf('\\') >= 0 || name.chars().anyMatch(Character::isISOControl)
|| !name.toLowerCase(Locale.ROOT).endsWith(".sc") || name.length() <= 3
|| input.sizeBytes() == null || input.sizeBytes() <= 0 || input.expectedVersion() == null || input.expectedVersion() < 0) {
throw new BusinessException(400, "CAD_INVALID_FILE", "请上传名称合法的非空 .sc 原生设计文件");
}
if (input.sizeBytes() > properties.getMaxFileBytes()) throw new BusinessException(413, "CAD_FILE_TOO_LARGE", "设计文件超过大小限制");
}
private void checkVersion(CadProject project, long expectedVersion) {
if (project.getVersion() != expectedVersion) {
log.warn("CAD 保存版本冲突 cadProjectCode={} expectedVersion={} currentVersion={}", project.getCadProjectCode(), expectedVersion, project.getVersion());
throw new BusinessException(409, "CAD_VERSION_CONFLICT", "项目已有更新,请保留本地修改并刷新后处理");
}
}
private void checkExpiry(CadProjectUpload upload) {
if (!upload.getExpiresAt().isAfter(now())) throw new BusinessException(409, "CAD_UPLOAD_EXPIRED", "上传批次已过期,请重新申请上传");
}
}
@@ -0,0 +1,36 @@
package com.linkerbot.vibemake.service.config;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.time.Duration;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Getter
@Setter
@Validated
@Component
@ConfigurationProperties(prefix = "vibemake.cad")
public class CadProperties {
@Valid @NotNull
private OssProperties oss = new OssProperties();
@Positive @Max(5368709120L)
private long maxFileBytes = 256L * 1024 * 1024;
@NotNull
private Duration uploadValidity = Duration.ofMinutes(15);
@NotNull
private Duration downloadValidity = Duration.ofMinutes(5);
@AssertTrue(message = "CAD 上传和下载签名有效期必须在 1 秒至 7 天之间")
public boolean isValidityValid() {
return valid(uploadValidity) && valid(downloadValidity);
}
private boolean valid(Duration duration) {
return duration != null && duration.compareTo(Duration.ofSeconds(1)) >= 0
&& duration.compareTo(Duration.ofDays(7)) <= 0;
}
}
@@ -41,6 +41,10 @@ public class LimitProperties {
values.put("file-write", 10);
values.put("cover-sign", 30);
values.put("urdf-sign", 20);
values.put("cad-create", 5);
values.put("cad-sign", 20);
values.put("cad-save", 30);
values.put("cad-read", 60);
values.put("comment", 10);
values.put("like", 60);
return values;
@@ -0,0 +1,12 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.CadProject;
import org.apache.ibatis.annotations.*;
@Mapper
public interface CadProjectMapper extends BaseMapper<CadProject> {
@Select("SELECT * FROM cad_project WHERE cad_project_code = #{code} "
+ "AND owner_user_id = #{userId} AND deleted = 0 FOR UPDATE")
CadProject lockOwner(@Param("userId") long userId, @Param("code") String code);
}
@@ -0,0 +1,12 @@
package com.linkerbot.vibemake.service.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkerbot.vibemake.bean.entity.CadProjectUpload;
import org.apache.ibatis.annotations.*;
@Mapper
public interface CadProjectUploadMapper extends BaseMapper<CadProjectUpload> {
@Select("SELECT * FROM cad_project_upload WHERE upload_code = #{code} "
+ "AND cad_project_id = #{projectId} FOR UPDATE")
CadProjectUpload lockUpload(@Param("projectId") long projectId, @Param("code") String code);
}
@@ -74,8 +74,18 @@ public class OssPostSigner {
return post(key, contentType, sizeBytes, sizeBytes, validity, true, contentDisposition);
}
public SignedPost signPrivateObject(String key, String contentType, long sizeBytes,
Duration validity, String contentDisposition) {
return post(key, contentType, sizeBytes, sizeBytes, validity, true, contentDisposition, true);
}
private SignedPost post(String key, String contentType, long minBytes, long maxBytes,
Duration validity, boolean forbidOverwrite, String contentDisposition) {
return post(key, contentType, minBytes, maxBytes, validity, forbidOverwrite, contentDisposition, false);
}
private SignedPost post(String key, String contentType, long minBytes, long maxBytes,
Duration validity, boolean forbidOverwrite, String contentDisposition, boolean privateAcl) {
Instant now = clock.instant().truncatedTo(ChronoUnit.MILLIS);
Instant expiration = now.plus(validity);
String date = DATE.format(now);
@@ -99,6 +109,7 @@ public class OssPostSigner {
}
if (contentDisposition != null)
conditions.add(List.of("eq", "$Content-Disposition", contentDisposition));
if (privateAcl) conditions.add(List.of("eq", "$x-oss-object-acl", "private"));
policy.put("conditions", conditions);
try {
String encoded = Base64.getEncoder().encodeToString(json.writeValueAsBytes(policy));
@@ -113,6 +124,7 @@ public class OssPostSigner {
fields.put("content-type", contentType);
fields.put("success_action_status", "200");
if (contentDisposition != null) fields.put("Content-Disposition", contentDisposition);
if (privateAcl) fields.put("x-oss-object-acl", "private");
if (forbidOverwrite) {
fields.put("x-oss-forbid-overwrite", "true");
fields.put("x-oss-content-type", contentType);
@@ -61,7 +61,7 @@ public class HttpSafetyFilter extends OncePerRequestFilter {
boolean read = "GET".equals(method) || "HEAD".equals(method);
boolean acquired = false;
try {
if (path.contains("/auth/") || path.endsWith("/signature"))
if (path.contains("/auth/") || path.endsWith("/signature") || path.startsWith("/api/cad/"))
response.setHeader("Cache-Control", "no-store");
String ip = addresses.resolve(request);
if (path.equals("/api/auth/captcha")) limits.request("captcha", ip);