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
@@ -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);